code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
// Copyright 2009 the V8 project authors. 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 Google Inc. 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 "v8.h" #include "log-utils.h" #include "string-stream.h" namespace v8 { namespace internal { const char* const Log::kLogToTemporaryFile = "&"; const char* const Log::kLogToConsole = "-"; Log::Log(Logger* logger) : is_stopped_(false), output_handle_(NULL), message_buffer_(NULL), logger_(logger) { } void Log::Initialize(const char* log_file_name) { message_buffer_ = NewArray<char>(kMessageBufferSize); // --log-all enables all the log flags. if (FLAG_log_all) { FLAG_log_runtime = true; FLAG_log_api = true; FLAG_log_code = true; FLAG_log_gc = true; FLAG_log_suspect = true; FLAG_log_handles = true; FLAG_log_regexp = true; FLAG_log_internal_timer_events = true; } // --prof implies --log-code. if (FLAG_prof) FLAG_log_code = true; // If we're logging anything, we need to open the log file. if (Log::InitLogAtStart()) { if (strcmp(log_file_name, kLogToConsole) == 0) { OpenStdout(); } else if (strcmp(log_file_name, kLogToTemporaryFile) == 0) { OpenTemporaryFile(); } else { OpenFile(log_file_name); } } } void Log::OpenStdout() { ASSERT(!IsEnabled()); output_handle_ = stdout; } void Log::OpenTemporaryFile() { ASSERT(!IsEnabled()); output_handle_ = i::OS::OpenTemporaryFile(); } void Log::OpenFile(const char* name) { ASSERT(!IsEnabled()); output_handle_ = OS::FOpen(name, OS::LogFileOpenMode); } FILE* Log::Close() { FILE* result = NULL; if (output_handle_ != NULL) { if (strcmp(FLAG_logfile, kLogToTemporaryFile) != 0) { fclose(output_handle_); } else { result = output_handle_; } } output_handle_ = NULL; DeleteArray(message_buffer_); message_buffer_ = NULL; is_stopped_ = false; return result; } Log::MessageBuilder::MessageBuilder(Log* log) : log_(log), lock_guard_(&log_->mutex_), pos_(0) { ASSERT(log_->message_buffer_ != NULL); } void Log::MessageBuilder::Append(const char* format, ...) { Vector<char> buf(log_->message_buffer_ + pos_, Log::kMessageBufferSize - pos_); va_list args; va_start(args, format); AppendVA(format, args); va_end(args); ASSERT(pos_ <= Log::kMessageBufferSize); } void Log::MessageBuilder::AppendVA(const char* format, va_list args) { Vector<char> buf(log_->message_buffer_ + pos_, Log::kMessageBufferSize - pos_); int result = v8::internal::OS::VSNPrintF(buf, format, args); // Result is -1 if output was truncated. if (result >= 0) { pos_ += result; } else { pos_ = Log::kMessageBufferSize; } ASSERT(pos_ <= Log::kMessageBufferSize); } void Log::MessageBuilder::Append(const char c) { if (pos_ < Log::kMessageBufferSize) { log_->message_buffer_[pos_++] = c; } ASSERT(pos_ <= Log::kMessageBufferSize); } void Log::MessageBuilder::AppendDoubleQuotedString(const char* string) { Append('"'); for (const char* p = string; *p != '\0'; p++) { if (*p == '"') { Append('\\'); } Append(*p); } Append('"'); } void Log::MessageBuilder::Append(String* str) { DisallowHeapAllocation no_gc; // Ensure string stay valid. int length = str->length(); for (int i = 0; i < length; i++) { Append(static_cast<char>(str->Get(i))); } } void Log::MessageBuilder::AppendAddress(Address addr) { Append("0x%" V8PRIxPTR, addr); } void Log::MessageBuilder::AppendSymbolName(Symbol* symbol) { ASSERT(symbol); Append("symbol("); if (!symbol->name()->IsUndefined()) { Append("\""); AppendDetailed(String::cast(symbol->name()), false); Append("\" "); } Append("hash %x)", symbol->Hash()); } void Log::MessageBuilder::AppendDetailed(String* str, bool show_impl_info) { if (str == NULL) return; DisallowHeapAllocation no_gc; // Ensure string stay valid. int len = str->length(); if (len > 0x1000) len = 0x1000; if (show_impl_info) { Append(str->IsOneByteRepresentation() ? 'a' : '2'); if (StringShape(str).IsExternal()) Append('e'); if (StringShape(str).IsInternalized()) Append('#'); Append(":%i:", str->length()); } for (int i = 0; i < len; i++) { uc32 c = str->Get(i); if (c > 0xff) { Append("\\u%04x", c); } else if (c < 32 || c > 126) { Append("\\x%02x", c); } else if (c == ',') { Append("\\,"); } else if (c == '\\') { Append("\\\\"); } else if (c == '\"') { Append("\"\""); } else { Append("%lc", c); } } } void Log::MessageBuilder::AppendStringPart(const char* str, int len) { if (pos_ + len > Log::kMessageBufferSize) { len = Log::kMessageBufferSize - pos_; ASSERT(len >= 0); if (len == 0) return; } Vector<char> buf(log_->message_buffer_ + pos_, Log::kMessageBufferSize - pos_); OS::StrNCpy(buf, str, len); pos_ += len; ASSERT(pos_ <= Log::kMessageBufferSize); } void Log::MessageBuilder::WriteToLogFile() { ASSERT(pos_ <= Log::kMessageBufferSize); const int written = log_->WriteToFile(log_->message_buffer_, pos_); if (written != pos_) { log_->stop(); log_->logger_->LogFailure(); } } } } // namespace v8::internal
msiebuhr/v8.go
v8/src/log-utils.cc
C++
mit
6,769
exports.modifyWebpackConfig = (config, stage) => { config.loader('eslint', { test: /\.js$/, exclude: /node_modules/, }) return config; };
francisdzheng/calwtcrew
gatsby-node.js
JavaScript
mit
154
<?php namespace Spy\Timeline\ResolveComponent; use Spy\Timeline\Exception\ResolveComponentDataException; use Spy\Timeline\ResolveComponent\ValueObject\ResolveComponentModelIdentifier; use Spy\Timeline\ResolveComponent\ValueObject\ResolvedComponentData; interface ComponentDataResolverInterface { /** * @param ResolveComponentModelIdentifier $resolve The ResolveComponentModelIdentifier value object. * * @return ResolvedComponentData The resolved component data value object. * * @throws ResolveComponentDataException When not able to resolve the component data */ public function resolveComponentData(ResolveComponentModelIdentifier $resolve); }
sonata-project/sandbox-build
vendor/stephpy/timeline/src/ResolveComponent/ComponentDataResolverInterface.php
PHP
mit
688
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Phaser Source: src/geom/Line.js</title> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/default.css"> <link type="text/css" rel="stylesheet" href="styles/sunlight.default.css"> <link type="text/css" rel="stylesheet" href="styles/site.cerulean.css"> </head> <body> <div class="container-fluid"> <div class="navbar navbar-fixed-top navbar-inverse"> <div style="position: absolute; width: 143px; height: 31px; right: 10px; top: 10px; z-index: 1050"><a href="http://phaser.io"><img src="img/phaser.png" border="0" /></a></div> <div class="navbar-inner"> <a class="brand" href="index.html">Phaser API</a> <ul class="nav"> <li class="dropdown"> <a href="namespaces.list.html" class="dropdown-toggle" data-toggle="dropdown">Namespaces<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-0"> <a href="Phaser.html">Phaser</a> </li> <li class="class-depth-0"> <a href="Phaser.KeyCode.html">KeyCode</a> </li> <li class="class-depth-0"> <a href="PIXI.html">PIXI</a> </li> </ul> </li> <li class="dropdown"> <a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"> <a href="Phaser.Animation.html">Animation</a> </li> <li class="class-depth-1"> <a href="Phaser.AnimationManager.html">AnimationManager</a> </li> <li class="class-depth-1"> <a href="Phaser.AnimationParser.html">AnimationParser</a> </li> <li class="class-depth-1"> <a href="Phaser.ArraySet.html">ArraySet</a> </li> <li class="class-depth-1"> <a href="Phaser.ArrayUtils.html">ArrayUtils</a> </li> <li class="class-depth-1"> <a href="Phaser.AudioSprite.html">AudioSprite</a> </li> <li class="class-depth-1"> <a href="Phaser.BitmapData.html">BitmapData</a> </li> <li class="class-depth-1"> <a href="Phaser.BitmapText.html">BitmapText</a> </li> <li class="class-depth-1"> <a href="Phaser.Button.html">Button</a> </li> <li class="class-depth-1"> <a href="Phaser.Cache.html">Cache</a> </li> <li class="class-depth-1"> <a href="Phaser.Camera.html">Camera</a> </li> <li class="class-depth-1"> <a href="Phaser.Canvas.html">Canvas</a> </li> <li class="class-depth-1"> <a href="Phaser.Circle.html">Circle</a> </li> <li class="class-depth-1"> <a href="Phaser.Color.html">Color</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Angle.html">Angle</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Animation.html">Animation</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.AutoCull.html">AutoCull</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Bounds.html">Bounds</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.BringToTop.html">BringToTop</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Core.html">Core</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Crop.html">Crop</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Delta.html">Delta</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Destroy.html">Destroy</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.FixedToCamera.html">FixedToCamera</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Health.html">Health</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.InCamera.html">InCamera</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.InputEnabled.html">InputEnabled</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.InWorld.html">InWorld</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.LifeSpan.html">LifeSpan</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.LoadTexture.html">LoadTexture</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Overlap.html">Overlap</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.PhysicsBody.html">PhysicsBody</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Reset.html">Reset</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.ScaleMinMax.html">ScaleMinMax</a> </li> <li class="class-depth-2"> <a href="Phaser.Component.Smoothed.html">Smoothed</a> </li> <li class="class-depth-1"> <a href="Phaser.Create.html">Create</a> </li> <li class="class-depth-1"> <a href="Phaser.Creature.html">Creature</a> </li> <li class="class-depth-1"> <a href="Phaser.Device.html">Device</a> </li> <li class="class-depth-1"> <a href="Phaser.DeviceButton.html">DeviceButton</a> </li> <li class="class-depth-1"> <a href="Phaser.DOM.html">DOM</a> </li> <li class="class-depth-1"> <a href="Phaser.Easing.html">Easing</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Back.html">Back</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Bounce.html">Bounce</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Circular.html">Circular</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Cubic.html">Cubic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Elastic.html">Elastic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Exponential.html">Exponential</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Linear.html">Linear</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Quadratic.html">Quadratic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Quartic.html">Quartic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Quintic.html">Quintic</a> </li> <li class="class-depth-2"> <a href="Phaser.Easing.Sinusoidal.html">Sinusoidal</a> </li> <li class="class-depth-1"> <a href="Phaser.Ellipse.html">Ellipse</a> </li> <li class="class-depth-1"> <a href="Phaser.Events.html">Events</a> </li> <li class="class-depth-1"> <a href="Phaser.Filter.html">Filter</a> </li> <li class="class-depth-1"> <a href="Phaser.FlexGrid.html">FlexGrid</a> </li> <li class="class-depth-1"> <a href="Phaser.FlexLayer.html">FlexLayer</a> </li> <li class="class-depth-1"> <a href="Phaser.Frame.html">Frame</a> </li> <li class="class-depth-1"> <a href="Phaser.FrameData.html">FrameData</a> </li> <li class="class-depth-1"> <a href="Phaser.Game.html">Game</a> </li> <li class="class-depth-1"> <a href="Phaser.GameObjectCreator.html">GameObjectCreator</a> </li> <li class="class-depth-1"> <a href="Phaser.GameObjectFactory.html">GameObjectFactory</a> </li> <li class="class-depth-1"> <a href="Phaser.Gamepad.html">Gamepad</a> </li> <li class="class-depth-1"> <a href="Phaser.Graphics.html">Graphics</a> </li> <li class="class-depth-1"> <a href="Phaser.Group.html">Group</a> </li> <li class="class-depth-1"> <a href="Phaser.Image.html">Image</a> </li> <li class="class-depth-1"> <a href="Phaser.ImageCollection.html">ImageCollection</a> </li> <li class="class-depth-1"> <a href="Phaser.Input.html">Input</a> </li> <li class="class-depth-1"> <a href="Phaser.InputHandler.html">InputHandler</a> </li> <li class="class-depth-1"> <a href="Phaser.Key.html">Key</a> </li> <li class="class-depth-1"> <a href="Phaser.Keyboard.html">Keyboard</a> </li> <li class="class-depth-1"> <a href="Phaser.Line.html">Line</a> </li> <li class="class-depth-1"> <a href="Phaser.LinkedList.html">LinkedList</a> </li> <li class="class-depth-1"> <a href="Phaser.Loader.html">Loader</a> </li> <li class="class-depth-1"> <a href="Phaser.LoaderParser.html">LoaderParser</a> </li> <li class="class-depth-1"> <a href="Phaser.Math.html">Math</a> </li> <li class="class-depth-1"> <a href="Phaser.Matrix.html">Matrix</a> </li> <li class="class-depth-1"> <a href="Phaser.Mouse.html">Mouse</a> </li> <li class="class-depth-1"> <a href="Phaser.MSPointer.html">MSPointer</a> </li> <li class="class-depth-1"> <a href="Phaser.Net.html">Net</a> </li> <li class="class-depth-1"> <a href="Phaser.Particle.html">Particle</a> </li> <li class="class-depth-1"> <a href="Phaser.Particles.html">Particles</a> </li> <li class="class-depth-2"> <a href="Phaser.Particles.Arcade.html">Arcade</a> </li> <li class="class-depth-3"> <a href="Phaser.Particles.Arcade.Emitter.html">Emitter</a> </li> <li class="class-depth-1"> <a href="Phaser.Physics.html">Physics</a> </li> <li class="class-depth-2"> <a href="Phaser.Physics.Arcade.html">Arcade</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Arcade.Body.html">Body</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Arcade.TilemapCollision.html">TilemapCollision</a> </li> <li class="class-depth-2"> <a href="Phaser.Physics.Ninja.html">Ninja</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.AABB.html">AABB</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.Body.html">Body</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.Circle.html">Circle</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.Ninja.Tile.html">Tile</a> </li> <li class="class-depth-2"> <a href="Phaser.Physics.P2.html">P2</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.Body.html">Body</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.BodyDebug.html">BodyDebug</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.CollisionGroup.html">CollisionGroup</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.ContactMaterial.html">ContactMaterial</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.DistanceConstraint.html">DistanceConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.FixtureList.html">FixtureList</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.GearConstraint.html">GearConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.InversePointProxy.html">InversePointProxy</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.LockConstraint.html">LockConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.Material.html">Material</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.PointProxy.html">PointProxy</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.PrismaticConstraint.html">PrismaticConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.RevoluteConstraint.html">RevoluteConstraint</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.RotationalSpring.html">RotationalSpring</a> </li> <li class="class-depth-3"> <a href="Phaser.Physics.P2.Spring.html">Spring</a> </li> <li class="class-depth-1"> <a href="Phaser.Plugin.html">Plugin</a> </li> <li class="class-depth-1"> <a href="Phaser.PluginManager.html">PluginManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Point.html">Point</a> </li> <li class="class-depth-1"> <a href="Phaser.Pointer.html">Pointer</a> </li> <li class="class-depth-1"> <a href="Phaser.PointerMode.html">PointerMode</a> </li> <li class="class-depth-1"> <a href="Phaser.Polygon.html">Polygon</a> </li> <li class="class-depth-1"> <a href="Phaser.QuadTree.html">QuadTree</a> </li> <li class="class-depth-1"> <a href="Phaser.RandomDataGenerator.html">RandomDataGenerator</a> </li> <li class="class-depth-1"> <a href="Phaser.Rectangle.html">Rectangle</a> </li> <li class="class-depth-1"> <a href="Phaser.RenderTexture.html">RenderTexture</a> </li> <li class="class-depth-1"> <a href="Phaser.RequestAnimationFrame.html">RequestAnimationFrame</a> </li> <li class="class-depth-1"> <a href="Phaser.RetroFont.html">RetroFont</a> </li> <li class="class-depth-1"> <a href="Phaser.Rope.html">Rope</a> </li> <li class="class-depth-1"> <a href="Phaser.RoundedRectangle.html">RoundedRectangle</a> </li> <li class="class-depth-1"> <a href="Phaser.ScaleManager.html">ScaleManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Signal.html">Signal</a> </li> <li class="class-depth-1"> <a href="Phaser.SignalBinding.html">SignalBinding</a> </li> <li class="class-depth-1"> <a href="Phaser.SinglePad.html">SinglePad</a> </li> <li class="class-depth-1"> <a href="Phaser.Sound.html">Sound</a> </li> <li class="class-depth-1"> <a href="Phaser.SoundManager.html">SoundManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Sprite.html">Sprite</a> </li> <li class="class-depth-1"> <a href="Phaser.SpriteBatch.html">SpriteBatch</a> </li> <li class="class-depth-1"> <a href="Phaser.Stage.html">Stage</a> </li> <li class="class-depth-1"> <a href="Phaser.State.html">State</a> </li> <li class="class-depth-1"> <a href="Phaser.StateManager.html">StateManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Text.html">Text</a> </li> <li class="class-depth-1"> <a href="Phaser.Tile.html">Tile</a> </li> <li class="class-depth-1"> <a href="Phaser.Tilemap.html">Tilemap</a> </li> <li class="class-depth-1"> <a href="Phaser.TilemapLayer.html">TilemapLayer</a> </li> <li class="class-depth-1"> <a href="Phaser.TilemapParser.html">TilemapParser</a> </li> <li class="class-depth-1"> <a href="Phaser.Tileset.html">Tileset</a> </li> <li class="class-depth-1"> <a href="Phaser.TileSprite.html">TileSprite</a> </li> <li class="class-depth-1"> <a href="Phaser.Time.html">Time</a> </li> <li class="class-depth-1"> <a href="Phaser.Timer.html">Timer</a> </li> <li class="class-depth-1"> <a href="Phaser.TimerEvent.html">TimerEvent</a> </li> <li class="class-depth-1"> <a href="Phaser.Touch.html">Touch</a> </li> <li class="class-depth-1"> <a href="Phaser.Tween.html">Tween</a> </li> <li class="class-depth-1"> <a href="Phaser.TweenData.html">TweenData</a> </li> <li class="class-depth-1"> <a href="Phaser.TweenManager.html">TweenManager</a> </li> <li class="class-depth-1"> <a href="Phaser.Utils.html">Utils</a> </li> <li class="class-depth-2"> <a href="Phaser.Utils.Debug.html">Debug</a> </li> <li class="class-depth-1"> <a href="Phaser.Video.html">Video</a> </li> <li class="class-depth-1"> <a href="Phaser.World.html">World</a> </li> <li class="class-depth-1"> <a href="PIXI.AbstractFilter.html">AbstractFilter</a> </li> <li class="class-depth-1"> <a href="PIXI.BaseTexture.html">BaseTexture</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasBuffer.html">CanvasBuffer</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasGraphics.html">CanvasGraphics</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasMaskManager.html">CanvasMaskManager</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasPool.html">CanvasPool</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasRenderer.html">CanvasRenderer</a> </li> <li class="class-depth-1"> <a href="PIXI.CanvasTinter.html">CanvasTinter</a> </li> <li class="class-depth-1"> <a href="PIXI.ComplexPrimitiveShader.html">ComplexPrimitiveShader</a> </li> <li class="class-depth-1"> <a href="PIXI.DisplayObject.html">DisplayObject</a> </li> <li class="class-depth-1"> <a href="PIXI.DisplayObjectContainer.html">DisplayObjectContainer</a> </li> <li class="class-depth-1"> <a href="PIXI.EarCut.html">EarCut</a> </li> <li class="class-depth-1"> <a href="PIXI.Event.html">Event</a> </li> <li class="class-depth-1"> <a href="PIXI.EventTarget.html">EventTarget</a> </li> <li class="class-depth-1"> <a href="PIXI.FilterTexture.html">FilterTexture</a> </li> <li class="class-depth-1"> <a href="PIXI.Graphics.html">Graphics</a> </li> <li class="class-depth-1"> <a href="PIXI.GraphicsData.html">GraphicsData</a> </li> <li class="class-depth-1"> <a href="PIXI.PIXI.html">PIXI</a> </li> <li class="class-depth-1"> <a href="PIXI.PixiFastShader.html">PixiFastShader</a> </li> <li class="class-depth-1"> <a href="PIXI.PixiShader.html">PixiShader</a> </li> <li class="class-depth-1"> <a href="PIXI.PolyK.html">PolyK</a> </li> <li class="class-depth-1"> <a href="PIXI.PrimitiveShader.html">PrimitiveShader</a> </li> <li class="class-depth-1"> <a href="PIXI.RenderTexture.html">RenderTexture</a> </li> <li class="class-depth-1"> <a href="PIXI.Rope.html">Rope</a> </li> <li class="class-depth-1"> <a href="PIXI.Sprite.html">Sprite</a> </li> <li class="class-depth-1"> <a href="PIXI.SpriteBatch.html">SpriteBatch</a> </li> <li class="class-depth-1"> <a href="PIXI.Strip.html">Strip</a> </li> <li class="class-depth-1"> <a href="PIXI.StripShader.html">StripShader</a> </li> <li class="class-depth-1"> <a href="PIXI.Texture.html">Texture</a> </li> <li class="class-depth-1"> <a href="PIXI.TilingSprite.html">TilingSprite</a> </li> <li class="class-depth-1"> <a href="PIXI.WebGLBlendModeManager.html">WebGLBlendModeManager</a> </li> <li class="class-depth-1"> <a href="PIXI.WebGLFastSpriteBatch.html">WebGLFastSpriteBatch</a> </li> <li class="class-depth-1"> <a href="PIXI.WebGLFilterManager.html">WebGLFilterManager</a> </li> <li class="class-depth-1"> <a href="PIXI.WebGLRenderer.html">WebGLRenderer</a> </li> </ul> </li> <li class="dropdown"> <a href="global.html" class="dropdown-toggle" data-toggle="dropdown">Global<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-0"> <a href="global.html#AUTO">AUTO</a> </li> <li class="class-depth-0"> <a href="global.html#BITMAPDATA">BITMAPDATA</a> </li> <li class="class-depth-0"> <a href="global.html#BITMAPTEXT">BITMAPTEXT</a> </li> <li class="class-depth-0"> <a href="global.html#blendModes">blendModes</a> </li> <li class="class-depth-0"> <a href="global.html#BUTTON">BUTTON</a> </li> <li class="class-depth-0"> <a href="global.html#CANVAS">CANVAS</a> </li> <li class="class-depth-0"> <a href="global.html#CANVAS_FILTER">CANVAS_FILTER</a> </li> <li class="class-depth-0"> <a href="global.html#CIRCLE">CIRCLE</a> </li> <li class="class-depth-0"> <a href="global.html#CREATURE">CREATURE</a> </li> <li class="class-depth-0"> <a href="global.html#DOWN">DOWN</a> </li> <li class="class-depth-0"> <a href="global.html#ELLIPSE">ELLIPSE</a> </li> <li class="class-depth-0"> <a href="global.html#EMITTER">EMITTER</a> </li> <li class="class-depth-0"> <a href="global.html#GAMES">GAMES</a> </li> <li class="class-depth-0"> <a href="global.html#GRAPHICS">GRAPHICS</a> </li> <li class="class-depth-0"> <a href="global.html#GROUP">GROUP</a> </li> <li class="class-depth-0"> <a href="global.html#HEADLESS">HEADLESS</a> </li> <li class="class-depth-0"> <a href="global.html#IMAGE">IMAGE</a> </li> <li class="class-depth-0"> <a href="global.html#LEFT">LEFT</a> </li> <li class="class-depth-0"> <a href="global.html#LINE">LINE</a> </li> <li class="class-depth-0"> <a href="global.html#MATRIX">MATRIX</a> </li> <li class="class-depth-0"> <a href="global.html#NONE">NONE</a> </li> <li class="class-depth-0"> <a href="global.html#PENDING_ATLAS">PENDING_ATLAS</a> </li> <li class="class-depth-0"> <a href="global.html#POINT">POINT</a> </li> <li class="class-depth-0"> <a href="global.html#POINTER">POINTER</a> </li> <li class="class-depth-0"> <a href="global.html#POLYGON">POLYGON</a> </li> <li class="class-depth-0"> <a href="global.html#RECTANGLE">RECTANGLE</a> </li> <li class="class-depth-0"> <a href="global.html#RENDERTEXTURE">RENDERTEXTURE</a> </li> <li class="class-depth-0"> <a href="global.html#RETROFONT">RETROFONT</a> </li> <li class="class-depth-0"> <a href="global.html#RIGHT">RIGHT</a> </li> <li class="class-depth-0"> <a href="global.html#ROPE">ROPE</a> </li> <li class="class-depth-0"> <a href="global.html#ROUNDEDRECTANGLE">ROUNDEDRECTANGLE</a> </li> <li class="class-depth-0"> <a href="global.html#scaleModes">scaleModes</a> </li> <li class="class-depth-0"> <a href="global.html#SPRITE">SPRITE</a> </li> <li class="class-depth-0"> <a href="global.html#SPRITEBATCH">SPRITEBATCH</a> </li> <li class="class-depth-0"> <a href="global.html#TEXT">TEXT</a> </li> <li class="class-depth-0"> <a href="global.html#TILEMAP">TILEMAP</a> </li> <li class="class-depth-0"> <a href="global.html#TILEMAPLAYER">TILEMAPLAYER</a> </li> <li class="class-depth-0"> <a href="global.html#TILESPRITE">TILESPRITE</a> </li> <li class="class-depth-0"> <a href="global.html#UP">UP</a> </li> <li class="class-depth-0"> <a href="global.html#VERSION">VERSION</a> </li> <li class="class-depth-0"> <a href="global.html#VIDEO">VIDEO</a> </li> <li class="class-depth-0"> <a href="global.html#WEBGL">WEBGL</a> </li> <li class="class-depth-0"> <a href="global.html#WEBGL_FILTER">WEBGL_FILTER</a> </li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Core<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.Game.html">Game</a></li> <li class="class-depth-1"><a href="Phaser.Group.html">Group</a></li> <li class="class-depth-1"><a href="Phaser.World.html">World</a></li> <li class="class-depth-1"><a href="Phaser.Loader.html">Loader</a></li> <li class="class-depth-1"><a href="Phaser.Cache.html">Cache</a></li> <li class="class-depth-1"><a href="Phaser.Time.html">Time</a></li> <li class="class-depth-1"><a href="Phaser.Camera.html">Camera</a></li> <li class="class-depth-1"><a href="Phaser.StateManager.html">State Manager</a></li> <li class="class-depth-1"><a href="Phaser.TweenManager.html">Tween Manager</a></li> <li class="class-depth-1"><a href="Phaser.SoundManager.html">Sound Manager</a></li> <li class="class-depth-1"><a href="Phaser.Input.html">Input Manager</a></li> <li class="class-depth-1"><a href="Phaser.ScaleManager.html">Scale Manager</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Game Objects<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.GameObjectFactory.html">Factory (game.add)</a></li> <li class="class-depth-1"><a href="Phaser.GameObjectCreator.html">Creator (game.make)</a></li> <li class="class-depth-1"><a href="Phaser.Sprite.html">Sprite</a></li> <li class="class-depth-1"><a href="Phaser.Image.html">Image</a></li> <li class="class-depth-1"><a href="Phaser.Sound.html">Sound</a></li> <li class="class-depth-1"><a href="Phaser.Video.html">Video</a></li> <li class="class-depth-1"><a href="Phaser.Particles.Arcade.Emitter.html">Particle Emitter</a></li> <li class="class-depth-1"><a href="Phaser.Particle.html">Particle</a></li> <li class="class-depth-1"><a href="Phaser.Text.html">Text</a></li> <li class="class-depth-1"><a href="Phaser.Tween.html">Tween</a></li> <li class="class-depth-1"><a href="Phaser.BitmapText.html">BitmapText</a></li> <li class="class-depth-1"><a href="Phaser.Tilemap.html">Tilemap</a></li> <li class="class-depth-1"><a href="Phaser.BitmapData.html">BitmapData</a></li> <li class="class-depth-1"><a href="Phaser.RetroFont.html">RetroFont</a></li> <li class="class-depth-1"><a href="Phaser.Button.html">Button</a></li> <li class="class-depth-1"><a href="Phaser.Animation.html">Animation</a></li> <li class="class-depth-1"><a href="Phaser.Graphics.html">Graphics</a></li> <li class="class-depth-1"><a href="Phaser.RenderTexture.html">RenderTexture</a></li> <li class="class-depth-1"><a href="Phaser.TileSprite.html">TileSprite</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Geometry<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.Circle.html">Circle</a></li> <li class="class-depth-1"><a href="Phaser.Ellipse.html">Ellipse</a></li> <li class="class-depth-1"><a href="Phaser.Line.html">Line</a></li> <li class="class-depth-1"><a href="Phaser.Matrix.html">Matrix</a></li> <li class="class-depth-1"><a href="Phaser.Point.html">Point</a></li> <li class="class-depth-1"><a href="Phaser.Polygon.html">Polygon</a></li> <li class="class-depth-1"><a href="Phaser.Rectangle.html">Rectangle</a></li> <li class="class-depth-1"><a href="Phaser.RoundedRectangle.html">Rounded Rectangle</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Physics<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.Physics.Arcade.html">Arcade Physics</a></li> <li class="class-depth-2"><a href="Phaser.Physics.Arcade.Body.html">Body</a></li> <li class="class-depth-1"><a href="Phaser.Physics.P2.html">P2 Physics</a></li> <li class="class-depth-2"><a href="Phaser.Physics.P2.Body.html">Body</a></li> <li class="class-depth-2"><a href="Phaser.Physics.P2.Spring.html">Spring</a></li> <li class="class-depth-2"><a href="Phaser.Physics.P2.CollisionGroup.html">CollisionGroup</a></li> <li class="class-depth-2"><a href="Phaser.Physics.P2.ContactMaterial.html">ContactMaterial</a></li> <li class="class-depth-1"><a href="Phaser.Physics.Ninja.html">Ninja Physics</a></li> <li class="class-depth-2"><a href="Phaser.Physics.Body.html">Body</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Input<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="Phaser.InputHandler.html">Input Handler</a></li> <li class="class-depth-1"><a href="Phaser.Pointer.html">Pointer</a></li> <li class="class-depth-1"><a href="Phaser.DeviceButton.html">Device Button</a></li> <li class="class-depth-1"><a href="Phaser.Mouse.html">Mouse</a></li> <li class="class-depth-1"><a href="Phaser.Keyboard.html">Keyboard</a></li> <li class="class-depth-1"><a href="Phaser.Key.html">Key</a></li> <li class="class-depth-1"><a href="Phaser.Gamepad.html">Gamepad</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Community<b class="caret"></b></a> <ul class="dropdown-menu "> <li class="class-depth-1"><a href="http://phaser.io">Phaser Web Site</a></li> <li class="class-depth-1"><a href="https://github.com/photonstorm/phaser">Phaser Github</a></li> <li class="class-depth-1"><a href="http://phaser.io/examples">Phaser Examples</a></li> <li class="class-depth-1"><a href="https://github.com/photonstorm/phaser-plugins">Phaser Plugins</a></li> <li class="class-depth-1"><a href="http://www.html5gamedevs.com/forum/14-phaser/">Forum</a></li> <li class="class-depth-1"><a href="http://stackoverflow.com/questions/tagged/phaser-framework">Stack Overflow</a></li> <li class="class-depth-1"><a href="http://phaser.io/learn">Tutorials</a></li> <li class="class-depth-1"><a href="https://confirmsubscription.com/h/r/369DE48E3E86AF1E">Newsletter</a></li> <li class="class-depth-1"><a href="http://phaser.io/community/twitter">Twitter</a></li> <li class="class-depth-1"><a href="http://phaser.io/community/irc">IRC</a></li> <li class="class-depth-1"><a href="https://www.codeandweb.com/texturepacker/phaser">Texture Packer</a></li> </ul> </li> </ul> </div> </div> <div class="row-fluid"> <div class="span12"> <div id="main"> <h1 class="page-title">Source: src/geom/Line.js</h1> <section> <article> <pre class="sunlight-highlight-javascript linenums">/** * @author Richard Davey &lt;[email protected]> * @copyright 2016 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Creates a new Line object with a start and an end point. * * @class Phaser.Line * @constructor * @param {number} [x1=0] - The x coordinate of the start of the line. * @param {number} [y1=0] - The y coordinate of the start of the line. * @param {number} [x2=0] - The x coordinate of the end of the line. * @param {number} [y2=0] - The y coordinate of the end of the line. */ Phaser.Line = function (x1, y1, x2, y2) { x1 = x1 || 0; y1 = y1 || 0; x2 = x2 || 0; y2 = y2 || 0; /** * @property {Phaser.Point} start - The start point of the line. */ this.start = new Phaser.Point(x1, y1); /** * @property {Phaser.Point} end - The end point of the line. */ this.end = new Phaser.Point(x2, y2); /** * @property {number} type - The const type of this object. * @readonly */ this.type = Phaser.LINE; }; Phaser.Line.prototype = { /** * Sets the components of the Line to the specified values. * * @method Phaser.Line#setTo * @param {number} [x1=0] - The x coordinate of the start of the line. * @param {number} [y1=0] - The y coordinate of the start of the line. * @param {number} [x2=0] - The x coordinate of the end of the line. * @param {number} [y2=0] - The y coordinate of the end of the line. * @return {Phaser.Line} This line object */ setTo: function (x1, y1, x2, y2) { this.start.setTo(x1, y1); this.end.setTo(x2, y2); return this; }, /** * Sets the line to match the x/y coordinates of the two given sprites. * Can optionally be calculated from their center coordinates. * * @method Phaser.Line#fromSprite * @param {Phaser.Sprite} startSprite - The coordinates of this Sprite will be set to the Line.start point. * @param {Phaser.Sprite} endSprite - The coordinates of this Sprite will be set to the Line.start point. * @param {boolean} [useCenter=false] - If true it will use startSprite.center.x, if false startSprite.x. Note that Sprites don't have a center property by default, so only enable if you've over-ridden your Sprite with a custom class. * @return {Phaser.Line} This line object */ fromSprite: function (startSprite, endSprite, useCenter) { if (useCenter === undefined) { useCenter = false; } if (useCenter) { return this.setTo(startSprite.center.x, startSprite.center.y, endSprite.center.x, endSprite.center.y); } return this.setTo(startSprite.x, startSprite.y, endSprite.x, endSprite.y); }, /** * Sets this line to start at the given `x` and `y` coordinates and for the segment to extend at `angle` for the given `length`. * * @method Phaser.Line#fromAngle * @param {number} x - The x coordinate of the start of the line. * @param {number} y - The y coordinate of the start of the line. * @param {number} angle - The angle of the line in radians. * @param {number} length - The length of the line in pixels. * @return {Phaser.Line} This line object */ fromAngle: function (x, y, angle, length) { this.start.setTo(x, y); this.end.setTo(x + (Math.cos(angle) * length), y + (Math.sin(angle) * length)); return this; }, /** * Rotates the line by the amount specified in `angle`. * * Rotation takes place from the center of the line. * If you wish to rotate around a different point see Line.rotateAround. * * If you wish to rotate the ends of the Line then see Line.start.rotate or Line.end.rotate. * * @method Phaser.Line#rotate * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by. * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? * @return {Phaser.Line} This line object */ rotate: function (angle, asDegrees) { var cx = (this.start.x + this.end.x) / 2; var cy = (this.start.y + this.end.y) / 2; this.start.rotate(cx, cy, angle, asDegrees); this.end.rotate(cx, cy, angle, asDegrees); return this; }, /** * Rotates the line by the amount specified in `angle`. * * Rotation takes place around the coordinates given. * * @method Phaser.Line#rotateAround * @param {number} x - The x coordinate to offset the rotation from. * @param {number} y - The y coordinate to offset the rotation from. * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by. * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)? * @return {Phaser.Line} This line object */ rotateAround: function (x, y, angle, asDegrees) { this.start.rotate(x, y, angle, asDegrees); this.end.rotate(x, y, angle, asDegrees); return this; }, /** * Checks for intersection between this line and another Line. * If asSegment is true it will check for segment intersection. If asSegment is false it will check for line intersection. * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. * * @method Phaser.Line#intersects * @param {Phaser.Line} line - The line to check against this one. * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created. * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. */ intersects: function (line, asSegment, result) { return Phaser.Line.intersectsPoints(this.start, this.end, line.start, line.end, asSegment, result); }, /** * Returns the reflected angle between two lines. * This is the outgoing angle based on the angle of this line and the normalAngle of the given line. * * @method Phaser.Line#reflect * @param {Phaser.Line} line - The line to reflect off this line. * @return {number} The reflected angle in radians. */ reflect: function (line) { return Phaser.Line.reflect(this, line); }, /** * Returns a Point object where the x and y values correspond to the center (or midpoint) of the Line segment. * * @method Phaser.Line#midPoint * @param {Phaser.Point} [out] - A Phaser.Point object into which the result will be populated. If not given a new Point object is created. * @return {Phaser.Point} A Phaser.Point object with the x and y values set to the center of the line segment. */ midPoint: function (out) { if (out === undefined) { out = new Phaser.Point(); } out.x = (this.start.x + this.end.x) / 2; out.y = (this.start.y + this.end.y) / 2; return out; }, /** * Centers this Line on the given coordinates. * * The line is centered by positioning the start and end points so that the lines midpoint matches * the coordinates given. * * @method Phaser.Line#centerOn * @param {number} x - The x position to center the line on. * @param {number} y - The y position to center the line on. * @return {Phaser.Line} This line object */ centerOn: function (x, y) { var cx = (this.start.x + this.end.x) / 2; var cy = (this.start.y + this.end.y) / 2; var tx = x - cx; var ty = y - cy; this.start.add(tx, ty); this.end.add(tx, ty); }, /** * Tests if the given coordinates fall on this line. See pointOnSegment to test against just the line segment. * * @method Phaser.Line#pointOnLine * @param {number} x - The line to check against this one. * @param {number} y - The line to check against this one. * @return {boolean} True if the point is on the line, false if not. */ pointOnLine: function (x, y) { return ((x - this.start.x) * (this.end.y - this.start.y) === (this.end.x - this.start.x) * (y - this.start.y)); }, /** * Tests if the given coordinates fall on this line and within the segment. See pointOnLine to test against just the line. * * @method Phaser.Line#pointOnSegment * @param {number} x - The line to check against this one. * @param {number} y - The line to check against this one. * @return {boolean} True if the point is on the line and segment, false if not. */ pointOnSegment: function (x, y) { var xMin = Math.min(this.start.x, this.end.x); var xMax = Math.max(this.start.x, this.end.x); var yMin = Math.min(this.start.y, this.end.y); var yMax = Math.max(this.start.y, this.end.y); return (this.pointOnLine(x, y) &amp;&amp; (x >= xMin &amp;&amp; x &lt;= xMax) &amp;&amp; (y >= yMin &amp;&amp; y &lt;= yMax)); }, /** * Picks a random point from anywhere on the Line segment and returns it. * * @method Phaser.Line#random * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in. * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an object. * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties. */ random: function (out) { if (out === undefined) { out = new Phaser.Point(); } var t = Math.random(); out.x = this.start.x + t * (this.end.x - this.start.x); out.y = this.start.y + t * (this.end.y - this.start.y); return out; }, /** * Using Bresenham's line algorithm this will return an array of all coordinates on this line. * The start and end points are rounded before this runs as the algorithm works on integers. * * @method Phaser.Line#coordinatesOnLine * @param {number} [stepRate=1] - How many steps will we return? 1 = every coordinate on the line, 2 = every other coordinate, etc. * @param {array} [results] - The array to store the results in. If not provided a new one will be generated. * @return {array} An array of coordinates. */ coordinatesOnLine: function (stepRate, results) { if (stepRate === undefined) { stepRate = 1; } if (results === undefined) { results = []; } var x1 = Math.round(this.start.x); var y1 = Math.round(this.start.y); var x2 = Math.round(this.end.x); var y2 = Math.round(this.end.y); var dx = Math.abs(x2 - x1); var dy = Math.abs(y2 - y1); var sx = (x1 &lt; x2) ? 1 : -1; var sy = (y1 &lt; y2) ? 1 : -1; var err = dx - dy; results.push([x1, y1]); var i = 1; while (!((x1 == x2) &amp;&amp; (y1 == y2))) { var e2 = err &lt;&lt; 1; if (e2 > -dy) { err -= dy; x1 += sx; } if (e2 &lt; dx) { err += dx; y1 += sy; } if (i % stepRate === 0) { results.push([x1, y1]); } i++; } return results; }, /** * Returns a new Line object with the same values for the start and end properties as this Line object. * @method Phaser.Line#clone * @param {Phaser.Line} output - Optional Line object. If given the values will be set into the object, otherwise a brand new Line object will be created and returned. * @return {Phaser.Line} The cloned Line object. */ clone: function (output) { if (output === undefined || output === null) { output = new Phaser.Line(this.start.x, this.start.y, this.end.x, this.end.y); } else { output.setTo(this.start.x, this.start.y, this.end.x, this.end.y); } return output; } }; /** * @name Phaser.Line#length * @property {number} length - Gets the length of the line segment. * @readonly */ Object.defineProperty(Phaser.Line.prototype, "length", { get: function () { return Math.sqrt((this.end.x - this.start.x) * (this.end.x - this.start.x) + (this.end.y - this.start.y) * (this.end.y - this.start.y)); } }); /** * @name Phaser.Line#angle * @property {number} angle - Gets the angle of the line in radians. * @readonly */ Object.defineProperty(Phaser.Line.prototype, "angle", { get: function () { return Math.atan2(this.end.y - this.start.y, this.end.x - this.start.x); } }); /** * @name Phaser.Line#slope * @property {number} slope - Gets the slope of the line (y/x). * @readonly */ Object.defineProperty(Phaser.Line.prototype, "slope", { get: function () { return (this.end.y - this.start.y) / (this.end.x - this.start.x); } }); /** * @name Phaser.Line#perpSlope * @property {number} perpSlope - Gets the perpendicular slope of the line (x/y). * @readonly */ Object.defineProperty(Phaser.Line.prototype, "perpSlope", { get: function () { return -((this.end.x - this.start.x) / (this.end.y - this.start.y)); } }); /** * @name Phaser.Line#x * @property {number} x - Gets the x coordinate of the top left of the bounds around this line. * @readonly */ Object.defineProperty(Phaser.Line.prototype, "x", { get: function () { return Math.min(this.start.x, this.end.x); } }); /** * @name Phaser.Line#y * @property {number} y - Gets the y coordinate of the top left of the bounds around this line. * @readonly */ Object.defineProperty(Phaser.Line.prototype, "y", { get: function () { return Math.min(this.start.y, this.end.y); } }); /** * @name Phaser.Line#left * @property {number} left - Gets the left-most point of this line. * @readonly */ Object.defineProperty(Phaser.Line.prototype, "left", { get: function () { return Math.min(this.start.x, this.end.x); } }); /** * @name Phaser.Line#right * @property {number} right - Gets the right-most point of this line. * @readonly */ Object.defineProperty(Phaser.Line.prototype, "right", { get: function () { return Math.max(this.start.x, this.end.x); } }); /** * @name Phaser.Line#top * @property {number} top - Gets the top-most point of this line. * @readonly */ Object.defineProperty(Phaser.Line.prototype, "top", { get: function () { return Math.min(this.start.y, this.end.y); } }); /** * @name Phaser.Line#bottom * @property {number} bottom - Gets the bottom-most point of this line. * @readonly */ Object.defineProperty(Phaser.Line.prototype, "bottom", { get: function () { return Math.max(this.start.y, this.end.y); } }); /** * @name Phaser.Line#width * @property {number} width - Gets the width of this bounds of this line. * @readonly */ Object.defineProperty(Phaser.Line.prototype, "width", { get: function () { return Math.abs(this.start.x - this.end.x); } }); /** * @name Phaser.Line#height * @property {number} height - Gets the height of this bounds of this line. * @readonly */ Object.defineProperty(Phaser.Line.prototype, "height", { get: function () { return Math.abs(this.start.y - this.end.y); } }); /** * @name Phaser.Line#normalX * @property {number} normalX - Gets the x component of the left-hand normal of this line. * @readonly */ Object.defineProperty(Phaser.Line.prototype, "normalX", { get: function () { return Math.cos(this.angle - 1.5707963267948966); } }); /** * @name Phaser.Line#normalY * @property {number} normalY - Gets the y component of the left-hand normal of this line. * @readonly */ Object.defineProperty(Phaser.Line.prototype, "normalY", { get: function () { return Math.sin(this.angle - 1.5707963267948966); } }); /** * @name Phaser.Line#normalAngle * @property {number} normalAngle - Gets the angle in radians of the normal of this line (line.angle - 90 degrees.) * @readonly */ Object.defineProperty(Phaser.Line.prototype, "normalAngle", { get: function () { return Phaser.Math.wrap(this.angle - 1.5707963267948966, -Math.PI, Math.PI); } }); /** * Checks for intersection between two lines as defined by the given start and end points. * If asSegment is true it will check for line segment intersection. If asSegment is false it will check for line intersection. * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. * Adapted from code by Keith Hair * * @method Phaser.Line.intersectsPoints * @param {Phaser.Point} a - The start of the first Line to be checked. * @param {Phaser.Point} b - The end of the first line to be checked. * @param {Phaser.Point} e - The start of the second Line to be checked. * @param {Phaser.Point} f - The end of the second line to be checked. * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. * @param {Phaser.Point|object} [result] - A Point object to store the result in, if not given a new one will be created. * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. */ Phaser.Line.intersectsPoints = function (a, b, e, f, asSegment, result) { if (asSegment === undefined) { asSegment = true; } if (result === undefined) { result = new Phaser.Point(); } var a1 = b.y - a.y; var a2 = f.y - e.y; var b1 = a.x - b.x; var b2 = e.x - f.x; var c1 = (b.x * a.y) - (a.x * b.y); var c2 = (f.x * e.y) - (e.x * f.y); var denom = (a1 * b2) - (a2 * b1); if (denom === 0) { return null; } result.x = ((b1 * c2) - (b2 * c1)) / denom; result.y = ((a2 * c1) - (a1 * c2)) / denom; if (asSegment) { var uc = ((f.y - e.y) * (b.x - a.x) - (f.x - e.x) * (b.y - a.y)); var ua = (((f.x - e.x) * (a.y - e.y)) - (f.y - e.y) * (a.x - e.x)) / uc; var ub = (((b.x - a.x) * (a.y - e.y)) - ((b.y - a.y) * (a.x - e.x))) / uc; if (ua >= 0 &amp;&amp; ua &lt;= 1 &amp;&amp; ub >= 0 &amp;&amp; ub &lt;= 1) { return result; } else { return null; } } return result; }; /** * Checks for intersection between two lines. * If asSegment is true it will check for segment intersection. * If asSegment is false it will check for line intersection. * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection. * Adapted from code by Keith Hair * * @method Phaser.Line.intersects * @param {Phaser.Line} a - The first Line to be checked. * @param {Phaser.Line} b - The second Line to be checked. * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection. * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created. * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection. */ Phaser.Line.intersects = function (a, b, asSegment, result) { return Phaser.Line.intersectsPoints(a.start, a.end, b.start, b.end, asSegment, result); }; /** * Returns the reflected angle between two lines. * This is the outgoing angle based on the angle of Line 1 and the normalAngle of Line 2. * * @method Phaser.Line.reflect * @param {Phaser.Line} a - The base line. * @param {Phaser.Line} b - The line to be reflected from the base line. * @return {number} The reflected angle in radians. */ Phaser.Line.reflect = function (a, b) { return 2 * b.normalAngle - 3.141592653589793 - a.angle; }; </pre> </article> </section> </div> <div class="clearfix"></div> <footer> <span class="copyright"> Phaser Copyright © 2012-2016 Photon Storm Ltd. </span> <br /> <span class="jsdoc-message"> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.3.2</a> on Fri Apr 22 2016 15:11:45 GMT+0100 (GMT Daylight Time) using the <a href="https://github.com/terryweiss/docstrap">DocStrap template</a>. </span> </footer> </div> <br clear="both"> </div> </div> <script src="scripts/sunlight.js"></script> <script src="scripts/sunlight.javascript.js"></script> <script src="scripts/sunlight-plugin.doclinks.js"></script> <script src="scripts/sunlight-plugin.linenumbers.js"></script> <script src="scripts/sunlight-plugin.menu.js"></script> <script src="scripts/jquery.min.js"></script> <script src="scripts/jquery.scrollTo.js"></script> <script src="scripts/jquery.localScroll.js"></script> <script src="scripts/bootstrap-dropdown.js"></script> <script src="scripts/toc.js"></script> <script> Sunlight.highlightAll({lineNumbers:true, showMenu: true, enableDoclinks :true}); </script> <script> $( function () { $( "#toc" ).toc( { anchorName : function(i, heading, prefix) { return $(heading).attr("id") || ( prefix + i ); }, selectors : "h1,h2,h3,h4", showAndHide : false, scrollTo : 60 } ); $( "#toc>ul" ).addClass( "nav nav-pills nav-stacked" ); $( "#main span[id^='toc']" ).addClass( "toc-shim" ); } ); </script> </body> </html>
pzyu/orbital-game
phaser/docs/src_geom_Line.js.html
HTML
mit
54,825
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using NuGet.Configuration; namespace Cake.NuGet.Tests.Stubs { internal sealed class FakeNuGetSettings : ISettings { public event EventHandler SettingsChanged; private IDictionary<string, FakeNuGetSettingSection> _settings; public FakeNuGetSettings() { _settings = new Dictionary<string, FakeNuGetSettingSection>(StringComparer.OrdinalIgnoreCase); } public void AddOrUpdate(string sectionName, SettingItem item) { if (!_settings.TryGetValue(sectionName, out var section)) { section = new FakeNuGetSettingSection(sectionName, null, Enumerable.Empty<SettingItem>()); _settings[sectionName] = section; } section.AddItem(item); SettingsChanged?.Invoke(this, new EventArgs()); } public IList<string> GetConfigFilePaths() { return Array.Empty<string>(); } public IList<string> GetConfigRoots() { return Array.Empty<string>(); } public SettingSection GetSection(string sectionName) { return _settings.TryGetValue(sectionName, out var value) ? value : null; } public void Remove(string sectionName, SettingItem item) { } public void SaveToDisk() { } } }
patriksvensson/cake
src/Cake.NuGet.Tests/Stubs/FakeNuGetSettings.cs
C#
mit
1,666
// Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_OBJECTS_MAYBE_OBJECT_H_ #define V8_OBJECTS_MAYBE_OBJECT_H_ #include "src/objects/tagged-impl.h" namespace v8 { namespace internal { // A MaybeObject is either a SMI, a strong reference to a HeapObject, a weak // reference to a HeapObject, or a cleared weak reference. It's used for // implementing in-place weak references (see design doc: goo.gl/j6SdcK ) class MaybeObject : public TaggedImpl<HeapObjectReferenceType::WEAK, Address> { public: constexpr MaybeObject() : TaggedImpl(kNullAddress) {} constexpr explicit MaybeObject(Address ptr) : TaggedImpl(ptr) {} // These operator->() overloads are required for handlified code. constexpr const MaybeObject* operator->() const { return this; } V8_INLINE static MaybeObject FromSmi(Smi smi); V8_INLINE static MaybeObject FromObject(Object object); V8_INLINE static MaybeObject MakeWeak(MaybeObject object); #ifdef VERIFY_HEAP static void VerifyMaybeObjectPointer(Isolate* isolate, MaybeObject p); #endif private: template <typename TFieldType, int kFieldOffset> friend class TaggedField; }; // A HeapObjectReference is either a strong reference to a HeapObject, a weak // reference to a HeapObject, or a cleared weak reference. class HeapObjectReference : public MaybeObject { public: explicit HeapObjectReference(Address address) : MaybeObject(address) {} V8_INLINE explicit HeapObjectReference(Object object); V8_INLINE static HeapObjectReference Strong(Object object); V8_INLINE static HeapObjectReference Weak(Object object); V8_INLINE static HeapObjectReference ClearedValue(Isolate* isolate); template <typename THeapObjectSlot> V8_INLINE static void Update(THeapObjectSlot slot, HeapObject value); }; } // namespace internal } // namespace v8 #endif // V8_OBJECTS_MAYBE_OBJECT_H_
enclose-io/compiler
lts/deps/v8/src/objects/maybe-object.h
C
mit
1,971
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\SecurityBundle\DataCollector; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Role\RoleHierarchyInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\DataCollector\DataCollector; use Symfony\Component\HttpKernel\DataCollector\LateDataCollectorInterface; use Symfony\Component\Security\Core\Role\RoleInterface; use Symfony\Component\Security\Http\Logout\LogoutUrlGenerator; use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface; use Symfony\Component\Security\Core\Authorization\TraceableAccessDecisionManager; use Symfony\Component\VarDumper\Caster\ClassStub; use Symfony\Component\VarDumper\Cloner\Data; use Symfony\Component\Security\Http\FirewallMapInterface; use Symfony\Bundle\SecurityBundle\Security\FirewallMap; /** * @author Fabien Potencier <[email protected]> */ class SecurityDataCollector extends DataCollector implements LateDataCollectorInterface { private $tokenStorage; private $roleHierarchy; private $logoutUrlGenerator; private $accessDecisionManager; private $firewallMap; private $hasVarDumper; /** * @param TokenStorageInterface|null $tokenStorage * @param RoleHierarchyInterface|null $roleHierarchy * @param LogoutUrlGenerator|null $logoutUrlGenerator * @param AccessDecisionManagerInterface|null $accessDecisionManager * @param FirewallMapInterface|null $firewallMap */ public function __construct(TokenStorageInterface $tokenStorage = null, RoleHierarchyInterface $roleHierarchy = null, LogoutUrlGenerator $logoutUrlGenerator = null, AccessDecisionManagerInterface $accessDecisionManager = null, FirewallMapInterface $firewallMap = null) { $this->tokenStorage = $tokenStorage; $this->roleHierarchy = $roleHierarchy; $this->logoutUrlGenerator = $logoutUrlGenerator; $this->accessDecisionManager = $accessDecisionManager; $this->firewallMap = $firewallMap; $this->hasVarDumper = class_exists(ClassStub::class); } /** * {@inheritdoc} */ public function collect(Request $request, Response $response, \Exception $exception = null) { if (null === $this->tokenStorage) { $this->data = array( 'enabled' => false, 'authenticated' => false, 'token' => null, 'token_class' => null, 'logout_url' => null, 'user' => '', 'roles' => array(), 'inherited_roles' => array(), 'supports_role_hierarchy' => null !== $this->roleHierarchy, ); } elseif (null === $token = $this->tokenStorage->getToken()) { $this->data = array( 'enabled' => true, 'authenticated' => false, 'token' => null, 'token_class' => null, 'logout_url' => null, 'user' => '', 'roles' => array(), 'inherited_roles' => array(), 'supports_role_hierarchy' => null !== $this->roleHierarchy, ); } else { $inheritedRoles = array(); $assignedRoles = $token->getRoles(); if (null !== $this->roleHierarchy) { $allRoles = $this->roleHierarchy->getReachableRoles($assignedRoles); foreach ($allRoles as $role) { if (!in_array($role, $assignedRoles, true)) { $inheritedRoles[] = $role; } } } $logoutUrl = null; try { if (null !== $this->logoutUrlGenerator) { $logoutUrl = $this->logoutUrlGenerator->getLogoutPath(); } } catch (\Exception $e) { // fail silently when the logout URL cannot be generated } $this->data = array( 'enabled' => true, 'authenticated' => $token->isAuthenticated(), 'token' => $token, 'token_class' => $this->hasVarDumper ? new ClassStub(get_class($token)) : get_class($token), 'logout_url' => $logoutUrl, 'user' => $token->getUsername(), 'roles' => array_map(function (RoleInterface $role) { return $role->getRole(); }, $assignedRoles), 'inherited_roles' => array_unique(array_map(function (RoleInterface $role) { return $role->getRole(); }, $inheritedRoles)), 'supports_role_hierarchy' => null !== $this->roleHierarchy, ); } // collect voters and access decision manager information if ($this->accessDecisionManager instanceof TraceableAccessDecisionManager) { $this->data['access_decision_log'] = $this->accessDecisionManager->getDecisionLog(); $this->data['voter_strategy'] = $this->accessDecisionManager->getStrategy(); foreach ($this->accessDecisionManager->getVoters() as $voter) { $this->data['voters'][] = $this->hasVarDumper ? new ClassStub(get_class($voter)) : get_class($voter); } } else { $this->data['access_decision_log'] = array(); $this->data['voter_strategy'] = 'unknown'; $this->data['voters'] = array(); } // collect firewall context information $this->data['firewall'] = null; if ($this->firewallMap instanceof FirewallMap) { $firewallConfig = $this->firewallMap->getFirewallConfig($request); if (null !== $firewallConfig) { $this->data['firewall'] = array( 'name' => $firewallConfig->getName(), 'allows_anonymous' => $firewallConfig->allowsAnonymous(), 'request_matcher' => $firewallConfig->getRequestMatcher(), 'security_enabled' => $firewallConfig->isSecurityEnabled(), 'stateless' => $firewallConfig->isStateless(), 'provider' => $firewallConfig->getProvider(), 'context' => $firewallConfig->getContext(), 'entry_point' => $firewallConfig->getEntryPoint(), 'access_denied_handler' => $firewallConfig->getAccessDeniedHandler(), 'access_denied_url' => $firewallConfig->getAccessDeniedUrl(), 'user_checker' => $firewallConfig->getUserChecker(), 'listeners' => $firewallConfig->getListeners(), ); } } } public function lateCollect() { $this->data = $this->cloneVar($this->data); } /** * Checks if security is enabled. * * @return bool true if security is enabled, false otherwise */ public function isEnabled() { return $this->data['enabled']; } /** * Gets the user. * * @return string The user */ public function getUser() { return $this->data['user']; } /** * Gets the roles of the user. * * @return array The roles */ public function getRoles() { return $this->data['roles']; } /** * Gets the inherited roles of the user. * * @return array The inherited roles */ public function getInheritedRoles() { return $this->data['inherited_roles']; } /** * Checks if the data contains information about inherited roles. Still the inherited * roles can be an empty array. * * @return bool true if the profile was contains inherited role information */ public function supportsRoleHierarchy() { return $this->data['supports_role_hierarchy']; } /** * Checks if the user is authenticated or not. * * @return bool true if the user is authenticated, false otherwise */ public function isAuthenticated() { return $this->data['authenticated']; } /** * Get the class name of the security token. * * @return string The token */ public function getTokenClass() { return $this->data['token_class']; } /** * Get the full security token class as Data object. * * @return Data */ public function getToken() { return $this->data['token']; } /** * Get the provider key (i.e. the name of the active firewall). * * @return string The provider key */ public function getLogoutUrl() { return $this->data['logout_url']; } /** * Returns the FQCN of the security voters enabled in the application. * * @return string[] */ public function getVoters() { return $this->data['voters']; } /** * Returns the strategy configured for the security voters. * * @return string */ public function getVoterStrategy() { return $this->data['voter_strategy']; } /** * Returns the log of the security decisions made by the access decision manager. * * @return array */ public function getAccessDecisionLog() { return $this->data['access_decision_log']; } /** * Returns the configuration of the current firewall context. * * @return array */ public function getFirewall() { return $this->data['firewall']; } /** * {@inheritdoc} */ public function getName() { return 'security'; } }
UrbanLion/developmentpricing
vendor/symfony/symfony/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php
PHP
mit
10,013
/* eslint no-console: ["error", { allow: ["error"] }] */ /** * @param {Object} $ - Global jQuery object * @param {Object} bolt - The Bolt module */ (function ($) { 'use strict'; /** * Mode identifiers. * * @memberOf jQuery.widget.bolt.fieldSlug * @static * @type {Object.<string, number>} */ var mode = { lock: 1, link: 2, edit: 3 }; /** * Slug field widget. * * @license http://opensource.org/licenses/mit-license.php MIT License * @author rarila * * @class fieldSlug * @memberOf jQuery.widget.bolt * @extends jQuery.widget.bolt.baseField */ $.widget('bolt.fieldSlug', $.bolt.baseField, /** @lends jQuery.widget.bolt.fieldSlug.prototype */ { /** * Default options. * * @property {string|null} contentId - Content Id * @property {string} key - The field key * @property {string} slug - Content slug * @property {Array} uses - Fields used to automatically generate a slug */ options: { contentId: null, key: '', slug: '', uses: [] }, /** * The constructor of the slug field widget. * * @private */ _create: function () { var self = this, fieldset = this.element; /** * Refs to UI elements of this widget. * * @type {Object} * @name _ui * @memberOf jQuery.widget.bolt.fieldSlug.prototype * @private * * @property {Object} form - The form this input is part of * @property {Object} group - Group container * @property {Object} data - Data field * @property {Object} uses - Collection of uses fields */ this._ui = { form: this.element.closest('form'), group: fieldset.find('.input-group'), data: fieldset.find('input'), uses: $() }; // Get all references to linked ellements. $('[name]', self._ui.form).each(function () { if (self.options.uses.indexOf(this.name.replace(/\[\]$/, '')) >= 0) { self._ui.uses = self._ui.uses.add($(this)); } }); /** * A timeout. * * @type {number} * @name _timeout * @memberOf jQuery.widget.bolt.fieldSlug.prototype * @private */ this._timeout = 0; /** * Slug is generated, if true. * * @type {number} * @name _mode * @memberOf jQuery.widget.bolt.fieldSlug.prototype * @private */ this._mode = mode.lock; // Initialize modes. if (this._ui.group.hasClass('linked')) { this._setMode(mode.link); } else if (this._ui.group.hasClass('editable')) { this._mode = mode.edit; } // Bind events. this._on({ 'click li.lock': function (event) { event.preventDefault(); this._setMode(mode.lock); }, 'click li.link': function (event) { event.preventDefault(); this._setMode(mode.link); }, 'click li.edit': function (event) { event.preventDefault(); this._setMode(mode.edit); this.element.find('input').focus(); }, 'focusout input': function () { if (this._mode === mode.edit) { this._setMode(mode.lock); } } }); }, /** * Cleanup. * * @private */ _destroy: function () { clearTimeout(this._timeout); }, /** * Update widgets visual and functional state. * * @private * @param {number} setMode - Mode to set */ _setMode: function (setMode) { var modeIsLocked = setMode === mode.lock, modeIsLinked = setMode === mode.link, modeIsEditable = setMode === mode.edit; // Set dropdown button states. $('li.lock', this.element).toggleClass('disabled', modeIsLocked); $('li.link', this.element).toggleClass('disabled', modeIsLinked); $('li.edit', this.element).toggleClass('disabled', modeIsEditable); // Set container class. this._ui.group .toggleClass('locked', modeIsLocked) .toggleClass('linked', modeIsLinked) .toggleClass('edititable', modeIsEditable); // Show/hide edit warning. $('.warning', this.element).toggleClass('hidden', !modeIsEditable); // Toggle the input readonly. this._ui.data.prop('readonly', !modeIsEditable); // Start/stop generating slugs from uses fields. if (modeIsLinked) { this._buildSlug(); this._on(this._ui.uses, { 'change': function () { this._buildSlug(); }, 'input': function () { this._buildSlug(); } }); } else if (this._timeout > 0) { clearTimeout(this._timeout); this._timeout = 0; this._off(this._ui.uses, 'change'); this._off(this._ui.uses, 'input'); } // Finally set new mode. this._mode = setMode; }, /** * Build the slug using the fields described in the uses parameter. * * @private */ _buildSlug: function () { var self = this, term = '', value; $.each(self.options.uses, function (i, field) { value = $('#' + field).val(); if (value) { term += (typeof value === 'object' ? value.join(' ') : value) + ' '; } }); clearTimeout(self._timeout); self._timeout = setTimeout( function () { self._getUri(term.trim()); }, 200 ); }, /** * Get URI for slug from remote. * * @private * @param {string} text - New slug text */ _getUri: function (text) { var self = this, data = { title: text, contenttypeslug: self.options.slug, id: self.options.contentId, slugfield: self.options.key, fulluri: false }; self._ui.group.addClass('loading'); $.get(self._ui.data.data('createSlugUrl'), data) .done(function (uri) { if (self._mode === mode.link) { self._ui.data.val(uri); } }) .fail(function () { console.error('Failed to get URI for ' + self.options.slug + '/' + self.options.contentId); }) .always(function () { self._ui.group.removeClass('loading'); }); } }); })(jQuery, Bolt);
nikgo/bolt
assets/js/widgets/fields/fieldSlug.js
JavaScript
mit
7,910
using System; using System.Globalization; using System.Net.Http; using Microsoft.Owin; using Microsoft.Owin.Logging; using Microsoft.Owin.Security; using Microsoft.Owin.Security.DataHandler; using Microsoft.Owin.Security.DataProtection; using Microsoft.Owin.Security.Infrastructure; using Owin.Security.Providers.Properties; namespace Owin.Security.Providers.Untappd { public class UntappdAuthenticationMiddleware : AuthenticationMiddleware<UntappdAuthenticationOptions> { private readonly HttpClient httpClient; private readonly ILogger logger; public UntappdAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, UntappdAuthenticationOptions options) : base(next, options) { if (String.IsNullOrWhiteSpace(Options.ClientId)) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, "ClientId")); if (String.IsNullOrWhiteSpace(Options.ClientSecret)) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, "ClientSecret")); logger = app.CreateLogger<UntappdAuthenticationMiddleware>(); if (Options.Provider == null) Options.Provider = new UntappdAuthenticationProvider(); if (Options.StateDataFormat == null) { IDataProtector dataProtector = app.CreateDataProtector( typeof(UntappdAuthenticationMiddleware).FullName, Options.AuthenticationType, "v1"); Options.StateDataFormat = new PropertiesDataFormat(dataProtector); } if (String.IsNullOrEmpty(Options.SignInAsAuthenticationType)) Options.SignInAsAuthenticationType = app.GetDefaultSignInAsAuthenticationType(); httpClient = new HttpClient(ResolveHttpMessageHandler(Options)) { Timeout = Options.BackchannelTimeout, MaxResponseContentBufferSize = 1024 * 1024 * 10, }; httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Microsoft Owin Untappd middleware"); httpClient.DefaultRequestHeaders.ExpectContinue = false; } /// <summary> /// Provides the <see cref="T:Microsoft.Owin.Security.Infrastructure.AuthenticationHandler" /> object for processing /// authentication-related requests. /// </summary> /// <returns> /// An <see cref="T:Microsoft.Owin.Security.Infrastructure.AuthenticationHandler" /> configured with the /// <see cref="T:Owin.Security.Providers.Untappd.UntappdAuthenticationOptions" /> supplied to the constructor. /// </returns> protected override AuthenticationHandler<UntappdAuthenticationOptions> CreateHandler() { return new UntappdAuthenticationHandler(httpClient, logger); } private HttpMessageHandler ResolveHttpMessageHandler(UntappdAuthenticationOptions options) { HttpMessageHandler handler = options.BackchannelHttpHandler ?? new WebRequestHandler(); // If they provided a validator, apply it or fail. if (options.BackchannelCertificateValidator == null) return handler; // Set the cert validate callback var webRequestHandler = handler as WebRequestHandler; if (webRequestHandler == null) { throw new InvalidOperationException(Resources.Exception_ValidatorHandlerMismatch); } webRequestHandler.ServerCertificateValidationCallback = options.BackchannelCertificateValidator.Validate; return handler; } } }
Lorac/OwinOAuthProviders
Owin.Security.Providers/Untappd/UntappdAuthenticationMiddleware.cs
C#
mit
3,832
//-----------------------------------------------------------------------------G // ____ _ // | ___| | ___ _ _ // | ___| | / __)\ \/ / // | | | |_| ___) | | // |_| \___|\___)/_/\_\ Image Library // // 2006, Intel Corporation, licensed under Apache 2.0 // // file : FlexDataExchange.h // author : Scott Ettinger - [email protected] // description: Definition of Conversion functions between image types. // Only a subset of functions are implemented for benchmarks. // // modified : //----------------------------------------------------------------------------- #ifndef FLEXDATAEXCHANGE_H #define FLEXDATAEXCHANGE_H #if defined(HAVE_CONFIG_H) # include "config.h" #endif #include "FlexDefs.h" //min() will be undefined at end of header to avoid conflicts #ifndef min # define min(x, y) (((x) < (y)) ? (x) : (y)) #endif template<class T, int C> class FlexImage; ////////////////////////////////////////////////////////////////////////////////////////////////// // Copy Functions // // Names: FlexCopy, FlexCopyM, FlexCopyCM, FlexCopyCMC1, FlexCopyC1CM, FlexCopyP3 // /////////////////////////////////////////////////////////////////////////////////////////////////// ///copy all pixels of all color channels template<class T, int C> FIStatus FlexCopy(const FlexImage<T,C> &src, FlexImage<T,C> &dst, bool allocate = true); ///copy a single channel image to a channel of a multi-channel image template<class T, int C> FIStatus FlexCopyC1CM(FlexImage<T,1> &src, FlexImage<T,C> &dst, int dstChannel); /* ///copy a single channel of a multi-channel image to a channel of another multi-channel image template<class T, int C> FIStatus FlexCopyCM(FlexImage<T,C> &src, FlexImage<T,C> &dst, int srcChannel, int dstChannel); ///copy a single channel of a multi-channel image to a single channel image template<class T, int C> FIStatus FlexCopyCMC1(FlexImage<T,C> &src, FlexImage<T,1> &dst, int srcChannel); //copy masked pixels of all color channels template<class T, int C> FIStatus FlexCopyM(FlexImage<T,C> &src, FlexImage<T,C> &dst, FlexImage<Ipp8u,1> &msk); ///split 3 channel image into separate plane images template<class T> FIStatus FlexCopyP3(FlexImage<T,3> &src, FlexImage<T,1> &p1, FlexImage<T,1> &p2, FlexImage<T,1> &p3); ///split 4 channel image into separate plane images template<class T> FIStatus FlexCopyP4(FlexImage<T,4> &src, FlexImage<T,1> &p1, FlexImage<T,1> &p2, FlexImage<T,1> &p3, FlexImage<T,1> &p4); */ /* ///copy all pixels of all color channels with alpha template<class T> FIStatus FlexCopyA(const FlexImage<T,4> &src, FlexImage<T,4> &dst); */ ////////////////////////////////////////////////////////////////////////////////////////////////// // Convert Functions // // Names: FlexConvert, FlexConvertA // /////////////////////////////////////////////////////////////////////////////////////////////////// ///Image conversion - Converts between images but uses size of src template<class T1, class T2, int C> FIStatus FlexConvert(const FlexImage<T1,C> &src, FlexImage<T2,C> &dst, bool allocate = true); //Allows for templated functions that convert from same type to same type template<class T, int C> FIStatus FlexConvert(const FlexImage<T,C> &src, FlexImage<T,C> &dst, bool allocate = true) { return( FlexCopy(src, dst, allocate) ); }; /* ///Same as FlexConvert, but uses Alpha channel (i.e. calls ippConvertAC4 instead of ippConverC4 ///src and dst must contain 4 channels or returns ippStsNumChannelsErr template<class T1, class T2, int C> FIStatus FlexConvertA(FlexImage<T1,C> &src, FlexImage<T2,C> &dst, IppRoundMode roundMode = ippRndNear); */ ////////////////////////////////////////////////////////////////////////////////////////////////// // Set Functions // // Names: FlexSet, FlexSetA, FlexSetM, ipipSetAM, FlexSetC // /////////////////////////////////////////////////////////////////////////////////////////////////// //---------------------------Set functions-------------------------- ///Image set single channel to a value template<class T> FIStatus FlexSet(FlexImage<T,1> &img, T value); ///Image set multi-channels to a value template<class T, int C> FIStatus FlexSet(FlexImage<T,C> &img, T value[]); /* ///Image set skipping alpha channel - 4 channel images only template<class T, int C> FIStatus FlexSetA(FlexImage<T,C> &img, T value[]); ///Image set masked values 1 channel template<class T> FIStatus FlexSetM(FlexImage<T,1> &img, T value, FlexImage<Ipp8u,1> &msk); ///Image set masked values multi-channel template<class T, int C> FIStatus FlexSetM(FlexImage<T,C> &img, T value[], FlexImage<Ipp8u,1> &msk); ///Image set masked values 4 channel alpha template<class T, int C> FIStatus FlexSetAM(FlexImage<T,C> &img, T *value, FlexImage<Ipp8u,1> &msk); ///Image set values on individual channel - 3 and 4 channel images only template<class T, int C> FIStatus FlexSetC(FlexImage<T,C> &img, T value, int channel); */ ////////////////////////////////////////////////////////////////////////////////////////////////// // SwapChannels Functions // // Names: SwapChannels, SwapChannelsA, SwapChannelsI // /////////////////////////////////////////////////////////////////////////////////////////////////// ///Swap Channels - order values must be from {0, 1, 2} template<class T, int C> FIStatus FlexSwapChannels(FlexImage<T,C> &src, FlexImage<T,C> &dst, int dstOrder[3]); //:Swap channels immediate template<class T, int C> FIStatus FlexSwapChannelsI(FlexImage<T,3> &src, int dstOrder[3]); /* template<class T> FIStatus FlexSwapChannelsA(FlexImage<T,4> &src, FlexImage<T,4> &dst, int dstOrder[3]); */ //---------------------------------------- Implementation ---------------------------------------- ////////////////////////////////////////////////////////////////////////////////////////////////// // Copy Functions // // Names: FlexCopy, FlexCopyM, FlexCopyCM, FlexCopyCMC1, FlexCopyC1CM, FlexCopyP3 // /////////////////////////////////////////////////////////////////////////////////////////////////// template<class T, int C> FIStatus FlexCopy(const FlexImage<T,C> &src, FlexImage<T,C> &dst, bool allocate) { if(allocate) //allocate destination if desired dst.Reallocate(src.Size()); int w = min(src.Width(), dst.Width()); //determine number of pixels to copy (intersection of src and dst areas) int h = min(src.Height(), dst.Height()); int n = w * sizeof(T) * C; //get number of bytes to copy per line T *pSrc = (T *)src.Data(), *pDst = (T *)dst.Data(); for(int i = 0; i < h; i++) //copy the data line by line { memcpy(pDst, pSrc, n); pSrc = (T *)((char *)pSrc + src.StepBytes()); pDst = (T *)((char *)pDst + dst.StepBytes()); } return 0; } template<class T, int C> FIStatus FlexCopyC1CM(FlexImage<T,1> &src, FlexImage<T,C> &dst, int dstChannel) { if(C < dstChannel + 1) //exit if invalid channel selected return -1; int w = min(src.Width(), dst.Width()); //determine number of pixels to copy (intersection of src and dst areas) int h = min(src.Height(), dst.Height()); T *pSrc = (T *)src.Data(), *pDst = (T *)dst.Data() + dstChannel; for(int j = 0; j < h; j++) { T *ps = pSrc, *pd = pDst; for(int i = 0; i < w; i++) { *pd = *(ps++); pd += C; } pSrc = (T *)((char *)pSrc + src.StepBytes()); pDst = (T *)((char *)pDst + dst.StepBytes()); } return 0; } ////////////////////////////////////////////////////////////////////////////////////////////////// // Convert Functions // // Names: FlexConvert, FlexConvertA // /////////////////////////////////////////////////////////////////////////////////////////////////// ///Image conversion - Converts between image types template<class T1, class T2, int C> FIStatus FlexConvert(const FlexImage<T1,C> &src, FlexImage<T2,C> &dst, bool allocate) { if(allocate) //allocate destination if desired dst.Reallocate(src.Size()); int w = min(src.Width(), dst.Width()); //determine number of pixels to copy (intersection of src and dst areas) int h = min(src.Height(), dst.Height()); T1 *pSrc = (T1 *)src.Data(); T2 *pDst = dst.Data(); for(int j = 0; j < h; j++) //copy the data line by line { T1 *ps = pSrc; T2 *pd = pDst; for(int i = 0; i < w * C; i++) *pd++ = T2(*ps++); pSrc = (T1 *)((char *)pSrc + src.StepBytes()); pDst = (T2 *)((char *)pDst + dst.StepBytes()); } return 0; } ////////////////////////////////////////////////////////////////////////////////////////////////// // Set Functions // // Names: FlexSet, FlexSetA, FlexSetM, ipipSetAM, FlexSetC // /////////////////////////////////////////////////////////////////////////////////////////////////// //---------------------------Set functions-------------------------- ///Set all channels to given value template<class T, int C> FIStatus FlexSet(FlexImage<T,1> &img, T value) { int w = img.Width() * C; T *pLine = img.Data(); //get pointer to the data for(int j = 0; j < img.Height(); j++) { T *p = pLine; for(int i = 0; i < w; i++) //set each pixel to value *(p++) = value; pLine += img.StepBytes(); } return 0; } ///set multi-channels to given values template<class T, int C> FIStatus FlexSet(FlexImage<T,C> &img, T value[]) { if(img.Height() < 1) return -1; T *p = img.Data(); //get pointer to data int w = img.Width() * C; for(int i = 0; i < w; i++) //generate first line of image *(p++) = value[i % C]; T *ps = img.Data(); char *pd = (char *)&img(0,1); int n = w * sizeof(T); for(int i = 1; i < img.Height(); i++) //copy first line to rest of image { memcpy(pd, ps, n); pd += img.StepBytes(); } return 0; } //undefine min() to avoid conflicts with system headers #undef min #endif
tudinfse/fex
src/parsec/bodytrack/src/FlexImageLib/FlexDataExchange.h
C
mit
10,053
// // SessionImpl.h // // $Id: //poco/Main/Data/SQLite/include/Poco/Data/SQLite/SessionImpl.h#2 $ // // Library: SQLite // Package: SQLite // Module: SessionImpl // // Definition of the SessionImpl class. // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #ifndef Data_SQLite_SessionImpl_INCLUDED #define Data_SQLite_SessionImpl_INCLUDED #include "Poco/Data/SQLite/SQLite.h" #include "Poco/Data/SQLite/Connector.h" #include "Poco/Data/SQLite/Binder.h" #include "Poco/Data/AbstractSessionImpl.h" #include "Poco/SharedPtr.h" struct sqlite3; struct sqlite3_stmt; namespace Poco { class Mutex; namespace Data { namespace SQLite { class SQLite_API SessionImpl: public Poco::Data::AbstractSessionImpl<SessionImpl> /// Implements SessionImpl interface. { public: SessionImpl(const std::string& fileName, std::size_t loginTimeout = LOGIN_TIMEOUT_DEFAULT); /// Creates the SessionImpl. Opens a connection to the database. ~SessionImpl(); /// Destroys the SessionImpl. Poco::Data::StatementImpl* createStatementImpl(); /// Returns an SQLite StatementImpl. void open(const std::string& connect = ""); /// Opens a connection to the Database. /// /// An in-memory system database (sys), with a single table (dual) /// containing single field (dummy) is attached to the database. /// The in-memory system database is used to force change count /// to be reset to zero on every new query (or batch of queries) /// execution. Without this functionality, select statements /// executions that do not return any rows return the count of /// changes effected by the most recent insert, update or delete. /// In-memory system database can be queried and updated but can not /// be dropped. It may be used for other purposes /// in the future. void close(); /// Closes the session. bool isConnected(); /// Returns true if connected, false otherwise. void setConnectionTimeout(std::size_t timeout); /// Sets the session connection timeout value. std::size_t getConnectionTimeout(); /// Returns the session connection timeout value. void begin(); /// Starts a transaction. void commit(); /// Commits and ends a transaction. void rollback(); /// Aborts a transaction. bool canTransact(); /// Returns true if session has transaction capabilities. bool isTransaction(); /// Returns true iff a transaction is a transaction is in progress, false otherwise. void setTransactionIsolation(Poco::UInt32 ti); /// Sets the transaction isolation level. Poco::UInt32 getTransactionIsolation(); /// Returns the transaction isolation level. bool hasTransactionIsolation(Poco::UInt32 ti); /// Returns true iff the transaction isolation level corresponding /// to the supplied bitmask is supported. bool isTransactionIsolation(Poco::UInt32 ti); /// Returns true iff the transaction isolation level corresponds /// to the supplied bitmask. void autoCommit(const std::string&, bool val); /// Sets autocommit property for the session. bool isAutoCommit(const std::string& name=""); /// Returns autocommit property value. const std::string& connectorName() const; /// Returns the name of the connector. protected: void setConnectionTimeout(const std::string& prop, const Poco::Any& value); Poco::Any getConnectionTimeout(const std::string& prop); private: std::string _connector; sqlite3* _pDB; bool _connected; bool _isTransaction; int _timeout; Mutex _mutex; static const std::string DEFERRED_BEGIN_TRANSACTION; static const std::string COMMIT_TRANSACTION; static const std::string ABORT_TRANSACTION; }; // // inlines // inline bool SessionImpl::canTransact() { return true; } inline bool SessionImpl::isTransaction() { return _isTransaction; } inline const std::string& SessionImpl::connectorName() const { return _connector; } inline std::size_t SessionImpl::getConnectionTimeout() { return static_cast<std::size_t>(_timeout); } } } } // namespace Poco::Data::SQLite #endif // Data_SQLite_SessionImpl_INCLUDED
veyesys/opencvr
3rdparty/poco/Data/SQLite/include/Poco/Data/SQLite/SessionImpl.h
C
mit
4,141
module Holidays module Definition module Validator class Region def initialize(regions_repo) @regions_repo = regions_repo end def valid?(r) return false unless r.is_a?(Symbol) region = find_wildcard_base(r) (region == :any || @regions_repo.loaded?(region) || @regions_repo.all_generated.include?(region)) end private # Ex: :gb_ transformed to :gb def find_wildcard_base(region) r = region.to_s if r =~ /_$/ base = r.split('_').first else base = r end base.to_sym end end end end end
ptrimble/holidays
lib/holidays/definition/validator/region.rb
Ruby
mit
714
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim <[UseExportProvider]> Public Class FileChangeTests <WpfTheory> <CombinatorialData> Public Async Function FileChangeAfterRemovalInUncommittedBatchIgnored(withDirectoryWatch As Boolean) As Task Using environment = New TestEnvironment() Dim projectInfo = New VisualStudioProjectCreationInfo ' If we have a project directory, then we'll also have a watch for the entire directory; ' test both cases If withDirectoryWatch Then projectInfo.FilePath = "Z:\Project.csproj" End If Dim project = Await environment.ProjectFactory.CreateAndAddToWorkspaceAsync( "project", LanguageNames.CSharp, projectInfo, CancellationToken.None) project.AddSourceFile("Z:\Foo.cs") Using project.CreateBatchScope() ' This shouldn't throw Await environment.RaiseStaleFileChangeAsync("Z:\Foo.cs", Sub() project.RemoveSourceFile("Z:\Foo.cs")) End Using End Using End Function <WpfTheory> <CombinatorialData> Public Async Function FileChangeAfterRemoveOfProjectIgnored(withDirectoryWatch As Boolean) As Task Using environment = New TestEnvironment() Dim projectInfo = New VisualStudioProjectCreationInfo ' If we have a project directory, then we'll also have a watch for the entire directory; ' test both cases If withDirectoryWatch Then projectInfo.FilePath = "Z:\Project.csproj" End If Dim project = Await environment.ProjectFactory.CreateAndAddToWorkspaceAsync( "project", LanguageNames.CSharp, projectInfo, CancellationToken.None) project.AddSourceFile("Z:\Foo.cs") Using project.CreateBatchScope() ' This shouldn't throw Await environment.RaiseStaleFileChangeAsync("Z:\Foo.cs", Sub() project.RemoveFromWorkspace()) End Using End Using End Function End Class End Namespace
CyrusNajmabadi/roslyn
src/VisualStudio/Core/Test/ProjectSystemShim/VisualStudioProjectTests/FileChangeTests.vb
Visual Basic
mit
2,804
var searchData= [ ['platform',['Platform',['../namespace_jmcpp.html#a5cfe2cd99045a069ebdbde3779622e1f',1,'Jmcpp']]] ];
war22moon/jpush-docs
zh/jmessage/client/im_win_api_docs/search/enums_1.js
JavaScript
mit
121
package firego import "encoding/json" // Push creates a reference to an auto-generated child location func (fb *Firebase) Push(v interface{}) (*Firebase, error) { bytes, err := json.Marshal(v) if err != nil { return nil, err } bytes, err = fb.doRequest("POST", bytes) if err != nil { return nil, err } var m map[string]string if err := json.Unmarshal(bytes, &m); err != nil { return nil, err } return &Firebase{ url: fb.url + "/" + m["name"], client: fb.client, }, err }
CloudCom/firego
push.go
GO
mit
497
(function () { 'use strict'; function MiniListViewDirective(entityResource, iconHelper) { function link(scope, el, attr, ctrl) { scope.search = ""; scope.miniListViews = []; scope.breadcrumb = []; scope.listViewAnimation = ""; var miniListViewsHistory = []; function onInit() { open(scope.node); } function open(node) { // convert legacy icon for node if(node && node.icon) { node.icon = iconHelper.convertFromLegacyIcon(node.icon); } var miniListView = { node: node, loading: true, pagination: { pageSize: 10, pageNumber: 1, filter: '', orderDirection: "Ascending", orderBy: "SortOrder", orderBySystemField: true } }; // clear and push mini list view in dom so we only render 1 view scope.miniListViews = []; scope.listViewAnimation = "in"; scope.miniListViews.push(miniListView); // store in history so we quickly can navigate back miniListViewsHistory.push(miniListView); // get children getChildrenForMiniListView(miniListView); makeBreadcrumb(); } function getChildrenForMiniListView(miniListView) { // start loading animation list view miniListView.loading = true; entityResource.getPagedChildren(miniListView.node.id, scope.entityType, miniListView.pagination) .then(function (data) { if (!data.items) { data.items = []; } if (scope.onItemsLoaded) { scope.onItemsLoaded({items: data.items}); } // update children miniListView.children = data.items; miniListView.children.forEach(c => { // child allowed by default c.allowed = true; // convert legacy icon for node if(c.icon) { c.icon = iconHelper.convertFromLegacyIcon(c.icon); } // set published state for content if (c.metaData) { c.hasChildren = c.metaData.hasChildren; if(scope.entityType === "Document") { c.published = c.metaData.IsPublished; } } // filter items if there is a filter and it's not advanced (advanced filtering is handled below) if (scope.entityTypeFilter && scope.entityTypeFilter.filter && !scope.entityTypeFilter.filterAdvanced) { var a = scope.entityTypeFilter.filter.toLowerCase().replace(/\s/g, '').split(','); var found = a.indexOf(c.metaData.ContentTypeAlias.toLowerCase()) >= 0; if (!scope.entityTypeFilter.filterExclude && !found || scope.entityTypeFilter.filterExclude && found) { c.allowed = false; } } }); // advanced item filtering is handled here if (scope.entityTypeFilter && scope.entityTypeFilter.filter && scope.entityTypeFilter.filterAdvanced) { var filtered = Utilities.isFunction(scope.entityTypeFilter.filter) ? _.filter(miniListView.children, scope.entityTypeFilter.filter) : _.where(miniListView.children, scope.entityTypeFilter.filter); filtered.forEach(node => node.allowed = false); } // update pagination miniListView.pagination.totalItems = data.totalItems; miniListView.pagination.totalPages = data.totalPages; // stop load indicator miniListView.loading = false; }); } scope.openNode = function(event, node) { open(node); event.stopPropagation(); }; scope.selectNode = function(node) { if (scope.onSelect && node.allowed) { scope.onSelect({'node': node}); } }; /* Pagination */ scope.goToPage = function(pageNumber, miniListView) { // set new page number miniListView.pagination.pageNumber = pageNumber; // get children getChildrenForMiniListView(miniListView); }; /* Breadcrumb */ scope.clickBreadcrumb = function(ancestor) { var found = false; scope.listViewAnimation = "out"; Utilities.forEach(miniListViewsHistory, (historyItem, index) => { // We need to make sure we can compare the two id's. // Some id's are integers and others are strings. // Members have string ids like "all-members". if (historyItem.node.id.toString() === ancestor.id.toString()) { // load the list view from history scope.miniListViews = []; scope.miniListViews.push(historyItem); // clean up history - remove all children after miniListViewsHistory.splice(index + 1, miniListViewsHistory.length); found = true; } }); if (!found) { // if we can't find the view in the history - close the list view scope.exitMiniListView(); } // update the breadcrumb makeBreadcrumb(); }; scope.showBackButton = function() { // don't show the back button if the start node is a list view if (scope.node.metaData && scope.node.metaData.IsContainer || scope.node.isContainer) { return false; } else { return true; } }; scope.exitMiniListView = function() { miniListViewsHistory = []; scope.miniListViews = []; if(scope.onClose) { scope.onClose(); } }; function makeBreadcrumb() { scope.breadcrumb = []; Utilities.forEach(miniListViewsHistory, historyItem => { scope.breadcrumb.push(historyItem.node); }); } /* Search */ scope.searchMiniListView = function(search, miniListView) { // set search value miniListView.pagination.filter = search; // reset pagination miniListView.pagination.pageNumber = 1; // start loading animation list view miniListView.loading = true; searchMiniListView(miniListView); }; var searchMiniListView = _.debounce(function (miniListView) { scope.$apply(function () { getChildrenForMiniListView(miniListView); }); }, 500); onInit(); } var directive = { restrict: 'E', replace: true, templateUrl: 'views/components/umb-mini-list-view.html', scope: { node: "=", entityType: "@", startNodeId: "=", onSelect: "&", onClose: "&", onItemsLoaded: "&", entityTypeFilter: "=" }, link: link }; return directive; } angular.module('umbraco.directives').directive('umbMiniListView', MiniListViewDirective); })();
umbraco/Umbraco-CMS
src/Umbraco.Web.UI.Client/src/common/directives/components/umbminilistview.directive.js
JavaScript
mit
8,819
var util = require("util"); var choreography = require("temboo/core/choreography"); /* FindPopularItems Searches for popular items based on a category or keyword. */ var FindPopularItems = function(session) { /* Create a new instance of the FindPopularItems Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/eBay/Shopping/FindPopularItems" FindPopularItems.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new FindPopularItemsResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new FindPopularItemsInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the FindPopularItems Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var FindPopularItemsInputSet = function() { FindPopularItemsInputSet.super_.call(this); /* Set the value of the AppID input for this Choreo. ((required, string) The unique identifier for the application.) */ this.set_AppID = function(value) { this.setInput("AppID", value); } /* Set the value of the CategoryIDExclude input for this Choreo. ((conditional, integer) The ID of a category to exclude from the result set. Multiple category IDs can be separated by commas.) */ this.set_CategoryIDExclude = function(value) { this.setInput("CategoryIDExclude", value); } /* Set the value of the CategoryID input for this Choreo. ((optional, string) The ID of a category to filter by. Multiple category IDs can be separated by commas.) */ this.set_CategoryID = function(value) { this.setInput("CategoryID", value); } /* Set the value of the MaxEntries input for this Choreo. ((conditional, integer) The maxiumum number of entries to return in the response.) */ this.set_MaxEntries = function(value) { this.setInput("MaxEntries", value); } /* Set the value of the QueryKeywords input for this Choreo. ((conditional, string) The text for a keyword search.) */ this.set_QueryKeywords = function(value) { this.setInput("QueryKeywords", value); } /* Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Valid values are: json (the default) and xml.) */ this.set_ResponseFormat = function(value) { this.setInput("ResponseFormat", value); } /* Set the value of the SandboxMode input for this Choreo. ((optional, boolean) Indicates that the request should be made to the sandbox endpoint instead of the production endpoint. Set to 1 to enable sandbox mode.) */ this.set_SandboxMode = function(value) { this.setInput("SandboxMode", value); } /* Set the value of the SiteID input for this Choreo. ((optional, string) The eBay site ID that you want to access. Defaults to 0 indicating the US site.) */ this.set_SiteID = function(value) { this.setInput("SiteID", value); } } /* A ResultSet with methods tailored to the values returned by the FindPopularItems Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var FindPopularItemsResultSet = function(resultStream) { FindPopularItemsResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. (The response from eBay.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(FindPopularItems, choreography.Choreography); util.inherits(FindPopularItemsInputSet, choreography.InputSet); util.inherits(FindPopularItemsResultSet, choreography.ResultSet); exports.FindPopularItems = FindPopularItems; /* FindProducts Retrieves the listings for products that match the specified keywords. */ var FindProducts = function(session) { /* Create a new instance of the FindProducts Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/eBay/Shopping/FindProducts" FindProducts.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new FindProductsResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new FindProductsInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the FindProducts Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var FindProductsInputSet = function() { FindProductsInputSet.super_.call(this); /* Set the value of the AppID input for this Choreo. ((required, string) The unique identifier for the application.) */ this.set_AppID = function(value) { this.setInput("AppID", value); } /* Set the value of the AvailableItemsOnly input for this Choreo. ((optional, boolean) If set to true, only retrieve data for products that have been used to pre-fill active listings. If false, retrieve all products that match the query. Defaults to false.) */ this.set_AvailableItemsOnly = function(value) { this.setInput("AvailableItemsOnly", value); } /* Set the value of the CategoryID input for this Choreo. ((conditional, string) Restricts your query to a specific category. The request requires one of the following filter parameters: QueryKeywords, ProductID, or CategoryID. Only one of the filters should be provided.) */ this.set_CategoryID = function(value) { this.setInput("CategoryID", value); } /* Set the value of the DomainName input for this Choreo. ((optional, string) A domain to search in (e.g. Textbooks).) */ this.set_DomainName = function(value) { this.setInput("DomainName", value); } /* Set the value of the HideDuplicateItems input for this Choreo. ((optional, string) Specifies whether or not to remove duplicate items from search results.) */ this.set_HideDuplicateItems = function(value) { this.setInput("HideDuplicateItems", value); } /* Set the value of the IncludeSelector input for this Choreo. ((optional, string) Defines standard subsets of fields to return within the response. Valid values are: Details, DomainHistogram, and Items.) */ this.set_IncludeSelector = function(value) { this.setInput("IncludeSelector", value); } /* Set the value of the MaxEntries input for this Choreo. ((optional, integer) The maximum number of entries to return in the response.) */ this.set_MaxEntries = function(value) { this.setInput("MaxEntries", value); } /* Set the value of the PageNumber input for this Choreo. ((optional, string) The page number to retrieve.) */ this.set_PageNumber = function(value) { this.setInput("PageNumber", value); } /* Set the value of the ProductID input for this Choreo. ((conditional, string) Used to retrieve product details. The request requires one of the following filter parameters: QueryKeywords, ProductID, or CategoryID. Only one of the filters should be provided.) */ this.set_ProductID = function(value) { this.setInput("ProductID", value); } /* Set the value of the ProductSort input for this Choreo. ((optional, string) Sorts the list of products returned. Valid values are: ItemCount, Popularity, Rating, ReviewCount, and Title.) */ this.set_ProductSort = function(value) { this.setInput("ProductSort", value); } /* Set the value of the QueryKeywords input for this Choreo. ((conditional, string) The query keywords to use for the product search. The request requires one of the following filter parameters: QueryKeywords, ProductID, or CategoryID. Only one of the filters should be provided.) */ this.set_QueryKeywords = function(value) { this.setInput("QueryKeywords", value); } /* Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Valid values are: json (the default) and xml.) */ this.set_ResponseFormat = function(value) { this.setInput("ResponseFormat", value); } /* Set the value of the SandboxMode input for this Choreo. ((optional, boolean) Indicates that the request should be made to the sandbox endpoint instead of the production endpoint. Set to 1 to enable sandbox mode.) */ this.set_SandboxMode = function(value) { this.setInput("SandboxMode", value); } /* Set the value of the SiteID input for this Choreo. ((optional, string) The eBay site ID that you want to access. Defaults to 0 indicating the US site.) */ this.set_SiteID = function(value) { this.setInput("SiteID", value); } /* Set the value of the SortOrder input for this Choreo. ((optional, string) Sorts search results in ascending or descending order. Valid values are: Ascending and Descending.) */ this.set_SortOrder = function(value) { this.setInput("SortOrder", value); } } /* A ResultSet with methods tailored to the values returned by the FindProducts Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var FindProductsResultSet = function(resultStream) { FindProductsResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. (The response from eBay.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(FindProducts, choreography.Choreography); util.inherits(FindProductsInputSet, choreography.InputSet); util.inherits(FindProductsResultSet, choreography.ResultSet); exports.FindProducts = FindProducts; /* GetCategoryInfo Retrieve high-level category information for a specified category. */ var GetCategoryInfo = function(session) { /* Create a new instance of the GetCategoryInfo Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/eBay/Shopping/GetCategoryInfo" GetCategoryInfo.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new GetCategoryInfoResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new GetCategoryInfoInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the GetCategoryInfo Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var GetCategoryInfoInputSet = function() { GetCategoryInfoInputSet.super_.call(this); /* Set the value of the AppID input for this Choreo. ((required, string) The unique identifier for the application.) */ this.set_AppID = function(value) { this.setInput("AppID", value); } /* Set the value of the CategoryID input for this Choreo. ((required, string) The ID of a category to retrieve. Use an ID of -1 to retrieve the root category and the top-level (level 1) meta categories.) */ this.set_CategoryID = function(value) { this.setInput("CategoryID", value); } /* Set the value of the IncludeSelector input for this Choreo. ((optional, string) Defines standard subsets of fields to return within the response. Valid values are: ChildCategories.) */ this.set_IncludeSelector = function(value) { this.setInput("IncludeSelector", value); } /* Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Valid values are: json (the default) and xml.) */ this.set_ResponseFormat = function(value) { this.setInput("ResponseFormat", value); } /* Set the value of the SandboxMode input for this Choreo. ((optional, boolean) Indicates that the request should be made to the sandbox endpoint instead of the production endpoint. Set to 1 to enable sandbox mode.) */ this.set_SandboxMode = function(value) { this.setInput("SandboxMode", value); } /* Set the value of the SiteID input for this Choreo. ((optional, string) The eBay site ID that you want to access. Defaults to 0 indicating the US site.) */ this.set_SiteID = function(value) { this.setInput("SiteID", value); } } /* A ResultSet with methods tailored to the values returned by the GetCategoryInfo Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var GetCategoryInfoResultSet = function(resultStream) { GetCategoryInfoResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. (The response from eBay.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(GetCategoryInfo, choreography.Choreography); util.inherits(GetCategoryInfoInputSet, choreography.InputSet); util.inherits(GetCategoryInfoResultSet, choreography.ResultSet); exports.GetCategoryInfo = GetCategoryInfo; /* GetItemStatus Allows you to get the status for a group of items. */ var GetItemStatus = function(session) { /* Create a new instance of the GetItemStatus Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/eBay/Shopping/GetItemStatus" GetItemStatus.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new GetItemStatusResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new GetItemStatusInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the GetItemStatus Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var GetItemStatusInputSet = function() { GetItemStatusInputSet.super_.call(this); /* Set the value of the AppID input for this Choreo. ((required, string) The unique identifier for the application.) */ this.set_AppID = function(value) { this.setInput("AppID", value); } /* Set the value of the ItemID input for this Choreo. ((required, string) The ID of an item to retrieve the status for. Multiple item IDs can be separated by commas.) */ this.set_ItemID = function(value) { this.setInput("ItemID", value); } /* Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Valid values are: json (the default) and xml.) */ this.set_ResponseFormat = function(value) { this.setInput("ResponseFormat", value); } /* Set the value of the SandboxMode input for this Choreo. ((optional, boolean) Indicates that the request should be made to the sandbox endpoint instead of the production endpoint. Set to 1 to enable sandbox mode.) */ this.set_SandboxMode = function(value) { this.setInput("SandboxMode", value); } /* Set the value of the SiteID input for this Choreo. ((optional, string) The eBay site ID that you want to access. Defaults to 0 indicating the US site.) */ this.set_SiteID = function(value) { this.setInput("SiteID", value); } } /* A ResultSet with methods tailored to the values returned by the GetItemStatus Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var GetItemStatusResultSet = function(resultStream) { GetItemStatusResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. (The response from eBay.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(GetItemStatus, choreography.Choreography); util.inherits(GetItemStatusInputSet, choreography.InputSet); util.inherits(GetItemStatusResultSet, choreography.ResultSet); exports.GetItemStatus = GetItemStatus; /* GetMultipleItems Retrieves publicly available data for one or more listings. */ var GetMultipleItems = function(session) { /* Create a new instance of the GetMultipleItems Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/eBay/Shopping/GetMultipleItems" GetMultipleItems.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new GetMultipleItemsResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new GetMultipleItemsInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the GetMultipleItems Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var GetMultipleItemsInputSet = function() { GetMultipleItemsInputSet.super_.call(this); /* Set the value of the AppID input for this Choreo. ((required, string) The unique identifier for the application.) */ this.set_AppID = function(value) { this.setInput("AppID", value); } /* Set the value of the ItemID input for this Choreo. ((required, string) The ID of an item to retrieve the status for. Multiple item IDs can be separated by commas.) */ this.set_ItemID = function(value) { this.setInput("ItemID", value); } /* Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Valid values are: json (the default) and xml.) */ this.set_ResponseFormat = function(value) { this.setInput("ResponseFormat", value); } /* Set the value of the SandboxMode input for this Choreo. ((optional, boolean) Indicates that the request should be made to the sandbox endpoint instead of the production endpoint. Set to 1 to enable sandbox mode.) */ this.set_SandboxMode = function(value) { this.setInput("SandboxMode", value); } /* Set the value of the SiteID input for this Choreo. ((optional, string) The eBay site ID that you want to access. Defaults to 0 indicating the US site.) */ this.set_SiteID = function(value) { this.setInput("SiteID", value); } } /* A ResultSet with methods tailored to the values returned by the GetMultipleItems Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var GetMultipleItemsResultSet = function(resultStream) { GetMultipleItemsResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. (The response from eBay.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(GetMultipleItems, choreography.Choreography); util.inherits(GetMultipleItemsInputSet, choreography.InputSet); util.inherits(GetMultipleItemsResultSet, choreography.ResultSet); exports.GetMultipleItems = GetMultipleItems; /* GetShippingCosts Retrieves shipping costs for an item. */ var GetShippingCosts = function(session) { /* Create a new instance of the GetShippingCosts Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/eBay/Shopping/GetShippingCosts" GetShippingCosts.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new GetShippingCostsResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new GetShippingCostsInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the GetShippingCosts Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var GetShippingCostsInputSet = function() { GetShippingCostsInputSet.super_.call(this); /* Set the value of the AppID input for this Choreo. ((required, string) The unique identifier for the application.) */ this.set_AppID = function(value) { this.setInput("AppID", value); } /* Set the value of the DestinationCountryCode input for this Choreo. ((conditional, string) The shipment destination country code.) */ this.set_DestinationCountryCode = function(value) { this.setInput("DestinationCountryCode", value); } /* Set the value of the DestinationPostalCode input for this Choreo. ((conditional, string) The shipment destination postal code.) */ this.set_DestinationPostalCode = function(value) { this.setInput("DestinationPostalCode", value); } /* Set the value of the IncludeDetails input for this Choreo. ((conditional, boolean) Indicates whether to return the ShippingDetails container in the response.) */ this.set_IncludeDetails = function(value) { this.setInput("IncludeDetails", value); } /* Set the value of the ItemID input for this Choreo. ((required, string) The ID of the item to get shipping costs for.) */ this.set_ItemID = function(value) { this.setInput("ItemID", value); } /* Set the value of the QuantitySold input for this Choreo. ((optional, string) The quantity of items being shipped.) */ this.set_QuantitySold = function(value) { this.setInput("QuantitySold", value); } /* Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Valid values are: json (the default) and xml.) */ this.set_ResponseFormat = function(value) { this.setInput("ResponseFormat", value); } /* Set the value of the SandboxMode input for this Choreo. ((optional, boolean) Indicates that the request should be made to the sandbox endpoint instead of the production endpoint. Set to 1 to enable sandbox mode.) */ this.set_SandboxMode = function(value) { this.setInput("SandboxMode", value); } /* Set the value of the SiteID input for this Choreo. ((optional, string) The eBay site ID that you want to access. Defaults to 0 indicating the US site.) */ this.set_SiteID = function(value) { this.setInput("SiteID", value); } } /* A ResultSet with methods tailored to the values returned by the GetShippingCosts Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var GetShippingCostsResultSet = function(resultStream) { GetShippingCostsResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. (The response from eBay.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(GetShippingCosts, choreography.Choreography); util.inherits(GetShippingCostsInputSet, choreography.InputSet); util.inherits(GetShippingCostsResultSet, choreography.ResultSet); exports.GetShippingCosts = GetShippingCosts; /* GetUserProfile Retrieves public user information based on the user ID you specify. */ var GetUserProfile = function(session) { /* Create a new instance of the GetUserProfile Choreo. A TembooSession object, containing a valid set of Temboo credentials, must be supplied. */ var location = "/Library/eBay/Shopping/GetUserProfile" GetUserProfile.super_.call(this, session, location); /* Define a callback that will be used to appropriately format the results of this Choreo. */ var newResultSet = function(resultStream) { return new GetUserProfileResultSet(resultStream); } /* Obtain a new InputSet object, used to specify the input values for an execution of this Choreo. */ this.newInputSet = function() { return new GetUserProfileInputSet(); } /* Execute this Choreo with the specified inputs, calling the specified callback upon success, and the specified errorCallback upon error. */ this.execute = function(inputs, callback, errorCallback) { this._execute(inputs, newResultSet, callback, errorCallback); } } /* An InputSet with methods appropriate for specifying the inputs to the GetUserProfile Choreo. The InputSet object is used to specify input parameters when executing this Choreo. */ var GetUserProfileInputSet = function() { GetUserProfileInputSet.super_.call(this); /* Set the value of the AppID input for this Choreo. ((required, string) The unique identifier for the application.) */ this.set_AppID = function(value) { this.setInput("AppID", value); } /* Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format that the response should be in. Valid values are: json (the default) and xml.) */ this.set_ResponseFormat = function(value) { this.setInput("ResponseFormat", value); } /* Set the value of the SandboxMode input for this Choreo. ((optional, boolean) Indicates that the request should be made to the sandbox endpoint instead of the production endpoint. Set to 1 to enable sandbox mode.) */ this.set_SandboxMode = function(value) { this.setInput("SandboxMode", value); } /* Set the value of the SiteID input for this Choreo. ((optional, string) The eBay site ID that you want to access. Defaults to 0 indicating the US site.) */ this.set_SiteID = function(value) { this.setInput("SiteID", value); } /* Set the value of the UserID input for this Choreo. ((required, string) The ID of the user to return the profile for.) */ this.set_UserID = function(value) { this.setInput("UserID", value); } } /* A ResultSet with methods tailored to the values returned by the GetUserProfile Choreo. The ResultSet object is used to retrieve the results of a Choreo execution. */ var GetUserProfileResultSet = function(resultStream) { GetUserProfileResultSet.super_.call(this, resultStream); /* Retrieve the value for the "Response" output from this Choreo execution. (The response from eBay.) */ this.get_Response = function() { return this.getResult("Response"); } } util.inherits(GetUserProfile, choreography.Choreography); util.inherits(GetUserProfileInputSet, choreography.InputSet); util.inherits(GetUserProfileResultSet, choreography.ResultSet); exports.GetUserProfile = GetUserProfile;
rwaldron/ideino-linino-dist
node_modules/temboo/Library/eBay/Shopping.js
JavaScript
mit
31,212
using System.ComponentModel.DataAnnotations; namespace EP.IdentityIsolation.Infra.CrossCutting.Identity.Model { public class AddPhoneNumberViewModel { [Required] [Phone] [Display(Name = "Phone Number")] public string Number { get; set; } } }
bellinat/IdentityIsolation
src/EP.IdentityIsolation.Infra.CrossCutting.Identity/Model/AddPhoneNumberViewModel.cs
C#
mit
289
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; namespace Microsoft.Azure.WebJobs.Host.Queues { /// <summary> /// Factory for creating <see cref="QueueProcessor"/> instances. /// </summary> [CLSCompliant(false)] public interface IQueueProcessorFactory { /// <summary> /// Creates a <see cref="QueueProcessor"/> using the specified context. /// </summary> /// <param name="context">The <see cref="QueueProcessorFactoryContext"/> to use.</param> /// <returns>A <see cref="QueueProcessor"/> instance.</returns> QueueProcessor Create(QueueProcessorFactoryContext context); } }
brendankowitz/azure-webjobs-sdk
src/Microsoft.Azure.WebJobs.Host/Queues/IQueueProcessorFactory.cs
C#
mit
771
/******************************************************************************* * Copyright (c) 2015 * * 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. *******************************************************************************/ package jsettlers.network.server.match; import java.util.List; import java.util.TimerTask; import jsettlers.network.NetworkConstants; import jsettlers.network.common.packets.ArrayOfMatchInfosPacket; import jsettlers.network.common.packets.MatchInfoPacket; import jsettlers.network.server.db.IDBFacade; /** * This {@link TimerTask} implementation gets the logged in players and sends them the open matches on every call to {@link #run()}. * * @author Andreas Eberle * */ public class MatchesListSendingTimerTask extends TimerTask { private final IDBFacade db; public MatchesListSendingTimerTask(IDBFacade db) { this.db = db; } @Override public void run() { List<Player> loggedInPlayers = db.getPlayers(EPlayerState.LOGGED_IN); ArrayOfMatchInfosPacket packet = getArrayOfMatchInfosPacket(); for (Player currPlayer : loggedInPlayers) { sendMatchesPacketToPlayer(currPlayer, packet); } } private void sendMatchesPacketToPlayer(Player player, ArrayOfMatchInfosPacket arrayOfMatchesPacket) { player.sendPacket(NetworkConstants.ENetworkKey.ARRAY_OF_MATCHES, arrayOfMatchesPacket); } private ArrayOfMatchInfosPacket getArrayOfMatchInfosPacket() { List<Match> matches = db.getJoinableMatches(); MatchInfoPacket[] matchInfoPackets = new MatchInfoPacket[matches.size()]; int i = 0; for (Match curr : matches) { matchInfoPackets[i] = new MatchInfoPacket(curr); i++; } return new ArrayOfMatchInfosPacket(matchInfoPackets); } public void sendMatchesTo(Player player) { ArrayOfMatchInfosPacket arrayOfMatchesPacket = getArrayOfMatchInfosPacket(); sendMatchesPacketToPlayer(player, arrayOfMatchesPacket); } }
jsettlers/settlers-remake
jsettlers.network/src/main/java/jsettlers/network/server/match/MatchesListSendingTimerTask.java
Java
mit
2,899
/*************************************************************************/ /* main.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* 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 MAIN_H #define MAIN_H /** @author Juan Linietsky <[email protected]> */ #include "error_list.h" #include "typedefs.h" class Main { static void print_help(const char* p_binary); static uint64_t last_ticks; static uint64_t target_ticks; static float time_accum; static uint32_t frames; static uint32_t frame; static bool force_redraw_requested; public: static Error setup(const char *execpath,int argc, char *argv[],bool p_second_phase=true); static Error setup2(); static bool start(); static bool iteration(); static void cleanup(); static void force_redraw(); }; #endif
DustinTriplett/godot
main/main.h
C
mit
2,728
package metro import "encoding/binary" func rotate_right(v uint64, k uint) uint64 { return (v >> k) | (v << (64 - k)) } func Hash128(buffer []byte, seed uint64) (uint64, uint64) { const ( k0 = 0xC83A91E1 k1 = 0x8648DBDB k2 = 0x7BDEC03B k3 = 0x2F5870A5 ) ptr := buffer var v [4]uint64 v[0] = (seed - k0) * k3 v[1] = (seed + k1) * k2 if len(ptr) >= 32 { v[2] = (seed + k0) * k2 v[3] = (seed - k1) * k3 for len(ptr) >= 32 { v[0] += binary.LittleEndian.Uint64(ptr) * k0 ptr = ptr[8:] v[0] = rotate_right(v[0], 29) + v[2] v[1] += binary.LittleEndian.Uint64(ptr) * k1 ptr = ptr[8:] v[1] = rotate_right(v[1], 29) + v[3] v[2] += binary.LittleEndian.Uint64(ptr) * k2 ptr = ptr[8:] v[2] = rotate_right(v[2], 29) + v[0] v[3] += binary.LittleEndian.Uint64(ptr) * k3 ptr = ptr[8:] v[3] = rotate_right(v[3], 29) + v[1] } v[2] ^= rotate_right(((v[0]+v[3])*k0)+v[1], 21) * k1 v[3] ^= rotate_right(((v[1]+v[2])*k1)+v[0], 21) * k0 v[0] ^= rotate_right(((v[0]+v[2])*k0)+v[3], 21) * k1 v[1] ^= rotate_right(((v[1]+v[3])*k1)+v[2], 21) * k0 } if len(ptr) >= 16 { v[0] += binary.LittleEndian.Uint64(ptr) * k2 ptr = ptr[8:] v[0] = rotate_right(v[0], 33) * k3 v[1] += binary.LittleEndian.Uint64(ptr) * k2 ptr = ptr[8:] v[1] = rotate_right(v[1], 33) * k3 v[0] ^= rotate_right((v[0]*k2)+v[1], 45) * k1 v[1] ^= rotate_right((v[1]*k3)+v[0], 45) * k0 } if len(ptr) >= 8 { v[0] += binary.LittleEndian.Uint64(ptr) * k2 ptr = ptr[8:] v[0] = rotate_right(v[0], 33) * k3 v[0] ^= rotate_right((v[0]*k2)+v[1], 27) * k1 } if len(ptr) >= 4 { v[1] += uint64(binary.LittleEndian.Uint32(ptr)) * k2 ptr = ptr[4:] v[1] = rotate_right(v[1], 33) * k3 v[1] ^= rotate_right((v[1]*k3)+v[0], 46) * k0 } if len(ptr) >= 2 { v[0] += uint64(binary.LittleEndian.Uint16(ptr)) * k2 ptr = ptr[2:] v[0] = rotate_right(v[0], 33) * k3 v[0] ^= rotate_right((v[0]*k2)+v[1], 22) * k1 } if len(ptr) >= 1 { v[1] += uint64(ptr[0]) * k2 v[1] = rotate_right(v[1], 33) * k3 v[1] ^= rotate_right((v[1]*k3)+v[0], 58) * k0 } v[0] += rotate_right((v[0]*k0)+v[1], 13) v[1] += rotate_right((v[1]*k1)+v[0], 37) v[0] += rotate_right((v[0]*k2)+v[1], 13) v[1] += rotate_right((v[1]*k3)+v[0], 37) return v[0], v[1] }
gphat/veneur
vendor/github.com/dgryski/go-metro/metro128.go
GO
mit
2,283
define('lodash/internal/baseFilter', ['exports', 'lodash/internal/baseEach'], function (exports, _lodashInternalBaseEach) { 'use strict'; /** * The base implementation of `_.filter` without support for callback * shorthands and `this` binding. * * @private * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; (0, _lodashInternalBaseEach['default'])(collection, function (value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } exports['default'] = baseFilter; });
hoka-plus/p-01-web
tmp/babel-output_path-hOv4KMmE.tmp/lodash/internal/baseFilter.js
JavaScript
mit
797
/*************************************************************************/ /* FBXParser.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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. */ /*************************************************************************/ /* Open Asset Import Library (assimp) ---------------------------------------------------------------------- Copyright (c) 2006-2019, assimp team All rights reserved. Redistribution and use of this software 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 assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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. ---------------------------------------------------------------------- */ /** @file FBXParser.h * @brief FBX parsing code */ #ifndef FBX_PARSER_H #define FBX_PARSER_H #include <stdint.h> #include <map> #include <memory> #include "core/math/color.h" #include "core/math/transform_3d.h" #include "core/math/vector2.h" #include "core/math/vector3.h" #include "FBXTokenizer.h" namespace FBXDocParser { class Scope; class Parser; class Element; typedef Element *ElementPtr; typedef Scope *ScopePtr; typedef std::vector<ScopePtr> ScopeList; typedef std::multimap<std::string, ElementPtr> ElementMap; typedef std::pair<ElementMap::const_iterator, ElementMap::const_iterator> ElementCollection; #define new_Scope new Scope #define new_Element new Element /** FBX data entity that consists of a key:value tuple. * * Example: * @verbatim * AnimationCurve: 23, "AnimCurve::", "" { * [..] * } * @endverbatim * * As can be seen in this sample, elements can contain nested #Scope * as their trailing member. **/ class Element { public: Element(TokenPtr key_token, Parser &parser); ~Element(); ScopePtr Compound() const { return compound; } TokenPtr KeyToken() const { return key_token; } const TokenList &Tokens() const { return tokens; } private: TokenList tokens; ScopePtr compound = nullptr; std::vector<ScopePtr> compound_scope; TokenPtr key_token = nullptr; }; /** FBX data entity that consists of a 'scope', a collection * of not necessarily unique #Element instances. * * Example: * @verbatim * GlobalSettings: { * Version: 1000 * Properties70: * [...] * } * @endverbatim */ class Scope { public: Scope(Parser &parser, bool topLevel = false); ~Scope(); ElementPtr GetElement(const std::string &index) const { ElementMap::const_iterator it = elements.find(index); return it == elements.end() ? nullptr : (*it).second; } ElementPtr FindElementCaseInsensitive(const std::string &elementName) const { for (FBXDocParser::ElementMap::const_iterator element = elements.begin(); element != elements.end(); ++element) { if (element->first.compare(elementName)) { return element->second; } } // nothing to reference / expired. return nullptr; } ElementCollection GetCollection(const std::string &index) const { return elements.equal_range(index); } const ElementMap &Elements() const { return elements; } private: ElementMap elements; }; /** FBX parsing class, takes a list of input tokens and generates a hierarchy * of nested #Scope instances, representing the fbx DOM.*/ class Parser { public: /** Parse given a token list. Does not take ownership of the tokens - * the objects must persist during the entire parser lifetime */ Parser(const TokenList &tokens, bool is_binary); ~Parser(); ScopePtr GetRootScope() const { return root; } bool IsBinary() const { return is_binary; } bool IsCorrupt() const { return corrupt; } private: friend class Scope; friend class Element; TokenPtr AdvanceToNextToken(); TokenPtr LastToken() const; TokenPtr CurrentToken() const; private: bool corrupt = false; ScopeList scopes; const TokenList &tokens; TokenPtr last = nullptr, current = nullptr; TokenList::const_iterator cursor; ScopePtr root = nullptr; const bool is_binary; }; /* token parsing - this happens when building the DOM out of the parse-tree*/ uint64_t ParseTokenAsID(const TokenPtr t, const char *&err_out); size_t ParseTokenAsDim(const TokenPtr t, const char *&err_out); float ParseTokenAsFloat(const TokenPtr t, const char *&err_out); int ParseTokenAsInt(const TokenPtr t, const char *&err_out); int64_t ParseTokenAsInt64(const TokenPtr t, const char *&err_out); std::string ParseTokenAsString(const TokenPtr t, const char *&err_out); /* wrapper around ParseTokenAsXXX() with DOMError handling */ uint64_t ParseTokenAsID(const TokenPtr t); size_t ParseTokenAsDim(const TokenPtr t); float ParseTokenAsFloat(const TokenPtr t); int ParseTokenAsInt(const TokenPtr t); int64_t ParseTokenAsInt64(const TokenPtr t); std::string ParseTokenAsString(const TokenPtr t); /* read data arrays */ void ParseVectorDataArray(std::vector<Vector3> &out, const ElementPtr el); void ParseVectorDataArray(std::vector<Color> &out, const ElementPtr el); void ParseVectorDataArray(std::vector<Vector2> &out, const ElementPtr el); void ParseVectorDataArray(std::vector<int> &out, const ElementPtr el); void ParseVectorDataArray(std::vector<float> &out, const ElementPtr el); void ParseVectorDataArray(std::vector<float> &out, const ElementPtr el); void ParseVectorDataArray(std::vector<unsigned int> &out, const ElementPtr el); void ParseVectorDataArray(std::vector<uint64_t> &out, const ElementPtr ep); void ParseVectorDataArray(std::vector<int64_t> &out, const ElementPtr el); bool HasElement(const ScopePtr sc, const std::string &index); // extract a required element from a scope, abort if the element cannot be found ElementPtr GetRequiredElement(const ScopePtr sc, const std::string &index, const ElementPtr element = nullptr); ScopePtr GetRequiredScope(const ElementPtr el); // New in 2020. (less likely to destroy application) ScopePtr GetOptionalScope(const ElementPtr el); // New in 2021. (even LESS likely to destroy application now) ElementPtr GetOptionalElement(const ScopePtr sc, const std::string &index, const ElementPtr element = nullptr); // extract required compound scope ScopePtr GetRequiredScope(const ElementPtr el); // get token at a particular index TokenPtr GetRequiredToken(const ElementPtr el, unsigned int index); // ------------------------------------------------------------------------------------------------ // read a 4x4 matrix from an array of 16 floats Transform3D ReadMatrix(const ElementPtr element); } // namespace FBXDocParser #endif // FBX_PARSER_H
honix/godot
modules/fbx/fbx_parser/FBXParser.h
C
mit
9,706
/* * 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. */ #include <inttypes.h> #include "encoding.h" #include <stdlib.h> #include <limits.h> #include <errno.h> #include <string.h> #include "utilities/kaa_mem.h" #include "avro_private.h" #define MAX_VARINT_BUF_SIZE 10 static int read_long(avro_reader_t reader, int64_t * l) { uint64_t value = 0; uint8_t b; int offset = 0; do { if (offset == MAX_VARINT_BUF_SIZE) { return EILSEQ; } AVRO_READ(reader, &b, 1); value |= (int64_t) (b & 0x7F) << (7 * offset); ++offset; } while (b & 0x80); *l = ((value >> 1) ^ -(value & 1)); return 0; } static int write_long(avro_writer_t writer, int64_t l) { char buf[MAX_VARINT_BUF_SIZE]; uint8_t bytes_written = 0; uint64_t n = (l << 1) ^ (l >> 63); while (n & ~0x7F) { buf[bytes_written++] = (char)((((uint8_t) n) & 0x7F) | 0x80); n >>= 7; } buf[bytes_written++] = (char)n; AVRO_WRITE(writer, buf, bytes_written); return 0; } static int read_int(avro_reader_t reader, int32_t * i) { int64_t l; int rval; check(rval, read_long(reader, &l)); if (!(INT_MIN <= l && l <= INT_MAX)) { return ERANGE; } *i = l; return 0; } static int write_int(avro_writer_t writer, const int32_t i) { int64_t l = i; return write_long(writer, l); } static int read_bytes(avro_reader_t reader, char **bytes, int64_t * len) { int rval; check_prefix(rval, read_long(reader, len), "Cannot read bytes length: "); *bytes = (char *) KAA_MALLOC(*len); if (!*bytes) { return ENOMEM; } AVRO_READ(reader, *bytes, *len); return 0; } static int write_bytes(avro_writer_t writer, const char *bytes, const int64_t len) { int rval; if (len < 0) { return EINVAL; } check_prefix(rval, write_long(writer, len), "Cannot write bytes length: "); AVRO_WRITE(writer, (char *)bytes, len); return 0; } static int read_string(avro_reader_t reader, char **s, int64_t *len) { (void)len; int64_t str_len = 0; int rval; check_prefix(rval, read_long(reader, &str_len), "Cannot read string length: "); *s = (char *) KAA_MALLOC(str_len + 1); if (!*s) { return ENOMEM; } (*s)[str_len] = '\0'; AVRO_READ(reader, *s, str_len); return 0; } static int write_string(avro_writer_t writer, const char *s) { int64_t len = strlen(s); return write_bytes(writer, s, len); } static int read_float(avro_reader_t reader, float *f) { #if AVRO_PLATFORM_IS_BIG_ENDIAN uint8_t buf[4]; #endif union { float f; int32_t i; } v; #if AVRO_PLATFORM_IS_BIG_ENDIAN AVRO_READ(reader, buf, 4); v.i = ((int32_t) buf[0] << 0) | ((int32_t) buf[1] << 8) | ((int32_t) buf[2] << 16) | ((int32_t) buf[3] << 24); #else AVRO_READ(reader, (void *)&v.i, 4); #endif *f = v.f; return 0; } static int write_float(avro_writer_t writer, const float f) { #if AVRO_PLATFORM_IS_BIG_ENDIAN uint8_t buf[4]; #endif union { float f; int32_t i; } v; v.f = f; #if AVRO_PLATFORM_IS_BIG_ENDIAN buf[0] = (uint8_t) (v.i >> 0); buf[1] = (uint8_t) (v.i >> 8); buf[2] = (uint8_t) (v.i >> 16); buf[3] = (uint8_t) (v.i >> 24); AVRO_WRITE(writer, buf, 4); #else AVRO_WRITE(writer, (void *)&v.i, 4); #endif return 0; } static int read_double(avro_reader_t reader, double *d) { #if AVRO_PLATFORM_IS_BIG_ENDIAN uint8_t buf[8]; #endif union { double d; int64_t l; } v; #if AVRO_PLATFORM_IS_BIG_ENDIAN AVRO_READ(reader, buf, 8); v.l = ((int64_t) buf[0] << 0) | ((int64_t) buf[1] << 8) | ((int64_t) buf[2] << 16) | ((int64_t) buf[3] << 24) | ((int64_t) buf[4] << 32) | ((int64_t) buf[5] << 40) | ((int64_t) buf[6] << 48) | ((int64_t) buf[7] << 56); #else AVRO_READ(reader, (void *)&v.l, 8); #endif *d = v.d; return 0; } static int write_double(avro_writer_t writer, const double d) { #if AVRO_PLATFORM_IS_BIG_ENDIAN uint8_t buf[8]; #endif union { double d; int64_t l; } v; v.d = d; #if AVRO_PLATFORM_IS_BIG_ENDIAN buf[0] = (uint8_t) (v.l >> 0); buf[1] = (uint8_t) (v.l >> 8); buf[2] = (uint8_t) (v.l >> 16); buf[3] = (uint8_t) (v.l >> 24); buf[4] = (uint8_t) (v.l >> 32); buf[5] = (uint8_t) (v.l >> 40); buf[6] = (uint8_t) (v.l >> 48); buf[7] = (uint8_t) (v.l >> 56); AVRO_WRITE(writer, buf, 8); #else AVRO_WRITE(writer, (void *)&v.l, 8); #endif return 0; } static int read_boolean(avro_reader_t reader, int8_t * b) { AVRO_READ(reader, b, 1); return 0; } static int write_boolean(avro_writer_t writer, const int8_t b) { AVRO_WRITE(writer, (char *)&b, 1); return 0; } static int read_skip_null(avro_reader_t reader) { /* * no-op */ AVRO_UNUSED(reader); return 0; } static int write_null(avro_writer_t writer) { /* * no-op */ AVRO_UNUSED(writer); return 0; } /* Win32 doesn't support the C99 method of initializing named elements * in a struct declaration. So hide the named parameters for Win32, * and initialize in the order the code was written. */ const avro_encoding_t avro_binary_encoding = { /* .description = */ "BINARY FORMAT", /* * string */ /* .read_string = */ read_string, /* .write_string = */ write_string, /* * bytes */ /* .read_bytes = */ read_bytes, /* .write_bytes = */ write_bytes, /* * int */ /* .read_int = */ read_int, /* .write_int = */ write_int, /* * long */ /* .read_long = */ read_long, /* .write_long = */ write_long, /* * float */ /* .read_float = */ read_float, /* .write_float = */ write_float, /* * double */ /* .read_double = */ read_double, /* .write_double = */ write_double, /* * boolean */ /* .read_boolean = */ read_boolean, /* .write_boolean = */ write_boolean, /* * null */ /* .read_null = */ read_skip_null, /* .write_null = */ write_null, };
Donny3000/auto-gardern-kaa
flowerbed-ep/kaa/src/kaa/avro_src/encoding_binary.c
C
mit
6,988
/* * 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. */ package javax.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, ElementType.PACKAGE, ElementType.PARAMETER, ElementType.TYPE}) @Retention(RetentionPolicy.SOURCE) public @interface Generated { public String[] value(); public String date() default ""; public String comment() default ""; }
plumer/codana
tomcat_files/7.0.0/Generated.java
Java
mit
1,373
# jsdom-global > Enables DOM in Node.js jsdom-global will inject `document`, `window` and other DOM API into your Node.js environment. Useful for running, in Node.js, tests that are made for browsers. [![Status](https://travis-ci.org/rstacruz/jsdom-global.svg?branch=master)](https://travis-ci.org/rstacruz/jsdom-global "See test builds") ## Install Requires [jsdom][]. ``` npm install --save-dev --save-exact jsdom jsdom-global ``` [jsdom]: https://github.com/tmpvar/jsdom ## Usage Just invoke it to turn your Node.js environment into a DOM environment. ```js require('jsdom-global')() // you can now use the DOM document.body.innerHTML = 'hello' ``` You may also pass parameters to jsdomGlobal() like so: `require('jsdom-global')(html, options)`. Check the [jsdom.jsdom()][] documentation for valid values for the `options` parameter. To clean up after itself, just invoke the function it returns. ```js var cleanup = require('jsdom-global')() // do things cleanup() ``` ## Tape In [tape][], run it before your other tests. ```js require('jsdom-global')() test('your tests', (t) => { /* and so on... */ }) ``` ## Mocha __Simple:__ Use Mocha's `--require` option. Add this to the `test/mocha.opts` file (create it if it doesn't exist) ``` -r jsdom-global/register ``` __Advanced:__ For finer control, you can instead add it via [mocha]'s `before` and `after` hooks. ```js before(function () { this.jsdom = require('jsdom-global')() }) after(function () { this.jsdom() }) ``` [tape]: https://github.com/substack/tape [mocha]: https://mochajs.org/ [jsdom.jsdom()]: https://github.com/tmpvar/jsdom/#for-the-hardcore-jsdomjsdom ## ES2015 If you prefer to use `import` rather that `require`, you might want to use `jsdom-global/register` instead. Place it on top of your other import calls. ```js import 'jsdom-global/register' import React from 'react' import jQuery from 'jquery' // ... ``` ## Browserify If you use [Browserify] on your tests (eg: [smokestack], [tape-run], [budo], [hihat], [zuul], and so on), doing `require('jsdom-global')()` is a noop. In practice, this means you can use jsdom-global even if your tests are powered by browserify, and your test will now work in both the browser and Node. [zuul]: https://www.npmjs.com/package/zuul [tape-run]: https://www.npmjs.com/package/tape-run [budo]: https://github.com/mattdesl/budo [hihat]: https://www.npmjs.com/package/hihat [smokestack]: https://www.npmjs.com/package/smokestack * Writing your tests (`test.js`): ```js require('jsdom-global')() // ...do your tests here ``` * Running it with [smokestack]: ```sh browserify test.js | smokestack # run in a browser node test.js # or the console browserify test.js --no-bundle-external # also works (but why bother?) ``` * Running it with Babel ([babelify] or [babel-cli]): ```sh browserify test.js -t babelify | smokestack # run in a browser (with babel) babel-node test.js # or the console ``` [Browserify]: http://browserify.org/ [babel-cli]: https://babeljs.io/docs/usage/cli/ [babelify]: https://github.com/babel/babelify ## Thanks **jsdom-global** © 2016+, Rico Sta. Cruz. Released under the [MIT] License.<br> Authored and maintained by Rico Sta. Cruz with help from contributors ([list][contributors]). > [ricostacruz.com](http://ricostacruz.com) &nbsp;&middot;&nbsp; > GitHub [@rstacruz](https://github.com/rstacruz) &nbsp;&middot;&nbsp; > Twitter [@rstacruz](https://twitter.com/rstacruz) [MIT]: http://mit-license.org/ [contributors]: http://github.com/rstacruz/jsdom-global/contributors
Amin52J/AutoMagic
test/node_modules/jsdom-global/README.md
Markdown
mit
3,652
Invoke-Expression "Invoke me" iex "Invoke me"
PowerShell/PSScriptAnalyzer
Tests/Rules/AvoidUsingInvokeExpression.ps1
PowerShell
mit
48
<?php /** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Catalog\Test\Constraint; use Magento\Catalog\Test\Page\Adminhtml\CatalogProductAttributeIndex; use Magento\Mtf\Constraint\AbstractConstraint; /** * Class AssertProductAttributeSaveMessage */ class AssertProductAttributeSaveMessage extends AbstractConstraint { /** * Product attribute success save message. */ const SUCCESS_MESSAGE = 'You saved the product attribute.'; /** * Assert that message "You saved the product attribute." is present on Attribute page * * @param CatalogProductAttributeIndex $attributeIndex * @return void */ public function processAssert(CatalogProductAttributeIndex $attributeIndex) { $actualMessage = $attributeIndex->getMessagesBlock()->getSuccessMessage(); \PHPUnit_Framework_Assert::assertEquals( self::SUCCESS_MESSAGE, $actualMessage, 'Wrong success message is displayed.' . "\nExpected: " . self::SUCCESS_MESSAGE . "\nActual: " . $actualMessage ); } /** * Text success present save message * * @return string */ public function toString() { return 'Attribute success save message is present.'; } }
j-froehlich/magento2_wk
vendor/magento/magento2-base/dev/tests/functional/tests/app/Magento/Catalog/Test/Constraint/AssertProductAttributeSaveMessage.php
PHP
mit
1,357
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef GrPathIter_DEFINED #define GrPathIter_DEFINED #include "GrTypes.h" struct GrPoint; /** 2D Path iterator. Porting layer creates a subclass of this. It allows Ganesh to parse the top-level API's 2D paths. Supports lines, quadratics, and cubic pieces and moves (multi-part paths). */ class GrPathIter { public: /** Returned by next(). Indicates the next piece of the path. */ enum Command { kMove_Command, //!< next() returns 1 pt // Starts a new subpath at // at the returned point kLine_Command, //!< next() returns 2 pts // Adds a line segment kQuadratic_Command, //!< next() returns 3 pts // Adds a quadratic segment kCubic_Command, //!< next() returns 4 pts // Adds a cubic segment kClose_Command, //!< next() returns 0 pts kEnd_Command //!< next() returns 0 pts // Implictly closes the last // point }; enum ConvexHint { kNone_ConvexHint, //<! No hint about convexity // of the path kConvex_ConvexHint, //<! Path is one convex piece kNonOverlappingConvexPieces_ConvexHint, //<! Multiple convex pieces, // pieces are known to be // disjoint kSameWindingConvexPieces_ConvexHint, //<! Multiple convex pieces, // may or may not intersect, // either all wind cw or all // wind ccw. kConcave_ConvexHint //<! Path is known to be // concave }; static int NumCommandPoints(Command cmd) { static const int numPoints[] = { 1, 2, 3, 4, 0, 0 }; return numPoints[cmd]; } virtual ~GrPathIter() {}; /** Iterates through the path. Should not be called after kEnd_Command has been returned once. This version retrieves the points for the command. @param points The points relevant to returned commend. See Command enum for number of points valid for each command. @return The next command of the path. */ virtual Command next(GrPoint points[4]) = 0; /** * If the host API has knowledge of the convexity of the path * it can be communicated by this hint. Ganesh can make these * determinations itself. So it is not necessary to compute * convexity status if it isn't already determined. * * @return a hint about the convexity of the path. */ virtual ConvexHint hint() const { return kNone_ConvexHint; } /** Iterates through the path. Should not be called after kEnd_Command has been returned once. This version does not retrieve the points for the command. @return The next command of the path. */ virtual Command next() = 0; /** Restarts iteration from the beginning. */ virtual void rewind() = 0; }; #endif
diwu/Tiny-Wings-Remake-on-Android
twxes10/libs/cocos2dx/platform/third_party/qnx/include/grskia/GrPathIter.h
C
mit
4,151
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Syndication { using System; using System.Collections.Generic; /// <summary> /// Internal representation of parsed RSS channel. /// </summary> internal class RssChannelDom { private readonly Dictionary<string, string> _channel; private readonly Dictionary<string, string> _image; private readonly List<Dictionary<string, string>> _items; private DateTime _utcExpiry; internal RssChannelDom(Dictionary<string, string> channel, Dictionary<string, string> image, List<Dictionary<string, string>> items) { this._channel = channel; this._image = image; this._items = items; this._utcExpiry = DateTime.MaxValue; } internal Dictionary<string, string> Channel { get { return this._channel; } } internal Dictionary<string, string> Image { get { return this._image; } } internal List<Dictionary<string, string>> Items { get { return this._items; } } internal DateTime UtcExpiry { get { return this._utcExpiry; } } internal void SetExpiry(DateTime utcExpiry) { this._utcExpiry = utcExpiry; } } }
nvisionative/Dnn.Platform
DNN Platform/Syndication/RSS/RssChannelDom.cs
C#
mit
1,709
define(function (require, exports, module) {/** @jsx React.DOM */ var React = require('react'); var classSet = require('./utils/classSet'); var TransitionEvents = require('./utils/TransitionEvents'); var TabPane = React.createClass({displayName: 'TabPane', getDefaultProps: function () { return { animation: true }; }, getInitialState: function () { return { animateIn: false, animateOut: false }; }, componentWillReceiveProps: function (nextProps) { if (this.props.animation) { if (!this.state.animateIn && nextProps.active && !this.props.active) { this.setState({ animateIn: true }); } else if (!this.state.animateOut && !nextProps.active && this.props.active) { this.setState({ animateOut: true }); } } }, componentDidUpdate: function () { if (this.state.animateIn) { setTimeout(this.startAnimateIn, 0); } if (this.state.animateOut) { TransitionEvents.addEndEventListener( this.getDOMNode(), this.stopAnimateOut ); } }, startAnimateIn: function () { if (this.isMounted()) { this.setState({ animateIn: false }); } }, stopAnimateOut: function () { if (this.isMounted()) { this.setState({ animateOut: false }); if (typeof this.props.onAnimateOutEnd === 'function') { this.props.onAnimateOutEnd(); } } }, render: function () { var classes = { 'tab-pane': true, 'fade': true, 'active': this.props.active || this.state.animateOut, 'in': this.props.active && !this.state.animateIn }; return this.transferPropsTo( React.DOM.div( {className:classSet(classes)}, this.props.children ) ); } }); module.exports = TabPane; });
zhanrnl/ag
webapp/js/vendor/react-bootstrap/TabPane.js
JavaScript
mit
1,854
<p>Russo means Russian. It seems strange that in a such font there is no snow, vodka or bears. What I wanted to show is that Russian culture is quite varied and modern. In Russia, too, some people love good fonts and typography. Russo One is designed for headlines and logotypes. It is simple and original, stylish and casual.</p><p>Russo One is a Unicode typeface family that supports languages that use the Cyrillic, Baltic, Turkish, Central Europe, Latin script and its variants, and could be expanded to support other scripts.</p> <p>To contribute to the project contact <a href="mailto:[email protected]">Jovanny Lemonad</a>.</p>
xErik/pdfmake-fonts-google
lib/ofl/russoone/DESCRIPTION.en_us.html
HTML
mit
636
'''login -- PythonWin user ID and password dialog box (Adapted from originally distributed with Mark Hammond's PythonWin - this now replaces it!) login.GetLogin() displays a modal "OK/Cancel" dialog box with input fields for a user ID and password. The password field input is masked with *'s. GetLogin takes two optional parameters, a window title, and a default user ID. If these parameters are omitted, the title defaults to "Login", and the user ID is left blank. GetLogin returns a (userid, password) tuple. GetLogin can be called from scripts running on the console - i.e. you don't need to write a full-blown GUI app to use it. login.GetPassword() is similar, except there is no username field. Example: import pywin.dialogs.login title = "FTP Login" def_user = "fred" userid, password = pywin.dialogs.login.GetLogin(title, def_user) Jim Eggleston, 28 August 1996 Merged with dlgpass and moved to pywin.dialogs by Mark Hammond Jan 1998. ''' import win32ui import win32api import win32con from pywin.mfc import dialog def MakeLoginDlgTemplate(title): style = win32con.DS_MODALFRAME | win32con.WS_POPUP | win32con.WS_VISIBLE | win32con.WS_CAPTION | win32con.WS_SYSMENU | win32con.DS_SETFONT cs = win32con.WS_CHILD | win32con.WS_VISIBLE # Window frame and title dlg = [ [title, (0, 0, 184, 40), style, None, (8, "MS Sans Serif")], ] # ID label and text box dlg.append([130, "User ID:", -1, (7, 9, 69, 9), cs | win32con.SS_LEFT]) s = cs | win32con.WS_TABSTOP | win32con.WS_BORDER dlg.append(['EDIT', None, win32ui.IDC_EDIT1, (50, 7, 60, 12), s]) # Password label and text box dlg.append([130, "Password:", -1, (7, 22, 69, 9), cs | win32con.SS_LEFT]) s = cs | win32con.WS_TABSTOP | win32con.WS_BORDER dlg.append(['EDIT', None, win32ui.IDC_EDIT2, (50, 20, 60, 12), s | win32con.ES_PASSWORD]) # OK/Cancel Buttons s = cs | win32con.WS_TABSTOP dlg.append([128, "OK", win32con.IDOK, (124, 5, 50, 14), s | win32con.BS_DEFPUSHBUTTON]) s = win32con.BS_PUSHBUTTON | s dlg.append([128, "Cancel", win32con.IDCANCEL, (124, 20, 50, 14), s]) return dlg def MakePasswordDlgTemplate(title): style = win32con.DS_MODALFRAME | win32con.WS_POPUP | win32con.WS_VISIBLE | win32con.WS_CAPTION | win32con.WS_SYSMENU | win32con.DS_SETFONT cs = win32con.WS_CHILD | win32con.WS_VISIBLE # Window frame and title dlg = [ [title, (0, 0, 177, 45), style, None, (8, "MS Sans Serif")], ] # Password label and text box dlg.append([130, "Password:", -1, (7, 7, 69, 9), cs | win32con.SS_LEFT]) s = cs | win32con.WS_TABSTOP | win32con.WS_BORDER dlg.append(['EDIT', None, win32ui.IDC_EDIT1, (50, 7, 60, 12), s | win32con.ES_PASSWORD]) # OK/Cancel Buttons s = cs | win32con.WS_TABSTOP | win32con.BS_PUSHBUTTON dlg.append([128, "OK", win32con.IDOK, (124, 5, 50, 14), s | win32con.BS_DEFPUSHBUTTON]) dlg.append([128, "Cancel", win32con.IDCANCEL, (124, 22, 50, 14), s]) return dlg class LoginDlg(dialog.Dialog): Cancel = 0 def __init__(self, title): dialog.Dialog.__init__(self, MakeLoginDlgTemplate(title) ) self.AddDDX(win32ui.IDC_EDIT1,'userid') self.AddDDX(win32ui.IDC_EDIT2,'password') def GetLogin(title='Login', userid='', password=''): d = LoginDlg(title) d['userid'] = userid d['password'] = password if d.DoModal() != win32con.IDOK: return (None, None) else: return (d['userid'], d['password']) class PasswordDlg(dialog.Dialog): def __init__(self, title): dialog.Dialog.__init__(self, MakePasswordDlgTemplate(title) ) self.AddDDX(win32ui.IDC_EDIT1,'password') def GetPassword(title='Password', password=''): d = PasswordDlg(title) d['password'] = password if d.DoModal()!=win32con.IDOK: return None return d['password'] if __name__ == "__main__": import sys title = 'Login' def_user = '' if len(sys.argv) > 1: title = sys.argv[1] if len(sys.argv) > 2: def_userid = sys.argv[2] userid, password = GetLogin(title, def_user) if userid == password == None: print("User pressed Cancel") else: print("User ID: ", userid) print("Password:", password) newpassword = GetPassword("Reenter just for fun", password) if newpassword is None: print("User cancelled") else: what = "" if newpassword != password: what = "not " print("The passwords did %smatch" % (what))
sserrot/champion_relationships
venv/Lib/site-packages/pythonwin/pywin/dialogs/login.py
Python
mit
4,250
#!/usr/bin/env python3 # Copyright (c) 2014-2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the wallet accounts properly when there is a double-spend conflict.""" from decimal import Decimal from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, find_output, ) class TxnMallTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 4 self.supports_cli = False def skip_test_if_missing_module(self): self.skip_if_no_wallet() def add_options(self, parser): parser.add_argument("--mineblock", dest="mine_block", default=False, action="store_true", help="Test double-spend of 1-confirmed transaction") def setup_network(self): # Start with split network: super().setup_network() self.disconnect_nodes(1, 2) def run_test(self): # All nodes should start with 1,250 BTC: starting_balance = 1250 # All nodes should be out of IBD. # If the nodes are not all out of IBD, that can interfere with # blockchain sync later in the test when nodes are connected, due to # timing issues. for n in self.nodes: assert n.getblockchaininfo()["initialblockdownload"] == False for i in range(4): assert_equal(self.nodes[i].getbalance(), starting_balance) self.nodes[i].getnewaddress("") # bug workaround, coins generated assigned to first getnewaddress! # Assign coins to foo and bar addresses: node0_address_foo = self.nodes[0].getnewaddress() fund_foo_txid = self.nodes[0].sendtoaddress(node0_address_foo, 1219) fund_foo_tx = self.nodes[0].gettransaction(fund_foo_txid) node0_address_bar = self.nodes[0].getnewaddress() fund_bar_txid = self.nodes[0].sendtoaddress(node0_address_bar, 29) fund_bar_tx = self.nodes[0].gettransaction(fund_bar_txid) assert_equal(self.nodes[0].getbalance(), starting_balance + fund_foo_tx["fee"] + fund_bar_tx["fee"]) # Coins are sent to node1_address node1_address = self.nodes[1].getnewaddress() # First: use raw transaction API to send 1240 BTC to node1_address, # but don't broadcast: doublespend_fee = Decimal('-.02') rawtx_input_0 = {} rawtx_input_0["txid"] = fund_foo_txid rawtx_input_0["vout"] = find_output(self.nodes[0], fund_foo_txid, 1219) rawtx_input_1 = {} rawtx_input_1["txid"] = fund_bar_txid rawtx_input_1["vout"] = find_output(self.nodes[0], fund_bar_txid, 29) inputs = [rawtx_input_0, rawtx_input_1] change_address = self.nodes[0].getnewaddress() outputs = {} outputs[node1_address] = 1240 outputs[change_address] = 1248 - 1240 + doublespend_fee rawtx = self.nodes[0].createrawtransaction(inputs, outputs) doublespend = self.nodes[0].signrawtransactionwithwallet(rawtx) assert_equal(doublespend["complete"], True) # Create two spends using 1 50 BTC coin each txid1 = self.nodes[0].sendtoaddress(node1_address, 40) txid2 = self.nodes[0].sendtoaddress(node1_address, 20) # Have node0 mine a block: if (self.options.mine_block): self.nodes[0].generate(1) self.sync_blocks(self.nodes[0:2]) tx1 = self.nodes[0].gettransaction(txid1) tx2 = self.nodes[0].gettransaction(txid2) # Node0's balance should be starting balance, plus 50BTC for another # matured block, minus 40, minus 20, and minus transaction fees: expected = starting_balance + fund_foo_tx["fee"] + fund_bar_tx["fee"] if self.options.mine_block: expected += 50 expected += tx1["amount"] + tx1["fee"] expected += tx2["amount"] + tx2["fee"] assert_equal(self.nodes[0].getbalance(), expected) if self.options.mine_block: assert_equal(tx1["confirmations"], 1) assert_equal(tx2["confirmations"], 1) # Node1's balance should be both transaction amounts: assert_equal(self.nodes[1].getbalance(), starting_balance - tx1["amount"] - tx2["amount"]) else: assert_equal(tx1["confirmations"], 0) assert_equal(tx2["confirmations"], 0) # Now give doublespend and its parents to miner: self.nodes[2].sendrawtransaction(fund_foo_tx["hex"]) self.nodes[2].sendrawtransaction(fund_bar_tx["hex"]) doublespend_txid = self.nodes[2].sendrawtransaction(doublespend["hex"]) # ... mine a block... self.nodes[2].generate(1) # Reconnect the split network, and sync chain: self.connect_nodes(1, 2) self.nodes[2].generate(1) # Mine another block to make sure we sync self.sync_blocks() assert_equal(self.nodes[0].gettransaction(doublespend_txid)["confirmations"], 2) # Re-fetch transaction info: tx1 = self.nodes[0].gettransaction(txid1) tx2 = self.nodes[0].gettransaction(txid2) # Both transactions should be conflicted assert_equal(tx1["confirmations"], -2) assert_equal(tx2["confirmations"], -2) # Node0's total balance should be starting balance, plus 100BTC for # two more matured blocks, minus 1240 for the double-spend, plus fees (which are # negative): expected = starting_balance + 100 - 1240 + fund_foo_tx["fee"] + fund_bar_tx["fee"] + doublespend_fee assert_equal(self.nodes[0].getbalance(), expected) # Node1's balance should be its initial balance (1250 for 25 block rewards) plus the doublespend: assert_equal(self.nodes[1].getbalance(), 1250 + 1240) if __name__ == '__main__': TxnMallTest().main()
EthanHeilman/bitcoin
test/functional/wallet_txn_doublespend.py
Python
mit
5,972
// // UIColor+Random.h // RZTransitions // // Created by Stephen Barnes on 12/16/13. // Copyright 2014 Raizlabs and other contributors // http://raizlabs.com/ // // 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. // #import <UIKit/UIKit.h> @interface UIColor (Random) + (UIColor *)randomColor; @end
lijie121210/RZTransitions
RZTransitions-Demo/RZTransitions-Demo/Utilities/UIColor+Random.h
C
mit
1,348
/** This controller supports all actions related to a topic @class TopicController @extends Discourse.ObjectController @namespace Discourse @module Discourse **/ Discourse.TopicController = Discourse.ObjectController.extend(Discourse.SelectedPostsCount, { multiSelect: false, needs: ['header', 'modal', 'composer', 'quoteButton'], allPostsSelected: false, editingTopic: false, selectedPosts: null, selectedReplies: null, init: function() { this._super(); this.set('selectedPosts', new Em.Set()); this.set('selectedReplies', new Em.Set()); }, actions: { jumpTop: function() { Discourse.URL.routeTo(this.get('url')); }, jumpBottom: function() { Discourse.URL.routeTo(this.get('lastPostUrl')); }, selectAll: function() { var posts = this.get('postStream.posts'), selectedPosts = this.get('selectedPosts'); if (posts) { selectedPosts.addObjects(posts); } this.set('allPostsSelected', true); }, deselectAll: function() { this.get('selectedPosts').clear(); this.get('selectedReplies').clear(); this.set('allPostsSelected', false); }, /** Toggle a participant for filtering @method toggleParticipant **/ toggleParticipant: function(user) { this.get('postStream').toggleParticipant(Em.get(user, 'username')); }, editTopic: function() { if (!this.get('details.can_edit')) return false; this.setProperties({ editingTopic: true, newTitle: this.get('title'), newCategoryId: this.get('category_id') }); return false; }, // close editing mode cancelEditingTopic: function() { this.set('editingTopic', false); }, toggleMultiSelect: function() { this.toggleProperty('multiSelect'); }, finishedEditingTopic: function() { var topicController = this; if (this.get('editingTopic')) { var topic = this.get('model'); // Topic title hasn't been sanitized yet, so the template shouldn't trust it. this.set('topicSaving', true); // manually update the titles & category topic.setProperties({ title: this.get('newTitle'), category_id: parseInt(this.get('newCategoryId'), 10), fancy_title: this.get('newTitle') }); // save the modifications topic.save().then(function(result){ // update the title if it has been changed (cleaned up) server-side var title = result.basic_topic.title; var fancy_title = result.basic_topic.fancy_title; topic.setProperties({ title: title, fancy_title: fancy_title }); topicController.set('topicSaving', false); }, function(error) { topicController.set('editingTopic', true); topicController.set('topicSaving', false); if (error && error.responseText) { bootbox.alert($.parseJSON(error.responseText).errors[0]); } else { bootbox.alert(I18n.t('generic_error')); } }); // close editing mode topicController.set('editingTopic', false); } }, toggledSelectedPost: function(post) { this.performTogglePost(post); }, toggledSelectedPostReplies: function(post) { var selectedReplies = this.get('selectedReplies'); if (this.performTogglePost(post)) { selectedReplies.addObject(post); } else { selectedReplies.removeObject(post); } }, deleteSelected: function() { var self = this; bootbox.confirm(I18n.t("post.delete.confirm", { count: this.get('selectedPostsCount')}), function(result) { if (result) { // If all posts are selected, it's the same thing as deleting the topic if (self.get('allPostsSelected')) { return self.deleteTopic(); } var selectedPosts = self.get('selectedPosts'), selectedReplies = self.get('selectedReplies'), postStream = self.get('postStream'), toRemove = new Ember.Set(); Discourse.Post.deleteMany(selectedPosts, selectedReplies); postStream.get('posts').forEach(function (p) { if (self.postSelected(p)) { toRemove.addObject(p); } }); postStream.removePosts(toRemove); self.send('toggleMultiSelect'); } }); }, toggleVisibility: function() { this.get('content').toggleStatus('visible'); }, toggleClosed: function() { this.get('content').toggleStatus('closed'); }, togglePinned: function() { this.get('content').toggleStatus('pinned'); }, toggleArchived: function() { this.get('content').toggleStatus('archived'); }, convertToRegular: function() { this.get('content').convertArchetype('regular'); }, // Toggle the star on the topic toggleStar: function() { this.get('content').toggleStar(); }, /** Clears the pin from a topic for the currently logged in user @method clearPin **/ clearPin: function() { this.get('content').clearPin(); }, resetRead: function() { Discourse.ScreenTrack.current().reset(); this.unsubscribe(); var topicController = this; this.get('model').resetRead().then(function() { topicController.set('message', I18n.t("topic.read_position_reset")); topicController.set('postStream.loaded', false); }); }, replyAsNewTopic: function(post) { var composerController = this.get('controllers.composer'), promise = composerController.open({ action: Discourse.Composer.CREATE_TOPIC, draftKey: Discourse.Composer.REPLY_AS_NEW_TOPIC_KEY }), postUrl = "" + location.protocol + "//" + location.host + (post.get('url')), postLink = "[" + (this.get('title')) + "](" + postUrl + ")"; promise.then(function() { Discourse.Post.loadQuote(post.get('id')).then(function(q) { composerController.appendText(I18n.t("post.continue_discussion", { postLink: postLink }) + "\n\n" + q); }); }); } }, slackRatio: function() { return Discourse.Capabilities.currentProp('slackRatio'); }.property(), jumpTopDisabled: function() { return (this.get('progressPosition') <= 3); }.property('progressPosition'), jumpBottomDisabled: function() { return this.get('progressPosition') >= this.get('postStream.filteredPostsCount') || this.get('progressPosition') >= this.get('highest_post_number'); }.property('postStream.filteredPostsCount', 'highest_post_number', 'progressPosition'), canMergeTopic: function() { if (!this.get('details.can_move_posts')) return false; return (this.get('selectedPostsCount') > 0); }.property('selectedPostsCount'), canSplitTopic: function() { if (!this.get('details.can_move_posts')) return false; if (this.get('allPostsSelected')) return false; return (this.get('selectedPostsCount') > 0); }.property('selectedPostsCount'), categories: function() { return Discourse.Category.list(); }.property(), canSelectAll: Em.computed.not('allPostsSelected'), canDeselectAll: function () { if (this.get('selectedPostsCount') > 0) return true; if (this.get('allPostsSelected')) return true; }.property('selectedPostsCount', 'allPostsSelected'), canDeleteSelected: function() { var selectedPosts = this.get('selectedPosts'); if (this.get('allPostsSelected')) return true; if (this.get('selectedPostsCount') === 0) return false; var canDelete = true; selectedPosts.forEach(function(p) { if (!p.get('can_delete')) { canDelete = false; return false; } }); return canDelete; }.property('selectedPostsCount'), hasError: Ember.computed.or('errorBodyHtml', 'message'), streamPercentage: function() { if (!this.get('postStream.loaded')) { return 0; } if (this.get('postStream.highest_post_number') === 0) { return 0; } var perc = this.get('progressPosition') / this.get('postStream.filteredPostsCount'); return (perc > 1.0) ? 1.0 : perc; }.property('postStream.loaded', 'progressPosition', 'postStream.filteredPostsCount'), multiSelectChanged: function() { // Deselect all posts when multi select is turned off if (!this.get('multiSelect')) { this.send('deselectAll'); } }.observes('multiSelect'), hideProgress: function() { if (!this.get('postStream.loaded')) return true; if (!this.get('currentPost')) return true; if (this.get('postStream.filteredPostsCount') < 2) return true; return false; }.property('postStream.loaded', 'currentPost', 'postStream.filteredPostsCount'), hugeNumberOfPosts: function() { return (this.get('postStream.filteredPostsCount') >= Discourse.SiteSettings.short_progress_text_threshold); }.property('highest_post_number'), jumpToBottomTitle: function() { if (this.get('hugeNumberOfPosts')) { return I18n.t('topic.progress.jump_bottom_with_number', {post_number: this.get('highest_post_number')}); } else { return I18n.t('topic.progress.jump_bottom'); } }.property('hugeNumberOfPosts', 'highest_post_number'), deselectPost: function(post) { this.get('selectedPosts').removeObject(post); var selectedReplies = this.get('selectedReplies'); selectedReplies.removeObject(post); var selectedReply = selectedReplies.findProperty('post_number', post.get('reply_to_post_number')); if (selectedReply) { selectedReplies.removeObject(selectedReply); } this.set('allPostsSelected', false); }, postSelected: function(post) { if (this.get('allPostsSelected')) { return true; } if (this.get('selectedPosts').contains(post)) { return true; } if (this.get('selectedReplies').findProperty('post_number', post.get('reply_to_post_number'))) { return true; } return false; }, showFavoriteButton: function() { return Discourse.User.current() && !this.get('isPrivateMessage'); }.property('isPrivateMessage'), recoverTopic: function() { this.get('content').recover(); }, deleteTopic: function() { this.unsubscribe(); this.get('content').destroy(Discourse.User.current()); }, // Receive notifications for this topic subscribe: function() { // Unsubscribe before subscribing again this.unsubscribe(); var bus = Discourse.MessageBus; var topicController = this; bus.subscribe("/topic/" + (this.get('id')), function(data) { var topic = topicController.get('model'); if (data.notification_level_change) { topic.set('details.notification_level', data.notification_level_change); topic.set('details.notifications_reason_id', data.notifications_reason_id); return; } // Add the new post into the stream topicController.get('postStream').triggerNewPostInStream(data.id); }); }, unsubscribe: function() { var topicId = this.get('content.id'); if (!topicId) return; // there is a condition where the view never calls unsubscribe, navigate to a topic from a topic Discourse.MessageBus.unsubscribe('/topic/*'); }, // Post related methods replyToPost: function(post) { var composerController = this.get('controllers.composer'); var quoteController = this.get('controllers.quoteButton'); var quotedText = Discourse.Quote.build(quoteController.get('post'), quoteController.get('buffer')); var topic = post ? post.get('topic') : this.get('model'); quoteController.set('buffer', ''); if (composerController.get('content.topic.id') === topic.get('id') && composerController.get('content.action') === Discourse.Composer.REPLY) { composerController.set('content.post', post); composerController.set('content.composeState', Discourse.Composer.OPEN); composerController.appendText(quotedText); } else { var opts = { action: Discourse.Composer.REPLY, draftKey: topic.get('draft_key'), draftSequence: topic.get('draft_sequence') }; if(post && post.get("post_number") !== 1){ opts.post = post; } else { opts.topic = topic; } var promise = composerController.open(opts); promise.then(function() { composerController.appendText(quotedText); }); } return false; }, // Topic related reply: function() { this.replyToPost(); }, // Edits a post editPost: function(post) { this.get('controllers.composer').open({ post: post, action: Discourse.Composer.EDIT, draftKey: post.get('topic.draft_key'), draftSequence: post.get('topic.draft_sequence') }); }, toggleBookmark: function(post) { if (!Discourse.User.current()) { alert(I18n.t("bookmarks.not_bookmarked")); return; } post.toggleProperty('bookmarked'); return false; }, recoverPost: function(post) { post.recover(); }, deletePost: function(post) { var user = Discourse.User.current(), replyCount = post.get('reply_count'), self = this; // If the user is staff and the post has replies, ask if they want to delete replies too. if (user.get('staff') && replyCount > 0) { bootbox.dialog(I18n.t("post.controls.delete_replies.confirm", {count: replyCount}), [ {label: I18n.t("cancel"), 'class': 'btn-danger rightg'}, {label: I18n.t("post.controls.delete_replies.no_value"), callback: function() { post.destroy(user); } }, {label: I18n.t("post.controls.delete_replies.yes_value"), 'class': 'btn-primary', callback: function() { Discourse.Post.deleteMany([post], [post]); self.get('postStream.posts').forEach(function (p) { if (p === post || p.get('reply_to_post_number') === post.get('post_number')) { p.setDeletedState(user); } }); } } ]); } else { post.destroy(user); } }, performTogglePost: function(post) { var selectedPosts = this.get('selectedPosts'); if (this.postSelected(post)) { this.deselectPost(post); return false; } else { selectedPosts.addObject(post); // If the user manually selects all posts, all posts are selected if (selectedPosts.length === this.get('posts_count')) { this.set('allPostsSelected', true); } return true; } }, // If our current post is changed, notify the router _currentPostChanged: function() { var currentPost = this.get('currentPost'); if (currentPost) { this.send('postChangedRoute', currentPost); } }.observes('currentPost'), sawObjects: function(posts) { if (posts) { var self = this, lastReadPostNumber = this.get('last_read_post_number'); posts.forEach(function(post) { var postNumber = post.get('post_number'); if (postNumber > lastReadPostNumber) { lastReadPostNumber = postNumber; } post.set('read', true); }); self.set('last_read_post_number', lastReadPostNumber); } }, /** Called the the topmost visible post on the page changes. @method topVisibleChanged @params {Discourse.Post} post that is at the top **/ topVisibleChanged: function(post) { var postStream = this.get('postStream'), firstLoadedPost = postStream.get('firstLoadedPost'); this.set('currentPost', post.get('post_number')); if (firstLoadedPost && firstLoadedPost === post) { // Note: jQuery shouldn't be done in a controller, but how else can we // trigger a scroll after a promise resolves in a controller? We need // to do this to preserve upwards infinte scrolling. var $body = $('body'), $elem = $('#post-cloak-' + post.get('post_number')), distToElement = $body.scrollTop() - $elem.position().top; postStream.prependMore().then(function() { Em.run.next(function () { $elem = $('#post-cloak-' + post.get('post_number')); $('html, body').scrollTop($elem.position().top + distToElement); }); }); } }, /** Called the the bottommost visible post on the page changes. @method bottomVisibleChanged @params {Discourse.Post} post that is at the bottom **/ bottomVisibleChanged: function(post) { var postStream = this.get('postStream'), lastLoadedPost = postStream.get('lastLoadedPost'), index = postStream.get('stream').indexOf(post.get('id'))+1; this.set('progressPosition', index); if (lastLoadedPost && lastLoadedPost === post) { postStream.appendMore(); } } });
tadp/learnswift
app/assets/javascripts/discourse/controllers/topic_controller.js
JavaScript
mit
16,947
package multiconfig import ( "fmt" "reflect" "github.com/fatih/structs" ) // Validator validates the config against any predefined rules, those predefined // rules should be given to this package. The implementer will be responsible // for the logic. type Validator interface { // Validate validates the config struct Validate(s interface{}) error } // RequiredValidator validates the struct against zero values. type RequiredValidator struct { // TagName holds the validator tag name. The default is "required" TagName string // TagValue holds the expected value of the validator. The default is "true" TagValue string } // Validate validates the given struct agaist field's zero values. If // intentionaly, the value of a field is `zero-valued`(e.g false, 0, "") // required tag should not be set for that field. func (e *RequiredValidator) Validate(s interface{}) error { if e.TagName == "" { e.TagName = "required" } if e.TagValue == "" { e.TagValue = "true" } for _, field := range structs.Fields(s) { if err := e.processField("", field); err != nil { return err } } return nil } func (e *RequiredValidator) processField(fieldName string, field *structs.Field) error { fieldName += field.Name() switch field.Kind() { case reflect.Struct: // this is used for error messages below, when we have an error at the // child properties add parent properties into the error message as well fieldName += "." for _, f := range field.Fields() { if err := e.processField(fieldName, f); err != nil { return err } } default: val := field.Tag(e.TagName) if val != e.TagValue { return nil } if field.IsZero() { return fmt.Errorf("multiconfig: field '%s' is required", fieldName) } } return nil }
zedio/zedlist
vendor/github.com/koding/multiconfig/validator.go
GO
mit
1,768
import styleSheet, { GRAY_DARK, GRAY_LIGHTER, BLUE_DARK, BLUE_LIGHT, GREEN_DARK, GREEN_LIGHT, RED_DARK, RED_LIGHT, YELLOW_DARK, YELLOW_LIGHT, FONT_FAMILY, FONT_SIZE_NORMAL, } from '../styles'; const ZAP_COOL_OFF_DURATION = '0.4s'; const EVENT_COOL_OFF_DURATION = '3s'; const ZCOD = ZAP_COOL_OFF_DURATION; const ECOD = EVENT_COOL_OFF_DURATION; const INACTIVE_OPACITY = '0.4'; const NODE_STROKE_WIDTH = '1px'; const NODE_ZAP_STROKE_WIDTH = '3px'; const EDGE_STROKE_WIDTH = '1px'; export default { sourceOrSinkNodeStyle: styleSheet.registerStyle({ 'fill': GRAY_LIGHTER, 'stroke': GRAY_DARK, 'stroke-width': NODE_STROKE_WIDTH, 'transition': `fill ${ZCOD}, stroke ${ZCOD}, stroke-width ${ZCOD}`, }), sourceOrSinkNodeNameStyle: styleSheet.registerStyle({ 'width': 120, 'font-family': FONT_FAMILY, 'font-size': FONT_SIZE_NORMAL, 'fill': GRAY_DARK, }), sourceOrSinkNodeLabelStyle: styleSheet.registerStyle({ 'font-family': FONT_FAMILY, 'font-size': FONT_SIZE_NORMAL, 'fill': GRAY_DARK, 'opacity': '0', 'transition': `opacity ${ECOD}, fill ${ZCOD}`, }), activeNodeStyle: styleSheet.registerStyle({ 'fill': BLUE_LIGHT, 'stroke': BLUE_DARK, 'stroke-width': NODE_STROKE_WIDTH, 'transition': `fill ${ZCOD}, stroke ${ZCOD}, stroke-width ${ZCOD}`, }), nodeZapNextStyle: styleSheet.registerStyle({ 'fill': GREEN_LIGHT, 'stroke': GREEN_DARK, 'stroke-width': NODE_ZAP_STROKE_WIDTH, }), nodeZapErrorStyle: styleSheet.registerStyle({ 'fill': RED_LIGHT, 'stroke': RED_DARK, 'stroke-width': NODE_ZAP_STROKE_WIDTH, }), nodeZapCompleteStyle: styleSheet.registerStyle({ 'fill': YELLOW_LIGHT, 'stroke': YELLOW_DARK, 'stroke-width': NODE_ZAP_STROKE_WIDTH, }), nodeInactiveErrorStyle: styleSheet.registerStyle({ 'fill': RED_LIGHT, 'stroke': RED_DARK, 'stroke-width': NODE_STROKE_WIDTH, 'opacity': INACTIVE_OPACITY, 'transition': `stroke-width ${ZCOD}, opacity ${ZCOD}`, }), edgeArrowHeadStyle: styleSheet.registerStyle({ 'stroke': BLUE_DARK, 'fill': BLUE_DARK, 'stroke-width': EDGE_STROKE_WIDTH, 'stroke-dasharray': '1,0', }), edgeType1Style: styleSheet.registerStyle({ 'fill': 'none', 'stroke': BLUE_DARK, 'stroke-width': EDGE_STROKE_WIDTH, 'stroke-dasharray': '1,0', }), edgeType2Style: styleSheet.registerStyle({ 'fill': 'none', 'stroke': BLUE_DARK, 'stroke-width': EDGE_STROKE_WIDTH, 'stroke-dasharray': '1,0', }), nodeInactiveCompleteStyle: styleSheet.registerStyle({ 'fill': YELLOW_LIGHT, 'stroke': YELLOW_DARK, 'stroke-width': NODE_STROKE_WIDTH, 'opacity': INACTIVE_OPACITY, 'transition': `stroke-width ${ZCOD}, opacity ${ZCOD}`, }), commonNodeLabelStyle: styleSheet.registerStyle({ 'font-family': FONT_FAMILY, 'font-size': FONT_SIZE_NORMAL, 'fill': BLUE_DARK, 'opacity': '0', 'transition': `opacity ${ECOD}, fill ${ZCOD}`, }), nodeLabelZapNextStyle: styleSheet.registerStyle({ 'font-family': FONT_FAMILY, 'font-size': FONT_SIZE_NORMAL, 'fill': GREEN_DARK, 'opacity': '1', }), nodeLabelZapErrorStyle: styleSheet.registerStyle({ 'font-family': FONT_FAMILY, 'font-size': FONT_SIZE_NORMAL, 'fill': RED_DARK, 'opacity': '1', }), operatorNodeStyle: styleSheet.registerStyle({ 'font-family': FONT_FAMILY, 'font-size': FONT_SIZE_NORMAL, 'fill': BLUE_DARK, 'tspan': { 'text-shadow': 'white 2px 2px 0, white -2px 2px 0, white -2px -2px 0, white 2px -2px 0', }, }), };
cyclejs/cycle-core
devtool/src/panel/graph/styles.ts
TypeScript
mit
3,613
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <base href="../../" /> <script src="list.js"></script> <script src="page.js"></script> <link type="text/css" rel="stylesheet" href="page.css" /> </head> <body> [page:Geometry] &rarr; <h1>[name]</h1> <div class="desc">[name] can be used to generate a convex hull for a given array of 3D points. The average time complexity for this task is considered to be O(nlog(n)).</div> <script> // iOS iframe auto-resize workaround if ( /(iPad|iPhone|iPod)/g.test( navigator.userAgent ) ) { var scene = document.getElementById( 'scene' ); scene.style.width = getComputedStyle( scene ).width; scene.style.height = getComputedStyle( scene ).height; scene.setAttribute( 'scrolling', 'no' ); } </script> <h2>Example</h2> <div>[example:webgl_geometry_convex geometry / convex ]</div> <code>var geometry = new THREE.ConvexGeometry( points ); var material = new THREE.MeshBasicMaterial( {color: 0x00ff00} ); var mesh = new THREE.Mesh( geometry, material ); scene.add( mesh ); </code> <h2>Constructor</h2> <h3>[name]( [page:Array points] )</h3> <div> points — Array of [page:Vector3 Vector3s] that the resulting convex hull will contain. </div> <h2>Source</h2> [link:https://github.com/mrdoob/three.js/blob/master/examples/js/geometries/ConvexGeometry.js examples/js/geometries/ConvexGeometry.js] </body> </html>
googlecreativelab/three.js
docs/examples/geometries/ConvexGeometry.html
HTML
mit
1,451
require_relative '../../spec_helper' describe "FalseClass#^" do it "returns false if other is nil or false, otherwise true" do (false ^ false).should == false (false ^ true).should == true (false ^ nil).should == false (false ^ "").should == true (false ^ mock('x')).should == true end end
pmq20/ruby-compiler
ruby/spec/ruby/core/false/xor_spec.rb
Ruby
mit
315
<?php /** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ /** * Tests, that perform search of words, that signal of obsolete code */ namespace Magento\Test\Legacy; use Magento\Framework\Component\ComponentRegistrar; class WordsTest extends \PHPUnit_Framework_TestCase { /** * @var \Magento\TestFramework\Inspection\WordsFinder */ protected static $_wordsFinder; public static function setUpBeforeClass() { self::$_wordsFinder = new \Magento\TestFramework\Inspection\WordsFinder( glob(__DIR__ . '/_files/words_*.xml'), BP, new ComponentRegistrar() ); } public function testWords() { $invoker = new \Magento\Framework\App\Utility\AggregateInvoker($this); $invoker( /** * @param string $file */ function ($file) { $words = self::$_wordsFinder->findWords(realpath($file)); if ($words) { $this->fail("Found words: '" . implode("', '", $words) . "' in '{$file}' file"); } }, \Magento\Framework\App\Utility\Files::init()->getAllFiles() ); } }
j-froehlich/magento2_wk
vendor/magento/magento2-base/dev/tests/static/testsuite/Magento/Test/Legacy/WordsTest.php
PHP
mit
1,260
function testConstructor() { type MyModel = { numericProperty: number }; let model: PouchDB.Core.Document<MyModel>; let db = new PouchDB<MyModel>(null, { adapter: 'fruitdown', }); db.get('model').then((result) => model); db = new PouchDB<MyModel>('myDb', { adapter: 'fruitdown', }); db.get('model').then((result) => model); }
mcrawshaw/DefinitelyTyped
types/pouchdb-adapter-fruitdown/pouchdb-adapter-fruitdown-tests.ts
TypeScript
mit
375
// // App.xaml.cpp // Implementation of the App class. // // clang-format off #include "pch.h" using namespace GLKitComplex; using namespace Platform; using namespace Windows::ApplicationModel; using namespace Windows::ApplicationModel::Activation; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Interop; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> App::App() { InitializeComponent(); Suspending += ref new SuspendingEventHandler(this, &App::OnSuspending); } extern "C" int main(int argc, char* argv[]); extern "C" void UIApplicationActivated(Windows::ApplicationModel::Activation::IActivatedEventArgs^ e); extern "C" void UIApplicationLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e); #ifdef ENABLE_BACKGROUND_TASK extern "C" void UIApplicationBackgroundActivated(Windows::ApplicationModel::Activation::BackgroundActivatedEventArgs^ e); #endif /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> void App::OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e) { main(0, NULL); UIApplicationLaunched(e); } void App::OnActivated(Windows::ApplicationModel::Activation::IActivatedEventArgs^ e) { main(0, NULL); UIApplicationActivated(e); } void App::OnFileActivated(FileActivatedEventArgs^ args) { main(0, NULL); UIApplicationActivated(args); } #ifdef ENABLE_BACKGROUND_TASK void App::OnBackgroundActivated(Windows::ApplicationModel::Activation::BackgroundActivatedEventArgs^ e) { __super ::OnBackgroundActivated(e); UIApplicationBackgroundActivated(e); } #endif /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> void App::OnSuspending(Object^ /*sender*/, SuspendingEventArgs^ /*e*/) { // TODO: Save application state and stop any background activity } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void App::OnNavigationFailed(Platform::Object^ sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs^ e) { throw ref new FailureException("Failed to load Page " + e->SourcePageType.Name); } // clang-format on
nathpete-msft/WinObjC
samples/GLKitComplex/GLKitComplex.vsimporter/GLKitComplex-WinStore10/App.xaml.cpp
C++
mit
3,278
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations.ModifierKeywordRecommenderTests Public Class InsideNamespaceDeclaration Inherits RecommenderTests ''' <summary> ''' Declarations outside of any namespace in the file are considered to be in the project's root namespace ''' </summary> Private Shared Sub VerifyContains(ParamArray recommendations As String()) VerifyRecommendationsContain(<NamespaceDeclaration>|</NamespaceDeclaration>, recommendations) VerifyRecommendationsContain(<File>|</File>, recommendations) VerifyRecommendationsContain( <File>Imports System |</File>, recommendations) End Sub ''' <summary> ''' Declarations outside of any namespace in the file are considered to be in the project's root namespace ''' </summary> Private Shared Sub VerifyMissing(ParamArray recommendations As String()) VerifyRecommendationsMissing(<NamespaceDeclaration>|</NamespaceDeclaration>, recommendations) VerifyRecommendationsMissing(<File>|</File>, recommendations) VerifyRecommendationsMissing( <File>Imports System |</File>, recommendations) End Sub <WorkItem(530100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530100")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AccessibilityModifiersTest() VerifyContains("Public", "Friend") VerifyMissing("Protected", "Private", "Protected Friend") End Sub <WorkItem(530100, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530100")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassModifiersTest() VerifyContains("MustInherit", "NotInheritable", "Partial") End Sub End Class End Namespace
CyrusNajmabadi/roslyn
src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/ModifierKeywordRecommenderTests.InsideNamespaceDeclaration.vb
Visual Basic
mit
2,132
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.tools.workbench.test.utility.string; import java.util.regex.Pattern; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.eclipse.persistence.tools.workbench.utility.string.RegExStringMatcherAdapter; import org.eclipse.persistence.tools.workbench.utility.string.StringMatcher; public class RegularExpressionStringMatcherAdapterTests extends TestCase { public static Test suite() { return new TestSuite(RegularExpressionStringMatcherAdapterTests.class); } public RegularExpressionStringMatcherAdapterTests(String name) { super(name); } public void testRegEx() { StringMatcher matcher = new RegExStringMatcherAdapter("a*b"); assertTrue(matcher.matches("ab")); assertTrue(matcher.matches("aaaaab")); assertFalse(matcher.matches("abc")); assertFalse(matcher.matches("AB")); assertFalse(matcher.matches("AAAAAB")); } public void testRegExCaseInsensitive() { StringMatcher matcher = new RegExStringMatcherAdapter("a*b", Pattern.CASE_INSENSITIVE); assertTrue(matcher.matches("ab")); assertTrue(matcher.matches("AB")); assertTrue(matcher.matches("aaaaab")); assertTrue(matcher.matches("AAAAAB")); assertFalse(matcher.matches("abc")); } }
RallySoftware/eclipselink.runtime
utils/eclipselink.utils.workbench.test/utility/source/org/eclipse/persistence/tools/workbench/test/utility/string/RegularExpressionStringMatcherAdapterTests.java
Java
epl-1.0
2,095
package p; import java.io.IOException; import java.util.List; import java.util.Set; /** typecomment template*/ interface I { List m(Set set) throws IOException; }
maxeler/eclipse
eclipse.jdt.ui/org.eclipse.jdt.ui.tests.refactoring/resources/UseSupertypeWherePossible/test6_/out/I.java
Java
epl-1.0
163
from cherrypy.test import test test.prefer_parent_path() import os curdir = os.path.join(os.getcwd(), os.path.dirname(__file__)) import cherrypy def setup_server(): class Dummy: def index(self): return "I said good day!" class City: def __init__(self, name): self.name = name self.population = 10000 def index(self, **kwargs): return "Welcome to %s, pop. %s" % (self.name, self.population) index._cp_config = {'tools.response_headers.on': True, 'tools.response_headers.headers': [('Content-Language', 'en-GB')]} def update(self, **kwargs): self.population = kwargs['pop'] return "OK" d = cherrypy.dispatch.RoutesDispatcher() d.connect(name='hounslow', route='hounslow', controller=City('Hounslow')) d.connect(name='surbiton', route='surbiton', controller=City('Surbiton'), action='index', conditions=dict(method=['GET'])) d.mapper.connect('surbiton', controller='surbiton', action='update', conditions=dict(method=['POST'])) d.connect('main', ':action', controller=Dummy()) conf = {'/': {'request.dispatch': d}} cherrypy.tree.mount(root=None, config=conf) from cherrypy.test import helper class RoutesDispatchTest(helper.CPWebCase): def test_Routes_Dispatch(self): self.getPage("/hounslow") self.assertStatus("200 OK") self.assertBody("Welcome to Hounslow, pop. 10000") self.getPage("/foo") self.assertStatus("404 Not Found") self.getPage("/surbiton") self.assertStatus("200 OK") self.assertBody("Welcome to Surbiton, pop. 10000") self.getPage("/surbiton", method="POST", body="pop=1327") self.assertStatus("200 OK") self.assertBody("OK") self.getPage("/surbiton") self.assertStatus("200 OK") self.assertHeader("Content-Language", "en-GB") self.assertBody("Welcome to Surbiton, pop. 1327") if __name__ == '__main__': helper.testmain()
CeltonMcGrath/TACTIC
3rd_party/CherryPy/cherrypy/test/test_routes.py
Python
epl-1.0
2,158
/** * **************************************************************************** * Copyright (c) 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * <p/> * Contributors: * Marcel Valovy - initial API and implementation * **************************************************************************** */ package org.eclipse.persistence.internal.cache; /** * Processor for computable tasks. * * Concurrent. * * @author Marcel Valovy - [email protected] * @since 2.6 */ public class AdvancedProcessor implements Processor, Clearable { private Memoizer<Object, Object> memoizer = new Memoizer<>(); @Override public <A, V> V compute(ComputableTask<A, V> task, A taskArgument) { while (true) { try { //noinspection unchecked return (V) memoizer.compute((ComputableTask<Object, Object>) task, taskArgument); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } @Override public void clear() { memoizer.forgetAll(); } }
RallySoftware/eclipselink.runtime
foundation/org.eclipse.persistence.core/src/org/eclipse/persistence/internal/cache/AdvancedProcessor.java
Java
epl-1.0
1,505
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.testing.oxm.descriptor.rootelement; public class MailingAddress { private String street; public MailingAddress() { super(); } public void setStreet(String street) { this.street = street; } public String getStreet() { return street; } public boolean equals(Object theObject) { if (theObject instanceof MailingAddress) { if (((street == null) && (((MailingAddress)theObject).getStreet() == null)) || (street.equals(((MailingAddress)theObject).getStreet()))) { return true; } } return false; } }
RallySoftware/eclipselink.runtime
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/oxm/descriptor/rootelement/MailingAddress.java
Java
epl-1.0
1,379
///////////////////////////////////////////////////////////////////////// // $Id: memory.cc,v 1.76 2009/03/13 18:48:08 sshwarts Exp $ ///////////////////////////////////////////////////////////////////////// // // Copyright (C) 2001 MandrakeSoft S.A. // // MandrakeSoft S.A. // 43, rue d'Aboukir // 75002 Paris - France // http://www.linux-mandrake.com/ // http://www.mandrakesoft.com/ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // ///////////////////////////////////////////////////////////////////////// #include "bochs.h" #include "cpu/cpu.h" #include "iodev/iodev.h" #define LOG_THIS BX_MEM_THIS #if BX_PROVIDE_CPU_MEMORY // // Memory map inside the 1st megabyte: // // 0x00000 - 0x7ffff DOS area (512K) // 0x80000 - 0x9ffff Optional fixed memory hole (128K) // 0xa0000 - 0xbffff Standard PCI/ISA Video Mem / SMMRAM (128K) // 0xc0000 - 0xdffff Expansion Card BIOS and Buffer Area (128K) // 0xe0000 - 0xeffff Lower BIOS Area (64K) // 0xf0000 - 0xfffff Upper BIOS Area (64K) // void BX_MEM_C::writePhysicalPage(BX_CPU_C *cpu, bx_phy_address addr, unsigned len, void *data) { Bit8u *data_ptr; bx_phy_address a20addr = A20ADDR(addr); struct memory_handler_struct *memory_handler = NULL; // Note: accesses should always be contained within a single page now if ((addr>>12) != ((addr+len-1)>>12)) { BX_PANIC(("writePhysicalPage: cross page access at address 0x" FMT_PHY_ADDRX ", len=%d", addr, len)); } #if BX_SUPPORT_MONITOR_MWAIT BX_MEM_THIS check_monitor(a20addr, len); #endif if (cpu != NULL) { #if BX_SUPPORT_IODEBUG bx_devices.pluginIODebug->mem_write(cpu, a20addr, len, data); #endif BX_INSTR_PHY_WRITE(cpu->which_cpu(), a20addr, len); if ((a20addr & 0xfffe0000) == 0x000a0000 && (BX_MEM_THIS smram_available)) { // SMRAM memory space if (BX_MEM_THIS smram_enable || (cpu->smm_mode() && !BX_MEM_THIS smram_restricted)) goto mem_write; } } memory_handler = BX_MEM_THIS memory_handlers[a20addr >> 20]; while (memory_handler) { if (memory_handler->begin <= a20addr && memory_handler->end >= a20addr && memory_handler->write_handler(a20addr, len, data, memory_handler->param)) { return; } memory_handler = memory_handler->next; } mem_write: // all memory access feets in single 4K page if (a20addr < BX_MEM_THIS len) { pageWriteStampTable.decWriteStamp(a20addr); // all of data is within limits of physical memory if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff)) { if (len == 8) { WriteHostQWordToLittleEndian(BX_MEM_THIS get_vector(a20addr), *(Bit64u*)data); return; } if (len == 4) { WriteHostDWordToLittleEndian(BX_MEM_THIS get_vector(a20addr), *(Bit32u*)data); return; } if (len == 2) { WriteHostWordToLittleEndian(BX_MEM_THIS get_vector(a20addr), *(Bit16u*)data); return; } if (len == 1) { * (BX_MEM_THIS get_vector(a20addr)) = * (Bit8u *) data; return; } // len == other, just fall thru to special cases handling } #ifdef BX_LITTLE_ENDIAN data_ptr = (Bit8u *) data; #else // BX_BIG_ENDIAN data_ptr = (Bit8u *) data + (len - 1); #endif if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff)) { while(1) { // addr *not* in range 000A0000 .. 000FFFFF *(BX_MEM_THIS get_vector(a20addr)) = *data_ptr; if (len == 1) return; len--; a20addr++; #ifdef BX_LITTLE_ENDIAN data_ptr++; #else // BX_BIG_ENDIAN data_ptr--; #endif } } // addr must be in range 000A0000 .. 000FFFFF for(unsigned i=0; i<len; i++) { // SMMRAM if (a20addr <= 0x000bffff) { // devices are not allowed to access SMMRAM under VGA memory if (cpu) { *(BX_MEM_THIS get_vector(a20addr)) = *data_ptr; } goto inc_one; } // adapter ROM C0000 .. DFFFF // ROM BIOS memory E0000 .. FFFFF #if BX_SUPPORT_PCI == 0 // ignore write to ROM #else // Write Based on 440fx Programming if (BX_MEM_THIS pci_enabled && ((a20addr & 0xfffc0000) == 0x000c0000)) { switch (DEV_pci_wr_memtype(a20addr)) { case 0x1: // Writes to ShadowRAM BX_DEBUG(("Writing to ShadowRAM: address 0x" FMT_PHY_ADDRX ", data %02x", a20addr, *data_ptr)); *(BX_MEM_THIS get_vector(a20addr)) = *data_ptr; break; case 0x0: // Writes to ROM, Inhibit BX_DEBUG(("Write to ROM ignored: address 0x" FMT_PHY_ADDRX ", data %02x", a20addr, *data_ptr)); break; default: BX_PANIC(("writePhysicalPage: default case")); } } #endif inc_one: a20addr++; #ifdef BX_LITTLE_ENDIAN data_ptr++; #else // BX_BIG_ENDIAN data_ptr--; #endif } } else { // access outside limits of physical memory, ignore BX_DEBUG(("Write outside the limits of physical memory (0x"FMT_PHY_ADDRX") (ignore)", a20addr)); } } void BX_MEM_C::readPhysicalPage(BX_CPU_C *cpu, bx_phy_address addr, unsigned len, void *data) { Bit8u *data_ptr; bx_phy_address a20addr = A20ADDR(addr); struct memory_handler_struct *memory_handler = NULL; // Note: accesses should always be contained within a single page now if ((addr>>12) != ((addr+len-1)>>12)) { BX_PANIC(("readPhysicalPage: cross page access at address 0x" FMT_PHY_ADDRX ", len=%d", addr, len)); } if (cpu != NULL) { #if BX_SUPPORT_IODEBUG bx_devices.pluginIODebug->mem_read(cpu, a20addr, len, data); #endif BX_INSTR_PHY_READ(cpu->which_cpu(), a20addr, len); if ((a20addr & 0xfffe0000) == 0x000a0000 && (BX_MEM_THIS smram_available)) { // SMRAM memory space if (BX_MEM_THIS smram_enable || (cpu->smm_mode() && !BX_MEM_THIS smram_restricted)) goto mem_read; } } memory_handler = BX_MEM_THIS memory_handlers[a20addr >> 20]; while (memory_handler) { if (memory_handler->begin <= a20addr && memory_handler->end >= a20addr && memory_handler->read_handler(a20addr, len, data, memory_handler->param)) { return; } memory_handler = memory_handler->next; } mem_read: if (a20addr <= BX_MEM_THIS len) { // all of data is within limits of physical memory if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff)) { if (len == 8) { ReadHostQWordFromLittleEndian(BX_MEM_THIS get_vector(a20addr), * (Bit64u*) data); return; } if (len == 4) { ReadHostDWordFromLittleEndian(BX_MEM_THIS get_vector(a20addr), * (Bit32u*) data); return; } if (len == 2) { ReadHostWordFromLittleEndian(BX_MEM_THIS get_vector(a20addr), * (Bit16u*) data); return; } if (len == 1) { * (Bit8u *) data = * (BX_MEM_THIS get_vector(a20addr)); return; } // len == other case can just fall thru to special cases handling } #ifdef BX_LITTLE_ENDIAN data_ptr = (Bit8u *) data; #else // BX_BIG_ENDIAN data_ptr = (Bit8u *) data + (len - 1); #endif if ((a20addr & 0xfff80000) != 0x00080000 || (a20addr <= 0x0009ffff)) { while(1) { // addr *not* in range 00080000 .. 000FFFFF *data_ptr = *(BX_MEM_THIS get_vector(a20addr)); if (len == 1) return; len--; a20addr++; #ifdef BX_LITTLE_ENDIAN data_ptr++; #else // BX_BIG_ENDIAN data_ptr--; #endif } } // addr must be in range 000A0000 .. 000FFFFF for (unsigned i=0; i<len; i++) { // SMMRAM if (a20addr <= 0x000bffff) { // devices are not allowed to access SMMRAM under VGA memory if (cpu) *data_ptr = *(BX_MEM_THIS get_vector(a20addr)); goto inc_one; } #if BX_SUPPORT_PCI if (BX_MEM_THIS pci_enabled && ((a20addr & 0xfffc0000) == 0x000c0000)) { switch (DEV_pci_rd_memtype(a20addr)) { case 0x0: // Read from ROM if ((a20addr & 0xfffe0000) == 0x000e0000) { *data_ptr = BX_MEM_THIS rom[a20addr & BIOS_MASK]; } else { *data_ptr = BX_MEM_THIS rom[(a20addr & EXROM_MASK) + BIOSROMSZ]; } break; case 0x1: // Read from ShadowRAM *data_ptr = *(BX_MEM_THIS get_vector(a20addr)); break; default: BX_PANIC(("readPhysicalPage: default case")); } } else #endif // #if BX_SUPPORT_PCI { if ((a20addr & 0xfffc0000) != 0x000c0000) { *data_ptr = *(BX_MEM_THIS get_vector(a20addr)); } else if ((a20addr & 0xfffe0000) == 0x000e0000) { *data_ptr = BX_MEM_THIS rom[a20addr & BIOS_MASK]; } else { *data_ptr = BX_MEM_THIS rom[(a20addr & EXROM_MASK) + BIOSROMSZ]; } } inc_one: a20addr++; #ifdef BX_LITTLE_ENDIAN data_ptr++; #else // BX_BIG_ENDIAN data_ptr--; #endif } } else { // access outside limits of physical memory #ifdef BX_LITTLE_ENDIAN data_ptr = (Bit8u *) data; #else // BX_BIG_ENDIAN data_ptr = (Bit8u *) data + (len - 1); #endif for (unsigned i = 0; i < len; i++) { #if BX_PHY_ADDRESS_LONG if (a20addr >= BX_CONST64(0xFFFFFFFF)) *data_ptr = 0xff; else #endif if (a20addr >= (bx_phy_address)~BIOS_MASK) *data_ptr = BX_MEM_THIS rom[a20addr & BIOS_MASK]; else *data_ptr = 0xff; addr++; a20addr = (addr); #ifdef BX_LITTLE_ENDIAN data_ptr++; #else // BX_BIG_ENDIAN data_ptr--; #endif } } } #endif // #if BX_PROVIDE_CPU_MEMORY
antmar/Skyeye-fixes
arch/x86/memory/memory.cc
C++
gpl-2.0
10,446
/******************** (C) COPYRIGHT 2007 STMicroelectronics ******************** * File Name : stm32f10x_usart.h * Author : MCD Application Team * Version : V1.0 * Date : 10/08/2007 * Description : This file contains all the functions prototypes for the * USART firmware library. ******************************************************************************** * THE PRESENT SOFTWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH SOFTWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F10x_USART_H #define __STM32F10x_USART_H /* Includes ------------------------------------------------------------------*/ #include "stm32f10x_map.h" /* Exported types ------------------------------------------------------------*/ /* UART Init Structure definition */ typedef struct { u32 USART_BaudRate; u16 USART_WordLength; u16 USART_StopBits; u16 USART_Parity; u16 USART_HardwareFlowControl; u16 USART_Mode; u16 USART_Clock; u16 USART_CPOL; u16 USART_CPHA; u16 USART_LastBit; } USART_InitTypeDef; /* Exported constants --------------------------------------------------------*/ /* USART Word Length ---------------------------------------------------------*/ #define USART_WordLength_8b ((u16)0x0000) #define USART_WordLength_9b ((u16)0x1000) #define IS_USART_WORD_LENGTH(LENGTH) ((LENGTH == USART_WordLength_8b) || \ (LENGTH == USART_WordLength_9b)) /* USART Stop Bits -----------------------------------------------------------*/ #define USART_StopBits_1 ((u16)0x0000) #define USART_StopBits_0_5 ((u16)0x1000) #define USART_StopBits_2 ((u16)0x2000) #define USART_StopBits_1_5 ((u16)0x3000) #define IS_USART_STOPBITS(STOPBITS) ((STOPBITS == USART_StopBits_1) || \ (STOPBITS == USART_StopBits_0_5) || \ (STOPBITS == USART_StopBits_2) || \ (STOPBITS == USART_StopBits_1_5)) /* USART Parity --------------------------------------------------------------*/ #define USART_Parity_No ((u16)0x0000) #define USART_Parity_Even ((u16)0x0400) #define USART_Parity_Odd ((u16)0x0600) #define IS_USART_PARITY(PARITY) ((PARITY == USART_Parity_No) || \ (PARITY == USART_Parity_Even) || \ (PARITY == USART_Parity_Odd)) /* USART Hardware Flow Control -----------------------------------------------*/ #define USART_HardwareFlowControl_None ((u16)0x0000) #define USART_HardwareFlowControl_RTS ((u16)0x0100) #define USART_HardwareFlowControl_CTS ((u16)0x0200) #define USART_HardwareFlowControl_RTS_CTS ((u16)0x0300) #define IS_USART_HARDWARE_FLOW_CONTROL(CONTROL)\ ((CONTROL == USART_HardwareFlowControl_None) || \ (CONTROL == USART_HardwareFlowControl_RTS) || \ (CONTROL == USART_HardwareFlowControl_CTS) || \ (CONTROL == USART_HardwareFlowControl_RTS_CTS)) /* USART Mode ----------------------------------------------------------------*/ #define USART_Mode_Rx ((u16)0x0004) #define USART_Mode_Tx ((u16)0x0008) #define IS_USART_MODE(MODE) (((MODE & (u16)0xFFF3) == 0x00) && (MODE != (u16)0x00)) /* USART Clock ---------------------------------------------------------------*/ #define USART_Clock_Disable ((u16)0x0000) #define USART_Clock_Enable ((u16)0x0800) #define IS_USART_CLOCK(CLOCK) ((CLOCK == USART_Clock_Disable) || \ (CLOCK == USART_Clock_Enable)) /* USART Clock Polarity ------------------------------------------------------*/ #define USART_CPOL_Low ((u16)0x0000) #define USART_CPOL_High ((u16)0x0400) #define IS_USART_CPOL(CPOL) ((CPOL == USART_CPOL_Low) || (CPOL == USART_CPOL_High)) /* USART Clock Phase ---------------------------------------------------------*/ #define USART_CPHA_1Edge ((u16)0x0000) #define USART_CPHA_2Edge ((u16)0x0200) #define IS_USART_CPHA(CPHA) ((CPHA == USART_CPHA_1Edge) || (CPHA == USART_CPHA_2Edge)) /* USART Last Bit ------------------------------------------------------------*/ #define USART_LastBit_Disable ((u16)0x0000) #define USART_LastBit_Enable ((u16)0x0100) #define IS_USART_LASTBIT(LASTBIT) ((LASTBIT == USART_LastBit_Disable) || \ (LASTBIT == USART_LastBit_Enable)) /* USART Interrupt definition ------------------------------------------------*/ #define USART_IT_PE ((u16)0x0028) #define USART_IT_TXE ((u16)0x0727) #define USART_IT_TC ((u16)0x0626) #define USART_IT_RXNE ((u16)0x0525) #define USART_IT_IDLE ((u16)0x0424) #define USART_IT_LBD ((u16)0x0846) #define USART_IT_CTS ((u16)0x096A) #define USART_IT_ERR ((u16)0x0060) #define USART_IT_ORE ((u16)0x0360) #define USART_IT_NE ((u16)0x0260) #define USART_IT_FE ((u16)0x0160) #define IS_USART_CONFIG_IT(IT) ((IT == USART_IT_PE) || (IT == USART_IT_TXE) || \ (IT == USART_IT_TC) || (IT == USART_IT_RXNE) || \ (IT == USART_IT_IDLE) || (IT == USART_IT_LBD) || \ (IT == USART_IT_CTS) || (IT == USART_IT_ERR)) #define IS_USART_IT(IT) ((IT == USART_IT_PE) || (IT == USART_IT_TXE) || \ (IT == USART_IT_TC) || (IT == USART_IT_RXNE) || \ (IT == USART_IT_IDLE) || (IT == USART_IT_LBD) || \ (IT == USART_IT_CTS) || (IT == USART_IT_ORE) || \ (IT == USART_IT_NE) || (IT == USART_IT_FE)) /* USART DMA Requests --------------------------------------------------------*/ #define USART_DMAReq_Tx ((u16)0x0080) #define USART_DMAReq_Rx ((u16)0x0040) #define IS_USART_DMAREQ(DMAREQ) (((DMAREQ & (u16)0xFF3F) == 0x00) && (DMAREQ != (u16)0x00)) /* USART WakeUp methods ------------------------------------------------------*/ #define USART_WakeUp_IdleLine ((u16)0x0000) #define USART_WakeUp_AddressMark ((u16)0x0800) #define IS_USART_WAKEUP(WAKEUP) ((WAKEUP == USART_WakeUp_IdleLine) || \ (WAKEUP == USART_WakeUp_AddressMark)) /* USART LIN Break Detection Length ------------------------------------------*/ #define USART_LINBreakDetectLength_10b ((u16)0x0000) #define USART_LINBreakDetectLength_11b ((u16)0x0020) #define IS_USART_LIN_BREAK_DETECT_LENGTH(LENGTH) \ ((LENGTH == USART_LINBreakDetectLength_10b) || \ (LENGTH == USART_LINBreakDetectLength_11b)) /* USART IrDA Low Power ------------------------------------------------------*/ #define USART_IrDAMode_LowPower ((u16)0x0004) #define USART_IrDAMode_Normal ((u16)0x0000) #define IS_USART_IRDA_MODE(MODE) ((MODE == USART_IrDAMode_LowPower) || \ (MODE == USART_IrDAMode_Normal)) /* USART Flags ---------------------------------------------------------------*/ #define USART_FLAG_CTS ((u16)0x0200) #define USART_FLAG_LBD ((u16)0x0100) #define USART_FLAG_TXE ((u16)0x0080) #define USART_FLAG_TC ((u16)0x0040) #define USART_FLAG_RXNE ((u16)0x0020) #define USART_FLAG_IDLE ((u16)0x0010) #define USART_FLAG_ORE ((u16)0x0008) #define USART_FLAG_NE ((u16)0x0004) #define USART_FLAG_FE ((u16)0x0002) #define USART_FLAG_PE ((u16)0x0001) #define IS_USART_FLAG(FLAG) ((FLAG == USART_FLAG_PE) || (FLAG == USART_FLAG_TXE) || \ (FLAG == USART_FLAG_TC) || (FLAG == USART_FLAG_RXNE) || \ (FLAG == USART_FLAG_IDLE) || (FLAG == USART_FLAG_LBD) || \ (FLAG == USART_FLAG_CTS) || (FLAG == USART_FLAG_ORE) || \ (FLAG == USART_FLAG_NE) || (FLAG == USART_FLAG_FE)) #define IS_USART_CLEAR_FLAG(FLAG) (((FLAG & (u16)0xFC00) == 0x00) && (FLAG != (u16)0x00)) #define IS_USART_BAUDRATE(BAUDRATE) ((BAUDRATE > 0) && (BAUDRATE < 0x0044AA21)) #define IS_USART_ADDRESS(ADDRESS) (ADDRESS <= 0xF) #define IS_USART_DATA(DATA) (DATA <= 0x1FF) /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ void USART_DeInit(USART_TypeDef* USARTx); void USART_Init(USART_TypeDef* USARTx, USART_InitTypeDef* USART_InitStruct); void USART_StructInit(USART_InitTypeDef* USART_InitStruct); void USART_Cmd(USART_TypeDef* USARTx, FunctionalState NewState); void USART_ITConfig(USART_TypeDef* USARTx, u16 USART_IT, FunctionalState NewState); void USART_DMACmd(USART_TypeDef* USARTx, u16 USART_DMAReq, FunctionalState NewState); void USART_SetAddress(USART_TypeDef* USARTx, u8 USART_Address); void USART_WakeUpConfig(USART_TypeDef* USARTx, u16 USART_WakeUp); void USART_ReceiverWakeUpCmd(USART_TypeDef* USARTx, FunctionalState NewState); void USART_LINBreakDetectLengthConfig(USART_TypeDef* USARTx, u16 USART_LINBreakDetectLength); void USART_LINCmd(USART_TypeDef* USARTx, FunctionalState NewState); void USART_SendData(USART_TypeDef* USARTx, u16 Data); u16 USART_ReceiveData(USART_TypeDef* USARTx); void USART_SendBreak(USART_TypeDef* USARTx); void USART_SetGuardTime(USART_TypeDef* USARTx, u8 USART_GuardTime); void USART_SetPrescaler(USART_TypeDef* USARTx, u8 USART_Prescaler); void USART_SmartCardCmd(USART_TypeDef* USARTx, FunctionalState NewState); void USART_SmartCardNACKCmd(USART_TypeDef* USARTx, FunctionalState NewState); void USART_HalfDuplexCmd(USART_TypeDef* USARTx, FunctionalState NewState); void USART_IrDAConfig(USART_TypeDef* USARTx, u16 USART_IrDAMode); void USART_IrDACmd(USART_TypeDef* USARTx, FunctionalState NewState); FlagStatus USART_GetFlagStatus(USART_TypeDef* USARTx, u16 USART_FLAG); void USART_ClearFlag(USART_TypeDef* USARTx, u16 USART_FLAG); ITStatus USART_GetITStatus(USART_TypeDef* USARTx, u16 USART_IT); void USART_ClearITPendingBit(USART_TypeDef* USARTx, u16 USART_IT); #endif /* __STM32F10x_USART_H */ /******************* (C) COPYRIGHT 2007 STMicroelectronics *****END OF FILE****/
yoshinrt/vsd
vsd2/library/inc/stm32f10x_usart.h
C
gpl-2.0
11,700
/** * StyleFix 1.0.3 * @author Lea Verou * MIT license */ (function(){ if(!window.addEventListener) { return; } var self = window.StyleFix = { link: function(link) { try { // Ignore stylesheets with data-noprefix attribute as well as alternate stylesheets if(link.rel !== 'stylesheet' || link.hasAttribute('data-noprefix')) { return; } } catch(e) { return; } var url = link.href || link.getAttribute('data-href'), base = url.replace(/[^\/]+$/, ''), parent = link.parentNode, xhr = new XMLHttpRequest(), process; xhr.onreadystatechange = function() { if(xhr.readyState === 4) { process(); } }; process = function() { var css = xhr.responseText; if(css && link.parentNode && (!xhr.status || xhr.status < 400 || xhr.status > 600)) { css = self.fix(css, true, link); // Convert relative URLs to absolute, if needed if(base) { css = css.replace(/url\(\s*?((?:"|')?)(.+?)\1\s*?\)/gi, function($0, quote, url) { if(!/^([a-z]{3,10}:|\/|#)/i.test(url)) { // If url not absolute & not a hash // May contain sequences like /../ and /./ but those DO work return 'url("' + base + url + '")'; } return $0; }); // behavior URLs shoudn’t be converted (Issue #19) // base should be escaped before added to RegExp (Issue #81) var escaped_base = base.replace(/([\\\^\$*+[\]?{}.=!:(|)])/g,"\\$1"); css = css.replace(RegExp('\\b(behavior:\\s*?url\\(\'?"?)' + escaped_base, 'gi'), '$1'); } var style = document.createElement('style'); style.textContent = css; style.media = link.media; style.disabled = link.disabled; style.setAttribute('data-href', link.getAttribute('href')); parent.insertBefore(style, link); parent.removeChild(link); style.media = link.media; // Duplicate is intentional. See issue #31 } }; try { xhr.open('GET', url); xhr.send(null); } catch (e) { // Fallback to XDomainRequest if available if (typeof XDomainRequest != "undefined") { xhr = new XDomainRequest(); xhr.onerror = xhr.onprogress = function() {}; xhr.onload = process; xhr.open("GET", url); xhr.send(null); } } link.setAttribute('data-inprogress', ''); }, styleElement: function(style) { if (style.hasAttribute('data-noprefix')) { return; } var disabled = style.disabled; style.textContent = self.fix(style.textContent, true, style); style.disabled = disabled; }, styleAttribute: function(element) { var css = element.getAttribute('style'); css = self.fix(css, false, element); element.setAttribute('style', css); }, process: function() { // Linked stylesheets $('link[rel="stylesheet"]:not([data-inprogress])').forEach(StyleFix.link); // Inline stylesheets $('style').forEach(StyleFix.styleElement); // Inline styles $('[style]').forEach(StyleFix.styleAttribute); }, register: function(fixer, index) { (self.fixers = self.fixers || []) .splice(index === undefined? self.fixers.length : index, 0, fixer); }, fix: function(css, raw) { for(var i=0; i<self.fixers.length; i++) { css = self.fixers[i](css, raw) || css; } return css; }, camelCase: function(str) { return str.replace(/-([a-z])/g, function($0, $1) { return $1.toUpperCase(); }).replace('-',''); }, deCamelCase: function(str) { return str.replace(/[A-Z]/g, function($0) { return '-' + $0.toLowerCase() }); } }; /************************************** * Process styles **************************************/ (function(){ setTimeout(function(){ $('link[rel="stylesheet"]').forEach(StyleFix.link); }, 10); document.addEventListener('DOMContentLoaded', StyleFix.process, false); })(); function $(expr, con) { return [].slice.call((con || document).querySelectorAll(expr)); } })(); /** * PrefixFree 1.0.6 * @author Lea Verou * MIT license */ (function(root, undefined){ if(!window.StyleFix || !window.getComputedStyle) { return; } // Private helper function fix(what, before, after, replacement, css) { what = self[what]; if(what.length) { var regex = RegExp(before + '(' + what.join('|') + ')' + after, 'gi'); css = css.replace(regex, replacement); } return css; } var self = window.PrefixFree = { prefixCSS: function(css, raw) { var prefix = self.prefix; css = fix('functions', '(\\s|:|,)', '\\s*\\(', '$1' + prefix + '$2(', css); css = fix('keywords', '(\\s|:)', '(\\s|;|\\}|$)', '$1' + prefix + '$2$3', css); css = fix('properties', '(^|\\{|\\s|;)', '\\s*:', '$1' + prefix + '$2:', css); // Prefix properties *inside* values (issue #8) if (self.properties.length) { var regex = RegExp('\\b(' + self.properties.join('|') + ')(?!:)', 'gi'); css = fix('valueProperties', '\\b', ':(.+?);', function($0) { return $0.replace(regex, prefix + "$1") }, css); } if(raw) { css = fix('selectors', '', '\\b', self.prefixSelector, css); css = fix('atrules', '@', '\\b', '@' + prefix + '$1', css); } // Fix double prefixing css = css.replace(RegExp('-' + prefix, 'g'), '-'); return css; }, property: function(property) { return (self.properties.indexOf(property)? self.prefix : '') + property; }, value: function(value, property) { value = fix('functions', '(^|\\s|,)', '\\s*\\(', '$1' + self.prefix + '$2(', value); value = fix('keywords', '(^|\\s)', '(\\s|$)', '$1' + self.prefix + '$2$3', value); // TODO properties inside values return value; }, // Warning: Prefixes no matter what, even if the selector is supported prefix-less prefixSelector: function(selector) { return selector.replace(/^:{1,2}/, function($0) { return $0 + self.prefix }) }, // Warning: Prefixes no matter what, even if the property is supported prefix-less prefixProperty: function(property, camelCase) { var prefixed = self.prefix + property; return camelCase? StyleFix.camelCase(prefixed) : prefixed; } }; /************************************** * Properties **************************************/ (function() { var prefixes = {}, properties = [], shorthands = {}, style = getComputedStyle(document.documentElement, null), dummy = document.createElement('div').style; // Why are we doing this instead of iterating over properties in a .style object? Cause Webkit won't iterate over those. var iterate = function(property) { if(property.charAt(0) === '-') { properties.push(property); var parts = property.split('-'), prefix = parts[1]; // Count prefix uses prefixes[prefix] = ++prefixes[prefix] || 1; // This helps determining shorthands while(parts.length > 3) { parts.pop(); var shorthand = parts.join('-'); if(supported(shorthand) && properties.indexOf(shorthand) === -1) { properties.push(shorthand); } } } }, supported = function(property) { return StyleFix.camelCase(property) in dummy; } // Some browsers have numerical indices for the properties, some don't if(style.length > 0) { for(var i=0; i<style.length; i++) { iterate(style[i]) } } else { for(var property in style) { iterate(StyleFix.deCamelCase(property)); } } // Find most frequently used prefix var highest = {uses:0}; for(var prefix in prefixes) { var uses = prefixes[prefix]; if(highest.uses < uses) { highest = {prefix: prefix, uses: uses}; } } self.prefix = '-' + highest.prefix + '-'; self.Prefix = StyleFix.camelCase(self.prefix); self.properties = []; // Get properties ONLY supported with a prefix for(var i=0; i<properties.length; i++) { var property = properties[i]; if(property.indexOf(self.prefix) === 0) { // we might have multiple prefixes, like Opera var unprefixed = property.slice(self.prefix.length); if(!supported(unprefixed)) { self.properties.push(unprefixed); } } } // IE fix if(self.Prefix == 'Ms' && !('transform' in dummy) && !('MsTransform' in dummy) && ('msTransform' in dummy)) { self.properties.push('transform', 'transform-origin'); } self.properties.sort(); })(); /************************************** * Values **************************************/ (function() { // Values that might need prefixing var functions = { 'linear-gradient': { property: 'backgroundImage', params: 'red, teal' }, 'calc': { property: 'width', params: '1px + 5%' }, 'element': { property: 'backgroundImage', params: '#foo' }, 'cross-fade': { property: 'backgroundImage', params: 'url(a.png), url(b.png), 50%' } }; functions['repeating-linear-gradient'] = functions['repeating-radial-gradient'] = functions['radial-gradient'] = functions['linear-gradient']; var keywords = { 'initial': 'color', 'zoom-in': 'cursor', 'zoom-out': 'cursor', 'box': 'display', 'flexbox': 'display', 'inline-flexbox': 'display', 'flex': 'display', 'inline-flex': 'display' }; self.functions = []; self.keywords = []; var style = document.createElement('div').style; function supported(value, property) { style[property] = ''; style[property] = value; return !!style[property]; } for (var func in functions) { var test = functions[func], property = test.property, value = func + '(' + test.params + ')'; if (!supported(value, property) && supported(self.prefix + value, property)) { // It's supported, but with a prefix self.functions.push(func); } } for (var keyword in keywords) { var property = keywords[keyword]; if (!supported(keyword, property) && supported(self.prefix + keyword, property)) { // It's supported, but with a prefix self.keywords.push(keyword); } } })(); /************************************** * Selectors and @-rules **************************************/ (function() { var selectors = { ':read-only': null, ':read-write': null, ':any-link': null, '::selection': null }, atrules = { 'keyframes': 'name', 'viewport': null, 'document': 'regexp(".")' }; self.selectors = []; self.atrules = []; var style = root.appendChild(document.createElement('style')); function supported(selector) { style.textContent = selector + '{}'; // Safari 4 has issues with style.innerHTML return !!style.sheet.cssRules.length; } for(var selector in selectors) { var test = selector + (selectors[selector]? '(' + selectors[selector] + ')' : ''); if(!supported(test) && supported(self.prefixSelector(test))) { self.selectors.push(selector); } } for(var atrule in atrules) { var test = atrule + ' ' + (atrules[atrule] || ''); if(!supported('@' + test) && supported('@' + self.prefix + test)) { self.atrules.push(atrule); } } root.removeChild(style); })(); // Properties that accept properties as their value self.valueProperties = [ 'transition', 'transition-property' ] // Add class for current prefix root.className += ' ' + self.prefix; StyleFix.register(self.prefixCSS); })(document.documentElement);
salem/aman
skins/admin/adminica/scripts/prefixfree/prefixfree.js
JavaScript
gpl-2.0
10,889
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * Additional copyright for this file: * Copyright (C) 1995-1997 Presto Studios, Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "common/system.h" #include "graphics/surface.h" #include "pegasus/transition.h" namespace Pegasus { ScreenFader::ScreenFader() { _isBlack = true; // Initially, assume screens are on at full brightness. Fader::setFaderValue(100); } ScreenFader::~ScreenFader() { _screen.free(); } void ScreenFader::doFadeOutSync(const TimeValue duration, const TimeValue scale, bool isBlack) { _isBlack = isBlack; _screen.copyFrom(*g_system->lockScreen()); g_system->unlockScreen(); FaderMoveSpec spec; spec.makeTwoKnotFaderSpec(scale, 0, getFaderValue(), duration, 0); startFaderSync(spec); _screen.free(); } void ScreenFader::doFadeInSync(const TimeValue duration, const TimeValue scale, bool isBlack) { _isBlack = isBlack; _screen.copyFrom(*g_system->lockScreen()); g_system->unlockScreen(); FaderMoveSpec spec; spec.makeTwoKnotFaderSpec(scale, 0, getFaderValue(), duration, 100); startFaderSync(spec); _screen.free(); } void ScreenFader::setFaderValue(const int32 value) { if (value != getFaderValue()) { Fader::setFaderValue(value); if (_screen.getPixels()) { // The original game does a gamma fade here using the Mac API. In order to do // that, it would require an immense amount of CPU processing. This does a // linear fade instead, which looks fairly well, IMO. Graphics::Surface *screen = g_system->lockScreen(); for (int y = 0; y < _screen.h; y++) { for (int x = 0; x < _screen.w; x++) { if (_screen.format.bytesPerPixel == 2) WRITE_UINT16(screen->getBasePtr(x, y), fadePixel(READ_UINT16(_screen.getBasePtr(x, y)), value)); else WRITE_UINT32(screen->getBasePtr(x, y), fadePixel(READ_UINT32(_screen.getBasePtr(x, y)), value)); } } g_system->unlockScreen(); g_system->updateScreen(); } } } static inline byte fadeComponent(byte comp, int32 percent) { return comp * percent / 100; } uint32 ScreenFader::fadePixel(uint32 color, int32 percent) const { byte r, g, b; _screen.format.colorToRGB(color, r, g, b); if (_isBlack) { r = fadeComponent(r, percent); g = fadeComponent(g, percent); b = fadeComponent(b, percent); } else { r = 0xFF - fadeComponent(0xFF - r, percent); g = 0xFF - fadeComponent(0xFF - g, percent); b = 0xFF - fadeComponent(0xFF - b, percent); } return _screen.format.RGBToColor(r, g, b); } Transition::Transition(const DisplayElementID id) : FaderAnimation(id) { _outPicture = 0; _inPicture = 0; } void Transition::setBounds(const Common::Rect &r) { FaderAnimation::setBounds(r); _boundsWidth = _bounds.width(); _boundsHeight = _bounds.height(); } void Transition::setInAndOutElements(DisplayElement *inElement, DisplayElement *outElement) { _inPicture = inElement; _outPicture = outElement; Common::Rect r; if (_outPicture) _outPicture->getBounds(r); else if (_inPicture) _inPicture->getBounds(r); setBounds(r); } void Slide::draw(const Common::Rect &r) { Common::Rect oldBounds, newBounds; adjustSlideRects(oldBounds, newBounds); drawElements(r, oldBounds, newBounds); } void Slide::adjustSlideRects(Common::Rect &oldBounds, Common::Rect &newBounds) { oldBounds = _bounds; newBounds = _bounds; } void Slide::drawElements(const Common::Rect &drawRect, const Common::Rect &oldBounds, const Common::Rect &newBounds) { drawSlideElement(drawRect, oldBounds, _outPicture); drawSlideElement(drawRect, newBounds, _inPicture); } void Slide::drawSlideElement(const Common::Rect &drawRect, const Common::Rect &oldBounds, DisplayElement *picture) { if (picture && drawRect.intersects(oldBounds)) { picture->moveElementTo(oldBounds.left, oldBounds.top); picture->draw(drawRect.findIntersectingRect(oldBounds)); } } void Push::adjustSlideRects(Common::Rect &oldBounds, Common::Rect &newBounds) { switch (_direction & kSlideHorizMask) { case kSlideLeftMask: newBounds.left = oldBounds.right = _bounds.right - pegasusRound(getFaderValue() * _boundsWidth, kTransitionRange); newBounds.right = newBounds.left + _boundsWidth; oldBounds.left = oldBounds.right - _boundsWidth; break; case kSlideRightMask: oldBounds.left = newBounds.right = _bounds.left + pegasusRound(getFaderValue() * _boundsWidth, kTransitionRange); oldBounds.right = oldBounds.left + _boundsWidth; newBounds.left = newBounds.right - _boundsWidth; break; default: newBounds.left = oldBounds.left = _bounds.left; newBounds.right = oldBounds.right = _bounds.right; break; } switch (_direction & kSlideVertMask) { case kSlideDownMask: oldBounds.top = newBounds.bottom = _bounds.top + pegasusRound(getFaderValue() * _boundsHeight, kTransitionRange); oldBounds.bottom = oldBounds.top + _boundsHeight; newBounds.top = newBounds.bottom - _boundsHeight; break; case kSlideUpMask: newBounds.top = oldBounds.bottom = _bounds.bottom - pegasusRound(getFaderValue() * _boundsHeight, kTransitionRange); newBounds.bottom = newBounds.top + _boundsHeight; oldBounds.top = oldBounds.bottom - _boundsHeight; break; default: newBounds.top = oldBounds.top = _bounds.top; newBounds.bottom = oldBounds.bottom = _bounds.bottom; break; } } } // End of namespace Pegasus
vanfanel/scummvm
engines/pegasus/transition.cpp
C++
gpl-2.0
6,165
#ifndef CLICK_UNQUEUE2_HH #define CLICK_UNQUEUE2_HH #include <click/element.hh> #include <click/task.hh> CLICK_DECLS /* * =c * Unqueue2([BURSTSIZE]) * =s shaping * pull-to-push converter * =d * Pulls packets whenever they are available, then pushes them out its single * output. Pulls a maximum of BURSTSIZE packets every time it is scheduled, * unless downstream queues are full. Default BURSTSIZE is 1. If BURSTSIZE is * 0, pull until nothing comes back. Unqueue2 will not pull if there is a * downstream queue that is full. It will also limit burst size to equal to * the number of available slots in the fullest downstream queue. * * =a Unqueue, RatedUnqueue, BandwidthRatedUnqueue */ class Unqueue2 : public Element { public: Unqueue2(); ~Unqueue2(); const char *class_name() const { return "Unqueue2"; } const char *port_count() const { return PORTS_1_1; } const char *processing() const { return PULL_TO_PUSH; } int configure(Vector<String> &, ErrorHandler *); int initialize(ErrorHandler *); void add_handlers(); bool run_task(Task *); static String read_param(Element *e, void *); private: int _burst; unsigned _packets; Task _task; Vector<Element*> _queue_elements; }; CLICK_ENDDECLS #endif
olanb7/fyp-client
elements/standard/unqueue2.hh
C++
gpl-2.0
1,258
/* * (C) Copyright 2001-2005 * Wolfgang Denk, DENX Software Engineering, [email protected]. * * SPDX-License-Identifier: GPL-2.0+ */ /* * board/config.h - configuration options, board specific */ #ifndef __CONFIG_H #define __CONFIG_H /* * High Level Configuration Options * (easy to change) */ #define CONFIG_MPC8260 1 /* This is an MPC8260 CPU */ #define CONFIG_CPU86 1 /* ...on a CPU86 board */ #define CONFIG_CPM2 1 /* Has a CPM2 */ #ifdef CONFIG_BOOT_ROM #define CONFIG_SYS_TEXT_BASE 0xFF800000 #else #define CONFIG_SYS_TEXT_BASE 0xFF000000 #endif /* * select serial console configuration * * if either CONFIG_CONS_ON_SMC or CONFIG_CONS_ON_SCC is selected, then * CONFIG_CONS_INDEX must be set to the channel number (1-2 for SMC, 1-4 * for SCC). * * if CONFIG_CONS_NONE is defined, then the serial console routines must * defined elsewhere (for example, on the cogent platform, there are serial * ports on the motherboard which are used for the serial console - see * cogent/cma101/serial.[ch]). */ #undef CONFIG_CONS_ON_SMC /* define if console on SMC */ #define CONFIG_CONS_ON_SCC /* define if console on SCC */ #undef CONFIG_CONS_NONE /* define if console on something else*/ #define CONFIG_CONS_INDEX 1 /* which serial channel for console */ #if defined(CONFIG_CONS_NONE) || defined(CONFIG_CONS_USE_EXTC) #define CONFIG_BAUDRATE 230400 #else #define CONFIG_BAUDRATE 9600 #endif /* * select ethernet configuration * * if either CONFIG_ETHER_ON_SCC or CONFIG_ETHER_ON_FCC is selected, then * CONFIG_ETHER_INDEX must be set to the channel number (1-4 for SCC, 1-3 * for FCC) * * if CONFIG_ETHER_NONE is defined, then either the ethernet routines must be * defined elsewhere (as for the console), or CONFIG_CMD_NET must be unset. */ #undef CONFIG_ETHER_ON_SCC /* define if ether on SCC */ #define CONFIG_ETHER_ON_FCC /* define if ether on FCC */ #undef CONFIG_ETHER_NONE /* define if ether on something else */ #define CONFIG_ETHER_INDEX 1 /* which SCC/FCC channel for ethernet */ #if defined(CONFIG_ETHER_ON_FCC) && (CONFIG_ETHER_INDEX == 1) /* * - Rx-CLK is CLK11 * - Tx-CLK is CLK12 * - RAM for BD/Buffers is on the 60x Bus (see 28-13) * - Enable Full Duplex in FSMR */ # define CONFIG_SYS_CMXFCR_MASK1 (CMXFCR_FC1|CMXFCR_RF1CS_MSK|CMXFCR_TF1CS_MSK) # define CONFIG_SYS_CMXFCR_VALUE1 (CMXFCR_RF1CS_CLK11|CMXFCR_TF1CS_CLK12) # define CONFIG_SYS_CPMFCR_RAMTYPE 0 # define CONFIG_SYS_FCC_PSMR (FCC_PSMR_FDE|FCC_PSMR_LPB) #elif defined(CONFIG_ETHER_ON_FCC) && (CONFIG_ETHER_INDEX == 2) /* * - Rx-CLK is CLK13 * - Tx-CLK is CLK14 * - RAM for BD/Buffers is on the 60x Bus (see 28-13) * - Enable Full Duplex in FSMR */ # define CONFIG_SYS_CMXFCR_MASK2 (CMXFCR_FC2|CMXFCR_RF2CS_MSK|CMXFCR_TF2CS_MSK) # define CONFIG_SYS_CMXFCR_VALUE2 (CMXFCR_RF2CS_CLK13|CMXFCR_TF2CS_CLK14) # define CONFIG_SYS_CPMFCR_RAMTYPE 0 # define CONFIG_SYS_FCC_PSMR (FCC_PSMR_FDE|FCC_PSMR_LPB) #endif /* CONFIG_ETHER_ON_FCC, CONFIG_ETHER_INDEX */ /* system clock rate (CLKIN) - equal to the 60x and local bus speed */ #define CONFIG_8260_CLKIN 64000000 /* in Hz */ #define CONFIG_BOOTDELAY 5 /* autoboot after 5 seconds */ #define CONFIG_PREBOOT \ "echo; " \ "echo Type \\\"run flash_nfs\\\" to mount root filesystem over NFS; " \ "echo" #undef CONFIG_BOOTARGS #define CONFIG_BOOTCOMMAND \ "bootp; " \ "setenv bootargs root=/dev/nfs rw nfsroot=${serverip}:${rootpath} " \ "ip=${ipaddr}:${serverip}:${gatewayip}:${netmask}:${hostname}::off; " \ "bootm" /*----------------------------------------------------------------------- * I2C/EEPROM/RTC configuration */ #define CONFIG_SYS_I2C #define CONFIG_SYS_I2C_SOFT /* I2C bit-banged */ #define CONFIG_SYS_I2C_SOFT_SPEED 50000 #define CONFIG_SYS_I2C_SOFT_SLAVE 0xFE /* * Software (bit-bang) I2C driver configuration */ #define I2C_PORT 3 /* Port A=0, B=1, C=2, D=3 */ #define I2C_ACTIVE (iop->pdir |= 0x00010000) #define I2C_TRISTATE (iop->pdir &= ~0x00010000) #define I2C_READ ((iop->pdat & 0x00010000) != 0) #define I2C_SDA(bit) if(bit) iop->pdat |= 0x00010000; \ else iop->pdat &= ~0x00010000 #define I2C_SCL(bit) if(bit) iop->pdat |= 0x00020000; \ else iop->pdat &= ~0x00020000 #define I2C_DELAY udelay(5) /* 1/4 I2C clock duration */ #define CONFIG_RTC_PCF8563 #define CONFIG_SYS_I2C_RTC_ADDR 0x51 #undef CONFIG_WATCHDOG /* watchdog disabled */ /*----------------------------------------------------------------------- * Miscellaneous configuration options */ #define CONFIG_LOADS_ECHO 1 /* echo on for serial download */ #undef CONFIG_SYS_LOADS_BAUD_CHANGE /* don't allow baudrate change */ /* * BOOTP options */ #define CONFIG_BOOTP_SUBNETMASK #define CONFIG_BOOTP_GATEWAY #define CONFIG_BOOTP_HOSTNAME #define CONFIG_BOOTP_BOOTPATH #define CONFIG_BOOTP_BOOTFILESIZE /* * Command line configuration. */ #include <config_cmd_default.h> #define CONFIG_CMD_BEDBUG #define CONFIG_CMD_DATE #define CONFIG_CMD_DHCP #define CONFIG_CMD_EEPROM #define CONFIG_CMD_I2C #define CONFIG_CMD_NFS #define CONFIG_CMD_SNTP /* * Miscellaneous configurable options */ #define CONFIG_SYS_LONGHELP /* undef to save memory */ #if defined(CONFIG_CMD_KGDB) #define CONFIG_SYS_CBSIZE 1024 /* Console I/O Buffer Size */ #else #define CONFIG_SYS_CBSIZE 256 /* Console I/O Buffer Size */ #endif #define CONFIG_SYS_PBSIZE (CONFIG_SYS_CBSIZE+sizeof(CONFIG_SYS_PROMPT)+16) /* Print Buffer Size */ #define CONFIG_SYS_MAXARGS 16 /* max number of command args */ #define CONFIG_SYS_BARGSIZE CONFIG_SYS_CBSIZE /* Boot Argument Buffer Size */ #define CONFIG_SYS_MEMTEST_START 0x0400000 /* memtest works on */ #define CONFIG_SYS_MEMTEST_END 0x0C00000 /* 4 ... 12 MB in DRAM */ #define CONFIG_SYS_LOAD_ADDR 0x100000 /* default load address */ #define CONFIG_SYS_RESET_ADDRESS 0xFFF00100 /* "bad" address */ /* * For booting Linux, the board info and command line data * have to be in the first 8 MB of memory, since this is * the maximum mapped by the Linux kernel during initialization. */ #define CONFIG_SYS_BOOTMAPSZ (8 << 20) /* Initial Memory map for Linux */ /*----------------------------------------------------------------------- * Flash configuration */ #define CONFIG_SYS_BOOTROM_BASE 0xFF800000 #define CONFIG_SYS_BOOTROM_SIZE 0x00080000 #define CONFIG_SYS_FLASH_BASE 0xFF000000 #define CONFIG_SYS_FLASH_SIZE 0x00800000 /*----------------------------------------------------------------------- * FLASH organization */ #define CONFIG_SYS_MAX_FLASH_BANKS 2 /* max num of memory banks */ #define CONFIG_SYS_MAX_FLASH_SECT 128 /* max num of sects on one chip */ #define CONFIG_SYS_FLASH_ERASE_TOUT 240000 /* Flash Erase Timeout (in ms) */ #define CONFIG_SYS_FLASH_WRITE_TOUT 500 /* Flash Write Timeout (in ms) */ /*----------------------------------------------------------------------- * Other areas to be mapped */ /* CS3: Dual ported SRAM */ #define CONFIG_SYS_DPSRAM_BASE 0x40000000 #define CONFIG_SYS_DPSRAM_SIZE 0x00020000 /* CS4: DiskOnChip */ #define CONFIG_SYS_DOC_BASE 0xF4000000 #define CONFIG_SYS_DOC_SIZE 0x00100000 /* CS5: FDC37C78 controller */ #define CONFIG_SYS_FDC37C78_BASE 0xF1000000 #define CONFIG_SYS_FDC37C78_SIZE 0x00100000 /* CS6: Board configuration registers */ #define CONFIG_SYS_BCRS_BASE 0xF2000000 #define CONFIG_SYS_BCRS_SIZE 0x00010000 /* CS7: VME Extended Access Range */ #define CONFIG_SYS_VMEEAR_BASE 0x80000000 #define CONFIG_SYS_VMEEAR_SIZE 0x01000000 /* CS8: VME Standard Access Range */ #define CONFIG_SYS_VMESAR_BASE 0xFE000000 #define CONFIG_SYS_VMESAR_SIZE 0x01000000 /* CS9: VME Short I/O Access Range */ #define CONFIG_SYS_VMESIOAR_BASE 0xFD000000 #define CONFIG_SYS_VMESIOAR_SIZE 0x01000000 /*----------------------------------------------------------------------- * Hard Reset Configuration Words * * if you change bits in the HRCW, you must also change the CONFIG_SYS_* * defines for the various registers affected by the HRCW e.g. changing * HRCW_DPPCxx requires you to also change CONFIG_SYS_SIUMCR. */ #if defined(CONFIG_BOOT_ROM) #define CONFIG_SYS_HRCW_MASTER (HRCW_CIP | HRCW_ISB100 | HRCW_BMS | \ HRCW_BPS01 | HRCW_CS10PC01) #else #define CONFIG_SYS_HRCW_MASTER (HRCW_CIP | HRCW_ISB100 | HRCW_BMS | HRCW_CS10PC01) #endif /* no slaves so just fill with zeros */ #define CONFIG_SYS_HRCW_SLAVE1 0 #define CONFIG_SYS_HRCW_SLAVE2 0 #define CONFIG_SYS_HRCW_SLAVE3 0 #define CONFIG_SYS_HRCW_SLAVE4 0 #define CONFIG_SYS_HRCW_SLAVE5 0 #define CONFIG_SYS_HRCW_SLAVE6 0 #define CONFIG_SYS_HRCW_SLAVE7 0 /*----------------------------------------------------------------------- * Internal Memory Mapped Register */ #define CONFIG_SYS_IMMR 0xF0000000 /*----------------------------------------------------------------------- * Definitions for initial stack pointer and data area (in DPRAM) */ #define CONFIG_SYS_INIT_RAM_ADDR CONFIG_SYS_IMMR #define CONFIG_SYS_INIT_RAM_SIZE 0x4000 /* Size of used area in DPRAM */ #define CONFIG_SYS_GBL_DATA_OFFSET (CONFIG_SYS_INIT_RAM_SIZE - GENERATED_GBL_DATA_SIZE) #define CONFIG_SYS_INIT_SP_OFFSET CONFIG_SYS_GBL_DATA_OFFSET /*----------------------------------------------------------------------- * Start addresses for the final memory configuration * (Set up by the startup code) * Please note that CONFIG_SYS_SDRAM_BASE _must_ start at 0 * * 60x SDRAM is mapped at CONFIG_SYS_SDRAM_BASE. */ #define CONFIG_SYS_SDRAM_BASE 0x00000000 #define CONFIG_SYS_SDRAM_MAX_SIZE 0x08000000 /* max. 128 MB */ #define CONFIG_SYS_MONITOR_BASE CONFIG_SYS_TEXT_BASE #define CONFIG_SYS_MONITOR_LEN (256 << 10) /* Reserve 256 kB for Monitor */ #define CONFIG_SYS_MALLOC_LEN (128 << 10) /* Reserve 128 kB for malloc()*/ #if (CONFIG_SYS_MONITOR_BASE < CONFIG_SYS_FLASH_BASE) # define CONFIG_SYS_RAMBOOT #endif #if 0 /* environment is in Flash */ #define CONFIG_ENV_IS_IN_FLASH 1 #ifdef CONFIG_BOOT_ROM # define CONFIG_ENV_ADDR (CONFIG_SYS_FLASH_BASE+0x70000) # define CONFIG_ENV_SIZE 0x10000 # define CONFIG_ENV_SECT_SIZE 0x10000 #endif #else /* environment is in EEPROM */ #define CONFIG_ENV_IS_IN_EEPROM 1 #define CONFIG_SYS_I2C_EEPROM_ADDR 0x58 /* EEPROM X24C16 */ #define CONFIG_SYS_I2C_EEPROM_ADDR_LEN 1 /* mask of address bits that overflow into the "EEPROM chip address" */ #define CONFIG_SYS_I2C_EEPROM_ADDR_OVERFLOW 0x07 #define CONFIG_SYS_EEPROM_PAGE_WRITE_BITS 4 #define CONFIG_SYS_EEPROM_PAGE_WRITE_DELAY_MS 10 /* and takes up to 10 msec */ #define CONFIG_ENV_OFFSET 512 #define CONFIG_ENV_SIZE (2048 - 512) #endif /*----------------------------------------------------------------------- * Cache Configuration */ #define CONFIG_SYS_CACHELINE_SIZE 32 /* For MPC8260 CPU */ #if defined(CONFIG_CMD_KGDB) # define CONFIG_SYS_CACHELINE_SHIFT 5 /* log base 2 of the above value */ #endif /*----------------------------------------------------------------------- * HIDx - Hardware Implementation-dependent Registers 2-11 *----------------------------------------------------------------------- * HID0 also contains cache control - initially enable both caches and * invalidate contents, then the final state leaves only the instruction * cache enabled. Note that Power-On and Hard reset invalidate the caches, * but Soft reset does not. * * HID1 has only read-only information - nothing to set. */ #define CONFIG_SYS_HID0_INIT (HID0_ICE|HID0_DCE|HID0_ICFI|\ HID0_DCI|HID0_IFEM|HID0_ABE) #define CONFIG_SYS_HID0_FINAL (HID0_IFEM|HID0_ABE) #define CONFIG_SYS_HID2 0 /*----------------------------------------------------------------------- * RMR - Reset Mode Register 5-5 *----------------------------------------------------------------------- * turn on Checkstop Reset Enable */ #define CONFIG_SYS_RMR RMR_CSRE /*----------------------------------------------------------------------- * BCR - Bus Configuration 4-25 *----------------------------------------------------------------------- */ #define BCR_APD01 0x10000000 #define CONFIG_SYS_BCR (BCR_APD01|BCR_ETM|BCR_LETM) /* 8260 mode */ /*----------------------------------------------------------------------- * SIUMCR - SIU Module Configuration 4-31 *----------------------------------------------------------------------- */ #define CONFIG_SYS_SIUMCR (SIUMCR_BBD|SIUMCR_DPPC00|SIUMCR_APPC10|\ SIUMCR_CS10PC01|SIUMCR_BCTLC10) /*----------------------------------------------------------------------- * SYPCR - System Protection Control 4-35 * SYPCR can only be written once after reset! *----------------------------------------------------------------------- * Watchdog & Bus Monitor Timer max, 60x Bus Monitor enable */ #if defined(CONFIG_WATCHDOG) #define CONFIG_SYS_SYPCR (SYPCR_SWTC|SYPCR_BMT|SYPCR_PBME|SYPCR_LBME|\ SYPCR_SWRI|SYPCR_SWP|SYPCR_SWE) #else #define CONFIG_SYS_SYPCR (SYPCR_SWTC|SYPCR_BMT|SYPCR_PBME|SYPCR_LBME|\ SYPCR_SWRI|SYPCR_SWP) #endif /* CONFIG_WATCHDOG */ /*----------------------------------------------------------------------- * TMCNTSC - Time Counter Status and Control 4-40 *----------------------------------------------------------------------- * Clear once per Second and Alarm Interrupt Status, Set 32KHz timersclk, * and enable Time Counter */ #define CONFIG_SYS_TMCNTSC (TMCNTSC_SEC|TMCNTSC_ALR|TMCNTSC_TCF|TMCNTSC_TCE) /*----------------------------------------------------------------------- * PISCR - Periodic Interrupt Status and Control 4-42 *----------------------------------------------------------------------- * Clear Periodic Interrupt Status, Set 32KHz timersclk, and enable * Periodic timer */ #define CONFIG_SYS_PISCR (PISCR_PS|PISCR_PTF|PISCR_PTE) /*----------------------------------------------------------------------- * SCCR - System Clock Control 9-8 *----------------------------------------------------------------------- * Ensure DFBRG is Divide by 16 */ #define CONFIG_SYS_SCCR SCCR_DFBRG01 /*----------------------------------------------------------------------- * RCCR - RISC Controller Configuration 13-7 *----------------------------------------------------------------------- */ #define CONFIG_SYS_RCCR 0 #define CONFIG_SYS_MIN_AM_MASK 0xC0000000 /*----------------------------------------------------------------------- * MPTPR - Memory Refresh Timer Prescaler Register 10-18 *----------------------------------------------------------------------- */ #define CONFIG_SYS_MPTPR 0x1F00 /*----------------------------------------------------------------------- * PSRT - Refresh Timer Register 10-16 *----------------------------------------------------------------------- */ #define CONFIG_SYS_PSRT 0x0f /*----------------------------------------------------------------------- * PSRT - SDRAM Mode Register 10-10 *----------------------------------------------------------------------- */ /* SDRAM initialization values for 8-column chips */ #define CONFIG_SYS_OR2_8COL (CONFIG_SYS_MIN_AM_MASK |\ ORxS_BPD_4 |\ ORxS_ROWST_PBI0_A9 |\ ORxS_NUMR_12) #define CONFIG_SYS_PSDMR_8COL (PSDMR_SDAM_A13_IS_A5 |\ PSDMR_BSMA_A14_A16 |\ PSDMR_SDA10_PBI0_A10 |\ PSDMR_RFRC_7_CLK |\ PSDMR_PRETOACT_2W |\ PSDMR_ACTTORW_1W |\ PSDMR_LDOTOPRE_1C |\ PSDMR_WRC_1C |\ PSDMR_CL_2) /* SDRAM initialization values for 9-column chips */ #define CONFIG_SYS_OR2_9COL (CONFIG_SYS_MIN_AM_MASK |\ ORxS_BPD_4 |\ ORxS_ROWST_PBI0_A7 |\ ORxS_NUMR_13) #define CONFIG_SYS_PSDMR_9COL (PSDMR_SDAM_A14_IS_A5 |\ PSDMR_BSMA_A13_A15 |\ PSDMR_SDA10_PBI0_A9 |\ PSDMR_RFRC_7_CLK |\ PSDMR_PRETOACT_2W |\ PSDMR_ACTTORW_1W |\ PSDMR_LDOTOPRE_1C |\ PSDMR_WRC_1C |\ PSDMR_CL_2) /* * Init Memory Controller: * * Bank Bus Machine PortSz Device * ---- --- ------- ------ ------ * 0 60x GPCM 8 bit Boot ROM * 1 60x GPCM 64 bit FLASH * 2 60x SDRAM 64 bit SDRAM * */ #define CONFIG_SYS_MRS_OFFS 0x00000000 #ifdef CONFIG_BOOT_ROM /* Bank 0 - Boot ROM */ #define CONFIG_SYS_BR0_PRELIM ((CONFIG_SYS_BOOTROM_BASE & BRx_BA_MSK)|\ BRx_PS_8 |\ BRx_MS_GPCM_P |\ BRx_V) #define CONFIG_SYS_OR0_PRELIM (P2SZ_TO_AM(CONFIG_SYS_BOOTROM_SIZE) |\ ORxG_CSNT |\ ORxG_ACS_DIV1 |\ ORxG_SCY_3_CLK |\ ORxU_EHTR_8IDLE) /* Bank 1 - FLASH */ #define CONFIG_SYS_BR1_PRELIM ((CONFIG_SYS_FLASH_BASE & BRx_BA_MSK) |\ BRx_PS_64 |\ BRx_MS_GPCM_P |\ BRx_V) #define CONFIG_SYS_OR1_PRELIM (P2SZ_TO_AM(CONFIG_SYS_FLASH_SIZE) |\ ORxG_CSNT |\ ORxG_ACS_DIV1 |\ ORxG_SCY_3_CLK |\ ORxU_EHTR_8IDLE) #else /* CONFIG_BOOT_ROM */ /* Bank 0 - FLASH */ #define CONFIG_SYS_BR0_PRELIM ((CONFIG_SYS_FLASH_BASE & BRx_BA_MSK) |\ BRx_PS_64 |\ BRx_MS_GPCM_P |\ BRx_V) #define CONFIG_SYS_OR0_PRELIM (P2SZ_TO_AM(CONFIG_SYS_FLASH_SIZE) |\ ORxG_CSNT |\ ORxG_ACS_DIV1 |\ ORxG_SCY_3_CLK |\ ORxU_EHTR_8IDLE) /* Bank 1 - Boot ROM */ #define CONFIG_SYS_BR1_PRELIM ((CONFIG_SYS_BOOTROM_BASE & BRx_BA_MSK)|\ BRx_PS_8 |\ BRx_MS_GPCM_P |\ BRx_V) #define CONFIG_SYS_OR1_PRELIM (P2SZ_TO_AM(CONFIG_SYS_BOOTROM_SIZE) |\ ORxG_CSNT |\ ORxG_ACS_DIV1 |\ ORxG_SCY_3_CLK |\ ORxU_EHTR_8IDLE) #endif /* CONFIG_BOOT_ROM */ /* Bank 2 - 60x bus SDRAM */ #ifndef CONFIG_SYS_RAMBOOT #define CONFIG_SYS_BR2_PRELIM ((CONFIG_SYS_SDRAM_BASE & BRx_BA_MSK) |\ BRx_PS_64 |\ BRx_MS_SDRAM_P |\ BRx_V) #define CONFIG_SYS_OR2_PRELIM CONFIG_SYS_OR2_9COL #define CONFIG_SYS_PSDMR CONFIG_SYS_PSDMR_9COL #endif /* CONFIG_SYS_RAMBOOT */ /* Bank 3 - Dual Ported SRAM */ #define CONFIG_SYS_BR3_PRELIM ((CONFIG_SYS_DPSRAM_BASE & BRx_BA_MSK) |\ BRx_PS_16 |\ BRx_MS_GPCM_P |\ BRx_V) #define CONFIG_SYS_OR3_PRELIM (P2SZ_TO_AM(CONFIG_SYS_DPSRAM_SIZE) |\ ORxG_CSNT |\ ORxG_ACS_DIV1 |\ ORxG_SCY_5_CLK |\ ORxG_SETA) /* Bank 4 - DiskOnChip */ #define CONFIG_SYS_BR4_PRELIM ((CONFIG_SYS_DOC_BASE & BRx_BA_MSK) |\ BRx_PS_8 |\ BRx_MS_GPCM_P |\ BRx_V) #define CONFIG_SYS_OR4_PRELIM (P2SZ_TO_AM(CONFIG_SYS_DOC_SIZE) |\ ORxG_ACS_DIV2 |\ ORxG_SCY_5_CLK |\ ORxU_EHTR_8IDLE) /* Bank 5 - FDC37C78 controller */ #define CONFIG_SYS_BR5_PRELIM ((CONFIG_SYS_FDC37C78_BASE & BRx_BA_MSK) |\ BRx_PS_8 |\ BRx_MS_GPCM_P |\ BRx_V) #define CONFIG_SYS_OR5_PRELIM (P2SZ_TO_AM(CONFIG_SYS_FDC37C78_SIZE) |\ ORxG_ACS_DIV2 |\ ORxG_SCY_8_CLK |\ ORxU_EHTR_8IDLE) /* Bank 6 - Board control registers */ #define CONFIG_SYS_BR6_PRELIM ((CONFIG_SYS_BCRS_BASE & BRx_BA_MSK) |\ BRx_PS_8 |\ BRx_MS_GPCM_P |\ BRx_V) #define CONFIG_SYS_OR6_PRELIM (P2SZ_TO_AM(CONFIG_SYS_BCRS_SIZE) |\ ORxG_CSNT |\ ORxG_SCY_5_CLK) /* Bank 7 - VME Extended Access Range */ #define CONFIG_SYS_BR7_PRELIM ((CONFIG_SYS_VMEEAR_BASE & BRx_BA_MSK) |\ BRx_PS_32 |\ BRx_MS_GPCM_P |\ BRx_V) #define CONFIG_SYS_OR7_PRELIM (P2SZ_TO_AM(CONFIG_SYS_VMEEAR_SIZE) |\ ORxG_CSNT |\ ORxG_ACS_DIV1 |\ ORxG_SCY_5_CLK |\ ORxG_SETA) /* Bank 8 - VME Standard Access Range */ #define CONFIG_SYS_BR8_PRELIM ((CONFIG_SYS_VMESAR_BASE & BRx_BA_MSK) |\ BRx_PS_16 |\ BRx_MS_GPCM_P |\ BRx_V) #define CONFIG_SYS_OR8_PRELIM (P2SZ_TO_AM(CONFIG_SYS_VMESAR_SIZE) |\ ORxG_CSNT |\ ORxG_ACS_DIV1 |\ ORxG_SCY_5_CLK |\ ORxG_SETA) /* Bank 9 - VME Short I/O Access Range */ #define CONFIG_SYS_BR9_PRELIM ((CONFIG_SYS_VMESIOAR_BASE & BRx_BA_MSK) |\ BRx_PS_16 |\ BRx_MS_GPCM_P |\ BRx_V) #define CONFIG_SYS_OR9_PRELIM (P2SZ_TO_AM(CONFIG_SYS_VMESIOAR_SIZE) |\ ORxG_CSNT |\ ORxG_ACS_DIV1 |\ ORxG_SCY_5_CLK |\ ORxG_SETA) #endif /* __CONFIG_H */
vkrmsngh/new_pro
u-boot/include/configs/CPU86.h
C
gpl-2.0
21,105
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"> <title>elFinder 2.1.x source version with PHP connector</title> <!-- Require JS (REQUIRED) --> <!-- Rename "main.default.js" to "main.js" and edit it if you need configure elFInder options or any things --> <script data-main="./main.default.js" src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.3.5/require.min.js"></script> <script> define('elFinderConfig', { // elFinder options (REQUIRED) // Documentation for client options: // https://github.com/Studio-42/elFinder/wiki/Client-configuration-options defaultOpts : { url : 'php/connector.minimal.php' // connector URL (REQUIRED) ,commandsOptions : { edit : { extraOptions : { // set API key to enable Creative Cloud image editor // see https://console.adobe.io/ creativeCloudApiKey : '', // browsing manager URL for CKEditor, TinyMCE // uses self location with the empty value managerUrl : '' } } ,quicklook : { // to enable CAD-Files and 3D-Models preview with sharecad.org sharecadMimes : ['image/vnd.dwg', 'image/vnd.dxf', 'model/vnd.dwf', 'application/vnd.hp-hpgl', 'application/plt', 'application/step', 'model/iges', 'application/vnd.ms-pki.stl', 'application/sat', 'image/cgm', 'application/x-msmetafile'], // to enable preview with Google Docs Viewer googleDocsMimes : ['application/pdf', 'image/tiff', 'application/vnd.ms-office', 'application/msword', 'application/vnd.ms-word', 'application/vnd.ms-excel', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/postscript', 'application/rtf'], // to enable preview with Microsoft Office Online Viewer // these MIME types override "googleDocsMimes" officeOnlineMimes : ['application/vnd.ms-office', 'application/msword', 'application/vnd.ms-word', 'application/vnd.ms-excel', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/vnd.oasis.opendocument.text', 'application/vnd.oasis.opendocument.spreadsheet', 'application/vnd.oasis.opendocument.presentation'] } } // bootCalback calls at before elFinder boot up ,bootCallback : function(fm, extraObj) { /* any bind functions etc. */ fm.bind('init', function() { // any your code }); // for example set document.title dynamically. var title = document.title; fm.bind('open', function() { var path = '', cwd = fm.cwd(); if (cwd) { path = fm.path(cwd.hash) || null; } document.title = path? path + ':' + title : title; }).bind('destroy', function() { document.title = title; }); } }, managers : { // 'DOM Element ID': { /* elFinder options of this DOM Element */ } 'elfinder': {} } }); </script> </head> <body> <!-- Element where elFinder will be created (REQUIRED) --> <div id="elfinder"></div> </body> </html>
jameswadsworth/k2
media/k2/assets/vendors/studio-42/elfinder/elfinder.html
HTML
gpl-2.0
3,547
.dojoxCalcLayout span.dijitButtonNode, .dojoxCalcLayout span.dijitButtonContents{ display:block; } .dojoxCalc .dojoxCalcLayout .dojoxCalcTextAreaContainer { padding-left: 0.2em; padding-right: 0.2em; #border-right: .3em; } .dojoxCalcLayout .dojoxCalcInputContainer .dijitTextBox { position: relative; border-left: 0 none; border-right: 0 none; width:100%; } .dojoxCalcLayout .dojoxCalcInputContainer, .dojoxCalcLayout .dojoxCalcInputContainer .dijitInputField { padding-left: 0; padding-right: 0; } .dojoxCalcLayout .dojoxCalcInputContainer .dijitInputContainer { padding-left: 0; #padding-left: 0.5em; padding-right: 0.3em; #padding-right: 0; } .dojoxCalcLayout .dojoxCalcInputContainer .dijitInputInner { text-align: left; padding-left: 0.2em !important; padding-right: 0 !important; #padding-right: 0.3em !important; overflow: hidden; } .dojoxCalcMinusButtonContainer { width: 4em; min-width: 4em; padding: 0; } .dojoxCalcMinusButtonContainer .dijitButton { margin: 0.1em; width: 3.8em; } .dojoxCalcMinusButtonContainer .dijitArrowButtonInner { width:1.3em; } .dojoxCalcMinusButtonContainer .dijitButtonNode .dijitButtonContents { width: 2.1em; min-width: 2.1em; } .dojoxCalcLayout .dojoxCalcMinusButtonContainer .dijitButtonText, .dojoxCalcLayout .dojoxCalcMinusButtonContainer .dijitButtonNode { padding-left: 0px; padding-right: 0px; } .dojoxCalcButtonContainer { width: 4em; min-width: 4em; padding: 0; } .dojoxCalcButtonContainer .dijitButton { margin: 0.1em; width: 3.8em; } .dojoxCalcLayout .dojoxCalcButtonContainer .dijitButtonText, .dojoxCalcLayout .dojoxCalcButtonContainer .dijitButtonNode { padding-left: 0px; padding-right: 0px; } .dojoxCalcLayout { table-layout:fixed; border-width: 0; border-style: none; width:16.0em; font:monospace; } .dojoxCalc { border: 0.4em ridge #909090; } .dojoxCalcGrapherLayout span.dijitButtonNode, .dojoxCalcGrapherLayout span.dijitButtonContents{ display:block; } .dojoxCalcGrapherButtonContainer { width: 10em; min-width: 10em; padding: 0; } .dojoxCalcGrapherButton { display:block; } .dojoxCalcGrapherLayout { table-layout:fixed; border-width: 0; border-style: none; width:20.0em; font:monospace; } .dojoxCalcExpressionBox { width:15em; } .dojoxCalcChartHolder { position:absolute; left:36em; top:5em; } .dojoxCalcGraphOptionTable { width:25em; } .dojoxCalcGraphWidth { width:5em; } .dojoxCalcGraphHeight { width:5em; } .dojoxCalcGraphMinX { width:5em; } .dojoxCalcGraphMaxX { width:5em; } .dojoxCalcGraphMinY { width:5em; } .dojoxCalcGraphMaxY { width:5em; } .dojoxCalcGrapherFuncOuterDiv { width:35em; height:15em; overflow-y:scroll; } .dojoxCalcGrapherModeTable { width:10em; } .dojoxCalcFunctionModeSelector { width:5em; } .dojoxCalcStatusBox { border:1px solid; padding:1px; display:inline; }
hariomkumarmth/champaranexpress
wp-content/plugins/dojo/dojox/calc/resources/Standard.css
CSS
gpl-2.0
2,968
/*------------------------------------------------------------------- Call_Hompack.c created 9/15/1994 last modified 9/15/1994 Birk Huber ([email protected] ALL RIGHTS RESERVED This File represents the interface between Pelican and Hompacks FIXPNF path tracker. The HOMPACK routines it calls have actually been translated from fortran into c with f2c and then modified a little so as not to require the f2c library. The two routines the user needs to be aware of are init_HPK which takes a pelican Pvector, converts it to "tableau" format, and initialies all the nescessary global variables to represent the homotopy. Call_HPK_Hom wich takes a double vector and uses it as a starting point for path continuation. --------------------------------------------------------------------*/ #include "pelclhpk.h" #define X(i) (DVref(X,i)) int HPK_cont(Dvector X, int tweak) { int i, ist, dst,N,N1; static int iflag,trace,nfe,*pivot,*ipar; static double *yold,*a,arcae; static double *qr, arclen, *wp, *yp, *tz,*par,*z0,*z1; static double ansre, *ypold, *sspar,*alpha,ansae,*w,*y,arcre; /* extern int fixpnf_(); IN Homotopies.h */ if (Hom_defd!=1) return 0; /* save start of free storage space */ ist=Itop(); dst=Dtop(); /* init numbers of real eqs with and without hom param*/ N=2*Hom_num_vars; N1=N+1; /* get space for local arrays from store */ ipar=Ires(1); pivot=Ires(N1); yold=Dres(N1); a=Dres(N1); alpha=Dres(N1); w=Dres(N1); y=Dres(N1); ypold=Dres(N1); sspar=Dres(8); z0=Dres(N1); z1=Dres(N1); qr=Dres(N*(N1+1)); wp=Dres(N1); yp=Dres(N1); tz=Dres(N1); par=Dres(1); /* initialize parameters */ iflag = -2; /* should not be changed switch to tell hompack to do path tracking*/ arcre = -1.; arcae = -1.; /* errors allowed during normal flow iteration will be automatically reset to appropriat values later*/ ansre = Hom_tol; ansae = Hom_tol; trace = 1; /* 1 keep a log , 0 dont */ nfe = 10; /* I am not sure what this one is for */ for(i=0;i<8;i++) sspar[i] = -1.; /* sspar holds a number of flags used to determine optimal step size, set to -1 will cause hompack to choose them by its own heuristics */ Htransform(X); /* print Starting point to Log File*/ print_proj_trans(); for(i=1;i<=N+3;i++) #ifdef CHP_PRINT fprintf(Hom_LogFile,"S %g", X(i)); fprintf(Hom_LogFile," 0 \n") #endif ; y[0]=X(N+3);/* y0 holds the initial deformation parameter */ for(i=3;i<=N+2;i++){ /* y1 and on hold the starting coordinates */ y[i-2]=X(i); } fixpnf_(&N, y, &iflag, &arcre, &arcae, &ansre, &ansae, &trace, a, &nfe, &arclen, yp, yold, ypold, qr, alpha, tz, pivot, w, wp, z0, z1, sspar, par, ipar, tweak); /* tweak is used to refine step size */ /* #ifdef CHP_PRINT fprintf(Hom_OutFile,"Done arclen=%f, LAMBDA=%f, return flag %d\n", arclen,y[0],iflag) #endif */ ; for(i=1;i<=N;i++) X(i+2)=y[i]; X(N+3)=y[0]; Huntransform(X); /* print ending point to log file */ #ifdef CHP_PRINT fprintf(Hom_LogFile,"E") #endif ; for(i=1;i<=N+3;i++) #ifdef CHP_PRINT fprintf(Hom_LogFile," %g", X(i)) #endif ; #ifdef CHP_PRINT fprintf(Hom_LogFile," 4 1 %d %f %f",iflag,arclen,y[0]); fprintf(Hom_LogFile,"\n") #endif ; /*free space*/ Ifree(ist), Dfree(dst); return 0; } #undef X
chumsley/gambit
src/tools/enumpoly/pelclhpk.cc
C++
gpl-2.0
3,575
#!/usr/bin/env python from wtforms import Form, SelectField, SubmitField class DispenserForm(Form): save = SubmitField(u"save") cancel = SubmitField(u"cancel") form = DispenserForm()
wyolum/bartendro
ui/bartendro/form/dispenser.py
Python
gpl-2.0
194
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2013 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #ifndef XCSOAR_DEVICE_DRIVER_VOLKSLOGGER_HPP #define XCSOAR_DEVICE_DRIVER_VOLKSLOGGER_HPP extern const struct DeviceRegister volkslogger_driver; #endif
onkelhotte/XCSoar
src/Device/Driver/Volkslogger.hpp
C++
gpl-2.0
1,054
from fail2ban.server.action import ActionBase class TestAction(ActionBase): def __init__(self, jail, name, opt1, opt2=None): super(TestAction, self).__init__(jail, name) self._logSys.debug("%s initialised" % self.__class__.__name__) self.opt1 = opt1 self.opt2 = opt2 self._opt3 = "Hello" def start(self): self._logSys.debug("%s action start" % self.__class__.__name__) def stop(self): self._logSys.debug("%s action stop" % self.__class__.__name__) def ban(self, aInfo): self._logSys.debug("%s action ban" % self.__class__.__name__) def unban(self, aInfo): self._logSys.debug("%s action unban" % self.__class__.__name__) def testmethod(self, text): return "%s %s %s" % (self._opt3, text, self.opt1) Action = TestAction
TonyThompson/fail2ban-patch
fail2ban/tests/files/action.d/action.py
Python
gpl-2.0
831
/* Target signal translation functions for GDB. Copyright (C) 1990-2003, 2006-2012 Free Software Foundation, Inc. Contributed by Cygnus Support. This file is part of GDB. 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/>. */ #ifdef GDBSERVER #include "server.h" #else #include "defs.h" #include "gdb_string.h" #endif #ifdef HAVE_SIGNAL_H #include <signal.h> #endif #include "gdb_signals.h" struct gdbarch; /* Always use __SIGRTMIN if it's available. SIGRTMIN is the lowest _available_ realtime signal, not the lowest supported; glibc takes several for its own use. */ #ifndef REALTIME_LO # if defined(__SIGRTMIN) # define REALTIME_LO __SIGRTMIN # define REALTIME_HI (__SIGRTMAX + 1) # elif defined(SIGRTMIN) # define REALTIME_LO SIGRTMIN # define REALTIME_HI (SIGRTMAX + 1) # endif #endif /* This table must match in order and size the signals in enum target_signal. */ static const struct { const char *name; const char *string; } signals [] = { #define SET(symbol, constant, name, string) { name, string }, #include "gdb/signals.def" #undef SET }; /* Return the string for a signal. */ const char * target_signal_to_string (enum target_signal sig) { if ((int) sig >= TARGET_SIGNAL_FIRST && (int) sig <= TARGET_SIGNAL_LAST) return signals[sig].string; else return signals[TARGET_SIGNAL_UNKNOWN].string; } /* Return the name for a signal. */ const char * target_signal_to_name (enum target_signal sig) { if ((int) sig >= TARGET_SIGNAL_FIRST && (int) sig <= TARGET_SIGNAL_LAST && signals[sig].name != NULL) return signals[sig].name; else /* I think the code which prints this will always print it along with the string, so no need to be verbose (very old comment). */ return "?"; } /* Given a name, return its signal. */ enum target_signal target_signal_from_name (const char *name) { enum target_signal sig; /* It's possible we also should allow "SIGCLD" as well as "SIGCHLD" for TARGET_SIGNAL_SIGCHLD. SIGIOT, on the other hand, is more questionable; seems like by now people should call it SIGABRT instead. */ /* This ugly cast brought to you by the native VAX compiler. */ for (sig = TARGET_SIGNAL_HUP; sig < TARGET_SIGNAL_LAST; sig = (enum target_signal) ((int) sig + 1)) if (signals[sig].name != NULL && strcmp (name, signals[sig].name) == 0) return sig; return TARGET_SIGNAL_UNKNOWN; } /* The following functions are to help certain targets deal with the signal/waitstatus stuff. They could just as well be in a file called native-utils.c or unixwaitstatus-utils.c or whatever. */ /* Convert host signal to our signals. */ enum target_signal target_signal_from_host (int hostsig) { /* A switch statement would make sense but would require special kludges to deal with the cases where more than one signal has the same number. */ if (hostsig == 0) return TARGET_SIGNAL_0; #if defined (SIGHUP) if (hostsig == SIGHUP) return TARGET_SIGNAL_HUP; #endif #if defined (SIGINT) if (hostsig == SIGINT) return TARGET_SIGNAL_INT; #endif #if defined (SIGQUIT) if (hostsig == SIGQUIT) return TARGET_SIGNAL_QUIT; #endif #if defined (SIGILL) if (hostsig == SIGILL) return TARGET_SIGNAL_ILL; #endif #if defined (SIGTRAP) if (hostsig == SIGTRAP) return TARGET_SIGNAL_TRAP; #endif #if defined (SIGABRT) if (hostsig == SIGABRT) return TARGET_SIGNAL_ABRT; #endif #if defined (SIGEMT) if (hostsig == SIGEMT) return TARGET_SIGNAL_EMT; #endif #if defined (SIGFPE) if (hostsig == SIGFPE) return TARGET_SIGNAL_FPE; #endif #if defined (SIGKILL) if (hostsig == SIGKILL) return TARGET_SIGNAL_KILL; #endif #if defined (SIGBUS) if (hostsig == SIGBUS) return TARGET_SIGNAL_BUS; #endif #if defined (SIGSEGV) if (hostsig == SIGSEGV) return TARGET_SIGNAL_SEGV; #endif #if defined (SIGSYS) if (hostsig == SIGSYS) return TARGET_SIGNAL_SYS; #endif #if defined (SIGPIPE) if (hostsig == SIGPIPE) return TARGET_SIGNAL_PIPE; #endif #if defined (SIGALRM) if (hostsig == SIGALRM) return TARGET_SIGNAL_ALRM; #endif #if defined (SIGTERM) if (hostsig == SIGTERM) return TARGET_SIGNAL_TERM; #endif #if defined (SIGUSR1) if (hostsig == SIGUSR1) return TARGET_SIGNAL_USR1; #endif #if defined (SIGUSR2) if (hostsig == SIGUSR2) return TARGET_SIGNAL_USR2; #endif #if defined (SIGCLD) if (hostsig == SIGCLD) return TARGET_SIGNAL_CHLD; #endif #if defined (SIGCHLD) if (hostsig == SIGCHLD) return TARGET_SIGNAL_CHLD; #endif #if defined (SIGPWR) if (hostsig == SIGPWR) return TARGET_SIGNAL_PWR; #endif #if defined (SIGWINCH) if (hostsig == SIGWINCH) return TARGET_SIGNAL_WINCH; #endif #if defined (SIGURG) if (hostsig == SIGURG) return TARGET_SIGNAL_URG; #endif #if defined (SIGIO) if (hostsig == SIGIO) return TARGET_SIGNAL_IO; #endif #if defined (SIGPOLL) if (hostsig == SIGPOLL) return TARGET_SIGNAL_POLL; #endif #if defined (SIGSTOP) if (hostsig == SIGSTOP) return TARGET_SIGNAL_STOP; #endif #if defined (SIGTSTP) if (hostsig == SIGTSTP) return TARGET_SIGNAL_TSTP; #endif #if defined (SIGCONT) if (hostsig == SIGCONT) return TARGET_SIGNAL_CONT; #endif #if defined (SIGTTIN) if (hostsig == SIGTTIN) return TARGET_SIGNAL_TTIN; #endif #if defined (SIGTTOU) if (hostsig == SIGTTOU) return TARGET_SIGNAL_TTOU; #endif #if defined (SIGVTALRM) if (hostsig == SIGVTALRM) return TARGET_SIGNAL_VTALRM; #endif #if defined (SIGPROF) if (hostsig == SIGPROF) return TARGET_SIGNAL_PROF; #endif #if defined (SIGXCPU) if (hostsig == SIGXCPU) return TARGET_SIGNAL_XCPU; #endif #if defined (SIGXFSZ) if (hostsig == SIGXFSZ) return TARGET_SIGNAL_XFSZ; #endif #if defined (SIGWIND) if (hostsig == SIGWIND) return TARGET_SIGNAL_WIND; #endif #if defined (SIGPHONE) if (hostsig == SIGPHONE) return TARGET_SIGNAL_PHONE; #endif #if defined (SIGLOST) if (hostsig == SIGLOST) return TARGET_SIGNAL_LOST; #endif #if defined (SIGWAITING) if (hostsig == SIGWAITING) return TARGET_SIGNAL_WAITING; #endif #if defined (SIGCANCEL) if (hostsig == SIGCANCEL) return TARGET_SIGNAL_CANCEL; #endif #if defined (SIGLWP) if (hostsig == SIGLWP) return TARGET_SIGNAL_LWP; #endif #if defined (SIGDANGER) if (hostsig == SIGDANGER) return TARGET_SIGNAL_DANGER; #endif #if defined (SIGGRANT) if (hostsig == SIGGRANT) return TARGET_SIGNAL_GRANT; #endif #if defined (SIGRETRACT) if (hostsig == SIGRETRACT) return TARGET_SIGNAL_RETRACT; #endif #if defined (SIGMSG) if (hostsig == SIGMSG) return TARGET_SIGNAL_MSG; #endif #if defined (SIGSOUND) if (hostsig == SIGSOUND) return TARGET_SIGNAL_SOUND; #endif #if defined (SIGSAK) if (hostsig == SIGSAK) return TARGET_SIGNAL_SAK; #endif #if defined (SIGPRIO) if (hostsig == SIGPRIO) return TARGET_SIGNAL_PRIO; #endif /* Mach exceptions. Assumes that the values for EXC_ are positive! */ #if defined (EXC_BAD_ACCESS) && defined (_NSIG) if (hostsig == _NSIG + EXC_BAD_ACCESS) return TARGET_EXC_BAD_ACCESS; #endif #if defined (EXC_BAD_INSTRUCTION) && defined (_NSIG) if (hostsig == _NSIG + EXC_BAD_INSTRUCTION) return TARGET_EXC_BAD_INSTRUCTION; #endif #if defined (EXC_ARITHMETIC) && defined (_NSIG) if (hostsig == _NSIG + EXC_ARITHMETIC) return TARGET_EXC_ARITHMETIC; #endif #if defined (EXC_EMULATION) && defined (_NSIG) if (hostsig == _NSIG + EXC_EMULATION) return TARGET_EXC_EMULATION; #endif #if defined (EXC_SOFTWARE) && defined (_NSIG) if (hostsig == _NSIG + EXC_SOFTWARE) return TARGET_EXC_SOFTWARE; #endif #if defined (EXC_BREAKPOINT) && defined (_NSIG) if (hostsig == _NSIG + EXC_BREAKPOINT) return TARGET_EXC_BREAKPOINT; #endif #if defined (SIGINFO) if (hostsig == SIGINFO) return TARGET_SIGNAL_INFO; #endif #if defined (REALTIME_LO) if (hostsig >= REALTIME_LO && hostsig < REALTIME_HI) { /* This block of TARGET_SIGNAL_REALTIME value is in order. */ if (33 <= hostsig && hostsig <= 63) return (enum target_signal) (hostsig - 33 + (int) TARGET_SIGNAL_REALTIME_33); else if (hostsig == 32) return TARGET_SIGNAL_REALTIME_32; else if (64 <= hostsig && hostsig <= 127) return (enum target_signal) (hostsig - 64 + (int) TARGET_SIGNAL_REALTIME_64); else error (_("GDB bug: target.c (target_signal_from_host): " "unrecognized real-time signal")); } #endif return TARGET_SIGNAL_UNKNOWN; } /* Convert a OURSIG (an enum target_signal) to the form used by the target operating system (refered to as the ``host'') or zero if the equivalent host signal is not available. Set/clear OURSIG_OK accordingly. */ static int do_target_signal_to_host (enum target_signal oursig, int *oursig_ok) { int retsig; /* Silence the 'not used' warning, for targets that do not support signals. */ (void) retsig; *oursig_ok = 1; switch (oursig) { case TARGET_SIGNAL_0: return 0; #if defined (SIGHUP) case TARGET_SIGNAL_HUP: return SIGHUP; #endif #if defined (SIGINT) case TARGET_SIGNAL_INT: return SIGINT; #endif #if defined (SIGQUIT) case TARGET_SIGNAL_QUIT: return SIGQUIT; #endif #if defined (SIGILL) case TARGET_SIGNAL_ILL: return SIGILL; #endif #if defined (SIGTRAP) case TARGET_SIGNAL_TRAP: return SIGTRAP; #endif #if defined (SIGABRT) case TARGET_SIGNAL_ABRT: return SIGABRT; #endif #if defined (SIGEMT) case TARGET_SIGNAL_EMT: return SIGEMT; #endif #if defined (SIGFPE) case TARGET_SIGNAL_FPE: return SIGFPE; #endif #if defined (SIGKILL) case TARGET_SIGNAL_KILL: return SIGKILL; #endif #if defined (SIGBUS) case TARGET_SIGNAL_BUS: return SIGBUS; #endif #if defined (SIGSEGV) case TARGET_SIGNAL_SEGV: return SIGSEGV; #endif #if defined (SIGSYS) case TARGET_SIGNAL_SYS: return SIGSYS; #endif #if defined (SIGPIPE) case TARGET_SIGNAL_PIPE: return SIGPIPE; #endif #if defined (SIGALRM) case TARGET_SIGNAL_ALRM: return SIGALRM; #endif #if defined (SIGTERM) case TARGET_SIGNAL_TERM: return SIGTERM; #endif #if defined (SIGUSR1) case TARGET_SIGNAL_USR1: return SIGUSR1; #endif #if defined (SIGUSR2) case TARGET_SIGNAL_USR2: return SIGUSR2; #endif #if defined (SIGCHLD) || defined (SIGCLD) case TARGET_SIGNAL_CHLD: #if defined (SIGCHLD) return SIGCHLD; #else return SIGCLD; #endif #endif /* SIGCLD or SIGCHLD */ #if defined (SIGPWR) case TARGET_SIGNAL_PWR: return SIGPWR; #endif #if defined (SIGWINCH) case TARGET_SIGNAL_WINCH: return SIGWINCH; #endif #if defined (SIGURG) case TARGET_SIGNAL_URG: return SIGURG; #endif #if defined (SIGIO) case TARGET_SIGNAL_IO: return SIGIO; #endif #if defined (SIGPOLL) case TARGET_SIGNAL_POLL: return SIGPOLL; #endif #if defined (SIGSTOP) case TARGET_SIGNAL_STOP: return SIGSTOP; #endif #if defined (SIGTSTP) case TARGET_SIGNAL_TSTP: return SIGTSTP; #endif #if defined (SIGCONT) case TARGET_SIGNAL_CONT: return SIGCONT; #endif #if defined (SIGTTIN) case TARGET_SIGNAL_TTIN: return SIGTTIN; #endif #if defined (SIGTTOU) case TARGET_SIGNAL_TTOU: return SIGTTOU; #endif #if defined (SIGVTALRM) case TARGET_SIGNAL_VTALRM: return SIGVTALRM; #endif #if defined (SIGPROF) case TARGET_SIGNAL_PROF: return SIGPROF; #endif #if defined (SIGXCPU) case TARGET_SIGNAL_XCPU: return SIGXCPU; #endif #if defined (SIGXFSZ) case TARGET_SIGNAL_XFSZ: return SIGXFSZ; #endif #if defined (SIGWIND) case TARGET_SIGNAL_WIND: return SIGWIND; #endif #if defined (SIGPHONE) case TARGET_SIGNAL_PHONE: return SIGPHONE; #endif #if defined (SIGLOST) case TARGET_SIGNAL_LOST: return SIGLOST; #endif #if defined (SIGWAITING) case TARGET_SIGNAL_WAITING: return SIGWAITING; #endif #if defined (SIGCANCEL) case TARGET_SIGNAL_CANCEL: return SIGCANCEL; #endif #if defined (SIGLWP) case TARGET_SIGNAL_LWP: return SIGLWP; #endif #if defined (SIGDANGER) case TARGET_SIGNAL_DANGER: return SIGDANGER; #endif #if defined (SIGGRANT) case TARGET_SIGNAL_GRANT: return SIGGRANT; #endif #if defined (SIGRETRACT) case TARGET_SIGNAL_RETRACT: return SIGRETRACT; #endif #if defined (SIGMSG) case TARGET_SIGNAL_MSG: return SIGMSG; #endif #if defined (SIGSOUND) case TARGET_SIGNAL_SOUND: return SIGSOUND; #endif #if defined (SIGSAK) case TARGET_SIGNAL_SAK: return SIGSAK; #endif #if defined (SIGPRIO) case TARGET_SIGNAL_PRIO: return SIGPRIO; #endif /* Mach exceptions. Assumes that the values for EXC_ are positive! */ #if defined (EXC_BAD_ACCESS) && defined (_NSIG) case TARGET_EXC_BAD_ACCESS: return _NSIG + EXC_BAD_ACCESS; #endif #if defined (EXC_BAD_INSTRUCTION) && defined (_NSIG) case TARGET_EXC_BAD_INSTRUCTION: return _NSIG + EXC_BAD_INSTRUCTION; #endif #if defined (EXC_ARITHMETIC) && defined (_NSIG) case TARGET_EXC_ARITHMETIC: return _NSIG + EXC_ARITHMETIC; #endif #if defined (EXC_EMULATION) && defined (_NSIG) case TARGET_EXC_EMULATION: return _NSIG + EXC_EMULATION; #endif #if defined (EXC_SOFTWARE) && defined (_NSIG) case TARGET_EXC_SOFTWARE: return _NSIG + EXC_SOFTWARE; #endif #if defined (EXC_BREAKPOINT) && defined (_NSIG) case TARGET_EXC_BREAKPOINT: return _NSIG + EXC_BREAKPOINT; #endif #if defined (SIGINFO) case TARGET_SIGNAL_INFO: return SIGINFO; #endif default: #if defined (REALTIME_LO) retsig = 0; if (oursig >= TARGET_SIGNAL_REALTIME_33 && oursig <= TARGET_SIGNAL_REALTIME_63) { /* This block of signals is continuous, and TARGET_SIGNAL_REALTIME_33 is 33 by definition. */ retsig = (int) oursig - (int) TARGET_SIGNAL_REALTIME_33 + 33; } else if (oursig == TARGET_SIGNAL_REALTIME_32) { /* TARGET_SIGNAL_REALTIME_32 isn't contiguous with TARGET_SIGNAL_REALTIME_33. It is 32 by definition. */ retsig = 32; } else if (oursig >= TARGET_SIGNAL_REALTIME_64 && oursig <= TARGET_SIGNAL_REALTIME_127) { /* This block of signals is continuous, and TARGET_SIGNAL_REALTIME_64 is 64 by definition. */ retsig = (int) oursig - (int) TARGET_SIGNAL_REALTIME_64 + 64; } if (retsig >= REALTIME_LO && retsig < REALTIME_HI) return retsig; #endif *oursig_ok = 0; return 0; } } int target_signal_to_host_p (enum target_signal oursig) { int oursig_ok; do_target_signal_to_host (oursig, &oursig_ok); return oursig_ok; } int target_signal_to_host (enum target_signal oursig) { int oursig_ok; int targ_signo = do_target_signal_to_host (oursig, &oursig_ok); if (!oursig_ok) { /* The user might be trying to do "signal SIGSAK" where this system doesn't have SIGSAK. */ warning (_("Signal %s does not exist on this system."), target_signal_to_name (oursig)); return 0; } else return targ_signo; } #ifndef GDBSERVER /* In some circumstances we allow a command to specify a numeric signal. The idea is to keep these circumstances limited so that users (and scripts) develop portable habits. For comparison, POSIX.2 `kill' requires that 1,2,3,6,9,14, and 15 work (and using a numeric signal at all is obsolescent. We are slightly more lenient and allow 1-15 which should match host signal numbers on most systems. Use of symbolic signal names is strongly encouraged. */ enum target_signal target_signal_from_command (int num) { if (num >= 1 && num <= 15) return (enum target_signal) num; error (_("Only signals 1-15 are valid as numeric signals.\n\ Use \"info signals\" for a list of symbolic signals.")); } extern initialize_file_ftype _initialize_signals; /* -Wmissing-prototype */ void _initialize_signals (void) { if (strcmp (signals[TARGET_SIGNAL_LAST].string, "TARGET_SIGNAL_MAGIC") != 0) internal_error (__FILE__, __LINE__, "failed internal consistency check"); } int default_target_signal_to_host (struct gdbarch *gdbarch, enum target_signal ts) { return target_signal_to_host (ts); } enum target_signal default_target_signal_from_host (struct gdbarch *gdbarch, int signo) { return target_signal_from_host (signo); } #endif /* ! GDBSERVER */
Lydux/gdb-7.4-human68k
gdb/common/signals.c
C
gpl-2.0
17,023
# # (C) Copyright 2001-2006 # Wolfgang Denk, DENX Software Engineering, [email protected]. # # SPDX-License-Identifier: GPL-2.0+ # include $(TOPDIR)/config.mk LIB = $(obj)lib$(BOARD).o COBJS = $(BOARD).o m48t59y.o pci.o flash.o SRCS := $(SOBJS:.o=.S) $(COBJS:.o=.c) OBJS := $(addprefix $(obj),$(COBJS)) SOBJS := $(addprefix $(obj),$(SOBJS)) $(LIB): $(obj).depend $(OBJS) $(call cmd_link_o_target, $(OBJS)) ######################################################################### # defines $(obj).depend target include $(SRCTREE)/rules.mk sinclude $(obj).depend #########################################################################
luckyboy/uboot
u-boot-2013.10/board/mousse/Makefile
Makefile
gpl-2.0
639
#include<Foundation/Foundation.h> @import GameKit; @import JavaScriptCore; @protocol JSBNSObject; @protocol JSBGKMatchmaker <JSExport, JSBNSObject> #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" @property (readonly, retain) NSString *inviter; @property (readonly, getter = isHosted) BOOL hosted; @property (readonly, nonatomic, assign) uint32_t playerAttributes; @property (nonatomic, copy) void (^inviteHandler)(GKInvite *acceptedInvite, NSArray *playerIDsToInvite); @property (nonatomic, assign) NSUInteger maxPlayers; @property (nonatomic, assign) NSUInteger defaultNumberOfPlayers; @property (nonatomic, copy) void (^inviteeResponseHandler)(NSString *playerID, GKInviteeResponse response); @property (nonatomic, retain) NSArray *playersToInvite; @property (readonly, nonatomic, assign) NSUInteger playerGroup; @property (nonatomic, assign) NSUInteger minPlayers; @property (nonatomic, copy) NSString *inviteMessage; + (GKMatchmaker *)sharedMatchmaker; - (void)matchForInvite:(GKInvite *)invite completionHandler:(void (^)(GKMatch *match , NSError *error))completionHandler; - (void)findMatchForRequest:(GKMatchRequest *)request withCompletionHandler:(void (^)(GKMatch *match , NSError *error))completionHandler; - (void)findPlayersForHostedMatchRequest:(GKMatchRequest *)request withCompletionHandler:(void (^)(NSArray *playerIDs , NSError *error))completionHandler; - (void)addPlayersToMatch:(GKMatch *)match matchRequest:(GKMatchRequest *)matchRequest completionHandler:(void (^)(NSError *error))completionHandler; - (void)cancel; - (void)cancelInviteToPlayer:(NSString *)playerID; - (void)finishMatchmakingForMatch:(GKMatch *)match; - (void)queryPlayerGroupActivity:(NSUInteger)playerGroup withCompletionHandler:(void (^)(NSInteger activity , NSError *error))completionHandler; - (void)queryActivityWithCompletionHandler:(void (^)(NSInteger activity , NSError *error))completionHandler; - (void)startBrowsingForNearbyPlayersWithReachableHandler:(void (^)(NSString *playerID , BOOL reachable))reachableHandler; - (void)stopBrowsingForNearbyPlayers; #pragma clang diagnostic pop @end
zikong/javascriptcore
Pods/JavaScriptBridge/Classes/iOS/FrameworkSupport/GameKit/JSBGKMatchmaker.h
C
gpl-2.0
2,142
/* audit.c -- Auditing support * Gateway between the kernel (e.g., selinux) and the user-space audit daemon. * System-call specific features have moved to auditsc.c * * Copyright 2003-2007 Red Hat Inc., Durham, North Carolina. * All Rights Reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; 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 * * Written by Rickard E. (Rik) Faith <[email protected]> * * Goals: 1) Integrate fully with Security Modules. * 2) Minimal run-time overhead: * a) Minimal when syscall auditing is disabled (audit_enable=0). * b) Small when syscall auditing is enabled and no audit record * is generated (defer as much work as possible to record * generation time): * i) context is allocated, * ii) names from getname are stored without a copy, and * iii) inode information stored from path_lookup. * 3) Ability to disable syscall auditing at boot time (audit=0). * 4) Usable by other parts of the kernel (if audit_log* is called, * then a syscall record will be generated automatically for the * current syscall). * 5) Netlink interface to user-space. * 6) Support low-overhead kernel-based filtering to minimize the * information that must be passed to user-space. * * Example user-space utilities: http://people.redhat.com/sgrubb/audit/ */ #include <linux/init.h> #include <asm/types.h> #include <linux/atomic.h> #include <linux/mm.h> #include <linux/export.h> #include <linux/slab.h> #include <linux/err.h> #include <linux/kthread.h> #include <linux/audit.h> #include <net/sock.h> #include <net/netlink.h> #include <linux/skbuff.h> #ifdef CONFIG_SECURITY #include <linux/security.h> #endif #include <linux/netlink.h> #include <linux/freezer.h> #include <linux/tty.h> #include "audit.h" /* No auditing will take place until audit_initialized == AUDIT_INITIALIZED. * (Initialization happens after skb_init is called.) */ #define AUDIT_DISABLED -1 #define AUDIT_UNINITIALIZED 0 #define AUDIT_INITIALIZED 1 static int audit_initialized; #define AUDIT_OFF 0 #define AUDIT_ON 1 #define AUDIT_LOCKED 2 int audit_enabled; int audit_ever_enabled; EXPORT_SYMBOL_GPL(audit_enabled); /* Default state when kernel boots without any parameters. */ static int audit_default; /* If auditing cannot proceed, audit_failure selects what happens. */ static int audit_failure = AUDIT_FAIL_PRINTK; /* * If audit records are to be written to the netlink socket, audit_pid * contains the pid of the auditd process and audit_nlk_pid contains * the pid to use to send netlink messages to that process. */ int audit_pid; static int audit_nlk_pid; /* If audit_rate_limit is non-zero, limit the rate of sending audit records * to that number per second. This prevents DoS attacks, but results in * audit records being dropped. */ static int audit_rate_limit; /* Number of outstanding audit_buffers allowed. */ static int audit_backlog_limit = 64; static int audit_backlog_wait_time = 60 * HZ; static int audit_backlog_wait_overflow = 0; /* The identity of the user shutting down the audit system. */ uid_t audit_sig_uid = -1; pid_t audit_sig_pid = -1; u32 audit_sig_sid = 0; /* Records can be lost in several ways: 0) [suppressed in audit_alloc] 1) out of memory in audit_log_start [kmalloc of struct audit_buffer] 2) out of memory in audit_log_move [alloc_skb] 3) suppressed due to audit_rate_limit 4) suppressed due to audit_backlog_limit */ static atomic_t audit_lost = ATOMIC_INIT(0); /* The netlink socket. */ static struct sock *audit_sock; /* Hash for inode-based rules */ struct list_head audit_inode_hash[AUDIT_INODE_BUCKETS]; /* The audit_freelist is a list of pre-allocated audit buffers (if more * than AUDIT_MAXFREE are in use, the audit buffer is freed instead of * being placed on the freelist). */ static DEFINE_SPINLOCK(audit_freelist_lock); static int audit_freelist_count; static LIST_HEAD(audit_freelist); static struct sk_buff_head audit_skb_queue; /* queue of skbs to send to auditd when/if it comes back */ static struct sk_buff_head audit_skb_hold_queue; static struct task_struct *kauditd_task; static DECLARE_WAIT_QUEUE_HEAD(kauditd_wait); static DECLARE_WAIT_QUEUE_HEAD(audit_backlog_wait); /* Serialize requests from userspace. */ DEFINE_MUTEX(audit_cmd_mutex); /* AUDIT_BUFSIZ is the size of the temporary buffer used for formatting * audit records. Since printk uses a 1024 byte buffer, this buffer * should be at least that large. */ #define AUDIT_BUFSIZ 1024 /* AUDIT_MAXFREE is the number of empty audit_buffers we keep on the * audit_freelist. Doing so eliminates many kmalloc/kfree calls. */ #define AUDIT_MAXFREE (2*NR_CPUS) /* The audit_buffer is used when formatting an audit record. The caller * locks briefly to get the record off the freelist or to allocate the * buffer, and locks briefly to send the buffer to the netlink layer or * to place it on a transmit queue. Multiple audit_buffers can be in * use simultaneously. */ struct audit_buffer { struct list_head list; struct sk_buff *skb; /* formatted skb ready to send */ struct audit_context *ctx; /* NULL or associated context */ gfp_t gfp_mask; }; struct audit_reply { int pid; struct sk_buff *skb; }; static void audit_set_pid(struct audit_buffer *ab, pid_t pid) { if (ab) { struct nlmsghdr *nlh = nlmsg_hdr(ab->skb); nlh->nlmsg_pid = pid; } } void audit_panic(const char *message) { switch (audit_failure) { case AUDIT_FAIL_SILENT: break; case AUDIT_FAIL_PRINTK: if (printk_ratelimit()) printk(KERN_ERR "audit: %s\n", message); break; case AUDIT_FAIL_PANIC: /* test audit_pid since printk is always losey, why bother? */ if (audit_pid) panic("audit: %s\n", message); break; } } static inline int audit_rate_check(void) { static unsigned long last_check = 0; static int messages = 0; static DEFINE_SPINLOCK(lock); unsigned long flags; unsigned long now; unsigned long elapsed; int retval = 0; if (!audit_rate_limit) return 1; spin_lock_irqsave(&lock, flags); if (++messages < audit_rate_limit) { retval = 1; } else { now = jiffies; elapsed = now - last_check; if (elapsed > HZ) { last_check = now; messages = 0; retval = 1; } } spin_unlock_irqrestore(&lock, flags); return retval; } /** * audit_log_lost - conditionally log lost audit message event * @message: the message stating reason for lost audit message * * Emit at least 1 message per second, even if audit_rate_check is * throttling. * Always increment the lost messages counter. */ void audit_log_lost(const char *message) { static unsigned long last_msg = 0; static DEFINE_SPINLOCK(lock); unsigned long flags; unsigned long now; int print; atomic_inc(&audit_lost); print = (audit_failure == AUDIT_FAIL_PANIC || !audit_rate_limit); if (!print) { spin_lock_irqsave(&lock, flags); now = jiffies; if (now - last_msg > HZ) { print = 1; last_msg = now; } spin_unlock_irqrestore(&lock, flags); } if (print) { if (printk_ratelimit()) printk(KERN_WARNING "audit: audit_lost=%d audit_rate_limit=%d " "audit_backlog_limit=%d\n", atomic_read(&audit_lost), audit_rate_limit, audit_backlog_limit); audit_panic(message); } } static int audit_log_config_change(char *function_name, int new, int old, uid_t loginuid, u32 sessionid, u32 sid, int allow_changes) { struct audit_buffer *ab; int rc = 0; ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE); audit_log_format(ab, "%s=%d old=%d auid=%u ses=%u", function_name, new, old, loginuid, sessionid); if (sid) { char *ctx = NULL; u32 len; rc = security_secid_to_secctx(sid, &ctx, &len); if (rc) { audit_log_format(ab, " sid=%u", sid); allow_changes = 0; /* Something weird, deny request */ } else { audit_log_format(ab, " subj=%s", ctx); security_release_secctx(ctx, len); } } audit_log_format(ab, " res=%d", allow_changes); audit_log_end(ab); return rc; } static int audit_do_config_change(char *function_name, int *to_change, int new, uid_t loginuid, u32 sessionid, u32 sid) { int allow_changes, rc = 0, old = *to_change; /* check if we are locked */ if (audit_enabled == AUDIT_LOCKED) allow_changes = 0; else allow_changes = 1; if (audit_enabled != AUDIT_OFF) { rc = audit_log_config_change(function_name, new, old, loginuid, sessionid, sid, allow_changes); if (rc) allow_changes = 0; } /* If we are allowed, make the change */ if (allow_changes == 1) *to_change = new; /* Not allowed, update reason */ else if (rc == 0) rc = -EPERM; return rc; } static int audit_set_rate_limit(int limit, uid_t loginuid, u32 sessionid, u32 sid) { return audit_do_config_change("audit_rate_limit", &audit_rate_limit, limit, loginuid, sessionid, sid); } static int audit_set_backlog_limit(int limit, uid_t loginuid, u32 sessionid, u32 sid) { return audit_do_config_change("audit_backlog_limit", &audit_backlog_limit, limit, loginuid, sessionid, sid); } static int audit_set_enabled(int state, uid_t loginuid, u32 sessionid, u32 sid) { int rc; if (state < AUDIT_OFF || state > AUDIT_LOCKED) return -EINVAL; rc = audit_do_config_change("audit_enabled", &audit_enabled, state, loginuid, sessionid, sid); if (!rc) audit_ever_enabled |= !!state; return rc; } static int audit_set_failure(int state, uid_t loginuid, u32 sessionid, u32 sid) { if (state != AUDIT_FAIL_SILENT && state != AUDIT_FAIL_PRINTK && state != AUDIT_FAIL_PANIC) return -EINVAL; return audit_do_config_change("audit_failure", &audit_failure, state, loginuid, sessionid, sid); } /* * Queue skbs to be sent to auditd when/if it comes back. These skbs should * already have been sent via prink/syslog and so if these messages are dropped * it is not a huge concern since we already passed the audit_log_lost() * notification and stuff. This is just nice to get audit messages during * boot before auditd is running or messages generated while auditd is stopped. * This only holds messages is audit_default is set, aka booting with audit=1 * or building your kernel that way. */ static void audit_hold_skb(struct sk_buff *skb) { if (audit_default && skb_queue_len(&audit_skb_hold_queue) < audit_backlog_limit) skb_queue_tail(&audit_skb_hold_queue, skb); else kfree_skb(skb); } /* * For one reason or another this nlh isn't getting delivered to the userspace * audit daemon, just send it to printk. */ static void audit_printk_skb(struct sk_buff *skb) { struct nlmsghdr *nlh = nlmsg_hdr(skb); char *data = NLMSG_DATA(nlh); if (nlh->nlmsg_type != AUDIT_EOE) { if (printk_ratelimit()) printk(KERN_NOTICE "type=%d %s\n", nlh->nlmsg_type, data); else audit_log_lost("printk limit exceeded\n"); } audit_hold_skb(skb); } static void kauditd_send_skb(struct sk_buff *skb) { int err; /* take a reference in case we can't send it and we want to hold it */ skb_get(skb); err = netlink_unicast(audit_sock, skb, audit_nlk_pid, 0); if (err < 0) { BUG_ON(err != -ECONNREFUSED); /* Shouldn't happen */ printk(KERN_ERR "audit: *NO* daemon at audit_pid=%d\n", audit_pid); audit_log_lost("auditd disappeared\n"); audit_pid = 0; /* we might get lucky and get this in the next auditd */ audit_hold_skb(skb); } else /* drop the extra reference if sent ok */ consume_skb(skb); } static int kauditd_thread(void *dummy) { struct sk_buff *skb; set_freezable(); while (!kthread_should_stop()) { /* * if auditd just started drain the queue of messages already * sent to syslog/printk. remember loss here is ok. we already * called audit_log_lost() if it didn't go out normally. so the * race between the skb_dequeue and the next check for audit_pid * doesn't matter. * * if you ever find kauditd to be too slow we can get a perf win * by doing our own locking and keeping better track if there * are messages in this queue. I don't see the need now, but * in 5 years when I want to play with this again I'll see this * note and still have no friggin idea what i'm thinking today. */ if (audit_default && audit_pid) { skb = skb_dequeue(&audit_skb_hold_queue); if (unlikely(skb)) { while (skb && audit_pid) { kauditd_send_skb(skb); skb = skb_dequeue(&audit_skb_hold_queue); } } } skb = skb_dequeue(&audit_skb_queue); wake_up(&audit_backlog_wait); if (skb) { if (audit_pid) kauditd_send_skb(skb); else audit_printk_skb(skb); } else { DECLARE_WAITQUEUE(wait, current); set_current_state(TASK_INTERRUPTIBLE); add_wait_queue(&kauditd_wait, &wait); if (!skb_queue_len(&audit_skb_queue)) { try_to_freeze(); schedule(); } __set_current_state(TASK_RUNNING); remove_wait_queue(&kauditd_wait, &wait); } } return 0; } static int audit_prepare_user_tty(pid_t pid, uid_t loginuid, u32 sessionid) { struct task_struct *tsk; int err; rcu_read_lock(); tsk = find_task_by_vpid(pid); if (!tsk) { rcu_read_unlock(); return -ESRCH; } get_task_struct(tsk); rcu_read_unlock(); err = tty_audit_push_task(tsk, loginuid, sessionid); put_task_struct(tsk); return err; } int audit_send_list(void *_dest) { struct audit_netlink_list *dest = _dest; int pid = dest->pid; struct sk_buff *skb; /* wait for parent to finish and send an ACK */ mutex_lock(&audit_cmd_mutex); mutex_unlock(&audit_cmd_mutex); while ((skb = __skb_dequeue(&dest->q)) != NULL) netlink_unicast(audit_sock, skb, pid, 0); kfree(dest); return 0; } struct sk_buff *audit_make_reply(int pid, int seq, int type, int done, int multi, const void *payload, int size) { struct sk_buff *skb; struct nlmsghdr *nlh; void *data; int flags = multi ? NLM_F_MULTI : 0; int t = done ? NLMSG_DONE : type; skb = nlmsg_new(size, GFP_KERNEL); if (!skb) return NULL; nlh = NLMSG_NEW(skb, pid, seq, t, size, flags); data = NLMSG_DATA(nlh); memcpy(data, payload, size); return skb; nlmsg_failure: /* Used by NLMSG_NEW */ if (skb) kfree_skb(skb); return NULL; } static int audit_send_reply_thread(void *arg) { struct audit_reply *reply = (struct audit_reply *)arg; mutex_lock(&audit_cmd_mutex); mutex_unlock(&audit_cmd_mutex); /* Ignore failure. It'll only happen if the sender goes away, because our timeout is set to infinite. */ netlink_unicast(audit_sock, reply->skb, reply->pid, 0); kfree(reply); return 0; } /** * audit_send_reply - send an audit reply message via netlink * @pid: process id to send reply to * @seq: sequence number * @type: audit message type * @done: done (last) flag * @multi: multi-part message flag * @payload: payload data * @size: payload size * * Allocates an skb, builds the netlink message, and sends it to the pid. * No failure notifications. */ static void audit_send_reply(int pid, int seq, int type, int done, int multi, const void *payload, int size) { struct sk_buff *skb; struct task_struct *tsk; struct audit_reply *reply = kmalloc(sizeof(struct audit_reply), GFP_KERNEL); if (!reply) return; skb = audit_make_reply(pid, seq, type, done, multi, payload, size); if (!skb) goto out; reply->pid = pid; reply->skb = skb; tsk = kthread_run(audit_send_reply_thread, reply, "audit_send_reply"); if (!IS_ERR(tsk)) return; kfree_skb(skb); out: kfree(reply); } /* * Check for appropriate CAP_AUDIT_ capabilities on incoming audit * control messages. */ static int audit_netlink_ok(struct sk_buff *skb, u16 msg_type) { int err = 0; switch (msg_type) { case AUDIT_GET: case AUDIT_LIST: case AUDIT_LIST_RULES: case AUDIT_SET: case AUDIT_ADD: case AUDIT_ADD_RULE: case AUDIT_DEL: case AUDIT_DEL_RULE: case AUDIT_SIGNAL_INFO: case AUDIT_TTY_GET: case AUDIT_TTY_SET: case AUDIT_TRIM: case AUDIT_MAKE_EQUIV: if (!capable(CAP_AUDIT_CONTROL)) err = -EPERM; break; case AUDIT_USER: case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG: case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2: if (!capable(CAP_AUDIT_WRITE)) err = -EPERM; break; default: /* bad msg */ err = -EINVAL; } return err; } static int audit_log_common_recv_msg(struct audit_buffer **ab, u16 msg_type, u32 pid, u32 uid, uid_t auid, u32 ses, u32 sid) { int rc = 0; char *ctx = NULL; u32 len; if (!audit_enabled) { *ab = NULL; return rc; } *ab = audit_log_start(NULL, GFP_KERNEL, msg_type); audit_log_format(*ab, "pid=%d uid=%u auid=%u ses=%u", pid, uid, auid, ses); if (sid) { rc = security_secid_to_secctx(sid, &ctx, &len); if (rc) audit_log_format(*ab, " ssid=%u", sid); else { audit_log_format(*ab, " subj=%s", ctx); security_release_secctx(ctx, len); } } return rc; } static int audit_receive_msg(struct sk_buff *skb, struct nlmsghdr *nlh) { u32 uid, pid, seq, sid; void *data; struct audit_status *status_get, status_set; int err; struct audit_buffer *ab; u16 msg_type = nlh->nlmsg_type; uid_t loginuid; /* loginuid of sender */ u32 sessionid; struct audit_sig_info *sig_data; char *ctx = NULL; u32 len; err = audit_netlink_ok(skb, msg_type); if (err) return err; /* As soon as there's any sign of userspace auditd, * start kauditd to talk to it */ if (!kauditd_task) kauditd_task = kthread_run(kauditd_thread, NULL, "kauditd"); if (IS_ERR(kauditd_task)) { err = PTR_ERR(kauditd_task); kauditd_task = NULL; return err; } pid = NETLINK_CREDS(skb)->pid; uid = NETLINK_CREDS(skb)->uid; loginuid = audit_get_loginuid(current); sessionid = audit_get_sessionid(current); security_task_getsecid(current, &sid); seq = nlh->nlmsg_seq; data = NLMSG_DATA(nlh); switch (msg_type) { case AUDIT_GET: status_set.enabled = audit_enabled; status_set.failure = audit_failure; status_set.pid = audit_pid; status_set.rate_limit = audit_rate_limit; status_set.backlog_limit = audit_backlog_limit; status_set.lost = atomic_read(&audit_lost); status_set.backlog = skb_queue_len(&audit_skb_queue); audit_send_reply(NETLINK_CB(skb).pid, seq, AUDIT_GET, 0, 0, &status_set, sizeof(status_set)); break; case AUDIT_SET: if (nlh->nlmsg_len < sizeof(struct audit_status)) return -EINVAL; status_get = (struct audit_status *)data; if (status_get->mask & AUDIT_STATUS_ENABLED) { err = audit_set_enabled(status_get->enabled, loginuid, sessionid, sid); if (err < 0) return err; } if (status_get->mask & AUDIT_STATUS_FAILURE) { err = audit_set_failure(status_get->failure, loginuid, sessionid, sid); if (err < 0) return err; } if (status_get->mask & AUDIT_STATUS_PID) { int new_pid = status_get->pid; if (audit_enabled != AUDIT_OFF) audit_log_config_change("audit_pid", new_pid, audit_pid, loginuid, sessionid, sid, 1); audit_pid = new_pid; audit_nlk_pid = NETLINK_CB(skb).pid; } if (status_get->mask & AUDIT_STATUS_RATE_LIMIT) { err = audit_set_rate_limit(status_get->rate_limit, loginuid, sessionid, sid); if (err < 0) return err; } if (status_get->mask & AUDIT_STATUS_BACKLOG_LIMIT) err = audit_set_backlog_limit(status_get->backlog_limit, loginuid, sessionid, sid); break; case AUDIT_USER: case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG: case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2: if (!audit_enabled && msg_type != AUDIT_USER_AVC) return 0; err = audit_filter_user(&NETLINK_CB(skb)); if (err == 1) { err = 0; if (msg_type == AUDIT_USER_TTY) { err = audit_prepare_user_tty(pid, loginuid, sessionid); if (err) break; } audit_log_common_recv_msg(&ab, msg_type, pid, uid, loginuid, sessionid, sid); if (msg_type != AUDIT_USER_TTY) audit_log_format(ab, " msg='%.1024s'", (char *)data); else { int size; audit_log_format(ab, " msg="); size = nlmsg_len(nlh); if (size > 0 && ((unsigned char *)data)[size - 1] == '\0') size--; audit_log_n_untrustedstring(ab, data, size); } audit_set_pid(ab, pid); audit_log_end(ab); } break; case AUDIT_ADD: case AUDIT_DEL: if (nlmsg_len(nlh) < sizeof(struct audit_rule)) return -EINVAL; if (audit_enabled == AUDIT_LOCKED) { audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE, pid, uid, loginuid, sessionid, sid); audit_log_format(ab, " audit_enabled=%d res=0", audit_enabled); audit_log_end(ab); return -EPERM; } /* fallthrough */ case AUDIT_LIST: err = audit_receive_filter(msg_type, NETLINK_CB(skb).pid, uid, seq, data, nlmsg_len(nlh), loginuid, sessionid, sid); break; case AUDIT_ADD_RULE: case AUDIT_DEL_RULE: if (nlmsg_len(nlh) < sizeof(struct audit_rule_data)) return -EINVAL; if (audit_enabled == AUDIT_LOCKED) { audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE, pid, uid, loginuid, sessionid, sid); audit_log_format(ab, " audit_enabled=%d res=0", audit_enabled); audit_log_end(ab); return -EPERM; } /* fallthrough */ case AUDIT_LIST_RULES: err = audit_receive_filter(msg_type, NETLINK_CB(skb).pid, uid, seq, data, nlmsg_len(nlh), loginuid, sessionid, sid); break; case AUDIT_TRIM: audit_trim_trees(); audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE, pid, uid, loginuid, sessionid, sid); audit_log_format(ab, " op=trim res=1"); audit_log_end(ab); break; case AUDIT_MAKE_EQUIV: { void *bufp = data; u32 sizes[2]; size_t msglen = nlmsg_len(nlh); char *old, *new; err = -EINVAL; if (msglen < 2 * sizeof(u32)) break; memcpy(sizes, bufp, 2 * sizeof(u32)); bufp += 2 * sizeof(u32); msglen -= 2 * sizeof(u32); old = audit_unpack_string(&bufp, &msglen, sizes[0]); if (IS_ERR(old)) { err = PTR_ERR(old); break; } new = audit_unpack_string(&bufp, &msglen, sizes[1]); if (IS_ERR(new)) { err = PTR_ERR(new); kfree(old); break; } /* OK, here comes... */ err = audit_tag_tree(old, new); audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE, pid, uid, loginuid, sessionid, sid); audit_log_format(ab, " op=make_equiv old="); audit_log_untrustedstring(ab, old); audit_log_format(ab, " new="); audit_log_untrustedstring(ab, new); audit_log_format(ab, " res=%d", !err); audit_log_end(ab); kfree(old); kfree(new); break; } case AUDIT_SIGNAL_INFO: len = 0; if (audit_sig_sid) { err = security_secid_to_secctx(audit_sig_sid, &ctx, &len); if (err) return err; } sig_data = kmalloc(sizeof(*sig_data) + len, GFP_KERNEL); if (!sig_data) { if (audit_sig_sid) security_release_secctx(ctx, len); return -ENOMEM; } sig_data->uid = audit_sig_uid; sig_data->pid = audit_sig_pid; if (audit_sig_sid) { memcpy(sig_data->ctx, ctx, len); security_release_secctx(ctx, len); } audit_send_reply(NETLINK_CB(skb).pid, seq, AUDIT_SIGNAL_INFO, 0, 0, sig_data, sizeof(*sig_data) + len); kfree(sig_data); break; case AUDIT_TTY_GET: { struct audit_tty_status s; struct task_struct *tsk; unsigned long flags; rcu_read_lock(); tsk = find_task_by_vpid(pid); if (tsk && lock_task_sighand(tsk, &flags)) { s.enabled = tsk->signal->audit_tty != 0; unlock_task_sighand(tsk, &flags); } else err = -ESRCH; rcu_read_unlock(); if (!err) audit_send_reply(NETLINK_CB(skb).pid, seq, AUDIT_TTY_GET, 0, 0, &s, sizeof(s)); break; } case AUDIT_TTY_SET: { struct audit_tty_status *s; struct task_struct *tsk; unsigned long flags; if (nlh->nlmsg_len < sizeof(struct audit_tty_status)) return -EINVAL; s = data; if (s->enabled != 0 && s->enabled != 1) return -EINVAL; rcu_read_lock(); tsk = find_task_by_vpid(pid); if (tsk && lock_task_sighand(tsk, &flags)) { tsk->signal->audit_tty = s->enabled != 0; unlock_task_sighand(tsk, &flags); } else err = -ESRCH; rcu_read_unlock(); break; } default: err = -EINVAL; break; } return err < 0 ? err : 0; } /* * Get message from skb. Each message is processed by audit_receive_msg. * Malformed skbs with wrong length are discarded silently. */ static void audit_receive_skb(struct sk_buff *skb) { struct nlmsghdr *nlh; /* * len MUST be signed for NLMSG_NEXT to be able to dec it below 0 * if the nlmsg_len was not aligned */ int len; int err; nlh = nlmsg_hdr(skb); len = skb->len; while (NLMSG_OK(nlh, len)) { err = audit_receive_msg(skb, nlh); /* if err or if this message says it wants a response */ if (err || (nlh->nlmsg_flags & NLM_F_ACK)) netlink_ack(skb, nlh, err); nlh = NLMSG_NEXT(nlh, len); } } /* Receive messages from netlink socket. */ static void audit_receive(struct sk_buff *skb) { mutex_lock(&audit_cmd_mutex); audit_receive_skb(skb); mutex_unlock(&audit_cmd_mutex); } /* Initialize audit support at boot time. */ static int __init audit_init(void) { int i; if (audit_initialized == AUDIT_DISABLED) return 0; printk(KERN_INFO "audit: initializing netlink socket (%s)\n", audit_default ? "enabled" : "disabled"); audit_sock = netlink_kernel_create(&init_net, NETLINK_AUDIT, 0, audit_receive, NULL, THIS_MODULE); if (!audit_sock) audit_panic("cannot initialize netlink socket"); else audit_sock->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT; skb_queue_head_init(&audit_skb_queue); skb_queue_head_init(&audit_skb_hold_queue); audit_initialized = AUDIT_INITIALIZED; audit_enabled = audit_default; audit_ever_enabled |= !!audit_default; audit_log(NULL, GFP_KERNEL, AUDIT_KERNEL, "initialized"); for (i = 0; i < AUDIT_INODE_BUCKETS; i++) INIT_LIST_HEAD(&audit_inode_hash[i]); return 0; } __initcall(audit_init); /* Process kernel command-line parameter at boot time. audit=0 or audit=1. */ static int __init audit_enable(char *str) { audit_default = !!simple_strtol(str, NULL, 0); if (!audit_default) audit_initialized = AUDIT_DISABLED; printk(KERN_INFO "audit: %s", audit_default ? "enabled" : "disabled"); if (audit_initialized == AUDIT_INITIALIZED) { audit_enabled = audit_default; audit_ever_enabled |= !!audit_default; } else if (audit_initialized == AUDIT_UNINITIALIZED) { printk(" (after initialization)"); } else { printk(" (until reboot)"); } printk("\n"); return 1; } __setup("audit=", audit_enable); static void audit_buffer_free(struct audit_buffer *ab) { unsigned long flags; if (!ab) return; if (ab->skb) kfree_skb(ab->skb); spin_lock_irqsave(&audit_freelist_lock, flags); if (audit_freelist_count > AUDIT_MAXFREE) kfree(ab); else { audit_freelist_count++; list_add(&ab->list, &audit_freelist); } spin_unlock_irqrestore(&audit_freelist_lock, flags); } static struct audit_buffer * audit_buffer_alloc(struct audit_context *ctx, gfp_t gfp_mask, int type) { unsigned long flags; struct audit_buffer *ab = NULL; struct nlmsghdr *nlh; spin_lock_irqsave(&audit_freelist_lock, flags); if (!list_empty(&audit_freelist)) { ab = list_entry(audit_freelist.next, struct audit_buffer, list); list_del(&ab->list); --audit_freelist_count; } spin_unlock_irqrestore(&audit_freelist_lock, flags); if (!ab) { ab = kmalloc(sizeof(*ab), gfp_mask); if (!ab) goto err; } ab->ctx = ctx; ab->gfp_mask = gfp_mask; ab->skb = nlmsg_new(AUDIT_BUFSIZ, gfp_mask); if (!ab->skb) goto nlmsg_failure; nlh = NLMSG_NEW(ab->skb, 0, 0, type, 0, 0); return ab; nlmsg_failure: /* Used by NLMSG_NEW */ kfree_skb(ab->skb); ab->skb = NULL; err: audit_buffer_free(ab); return NULL; } /** * audit_serial - compute a serial number for the audit record * * Compute a serial number for the audit record. Audit records are * written to user-space as soon as they are generated, so a complete * audit record may be written in several pieces. The timestamp of the * record and this serial number are used by the user-space tools to * determine which pieces belong to the same audit record. The * (timestamp,serial) tuple is unique for each syscall and is live from * syscall entry to syscall exit. * * NOTE: Another possibility is to store the formatted records off the * audit context (for those records that have a context), and emit them * all at syscall exit. However, this could delay the reporting of * significant errors until syscall exit (or never, if the system * halts). */ unsigned int audit_serial(void) { static DEFINE_SPINLOCK(serial_lock); static unsigned int serial = 0; unsigned long flags; unsigned int ret; spin_lock_irqsave(&serial_lock, flags); do { ret = ++serial; } while (unlikely(!ret)); spin_unlock_irqrestore(&serial_lock, flags); return ret; } static inline void audit_get_stamp(struct audit_context *ctx, struct timespec *t, unsigned int *serial) { if (!ctx || !auditsc_get_stamp(ctx, t, serial)) { *t = CURRENT_TIME; *serial = audit_serial(); } } /* Obtain an audit buffer. This routine does locking to obtain the * audit buffer, but then no locking is required for calls to * audit_log_*format. If the tsk is a task that is currently in a * syscall, then the syscall is marked as auditable and an audit record * will be written at syscall exit. If there is no associated task, tsk * should be NULL. */ /** * audit_log_start - obtain an audit buffer * @ctx: audit_context (may be NULL) * @gfp_mask: type of allocation * @type: audit message type * * Returns audit_buffer pointer on success or NULL on error. * * Obtain an audit buffer. This routine does locking to obtain the * audit buffer, but then no locking is required for calls to * audit_log_*format. If the task (ctx) is a task that is currently in a * syscall, then the syscall is marked as auditable and an audit record * will be written at syscall exit. If there is no associated task, then * task context (ctx) should be NULL. */ struct audit_buffer *audit_log_start(struct audit_context *ctx, gfp_t gfp_mask, int type) { struct audit_buffer *ab = NULL; struct timespec t; unsigned int uninitialized_var(serial); int reserve; unsigned long timeout_start = jiffies; if (audit_initialized != AUDIT_INITIALIZED) return NULL; if (unlikely(audit_filter_type(type))) return NULL; if (gfp_mask & __GFP_WAIT) reserve = 0; else reserve = 5; /* Allow atomic callers to go up to five entries over the normal backlog limit */ while (audit_backlog_limit && skb_queue_len(&audit_skb_queue) > audit_backlog_limit + reserve) { if (gfp_mask & __GFP_WAIT && audit_backlog_wait_time && time_before(jiffies, timeout_start + audit_backlog_wait_time)) { /* Wait for auditd to drain the queue a little */ DECLARE_WAITQUEUE(wait, current); set_current_state(TASK_UNINTERRUPTIBLE); add_wait_queue(&audit_backlog_wait, &wait); if (audit_backlog_limit && skb_queue_len(&audit_skb_queue) > audit_backlog_limit) schedule_timeout(timeout_start + audit_backlog_wait_time - jiffies); __set_current_state(TASK_RUNNING); remove_wait_queue(&audit_backlog_wait, &wait); continue; } if (audit_rate_check() && printk_ratelimit()) printk(KERN_WARNING "audit: audit_backlog=%d > " "audit_backlog_limit=%d\n", skb_queue_len(&audit_skb_queue), audit_backlog_limit); audit_log_lost("backlog limit exceeded"); audit_backlog_wait_time = audit_backlog_wait_overflow; wake_up(&audit_backlog_wait); return NULL; } ab = audit_buffer_alloc(ctx, gfp_mask, type); if (!ab) { audit_log_lost("out of memory in audit_log_start"); return NULL; } audit_get_stamp(ab->ctx, &t, &serial); audit_log_format(ab, "audit(%lu.%03lu:%u): ", t.tv_sec, t.tv_nsec/1000000, serial); return ab; } /** * audit_expand - expand skb in the audit buffer * @ab: audit_buffer * @extra: space to add at tail of the skb * * Returns 0 (no space) on failed expansion, or available space if * successful. */ static inline int audit_expand(struct audit_buffer *ab, int extra) { struct sk_buff *skb = ab->skb; int oldtail = skb_tailroom(skb); int ret = pskb_expand_head(skb, 0, extra, ab->gfp_mask); int newtail = skb_tailroom(skb); if (ret < 0) { audit_log_lost("out of memory in audit_expand"); return 0; } skb->truesize += newtail - oldtail; return newtail; } /* * Format an audit message into the audit buffer. If there isn't enough * room in the audit buffer, more room will be allocated and vsnprint * will be called a second time. Currently, we assume that a printk * can't format message larger than 1024 bytes, so we don't either. */ static void audit_log_vformat(struct audit_buffer *ab, const char *fmt, va_list args) { int len, avail; struct sk_buff *skb; va_list args2; if (!ab) return; BUG_ON(!ab->skb); skb = ab->skb; avail = skb_tailroom(skb); if (avail == 0) { avail = audit_expand(ab, AUDIT_BUFSIZ); if (!avail) goto out; } va_copy(args2, args); len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args); if (len >= avail) { /* The printk buffer is 1024 bytes long, so if we get * here and AUDIT_BUFSIZ is at least 1024, then we can * log everything that printk could have logged. */ avail = audit_expand(ab, max_t(unsigned, AUDIT_BUFSIZ, 1+len-avail)); if (!avail) goto out_va_end; len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args2); } if (len > 0) skb_put(skb, len); out_va_end: va_end(args2); out: return; } /** * audit_log_format - format a message into the audit buffer. * @ab: audit_buffer * @fmt: format string * @...: optional parameters matching @fmt string * * All the work is done in audit_log_vformat. */ void audit_log_format(struct audit_buffer *ab, const char *fmt, ...) { va_list args; if (!ab) return; va_start(args, fmt); audit_log_vformat(ab, fmt, args); va_end(args); } /** * audit_log_hex - convert a buffer to hex and append it to the audit skb * @ab: the audit_buffer * @buf: buffer to convert to hex * @len: length of @buf to be converted * * No return value; failure to expand is silently ignored. * * This function will take the passed buf and convert it into a string of * ascii hex digits. The new string is placed onto the skb. */ void audit_log_n_hex(struct audit_buffer *ab, const unsigned char *buf, size_t len) { int i, avail, new_len; unsigned char *ptr; struct sk_buff *skb; static const unsigned char *hex = "0123456789ABCDEF"; if (!ab) return; BUG_ON(!ab->skb); skb = ab->skb; avail = skb_tailroom(skb); new_len = len<<1; if (new_len >= avail) { /* Round the buffer request up to the next multiple */ new_len = AUDIT_BUFSIZ*(((new_len-avail)/AUDIT_BUFSIZ) + 1); avail = audit_expand(ab, new_len); if (!avail) return; } ptr = skb_tail_pointer(skb); for (i=0; i<len; i++) { *ptr++ = hex[(buf[i] & 0xF0)>>4]; /* Upper nibble */ *ptr++ = hex[buf[i] & 0x0F]; /* Lower nibble */ } *ptr = 0; skb_put(skb, len << 1); /* new string is twice the old string */ } /* * Format a string of no more than slen characters into the audit buffer, * enclosed in quote marks. */ void audit_log_n_string(struct audit_buffer *ab, const char *string, size_t slen) { int avail, new_len; unsigned char *ptr; struct sk_buff *skb; if (!ab) return; BUG_ON(!ab->skb); skb = ab->skb; avail = skb_tailroom(skb); new_len = slen + 3; /* enclosing quotes + null terminator */ if (new_len > avail) { avail = audit_expand(ab, new_len); if (!avail) return; } ptr = skb_tail_pointer(skb); *ptr++ = '"'; memcpy(ptr, string, slen); ptr += slen; *ptr++ = '"'; *ptr = 0; skb_put(skb, slen + 2); /* don't include null terminator */ } /** * audit_string_contains_control - does a string need to be logged in hex * @string: string to be checked * @len: max length of the string to check */ int audit_string_contains_control(const char *string, size_t len) { const unsigned char *p; for (p = string; p < (const unsigned char *)string + len; p++) { if (*p == '"' || *p < 0x21 || *p > 0x7e) return 1; } return 0; } /** * audit_log_n_untrustedstring - log a string that may contain random characters * @ab: audit_buffer * @len: length of string (not including trailing null) * @string: string to be logged * * This code will escape a string that is passed to it if the string * contains a control character, unprintable character, double quote mark, * or a space. Unescaped strings will start and end with a double quote mark. * Strings that are escaped are printed in hex (2 digits per char). * * The caller specifies the number of characters in the string to log, which may * or may not be the entire string. */ void audit_log_n_untrustedstring(struct audit_buffer *ab, const char *string, size_t len) { if (audit_string_contains_control(string, len)) audit_log_n_hex(ab, string, len); else audit_log_n_string(ab, string, len); } /** * audit_log_untrustedstring - log a string that may contain random characters * @ab: audit_buffer * @string: string to be logged * * Same as audit_log_n_untrustedstring(), except that strlen is used to * determine string length. */ void audit_log_untrustedstring(struct audit_buffer *ab, const char *string) { audit_log_n_untrustedstring(ab, string, strlen(string)); } /* This is a helper-function to print the escaped d_path */ void audit_log_d_path(struct audit_buffer *ab, const char *prefix, const struct path *path) { char *p, *pathname; if (prefix) audit_log_format(ab, "%s", prefix); /* We will allow 11 spaces for ' (deleted)' to be appended */ pathname = kmalloc(PATH_MAX+11, ab->gfp_mask); if (!pathname) { audit_log_string(ab, "<no_memory>"); return; } p = d_path(path, pathname, PATH_MAX+11); if (IS_ERR(p)) { /* Should never happen since we send PATH_MAX */ /* FIXME: can we save some information here? */ audit_log_string(ab, "<too_long>"); } else audit_log_untrustedstring(ab, p); kfree(pathname); } void audit_log_key(struct audit_buffer *ab, char *key) { audit_log_format(ab, " key="); if (key) audit_log_untrustedstring(ab, key); else audit_log_format(ab, "(null)"); } /** * audit_log_end - end one audit record * @ab: the audit_buffer * * The netlink_* functions cannot be called inside an irq context, so * the audit buffer is placed on a queue and a tasklet is scheduled to * remove them from the queue outside the irq context. May be called in * any context. */ void audit_log_end(struct audit_buffer *ab) { if (!ab) return; if (!audit_rate_check()) { audit_log_lost("rate limit exceeded"); } else { struct nlmsghdr *nlh = nlmsg_hdr(ab->skb); nlh->nlmsg_len = ab->skb->len - NLMSG_SPACE(0); if (audit_pid) { skb_queue_tail(&audit_skb_queue, ab->skb); wake_up_interruptible(&kauditd_wait); } else { audit_printk_skb(ab->skb); } ab->skb = NULL; } audit_buffer_free(ab); } /** * audit_log - Log an audit record * @ctx: audit context * @gfp_mask: type of allocation * @type: audit message type * @fmt: format string to use * @...: variable parameters matching the format string * * This is a convenience function that calls audit_log_start, * audit_log_vformat, and audit_log_end. It may be called * in any context. */ void audit_log(struct audit_context *ctx, gfp_t gfp_mask, int type, const char *fmt, ...) { struct audit_buffer *ab; va_list args; ab = audit_log_start(ctx, gfp_mask, type); if (ab) { va_start(args, fmt); audit_log_vformat(ab, fmt, args); va_end(args); audit_log_end(ab); } } #ifdef CONFIG_SECURITY /** * audit_log_secctx - Converts and logs SELinux context * @ab: audit_buffer * @secid: security number * * This is a helper function that calls security_secid_to_secctx to convert * secid to secctx and then adds the (converted) SELinux context to the audit * log by calling audit_log_format, thus also preventing leak of internal secid * to userspace. If secid cannot be converted audit_panic is called. */ void audit_log_secctx(struct audit_buffer *ab, u32 secid) { u32 len; char *secctx; if (security_secid_to_secctx(secid, &secctx, &len)) { audit_panic("Cannot convert secid to context"); } else { audit_log_format(ab, " obj=%s", secctx); security_release_secctx(secctx, len); } } EXPORT_SYMBOL(audit_log_secctx); #endif EXPORT_SYMBOL(audit_log_start); EXPORT_SYMBOL(audit_log_end); EXPORT_SYMBOL(audit_log_format); EXPORT_SYMBOL(audit_log);
myfluxi/android_kernel_lge_hammerhead
kernel/audit.c
C
gpl-2.0
41,125
<?php /** * Chinese(Traditional) language file * * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * @author chinsan <[email protected]> * @author Li-Jiun Huang <[email protected]> * @author http://www.chinese-tools.com/tools/converter-simptrad.html * @author Wayne San <[email protected]> * @author Li-Jiun Huang <[email protected]> * @author Cheng-Wei Chien <[email protected]> */ $lang['admin_acl'] = '設定 ACL 存取名單'; $lang['acl_group'] = '群組'; $lang['acl_user'] = '帳號'; $lang['acl_perms'] = '設定權限於'; $lang['page'] = '頁面'; $lang['namespace'] = '命名空間'; $lang['btn_select'] = '選擇'; $lang['p_user_id'] = '使用者 <b class="acluser">%s</b> 在頁面 <b class="aclpage">%s</b>目前擁有以下的權限: <i>%s</i>.'; $lang['p_user_ns'] = '用戶 <b class=\"acluser\">%s</b> 當前在命名空間 <b class=\"aclns\">%s</b> 擁有以下權限:<i>%s</i>。'; $lang['p_group_id'] = '群組 <b class="aclgroup">%s</b> 的成員目前對於頁面 <b class="aclpage">%s</b> 擁有以下的權限: <i>%s</i>.'; $lang['p_group_ns'] = '<b class=\"aclgroup\">%s</b> 組成員當前在命名空間 <b class=\"aclns\">%s</b> 擁有以下權限:<i>%s</i>。'; $lang['p_choose_id'] = '請在上方的表格中 <b>輸入一個帳號或群組</b> 來觀看或編輯頁面 <b class="aclpage">%s</b> 的權限.'; $lang['p_choose_ns'] = '請在上表中<b>輸入用戶名或組名稱</b>,來查看或編輯命名空間 <b class=\"aclns\">%s</b> 的權限設置。'; $lang['p_inherited'] = '請注意:這些權限並沒有明確設定,而是從其他組或更高級的名稱空間繼承而來。'; $lang['p_isadmin'] = '請注意:選定的組或用戶擁有完全權限,因為它被設定為超級用戶。'; $lang['p_include'] = '較高的權限亦包含了較低的權限。新增、上傳與刪除權限只能在命名空間中使用,而非頁面。'; $lang['current'] = '目前的ACL規則'; $lang['where'] = '頁面/命名空間'; $lang['who'] = '使用者/群組'; $lang['perm'] = '權限'; $lang['acl_perm0'] = '無'; $lang['acl_perm1'] = '讀取權限'; $lang['acl_perm2'] = '編輯頁面'; $lang['acl_perm4'] = '新增頁面'; $lang['acl_perm8'] = '上傳圖檔'; $lang['acl_perm16'] = '刪除檔案'; $lang['acl_new'] = '新增管理規則'; $lang['acl_mod'] = '修改規則';
lorea/dokuwiki
vendors/dokuwiki/lib/plugins/acl/lang/zh-tw/lang.php
PHP
gpl-2.0
2,715
// Copyright (C) 2010,2011,2012 GlavSoft LLC. // All rights reserved. // //------------------------------------------------------------------------- // This file is part of the TightVNC software. Please visit our Web site: // // http://www.tightvnc.com/ // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. //------------------------------------------------------------------------- // #ifndef _ABOUT_DIALOG_H_ #define _ABOUT_DIALOG_H_ #include "gui/BaseDialog.h" /** * TightVNC server about dialog. */ class AboutDialog : public BaseDialog { public: /** * Creates dialog. */ AboutDialog(); /** * Destroys dialog. */ virtual ~AboutDialog(); protected: /** * Called when user press "Close" button. */ void onCloseButtonClick(); /** * Called when user press "Order Technical Support" button. */ void onOrderSupportButtonClock(); /** * Called when user press "Visit Web Site" button. */ void onVisitSiteButtonClick(); /** * Opens url in default browser or shows error message on fail. */ void openUrl(const TCHAR *url); protected: /** * Inherited from BaseDialog. * Does nothing. */ virtual BOOL onInitDialog(); /** * Inherited from BaseDialog. * Does nothing. */ virtual BOOL onNotify(UINT controlID, LPARAM data); /** * Inherited from BaseDialog. * Handles buttons events. */ virtual BOOL onCommand(UINT controlID, UINT notificationID); /** * Inherited from BaseDialog. * Does nothing. */ virtual BOOL onDestroy(); }; #endif
skbkontur/KonturVNC
tvnviewer/AboutDialog.h
C
gpl-2.0
2,320
<?php /* +--------------------------------------------------------------------+ | CiviCRM version 4.2 | +--------------------------------------------------------------------+ | Copyright CiviCRM LLC (c) 2004-2012 | +--------------------------------------------------------------------+ | This file is a part of CiviCRM. | | | | CiviCRM is free software; you can copy, modify, and distribute it | | under the terms of the GNU Affero General Public License | | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. | | | | CiviCRM 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 Affero General Public License for more details. | | | | You should have received a copy of the GNU Affero General Public | | License and the CiviCRM Licensing Exception along | | with this program; if not, contact CiviCRM LLC | | at info[AT]civicrm[DOT]org. If you have questions about the | | GNU Affero General Public License or the licensing of CiviCRM, | | see the CiviCRM license FAQ at http://civicrm.org/licensing | +--------------------------------------------------------------------+ */ /** * * @package CRM * @copyright CiviCRM LLC (c) 2004-2012 * $Id$ * */ /** * This class generates form components for processing a pcp page creati * */ class CRM_PCP_Form_Campaign extends CRM_Core_Form { public $_context; public $_component; public function preProcess() { // we do not want to display recently viewed items, so turn off $this->assign('displayRecent', FALSE); // component null in controller object - fix? dgg // $this->_component = $this->controller->get('component'); $this->_component = CRM_Utils_Request::retrieve('component', 'String', $this); $this->assign('component', $this->_component); $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this); $this->assign('context', $this->_context); $this->_pageId = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE); $title = ts('Setup a Personal Campaign Page - Step 2'); if ($this->_pageId) { $title = ts('Edit Your Personal Campaign Page'); } CRM_Utils_System::setTitle($title); parent::preProcess(); } function setDefaultValues() { $dafaults = array(); $dao = new CRM_PCP_DAO_PCP(); if ($this->_pageId) { $dao->id = $this->_pageId; if ($dao->find(TRUE)) { CRM_Core_DAO::storeValues($dao, $defaults); } // fix the display of the monetary value, CRM-4038 if (isset($defaults['goal_amount'])) { $defaults['goal_amount'] = CRM_Utils_Money::format($defaults['goal_amount'], NULL, '%a'); } $defaults['pcp_title'] = CRM_Utils_Array::value('title', $defaults); $defaults['pcp_intro_text'] = CRM_Utils_Array::value('intro_text', $defaults); } if ($this->get('action') & CRM_Core_Action::ADD) { $defaults['is_active'] = 1; $defaults['is_honor_roll'] = 1; $defaults['is_thermometer'] = 1; } $this->_contactID = CRM_Utils_Array::value('contact_id', $defaults); $this->_contriPageId = CRM_Utils_Array::value('page_id', $defaults); return $defaults; } /** * Function to build the form * * @return None * @access public */ public function buildQuickForm() { $this->add('text', 'pcp_title', ts('Title'), NULL, TRUE); $this->add('textarea', 'pcp_intro_text', ts('Welcome'), NULL, TRUE); $this->add('text', 'goal_amount', ts('Your Goal'), NULL, TRUE); $this->addRule('goal_amount', ts('Goal Amount should be a numeric value'), 'money'); $attributes = array(); if ($this->_component == 'event') { if ($this->get('action') & CRM_Core_Action::ADD) { $attributes = array('value' => ts('Join Us'), 'onClick' => 'select();'); } $this->add('text', 'donate_link_text', ts('Sign up Button'), $attributes); } else { if ($this->get('action') & CRM_Core_Action::ADD) { $attributes = array('value' => ts('Donate Now'), 'onClick' => 'select();'); } $this->add('text', 'donate_link_text', ts('Donation Button'), $attributes); } $attrib = array('rows' => 8, 'cols' => 60); $this->add('textarea', 'page_text', ts('Your Message'), null, false ); $maxAttachments = 1; CRM_Core_BAO_File::buildAttachment($this, 'civicrm_pcp', $this->_pageId, $maxAttachments); $this->addElement('checkbox', 'is_thermometer', ts('Progress Bar')); $this->addElement('checkbox', 'is_honor_roll', ts('Honor Roll'), NULL); $this->addElement('checkbox', 'is_active', ts('Active')); $this->addButtons(array( array( 'type' => 'upload', 'name' => ts('Save'), 'isDefault' => TRUE, ), array( 'type' => 'cancel', 'name' => ts('Cancel'), ), ) ); $this->addFormRule(array('CRM_PCP_Form_Campaign', 'formRule'), $this); } /** * global form rule * * @param array $fields the input form values * @param array $files the uploaded files if any * @param array $options additional user data * * @return true if no errors, else array of errors * @access public * @static */ static function formRule($fields, $files, $self) { $errors = array(); if ($fields['goal_amount'] <= 0) { $errors['goal_amount'] = ts('Goal Amount should be a numeric value greater than zero.'); } if (strlen($fields['donate_link_text']) >= 64) { $errors['donate_link_text'] = ts('Button Text must be less than 64 characters.'); } if (isset($files['attachFile_1']) && CRM_Utils_Array::value('tmp_name', $files['attachFile_1']) ) { list($width, $height) = getimagesize($files['attachFile_1']['tmp_name']); if ($width > 360 || $height > 360) { $errors['attachFile_1'] = ts("Your picture or image file cannot be larger than 360 x 360 pixels in size.") . ' ' . ts("The dimensions of the image you have selected are %1 x %2.", array(1 => $width, 2 => $height)) . ' ' . ts("Please shrink or crop the file or find another smaller image and try again."); } } return $errors; } /** * Function to process the form * * @access public * * @return None */ public function postProcess() { $params = $this->controller->exportValues( $this->_name ); $checkBoxes = array('is_thermometer', 'is_honor_roll', 'is_active'); foreach ($checkBoxes as $key) { if (!isset($params[$key])) { $params[$key] = 0; } } $session = CRM_Core_Session::singleton(); $contactID = isset($this->_contactID) ? $this->_contactID : $session->get('userID'); if (!$contactID) { $contactID = $this->get('contactID'); } $params['title'] = $params['pcp_title']; $params['intro_text'] = $params['pcp_intro_text']; $params['contact_id'] = $contactID; $params['page_id'] = $this->get('component_page_id') ? $this->get('component_page_id') : $this->_contriPageId; $params['page_type'] = $this->_component; // since we are allowing html input from the user // we also need to purify it, so lets clean it up $htmlFields = array( 'intro_text', 'page_text', 'title' ); foreach ( $htmlFields as $field ) { if ( ! empty($params[$field]) ) { $params[$field] = CRM_Utils_String::purifyHTML($params[$field]); } } $entity_table = CRM_PCP_BAO_PCP::getPcpEntityTable($params['page_type']); $pcpBlock = new CRM_PCP_DAO_PCPBlock(); $pcpBlock->entity_table = $entity_table; $pcpBlock->entity_id = $params['page_id']; $pcpBlock->find(TRUE); $params['pcp_block_id'] = $pcpBlock->id; $params['goal_amount'] = CRM_Utils_Rule::cleanMoney($params['goal_amount']); $approval_needed = $pcpBlock->is_approval_needed; $approvalMessage = NULL; if ($this->get('action') & CRM_Core_Action::ADD) { $params['status_id'] = $approval_needed ? 1 : 2; $approvalMessage = $approval_needed ? ts('but requires administrator review before you can begin promoting your campaign. You will receive an email confirmation shortly which includes a link to return to this page.') : ts('and is ready to use.'); } $params['id'] = $this->_pageId; $pcp = CRM_PCP_BAO_PCP::add($params, FALSE); // add attachments as needed CRM_Core_BAO_File::formatAttachment($params, $params, 'civicrm_pcp', $pcp->id ); $pageStatus = isset($this->_pageId) ? ts('updated') : ts('created'); $statusId = CRM_Core_DAO::getFieldValue('CRM_PCP_DAO_PCP', $pcp->id, 'status_id'); //send notification of PCP create/update. $pcpParams = array('entity_table' => $entity_table, 'entity_id' => $pcp->page_id); $notifyParams = array(); $notifyStatus = ""; CRM_Core_DAO::commonRetrieve('CRM_PCP_DAO_PCPBlock', $pcpParams, $notifyParams, array('notify_email')); if ($emails = $pcpBlock->notify_email) { $this->assign('pcpTitle', $pcp->title); if ($this->_pageId) { $this->assign('mode', 'Update'); } else { $this->assign('mode', 'Add'); } $pcpStatus = CRM_Core_OptionGroup::getLabel('pcp_status', $statusId); $this->assign('pcpStatus', $pcpStatus); $this->assign('pcpId', $pcp->id); $supporterUrl = CRM_Utils_System::url("civicrm/contact/view", "reset=1&cid={$pcp->contact_id}", TRUE, NULL, FALSE, FALSE ); $this->assign('supporterUrl', $supporterUrl); $supporterName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $pcp->contact_id, 'display_name'); $this->assign('supporterName', $supporterName); if ($this->_component == 'contribute') { $pageUrl = CRM_Utils_System::url("civicrm/contribute/transact", "reset=1&id={$pcpBlock->entity_id}", TRUE, NULL, FALSE, TRUE ); $contribPageTitle = CRM_Core_DAO::getFieldValue('CRM_Contribute_DAO_ContributionPage', $pcpBlock->entity_id, 'title'); } elseif ($this->_component == 'event') { $pageUrl = CRM_Utils_System::url("civicrm/event", "reset=1&id={$pcpBlock->entity_id}", TRUE, NULL, FALSE, TRUE ); $contribPageTitle = CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $pcpBlock->entity_id, 'title'); } $this->assign('contribPageUrl', $pageUrl); $this->assign('contribPageTitle', $contribPageTitle); $managePCPUrl = CRM_Utils_System::url("civicrm/admin/pcp", "reset=1", TRUE, NULL, FALSE, FALSE ); $this->assign('managePCPUrl', $managePCPUrl); //get the default domain email address. list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail(); if (!$domainEmailAddress || $domainEmailAddress == '[email protected]') { $fixUrl = CRM_Utils_System::url("civicrm/admin/domain", 'action=update&reset=1'); CRM_Core_Error::fatal(ts('The site administrator needs to enter a valid \'FROM Email Address\' in <a href="%1">Administer CiviCRM &raquo; Communications &raquo; FROM Email Addresses</a>. The email address used may need to be a valid mail account with your email service provider.', array(1 => $fixUrl))); } //if more than one email present for PCP notification , //first email take it as To and other as CC and First email //address should be sent in users email receipt for //support purpose. $emailArray = explode(',', $emails); $to = $emailArray[0]; unset($emailArray[0]); $cc = implode(',', $emailArray); list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplates::sendTemplate( array( 'groupName' => 'msg_tpl_workflow_contribution', 'valueName' => 'pcp_notify', 'contactId' => $contactID, 'from' => "$domainEmailName <$domainEmailAddress>", 'toEmail' => $to, 'cc' => $cc, ) ); if ($sent) { $notifyStatus = ts('A notification email has been sent to the site administrator.'); } } CRM_Core_BAO_File::processAttachment($params, 'civicrm_pcp', $pcp->id); // send email notification to supporter, if initial setup / add mode. if (!$this->_pageId) { CRM_PCP_BAO_PCP::sendStatusUpdate($pcp->id, $statusId, TRUE, $this->_component); if ($approvalMessage && CRM_Utils_Array::value('status_id', $params) == 1) { $notifyStatus .= ts(' You will receive a second email as soon as the review process is complete.'); } } //check if pcp created by anonymous user $anonymousPCP = 0; if (!$session->get('userID')) { $anonymousPCP = 1; } CRM_Core_Session::setStatus(ts("Your Personal Campaign Page has been %1 %2 %3", array(1 => $pageStatus, 2 => $approvalMessage, 3 => $notifyStatus) )); if (!$this->_pageId) { $session->pushUserContext(CRM_Utils_System::url('civicrm/pcp/info', "reset=1&id={$pcp->id}&ap={$anonymousPCP}")); } elseif ($this->_context == 'dashboard') { $session->pushUserContext(CRM_Utils_System::url('civicrm/admin/pcp', "reset=1")); } } }
rowead/drupal-civicrm-puphpet
sites/all/modules/civicrm/CRM/PCP/Form/Campaign.php
PHP
gpl-2.0
13,800
# AMD K6 mpn_copyd -- copy limb vector, decrementing. # # K6: 0.56 or 1.0 cycles/limb (at 32 limbs/loop), depending on data # alignment. # Copyright (C) 1999, 2000 Free Software Foundation, Inc. # # This file is part of the GNU MP Library. # # The GNU MP Library is free software; you can redistribute it and/or modify # it under the terms of the GNU Library General Public License as published by # the Free Software Foundation; either version 2 of the License, or (at your # option) any later version. # # The GNU MP Library is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public # License for more details. # # You should have received a copy of the GNU Library General Public License # along with the GNU MP Library; see the file COPYING.LIB. If not, write to # the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, # MA 02111-1307, USA. include(`../config.m4') dnl K6 aligned: dnl UNROLL_COUNT cycles/limb dnl 8 0.75 dnl 16 0.625 dnl 32 0.5625 dnl 64 0.53 dnl Maximum possible with the current code is 64, the minimum is 2. deflit(UNROLL_COUNT, 32) # void mpn_copyd (mp_ptr dst, mp_srcptr src, mp_size_t size); # # Copy src,size to dst,size, processing limbs from high to low addresses. # # The comments in copyi.asm apply here too. defframe(PARAM_SIZE,12) defframe(PARAM_SRC, 8) defframe(PARAM_DST, 4) deflit(`FRAME',0) .text ALIGN(32) PROLOGUE(mpn_copyd) movl PARAM_SIZE, %ecx movl %esi, %eax movl PARAM_SRC, %esi movl %edi, %edx std movl PARAM_DST, %edi cmpl $UNROLL_COUNT, %ecx leal -4(%esi,%ecx,4), %esi leal -4(%edi,%ecx,4), %edi ja L(unroll) L(simple): rep movsl cld movl %eax, %esi movl %edx, %edi ret L(unroll): # if src and dst are different alignments mod8, then use rep movs # if src and dst are both 4mod8 then process one limb to get 0mod8 pushl %ebx leal (%esi,%edi), %ebx testb $4, %bl popl %ebx jnz L(simple) testl $4, %esi leal -UNROLL_COUNT(%ecx), %ecx jnz L(already_aligned) movsl decl %ecx L(already_aligned): ifelse(UNROLL_BYTES,256,` # for testing speed at 64 limbs/loop unrolling subl $128, %esi subl $128, %edi ') # aligning to 16 here isn't enough, 32 is needed to get the speeds # claimed ALIGN(32) L(top): # eax saved esi # ebx # ecx counter, limbs # edx saved edi # esi src, incrementing # edi dst, incrementing # ebp # # `disp' is never 0, so don't need to force 0(%esi). deflit(CHUNK_COUNT, 2) forloop(`i', 0, UNROLL_COUNT/CHUNK_COUNT-1, ` deflit(`disp', eval(-4-i*CHUNK_COUNT*4 ifelse(UNROLL_BYTES,256,+128))) movq disp(%esi), %mm0 movq %mm0, disp(%edi) ') leal -UNROLL_BYTES(%esi), %esi subl $UNROLL_COUNT, %ecx leal -UNROLL_BYTES(%edi), %edi jns L(top) # now %ecx is -UNROLL_COUNT to -1 representing repectively 0 to # UNROLL_COUNT-1 limbs remaining testb $eval(UNROLL_COUNT/2), %cl leal UNROLL_COUNT(%ecx), %ecx jz L(not_half) # at an unroll count of 32 this block of code is 16 cycles faster than # the rep movs, less 3 or 4 to test whether to do it forloop(`i', 0, UNROLL_COUNT/CHUNK_COUNT/2-1, ` deflit(`disp', eval(-4-i*CHUNK_COUNT*4 ifelse(UNROLL_BYTES,256,+128))) movq disp(%esi), %mm0 movq %mm0, disp(%edi) ') subl $eval(UNROLL_BYTES/2), %esi subl $eval(UNROLL_BYTES/2), %edi subl $eval(UNROLL_COUNT/2), %ecx L(not_half): ifelse(UNROLL_BYTES,256,` # for testing speed at 64 limbs/loop unrolling addl $128, %esi addl $128, %edi ') rep movsl cld movl %eax, %esi movl %edx, %edi emms_or_femms ret EPILOGUE()
ysleu/RTL8685
uClinux-dist/lib/libgmp/mpn/x86/k6/mmx/copyd.asm
Assembly
gpl-2.0
3,715
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2015 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #include "GeoPoint.hpp" #include "GeoVector.hpp" #include "Math.hpp" GeoPoint GeoPoint::Parametric(const GeoPoint &delta, const fixed t) const { return (*this) + delta * t; } GeoPoint GeoPoint::Interpolate(const GeoPoint &end, const fixed t) const { return (*this) + (end - (*this)) * t; } fixed GeoPoint::Distance(const GeoPoint &other) const { return ::Distance(*this, other); } Angle GeoPoint::Bearing(const GeoPoint &other) const { return ::Bearing(*this, other); } GeoVector GeoPoint::DistanceBearing(const GeoPoint &other) const { GeoVector gv; ::DistanceBearing(*this, other, &gv.distance, &gv.bearing); return gv; } fixed GeoPoint::ProjectedDistance(const GeoPoint &from, const GeoPoint &to) const { return ::ProjectedDistance(from, to, *this); } GeoPoint GeoPoint::Middle(const GeoPoint &other) const { return ::Middle(*this, other); } bool GeoPoint::Sort(const GeoPoint &sp) const { if (longitude < sp.longitude) return false; else if (longitude == sp.longitude) return latitude > sp.latitude; else return true; } GeoPoint GeoPoint::IntermediatePoint(const GeoPoint &destination, const fixed distance) const { return ::IntermediatePoint(*this, destination, distance); }
M-Scholli/XCSoar-SE
src/Geo/GeoPoint.cpp
C++
gpl-2.0
2,192
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>glm::gtx::handed_coordinate_space Namespace Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body> <!-- Generated by Doxygen 1.7.4 --> <div id="top"> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="logo-mini.png"/></td> </tr> </tbody> </table> </div> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li class="current"><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="namespaces.html"><span>Namespace&#160;List</span></a></li> <li><a href="namespacemembers.html"><span>Namespace&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="a00143.html">glm</a> </li> <li class="navelem"><a class="el" href="a00168.html">gtx</a> </li> <li class="navelem"><a class="el" href="a00185.html">handed_coordinate_space</a> </li> </ul> </div> </div> <div class="header"> <div class="summary"> <a href="#func-members">Functions</a> </div> <div class="headertitle"> <div class="title">glm::gtx::handed_coordinate_space Namespace Reference</div> </div> </div> <div class="contents"> <p>&lt; GLM_GTX_handed_coordinate_space extension: To know if a set of three basis vectors defines a right or left-handed coordinate system. <a href="#details">More...</a></p> <table class="memberdecls"> <tr><td colspan="2"><h2><a name="func-members"></a> Functions</h2></td></tr> <tr><td class="memTemplParams" colspan="2">template&lt;typename T &gt; </td></tr> <tr><td class="memTemplItemLeft" align="right" valign="top">bool&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00264.html#gac222c8dd989fe9fb2142f18320bd683c">leftHanded</a> (<a class="el" href="a00021.html">detail::tvec3</a>&lt; T &gt; const &amp;tangent, <a class="el" href="a00021.html">detail::tvec3</a>&lt; T &gt; const &amp;binormal, <a class="el" href="a00021.html">detail::tvec3</a>&lt; T &gt; const &amp;normal)</td></tr> <tr><td class="memTemplParams" colspan="2">template&lt;typename T &gt; </td></tr> <tr><td class="memTemplItemLeft" align="right" valign="top">bool&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00264.html#ga472eb0d6e9fcf9b503d3c1a74fdee645">rightHanded</a> (<a class="el" href="a00021.html">detail::tvec3</a>&lt; T &gt; const &amp;tangent, <a class="el" href="a00021.html">detail::tvec3</a>&lt; T &gt; const &amp;binormal, <a class="el" href="a00021.html">detail::tvec3</a>&lt; T &gt; const &amp;normal)</td></tr> </table> <hr/><a name="details" id="details"></a><h2>Detailed Description</h2> <div class="textblock"><p>&lt; GLM_GTX_handed_coordinate_space extension: To know if a set of three basis vectors defines a right or left-handed coordinate system. </p> </div></div> <hr class="footer"/><address class="footer"><small>Generated by&#160; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.4 </small></address> </body> </html>
tuituji/184.1x-BerkeleyX-CG
hw2-linuxosx/glm-0.9.2.7/doc/api-0.9.2/a00185.html
HTML
gpl-2.0
3,831
/* * Copyright (C) 2010-2012 ARM Limited. All rights reserved. * * This program is free software and is provided to you under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation, and any use by you of this program is subject to the terms of such GNU licence. * * A copy of the licence is included with the program, and can also be obtained from Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * @file mali_uk_types.h * Defines the types and constants used in the user-kernel interface */ #ifndef __MALI_UTGARD_UK_TYPES_H__ #define __MALI_UTGARD_UK_TYPES_H__ #ifdef __cplusplus extern "C" { #endif /** * @addtogroup uddapi Unified Device Driver (UDD) APIs * * @{ */ /** * @addtogroup u_k_api UDD User/Kernel Interface (U/K) APIs * * @{ */ /** @defgroup _mali_uk_core U/K Core * @{ */ /** Definition of subsystem numbers, to assist in creating a unique identifier * for each U/K call. * * @see _mali_uk_functions */ typedef enum { _MALI_UK_CORE_SUBSYSTEM, /**< Core Group of U/K calls */ _MALI_UK_MEMORY_SUBSYSTEM, /**< Memory Group of U/K calls */ _MALI_UK_PP_SUBSYSTEM, /**< Fragment Processor Group of U/K calls */ _MALI_UK_GP_SUBSYSTEM, /**< Vertex Processor Group of U/K calls */ _MALI_UK_PROFILING_SUBSYSTEM, /**< Profiling Group of U/K calls */ _MALI_UK_PMM_SUBSYSTEM, /**< Power Management Module Group of U/K calls */ _MALI_UK_VSYNC_SUBSYSTEM, /**< VSYNC Group of U/K calls */ } _mali_uk_subsystem_t; /** Within a function group each function has its unique sequence number * to assist in creating a unique identifier for each U/K call. * * An ordered pair of numbers selected from * ( \ref _mali_uk_subsystem_t,\ref _mali_uk_functions) will uniquely identify the * U/K call across all groups of functions, and all functions. */ typedef enum { /** Core functions */ _MALI_UK_OPEN = 0, /**< _mali_ukk_open() */ _MALI_UK_CLOSE, /**< _mali_ukk_close() */ _MALI_UK_WAIT_FOR_NOTIFICATION, /**< _mali_ukk_wait_for_notification() */ _MALI_UK_GET_API_VERSION, /**< _mali_ukk_get_api_version() */ _MALI_UK_POST_NOTIFICATION, /**< _mali_ukk_post_notification() */ _MALI_UK_GET_USER_SETTING, /**< _mali_ukk_get_user_setting() *//**< [out] */ _MALI_UK_GET_USER_SETTINGS, /**< _mali_ukk_get_user_settings() *//**< [out] */ _MALI_UK_STREAM_CREATE, /**< _mali_ukk_stream_create() */ _MALI_UK_FENCE_CREATE_EMPTY, /**< _mali_ukk_fence_create_empty() */ _MALI_UK_FENCE_VALIDATE, /**< _mali_ukk_fence_validate() */ _MALI_UK_COMPOSITOR_PRIORITY, /**< _mali_ukk_compositor_priority() */ /** Memory functions */ _MALI_UK_INIT_MEM = 0, /**< _mali_ukk_init_mem() */ _MALI_UK_TERM_MEM, /**< _mali_ukk_term_mem() */ _MALI_UK_GET_BIG_BLOCK, /**< _mali_ukk_get_big_block() */ _MALI_UK_FREE_BIG_BLOCK, /**< _mali_ukk_free_big_block() */ _MALI_UK_MAP_MEM, /**< _mali_ukk_mem_mmap() */ _MALI_UK_UNMAP_MEM, /**< _mali_ukk_mem_munmap() */ _MALI_UK_QUERY_MMU_PAGE_TABLE_DUMP_SIZE, /**< _mali_ukk_mem_get_mmu_page_table_dump_size() */ _MALI_UK_DUMP_MMU_PAGE_TABLE, /**< _mali_ukk_mem_dump_mmu_page_table() */ _MALI_UK_ATTACH_DMA_BUF, /**< _mali_ukk_attach_dma_buf() */ _MALI_UK_RELEASE_DMA_BUF, /**< _mali_ukk_release_dma_buf() */ _MALI_UK_DMA_BUF_GET_SIZE, /**< _mali_ukk_dma_buf_get_size() */ _MALI_UK_ATTACH_UMP_MEM, /**< _mali_ukk_attach_ump_mem() */ _MALI_UK_RELEASE_UMP_MEM, /**< _mali_ukk_release_ump_mem() */ _MALI_UK_MAP_EXT_MEM, /**< _mali_uku_map_external_mem() */ _MALI_UK_UNMAP_EXT_MEM, /**< _mali_uku_unmap_external_mem() */ _MALI_UK_VA_TO_MALI_PA, /**< _mali_uku_va_to_mali_pa() */ _MALI_UK_MEM_WRITE_SAFE, /**< _mali_uku_mem_write_safe() */ /** Common functions for each core */ _MALI_UK_START_JOB = 0, /**< Start a Fragment/Vertex Processor Job on a core */ _MALI_UK_GET_NUMBER_OF_CORES, /**< Get the number of Fragment/Vertex Processor cores */ _MALI_UK_GET_CORE_VERSION, /**< Get the Fragment/Vertex Processor version compatible with all cores */ /** Fragment Processor Functions */ _MALI_UK_PP_START_JOB = _MALI_UK_START_JOB, /**< _mali_ukk_pp_start_job() */ _MALI_UK_GET_PP_NUMBER_OF_CORES = _MALI_UK_GET_NUMBER_OF_CORES, /**< _mali_ukk_get_pp_number_of_cores() */ _MALI_UK_GET_PP_CORE_VERSION = _MALI_UK_GET_CORE_VERSION, /**< _mali_ukk_get_pp_core_version() */ _MALI_UK_PP_DISABLE_WB, /**< _mali_ukk_pp_job_disable_wb() */ /** Vertex Processor Functions */ _MALI_UK_GP_START_JOB = _MALI_UK_START_JOB, /**< _mali_ukk_gp_start_job() */ _MALI_UK_GET_GP_NUMBER_OF_CORES = _MALI_UK_GET_NUMBER_OF_CORES, /**< _mali_ukk_get_gp_number_of_cores() */ _MALI_UK_GET_GP_CORE_VERSION = _MALI_UK_GET_CORE_VERSION, /**< _mali_ukk_get_gp_core_version() */ _MALI_UK_GP_SUSPEND_RESPONSE, /**< _mali_ukk_gp_suspend_response() */ /** Profiling functions */ _MALI_UK_PROFILING_START = 0, /**< __mali_uku_profiling_start() */ _MALI_UK_PROFILING_ADD_EVENT, /**< __mali_uku_profiling_add_event() */ _MALI_UK_PROFILING_STOP, /**< __mali_uku_profiling_stop() */ _MALI_UK_PROFILING_GET_EVENT, /**< __mali_uku_profiling_get_event() */ _MALI_UK_PROFILING_CLEAR, /**< __mali_uku_profiling_clear() */ _MALI_UK_PROFILING_GET_CONFIG, /**< __mali_uku_profiling_get_config() */ _MALI_UK_PROFILING_REPORT_SW_COUNTERS,/**< __mali_uku_profiling_report_sw_counters() */ /** VSYNC reporting fuctions */ _MALI_UK_VSYNC_EVENT_REPORT = 0, /**< _mali_ukk_vsync_event_report() */ } _mali_uk_functions; /** @brief Get the size necessary for system info * * @see _mali_ukk_get_system_info_size() */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32 size; /**< [out] size of buffer necessary to hold system information data, in bytes */ } _mali_uk_get_system_info_size_s; /** @defgroup _mali_uk_getsysteminfo U/K Get System Info * @{ */ /** * Type definition for the core version number. * Used when returning the version number read from a core * * Its format is that of the 32-bit Version register for a particular core. * Refer to the "Mali200 and MaliGP2 3D Graphics Processor Technical Reference * Manual", ARM DDI 0415C, for more information. */ typedef u32 _mali_core_version; /** * Enum values for the different modes the driver can be put in. * Normal is the default mode. The driver then uses a job queue and takes job objects from the clients. * Job completion is reported using the _mali_ukk_wait_for_notification call. * The driver blocks this io command until a job has completed or failed or a timeout occurs. * * The 'raw' mode is reserved for future expansion. */ typedef enum _mali_driver_mode { _MALI_DRIVER_MODE_RAW = 1, /**< Reserved for future expansion */ _MALI_DRIVER_MODE_NORMAL = 2 /**< Normal mode of operation */ } _mali_driver_mode; /** @brief List of possible cores * * add new entries to the end of this enum */ typedef enum _mali_core_type { _MALI_GP2 = 2, /**< MaliGP2 Programmable Vertex Processor */ _MALI_200 = 5, /**< Mali200 Programmable Fragment Processor */ _MALI_400_GP = 6, /**< Mali400 Programmable Vertex Processor */ _MALI_400_PP = 7, /**< Mali400 Programmable Fragment Processor */ /* insert new core here, do NOT alter the existing values */ } _mali_core_type; /** @brief Capabilities of Memory Banks * * These may be used to restrict memory banks for certain uses. They may be * used when access is not possible (e.g. Bus does not support access to it) * or when access is possible but not desired (e.g. Access is slow). * * In the case of 'possible but not desired', there is no way of specifying * the flags as an optimization hint, so that the memory could be used as a * last resort. * * @see _mali_mem_info */ typedef enum _mali_bus_usage { _MALI_PP_READABLE = (1<<0), /** Readable by the Fragment Processor */ _MALI_PP_WRITEABLE = (1<<1), /** Writeable by the Fragment Processor */ _MALI_GP_READABLE = (1<<2), /** Readable by the Vertex Processor */ _MALI_GP_WRITEABLE = (1<<3), /** Writeable by the Vertex Processor */ _MALI_CPU_READABLE = (1<<4), /** Readable by the CPU */ _MALI_CPU_WRITEABLE = (1<<5), /** Writeable by the CPU */ _MALI_GP_L2_ALLOC = (1<<6), /** GP allocate mali L2 cache lines*/ _MALI_MMU_READABLE = _MALI_PP_READABLE | _MALI_GP_READABLE, /** Readable by the MMU (including all cores behind it) */ _MALI_MMU_WRITEABLE = _MALI_PP_WRITEABLE | _MALI_GP_WRITEABLE, /** Writeable by the MMU (including all cores behind it) */ } _mali_bus_usage; typedef enum mali_memory_cache_settings { MALI_CACHE_STANDARD = 0, MALI_CACHE_GP_READ_ALLOCATE = 1, } mali_memory_cache_settings ; /** @brief Information about the Mali Memory system * * Information is stored in a linked list, which is stored entirely in the * buffer pointed to by the system_info member of the * _mali_uk_get_system_info_s arguments provided to _mali_ukk_get_system_info() * * Each element of the linked list describes a single Mali Memory bank. * Each allocation can only come from one bank, and will not cross multiple * banks. * * On Mali-MMU systems, there is only one bank, which describes the maximum * possible address range that could be allocated (which may be much less than * the available physical memory) * * The flags member describes the capabilities of the memory. It is an error * to attempt to build a job for a particular core (PP or GP) when the memory * regions used do not have the capabilities for supporting that core. This * would result in a job abort from the Device Driver. * * For example, it is correct to build a PP job where read-only data structures * are taken from a memory with _MALI_PP_READABLE set and * _MALI_PP_WRITEABLE clear, and a framebuffer with _MALI_PP_WRITEABLE set and * _MALI_PP_READABLE clear. However, it would be incorrect to use a framebuffer * where _MALI_PP_WRITEABLE is clear. */ typedef struct _mali_mem_info { u32 size; /**< Size of the memory bank in bytes */ _mali_bus_usage flags; /**< Capabilitiy flags of the memory */ u32 maximum_order_supported; /**< log2 supported size */ u32 identifier; /* mali_memory_cache_settings cache_settings; */ struct _mali_mem_info * next; /**< Next List Link */ } _mali_mem_info; /** @} */ /* end group _mali_uk_core */ /** @defgroup _mali_uk_gp U/K Vertex Processor * @{ */ /** @defgroup _mali_uk_gp_suspend_response_s Vertex Processor Suspend Response * @{ */ /** @brief Arguments for _mali_ukk_gp_suspend_response() * * When _mali_wait_for_notification() receives notification that a * Vertex Processor job was suspended, you need to send a response to indicate * what needs to happen with this job. You can either abort or resume the job. * * - set @c code to indicate response code. This is either @c _MALIGP_JOB_ABORT or * @c _MALIGP_JOB_RESUME_WITH_NEW_HEAP to indicate you will provide a new heap * for the job that will resolve the out of memory condition for the job. * - copy the @c cookie value from the @c _mali_uk_gp_job_suspended_s notification; * this is an identifier for the suspended job * - set @c arguments[0] and @c arguments[1] to zero if you abort the job. If * you resume it, @c argument[0] should specify the Mali start address for the new * heap and @c argument[1] the Mali end address of the heap. * - pass in the user-kernel context @c ctx that was returned from _mali_ukk_open() * */ typedef enum _maligp_job_suspended_response_code { _MALIGP_JOB_ABORT, /**< Abort the Vertex Processor job */ _MALIGP_JOB_RESUME_WITH_NEW_HEAP /**< Resume the Vertex Processor job with a new heap */ } _maligp_job_suspended_response_code; typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32 cookie; /**< [in] cookie from the _mali_uk_gp_job_suspended_s notification */ _maligp_job_suspended_response_code code; /**< [in] abort or resume response code, see \ref _maligp_job_suspended_response_code */ u32 arguments[2]; /**< [in] 0 when aborting a job. When resuming a job, the Mali start and end address for a new heap to resume the job with */ } _mali_uk_gp_suspend_response_s; /** @} */ /* end group _mali_uk_gp_suspend_response_s */ /** @defgroup _mali_uk_gpstartjob_s Vertex Processor Start Job * @{ */ /** @brief Status indicating the result of starting a Vertex or Fragment processor job */ typedef enum { _MALI_UK_START_JOB_STARTED, /**< Job started */ _MALI_UK_START_JOB_NOT_STARTED_DO_REQUEUE /**< Job could not be started at this time. Try starting the job again */ } _mali_uk_start_job_status; /** @brief Status indicating the result of the execution of a Vertex or Fragment processor job */ typedef enum { _MALI_UK_JOB_STATUS_END_SUCCESS = 1<<(16+0), _MALI_UK_JOB_STATUS_END_OOM = 1<<(16+1), _MALI_UK_JOB_STATUS_END_ABORT = 1<<(16+2), _MALI_UK_JOB_STATUS_END_TIMEOUT_SW = 1<<(16+3), _MALI_UK_JOB_STATUS_END_HANG = 1<<(16+4), _MALI_UK_JOB_STATUS_END_SEG_FAULT = 1<<(16+5), _MALI_UK_JOB_STATUS_END_ILLEGAL_JOB = 1<<(16+6), _MALI_UK_JOB_STATUS_END_UNKNOWN_ERR = 1<<(16+7), _MALI_UK_JOB_STATUS_END_SHUTDOWN = 1<<(16+8), _MALI_UK_JOB_STATUS_END_SYSTEM_UNUSABLE = 1<<(16+9) } _mali_uk_job_status; #define MALIGP2_NUM_REGS_FRAME (6) /** @brief Arguments for _mali_ukk_gp_start_job() * * To start a Vertex Processor job * - associate the request with a reference to a @c mali_gp_job_info by setting * user_job_ptr to the address of the @c mali_gp_job_info of the job. * - set @c priority to the priority of the @c mali_gp_job_info * - specify a timeout for the job by setting @c watchdog_msecs to the number of * milliseconds the job is allowed to run. Specifying a value of 0 selects the * default timeout in use by the device driver. * - copy the frame registers from the @c mali_gp_job_info into @c frame_registers. * - set the @c perf_counter_flag, @c perf_counter_src0 and @c perf_counter_src1 to zero * for a non-instrumented build. For an instrumented build you can use up * to two performance counters. Set the corresponding bit in @c perf_counter_flag * to enable them. @c perf_counter_src0 and @c perf_counter_src1 specify * the source of what needs to get counted (e.g. number of vertex loader * cache hits). For source id values, see ARM DDI0415A, Table 3-60. * - pass in the user-kernel context @c ctx that was returned from _mali_ukk_open() * * When @c _mali_ukk_gp_start_job() returns @c _MALI_OSK_ERR_OK, status contains the * result of the request (see \ref _mali_uk_start_job_status). If the job could * not get started (@c _MALI_UK_START_JOB_NOT_STARTED_DO_REQUEUE) it should be * tried again. * * After the job has started, @c _mali_wait_for_notification() will be notified * that the job finished or got suspended. It may get suspended due to * resource shortage. If it finished (see _mali_ukk_wait_for_notification()) * the notification will contain a @c _mali_uk_gp_job_finished_s result. If * it got suspended the notification will contain a @c _mali_uk_gp_job_suspended_s * result. * * The @c _mali_uk_gp_job_finished_s contains the job status (see \ref _mali_uk_job_status), * the number of milliseconds the job took to render, and values of core registers * when the job finished (irq status, performance counters, renderer list * address). A job has finished succesfully when its status is * @c _MALI_UK_JOB_STATUS_FINISHED. If the hardware detected a timeout while rendering * the job, or software detected the job is taking more than watchdog_msecs to * complete, the status will indicate @c _MALI_UK_JOB_STATUS_HANG. * If the hardware detected a bus error while accessing memory associated with the * job, status will indicate @c _MALI_UK_JOB_STATUS_SEG_FAULT. * status will indicate @c _MALI_UK_JOB_STATUS_NOT_STARTED if the driver had to * stop the job but the job didn't start on the hardware yet, e.g. when the * driver shutdown. * * In case the job got suspended, @c _mali_uk_gp_job_suspended_s contains * the @c user_job_ptr identifier used to start the job with, the @c reason * why the job stalled (see \ref _maligp_job_suspended_reason) and a @c cookie * to identify the core on which the job stalled. This @c cookie will be needed * when responding to this nofication by means of _mali_ukk_gp_suspend_response(). * (see _mali_ukk_gp_suspend_response()). The response is either to abort or * resume the job. If the job got suspended due to an out of memory condition * you may be able to resolve this by providing more memory and resuming the job. * */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32 user_job_ptr; /**< [in] identifier for the job in user space, a @c mali_gp_job_info* */ u32 priority; /**< [in] job priority. A lower number means higher priority */ u32 frame_registers[MALIGP2_NUM_REGS_FRAME]; /**< [in] core specific registers associated with this job */ u32 perf_counter_flag; /**< [in] bitmask indicating which performance counters to enable, see \ref _MALI_PERFORMANCE_COUNTER_FLAG_SRC0_ENABLE and related macro definitions */ u32 perf_counter_src0; /**< [in] source id for performance counter 0 (see ARM DDI0415A, Table 3-60) */ u32 perf_counter_src1; /**< [in] source id for performance counter 1 (see ARM DDI0415A, Table 3-60) */ u32 frame_builder_id; /**< [in] id of the originating frame builder */ u32 flush_id; /**< [in] flush id within the originating frame builder */ } _mali_uk_gp_start_job_s; #define _MALI_PERFORMANCE_COUNTER_FLAG_SRC0_ENABLE (1<<0) /**< Enable performance counter SRC0 for a job */ #define _MALI_PERFORMANCE_COUNTER_FLAG_SRC1_ENABLE (1<<1) /**< Enable performance counter SRC1 for a job */ /** @} */ /* end group _mali_uk_gpstartjob_s */ typedef struct { u32 user_job_ptr; /**< [out] identifier for the job in user space */ _mali_uk_job_status status; /**< [out] status of finished job */ u32 heap_current_addr; /**< [out] value of the GP PLB PL heap start address register */ u32 perf_counter0; /**< [out] value of perfomance counter 0 (see ARM DDI0415A) */ u32 perf_counter1; /**< [out] value of perfomance counter 1 (see ARM DDI0415A) */ } _mali_uk_gp_job_finished_s; typedef enum _maligp_job_suspended_reason { _MALIGP_JOB_SUSPENDED_OUT_OF_MEMORY /**< Polygon list builder unit (PLBU) has run out of memory */ } _maligp_job_suspended_reason; typedef struct { u32 user_job_ptr; /**< [out] identifier for the job in user space */ _maligp_job_suspended_reason reason; /**< [out] reason why the job stalled */ u32 cookie; /**< [out] identifier for the core in kernel space on which the job stalled */ } _mali_uk_gp_job_suspended_s; /** @} */ /* end group _mali_uk_gp */ /** @defgroup _mali_uk_pp U/K Fragment Processor * @{ */ #define _MALI_PP_MAX_SUB_JOBS 8 #define _MALI_PP_MAX_FRAME_REGISTERS ((0x058/4)+1) #define _MALI_PP_MAX_WB_REGISTERS ((0x02C/4)+1) #define _MALI_DLBU_MAX_REGISTERS 4 /** Flag for _mali_uk_pp_start_job_s */ #define _MALI_PP_JOB_FLAG_NO_NOTIFICATION (1<<0) #define _MALI_PP_JOB_FLAG_BARRIER (1<<1) #define _MALI_PP_JOB_FLAG_FENCE (1<<2) #define _MALI_PP_JOB_FLAG_EMPTY_FENCE (1<<3) /** @defgroup _mali_uk_ppstartjob_s Fragment Processor Start Job * @{ */ /** @brief Arguments for _mali_ukk_pp_start_job() * * To start a Fragment Processor job * - associate the request with a reference to a mali_pp_job by setting * @c user_job_ptr to the address of the @c mali_pp_job of the job. * - set @c priority to the priority of the mali_pp_job * - specify a timeout for the job by setting @c watchdog_msecs to the number of * milliseconds the job is allowed to run. Specifying a value of 0 selects the * default timeout in use by the device driver. * - copy the frame registers from the @c mali_pp_job into @c frame_registers. * For MALI200 you also need to copy the write back 0,1 and 2 registers. * - set the @c perf_counter_flag, @c perf_counter_src0 and @c perf_counter_src1 to zero * for a non-instrumented build. For an instrumented build you can use up * to two performance counters. Set the corresponding bit in @c perf_counter_flag * to enable them. @c perf_counter_src0 and @c perf_counter_src1 specify * the source of what needs to get counted (e.g. number of vertex loader * cache hits). For source id values, see ARM DDI0415A, Table 3-60. * - pass in the user-kernel context in @c ctx that was returned from _mali_ukk_open() * * When _mali_ukk_pp_start_job() returns @c _MALI_OSK_ERR_OK, @c status contains the * result of the request (see \ref _mali_uk_start_job_status). If the job could * not get started (@c _MALI_UK_START_JOB_NOT_STARTED_DO_REQUEUE) it should be * tried again. * * After the job has started, _mali_wait_for_notification() will be notified * when the job finished. The notification will contain a * @c _mali_uk_pp_job_finished_s result. It contains the @c user_job_ptr * identifier used to start the job with, the job @c status (see \ref _mali_uk_job_status), * the number of milliseconds the job took to render, and values of core registers * when the job finished (irq status, performance counters, renderer list * address). A job has finished succesfully when its status is * @c _MALI_UK_JOB_STATUS_FINISHED. If the hardware detected a timeout while rendering * the job, or software detected the job is taking more than @c watchdog_msecs to * complete, the status will indicate @c _MALI_UK_JOB_STATUS_HANG. * If the hardware detected a bus error while accessing memory associated with the * job, status will indicate @c _MALI_UK_JOB_STATUS_SEG_FAULT. * status will indicate @c _MALI_UK_JOB_STATUS_NOT_STARTED if the driver had to * stop the job but the job didn't start on the hardware yet, e.g. when the * driver shutdown. * */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32 user_job_ptr; /**< [in] identifier for the job in user space */ u32 priority; /**< [in] job priority. A lower number means higher priority */ u32 frame_registers[_MALI_PP_MAX_FRAME_REGISTERS]; /**< [in] core specific registers associated with first sub job, see ARM DDI0415A */ u32 frame_registers_addr_frame[_MALI_PP_MAX_SUB_JOBS - 1]; /**< [in] ADDR_FRAME registers for sub job 1-7 */ u32 frame_registers_addr_stack[_MALI_PP_MAX_SUB_JOBS - 1]; /**< [in] ADDR_STACK registers for sub job 1-7 */ u32 wb0_registers[_MALI_PP_MAX_WB_REGISTERS]; u32 wb1_registers[_MALI_PP_MAX_WB_REGISTERS]; u32 wb2_registers[_MALI_PP_MAX_WB_REGISTERS]; u32 dlbu_registers[_MALI_DLBU_MAX_REGISTERS]; /**< [in] Dynamic load balancing unit registers */ u32 num_cores; /**< [in] Number of cores to set up (valid range: 1-4) */ u32 perf_counter_flag; /**< [in] bitmask indicating which performance counters to enable, see \ref _MALI_PERFORMANCE_COUNTER_FLAG_SRC0_ENABLE and related macro definitions */ u32 perf_counter_src0; /**< [in] source id for performance counter 0 (see ARM DDI0415A, Table 3-60) */ u32 perf_counter_src1; /**< [in] source id for performance counter 1 (see ARM DDI0415A, Table 3-60) */ u32 frame_builder_id; /**< [in] id of the originating frame builder */ u32 flush_id; /**< [in] flush id within the originating frame builder */ u32 flags; /**< [in] See _MALI_PP_JOB_FLAG_* for a list of avaiable flags */ s32 fence; /**< [in,out] Fence to wait on / fence that will be signalled on job completion, if _MALI_PP_JOB_FLAG_FENCE is set */ s32 stream; /**< [in] Steam identifier if _MALI_PP_JOB_FLAG_FENCE, an empty fence to use for this job if _MALI_PP_JOB_FLAG_EMPTY_FENCE is set */ u32 num_memory_cookies; /**< [in] number of memory cookies attached to job */ u32 *memory_cookies; /**< [in] memory cookies attached to job */ } _mali_uk_pp_start_job_s; /** @} */ /* end group _mali_uk_ppstartjob_s */ typedef struct { u32 user_job_ptr; /**< [out] identifier for the job in user space */ _mali_uk_job_status status; /**< [out] status of finished job */ u32 perf_counter0[_MALI_PP_MAX_SUB_JOBS]; /**< [out] value of perfomance counter 0 (see ARM DDI0415A), one for each sub job */ u32 perf_counter1[_MALI_PP_MAX_SUB_JOBS]; /**< [out] value of perfomance counter 1 (see ARM DDI0415A), one for each sub job */ } _mali_uk_pp_job_finished_s; typedef struct { u32 number_of_enabled_cores; /**< [out] the new number of enabled cores */ } _mali_uk_pp_num_cores_changed_s; /** * Flags to indicate write-back units */ typedef enum { _MALI_UK_PP_JOB_WB0 = 1, _MALI_UK_PP_JOB_WB1 = 2, _MALI_UK_PP_JOB_WB2 = 4, } _mali_uk_pp_job_wbx_flag; typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32 fb_id; /**< [in] Frame builder ID of job to disable WB units for */ u32 flush_id; /**< [in] Flush ID of job to disable WB units for */ _mali_uk_pp_job_wbx_flag wbx; /**< [in] write-back units to disable */ } _mali_uk_pp_disable_wb_s; /** @} */ /* end group _mali_uk_pp */ /** @addtogroup _mali_uk_core U/K Core * @{ */ /** @defgroup _mali_uk_waitfornotification_s Wait For Notification * @{ */ /** @brief Notification type encodings * * Each Notification type is an ordered pair of (subsystem,id), and is unique. * * The encoding of subsystem,id into a 32-bit word is: * encoding = (( subsystem << _MALI_NOTIFICATION_SUBSYSTEM_SHIFT ) & _MALI_NOTIFICATION_SUBSYSTEM_MASK) * | (( id << _MALI_NOTIFICATION_ID_SHIFT ) & _MALI_NOTIFICATION_ID_MASK) * * @see _mali_uk_wait_for_notification_s */ typedef enum { /** core notifications */ _MALI_NOTIFICATION_CORE_SHUTDOWN_IN_PROGRESS = (_MALI_UK_CORE_SUBSYSTEM << 16) | 0x20, _MALI_NOTIFICATION_APPLICATION_QUIT = (_MALI_UK_CORE_SUBSYSTEM << 16) | 0x40, _MALI_NOTIFICATION_SETTINGS_CHANGED = (_MALI_UK_CORE_SUBSYSTEM << 16) | 0x80, /** Fragment Processor notifications */ _MALI_NOTIFICATION_PP_FINISHED = (_MALI_UK_PP_SUBSYSTEM << 16) | 0x10, _MALI_NOTIFICATION_PP_NUM_CORE_CHANGE = (_MALI_UK_PP_SUBSYSTEM << 16) | 0x20, /** Vertex Processor notifications */ _MALI_NOTIFICATION_GP_FINISHED = (_MALI_UK_GP_SUBSYSTEM << 16) | 0x10, _MALI_NOTIFICATION_GP_STALLED = (_MALI_UK_GP_SUBSYSTEM << 16) | 0x20, } _mali_uk_notification_type; /** to assist in splitting up 32-bit notification value in subsystem and id value */ #define _MALI_NOTIFICATION_SUBSYSTEM_MASK 0xFFFF0000 #define _MALI_NOTIFICATION_SUBSYSTEM_SHIFT 16 #define _MALI_NOTIFICATION_ID_MASK 0x0000FFFF #define _MALI_NOTIFICATION_ID_SHIFT 0 /** @brief Enumeration of possible settings which match mali_setting_t in user space * * */ typedef enum { _MALI_UK_USER_SETTING_SW_EVENTS_ENABLE = 0, _MALI_UK_USER_SETTING_COLORBUFFER_CAPTURE_ENABLED, _MALI_UK_USER_SETTING_DEPTHBUFFER_CAPTURE_ENABLED, _MALI_UK_USER_SETTING_STENCILBUFFER_CAPTURE_ENABLED, _MALI_UK_USER_SETTING_PER_TILE_COUNTERS_CAPTURE_ENABLED, _MALI_UK_USER_SETTING_BUFFER_CAPTURE_COMPOSITOR, _MALI_UK_USER_SETTING_BUFFER_CAPTURE_WINDOW, _MALI_UK_USER_SETTING_BUFFER_CAPTURE_OTHER, _MALI_UK_USER_SETTING_BUFFER_CAPTURE_N_FRAMES, _MALI_UK_USER_SETTING_BUFFER_CAPTURE_RESIZE_FACTOR, _MALI_UK_USER_SETTING_SW_COUNTER_ENABLED, _MALI_UK_USER_SETTING_MAX, } _mali_uk_user_setting_t; /* See mali_user_settings_db.c */ extern const char *_mali_uk_user_setting_descriptions[]; #define _MALI_UK_USER_SETTING_DESCRIPTIONS \ { \ "sw_events_enable", \ "colorbuffer_capture_enable", \ "depthbuffer_capture_enable", \ "stencilbuffer_capture_enable", \ "per_tile_counters_enable", \ "buffer_capture_compositor", \ "buffer_capture_window", \ "buffer_capture_other", \ "buffer_capture_n_frames", \ "buffer_capture_resize_factor", \ "sw_counters_enable", \ }; /** @brief struct to hold the value to a particular setting as seen in the kernel space */ typedef struct { _mali_uk_user_setting_t setting; u32 value; } _mali_uk_settings_changed_s; /** @brief Arguments for _mali_ukk_wait_for_notification() * * On successful return from _mali_ukk_wait_for_notification(), the members of * this structure will indicate the reason for notification. * * Specifically, the source of the notification can be identified by the * subsystem and id fields of the mali_uk_notification_type in the code.type * member. The type member is encoded in a way to divide up the types into a * subsystem field, and a per-subsystem ID field. See * _mali_uk_notification_type for more information. * * Interpreting the data union member depends on the notification type: * * - type == _MALI_NOTIFICATION_CORE_SHUTDOWN_IN_PROGRESS * - The kernel side is shutting down. No further * _mali_uk_wait_for_notification() calls should be made. * - In this case, the value of the data union member is undefined. * - This is used to indicate to the user space client that it should close * the connection to the Mali Device Driver. * - type == _MALI_NOTIFICATION_PP_FINISHED * - The notification data is of type _mali_uk_pp_job_finished_s. It contains the user_job_ptr * identifier used to start the job with, the job status, the number of milliseconds the job took to render, * and values of core registers when the job finished (irq status, performance counters, renderer list * address). * - A job has finished succesfully when its status member is _MALI_UK_JOB_STATUS_FINISHED. * - If the hardware detected a timeout while rendering the job, or software detected the job is * taking more than watchdog_msecs (see _mali_ukk_pp_start_job()) to complete, the status member will * indicate _MALI_UK_JOB_STATUS_HANG. * - If the hardware detected a bus error while accessing memory associated with the job, status will * indicate _MALI_UK_JOB_STATUS_SEG_FAULT. * - Status will indicate MALI_UK_JOB_STATUS_NOT_STARTED if the driver had to stop the job but the job * didn't start the hardware yet, e.g. when the driver closes. * - type == _MALI_NOTIFICATION_GP_FINISHED * - The notification data is of type _mali_uk_gp_job_finished_s. The notification is similar to that of * type == _MALI_NOTIFICATION_PP_FINISHED, except that several other GP core register values are returned. * The status values have the same meaning for type == _MALI_NOTIFICATION_PP_FINISHED. * - type == _MALI_NOTIFICATION_GP_STALLED * - The nofication data is of type _mali_uk_gp_job_suspended_s. It contains the user_job_ptr * identifier used to start the job with, the reason why the job stalled and a cookie to identify the core on * which the job stalled. * - The reason member of gp_job_suspended is set to _MALIGP_JOB_SUSPENDED_OUT_OF_MEMORY * when the polygon list builder unit has run out of memory. */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ _mali_uk_notification_type type; /**< [out] Type of notification available */ union { _mali_uk_gp_job_suspended_s gp_job_suspended;/**< [out] Notification data for _MALI_NOTIFICATION_GP_STALLED notification type */ _mali_uk_gp_job_finished_s gp_job_finished; /**< [out] Notification data for _MALI_NOTIFICATION_GP_FINISHED notification type */ _mali_uk_pp_job_finished_s pp_job_finished; /**< [out] Notification data for _MALI_NOTIFICATION_PP_FINISHED notification type */ _mali_uk_settings_changed_s setting_changed;/**< [out] Notification data for _MALI_NOTIFICAATION_SETTINGS_CHANGED notification type */ } data; } _mali_uk_wait_for_notification_s; /** @brief Arguments for _mali_ukk_post_notification() * * Posts the specified notification to the notification queue for this application. * This is used to send a quit message to the callback thread. */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ _mali_uk_notification_type type; /**< [in] Type of notification to post */ } _mali_uk_post_notification_s; /** @} */ /* end group _mali_uk_waitfornotification_s */ /** @defgroup _mali_uk_getapiversion_s Get API Version * @{ */ /** helpers for Device Driver API version handling */ /** @brief Encode a version ID from a 16-bit input * * @note the input is assumed to be 16 bits. It must not exceed 16 bits. */ #define _MAKE_VERSION_ID(x) (((x) << 16UL) | (x)) /** @brief Check whether a 32-bit value is likely to be Device Driver API * version ID. */ #define _IS_VERSION_ID(x) (((x) & 0xFFFF) == (((x) >> 16UL) & 0xFFFF)) /** @brief Decode a 16-bit version number from a 32-bit Device Driver API version * ID */ #define _GET_VERSION(x) (((x) >> 16UL) & 0xFFFF) /** @brief Determine whether two 32-bit encoded version IDs match */ #define _IS_API_MATCH(x, y) (IS_VERSION_ID((x)) && IS_VERSION_ID((y)) && (GET_VERSION((x)) == GET_VERSION((y)))) /** * API version define. * Indicates the version of the kernel API * The version is a 16bit integer incremented on each API change. * The 16bit integer is stored twice in a 32bit integer * For example, for version 1 the value would be 0x00010001 */ #define _MALI_API_VERSION 29 #define _MALI_UK_API_VERSION _MAKE_VERSION_ID(_MALI_API_VERSION) /** * The API version is a 16-bit integer stored in both the lower and upper 16-bits * of a 32-bit value. The 16-bit API version value is incremented on each API * change. Version 1 would be 0x00010001. Used in _mali_uk_get_api_version_s. */ typedef u32 _mali_uk_api_version; /** @brief Arguments for _mali_uk_get_api_version() * * The user-side interface version must be written into the version member, * encoded using _MAKE_VERSION_ID(). It will be compared to the API version of * the kernel-side interface. * * On successful return, the version member will be the API version of the * kernel-side interface. _MALI_UK_API_VERSION macro defines the current version * of the API. * * The compatible member must be checked to see if the version of the user-side * interface is compatible with the kernel-side interface, since future versions * of the interface may be backwards compatible. */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ _mali_uk_api_version version; /**< [in,out] API version of user-side interface. */ int compatible; /**< [out] @c 1 when @version is compatible, @c 0 otherwise */ } _mali_uk_get_api_version_s; /** @} */ /* end group _mali_uk_getapiversion_s */ /** @defgroup _mali_uk_get_user_settings_s Get user space settings * @{ */ /** @brief struct to keep the matching values of the user space settings within certain context * * Each member of the settings array corresponds to a matching setting in the user space and its value is the value * of that particular setting. * * All settings are given reference to the context pointed to by the ctx pointer. * */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32 settings[_MALI_UK_USER_SETTING_MAX]; /**< [out] The values for all settings */ } _mali_uk_get_user_settings_s; /** @brief struct to hold the value of a particular setting from the user space within a given context */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ _mali_uk_user_setting_t setting; /**< [in] setting to get */ u32 value; /**< [out] value of setting */ } _mali_uk_get_user_setting_s; /** @} */ /* end group _mali_uk_get_user_settings_s */ /** @brief Arguments for _mali_ukk_compositor_priority */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ } _mali_uk_compositor_priority_s; /** @} */ /* end group _mali_uk_core */ /** @defgroup _mali_uk_memory U/K Memory * @{ */ /** @brief Arguments for _mali_ukk_init_mem(). */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32 mali_address_base; /**< [out] start of MALI address space */ u32 memory_size; /**< [out] total MALI address space available */ } _mali_uk_init_mem_s; /** @brief Arguments for _mali_ukk_term_mem(). */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ } _mali_uk_term_mem_s; /** Flag for _mali_uk_map_external_mem_s, _mali_uk_attach_ump_mem_s and _mali_uk_attach_dma_buf_s */ #define _MALI_MAP_EXTERNAL_MAP_GUARD_PAGE (1<<0) typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32 phys_addr; /**< [in] physical address */ u32 size; /**< [in] size */ u32 mali_address; /**< [in] mali address to map the physical memory to */ u32 rights; /**< [in] rights necessary for accessing memory */ u32 flags; /**< [in] flags, see \ref _MALI_MAP_EXTERNAL_MAP_GUARD_PAGE */ u32 cookie; /**< [out] identifier for mapped memory object in kernel space */ } _mali_uk_map_external_mem_s; typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32 cookie; /**< [out] identifier for mapped memory object in kernel space */ } _mali_uk_unmap_external_mem_s; /** @note This is identical to _mali_uk_map_external_mem_s above, however phys_addr is replaced by memory descriptor */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32 mem_fd; /**< [in] Memory descriptor */ u32 size; /**< [in] size */ u32 mali_address; /**< [in] mali address to map the physical memory to */ u32 rights; /**< [in] rights necessary for accessing memory */ u32 flags; /**< [in] flags, see \ref _MALI_MAP_EXTERNAL_MAP_GUARD_PAGE */ u32 cookie; /**< [out] identifier for mapped memory object in kernel space */ } _mali_uk_attach_dma_buf_s; typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32 mem_fd; /**< [in] Memory descriptor */ u32 size; /**< [out] size */ } _mali_uk_dma_buf_get_size_s; typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32 cookie; /**< [in] identifier for mapped memory object in kernel space */ } _mali_uk_release_dma_buf_s; /** @note This is identical to _mali_uk_map_external_mem_s above, however phys_addr is replaced by secure_id */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32 secure_id; /**< [in] secure id */ u32 size; /**< [in] size */ u32 mali_address; /**< [in] mali address to map the physical memory to */ u32 rights; /**< [in] rights necessary for accessing memory */ u32 flags; /**< [in] flags, see \ref _MALI_MAP_EXTERNAL_MAP_GUARD_PAGE */ u32 cookie; /**< [out] identifier for mapped memory object in kernel space */ } _mali_uk_attach_ump_mem_s; typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32 cookie; /**< [in] identifier for mapped memory object in kernel space */ } _mali_uk_release_ump_mem_s; /** @brief Arguments for _mali_ukk_va_to_mali_pa() * * if size is zero or not a multiple of the system's page size, it will be * rounded up to the next multiple of the page size. This will occur before * any other use of the size parameter. * * if va is not PAGE_SIZE aligned, it will be rounded down to the next page * boundary. * * The range (va) to ((u32)va)+(size-1) inclusive will be checked for physical * contiguity. * * The implementor will check that the entire physical range is allowed to be mapped * into user-space. * * Failure will occur if either of the above are not satisfied. * * Otherwise, the physical base address of the range is returned through pa, * va is updated to be page aligned, and size is updated to be a non-zero * multiple of the system's pagesize. */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ void *va; /**< [in,out] Virtual address of the start of the range */ u32 pa; /**< [out] Physical base address of the range */ u32 size; /**< [in,out] Size of the range, in bytes. */ } _mali_uk_va_to_mali_pa_s; /** * @brief Arguments for _mali_uk[uk]_mem_write_safe() */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ const void *src; /**< [in] Pointer to source data */ void *dest; /**< [in] Destination Mali buffer */ u32 size; /**< [in,out] Number of bytes to write/copy on input, number of bytes actually written/copied on output */ } _mali_uk_mem_write_safe_s; typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32 size; /**< [out] size of MMU page table information (registers + page tables) */ } _mali_uk_query_mmu_page_table_dump_size_s; typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32 size; /**< [in] size of buffer to receive mmu page table information */ void *buffer; /**< [in,out] buffer to receive mmu page table information */ u32 register_writes_size; /**< [out] size of MMU register dump */ u32 *register_writes; /**< [out] pointer within buffer where MMU register dump is stored */ u32 page_table_dump_size; /**< [out] size of MMU page table dump */ u32 *page_table_dump; /**< [out] pointer within buffer where MMU page table dump is stored */ } _mali_uk_dump_mmu_page_table_s; /** @} */ /* end group _mali_uk_memory */ /** @addtogroup _mali_uk_pp U/K Fragment Processor * @{ */ /** @brief Arguments for _mali_ukk_get_pp_number_of_cores() * * - pass in the user-kernel context @c ctx that was returned from _mali_ukk_open() * - Upon successful return from _mali_ukk_get_pp_number_of_cores(), @c number_of_cores * will contain the number of Fragment Processor cores in the system. */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32 number_of_total_cores; /**< [out] Total number of Fragment Processor cores in the system */ u32 number_of_enabled_cores; /**< [out] Number of enabled Fragment Processor cores */ } _mali_uk_get_pp_number_of_cores_s; /** @brief Arguments for _mali_ukk_get_pp_core_version() * * - pass in the user-kernel context @c ctx that was returned from _mali_ukk_open() * - Upon successful return from _mali_ukk_get_pp_core_version(), @c version contains * the version that all Fragment Processor cores are compatible with. */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ _mali_core_version version; /**< [out] version returned from core, see \ref _mali_core_version */ } _mali_uk_get_pp_core_version_s; /** @} */ /* end group _mali_uk_pp */ /** @addtogroup _mali_uk_gp U/K Vertex Processor * @{ */ /** @brief Arguments for _mali_ukk_get_gp_number_of_cores() * * - pass in the user-kernel context @c ctx that was returned from _mali_ukk_open() * - Upon successful return from _mali_ukk_get_gp_number_of_cores(), @c number_of_cores * will contain the number of Vertex Processor cores in the system. */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32 number_of_cores; /**< [out] number of Vertex Processor cores in the system */ } _mali_uk_get_gp_number_of_cores_s; /** @brief Arguments for _mali_ukk_get_gp_core_version() * * - pass in the user-kernel context @c ctx that was returned from _mali_ukk_open() * - Upon successful return from _mali_ukk_get_gp_core_version(), @c version contains * the version that all Vertex Processor cores are compatible with. */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ _mali_core_version version; /**< [out] version returned from core, see \ref _mali_core_version */ } _mali_uk_get_gp_core_version_s; typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32 limit; /**< [in,out] The desired limit for number of events to record on input, actual limit on output */ } _mali_uk_profiling_start_s; typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32 event_id; /**< [in] event id to register (see enum mali_profiling_events for values) */ u32 data[5]; /**< [in] event specific data */ } _mali_uk_profiling_add_event_s; typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32 count; /**< [out] The number of events sampled */ } _mali_uk_profiling_stop_s; typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32 index; /**< [in] which index to get (starting at zero) */ u64 timestamp; /**< [out] timestamp of event */ u32 event_id; /**< [out] event id of event (see enum mali_profiling_events for values) */ u32 data[5]; /**< [out] event specific data */ } _mali_uk_profiling_get_event_s; typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ } _mali_uk_profiling_clear_s; /** @} */ /* end group _mali_uk_gp */ /** @addtogroup _mali_uk_memory U/K Memory * @{ */ /** @brief Arguments to _mali_ukk_mem_mmap() * * Use of the phys_addr member depends on whether the driver is compiled for * Mali-MMU or nonMMU: * - in the nonMMU case, this is the physical address of the memory as seen by * the CPU (which may be a constant offset from that used by Mali) * - in the MMU case, this is the Mali Virtual base address of the memory to * allocate, and the particular physical pages used to back the memory are * entirely determined by _mali_ukk_mem_mmap(). The details of the physical pages * are not reported to user-space for security reasons. * * The cookie member must be stored for use later when freeing the memory by * calling _mali_ukk_mem_munmap(). In the Mali-MMU case, the cookie is secure. * * The ukk_private word must be set to zero when calling from user-space. On * Kernel-side, the OS implementation of the U/K interface can use it to * communicate data to the OS implementation of the OSK layer. In particular, * _mali_ukk_get_big_block() directly calls _mali_ukk_mem_mmap directly, and * will communicate its own ukk_private word through the ukk_private member * here. The common code itself will not inspect or modify the ukk_private * word, and so it may be safely used for whatever purposes necessary to * integrate Mali Memory handling into the OS. * * The uku_private member is currently reserved for use by the user-side * implementation of the U/K interface. Its value must be zero. */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ void *mapping; /**< [out] Returns user-space virtual address for the mapping */ u32 size; /**< [in] Size of the requested mapping */ u32 phys_addr; /**< [in] Physical address - could be offset, depending on caller+callee convention */ u32 cookie; /**< [out] Returns a cookie for use in munmap calls */ void *uku_private; /**< [in] User-side Private word used by U/K interface */ void *ukk_private; /**< [in] Kernel-side Private word used by U/K interface */ mali_memory_cache_settings cache_settings; /**< [in] Option to set special cache flags, tuning L2 efficency */ } _mali_uk_mem_mmap_s; /** @brief Arguments to _mali_ukk_mem_munmap() * * The cookie and mapping members must be that returned from the same previous * call to _mali_ukk_mem_mmap(). The size member must correspond to cookie * and mapping - that is, it must be the value originally supplied to a call to * _mali_ukk_mem_mmap that returned the values of mapping and cookie. * * An error will be returned if an attempt is made to unmap only part of the * originally obtained range, or to unmap more than was originally obtained. */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ void *mapping; /**< [in] The mapping returned from mmap call */ u32 size; /**< [in] The size passed to mmap call */ u32 cookie; /**< [in] Cookie from mmap call */ } _mali_uk_mem_munmap_s; /** @} */ /* end group _mali_uk_memory */ /** @defgroup _mali_uk_vsync U/K VSYNC Wait Reporting Module * @{ */ /** @brief VSYNC events * * These events are reported when DDK starts to wait for vsync and when the * vsync has occured and the DDK can continue on the next frame. */ typedef enum _mali_uk_vsync_event { _MALI_UK_VSYNC_EVENT_BEGIN_WAIT = 0, _MALI_UK_VSYNC_EVENT_END_WAIT } _mali_uk_vsync_event; /** @brief Arguments to _mali_ukk_vsync_event() * */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ _mali_uk_vsync_event event; /**< [in] VSYNCH event type */ } _mali_uk_vsync_event_report_s; /** @} */ /* end group _mali_uk_vsync */ /** @defgroup _mali_uk_sw_counters_report U/K Software Counter Reporting * @{ */ /** @brief Software counter values * * Values recorded for each of the software counters during a single renderpass. */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ u32* counters; /**< [in] The array of counter values */ u32 num_counters; /**< [in] The number of elements in counters array */ } _mali_uk_sw_counters_report_s; /** @} */ /* end group _mali_uk_sw_counters_report */ /** @defgroup _mali_uk_stream U/K Mali stream module * @{ */ /** @brief Create stream */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ int fd; /**< [out] file descriptor describing stream */ } _mali_uk_stream_create_s; /** @brief Destroy stream */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ int fd; /**< [in] file descriptor describing stream */ } _mali_uk_stream_destroy_s; /** @brief Create empty fence */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ s32 stream; /**< [in] stream to create fence on */ s32 fence; /**< [out] file descriptor describing fence */ } _mali_uk_fence_create_empty_s; /** @brief Check fence validity */ typedef struct { void *ctx; /**< [in,out] user-kernel context (trashed on output) */ int fd; /**< [in] file descriptor describing fence */ } _mali_uk_fence_validate_s; /** @} */ /* end group _mali_uk_stream */ /** @} */ /* end group u_k_api */ /** @} */ /* end group uddapi */ #ifdef __cplusplus } #endif #endif /* __MALI_UTGARD_UK_TYPES_H__ */
Oebbler/elite-boeffla-kernel-cm12.1-i9300
drivers/gpu/mali400/r3p2/mali/include/linux/mali/mali_utgard_uk_types.h
C
gpl-2.0
53,700
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * This file is part of Beaver Parser Generator. * * Copyright (C) 2003,2004 Alexander Demenchuk <[email protected]>. * * All rights reserved. * * See the file "LICENSE" for the terms and conditions for copying, * * distribution and modification of Beaver. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package beaver; /** * An "interface" to Java code executed when a production is reduced. */ public abstract class Action { static public final Action NONE = new Action() { public Symbol reduce(Symbol[] args, int offset) { return new Symbol(null); } }; static public final Action RETURN = new Action() { public Symbol reduce(Symbol[] args, int offset) { return args[offset + 1]; } }; /** * Am action code that is executed when the production is reduced. * * @param args an array part of which is filled with this action arguments * @param offset to the last element <b>BEFORE</b> the first argument of this action * @return a symbol or a value of a LHS nonterminal */ public abstract Symbol reduce(Symbol[] args, int offset); }
BuddhaLabs/DeD-OSX
soot/soot-2.3.0/generated/jastadd/beaver/Action.java
Java
gpl-2.0
1,327
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include "common/str.h" #include "gob/gob.h" #include "gob/goblin.h" #include "gob/global.h" #include "gob/util.h" #include "gob/draw.h" #include "gob/game.h" #include "gob/map.h" #include "gob/mult.h" #include "gob/scenery.h" #include "gob/inter.h" #include "gob/sound/sound.h" namespace Gob { Goblin::Goblin(GobEngine *vm) : _vm(vm) { _goesAtTarget = 0; _readyToAct = 0; _gobAction = 0; _itemIndInPocket = 5; _itemIdInPocket = 2; _itemByteFlag = 0; _destItemId = -1; _destActionItem = 0; _actDestItemDesc = 0; _forceNextState[0] = -1; _forceNextState[1] = -1; _forceNextState[2] = -1; _forceNextState[3] = -1; _forceNextState[4] = -1; _forceNextState[5] = -1; _forceNextState[6] = -1; _forceNextState[7] = 0; _forceNextState[8] = 0; _forceNextState[9] = 0; _boreCounter = 0; _positionedGob = 5; _noPick = 0; _objList = 0; for (int i = 0; i < 4; i++) _goblins[i] = 0; for (int i = 0; i < 3; i++) { _gobPositions[i].x = 0; _gobPositions[i].y = 0; } _currentGoblin = 0; _gobDestX = 0; _gobDestY = 0; _pressedMapX = 0; _pressedMapY = 0; _pathExistence = 0; _destItemType = 0; _destItemState = 0; for (int i = 0; i < 20; i++) { _itemToObject[i] = 0; _objects[i] = 0; } _objCount = 0; _gobsCount = 0; _soundSlotsCount = 0; for (int i = 0; i < 60; i++) _soundSlots[i] = -1; _gob1Busy = false; _gob2Busy = false; _gob1RelaxTimeVar = 0; _gob2RelaxTimeVar = 0; _gob1NoTurn = false; _gob2NoTurn = false; } Goblin::~Goblin() { int i, state, col; if (_objList) _vm->_util->deleteList(_objList); for (i = 0; i < 4; i++) { if (_goblins[i]) { if (_goblins[i]->realStateMach) { for (state = 0; state < (i == 3 ? 70 : 40); state++) if (_goblins[i]->realStateMach[state]) for (col = 0; col < 6; col++) if (_goblins[i]->realStateMach[state][col]) delete _goblins[i]->realStateMach[state][col]; delete[] _goblins[i]->realStateMach; } delete _goblins[i]; } } for (i = 0; i < 20; i++) { if (_objects[i]) { if (_objects[i]->realStateMach) { for (state = 0; state < 40; state++) for (col = 0; col < 6; col++) if (_objects[i]->realStateMach[state][col]) delete _objects[i]->realStateMach[state][col]; delete[] _objects[i]->realStateMach; } delete _objects[i]; } } for (i = 0; i < 16; i++) _soundData[i].free(); } char Goblin::rotateState(int16 from, int16 to) { return _rotStates[from / 2][to / 2]; } int16 Goblin::peekGoblin(Gob_Object *_curGob) { Util::ListNode *ptr; Gob_Object *desc; int16 index; int16 i; ptr = _objList->pHead; index = 0; while (ptr != 0) { desc = (Gob_Object *)ptr->pData; if (desc != _curGob) { for (i = 0; i < 3; i++) { if (desc != _goblins[i]) continue; if ((_vm->_global->_inter_mouseX < desc->right) && (_vm->_global->_inter_mouseX > desc->left) && (_vm->_global->_inter_mouseY < desc->bottom) && (_vm->_global->_inter_mouseY > desc->top)) { index = i + 1; } } } ptr = ptr->pNext; } return index; } void Goblin::initList() { _objList = new Util::List; _objList->pHead = 0; _objList->pTail = 0; } void Goblin::sortByOrder(Util::List *list) { Util::ListNode *ptr; Util::ListNode *ptr2; ptr = list->pHead; while (ptr->pNext != 0) { for (ptr2 = ptr->pNext; ptr2 != 0; ptr2 = ptr2->pNext) { Gob_Object *objDesc = (Gob_Object *)ptr->pData; Gob_Object *objDesc2 = (Gob_Object *)ptr2->pData; if (objDesc->order <= objDesc2->order) { if (objDesc->order != objDesc2->order) continue; if (objDesc->bottom <= objDesc2->bottom) { if (objDesc->bottom != objDesc2->bottom) continue; if (objDesc != _goblins[_currentGoblin]) continue; } } SWAP(ptr->pData, ptr2->pData); } ptr = ptr->pNext; } } void Goblin::playSound(SoundDesc &snd, int16 repCount, int16 freq) { if (!snd.empty()) { _vm->_sound->blasterStop(0); _vm->_sound->blasterPlay(&snd, repCount, freq); } } void Goblin::drawObjects() { Util::ListNode *ptr; Util::ListNode *ptr2; Gob_Object *objDesc; Gob_Object *gobDesc2; int16 layer; ptr = _objList->pHead; for (ptr = _objList->pHead; ptr != 0; ptr = ptr->pNext) { objDesc = (Gob_Object *)ptr->pData; if (objDesc->type == 3) objDesc->toRedraw = 1; else if (objDesc->type == 1) objDesc->toRedraw = 0; } for (ptr = _objList->pHead; ptr != 0; ptr = ptr->pNext) { objDesc = (Gob_Object *)ptr->pData; if (objDesc->toRedraw == 0) continue; _vm->_draw->_backSurface->blit(*_vm->_mult->_animSurf, objDesc->left, objDesc->top, objDesc->right, objDesc->bottom, objDesc->left, objDesc->top); _vm->_draw->invalidateRect(objDesc->left, objDesc->top, objDesc->right, objDesc->bottom); if (objDesc->type != 0) continue; layer = objDesc->stateMach[objDesc->state][objDesc->stateColumn]-> layer; _vm->_scenery->updateAnim(layer, objDesc->curFrame, objDesc->animation, 0, objDesc->xPos, objDesc->yPos, 0); if (_vm->_scenery->_toRedrawLeft == -12345) { objDesc->dirtyLeft = objDesc->left; objDesc->dirtyRight = objDesc->right; objDesc->dirtyTop = objDesc->top; objDesc->dirtyBottom = objDesc->bottom; } else { objDesc->dirtyLeft = MIN(objDesc->left, _vm->_scenery->_toRedrawLeft); objDesc->dirtyRight = MAX(objDesc->right, _vm->_scenery->_toRedrawRight); objDesc->dirtyTop = MIN(objDesc->top, _vm->_scenery->_toRedrawTop); objDesc->dirtyBottom = MAX(objDesc->bottom, _vm->_scenery->_toRedrawBottom); } objDesc->dirtyLeft = 0; objDesc->dirtyRight = 319; objDesc->dirtyTop = 0; objDesc->dirtyBottom = 199; } sortByOrder(_objList); for (ptr = _objList->pHead; ptr != 0; ptr = ptr->pNext) { objDesc = (Gob_Object *)ptr->pData; if (objDesc->toRedraw) { layer = objDesc->stateMach[objDesc->state][objDesc-> stateColumn]->layer; if (objDesc->type == 0) { if (objDesc->visible == 0) { _vm->_scenery->updateAnim(layer, objDesc->curFrame, objDesc->animation, 0, objDesc->xPos, objDesc->yPos, 0); } else { _vm->_scenery->updateAnim(layer, objDesc->curFrame, objDesc->animation, 2, objDesc->xPos, objDesc->yPos, 1); } if (_vm->_scenery->_toRedrawLeft == -12345) { objDesc->left = 0; objDesc->top = 0; objDesc->right = 0; objDesc->bottom = 0; } else { _vm->_draw->invalidateRect(_vm->_scenery->_toRedrawLeft, _vm->_scenery->_toRedrawTop, _vm->_scenery->_toRedrawRight, _vm->_scenery->_toRedrawBottom); objDesc->left = _vm->_scenery->_toRedrawLeft; objDesc->top = _vm->_scenery->_toRedrawTop; objDesc->right = _vm->_scenery->_toRedrawRight; objDesc->bottom = _vm->_scenery->_toRedrawBottom; _vm->_scenery->updateStatic(objDesc->order); } } else { objDesc->left = 0; objDesc->top = 0; objDesc->right = 0; objDesc->bottom = 0; objDesc->type = 1; } continue; } if ((objDesc->type == 0) && (objDesc->visible != 0)) { for (ptr2 = _objList->pHead; ptr2 != 0; ptr2 = ptr2->pNext) { gobDesc2 = (Gob_Object *)ptr2->pData; if (gobDesc2->toRedraw == 0) continue; if (objDesc->right < gobDesc2->dirtyLeft) continue; if (gobDesc2->dirtyRight < objDesc->left) continue; if (objDesc->bottom < gobDesc2->dirtyTop) continue; if (gobDesc2->dirtyBottom < objDesc->top) continue; _vm->_scenery->_toRedrawLeft = gobDesc2->dirtyLeft; _vm->_scenery->_toRedrawRight = gobDesc2->dirtyRight; _vm->_scenery->_toRedrawTop = gobDesc2->dirtyTop; _vm->_scenery->_toRedrawBottom = gobDesc2->dirtyBottom; layer = objDesc->stateMach[objDesc-> state][objDesc->stateColumn]->layer; _vm->_scenery->updateAnim(layer, objDesc->curFrame, objDesc->animation, 4, objDesc->xPos, objDesc->yPos, 1); _vm->_scenery->updateStatic(objDesc->order); } } } for (ptr = _objList->pHead; ptr != 0; ptr = ptr->pNext) { objDesc = (Gob_Object *)ptr->pData; if ((objDesc->toRedraw == 0) || (objDesc->type == 1)) continue; Gob_State *state = objDesc->stateMach[objDesc->state][objDesc->stateColumn]; int16 sndFrame; int16 sndItem; int16 freq; int16 repCount; if (state->sndFrame & 0xFF00) { // There are two frames which trigger a sound effect, // so everything has to be encoded in one byte each. // Note that the frequency is multiplied by 100, not - // as I would have thought, 0x100. sndFrame = (state->sndFrame >> 8) & 0xFF; sndItem = (state->sndItem >> 8) & 0xFF; freq = 100 * ((state->freq >> 8) & 0xFF); repCount = (state->repCount >> 8) & 0xFF; if (objDesc->curFrame == sndFrame) { if (sndItem != 0xFF) { playSound(_soundData[sndItem], repCount, freq); } } sndFrame = state->sndFrame & 0xFF; sndItem = state->sndItem & 0xFF; freq = 100 * (state->freq & 0xFF); repCount = state->repCount & 0xFF; if (objDesc->curFrame == sndFrame) { if (sndItem != 0xFF) { playSound(_soundData[sndItem], repCount, freq); } } } else { // There is only one, so frequency etc. are used as is. sndFrame = state->sndFrame; sndItem = state->sndItem; freq = state->freq; repCount = state->repCount; if (objDesc->curFrame == sndFrame) { if (sndItem != -1) { playSound(_soundData[sndItem], repCount, freq); } } } } } void Goblin::animateObjects() { Util::ListNode *node; Gob_Object *objDesc; Scenery::AnimLayer *pLayer; int16 layer; for (node = _objList->pHead; node != 0; node = node->pNext) { objDesc = (Gob_Object *)node->pData; if ((objDesc->doAnim != 1) || (objDesc->type != 0)) continue; if (objDesc->noTick != 0) continue; if (objDesc->tick < objDesc->maxTick) objDesc->tick++; if (objDesc->tick >= objDesc->maxTick) { objDesc->tick = 1; objDesc->curFrame++; layer = objDesc->stateMach[objDesc->state][0]->layer; pLayer = _vm->_scenery->getAnimLayer(objDesc->animation, layer); if (objDesc->curFrame < pLayer->framesCount) continue; objDesc->curFrame = 0; objDesc->xPos += pLayer->animDeltaX; objDesc->yPos += pLayer->animDeltaY; if ((objDesc->nextState == -1) && (objDesc->multState == -1) && (objDesc->unk14 == 0)) { objDesc->toRedraw = 0; objDesc->curFrame = pLayer->framesCount - 1; } if (objDesc->multState != -1) { if (objDesc->multState > 39) { objDesc->stateMach = _goblins[(int)(objDesc->multObjIndex)]->stateMach; objDesc->state = objDesc->multState - 40; } else { objDesc->stateMach = objDesc->realStateMach; objDesc->state = objDesc->multState; } objDesc->animation = objDesc->stateMach[objDesc->state][0]-> animation; objDesc->multState = -1; } else { if (objDesc->nextState == -1) continue; objDesc->stateMach = objDesc->realStateMach; objDesc->state = objDesc->nextState; objDesc->animation = objDesc->stateMach[objDesc->state][0]-> animation; objDesc->nextState = -1; } objDesc->toRedraw = 1; } } } int16 Goblin::getObjMaxFrame(Gob_Object * objDesc) { int16 layer; layer = objDesc->stateMach[objDesc->state][0]->layer; return _vm->_scenery->getAnimLayer(objDesc->animation, layer)->framesCount - 1; } bool Goblin::objIntersected(Gob_Object *obj1, Gob_Object *obj2) { if ((obj1->type == 1) || (obj2->type == 1)) return false; if (obj1->right < obj2->left) return false; if (obj1->left > obj2->right) return false; if (obj1->bottom < obj2->top) return false; if (obj1->top > obj2->bottom) return false; return true; } void Goblin::setMultStates(Gob_Object * gobDesc) { gobDesc->stateMach = _goblins[(int)gobDesc->multObjIndex]->stateMach; } int16 Goblin::nextLayer(Gob_Object *gobDesc) { if (gobDesc->nextState == 10) gobDesc->curLookDir = 0; if (gobDesc->nextState == 11) gobDesc->curLookDir = 4; if (gobDesc->nextState > 39) { setMultStates(gobDesc); } else { gobDesc->stateMach = gobDesc->realStateMach; } gobDesc->curFrame = 0; if (gobDesc->nextState > 39) gobDesc->state = gobDesc->nextState - 40; else gobDesc->state = gobDesc->nextState; gobDesc->animation = gobDesc->stateMach[gobDesc->state][0]->animation; return gobDesc->stateMach[gobDesc->state][0]->layer; } void Goblin::showBoredom(int16 gobIndex) { Gob_Object *gobDesc; int16 frame; int16 frameCount; int16 layer; int16 state; int16 boreFlag; gobDesc = _goblins[gobIndex]; layer = gobDesc->stateMach[gobDesc->state][0]->layer; frameCount = _vm->_scenery->getAnimLayer(gobDesc->animation, layer)->framesCount; state = gobDesc->state; frame = gobDesc->curFrame; gobDesc->noTick = 0; gobDesc->toRedraw = 1; boreFlag = 1 << _vm->_util->getRandom(7); if (gobIndex != _currentGoblin && _vm->_util->getRandom(3) != 0) { if (state == 21) { if ((boreFlag & 16) || (boreFlag & 32)) { gobDesc->multState = 92 + gobIndex; } else if (boreFlag & 1) { gobDesc->multState = 86 + gobIndex; } else if (boreFlag & 2) { gobDesc->multState = 80 + gobIndex; } else if (boreFlag & 4) { gobDesc->multState = 89 + gobIndex; } else if (boreFlag & 8) { gobDesc->multState = 104 + gobIndex; } } gobDesc->nextState = 21; } else if ((state >= 18) && (state <= 21) && (VAR(59) == 0)) { if ((state == 30) || (state == 31)) // ??? return; if (frame != frameCount) return; gobDesc->multState = 104 + gobIndex; } } // index - goblin to select+1 // index==0 - switch to next void Goblin::switchGoblin(int16 index) { int16 next; int16 tmp; debugC(4, kDebugGameFlow, "switchGoblin"); if (VAR(59) != 0) return; if ((_goblins[_currentGoblin]->state <= 39) && (_goblins[_currentGoblin]->curFrame != 0)) return; if ((index != 0) && (_goblins[index - 1]->type != 0)) return; if (index == 0) next = (_currentGoblin + 1) % 3; else next = index - 1; if ((_vm->_map->getPass(_vm->_map->_curGoblinX, _vm->_map->_curGoblinY) == 3) || (_vm->_map->getPass(_vm->_map->_curGoblinX, _vm->_map->_curGoblinY) == 6)) return; if ((_goblins[(_currentGoblin + 1) % 3]->type != 0) && (_goblins[(_currentGoblin + 2) % 3]->type != 0)) return; _gobPositions[_currentGoblin].x = _vm->_map->_curGoblinX; _gobPositions[_currentGoblin].y = _vm->_map->_curGoblinY; _goblins[_currentGoblin]->doAnim = 1; _goblins[_currentGoblin]->nextState = 21; nextLayer(_goblins[_currentGoblin]); _currentGoblin = next; if (_goblins[_currentGoblin]->type != 0) _currentGoblin = (_currentGoblin + 1) % 3; _goblins[_currentGoblin]->doAnim = 0; if (_goblins[_currentGoblin]->curLookDir == 4) _goblins[_currentGoblin]->nextState = 18; else _goblins[_currentGoblin]->nextState = 19; _goblins[_currentGoblin]->toRedraw = 1; nextLayer(_goblins[_currentGoblin]); tmp = _gobPositions[_currentGoblin].x; _pressedMapX = tmp; _vm->_map->_destX = tmp; _gobDestX = tmp; _vm->_map->_curGoblinX = tmp; tmp = _gobPositions[_currentGoblin].y; _pressedMapY = tmp; _vm->_map->_destY = tmp; _gobDestY = tmp; _vm->_map->_curGoblinY = tmp; _curGobVarPtr = (uint32) _currentGoblin; _pathExistence = 0; _readyToAct = 0; } void Goblin::adjustDest(int16 posX, int16 posY) { int16 resDelta; int16 resDeltaDir; int16 resDeltaPix; int16 deltaPix; int16 i; if ((_vm->_map->getPass(_pressedMapX, _pressedMapY) == 0) && ((_gobAction == 0) || (_vm->_map->getItem(_pressedMapX, _pressedMapY) == 0))) { resDelta = -1; resDeltaDir = 0; resDeltaPix = 0; for (i = 1; (i <= _pressedMapX) && (_vm->_map->getPass(_pressedMapX - i, _pressedMapY) == 0); i++) ; if (i <= _pressedMapX) { resDeltaPix = (i - 1) * 12 + (posX % 12) + 1; resDelta = i; } for (i = 1; ((i + _pressedMapX) < _vm->_map->getMapWidth()) && (_vm->_map->getPass(_pressedMapX + i, _pressedMapY) == 0); i++) ; if ((_pressedMapX + i) < _vm->_map->getMapWidth()) { deltaPix = (i * 12) - (posX % 12); if ((resDelta == -1) || (deltaPix < resDeltaPix)) { resDeltaPix = deltaPix; resDelta = i; resDeltaDir = 1; } } for (i = 1; ((i + _pressedMapY) < _vm->_map->getMapHeight()) && (_vm->_map->getPass(_pressedMapX, _pressedMapY + i) == 0); i++) ; if ((_pressedMapY + i) < _vm->_map->getMapHeight()) { deltaPix = (i * 6) - (posY % 6); if ((resDelta == -1) || (deltaPix < resDeltaPix)) { resDeltaPix = deltaPix; resDelta = i; resDeltaDir = 2; } } for (i = 1; (i <= _pressedMapY) && (_vm->_map->getPass(_pressedMapX, _pressedMapY - i) == 0); i++) ; if (i <= _pressedMapY) { deltaPix = (i * 6) + (posY % 6); if ((resDelta == -1) || (deltaPix < resDeltaPix)) { resDeltaPix = deltaPix; resDelta = i; resDeltaDir = 3; } } switch (resDeltaDir) { case 0: _pressedMapX -= resDelta; break; case 1: _pressedMapX += resDelta; break; case 2: _pressedMapY += resDelta; break; case 3: _pressedMapY -= resDelta; break; } } _pressedMapX = CLIP((int)_pressedMapX, 0, _vm->_map->getMapWidth() - 1); _pressedMapY = CLIP((int)_pressedMapY, 0, _vm->_map->getMapHeight() - 1); } void Goblin::adjustTarget() { if ((_gobAction == 4) && (_vm->_map->getItem(_pressedMapX, _pressedMapY) == 0)) { if ((_pressedMapY > 0) && (_vm->_map->getItem(_pressedMapX, _pressedMapY - 1) != 0)) { _pressedMapY--; } else if ((_pressedMapX < (_vm->_map->getMapWidth() - 1)) && (_vm->_map->getItem(_pressedMapX + 1, _pressedMapY) != 0)) { _pressedMapX++; } else if ((_pressedMapX < (_vm->_map->getMapWidth() - 1)) && (_pressedMapY > 0) && (_vm->_map->getItem(_pressedMapX + 1, _pressedMapY - 1) != 0)) { _pressedMapY--; _pressedMapX++; } } _pressedMapX = CLIP((int)_pressedMapX, 0, _vm->_map->getMapWidth() - 1); _pressedMapY = CLIP((int)_pressedMapY, 0, _vm->_map->getMapHeight() - 1); } void Goblin::targetDummyItem(Gob_Object *gobDesc) { if (_vm->_map->getItem(_pressedMapX, _pressedMapY) == 0 && _vm->_map->getPass(_pressedMapX, _pressedMapY) == 1) { if (gobDesc->curLookDir == 0) { _vm->_map->_itemPoses[0].x = _pressedMapX; _vm->_map->_itemPoses[0].y = _pressedMapY; _vm->_map->_itemPoses[0].orient = -4; } else { _vm->_map->_itemPoses[0].x = _pressedMapX; _vm->_map->_itemPoses[0].y = _pressedMapY; _vm->_map->_itemPoses[0].orient = -1; } } } void Goblin::targetItem() { int16 tmpX; int16 tmpY; int16 items; int16 layer; int16 tmpPosX; int16 tmpPosY; Gob_Object *itemDesc; if ((_gobAction == 3) || (_gobAction == 4)) { items = _vm->_map->getItem(_pressedMapX, _pressedMapY); if ((_gobAction == 4) && ((items & 0xFF00) != 0) && (_objects[_itemToObject[(items & 0xFF00) >> 8]]->pickable == 1)) { _destItemId = (items & 0xFF00) >> 8; _destActionItem = (items & 0xFF00) >> 8; _itemByteFlag = 1; } else if ((items & 0xFF) == 0) { _destItemId = (items & 0xFF00) >> 8; _destActionItem = (items & 0xFF00) >> 8; _itemByteFlag = 1; } else if ((_gobAction == 3) && (_currentGoblin == 2) && ((items & 0xFF00) != 0)) { _destItemId = (items & 0xFF00) >> 8; _destActionItem = (items & 0xFF00) >> 8; _itemByteFlag = 1; } else { _destItemId = items & 0xFF; _destActionItem = items & 0xFF; _itemByteFlag = 0; } _pressedMapY = _vm->_map->_itemPoses[_destItemId].y; _vm->_map->_destY = _vm->_map->_itemPoses[_destItemId].y; _gobDestY = _vm->_map->_itemPoses[_destItemId].y; if ((_gobAction == 3) || (_destActionItem == 0)) { _pressedMapX = _vm->_map->_itemPoses[_destItemId].x; _vm->_map->_destX = _vm->_map->_itemPoses[_destItemId].x; _gobDestX = _vm->_map->_itemPoses[_destItemId].x; } else if ((items & 0xFF00) != 0) { if (_vm->_map->_itemPoses[_destItemId].orient == 4) { if ((_vm->_map->getItem(_pressedMapX - 1, _pressedMapY) & 0xFF00) == (_vm->_map->getItem(_pressedMapX, _pressedMapY) & 0xFF00)) { _pressedMapX--; _vm->_map->_destX = _pressedMapX; _gobDestX = _pressedMapX; } } else if (_vm->_map->_itemPoses[_destItemId].orient == 0) { if ((_vm->_map->getItem(_pressedMapX + 1, _pressedMapY) & 0xFF00) == (_vm->_map->getItem(_pressedMapX, _pressedMapY) & 0xFF00)) { _pressedMapX++; _vm->_map->_destX = _pressedMapX; _gobDestX = _pressedMapX; } } if ((_vm->_map->getItem(_pressedMapX, _pressedMapY + 1) & 0xFF00) == (_vm->_map->getItem(_pressedMapX, _pressedMapY) & 0xFF00)) { _pressedMapY++; _vm->_map->_destY = _pressedMapY; _gobDestY = _pressedMapY; } } else { if (_vm->_map->_itemPoses[_destItemId].orient == 4) { if ((_vm->_map->getItem(_pressedMapX - 1, _pressedMapY)) == (_vm->_map->getItem(_pressedMapX, _pressedMapY))) { _pressedMapX--; _vm->_map->_destX = _pressedMapX; _gobDestX = _pressedMapX; } } else if (_vm->_map->_itemPoses[_destItemId].orient == 0) { if ((_vm->_map->getItem(_pressedMapX + 1, _pressedMapY)) == (_vm->_map->getItem(_pressedMapX, _pressedMapY))) { _pressedMapX++; _vm->_map->_destX = _pressedMapX; _gobDestX = _pressedMapX; } } if (_pressedMapY < (_vm->_map->getMapHeight()-1)) { if ((_vm->_map->getItem(_pressedMapX, _pressedMapY + 1)) == (_vm->_map->getItem(_pressedMapX, _pressedMapY))) { _pressedMapY++; _vm->_map->_destY = _pressedMapY; _gobDestY = _pressedMapY; } } } if ((_gobAction == 4) && (_destActionItem != 0) && (_itemToObject[_destActionItem] != -1) && (_objects[_itemToObject[_destActionItem]]->pickable == 1)) { itemDesc = _objects[_itemToObject[_destActionItem]]; itemDesc->animation = itemDesc->stateMach[itemDesc->state][0]->animation; layer = itemDesc->stateMach[itemDesc->state][itemDesc->stateColumn]->layer; _vm->_scenery->updateAnim(layer, 0, itemDesc->animation, 0, itemDesc->xPos, itemDesc->yPos, 0); tmpX = (_vm->_scenery->_toRedrawRight + _vm->_scenery->_toRedrawLeft) / 2; tmpY = _vm->_scenery->_toRedrawBottom; tmpPosY = tmpY / 6; if (((tmpY % 3) < 3) && (tmpPosY > 0)) tmpPosY--; tmpPosX = tmpX / 12; if (((tmpX % 12) < 6) && (tmpPosX > 0)) tmpPosX--; if ((_vm->_map->_itemPoses[_destActionItem].orient == 0) || (_vm->_map->_itemPoses[_destActionItem].orient == -1)) { tmpPosX++; } if (_vm->_map->getPass(tmpPosX, tmpPosY) == 1) { _pressedMapX = tmpPosX; _vm->_map->_destX = tmpPosX; _gobDestX = tmpPosX; _pressedMapY = tmpPosY; _vm->_map->_destY = tmpPosY; _gobDestY = tmpPosY; } } } _pressedMapX = CLIP((int)_pressedMapX, 0, _vm->_map->getMapWidth() - 1); _pressedMapY = CLIP((int)_pressedMapY, 0, _vm->_map->getMapHeight() - 1); } void Goblin::moveFindItem(int16 posX, int16 posY) { int16 i; if ((_gobAction == 3) || (_gobAction == 4)) { for (i = 0; i < 20; i++) { if (_objects[i] == 0) continue; if (_objects[i]->type != 0) continue; if (_objects[i]->left > posX) continue; if (_objects[i]->right < posX) continue; if (_objects[i]->top > posY) continue; if (_objects[i]->bottom < posY) continue; if ((_objects[i]->right - _objects[i]->left) < 40) posX = (_objects[i]->left + _objects[i]->right) / 2; if ((_objects[i]->bottom - _objects[i]->top) < 40) posY = (_objects[i]->top + _objects[i]->bottom) / 2; break; } _pressedMapX = CLIP(posX / 12, 0, _vm->_map->getMapWidth() - 1); _pressedMapY = CLIP(posY / 6, 0, _vm->_map->getMapHeight() - 1); if ((_vm->_map->getItem(_pressedMapX, _pressedMapY) == 0) && (i < 20)) { if ((_pressedMapY < (_vm->_map->getMapHeight() - 1)) && (_vm->_map->getItem(_pressedMapX, _pressedMapY + 1) != 0)) { _pressedMapY++; } else if ((_pressedMapX < (_vm->_map->getMapWidth() - 1)) && (_pressedMapY < (_vm->_map->getMapHeight() - 1)) && (_vm->_map->getItem(_pressedMapX + 1, _pressedMapY + 1) != 0)) { _pressedMapX++; _pressedMapY++; } else if ((_pressedMapX < (_vm->_map->getMapWidth() - 1)) && (_vm->_map->getItem(_pressedMapX + 1, _pressedMapY) != 0)) { _pressedMapX++; } else if ((_pressedMapX < (_vm->_map->getMapWidth() - 1)) && (_pressedMapY > 0) && (_vm->_map->getItem(_pressedMapX + 1, _pressedMapY - 1) != 0)) { _pressedMapX++; _pressedMapY--; } else if ((_pressedMapY > 0) && (_vm->_map->getItem(_pressedMapX, _pressedMapY - 1) != 0)) { _pressedMapY--; } else if ((_pressedMapY > 0) && (_pressedMapX > 0) && (_vm->_map->getItem(_pressedMapX - 1, _pressedMapY - 1) != 0)) { _pressedMapY--; _pressedMapX--; } else if ((_pressedMapX > 0) && (_vm->_map->getItem(_pressedMapX - 1, _pressedMapY) != 0)) { _pressedMapX--; } else if ((_pressedMapX > 0) && (_pressedMapY < (_vm->_map->getMapHeight() - 1)) && (_vm->_map->getItem(_pressedMapX - 1, _pressedMapY + 1) != 0)) { _pressedMapX--; _pressedMapY++; } } } else { _pressedMapX = CLIP(posX / 12, 0, _vm->_map->getMapWidth() - 1); _pressedMapY = CLIP(posY / 6, 0, _vm->_map->getMapHeight() - 1); } } void Goblin::moveCheckSelect(int16 framesCount, Gob_Object *gobDesc, int16 *pGobIndex, int16 *nextAct) { if ((gobDesc->right > _vm->_global->_inter_mouseX) && (gobDesc->left < _vm->_global->_inter_mouseX) && (gobDesc->bottom > _vm->_global->_inter_mouseY) && ((gobDesc->bottom - 10) < _vm->_global->_inter_mouseY) && (_gobAction == 0)) { if (gobDesc->curLookDir & 4) *nextAct = 16; else *nextAct = 23; gobDesc->curFrame = framesCount - 1; _pathExistence = 0; } else { *pGobIndex = peekGoblin(gobDesc); if (*pGobIndex != 0) { _pathExistence = 0; } else if ((_vm->_map->_curGoblinX == _pressedMapX) && (_vm->_map->_curGoblinY == _pressedMapY)) { if (_gobAction != 0) _readyToAct = 1; _pathExistence = 0; } } } void Goblin::moveInitStep(int16 framesCount, int16 action, int16 cont, Gob_Object *gobDesc, int16 *pGobIndex, int16 *pNextAct) { int16 posX; int16 posY; if ((cont != 0) && (_goesAtTarget == 0) && (_readyToAct == 0) && (VAR(59) == 0) && (gobDesc->type != 1) && (gobDesc->state != 10) && (gobDesc->state != 11)) { if (gobDesc->state >= 40) { gobDesc->curFrame = framesCount - 1; } _gobAction = action; _forceNextState[0] = -1; _forceNextState[1] = -1; _forceNextState[2] = -1; if (action == 3) { posX = _vm->_global->_inter_mouseX + 6; posY = _vm->_global->_inter_mouseY + 7; } else if (action == 4) { posX = _vm->_global->_inter_mouseX + 7; posY = _vm->_global->_inter_mouseY + 12; } else { posX = _vm->_global->_inter_mouseX; posY = _vm->_global->_inter_mouseY; } moveFindItem(posX, posY); adjustDest(posX, posY); adjustTarget(); _vm->_map->_destX = _pressedMapX; _gobDestX = _pressedMapX; _vm->_map->_destY = _pressedMapY; _gobDestY = _pressedMapY; targetDummyItem(gobDesc); targetItem(); initiateMove(0); moveCheckSelect(framesCount, gobDesc, pGobIndex, pNextAct); } else { if ((_readyToAct != 0) && ((_vm->_map->_curGoblinX != _pressedMapX) || (_vm->_map->_curGoblinY != _pressedMapY))) _readyToAct = 0; if (gobDesc->type == 1) { *pGobIndex = peekGoblin(gobDesc); } } } void Goblin::moveTreatRopeStairs(Gob_Object *gobDesc) { if (_currentGoblin != 1) return; if ((gobDesc->nextState == 28) && (_vm->_map->getPass(_vm->_map->_curGoblinX, _vm->_map->_curGoblinY - 1) == 6)) { _forceNextState[0] = 28; _forceNextState[1] = -1; } if ((gobDesc->nextState == 29) && (_vm->_map->getPass(_vm->_map->_curGoblinX, _vm->_map->_curGoblinY + 1) == 6)) { _forceNextState[0] = 29; _forceNextState[1] = -1; } if (((gobDesc->nextState == 28) || (gobDesc->nextState == 29) || (gobDesc->nextState == 20)) && (_vm->_map->getPass(_vm->_map->_curGoblinX, _vm->_map->_curGoblinY) == 6)) { if (((gobDesc->curLookDir == 0) || (gobDesc->curLookDir == 4) || (gobDesc->curLookDir == 2)) && (_vm->_map->getPass(_vm->_map->_curGoblinX, _vm->_map->_curGoblinY - 1) == 6)) { _forceNextState[0] = 28; _forceNextState[1] = -1; } else if (((gobDesc->curLookDir == 0) || (gobDesc->curLookDir == 4) || (gobDesc->curLookDir == 6)) && (_vm->_map->getPass(_vm->_map->_curGoblinX, _vm->_map->_curGoblinY + 1) == 6)) { _forceNextState[0] = 29; _forceNextState[1] = -1; } } if ((gobDesc->nextState == 8) && (_vm->_map->getPass(_vm->_map->_curGoblinX, _vm->_map->_curGoblinY - 1) == 3)) { _forceNextState[0] = 8; _forceNextState[1] = -1; } if ((gobDesc->nextState == 9) && (_vm->_map->getPass(_vm->_map->_curGoblinX, _vm->_map->_curGoblinY + 1) == 3)) { _forceNextState[0] = 9; _forceNextState[1] = -1; } if ((gobDesc->nextState == 20) && (_vm->_map->getPass(_vm->_map->_curGoblinX, _vm->_map->_curGoblinY) == 3)) { if (((gobDesc->curLookDir == 0) || (gobDesc->curLookDir == 4) || (gobDesc->curLookDir == 2)) && (_vm->_map->getPass(_vm->_map->_curGoblinX, _vm->_map->_curGoblinY - 1) == 3)) { _forceNextState[0] = 8; _forceNextState[1] = -1; } else if (((gobDesc->curLookDir == 0) || (gobDesc->curLookDir == 4) || (gobDesc->curLookDir == 6)) && (_vm->_map->getPass(_vm->_map->_curGoblinX, _vm->_map->_curGoblinY + 1) == 3)) { _forceNextState[0] = 9; _forceNextState[1] = -1; } } } int16 Goblin::doMove(Gob_Object *gobDesc, int16 cont, int16 action) { int16 framesCount; int16 nextAct; int16 gobIndex; int16 layer; nextAct = 0; gobIndex = 0; layer = gobDesc->stateMach[gobDesc->state][0]->layer; framesCount = _vm->_scenery->getAnimLayer(gobDesc->animation, layer)->framesCount; if ((VAR(59) == 0) && (gobDesc->state != 30) && (gobDesc->state != 31)) { gobDesc->order = (gobDesc->bottom) / 24 + 3; } if (_positionedGob != _currentGoblin) { _vm->_map->_curGoblinX = _gobPositions[_currentGoblin].x; _vm->_map->_curGoblinY = _gobPositions[_currentGoblin].y; } _positionedGob = _currentGoblin; gobDesc->animation = gobDesc->stateMach[gobDesc->state][gobDesc->stateColumn]->animation; _gobStateLayer = gobDesc->stateMach[gobDesc->state][gobDesc->stateColumn]->layer; moveInitStep(framesCount, action, cont, gobDesc, &gobIndex, &nextAct); moveTreatRopeStairs(gobDesc); moveAdvance(0, gobDesc, nextAct, framesCount); return gobIndex; } void Goblin::zeroObjects() { for (int i = 0; i < 4; i++) _goblins[i] = 0; for (int i = 0; i < 20; i++) _objects[i] = 0; for (int i = 0; i < 16; i++) _vm->_sound->sampleFree(&_soundData[i]); } void Goblin::freeAllObjects() { _vm->_util->deleteList(_objList); _objList = 0; freeObjects(); } void Goblin::loadObjects(const char *source) { zeroObjects(); for (int i = 0; i < 20; i++) _itemToObject[i] = 100; freeObjects(); initList(); Common::strlcpy(_vm->_map->_sourceFile, source, 15); _vm->_map->_sourceFile[strlen(_vm->_map->_sourceFile) - 4] = 0; _vm->_map->loadMapObjects(source); for (int i = 0; i < _gobsCount; i++) placeObject(_goblins[i], 0, 0, 0, 0, 0); for (int i = 0; i < _objCount; i++) placeObject(_objects[i], 1, 0, 0, 0, 0); initVarPointers(); _actDestItemDesc = 0; } void Goblin::saveGobDataToVars(int16 xPos, int16 yPos, int16 someVal) { Gob_Object *obj; _some0ValPtr = (uint32) someVal; _curGobXPosVarPtr = (uint32) xPos; _curGobYPosVarPtr = (uint32) yPos; _itemInPocketVarPtr = (uint32) _itemIndInPocket; obj = _goblins[_currentGoblin]; _curGobStateVarPtr = (uint32) obj->state; _curGobFrameVarPtr = (uint32) obj->curFrame; _curGobMultStateVarPtr = (uint32) obj->multState; _curGobNextStateVarPtr = (uint32) obj->nextState; _curGobScrXVarPtr = (uint32) obj->xPos; _curGobScrYVarPtr = (uint32) obj->yPos; _curGobLeftVarPtr = (uint32) obj->left; _curGobTopVarPtr = (uint32) obj->top; _curGobRightVarPtr = (uint32) obj->right; _curGobBottomVarPtr = (uint32) obj->bottom; _curGobDoAnimVarPtr = (uint32) obj->doAnim; _curGobOrderVarPtr = (uint32) obj->order; _curGobNoTickVarPtr = (uint32) obj->noTick; _curGobTypeVarPtr = (uint32) obj->type; _curGobMaxTickVarPtr = (uint32) obj->maxTick; _curGobTickVarPtr = (uint32) obj->tick; _curGobActStartStateVarPtr = (uint32) obj->actionStartState; _curGobLookDirVarPtr = (uint32) obj->curLookDir; _curGobPickableVarPtr = (uint32) obj->pickable; _curGobRelaxVarPtr = (uint32) obj->relaxTime; _curGobMaxFrameVarPtr = (uint32) getObjMaxFrame(obj); if (_actDestItemDesc == 0) return; obj = _actDestItemDesc; _destItemStateVarPtr = (uint32) obj->state; _destItemFrameVarPtr = (uint32) obj->curFrame; _destItemMultStateVarPtr = (uint32) obj->multState; _destItemNextStateVarPtr = (uint32) obj->nextState; _destItemScrXVarPtr = (uint32) obj->xPos; _destItemScrYVarPtr = (uint32) obj->yPos; _destItemLeftVarPtr = (uint32) obj->left; _destItemTopVarPtr = (uint32) obj->top; _destItemRightVarPtr = (uint32) obj->right; _destItemBottomVarPtr = (uint32) obj->bottom; _destItemDoAnimVarPtr = (uint32) obj->doAnim; _destItemOrderVarPtr = (uint32) obj->order; _destItemNoTickVarPtr = (uint32) obj->noTick; _destItemTypeVarPtr = (uint32) obj->type; _destItemMaxTickVarPtr = (uint32) obj->maxTick; _destItemTickVarPtr = (uint32) obj->tick; _destItemActStartStVarPtr = (uint32) obj->actionStartState; _destItemLookDirVarPtr = (uint32) obj->curLookDir; _destItemPickableVarPtr = (uint32) obj->pickable; _destItemRelaxVarPtr = (uint32) obj->relaxTime; _destItemMaxFrameVarPtr = (uint32) getObjMaxFrame(obj); _destItemState = obj->state; _destItemType = obj->type; } void Goblin::initVarPointers() { _gobRetVarPtr.set(*_vm->_inter->_variables, 236); _curGobStateVarPtr.set(*_vm->_inter->_variables, 240); _curGobFrameVarPtr.set(*_vm->_inter->_variables, 244); _curGobMultStateVarPtr.set(*_vm->_inter->_variables, 248); _curGobNextStateVarPtr.set(*_vm->_inter->_variables, 252); _curGobScrXVarPtr.set(*_vm->_inter->_variables, 256); _curGobScrYVarPtr.set(*_vm->_inter->_variables, 260); _curGobLeftVarPtr.set(*_vm->_inter->_variables, 264); _curGobTopVarPtr.set(*_vm->_inter->_variables, 268); _curGobRightVarPtr.set(*_vm->_inter->_variables, 272); _curGobBottomVarPtr.set(*_vm->_inter->_variables, 276); _curGobDoAnimVarPtr.set(*_vm->_inter->_variables, 280); _curGobOrderVarPtr.set(*_vm->_inter->_variables, 284); _curGobNoTickVarPtr.set(*_vm->_inter->_variables, 288); _curGobTypeVarPtr.set(*_vm->_inter->_variables, 292); _curGobMaxTickVarPtr.set(*_vm->_inter->_variables, 296); _curGobTickVarPtr.set(*_vm->_inter->_variables, 300); _curGobActStartStateVarPtr.set(*_vm->_inter->_variables, 304); _curGobLookDirVarPtr.set(*_vm->_inter->_variables, 308); _curGobPickableVarPtr.set(*_vm->_inter->_variables, 320); _curGobRelaxVarPtr.set(*_vm->_inter->_variables, 324); _destItemStateVarPtr.set(*_vm->_inter->_variables, 328); _destItemFrameVarPtr.set(*_vm->_inter->_variables, 332); _destItemMultStateVarPtr.set(*_vm->_inter->_variables, 336); _destItemNextStateVarPtr.set(*_vm->_inter->_variables, 340); _destItemScrXVarPtr.set(*_vm->_inter->_variables, 344); _destItemScrYVarPtr.set(*_vm->_inter->_variables, 348); _destItemLeftVarPtr.set(*_vm->_inter->_variables, 352); _destItemTopVarPtr.set(*_vm->_inter->_variables, 356); _destItemRightVarPtr.set(*_vm->_inter->_variables, 360); _destItemBottomVarPtr.set(*_vm->_inter->_variables, 364); _destItemDoAnimVarPtr.set(*_vm->_inter->_variables, 368); _destItemOrderVarPtr.set(*_vm->_inter->_variables, 372); _destItemNoTickVarPtr.set(*_vm->_inter->_variables, 376); _destItemTypeVarPtr.set(*_vm->_inter->_variables, 380); _destItemMaxTickVarPtr.set(*_vm->_inter->_variables, 384); _destItemTickVarPtr.set(*_vm->_inter->_variables, 388); _destItemActStartStVarPtr.set(*_vm->_inter->_variables, 392); _destItemLookDirVarPtr.set(*_vm->_inter->_variables, 396); _destItemPickableVarPtr.set(*_vm->_inter->_variables, 408); _destItemRelaxVarPtr.set(*_vm->_inter->_variables, 412); _destItemMaxFrameVarPtr.set(*_vm->_inter->_variables, 420); _curGobVarPtr.set(*_vm->_inter->_variables, 424); _some0ValPtr.set(*_vm->_inter->_variables, 428); _curGobXPosVarPtr.set(*_vm->_inter->_variables, 432); _curGobYPosVarPtr.set(*_vm->_inter->_variables, 436); _curGobMaxFrameVarPtr.set(*_vm->_inter->_variables, 440); _itemInPocketVarPtr.set(*_vm->_inter->_variables, 456); _itemInPocketVarPtr = (uint32) -2; } void Goblin::loadGobDataFromVars() { Gob_Object *obj; _itemIndInPocket = (int32) _itemInPocketVarPtr; obj = _goblins[_currentGoblin]; obj->state = (int32) _curGobStateVarPtr; obj->curFrame = (int32) _curGobFrameVarPtr; obj->multState = (int32) _curGobMultStateVarPtr; obj->nextState = (int32) _curGobNextStateVarPtr; obj->xPos = (int32) _curGobScrXVarPtr; obj->yPos = (int32) _curGobScrYVarPtr; obj->left = (int32) _curGobLeftVarPtr; obj->top = (int32) _curGobTopVarPtr; obj->right = (int32) _curGobRightVarPtr; obj->bottom = (int32) _curGobBottomVarPtr; obj->doAnim = (int32) _curGobDoAnimVarPtr; obj->order = (int32) _curGobOrderVarPtr; obj->noTick = (int32) _curGobNoTickVarPtr; obj->type = (int32) _curGobTypeVarPtr; obj->maxTick = (int32) _curGobMaxTickVarPtr; obj->tick = (int32) _curGobTickVarPtr; obj->actionStartState = (int32) _curGobActStartStateVarPtr; obj->curLookDir = (int32) _curGobLookDirVarPtr; obj->pickable = (int32) _curGobPickableVarPtr; obj->relaxTime = (int32) _curGobRelaxVarPtr; if (_actDestItemDesc == 0) return; obj = _actDestItemDesc; obj->state = (int32) _destItemStateVarPtr; obj->curFrame = (int32) _destItemFrameVarPtr; obj->multState = (int32) _destItemMultStateVarPtr; obj->nextState = (int32) _destItemNextStateVarPtr; obj->xPos = (int32) _destItemScrXVarPtr; obj->yPos = (int32) _destItemScrYVarPtr; obj->left = (int32) _destItemLeftVarPtr; obj->top = (int32) _destItemTopVarPtr; obj->right = (int32) _destItemRightVarPtr; obj->bottom = (int32) _destItemBottomVarPtr; obj->doAnim = (int32) _destItemDoAnimVarPtr; obj->order = (int32) _destItemOrderVarPtr; obj->noTick = (int32) _destItemNoTickVarPtr; obj->type = (int32) _destItemTypeVarPtr; obj->maxTick = (int32) _destItemMaxTickVarPtr; obj->tick = (int32) _destItemTickVarPtr; obj->actionStartState = (int32) _destItemActStartStVarPtr; obj->curLookDir = (int32) _destItemLookDirVarPtr; obj->pickable = (int32) _destItemPickableVarPtr; obj->relaxTime = (int32) _destItemRelaxVarPtr; if (obj->type != _destItemType) obj->toRedraw = 1; if ((obj->state != _destItemState) && (obj->type == 0)) obj->toRedraw = 1; } void Goblin::pickItem(int16 indexToPocket, int16 idToPocket) { if (_objects[indexToPocket]->pickable != 1) return; _objects[indexToPocket]->type = 3; _itemIndInPocket = indexToPocket; _itemIdInPocket = idToPocket; for (int y = 0; y < _vm->_map->getMapHeight(); y++) { for (int x = 0; x < _vm->_map->getMapWidth(); x++) { if (_itemByteFlag == 1) { if (((_vm->_map->getItem(x, y) & 0xFF00) >> 8) == idToPocket) _vm->_map->setItem(x, y, _vm->_map->getItem(x, y) & 0xFF); } else { if ((_vm->_map->getItem(x, y) & 0xFF) == idToPocket) _vm->_map->setItem(x, y, _vm->_map->getItem(x, y) & 0xFF00); } } } if ((idToPocket >= 0) && (idToPocket < 20)) { _vm->_map->_itemPoses[_itemIdInPocket].x = 0; _vm->_map->_itemPoses[_itemIdInPocket].y = 0; _vm->_map->_itemPoses[_itemIdInPocket].orient = 0; } } void Goblin::placeItem(int16 indexInPocket, int16 idInPocket) { Gob_Object *itemDesc; int16 lookDir; int16 xPos; int16 yPos; int16 layer; itemDesc = _objects[indexInPocket]; lookDir = _goblins[0]->curLookDir & 4; xPos = _gobPositions[0].x; yPos = _gobPositions[0].y; _itemIndInPocket = -1; _itemIdInPocket = 0; itemDesc->pickable = 1; itemDesc->type = 0; itemDesc->toRedraw = 1; itemDesc->curFrame = 0; itemDesc->order = _goblins[0]->order; itemDesc->animation = itemDesc->stateMach[itemDesc->state][0]->animation; layer = itemDesc->stateMach[itemDesc->state][itemDesc->stateColumn]->layer; _vm->_scenery->updateAnim(layer, 0, itemDesc->animation, 0, itemDesc->xPos, itemDesc->yPos, 0); itemDesc->yPos += (_gobPositions[0].y * 6) + 5 - _vm->_scenery->_toRedrawBottom; if (lookDir == 4) itemDesc->xPos += (_gobPositions[0].x * 12 + 14) - (_vm->_scenery->_toRedrawLeft + _vm->_scenery->_toRedrawRight) / 2; else itemDesc->xPos += (_gobPositions[0].x * 12) - (_vm->_scenery->_toRedrawLeft + _vm->_scenery->_toRedrawRight) / 2; _vm->_map->placeItem(xPos, yPos, idInPocket); if (yPos > 0) _vm->_map->placeItem(xPos, yPos - 1, idInPocket); if (lookDir == 4) { if (xPos < _vm->_map->getMapWidth() - 1) { _vm->_map->placeItem(xPos + 1, yPos, idInPocket); if (yPos > 0) _vm->_map->placeItem(xPos + 1, yPos - 1, idInPocket); } } else { if (xPos > 0) { _vm->_map->placeItem(xPos - 1, yPos, idInPocket); if (yPos > 0) _vm->_map->placeItem(xPos - 1, yPos - 1, idInPocket); } } if ((idInPocket >= 0) && (idInPocket < 20)) { _vm->_map->_itemPoses[idInPocket].x = _gobPositions[0].x; _vm->_map->_itemPoses[idInPocket].y = _gobPositions[0].y; _vm->_map->_itemPoses[idInPocket].orient = lookDir; if (_vm->_map->_itemPoses[idInPocket].orient == 0) { if (_vm->_map->getPass(_vm->_map->_itemPoses[idInPocket].x + 1, (int)_vm->_map->_itemPoses[idInPocket].y) == 1) _vm->_map->_itemPoses[idInPocket].x++; } else { if (_vm->_map->getPass(_vm->_map->_itemPoses[idInPocket].x - 1, (int)_vm->_map->_itemPoses[idInPocket].y) == 1) _vm->_map->_itemPoses[idInPocket].x--; } } } void Goblin::swapItems(int16 indexToPick, int16 idToPick) { int16 layer; Gob_Object *pickObj; Gob_Object *placeObj; int16 idToPlace; int16 x, y; pickObj = _objects[indexToPick]; placeObj = _objects[_itemIndInPocket]; idToPlace = _itemIdInPocket; pickObj->type = 3; _itemIndInPocket = indexToPick; _itemIdInPocket = idToPick; if (_itemByteFlag == 0) { for (y = 0; y < _vm->_map->getMapHeight(); y++) { for (x = 0; x < _vm->_map->getMapWidth(); x++) { if ((_vm->_map->getItem(x, y) & 0xFF) == idToPick) _vm->_map->setItem(x, y, (_vm->_map->getItem(x, y) & 0xFF00) + idToPlace); } } } else { for (y = 0; y < _vm->_map->getMapHeight(); y++) { for (x = 0; x < _vm->_map->getMapWidth(); x++) { if (((_vm->_map->getItem(x, y) & 0xFF00) >> 8) == idToPick) _vm->_map->setItem(x, y, (_vm->_map->getItem(x, y) & 0xFF) + (idToPlace << 8)); } } } if (idToPick >= 0 && idToPick < 20) { _vm->_map->_itemPoses[idToPlace].x = _vm->_map->_itemPoses[_itemIdInPocket].x; _vm->_map->_itemPoses[idToPlace].y = _vm->_map->_itemPoses[_itemIdInPocket].y; _vm->_map->_itemPoses[idToPlace].orient = _vm->_map->_itemPoses[_itemIdInPocket].orient; _vm->_map->_itemPoses[_itemIdInPocket].x = 0; _vm->_map->_itemPoses[_itemIdInPocket].y = 0; _vm->_map->_itemPoses[_itemIdInPocket].orient = 0; } _itemIndInPocket = -1; _itemIdInPocket = 0; placeObj->type = 0; placeObj->nextState = -1; placeObj->multState = -1; placeObj->unk14 = 0; placeObj->toRedraw = 1; placeObj->curFrame = 0; placeObj->order = _goblins[0]->order; placeObj->animation = placeObj->stateMach[placeObj->state][0]->animation; layer = placeObj->stateMach[placeObj->state][placeObj->stateColumn]->layer; _vm->_scenery->updateAnim(layer, 0, placeObj->animation, 0, placeObj->xPos, placeObj->yPos, 0); placeObj->yPos += (_gobPositions[0].y * 6) + 5 - _vm->_scenery->_toRedrawBottom; if (_vm->_map->_itemPoses[idToPlace].orient == 4) placeObj->xPos += (_gobPositions[0].x * 12 + 14) - (_vm->_scenery->_toRedrawLeft + _vm->_scenery->_toRedrawRight) / 2; else placeObj->xPos += (_gobPositions[0].x * 12) - (_vm->_scenery->_toRedrawLeft + _vm->_scenery->_toRedrawRight) / 2; } void Goblin::treatItemPick(int16 itemId) { int16 itemIndex; Gob_Object *gobDesc; gobDesc = _goblins[_currentGoblin]; if (gobDesc->curFrame != 9) return; if (gobDesc->stateMach != gobDesc->realStateMach) return; _readyToAct = 0; _goesAtTarget = 0; itemIndex = _itemToObject[itemId]; if ((itemId != 0) && (itemIndex != -1) && (_objects[itemIndex]->pickable != 1)) itemIndex = -1; if ((_itemIndInPocket != -1) && (_itemIndInPocket == itemIndex)) itemIndex = -1; if ((_itemIndInPocket != -1) && (itemIndex != -1) && (_objects[itemIndex]->pickable == 1)) { swapItems(itemIndex, itemId); _itemIndInPocket = itemIndex; _itemIdInPocket = itemId; return; } if ((_itemIndInPocket != -1) && (itemIndex == -1)) { placeItem(_itemIndInPocket, _itemIdInPocket); return; } if ((_itemIndInPocket == -1) && (itemIndex != -1)) { pickItem(itemIndex, itemId); return; } } int16 Goblin::treatItem(int16 action) { int16 state; state = _goblins[_currentGoblin]->state; if (((state == 10) || (state == 11)) && (_goblins[_currentGoblin]->curFrame == 0)) { _readyToAct = 0; } if ((action == 3) && (_currentGoblin == 0) && ((state == 10) || (state == 11)) && (_goblins[0]->curFrame == 0)) { saveGobDataToVars(_gobPositions[_currentGoblin].x, _gobPositions[_currentGoblin].y, 0); _goesAtTarget = 1; return -1; } if ((_noPick == 0) && (_currentGoblin == 0) && ((state == 10) || (state == 11))) { treatItemPick(_destActionItem); saveGobDataToVars(_gobPositions[_currentGoblin].x, _gobPositions[_currentGoblin].y, 0); return 0; } if (_goesAtTarget == 0) { saveGobDataToVars(_gobPositions[_currentGoblin].x, _gobPositions[_currentGoblin].y, 0); return 0; } else { if ((_itemToObject[_destActionItem] != 100) && (_destActionItem != 0)) { if (_itemToObject[_destActionItem] == -1) _actDestItemDesc = 0; else _actDestItemDesc = _objects[_itemToObject[_destActionItem]]; } _goesAtTarget = 0; saveGobDataToVars(_gobPositions[_currentGoblin].x, _gobPositions[_currentGoblin].y, 0); return _destActionItem; } } void Goblin::playSounds(Mult::Mult_Object *obj) { Mult::Mult_AnimData *animData; bool speaker; int16 frequency; int16 repCount; int16 sndSlot; int16 frame; if (!obj->goblinStates) return; animData = obj->pAnimData; for (int i = 1; i <= obj->goblinStates[animData->state][0].dataCount; i++) { speaker = obj->goblinStates[animData->state][i].speaker != 0; if ((obj->goblinStates[animData->state][i].sndItem != -1) || (speaker == 1)) { frame = obj->goblinStates[animData->state][i].sndFrame; repCount = obj->goblinStates[animData->state][i].repCount; frequency = obj->goblinStates[animData->state][i].freq; if (animData->frame != frame) continue; if (!speaker) { sndSlot = obj->goblinStates[animData->state][i].sndItem; _vm->_sound->blasterStop(0); if (sndSlot < _soundSlotsCount) _vm->_sound->blasterPlay(_vm->_sound->sampleGetBySlot(_soundSlots[sndSlot] & 0x7FFF), repCount, frequency); } else _vm->_sound->speakerOn(frequency, repCount * 10); } } } void Goblin::setState(int16 index, int16 state) { Mult::Mult_Object *obj; Mult::Mult_AnimData *animData; int16 layer; int16 animation; obj = &_vm->_mult->_objects[index]; animData = obj->pAnimData; if (obj->goblinStates[state] == 0) return; layer = obj->goblinStates[state][0].layer; animation = obj->goblinStates[state][0].animation; animData->layer = layer; animData->animation = animation; animData->state = state; animData->frame = 0; animData->isPaused = 0; animData->isStatic = 0; animData->newCycle = _vm->_scenery->getAnimLayer(animation, layer)->framesCount; _vm->_scenery->updateAnim(layer, 0, animation, 0, *obj->pPosX, *obj->pPosY, 1); if (_vm->_map->hasBigTiles()) { *obj->pPosY = ((obj->goblinY + 1) * _vm->_map->getTilesHeight()) - (_vm->_scenery->_animBottom - _vm->_scenery->_animTop) - (obj->goblinY + 1) / 2; } else { *obj->pPosY = (obj->goblinY + 1) * _vm->_map->getTilesHeight() - (_vm->_scenery->_animBottom - _vm->_scenery->_animTop); } *obj->pPosX = obj->goblinX * _vm->_map->getTilesWidth(); } void Goblin::animate(Mult::Mult_Object *obj) { Mult::Mult_AnimData *animData; int16 layer; int16 animation; int16 framesCount; animData = obj->pAnimData; if (animData->isStatic != 0) return; layer = obj->goblinStates[animData->state][0].layer; animation = obj->goblinStates[animData->state][0].animation; framesCount = _vm->_scenery->getAnimLayer(animation, layer)->framesCount; animData->newCycle = framesCount; playSounds(obj); if (animData->isPaused == 0) animData->frame++; switch (animData->stateType) { case 0: case 1: animData->isPaused = 0; break; case 4: if (animData->frame == 0) animData->isPaused = 1; break; case 6: if (animData->frame >= framesCount) animData->isPaused = 1; break; } if ((animData->newState == -1) && (animData->frame >= framesCount)) { if (animData->framesLeft <= 0) { animData->framesLeft = animData->maxFrame; animData->frame = 0; } else animData->framesLeft --; } if (animData->frame < framesCount) return; if (animData->newState != -1) { animData->frame = 0; animData->state = animData->newState; animData->newState = -1; animData->animation = obj->goblinStates[animData->state][0].animation; animData->layer = obj->goblinStates[animData->state][0].layer; Scenery::AnimLayer *animLayer = _vm->_scenery->getAnimLayer(animation, layer); *obj->pPosX += animLayer->animDeltaX; *obj->pPosY += animLayer->animDeltaY; animData->newCycle = animLayer->framesCount; animData->isPaused = 0; } else animData->frame--; } void Goblin::move(int16 destX, int16 destY, int16 objIndex) { Mult::Mult_Object *obj = &_vm->_mult->_objects[objIndex]; Mult::Mult_AnimData *animData = obj->pAnimData; obj->gobDestX = destX; obj->gobDestY = destY; animData->destX = destX; animData->destY = destY; if (animData->isBusy != 0) { if ((destX == -1) && (destY == -1)) { int16 mouseX = _vm->_global->_inter_mouseX; int16 mouseY = _vm->_global->_inter_mouseY; if (_vm->_map->hasBigTiles()) mouseY += ((_vm->_global->_inter_mouseY / _vm->_map->getTilesHeight()) + 1) / 2; int16 gobDestX = mouseX / _vm->_map->getTilesWidth(); int16 gobDestY = mouseY / _vm->_map->getTilesHeight(); if (_vm->_map->getPass(gobDestX, gobDestY) == 0) _vm->_map->findNearestWalkable(gobDestX, gobDestY, mouseX, mouseY); obj->gobDestX = (gobDestX == -1) ? obj->goblinX : gobDestX; obj->gobDestY = (gobDestY == -1) ? obj->goblinY : gobDestY; animData->destX = obj->gobDestX; animData->destY = obj->gobDestY; } } WRITE_VAR(56, 0); byte passType = _vm->_map->getPass(obj->gobDestX, obj->gobDestY); // Prevent continuous walking on wide stairs if (passType == 11) { if (_vm->_map->getScreenWidth() == 640) { obj->gobDestY++; animData->destY++; } } // Prevent stopping in the middle of big ladders if ((passType == 19) || (passType == 20)) { int ladderTop = 0; while (_vm->_map->getPass(obj->gobDestX, obj->gobDestY + ladderTop) == passType) ladderTop++; int ladderBottom = 0; while (_vm->_map->getPass(obj->gobDestX, obj->gobDestY + ladderBottom) == passType) ladderBottom--; int ladderDest; if (ABS(ladderBottom) <= ladderTop) ladderDest = obj->gobDestY + ladderBottom; else ladderDest = obj->gobDestY + ladderTop; obj->gobDestY = ladderDest; animData->destY = ladderDest; } initiateMove(obj); } void Goblin::updateLayer1(Mult::Mult_AnimData *animData) { switch (animData->state) { case 2: animData->layer = 8; break; case 6: animData->layer = 9; break; case 17: animData->layer = 26; break; case 18: animData->layer = 32; break; case 21: animData->layer = 22; break; case 22: animData->layer = 20; break; case 23: animData->layer = 21; break; } } void Goblin::updateLayer2(Mult::Mult_AnimData *animData) { switch (animData->state) { case 2: animData->layer = 10; break; case 6: animData->layer = 11; break; case 17: animData->layer = 29; break; case 18: animData->layer = 35; break; case 21: animData->layer = 25; break; case 22: animData->layer = 23; break; case 23: animData->layer = 24; break; } } } // End of namespace Gob
alexbevi/scummvm
engines/gob/goblin.cpp
C++
gpl-2.0
53,315
%{ /* x86/linux lburg spec. Derived from x86.md by Marcos Ramirez <[email protected]> Horst von Brand <[email protected]> Jacob Navia <[email protected]> */ enum { EAX=0, ECX=1, EDX=2, EBX=3, ESI=6, EDI=7 }; #include "c.h" #define NODEPTR_TYPE Node #define OP_LABEL(p) ((p)->op) #define LEFT_CHILD(p) ((p)->kids[0]) #define RIGHT_CHILD(p) ((p)->kids[1]) #define STATE_LABEL(p) ((p)->x.state) extern int ckstack(Node, int); extern int memop(Node); extern int sametree(Node, Node); static Symbol charreg[32], shortreg[32], intreg[32]; static Symbol fltreg[32]; static Symbol charregw, shortregw, intregw, fltregw; static int cseg; static Symbol quo, rem; extern char *stabprefix; extern void stabblock(int, int, Symbol*); extern void stabend(Coordinate *, Symbol, Coordinate **, Symbol *, Symbol *); extern void stabfend(Symbol, int); extern void stabinit(char *, int, char *[]); extern void stabline(Coordinate *); extern void stabsym(Symbol); extern void stabtype(Symbol); static int pflag = 0; static char rcsid[] = "$Id: x86linux.md,v 1.1.1.1 2001/10/17 21:53:38 timo Exp $"; #define hasargs(p) (p->syms[0] && p->syms[0]->u.c.v.i > 0 ? 0 : LBURG_MAX) %} %start stmt %term CNSTF4=4113 %term CNSTF8=8209 %term CNSTF16=16401 %term CNSTI1=1045 %term CNSTI2=2069 %term CNSTI4=4117 %term CNSTI8=8213 %term CNSTP4=4119 %term CNSTP8=8215 %term CNSTU1=1046 %term CNSTU2=2070 %term CNSTU4=4118 %term CNSTU8=8214 %term ARGB=41 %term ARGF4=4129 %term ARGF8=8225 %term ARGF16=16417 %term ARGI4=4133 %term ARGI8=8229 %term ARGP4=4135 %term ARGP8=8231 %term ARGU4=4134 %term ARGU8=8230 %term ASGNB=57 %term ASGNF4=4145 %term ASGNF8=8241 %term ASGNF16=16433 %term ASGNI1=1077 %term ASGNI2=2101 %term ASGNI4=4149 %term ASGNI8=8245 %term ASGNP4=4151 %term ASGNP8=8247 %term ASGNU1=1078 %term ASGNU2=2102 %term ASGNU4=4150 %term ASGNU8=8246 %term INDIRB=73 %term INDIRF4=4161 %term INDIRF8=8257 %term INDIRF16=16449 %term INDIRI1=1093 %term INDIRI2=2117 %term INDIRI4=4165 %term INDIRI8=8261 %term INDIRP4=4167 %term INDIRP8=8263 %term INDIRU1=1094 %term INDIRU2=2118 %term INDIRU4=4166 %term INDIRU8=8262 %term CVFF4=4209 %term CVFF8=8305 %term CVFF16=16497 %term CVFI4=4213 %term CVFI8=8309 %term CVIF4=4225 %term CVIF8=8321 %term CVIF16=16513 %term CVII1=1157 %term CVII2=2181 %term CVII4=4229 %term CVII8=8325 %term CVIU1=1158 %term CVIU2=2182 %term CVIU4=4230 %term CVIU8=8326 %term CVPP4=4247 %term CVPP8=8343 %term CVPP16=16535 %term CVPU4=4246 %term CVPU8=8342 %term CVUI1=1205 %term CVUI2=2229 %term CVUI4=4277 %term CVUI8=8373 %term CVUP4=4279 %term CVUP8=8375 %term CVUP16=16567 %term CVUU1=1206 %term CVUU2=2230 %term CVUU4=4278 %term CVUU8=8374 %term NEGF4=4289 %term NEGF8=8385 %term NEGF16=16577 %term NEGI4=4293 %term NEGI8=8389 %term CALLB=217 %term CALLF4=4305 %term CALLF8=8401 %term CALLF16=16593 %term CALLI4=4309 %term CALLI8=8405 %term CALLP4=4311 %term CALLP8=8407 %term CALLU4=4310 %term CALLU8=8406 %term CALLV=216 %term RETF4=4337 %term RETF8=8433 %term RETF16=16625 %term RETI4=4341 %term RETI8=8437 %term RETP4=4343 %term RETP8=8439 %term RETU4=4342 %term RETU8=8438 %term RETV=248 %term ADDRGP4=4359 %term ADDRGP8=8455 %term ADDRFP4=4375 %term ADDRFP8=8471 %term ADDRLP4=4391 %term ADDRLP8=8487 %term ADDF4=4401 %term ADDF8=8497 %term ADDF16=16689 %term ADDI4=4405 %term ADDI8=8501 %term ADDP4=4407 %term ADDP8=8503 %term ADDU4=4406 %term ADDU8=8502 %term SUBF4=4417 %term SUBF8=8513 %term SUBF16=16705 %term SUBI4=4421 %term SUBI8=8517 %term SUBP4=4423 %term SUBP8=8519 %term SUBU4=4422 %term SUBU8=8518 %term LSHI4=4437 %term LSHI8=8533 %term LSHU4=4438 %term LSHU8=8534 %term MODI4=4453 %term MODI8=8549 %term MODU4=4454 %term MODU8=8550 %term RSHI4=4469 %term RSHI8=8565 %term RSHU4=4470 %term RSHU8=8566 %term BANDI4=4485 %term BANDI8=8581 %term BANDU4=4486 %term BANDU8=8582 %term BCOMI4=4501 %term BCOMI8=8597 %term BCOMU4=4502 %term BCOMU8=8598 %term BORI4=4517 %term BORI8=8613 %term BORU4=4518 %term BORU8=8614 %term BXORI4=4533 %term BXORI8=8629 %term BXORU4=4534 %term BXORU8=8630 %term DIVF4=4545 %term DIVF8=8641 %term DIVF16=16833 %term DIVI4=4549 %term DIVI8=8645 %term DIVU4=4550 %term DIVU8=8646 %term MULF4=4561 %term MULF8=8657 %term MULF16=16849 %term MULI4=4565 %term MULI8=8661 %term MULU4=4566 %term MULU8=8662 %term EQF4=4577 %term EQF8=8673 %term EQF16=16865 %term EQI4=4581 %term EQI8=8677 %term EQU4=4582 %term EQU8=8678 %term GEF4=4593 %term GEF8=8689 %term GEI4=4597 %term GEI8=8693 %term GEI16=16885 %term GEU4=4598 %term GEU8=8694 %term GTF4=4609 %term GTF8=8705 %term GTF16=16897 %term GTI4=4613 %term GTI8=8709 %term GTU4=4614 %term GTU8=8710 %term LEF4=4625 %term LEF8=8721 %term LEF16=16913 %term LEI4=4629 %term LEI8=8725 %term LEU4=4630 %term LEU8=8726 %term LTF4=4641 %term LTF8=8737 %term LTF16=16929 %term LTI4=4645 %term LTI8=8741 %term LTU4=4646 %term LTU8=8742 %term NEF4=4657 %term NEF8=8753 %term NEF16=16945 %term NEI4=4661 %term NEI8=8757 %term NEU4=4662 %term NEU8=8758 %term JUMPV=584 %term LABELV=600 %term LOADB=233 %term LOADF4=4321 %term LOADF8=8417 %term LOADF16=16609 %term LOADI1=1253 %term LOADI2=2277 %term LOADI4=4325 %term LOADI8=8421 %term LOADP4=4327 %term LOADP8=8423 %term LOADU1=1254 %term LOADU2=2278 %term LOADU4=4326 %term LOADU8=8422 %term VREGP=711 %% reg: INDIRI1(VREGP) "# read register\n" reg: INDIRU1(VREGP) "# read register\n" reg: INDIRI2(VREGP) "# read register\n" reg: INDIRU2(VREGP) "# read register\n" reg: INDIRI4(VREGP) "# read register\n" reg: INDIRP4(VREGP) "# read register\n" reg: INDIRU4(VREGP) "# read register\n" reg: INDIRI8(VREGP) "# read register\n" reg: INDIRP8(VREGP) "# read register\n" reg: INDIRU8(VREGP) "# read register\n" freg: INDIRF4(VREGP) "# read register\n" freg: INDIRF8(VREGP) "# read register\n" stmt: ASGNI1(VREGP,reg) "# write register\n" stmt: ASGNU1(VREGP,reg) "# write register\n" stmt: ASGNI2(VREGP,reg) "# write register\n" stmt: ASGNU2(VREGP,reg) "# write register\n" stmt: ASGNF4(VREGP,reg) "# write register\n" stmt: ASGNI4(VREGP,reg) "# write register\n" stmt: ASGNP4(VREGP,reg) "# write register\n" stmt: ASGNU4(VREGP,reg) "# write register\n" stmt: ASGNF8(VREGP,reg) "# write register\n" stmt: ASGNI8(VREGP,reg) "# write register\n" stmt: ASGNP8(VREGP,reg) "# write register\n" stmt: ASGNU8(VREGP,reg) "# write register\n" cnst: CNSTI1 "%a" cnst: CNSTU1 "%a" cnst: CNSTI2 "%a" cnst: CNSTU2 "%a" cnst: CNSTI4 "%a" cnst: CNSTU4 "%a" cnst: CNSTP4 "%a" cnst: CNSTI8 "%a" cnst: CNSTU8 "%a" cnst: CNSTP8 "%a" con: cnst "$%0" stmt: reg "" stmt: freg "" acon: ADDRGP4 "%a" acon: ADDRGP8 "%a" acon: cnst "%0" baseaddr: ADDRGP4 "%a" base: reg "(%0)" base: ADDI4(reg,acon) "%1(%0)" base: ADDP4(reg,acon) "%1(%0)" base: ADDU4(reg,acon) "%1(%0)" base: ADDRFP4 "%a(%%ebp)" base: ADDRLP4 "%a(%%ebp)" index: reg "%0" index: LSHI4(reg,con1) "%0,2" index: LSHI4(reg,con2) "%0,4" index: LSHI4(reg,con3) "%0,8" index: LSHU4(reg,con1) "%0,2" index: LSHU4(reg,con2) "%0,4" index: LSHU4(reg,con3) "%0,8" con0: CNSTI4 "1" range(a, 0, 0) con0: CNSTU4 "1" range(a, 0, 0) con1: CNSTI4 "1" range(a, 1, 1) con1: CNSTU4 "1" range(a, 1, 1) con2: CNSTI4 "2" range(a, 2, 2) con2: CNSTU4 "2" range(a, 2, 2) con3: CNSTI4 "3" range(a, 3, 3) con3: CNSTU4 "3" range(a, 3, 3) addr: base "%0" addr: baseaddr "%0" addr: ADDI4(index,baseaddr) "%1(,%0)" addr: ADDP4(index,baseaddr) "%1(,%0)" addr: ADDU4(index,baseaddr) "%1(,%0)" addr: ADDI4(reg,baseaddr) "%1(%0)" addr: ADDP4(reg,baseaddr) "%1(%0)" addr: ADDU4(reg,baseaddr) "%1(%0)" addr: ADDI4(index,reg) "(%1,%0)" addr: ADDP4(index,reg) "(%1,%0)" addr: ADDU4(index,reg) "(%1,%0)" addr: index "(,%0)" mem1: INDIRI1(addr) "%0" mem1: INDIRU1(addr) "%0" mem2: INDIRI2(addr) "%0" mem2: INDIRU2(addr) "%0" mem4: INDIRI4(addr) "%0" mem4: INDIRU4(addr) "%0" mem4: INDIRP4(addr) "%0" rc: reg "%0" rc: con "%0" mr: reg "%0" mr: mem4 "%0" mr1: reg "%0" mr1: mem1 "%0" mr2: reg "%0" mr2: mem2 "%0" mrc: mem4 "%0" 1 mrc: mem1 "%0" 1 mrc: mem2 "%0" 1 mrc: rc "%0" reg: addr "leal %0,%c\n" 1 reg: mr "movl %0,%c\n" 1 reg: mr1 "movb %0,%c\n" 1 reg: mr2 "movw %0,%c\n" 1 reg: con "movl %0,%c\n" 1 reg: LOADI1(reg) "# move\n" 1 reg: LOADI2(reg) "# move\n" 1 reg: LOADI4(reg) "# move\n" move(a) reg: LOADU1(reg) "# move\n" 1 reg: LOADU2(reg) "# move\n" 1 reg: LOADU4(reg) "# move\n" move(a) reg: LOADP4(reg) "# move\n" move(a) reg: ADDI4(reg,mrc) "?movl %0,%c\naddl %1,%c\n" 1 reg: ADDP4(reg,mrc) "?movl %0,%c\naddl %1,%c\n" 1 reg: ADDU4(reg,mrc) "?movl %0,%c\naddl %1,%c\n" 1 reg: SUBI4(reg,mrc) "?movl %0,%c\nsubl %1,%c\n" 1 reg: SUBP4(reg,mrc) "?movl %0,%c\nsubl %1,%c\n" 1 reg: SUBU4(reg,mrc) "?movl %0,%c\nsubl %1,%c\n" 1 reg: BANDI4(reg,mrc) "?movl %0,%c\nandl %1,%c\n" 1 reg: BORI4(reg,mrc) "?movl %0,%c\norl %1,%c\n" 1 reg: BXORI4(reg,mrc) "?movl %0,%c\nxorl %1,%c\n" 1 reg: BANDU4(reg,mrc) "?movl %0,%c\nandl %1,%c\n" 1 reg: BORU4(reg,mrc) "?movl %0,%c\norl %1,%c\n" 1 reg: BXORU4(reg,mrc) "?movl %0,%c\nxorl %1,%c\n" 1 stmt: ASGNI4(addr,ADDI4(mem4,con1)) "incl %1\n" memop(a) stmt: ASGNI4(addr,ADDU4(mem4,con1)) "incl %1\n" memop(a) stmt: ASGNP4(addr,ADDP4(mem4,con1)) "incl %1\n" memop(a) stmt: ASGNI4(addr,SUBI4(mem4,con1)) "decl %1\n" memop(a) stmt: ASGNI4(addr,SUBU4(mem4,con1)) "decl %1\n" memop(a) stmt: ASGNP4(addr,SUBP4(mem4,con1)) "decl %1\n" memop(a) stmt: ASGNI4(addr,ADDI4(mem4,rc)) "addl %2,%1\n" memop(a) stmt: ASGNI4(addr,SUBI4(mem4,rc)) "sub %2,%1\n" memop(a) stmt: ASGNU4(addr,ADDU4(mem4,rc)) "add %2,%1\n" memop(a) stmt: ASGNU4(addr,SUBU4(mem4,rc)) "sub %2,%1\n" memop(a) stmt: ASGNI4(addr,BANDI4(mem4,rc)) "andl %2,%1\n" memop(a) stmt: ASGNI4(addr,BORI4(mem4,rc)) "orl %2,%1\n" memop(a) stmt: ASGNI4(addr,BXORI4(mem4,rc)) "xorl %2,%1\n" memop(a) stmt: ASGNU4(addr,BANDU4(mem4,rc)) "andl %2,%1\n" memop(a) stmt: ASGNU4(addr,BORU4(mem4,rc)) "orl %2,%1\n" memop(a) stmt: ASGNU4(addr,BXORU4(mem4,rc)) "xorl %2,%1\n" memop(a) reg: BCOMI4(reg) "?movl %0,%c\nnotl %c\n" 2 reg: BCOMU4(reg) "?movl %0,%c\nnotl %c\n" 2 reg: NEGI4(reg) "?movl %0,%c\nnegl %c\n" 2 stmt: ASGNI4(addr,BCOMI4(mem4)) "notl %1\n" memop(a) stmt: ASGNU4(addr,BCOMU4(mem4)) "notl %1\n" memop(a) stmt: ASGNI4(addr,NEGI4(mem4)) "negl %1\n" memop(a) reg: LSHI4(reg,rc5) "?movl %0,%c\nsall %1,%c\n" 2 reg: LSHU4(reg,rc5) "?movl %0,%c\nshll %1,%c\n" 2 reg: RSHI4(reg,rc5) "?movl %0,%c\nsarl %1,%c\n" 2 reg: RSHU4(reg,rc5) "?movl %0,%c\nshrl %1,%c\n" 2 stmt: ASGNI4(addr,LSHI4(mem4,rc5)) "sall %2,%1\n" memop(a) stmt: ASGNI4(addr,LSHU4(mem4,rc5)) "shll %2,%1\n" memop(a) stmt: ASGNI4(addr,RSHI4(mem4,rc5)) "sarl %2,%1\n" memop(a) stmt: ASGNI4(addr,RSHU4(mem4,rc5)) "shrl %2,%1\n" memop(a) rc5: CNSTI4 "$%a" range(a, 0, 31) rc5: reg "%%cl" reg: MULI4(reg,mrc) "?movl %0,%c\nimull %1,%c\n" 14 reg: MULI4(con,mr) "imul %0,%1,%c\n" 13 reg: MULU4(reg,mr) "mull %1\n" 13 reg: DIVU4(reg,reg) "xorl %%edx,%%edx\ndivl %1\n" reg: MODU4(reg,reg) "xorl %%edx,%%edx\ndivl %1\n" reg: DIVI4(reg,reg) "cdq\nidivl %1\n" reg: MODI4(reg,reg) "cdq\nidivl %1\n" reg: CVPU4(reg) "movl %0,%c\n" move(a) reg: CVUP4(reg) "movl %0,%c\n" move(a) reg: CVII4(INDIRI1(addr)) "movsbl %0,%c\n" 3 reg: CVII4(INDIRI2(addr)) "movswl %0,%c\n" 3 reg: CVUU4(INDIRU1(addr)) "movzbl %0,%c\n" 3 reg: CVUU4(INDIRU2(addr)) "movzwl %0,%c\n" 3 reg: CVII4(reg) "# extend\n" 3 reg: CVIU4(reg) "# extend\n" 3 reg: CVUI4(reg) "# extend\n" 3 reg: CVUU4(reg) "# extend\n" 3 reg: CVII1(reg) "# truncate\n" 1 reg: CVII2(reg) "# truncate\n" 1 reg: CVUU1(reg) "# truncate\n" 1 reg: CVUU2(reg) "# truncate\n" 1 mrca: mem4 "%0" mrca: rc "%0" mrca: ADDRGP4 "$%a" mrca: ADDRGP8 "$%a" stmt: ASGNI1(addr,rc) "movb %1,%0\n" 1 stmt: ASGNI2(addr,rc) "movw %1,%0\n" 1 stmt: ASGNI4(addr,rc) "movl %1,%0\n" 1 stmt: ASGNU1(addr,rc) "movb %1,%0\n" 1 stmt: ASGNU2(addr,rc) "movw %1,%0\n" 1 stmt: ASGNU4(addr,rc) "movl %1,%0\n" 1 stmt: ASGNP4(addr,rc) "movl %1,%0\n" 1 stmt: ARGI4(mrca) "pushl %0\n" 1 stmt: ARGU4(mrca) "pushl %0\n" 1 stmt: ARGP4(mrca) "pushl %0\n" 1 stmt: ASGNB(reg,INDIRB(reg)) "movl $%a,%%ecx\nrep\nmovsb\n" stmt: ARGB(INDIRB(reg)) "subl $%a,%%esp\nmovl %%esp,%%edi\nmovl $%a,%%ecx\nrep\nmovsb\n" memf: INDIRF8(addr) "l %0" memf: INDIRF4(addr) "s %0" memf: CVFF8(INDIRF4(addr)) "s %0" memf: CVFF4(INDIRF8(addr)) "l %0" freg: memf "fld%0\n" 3 stmt: ASGNF8(addr,freg) "fstpl %0\n" 7 stmt: ASGNF4(addr,freg) "fstps %0\n" 7 stmt: ASGNF4(addr,CVFF4(freg)) "fstps %0\n" 7 stmt: ARGF8(freg) "subl $8,%%esp\nfstpl (%%esp)\n" stmt: ARGF4(freg) "subl $4,%%esp\nfstps (%%esp)\n" freg: NEGF8(freg) "fchs\n" freg: NEGF4(freg) "fchs\n" flt: memf "%0" flt: freg "p %%st(1),%%st" freg: ADDF4(freg,flt) "fadd%1\n" freg: ADDF8(freg,flt) "fadd%1\n" freg: DIVF4(freg,flt) "fdiv%1\n" freg: DIVF8(freg,flt) "fdiv%1\n" freg: MULF4(freg,flt) "fmul%1\n" freg: MULF8(freg,flt) "fmul%1\n" freg: SUBF4(freg,flt) "fsub%1\n" freg: SUBF8(freg,flt) "fsub%1\n" freg: CVFF8(freg) "# CVFF8\n" freg: CVFF4(freg) "sub $4,%%esp\nfstps (%%esp)\nflds (%%esp)\naddl $4,%%esp\n" 12 stmt: ASGNI4(addr,CVFI4(freg)) "fistpl %0\n" 29 reg: CVFI4(freg) "subl $4,%%esp\nfistpl 0(%%esp)\npopl %c\n" 31 freg: CVIF8(INDIRI4(addr)) "fildl %0\n" 10 freg: CVIF8(reg) "pushl %0\nfildl (%%esp)\naddl $4,%%esp\n" 12 freg: CVIF4(INDIRI4(addr)) "fildl %0\n" 10 freg: CVIF4(reg) "pushl %0\nfildl (%%esp)\naddl $4,%%esp\n" 12 addrj: ADDRGP4 "%a" addrj: reg "*%0" 2 addrj: mem4 "*%0" 2 stmt: LABELV "%a:\n" stmt: JUMPV(addrj) "jmp %0\n" 3 stmt: EQI4(mem4,rc) "cmpl %1,%0\nje %a\n" 5 stmt: GEI4(mem4,rc) "cmpl %1,%0\njge %a\n" 5 stmt: GTI4(mem4,rc) "cmpl %1,%0\njg %a\n" 5 stmt: LEI4(mem4,rc) "cmpl %1,%0\njle %a\n" 5 stmt: LTI4(mem4,rc) "cmpl %1,%0\njl %a\n" 5 stmt: NEI4(mem4,rc) "cmpl %1,%0\njne %a\n" 5 stmt: GEU4(mem4,rc) "cmpl %1,%0\njae %a\n" 5 stmt: GTU4(mem4,rc) "cmpl %1,%0\nja %a\n" 5 stmt: LEU4(mem4,rc) "cmpl %1,%0\njbe %a\n" 5 stmt: LTU4(mem4,rc) "cmpl %1,%0\njb %a\n" 5 stmt: EQI4(reg,mrc) "cmpl %1,%0\nje %a\n" 4 stmt: GEI4(reg,mrc) "cmpl %1,%0\njge %a\n" 4 stmt: GTI4(reg,mrc) "cmpl %1,%0\njg %a\n" 4 stmt: LEI4(reg,mrc) "cmpl %1,%0\njle %a\n" 4 stmt: LTI4(reg,mrc) "cmpl %1,%0\njl %a\n" 4 stmt: NEI4(reg,mrc) "cmpl %1,%0\njne %a\n" 4 stmt: EQU4(reg,mrc) "cmpl %1,%0\nje %a\n" 4 stmt: GEU4(reg,mrc) "cmpl %1,%0\njae %a\n" 4 stmt: GTU4(reg,mrc) "cmpl %1,%0\nja %a\n" 4 stmt: LEU4(reg,mrc) "cmpl %1,%0\njbe %a\n" 4 stmt: LTU4(reg,mrc) "cmpl %1,%0\njb %a\n" 4 stmt: NEU4(reg,mrc) "cmpl %1,%0\njne %a\n" 4 stmt: EQI4(BANDU4(mr,con),con0) "testl %1,%0\nje %a\n" 3 stmt: NEI4(BANDU4(mr,con),con0) "testl %1,%0\njne %a\n" stmt: EQI4(BANDU4(CVII2(INDIRI2(addr)),con),con0) "testw %1,%0\nje %a\n" stmt: NEI4(BANDU4(CVII2(INDIRI2(addr)),con),con0) "testw %1,%0\njne %a\n" stmt: EQI4(BANDU4(CVIU2(INDIRI2(addr)),con),con0) "testw %1,%0\nje %a\n" stmt: NEI4(BANDU4(CVIU2(INDIRI2(addr)),con),con0) "testw %1,%0\njne %a\n" stmt: EQI4(BANDU4(CVII1(INDIRI1(addr)),con),con0) "testb %1,%0\nje %a\n" cmpf: INDIRF8(addr) "l %0" cmpf: INDIRF4(addr) "s %0" cmpf: CVFF8(INDIRF4(addr)) "s %0" cmpf: freg "p" stmt: EQF8(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\nje %a\n" stmt: GEF8(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\njbe %a\n" stmt: GTF8(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\njb %a\n" stmt: LEF8(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\njae %a\n" stmt: LTF8(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\nja %a\n" stmt: NEF8(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\njne %a\n" stmt: EQF4(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\nje %a\n" stmt: GEF4(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\njbe %a\n" stmt: GTF4(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\njb %a\n" stmt: LEF4(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\njae %a\n" stmt: LTF4(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\nja %a\n" stmt: NEF4(cmpf,freg) "fcomp%0\nfstsw %%ax\nsahf\njne %a\n" freg: DIVF8(freg,CVIF8(INDIRI4(addr))) "fidivl %1\n" freg: DIVF8(CVIF8(INDIRI4(addr)),freg) "fidivrl %0\n" freg: DIVF8(freg,CVIF8(CVII2(INDIRI2(addr)))) "fidivs %1\n" freg: DIVF8(CVIF8(CVII2(INDIRI2(addr))),freg) "fidivrs %0\n" freg: MULF8(freg,CVIF8(INDIRI4(addr))) "fimull %1\n" freg: MULF8(freg,CVIF8(CVII2(INDIRI2(addr)))) "fimuls %1\n" freg: SUBF8(freg,CVIF8(INDIRI4(addr))) "fisubl %1\n" freg: SUBF8(CVIF8(INDIRI4(addr)),freg) "fisubrl %0\n" freg: SUBF8(freg,CVIF8(CVII2(INDIRI2(addr)))) "fisubs %1\n" freg: SUBF8(CVIF8(CVII2(INDIRI2(addr))),freg) "fisubrs %0\n" freg: ADDF8(freg,CVIF8(INDIRI4(addr))) "fiaddl %1\n" freg: ADDF8(freg,CVIF8(CVII2(INDIRI2(addr)))) "fiadds %1\n" freg: ADDF8(freg,CVFF8(INDIRF4(addr))) "fdivs %1\n" freg: SUBF8(freg,CVFF8(INDIRF4(addr))) "fsubs %1\n" freg: MULF8(freg,CVFF8(INDIRF4(addr))) "fmuls %1\n" freg: DIVF8(freg,CVFF8(INDIRF4(addr))) "fdivs %1\n" freg: LOADF8(memf) "fld%0\n" reg: CALLI4(addrj) "call %0\naddl $%a,%%esp\n" hasargs(a) reg: CALLU4(addrj) "call %0\naddl $%a,%%esp\n" hasargs(a) reg: CALLP4(addrj) "call %0\naddl $%a,%%esp\n" hasargs(a) reg: CALLI4(addrj) "call %0\n" 1 reg: CALLU4(addrj) "call %0\n" 1 reg: CALLP4(addrj) "call %0\n" 1 stmt: CALLV(addrj) "call %0\naddl $%a,%%esp\n" hasargs(a) stmt: CALLV(addrj) "call %0\n" 1 freg: CALLF4(addrj) "call %0\naddl $%a,%%esp\n" hasargs(a) freg: CALLF4(addrj) "call %0\n" 1 stmt: CALLF4(addrj) "call %0\naddl $%a,%%esp\nfstp %%st(0)\n" hasargs(a) stmt: CALLF4(addrj) "call %0\nfstp %%st(0)\n" 1 freg: CALLF8(addrj) "call %0\naddl $%a,%%esp\n" hasargs(a) freg: CALLF8(addrj) "call %0\n" 1 stmt: CALLF8(addrj) "call %0\naddl $%a,%%esp\nfstp %%st(0)\n" hasargs(a) stmt: CALLF8(addrj) "call %0\nfstp %%st(0)\n" 1 stmt: RETI4(reg) "# ret\n" stmt: RETU4(reg) "# ret\n" stmt: RETP4(reg) "# ret\n" stmt: RETF4(freg) "# ret\n" stmt: RETF8(freg) "# ret\n" %% static void progbeg(int argc, char *argv[]) { int i; { union { char c; int i; } u; u.i = 0; u.c = 1; swap = ((int)(u.i == 1)) != IR->little_endian; } parseflags(argc, argv); for (i = 0; i < argc; i++) if (strcmp(argv[i], "-p") == 0 || strcmp(argv[i], "-pg") == 0) pflag = 1; intreg[EAX] = mkreg("%%eax", EAX, 1, IREG); intreg[EDX] = mkreg("%%edx", EDX, 1, IREG); intreg[ECX] = mkreg("%%ecx", ECX, 1, IREG); intreg[EBX] = mkreg("%%ebx", EBX, 1, IREG); intreg[ESI] = mkreg("%%esi", ESI, 1, IREG); intreg[EDI] = mkreg("%%edi", EDI, 1, IREG); shortreg[EAX] = mkreg("%%ax", EAX, 1, IREG); shortreg[ECX] = mkreg("%%cx", ECX, 1, IREG); shortreg[EDX] = mkreg("%%dx", EDX, 1, IREG); shortreg[EBX] = mkreg("%%bx", EBX, 1, IREG); shortreg[ESI] = mkreg("%%si", ESI, 1, IREG); shortreg[EDI] = mkreg("%%di", EDI, 1, IREG); charreg[EAX] = mkreg("%%al", EAX, 1, IREG); charreg[ECX] = mkreg("%%cl", ECX, 1, IREG); charreg[EDX] = mkreg("%%dl", EDX, 1, IREG); charreg[EBX] = mkreg("%%bl", EBX, 1, IREG); for (i = 0; i < 8; i++) fltreg[i] = mkreg("%d", i, 0, FREG); charregw = mkwildcard(charreg); shortregw = mkwildcard(shortreg); intregw = mkwildcard(intreg); fltregw = mkwildcard(fltreg); tmask[IREG] = (1<<EDI) | (1<<ESI) | (1<<EBX) | (1<<EDX) | (1<<ECX) | (1<<EAX); vmask[IREG] = 0; tmask[FREG] = 0xff; vmask[FREG] = 0; cseg = 0; quo = mkreg("%%eax", EAX, 1, IREG); quo->x.regnode->mask |= 1<<EDX; rem = mkreg("%%edx", EDX, 1, IREG); rem->x.regnode->mask |= 1<<EAX; stabprefix = ".LL"; } static Symbol rmap(int opk) { switch (optype(opk)) { case B: case P: return intregw; case I: case U: if (opsize(opk) == 1) return charregw; else if (opsize(opk) == 2) return shortregw; else return intregw; case F: return fltregw; default: return 0; } } static Symbol prevg; static void globalend(void) { if (prevg && prevg->type->size > 0) print(".size %s,%d\n", prevg->x.name, prevg->type->size); prevg = NULL; } static void progend(void) { globalend(); (*IR->segment)(CODE); print(".ident \"LCC: 4.1\"\n"); } static void target(Node p) { assert(p); switch (specific(p->op)) { case RSH+I: case RSH+U: case LSH+I: case LSH+U: if (generic(p->kids[1]->op) != CNST && !( generic(p->kids[1]->op) == INDIR && specific(p->kids[1]->kids[0]->op) == VREG+P && p->kids[1]->syms[RX]->u.t.cse && generic(p->kids[1]->syms[RX]->u.t.cse->op) == CNST)) { rtarget(p, 1, intreg[ECX]); setreg(p, intreg[EAX]); } break; case MUL+U: setreg(p, quo); rtarget(p, 0, intreg[EAX]); break; case DIV+I: case DIV+U: setreg(p, quo); rtarget(p, 0, intreg[EAX]); rtarget(p, 1, intreg[ECX]); break; case MOD+I: case MOD+U: setreg(p, rem); rtarget(p, 0, intreg[EAX]); rtarget(p, 1, intreg[ECX]); break; case ASGN+B: rtarget(p, 0, intreg[EDI]); rtarget(p->kids[1], 0, intreg[ESI]); break; case ARG+B: rtarget(p->kids[0], 0, intreg[ESI]); break; case CVF+I: setreg(p, intreg[EAX]); break; case CALL+I: case CALL+U: case CALL+P: case CALL+V: setreg(p, intreg[EAX]); break; case RET+I: case RET+U: case RET+P: rtarget(p, 0, intreg[EAX]); break; } } static void clobber(Node p) { static int nstack = 0; assert(p); nstack = ckstack(p, nstack); switch (specific(p->op)) { case ASGN+B: case ARG+B: spill(1<<ECX | 1<<ESI | 1<<EDI, IREG, p); break; case EQ+F: case LE+F: case GE+F: case LT+F: case GT+F: case NE+F: spill(1<<EAX, IREG, p); break; case CALL+F: spill(1<<EDX | 1<<EAX | 1<<ECX, IREG, p); break; case CALL+I: case CALL+U: case CALL+P: case CALL+V: spill(1<<EDX | 1<<ECX, IREG, p); break; } } static void emit2(Node p) { int op = specific(p->op); #define preg(f) ((f)[getregnum(p->x.kids[0])]->x.name) if (op == CVI+I && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 1) print("movsbl %s,%s\n", preg(charreg), p->syms[RX]->x.name); else if (op == CVI+U && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 1) print("movsbl %s,%s\n", preg(charreg), p->syms[RX]->x.name); else if (op == CVI+I && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 2) print("movswl %s,%s\n", preg(shortreg), p->syms[RX]->x.name); else if (op == CVI+U && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 2) print("movswl %s,%s\n", preg(shortreg), p->syms[RX]->x.name); else if (op == CVU+I && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 1) print("movzbl %s,%s\n", preg(charreg), p->syms[RX]->x.name); else if (op == CVU+U && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 1) print("movzbl %s,%s\n", preg(charreg), p->syms[RX]->x.name); else if (op == CVU+I && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 2) print("movzwl %s,%s\n", preg(shortreg), p->syms[RX]->x.name); else if (op == CVU+U && opsize(p->op) == 4 && opsize(p->x.kids[0]->op) == 2) print("movzwl %s,%s\n", preg(shortreg), p->syms[RX]->x.name); else if (generic(op) == CVI || generic(op) == CVU || generic(op) == LOAD) { char *dst = intreg[getregnum(p)]->x.name; char *src = preg(intreg); assert(opsize(p->op) <= opsize(p->x.kids[0]->op)); if (dst != src) print("movl %s,%s\n", src, dst); } } static void function(Symbol f, Symbol caller[], Symbol callee[], int n) { int i; globalend(); print(".align 16\n"); print(".type %s,@function\n", f->x.name); print("%s:\n", f->x.name); print("pushl %%ebp\n"); if (pflag) { static int plab; print("movl %%esp,%%ebp\n"); (*IR->segment)(DATA); print(".align 4\n.LP%d:\n.long 0\n", plab); (*IR->segment)(CODE); print("movl $.LP%d,%%edx\ncall mcount\n", plab); plab++; } print("pushl %%ebx\n"); print("pushl %%esi\n"); print("pushl %%edi\n"); print("movl %%esp,%%ebp\n"); usedmask[0] = usedmask[1] = 0; freemask[0] = freemask[1] = ~0U; offset = 16 + 4; for (i = 0; callee[i]; i++) { Symbol p = callee[i]; Symbol q = caller[i]; assert(q); offset = roundup(offset, q->type->align); p->x.offset = q->x.offset = offset; p->x.name = q->x.name = stringf("%d", p->x.offset); p->sclass = q->sclass = AUTO; offset += roundup(q->type->size, 4); } assert(caller[i] == 0); offset = maxoffset = 0; gencode(caller, callee); framesize = roundup(maxoffset, 4); if (framesize > 0) print("subl $%d,%%esp\n", framesize); emitcode(); print("movl %%ebp,%%esp\n"); print("popl %%edi\n"); print("popl %%esi\n"); print("popl %%ebx\n"); print("popl %%ebp\n"); print("ret\n"); { int l = genlabel(1); print(".Lf%d:\n", l); print(".size %s,.Lf%d-%s\n", f->x.name, l, f->x.name); } } static void defsymbol(Symbol p) { if (p->scope >= LOCAL && p->sclass == STATIC) p->x.name = stringf("%s.%d", p->name, genlabel(1)); else if (p->generated) p->x.name = stringf(".LC%s", p->name); else if (p->scope == GLOBAL || p->sclass == EXTERN) p->x.name = stringf("%s", p->name); else p->x.name = p->name; } static void segment(int n) { if (n == cseg) return; cseg = n; if (cseg == CODE) print(".text\n"); else if (cseg == BSS) print(".bss\n"); else if (cseg == DATA || cseg == LIT) print(".data\n"); } static void defconst(int suffix, int size, Value v) { if (suffix == I && size == 1) print(".byte %d\n", v.u); else if (suffix == I && size == 2) print(".word %d\n", v.i); else if (suffix == I && size == 4) print(".long %d\n", v.i); else if (suffix == U && size == 1) print(".byte %d\n", v.u); else if (suffix == U && size == 2) print(".word %d\n", v.u); else if (suffix == U && size == 4) print(".long %d\n", v.u); else if (suffix == P && size == 4) print(".long %d\n", v.p); else if (suffix == F && size == 4) { float f = v.d; print(".long %d\n", *(unsigned *)&f); } else if (suffix == F && size == 8) { double d = v.d; unsigned *p = (unsigned *)&d; print(".long %d\n.long %d\n", p[swap], p[!swap]); } else assert(0); } static void defaddress(Symbol p) { print(".long %s\n", p->x.name); } static void defstring(int n, char *str) { char *s; for (s = str; s < str + n; s++) print(".byte %d\n", (*s)&0377); } static void export(Symbol p) { globalend(); print(".globl %s\n", p->x.name); } static void import(Symbol p) {} static void global(Symbol p) { globalend(); print(".align %d\n", p->type->align > 4 ? 4 : p->type->align); if (!p->generated) { print(".type %s,@%s\n", p->x.name, isfunc(p->type) ? "function" : "object"); if (p->type->size > 0) print(".size %s,%d\n", p->x.name, p->type->size); else prevg = p; } if (p->u.seg == BSS) { if (p->sclass == STATIC) print(".lcomm %s,%d\n", p->x.name, p->type->size); else print(".comm %s,%d\n", p->x.name, p->type->size); } else { print("%s:\n", p->x.name); } } static void space(int n) { if (cseg != BSS) print(".space %d\n", n); } Interface x86linuxIR = { 1, 1, 0, /* char */ 2, 2, 0, /* short */ 4, 4, 0, /* int */ 4, 4, 0, /* long */ 4, 4, 0, /* long long */ 4, 4, 1, /* float */ 8, 4, 1, /* double */ 8, 4, 1, /* long double */ 4, 4, 0, /* T * */ 0, 4, 0, /* struct; so that ARGB keeps stack aligned */ 1, /* little_endian */ 0, /* mulops_calls */ 0, /* wants_callb */ 1, /* wants_argb */ 0, /* left_to_right */ 0, /* wants_dag */ 0, /* unsigned_char */ 0, /* address */ blockbeg, blockend, defaddress, defconst, defstring, defsymbol, emit, export, function, gen, global, import, 0, /* local */ progbeg, progend, segment, space, stabblock, stabend, 0, stabinit, stabline, stabsym, stabtype, {1, rmap, 0, 0, 0, /* blkfetch, blkstore, blkloop */ _label, _rule, _nts, _kids, _string, _templates, _isinstruction, _ntname, emit2, 0, /* doarg */ target, clobber, } }; void x86linux_init(int argc, char *argv[]) { static int inited; extern Interface x86IR; if (inited) return; inited = 1; #define xx(f) assert(!x86linuxIR.f); x86linuxIR.f = x86IR.f xx(address); xx(local); xx(x.blkfetch); xx(x.blkstore); xx(x.blkloop); xx(x.doarg); #undef xx }
deurk/ktx-tests
tools/lcc/src/x86linux.md
Markdown
gpl-2.0
32,436
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */ /* * Based on gjs/console.c from GJS * * Copyright (c) 2008 litl, LLC * Copyright (c) 2010 Red Hat, Inc. * * 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 "config.h" #include <locale.h> #include <stdlib.h> #include <string.h> #include <clutter/x11/clutter-x11.h> #include <gdk/gdkx.h> #include <girepository.h> #include <gjs/gjs.h> #include <gtk/gtk.h> #include "shell-global.h" #include "shell-global-private.h" static char *command = NULL; static GOptionEntry entries[] = { { "command", 'c', 0, G_OPTION_ARG_STRING, &command, "Program passed in as a string", "COMMAND" }, { NULL } }; static GdkFilterReturn event_filter (GdkXEvent *xevent, GdkEvent *event, gpointer data) { XEvent *xev = (XEvent *)xevent; if (clutter_x11_handle_event (xev) == CLUTTER_X11_FILTER_CONTINUE) return GDK_FILTER_CONTINUE; else return GDK_FILTER_REMOVE; } int main(int argc, char **argv) { GOptionContext *context; GError *error = NULL; ShellGlobal *global; GjsContext *js_context; char *script; const char *filename; char *title; gsize len; int code; gtk_init (&argc, &argv); clutter_x11_set_display (GDK_DISPLAY_XDISPLAY (gdk_display_get_default ())); clutter_x11_disable_event_retrieval (); if (clutter_init (&argc, &argv) != CLUTTER_INIT_SUCCESS) return 1; gdk_window_add_filter (NULL, event_filter, NULL); context = g_option_context_new (NULL); /* pass unknown through to the JS script */ g_option_context_set_ignore_unknown_options (context, TRUE); g_option_context_add_main_entries (context, entries, NULL); if (!g_option_context_parse (context, &argc, &argv, &error)) g_error ("option parsing failed: %s", error->message); setlocale (LC_ALL, ""); _shell_global_init (NULL); global = shell_global_get (); js_context = _shell_global_get_gjs_context (global); /* prepare command line arguments */ if (!gjs_context_define_string_array (js_context, "ARGV", argc - 2, (const char**)argv + 2, &error)) { g_printerr ("Failed to defined ARGV: %s", error->message); exit (1); } if (command != NULL) { script = command; len = strlen (script); filename = "<command line>"; } else if (argc <= 1) { script = g_strdup ("const Console = imports.console; Console.interact();"); len = strlen (script); filename = "<stdin>"; } else /*if (argc >= 2)*/ { error = NULL; if (!g_file_get_contents (argv[1], &script, &len, &error)) { g_printerr ("%s\n", error->message); exit (1); } filename = argv[1]; } title = g_filename_display_basename (filename); g_set_prgname (title); g_free (title); #if HAVE_BLUETOOTH /* The module imports are all so intertwined that if the test * imports anything in js/ui, it will probably eventually end up * pulling in ui/status/bluetooth.js. So we need this. */ g_irepository_prepend_search_path (BLUETOOTH_DIR); #endif /* evaluate the script */ error = NULL; if (!gjs_context_eval (js_context, script, len, filename, &code, &error)) { g_free (script); g_printerr ("%s\n", error->message); exit (1); } gjs_context_gc (js_context); gjs_context_gc (js_context); g_free (script); exit (code); }
fanpenggogo/gnome-shel
src/run-js-test.c
C
gpl-2.0
4,452
/* Soot - a J*va Optimization Framework * Copyright (C) 2003 Jennifer Lhotak * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ package ca.mcgill.sable.soot.ui; import java.util.*; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.jface.dialogs.*; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.*; import ca.mcgill.sable.soot.SootPlugin; import ca.mcgill.sable.soot.launching.*; import ca.mcgill.sable.soot.ui.PhaseOptionsDialog; public class SootConfigManagerDialog extends TitleAreaDialog implements ISelectionChangedListener { private SashForm sashForm; private Composite selectionArea; private TreeViewer treeViewer; private String selected; private Composite buttonPanel; private SootConfiguration treeRoot; private HashMap editDefs; private SootLauncher launcher; private void addEclipseDefsToDialog(PhaseOptionsDialog dialog) { if (getEclipseDefList() == null) return; Iterator it = getEclipseDefList().keySet().iterator(); while (it.hasNext()) { String key = (String)it.next(); dialog.addToEclipseDefList(key, getEclipseDefList().get(key)); } } private void setMainClassInDialog(PhaseOptionsDialog dialog, String mainClass){ String mainProject; String realMainClass; if(mainClass.contains(":")) { String[] split = mainClass.split(":"); mainProject = split[0]; realMainClass = split[1]; } else { mainProject = null; realMainClass = mainClass; } dialog.addToEclipseDefList("sootMainClass", realMainClass); dialog.addToEclipseDefList("sootMainProject", mainProject); } private HashMap eclipseDefList; /** * Returns the eclipseDefList. * @return HashMap */ public HashMap getEclipseDefList() { return eclipseDefList; } /** * Sets the eclipseDefList. * @param eclipseDefList The eclipseDefList to set */ public void setEclipseDefList(HashMap eclipseDefList) { this.eclipseDefList = eclipseDefList; } public SootConfigManagerDialog(Shell parentShell) { super(parentShell); this.setShellStyle(SWT.RESIZE); } protected void configureShell(Shell shell){ super.configureShell(shell); shell.setText(Messages.getString("SootConfigManagerDialog.Manage_Configurations")); //$NON-NLS-1$ } /** * creates a sash form - one side for a selection tree * and the other for the options */ protected Control createDialogArea(Composite parent) { GridData gd; Composite dialogComp = (Composite)super.createDialogArea(parent); Composite topComp = new Composite(dialogComp, SWT.NONE); gd = new GridData(GridData.FILL_BOTH); topComp.setLayoutData(gd); GridLayout topLayout = new GridLayout(); topLayout.numColumns = 2; topComp.setLayout(topLayout); // Set the things that TitleAreaDialog takes care of setTitle(Messages.getString("SootConfigManagerDialog.Soot_Configurations_Manager")); //$NON-NLS-1$ setMessage(""); //$NON-NLS-1$ Composite selection = createSelectionArea(topComp); gd = new GridData(GridData.FILL_BOTH); gd.horizontalSpan = 1; selection.setLayoutData(gd); Control specialButtons = createSpecialButtonBar(topComp); gd = new GridData(GridData.FILL_BOTH); specialButtons.setLayoutData(gd); Label separator = new Label(topComp, SWT.HORIZONTAL | SWT.SEPARATOR); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; separator.setLayoutData(gd); dialogComp.layout(true); return dialogComp; } /** * creates the tree of options sections */ private Composite createSelectionArea(Composite parent) { Composite comp = new Composite(parent, SWT.NONE); setSelectionArea(comp); GridLayout layout = new GridLayout(); layout.numColumns = 1; comp.setLayout(layout); GridData gd = new GridData(); TreeViewer tree = new TreeViewer(comp); gd = new GridData(GridData.FILL_BOTH); tree.getControl().setLayoutData(gd); tree.setContentProvider(new SootConfigContentProvider()); tree.setLabelProvider(new SootConfigLabelProvider()); tree.setInput(getInitialInput()); setTreeViewer(tree); tree.addSelectionChangedListener(this); tree.expandAll(); tree.getControl().addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { handleKeyPressed(e); } }); return comp; } public void selectionChanged(SelectionChangedEvent event) { IStructuredSelection selection = (IStructuredSelection)event.getSelection(); if (!selection.isEmpty()) { Object elem = selection.getFirstElement(); if (elem instanceof SootConfiguration) { SootConfiguration sel = (SootConfiguration)elem; setSelected(sel.getLabel()); } enableButtons(); } } private void enableButtons(){ Iterator it = specialButtonList.iterator(); while (it.hasNext()){ ((Button)it.next()).setEnabled(true); } } protected void handleKeyPressed(KeyEvent e) { } private SootConfiguration getInitialInput() { IDialogSettings settings = SootPlugin.getDefault().getDialogSettings(); int numConfig = 0; try { numConfig = settings.getInt(Messages.getString("SootConfigManagerDialog.config_count")); //$NON-NLS-1$ } catch(NumberFormatException e) { } SootConfiguration root = new SootConfiguration(""); //$NON-NLS-1$ if (numConfig != 0) { String [] configNames = new String[numConfig]; for (int i = 0; i < numConfig; i++) { configNames[i] = settings.get(Messages.getString("SootConfigManagerDialog.soot_run_config")+(i+1)); //$NON-NLS-1$ root.addChild(new SootConfiguration(configNames[i])); } } setTreeRoot(root); return root; } /* * @see Dialog#createButtonBar(Composite) */ protected Control createSpecialButtonBar(Composite parent) { Composite composite= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.numColumns= 1; composite.setLayout(layout); composite.setLayoutData(new GridData(GridData.FILL_VERTICAL)); applyDialogFont(composite); composite.setLayout(layout); GridData data = new GridData( GridData.VERTICAL_ALIGN_END | GridData.HORIZONTAL_ALIGN_CENTER); composite.setLayoutData(data); // Add the buttons to the button bar. createSpecialButtonsForButtonBar(composite); return composite; } ArrayList specialButtonList = new ArrayList(); protected Button createSpecialButton( Composite parent, int id, String label, boolean defaultButton, boolean enabled) { Button button = new Button(parent, SWT.PUSH); button.setText(label); button.setData(new Integer(id)); button.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { buttonPressed(((Integer) event.widget.getData()).intValue()); } }); if (defaultButton) { Shell shell = parent.getShell(); if (shell != null) { shell.setDefaultButton(button); } } button.setFont(parent.getFont()); if (!enabled){ button.setEnabled(false); } setButtonLayoutData(button); specialButtonList.add(button); return button; } protected void createButtonsForButtonBar(Composite parent){ //run and close will close dialog Button runButton = createButton(parent, 5, Messages.getString("SootConfigManagerDialog.Run"), false); //$NON-NLS-1$ runButton.setEnabled(false); specialButtonList.add(runButton); createButton(parent, 6, Messages.getString("SootConfigManagerDialog.Close"), true); //$NON-NLS-1$ } protected void createSpecialButtonsForButtonBar(Composite parent) { createSpecialButton(parent, 0, Messages.getString("SootConfigManagerDialog.New"), false, true); //$NON-NLS-1$ createSpecialButton(parent, 1, Messages.getString("SootConfigManagerDialog.Edit"), false, false); //$NON-NLS-1$ createSpecialButton(parent, 2, Messages.getString("SootConfigManagerDialog.Delete"), false, false); //$NON-NLS-1$ createSpecialButton(parent, 3, Messages.getString("SootConfigManagerDialog.Rename"), false, false); //$NON-NLS-1$ createSpecialButton(parent, 4, Messages.getString("SootConfigManagerDialog.Clone"), false, false); //$NON-NLS-1$ } protected void buttonPressed(int id) { switch (id) { case 0: { newPressed(); break; } case 1: { editPressed(); break; } case 2: { deletePressed(); break; } case 3: { renamePressed(); break; } case 4: { clonePressed(); break; } case 5: { runPressed(); break; } case 6: { cancelPressed(); break; } case 7: { break; } case 8: { break; } } } // shows a phaseOptionsDialog with save and close buttons // only and asks for a name first private void newPressed() { IDialogSettings settings = SootPlugin.getDefault().getDialogSettings(); // gets current number of configurations before adding any int config_count = 0; try { config_count = settings.getInt(Messages.getString("SootConfigManagerDialog.config_count")); //$NON-NLS-1$ } catch (NumberFormatException e) { } ArrayList currentNames = new ArrayList(); for (int i = 1; i <= config_count; i++) { currentNames.add(settings.get(Messages.getString("SootConfigManagerDialog.soot_run_config")+i)); //$NON-NLS-1$ } // sets validator to know about already used names - but it doesn't use // them because then editing a file cannot use same file name SootConfigNameInputValidator validator = new SootConfigNameInputValidator(); validator.setAlreadyUsed(currentNames); // create dialog to get name InputDialog nameDialog = new InputDialog(this.getShell(), Messages.getString("SootConfigManagerDialog.Saving_Configuration_Name"), Messages.getString("SootConfigManagerDialog.Enter_name_to_save_configuration_with"), "", validator); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ nameDialog.open(); if (nameDialog.getReturnCode() == Dialog.OK) { setEditDefs(null); int returnCode = displayOptions(nameDialog.getValue(), "soot.Main"); //handle selection of main class here if (returnCode != Dialog.CANCEL) { getTreeRoot().addChild(new SootConfiguration(nameDialog.getValue())); refreshTree(); } } else { // cancel and do nothing } } // saves the main class to run with this configuration private void saveMainClass(String configName, String mainClass){ IDialogSettings settings = SootPlugin.getDefault().getDialogSettings(); settings.put(configName+"_mainClass", mainClass); } // returns the main class to run with this configuration private String getMainClass(String configName){ IDialogSettings settings = SootPlugin.getDefault().getDialogSettings(); String mainClass = settings.get(configName+"_mainClass"); if ((mainClass == null) || (mainClass.length() == 0)){ return "soot.Main"; } else { return mainClass; } } private ArrayList stringToList(String string){ StringTokenizer st = new StringTokenizer(string, ","); ArrayList list = new ArrayList(); while (st.hasMoreTokens()){ list.add(st.nextToken()); } return list; } private void refreshTree() { getTreeViewer().setInput(getTreeRoot()); getTreeViewer().setExpandedState(getTreeRoot(), true); getTreeViewer().refresh(getTreeRoot(), false); } private int displayOptions(String name) { return displayOptions(name, "soot.Main"); } private int displayOptions(String name, String mainClass) { PhaseOptionsDialog dialog = new PhaseOptionsDialog(getShell()); addEclipseDefsToDialog(dialog); setMainClassInDialog(dialog, mainClass); if (getEditDefs() != null) { Iterator it = getEditDefs().keySet().iterator(); while (it.hasNext()) { Object next = it.next(); String key = (String)next; String val = (String)getEditDefs().get(key); if ((val.equals("true")) || (val.equals("false"))) { //$NON-NLS-1$ //$NON-NLS-2$ dialog.addToDefList(key, new Boolean(val)); } else { dialog.addToDefList(key, val); } } } dialog.setConfigName(name); dialog.setCanRun(false); dialog.open(); if (dialog.getReturnCode() == Dialog.OK){ //save main class saveMainClass(name, dialog.getSootMainClass()); } return dialog.getReturnCode(); // saved - should show up in tree } // same as newPressed except does not ask for name private void editPressed() { if (getSelected() == null) return; String result = this.getSelected(); IDialogSettings settings = SootPlugin.getDefault().getDialogSettings(); String [] saveArray = settings.getArray(result); SootSavedConfiguration ssc = new SootSavedConfiguration(result, saveArray); setEditDefs(ssc.toHashMapFromArray()); displayOptions(result, getMainClass(result)); } // removes form tree private void deletePressed() { if (getSelected() == null) return; String result = this.getSelected(); // maybe ask if they are sure here first MessageDialog msgDialog = new MessageDialog(this.getShell(), Messages.getString("SootConfigManagerDialog.Soot_Configuration_Remove_Message"), null, Messages.getString("SootConfigManagerDialog.Are_you_sure_you_want_to_remove_this_configuration"), 0, new String [] {Messages.getString("SootConfigManagerDialog.Yes"), Messages.getString("SootConfigManagerDialog.No")}, 0); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ msgDialog.open(); if (msgDialog.getReturnCode() == 0) { // do the delete ArrayList toRemove = new ArrayList(); toRemove.add(result); SavedConfigManager scm = new SavedConfigManager(); scm.setDeleteList(toRemove); scm.handleDeletes(); // remove also from tree getTreeRoot().removeChild(result); refreshTree(); } } private void renamePressed(){ if (getSelected() == null) return; String result = this.getSelected(); IDialogSettings settings = SootPlugin.getDefault().getDialogSettings(); // gets current number of configurations int config_count = 0; int oldNameCount = 0; try { config_count = settings.getInt(Messages.getString("SootConfigManagerDialog.config_count")); //$NON-NLS-1$ } catch (NumberFormatException e) { } ArrayList currentNames = new ArrayList(); for (int i = 1; i <= config_count; i++) { currentNames.add(settings.get(Messages.getString("SootConfigManagerDialog.soot_run_config")+i)); //$NON-NLS-1$ if (((String)currentNames.get(i-1)).equals(result)){ oldNameCount = i; } } // sets validator to know about already used names SootConfigNameInputValidator validator = new SootConfigNameInputValidator(); validator.setAlreadyUsed(currentNames); InputDialog nameDialog = new InputDialog(this.getShell(), Messages.getString("SootConfigManagerDialog.Rename_Saved_Configuration"), Messages.getString("SootConfigManagerDialog.Enter_new_name"), "", validator); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ nameDialog.open(); if (nameDialog.getReturnCode() == Dialog.OK){ settings.put(Messages.getString("SootConfigManagerDialog.soot_run_config")+oldNameCount, nameDialog.getValue()); //$NON-NLS-1$ settings.put(nameDialog.getValue(), settings.getArray(result)); getTreeRoot().renameChild(result, nameDialog.getValue()); saveMainClass(nameDialog.getValue(), settings.get(result+"_mainClass")); } refreshTree(); } private void clonePressed(){ if (getSelected() == null) return; String result = this.getSelected(); IDialogSettings settings = SootPlugin.getDefault().getDialogSettings(); // gets current number of configurations int config_count = 0; try { config_count = settings.getInt(Messages.getString("SootConfigManagerDialog.config_count")); //$NON-NLS-1$ } catch (NumberFormatException e) { } ArrayList currentNames = new ArrayList(); for (int i = 1; i <= config_count; i++) { currentNames.add(settings.get(Messages.getString("SootConfigManagerDialog.soot_run_config")+i)); //$NON-NLS-1$ } // sets validator to know about already used names SootConfigNameInputValidator validator = new SootConfigNameInputValidator(); validator.setAlreadyUsed(currentNames); InputDialog nameDialog = new InputDialog(this.getShell(), Messages.getString("SootConfigManagerDialog.Clone_Saved_Configuration"), Messages.getString("SootConfigManagerDialog.Enter_new_name"), result, validator); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ nameDialog.open(); if (nameDialog.getReturnCode() == Dialog.OK){ config_count++; settings.put(Messages.getString("SootConfigManagerDialog.soot_run_config")+config_count, nameDialog.getValue()); //$NON-NLS-1$ settings.put(nameDialog.getValue(), settings.getArray(result)); settings.put(Messages.getString("SootConfigManagerDialog.config_count"), config_count); //$NON-NLS-1$ getTreeRoot().addChild(new SootConfiguration(nameDialog.getValue())); saveMainClass(nameDialog.getValue(), settings.get(result+"_mainClass")); } refreshTree(); } // runs the config private void runPressed() { super.okPressed(); if (getSelected() == null) return; IDialogSettings settings = SootPlugin.getDefault().getDialogSettings(); String mainClass = settings.get(getSelected()+"_mainClass"); if (getLauncher() instanceof SootConfigProjectLauncher) { ((SootConfigProjectLauncher)getLauncher()).launch(getSelected(), mainClass); } else if (getLauncher() instanceof SootConfigJavaProjectLauncher){ ((SootConfigJavaProjectLauncher)getLauncher()).launch(getSelected(), mainClass); } else if (getLauncher() instanceof SootConfigFileLauncher) { ((SootConfigFileLauncher)getLauncher()).launch(getSelected(), mainClass); } else if (getLauncher() instanceof SootConfigFromJavaFileLauncher){ ((SootConfigFromJavaFileLauncher)getLauncher()).launch(getSelected(), mainClass); } } private void importPressed(){ } /** * Returns the sashForm. * @return SashForm */ public SashForm getSashForm() { return sashForm; } /** * Sets the sashForm. * @param sashForm The sashForm to set */ public void setSashForm(SashForm sashForm) { this.sashForm = sashForm; } /** * Returns the selectionArea. * @return Composite */ public Composite getSelectionArea() { return selectionArea; } /** * Returns the treeViewer. * @return TreeViewer */ public TreeViewer getTreeViewer() { return treeViewer; } /** * Sets the selectionArea. * @param selectionArea The selectionArea to set */ public void setSelectionArea(Composite selectionArea) { this.selectionArea = selectionArea; } /** * Sets the treeViewer. * @param treeViewer The treeViewer to set */ public void setTreeViewer(TreeViewer treeViewer) { this.treeViewer = treeViewer; } /** * Returns the selected. * @return String */ public String getSelected() { return selected; } /** * Sets the selected. * @param selected The selected to set */ public void setSelected(String selected) { this.selected = selected; } /** * Returns the buttonPanel. * @return Composite */ public Composite getButtonPanel() { return buttonPanel; } /** * Sets the buttonPanel. * @param buttonPanel The buttonPanel to set */ public void setButtonPanel(Composite buttonPanel) { this.buttonPanel = buttonPanel; } /** * Returns the treeRoot. * @return SootConfiguration */ public SootConfiguration getTreeRoot() { return treeRoot; } /** * Sets the treeRoot. * @param treeRoot The treeRoot to set */ public void setTreeRoot(SootConfiguration treeRoot) { this.treeRoot = treeRoot; } /** * Returns the editDefs. * @return HashMap */ public HashMap getEditDefs() { return editDefs; } /** * Sets the editDefs. * @param editDefs The editDefs to set */ public void setEditDefs(HashMap editDefs) { this.editDefs = editDefs; } /** * Returns the launcher. * @return SootLauncher */ public SootLauncher getLauncher() { return launcher; } /** * Sets the launcher. * @param launcher The launcher to set */ public void setLauncher(SootLauncher launcher) { this.launcher = launcher; } }
BuddhaLabs/DeD-OSX
soot/soot-2.3.0/eclipse/ca.mcgill.sable.soot/src/ca/mcgill/sable/soot/ui/SootConfigManagerDialog.java
Java
gpl-2.0
21,587
// $Id$ /* * Superfish v1.4.8 - jQuery menu widget * Copyright (c) 2008 Joel Birch * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt */ jQuery(document).ready(function($) { $("#superfish ul.menu").superfish({ delay: 250, animation: {opacity:'show',height:'show'}, speed: 'fast', autoArrows: false, dropShadows: false }); }); ;(function($){ $.fn.superfish = function(op){ var sf = $.fn.superfish, c = sf.c, $arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')), over = function(){ var $$ = $(this), menu = getMenu($$); clearTimeout(menu.sfTimer); $$.showSuperfishUl().siblings().hideSuperfishUl(); }, out = function(){ var $$ = $(this), menu = getMenu($$), o = sf.op; clearTimeout(menu.sfTimer); menu.sfTimer=setTimeout(function(){ o.retainPath=($.inArray($$[0],o.$path)>-1); $$.hideSuperfishUl(); if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);} },o.delay); }, getMenu = function($menu){ var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0]; sf.op = sf.o[menu.serial]; return menu; }, addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); }; return this.each(function() { var s = this.serial = sf.o.length; var o = $.extend({},sf.defaults,op); o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){ $(this).addClass([o.hoverClass,c.bcClass].join(' ')) .filter('li:has(ul)').removeClass(o.pathClass); }); sf.o[s] = sf.op = o; $('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() { if (o.autoArrows) addArrow( $('>a:first-child',this) ); }) .not('.'+c.bcClass) .hideSuperfishUl(); var $a = $('a',this); $a.each(function(i){ var $li = $a.eq(i).parents('li'); $a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);}); }); o.onInit.call(this); }).each(function() { menuClasses = [c.menuClass]; if (sf.op.dropShadows && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass); $(this).addClass(menuClasses.join(' ')); }); }; var sf = $.fn.superfish; sf.o = []; sf.op = {}; sf.IE7fix = function(){ var o = sf.op; if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined) this.toggleClass(sf.c.shadowClass+'-off'); }; sf.c = { bcClass : 'sf-breadcrumb', menuClass : 'sf-js-enabled', anchorClass : 'sf-with-ul', arrowClass : 'sf-sub-indicator', shadowClass : 'sf-shadow' }; sf.defaults = { hoverClass : 'sfHover', pathClass : 'overideThisToUse', pathLevels : 1, delay : 700, animation : {opacity:'show'}, speed : 'slow', autoArrows : true, dropShadows : false, disableHI : false, // true disables hoverIntent detection onInit : function(){}, // callback functions onBeforeShow : function(){}, onShow : function(){}, onHide : function(){} }; $.fn.extend({ hideSuperfishUl : function(){ var o = sf.op, not = (o.retainPath===true) ? o.$path : ''; o.retainPath = false; var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass) .find('>ul').hide().css('visibility','hidden'); o.onHide.call($ul); return this; }, showSuperfishUl : function(){ var o = sf.op, sh = sf.c.shadowClass+'-off', $ul = this.addClass(o.hoverClass) .find('>ul:hidden').css('visibility','visible'); sf.IE7fix.call($ul); o.onBeforeShow.call($ul); $ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); }); return this; } }); })(jQuery);
moorebrett0/Partake
sites/all/themes/metropolis/scripts/superfish.js
JavaScript
gpl-2.0
4,145
/* * Copyright (C) ST-Ericsson SA 2010 * * Author: Rabin Vincent <[email protected]> * License terms: GNU General Public License (GPL) version 2 */ #ifndef __MACH_IRQS_BOARD_MOP500_H #define __MACH_IRQS_BOARD_MOP500_H #define AB8500_NR_IRQS 112 #define MOP500_AB8500_IRQ_BASE IRQ_BOARD_START #define MOP500_AB8500_IRQ_END (MOP500_AB8500_IRQ_BASE \ + AB8500_NR_IRQS) /* TC3589X irqs */ #define TC35892_NR_INTERNAL_IRQS 8 #define TC35892_INT_GPIO(x) (TC35892_NR_INTERNAL_IRQS + (x)) #define TC35892_NR_GPIOS 24 #define TC35892_NR_IRQS TC35892_INT_GPIO(TC35892_NR_GPIOS) #define MOP500_EGPIO_NR_IRQS TC35892_NR_IRQS #define MOP500_EGPIO_IRQ_BASE MOP500_AB8500_IRQ_END #define MOP500_EGPIO_IRQ(x) (MOP500_EGPIO_IRQ_BASE + (x)) #define MOP500_EGPIO_IRQ_END (MOP500_EGPIO_IRQ_BASE \ + MOP500_EGPIO_NR_IRQS) /* STMPE1601 irqs */ #define STMPE_NR_INTERNAL_IRQS 9 #define STMPE_INT_GPIO(x) (STMPE_NR_INTERNAL_IRQS + (x)) #define STMPE_NR_GPIOS 24 #define STMPE_NR_IRQS STMPE_INT_GPIO(STMPE_NR_GPIOS) #define MOP500_STMPE1601_IRQBASE MOP500_EGPIO_IRQ_END #define MOP500_STMPE1601_IRQ(x) (MOP500_STMPE1601_IRQBASE + (x)) #define MOP500_STMPE1601_IRQ_END \ MOP500_STMPE1601_IRQ(STMPE_NR_INTERNAL_IRQS) /* AB8500 virtual gpio IRQ */ #define AB8500_VIR_GPIO_NR_IRQS 16 #define MOP500_AB8500_VIR_GPIO_IRQ_BASE \ MOP500_STMPE1601_IRQ_END #define MOP500_AB8500_VIR_GPIO_IRQ_END \ (MOP500_AB8500_VIR_GPIO_IRQ_BASE + AB8500_VIR_GPIO_NR_IRQS) #define MOP500_NR_IRQS MOP500_AB8500_VIR_GPIO_IRQ_END #define MOP500_IRQ_END MOP500_NR_IRQS #if MOP500_IRQ_END > IRQ_BOARD_END #undef IRQ_BOARD_END #define IRQ_BOARD_END MOP500_IRQ_END #endif #endif
oschmidt/kernel_I8160P
arch/arm/mach-ux500/include/mach/irqs-board-mop500.h
C
gpl-2.0
1,702
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Resizable Visual Test : Resizable option aspectRatio 0.5</title> <link rel="stylesheet" href="../visual.css" type="text/css" /> <link rel="stylesheet" href="../../../themes/base/jquery.ui.all.css" type="text/css" /> <script type="text/javascript" src="../../../jquery-1.5.1.js"></script> <script type="text/javascript" src="../../../ui/jquery.ui.core.js"></script> <script type="text/javascript" src="../../../ui/jquery.ui.widget.js"></script> <script type="text/javascript" src="../../../ui/jquery.ui.mouse.js"></script> <script type="text/javascript" src="../../../ui/jquery.ui.resizable.js"></script> <script type="text/javascript"> $(function() { $("#resizable").resizable({ aspectRatio: 0.5 }); }); </script> <style type="text/css"> #resizable { width: 100px; height: 100px; background: silver; } </style> </head> <body> <div id="resizable">Resizable</div> </body> </html>
addyosmani/jqueryui-extendables
tests/visual/resizable/resizable_option_aspectRatio_0.5.html
HTML
gpl-2.0
975
#include <stdio.h> #undef _ANSI_ARGS_ #if defined(USE_PROTOTYPE) || ((defined(__STDC__) || defined(SABER)) && !defined(NO_PROTOTYPE)) || defined(__cplusplus) # define _USING_PROTOTYPES_ 1 # define _ANSI_ARGS_(x) x #else # define _ANSI_ARGS_(x) () #endif #ifdef SPRINTF_RETURN_CHAR extern char *sprintf _ANSI_ARGS_((char *,const char *, ...)); #else extern int sprintf _ANSI_ARGS_((char *,const char *, ...)); #endif int main() { char buf[16]; sprintf(buf,"%d",0); return 0; }
mads-bertelsen/McCode
support/MacOSX/Perl-Tk/Tk-804.032/config/Ksprintf.c
C
gpl-2.0
487
require("comp_tree/queue/queue_" + (RUBY_VERSION < "1.9" ? "18" : "19"))
UbiCastTeam/mkvtoolnix-ubicast
rake.d/vendor/comp_tree-1.1.3/lib/comp_tree/queue/queue.rb
Ruby
gpl-2.0
73
/* * oledlg internal header file * * Copyright (C) 2006 Huw Davies * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ #ifndef __OLEDLG_PRIVATE_H__ #define __OLEDLG_PRIVATE_H__ #include <stdarg.h> #define WIN32_NO_STATUS #define _INC_WINDOWS #define COM_NO_WINDOWS_H #define COBJMACROS #define NONAMELESSSTRUCT #define NONAMELESSUNION #include <windef.h> #include <winbase.h> #include <wingdi.h> #include <winuser.h> #include <oledlg.h> #include <wine/debug.h> #include <wine/unicode.h> #include "resource.h" extern HINSTANCE OLEDLG_hInstance DECLSPEC_HIDDEN; extern UINT cf_embed_source DECLSPEC_HIDDEN; extern UINT cf_embedded_object DECLSPEC_HIDDEN; extern UINT cf_link_source DECLSPEC_HIDDEN; extern UINT cf_object_descriptor DECLSPEC_HIDDEN; extern UINT cf_link_src_descriptor DECLSPEC_HIDDEN; extern UINT cf_ownerlink DECLSPEC_HIDDEN; extern UINT cf_filename DECLSPEC_HIDDEN; extern UINT cf_filenamew DECLSPEC_HIDDEN; extern UINT oleui_msg_help DECLSPEC_HIDDEN; extern UINT oleui_msg_enddialog DECLSPEC_HIDDEN; #endif /* __OLEDLG_PRIVATE_H__ */
GreenteaOS/Kernel
third-party/reactos/dll/win32/oledlg/oledlg_private.h
C
gpl-2.0
1,756
<?php /* +--------------------------------------------------------------------+ | CiviCRM version 4.3 | +--------------------------------------------------------------------+ | Copyright CiviCRM LLC (c) 2004-2013 | +--------------------------------------------------------------------+ | This file is a part of CiviCRM. | | | | CiviCRM is free software; you can copy, modify, and distribute it | | under the terms of the GNU Affero General Public License | | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. | | | | CiviCRM 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 Affero General Public License for more details. | | | | You should have received a copy of the GNU Affero General Public | | License and the CiviCRM Licensing Exception along | | with this program; if not, contact CiviCRM LLC | | at info[AT]civicrm[DOT]org. If you have questions about the | | GNU Affero General Public License or the licensing of CiviCRM, | | see the CiviCRM license FAQ at http://civicrm.org/licensing | +--------------------------------------------------------------------+ */ /** * * @package CRM * @copyright CiviCRM LLC (c) 2004-2013 * $Id$ * */ /** * This class summarizes the import results */ class CRM_Member_Import_Form_Summary extends CRM_Core_Form { /** * Function to set variables up before form is built * * @return void * @access public */ public function preProcess() { // set the error message path to display $errorFile = $this->assign('errorFile', $this->get('errorFile')); $totalRowCount = $this->get('totalRowCount'); $relatedCount = $this->get('relatedCount'); $totalRowCount += $relatedCount; $this->set('totalRowCount', $totalRowCount); $invalidRowCount = $this->get('invalidRowCount'); $conflictRowCount = $this->get('conflictRowCount'); $duplicateRowCount = $this->get('duplicateRowCount'); $onDuplicate = $this->get('onDuplicate'); $mismatchCount = $this->get('unMatchCount'); if ($duplicateRowCount > 0) { $urlParams = 'type=' . CRM_Member_Import_Parser::DUPLICATE . '&parser=CRM_Member_Import_Parser'; $this->set('downloadDuplicateRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams)); } elseif ($mismatchCount) { $urlParams = 'type=' . CRM_Member_Import_Parser::NO_MATCH . '&parser=CRM_Member_Import_Parser'; $this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams)); } else { $duplicateRowCount = 0; $this->set('duplicateRowCount', $duplicateRowCount); } $this->assign('dupeError', FALSE); if ($onDuplicate == CRM_Member_Import_Parser::DUPLICATE_UPDATE) { $dupeActionString = ts('These records have been updated with the imported data.'); } elseif ($onDuplicate == CRM_Member_Import_Parser::DUPLICATE_FILL) { $dupeActionString = ts('These records have been filled in with the imported data.'); } else { /* Skip by default */ $dupeActionString = ts('These records have not been imported.'); $this->assign('dupeError', TRUE); /* only subtract dupes from successful import if we're skipping */ $this->set('validRowCount', $totalRowCount - $invalidRowCount - $conflictRowCount - $duplicateRowCount - $mismatchCount ); } $this->assign('dupeActionString', $dupeActionString); $properties = array('totalRowCount', 'validRowCount', 'invalidRowCount', 'conflictRowCount', 'downloadConflictRecordsUrl', 'downloadErrorRecordsUrl', 'duplicateRowCount', 'downloadDuplicateRecordsUrl', 'downloadMismatchRecordsUrl', 'groupAdditions', 'unMatchCount'); foreach ($properties as $property) { $this->assign($property, $this->get($property)); } } /** * Function to actually build the form * * @return None * @access public */ public function buildQuickForm() { $this->addButtons(array( array( 'type' => 'next', 'name' => ts('Done'), 'isDefault' => TRUE, ), ) ); } /** * Return a descriptive name for the page, used in wizard header * * @return string * @access public */ public function getTitle() { return ts('Summary'); } }
tomlagier/NoblePower
wp-content/plugins/civicrm/civicrm/CRM/Member/Import/Form/Summary.php
PHP
gpl-2.0
4,848
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members import os import shutil from twisted.internet import defer class DirsMixin: _dirs = None def setUpDirs(self, *dirs): """Make sure C{dirs} exist and are empty, and set them up to be deleted in tearDown.""" self._dirs = map(os.path.abspath, dirs) for dir in self._dirs: if os.path.exists(dir): shutil.rmtree(dir) os.makedirs(dir) # return a deferred to make chaining easier return defer.succeed(None) def tearDownDirs(self): for dir in self._dirs: if os.path.exists(dir): shutil.rmtree(dir) # return a deferred to make chaining easier return defer.succeed(None)
pmisik/buildbot
master/buildbot/test/util/dirs.py
Python
gpl-2.0
1,425
#ifndef _ARCH_ARCHOS_AUDIO_TWL6040_H_ #define _ARCH_ARCHOS_AUDIO_TWL6040_H_ #include <linux/i2c/twl.h> struct audio_twl6040_device_config { void (*set_codec_master_clk_state)(int state); int (*get_master_clock_rate)(void); void (*set_speaker_state)(int state); void (*suspend)(void); void (*resume)(void); }; struct audio_twl6040_device_config * archos_audio_twl6040_get_io(void); extern int __init archos_audio_twl6040_init(struct twl4030_codec_data * codec_data); #endif
archos-sa/archos-gpl-gen9-kernel-ics
arch/arm/plat-omap/include/plat/archos-audio-twl6040.h
C
gpl-2.0
483
// license:BSD-3-Clause // copyright-holders:Luca Elia, David Haywood typedef device_delegate<int (UINT16 code, UINT8 color)> gfxbank_cb_delegate; #define SETA001_SPRITE_GFXBANK_CB_MEMBER(_name) int _name(UINT16 code, UINT8 color) #define MCFG_SETA001_SPRITE_GFXBANK_CB(_class, _method) \ seta001_device::set_gfxbank_callback(*device, gfxbank_cb_delegate(&_class::_method, #_class "::" #_method, downcast<_class *>(owner))); class seta001_device : public device_t { public: seta001_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock); // static configuration static void static_set_gfxdecode_tag(device_t &device, const char *tag); static void set_gfxbank_callback(device_t &device, gfxbank_cb_delegate callback) { downcast<seta001_device &>(device).m_gfxbank_cb = callback; } DECLARE_WRITE8_MEMBER( spritebgflag_w8 ); DECLARE_READ16_MEMBER( spritectrl_r16 ); DECLARE_WRITE16_MEMBER( spritectrl_w16 ); DECLARE_READ8_MEMBER( spritectrl_r8 ); DECLARE_WRITE8_MEMBER( spritectrl_w8 ); DECLARE_READ16_MEMBER( spriteylow_r16 ); DECLARE_WRITE16_MEMBER( spriteylow_w16 ); DECLARE_READ8_MEMBER( spriteylow_r8 ); DECLARE_WRITE8_MEMBER( spriteylow_w8 ); DECLARE_READ8_MEMBER( spritecodelow_r8 ); DECLARE_WRITE8_MEMBER( spritecodelow_w8 ); DECLARE_READ8_MEMBER( spritecodehigh_r8 ); DECLARE_WRITE8_MEMBER( spritecodehigh_w8 ); DECLARE_READ16_MEMBER( spritecode_r16 ); DECLARE_WRITE16_MEMBER( spritecode_w16 ); void draw_sprites(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect, int bank_size, int setac); void setac_eof( void ); void tnzs_eof( void ); // position kludges for seta.c & srmp2.c void set_fg_xoffsets( int flip, int noflip ) { m_fg_flipxoffs = flip; m_fg_noflipxoffs = noflip; }; void set_fg_yoffsets( int flip, int noflip ) { m_fg_flipyoffs = flip; m_fg_noflipyoffs = noflip; }; void set_bg_yoffsets( int flip, int noflip ) { m_bg_flipyoffs = flip; m_bg_noflipyoffs = noflip; }; void set_bg_xoffsets( int flip, int noflip ) { m_bg_flipxoffs = flip; m_bg_noflipxoffs = noflip; }; void set_colorbase(int base) { m_colorbase = base; }; void set_spritelimit(int limit) { m_spritelimit = limit; }; void set_transpen ( int pen ) { m_transpen = pen; }; int is_flipped() { return ((m_spritectrl[ 0 ] & 0x40) >> 6); }; protected: virtual void device_start() override; virtual void device_reset() override; private: void draw_background( bitmap_ind16 &bitmap, const rectangle &cliprect, int bank_size, int setac_type); void draw_foreground( screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect, int bank_size); required_device<gfxdecode_device> m_gfxdecode; gfxbank_cb_delegate m_gfxbank_cb; // configuration int m_fg_flipxoffs, m_fg_noflipxoffs; int m_fg_flipyoffs, m_fg_noflipyoffs; int m_bg_flipyoffs, m_bg_noflipyoffs; int m_bg_flipxoffs, m_bg_noflipxoffs; int m_colorbase; int m_spritelimit; int m_transpen; // live state UINT8 m_bgflag; UINT8 m_spritectrl[4]; UINT8 m_spriteylow[0x300]; // 0x200 low y + 0x100 bg stuff UINT8 m_spritecodelow[0x2000]; // tnzs.c stuff only uses half? UINT8 m_spritecodehigh[0x2000]; // ^ }; extern const device_type SETA001_SPRITE; #define MCFG_SETA001_SPRITE_GFXDECODE(_gfxtag) \ seta001_device::static_set_gfxdecode_tag(*device, "^" _gfxtag);
RJRetro/mame
src/mame/video/seta001.h
C
gpl-2.0
3,323
#ifndef MDL_H #define MDL_H /* Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ #if defined(__IBMC__) || defined(__IBMCPP__) /* Further down, "next_in_lock" and "next_in_context" have the same type, and in "sql_plist.h" this leads to an identical signature, which causes problems in function overloading. */ #pragma namemangling(v5) #endif #include "sql_plist.h" #include <my_sys.h> #include <m_string.h> #include <mysql_com.h> #include <hash.h> #include <algorithm> class THD; class MDL_context; class MDL_lock; class MDL_ticket; bool ok_for_lower_case_names(const char *name); /** @def ENTER_COND(C, M, S, O) Start a wait on a condition. @param C the condition to wait on @param M the associated mutex @param S the new stage to enter @param O the previous stage @sa EXIT_COND(). */ #define ENTER_COND(C, M, S, O) enter_cond(C, M, S, O, __func__, __FILE__, __LINE__) /** @def EXIT_COND(S) End a wait on a condition @param S the new stage to enter */ #define EXIT_COND(S) exit_cond(S, __func__, __FILE__, __LINE__) /** An interface to separate the MDL module from the THD, and the rest of the server code. */ class MDL_context_owner { public: virtual ~MDL_context_owner() {} /** Enter a condition wait. For @c enter_cond() / @c exit_cond() to work the mutex must be held before @c enter_cond(); this mutex is then released by @c exit_cond(). Usage must be: lock mutex; enter_cond(); your code; exit_cond(). @param cond the condition to wait on @param mutex the associated mutex @param [in] stage the stage to enter, or NULL @param [out] old_stage the previous stage, or NULL @param src_function function name of the caller @param src_file file name of the caller @param src_line line number of the caller @sa ENTER_COND(), THD::enter_cond() @sa EXIT_COND(), THD::exit_cond() */ virtual void enter_cond(mysql_cond_t *cond, mysql_mutex_t *mutex, const PSI_stage_info *stage, PSI_stage_info *old_stage, const char *src_function, const char *src_file, int src_line) = 0; /** @def EXIT_COND(S) End a wait on a condition @param [in] stage the new stage to enter @param src_function function name of the caller @param src_file file name of the caller @param src_line line number of the caller @sa ENTER_COND(), THD::enter_cond() @sa EXIT_COND(), THD::exit_cond() */ virtual void exit_cond(const PSI_stage_info *stage, const char *src_function, const char *src_file, int src_line) = 0; /** Has the owner thread been killed? */ virtual int is_killed() = 0; /** This one is only used for DEBUG_SYNC. (Do not use it to peek/poke into other parts of THD.) */ virtual THD* get_thd() = 0; /** @see THD::notify_shared_lock() */ virtual bool notify_shared_lock(MDL_context_owner *in_use, bool needs_thr_lock_abort) = 0; }; /** Type of metadata lock request. @sa Comments for MDL_object_lock::can_grant_lock() and MDL_scoped_lock::can_grant_lock() for details. */ enum enum_mdl_type { /* An intention exclusive metadata lock. Used only for scoped locks. Owner of this type of lock can acquire upgradable exclusive locks on individual objects. Compatible with other IX locks, but is incompatible with scoped S and X locks. */ MDL_INTENTION_EXCLUSIVE= 0, /* A shared metadata lock. To be used in cases when we are interested in object metadata only and there is no intention to access object data (e.g. for stored routines or during preparing prepared statements). We also mis-use this type of lock for open HANDLERs, since lock acquired by this statement has to be compatible with lock acquired by LOCK TABLES ... WRITE statement, i.e. SNRW (We can't get by by acquiring S lock at HANDLER ... OPEN time and upgrading it to SR lock for HANDLER ... READ as it doesn't solve problem with need to abort DML statements which wait on table level lock while having open HANDLER in the same connection). To avoid deadlock which may occur when SNRW lock is being upgraded to X lock for table on which there is an active S lock which is owned by thread which waits in its turn for table-level lock owned by thread performing upgrade we have to use thr_abort_locks_for_thread() facility in such situation. This problem does not arise for locks on stored routines as we don't use SNRW locks for them. It also does not arise when S locks are used during PREPARE calls as table-level locks are not acquired in this case. */ MDL_SHARED, /* A high priority shared metadata lock. Used for cases when there is no intention to access object data (i.e. data in the table). "High priority" means that, unlike other shared locks, it is granted ignoring pending requests for exclusive locks. Intended for use in cases when we only need to access metadata and not data, e.g. when filling an INFORMATION_SCHEMA table. Since SH lock is compatible with SNRW lock, the connection that holds SH lock lock should not try to acquire any kind of table-level or row-level lock, as this can lead to a deadlock. Moreover, after acquiring SH lock, the connection should not wait for any other resource, as it might cause starvation for X locks and a potential deadlock during upgrade of SNW or SNRW to X lock (e.g. if the upgrading connection holds the resource that is being waited for). */ MDL_SHARED_HIGH_PRIO, /* A shared metadata lock for cases when there is an intention to read data from table. A connection holding this kind of lock can read table metadata and read table data (after acquiring appropriate table and row-level locks). This means that one can only acquire TL_READ, TL_READ_NO_INSERT, and similar table-level locks on table if one holds SR MDL lock on it. To be used for tables in SELECTs, subqueries, and LOCK TABLE ... READ statements. */ MDL_SHARED_READ, /* A shared metadata lock for cases when there is an intention to modify (and not just read) data in the table. A connection holding SW lock can read table metadata and modify or read table data (after acquiring appropriate table and row-level locks). To be used for tables to be modified by INSERT, UPDATE, DELETE statements, but not LOCK TABLE ... WRITE or DDL). Also taken by SELECT ... FOR UPDATE. */ MDL_SHARED_WRITE, /* An upgradable shared metadata lock for cases when there is an intention to modify (and not just read) data in the table. Can be upgraded to MDL_SHARED_NO_WRITE and MDL_EXCLUSIVE. A connection holding SU lock can read table metadata and modify or read table data (after acquiring appropriate table and row-level locks). To be used for the first phase of ALTER TABLE. */ MDL_SHARED_UPGRADABLE, /* An upgradable shared metadata lock which blocks all attempts to update table data, allowing reads. A connection holding this kind of lock can read table metadata and read table data. Can be upgraded to X metadata lock. Note, that since this type of lock is not compatible with SNRW or SW lock types, acquiring appropriate engine-level locks for reading (TL_READ* for MyISAM, shared row locks in InnoDB) should be contention-free. To be used for the first phase of ALTER TABLE, when copying data between tables, to allow concurrent SELECTs from the table, but not UPDATEs. */ MDL_SHARED_NO_WRITE, /* An upgradable shared metadata lock which allows other connections to access table metadata, but not data. It blocks all attempts to read or update table data, while allowing INFORMATION_SCHEMA and SHOW queries. A connection holding this kind of lock can read table metadata modify and read table data. Can be upgraded to X metadata lock. To be used for LOCK TABLES WRITE statement. Not compatible with any other lock type except S and SH. */ MDL_SHARED_NO_READ_WRITE, /* An exclusive metadata lock. A connection holding this lock can modify both table's metadata and data. No other type of metadata lock can be granted while this lock is held. To be used for CREATE/DROP/RENAME TABLE statements and for execution of certain phases of other DDL statements. */ MDL_EXCLUSIVE, /* This should be the last !!! */ MDL_TYPE_END}; /** Duration of metadata lock. */ enum enum_mdl_duration { /** Locks with statement duration are automatically released at the end of statement or transaction. */ MDL_STATEMENT= 0, /** Locks with transaction duration are automatically released at the end of transaction. */ MDL_TRANSACTION, /** Locks with explicit duration survive the end of statement and transaction. They have to be released explicitly by calling MDL_context::release_lock(). */ MDL_EXPLICIT, /* This should be the last ! */ MDL_DURATION_END }; /** Maximal length of key for metadata locking subsystem. */ #define MAX_MDLKEY_LENGTH (1 + NAME_LEN + 1 + NAME_LEN + 1) /** Metadata lock object key. A lock is requested or granted based on a fully qualified name and type. E.g. They key for a table consists of <0 (=table)>+<database>+<table name>. Elsewhere in the comments this triple will be referred to simply as "key" or "name". */ class MDL_key { public: #ifdef HAVE_PSI_INTERFACE static void init_psi_keys(); #endif /** Object namespaces. Sic: when adding a new member to this enum make sure to update m_namespace_to_wait_state_name array in mdl.cc! Different types of objects exist in different namespaces - TABLE is for tables and views. - FUNCTION is for stored functions. - PROCEDURE is for stored procedures. - TRIGGER is for triggers. - EVENT is for event scheduler events Note that although there isn't metadata locking on triggers, it's necessary to have a separate namespace for them since MDL_key is also used outside of the MDL subsystem. */ enum enum_mdl_namespace { GLOBAL=0, SCHEMA, TABLE, FUNCTION, PROCEDURE, TRIGGER, EVENT, COMMIT, USER_LOCK, /* user level locks. */ /* This should be the last ! */ NAMESPACE_END }; const uchar *ptr() const { return (uchar*) m_ptr; } uint length() const { return m_length; } const char *db_name() const { return m_ptr + 1; } uint db_name_length() const { return m_db_name_length; } const char *name() const { return m_ptr + m_db_name_length + 2; } uint name_length() const { return m_length - m_db_name_length - 3; } enum_mdl_namespace mdl_namespace() const { return (enum_mdl_namespace)(m_ptr[0]); } /** Construct a metadata lock key from a triplet (mdl_namespace, database and name). @remark The key for a table is <mdl_namespace>+<database name>+<table name> @param mdl_namespace Id of namespace of object to be locked @param db Name of database to which the object belongs @param name Name of of the object @param key Where to store the the MDL key. */ void mdl_key_init(enum_mdl_namespace mdl_namespace, const char *db, const char *name) { m_ptr[0]= (char) mdl_namespace; /* It is responsibility of caller to ensure that db and object names are not longer than NAME_LEN. Still we play safe and try to avoid buffer overruns. */ DBUG_ASSERT(strlen(db) <= NAME_LEN); DBUG_ASSERT(strlen(name) <= NAME_LEN); m_db_name_length= static_cast<uint16>(strmake(m_ptr + 1, db, NAME_LEN) - m_ptr - 1); m_length= static_cast<uint16>(strmake(m_ptr + m_db_name_length + 2, name, NAME_LEN) - m_ptr + 1); m_hash_value= my_hash_sort(&my_charset_bin, (uchar*) m_ptr + 1, m_length - 1); DBUG_ASSERT(mdl_namespace == USER_LOCK || ok_for_lower_case_names(db)); } void mdl_key_init(const MDL_key *rhs) { memcpy(m_ptr, rhs->m_ptr, rhs->m_length); m_length= rhs->m_length; m_db_name_length= rhs->m_db_name_length; m_hash_value= rhs->m_hash_value; } bool is_equal(const MDL_key *rhs) const { return (m_length == rhs->m_length && memcmp(m_ptr, rhs->m_ptr, m_length) == 0); } /** Compare two MDL keys lexicographically. */ int cmp(const MDL_key *rhs) const { /* The key buffer is always '\0'-terminated. Since key character set is utf-8, we can safely assume that no character starts with a zero byte. */ using std::min; return memcmp(m_ptr, rhs->m_ptr, min(m_length, rhs->m_length)); } MDL_key(const MDL_key *rhs) { mdl_key_init(rhs); } MDL_key(enum_mdl_namespace namespace_arg, const char *db_arg, const char *name_arg) { mdl_key_init(namespace_arg, db_arg, name_arg); } MDL_key() {} /* To use when part of MDL_request. */ /** Get thread state name to be used in case when we have to wait on resource identified by key. */ const PSI_stage_info * get_wait_state_name() const { return & m_namespace_to_wait_state_name[(int)mdl_namespace()]; } my_hash_value_type hash_value() const { return m_hash_value + mdl_namespace(); } my_hash_value_type tc_hash_value() const { return m_hash_value; } private: uint16 m_length; uint16 m_db_name_length; my_hash_value_type m_hash_value; char m_ptr[MAX_MDLKEY_LENGTH]; static PSI_stage_info m_namespace_to_wait_state_name[NAMESPACE_END]; private: MDL_key(const MDL_key &); /* not implemented */ MDL_key &operator=(const MDL_key &); /* not implemented */ friend my_hash_value_type mdl_hash_function(const CHARSET_INFO *, const uchar *, size_t); }; /** A pending metadata lock request. A lock request and a granted metadata lock are represented by different classes because they have different allocation sites and hence different lifetimes. The allocation of lock requests is controlled from outside of the MDL subsystem, while allocation of granted locks (tickets) is controlled within the MDL subsystem. MDL_request is a C structure, you don't need to call a constructor or destructor for it. */ class MDL_request { public: /** Type of metadata lock. */ enum enum_mdl_type type; /** Duration for requested lock. */ enum enum_mdl_duration duration; /** Pointers for participating in the list of lock requests for this context. */ MDL_request *next_in_list; MDL_request **prev_in_list; /** Pointer to the lock ticket object for this lock request. Valid only if this lock request is satisfied. */ MDL_ticket *ticket; /** A lock is requested based on a fully qualified name and type. */ MDL_key key; public: static void *operator new(size_t size, MEM_ROOT *mem_root) throw () { return alloc_root(mem_root, size); } static void operator delete(void *ptr, MEM_ROOT *mem_root) {} void init(MDL_key::enum_mdl_namespace namespace_arg, const char *db_arg, const char *name_arg, enum_mdl_type mdl_type_arg, enum_mdl_duration mdl_duration_arg); void init(const MDL_key *key_arg, enum_mdl_type mdl_type_arg, enum_mdl_duration mdl_duration_arg); /** Set type of lock request. Can be only applied to pending locks. */ inline void set_type(enum_mdl_type type_arg) { DBUG_ASSERT(ticket == NULL); type= type_arg; } /* This is to work around the ugliness of TABLE_LIST compiler-generated assignment operator. It is currently used in several places to quickly copy "most" of the members of the table list. These places currently never assume that the mdl request is carried over to the new TABLE_LIST, or shared between lists. This method does not initialize the instance being assigned! Use of init() for initialization after this assignment operator is mandatory. Can only be used before the request has been granted. */ MDL_request& operator=(const MDL_request &rhs) { ticket= NULL; /* Do nothing, in particular, don't try to copy the key. */ return *this; } /* Another piece of ugliness for TABLE_LIST constructor */ MDL_request() {} MDL_request(const MDL_request *rhs) :type(rhs->type), duration(rhs->duration), ticket(NULL), key(&rhs->key) {} }; typedef void (*mdl_cached_object_release_hook)(void *); /** An abstract class for inspection of a connected subgraph of the wait-for graph. */ class MDL_wait_for_graph_visitor { public: virtual bool enter_node(MDL_context *node) = 0; virtual void leave_node(MDL_context *node) = 0; virtual bool inspect_edge(MDL_context *dest) = 0; virtual ~MDL_wait_for_graph_visitor(); MDL_wait_for_graph_visitor() {} }; /** Abstract class representing an edge in the waiters graph to be traversed by deadlock detection algorithm. */ class MDL_wait_for_subgraph { public: virtual ~MDL_wait_for_subgraph(); /** Accept a wait-for graph visitor to inspect the node this edge is leading to. */ virtual bool accept_visitor(MDL_wait_for_graph_visitor *gvisitor) = 0; enum enum_deadlock_weight { DEADLOCK_WEIGHT_DML= 0, DEADLOCK_WEIGHT_DDL= 100 }; /* A helper used to determine which lock request should be aborted. */ virtual uint get_deadlock_weight() const = 0; }; /** A granted metadata lock. @warning MDL_ticket members are private to the MDL subsystem. @note Multiple shared locks on a same object are represented by a single ticket. The same does not apply for other lock types. @note There are two groups of MDL_ticket members: - "Externally accessible". These members can be accessed from threads/contexts different than ticket owner in cases when ticket participates in some list of granted or waiting tickets for a lock. Therefore one should change these members before including then to waiting/granted lists or while holding lock protecting those lists. - "Context private". Such members are private to thread/context owning this ticket. I.e. they should not be accessed from other threads/contexts. */ class MDL_ticket : public MDL_wait_for_subgraph { public: /** Pointers for participating in the list of lock requests for this context. Context private. */ MDL_ticket *next_in_context; MDL_ticket **prev_in_context; /** Pointers for participating in the list of satisfied/pending requests for the lock. Externally accessible. */ MDL_ticket *next_in_lock; MDL_ticket **prev_in_lock; public: bool has_pending_conflicting_lock() const; MDL_context *get_ctx() const { return m_ctx; } bool is_upgradable_or_exclusive() const { return m_type == MDL_SHARED_UPGRADABLE || m_type == MDL_SHARED_NO_WRITE || m_type == MDL_SHARED_NO_READ_WRITE || m_type == MDL_EXCLUSIVE; } enum_mdl_type get_type() const { return m_type; } MDL_lock *get_lock() const { return m_lock; } MDL_key *get_key() const; void downgrade_lock(enum_mdl_type type); bool has_stronger_or_equal_type(enum_mdl_type type) const; bool is_incompatible_when_granted(enum_mdl_type type) const; bool is_incompatible_when_waiting(enum_mdl_type type) const; /** Implement MDL_wait_for_subgraph interface. */ virtual bool accept_visitor(MDL_wait_for_graph_visitor *dvisitor); virtual uint get_deadlock_weight() const; private: friend class MDL_context; MDL_ticket(MDL_context *ctx_arg, enum_mdl_type type_arg #ifndef DBUG_OFF , enum_mdl_duration duration_arg #endif ) : m_type(type_arg), #ifndef DBUG_OFF m_duration(duration_arg), #endif m_ctx(ctx_arg), m_lock(NULL) {} static MDL_ticket *create(MDL_context *ctx_arg, enum_mdl_type type_arg #ifndef DBUG_OFF , enum_mdl_duration duration_arg #endif ); static void destroy(MDL_ticket *ticket); private: /** Type of metadata lock. Externally accessible. */ enum enum_mdl_type m_type; #ifndef DBUG_OFF /** Duration of lock represented by this ticket. Context private. Debug-only. */ enum_mdl_duration m_duration; #endif /** Context of the owner of the metadata lock ticket. Externally accessible. */ MDL_context *m_ctx; /** Pointer to the lock object for this lock ticket. Externally accessible. */ MDL_lock *m_lock; private: MDL_ticket(const MDL_ticket &); /* not implemented */ MDL_ticket &operator=(const MDL_ticket &); /* not implemented */ }; /** Savepoint for MDL context. Doesn't include metadata locks with explicit duration as they are not released during rollback to savepoint. */ class MDL_savepoint { public: MDL_savepoint() {}; private: MDL_savepoint(MDL_ticket *stmt_ticket, MDL_ticket *trans_ticket) : m_stmt_ticket(stmt_ticket), m_trans_ticket(trans_ticket) {} friend class MDL_context; private: /** Pointer to last lock with statement duration which was taken before creation of savepoint. */ MDL_ticket *m_stmt_ticket; /** Pointer to last lock with transaction duration which was taken before creation of savepoint. */ MDL_ticket *m_trans_ticket; }; /** A reliable way to wait on an MDL lock. */ class MDL_wait { public: MDL_wait(); ~MDL_wait(); enum enum_wait_status { EMPTY = 0, GRANTED, VICTIM, TIMEOUT, KILLED }; bool set_status(enum_wait_status result_arg); enum_wait_status get_status(); void reset_status(); enum_wait_status timed_wait(MDL_context_owner *owner, struct timespec *abs_timeout, bool signal_timeout, const PSI_stage_info *wait_state_name); private: /** Condvar which is used for waiting until this context's pending request can be satisfied or this thread has to perform actions to resolve a potential deadlock (we subscribe to such notification by adding a ticket corresponding to the request to an appropriate queue of waiters). */ mysql_mutex_t m_LOCK_wait_status; mysql_cond_t m_COND_wait_status; enum_wait_status m_wait_status; }; typedef I_P_List<MDL_request, I_P_List_adapter<MDL_request, &MDL_request::next_in_list, &MDL_request::prev_in_list>, I_P_List_counter> MDL_request_list; /** Context of the owner of metadata locks. I.e. each server connection has such a context. */ class MDL_context { public: typedef I_P_List<MDL_ticket, I_P_List_adapter<MDL_ticket, &MDL_ticket::next_in_context, &MDL_ticket::prev_in_context> > Ticket_list; typedef Ticket_list::Iterator Ticket_iterator; MDL_context(); void destroy(); bool try_acquire_lock(MDL_request *mdl_request); bool acquire_lock(MDL_request *mdl_request, ulong lock_wait_timeout); bool acquire_locks(MDL_request_list *requests, ulong lock_wait_timeout); bool upgrade_shared_lock(MDL_ticket *mdl_ticket, enum_mdl_type new_type, ulong lock_wait_timeout); bool clone_ticket(MDL_request *mdl_request); void release_all_locks_for_name(MDL_ticket *ticket); void release_lock(MDL_ticket *ticket); bool is_lock_owner(MDL_key::enum_mdl_namespace mdl_namespace, const char *db, const char *name, enum_mdl_type mdl_type); unsigned long get_lock_owner(MDL_key *mdl_key); bool has_lock(const MDL_savepoint &mdl_savepoint, MDL_ticket *mdl_ticket); inline bool has_locks() const { return !(m_tickets[MDL_STATEMENT].is_empty() && m_tickets[MDL_TRANSACTION].is_empty() && m_tickets[MDL_EXPLICIT].is_empty()); } MDL_savepoint mdl_savepoint() { return MDL_savepoint(m_tickets[MDL_STATEMENT].front(), m_tickets[MDL_TRANSACTION].front()); } void set_explicit_duration_for_all_locks(); void set_transaction_duration_for_all_locks(); void set_lock_duration(MDL_ticket *mdl_ticket, enum_mdl_duration duration); void release_statement_locks(); void release_transactional_locks(); void rollback_to_savepoint(const MDL_savepoint &mdl_savepoint); MDL_context_owner *get_owner() { return m_owner; } /** @pre Only valid if we started waiting for lock. */ inline uint get_deadlock_weight() const { return m_waiting_for->get_deadlock_weight(); } /** Post signal to the context (and wake it up if necessary). @retval FALSE - Success, signal was posted. @retval TRUE - Failure, signal was not posted since context already has received some signal or closed signal slot. */ void init(MDL_context_owner *arg) { m_owner= arg; } void set_needs_thr_lock_abort(bool needs_thr_lock_abort) { /* @note In theory, this member should be modified under protection of some lock since it can be accessed from different threads. In practice, this is not necessary as code which reads this value and so might miss the fact that value was changed will always re-try reading it after small timeout and therefore will see the new value eventually. */ m_needs_thr_lock_abort= needs_thr_lock_abort; } bool get_needs_thr_lock_abort() const { return m_needs_thr_lock_abort; } public: /** If our request for a lock is scheduled, or aborted by the deadlock detector, the result is recorded in this class. */ MDL_wait m_wait; private: /** Lists of all MDL tickets acquired by this connection. Lists of MDL tickets: --------------------- The entire set of locks acquired by a connection can be separated in three subsets according to their duration: locks released at the end of statement, at the end of transaction and locks are released explicitly. Statement and transactional locks are locks with automatic scope. They are accumulated in the course of a transaction, and released either at the end of uppermost statement (for statement locks) or on COMMIT, ROLLBACK or ROLLBACK TO SAVEPOINT (for transactional locks). They must not be (and never are) released manually, i.e. with release_lock() call. Tickets with explicit duration are taken for locks that span multiple transactions or savepoints. These are: HANDLER SQL locks (HANDLER SQL is transaction-agnostic), LOCK TABLES locks (you can COMMIT/etc under LOCK TABLES, and the locked tables stay locked), user level locks (GET_LOCK()/RELEASE_LOCK() functions) and locks implementing "global read lock". Statement/transactional locks are always prepended to the beginning of the appropriate list. In other words, they are stored in reverse temporal order. Thus, when we rollback to a savepoint, we start popping and releasing tickets from the front until we reach the last ticket acquired after the savepoint. Locks with explicit duration are not stored in any particular order, and among each other can be split into four sets: [LOCK TABLES locks] [USER locks] [HANDLER locks] [GLOBAL READ LOCK locks] The following is known about these sets: * GLOBAL READ LOCK locks are always stored last. This is because one can't say SET GLOBAL read_only=1 or FLUSH TABLES WITH READ LOCK if one has locked tables. One can, however, LOCK TABLES after having entered the read only mode. Note, that subsequent LOCK TABLES statement will unlock the previous set of tables, but not the GRL! There are no HANDLER locks after GRL locks because SET GLOBAL read_only performs a FLUSH TABLES WITH READ LOCK internally, and FLUSH TABLES, in turn, implicitly closes all open HANDLERs. However, one can open a few HANDLERs after entering the read only mode. * LOCK TABLES locks include intention exclusive locks on involved schemas and global intention exclusive lock. */ Ticket_list m_tickets[MDL_DURATION_END]; MDL_context_owner *m_owner; /** TRUE - if for this context we will break protocol and try to acquire table-level locks while having only S lock on some table. To avoid deadlocks which might occur during concurrent upgrade of SNRW lock on such object to X lock we have to abort waits for table-level locks for such connections. FALSE - Otherwise. */ bool m_needs_thr_lock_abort; /** Read-write lock protecting m_waiting_for member. @note The fact that this read-write lock prefers readers is important as deadlock detector won't work correctly otherwise. @sa Comment for MDL_lock::m_rwlock. */ mysql_prlock_t m_LOCK_waiting_for; /** Tell the deadlock detector what metadata lock or table definition cache entry this session is waiting for. In principle, this is redundant, as information can be found by inspecting waiting queues, but we'd very much like it to be readily available to the wait-for graph iterator. */ MDL_wait_for_subgraph *m_waiting_for; private: THD *get_thd() const { return m_owner->get_thd(); } MDL_ticket *find_ticket(MDL_request *mdl_req, enum_mdl_duration *duration); void release_locks_stored_before(enum_mdl_duration duration, MDL_ticket *sentinel); void release_lock(enum_mdl_duration duration, MDL_ticket *ticket); bool try_acquire_lock_impl(MDL_request *mdl_request, MDL_ticket **out_ticket); public: void find_deadlock(); ulong get_thread_id() const { return thd_get_thread_id(get_thd()); } bool visit_subgraph(MDL_wait_for_graph_visitor *dvisitor); /** Inform the deadlock detector there is an edge in the wait-for graph. */ void will_wait_for(MDL_wait_for_subgraph *waiting_for_arg) { mysql_prlock_wrlock(&m_LOCK_waiting_for); m_waiting_for= waiting_for_arg; mysql_prlock_unlock(&m_LOCK_waiting_for); } /** Remove the wait-for edge from the graph after we're done waiting. */ void done_waiting_for() { mysql_prlock_wrlock(&m_LOCK_waiting_for); m_waiting_for= NULL; mysql_prlock_unlock(&m_LOCK_waiting_for); } void lock_deadlock_victim() { mysql_prlock_rdlock(&m_LOCK_waiting_for); } void unlock_deadlock_victim() { mysql_prlock_unlock(&m_LOCK_waiting_for); } private: MDL_context(const MDL_context &rhs); /* not implemented */ MDL_context &operator=(MDL_context &rhs); /* not implemented */ /* metadata_lock_info plugin */ friend int i_s_metadata_lock_info_fill_row(MDL_ticket*, void*); }; void mdl_init(); void mdl_destroy(); extern "C" unsigned long thd_get_thread_id(const MYSQL_THD thd); /** Check if a connection in question is no longer connected. @details Replication apply thread is always connected. Otherwise, does a poll on the associated socket to check if the client is gone. */ extern "C" int thd_is_connected(MYSQL_THD thd); /* Start-up parameter for the maximum size of the unused MDL_lock objects cache and a constant for its default value. */ extern ulong mdl_locks_cache_size; static const ulong MDL_LOCKS_CACHE_SIZE_DEFAULT = 1024; /* Start-up parameter for the number of partitions of the hash containing all the MDL_lock objects and a constant for its default value. */ extern ulong mdl_locks_hash_partitions; static const ulong MDL_LOCKS_HASH_PARTITIONS_DEFAULT = 8; /* Metadata locking subsystem tries not to grant more than max_write_lock_count high-prio, strong locks successively, to avoid starving out weak, low-prio locks. */ extern "C" ulong max_write_lock_count; extern MYSQL_PLUGIN_IMPORT int mdl_iterate(int (*callback)(MDL_ticket *ticket, void *arg), void *arg); #endif
jb-boin/mariadb-10.0
sql/mdl.h
C
gpl-2.0
33,341
/*if (window.attachEvent) window.attachEvent('onLoad', checkNumItems); else window.addEventListener('load', checkNumItems, false); */ $(document).ready(function() { checkNumItems(); }); var numItems = 0; function checkNumItems() { if (document.getElementById("imageGalleryNextPageItem")) { var ul = document.getElementById("imageGalleryItemList"); if (ul) { var li = ul.getElementsByTagName("li"); //alert(li.length); if (li[0]) { numItems = li.length - 1; checkShowOrHide(); if (window.attachEvent) window.attachEvent('onresize', checkShowOrHide); else window.addEventListener('resize', checkShowOrHide, false); } } } } function checkShowOrHide() { var ul = document.getElementById("imageGalleryItemList"); if (ul) { var li = ul.getElementsByTagName("li"); if (li[0]) { var top = li[0].offsetTop; for(var i=1; i < li.length - 1; i++) { if (li[i].offsetTop != top) break; } if (numItems % i == 0) { document.getElementById("imageGalleryNextPageItem").style.display = 'none'; } else { document.getElementById("imageGalleryNextPageItem").style.display = 'inline-block'; } } } }
carleton/reason_package
reason_4.0/www/js/gallery2/next_page_link.v2.js
JavaScript
gpl-2.0
1,309
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2013 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #ifndef UTM_HPP #define UTM_HPP #include "Math/fixed.hpp" struct GeoPoint; class Angle; struct UTM { unsigned char zone_number; char zone_letter; fixed easting, northing; UTM() = default; constexpr UTM(unsigned char _zone_number, char _zone_letter, fixed _easting, fixed _northing) :zone_number(_zone_number), zone_letter(_zone_letter), easting(_easting), northing(_northing) {} static UTM FromGeoPoint(const GeoPoint &p); GeoPoint ToGeoPoint() const; private: static unsigned char CalculateZoneNumber(const GeoPoint &p); static char CalculateZoneLetter(const Angle latitude); static Angle GetCentralMeridian(unsigned char zone_number); }; #endif
onkelhotte/XCSoar
src/Geo/UTM.hpp
C++
gpl-2.0
1,592
/****************************************************************************** * * Copyright (C) 1997-2014 by Dimitri van Heesch. * * Permission to use, copy, modify, and distribute this software and its * documentation under the terms of the GNU General Public License is hereby * granted. No representations are made about the suitability of this software * for any purpose. It is provided "as is" without express or implied warranty. * See the GNU General Public License for more details. * * Documents produced by Doxygen are derivative works derived from the * input used in their production; they are not affected by this license. * */ #ifndef MARKDOWN_H #define MARKDOWN_H #include <qcstring.h> #include "parserintf.h" class Entry; /** processes string \a s and converts markdown into doxygen/html commands. */ QCString processMarkdown(const QCString &fileName,const int lineNr,Entry *e,const QCString &s); QCString markdownFileNameToId(const QCString &fileName); class MarkdownFileParser : public ParserInterface { public: virtual ~MarkdownFileParser() {} void startTranslationUnit(const char *) {} void finishTranslationUnit() {} void parseInput(const char *fileName, const char *fileBuf, Entry *root, bool sameTranslationUnit, QStrList &filesInSameTranslationUnit); bool needsPreprocessing(const QCString &) { return FALSE; } void parseCode(CodeOutputInterface &codeOutIntf, const char *scopeName, const QCString &input, SrcLangExt lang, bool isExampleBlock, const char *exampleName=0, FileDef *fileDef=0, int startLine=-1, int endLine=-1, bool inlineFragment=FALSE, MemberDef *memberDef=0, bool showLineNumbers=TRUE, Definition *searchCtx=0, bool collectXRefs=TRUE ); void resetCodeParserState(); void parsePrototype(const char *text); }; #endif
andyque/doxygen
src/markdown.h
C
gpl-2.0
2,163
/* Copyright (C) 1994, 1995, 1996 Free Software Foundation This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "priv.h" #include "io_S.h" /* Implement io_duplicate as described in <hurd/io.defs>. */ kern_return_t diskfs_S_io_duplicate (struct protid *cred, mach_port_t *port, mach_msg_type_name_t *portpoly) { error_t err; struct protid *newpi; if (!cred) return EOPNOTSUPP; pthread_mutex_lock (&cred->po->np->lock); refcount_ref (&cred->po->refcnt); err = diskfs_create_protid (cred->po, cred->user, &newpi); if (! err) { *port = ports_get_right (newpi); *portpoly = MACH_MSG_TYPE_MAKE_SEND; ports_port_deref (newpi); } else refcount_deref (&cred->po->refcnt); pthread_mutex_unlock (&cred->po->np->lock); return err; }
Phant0mas/Hurd
libdiskfs/io-duplicate.c
C
gpl-2.0
1,444
/* * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import javax.swing.*; import java.awt.*; /* * @test * @bug 8164811 * @key headful * @summary Check if a per-pixel translucent window shows only the area having * opaque pixels * Test Description: Check if PERPIXEL_TRANSLUCENT Translucency type is supported * on the current platform. Proceed if it is supported. Create a swing window * with some swing components in it and a transparent background (alpha 0.0). * Bring this window on top of a known background. Do this test for JFrame, * JWindow and JDialog * Expected Result: Only the components present in the window must be shown. Other * areas of the window must be transparent so that the background shows * @author mrkam * @library /lib/client * @build Common ExtendedRobot * @run main PerPixelTranslucentSwing * @run main/othervm -Dsun.java2d.uiScale=1.5 PerPixelTranslucentSwing */ public class PerPixelTranslucentSwing extends Common { JButton north; public static void main(String[] ignored) throws Exception { FG_COLOR = new Color(200, 0, 0, 0); if (checkTranslucencyMode(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSLUCENT)) for (Class<Window> windowClass: WINDOWS_TO_TEST) new PerPixelTranslucentSwing(windowClass).doTest(); } public PerPixelTranslucentSwing(Class windowClass) throws Exception { super(windowClass); } @Override public void createSwingComponents() { Container contentPane = RootPaneContainer.class.cast(window).getContentPane(); BorderLayout bl = new BorderLayout(10, 5); contentPane.setLayout(bl); north = new JButton("North"); contentPane.add(north, BorderLayout.NORTH); JList center = new JList(new String[] {"Center"}); contentPane.add(center, BorderLayout.CENTER); JTextField south = new JTextField("South"); contentPane.add(south, BorderLayout.SOUTH); window.pack(); window.setVisible(true); north.requestFocus(); } @Override public void doTest() throws Exception { robot.waitForIdle(delay); // Check for background translucency Rectangle bounds = north.getBounds(); Point loc = north.getLocationOnScreen(); Color color = robot.getPixelColor(loc.x + bounds.width / 2, loc.y + bounds.height + 3); System.out.println(color); if (BG_COLOR.getRGB() != color.getRGB()) throw new RuntimeException("Background is not translucent (" + color + ")"); EventQueue.invokeAndWait(this::dispose); } }
md-5/jdk10
test/jdk/javax/swing/JWindow/ShapedAndTranslucentWindows/PerPixelTranslucentSwing.java
Java
gpl-2.0
3,668
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2006 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "download_helper.h" #include <algorithm> #include <sstream> #include "RequestGroup.h" #include "Option.h" #include "prefs.h" #include "Metalink2RequestGroup.h" #include "ProtocolDetector.h" #include "paramed_string.h" #include "UriListParser.h" #include "DownloadContext.h" #include "RecoverableException.h" #include "DlAbortEx.h" #include "message.h" #include "fmt.h" #include "FileEntry.h" #include "LogFactory.h" #include "File.h" #include "util.h" #include "array_fun.h" #include "OptionHandler.h" #include "ByteArrayDiskWriter.h" #include "a2functional.h" #include "ByteArrayDiskWriterFactory.h" #include "MetadataInfo.h" #include "OptionParser.h" #include "SegList.h" #include "download_handlers.h" #include "SimpleRandomizer.h" #ifdef ENABLE_BITTORRENT # include "bittorrent_helper.h" # include "BtConstants.h" # include "ValueBaseBencodeParser.h" #endif // ENABLE_BITTORRENT namespace aria2 { namespace { void unfoldURI (std::vector<std::string>& result, const std::vector<std::string>& args) { for(const auto& i : args) { paramed_string::expand(std::begin(i), std::end(i), std::back_inserter(result)); } } } // namespace namespace { template<typename InputIterator> void splitURI(std::vector<std::string>& result, InputIterator begin, InputIterator end, size_t numSplit, size_t maxIter) { size_t numURIs = std::distance(begin, end); if(numURIs >= numSplit) { result.insert(std::end(result), begin, end); } else if(numURIs > 0) { size_t num = std::min(numSplit/numURIs, maxIter); for(size_t i = 0; i < num; ++i) { result.insert(std::end(result), begin, end); } if(num < maxIter) { result.insert(std::end(result), begin, begin+(numSplit%numURIs)); } } } } // namespace namespace { std::shared_ptr<GroupId> getGID(const std::shared_ptr<Option>& option) { std::shared_ptr<GroupId> gid; if(option->defined(PREF_GID)) { a2_gid_t n; if(GroupId::toNumericId(n, option->get(PREF_GID).c_str()) != 0) { throw DL_ABORT_EX(fmt("%s is invalid for GID.", option->get(PREF_GID).c_str())); } gid = GroupId::import(n); if(!gid) { throw DL_ABORT_EX(fmt("GID %s is not unique.", option->get(PREF_GID).c_str())); } } else { gid = GroupId::create(); } return gid; } } // namespace namespace { std::shared_ptr<RequestGroup> createRequestGroup (const std::shared_ptr<Option>& optionTemplate, const std::vector<std::string>& uris, bool useOutOption = false) { auto option = util::copy(optionTemplate); auto rg = std::make_shared<RequestGroup>(getGID(option), option); auto dctx = std::make_shared<DownloadContext> (option->getAsInt(PREF_PIECE_LENGTH), 0, useOutOption&&!option->blank(PREF_OUT)? util::applyDir(option->get(PREF_DIR), option->get(PREF_OUT)):A2STR::NIL); dctx->getFirstFileEntry()->setUris(uris); dctx->getFirstFileEntry()->setMaxConnectionPerServer (option->getAsInt(PREF_MAX_CONNECTION_PER_SERVER)); const std::string& checksum = option->get(PREF_CHECKSUM); if(!checksum.empty()) { auto p = util::divide(std::begin(checksum), std::end(checksum), '='); std::string hashType(p.first.first, p.first.second); std::string hexDigest(p.second.first, p.second.second); util::lowercase(hashType); dctx->setDigest(hashType, util::fromHex(std::begin(hexDigest), std::end(hexDigest))); } rg->setDownloadContext(dctx); if(option->getAsBool(PREF_ENABLE_RPC)) { rg->setPauseRequested(option->getAsBool(PREF_PAUSE)); } removeOneshotOption(option); return rg; } } // namespace #if defined(ENABLE_BITTORRENT) || defined(ENABLE_METALINK) namespace { std::shared_ptr<MetadataInfo> createMetadataInfo (const std::shared_ptr<GroupId>& gid, const std::string& uri) { return std::make_shared<MetadataInfo>(gid, uri); } } // namespace namespace { std::shared_ptr<MetadataInfo> createMetadataInfoDataOnly() { return std::make_shared<MetadataInfo>(); } } // namespace #endif // ENABLE_BITTORRENT || ENABLE_METALINK #ifdef ENABLE_BITTORRENT namespace { std::shared_ptr<RequestGroup> createBtRequestGroup(const std::string& metaInfoUri, const std::shared_ptr<Option>& optionTemplate, const std::vector<std::string>& auxUris, const ValueBase* torrent, bool adjustAnnounceUri = true) { auto option = util::copy(optionTemplate); auto gid = getGID(option); auto rg = std::make_shared<RequestGroup>(gid, option); auto dctx = std::make_shared<DownloadContext>(); // may throw exception bittorrent::loadFromMemory(torrent, dctx, option, auxUris, metaInfoUri.empty() ? "default" : metaInfoUri); for (auto &fe : dctx->getFileEntries()) { auto &uris = fe->getRemainingUris(); std::shuffle(std::begin(uris), std::end(uris), *SimpleRandomizer::getInstance()); } if(metaInfoUri.empty()) { rg->setMetadataInfo(createMetadataInfoDataOnly()); } else { rg->setMetadataInfo(createMetadataInfo(gid, metaInfoUri)); } if(adjustAnnounceUri) { bittorrent::adjustAnnounceUri(bittorrent::getTorrentAttrs(dctx), option); } auto sgl = util::parseIntSegments(option->get(PREF_SELECT_FILE)); sgl.normalize(); dctx->setFileFilter(std::move(sgl)); std::istringstream indexOutIn(option->get(PREF_INDEX_OUT)); auto indexPaths = util::createIndexPaths(indexOutIn); for(const auto& i : indexPaths) { dctx->setFilePathWithIndex (i.first, util::applyDir(option->get(PREF_DIR), i.second)); } rg->setDownloadContext(dctx); if(option->getAsBool(PREF_ENABLE_RPC)) { rg->setPauseRequested(option->getAsBool(PREF_PAUSE)); } // Remove "metalink" from Accept Type list to avoid server from // responding Metalink file for web-seeding URIs. dctx->setAcceptMetalink(false); removeOneshotOption(option); return rg; } } // namespace namespace { std::shared_ptr<RequestGroup> createBtMagnetRequestGroup (const std::string& magnetLink, const std::shared_ptr<Option>& optionTemplate) { auto option = util::copy(optionTemplate); auto gid = getGID(option); auto rg = std::make_shared<RequestGroup>(gid, option); auto dctx = std::make_shared<DownloadContext>(METADATA_PIECE_SIZE, 0); // We only know info hash. Total Length is unknown at this moment. dctx->markTotalLengthIsUnknown(); rg->setFileAllocationEnabled(false); rg->setPreLocalFileCheckEnabled(false); bittorrent::loadMagnet(magnetLink, dctx); auto torrentAttrs = bittorrent::getTorrentAttrs(dctx); bittorrent::adjustAnnounceUri(torrentAttrs, option); dctx->getFirstFileEntry()->setPath(torrentAttrs->name); rg->setDownloadContext(dctx); rg->clearPostDownloadHandler(); rg->addPostDownloadHandler (download_handlers::getUTMetadataPostDownloadHandler()); rg->setDiskWriterFactory(std::make_shared<ByteArrayDiskWriterFactory>()); rg->setMetadataInfo(createMetadataInfo(gid, magnetLink)); rg->markInMemoryDownload(); if(option->getAsBool(PREF_ENABLE_RPC)) { rg->setPauseRequested(option->getAsBool(PREF_PAUSE)); } removeOneshotOption(option); return rg; } } // namespace void createRequestGroupForBitTorrent (std::vector<std::shared_ptr<RequestGroup>>& result, const std::shared_ptr<Option>& option, const std::vector<std::string>& uris, const std::string& metaInfoUri, const std::string& torrentData, bool adjustAnnounceUri) { std::unique_ptr<ValueBase> torrent; bittorrent::ValueBaseBencodeParser parser; if(torrentData.empty()) { torrent = parseFile(parser, metaInfoUri); } else { ssize_t error; torrent = parser.parseFinal(torrentData.c_str(), torrentData.size(), error); } if(!torrent) { throw DL_ABORT_EX2("Bencode decoding failed", error_code::BENCODE_PARSE_ERROR); } createRequestGroupForBitTorrent(result, option, uris, metaInfoUri, torrent.get(), adjustAnnounceUri); } void createRequestGroupForBitTorrent (std::vector<std::shared_ptr<RequestGroup>>& result, const std::shared_ptr<Option>& option, const std::vector<std::string>& uris, const std::string& metaInfoUri, const ValueBase* torrent, bool adjustAnnounceUri) { std::vector<std::string> nargs; if(option->get(PREF_PARAMETERIZED_URI) == A2_V_TRUE) { unfoldURI(nargs, uris); } else { nargs = uris; } // we ignore -Z option here size_t numSplit = option->getAsInt(PREF_SPLIT); auto rg = createBtRequestGroup(metaInfoUri, option, nargs, torrent, adjustAnnounceUri); rg->setNumConcurrentCommand(numSplit); result.push_back(rg); } #endif // ENABLE_BITTORRENT #ifdef ENABLE_METALINK void createRequestGroupForMetalink (std::vector<std::shared_ptr<RequestGroup>>& result, const std::shared_ptr<Option>& option, const std::string& metalinkData) { if(metalinkData.empty()) { Metalink2RequestGroup().generate(result, option->get(PREF_METALINK_FILE), option, option->get(PREF_METALINK_BASE_URI)); } else { auto dw = std::make_shared<ByteArrayDiskWriter>(); dw->setString(metalinkData); Metalink2RequestGroup().generate(result, dw, option, option->get(PREF_METALINK_BASE_URI)); } } #endif // ENABLE_METALINK namespace { class AccRequestGroup { private: std::vector<std::shared_ptr<RequestGroup>>& requestGroups_; ProtocolDetector detector_; std::shared_ptr<Option> option_; bool ignoreLocalPath_; bool throwOnError_; public: AccRequestGroup(std::vector<std::shared_ptr<RequestGroup>>& requestGroups, std::shared_ptr<Option> option, bool ignoreLocalPath = false, bool throwOnError = false): requestGroups_(requestGroups), option_(std::move(option)), ignoreLocalPath_(ignoreLocalPath), throwOnError_(throwOnError) {} void operator()(const std::string& uri) { if(detector_.isStreamProtocol(uri)) { std::vector<std::string> streamURIs; size_t numIter = option_->getAsInt(PREF_MAX_CONNECTION_PER_SERVER); size_t numSplit = option_->getAsInt(PREF_SPLIT); size_t num = std::min(numIter, numSplit); for(size_t i = 0; i < num; ++i) { streamURIs.push_back(uri); } auto rg = createRequestGroup(option_, streamURIs); rg->setNumConcurrentCommand(numSplit); requestGroups_.push_back(rg); } #ifdef ENABLE_BITTORRENT else if(detector_.guessTorrentMagnet(uri)) { requestGroups_.push_back(createBtMagnetRequestGroup(uri, option_)); } else if(!ignoreLocalPath_ && detector_.guessTorrentFile(uri)) { try { bittorrent::ValueBaseBencodeParser parser; auto torrent = parseFile(parser, uri); if(!torrent) { throw DL_ABORT_EX2("Bencode decoding failed", error_code::BENCODE_PARSE_ERROR); } requestGroups_.push_back (createBtRequestGroup(uri, option_, {}, torrent.get())); } catch(RecoverableException& e) { if(throwOnError_) { throw; } else { // error occurred while parsing torrent file. // We simply ignore it. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e); } } } #endif // ENABLE_BITTORRENT #ifdef ENABLE_METALINK else if(!ignoreLocalPath_ && detector_.guessMetalinkFile(uri)) { try { Metalink2RequestGroup().generate(requestGroups_, uri, option_, option_->get(PREF_METALINK_BASE_URI)); } catch(RecoverableException& e) { if(throwOnError_) { throw; } else { // error occurred while parsing metalink file. // We simply ignore it. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e); } } } #endif // ENABLE_METALINK else { if(throwOnError_) { throw DL_ABORT_EX(fmt(MSG_UNRECOGNIZED_URI, uri.c_str())); } else { A2_LOG_ERROR(fmt(MSG_UNRECOGNIZED_URI, uri.c_str())); } } } }; } // namespace namespace { class StreamProtocolFilter { private: ProtocolDetector detector_; public: bool operator()(const std::string& uri) { return detector_.isStreamProtocol(uri); } }; } // namespace void createRequestGroupForUri (std::vector<std::shared_ptr<RequestGroup>>& result, const std::shared_ptr<Option>& option, const std::vector<std::string>& uris, bool ignoreForceSequential, bool ignoreLocalPath, bool throwOnError) { std::vector<std::string> nargs; if(option->get(PREF_PARAMETERIZED_URI) == A2_V_TRUE) { unfoldURI(nargs, uris); } else { nargs = uris; } if(!ignoreForceSequential && option->get(PREF_FORCE_SEQUENTIAL) == A2_V_TRUE) { std::for_each(std::begin(nargs), std::end(nargs), AccRequestGroup(result, option, ignoreLocalPath, throwOnError)); } else { auto strmProtoEnd = std::stable_partition(std::begin(nargs), std::end(nargs), StreamProtocolFilter()); // let's process http/ftp protocols first. if(std::begin(nargs) != strmProtoEnd) { size_t numIter = option->getAsInt(PREF_MAX_CONNECTION_PER_SERVER); size_t numSplit = option->getAsInt(PREF_SPLIT); std::vector<std::string> streamURIs; splitURI(streamURIs, std::begin(nargs), strmProtoEnd, numSplit, numIter); try { auto rg = createRequestGroup(option, streamURIs, true); rg->setNumConcurrentCommand(numSplit); result.push_back(rg); } catch(RecoverableException& e) { if(throwOnError) { throw; } else { A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e); } } } // process remaining URIs(local metalink, BitTorrent files) std::for_each(strmProtoEnd, std::end(nargs), AccRequestGroup(result, option, ignoreLocalPath, throwOnError)); } } bool createRequestGroupFromUriListParser (std::vector<std::shared_ptr<RequestGroup>>& result, const Option* option, UriListParser* uriListParser) { // Since result already contains some entries, we cache the size of // it. Later, we use this value to determine RequestGroup is // actually created. size_t num = result.size(); while(uriListParser->hasNext()) { std::vector<std::string> uris; Option tempOption; uriListParser->parseNext(uris, tempOption); if(uris.empty()) { continue; } auto requestOption = std::make_shared<Option>(*option); requestOption->remove(PREF_OUT); const auto& oparser = OptionParser::getInstance(); for(size_t i = 1, len = option::countOption(); i < len; ++i) { auto pref = option::i2p(i); auto h = oparser->find(pref); if(h && h->getInitialOption() && tempOption.defined(pref)) { requestOption->put(pref, tempOption.get(pref)); } } // This does not throw exception because throwOnError = false. createRequestGroupForUri(result, requestOption, uris); if(num < result.size()) { return true; } } return false; } std::shared_ptr<UriListParser> openUriListParser(const std::string& filename) { std::string listPath; if(filename == "-") { listPath = DEV_STDIN; } else { if(!File(filename).isFile()) { throw DL_ABORT_EX (fmt(EX_FILE_OPEN, filename.c_str(), "No such file")); } listPath = filename; } return std::make_shared<UriListParser>(listPath); } void createRequestGroupForUriList (std::vector<std::shared_ptr<RequestGroup>>& result, const std::shared_ptr<Option>& option) { auto uriListParser = openUriListParser(option->get(PREF_INPUT_FILE)); while(createRequestGroupFromUriListParser(result, option.get(), uriListParser.get())); } std::shared_ptr<MetadataInfo> createMetadataInfoFromFirstFileEntry (const std::shared_ptr<GroupId>& gid, const std::shared_ptr<DownloadContext>& dctx) { if(dctx->getFileEntries().empty()) { return nullptr; } else { auto uris = dctx->getFileEntries()[0]->getUris(); if(uris.empty()) { return nullptr; } return std::make_shared<MetadataInfo>(gid, uris[0]); } } void removeOneshotOption(const std::shared_ptr<Option>& option) { option->remove(PREF_PAUSE); option->remove(PREF_GID); } } // namespace aria2
bright-sparks/aria2
src/download_helper.cc
C++
gpl-2.0
18,245
/* * GPL HEADER START * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 only, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License version 2 for more details (a copy is included * in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU General Public License * version 2 along with this program; If not, see * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. * * GPL HEADER END */ /* * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. * Use is subject to license terms. */ /* * This file is part of Lustre, http://www.lustre.org/ * Lustre is a trademark of Sun Microsystems, Inc. */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <liblustre.h> #include <lustre_lib.h> #include <obd.h> int main(int argc, char **argv) { struct obd_ioctl_data data = { 0 }; char rawbuf[8192], parent[4096], *buf = rawbuf, *base, *t; int max = sizeof(rawbuf), fd, offset, rc; if (argc != 2) { printf("usage: %s filename\n", argv[0]); return 1; } base = argv[1]; t = strrchr(base, '/'); if (!t) { strcpy(parent, "."); offset = -1; } else { strncpy(parent, base, t - base); offset = t - base - 1; } fd = open(parent, O_RDONLY); if (fd < 0) { printf("open(%s) error: %s\n", parent, strerror(errno)); exit(errno); } data.ioc_version = OBD_IOCTL_VERSION; data.ioc_len = sizeof(data); if (offset >= 0) data.ioc_inlbuf1 = base + offset + 2; else data.ioc_inlbuf1 = base; data.ioc_inllen1 = strlen(data.ioc_inlbuf1) + 1; if (obd_ioctl_pack(&data, &buf, max)) { printf("ioctl_pack failed.\n"); exit(1); } rc = ioctl(fd, IOC_MDC_LOOKUP, buf); if (rc < 0) { printf("ioctl(%s/%s) error: %s\n", parent, data.ioc_inlbuf1, strerror(errno)); exit(errno); } return 0; }
dmlb2000/lustre-release
lustre/tests/statone.c
C
gpl-2.0
2,595
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * PF_INET protocol family socket handler. * * Version: $Id: af_inet.c,v 1.137 2002/02/01 22:01:03 davem Exp $ * * Authors: Ross Biro * Fred N. van Kempen, <[email protected]> * Florian La Roche, <[email protected]> * Alan Cox, <[email protected]> * * Changes (see also sock.c) * * piggy, * Karl Knutson : Socket protocol table * A.N.Kuznetsov : Socket death error in accept(). * John Richardson : Fix non blocking error in connect() * so sockets that fail to connect * don't return -EINPROGRESS. * Alan Cox : Asynchronous I/O support * Alan Cox : Keep correct socket pointer on sock * structures * when accept() ed * Alan Cox : Semantics of SO_LINGER aren't state * moved to close when you look carefully. * With this fixed and the accept bug fixed * some RPC stuff seems happier. * Niibe Yutaka : 4.4BSD style write async I/O * Alan Cox, * Tony Gale : Fixed reuse semantics. * Alan Cox : bind() shouldn't abort existing but dead * sockets. Stops FTP netin:.. I hope. * Alan Cox : bind() works correctly for RAW sockets. * Note that FreeBSD at least was broken * in this respect so be careful with * compatibility tests... * Alan Cox : routing cache support * Alan Cox : memzero the socket structure for * compactness. * Matt Day : nonblock connect error handler * Alan Cox : Allow large numbers of pending sockets * (eg for big web sites), but only if * specifically application requested. * Alan Cox : New buffering throughout IP. Used * dumbly. * Alan Cox : New buffering now used smartly. * Alan Cox : BSD rather than common sense * interpretation of listen. * Germano Caronni : Assorted small races. * Alan Cox : sendmsg/recvmsg basic support. * Alan Cox : Only sendmsg/recvmsg now supported. * Alan Cox : Locked down bind (see security list). * Alan Cox : Loosened bind a little. * Mike McLagan : ADD/DEL DLCI Ioctls * Willy Konynenberg : Transparent proxying support. * David S. Miller : New socket lookup architecture. * Some other random speedups. * Cyrus Durgin : Cleaned up file for kmod hacks. * Andi Kleen : Fix inet_stream_connect TCP race. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/err.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/in.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/sched.h> #include <linux/timer.h> #include <linux/string.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/capability.h> #include <linux/fcntl.h> #include <linux/mm.h> #include <linux/interrupt.h> #include <linux/stat.h> #include <linux/init.h> #include <linux/poll.h> #include <linux/netfilter_ipv4.h> #include <linux/random.h> #include <asm/uaccess.h> #include <asm/system.h> #include <linux/inet.h> #include <linux/igmp.h> #include <linux/inetdevice.h> #include <linux/netdevice.h> #include <net/ip.h> #include <net/protocol.h> #include <net/arp.h> #include <net/route.h> #include <net/ip_fib.h> #include <net/inet_connection_sock.h> #include <net/tcp.h> #include <net/udp.h> #include <net/udplite.h> #include <linux/skbuff.h> #include <net/sock.h> #include <net/raw.h> #include <net/icmp.h> #include <net/ipip.h> #include <net/inet_common.h> #include <net/xfrm.h> #ifdef CONFIG_IP_MROUTE #include <linux/mroute.h> #endif DEFINE_SNMP_STAT(struct linux_mib, net_statistics) __read_mostly; extern void ip_mc_drop_socket(struct sock *sk); /* The inetsw table contains everything that inet_create needs to * build a new socket. */ static struct list_head inetsw[SOCK_MAX]; static DEFINE_SPINLOCK(inetsw_lock); /* New destruction routine */ void inet_sock_destruct(struct sock *sk) { struct inet_sock *inet = inet_sk(sk); __skb_queue_purge(&sk->sk_receive_queue); __skb_queue_purge(&sk->sk_error_queue); if (sk->sk_type == SOCK_STREAM && sk->sk_state != TCP_CLOSE) { printk("Attempt to release TCP socket in state %d %p\n", sk->sk_state, sk); return; } if (!sock_flag(sk, SOCK_DEAD)) { printk("Attempt to release alive inet socket %p\n", sk); return; } BUG_TRAP(!atomic_read(&sk->sk_rmem_alloc)); BUG_TRAP(!atomic_read(&sk->sk_wmem_alloc)); BUG_TRAP(!sk->sk_wmem_queued); BUG_TRAP(!sk->sk_forward_alloc); kfree(inet->opt); dst_release(sk->sk_dst_cache); sk_refcnt_debug_dec(sk); } /* * The routines beyond this point handle the behaviour of an AF_INET * socket object. Mostly it punts to the subprotocols of IP to do * the work. */ /* * Automatically bind an unbound socket. */ static int inet_autobind(struct sock *sk) { struct inet_sock *inet; /* We may need to bind the socket. */ lock_sock(sk); inet = inet_sk(sk); if (!inet->num) { if (sk->sk_prot->get_port(sk, 0)) { release_sock(sk); return -EAGAIN; } inet->sport = htons(inet->num); } release_sock(sk); return 0; } /* * Move a socket into listening state. */ int inet_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; unsigned char old_state; int err; lock_sock(sk); err = -EINVAL; if (sock->state != SS_UNCONNECTED || sock->type != SOCK_STREAM) goto out; old_state = sk->sk_state; if (!((1 << old_state) & (TCPF_CLOSE | TCPF_LISTEN))) goto out; /* Really, if the socket is already in listen state * we can only allow the backlog to be adjusted. */ if (old_state != TCP_LISTEN) { err = inet_csk_listen_start(sk, backlog); if (err) goto out; } sk->sk_max_ack_backlog = backlog; err = 0; out: release_sock(sk); return err; } u32 inet_ehash_secret __read_mostly; EXPORT_SYMBOL(inet_ehash_secret); /* * inet_ehash_secret must be set exactly once * Instead of using a dedicated spinlock, we (ab)use inetsw_lock */ void build_ehash_secret(void) { u32 rnd; do { get_random_bytes(&rnd, sizeof(rnd)); } while (rnd == 0); spin_lock_bh(&inetsw_lock); if (!inet_ehash_secret) inet_ehash_secret = rnd; spin_unlock_bh(&inetsw_lock); } EXPORT_SYMBOL(build_ehash_secret); /* * Create an inet socket. */ static int inet_create(struct socket *sock, int protocol) { struct sock *sk; struct list_head *p; struct inet_protosw *answer; struct inet_sock *inet; struct proto *answer_prot; unsigned char answer_flags; char answer_no_check; int try_loading_module = 0; int err; if (sock->type != SOCK_RAW && sock->type != SOCK_DGRAM && !inet_ehash_secret) build_ehash_secret(); sock->state = SS_UNCONNECTED; /* Look for the requested type/protocol pair. */ answer = NULL; lookup_protocol: err = -ESOCKTNOSUPPORT; rcu_read_lock(); list_for_each_rcu(p, &inetsw[sock->type]) { answer = list_entry(p, struct inet_protosw, list); /* Check the non-wild match. */ if (protocol == answer->protocol) { if (protocol != IPPROTO_IP) break; } else { /* Check for the two wild cases. */ if (IPPROTO_IP == protocol) { protocol = answer->protocol; break; } if (IPPROTO_IP == answer->protocol) break; } err = -EPROTONOSUPPORT; answer = NULL; } if (unlikely(answer == NULL)) { if (try_loading_module < 2) { rcu_read_unlock(); /* * Be more specific, e.g. net-pf-2-proto-132-type-1 * (net-pf-PF_INET-proto-IPPROTO_SCTP-type-SOCK_STREAM) */ if (++try_loading_module == 1) request_module("net-pf-%d-proto-%d-type-%d", PF_INET, protocol, sock->type); /* * Fall back to generic, e.g. net-pf-2-proto-132 * (net-pf-PF_INET-proto-IPPROTO_SCTP) */ else request_module("net-pf-%d-proto-%d", PF_INET, protocol); goto lookup_protocol; } else goto out_rcu_unlock; } err = -EPERM; if (answer->capability > 0 && !capable(answer->capability)) goto out_rcu_unlock; sock->ops = answer->ops; answer_prot = answer->prot; answer_no_check = answer->no_check; answer_flags = answer->flags; rcu_read_unlock(); BUG_TRAP(answer_prot->slab != NULL); err = -ENOBUFS; sk = sk_alloc(PF_INET, GFP_KERNEL, answer_prot, 1); if (sk == NULL) goto out; err = 0; sk->sk_no_check = answer_no_check; if (INET_PROTOSW_REUSE & answer_flags) sk->sk_reuse = 1; inet = inet_sk(sk); inet->is_icsk = (INET_PROTOSW_ICSK & answer_flags) != 0; if (SOCK_RAW == sock->type) { inet->num = protocol; if (IPPROTO_RAW == protocol) inet->hdrincl = 1; } if (ipv4_config.no_pmtu_disc) inet->pmtudisc = IP_PMTUDISC_DONT; else inet->pmtudisc = IP_PMTUDISC_WANT; inet->id = 0; sock_init_data(sock, sk); sk->sk_destruct = inet_sock_destruct; sk->sk_family = PF_INET; sk->sk_protocol = protocol; sk->sk_backlog_rcv = sk->sk_prot->backlog_rcv; inet->uc_ttl = -1; inet->mc_loop = 1; inet->mc_ttl = 1; inet->mc_index = 0; inet->mc_list = NULL; sk_refcnt_debug_inc(sk); if (inet->num) { /* It assumes that any protocol which allows * the user to assign a number at socket * creation time automatically * shares. */ inet->sport = htons(inet->num); /* Add to protocol hash chains. */ sk->sk_prot->hash(sk); } if (sk->sk_prot->init) { err = sk->sk_prot->init(sk); if (err) sk_common_release(sk); } out: return err; out_rcu_unlock: rcu_read_unlock(); goto out; } /* * The peer socket should always be NULL (or else). When we call this * function we are destroying the object and from then on nobody * should refer to it. */ int inet_release(struct socket *sock) { struct sock *sk = sock->sk; if (sk) { long timeout; /* Applications forget to leave groups before exiting */ ip_mc_drop_socket(sk); /* If linger is set, we don't return until the close * is complete. Otherwise we return immediately. The * actually closing is done the same either way. * * If the close is due to the process exiting, we never * linger.. */ timeout = 0; if (sock_flag(sk, SOCK_LINGER) && !(current->flags & PF_EXITING)) timeout = sk->sk_lingertime; sock->sk = NULL; sk->sk_prot->close(sk, timeout); } return 0; } /* It is off by default, see below. */ int sysctl_ip_nonlocal_bind __read_mostly; int inet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len) { struct sockaddr_in *addr = (struct sockaddr_in *)uaddr; struct sock *sk = sock->sk; struct inet_sock *inet = inet_sk(sk); unsigned short snum; int chk_addr_ret; int err; /* If the socket has its own bind function then use it. (RAW) */ if (sk->sk_prot->bind) { err = sk->sk_prot->bind(sk, uaddr, addr_len); goto out; } err = -EINVAL; if (addr_len < sizeof(struct sockaddr_in)) goto out; chk_addr_ret = inet_addr_type(addr->sin_addr.s_addr); /* Not specified by any standard per-se, however it breaks too * many applications when removed. It is unfortunate since * allowing applications to make a non-local bind solves * several problems with systems using dynamic addressing. * (ie. your servers still start up even if your ISDN link * is temporarily down) */ err = -EADDRNOTAVAIL; if (!sysctl_ip_nonlocal_bind && !inet->freebind && addr->sin_addr.s_addr != INADDR_ANY && chk_addr_ret != RTN_LOCAL && chk_addr_ret != RTN_MULTICAST && chk_addr_ret != RTN_BROADCAST) goto out; snum = ntohs(addr->sin_port); err = -EACCES; if (snum && snum < PROT_SOCK && !capable(CAP_NET_BIND_SERVICE)) goto out; /* We keep a pair of addresses. rcv_saddr is the one * used by hash lookups, and saddr is used for transmit. * * In the BSD API these are the same except where it * would be illegal to use them (multicast/broadcast) in * which case the sending device address is used. */ lock_sock(sk); /* Check these errors (active socket, double bind). */ err = -EINVAL; if (sk->sk_state != TCP_CLOSE || inet->num) goto out_release_sock; inet->rcv_saddr = inet->saddr = addr->sin_addr.s_addr; if (chk_addr_ret == RTN_MULTICAST || chk_addr_ret == RTN_BROADCAST) inet->saddr = 0; /* Use device */ /* Make sure we are allowed to bind here. */ if (sk->sk_prot->get_port(sk, snum)) { inet->saddr = inet->rcv_saddr = 0; err = -EADDRINUSE; goto out_release_sock; } if (inet->rcv_saddr) sk->sk_userlocks |= SOCK_BINDADDR_LOCK; if (snum) sk->sk_userlocks |= SOCK_BINDPORT_LOCK; inet->sport = htons(inet->num); inet->daddr = 0; inet->dport = 0; sk_dst_reset(sk); err = 0; out_release_sock: release_sock(sk); out: return err; } int inet_dgram_connect(struct socket *sock, struct sockaddr * uaddr, int addr_len, int flags) { struct sock *sk = sock->sk; if (uaddr->sa_family == AF_UNSPEC) return sk->sk_prot->disconnect(sk, flags); if (!inet_sk(sk)->num && inet_autobind(sk)) return -EAGAIN; return sk->sk_prot->connect(sk, (struct sockaddr *)uaddr, addr_len); } static long inet_wait_for_connect(struct sock *sk, long timeo) { DEFINE_WAIT(wait); prepare_to_wait(sk->sk_sleep, &wait, TASK_INTERRUPTIBLE); /* Basic assumption: if someone sets sk->sk_err, he _must_ * change state of the socket from TCP_SYN_*. * Connect() does not allow to get error notifications * without closing the socket. */ while ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) { release_sock(sk); timeo = schedule_timeout(timeo); lock_sock(sk); if (signal_pending(current) || !timeo) break; prepare_to_wait(sk->sk_sleep, &wait, TASK_INTERRUPTIBLE); } finish_wait(sk->sk_sleep, &wait); return timeo; } /* * Connect to a remote host. There is regrettably still a little * TCP 'magic' in here. */ int inet_stream_connect(struct socket *sock, struct sockaddr *uaddr, int addr_len, int flags) { struct sock *sk = sock->sk; int err; long timeo; lock_sock(sk); if (uaddr->sa_family == AF_UNSPEC) { err = sk->sk_prot->disconnect(sk, flags); sock->state = err ? SS_DISCONNECTING : SS_UNCONNECTED; goto out; } switch (sock->state) { default: err = -EINVAL; goto out; case SS_CONNECTED: err = -EISCONN; goto out; case SS_CONNECTING: err = -EALREADY; /* Fall out of switch with err, set for this state */ break; case SS_UNCONNECTED: err = -EISCONN; if (sk->sk_state != TCP_CLOSE) goto out; err = sk->sk_prot->connect(sk, uaddr, addr_len); if (err < 0) goto out; sock->state = SS_CONNECTING; /* Just entered SS_CONNECTING state; the only * difference is that return value in non-blocking * case is EINPROGRESS, rather than EALREADY. */ err = -EINPROGRESS; break; } timeo = sock_sndtimeo(sk, flags & O_NONBLOCK); if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) { /* Error code is set above */ if (!timeo || !inet_wait_for_connect(sk, timeo)) goto out; err = sock_intr_errno(timeo); if (signal_pending(current)) goto out; } /* Connection was closed by RST, timeout, ICMP error * or another process disconnected us. */ if (sk->sk_state == TCP_CLOSE) goto sock_error; /* sk->sk_err may be not zero now, if RECVERR was ordered by user * and error was received after socket entered established state. * Hence, it is handled normally after connect() return successfully. */ sock->state = SS_CONNECTED; err = 0; out: release_sock(sk); return err; sock_error: err = sock_error(sk) ? : -ECONNABORTED; sock->state = SS_UNCONNECTED; if (sk->sk_prot->disconnect(sk, flags)) sock->state = SS_DISCONNECTING; goto out; } /* * Accept a pending connection. The TCP layer now gives BSD semantics. */ int inet_accept(struct socket *sock, struct socket *newsock, int flags) { struct sock *sk1 = sock->sk; int err = -EINVAL; struct sock *sk2 = sk1->sk_prot->accept(sk1, flags, &err); if (!sk2) goto do_err; lock_sock(sk2); BUG_TRAP((1 << sk2->sk_state) & (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_CLOSE)); sock_graft(sk2, newsock); newsock->state = SS_CONNECTED; err = 0; release_sock(sk2); do_err: return err; } /* * This does both peername and sockname. */ int inet_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sock *sk = sock->sk; struct inet_sock *inet = inet_sk(sk); struct sockaddr_in *sin = (struct sockaddr_in *)uaddr; sin->sin_family = AF_INET; if (peer) { if (!inet->dport || (((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_SYN_SENT)) && peer == 1)) return -ENOTCONN; sin->sin_port = inet->dport; sin->sin_addr.s_addr = inet->daddr; } else { __be32 addr = inet->rcv_saddr; if (!addr) addr = inet->saddr; sin->sin_port = inet->sport; sin->sin_addr.s_addr = addr; } memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); *uaddr_len = sizeof(*sin); return 0; } int inet_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size) { struct sock *sk = sock->sk; /* We may need to bind the socket. */ if (!inet_sk(sk)->num && inet_autobind(sk)) return -EAGAIN; return sk->sk_prot->sendmsg(iocb, sk, msg, size); } static ssize_t inet_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags) { struct sock *sk = sock->sk; /* We may need to bind the socket. */ if (!inet_sk(sk)->num && inet_autobind(sk)) return -EAGAIN; if (sk->sk_prot->sendpage) return sk->sk_prot->sendpage(sk, page, offset, size, flags); return sock_no_sendpage(sock, page, offset, size, flags); } int inet_shutdown(struct socket *sock, int how) { struct sock *sk = sock->sk; int err = 0; /* This should really check to make sure * the socket is a TCP socket. (WHY AC...) */ how++; /* maps 0->1 has the advantage of making bit 1 rcvs and 1->2 bit 2 snds. 2->3 */ if ((how & ~SHUTDOWN_MASK) || !how) /* MAXINT->0 */ return -EINVAL; lock_sock(sk); if (sock->state == SS_CONNECTING) { if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV | TCPF_CLOSE)) sock->state = SS_DISCONNECTING; else sock->state = SS_CONNECTED; } switch (sk->sk_state) { case TCP_CLOSE: err = -ENOTCONN; /* Hack to wake up other listeners, who can poll for POLLHUP, even on eg. unconnected UDP sockets -- RR */ default: sk->sk_shutdown |= how; if (sk->sk_prot->shutdown) sk->sk_prot->shutdown(sk, how); break; /* Remaining two branches are temporary solution for missing * close() in multithreaded environment. It is _not_ a good idea, * but we have no choice until close() is repaired at VFS level. */ case TCP_LISTEN: if (!(how & RCV_SHUTDOWN)) break; /* Fall through */ case TCP_SYN_SENT: err = sk->sk_prot->disconnect(sk, O_NONBLOCK); sock->state = err ? SS_DISCONNECTING : SS_UNCONNECTED; break; } /* Wake up anyone sleeping in poll. */ sk->sk_state_change(sk); release_sock(sk); return err; } /* * ioctl() calls you can issue on an INET socket. Most of these are * device configuration and stuff and very rarely used. Some ioctls * pass on to the socket itself. * * NOTE: I like the idea of a module for the config stuff. ie ifconfig * loads the devconfigure module does its configuring and unloads it. * There's a good 20K of config code hanging around the kernel. */ int inet_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { struct sock *sk = sock->sk; int err = 0; switch (cmd) { case SIOCGSTAMP: err = sock_get_timestamp(sk, (struct timeval __user *)arg); break; case SIOCGSTAMPNS: err = sock_get_timestampns(sk, (struct timespec __user *)arg); break; case SIOCADDRT: case SIOCDELRT: case SIOCRTMSG: err = ip_rt_ioctl(cmd, (void __user *)arg); break; case SIOCDARP: case SIOCGARP: case SIOCSARP: err = arp_ioctl(cmd, (void __user *)arg); break; case SIOCGIFADDR: case SIOCSIFADDR: case SIOCGIFBRDADDR: case SIOCSIFBRDADDR: case SIOCGIFNETMASK: case SIOCSIFNETMASK: case SIOCGIFDSTADDR: case SIOCSIFDSTADDR: case SIOCSIFPFLAGS: case SIOCGIFPFLAGS: case SIOCSIFFLAGS: err = devinet_ioctl(cmd, (void __user *)arg); break; default: if (sk->sk_prot->ioctl) err = sk->sk_prot->ioctl(sk, cmd, arg); else err = -ENOIOCTLCMD; break; } return err; } const struct proto_ops inet_stream_ops = { .family = PF_INET, .owner = THIS_MODULE, .release = inet_release, .bind = inet_bind, .connect = inet_stream_connect, .socketpair = sock_no_socketpair, .accept = inet_accept, .getname = inet_getname, .poll = tcp_poll, .ioctl = inet_ioctl, .listen = inet_listen, .shutdown = inet_shutdown, .setsockopt = sock_common_setsockopt, .getsockopt = sock_common_getsockopt, .sendmsg = tcp_sendmsg, .recvmsg = sock_common_recvmsg, .mmap = sock_no_mmap, .sendpage = tcp_sendpage, #ifdef CONFIG_COMPAT .compat_setsockopt = compat_sock_common_setsockopt, .compat_getsockopt = compat_sock_common_getsockopt, #endif }; const struct proto_ops inet_dgram_ops = { .family = PF_INET, .owner = THIS_MODULE, .release = inet_release, .bind = inet_bind, .connect = inet_dgram_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = inet_getname, .poll = udp_poll, .ioctl = inet_ioctl, .listen = sock_no_listen, .shutdown = inet_shutdown, .setsockopt = sock_common_setsockopt, .getsockopt = sock_common_getsockopt, .sendmsg = inet_sendmsg, .recvmsg = sock_common_recvmsg, .mmap = sock_no_mmap, .sendpage = inet_sendpage, #ifdef CONFIG_COMPAT .compat_setsockopt = compat_sock_common_setsockopt, .compat_getsockopt = compat_sock_common_getsockopt, #endif }; /* * For SOCK_RAW sockets; should be the same as inet_dgram_ops but without * udp_poll */ static const struct proto_ops inet_sockraw_ops = { .family = PF_INET, .owner = THIS_MODULE, .release = inet_release, .bind = inet_bind, .connect = inet_dgram_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = inet_getname, .poll = datagram_poll, .ioctl = inet_ioctl, .listen = sock_no_listen, .shutdown = inet_shutdown, .setsockopt = sock_common_setsockopt, .getsockopt = sock_common_getsockopt, .sendmsg = inet_sendmsg, .recvmsg = sock_common_recvmsg, .mmap = sock_no_mmap, .sendpage = inet_sendpage, #ifdef CONFIG_COMPAT .compat_setsockopt = compat_sock_common_setsockopt, .compat_getsockopt = compat_sock_common_getsockopt, #endif }; static struct net_proto_family inet_family_ops = { .family = PF_INET, .create = inet_create, .owner = THIS_MODULE, }; /* Upon startup we insert all the elements in inetsw_array[] into * the linked list inetsw. */ static struct inet_protosw inetsw_array[] = { { .type = SOCK_STREAM, .protocol = IPPROTO_TCP, .prot = &tcp_prot, .ops = &inet_stream_ops, .capability = -1, .no_check = 0, .flags = INET_PROTOSW_PERMANENT | INET_PROTOSW_ICSK, }, { .type = SOCK_DGRAM, .protocol = IPPROTO_UDP, .prot = &udp_prot, .ops = &inet_dgram_ops, .capability = -1, .no_check = UDP_CSUM_DEFAULT, .flags = INET_PROTOSW_PERMANENT, }, { .type = SOCK_RAW, .protocol = IPPROTO_IP, /* wild card */ .prot = &raw_prot, .ops = &inet_sockraw_ops, .capability = CAP_NET_RAW, .no_check = UDP_CSUM_DEFAULT, .flags = INET_PROTOSW_REUSE, } }; #define INETSW_ARRAY_LEN (sizeof(inetsw_array) / sizeof(struct inet_protosw)) void inet_register_protosw(struct inet_protosw *p) { struct list_head *lh; struct inet_protosw *answer; int protocol = p->protocol; struct list_head *last_perm; spin_lock_bh(&inetsw_lock); if (p->type >= SOCK_MAX) goto out_illegal; /* If we are trying to override a permanent protocol, bail. */ answer = NULL; last_perm = &inetsw[p->type]; list_for_each(lh, &inetsw[p->type]) { answer = list_entry(lh, struct inet_protosw, list); /* Check only the non-wild match. */ if (INET_PROTOSW_PERMANENT & answer->flags) { if (protocol == answer->protocol) break; last_perm = lh; } answer = NULL; } if (answer) goto out_permanent; /* Add the new entry after the last permanent entry if any, so that * the new entry does not override a permanent entry when matched with * a wild-card protocol. But it is allowed to override any existing * non-permanent entry. This means that when we remove this entry, the * system automatically returns to the old behavior. */ list_add_rcu(&p->list, last_perm); out: spin_unlock_bh(&inetsw_lock); synchronize_net(); return; out_permanent: printk(KERN_ERR "Attempt to override permanent protocol %d.\n", protocol); goto out; out_illegal: printk(KERN_ERR "Ignoring attempt to register invalid socket type %d.\n", p->type); goto out; } void inet_unregister_protosw(struct inet_protosw *p) { if (INET_PROTOSW_PERMANENT & p->flags) { printk(KERN_ERR "Attempt to unregister permanent protocol %d.\n", p->protocol); } else { spin_lock_bh(&inetsw_lock); list_del_rcu(&p->list); spin_unlock_bh(&inetsw_lock); synchronize_net(); } } /* * Shall we try to damage output packets if routing dev changes? */ int sysctl_ip_dynaddr __read_mostly; static int inet_sk_reselect_saddr(struct sock *sk) { struct inet_sock *inet = inet_sk(sk); int err; struct rtable *rt; __be32 old_saddr = inet->saddr; __be32 new_saddr; __be32 daddr = inet->daddr; if (inet->opt && inet->opt->srr) daddr = inet->opt->faddr; /* Query new route. */ err = ip_route_connect(&rt, daddr, 0, RT_CONN_FLAGS(sk), sk->sk_bound_dev_if, sk->sk_protocol, inet->sport, inet->dport, sk, 0); if (err) return err; sk_setup_caps(sk, &rt->u.dst); new_saddr = rt->rt_src; if (new_saddr == old_saddr) return 0; if (sysctl_ip_dynaddr > 1) { printk(KERN_INFO "%s(): shifting inet->" "saddr from %d.%d.%d.%d to %d.%d.%d.%d\n", __FUNCTION__, NIPQUAD(old_saddr), NIPQUAD(new_saddr)); } inet->saddr = inet->rcv_saddr = new_saddr; /* * XXX The only one ugly spot where we need to * XXX really change the sockets identity after * XXX it has entered the hashes. -DaveM * * Besides that, it does not check for connection * uniqueness. Wait for troubles. */ __sk_prot_rehash(sk); return 0; } int inet_sk_rebuild_header(struct sock *sk) { struct inet_sock *inet = inet_sk(sk); struct rtable *rt = (struct rtable *)__sk_dst_check(sk, 0); __be32 daddr; int err; /* Route is OK, nothing to do. */ if (rt) return 0; /* Reroute. */ daddr = inet->daddr; if (inet->opt && inet->opt->srr) daddr = inet->opt->faddr; { struct flowi fl = { .oif = sk->sk_bound_dev_if, .nl_u = { .ip4_u = { .daddr = daddr, .saddr = inet->saddr, .tos = RT_CONN_FLAGS(sk), }, }, .proto = sk->sk_protocol, .uli_u = { .ports = { .sport = inet->sport, .dport = inet->dport, }, }, }; security_sk_classify_flow(sk, &fl); err = ip_route_output_flow(&rt, &fl, sk, 0); } if (!err) sk_setup_caps(sk, &rt->u.dst); else { /* Routing failed... */ sk->sk_route_caps = 0; /* * Other protocols have to map its equivalent state to TCP_SYN_SENT. * DCCP maps its DCCP_REQUESTING state to TCP_SYN_SENT. -acme */ if (!sysctl_ip_dynaddr || sk->sk_state != TCP_SYN_SENT || (sk->sk_userlocks & SOCK_BINDADDR_LOCK) || (err = inet_sk_reselect_saddr(sk)) != 0) sk->sk_err_soft = -err; } return err; } EXPORT_SYMBOL(inet_sk_rebuild_header); static int inet_gso_send_check(struct sk_buff *skb) { struct iphdr *iph; struct net_protocol *ops; int proto; int ihl; int err = -EINVAL; if (unlikely(!pskb_may_pull(skb, sizeof(*iph)))) goto out; iph = ip_hdr(skb); ihl = iph->ihl * 4; if (ihl < sizeof(*iph)) goto out; if (unlikely(!pskb_may_pull(skb, ihl))) goto out; __skb_pull(skb, ihl); skb_reset_transport_header(skb); iph = ip_hdr(skb); proto = iph->protocol & (MAX_INET_PROTOS - 1); err = -EPROTONOSUPPORT; rcu_read_lock(); ops = rcu_dereference(inet_protos[proto]); if (likely(ops && ops->gso_send_check)) err = ops->gso_send_check(skb); rcu_read_unlock(); out: return err; } static struct sk_buff *inet_gso_segment(struct sk_buff *skb, int features) { struct sk_buff *segs = ERR_PTR(-EINVAL); struct iphdr *iph; struct net_protocol *ops; int proto; int ihl; int id; if (!(features & NETIF_F_V4_CSUM)) features &= ~NETIF_F_SG; if (unlikely(skb_shinfo(skb)->gso_type & ~(SKB_GSO_TCPV4 | SKB_GSO_UDP | SKB_GSO_DODGY | SKB_GSO_TCP_ECN | 0))) goto out; if (unlikely(!pskb_may_pull(skb, sizeof(*iph)))) goto out; iph = ip_hdr(skb); ihl = iph->ihl * 4; if (ihl < sizeof(*iph)) goto out; if (unlikely(!pskb_may_pull(skb, ihl))) goto out; __skb_pull(skb, ihl); skb_reset_transport_header(skb); iph = ip_hdr(skb); id = ntohs(iph->id); proto = iph->protocol & (MAX_INET_PROTOS - 1); segs = ERR_PTR(-EPROTONOSUPPORT); rcu_read_lock(); ops = rcu_dereference(inet_protos[proto]); if (likely(ops && ops->gso_segment)) segs = ops->gso_segment(skb, features); rcu_read_unlock(); if (!segs || unlikely(IS_ERR(segs))) goto out; skb = segs; do { iph = ip_hdr(skb); iph->id = htons(id++); iph->tot_len = htons(skb->len - skb->mac_len); iph->check = 0; iph->check = ip_fast_csum(skb_network_header(skb), iph->ihl); } while ((skb = skb->next)); out: return segs; } unsigned long snmp_fold_field(void *mib[], int offt) { unsigned long res = 0; int i; for_each_possible_cpu(i) { res += *(((unsigned long *) per_cpu_ptr(mib[0], i)) + offt); res += *(((unsigned long *) per_cpu_ptr(mib[1], i)) + offt); } return res; } EXPORT_SYMBOL_GPL(snmp_fold_field); int snmp_mib_init(void *ptr[2], size_t mibsize, size_t mibalign) { BUG_ON(ptr == NULL); ptr[0] = __alloc_percpu(mibsize); if (!ptr[0]) goto err0; ptr[1] = __alloc_percpu(mibsize); if (!ptr[1]) goto err1; return 0; err1: free_percpu(ptr[0]); ptr[0] = NULL; err0: return -ENOMEM; } EXPORT_SYMBOL_GPL(snmp_mib_init); void snmp_mib_free(void *ptr[2]) { BUG_ON(ptr == NULL); free_percpu(ptr[0]); free_percpu(ptr[1]); ptr[0] = ptr[1] = NULL; } EXPORT_SYMBOL_GPL(snmp_mib_free); #ifdef CONFIG_IP_MULTICAST static struct net_protocol igmp_protocol = { .handler = igmp_rcv, }; #endif static struct net_protocol tcp_protocol = { .handler = tcp_v4_rcv, .err_handler = tcp_v4_err, .gso_send_check = tcp_v4_gso_send_check, .gso_segment = tcp_tso_segment, .no_policy = 1, }; static struct net_protocol udp_protocol = { .handler = udp_rcv, .err_handler = udp_err, .no_policy = 1, }; static struct net_protocol icmp_protocol = { .handler = icmp_rcv, }; static int __init init_ipv4_mibs(void) { if (snmp_mib_init((void **)net_statistics, sizeof(struct linux_mib), __alignof__(struct linux_mib)) < 0) goto err_net_mib; if (snmp_mib_init((void **)ip_statistics, sizeof(struct ipstats_mib), __alignof__(struct ipstats_mib)) < 0) goto err_ip_mib; if (snmp_mib_init((void **)icmp_statistics, sizeof(struct icmp_mib), __alignof__(struct icmp_mib)) < 0) goto err_icmp_mib; if (snmp_mib_init((void **)tcp_statistics, sizeof(struct tcp_mib), __alignof__(struct tcp_mib)) < 0) goto err_tcp_mib; if (snmp_mib_init((void **)udp_statistics, sizeof(struct udp_mib), __alignof__(struct udp_mib)) < 0) goto err_udp_mib; if (snmp_mib_init((void **)udplite_statistics, sizeof(struct udp_mib), __alignof__(struct udp_mib)) < 0) goto err_udplite_mib; tcp_mib_init(); return 0; err_udplite_mib: snmp_mib_free((void **)udp_statistics); err_udp_mib: snmp_mib_free((void **)tcp_statistics); err_tcp_mib: snmp_mib_free((void **)icmp_statistics); err_icmp_mib: snmp_mib_free((void **)ip_statistics); err_ip_mib: snmp_mib_free((void **)net_statistics); err_net_mib: return -ENOMEM; } static int ipv4_proc_init(void); /* * IP protocol layer initialiser */ static struct packet_type ip_packet_type = { .type = __constant_htons(ETH_P_IP), .func = ip_rcv, .gso_send_check = inet_gso_send_check, .gso_segment = inet_gso_segment, }; static int __init inet_init(void) { struct sk_buff *dummy_skb; struct inet_protosw *q; struct list_head *r; int rc = -EINVAL; BUILD_BUG_ON(sizeof(struct inet_skb_parm) > sizeof(dummy_skb->cb)); rc = proto_register(&tcp_prot, 1); if (rc) goto out; rc = proto_register(&udp_prot, 1); if (rc) goto out_unregister_tcp_proto; rc = proto_register(&raw_prot, 1); if (rc) goto out_unregister_udp_proto; /* * Tell SOCKET that we are alive... */ (void)sock_register(&inet_family_ops); /* * Add all the base protocols. */ if (inet_add_protocol(&icmp_protocol, IPPROTO_ICMP) < 0) printk(KERN_CRIT "inet_init: Cannot add ICMP protocol\n"); if (inet_add_protocol(&udp_protocol, IPPROTO_UDP) < 0) printk(KERN_CRIT "inet_init: Cannot add UDP protocol\n"); if (inet_add_protocol(&tcp_protocol, IPPROTO_TCP) < 0) printk(KERN_CRIT "inet_init: Cannot add TCP protocol\n"); #ifdef CONFIG_IP_MULTICAST if (inet_add_protocol(&igmp_protocol, IPPROTO_IGMP) < 0) printk(KERN_CRIT "inet_init: Cannot add IGMP protocol\n"); #endif /* Register the socket-side information for inet_create. */ for (r = &inetsw[0]; r < &inetsw[SOCK_MAX]; ++r) INIT_LIST_HEAD(r); for (q = inetsw_array; q < &inetsw_array[INETSW_ARRAY_LEN]; ++q) inet_register_protosw(q); /* * Set the ARP module up */ arp_init(); /* * Set the IP module up */ ip_init(); tcp_v4_init(&inet_family_ops); /* Setup TCP slab cache for open requests. */ tcp_init(); /* Add UDP-Lite (RFC 3828) */ udplite4_register(); /* * Set the ICMP layer up */ icmp_init(&inet_family_ops); /* * Initialise the multicast router */ #if defined(CONFIG_IP_MROUTE) ip_mr_init(); #endif /* * Initialise per-cpu ipv4 mibs */ if (init_ipv4_mibs()) printk(KERN_CRIT "inet_init: Cannot init ipv4 mibs\n"); ; ipv4_proc_init(); ipfrag_init(); dev_add_pack(&ip_packet_type); rc = 0; out: return rc; out_unregister_udp_proto: proto_unregister(&udp_prot); out_unregister_tcp_proto: proto_unregister(&tcp_prot); goto out; } fs_initcall(inet_init); /* ------------------------------------------------------------------------ */ #ifdef CONFIG_PROC_FS static int __init ipv4_proc_init(void) { int rc = 0; if (raw_proc_init()) goto out_raw; if (tcp4_proc_init()) goto out_tcp; if (udp4_proc_init()) goto out_udp; if (fib_proc_init()) goto out_fib; if (ip_misc_proc_init()) goto out_misc; out: return rc; out_misc: fib_proc_exit(); out_fib: udp4_proc_exit(); out_udp: tcp4_proc_exit(); out_tcp: raw_proc_exit(); out_raw: rc = -ENOMEM; goto out; } #else /* CONFIG_PROC_FS */ static int __init ipv4_proc_init(void) { return 0; } #endif /* CONFIG_PROC_FS */ MODULE_ALIAS_NETPROTO(PF_INET); EXPORT_SYMBOL(inet_accept); EXPORT_SYMBOL(inet_bind); EXPORT_SYMBOL(inet_dgram_connect); EXPORT_SYMBOL(inet_dgram_ops); EXPORT_SYMBOL(inet_getname); EXPORT_SYMBOL(inet_ioctl); EXPORT_SYMBOL(inet_listen); EXPORT_SYMBOL(inet_register_protosw); EXPORT_SYMBOL(inet_release); EXPORT_SYMBOL(inet_sendmsg); EXPORT_SYMBOL(inet_shutdown); EXPORT_SYMBOL(inet_sock_destruct); EXPORT_SYMBOL(inet_stream_connect); EXPORT_SYMBOL(inet_stream_ops); EXPORT_SYMBOL(inet_unregister_protosw); EXPORT_SYMBOL(net_statistics); EXPORT_SYMBOL(sysctl_ip_nonlocal_bind);
tmatsuya/milkymist-linux
net/ipv4/af_inet.c
C
gpl-2.0
35,856
#include <linux/regulator/machine.h> #include <linux/regulator/act8846.h> #include <mach/sram.h> #include <linux/platform_device.h> #include <mach/gpio.h> #include <mach/iomux.h> #include <mach/board.h> #ifdef CONFIG_REGULATOR_ACT8846 static int act8846_set_init(struct act8846 *act8846) { struct regulator *dcdc; struct regulator *ldo; int i = 0; printk("%s,line=%d\n", __func__,__LINE__); #ifndef CONFIG_RK_CONFIG g_pmic_type = PMIC_TYPE_ACT8846; #endif printk("%s:g_pmic_type=%d\n",__func__,g_pmic_type); for(i = 0; i < ARRAY_SIZE(act8846_dcdc_info); i++) { if(act8846_dcdc_info[i].min_uv == 0 && act8846_dcdc_info[i].max_uv == 0) continue; dcdc =regulator_get(NULL, act8846_dcdc_info[i].name); regulator_set_voltage(dcdc, act8846_dcdc_info[i].min_uv, act8846_dcdc_info[i].max_uv); regulator_set_suspend_voltage(dcdc, act8846_dcdc_info[i].suspend_vol); regulator_enable(dcdc); printk("%s %s =%dmV end\n", __func__,act8846_dcdc_info[i].name, regulator_get_voltage(dcdc)); regulator_put(dcdc); udelay(100); } for(i = 0; i < ARRAY_SIZE(act8846_ldo_info); i++) { if(act8846_ldo_info[i].min_uv == 0 && act8846_ldo_info[i].max_uv == 0) continue; ldo =regulator_get(NULL, act8846_ldo_info[i].name); regulator_set_voltage(ldo, act8846_ldo_info[i].min_uv, act8846_ldo_info[i].max_uv); regulator_enable(ldo); printk("%s %s =%dmV end\n", __func__,act8846_ldo_info[i].name, regulator_get_voltage(ldo)); regulator_put(ldo); } #ifdef CONFIG_RK_CONFIG if(sram_gpio_init(get_port_config(pmic_slp).gpio, &pmic_sleep) < 0){ printk(KERN_ERR "sram_gpio_init failed\n"); return -EINVAL; } if(port_output_init(pmic_slp, 0, "pmic_slp") < 0){ printk(KERN_ERR "port_output_init failed\n"); return -EINVAL; } #else if(sram_gpio_init(PMU_POWER_SLEEP, &pmic_sleep) < 0){ printk(KERN_ERR "sram_gpio_init failed\n"); return -EINVAL; } gpio_request(PMU_POWER_SLEEP, "NULL"); gpio_direction_output(PMU_POWER_SLEEP, GPIO_LOW); #ifdef CONFIG_ACT8846_SUPPORT_RESET if(sram_gpio_init(PMU_VSEL, &pmic_vsel) < 0){ printk(KERN_ERR "sram_gpio_init failed\n"); return -EINVAL; } // rk30_mux_api_set(GPIO3D3_PWM0_NAME,GPIO3D_GPIO3D3); gpio_request(PMU_VSEL, "NULL"); gpio_direction_output(PMU_VSEL, GPIO_HIGH); #endif #endif printk("%s,line=%d END\n", __func__,__LINE__); return 0; } static struct regulator_consumer_supply act8846_buck1_supply[] = { { .supply = "act_dcdc1", }, }; static struct regulator_consumer_supply act8846_buck2_supply[] = { { .supply = "act_dcdc2", }, { .supply = "vdd_core", }, }; static struct regulator_consumer_supply act8846_buck3_supply[] = { { .supply = "act_dcdc3", }, { .supply = "vdd_cpu", }, }; static struct regulator_consumer_supply act8846_buck4_supply[] = { { .supply = "act_dcdc4", }, }; static struct regulator_consumer_supply act8846_ldo1_supply[] = { { .supply = "act_ldo1", }, }; static struct regulator_consumer_supply act8846_ldo2_supply[] = { { .supply = "act_ldo2", }, }; static struct regulator_consumer_supply act8846_ldo3_supply[] = { { .supply = "act_ldo3", }, }; static struct regulator_consumer_supply act8846_ldo4_supply[] = { { .supply = "act_ldo4", }, }; static struct regulator_consumer_supply act8846_ldo5_supply[] = { { .supply = "act_ldo5", }, }; static struct regulator_consumer_supply act8846_ldo6_supply[] = { { .supply = "act_ldo6", }, }; static struct regulator_consumer_supply act8846_ldo7_supply[] = { { .supply = "act_ldo7", }, }; static struct regulator_consumer_supply act8846_ldo8_supply[] = { { .supply = "act_ldo8", }, }; static struct regulator_consumer_supply act8846_ldo9_supply[] = { { .supply = "act_ldo9", }, }; static struct regulator_init_data act8846_buck1 = { .constraints = { .name = "ACT_DCDC1", .min_uV = 600000, .max_uV = 3900000, .apply_uV = 1, .always_on = 1, .valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE, .valid_modes_mask = REGULATOR_MODE_STANDBY | REGULATOR_MODE_NORMAL, }, .num_consumer_supplies = ARRAY_SIZE(act8846_buck1_supply), .consumer_supplies = act8846_buck1_supply, }; /* */ static struct regulator_init_data act8846_buck2 = { .constraints = { .name = "ACT_DCDC2", .min_uV = 600000, .max_uV = 3900000, .apply_uV = 1, .always_on = 1, .valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE, .valid_modes_mask = REGULATOR_MODE_STANDBY | REGULATOR_MODE_NORMAL, }, .num_consumer_supplies = ARRAY_SIZE(act8846_buck2_supply), .consumer_supplies = act8846_buck2_supply, }; /* */ static struct regulator_init_data act8846_buck3 = { .constraints = { .name = "ACT_DCDC3", .min_uV = 600000, .max_uV = 3900000, .apply_uV = 1, .always_on = 1, .valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE, .valid_modes_mask = REGULATOR_MODE_STANDBY | REGULATOR_MODE_NORMAL, }, .num_consumer_supplies = ARRAY_SIZE(act8846_buck3_supply), .consumer_supplies = act8846_buck3_supply, }; static struct regulator_init_data act8846_buck4 = { .constraints = { .name = "ACT_DCDC4", .min_uV = 600000, .max_uV = 3900000, .apply_uV = 1, .always_on = 1, .valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE, .valid_modes_mask = REGULATOR_MODE_STANDBY | REGULATOR_MODE_NORMAL, }, .num_consumer_supplies = ARRAY_SIZE(act8846_buck4_supply), .consumer_supplies = act8846_buck4_supply, }; static struct regulator_init_data act8846_ldo1 = { .constraints = { .name = "ACT_LDO1", .min_uV = 600000, .max_uV = 3900000, .apply_uV = 1, .valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE, .valid_modes_mask = REGULATOR_MODE_STANDBY | REGULATOR_MODE_NORMAL, }, .num_consumer_supplies = ARRAY_SIZE(act8846_ldo1_supply), .consumer_supplies = act8846_ldo1_supply, }; /* */ static struct regulator_init_data act8846_ldo2 = { .constraints = { .name = "ACT_LDO2", .min_uV = 600000, .max_uV = 3900000, .apply_uV = 1, .valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE, .valid_modes_mask = REGULATOR_MODE_STANDBY | REGULATOR_MODE_NORMAL, }, .num_consumer_supplies = ARRAY_SIZE(act8846_ldo2_supply), .consumer_supplies = act8846_ldo2_supply, }; /* */ static struct regulator_init_data act8846_ldo3 = { .constraints = { .name = "ACT_LDO3", .min_uV = 600000, .max_uV = 3900000, .apply_uV = 1, .valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE, .valid_modes_mask = REGULATOR_MODE_STANDBY | REGULATOR_MODE_NORMAL, }, .num_consumer_supplies = ARRAY_SIZE(act8846_ldo3_supply), .consumer_supplies = act8846_ldo3_supply, }; /* */ static struct regulator_init_data act8846_ldo4 = { .constraints = { .name = "ACT_LDO4", .min_uV = 600000, .max_uV = 3900000, .apply_uV = 1, .valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE, .valid_modes_mask = REGULATOR_MODE_STANDBY | REGULATOR_MODE_NORMAL, }, .num_consumer_supplies = ARRAY_SIZE(act8846_ldo4_supply), .consumer_supplies = act8846_ldo4_supply, }; static struct regulator_init_data act8846_ldo5 = { .constraints = { .name = "ACT_LDO5", .min_uV = 600000, .max_uV = 3900000, .apply_uV = 1, .valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE, .valid_modes_mask = REGULATOR_MODE_STANDBY | REGULATOR_MODE_NORMAL, }, .num_consumer_supplies = ARRAY_SIZE(act8846_ldo5_supply), .consumer_supplies = act8846_ldo5_supply, }; static struct regulator_init_data act8846_ldo6 = { .constraints = { .name = "ACT_LDO6", .min_uV = 600000, .max_uV = 3900000, .apply_uV = 1, .valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE, .valid_modes_mask = REGULATOR_MODE_STANDBY | REGULATOR_MODE_NORMAL, }, .num_consumer_supplies = ARRAY_SIZE(act8846_ldo6_supply), .consumer_supplies = act8846_ldo6_supply, }; static struct regulator_init_data act8846_ldo7 = { .constraints = { .name = "ACT_LDO7", .min_uV = 600000, .max_uV = 3900000, .apply_uV = 1, .valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE, .valid_modes_mask = REGULATOR_MODE_STANDBY | REGULATOR_MODE_NORMAL, }, .num_consumer_supplies = ARRAY_SIZE(act8846_ldo7_supply), .consumer_supplies = act8846_ldo7_supply, }; static struct regulator_init_data act8846_ldo8 = { .constraints = { .name = "ACT_LDO8", .min_uV = 600000, .max_uV = 3900000, .apply_uV = 1, .valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE, .valid_modes_mask = REGULATOR_MODE_STANDBY | REGULATOR_MODE_NORMAL, }, .num_consumer_supplies = ARRAY_SIZE(act8846_ldo8_supply), .consumer_supplies = act8846_ldo8_supply, }; static struct regulator_init_data act8846_ldo9 = { .constraints = { .name = "ACT_LDO9", .min_uV = 600000, .max_uV = 3900000, .apply_uV = 1, .valid_ops_mask = REGULATOR_CHANGE_STATUS | REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_MODE, .valid_modes_mask = REGULATOR_MODE_STANDBY | REGULATOR_MODE_NORMAL, }, .num_consumer_supplies = ARRAY_SIZE(act8846_ldo9_supply), .consumer_supplies = act8846_ldo9_supply, }; struct act8846_regulator_subdev act8846_regulator_subdev_id[] = { { .id=0, .initdata=&act8846_buck1, }, { .id=1, .initdata=&act8846_buck2, }, { .id=2, .initdata=&act8846_buck3, }, { .id=3, .initdata=&act8846_buck4, }, { .id=4, .initdata=&act8846_ldo1, }, { .id=5, .initdata=&act8846_ldo2, }, { .id=6, .initdata=&act8846_ldo3, }, { .id=7, .initdata=&act8846_ldo4, }, { .id=8, .initdata=&act8846_ldo5, }, { .id=9, .initdata=&act8846_ldo6, }, { .id=10, .initdata=&act8846_ldo7, }, { .id=11, .initdata=&act8846_ldo8, }, #if 1 { .id=12, .initdata=&act8846_ldo9, }, #endif }; static struct act8846_platform_data act8846_data={ .set_init=act8846_set_init, .num_regulators=13, .regulators=act8846_regulator_subdev_id, }; #ifdef CONFIG_HAS_EARLYSUSPEND void act8846_early_suspend(struct early_suspend *h) { } void act8846_late_resume(struct early_suspend *h) { } #endif #ifdef CONFIG_PM int __sramdata vdd_cpu_vol ,vdd_core_vol; void act8846_device_suspend(void) { struct regulator *dcdc; #ifdef CONFIG_ACT8846_SUPPORT_RESET sram_gpio_set_value(pmic_vsel, GPIO_LOW); dcdc =dvfs_get_regulator( "vdd_cpu"); vdd_cpu_vol = regulator_get_voltage(dcdc); regulator_set_voltage(dcdc, 900000, 900000); udelay(100); dcdc =dvfs_get_regulator( "vdd_core"); vdd_core_vol = regulator_get_voltage(dcdc); regulator_set_voltage(dcdc, 900000, 900000); udelay(100); dcdc =regulator_get(NULL, "act_dcdc4"); regulator_set_voltage(dcdc, 3000000, 3000000); regulator_put(dcdc); udelay(100); #endif } void act8846_device_resume(void) { struct regulator *dcdc; #ifdef CONFIG_ACT8846_SUPPORT_RESET dcdc =dvfs_get_regulator( "vdd_cpu"); regulator_set_voltage(dcdc, vdd_cpu_vol, vdd_cpu_vol); udelay(100); dcdc =dvfs_get_regulator( "vdd_core"); regulator_set_voltage(dcdc, vdd_core_vol, vdd_core_vol); udelay(100); dcdc =regulator_get(NULL, "act_dcdc4"); regulator_set_voltage(dcdc, 3000000, 3000000); regulator_put(dcdc); udelay(100); sram_gpio_set_value(pmic_vsel, GPIO_HIGH); #endif } #else void act8846_device_suspend(void) { } void act8846_device_resume(void) { } #endif void __sramfunc board_pmu_act8846_suspend(void) { #ifdef CONFIG_CLK_SWITCH_TO_32K sram_gpio_set_value(pmic_sleep, GPIO_HIGH); #endif } void __sramfunc board_pmu_act8846_resume(void) { #ifdef CONFIG_CLK_SWITCH_TO_32K sram_gpio_set_value(pmic_sleep, GPIO_LOW); sram_32k_udelay(10000); #endif } void __sramfunc board_act8846_set_suspend_vol(void) { #ifdef CONFIG_ACT8846_SUPPORT_RESET sram_gpio_set_value(pmic_vsel, GPIO_HIGH); #endif } void __sramfunc board_act8846_set_resume_vol(void) { #ifdef CONFIG_ACT8846_SUPPORT_RESET sram_gpio_set_value(pmic_vsel, GPIO_LOW); sram_32k_udelay(1000); #endif } #endif
bq-rk3066/android_kernel_bq_rk3188_DEPRECATED
arch/arm/mach-rk3188/board-pmu-act8846.c
C
gpl-2.0
12,632
//============================================================================== // // Copyright (c) 2002- // Authors: // * Vincent Nimal <[email protected]> (University of Oxford) // * Dave Parker <[email protected]> (University of Oxford) // //------------------------------------------------------------------------------ // // This file is part of PRISM. // // PRISM 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. // // PRISM 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 PRISM; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //============================================================================== package simulator.method; import prism.PrismException; import simulator.sampler.Sampler; /** * SimulationMethod class for the APMC ("approximate probabilistic model checking") * approach of Herault/Lassaigne/Magniette/Peyronnet (VMCAI'04). * Case where 'approximation' is unknown parameter. */ public class APMCapproximation extends APMCMethod { public APMCapproximation(double confidence, int iterations) { this.confidence = confidence; this.numSamples = iterations; } @Override public void computeMissingParameterBeforeSim() throws PrismException { approximation = Math.sqrt((0.5 * Math.log(2.0 / confidence)) / numSamples); missingParameterComputed = true; } @Override public Object getMissingParameter() throws PrismException { if (!missingParameterComputed) computeMissingParameterBeforeSim(); return approximation; } @Override public String getParametersString() { if (!missingParameterComputed) return "approximation=" + "unknown" + ", confidence=" + confidence + ", number of samples=" + numSamples; else return "approximation=" + approximation + ", confidence=" + confidence + ", number of samples=" + numSamples; } @Override public Object getResult(Sampler sampler) throws PrismException { // We may use 'approximation' to compute the result, so compute if necessary // (this should never happen) if (!missingParameterComputed) computeMissingParameterBeforeSim(); return super.getResult(sampler); } @Override public SimulationMethod clone() { APMCapproximation m = new APMCapproximation(confidence, numSamples); m.approximation = approximation; m.missingParameterComputed = missingParameterComputed; m.prOp = prOp; m.theta = theta; return m; } }
nicodelpiano/prism
src/simulator/method/APMCapproximation.java
Java
gpl-2.0
2,908
#ifndef _LINUX_WAIT_H #define _LINUX_WAIT_H #define WNOHANG 0x00000001 #define WUNTRACED 0x00000002 #define WSTOPPED WUNTRACED #define WEXITED 0x00000004 #define WCONTINUED 0x00000008 #define WNOWAIT 0x01000000 #define __WNOTHREAD 0x20000000 #define __WALL 0x40000000 #define __WCLONE 0x80000000 #define P_ALL 0 #define P_PID 1 #define P_PGID 2 #ifdef __KERNEL__ #include <linux/list.h> #include <linux/stddef.h> #include <linux/spinlock.h> #include <asm/current.h> typedef struct __wait_queue wait_queue_t; typedef int (*wait_queue_func_t)(wait_queue_t *wait, unsigned mode, int flags, void *key); int default_wake_function(wait_queue_t *wait, unsigned mode, int flags, void *key); struct __wait_queue { unsigned int flags; #define WQ_FLAG_EXCLUSIVE 0x01 void *private; wait_queue_func_t func; struct list_head task_list; }; struct wait_bit_key { void *flags; int bit_nr; }; struct wait_bit_queue { struct wait_bit_key key; wait_queue_t wait; }; struct __wait_queue_head { spinlock_t lock; struct list_head task_list; }; typedef struct __wait_queue_head wait_queue_head_t; struct task_struct; #define __WAITQUEUE_INITIALIZER(name, tsk) { \ .private = tsk, \ .func = default_wake_function, \ .task_list = { NULL, NULL } } #define DECLARE_WAITQUEUE(name, tsk) \ wait_queue_t name = __WAITQUEUE_INITIALIZER(name, tsk) #define __WAIT_QUEUE_HEAD_INITIALIZER(name) { \ .lock = __SPIN_LOCK_UNLOCKED(name.lock), \ .task_list = { &(name).task_list, &(name).task_list } } #define DECLARE_WAIT_QUEUE_HEAD(name) \ wait_queue_head_t name = __WAIT_QUEUE_HEAD_INITIALIZER(name) #define __WAIT_BIT_KEY_INITIALIZER(word, bit) \ { .flags = word, .bit_nr = bit, } extern void __init_waitqueue_head(wait_queue_head_t *q, const char *name, struct lock_class_key *); #define init_waitqueue_head(q) \ do { \ static struct lock_class_key __key; \ \ __init_waitqueue_head((q), #q, &__key); \ } while (0) #ifdef CONFIG_LOCKDEP # define __WAIT_QUEUE_HEAD_INIT_ONSTACK(name) \ ({ init_waitqueue_head(&name); name; }) # define DECLARE_WAIT_QUEUE_HEAD_ONSTACK(name) \ wait_queue_head_t name = __WAIT_QUEUE_HEAD_INIT_ONSTACK(name) #else # define DECLARE_WAIT_QUEUE_HEAD_ONSTACK(name) DECLARE_WAIT_QUEUE_HEAD(name) #endif static inline void init_waitqueue_entry(wait_queue_t *q, struct task_struct *p) { q->flags = 0; q->private = p; q->func = default_wake_function; } static inline void init_waitqueue_func_entry(wait_queue_t *q, wait_queue_func_t func) { q->flags = 0; q->private = NULL; q->func = func; } static inline int waitqueue_active(wait_queue_head_t *q) { return !list_empty(&q->task_list); } extern void add_wait_queue(wait_queue_head_t *q, wait_queue_t *wait); extern void add_wait_queue_exclusive(wait_queue_head_t *q, wait_queue_t *wait); extern void remove_wait_queue(wait_queue_head_t *q, wait_queue_t *wait); static inline void __add_wait_queue(wait_queue_head_t *head, wait_queue_t *new) { list_add(&new->task_list, &head->task_list); } static inline void __add_wait_queue_exclusive(wait_queue_head_t *q, wait_queue_t *wait) { wait->flags |= WQ_FLAG_EXCLUSIVE; __add_wait_queue(q, wait); } static inline void __add_wait_queue_tail(wait_queue_head_t *head, wait_queue_t *new) { list_add_tail(&new->task_list, &head->task_list); } static inline void __add_wait_queue_tail_exclusive(wait_queue_head_t *q, wait_queue_t *wait) { wait->flags |= WQ_FLAG_EXCLUSIVE; __add_wait_queue_tail(q, wait); } static inline void __remove_wait_queue(wait_queue_head_t *head, wait_queue_t *old) { list_del(&old->task_list); } void __wake_up(wait_queue_head_t *q, unsigned int mode, int nr, void *key); void __wake_up_locked_key(wait_queue_head_t *q, unsigned int mode, void *key); void __wake_up_sync_key(wait_queue_head_t *q, unsigned int mode, int nr, void *key); void __wake_up_locked(wait_queue_head_t *q, unsigned int mode, int nr); void __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr); void __wake_up_bit(wait_queue_head_t *, void *, int); int __wait_on_bit(wait_queue_head_t *, struct wait_bit_queue *, int (*)(void *), unsigned); int __wait_on_bit_lock(wait_queue_head_t *, struct wait_bit_queue *, int (*)(void *), unsigned); void wake_up_bit(void *, int); int out_of_line_wait_on_bit(void *, int, int (*)(void *), unsigned); int out_of_line_wait_on_bit_lock(void *, int, int (*)(void *), unsigned); wait_queue_head_t *bit_waitqueue(void *, int); #define wake_up(x) __wake_up(x, TASK_NORMAL, 1, NULL) #define wake_up_nr(x, nr) __wake_up(x, TASK_NORMAL, nr, NULL) #define wake_up_all(x) __wake_up(x, TASK_NORMAL, 0, NULL) #define wake_up_locked(x) __wake_up_locked((x), TASK_NORMAL, 1) #define wake_up_all_locked(x) __wake_up_locked((x), TASK_NORMAL, 0) #define wake_up_interruptible(x) __wake_up(x, TASK_INTERRUPTIBLE, 1, NULL) #define wake_up_interruptible_nr(x, nr) __wake_up(x, TASK_INTERRUPTIBLE, nr, NULL) #define wake_up_interruptible_all(x) __wake_up(x, TASK_INTERRUPTIBLE, 0, NULL) #define wake_up_interruptible_sync(x) __wake_up_sync((x), TASK_INTERRUPTIBLE, 1) #define wake_up_poll(x, m) \ __wake_up(x, TASK_NORMAL, 1, (void *) (m)) #define wake_up_locked_poll(x, m) \ __wake_up_locked_key((x), TASK_NORMAL, (void *) (m)) #define wake_up_interruptible_poll(x, m) \ __wake_up(x, TASK_INTERRUPTIBLE, 1, (void *) (m)) #define wake_up_interruptible_sync_poll(x, m) \ __wake_up_sync_key((x), TASK_INTERRUPTIBLE, 1, (void *) (m)) #define __wait_event(wq, condition) \ do { \ DEFINE_WAIT(__wait); \ \ for (;;) { \ prepare_to_wait(&wq, &__wait, TASK_UNINTERRUPTIBLE); \ if (condition) \ break; \ schedule(); \ } \ finish_wait(&wq, &__wait); \ } while (0) #define wait_event(wq, condition) \ do { \ if (condition) \ break; \ __wait_event(wq, condition); \ } while (0) #define __wait_event_timeout(wq, condition, ret) \ do { \ DEFINE_WAIT(__wait); \ \ for (;;) { \ prepare_to_wait(&wq, &__wait, TASK_UNINTERRUPTIBLE); \ if (condition) \ break; \ ret = schedule_timeout(ret); \ if (!ret) \ break; \ } \ if (!ret && (condition)) \ ret = 1; \ finish_wait(&wq, &__wait); \ } while (0) /** * wait_event_timeout - sleep until a condition gets true or a timeout elapses * @wq: the waitqueue to wait on * @condition: a C expression for the event to wait for * @timeout: timeout, in jiffies * * The process is put to sleep (TASK_UNINTERRUPTIBLE) until the * @condition evaluates to true. The @condition is checked each time * the waitqueue @wq is woken up. * * wake_up() has to be called after changing any variable that could * change the result of the wait condition. * * The function returns 0 if the @timeout elapsed, or the remaining * jiffies (at least 1) if the @condition evaluated to %true before * the @timeout elapsed. */ #define wait_event_timeout(wq, condition, timeout) \ ({ \ long __ret = timeout; \ if (!(condition)) \ __wait_event_timeout(wq, condition, __ret); \ __ret; \ }) #define __wait_event_interruptible(wq, condition, ret) \ do { \ DEFINE_WAIT(__wait); \ \ for (;;) { \ prepare_to_wait(&wq, &__wait, TASK_INTERRUPTIBLE); \ if (condition) \ break; \ if (!signal_pending(current)) { \ schedule(); \ continue; \ } \ ret = -ERESTARTSYS; \ break; \ } \ finish_wait(&wq, &__wait); \ } while (0) #define wait_event_interruptible(wq, condition) \ ({ \ int __ret = 0; \ if (!(condition)) \ __wait_event_interruptible(wq, condition, __ret); \ __ret; \ }) #define __wait_event_interruptible_timeout(wq, condition, ret) \ do { \ DEFINE_WAIT(__wait); \ \ for (;;) { \ prepare_to_wait(&wq, &__wait, TASK_INTERRUPTIBLE); \ if (condition) \ break; \ if (!signal_pending(current)) { \ ret = schedule_timeout(ret); \ if (!ret) \ break; \ continue; \ } \ ret = -ERESTARTSYS; \ break; \ } \ if (!ret && (condition)) \ ret = 1; \ finish_wait(&wq, &__wait); \ } while (0) /** * wait_event_interruptible_timeout - sleep until a condition gets true or a timeout elapses * @wq: the waitqueue to wait on * @condition: a C expression for the event to wait for * @timeout: timeout, in jiffies * * The process is put to sleep (TASK_INTERRUPTIBLE) until the * @condition evaluates to true or a signal is received. * The @condition is checked each time the waitqueue @wq is woken up. * * wake_up() has to be called after changing any variable that could * change the result of the wait condition. * * Returns: * 0 if the @timeout elapsed, -%ERESTARTSYS if it was interrupted by * a signal, or the remaining jiffies (at least 1) if the @condition * evaluated to %true before the @timeout elapsed. */ #define wait_event_interruptible_timeout(wq, condition, timeout) \ ({ \ long __ret = timeout; \ if (!(condition)) \ __wait_event_interruptible_timeout(wq, condition, __ret); \ __ret; \ }) #define __wait_io_event_interruptible(wq, condition, ret) \ do { \ DEFINE_WAIT(__wait); \ \ for (;;) { \ prepare_to_wait(&wq, &__wait, TASK_INTERRUPTIBLE); \ if (condition) \ break; \ if (!signal_pending(current)) { \ io_schedule(); \ continue; \ } \ ret = -ERESTARTSYS; \ break; \ } \ finish_wait(&wq, &__wait); \ } while (0) #define wait_io_event_interruptible(wq, condition) \ ({ \ int __ret = 0; \ if (!(condition)) \ __wait_io_event_interruptible(wq, condition, __ret); \ __ret; \ }) #define __wait_io_event_interruptible_timeout(wq, condition, ret) \ do { \ DEFINE_WAIT(__wait); \ \ for (;;) { \ prepare_to_wait(&wq, &__wait, TASK_INTERRUPTIBLE); \ if (condition) \ break; \ if (!signal_pending(current)) { \ ret = io_schedule_timeout(ret); \ if (!ret) \ break; \ continue; \ } \ ret = -ERESTARTSYS; \ break; \ } \ finish_wait(&wq, &__wait); \ } while (0) #define wait_io_event_interruptible_timeout(wq, condition, timeout) \ ({ \ long __ret = timeout; \ if (!(condition)) \ __wait_io_event_interruptible_timeout(wq, condition, __ret); \ __ret; \ }) #define __wait_event_interruptible_exclusive(wq, condition, ret) \ do { \ DEFINE_WAIT(__wait); \ \ for (;;) { \ prepare_to_wait_exclusive(&wq, &__wait, \ TASK_INTERRUPTIBLE); \ if (condition) { \ finish_wait(&wq, &__wait); \ break; \ } \ if (!signal_pending(current)) { \ schedule(); \ continue; \ } \ ret = -ERESTARTSYS; \ abort_exclusive_wait(&wq, &__wait, \ TASK_INTERRUPTIBLE, NULL); \ break; \ } \ } while (0) #define wait_event_interruptible_exclusive(wq, condition) \ ({ \ int __ret = 0; \ if (!(condition)) \ __wait_event_interruptible_exclusive(wq, condition, __ret);\ __ret; \ }) #define __wait_event_interruptible_locked(wq, condition, exclusive, irq) \ ({ \ int __ret = 0; \ DEFINE_WAIT(__wait); \ if (exclusive) \ __wait.flags |= WQ_FLAG_EXCLUSIVE; \ do { \ if (likely(list_empty(&__wait.task_list))) \ __add_wait_queue_tail(&(wq), &__wait); \ set_current_state(TASK_INTERRUPTIBLE); \ if (signal_pending(current)) { \ __ret = -ERESTARTSYS; \ break; \ } \ if (irq) \ spin_unlock_irq(&(wq).lock); \ else \ spin_unlock(&(wq).lock); \ schedule(); \ if (irq) \ spin_lock_irq(&(wq).lock); \ else \ spin_lock(&(wq).lock); \ } while (!(condition)); \ __remove_wait_queue(&(wq), &__wait); \ __set_current_state(TASK_RUNNING); \ __ret; \ }) #define wait_event_interruptible_locked(wq, condition) \ ((condition) \ ? 0 : __wait_event_interruptible_locked(wq, condition, 0, 0)) #define wait_event_interruptible_locked_irq(wq, condition) \ ((condition) \ ? 0 : __wait_event_interruptible_locked(wq, condition, 0, 1)) #define wait_event_interruptible_exclusive_locked(wq, condition) \ ((condition) \ ? 0 : __wait_event_interruptible_locked(wq, condition, 1, 0)) #define wait_event_interruptible_exclusive_locked_irq(wq, condition) \ ((condition) \ ? 0 : __wait_event_interruptible_locked(wq, condition, 1, 1)) #define __wait_event_interruptible_lock_irq_timeout(wq, condition, \ lock, ret) \ do { \ DEFINE_WAIT(__wait); \ \ for (;;) { \ prepare_to_wait(&wq, &__wait, TASK_INTERRUPTIBLE); \ if (condition) \ break; \ if (signal_pending(current)) { \ ret = -ERESTARTSYS; \ break; \ } \ spin_unlock_irq(&lock); \ ret = schedule_timeout(ret); \ spin_lock_irq(&lock); \ if (!ret) \ break; \ } \ finish_wait(&wq, &__wait); \ } while (0) /** * wait_event_interruptible_lock_irq_timeout - sleep until a condition gets true or a timeout elapses. * The condition is checked under the lock. This is expected * to be called with the lock taken. * @wq: the waitqueue to wait on * @condition: a C expression for the event to wait for * @lock: a locked spinlock_t, which will be released before schedule() * and reacquired afterwards. * @timeout: timeout, in jiffies * * The process is put to sleep (TASK_INTERRUPTIBLE) until the * @condition evaluates to true or signal is received. The @condition is * checked each time the waitqueue @wq is woken up. * * wake_up() has to be called after changing any variable that could * change the result of the wait condition. * * This is supposed to be called while holding the lock. The lock is * dropped before going to sleep and is reacquired afterwards. * * The function returns 0 if the @timeout elapsed, -ERESTARTSYS if it * was interrupted by a signal, and the remaining jiffies otherwise * if the condition evaluated to true before the timeout elapsed. */ #define wait_event_interruptible_lock_irq_timeout(wq, condition, lock, \ timeout) \ ({ \ int __ret = timeout; \ \ if (!(condition)) \ __wait_event_interruptible_lock_irq_timeout( \ wq, condition, lock, __ret); \ __ret; \ }) #define __wait_event_killable(wq, condition, ret) \ do { \ DEFINE_WAIT(__wait); \ \ for (;;) { \ prepare_to_wait(&wq, &__wait, TASK_KILLABLE); \ if (condition) \ break; \ if (!fatal_signal_pending(current)) { \ schedule(); \ continue; \ } \ ret = -ERESTARTSYS; \ break; \ } \ finish_wait(&wq, &__wait); \ } while (0) #define wait_event_killable(wq, condition) \ ({ \ int __ret = 0; \ if (!(condition)) \ __wait_event_killable(wq, condition, __ret); \ __ret; \ }) extern void sleep_on(wait_queue_head_t *q); extern long sleep_on_timeout(wait_queue_head_t *q, signed long timeout); extern void interruptible_sleep_on(wait_queue_head_t *q); extern long interruptible_sleep_on_timeout(wait_queue_head_t *q, signed long timeout); void prepare_to_wait(wait_queue_head_t *q, wait_queue_t *wait, int state); void prepare_to_wait_exclusive(wait_queue_head_t *q, wait_queue_t *wait, int state); void finish_wait(wait_queue_head_t *q, wait_queue_t *wait); void abort_exclusive_wait(wait_queue_head_t *q, wait_queue_t *wait, unsigned int mode, void *key); int autoremove_wake_function(wait_queue_t *wait, unsigned mode, int sync, void *key); int wake_bit_function(wait_queue_t *wait, unsigned mode, int sync, void *key); #define DEFINE_WAIT_FUNC(name, function) \ wait_queue_t name = { \ .private = current, \ .func = function, \ .task_list = LIST_HEAD_INIT((name).task_list), \ } #define DEFINE_WAIT(name) DEFINE_WAIT_FUNC(name, autoremove_wake_function) #define DEFINE_WAIT_BIT(name, word, bit) \ struct wait_bit_queue name = { \ .key = __WAIT_BIT_KEY_INITIALIZER(word, bit), \ .wait = { \ .private = current, \ .func = wake_bit_function, \ .task_list = \ LIST_HEAD_INIT((name).wait.task_list), \ }, \ } #define init_wait(wait) \ do { \ (wait)->private = current; \ (wait)->func = autoremove_wake_function; \ INIT_LIST_HEAD(&(wait)->task_list); \ (wait)->flags = 0; \ } while (0) static inline int wait_on_bit(void *word, int bit, int (*action)(void *), unsigned mode) { if (!test_bit(bit, word)) return 0; return out_of_line_wait_on_bit(word, bit, action, mode); } static inline int wait_on_bit_lock(void *word, int bit, int (*action)(void *), unsigned mode) { if (!test_and_set_bit(bit, word)) return 0; return out_of_line_wait_on_bit_lock(word, bit, action, mode); } #endif #endif
Team-SennyC2/android_kernel_htc_villec2
include/linux/wait.h
C
gpl-2.0
17,317