text:
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using MeshExplorer.Controls;
using MeshExplorer.IO;
using TriangleNet;
using TriangleNet.Geometry;
using TriangleNet.Meshing;
using TriangleNet.Meshing.Algorithm;
using TriangleNet.Rendering;
using TriangleNet.Smoothing;
using TriangleNet.Voronoi;

namespace MeshExplorer
{
    public partial class FormMain : Form
    {
        Settings settings;

        Mesh mesh;
        IPolygon input;
        VoronoiBase voronoi;

        FormLog frmLog;
        FormGenerator frmGenerator;

        RenderManager renderManager;

        public FormMain()
        {
            InitializeComponent();

            ToolStripManager.Renderer = new DarkToolStripRenderer();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            oldClientSize = this.ClientSize;

            settings = new Settings();

            renderManager = new RenderManager();

            IRenderControl control = new TriangleNet.Rendering.GDI.RenderControl();

            /*
            if (!renderManager.TryCreateControl("Triangle.Rendering.SharpGL.dll",
                new string[] { "SharpGL.dll" }, out control))
            {
                control = new TriangleNet.Rendering.GDI.RenderControl();

                if (frmLog == null)
                {
                    frmLog = new FormLog();
                }

                frmLog.AddItem("Failed to initialize OpenGL.", true);
            }
            //*/

            if (control != null)
            {
                InitializeRenderControl((Control)control);
                renderManager.Initialize(control);
            }
            else
            {
                DarkMessageBox.Show("Ooops ...", "Failed to initialize renderer.");
            }
        }

        private void InitializeRenderControl(Control control)
        {
            this.splitContainer.SuspendLayout();
            this.splitContainer.Panel2.Controls.Add(control);

            var size = this.splitContainer.Panel2.ClientRectangle;

            // Initialize control
            control.BackColor = Color.Black;
            control.Dock = DockStyle.Fill;
            control.Font = new Font("Consolas", 8.25F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
            control.Location = new System.Drawing.Point(0, 0);
            control.Name = "renderControl1";
            control.Size = new Size(size.Width, size.Height);
            control.TabIndex = 0;
            control.Text = "renderControl1";

            this.splitContainer.ResumeLayout();
        }

        protected override void OnMouseWheel(MouseEventArgs e)
        {
            if (splitContainer.Panel2.Bounds.Contains(e.Location))
            {
                var control = renderManager.Control as Control;

                // Set focus on the render control.
                if (control != null && !control.Focused)
                {
                    control.Focus();
                }
            }
        }

        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F3:
                    OpenWithDialog();
                    break;
                case Keys.F4:
                    Save();
                    break;
                case Keys.F5:
                    Reload();
                    break;
                case Keys.F8:
                    TriangulateOrRefine();
                    break;
                case Keys.F9:
                    Smooth();
                    break;
                case Keys.F12:
                    ShowLog();
                    break;
            }
        }

        void frmGenerator_InputGenerated(object sender, EventArgs e)
        {
            this.input = sender as IPolygon;

            if (input != null)
            {
                settings.CurrentFile = "tmp-" + DateTime.Now.ToString("HH-mm-ss");
                HandleNewInput();
            }
        }

        private void btnMesh_Click(object sender, EventArgs e)
        {
            TriangulateOrRefine();
        }

        private void btnSmooth_Click(object sender, EventArgs e)
        {
            Smooth();
        }

        #region Drag and drop

        private void frmDragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] args = (string[])e.Data.GetData(DataFormats.FileDrop);

                Open(args[0]);
            }
        }

        private void frmDragOver(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] args = (string[])e.Data.GetData(DataFormats.FileDrop);

                if (args.Length > 1)
                {
                    e.Effect = DragDropEffects.None;
                    return;
                }

                string file = args[0].ToLower();

                // Check if file extension is known
                if (FileProcessor.CanHandleFile(file))
                {
                    e.Effect = DragDropEffects.Copy;
                }
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        #endregion

        #region Resize event handler

        bool isResizing = false;
        Size oldClientSize;

        private void ResizeHandler(object sender, EventArgs e)
        {
            // Handle window minimize and maximize
            if (!isResizing)
            {
                renderManager.Resize();
            }
        }

        private void ResizeEndHandler(object sender, EventArgs e)
        {
            isResizing = false;

            if (this.ClientSize != this.oldClientSize)
            {
                this.oldClientSize = this.ClientSize;
                renderManager.Resize();
            }
        }

        private void ResizeBeginHandler(object sender, EventArgs e)
        {
            isResizing = true;
        }

        #endregion

        #region State changes

        private void LockOnException()
        {
            btnMesh.Enabled = false;
            btnSmooth.Enabled = false;

            //menuFileSave.Enabled = false;
            //menuFileExport.Enabled = false;
            menuViewVoronoi.Enabled = false;
            menuToolsCheck.Enabled = false;
            menuToolsRcm.Enabled = false;

            settings.ExceptionThrown = true;
        }

        private void HandleNewInput()
        {
            // Reset mesh
            mesh = null;
            voronoi = null;

            // Reset state
            settings.RefineMode = false;
            settings.ExceptionThrown = false;

            // Reset buttons
            btnMesh.Enabled = true;
            btnMesh.Text = "Triangulate";
            btnSmooth.Enabled = false;

            // Update Statistic view
            statisticView.HandleNewInput(input);

            // Clear voronoi
            menuViewVoronoi.Checked = false;

            // Disable menu items
            menuFileSave.Enabled = false;
            menuFileExport.Enabled = false;
            menuViewVoronoi.Enabled = false;
            menuToolsCheck.Enabled = false;
            menuToolsRcm.Enabled = false;

            // Render input
            renderManager.Set(input);

            // Update window caption
            this.Text = "Triangle.NET - Mesh Explorer - " + settings.CurrentFile;
        }

        private void HandleMeshImport()
        {
            voronoi = null;

            // Render mesh
            renderManager.Set(mesh, true);

            // Update window caption
            this.Text = "Triangle.NET - Mesh Explorer - " + settings.CurrentFile;

            // Update Statistic view
            statisticView.HandleMeshImport(input, mesh);

            // Set refine mode
            btnMesh.Enabled = true;
            btnMesh.Text = "Refine";

            settings.RefineMode = true;

            HandleMeshChange();
        }

        private void HandleMeshUpdate()
        {
            // Render mesh
            renderManager.Set(mesh, false);

            // Update Statistic view
            statisticView.HandleMeshUpdate(mesh);

            HandleMeshChange();
        }

        private void HandleMeshChange()
        {
            // Update Statistic view
            statisticView.HandleMeshChange(mesh);

            // TODO: Should the Voronoi diagram automatically update?
            voronoi = null;
            menuViewVoronoi.Checked = false;

            // Enable menu items
            menuFileSave.Enabled = true;
            menuFileExport.Enabled = true;
            menuViewVoronoi.Enabled = true;
            menuToolsCheck.Enabled = true;
            menuToolsRcm.Enabled = true;
        }

        #endregion

        #region Commands

        private void OpenWithDialog()
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Filter = settings.OfdFilter;
            ofd.FilterIndex = settings.OfdFilterIndex;
            ofd.InitialDirectory = settings.OfdDirectory;
            ofd.FileName = "";

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                if (Open(ofd.FileName))
                {
                    // Update folder settings
                    settings.OfdFilterIndex = ofd.FilterIndex;
                    settings.OfdDirectory = Path.GetDirectoryName(ofd.FileName);
                }
            }
        }

        private bool Open(string filename)
        {
            if (!FileProcessor.CanHandleFile(filename))
            {
                // TODO: show message.
            }
            else
            {
                if (FileProcessor.ContainsMeshData(filename))
                {
                    if (filename.EndsWith(".ele") || DarkMessageBox.Show("Import mesh", Settings.ImportString,
                        "Do you want to import the mesh?", MessageBoxButtons.YesNo) == DialogResult.OK)
                    {
                        input = null;

                        try
                        {
                            mesh = FileProcessor.Import(filename);
                        }
                        catch (Exception e)
                        {
                            DarkMessageBox.Show("Import mesh error", e.Message, MessageBoxButtons.OK);
                            return false;
                        }

                        if (mesh != null)
                        {
                            statisticView.UpdateStatistic(mesh);

                            // Update settings
                            settings.CurrentFile = Path.GetFileName(filename);

                            HandleMeshImport();
                            btnSmooth.Enabled = true; // TODO: Remove
                        }
                        // else Message

                        return true;
                    }
                }

                input = FileProcessor.Read(filename);
            }

            if (input != null)
            {
                // Update settings
                settings.CurrentFile = Path.GetFileName(filename);

                HandleNewInput();
            }
            // else Message

            return true;
        }

        private void Save()
        {
            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Filter = settings.SfdFilter;
            sfd.FilterIndex = settings.SfdFilterIndex;
            sfd.InitialDirectory = settings.SfdDirectory;
            sfd.FileName = "";

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                FileProcessor.Save(sfd.FileName, mesh);
            }
        }

        private void Reload()
        {
            if (input != null)
            {
                mesh = null;
                settings.RefineMode = false;
                settings.ExceptionThrown = false;

                HandleNewInput();
            }
        }

        private void TriangulateOrRefine()
        {
            if ((input == null && !settings.RefineMode) || settings.ExceptionThrown)
            {
                return;
            }

            if (settings.RefineMode == false)
            {
                Triangulate();

                if (meshControlView.ParamQualityChecked)
                {
                    btnMesh.Text = "Refine";
                    btnSmooth.Enabled = mesh.IsPolygon;
                }
            }
            else if (meshControlView.ParamQualityChecked)
            {
                Refine();
            }
        }

        private void Triangulate()
        {
            if (input == null) return;

            var options = new ConstraintOptions();
            var quality = new QualityOptions();

            if (meshControlView.ParamConformDelChecked)
            {
                options.ConformingDelaunay = true;
            }

            if (meshControlView.ParamQualityChecked)
            {
                quality.MinimumAngle = meshControlView.ParamMinAngleValue;

                double maxAngle = meshControlView.ParamMaxAngleValue;

                if (maxAngle < 180)
                {
                    quality.MaximumAngle = maxAngle;
                }

                // Ignore area constraints on initial triangulation.

                //double area = slMaxArea.Value * 0.01;
                //if (area > 0 && area < 1)
                //{
                //    var size = input.Bounds;
                //    double min = Math.Min(size.Width, size.Height);
                //    mesh.SetOption(Options.MaxArea, area * min);
                //}
            }

            if (meshControlView.ParamConvexChecked)
            {
                options.Convex = true;
            }

            try
            {
                if (meshControlView.ParamSweeplineChecked)
                {
                    mesh = (Mesh)input.Triangulate(options, quality, new SweepLine());
                }
                else
                {
                    mesh = (Mesh)input.Triangulate(options, quality);
                }

                statisticView.UpdateStatistic(mesh);

                HandleMeshUpdate();

                if (meshControlView.ParamQualityChecked)
                {
                    settings.RefineMode = true;
                }
            }
            catch (Exception ex)
            {
                LockOnException();
                DarkMessageBox.Show("Exception - Triangulate", ex.Message, MessageBoxButtons.OK);
            }

            UpdateLog();
        }

        private void Refine()
        {
            if (mesh == null) return;

            double area = meshControlView.ParamMaxAreaValue;

            var quality = new QualityOptions();

            if (area > 0 && area < 1)
            {
                quality.MaximumArea = area * statisticView.Statistic.LargestArea;
            }

            quality.MinimumAngle = meshControlView.ParamMinAngleValue;

            double maxAngle = meshControlView.ParamMaxAngleValue;

            if (maxAngle < 180)
            {
                quality.MaximumAngle = maxAngle;
            }

            try
            {
                mesh.Refine(quality, meshControlView.ParamConformDelChecked);

                statisticView.UpdateStatistic(mesh);

                HandleMeshUpdate();
            }
            catch (Exception ex)
            {
                LockOnException();
                DarkMessageBox.Show("Exception - Refine", ex.Message, MessageBoxButtons.OK);
            }

            UpdateLog();
        }

        private void Renumber()
        {
            if (mesh == null || settings.ExceptionThrown) return;

            bool tmp = Log.Verbose;
            Log.Verbose = true;

            mesh.Renumber(NodeNumbering.CuthillMcKee);
            ShowLog();

            Log.Verbose = tmp;
        }

        private void Smooth()
        {
            if (mesh == null || settings.ExceptionThrown) return;

            if (!mesh.IsPolygon)
            {
                return;
            }

            var smoother = new SimpleSmoother();

            try
            {
                smoother.Smooth(this.mesh);

                statisticView.UpdateStatistic(mesh);

                HandleMeshUpdate();
            }
            catch (Exception ex)
            {
                LockOnException();
                DarkMessageBox.Show("Exception - Smooth", ex.Message, MessageBoxButtons.OK);
            }

            UpdateLog();
        }

        private bool CreateVoronoi()
        {
            if (mesh == null)
            {
                return false;
            }

            if (mesh.IsPolygon)
            {
                try
                {
                    this.voronoi = new BoundedVoronoi(mesh);
                }
                catch (Exception ex)
                {
                    if (!meshControlView.ParamConformDelChecked)
                    {
                        DarkMessageBox.Show("Exception - Bounded Voronoi", Settings.VoronoiString, MessageBoxButtons.OK);
                    }
                    else
                    {
                        DarkMessageBox.Show("Exception - Bounded Voronoi", ex.Message, MessageBoxButtons.OK);
                    }

                    return false;
                }
            }
            else
            {
                this.voronoi = new StandardVoronoi(mesh);
            }

            // HACK: List<Vertex> -> ICollection<Point> ? Nope, no way.
            //           Vertex[] -> ICollection<Point> ? Well, ok.
            renderManager.Set(voronoi.Vertices.ToArray(), voronoi.Edges, false);

            return true;
        }

        private void ShowLog()
        {
            if (frmLog == null)
            {
                frmLog = new FormLog();
            }

            UpdateLog();

            if (!frmLog.Visible)
            {
                frmLog.Show(this);
            }
        }

        private void UpdateLog()
        {
            if (frmLog != null)
            {
                frmLog.UpdateItems();
            }
        }

        #endregion

        #region Menu Handler

        private void menuFileOpen_Click(object sender, EventArgs e)
        {
            OpenWithDialog();
        }

        private void menuFileSave_Click(object sender, EventArgs ev)
        {
            if (mesh != null)
            {
                Save();
            }
        }

        private void menuFileExport_Click(object sender, EventArgs e)
        {
            if (mesh != null)
            {
                FormExport export = new FormExport();

                string file = settings.OfdDirectory;

                if (!file.EndsWith("\\"))
                {
                    file += "\\";
                }

                file += settings.CurrentFile;

                export.ImageName = Path.ChangeExtension(file, ".png");

                if (export.ShowDialog() == DialogResult.OK)
                {
                    int format = export.ImageFormat;
                    int size = export.ImageSize;
                    bool compress = export.UseCompression;

                    var writer = new ImageWriter();

                    writer.Export(this.mesh, export.ImageName, format, size, compress);
                }
            }
        }

        private void menuFileQuit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void menuViewVoronoi_Click(object sender, EventArgs e)
        {
            if (this.voronoi == null)
            {
                menuViewVoronoi.Checked = CreateVoronoi();
            }
            else
            {
                bool visible = menuViewVoronoi.Checked;

                renderManager.Enable(4, !visible);
                menuViewVoronoi.Checked = !visible;
            }
        }

        private void menuViewLog_Click(object sender, EventArgs e)
        {
            ShowLog();
        }

        private void menuToolsGenerator_Click(object sender, EventArgs e)
        {
            if (frmGenerator == null || frmGenerator.IsDisposed)
            {
                frmGenerator = new FormGenerator();
                frmGenerator.InputGenerated += new EventHandler(frmGenerator_InputGenerated);
            }

            if (!frmGenerator.Visible)
            {
                frmGenerator.Show();
            }
            else
            {
                frmGenerator.Activate();
            }
        }

        private void menuToolsCheck_Click(object sender, EventArgs e)
        {
            if (mesh != null)
            {
                bool save = Log.Verbose;

                Log.Verbose = true;

                bool isConsistent = MeshValidator.IsConsistent(mesh);
                bool isDelaunay = MeshValidator.IsDelaunay(mesh);

                Log.Verbose = save;

                if (isConsistent)
                {
                    Log.Instance.Info("Mesh topology appears to be consistent.");
                }

                if (isDelaunay)
                {
                    Log.Instance.Info("Mesh is (conforming) Delaunay.");
                }

                ShowLog();
            }
        }

        private void menuToolsTopology_Click(object sender, EventArgs e)
        {
            (new FormTopology()).ShowDialog(this);
        }

        private void menuToolsRcm_Click(object sender, EventArgs e)
        {
            Renumber();
        }

        #endregion
    }
}


