<commit_before>/* GStreamer taglib-based ID3v2 muxer
 * Copyright (C) 2006 Christophe Fergeau <teuf@gnome.org>
 * Copyright (C) 2006 Tim-Philipp Müller <tim centricular net>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

/**
 * SECTION:element-id3v2mux
 * @see_also: #GstID3Demux, #GstTagSetter
 *
 * <refsect2>
 * <para>
 * This element adds ID3v2 tags to the beginning of a stream using the taglib
 * library. More precisely, the tags written are ID3 version 2.4.0 tags (which
 * means in practice that some hardware players or outdated programs might not
 * be able to read them properly).
 * </para>
 * <para>
 * Applications can set the tags to write using the #GstTagSetter interface.
 * Tags sent by upstream elements will be picked up automatically (and merged
 * according to the merge mode set via the tag setter interface).
 * </para>
 * <para>
 * Here is a simple pipeline that transcodes a file from Ogg/Vorbis to mp3
 * format with an ID3v2 that contains the same as the the Ogg/Vorbis file:
 * <programlisting>
 * gst-launch -v filesrc location=foo.ogg ! decodebin ! audioconvert ! lame ! id3v2mux ! filesink location=foo.mp3
 * </programlisting>
 * Make sure the Ogg/Vorbis file actually has comments to preserve.
 * You can verify the tags were written using:
 * <programlisting>
 * gst-launch -m filesrc location=foo.mp3 ! id3demux ! fakesink silent=TRUE 2¨ /dev/null | grep taglist
 * </programlisting>
 * </para>
 * </refsect2>
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "gstid3v2mux.h"

#include <string.h>
#include <textidentificationframe.h>
#include <uniquefileidentifierframe.h>
#include <id3v2tag.h>
#include <gst/tag/tag.h>

using namespace TagLib;

GST_DEBUG_CATEGORY_STATIC (gst_id3v2_mux_debug);
#define GST_CAT_DEFAULT gst_id3v2_mux_debug

static const GstElementDetails gst_id3v2_mux_details =
GST_ELEMENT_DETAILS ("TagLib ID3v2 Muxer",
    "Formatter/Metadata",
    "Adds an ID3v2 header to the beginning of MP3 files using taglib",
    "Christophe Fergeau <teuf@gnome.org>");

static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src",
    GST_PAD_SRC,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS ("application/x-id3"));

GST_BOILERPLATE (GstId3v2Mux, gst_id3v2_mux, GstTagLibMux,
    GST_TYPE_TAG_LIB_MUX);

static GstBuffer *gst_id3v2_mux_render_tag (GstTagLibMux * mux,
    GstTagList * taglist);

static void
gst_id3v2_mux_base_init (gpointer g_class)
{
  GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);

  gst_element_class_add_pad_template (element_class,
      gst_static_pad_template_get (&src_template));

  gst_element_class_set_details (element_class, &gst_id3v2_mux_details);

  GST_DEBUG_CATEGORY_INIT (gst_id3v2_mux_debug, "id3v2mux", 0,
      "taglib-based ID3v2 tag muxer");
}

static void
gst_id3v2_mux_class_init (GstId3v2MuxClass * klass)
{
  GST_TAG_LIB_MUX_CLASS (klass)->render_tag =
      GST_DEBUG_FUNCPTR (gst_id3v2_mux_render_tag);
}

static void
gst_id3v2_mux_init (GstId3v2Mux * id3v2mux, GstId3v2MuxClass * id3v2mux_class)
{
  /* nothing to do */
}

static void
add_one_txxx_musicbrainz_tag (ID3v2::Tag * id3v2tag, const gchar * spec_id,
    const gchar * realworld_id, const gchar * id_str)
{
  ID3v2::UserTextIdentificationFrame * frame;

  if (id_str == NULL)
    return;

  GST_DEBUG ("Setting %s to %s", GST_STR_NULL (spec_id), id_str);

  if (spec_id) {
    frame = new ID3v2::UserTextIdentificationFrame (String::Latin1);
    id3v2tag->addFrame (frame);
    frame->setDescription (spec_id);
    frame->setText (id_str);
  }

  if (realworld_id) {
    frame = new ID3v2::UserTextIdentificationFrame (String::Latin1);
    id3v2tag->addFrame (frame);
    frame->setDescription (realworld_id);
    frame->setText (id_str);
  }
}

static void
add_one_tag (const GstTagList * list, const gchar * tag, gpointer user_data)
{
  ID3v2::Tag * id3v2tag = (ID3v2::Tag *) user_data;
  gboolean result;

  /* FIXME: if there are several values set for the same tag, this won't
   * work, only the first value will be taken into account
   */
  if (strcmp (tag, GST_TAG_TITLE) == 0) {
    char *title;

    result = gst_tag_list_get_string_index (list, tag, 0, &title);
    if (result != FALSE) {
      GST_DEBUG ("Setting title to %s", title);
      id3v2tag->setTitle (String::String (title, String::UTF8));
    }
    g_free (title);
  } else if (strcmp (tag, GST_TAG_ALBUM) == 0) {
    char *album;

    result = gst_tag_list_get_string_index (list, tag, 0, &album);
    if (result != FALSE) {
      GST_DEBUG ("Setting album to %s", album);
      id3v2tag->setAlbum (String::String (album, String::UTF8));
    }
    g_free (album);
  } else if (strcmp (tag, GST_TAG_ARTIST) == 0) {
    char *artist;

    result = gst_tag_list_get_string_index (list, tag, 0, &artist);
    if (result != FALSE) {
      GST_DEBUG ("Setting artist to %s", artist);
      id3v2tag->setArtist (String::String (artist, String::UTF8));
    }
    g_free (artist);
  } else if (strcmp (tag, GST_TAG_GENRE) == 0) {
    char *genre;

    result = gst_tag_list_get_string_index (list, tag, 0, &genre);
    if (result != FALSE) {
      GST_DEBUG ("Setting genre to %s", genre);
      id3v2tag->setGenre (String::String (genre, String::UTF8));
    }
    g_free (genre);
  } else if (strcmp (tag, GST_TAG_COMMENT) == 0) {
    char *comment;

    result = gst_tag_list_get_string_index (list, tag, 0, &comment);
    if (result != FALSE) {
      GST_DEBUG ("Setting comment to %s", comment);
      id3v2tag->setComment (String::String (comment, String::UTF8));
    }
    g_free (comment);
  } else if (strcmp (tag, GST_TAG_DATE) == 0) {
    GDate *date;

    result = gst_tag_list_get_date_index (list, tag, 0, &date);
    if (result != FALSE) {
      GDateYear year;

      year = g_date_get_year (date);
      GST_DEBUG ("Setting track year to %d", year);
      id3v2tag->setYear (year);
      g_date_free (date);
    }
  } else if (strcmp (tag, GST_TAG_TRACK_NUMBER) == 0) {
    guint track_number;

    result = gst_tag_list_get_uint_index (list, tag, 0, &track_number);
    if (result != FALSE) {
      guint total_tracks;

      result = gst_tag_list_get_uint_index (list, GST_TAG_TRACK_COUNT,
          0, &total_tracks);
      if (result) {
        gchar *tag_str;

        ID3v2::TextIdentificationFrame * frame;

        frame = new ID3v2::TextIdentificationFrame ("TRCK", String::UTF8);
        tag_str = g_strdup_printf ("%d/%d", track_number, total_tracks);
        GST_DEBUG ("Setting track number to %s", tag_str);
        id3v2tag->addFrame (frame);
        frame->setText (tag_str);
        g_free (tag_str);
      } else {
        GST_DEBUG ("Setting track number to %d", track_number);
        id3v2tag->setTrack (track_number);
      }
    }
  } else if (strcmp (tag, GST_TAG_ALBUM_VOLUME_NUMBER) == 0) {
    guint volume_number;

    result = gst_tag_list_get_uint_index (list, tag, 0, &volume_number);

    if (result != FALSE) {
      guint volume_count;
      gchar *tag_str;

      ID3v2::TextIdentificationFrame * frame;

      frame = new ID3v2::TextIdentificationFrame ("TPOS", String::UTF8);
      result = gst_tag_list_get_uint_index (list, GST_TAG_ALBUM_VOLUME_COUNT,
          0, &volume_count);
      if (result) {
        tag_str = g_strdup_printf ("%d/%d", volume_number, volume_count);
      } else {
        tag_str = g_strdup_printf ("%d", volume_number);
      }

      GST_DEBUG ("Setting album number to %s", tag_str);

      id3v2tag->addFrame (frame);
      frame->setText (tag_str);
      g_free (tag_str);
    }
  } else if (strcmp (tag, GST_TAG_COPYRIGHT) == 0) {
    gchar *copyright;

    result = gst_tag_list_get_string_index (list, tag, 0, &copyright);

    if (result != FALSE) {
      ID3v2::TextIdentificationFrame * frame;

      GST_DEBUG ("Setting copyright to %s", copyright);

      frame = new ID3v2::TextIdentificationFrame ("TCOP", String::UTF8);

      id3v2tag->addFrame (frame);
      frame->setText (copyright);
      g_free (copyright);
    }
  } else if (strcmp (tag, GST_TAG_MUSICBRAINZ_ARTISTID) == 0) {
    gchar *id_str;

    if (gst_tag_list_get_string_index (list, tag, 0, &id_str) && id_str) {
      add_one_txxx_musicbrainz_tag (id3v2tag, "MusicBrainz Artist Id",
          "musicbrainz_artistid", id_str);
      g_free (id_str);
    }
  } else if (strcmp (tag, GST_TAG_MUSICBRAINZ_ALBUMID) == 0) {
    gchar *id_str;

    if (gst_tag_list_get_string_index (list, tag, 0, &id_str) && id_str) {
      add_one_txxx_musicbrainz_tag (id3v2tag, "MusicBrainz Album Id",
          "musicbrainz_albumid", id_str);
      g_free (id_str);
    }
  } else if (strcmp (tag, GST_TAG_MUSICBRAINZ_ALBUMARTISTID) == 0) {
    gchar *id_str;

    if (gst_tag_list_get_string_index (list, tag, 0, &id_str) && id_str) {
      add_one_txxx_musicbrainz_tag (id3v2tag, "MusicBrainz Album Artist Id",
          "musicbrainz_albumartistid", id_str);
      g_free (id_str);
    }
  } else if (strcmp (tag, GST_TAG_MUSICBRAINZ_TRMID) == 0) {
    gchar *id_str;

    if (gst_tag_list_get_string_index (list, tag, 0, &id_str) && id_str) {
      add_one_txxx_musicbrainz_tag (id3v2tag, "MusicBrainz TRM Id",
          "musicbrainz_trmid", id_str);
      g_free (id_str);
    }
  } else if (strcmp (tag, GST_TAG_MUSICBRAINZ_TRACKID) == 0) {
    gchar *id_str;

    if (gst_tag_list_get_string_index (list, tag, 0, &id_str) && id_str) {
      ID3v2::UniqueFileIdentifierFrame * frame;

      GST_DEBUG ("Setting Musicbrainz Track Id to %s", id_str);

      frame = new ID3v2::UniqueFileIdentifierFrame ("http://musicbrainz.org",
          id_str);
      id3v2tag->addFrame (frame);
      g_free (id_str);
    }
  } else {
    GST_WARNING ("Unsupported tag: %s", tag);
  }
}