text:
<!doctype html>

    <title>Code coverage report for ./app/scripts/Section\</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../../../prettify.css">
    <link rel="stylesheet" href="../../../base.css">

Code coverage report for ./app/scripts/Section\

        Statements: 61.02% (36 / 59)
        Branches: 60.71% (17 / 28)
        Functions: 57.14% (8 / 14)
        Lines: 62.07% (36 / 58)
        Ignored: none

All files » ./app/scripts/Section/

   File

   Statements

   Branches

   Functions

   Lines

	Section.js

	60.34%
	(35 / 58)
	60.71%
	(17 / 28)
	57.14%
	(8 / 14)
	61.4%
	(35 / 57)

	examples.js

	100%
	(1 / 1)
	100%
	(0 / 0)
	100%
	(0 / 0)
	100%
	(1 / 1)

Generated by istanbul at Thu Apr 21 2016 16:42:36 GMT-0500 (Central Daylight Time)

redpajama_set_name: RedPajamaGithub


text:
package org.usfirst.frc.team2084.CMonster2016.test;

import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.usfirst.frc.team2084.CMonster2016.RobotMap;

import jaci.pathfinder.Trajectory;

/**
 * Test that checks to make sure the maximum velocity of the trajectory does not
 * exceed physically allowable limits.
 *
 * @author Ben Wolsieffer
 */
@RunWith(Parameterized.class)
public class WaypointTest {

    @Parameter
    public Future<Trajectory[]> trajectory;

    @Test
    public void testGenerate() throws InterruptedException, ExecutionException {
        trajectory.get();
    }

    @Test
    public void testVelocity() throws InterruptedException, ExecutionException {
        for (Trajectory t : trajectory.get()) {
            assertThat("Max velocity must not exceed what physics allows",
                    Arrays.stream(t.segments).mapToDouble((s) -> s.velocity).max().getAsDouble(),
                    lessThanOrEqualTo(RobotMap.DRIVE_SUBSYSTEM_MAX_WHEEL_SPEED));
        }
    }

    @SuppressWarnings("unchecked")
    @Parameters
    public static Collection<Future<Trajectory[]>> trajectories() {
        Class<RobotMap> robotMapClass = RobotMap.class;
        return Arrays.stream(robotMapClass.getFields())
                .filter((f) -> f.getType().equals(Future.class) && f.getName().contains("TRAJECTORY")).map((f) -> {
                    try {
                        return (Future<Trajectory[]>) f.get(null);
                    } catch (Exception e) {
                        fail("Could not get trajectory field value:" + e);
                        return null;
                    }
                }).filter((f) -> f != null).collect(Collectors.toList());
    }

}


text:
namespace WpfHelpers.Windows {
    using System.Windows;

    /// <summary>
    ///   Helper extensions for visibility
    /// </summary>
    public static class VisibilityHelper {
        /// <summary>
        ///   Converts a <see cref="Visibility" /> value to a <see cref="bool" /> with <see cref="Visibility.Visible"/> being <c>true</c>
        /// </summary>
        /// <param name="v"> </param>
        /// <returns> </returns>
        public static bool ToBoolean (this Visibility v) {
            return v == Visibility.Visible;
        }

        /// <summary>
        /// Inverts the specified visibility: <see cref="Visibility.Visible"/> to <see cref="Visibility.Collapsed"/> and vice versa
        /// </summary>
        /// <param name="v"></param>
        /// <returns></returns>
        public static Visibility Inverse(this Visibility v) {
            return v == Visibility.Visible ? Visibility.Collapsed : Visibility.Visible;
        }

        /// <summary>
        /// Converts a <see cref="bool"/> value to a <see cref="Visibility"/> value, with <c>true</c> being <see cref="Visibility.Visible"/>
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        public static Visibility ToVisibility(this bool b) {
            return b ? Visibility.Visible : Visibility.Collapsed;
        }
    }
}


text:
<?php
declare(strict_types=1);

namespace Doctrine\Common\Cache;

use InvalidArgumentException;
use function sprintf;

final class InvalidCacheId extends InvalidArgumentException
{
    public static function exceedsMaxLength($id, int $maxLength) : self
    {
        return new self(sprintf('Cache id "%s" exceeds maximum length %d', $id, $maxLength));
    }

    public static function containsUnauthorizedCharacter($id, string $character) : self
    {
        return new self(sprintf('Cache id "%s" contains unauthorized character "%s"', $id, $character));
    }

    public static function containsControlCharacter($id) : self
    {
        return new self(sprintf('Cache id "%s" contains at least one control character', $id));
    }
}


text:
class SetChildrenTag extends MonoBehaviour
{
	public var desiredTag : String;

	function Start()
	{
		if(String.IsNullOrEmpty(desiredTag)) return;

		gameObject.tag = desiredTag;

		for(var i : int = 0; i < transform.childCount; i++)
		{
			SetTag(transform.GetChild(i));
		}
	}

	function SetTag(t : Transform)
	{
		t.tag = desiredTag;

		for(var i : int = 0; i < t.childCount; i++)
		{
			SetTag(t.GetChild(i));
		}
	}
}


text:
bool DefaultEvaluateStrategy::IsCommon(const std::string &word)
{
    return dict.GetLevel(word) >= 3;
}

bool DefaultEvaluateStrategy::IsForgettable(const std::string &word)
{
    auto c = user.GetCounters(word);
    return (c[COUNTER_RETRIVE] + c[COUNTER_LEARN] > c[COUNTER_PASS]) || ((c[COUNTER_TEST] > 0) && (c[COUNTER_PASS] * 100 / c[COUNTER_TEST] < 20));
}

bool DefaultEvaluateStrategy::IsKnown(const std::string &word)
{
    auto c = user.GetCounters(word);
    if (c[COUNTER_PASS] > 0 && c[COUNTER_TEST] == 0)
    {
        throw std::string("assert failed");
    }
    return (c[COUNTER_PASS] >= 1) && (c[COUNTER_PASS] * 100 / c[COUNTER_TEST] > 60);
}

bool DefaultEvaluateStrategy::IsLearned(const std::string &word)
{
    auto c = user.GetCounters(word);
    return c[COUNTER_LEARN] > 0;
}


text:
package org.talend.sdk.component.design.extension.repository;

import lombok.Data;

@Data
public class ConfigKey {

    private final String family;

    private final String configName;

    private final String configType;
}