static GstBuffer *
gst_id3v2_mux_render_tag (GstTagLibMux * mux, GstTagList * taglist)
{
  ID3v2::Tag id3v2tag;
  ByteVector rendered_tag;
  GstBuffer *buf;
  guint tag_size;

  /* Render the tag */
  gst_tag_list_foreach (taglist, add_one_tag, &id3v2tag);

  rendered_tag = id3v2tag.render ();
  tag_size = rendered_tag.size ();

  GST_LOG_OBJECT (mux, "tag size = %d bytes", tag_size);

  /* Create buffer with tag */
  buf = gst_buffer_new_and_alloc (tag_size);
  memcpy (GST_BUFFER_DATA (buf), rendered_tag.data (), tag_size);
  gst_buffer_set_caps (buf, GST_PAD_CAPS (mux->srcpad));

  return buf;
}

static gboolean
plugin_init (GstPlugin * plugin)
{
  if (!gst_element_register (plugin, "id3v2mux", GST_RANK_NONE,
          GST_TYPE_ID3V2_MUX))
    return FALSE;

  gst_tag_register_musicbrainz_tags ();

  return TRUE;
}

GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
    GST_VERSION_MINOR,
    "taglib",
    "Tag-writing plug-in based on taglib",
    plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN);
<commit_msg>fix docs<commit_after>/* GStreamer taglib-based ID3v2 muxer
 * Copyright (C) 2006 Christophe Fergeau <teuf@gnome.org>
 * Copyright (C) 2006 Tim-Philipp Müller <tim centricular net>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

/**
 * SECTION:element-id3v2mux
 * @see_also: #GstID3Demux, #GstTagSetter
 *
 * <refsect2>
 * <para>
 * This element adds ID3v2 tags to the beginning of a stream using the taglib
 * library. More precisely, the tags written are ID3 version 2.4.0 tags (which
 * means in practice that some hardware players or outdated programs might not
 * be able to read them properly).
 * </para>
 * <para>
 * Applications can set the tags to write using the #GstTagSetter interface.
 * Tags sent by upstream elements will be picked up automatically (and merged
 * according to the merge mode set via the tag setter interface).
 * </para>
 * <para>
 * Here is a simple pipeline that transcodes a file from Ogg/Vorbis to mp3
 * format with an ID3v2 that contains the same as the the Ogg/Vorbis file:
 * <programlisting>
 * gst-launch -v filesrc location=foo.ogg ! decodebin ! audioconvert ! lame ! id3v2mux ! filesink location=foo.mp3
 * </programlisting>
 * Make sure the Ogg/Vorbis file actually has comments to preserve.
 * You can verify the tags were written using:
 * <programlisting>
 * gst-launch -m filesrc location=foo.mp3 ! id3demux ! fakesink silent=TRUE 2> /dev/null | grep taglist
 * </programlisting>
 * </para>
 * </refsect2>
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "gstid3v2mux.h"

#include <string.h>
#include <textidentificationframe.h>
#include <uniquefileidentifierframe.h>
#include <id3v2tag.h>
#include <gst/tag/tag.h>

using namespace TagLib;

GST_DEBUG_CATEGORY_STATIC (gst_id3v2_mux_debug);
#define GST_CAT_DEFAULT gst_id3v2_mux_debug

static const GstElementDetails gst_id3v2_mux_details =
GST_ELEMENT_DETAILS ("TagLib ID3v2 Muxer",
    "Formatter/Metadata",
    "Adds an ID3v2 header to the beginning of MP3 files using taglib",
    "Christophe Fergeau <teuf@gnome.org>");

static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src",
    GST_PAD_SRC,
    GST_PAD_ALWAYS,
    GST_STATIC_CAPS ("application/x-id3"));

GST_BOILERPLATE (GstId3v2Mux, gst_id3v2_mux, GstTagLibMux,
    GST_TYPE_TAG_LIB_MUX);

static GstBuffer *gst_id3v2_mux_render_tag (GstTagLibMux * mux,
    GstTagList * taglist);

static void
gst_id3v2_mux_base_init (gpointer g_class)
{
  GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);

  gst_element_class_add_pad_template (element_class,
      gst_static_pad_template_get (&src_template));

  gst_element_class_set_details (element_class, &gst_id3v2_mux_details);

  GST_DEBUG_CATEGORY_INIT (gst_id3v2_mux_debug, "id3v2mux", 0,
      "taglib-based ID3v2 tag muxer");
}

static void
gst_id3v2_mux_class_init (GstId3v2MuxClass * klass)
{
  GST_TAG_LIB_MUX_CLASS (klass)->render_tag =
      GST_DEBUG_FUNCPTR (gst_id3v2_mux_render_tag);
}

static void
gst_id3v2_mux_init (GstId3v2Mux * id3v2mux, GstId3v2MuxClass * id3v2mux_class)
{
  /* nothing to do */
}

static void
add_one_txxx_musicbrainz_tag (ID3v2::Tag * id3v2tag, const gchar * spec_id,
    const gchar * realworld_id, const gchar * id_str)
{
  ID3v2::UserTextIdentificationFrame * frame;

  if (id_str == NULL)
    return;

  GST_DEBUG ("Setting %s to %s", GST_STR_NULL (spec_id), id_str);

  if (spec_id) {
    frame = new ID3v2::UserTextIdentificationFrame (String::Latin1);
    id3v2tag->addFrame (frame);
    frame->setDescription (spec_id);
    frame->setText (id_str);
  }

  if (realworld_id) {
    frame = new ID3v2::UserTextIdentificationFrame (String::Latin1);
    id3v2tag->addFrame (frame);
    frame->setDescription (realworld_id);
    frame->setText (id_str);
  }
}

static void
add_one_tag (const GstTagList * list, const gchar * tag, gpointer user_data)
{
  ID3v2::Tag * id3v2tag = (ID3v2::Tag *) user_data;
  gboolean result;

  /* FIXME: if there are several values set for the same tag, this won't
   * work, only the first value will be taken into account
   */
  if (strcmp (tag, GST_TAG_TITLE) == 0) {
    char *title;

    result = gst_tag_list_get_string_index (list, tag, 0, &title);
    if (result != FALSE) {
      GST_DEBUG ("Setting title to %s", title);
      id3v2tag->setTitle (String::String (title, String::UTF8));
    }
    g_free (title);
  } else if (strcmp (tag, GST_TAG_ALBUM) == 0) {
    char *album;

    result = gst_tag_list_get_string_index (list, tag, 0, &album);
    if (result != FALSE) {
      GST_DEBUG ("Setting album to %s", album);
      id3v2tag->setAlbum (String::String (album, String::UTF8));
    }
    g_free (album);
  } else if (strcmp (tag, GST_TAG_ARTIST) == 0) {
    char *artist;

    result = gst_tag_list_get_string_index (list, tag, 0, &artist);
    if (result != FALSE) {
      GST_DEBUG ("Setting artist to %s", artist);
      id3v2tag->setArtist (String::String (artist, String::UTF8));
    }
    g_free (artist);
  } else if (strcmp (tag, GST_TAG_GENRE) == 0) {
    char *genre;

    result = gst_tag_list_get_string_index (list, tag, 0, &genre);
    if (result != FALSE) {
      GST_DEBUG ("Setting genre to %s", genre);
      id3v2tag->setGenre (String::String (genre, String::UTF8));
    }
    g_free (genre);
  } else if (strcmp (tag, GST_TAG_COMMENT) == 0) {
    char *comment;

    result = gst_tag_list_get_string_index (list, tag, 0, &comment);
    if (result != FALSE) {
      GST_DEBUG ("Setting comment to %s", comment);
      id3v2tag->setComment (String::String (comment, String::UTF8));
    }
    g_free (comment);
  } else if (strcmp (tag, GST_TAG_DATE) == 0) {
    GDate *date;

    result = gst_tag_list_get_date_index (list, tag, 0, &date);
    if (result != FALSE) {
      GDateYear year;

      year = g_date_get_year (date);
      GST_DEBUG ("Setting track year to %d", year);
      id3v2tag->setYear (year);
      g_date_free (date);
    }
  } else if (strcmp (tag, GST_TAG_TRACK_NUMBER) == 0) {
    guint track_number;

    result = gst_tag_list_get_uint_index (list, tag, 0, &track_number);
    if (result != FALSE) {
      guint total_tracks;

      result = gst_tag_list_get_uint_index (list, GST_TAG_TRACK_COUNT,
          0, &total_tracks);
      if (result) {
        gchar *tag_str;

        ID3v2::TextIdentificationFrame * frame;

        frame = new ID3v2::TextIdentificationFrame ("TRCK", String::UTF8);
        tag_str = g_strdup_printf ("%d/%d", track_number, total_tracks);
        GST_DEBUG ("Setting track number to %s", tag_str);
        id3v2tag->addFrame (frame);
        frame->setText (tag_str);
        g_free (tag_str);
      } else {
        GST_DEBUG ("Setting track number to %d", track_number);
        id3v2tag->setTrack (track_number);
      }
    }
  } else if (strcmp (tag, GST_TAG_ALBUM_VOLUME_NUMBER) == 0) {
    guint volume_number;

    result = gst_tag_list_get_uint_index (list, tag, 0, &volume_number);

    if (result != FALSE) {
      guint volume_count;
      gchar *tag_str;

      ID3v2::TextIdentificationFrame * frame;

      frame = new ID3v2::TextIdentificationFrame ("TPOS", String::UTF8);
      result = gst_tag_list_get_uint_index (list, GST_TAG_ALBUM_VOLUME_COUNT,
          0, &volume_count);
      if (result) {
        tag_str = g_strdup_printf ("%d/%d", volume_number, volume_count);
      } else {
        tag_str = g_strdup_printf ("%d", volume_number);
      }

      GST_DEBUG ("Setting album number to %s", tag_str);

      id3v2tag->addFrame (frame);
      frame->setText (tag_str);
      g_free (tag_str);
    }
  } else if (strcmp (tag, GST_TAG_COPYRIGHT) == 0) {
    gchar *copyright;

    result = gst_tag_list_get_string_index (list, tag, 0, &copyright);

    if (result != FALSE) {
      ID3v2::TextIdentificationFrame * frame;

      GST_DEBUG ("Setting copyright to %s", copyright);

      frame = new ID3v2::TextIdentificationFrame ("TCOP", String::UTF8);

      id3v2tag->addFrame (frame);
      frame->setText (copyright);
      g_free (copyright);
    }
  } else if (strcmp (tag, GST_TAG_MUSICBRAINZ_ARTISTID) == 0) {
    gchar *id_str;

    if (gst_tag_list_get_string_index (list, tag, 0, &id_str) && id_str) {
      add_one_txxx_musicbrainz_tag (id3v2tag, "MusicBrainz Artist Id",
          "musicbrainz_artistid", id_str);
      g_free (id_str);
    }
  } else if (strcmp (tag, GST_TAG_MUSICBRAINZ_ALBUMID) == 0) {
    gchar *id_str;

    if (gst_tag_list_get_string_index (list, tag, 0, &id_str) && id_str) {
      add_one_txxx_musicbrainz_tag (id3v2tag, "MusicBrainz Album Id",
          "musicbrainz_albumid", id_str);
      g_free (id_str);
    }
  } else if (strcmp (tag, GST_TAG_MUSICBRAINZ_ALBUMARTISTID) == 0) {
    gchar *id_str;

    if (gst_tag_list_get_string_index (list, tag, 0, &id_str) && id_str) {
      add_one_txxx_musicbrainz_tag (id3v2tag, "MusicBrainz Album Artist Id",
          "musicbrainz_albumartistid", id_str);
      g_free (id_str);
    }
  } else if (strcmp (tag, GST_TAG_MUSICBRAINZ_TRMID) == 0) {
    gchar *id_str;

    if (gst_tag_list_get_string_index (list, tag, 0, &id_str) && id_str) {
      add_one_txxx_musicbrainz_tag (id3v2tag, "MusicBrainz TRM Id",
          "musicbrainz_trmid", id_str);
      g_free (id_str);
    }
  } else if (strcmp (tag, GST_TAG_MUSICBRAINZ_TRACKID) == 0) {
    gchar *id_str;

    if (gst_tag_list_get_string_index (list, tag, 0, &id_str) && id_str) {
      ID3v2::UniqueFileIdentifierFrame * frame;

      GST_DEBUG ("Setting Musicbrainz Track Id to %s", id_str);

      frame = new ID3v2::UniqueFileIdentifierFrame ("http://musicbrainz.org",
          id_str);
      id3v2tag->addFrame (frame);
      g_free (id_str);
    }
  } else {
    GST_WARNING ("Unsupported tag: %s", tag);
  }
}