text:
/*============================================================================
=   Include files
============================================================================*/
#include "general.h"

#include <string.h>
#include <ctype.h>	/* to define isspace() */
#include <errno.h>

#if defined(HAVE_SYS_TYPES_H)
# include <sys/types.h>	    /* to declare off_t on some hosts */
#endif
#if defined(HAVE_UNISTD_H)
# include <unistd.h>	/* to declare close(), ftruncate(), truncate() */
#endif

/*  These header files provide for the functions necessary to do file
 *  truncation.
 */
#include <fcntl.h>
#ifdef HAVE_IO_H
# include <io.h>
#endif

#include "debug.h"
#include "entry.h"
#include "main.h"
#include "options.h"
#include "read.h"
#include "sort.h"
#include "strlist.h"

/*============================================================================
*=	Defines
============================================================================*/
#define PSEUDO_TAG_PREFIX	"!_"

#define includeExtensionFlags()		(Option.tagFileFormat > 1)

/*----------------------------------------------------------------------------
 *  Portability defines
 *--------------------------------------------------------------------------*/
#if !defined(HAVE_TRUNCATE) && !defined(HAVE_FTRUNCATE) && !defined(HAVE_CHSIZE)
# define USE_REPLACEMENT_TRUNCATE
#endif

/*  Hack for rediculous practice of Microsoft Visual C++.
 */
#if defined(WIN32) && defined(_MSC_VER)
# define chsize		_chsize
# define open		_open
# define close		_close
# define O_RDWR 	_O_RDWR
#endif

/*============================================================================
=   Data definitions
============================================================================*/

tagFile TagFile = {
    NULL,		/* file name */
    NULL,		/* file pointer */
    { 0, 0 },		/* numTags */
    { 0, 0, 0 },	/* max */
    { NULL, NULL, 0 },	/* etags */
    NULL		/* vLine */
};

static boolean TagsToStdout = FALSE;

/*============================================================================
=   Function prototypes
============================================================================*/
#ifdef NEED_PROTO_TRUNCATE
extern int truncate __ARGS((const char *path, off_t length));
#endif

#ifdef NEED_PROTO_FTRUNCATE
extern int ftruncate __ARGS((int fd, off_t length));
#endif

static void writePseudoTag __ARGS((const char *const tagName, const char *const fileName, const char *const pattern));
static void updateSortedFlag __ARGS((const char *const line, FILE *const fp, fpos_t startOfLine));
static void addPseudoTags __ARGS((void));
static long unsigned int updatePseudoTags __ARGS((FILE *const fp));
static boolean isValidTagAddress __ARGS((const char *const tag));
static boolean isCtagsLine __ARGS((const char *const tag));
static boolean isEtagsLine __ARGS((const char *const tag));
static boolean isTagFile __ARGS((const char *const filename));
#ifdef ENABLE_UPDATE
static boolean isNameInList __ARGS((Arguments* const args, const char *const name, const size_t length));
#endif
static void sortTagFile __ARGS((void));
static void resizeTagFile __ARGS((const long newSize));
static void writeEtagsIncludes __ARGS((FILE *const fp));
static size_t writeSourceLine __ARGS((FILE *const fp, const char *const line));
static size_t writeCompactSourceLine __ARGS((FILE *const fp, const char *const line));
static void rememberMaxLengths __ARGS((const size_t nameLength, const size_t lineLength));
static int writeXrefEntry __ARGS((const tagEntryInfo *const tag));
static void truncateTagLine __ARGS((char *const line, const char *const token, const boolean discardNewline));
static int writeEtagsEntry __ARGS((const tagEntryInfo *const tag));
static int addExtensionFlags __ARGS((const tagEntryInfo *const tag));
static int writePatternEntry __ARGS((const tagEntryInfo *const tag));
static int writeLineNumberEntry __ARGS((const tagEntryInfo *const tag));
static int writeCtagsEntry __ARGS((const tagEntryInfo *const tag));

/*============================================================================
=   Function definitions
============================================================================*/

extern void freeTagFileResources()
{
    vStringDelete(TagFile.vLine);
}

extern const char *tagFileName()
{
    return TagFile.name;
}

/*----------------------------------------------------------------------------
*-	Pseudo tag support
----------------------------------------------------------------------------*/

static void writePseudoTag( tagName, fileName, pattern )
    const char *const tagName;
    const char *const fileName;
    const char *const pattern;
{
    const int length = fprintf(TagFile.fp, "%s%s\t%s\t/%s/\n",
			       PSEUDO_TAG_PREFIX, tagName, fileName, pattern);
    ++TagFile.numTags.added;
    rememberMaxLengths(strlen(tagName), (size_t)length);
}

static void addPseudoTags()
{
    if (! Option.xref)
    {
	char format[11];
	const char *formatComment = "unknown format";

	sprintf(format, "%u", Option.tagFileFormat);

	if (Option.tagFileFormat == 1)
	    formatComment = "original ctags format";
	else if (Option.tagFileFormat == 2)
	    formatComment =
		    "extended format; --format=1 will not append ;\" to lines";

	writePseudoTag("TAG_FILE_FORMAT", format, formatComment);
	writePseudoTag("TAG_FILE_SORTED", Option.sorted ? "1":"0",
		       "0=unsorted, 1=sorted");
	writePseudoTag("TAG_PROGRAM_AUTHOR",	AUTHOR_NAME,  AUTHOR_EMAIL);
	writePseudoTag("TAG_PROGRAM_NAME",	PROGRAM_NAME, "");
	writePseudoTag("TAG_PROGRAM_URL",	PROGRAM_URL,  "official site");
	writePseudoTag("TAG_PROGRAM_VERSION",	PROGRAM_VERSION,
		       "with C, C++, Eiffel, Fortran, and Java  support");
    }
}

static void updateSortedFlag( line, fp, startOfLine )
    const char *const line;
    FILE *const fp;
    fpos_t startOfLine;
{
    const char *const tab = strchr(line, '\t');

    if (tab != NULL)
    {
	const long boolOffset = tab - line + 1;		/* where it should be */

	if (line[boolOffset] == '0'  ||  line[boolOffset] == '1')
	{
	    fpos_t nextLine;

	    if (fgetpos(fp, &nextLine) == -1 || fsetpos(fp, &startOfLine) == -1)
		error(WARNING, "Failed to update 'sorted' pseudo-tag");
	    else
	    {
		fpos_t flagLocation;
		int c, d;

		do
		    c = fgetc(fp);
		while (c != '\t'  &&  c != '\n');
		fgetpos(fp, &flagLocation);
		d = fgetc(fp);
		if (c == '\t'  &&  (d == '0'  ||  d == '1')  &&
		    d != (int)Option.sorted)
		{
		    fsetpos(fp, &flagLocation);
		    fputc(Option.sorted ? '1' : '0', fp);
		}
		fsetpos(fp, &nextLine);
	    }
	}
    }
}

/*  Look through all line beginning with "!_TAG_FILE", and update those which
 *  require it.
 */
static unsigned long updatePseudoTags( fp )
    FILE *const fp;
{
    enum { maxClassLength = 20 };
    char class[maxClassLength + 1];
    unsigned long linesRead = 0;
    fpos_t startOfLine;
    size_t classLength;
    const char *line;

    sprintf(class, "%sTAG_FILE", PSEUDO_TAG_PREFIX);
    classLength = strlen(class);
    Assert(classLength < maxClassLength);

    fgetpos(fp, &startOfLine);
    line = readLine(TagFile.vLine, fp);
    while (line != NULL  &&  line[0] == class[0])
    {
	++linesRead;
	if (strncmp(line, class, classLength) == 0)
	{
	    char tab, classType[16];

	    if (sscanf(line + classLength, "%15s%c", classType, &tab) == 2  &&
		tab == '\t')
	    {
		if (strcmp(classType, "_SORTED") == 0)
		    updateSortedFlag(line, fp, startOfLine);
	    }
	    fgetpos(fp, &startOfLine);
	}
	line = readLine(TagFile.vLine, fp);
    }
    while (line != NULL)			/* skip to end of file */
    {
	++linesRead;
	line = readLine(TagFile.vLine, fp);
    }
    return linesRead;
}

/*----------------------------------------------------------------------------
 *  Tag file management
 *--------------------------------------------------------------------------*/

static boolean isValidTagAddress( excmd )
    const char *const excmd;
{
    boolean isValid = FALSE;

    if (strchr("/?", excmd[0]) != NULL)
	isValid = TRUE;
    else
    {
	char *address = (char *)eMalloc(strlen(excmd) + 1);

	if (address != NULL)
	{
	    if (sscanf(excmd, "%[^;\n]", address) == 1  &&
		strspn(address,"0123456789") == strlen(address))
		    isValid = TRUE;
	    eFree(address);
	}
    }
    return isValid;
}

static boolean isCtagsLine( line )
    const char *const line;
{
    enum fieldList { TAG, TAB1, SRC_FILE, TAB2, EXCMD, NUM_FIELDS };
    boolean ok = FALSE;			/* we assume not unless confirmed */
    const size_t fieldLength = strlen(line) + 1;
    char *const fields = (char *)eMalloc((size_t)NUM_FIELDS * fieldLength);

    if (fields == NULL)
	error(FATAL, "Cannot analyze tag file");
    else
    {
#define field(x)	(fields + ((size_t)(x) * fieldLength))

	const int numFields = sscanf(line, "%[^\t]%[\t]%[^\t]%[\t]%[^\r\n]",
				     field(TAG), field(TAB1), field(SRC_FILE),
				     field(TAB2), field(EXCMD));

	/*  There must be exactly five fields: two tab fields containing
	 *  exactly one tab each, the tag must not begin with "#", and the
	 *  file name should not end with ";", and the excmd must be
	 *  accceptable.
	 *
	 *  These conditions will reject tag-looking lines like:
	 *      int	a;	<C-comment>
	 *      #define	LABEL	<C-comment>
	 */
	if (numFields == NUM_FIELDS   &&
	    strlen(field(TAB1)) == 1  &&
	    strlen(field(TAB2)) == 1  &&
	    field(TAG)[0] != '#'      &&
	    field(SRC_FILE)[strlen(field(SRC_FILE)) - 1] != ';'  &&
	    isValidTagAddress(field(EXCMD)))
		ok = TRUE;

	eFree(fields);
    }
    return ok;
}

static boolean isEtagsLine( line )
    const char *const line;
{
    const char *const magic = "\f\n";

    return (boolean)(strncmp(line, magic, strlen(magic)) == 0);
}

static boolean isTagFile( filename )
    const char *const filename;
{
    boolean ok = FALSE;			/* we assume not unless confirmed */
    FILE *const fp = fopen(filename, "rb");

    if (fp == NULL  &&  errno == ENOENT)
	ok = TRUE;
    else if (fp != NULL)
    {
	const char *line = readLine(TagFile.vLine, fp);

	if (line == NULL)
	    ok = TRUE;
	else if (Option.etags)		/* check for etags magic number */
	    ok = isEtagsLine(line);
	else
	    ok = isCtagsLine(line);
	fclose(fp);
    }
    return ok;
}

extern void copyBytes( fromFp, toFp, size )
    FILE* const fromFp;
    FILE* const toFp;
    const long size;
{
    enum { BufferSize = 1000 };
    long toRead, numRead;
    char* buffer = (char*)eMalloc((size_t)BufferSize);
    long remaining = size;
    do
    {
	toRead = (0 < remaining && remaining < BufferSize) ?
		    remaining : BufferSize;
	numRead = fread(buffer, (size_t)1, (size_t)toRead, fromFp);
	if (fwrite(buffer, (size_t)1, (size_t)numRead, toFp) < (size_t)numRead)
	    error (FATAL | PERROR, "cannot complete write");
	if (remaining > 0)
	    remaining -= numRead;
    } while (numRead == toRead  &&  remaining != 0);
    eFree(buffer);
}

extern void copyFile( from, to, size )
    const char *const from;
    const char *const to;
    const long size;
{
    FILE* const fromFp = fopen(from, "rb");
    if (fromFp == NULL)
	error (FATAL | PERROR, "cannot open file to copy");
    else
    {
	FILE* const toFp = fopen(to, "wb");
	if (toFp == NULL)
	    error (FATAL | PERROR, "cannot open copy destination");
	else
	{
	    copyBytes (fromFp, toFp, size);
	    fclose(toFp);
	}
	fclose(fromFp);
    }
}

extern void openTagFile()
{
    setDefaultTagFileName();
    TagsToStdout = isDestinationStdout();

    if (TagFile.vLine == NULL)
	TagFile.vLine = vStringNew();

    /*  Open the tags file.
     */
    if (TagsToStdout)
	TagFile.fp = tempFile("w", &TagFile.name);
    else
    {
	char* fname;
	boolean fileExists;

	setDefaultTagFileName();
	fname = (char*)eMalloc(strlen(Option.tagFileName) + 1);
	strcpy(fname, Option.tagFileName);
	TagFile.name = fname;
	fileExists = doesFileExist(fname);
	if (fileExists  &&  ! isTagFile(fname))
	    error(FATAL,
	      "\"%s\" doesn't look like a tag file; I refuse to overwrite it.",
		  fname);

	if (Option.etags)
	{
	    if (Option.append  &&  fileExists)
		TagFile.fp = fopen(fname, "a+b");
	    else
		TagFile.fp = fopen(fname, "w+b");
	}
	else
	{
	    if (Option.append  &&  fileExists)
	    {
		TagFile.fp = fopen(fname, "r+");
		if (TagFile.fp != NULL)
		{
		    TagFile.numTags.prev = updatePseudoTags(TagFile.fp);
		    fclose(TagFile.fp);
		    TagFile.fp = fopen(fname, "a+");
		}
	    }
	    else
	    {
		TagFile.fp = fopen(fname, "w");
		if (TagFile.fp != NULL)
		    addPseudoTags();
	    }
	}
	if (TagFile.fp == NULL)
	{
	    error(FATAL | PERROR, "cannot open tag file");
	    exit(1);
	}
    }
}

#ifdef USE_REPLACEMENT_TRUNCATE

static int replacementTruncate __ARGS((const char *const name, const long size));

/*  Replacement for missing library function.
 */
static int replacementTruncate( name, size )
    const char *const name;
    const long size;
{
    char *tempName = NULL;
    FILE *fp = tempFile("w", &tempName);
    fclose(fp);
    copyFile(name, tempName, size);
    copyFile(tempName, name, WHOLE_FILE);
    remove(tempName);
    eFree(tempName);

    return 0;
}

#endif

static void sortTagFile()
{
    if (TagFile.numTags.added > 0L)
    {
	if (Option.sorted)
	{
	    if (Option.verbose)
		printf("sorting tag file\n");
#ifdef EXTERNAL_SORT
	    externalSortTags(TagsToStdout);
#else
	    internalSortTags(TagsToStdout);
#endif
	}
	else if (TagsToStdout)
	    catFile(tagFileName());
    }
    if (TagsToStdout)
	remove(tagFileName());		/* remove temporary file */
}

static void resizeTagFile( newSize )
    const long newSize;
{
    int result = 0;

#ifdef USE_REPLACEMENT_TRUNCATE
    result = replacementTruncate(TagFile.name, newSize);
#else
# ifdef HAVE_TRUNCATE
    result = truncate(TagFile.name, (off_t)newSize);
# else
    const int fd = open(TagFile.name, O_RDWR);

    if (fd != -1)
    {
#  ifdef HAVE_FTRUNCATE
	result = ftruncate(fd, (off_t)newSize);
#  else
#   ifdef HAVE_CHSIZE
	result = chsize(fd, newSize);
#   endif
#  endif
	close(fd);
    }
# endif
#endif
    if (result == -1)
	fprintf(errout, "Cannot shorten tag file: errno = %d\n", errno);
}

static void writeEtagsIncludes( fp )
    FILE *const fp;
{
    if (Option.etagsInclude)
    {
	unsigned int i;
	for (i = 0  ;  i < stringListCount(Option.etagsInclude)  ;  ++i)
	{
	    vString *item = stringListItem(Option.etagsInclude, i);
	    fprintf(fp, "\f\n%s,include\n", vStringValue(item));
	}
    }
}

extern void closeTagFile( resize )
    const boolean resize;
{
    long desiredSize, size;

    if (Option.etags)
	writeEtagsIncludes(TagFile.fp);
    desiredSize = ftell(TagFile.fp);
    fseek(TagFile.fp, 0L, SEEK_END);
    size = ftell(TagFile.fp);
    fclose(TagFile.fp);
    if (resize  &&  desiredSize < size)
    {
	DebugStatement(
	    debugPrintf(DEBUG_STATUS, "shrinking %s from %ld to %ld bytes\n",
			TagFile.name, size, desiredSize); )
	resizeTagFile(desiredSize);
    }
    if (! Option.etags)
	sortTagFile();
    eFree(TagFile.name);
    TagFile.name = NULL;
}

extern void beginEtagsFile()
{
    TagFile.etags.fp = tempFile("w+b", &TagFile.etags.name);
    TagFile.etags.byteCount = 0;
}

extern void endEtagsFile( name )
    const char *const name;
{
    const char *line;

    fprintf(TagFile.fp, "\f\n%s,%ld\n", name, (long)TagFile.etags.byteCount);
    if (TagFile.etags.fp != NULL)
    {
	rewind(TagFile.etags.fp);
	while ((line = readLine(TagFile.vLine, TagFile.etags.fp)) != NULL)
	    fputs(line, TagFile.fp);
	fclose(TagFile.etags.fp);
	remove(TagFile.etags.name);
	eFree(TagFile.etags.name);
	TagFile.etags.fp = NULL;
	TagFile.etags.name = NULL;
    }
}

/*----------------------------------------------------------------------------
 *  Tag entry management
 *--------------------------------------------------------------------------*/

/*  This function copies the current line out to a specified file. It has no
 *  effect on the fileGetc() function.  During copying, any '\' characters
 *  are doubled and a leading '^' or trailing '$' is also quoted. End of line
 *  characters (line feed or carriage return) are dropped.
 */
static size_t writeSourceLine( fp, line )
    FILE *const fp;
    const char *const line;
{
    size_t length = 0;
    const char *p;

    /*	Write everything up to, but not including, a line end character.
     */
    for (p = line  ;  *p != '\0'  ;  ++p)
    {
	const int next = *(p + 1);
	const int c = *p;

	if (c == CRETURN  ||  c == NEWLINE)
	    break;

	/*  If character is '\', or a terminal '$', then quote it.
	 */
	if (c == BACKSLASH  ||  c == (Option.backward ? '?' : '/')  ||
	    (c == '$'  &&  (next == NEWLINE  ||  next == CRETURN)))
	{
	    putc(BACKSLASH, fp);
	    ++length;
	}
	putc(c, fp);
	++length;
    }
    return length;
}

/*  Writes "line", stripping leading and duplicate white space.
 */
static size_t writeCompactSourceLine( fp, line )
    FILE *const fp;
    const char *const line;
{
    boolean lineStarted = FALSE;
    size_t  length = 0;
    const char *p;
    int c;

    /*	Write everything up to, but not including, the newline.
     */
    for (p = line, c = *p  ;  c != NEWLINE  &&  c != '\0'  ;  c = *++p)
    {
	if (lineStarted  || ! isspace(c))	/* ignore leading spaces */
	{
	    lineStarted = TRUE;
	    if (isspace(c))
	    {
		int next;

		/*  Consume repeating white space.
		 */
		while (next = *(p+1) , isspace(next)  &&  next != NEWLINE)
		    ++p;
		c = ' ';	/* force space character for any white space */
	    }
	    if (c != CRETURN  ||  *(p + 1) != NEWLINE)
	    {
		putc(c, fp);
		++length;
	    }
	}
    }
    return length;
}

static void rememberMaxLengths( nameLength, lineLength )
    const size_t nameLength;
    const size_t lineLength;
{
    if (nameLength > TagFile.max.tag)
	TagFile.max.tag = nameLength;

    if (lineLength > TagFile.max.line)
	TagFile.max.line = lineLength;
}

static int writeXrefEntry( tag )
    const tagEntryInfo *const tag;
{
    const char *const line =
			readSourceLine(TagFile.vLine, tag->filePosition, NULL);
    int length = fprintf(TagFile.fp, "%-20s %-10s %4lu  %-14s ", tag->name,
			 tag->kindName, tag->lineNumber, tag->sourceFileName);

    length += writeCompactSourceLine(TagFile.fp, line);
    putc(NEWLINE, TagFile.fp);
    ++length;

    return length;
}

/*  Truncates the text line containing the tag at the character following the
 *  tag, providing a character which designates the end of the tag.
 */
static void truncateTagLine( line, token, discardNewline )
    char *const line;
    const char *const token;
    const boolean discardNewline;
{
    char *p = strstr(line, token);

    if (p != NULL)
    {
	p += strlen(token);
	if (*p != '\0'  &&  !(*p == '\n'  &&  discardNewline))
	    ++p;		/* skip past character terminating character */
	*p = '\0';
    }
}

static int writeEtagsEntry( tag )
    const tagEntryInfo *const tag;
{
    int length;

    if (tag->isFileEntry)
	length = fprintf(TagFile.etags.fp, "\177%s\001%lu,0\n",
			 tag->name, tag->lineNumber);
    else
    {
	long seekValue;
	char *const line =
		readSourceLine(TagFile.vLine, tag->filePosition, &seekValue);

	if (tag->truncateLine)
	    truncateTagLine(line, tag->name, TRUE);
	else
	{
	    char *p;

	    for (p = line  ;  *p != '\0'  ;  ++p)
		if (strchr("\n\r", *p) != NULL)
		{
		    *p = '\0';
		    break;
		}
	}
	length = fprintf(TagFile.etags.fp, "%s\177%s\001%lu,%ld\n", line,
			 tag->name, tag->lineNumber, seekValue);
    }
    TagFile.etags.byteCount += length;

    return length;
}

static int addExtensionFlags( tag )
    const tagEntryInfo *const tag;
{
    const char *const prefix = ";\"\t";
    const char *const separator = "\t";
    unsigned int i;
    int length = 0;

    /*  Add an extension flag designating that the type of the tag.
     */
    if (Option.kindLong)
	length += fprintf(TagFile.fp, "%s%s", prefix, tag->kindName);
    else
	length += fprintf(TagFile.fp, "%s%c", prefix, tag->kind);

    /*  If this is a static tag, add the appropriate extension flag.
     */
    if (tag->isFileScope)
	length += fprintf(TagFile.fp, "%sfile:", separator);

    /*  Add any other extension flags.
     */
    for (i = 0  ;  i < tag->otherFields.count  ;  ++i)
    {
	const char *const label = tag->otherFields.label[i];
	const char *const value = tag->otherFields.value[i];

	if (label != NULL)
	    length += fprintf(TagFile.fp, "%s%s:%s", separator,
			      label, value == NULL ? "" : value);
    }

    return length;
}