static GstBuffer *
gst_id3v2_mux_render_tag (GstTagLibMux * mux, GstTagList * taglist)
{
  ID3v2::Tag id3v2tag;
  ByteVector rendered_tag;
  GstBuffer *buf;
  guint tag_size;

  /* Render the tag */
  gst_tag_list_foreach (taglist, add_one_tag, &id3v2tag);

  rendered_tag = id3v2tag.render ();
  tag_size = rendered_tag.size ();

  GST_LOG_OBJECT (mux, "tag size = %d bytes", tag_size);

  /* Create buffer with tag */
  buf = gst_buffer_new_and_alloc (tag_size);
  memcpy (GST_BUFFER_DATA (buf), rendered_tag.data (), tag_size);
  gst_buffer_set_caps (buf, GST_PAD_CAPS (mux->srcpad));

  return buf;
}

static gboolean
plugin_init (GstPlugin * plugin)
{
  if (!gst_element_register (plugin, "id3v2mux", GST_RANK_NONE,
          GST_TYPE_ID3V2_MUX))
    return FALSE;

  gst_tag_register_musicbrainz_tags ();

  return TRUE;
}

GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
    GST_VERSION_MINOR,
    "taglib",
    "Tag-writing plug-in based on taglib",
    plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN);
<|endoftext|>


<commit_before>#ifndef VEXCL_VEXCL_HPP
#define VEXCL_VEXCL_HPP

/*
The MIT License

Copyright (c) 2012-2013 Denis Demidov <ddemidov@ksu.ru>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/**
 * \file   vexcl.hpp
 * \author Denis Demidov <ddemidov@ksu.ru>
 * \brief  Vector expression template library for OpenCL.
 */

#include <vexcl/devlist.hpp>
#include <vexcl/element_index.hpp>
#include <vexcl/vector.hpp>
#include <vexcl/vector_view.hpp>
#include <vexcl/tagged_terminal.hpp>
#include <vexcl/multivector.hpp>
#include <vexcl/reductor.hpp>
#include <vexcl/spmat.hpp>
#include <vexcl/stencil.hpp>
#include <vexcl/gather.hpp>
#include <vexcl/random.hpp>
#include <vexcl/fft.hpp>
#include <vexcl/generator.hpp>
#include <vexcl/profiler.hpp>

#endif
<commit_msg>Include vexcl/temporary.hpp by default<commit_after>#ifndef VEXCL_VEXCL_HPP
#define VEXCL_VEXCL_HPP

/*
The MIT License

Copyright (c) 2012-2013 Denis Demidov <ddemidov@ksu.ru>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/**
 * \file   vexcl.hpp
 * \author Denis Demidov <ddemidov@ksu.ru>
 * \brief  Vector expression template library for OpenCL.
 */

#include <vexcl/devlist.hpp>
#include <vexcl/element_index.hpp>
#include <vexcl/vector.hpp>
#include <vexcl/vector_view.hpp>
#include <vexcl/tagged_terminal.hpp>
#include <vexcl/temporary.hpp>
#include <vexcl/multivector.hpp>
#include <vexcl/reductor.hpp>
#include <vexcl/spmat.hpp>
#include <vexcl/stencil.hpp>
#include <vexcl/gather.hpp>
#include <vexcl/random.hpp>
#include <vexcl/fft.hpp>
#include <vexcl/generator.hpp>
#include <vexcl/profiler.hpp>

#endif
<|endoftext|>


<commit_before>// Copyright (c) 2018-2020 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <consensus/validation.h>
#include <core_io.h>
#include <init.h>
#include <rpc/server.h>
#include <util/moneystr.h>
#include <validation.h>

#include <evo/deterministicmns.h>
#include <evo/simplifiedmns.h>

#include <bls/bls.h>

#include <masternode/masternodemeta.h>
#include <rpc/util.h>
#include <rpc/blockchain.h>
#include <node/context.h>

UniValue BuildDMNListEntry(const NodeContext& node, const CDeterministicMNCPtr& dmn, bool detailed)
{
    if (!detailed) {
        return dmn->proTxHash.ToString();
    }
    UniValue o(UniValue::VOBJ);

    dmn->ToJson(*node.chain, o);
    std::map<COutPoint, Coin> coins;
    coins[dmn->collateralOutpoint];
    node.chain->findCoins(coins);
    int confirmations = 0;
    const Coin &coin = coins.at(dmn->collateralOutpoint);
    if (!coin.IsSpent()) {
        confirmations = *node.chain->getHeight() - coin.nHeight;
    }
    o.pushKV("confirmations", confirmations);
    auto metaInfo = mmetaman.GetMetaInfo(dmn->proTxHash);
    o.pushKV("metaInfo", metaInfo->ToJson());

    return o;
}