static int writePatternEntry( tag )
    const tagEntryInfo *const tag;
{
    char *const line = readSourceLine(TagFile.vLine, tag->filePosition, NULL);
    const int searchChar = Option.backward ? '?' : '/';
    boolean newlineTerminated;
    int length = 0;

    if (tag->truncateLine)
	truncateTagLine(line, tag->name, FALSE);
    newlineTerminated = (boolean)(strchr("\n\r", line[strlen(line)-1]) != NULL);

    length += fprintf(TagFile.fp, "%c^", searchChar);
    length += writeSourceLine(TagFile.fp, line);
    length += fprintf(TagFile.fp, "%s%c", newlineTerminated ? "$":"",
		      searchChar);

    return length;
}

static int writeLineNumberEntry( tag )
    const tagEntryInfo *const tag;
{
    return fprintf(TagFile.fp, "%lu", tag->lineNumber);
}

static int writeCtagsEntry( tag )
    const tagEntryInfo *const tag;
{
    int length = fprintf(TagFile.fp, "%s\t%s\t", tag->name,tag->sourceFileName);

    if (tag->lineNumberEntry)
	length += writeLineNumberEntry(tag);
    else
	length += writePatternEntry(tag);

    if (includeExtensionFlags())
	length += addExtensionFlags(tag);

    length += fprintf(TagFile.fp, "\n");

    return length;
}

extern void makeTagEntry( tag )
    const tagEntryInfo *const tag;
{
    int length = 0;

    DebugStatement( debugEntry(tag); )

    if (Option.xref)
    {
	if (! tag->isFileEntry)
	    length = writeXrefEntry(tag);
    }
    else if (Option.etags)
	length = writeEtagsEntry(tag);
    else
	length = writeCtagsEntry(tag);

    ++TagFile.numTags.added;
    rememberMaxLengths(strlen(tag->name), (size_t)length);
}

extern void initTagEntry( e, name )
    tagEntryInfo *const e;
    const char *const name;
{
    e->lineNumberEntry	= (boolean)(Option.locate == EX_LINENUM);
    e->lineNumber	= getFileLine();
    e->filePosition	= getFilePosition();
    e->isFileScope	= FALSE;
    e->isFileEntry	= FALSE;
    e->truncateLine	= FALSE;
    e->sourceFileName	= getFileName();
    e->name		= name;
    e->kindName		= "";
    e->kind		= ' ';
    e->otherFields.count = 0;
    e->otherFields.label = NULL;
    e->otherFields.value = NULL;
}

/* vi:set tabstop=8 shiftwidth=4: */


text:
/******************************************************************************
 *
 * Name: actbl3.h - ACPI Table Definitions
 *
 *****************************************************************************/

/******************************************************************************
 *
 * 1. Copyright Notice
 *
 * Some or all of this work - Copyright (c) 1999 - 2021, Intel Corp.
 * All rights reserved.
 *
 * 2. License
 *
 * 2.1. This is your license from Intel Corp. under its intellectual property
 * rights. You may have additional license terms from the party that provided
 * you this software, covering your right to use that party's intellectual
 * property rights.
 *
 * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a
 * copy of the source code appearing in this file ("Covered Code") an
 * irrevocable, perpetual, worldwide license under Intel's copyrights in the
 * base code distributed originally by Intel ("Original Intel Code") to copy,
 * make derivatives, distribute, use and display any portion of the Covered
 * Code in any form, with the right to sublicense such rights; and
 *
 * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent
 * license (with the right to sublicense), under only those claims of Intel
 * patents that are infringed by the Original Intel Code, to make, use, sell,
 * offer to sell, and import the Covered Code and derivative works thereof
 * solely to the minimum extent necessary to exercise the above copyright
 * license, and in no event shall the patent license extend to any additions
 * to or modifications of the Original Intel Code. No other license or right
 * is granted directly or by implication, estoppel or otherwise;
 *
 * The above copyright and patent license is granted only if the following
 * conditions are met:
 *
 * 3. Conditions
 *
 * 3.1. Redistribution of Source with Rights to Further Distribute Source.
 * Redistribution of source code of any substantial portion of the Covered
 * Code or modification with rights to further distribute source must include
 * the above Copyright Notice, the above License, this list of Conditions,
 * and the following Disclaimer and Export Compliance provision. In addition,
 * Licensee must cause all Covered Code to which Licensee contributes to
 * contain a file documenting the changes Licensee made to create that Covered
 * Code and the date of any change. Licensee must include in that file the
 * documentation of any changes made by any predecessor Licensee. Licensee
 * must include a prominent statement that the modification is derived,
 * directly or indirectly, from Original Intel Code.
 *
 * 3.2. Redistribution of Source with no Rights to Further Distribute Source.
 * Redistribution of source code of any substantial portion of the Covered
 * Code or modification without rights to further distribute source must
 * include the following Disclaimer and Export Compliance provision in the
 * documentation and/or other materials provided with distribution. In
 * addition, Licensee may not authorize further sublicense of source of any
 * portion of the Covered Code, and must include terms to the effect that the
 * license from Licensee to its licensee is limited to the intellectual
 * property embodied in the software Licensee provides to its licensee, and
 * not to intellectual property embodied in modifications its licensee may
 * make.
 *
 * 3.3. Redistribution of Executable. Redistribution in executable form of any
 * substantial portion of the Covered Code or modification must reproduce the
 * above Copyright Notice, and the following Disclaimer and Export Compliance
 * provision in the documentation and/or other materials provided with the
 * distribution.
 *
 * 3.4. Intel retains all right, title, and interest in and to the Original
 * Intel Code.
 *
 * 3.5. Neither the name Intel nor any other trademark owned or controlled by
 * Intel shall be used in advertising or otherwise to promote the sale, use or
 * other dealings in products derived from or relating to the Covered Code
 * without prior written authorization from Intel.
 *
 * 4. Disclaimer and Export Compliance
 *
 * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED
 * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE
 * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE,
 * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY
 * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY
 * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A
 * PARTICULAR PURPOSE.
 *
 * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES
 * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR
 * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT,
 * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY
 * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL
 * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS
 * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY
 * LIMITED REMEDY.
 *
 * 4.3. Licensee shall not export, either directly or indirectly, any of this
 * software or system incorporating such software without first obtaining any
 * required license or other approval from the U. S. Department of Commerce or
 * any other agency or department of the United States Government. In the
 * event Licensee exports any such software from the United States or
 * re-exports any such software from a foreign destination, Licensee shall
 * ensure that the distribution and export/re-export of the software is in
 * compliance with all laws, regulations, orders, or other restrictions of the
 * U.S. Export Administration Regulations. Licensee agrees that neither it nor
 * any of its subsidiaries will export/re-export any technical data, process,
 * software, or service, directly or indirectly, to any country for which the
 * United States government or any agency thereof requires an export license,
 * other governmental approval, or letter of assurance, without first obtaining
 * such license, approval or letter.
 *
 *****************************************************************************
 *
 * Alternatively, you may choose to be licensed under the terms of the
 * following license:
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions, and the following disclaimer,
 *    without modification.
 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
 *    substantially similar to the "NO WARRANTY" disclaimer below
 *    ("Disclaimer") and any redistribution must be conditioned upon
 *    including a substantially similar Disclaimer requirement for further
 *    binary redistribution.
 * 3. Neither the names of the above-listed copyright holders nor the names
 *    of any 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.
 *
 * Alternatively, you may choose to be licensed under the terms of the
 * GNU General Public License ("GPL") version 2 as published by the Free
 * Software Foundation.
 *
 *****************************************************************************/

#ifndef __ACTBL3_H__
#define __ACTBL3_H__

/*******************************************************************************
 *
 * Additional ACPI Tables
 *
 * These tables are not consumed directly by the ACPICA subsystem, but are
 * included here to support device drivers and the AML disassembler.
 *
 ******************************************************************************/

/*
 * Values for description table header signatures for tables defined in this
 * file. Useful because they make it more difficult to inadvertently type in
 * the wrong signature.
 */
#define ACPI_SIG_SLIC           "SLIC"      /* Software Licensing Description Table */
#define ACPI_SIG_SLIT           "SLIT"      /* System Locality Distance Information Table */
#define ACPI_SIG_SPCR           "SPCR"      /* Serial Port Console Redirection table */
#define ACPI_SIG_SPMI           "SPMI"      /* Server Platform Management Interface table */
#define ACPI_SIG_SRAT           "SRAT"      /* System Resource Affinity Table */
#define ACPI_SIG_STAO           "STAO"      /* Status Override table */
#define ACPI_SIG_TCPA           "TCPA"      /* Trusted Computing Platform Alliance table */
#define ACPI_SIG_TPM2           "TPM2"      /* Trusted Platform Module 2.0 H/W interface table */
#define ACPI_SIG_UEFI           "UEFI"      /* Uefi Boot Optimization Table */
#define ACPI_SIG_VIOT           "VIOT"      /* Virtual I/O Translation Table */
#define ACPI_SIG_WAET           "WAET"      /* Windows ACPI Emulated devices Table */
#define ACPI_SIG_WDAT           "WDAT"      /* Watchdog Action Table */
#define ACPI_SIG_WDDT           "WDDT"      /* Watchdog Timer Description Table */
#define ACPI_SIG_WDRT           "WDRT"      /* Watchdog Resource Table */
#define ACPI_SIG_WPBT           "WPBT"      /* Windows Platform Binary Table */
#define ACPI_SIG_WSMT           "WSMT"      /* Windows SMM Security Mitigations Table */
#define ACPI_SIG_XENV           "XENV"      /* Xen Environment table */
#define ACPI_SIG_XXXX           "XXXX"      /* Intermediate AML header for ASL/ASL+ converter */

/*
 * All tables must be byte-packed to match the ACPI specification, since
 * the tables are provided by the system BIOS.
 */
#pragma pack(1)

/*
 * Note: C bitfields are not used for this reason:
 *
 * "Bitfields are great and easy to read, but unfortunately the C language
 * does not specify the layout of bitfields in memory, which means they are
 * essentially useless for dealing with packed data in on-disk formats or
 * binary wire protocols." (Or ACPI tables and buffers.) "If you ask me,
 * this decision was a design error in C. Ritchie could have picked an order
 * and stuck with it." Norman Ramsey.
 * See http://stackoverflow.com/a/1053662/41661
 */

/*******************************************************************************
 *
 * SLIC - Software Licensing Description Table
 *
 * Conforms to "Microsoft Software Licensing Tables (SLIC and MSDM)",
 * November 29, 2011. Copyright 2011 Microsoft
 *
 ******************************************************************************/

/* Basic SLIC table is only the common ACPI header */

typedef struct acpi_table_slic
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */

} ACPI_TABLE_SLIC;

/*******************************************************************************
 *
 * SLIT - System Locality Distance Information Table
 *        Version 1
 *
 ******************************************************************************/

typedef struct acpi_table_slit
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT64                  LocalityCount;
    UINT8                   Entry[1];           /* Real size = localities^2 */

} ACPI_TABLE_SLIT;

/*******************************************************************************
 *
 * SPCR - Serial Port Console Redirection table
 *        Version 2
 *
 * Conforms to "Serial Port Console Redirection Table",
 * Version 1.03, August 10, 2015
 *
 ******************************************************************************/

typedef struct acpi_table_spcr
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT8                   InterfaceType;      /* 0=full 16550, 1=subset of 16550 */
    UINT8                   Reserved[3];
    ACPI_GENERIC_ADDRESS    SerialPort;
    UINT8                   InterruptType;
    UINT8                   PcInterrupt;
    UINT32                  Interrupt;
    UINT8                   BaudRate;
    UINT8                   Parity;
    UINT8                   StopBits;
    UINT8                   FlowControl;
    UINT8                   TerminalType;
    UINT8                   Reserved1;
    UINT16                  PciDeviceId;
    UINT16                  PciVendorId;
    UINT8                   PciBus;
    UINT8                   PciDevice;
    UINT8                   PciFunction;
    UINT32                  PciFlags;
    UINT8                   PciSegment;
    UINT32                  Reserved2;

} ACPI_TABLE_SPCR;

/* Masks for PciFlags field above */

#define ACPI_SPCR_DO_NOT_DISABLE    (1)

/* Values for Interface Type: See the definition of the DBG2 table */

/*******************************************************************************
 *
 * SPMI - Server Platform Management Interface table
 *        Version 5
 *
 * Conforms to "Intelligent Platform Management Interface Specification
 * Second Generation v2.0", Document Revision 1.0, February 12, 2004 with
 * June 12, 2009 markup.
 *
 ******************************************************************************/

typedef struct acpi_table_spmi
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT8                   InterfaceType;
    UINT8                   Reserved;           /* Must be 1 */
    UINT16                  SpecRevision;       /* Version of IPMI */
    UINT8                   InterruptType;
    UINT8                   GpeNumber;          /* GPE assigned */
    UINT8                   Reserved1;
    UINT8                   PciDeviceFlag;
    UINT32                  Interrupt;
    ACPI_GENERIC_ADDRESS    IpmiRegister;
    UINT8                   PciSegment;
    UINT8                   PciBus;
    UINT8                   PciDevice;
    UINT8                   PciFunction;
    UINT8                   Reserved2;

} ACPI_TABLE_SPMI;

/* Values for InterfaceType above */

enum AcpiSpmiInterfaceTypes
{
    ACPI_SPMI_NOT_USED              = 0,
    ACPI_SPMI_KEYBOARD              = 1,
    ACPI_SPMI_SMI                   = 2,
    ACPI_SPMI_BLOCK_TRANSFER        = 3,
    ACPI_SPMI_SMBUS                 = 4,
    ACPI_SPMI_RESERVED              = 5         /* 5 and above are reserved */
};

/*******************************************************************************
 *
 * SRAT - System Resource Affinity Table
 *        Version 3
 *
 ******************************************************************************/

typedef struct acpi_table_srat
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT32                  TableRevision;      /* Must be value '1' */
    UINT64                  Reserved;           /* Reserved, must be zero */

} ACPI_TABLE_SRAT;

/* Values for subtable type in ACPI_SUBTABLE_HEADER */

enum AcpiSratType
{
    ACPI_SRAT_TYPE_CPU_AFFINITY         = 0,
    ACPI_SRAT_TYPE_MEMORY_AFFINITY      = 1,
    ACPI_SRAT_TYPE_X2APIC_CPU_AFFINITY  = 2,
    ACPI_SRAT_TYPE_GICC_AFFINITY        = 3,
    ACPI_SRAT_TYPE_GIC_ITS_AFFINITY     = 4, /* ACPI 6.2 */
    ACPI_SRAT_TYPE_GENERIC_AFFINITY     = 5, /* ACPI 6.3 */
    ACPI_SRAT_TYPE_RESERVED             = 6  /* 5 and greater are reserved */
};

/*
 * SRAT Subtables, correspond to Type in ACPI_SUBTABLE_HEADER
 */

/* 0: Processor Local APIC/SAPIC Affinity */

typedef struct acpi_srat_cpu_affinity
{
    ACPI_SUBTABLE_HEADER    Header;
    UINT8                   ProximityDomainLo;
    UINT8                   ApicId;
    UINT32                  Flags;
    UINT8                   LocalSapicEid;
    UINT8                   ProximityDomainHi[3];
    UINT32                  ClockDomain;

} ACPI_SRAT_CPU_AFFINITY;

/* Flags */

#define ACPI_SRAT_CPU_USE_AFFINITY  (1)         /* 00: Use affinity structure */

/* 1: Memory Affinity */

typedef struct acpi_srat_mem_affinity
{
    ACPI_SUBTABLE_HEADER    Header;
    UINT32                  ProximityDomain;
    UINT16                  Reserved;           /* Reserved, must be zero */
    UINT64                  BaseAddress;
    UINT64                  Length;
    UINT32                  Reserved1;
    UINT32                  Flags;
    UINT64                  Reserved2;          /* Reserved, must be zero */

} ACPI_SRAT_MEM_AFFINITY;

/* Flags */

#define ACPI_SRAT_MEM_ENABLED       (1)         /* 00: Use affinity structure */
#define ACPI_SRAT_MEM_HOT_PLUGGABLE (1<<1)      /* 01: Memory region is hot pluggable */
#define ACPI_SRAT_MEM_NON_VOLATILE  (1<<2)      /* 02: Memory region is non-volatile */

/* 2: Processor Local X2_APIC Affinity (ACPI 4.0) */

typedef struct acpi_srat_x2apic_cpu_affinity
{
    ACPI_SUBTABLE_HEADER    Header;
    UINT16                  Reserved;           /* Reserved, must be zero */
    UINT32                  ProximityDomain;
    UINT32                  ApicId;
    UINT32                  Flags;
    UINT32                  ClockDomain;
    UINT32                  Reserved2;

} ACPI_SRAT_X2APIC_CPU_AFFINITY;

/* Flags for ACPI_SRAT_CPU_AFFINITY and ACPI_SRAT_X2APIC_CPU_AFFINITY */

#define ACPI_SRAT_CPU_ENABLED       (1)         /* 00: Use affinity structure */

/* 3: GICC Affinity (ACPI 5.1) */

typedef struct acpi_srat_gicc_affinity
{
    ACPI_SUBTABLE_HEADER    Header;
    UINT32                  ProximityDomain;
    UINT32                  AcpiProcessorUid;
    UINT32                  Flags;
    UINT32                  ClockDomain;

} ACPI_SRAT_GICC_AFFINITY;

/* Flags for ACPI_SRAT_GICC_AFFINITY */

#define ACPI_SRAT_GICC_ENABLED     (1)         /* 00: Use affinity structure */

/* 4: GCC ITS Affinity (ACPI 6.2) */

typedef struct acpi_srat_gic_its_affinity
{
    ACPI_SUBTABLE_HEADER    Header;
    UINT32                  ProximityDomain;
    UINT16                  Reserved;
    UINT32                  ItsId;

} ACPI_SRAT_GIC_ITS_AFFINITY;

/* 5: Generic Initiator Affinity Structure (ACPI 6.3) */

typedef struct acpi_srat_generic_affinity
{
    ACPI_SUBTABLE_HEADER    Header;
    UINT8                   Reserved;
    UINT8                   DeviceHandleType;
    UINT32                  ProximityDomain;
    UINT8                   DeviceHandle[16];
    UINT32                  Flags;
    UINT32                  Reserved1;

} ACPI_SRAT_GENERIC_AFFINITY;

/* Flags for ACPI_SRAT_GENERIC_AFFINITY */

#define ACPI_SRAT_GENERIC_AFFINITY_ENABLED     (1)      /* 00: Use affinity structure */
#define ACPI_SRAT_ARCHITECTURAL_TRANSACTIONS   (1<<1)   /* ACPI 6.4 */

/*******************************************************************************
 *
 * STAO - Status Override Table (_STA override) - ACPI 6.0
 *        Version 1
 *
 * Conforms to "ACPI Specification for Status Override Table"
 * 6 January 2015
 *
 ******************************************************************************/

typedef struct acpi_table_stao
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT8                   IgnoreUart;

} ACPI_TABLE_STAO;

/*******************************************************************************
 *
 * TCPA - Trusted Computing Platform Alliance table
 *        Version 2
 *
 * TCG Hardware Interface Table for TPM 1.2 Clients and Servers
 *
 * Conforms to "TCG ACPI Specification, Family 1.2 and 2.0",
 * Version 1.2, Revision 8
 * February 27, 2017
 *
 * NOTE: There are two versions of the table with the same signature --
 * the client version and the server version. The common PlatformClass
 * field is used to differentiate the two types of tables.
 *
 ******************************************************************************/

typedef struct acpi_table_tcpa_hdr
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT16                  PlatformClass;

} ACPI_TABLE_TCPA_HDR;

/*
 * Values for PlatformClass above.
 * This is how the client and server subtables are differentiated
 */
#define ACPI_TCPA_CLIENT_TABLE          0
#define ACPI_TCPA_SERVER_TABLE          1

typedef struct acpi_table_tcpa_client
{
    UINT32                  MinimumLogLength;   /* Minimum length for the event log area */
    UINT64                  LogAddress;         /* Address of the event log area */

} ACPI_TABLE_TCPA_CLIENT;

typedef struct acpi_table_tcpa_server
{
    UINT16                  Reserved;
    UINT64                  MinimumLogLength;   /* Minimum length for the event log area */
    UINT64                  LogAddress;         /* Address of the event log area */
    UINT16                  SpecRevision;
    UINT8                   DeviceFlags;
    UINT8                   InterruptFlags;
    UINT8                   GpeNumber;
    UINT8                   Reserved2[3];
    UINT32                  GlobalInterrupt;
    ACPI_GENERIC_ADDRESS    Address;
    UINT32                  Reserved3;
    ACPI_GENERIC_ADDRESS    ConfigAddress;
    UINT8                   Group;
    UINT8                   Bus;                /* PCI Bus/Segment/Function numbers */
    UINT8                   Device;
    UINT8                   Function;

} ACPI_TABLE_TCPA_SERVER;

/* Values for DeviceFlags above */

#define ACPI_TCPA_PCI_DEVICE            (1)
#define ACPI_TCPA_BUS_PNP               (1<<1)
#define ACPI_TCPA_ADDRESS_VALID         (1<<2)

/* Values for InterruptFlags above */

#define ACPI_TCPA_INTERRUPT_MODE        (1)
#define ACPI_TCPA_INTERRUPT_POLARITY    (1<<1)
#define ACPI_TCPA_SCI_VIA_GPE           (1<<2)
#define ACPI_TCPA_GLOBAL_INTERRUPT      (1<<3)

/*******************************************************************************
 *
 * TPM2 - Trusted Platform Module (TPM) 2.0 Hardware Interface Table
 *        Version 4
 *
 * TCG Hardware Interface Table for TPM 2.0 Clients and Servers
 *
 * Conforms to "TCG ACPI Specification, Family 1.2 and 2.0",
 * Version 1.2, Revision 8
 * February 27, 2017
 *
 ******************************************************************************/

/* Revision 3 */

typedef struct acpi_table_tpm23
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT32                  Reserved;
    UINT64                  ControlAddress;
    UINT32                  StartMethod;

} ACPI_TABLE_TPM23;

/* Value for StartMethod above */

#define ACPI_TPM23_ACPI_START_METHOD                 2

/*
 * Optional trailer for revision 3. If start method is 2, there is a 4 byte
 * reserved area of all zeros.
 */
typedef struct acpi_tmp23_trailer
{
    UINT32                  Reserved;

} ACPI_TPM23_TRAILER;

/* Revision 4 */

typedef struct acpi_table_tpm2
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT16                  PlatformClass;
    UINT16                  Reserved;
    UINT64                  ControlAddress;
    UINT32                  StartMethod;

    /* Platform-specific data follows */

} ACPI_TABLE_TPM2;

/* Values for StartMethod above */