static RPCHelpMan protx_list()
{
    return RPCHelpMan{"protx_list",
        "\nLists all ProTxs on-chain, depending on the given type.\n"
        "This will also include ProTx which failed PoSe verification.\n",
        {
             {"type", RPCArg::Type::STR, RPCArg::Default{"registered"}, "Type of ProTx.\n",
            "\nAvailable types:\n"
            "  registered   - List all ProTx which are registered at the given chain height.\n"
            "                 This will also include ProTx which failed PoSe verification.\n"
            "  valid        - List only ProTx which are active/valid at the given chain height.\n"},
            {"detailed", RPCArg::Type::BOOL,  RPCArg::Default{false}, "If true, only the hashes of the ProTx will be returned."},
            {"height", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "Height to look for ProTx transactions, if not specified defaults to current chain-tip"},
        },
        RPCResult{RPCResult::Type::ANY, "", ""},
        RPCExamples{
                HelpExampleCli("protx_list", "registered true")
            + HelpExampleRpc("protx_list", "\"registered\", true")
        },
    [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{

    const NodeContext& node = EnsureAnyNodeContext(request.context);
    std::string type = "registered";
    if (!request.params[0].isNull()) {
        type = request.params[0].get_str();
    }

    UniValue ret(UniValue::VARR);

    if (type == "valid" || type == "registered") {
        CDeterministicMNList mnList;
        bool detailed = !request.params[1].isNull() ? request.params[1].get_bool() : false;
        {
            LOCK(cs_main);
            int height = !request.params[2].isNull() ? request.params[2].get_int() : node.chainman->ActiveHeight();
            if (height < 1 || height > node.chainman->ActiveHeight()) {
                throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid height specified");
            }
            CDeterministicMNList mnList = deterministicMNManager->GetListForBlock(node.chainman->ActiveChain()[height]);
        }
        bool onlyValid = type == "valid";
        mnList.ForEachMN(onlyValid, [&](const CDeterministicMNCPtr& dmn) {
            ret.push_back(BuildDMNListEntry(node, dmn, detailed));
        });

    } else {
        throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid type specified");
    }

    return ret;
},
    };
}

static RPCHelpMan protx_info()
{
    return RPCHelpMan{"protx_info",
        "\nReturns detailed information about a deterministic masternode.\n",
        {
            {"proTxHash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hash of the initial ProRegTx."},
        },
        RPCResult{RPCResult::Type::ANY, "", ""},
        RPCExamples{
                HelpExampleCli("protx_info", "1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d")
            + HelpExampleRpc("protx_info", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
        },
    [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
    const NodeContext& node = EnsureAnyNodeContext(request.context);
    uint256 proTxHash = ParseHashV(request.params[0], "proTxHash");
    auto mnList = deterministicMNManager->GetListAtChainTip();
    auto dmn = mnList.GetMN(proTxHash);
    if (!dmn) {
        throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s not found", proTxHash.ToString()));
    }

    return BuildDMNListEntry(node, dmn, true);
},
    };
}

static uint256 ParseBlock(ChainstateManager& chainman, const UniValue& v, std::string strName)
{
    try {
        return ParseHashV(v, strName);
    } catch (...) {
        LOCK(cs_main);
        int h = v.get_int();
        if (h < 1 || h > chainman.ActiveHeight())
            throw std::runtime_error(strprintf("%s must be a block hash or chain height and not %s", strName, v.getValStr()));
        return *chainman.ActiveChain()[h]->phashBlock;
    }
}

static RPCHelpMan protx_diff()
{
    return RPCHelpMan{"protx_diff",
        "\nReturns detailed information about a deterministic masternode.\n",
        {
            {"baseBlock", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The starting block hash."},
            {"block", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The ending block hash."},
        },
        RPCResult{RPCResult::Type::ANY, "", ""},
        RPCExamples{
                HelpExampleCli("protx_diff", "1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d")
            + HelpExampleRpc("protx_diff", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
        },
    [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
    const NodeContext& node = EnsureAnyNodeContext(request.context);
    uint256 baseBlockHash = ParseBlock(*node.chainman, request.params[0], "baseBlock");
    uint256 blockHash = ParseBlock(*node.chainman, request.params[1], "block");

    CSimplifiedMNListDiff mnListDiff;
    std::string strError;
    if (!BuildSimplifiedMNListDiff(*node.chainman, baseBlockHash, blockHash, mnListDiff, strError)) {
        throw std::runtime_error(strError);
    }

    UniValue ret;
    mnListDiff.ToJson(ret);
    return ret;
},
    };
}

static RPCHelpMan bls_generate()
{
     return RPCHelpMan{"bls_generate",
        "\nReturns a BLS secret/public key pair.\n",
        {
        },
        RPCResult{RPCResult::Type::ANY, "", ""},
        RPCExamples{
                HelpExampleCli("bls_generate", "")
            + HelpExampleRpc("bls_generate", "")
        },
    [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{

    CBLSSecretKey sk;
    sk.MakeNewKey();

    UniValue ret(UniValue::VOBJ);
    ret.pushKV("secret", sk.ToString());
    ret.pushKV("public", sk.GetPublicKey().ToString());
    return ret;
},
    };
}

static RPCHelpMan bls_fromsecret()
{
     return RPCHelpMan{"bls_fromsecret",
        "\nParses a BLS secret key and returns the secret/public key pair.\n",
        {
             {"secret", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The BLS secret key."},
        },
        RPCResult{RPCResult::Type::ANY, "", ""},
        RPCExamples{
                HelpExampleCli("bls_fromsecret", "")
            + HelpExampleRpc("bls_fromsecret", "")
        },
    [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
    CBLSSecretKey sk;
    if (!sk.SetHexStr(request.params[0].get_str())) {
        throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Secret key must be a valid hex string of length %d", sk.SerSize*2));
    }

    UniValue ret(UniValue::VOBJ);
    ret.pushKV("secret", sk.ToString());
    ret.pushKV("public", sk.GetPublicKey().ToString());
    return ret;
},
    };
}

void RegisterEvoRPCCommands(CRPCTable &t)
{
// clang-format off
static const CRPCCommand commands[] =
{ //  category              name                      actor (function)
  //  --------------------- ------------------------  -----------------------
    { "evo",                &bls_generate,                },
    { "evo",                &bls_fromsecret,              },
    { "evo",                &protx_list,                  },
    { "evo",                &protx_info,                  },
    { "evo",                &protx_diff,                  },
};
// clang-format on
    for (const auto& c : commands) {
        t.appendCommand(c.name, &c);
    }
}
<commit_msg>Update rpcevo.cpp<commit_after>// Copyright (c) 2018-2020 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <consensus/validation.h>
#include <core_io.h>
#include <init.h>
#include <rpc/server.h>
#include <util/moneystr.h>
#include <validation.h>

#include <evo/deterministicmns.h>
#include <evo/simplifiedmns.h>

#include <bls/bls.h>

#include <masternode/masternodemeta.h>
#include <rpc/util.h>
#include <rpc/blockchain.h>
#include <node/context.h>

UniValue BuildDMNListEntry(const NodeContext& node, const CDeterministicMNCPtr& dmn, bool detailed)
{
    if (!detailed) {
        return dmn->proTxHash.ToString();
    }
    UniValue o(UniValue::VOBJ);

    dmn->ToJson(*node.chain, o);
    std::map<COutPoint, Coin> coins;
    coins[dmn->collateralOutpoint];
    node.chain->findCoins(coins);
    int confirmations = 0;
    const Coin &coin = coins.at(dmn->collateralOutpoint);
    if (!coin.IsSpent()) {
        confirmations = *node.chain->getHeight() - coin.nHeight;
    }
    o.pushKV("confirmations", confirmations);
    auto metaInfo = mmetaman.GetMetaInfo(dmn->proTxHash);
    o.pushKV("metaInfo", metaInfo->ToJson());

    return o;
}

static RPCHelpMan protx_list()
{
    return RPCHelpMan{"protx_list",
        "\nLists all ProTxs on-chain, depending on the given type.\n"
        "This will also include ProTx which failed PoSe verification.\n",
        {
             {"type", RPCArg::Type::STR, RPCArg::Default{"registered"}, "Type of ProTx.\n",
            "\nAvailable types:\n"
            "  registered   - List all ProTx which are registered at the given chain height.\n"
            "                 This will also include ProTx which failed PoSe verification.\n"
            "  valid        - List only ProTx which are active/valid at the given chain height.\n"},
            {"detailed", RPCArg::Type::BOOL,  RPCArg::Default{false}, "If true, only the hashes of the ProTx will be returned."},
            {"height", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "Height to look for ProTx transactions, if not specified defaults to current chain-tip"},
        },
        RPCResult{RPCResult::Type::ANY, "", ""},
        RPCExamples{
                HelpExampleCli("protx_list", "registered true")
            + HelpExampleRpc("protx_list", "\"registered\", true")
        },
    [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{

    const NodeContext& node = EnsureAnyNodeContext(request.context);
    std::string type = "registered";
    if (!request.params[0].isNull()) {
        type = request.params[0].get_str();
    }

    UniValue ret(UniValue::VARR);

    if (type == "valid" || type == "registered") {
        CDeterministicMNList mnList;
        bool detailed = !request.params[1].isNull() ? request.params[1].get_bool() : false;
        {
            LOCK(cs_main);
            int height = !request.params[2].isNull() ? request.params[2].get_int() : node.chainman->ActiveHeight();
            if (height < 1 || height > node.chainman->ActiveHeight()) {
                throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid height specified");
            }
            mnList = deterministicMNManager->GetListForBlock(node.chainman->ActiveChain()[height]);
        }
        bool onlyValid = type == "valid";
        mnList.ForEachMN(onlyValid, [&](const CDeterministicMNCPtr& dmn) {
            ret.push_back(BuildDMNListEntry(node, dmn, detailed));
        });

    } else {
        throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid type specified");
    }

    return ret;
},
    };
}

static RPCHelpMan protx_info()
{
    return RPCHelpMan{"protx_info",
        "\nReturns detailed information about a deterministic masternode.\n",
        {
            {"proTxHash", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hash of the initial ProRegTx."},
        },
        RPCResult{RPCResult::Type::ANY, "", ""},
        RPCExamples{
                HelpExampleCli("protx_info", "1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d")
            + HelpExampleRpc("protx_info", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
        },
    [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
    const NodeContext& node = EnsureAnyNodeContext(request.context);
    uint256 proTxHash = ParseHashV(request.params[0], "proTxHash");
    auto mnList = deterministicMNManager->GetListAtChainTip();
    auto dmn = mnList.GetMN(proTxHash);
    if (!dmn) {
        throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s not found", proTxHash.ToString()));
    }

    return BuildDMNListEntry(node, dmn, true);
},
    };
}

static uint256 ParseBlock(ChainstateManager& chainman, const UniValue& v, std::string strName)
{
    try {
        return ParseHashV(v, strName);
    } catch (...) {
        LOCK(cs_main);
        int h = v.get_int();
        if (h < 1 || h > chainman.ActiveHeight())
            throw std::runtime_error(strprintf("%s must be a block hash or chain height and not %s", strName, v.getValStr()));
        return *chainman.ActiveChain()[h]->phashBlock;
    }
}

static RPCHelpMan protx_diff()
{
    return RPCHelpMan{"protx_diff",
        "\nReturns detailed information about a deterministic masternode.\n",
        {
            {"baseBlock", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The starting block hash."},
            {"block", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The ending block hash."},
        },
        RPCResult{RPCResult::Type::ANY, "", ""},
        RPCExamples{
                HelpExampleCli("protx_diff", "1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d")
            + HelpExampleRpc("protx_diff", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
        },
    [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
    const NodeContext& node = EnsureAnyNodeContext(request.context);
    uint256 baseBlockHash = ParseBlock(*node.chainman, request.params[0], "baseBlock");
    uint256 blockHash = ParseBlock(*node.chainman, request.params[1], "block");

    CSimplifiedMNListDiff mnListDiff;
    std::string strError;
    if (!BuildSimplifiedMNListDiff(*node.chainman, baseBlockHash, blockHash, mnListDiff, strError)) {
        throw std::runtime_error(strError);
    }

    UniValue ret;
    mnListDiff.ToJson(ret);
    return ret;
},
    };
}

static RPCHelpMan bls_generate()
{
     return RPCHelpMan{"bls_generate",
        "\nReturns a BLS secret/public key pair.\n",
        {
        },
        RPCResult{RPCResult::Type::ANY, "", ""},
        RPCExamples{
                HelpExampleCli("bls_generate", "")
            + HelpExampleRpc("bls_generate", "")
        },
    [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{

    CBLSSecretKey sk;
    sk.MakeNewKey();

    UniValue ret(UniValue::VOBJ);
    ret.pushKV("secret", sk.ToString());
    ret.pushKV("public", sk.GetPublicKey().ToString());
    return ret;
},
    };
}

static RPCHelpMan bls_fromsecret()
{
     return RPCHelpMan{"bls_fromsecret",
        "\nParses a BLS secret key and returns the secret/public key pair.\n",
        {
             {"secret", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The BLS secret key."},
        },
        RPCResult{RPCResult::Type::ANY, "", ""},
        RPCExamples{
                HelpExampleCli("bls_fromsecret", "")
            + HelpExampleRpc("bls_fromsecret", "")
        },
    [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
    CBLSSecretKey sk;
    if (!sk.SetHexStr(request.params[0].get_str())) {
        throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Secret key must be a valid hex string of length %d", sk.SerSize*2));
    }

    UniValue ret(UniValue::VOBJ);
    ret.pushKV("secret", sk.ToString());
    ret.pushKV("public", sk.GetPublicKey().ToString());
    return ret;
},
    };
}

void RegisterEvoRPCCommands(CRPCTable &t)
{
// clang-format off
static const CRPCCommand commands[] =
{ //  category              name                      actor (function)
  //  --------------------- ------------------------  -----------------------
    { "evo",                &bls_generate,                },
    { "evo",                &bls_fromsecret,              },
    { "evo",                &protx_list,                  },
    { "evo",                &protx_info,                  },
    { "evo",                &protx_diff,                  },
};
// clang-format on
    for (const auto& c : commands) {
        t.appendCommand(c.name, &c);
    }
}
<|endoftext|>


<commit_before>/* This file is part of qjson
  *
  * Copyright (C) 2009 Till Adam <adam@kde.org>
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
  * License as published by the Free Software Foundation; either
  * version 2 of the License, or (at your option) any later version.
  *
  * This library is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Library General Public License for more details.
  *
  * You should have received a copy of the GNU Library General Public License
  * along with this library; see the file COPYING.LIB.  If not, write to
  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  * Boston, MA 02110-1301, USA.
  */

#include "serializer.h"

#include <QDataStream>
#include <QStringList>
#include <QVariant>

using namespace QJson;

class Serializer::SerializerPrivate {

};

Serializer::Serializer() : d( new SerializerPrivate ) {
}

Serializer::~Serializer() {
  delete d;
}

void Serializer::serialize( const QVariant& v, QIODevice* io, bool* ok )
{
  Q_ASSERT( io );
  if (!io->isOpen()) {
    if (!io->open(QIODevice::WriteOnly)) {
      if ( ok != 0 )
        *ok = false;
      qCritical ("Error opening device");
      return;
    }
  }

  if (!io->isWritable()) {
    if (ok != 0)
      *ok = false;
    qCritical ("Device is not readable");
    io->close();
    return;
  }

  const QByteArray str = serialize( v );
  if ( !str.isNull() ) {
    QDataStream stream( io );
    stream << str;
  } else {
    if ( ok )
      *ok = false;
  }
}

static QString sanitizeString( const QString& s )
{
  const QString str = QLatin1String("\"") + s + QLatin1String("\"");
  return str;
}

static QByteArray join( const QList<QByteArray>& list, const QByteArray& sep ) {
  QByteArray res;
  Q_FOREACH( const QByteArray& i, list ) {
    if ( !res.isEmpty() )
      res += sep;
    res += i;
  }
  return res;
}

QByteArray Serializer::serialize( const QVariant &v )
{
  if ( !v.isValid() )
    return ""; // no parse error
  QByteArray str;
  bool error = false;

  // two major cases, either it's an array or ... not
  if ( v.canConvert<QVariantList>() ) {
    const QVariantList list = v.toList();
    QList<QByteArray> values;
    Q_FOREACH( const QVariant& v, list )
      values << serialize( v );
    str = "[ " + join( values, ", " ) + " ]";
  } else {
    // not a list, so it must be an object
    if ( !v.canConvert<QVariantMap>() ) {
      // not a map, so it must be a value
      if ( v.type() == QVariant::String )
        str = sanitizeString( v.toString() ).toUtf8();
      else
        str = v.toByteArray();
    } else {
      const QVariantMap vmap = v.toMap();
      QMapIterator<QString, QVariant> it( vmap );
      str = "{ ";
      while ( it.hasNext() ) {
        it.next();
        str += sanitizeString(it.key()).toUtf8() + " : " + serialize(it.value());
      }
      str += " }";
    }
  }
  if ( !error )
    return str;
  else
    return QByteArray();
}

<commit_msg>Use correct separators in docuemnts.<commit_after>/* This file is part of qjson
  *
  * Copyright (C) 2009 Till Adam <adam@kde.org>
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
  * License as published by the Free Software Foundation; either
  * version 2 of the License, or (at your option) any later version.
  *
  * This library is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Library General Public License for more details.
  *
  * You should have received a copy of the GNU Library General Public License
  * along with this library; see the file COPYING.LIB.  If not, write to
  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  * Boston, MA 02110-1301, USA.
  */

#include "serializer.h"

#include <QDataStream>
#include <QStringList>
#include <QVariant>

using namespace QJson;

class Serializer::SerializerPrivate {

};

Serializer::Serializer() : d( new SerializerPrivate ) {
}

Serializer::~Serializer() {
  delete d;
}

void Serializer::serialize( const QVariant& v, QIODevice* io, bool* ok )
{
  Q_ASSERT( io );
  if (!io->isOpen()) {
    if (!io->open(QIODevice::WriteOnly)) {
      if ( ok != 0 )
        *ok = false;
      qCritical ("Error opening device");
      return;
    }
  }

  if (!io->isWritable()) {
    if (ok != 0)
      *ok = false;
    qCritical ("Device is not readable");
    io->close();
    return;
  }

  const QByteArray str = serialize( v );
  if ( !str.isNull() ) {
    QDataStream stream( io );
    stream << str;
  } else {
    if ( ok )
      *ok = false;
  }
}

static QString sanitizeString( const QString& s )
{
  const QString str = QLatin1String("\"") + s + QLatin1String("\"");
  return str;
}

static QByteArray join( const QList<QByteArray>& list, const QByteArray& sep ) {
  QByteArray res;
  Q_FOREACH( const QByteArray& i, list ) {
    if ( !res.isEmpty() )
      res += sep;
    res += i;
  }
  return res;
}

QByteArray Serializer::serialize( const QVariant &v )
{
  if ( !v.isValid() )
    return ""; // no parse error
  QByteArray str;
  bool error = false;

  // two major cases, either it's an array or ... not
  if ( v.canConvert<QVariantList>() ) {
    const QVariantList list = v.toList();
    QList<QByteArray> values;
    Q_FOREACH( const QVariant& v, list )
      values << serialize( v );
    str = "[ " + join( values, ", " ) + " ]";
  } else {
    // not a list, so it must be an object
    if ( !v.canConvert<QVariantMap>() ) {
      // not a map, so it must be a value
      if ( v.type() == QVariant::String )
        str = sanitizeString( v.toString() ).toUtf8();
      else
        str = v.toByteArray();
    } else {
      const QVariantMap vmap = v.toMap();
      QMapIterator<QString, QVariant> it( vmap );
      str = "{ ";
      QList<QByteArray> pairs;
      while ( it.hasNext() ) {
        it.next();
        pairs << sanitizeString(it.key()).toUtf8() + " : " + serialize(it.value() );
      }
      str += join( pairs, ", " );
      str += " }";
    }
  }
  if ( !error )
    return str;
  else
    return QByteArray();
}

<|endoftext|>


<commit_before>//
//  serializer.hpp
//  integral
//
//  Copyright (C) 2016  André Pereira Henriques
//  aphenriques (at) outlook (dot) com
//
//  This file is part of integral.
//
//  integral is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  integral is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with integral.  If not, see <http://www.gnu.org/licenses/>.
//

#ifndef integral_serializer_hpp
#define integral_serializer_hpp

#include <sstream>
#include <string>
#include <type_traits>
#include <typeinfo>
#include "generic.hpp"

namespace integral {
    namespace detail {
        namespace serializer {
            template <typename T, typename Enable = void>
            class Serializer {
            public:
                static std::string getString(const T &t) {
                    std::stringstream stringStream;
                    stringStream << "object:"<< typeid(t).name();
                    return stringStream.str();
                }
            };

            template <typename T>
            class Serializer<T, typename std::enable_if<std::is_arithmetic<T>::value>::type> {
            public:
                static std::string getString(const T &value) {
                    std::stringstream stringStream;
                    stringStream << std::boolalpha << value;
                    return stringStream.str();
                }
            };

            template <typename T>
            class Serializer<T, typename std::enable_if<std::is_same<T, std::string>::value || std::is_same<T, const char *>::value>::type> {
            public:
                static std::string getString(const T &value) {
                    std::stringstream stringStream;
                    stringStream << '"' << value << '"';
                    return stringStream.str();
                }
            };

            template<typename T>
            std::string getString(T &&t) {
                return Serializer<generic::BasicType<T>>::getString(std::forward<T>(t));
            }
        }
    }
}

#endif /* integral_serializer_hpp */
<commit_msg>definition separated from implementation<commit_after>//
//  serializer.hpp
//  integral
//
//  Copyright (C) 2016  André Pereira Henriques
//  aphenriques (at) outlook (dot) com
//
//  This file is part of integral.
//
//  integral is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  integral is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with integral.  If not, see <http://www.gnu.org/licenses/>.
//

#ifndef integral_serializer_hpp
#define integral_serializer_hpp

#include <sstream>
#include <string>
#include <type_traits>
#include <typeinfo>
#include "generic.hpp"

namespace integral {
    namespace detail {
        namespace serializer {
            template <typename T, typename Enable = void>
            class Serializer {
            public:
                static std::string getString(const T &t);
            };

            template <typename T>
            class Serializer<T, typename std::enable_if<std::is_arithmetic<T>::value>::type> {
            public:
                static std::string getString(const T &value);
            };

            template <typename T>
            class Serializer<T, typename std::enable_if<std::is_same<T, std::string>::value || std::is_same<T, const char *>::value>::type> {
            public:
                static std::string getString(const T &value);
            };

            template<typename T>
            inline std::string getString(T &&t);

            //--

            template <typename T, typename Enable>
            std::string Serializer<T, Enable>::getString(const T &t) {
                std::ostringstream stringStream;
                stringStream << "object:["<< typeid(t).name() << "]";
                return stringStream.str();
            }

            template<typename T>
            std::string Serializer<T, typename std::enable_if<std::is_arithmetic<T>::value>::type>::getString(const T &value) {
                std::ostringstream stringStream;
                stringStream << std::boolalpha << value;
                return stringStream.str();
            }

            template<typename T>
            std::string Serializer<T, typename std::enable_if<std::is_same<T, std::string>::value || std::is_same<T, const char *>::value>::type>::getString(const T &value) {
                std::ostringstream stringStream;
                stringStream << '"' << value << '"';
                return stringStream.str();
            }

            template<typename T>
            inline std::string getString(T &&t) {
                return Serializer<generic::BasicType<T>>::getString(std::forward<T>(t));
            }
        }
    }
}

#endif /* integral_serializer_hpp */
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2006-2014, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <cmake.h>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <cstring>
#include <string.h>

#include <text.h>
#include <i18n.h>
#include <Color.h>
#include <Context.h>
#include <Readline.h>

Context context;

#define MAX_ARGUMENTS 256

////////////////////////////////////////////////////////////////////////////////
int main (int argc, const char** argv)
{
  bool read_from_file = false;

  if (argc > 2)
  {
    std::cout << STRING_SHELL_USAGE << "\n";
    return -1;
  }
  else if (argc == 2)
  {
    if (!strcmp (argv[1], "--version"))
    {
      std::cout << VERSION << "\n";
      return 0;
    }
    else if (!strcmp (argv[1], "--help"))
    {
      std::cout << STRING_SHELL_USAGE << "\n";
      return 0;
    }
    else
    {
      // The user has given tasksh a task commands file to execute
      File input_file = File (argv[1]);
      if (!input_file.exists ())
      {
        std::cout << STRING_SHELL_NO_FILE;
        std::cout << STRING_SHELL_USAGE << "\n";
        return -1;
      }

      read_from_file = true;
    }
  }

  // If a file is given, read from it
  std::ifstream fin;
  if (read_from_file)
  {
    fin.open (argv[1]);
  }

  // Commands may be redirected too
  std::istream &in = read_from_file ? fin : std::cin;

  if (Readline::interactiveMode (in))
  {
    // Begining initilaization
    if (context.initialize (0, NULL))
    {
      return -1;
    }

    // Display some kind of welcome message.
    Color bold (Color::nocolor, Color::nocolor, false, true, false);

    std::cout << (context.color () ? bold.colorize (PACKAGE_STRING)
                                   : PACKAGE_STRING)
              << " shell\n\n"
              << STRING_CMD_SHELL_HELP1 << '\n'
              << STRING_CMD_SHELL_HELP2 << '\n'
              << STRING_CMD_SHELL_HELP3 << "\n\n";
  }

  // Make a copy because context.clear will delete them.
  std::string permanent_overrides;
  std::vector <Arg>::iterator i;
  for (i = context.a3.begin (); i != context.a3.end (); ++i)
  {
    if (i->_category == Arg::cat_rc ||
        i->_category == Arg::cat_override)
    {
      if (i != context.a3.begin ())
        permanent_overrides += " ";

      permanent_overrides += i->_raw;
    }
  }

  std::string input;

  std::vector <std::string> quit_commands;
  quit_commands.push_back ("quit");
  quit_commands.push_back ("exit");
  quit_commands.push_back ("bye");

  // The event loop.
  while (in)
  {
    std::string prompt (context.config.get ("shell.prompt") + " ");
    context.clear ();

    if (Readline::interactiveMode (in))
    {
      input = Readline::gets (prompt);

      // if a string has nothing but whitespaces, ignore it
      if (input.find_first_not_of (" \t") == std::string::npos)
        continue;
    }
    else
    {
      std::getline (in, input);

      // if a string has nothing but whitespaces, ignore it
      if (input.find_first_not_of (" \t") == std::string::npos)
        continue;

      std::cout << prompt << input << '\n';
    }

    try
    {
#ifdef HAVE_WORDEXP
      std::string command = "task " + trim (input + permanent_overrides);

      // Escape special chars.
      size_t i = 0;
      while ((i = command.find_first_of ("$*?!|&;<>(){}~#@", i)) != std::string::npos)
      {
        command.insert(i, 1, '\\');
        i += 2;
      }

      // Perform expansion.
      wordexp_t p;
      wordexp (command.c_str (), &p, 0);
      char** w = p.we_wordv;

      for (int i = 0; i < p.we_wordc; ++i)
      {
        if (std::find (quit_commands.begin (), quit_commands.end (),
                       lowerCase (w[i])) != quit_commands.end ())
        {
          context.clearMessages ();
          return 0;
        }
      }

      int status = context.initialize (p.we_wordc, (const char**)p.we_wordv);
      wordfree(&p);
#else
      std::string command = "task " + trim (input + permanent_overrides);
      int arg_count = 0;
      char* arg_vector[MAX_ARGUMENTS];

      char* arg = strtok ((char*)command.c_str (), " ");
      while (arg && arg_count < MAX_ARGUMENTS)
      {
        arg_vector[arg_count++] = arg;
        arg = strtok (0, " ");
      }

      for (int i = 1; i < arg_count; ++i)
      {
        if (std::find (quit_commands.begin (), quit_commands.end (),
                       lowerCase (arg_vector[i])) != quit_commands.end ())
        {
          context.clearMessages ();
          return 0;
        }
      }

      int status = context.initialize (arg_count, (const char**) arg_vector);
#endif

      if (status == 0)
        context.run ();
    }

    catch (const std::string& error)
    {
      std::cerr << error << '\n';
      return -1;
    }

    catch (...)
    {
      std::cerr << STRING_UNKNOWN_ERROR << '\n';
      return -2;
    }
  }

  return 0;
}

////////////////////////////////////////////////////////////////////////////////
<commit_msg>taskshell<commit_after>////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2006-2014, Paul Beckingham, Federico Hernandez.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#include <cmake.h>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <cstring>
#include <string.h>

#include <text.h>
#include <i18n.h>
#include <Color.h>
#include <Context.h>
#include <Readline.h>

Context context;

#define MAX_ARGUMENTS 256

////////////////////////////////////////////////////////////////////////////////
int main (int argc, const char** argv)
{
  bool read_from_file = false;

  if (argc > 2)
  {
    std::cout << STRING_SHELL_USAGE << "\n";
    return -1;
  }
  else if (argc == 2)
  {
    if (!strcmp (argv[1], "--version"))
    {
      std::cout << VERSION << "\n";
      return 0;
    }
    else if (!strcmp (argv[1], "--help"))
    {
      std::cout << STRING_SHELL_USAGE << "\n";
      return 0;
    }
    else
    {
      // The user has given tasksh a task commands file to execute
      File input_file = File (argv[1]);
      if (!input_file.exists ())
      {
        std::cout << STRING_SHELL_NO_FILE;
        std::cout << STRING_SHELL_USAGE << "\n";
        return -1;
      }

      read_from_file = true;
    }
  }

  // If a file is given, read from it
  std::ifstream fin;
  if (read_from_file)
  {
    fin.open (argv[1]);
  }

  // Commands may be redirected too
  std::istream &in = read_from_file ? fin : std::cin;

  if (Readline::interactiveMode (in))
  {
    // Begining initilaization
    if (context.initialize (0, NULL))
    {
      return -1;
    }

    // Display some kind of welcome message.
    Color bold (Color::nocolor, Color::nocolor, false, true, false);

    std::cout << (context.color () ? bold.colorize (PACKAGE_STRING)
                                   : PACKAGE_STRING)
              << " shell\n\n"
              << STRING_CMD_SHELL_HELP1 << '\n'
              << STRING_CMD_SHELL_HELP2 << '\n'
              << STRING_CMD_SHELL_HELP3 << "\n\n";
  }

  // Make a copy because context.clear will delete them.
  std::string permanent_overrides;
  std::vector <Arg>::iterator i;
  for (i = context.a3.begin (); i != context.a3.end (); ++i)
  {
    if (i->_category == Arg::cat_rc ||
        i->_category == Arg::cat_override)
    {
      if (i != context.a3.begin ())
        permanent_overrides += " ";

      permanent_overrides += i->_raw;
    }
  }

  std::string input;

  std::vector <std::string> quit_commands;
  quit_commands.push_back ("quit");
  quit_commands.push_back ("exit");
  quit_commands.push_back ("bye");

  // The event loop.
  while (in)
  {
    std::string prompt (context.config.get ("shell.prompt") + " ");
    context.clear ();

    if (Readline::interactiveMode (in))
    {
      input = Readline::gets (prompt);

      // if a string has nothing but whitespaces, ignore it
      if (input.find_first_not_of (" \t") == std::string::npos)
        continue;
    }
    else
    {
      std::getline (in, input);

      // if a string has nothing but whitespaces, ignore it
      if (input.find_first_not_of (" \t") == std::string::npos)
        continue;

      std::cout << prompt << input << '\n';
    }

    try
    {
#ifdef HAVE_WORDEXP
      std::string command = "task " + trim (input + permanent_overrides);

      // Escape special chars.
      size_t i = 0;
      while ((i = command.find_first_of ("$*?!|&;<>(){}~#@", i)) != std::string::npos)
      {
        command.insert(i, 1, '\\');
        i += 2;
      }

      // Perform expansion.
      wordexp_t p;
      wordexp (command.c_str (), &p, 0);
      char** w = p.we_wordv;

      for (int i = 0; i < p.we_wordc; ++i)
      {
        if (std::find (quit_commands.begin (), quit_commands.end (),
                       lowerCase (w[i])) != quit_commands.end ())
        {
          context.clearMessages ();
          return 0;
        }
      }

      // External calls.
      if (strcmp (w[1], "xc") == 0 && p.we_wordc > 2)
      {
        std::string combined = "";
        for (int i = 2; i < p.we_wordc - 1 ; ++i)
        {
          combined += std::string (w[i]) + " ";
        }
        combined += w[p.we_wordc - 1];          // last goes without a blank
        system (combined.c_str ());             // not checked
        continue;
      }

      int status = context.initialize (p.we_wordc, (const char**)p.we_wordv);
      wordfree(&p);
#else
      std::string command = "task " + trim (input + permanent_overrides);
      int arg_count = 0;
      char* arg_vector[MAX_ARGUMENTS];

      char* arg = strtok ((char*)command.c_str (), " ");
      while (arg && arg_count < MAX_ARGUMENTS)
      {
        arg_vector[arg_count++] = arg;
        arg = strtok (0, " ");
      }

      for (int i = 1; i < arg_count; ++i)
      {
        if (std::find (quit_commands.begin (), quit_commands.end (),
                       lowerCase (arg_vector[i])) != quit_commands.end ())
        {
          context.clearMessages ();
          return 0;
        }
      }

      int status = context.initialize (arg_count, (const char**) arg_vector);
#endif

      if (status == 0)
        context.run ();
    }

    catch (const std::string& error)
    {
      std::cerr << error << '\n';
      return -1;
    }

    catch (...)
    {
      std::cerr << STRING_UNKNOWN_ERROR << '\n';
      return -2;
    }
  }

  return 0;
}

////////////////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "Test.h"
#include "SkPathMeasure.h"

static void TestPathMeasure(skiatest::Reporter* reporter) {
    SkPath  path;

    path.moveTo(0, 0);
    path.lineTo(SK_Scalar1, 0);
    path.lineTo(SK_Scalar1, SK_Scalar1);
    path.lineTo(0, SK_Scalar1);

    SkPathMeasure   meas(path, true);
    SkScalar        length = meas.getLength();
    SkASSERT(length == SK_Scalar1*4);

    path.reset();
    path.moveTo(0, 0);
    path.lineTo(SK_Scalar1*3, SK_Scalar1*4);
    meas.setPath(&path, false);
    length = meas.getLength();
    REPORTER_ASSERT(reporter, length == SK_Scalar1*5);

    path.reset();
    path.addCircle(0, 0, SK_Scalar1);
    meas.setPath(&path, true);
    length = meas.getLength();
//    SkDebugf("circle arc-length = %g\n", length);

    for (int i = 0; i < 8; i++) {
        SkScalar    d = length * i / 8;
        SkPoint     p;
        SkVector    v;
        meas.getPosTan(d, &p, &v);
#if 0
        SkDebugf("circle arc-length=%g, pos[%g %g] tan[%g %g]\n",
                 d, p.fX, p.fY, v.fX, v.fY);
#endif
    }
}

#include "TestClassDef.h"
DEFINE_TESTCLASS("PathMeasure", PathMeasureTestClass, TestPathMeasure)
<commit_msg>Adding new SkPathMeasure tests, defined out for now as they fail. Review URL: http://codereview.appspot.com/5529078<commit_after>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "Test.h"
#include "SkPathMeasure.h"

static void TestPathMeasure(skiatest::Reporter* reporter) {
    SkPath  path;

    path.moveTo(0, 0);
    path.lineTo(SK_Scalar1, 0);
    path.lineTo(SK_Scalar1, SK_Scalar1);
    path.lineTo(0, SK_Scalar1);

    SkPathMeasure   meas(path, true);
    SkScalar        length = meas.getLength();
    SkASSERT(length == SK_Scalar1*4);

    path.reset();
    path.moveTo(0, 0);
    path.lineTo(SK_Scalar1*3, SK_Scalar1*4);
    meas.setPath(&path, false);
    length = meas.getLength();
    REPORTER_ASSERT(reporter, length == SK_Scalar1*5);

    path.reset();
    path.addCircle(0, 0, SK_Scalar1);
    meas.setPath(&path, true);
    length = meas.getLength();
//    SkDebugf("circle arc-length = %g\n", length);

    for (int i = 0; i < 8; i++) {
        SkScalar    d = length * i / 8;
        SkPoint     p;
        SkVector    v;
        meas.getPosTan(d, &p, &v);
#if 0
        SkDebugf("circle arc-length=%g, pos[%g %g] tan[%g %g]\n",
                 d, p.fX, p.fY, v.fX, v.fY);
#endif
    }

#if 0
    // Test the behavior following a close not followed by a move.
    path.reset();
    path.lineTo(SK_Scalar1, 0);
    path.lineTo(SK_Scalar1, SK_Scalar1);
    path.lineTo(0, SK_Scalar1);
    path.close();
    path.lineTo(-SK_Scalar1, 0);
    meas.setPath(&path, false);
    length = meas.getLength();
    REPORTER_ASSERT(reporter, length == SK_Scalar1 * 4);
    meas.nextContour();
    length = meas.getLength();
    REPORTER_ASSERT(reporter, length == SK_Scalar1);
    SkPoint position;
    SkVector tangent;
    REPORTER_ASSERT(reporter, meas.getPosTan(SK_ScalarHalf, &position, &tangent));
    REPORTER_ASSERT(reporter,
        SkScalarNearlyEqual(position.fX, -SK_ScalarHalf, SK_Scalar1 * 0.0001));
    REPORTER_ASSERT(reporter, position.fY == 0);
    REPORTER_ASSERT(reporter, tangent.fX == -SK_Scalar1);
    REPORTER_ASSERT(reporter, tangent.fY == 0);

    // Test degenerate paths
    path.reset();
    path.moveTo(0, 0);
    path.lineTo(0, 0);
    path.lineTo(SK_Scalar1, 0);
    path.quadTo(SK_Scalar1, 0, SK_Scalar1, 0);
    path.quadTo(SK_Scalar1, SK_Scalar1, SK_Scalar1, SK_Scalar1 * 2);
    path.cubicTo(SK_Scalar1, SK_Scalar1 * 2,
                 SK_Scalar1, SK_Scalar1 * 2,
                 SK_Scalar1, SK_Scalar1 * 2);
    path.cubicTo(SK_Scalar1*2, SK_Scalar1 * 2,
                 SK_Scalar1*3, SK_Scalar1 * 2,
                 SK_Scalar1*4, SK_Scalar1 * 2);
    meas.setPath(&path, false);
    length = meas.getLength();
    REPORTER_ASSERT(reporter, length == SK_Scalar1 * 6);
    REPORTER_ASSERT(reporter, meas.getPosTan(SK_ScalarHalf, &position, &tangent));
    REPORTER_ASSERT(reporter,
        SkScalarNearlyEqual(position.fX, SK_ScalarHalf, SK_Scalar1 * 0.0001));
    REPORTER_ASSERT(reporter, position.fY == 0);
    REPORTER_ASSERT(reporter, tangent.fX == SK_Scalar1);
    REPORTER_ASSERT(reporter, tangent.fY == 0);
    REPORTER_ASSERT(reporter, meas.getPosTan(SK_Scalar1 * 2.5f, &position, &tangent));
    REPORTER_ASSERT(reporter,
        SkScalarNearlyEqual(position.fX, SK_Scalar1, SK_Scalar1 * 0.0001));
    REPORTER_ASSERT(reporter,
        SkScalarNearlyEqual(position.fY, SK_Scalar1 * 1.5f));
    REPORTER_ASSERT(reporter, tangent.fX == 0);
    REPORTER_ASSERT(reporter, tangent.fY == SK_Scalar1);
    REPORTER_ASSERT(reporter, meas.getPosTan(SK_Scalar1 * 4.5f, &position, &tangent));
    REPORTER_ASSERT(reporter,
        SkScalarNearlyEqual(position.fX, SK_Scalar1 * 2.5f, SK_Scalar1 * 0.0001));
    REPORTER_ASSERT(reporter,
        SkScalarNearlyEqual(position.fY, SK_Scalar1 * 2.0f, SK_Scalar1 * 0.0001));
    REPORTER_ASSERT(reporter, tangent.fX == SK_Scalar1);
    REPORTER_ASSERT(reporter, tangent.fY == 0);

    path.reset();
    path.moveTo(0, 0);
    path.lineTo(SK_Scalar1, 0);
    path.moveTo(SK_Scalar1, SK_Scalar1);
    path.moveTo(SK_Scalar1 * 2, SK_Scalar1 * 2);
    path.lineTo(SK_Scalar1, SK_Scalar1 * 2);
    meas.setPath(&path, false);
    length = meas.getLength();
    REPORTER_ASSERT(reporter, length == SK_Scalar1);
    REPORTER_ASSERT(reporter, meas.getPosTan(SK_ScalarHalf, &position, &tangent));
    REPORTER_ASSERT(reporter,
        SkScalarNearlyEqual(position.fX, SK_ScalarHalf, SK_Scalar1 * 0.0001));
    REPORTER_ASSERT(reporter, position.fY == 0);
    REPORTER_ASSERT(reporter, tangent.fX == SK_Scalar1);
    REPORTER_ASSERT(reporter, tangent.fY == 0);
    meas.nextContour();
    length = meas.getLength();
    REPORTER_ASSERT(reporter, length == SK_Scalar1);
    REPORTER_ASSERT(reporter, meas.getPosTan(SK_ScalarHalf, &position, &tangent));
    REPORTER_ASSERT(reporter,
        SkScalarNearlyEqual(position.fX, SK_Scalar1 * 1.5f, SK_Scalar1 * 0.0001));
    REPORTER_ASSERT(reporter,
        SkScalarNearlyEqual(position.fY, SK_Scalar1 * 2.0f, SK_Scalar1 * 0.0001));
    REPORTER_ASSERT(reporter, tangent.fX == -SK_Scalar1);
    REPORTER_ASSERT(reporter, tangent.fY == 0);
#endif
}

#include "TestClassDef.h"
DEFINE_TESTCLASS("PathMeasure", PathMeasureTestClass, TestPathMeasure)
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Leiden University Medical Center, Erasmus University Medical
 *  Center and contributors
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "selxElastixComponent.h"

namespace selx
{
  template<int Dimensionality, class TPixel>
  ElastixComponent< Dimensionality, TPixel>::ElastixComponent()
  {
    m_elastixFilter = ElastixFilterType::New();
    m_transformixFilter = TransformixFilterType::New();

    // TODO: Due to some issues with Criteria being propagated as elastix settings, I need to empty the selxparameterObject.
    elxParameterObjectPointer elxParameterObject = elxParameterObjectType::New();
    typename elxParameterObjectType::ParameterMapType defaultParameters = elxParameterObject->GetDefaultParameterMap("rigid");

    elxParameterObject->SetParameterMap(defaultParameters);
    m_elastixFilter->SetParameterObject(elxParameterObject);

    m_elastixFilter->LogToConsoleOn();

    m_transformixFilter->ComputeDeformationFieldOn();
    m_transformixFilter->LogToConsoleOn();
    m_transformixFilter->LogToFileOn();
    // In the current transformix filter an input image is required even if we want a deformation field only.
    m_transformixFilter->SetInput(m_elastixFilter->GetOutput());

    //TODO m_elastixFilter returns a nullptr GetTransformParameterObject instead of a valid object. However, we need this object to satisfy the input conditions of m_transformixFilter
    //m_transformixFilter->SetTransformParameterObject(m_elastixFilter->GetTransformParameterObject());
    m_transformixFilter->SetTransformParameterObject(elxParameterObject); // supply a dummy object

    //TODO: instantiating the filter in the constructor might be heavy for the use in component selector factory, since all components of the database are created during the selection process.
    // we could choose to keep the component light weighted (for checking criteria such as names and connections) until the settings are passed to the filter, but this requires an additional initialization step.
  }

  template<int Dimensionality, class TPixel>
  ElastixComponent< Dimensionality, TPixel>::~ElastixComponent()
  {
  }

  template<int Dimensionality, class TPixel>
  int ElastixComponent< Dimensionality, TPixel>::Set(itkImageFixedInterface<Dimensionality, TPixel>* component)
  {
    auto fixedImage = component->GetItkImageFixed();
    // connect the itk pipeline
    this->m_elastixFilter->SetFixedImage(fixedImage);
    return 0;
  }

  template<int Dimensionality, class TPixel>
  int ElastixComponent< Dimensionality, TPixel>::Set(itkImageMovingInterface<Dimensionality, TPixel>* component)
  {
    auto movingImage = component->GetItkImageMoving();
    // connect the itk pipeline
    this->m_elastixFilter->SetMovingImage(movingImage);
    return 0;
  }

  //Since elastixFilter is not a true itkfilter we cannot use itkImageSourceInterface (yet)
  /*template<int Dimensionality, class TPixel>
  typename ElastixComponent< Dimensionality, TPixel>::ItkImageSourcePointer ElastixComponent< Dimensionality, TPixel>::GetItkImageSource()
  {

    return (ItkImageSourcePointer) this->m_theItkFilter;
  }
  */

  template<int Dimensionality, class TPixel>
  typename ElastixComponent< Dimensionality, TPixel>::ItkImagePointer ElastixComponent< Dimensionality, TPixel>::GetItkImage()
  {
    return this->m_transformixFilter->GetOutput();
  }

  template<int Dimensionality, class TPixel>
  void ElastixComponent< Dimensionality, TPixel>::RunRegistration(void)
  {
    // TODO currently, the pipeline with elastix and tranformix can only be created after the update of elastix
    this->m_elastixFilter->Update();
    this->m_transformixFilter->SetTransformParameterObject(this->m_elastixFilter->GetTransformParameterObject());
    this->m_transformixFilter->Update();
  }

  template<int Dimensionality, class TPixel>
  bool
    ElastixComponent< Dimensionality, TPixel>
    ::MeetsCriterion(const CriterionType &criterion)
  {
    bool hasUndefinedCriteria(false);
    bool meetsCriteria(false);
    if (criterion.first == "ComponentProperty")
    {
      meetsCriteria = true;
      for (auto const & criterionValue : criterion.second) // auto&& preferred?
      {
        if (criterionValue != "SomeProperty")  // e.g. "GradientDescent", "SupportsSparseSamples
        {
          meetsCriteria = false;
        }
      }
    }
    else if (criterion.first == "Dimensionality") //Supports this?
    {
      meetsCriteria = true;
      for (auto const & criterionValue : criterion.second) // auto&& preferred?
      {
        if (std::stoi(criterionValue) != Dimensionality)
        {
          meetsCriteria = false;
        }
      }

    }
    else if (criterion.first == "PixelType") //Supports this?
    {
      meetsCriteria = true;
      for (auto const & criterionValue : criterion.second) // auto&& preferred?
      {
        if (criterionValue != Self::GetPixelTypeNameString())
        {
          meetsCriteria = false;
        }
      }

    }
    else if (criterion.first == "RegistrationPreset") //Supports this?
    {
      // Temporary solution: RegistrationPreset: rigid, nonrigid, etc overwrite the current selxparameterObject.
      // Warning: the order of Criteria matters, since selxparameterObject may be overwritten
      // Warning: this probably fails because the Criteria map entries are processed in arbitrary order.

      elxParameterObjectPointer elxParameterObject = elxParameterObjectType::New();

      meetsCriteria = true;
      for (auto const & presetName : criterion.second) // auto&& preferred?
      {
        typename elxParameterObjectType::ParameterMapType presetParameters = elxParameterObject->GetDefaultParameterMap(presetName);
        elxParameterObject->SetParameterMap(presetParameters);

        try
        {
          this->m_elastixFilter->SetParameterObject(elxParameterObject);
        }
        catch (itk::ExceptionObject & err)
        {
          std::cout << err;
          //TODO log the error message?
          meetsCriteria = false;
        }
      }

    }
    else
    {
      // temporary solution: pass all SuperElastixComponent parameters as is to elastix. This should be defined in deeper hierarchy of the criteria, but for now we have a flat mapping only.
      elxParameterObjectPointer elxParameterObject = this->m_elastixFilter->GetParameterObject();
      typename elxParameterObjectType::ParameterMapType newParameterMap = elxParameterObject->GetParameterMap(0); //copy const paramtermap to a non const map
      newParameterMap[criterion.first] = criterion.second; //overwrite element
      elxParameterObjectPointer newParameterObject = elxParameterObjectType::New();
      newParameterObject->SetParameterMap(newParameterMap);
      this->m_elastixFilter->SetParameterObject(newParameterObject);
      meetsCriteria = true;
    }
    return meetsCriteria;
  }

} //end namespace selx
<commit_msg>BUG: elastix/transformix require output directory to be set explicitly<commit_after>/*=========================================================================
 *
 *  Copyright Leiden University Medical Center, Erasmus University Medical
 *  Center and contributors
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "selxElastixComponent.h"

namespace selx
{
  template<int Dimensionality, class TPixel>
  ElastixComponent< Dimensionality, TPixel>::ElastixComponent()
  {
    m_elastixFilter = ElastixFilterType::New();
    m_transformixFilter = TransformixFilterType::New();

    // TODO: Due to some issues with Criteria being propagated as elastix settings, I need to empty the selxparameterObject.
    elxParameterObjectPointer elxParameterObject = elxParameterObjectType::New();
    typename elxParameterObjectType::ParameterMapType defaultParameters = elxParameterObject->GetDefaultParameterMap("rigid");

    elxParameterObject->SetParameterMap(defaultParameters);
    m_elastixFilter->SetParameterObject(elxParameterObject);
    m_elastixFilter->LogToConsoleOn();
    m_elastixFilter->LogToFileOff();
    m_elastixFilter->SetOutputDirectory(".");

    m_transformixFilter->ComputeDeformationFieldOn();
    m_transformixFilter->LogToConsoleOn();
    m_transformixFilter->LogToFileOff();
    m_transformixFilter->SetOutputDirectory(".");

    // In the current transformix filter an input image is required even if we want a deformation field only.
    m_transformixFilter->SetInput(m_elastixFilter->GetOutput());

    //TODO m_elastixFilter returns a nullptr GetTransformParameterObject instead of a valid object. However, we need this object to satisfy the input conditions of m_transformixFilter
    //m_transformixFilter->SetTransformParameterObject(m_elastixFilter->GetTransformParameterObject());
    m_transformixFilter->SetTransformParameterObject(elxParameterObject); // supply a dummy object

    //TODO: instantiating the filter in the constructor might be heavy for the use in component selector factory, since all components of the database are created during the selection process.
    // we could choose to keep the component light weighted (for checking criteria such as names and connections) until the settings are passed to the filter, but this requires an additional initialization step.
  }

  template<int Dimensionality, class TPixel>
  ElastixComponent< Dimensionality, TPixel>::~ElastixComponent()
  {
  }

  template<int Dimensionality, class TPixel>
  int ElastixComponent< Dimensionality, TPixel>::Set(itkImageFixedInterface<Dimensionality, TPixel>* component)
  {
    auto fixedImage = component->GetItkImageFixed();
    // connect the itk pipeline
    this->m_elastixFilter->SetFixedImage(fixedImage);
    return 0;
  }

  template<int Dimensionality, class TPixel>
  int ElastixComponent< Dimensionality, TPixel>::Set(itkImageMovingInterface<Dimensionality, TPixel>* component)
  {
    auto movingImage = component->GetItkImageMoving();
    // connect the itk pipeline
    this->m_elastixFilter->SetMovingImage(movingImage);
    return 0;
  }

  //Since elastixFilter is not a true itkfilter we cannot use itkImageSourceInterface (yet)
  /*template<int Dimensionality, class TPixel>
  typename ElastixComponent< Dimensionality, TPixel>::ItkImageSourcePointer ElastixComponent< Dimensionality, TPixel>::GetItkImageSource()
  {

    return (ItkImageSourcePointer) this->m_theItkFilter;
  }
  */

  template<int Dimensionality, class TPixel>
  typename ElastixComponent< Dimensionality, TPixel>::ItkImagePointer ElastixComponent< Dimensionality, TPixel>::GetItkImage()
  {
    return this->m_transformixFilter->GetOutput();
  }

  template<int Dimensionality, class TPixel>
  void ElastixComponent< Dimensionality, TPixel>::RunRegistration(void)
  {
    // TODO currently, the pipeline with elastix and tranformix can only be created after the update of elastix
    this->m_elastixFilter->Update();
    this->m_transformixFilter->SetTransformParameterObject(this->m_elastixFilter->GetTransformParameterObject());
    this->m_transformixFilter->Update();
  }

  template<int Dimensionality, class TPixel>
  bool
    ElastixComponent< Dimensionality, TPixel>
    ::MeetsCriterion(const CriterionType &criterion)
  {
    bool hasUndefinedCriteria(false);
    bool meetsCriteria(false);
    if (criterion.first == "ComponentProperty")
    {
      meetsCriteria = true;
      for (auto const & criterionValue : criterion.second) // auto&& preferred?
      {
        if (criterionValue != "SomeProperty")  // e.g. "GradientDescent", "SupportsSparseSamples
        {
          meetsCriteria = false;
        }
      }
    }
    else if (criterion.first == "Dimensionality") //Supports this?
    {
      meetsCriteria = true;
      for (auto const & criterionValue : criterion.second) // auto&& preferred?
      {
        if (std::stoi(criterionValue) != Dimensionality)
        {
          meetsCriteria = false;
        }
      }

    }
    else if (criterion.first == "PixelType") //Supports this?
    {
      meetsCriteria = true;
      for (auto const & criterionValue : criterion.second) // auto&& preferred?
      {
        if (criterionValue != Self::GetPixelTypeNameString())
        {
          meetsCriteria = false;
        }
      }

    }
    else if (criterion.first == "RegistrationPreset") //Supports this?
    {
      // Temporary solution: RegistrationPreset: rigid, nonrigid, etc overwrite the current selxparameterObject.
      // Warning: the order of Criteria matters, since selxparameterObject may be overwritten
      // Warning: this probably fails because the Criteria map entries are processed in arbitrary order.

      elxParameterObjectPointer elxParameterObject = elxParameterObjectType::New();

      meetsCriteria = true;
      for (auto const & presetName : criterion.second) // auto&& preferred?
      {
        typename elxParameterObjectType::ParameterMapType presetParameters = elxParameterObject->GetDefaultParameterMap(presetName);
        elxParameterObject->SetParameterMap(presetParameters);

        try
        {
          this->m_elastixFilter->SetParameterObject(elxParameterObject);
        }
        catch (itk::ExceptionObject & err)
        {
          std::cout << err;
          //TODO log the error message?
          meetsCriteria = false;
        }
      }

    }
    else
    {
      // temporary solution: pass all SuperElastixComponent parameters as is to elastix. This should be defined in deeper hierarchy of the criteria, but for now we have a flat mapping only.
      elxParameterObjectPointer elxParameterObject = this->m_elastixFilter->GetParameterObject();
      typename elxParameterObjectType::ParameterMapType newParameterMap = elxParameterObject->GetParameterMap(0); //copy const paramtermap to a non const map
      newParameterMap[criterion.first] = criterion.second; //overwrite element
      elxParameterObjectPointer newParameterObject = elxParameterObjectType::New();
      newParameterObject->SetParameterMap(newParameterMap);
      this->m_elastixFilter->SetParameterObject(newParameterObject);
      meetsCriteria = true;
    }
    return meetsCriteria;
  }

} //end namespace selx
<|endoftext|>


<commit_before>#include <chrono>
#include <thread>
#include <iostream>

#include "simulation.hpp"
#include "event.hpp"

#define LOGURU_WITH_STREAMS 1
#include "loguru.hpp"

namespace config  // some of these may later be read from config files
{

const float threshold = 0.01;

}

namespace sim
{

Simulation::Simulation( std::string _scenario_fname )
{
  scenario_fname = _scenario_fname;
  user_command_received = false;
  quit_now = false;
  restart = false;
}

void
Simulation::run()
{
  using namespace std::chrono_literals;

  loguru::set_thread_name("sim manager");

  Scenario scenario( scenario_fname );
  for( ;; )
  {
    if( scenario.requires_recompute() ) { recompute_with( scenario ); }

    std::unique_lock<std::mutex> lk( user_command_mutex );
    cv.wait_for( lk, 500ms );
    // Spurious wake ups are not a problem here
    if( quit_now ) break;

    scenario.reload_changes();
  }

  if( compute_thread.joinable() ) compute_thread.join();
}

void
Simulation::recompute_with( const Scenario& new_scenario )
{
  restart = true;
  if( compute_thread.joinable() ) compute_thread.join();

  // once more unto the breach
  compute_thread = std::thread(
    &sim::Simulation::compute,
    std::ref( *this ),
    new_scenario
  );
}

void
Simulation::wait()
{
  std::unique_lock<std::mutex> lk( user_command_mutex );
  cv.wait(lk, [this](){ return user_command_received; });  // protects against spurious unblocks
  user_command_received = false;
}

void
Simulation::quit()
{
  std::lock_guard<std::mutex> lk( user_command_mutex );
  user_command_received = true;
  quit_now = true;
  cv.notify_one();
}

void
Simulation::compute( Scenario scenario )
{
  loguru::set_thread_name("compute");

  load( scenario );

  restart = false;
  DLOG_S(INFO) << "Starting simulation: " << scenario.start_jd << " - " << scenario.stop_jd;

  double jd = scenario.start_jd;
  while( !restart & !quit_now & ( jd < scenario.stop_jd ) )
  {
    step( jd, scenario.step_jd);
    jd += scenario.step_jd;
    //std::cout << jd << std::endl;
  }
  mark_sim_buffers_as_ready();

  DLOG_S(INFO) << "Stopping simulation: " << jd;
}

void
Simulation::step( double jd, double dt )
{
  propagate_orrery( jd, dt );
  compute_g();
  propagate_space_fleet( jd, dt );
  resolve_actions( jd );
}

void
Simulation::propagate_orrery( double jd, double dt )
{
  for( auto& b : orrery_bodies )
    b.step( jd, dt );
}

void
Simulation::compute_g()
{
  for( auto& b : orrery_bodies ) {
    for( auto& s : space_ships ) {
      Vector R = b.pos - s.pos;
      // Good time to check for collisions too! TODO
      s.accel += (b.GM / R.norm_sq()) * R / R.norm();
    }
  }
}

void
Simulation::propagate_space_fleet( double jd, double dt )
{
  for( auto& s : space_ships )
  {
    //bool bingo_fuel = false;
    s.step( jd, dt);
    // if( bingo_fuel )
    // {
    //   // checkpoints.push_back( checkpointp_t( new Event(
    //   //   jd,
    //   //   EventType::BingoFuel,
    //   //   v.name,
    //   //   ""
    //   // )));
    // }
  }
}

void
Simulation::resolve_actions( double jd )
{

}

void
Simulation::mark_sim_buffers_as_ready()
{
  for( auto& b : orrery_bodies ) { b.mark_buffer_as_ready(); }
  for( auto& s : space_ships ) { s.mark_buffer_as_ready(); }
}

void
Simulation::load( Scenario& new_scenario )
{
  copy_mutex.lock();
  // This changes the simulation contents, so we need to lock/unlock

  // Safest to explicitly delete
  orrery_bodies.clear();
  space_ships.clear();

  sim_version_no++;

  // XXX Just for testing
  orrery_bodies = load_debugging_orrery();
  for( auto& b : orrery_bodies ) { b.tolerance_sq = 0.01; }

  copy_mutex.unlock();
}

} // namespace sim
<commit_msg>log: now printing number of sim steps<commit_after>#include <chrono>
#include <thread>
#include <iostream>

#include "simulation.hpp"
#include "event.hpp"

#define LOGURU_WITH_STREAMS 1
#include "loguru.hpp"

namespace config  // some of these may later be read from config files
{

const float threshold = 0.01;

}

namespace sim
{

Simulation::Simulation( std::string _scenario_fname )
{
  scenario_fname = _scenario_fname;
  user_command_received = false;
  quit_now = false;
  restart = false;
}

void
Simulation::run()
{
  using namespace std::chrono_literals;

  loguru::set_thread_name("sim manager");

  Scenario scenario( scenario_fname );
  for( ;; )
  {
    if( scenario.requires_recompute() ) { recompute_with( scenario ); }

    std::unique_lock<std::mutex> lk( user_command_mutex );
    cv.wait_for( lk, 500ms );
    // Spurious wake ups are not a problem here
    if( quit_now ) break;

    scenario.reload_changes();
  }

  if( compute_thread.joinable() ) compute_thread.join();
}

void
Simulation::recompute_with( const Scenario& new_scenario )
{
  restart = true;
  if( compute_thread.joinable() ) compute_thread.join();

  // once more unto the breach
  compute_thread = std::thread(
    &sim::Simulation::compute,
    std::ref( *this ),
    new_scenario
  );
}

void
Simulation::wait()
{
  std::unique_lock<std::mutex> lk( user_command_mutex );
  cv.wait(lk, [this](){ return user_command_received; });  // protects against spurious unblocks
  user_command_received = false;
}

void
Simulation::quit()
{
  std::lock_guard<std::mutex> lk( user_command_mutex );
  user_command_received = true;
  quit_now = true;
  cv.notify_one();
}

void
Simulation::compute( Scenario scenario )
{
  loguru::set_thread_name("compute");

  load( scenario );

  restart = false;
  DLOG_S(INFO) << "Starting simulation: " << scenario.start_jd << " - " << scenario.stop_jd;

  int simulation_steps = 0;
  double jd = scenario.start_jd;
  while( !restart & !quit_now & ( jd < scenario.stop_jd ) )
  {
    step( jd, scenario.step_jd);
    jd += scenario.step_jd;
    simulation_steps++;
  }
  mark_sim_buffers_as_ready();

  DLOG_S(INFO) << "Stopping simulation: " << jd << " (" << simulation_steps << " steps)";
}

void
Simulation::step( double jd, double dt )
{
  propagate_orrery( jd, dt );
  compute_g();
  propagate_space_fleet( jd, dt );
  resolve_actions( jd );
}

void
Simulation::propagate_orrery( double jd, double dt )
{
  for( auto& b : orrery_bodies )
    b.step( jd, dt );
}

void
Simulation::compute_g()
{
  for( auto& b : orrery_bodies ) {
    for( auto& s : space_ships ) {
      Vector R = b.pos - s.pos;
      // Good time to check for collisions too! TODO
      s.accel += (b.GM / R.norm_sq()) * R / R.norm();
    }
  }
}

void
Simulation::propagate_space_fleet( double jd, double dt )
{
  for( auto& s : space_ships )
  {
    //bool bingo_fuel = false;
    s.step( jd, dt);
    // if( bingo_fuel )
    // {
    //   // checkpoints.push_back( checkpointp_t( new Event(
    //   //   jd,
    //   //   EventType::BingoFuel,
    //   //   v.name,
    //   //   ""
    //   // )));
    // }
  }
}

void
Simulation::resolve_actions( double jd )
{

}

void
Simulation::mark_sim_buffers_as_ready()
{
  for( auto& b : orrery_bodies ) { b.mark_buffer_as_ready(); }
  for( auto& s : space_ships ) { s.mark_buffer_as_ready(); }
}

void
Simulation::load( Scenario& new_scenario )
{
  copy_mutex.lock();
  // This changes the simulation contents, so we need to lock/unlock

  // Safest to explicitly delete
  orrery_bodies.clear();
  space_ships.clear();

  sim_version_no++;

  // XXX Just for testing
  orrery_bodies = load_debugging_orrery();
  for( auto& b : orrery_bodies ) { b.tolerance_sq = 0.01; }

  copy_mutex.unlock();
}

} // namespace sim
<|endoftext|>