#define ACPI_TPM2_NOT_ALLOWED                       0
#define ACPI_TPM2_RESERVED1                         1
#define ACPI_TPM2_START_METHOD                      2
#define ACPI_TPM2_RESERVED3                         3
#define ACPI_TPM2_RESERVED4                         4
#define ACPI_TPM2_RESERVED5                         5
#define ACPI_TPM2_MEMORY_MAPPED                     6
#define ACPI_TPM2_COMMAND_BUFFER                    7
#define ACPI_TPM2_COMMAND_BUFFER_WITH_START_METHOD  8
#define ACPI_TPM2_RESERVED9                         9
#define ACPI_TPM2_RESERVED10                        10
#define ACPI_TPM2_COMMAND_BUFFER_WITH_ARM_SMC       11  /* V1.2 Rev 8 */
#define ACPI_TPM2_RESERVED                          12

/* Optional trailer appears after any StartMethod subtables */

typedef struct acpi_tpm2_trailer
{
    UINT8                   MethodParameters[12];
    UINT32                  MinimumLogLength;   /* Minimum length for the event log area */
    UINT64                  LogAddress;         /* Address of the event log area */

} ACPI_TPM2_TRAILER;

/*
 * Subtables (StartMethod-specific)
 */

/* 11: Start Method for ARM SMC (V1.2 Rev 8) */

typedef struct acpi_tpm2_arm_smc
{
    UINT32                  GlobalInterrupt;
    UINT8                   InterruptFlags;
    UINT8                   OperationFlags;
    UINT16                  Reserved;
    UINT32                  FunctionId;

} ACPI_TPM2_ARM_SMC;

/* Values for InterruptFlags above */

#define ACPI_TPM2_INTERRUPT_SUPPORT     (1)

/* Values for OperationFlags above */

#define ACPI_TPM2_IDLE_SUPPORT          (1)

/*******************************************************************************
 *
 * UEFI - UEFI Boot optimization Table
 *        Version 1
 *
 * Conforms to "Unified Extensible Firmware Interface Specification",
 * Version 2.3, May 8, 2009
 *
 ******************************************************************************/

typedef struct acpi_table_uefi
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT8                   Identifier[16];     /* UUID identifier */
    UINT16                  DataOffset;         /* Offset of remaining data in table */

} ACPI_TABLE_UEFI;

/*******************************************************************************
 *
 * VIOT - Virtual I/O Translation Table
 *        Version 1
 *
 ******************************************************************************/

typedef struct acpi_table_viot
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT16                  NodeCount;
    UINT16                  NodeOffset;
    UINT8                   Reserved[8];

} ACPI_TABLE_VIOT;

/* VIOT subtable header */

typedef struct acpi_viot_header
{
    UINT8                   Type;
    UINT8                   Reserved;
    UINT16                  Length;

} ACPI_VIOT_HEADER;

/* Values for Type field above */

enum AcpiViotNodeType
{
    ACPI_VIOT_NODE_PCI_RANGE            = 0x01,
    ACPI_VIOT_NODE_MMIO                 = 0x02,
    ACPI_VIOT_NODE_VIRTIO_IOMMU_PCI     = 0x03,
    ACPI_VIOT_NODE_VIRTIO_IOMMU_MMIO    = 0x04,
    ACPI_VIOT_RESERVED                  = 0x05
};

/* VIOT subtables */

typedef struct acpi_viot_pci_range
{
    ACPI_VIOT_HEADER        Header;
    UINT32                  EndpointStart;
    UINT16                  SegmentStart;
    UINT16                  SegmentEnd;
    UINT16                  BdfStart;
    UINT16                  BdfEnd;
    UINT16                  OutputNode;
    UINT8                   Reserved[6];

} ACPI_VIOT_PCI_RANGE;

typedef struct acpi_viot_mmio
{
    ACPI_VIOT_HEADER        Header;
    UINT32                  Endpoint;
    UINT64                  BaseAddress;
    UINT16                  OutputNode;
    UINT8                   Reserved[6];

} ACPI_VIOT_MMIO;

typedef struct acpi_viot_virtio_iommu_pci
{
    ACPI_VIOT_HEADER        Header;
    UINT16                  Segment;
    UINT16                  Bdf;
    UINT8                   Reserved[8];

} ACPI_VIOT_VIRTIO_IOMMU_PCI;

typedef struct acpi_viot_virtio_iommu_mmio
{
    ACPI_VIOT_HEADER        Header;
    UINT8                   Reserved[4];
    UINT64                  BaseAddress;

} ACPI_VIOT_VIRTIO_IOMMU_MMIO;

/*******************************************************************************
 *
 * WAET - Windows ACPI Emulated devices Table
 *        Version 1
 *
 * Conforms to "Windows ACPI Emulated Devices Table", version 1.0, April 6, 2009
 *
 ******************************************************************************/

typedef struct acpi_table_waet
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT32                  Flags;

} ACPI_TABLE_WAET;

/* Masks for Flags field above */

#define ACPI_WAET_RTC_NO_ACK        (1)         /* RTC requires no int acknowledge */
#define ACPI_WAET_TIMER_ONE_READ    (1<<1)      /* PM timer requires only one read */

/*******************************************************************************
 *
 * WDAT - Watchdog Action Table
 *        Version 1
 *
 * Conforms to "Hardware Watchdog Timers Design Specification",
 * Copyright 2006 Microsoft Corporation.
 *
 ******************************************************************************/

typedef struct acpi_table_wdat
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT32                  HeaderLength;       /* Watchdog Header Length */
    UINT16                  PciSegment;         /* PCI Segment number */
    UINT8                   PciBus;             /* PCI Bus number */
    UINT8                   PciDevice;          /* PCI Device number */
    UINT8                   PciFunction;        /* PCI Function number */
    UINT8                   Reserved[3];
    UINT32                  TimerPeriod;        /* Period of one timer count (msec) */
    UINT32                  MaxCount;           /* Maximum counter value supported */
    UINT32                  MinCount;           /* Minimum counter value */
    UINT8                   Flags;
    UINT8                   Reserved2[3];
    UINT32                  Entries;            /* Number of watchdog entries that follow */

} ACPI_TABLE_WDAT;

/* Masks for Flags field above */

#define ACPI_WDAT_ENABLED           (1)
#define ACPI_WDAT_STOPPED           0x80

/* WDAT Instruction Entries (actions) */

typedef struct acpi_wdat_entry
{
    UINT8                   Action;
    UINT8                   Instruction;
    UINT16                  Reserved;
    ACPI_GENERIC_ADDRESS    RegisterRegion;
    UINT32                  Value;              /* Value used with Read/Write register */
    UINT32                  Mask;               /* Bitmask required for this register instruction */

} ACPI_WDAT_ENTRY;

/* Values for Action field above */

enum AcpiWdatActions
{
    ACPI_WDAT_RESET                 = 1,
    ACPI_WDAT_GET_CURRENT_COUNTDOWN = 4,
    ACPI_WDAT_GET_COUNTDOWN         = 5,
    ACPI_WDAT_SET_COUNTDOWN         = 6,
    ACPI_WDAT_GET_RUNNING_STATE     = 8,
    ACPI_WDAT_SET_RUNNING_STATE     = 9,
    ACPI_WDAT_GET_STOPPED_STATE     = 10,
    ACPI_WDAT_SET_STOPPED_STATE     = 11,
    ACPI_WDAT_GET_REBOOT            = 16,
    ACPI_WDAT_SET_REBOOT            = 17,
    ACPI_WDAT_GET_SHUTDOWN          = 18,
    ACPI_WDAT_SET_SHUTDOWN          = 19,
    ACPI_WDAT_GET_STATUS            = 32,
    ACPI_WDAT_SET_STATUS            = 33,
    ACPI_WDAT_ACTION_RESERVED       = 34    /* 34 and greater are reserved */
};

/* Values for Instruction field above */

enum AcpiWdatInstructions
{
    ACPI_WDAT_READ_VALUE            = 0,
    ACPI_WDAT_READ_COUNTDOWN        = 1,
    ACPI_WDAT_WRITE_VALUE           = 2,
    ACPI_WDAT_WRITE_COUNTDOWN       = 3,
    ACPI_WDAT_INSTRUCTION_RESERVED  = 4,    /* 4 and greater are reserved */
    ACPI_WDAT_PRESERVE_REGISTER     = 0x80  /* Except for this value */
};

/*******************************************************************************
 *
 * WDDT - Watchdog Descriptor Table
 *        Version 1
 *
 * Conforms to "Using the Intel ICH Family Watchdog Timer (WDT)",
 * Version 001, September 2002
 *
 ******************************************************************************/

typedef struct acpi_table_wddt
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT16                  SpecVersion;
    UINT16                  TableVersion;
    UINT16                  PciVendorId;
    ACPI_GENERIC_ADDRESS    Address;
    UINT16                  MaxCount;           /* Maximum counter value supported */
    UINT16                  MinCount;           /* Minimum counter value supported */
    UINT16                  Period;
    UINT16                  Status;
    UINT16                  Capability;

} ACPI_TABLE_WDDT;

/* Flags for Status field above */

#define ACPI_WDDT_AVAILABLE     (1)
#define ACPI_WDDT_ACTIVE        (1<<1)
#define ACPI_WDDT_TCO_OS_OWNED  (1<<2)
#define ACPI_WDDT_USER_RESET    (1<<11)
#define ACPI_WDDT_WDT_RESET     (1<<12)
#define ACPI_WDDT_POWER_FAIL    (1<<13)
#define ACPI_WDDT_UNKNOWN_RESET (1<<14)

/* Flags for Capability field above */

#define ACPI_WDDT_AUTO_RESET    (1)
#define ACPI_WDDT_ALERT_SUPPORT (1<<1)

/*******************************************************************************
 *
 * WDRT - Watchdog Resource Table
 *        Version 1
 *
 * Conforms to "Watchdog Timer Hardware Requirements for Windows Server 2003",
 * Version 1.01, August 28, 2006
 *
 ******************************************************************************/

typedef struct acpi_table_wdrt
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    ACPI_GENERIC_ADDRESS    ControlRegister;
    ACPI_GENERIC_ADDRESS    CountRegister;
    UINT16                  PciDeviceId;
    UINT16                  PciVendorId;
    UINT8                   PciBus;             /* PCI Bus number */
    UINT8                   PciDevice;          /* PCI Device number */
    UINT8                   PciFunction;        /* PCI Function number */
    UINT8                   PciSegment;         /* PCI Segment number */
    UINT16                  MaxCount;           /* Maximum counter value supported */
    UINT8                   Units;

} ACPI_TABLE_WDRT;

/*******************************************************************************
 *
 * WPBT - Windows Platform Environment Table (ACPI 6.0)
 *        Version 1
 *
 * Conforms to "Windows Platform Binary Table (WPBT)" 29 November 2011
 *
 ******************************************************************************/

typedef struct acpi_table_wpbt
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT32                  HandoffSize;
    UINT64                  HandoffAddress;
    UINT8                   Layout;
    UINT8                   Type;
    UINT16                  ArgumentsLength;

} ACPI_TABLE_WPBT;

/*******************************************************************************
 *
 * WSMT - Windows SMM Security Mitigations Table
 *        Version 1
 *
 * Conforms to "Windows SMM Security Mitigations Table",
 * Version 1.0, April 18, 2016
 *
 ******************************************************************************/

typedef struct acpi_table_wsmt
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT32                  ProtectionFlags;

} ACPI_TABLE_WSMT;

/* Flags for ProtectionFlags field above */

#define ACPI_WSMT_FIXED_COMM_BUFFERS                (1)
#define ACPI_WSMT_COMM_BUFFER_NESTED_PTR_PROTECTION (2)
#define ACPI_WSMT_SYSTEM_RESOURCE_PROTECTION        (4)

/*******************************************************************************
 *
 * XENV - Xen Environment Table (ACPI 6.0)
 *        Version 1
 *
 * Conforms to "ACPI Specification for Xen Environment Table" 4 January 2015
 *
 ******************************************************************************/

typedef struct acpi_table_xenv
{
    ACPI_TABLE_HEADER       Header;             /* Common ACPI table header */
    UINT64                  GrantTableAddress;
    UINT64                  GrantTableSize;
    UINT32                  EventInterrupt;
    UINT8                   EventFlags;

} ACPI_TABLE_XENV;

/* Reset to default packing */

#pragma pack()

#endif /* __ACTBL3_H__ */


text: {{ include.caption }}


text:
@implementation UILocalNotification (Helper)

+(void)createNotificationWithMessage:(NSString*)message {

    UILocalNotification* notification = [[UILocalNotification alloc] init];
    notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:0];
    notification.timeZone = [NSTimeZone defaultTimeZone];
    notification.alertBody = message;
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

@end


text:
package org.xdevs23.android.content.share;

import android.app.Activity;
import android.content.Intent;

public class ShareUtil {

    private ShareUtil() {

    }

    public static void shareText(String title, String text, Activity activity) {
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra
                (Intent.EXTRA_TEXT, text);
        activity.startActivity(Intent.createChooser(shareIntent, title));
    }

}


text:
package com.snowplowanalytics;

import com.snowplowanalytics.snowplow.tracker.Snowplow;
import com.snowplowanalytics.snowplow.tracker.Subject;
import com.snowplowanalytics.snowplow.tracker.Tracker;
import com.snowplowanalytics.snowplow.tracker.configuration.EmitterConfiguration;
import com.snowplowanalytics.snowplow.tracker.configuration.NetworkConfiguration;
import com.snowplowanalytics.snowplow.tracker.configuration.TrackerConfiguration;
import com.snowplowanalytics.snowplow.tracker.events.*;
import com.snowplowanalytics.snowplow.tracker.payload.SelfDescribingJson;

import java.util.Collections;
import static java.util.Collections.singletonList;
import java.util.List;

public class Main {

    public static String getUrlFromArgs(String[] args) {
        if (args == null || args.length < 1) {
            throw new IllegalArgumentException("Collector URL is required");
        }
        return args[0];
    }

    public static void main(String[] args) throws InterruptedException {
        String collectorEndpoint = getUrlFromArgs(args);

        // the application id to attach to events
        String appId = "java-tracker-sample-console-app";
        // the namespace to attach to events
        String namespace = "demo";

        // The easiest way to build a tracker is with configuration classes
        TrackerConfiguration trackerConfig = new TrackerConfiguration(namespace, appId);
        NetworkConfiguration networkConfig = new NetworkConfiguration(collectorEndpoint);
        EmitterConfiguration emitterConfig = new EmitterConfiguration().batchSize(4); // send batches of 4 events. In production this number should be higher, depending on the size/event volume

        // We need a tracker to turn our events into something a Snowplow collector can understand
        final Tracker tracker = Snowplow.createTracker(trackerConfig, networkConfig, emitterConfig);

        System.out.println("Sending events to " + collectorEndpoint);
        System.out.println("Using tracker version " + tracker.getTrackerVersion());

        // This is an example of a custom context entity
        List<SelfDescribingJson> context = singletonList(
            new SelfDescribingJson(
                "iglu:com.snowplowanalytics.iglu/anything-c/jsonschema/1-0-0",
                Collections.singletonMap("foo", "bar")));

        // This is an example of a eventSubject for adding user data
        Subject eventSubject = new Subject();
        eventSubject.setUserId("example@snowplowanalytics.com");
        eventSubject.setLanguage("EN");

        // This is a sample page view event
        // the eventSubject has been included in this event
        PageView pageViewEvent = PageView.builder()
            .pageTitle("Snowplow Analytics")
            .pageUrl("https://www.snowplowanalytics.com")
            .referrer("https://www.google.com")
            .customContext(context)
            .subject(eventSubject)
            .build();

        // EcommerceTransactions will be deprecated soon: we advise using SelfDescribing events instead
        // EcommerceTransactionItems are tracked as part of an EcommerceTransaction event
        // They are processed into separate events during the `track()` call
        EcommerceTransactionItem item = EcommerceTransactionItem.builder()
            .itemId("order_id")
            .sku("sku")
            .price(1.0)
            .quantity(2)
            .name("name")
            .category("category")
            .currency("currency")
            .customContext(context)
            .build();

        // EcommerceTransaction event
        EcommerceTransaction ecommerceTransaction = EcommerceTransaction.builder()
            .orderId("order_id")
            .totalValue(1.0)
            .affiliation("affiliation")
            .taxValue(2.0)
            .shipping(3.0)
            .city("city")
            .state("state")
            .country("country")
            .currency("currency")
            .items(item) // EcommerceTransactionItem events are added to a parent EcommerceTransaction here
            .customContext(context)
            .build();

        // This is an example of a custom SelfDescribing event based on a schema
        SelfDescribing selfDescribing = SelfDescribing.builder()
            .eventData(new SelfDescribingJson(
                    "iglu:com.snowplowanalytics.iglu/anything-a/jsonschema/1-0-0",
                    Collections.singletonMap("foo", "bar")
            ))
            .customContext(context)
            .build();

        // This is an example of a ScreenView event which will be translated into a SelfDescribing event
        ScreenView screenView = ScreenView.builder()
            .name("name")
            .id("id")
            .customContext(context)
            .build();

        // This is an example of a Timing event which will be translated into a SelfDescribing event
        Timing timing = Timing.builder()
            .category("category")
            .label("label")
            .variable("variable")
            .timing(10)
            .customContext(context)
            .build();

        // This is an example of a Structured event
        Structured structured = Structured.builder()
                .category("category")
                .action("action")
                .label("label")
                .property("property")
                .value(12.34)
                .customContext(context)
                .build();

        tracker.track(pageViewEvent); // the .track method schedules the event for delivery to Snowplow
        tracker.track(ecommerceTransaction); // This will track two events
        tracker.track(selfDescribing);
        tracker.track(screenView);
        tracker.track(timing);
        tracker.track(structured);

        // Will close all threads and force send remaining events
        tracker.close();
        Thread.sleep(5000);

        System.out.println("Tracked 7 events");
    }

}


text:
Carte des magasins

								<input type="button" value="Centrer sur ma position"
									class="button locate-me">


text:
:mod:`apscheduler.jobstores.ram_store`
=============================================

.. automodule:: apscheduler.jobstores.ram_store

Module Contents
---------------

.. autoclass:: RAMJobStore
    :members:


text:
package org.broadinstitute.hellbender.cmdline;

import java.lang.annotation.*;

/**
 * Used to annotate a field in a CommandLineProgram that holds a instance containing @Option-annotated
 * fields.  To set a value for a nested option on the command line, use <member-name>.<option>=value.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
@Inherited
public @interface ArgumentCollection {
    /** Text that appears for this group of options in text describing usage of the command line program. */
    String doc() default "";
}


text:
/* Original interface by Yuhang Liao,
 * annotation and imports by Sarah Abowitz.
 */

package codeu.chat.server;

import codeu.chat.common.ConversationHeader;
import codeu.chat.common.ConversationHeader.ConversationUuid;
import codeu.chat.util.Uuid;

public interface AuthorityModel
{
  public void changeAuthority(ConversationUuid conversation, Uuid targetUser, byte authorityByte);

  public boolean isMember(ConversationHeader conversation,Uuid targetUser);
  public boolean isMember(ConversationUuid conversation,Uuid targetUser);
  public boolean isOwner(ConversationHeader conversation,Uuid targetUser);
  public boolean isOwner(ConversationUuid conversation,Uuid targetUser);
  public boolean isCreator(ConversationHeader conversation,Uuid targetUser);
  public boolean isCreator(ConversationUuid conversation,Uuid targetUser);
}


text:
"""setup.py: setuptools control."""

import re
from setuptools import setup

version = re.search(
    '^__version__\s*=\s*"(.*)"',
    open('ddwrtcli/ddwrtcli.py').read(),
    re.M
    ).group(1)

with open("README.md", "rb") as f:
    long_descr = f.read().decode("utf-8")

setup(
    name = "dd-wrt-cli",
    packages = ["ddwrtcli","fabfile"],
    install_requires=[
        'Fabric',
        'tabulate'
    ],
    entry_points = {
        "console_scripts": ['ddwrt = ddwrtcli.ddwrtcli:main']
        },
    version = version,
    description = "Python command line application bare bones template.",
    long_description = long_descr,
    author = "Jan-Philip Gehrcke",
    author_email = "jgehrcke@googlemail.com",
    url = "http://gehrcke.de/2014/02/distributing-a-python-command-line-application",
    )


text:
<!DOCTYPE HTML>

<title>Uses of Class io.ebean.event.changelog.ChangeSet (ebean api 13.6.0 API)</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2022-05-03">
<meta name="description" content="use: module: io.ebean.api, package: io.ebean.event.changelog, class: ChangeSet">
<meta name="generator" content="javadoc/ClassUseWriter">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../../script-dir/jquery-ui.min.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../../jquery-ui.overrides.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Module

Package

Class

Use

Tree

Deprecated

Index

Help

SEARCH:
<input type="text" id="search-input" value="search" disabled="disabled">
<input type="reset" id="reset-button" value="reset" disabled="disabled">

Uses of Class
io.ebean.event.changelog.ChangeSet

Packages that use ChangeSet

Package

Description

io.ebean.event.changelog

Provides a built in change log mechanism and can audit changes.

Uses of ChangeSet in io.ebean.event.changelog

Methods in io.ebean.event.changelog with parameters of type ChangeSet

Modifier and Type

Method

Description

void

ChangeLogListener.log<wbr>(ChangeSet changeSet)

Log the batch of changes.

boolean

ChangeLogPrepare.prepare<wbr>(ChangeSet changeSet)

In the foreground prepare the changeLog for sending.

Copyright © 2022. All rights reserved.


text:
'use strict';

var fs = require('graceful-fs');

var futimes = require('../../futimes');

function writeBuffer(writePath, file, cb) {
  var stat = file.stat;

  fs.open(writePath, file.flag, stat.mode, function(err, fd) {
    if (err) {
      return cb(err);
    }

    fs.write(fd, file.contents, 0, file.contents.length, 0, function(error) {
      if (error) {
        return complete(error);
      }
      futimes(fd, stat, complete);
    });

    // cleanup
    function complete(err1) {
      fs.close(fd, function(err2) {
        cb(err1 || err2);
      });
    }
  });

}

module.exports = writeBuffer;


text:
using System;

namespace Microsoft.Win32
{
    [Flags]
    public enum RegistryOptions
    {
        None = Interop.REG_OPTION_NON_VOLATILE,       // 0x0000
        Volatile = Interop.REG_OPTION_VOLATILE,      // 0x0001
    };
}


text:
<!doctype html>
<title>CodeMirror: VBScript mode</title>
<meta charset="utf-8" />
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">

CodeMirror

            Home

                Manual

                    Code

            Language modes

                VBScript

VBScript mode

        <textarea id="code" name="code"> ' Pete Guhl ' 03-04-2012 ' ' Basic VBScript support for codemirror2 Const ForReading = 1, ForWriting = 2, ForAppending = 8 Call Sub020_PostBroadcastToUrbanAirship(strUserName, strPassword, intTransmitID, strResponse) If Not IsNull(strResponse)
            AND Len(strResponse) = 0 Then boolTransmitOkYN = False Else ' WScript.Echo "Oh Happy Day! Oh Happy DAY!" boolTransmitOkYN = True End If </textarea>

        MIME types defined: text/vbscript.