CombinedText stringlengths 4 3.42M |
|---|
class Pnpm < Formula
require "language/node"
desc "📦🚀 Fast, disk space efficient package manager"
homepage "https://pnpm.io/"
url "https://registry.npmjs.org/pnpm/-/pnpm-6.32.7.tgz"
sha256 "3915b7e6deda1c8246052097f13b77b006856b5ae82eb296390113286096dfaa"
license "MIT"
livecheck do
url "https://registry.npmjs.org/pnpm/latest"
regex(/["']version["']:\s*?["']([^"']+)["']/i)
end
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "eb84077f7091cdb4998f7d9cbcdef0663f5005e8c99b1e32e55ca0a9241845ad"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "eb84077f7091cdb4998f7d9cbcdef0663f5005e8c99b1e32e55ca0a9241845ad"
sha256 cellar: :any_skip_relocation, monterey: "f3d85676f31743eaec772086bb95c74ea21d9f671d381b2f0fcd421223bc43b9"
sha256 cellar: :any_skip_relocation, big_sur: "662eb836285ff0d80be83e5449713c76253e51858ed9f95b83ec9d24c12dddff"
sha256 cellar: :any_skip_relocation, catalina: "662eb836285ff0d80be83e5449713c76253e51858ed9f95b83ec9d24c12dddff"
sha256 cellar: :any_skip_relocation, x86_64_linux: "eb84077f7091cdb4998f7d9cbcdef0663f5005e8c99b1e32e55ca0a9241845ad"
end
depends_on "node"
conflicts_with "corepack", because: "both installs `pnpm` and `pnpx` binaries"
def install
system "npm", "install", *Language::Node.std_npm_install_args(libexec)
bin.install_symlink Dir["#{libexec}/bin/*"]
end
test do
system "#{bin}/pnpm", "init", "-y"
assert_predicate testpath/"package.json", :exist?, "package.json must exist"
end
end
pnpm 6.32.8
Closes #99404.
Signed-off-by: Michka Popoff <5d406f95fb0e0230f83654e4a22d0115cc205d59@users.noreply.github.com>
Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com>
class Pnpm < Formula
require "language/node"
desc "📦🚀 Fast, disk space efficient package manager"
homepage "https://pnpm.io/"
url "https://registry.npmjs.org/pnpm/-/pnpm-6.32.8.tgz"
sha256 "174f17e00423c1ba1a4e382c89021feaa254cc4083e4bb433ed3ec0a0c21ff5a"
license "MIT"
livecheck do
url "https://registry.npmjs.org/pnpm/latest"
regex(/["']version["']:\s*?["']([^"']+)["']/i)
end
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "eb84077f7091cdb4998f7d9cbcdef0663f5005e8c99b1e32e55ca0a9241845ad"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "eb84077f7091cdb4998f7d9cbcdef0663f5005e8c99b1e32e55ca0a9241845ad"
sha256 cellar: :any_skip_relocation, monterey: "f3d85676f31743eaec772086bb95c74ea21d9f671d381b2f0fcd421223bc43b9"
sha256 cellar: :any_skip_relocation, big_sur: "662eb836285ff0d80be83e5449713c76253e51858ed9f95b83ec9d24c12dddff"
sha256 cellar: :any_skip_relocation, catalina: "662eb836285ff0d80be83e5449713c76253e51858ed9f95b83ec9d24c12dddff"
sha256 cellar: :any_skip_relocation, x86_64_linux: "eb84077f7091cdb4998f7d9cbcdef0663f5005e8c99b1e32e55ca0a9241845ad"
end
depends_on "node"
conflicts_with "corepack", because: "both installs `pnpm` and `pnpx` binaries"
def install
system "npm", "install", *Language::Node.std_npm_install_args(libexec)
bin.install_symlink Dir["#{libexec}/bin/*"]
end
test do
system "#{bin}/pnpm", "init", "-y"
assert_predicate testpath/"package.json", :exist?, "package.json must exist"
end
end
|
class Proj < Formula
desc "Cartographic Projections Library"
homepage "https://proj.org/"
url "https://github.com/OSGeo/PROJ/releases/download/7.1.0/proj-7.1.0.tar.gz"
sha256 "876151e2279346f6bdbc63bd59790b48733496a957bccd5e51b640fdd26eaa8d"
bottle do
sha256 "53ecef2f47a68f3408c6c1e4c1abe1fdd3359419b8aca0e307f5da6f4c878ec2" => :catalina
sha256 "4ff4088f982c26e43fd33e6eeef921a4731620ad55b8b3f91df1fc3fcdf3474f" => :mojave
sha256 "c68d5683285b248ef35d7709adf5f35ed0ca8158a633e6887a6990af65f03a85" => :high_sierra
end
head do
url "https://github.com/OSGeo/proj.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
end
depends_on "pkg-config" => :build
depends_on "libtiff"
uses_from_macos "curl"
uses_from_macos "sqlite"
conflicts_with "blast", because: "both install a `libproj.a` library"
skip_clean :la
# The datum grid files are required to support datum shifting
resource "datumgrid" do
url "https://download.osgeo.org/proj/proj-datumgrid-1.8.zip"
sha256 "b9838ae7e5f27ee732fb0bfed618f85b36e8bb56d7afb287d506338e9f33861e"
end
def install
(buildpath/"nad").install resource("datumgrid")
system "./autogen.sh" if build.head?
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make", "install"
end
test do
(testpath/"test").write <<~EOS
45d15n 71d07w Boston, United States
40d40n 73d58w New York, United States
48d51n 2d20e Paris, France
51d30n 7'w London, England
EOS
match = <<~EOS
-4887590.49\t7317961.48 Boston, United States
-5542524.55\t6982689.05 New York, United States
171224.94\t5415352.81 Paris, France
-8101.66\t5707500.23 London, England
EOS
output = shell_output("#{bin}/proj +proj=poly +ellps=clrk66 -r #{testpath}/test")
assert_equal match, output
end
end
proj: add license
class Proj < Formula
desc "Cartographic Projections Library"
homepage "https://proj.org/"
url "https://github.com/OSGeo/PROJ/releases/download/7.1.0/proj-7.1.0.tar.gz"
sha256 "876151e2279346f6bdbc63bd59790b48733496a957bccd5e51b640fdd26eaa8d"
license "MIT"
bottle do
sha256 "53ecef2f47a68f3408c6c1e4c1abe1fdd3359419b8aca0e307f5da6f4c878ec2" => :catalina
sha256 "4ff4088f982c26e43fd33e6eeef921a4731620ad55b8b3f91df1fc3fcdf3474f" => :mojave
sha256 "c68d5683285b248ef35d7709adf5f35ed0ca8158a633e6887a6990af65f03a85" => :high_sierra
end
head do
url "https://github.com/OSGeo/proj.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
end
depends_on "pkg-config" => :build
depends_on "libtiff"
uses_from_macos "curl"
uses_from_macos "sqlite"
conflicts_with "blast", because: "both install a `libproj.a` library"
skip_clean :la
# The datum grid files are required to support datum shifting
resource "datumgrid" do
url "https://download.osgeo.org/proj/proj-datumgrid-1.8.zip"
sha256 "b9838ae7e5f27ee732fb0bfed618f85b36e8bb56d7afb287d506338e9f33861e"
end
def install
(buildpath/"nad").install resource("datumgrid")
system "./autogen.sh" if build.head?
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make", "install"
end
test do
(testpath/"test").write <<~EOS
45d15n 71d07w Boston, United States
40d40n 73d58w New York, United States
48d51n 2d20e Paris, France
51d30n 7'w London, England
EOS
match = <<~EOS
-4887590.49\t7317961.48 Boston, United States
-5542524.55\t6982689.05 New York, United States
171224.94\t5415352.81 Paris, France
-8101.66\t5707500.23 London, England
EOS
output = shell_output("#{bin}/proj +proj=poly +ellps=clrk66 -r #{testpath}/test")
assert_equal match, output
end
end
|
class Pypy < Formula
desc "Highly performant implementation of Python 2 in Python"
homepage "https://pypy.org/"
url "https://bitbucket.org/pypy/pypy/downloads/pypy2.7-v7.1.1-src.tar.bz2"
sha256 "5f06bede6d71dce8dfbfe797aab26c8e35cb990e16b826914652dc093ad74451"
head "https://bitbucket.org/pypy/pypy", :using => :hg
bottle do
cellar :any
sha256 "dfb8b553b52f71ecdbc700fa4960df3f61a9f2ae7c7f79a91c873efc8bbcc37c" => :mojave
sha256 "1b371dea9a157ac6148f355e4cc12b08290955df38b6a85063a49022f49e70e8" => :high_sierra
sha256 "836b5eb5e60478e73d89598ff2fb21d9100f4758d433209b1c9b73d675a3613a" => :sierra
end
depends_on "pkg-config" => :build
depends_on :arch => :x86_64
depends_on "gdbm"
# pypy does not find system libffi, and its location cannot be given
# as a build option
depends_on "libffi" if DevelopmentTools.clang_build_version >= 1000
depends_on "openssl"
depends_on "sqlite"
resource "bootstrap" do
url "https://bitbucket.org/pypy/pypy/downloads/pypy2.7-v7.0.0-osx64.tar.bz2"
version "7.0.0"
sha256 "e7ecb029d9c7a59388838fc4820a50a2f5bee6536010031060e3dfa882730dc8"
end
resource "setuptools" do
url "https://files.pythonhosted.org/packages/source/s/setuptools/setuptools-41.0.1.zip"
sha256 "a222d126f5471598053c9a77f4b5d4f26eaa1f150ad6e01dcf1a42e185d05613"
end
resource "pip" do
url "https://files.pythonhosted.org/packages/source/p/pip/pip-19.1.1.tar.gz"
sha256 "44d3d7d3d30a1eb65c7e5ff1173cdf8f7467850605ac7cc3707b6064bddd0958"
end
def install
ENV.append "CFLAGS", "-I#{MacOS.sdk_path}/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers"
# Having PYTHONPATH set can cause the build to fail if another
# Python is present, e.g. a Homebrew-provided Python 2.x
# See https://github.com/Homebrew/homebrew/issues/24364
ENV["PYTHONPATH"] = ""
ENV["PYPY_USESSION_DIR"] = buildpath
resource("bootstrap").stage buildpath/"bootstrap"
python = buildpath/"bootstrap/bin/pypy"
cd "pypy/goal" do
system python, buildpath/"rpython/bin/rpython",
"-Ojit", "--shared", "--cc", ENV.cc, "--verbose",
"--make-jobs", ENV.make_jobs, "targetpypystandalone.py"
end
libexec.mkpath
cd "pypy/tool/release" do
package_args = %w[--archive-name pypy --targetdir .]
system python, "package.py", *package_args
system "tar", "-C", libexec.to_s, "--strip-components", "1", "-xf", "pypy.tar.bz2"
end
(libexec/"lib").install libexec/"bin/libpypy-c.dylib"
MachO::Tools.change_install_name("#{libexec}/bin/pypy",
"@rpath/libpypy-c.dylib",
"#{libexec}/lib/libpypy-c.dylib")
# The PyPy binary install instructions suggest installing somewhere
# (like /opt) and symlinking in binaries as needed. Specifically,
# we want to avoid putting PyPy's Python.h somewhere that configure
# scripts will find it.
bin.install_symlink libexec/"bin/pypy"
lib.install_symlink libexec/"lib/libpypy-c.dylib"
end
def post_install
# Post-install, fix up the site-packages and install-scripts folders
# so that user-installed Python software survives minor updates, such
# as going from 1.7.0 to 1.7.1.
# Create a site-packages in the prefix.
prefix_site_packages.mkpath
# Symlink the prefix site-packages into the cellar.
unless (libexec/"site-packages").symlink?
# fix the case where libexec/site-packages/site-packages was installed
rm_rf libexec/"site-packages/site-packages"
mv Dir[libexec/"site-packages/*"], prefix_site_packages
rm_rf libexec/"site-packages"
end
libexec.install_symlink prefix_site_packages
# Tell distutils-based installers where to put scripts
scripts_folder.mkpath
(distutils+"distutils.cfg").atomic_write <<~EOS
[install]
install-scripts=#{scripts_folder}
EOS
%w[setuptools pip].each do |pkg|
resource(pkg).stage do
system bin/"pypy", "-s", "setup.py", "--no-user-cfg", "install",
"--force", "--verbose"
end
end
# Symlinks to easy_install_pypy and pip_pypy
bin.install_symlink scripts_folder/"easy_install" => "easy_install_pypy"
bin.install_symlink scripts_folder/"pip" => "pip_pypy"
# post_install happens after linking
%w[easy_install_pypy pip_pypy].each { |e| (HOMEBREW_PREFIX/"bin").install_symlink bin/e }
end
def caveats; <<~EOS
A "distutils.cfg" has been written to:
#{distutils}
specifying the install-scripts folder as:
#{scripts_folder}
If you install Python packages via "pypy setup.py install", easy_install_pypy,
or pip_pypy, any provided scripts will go into the install-scripts folder
above, so you may want to add it to your PATH *after* #{HOMEBREW_PREFIX}/bin
so you don't overwrite tools from CPython.
Setuptools and pip have been installed, so you can use easy_install_pypy and
pip_pypy.
To update setuptools and pip between pypy releases, run:
pip_pypy install --upgrade pip setuptools
See: https://docs.brew.sh/Homebrew-and-Python
EOS
end
# The HOMEBREW_PREFIX location of site-packages
def prefix_site_packages
HOMEBREW_PREFIX+"lib/pypy/site-packages"
end
# Where setuptools will install executable scripts
def scripts_folder
HOMEBREW_PREFIX+"share/pypy"
end
# The Cellar location of distutils
def distutils
libexec+"lib-python/2.7/distutils"
end
test do
system bin/"pypy", "-c", "print('Hello, world!')"
system bin/"pypy", "-c", "import time; time.clock()"
system scripts_folder/"pip", "list"
end
end
pypy: move to OpenSSL 1.1
class Pypy < Formula
desc "Highly performant implementation of Python 2 in Python"
homepage "https://pypy.org/"
url "https://bitbucket.org/pypy/pypy/downloads/pypy2.7-v7.1.1-src.tar.bz2"
sha256 "5f06bede6d71dce8dfbfe797aab26c8e35cb990e16b826914652dc093ad74451"
revision 1
head "https://bitbucket.org/pypy/pypy", :using => :hg
bottle do
cellar :any
sha256 "dfb8b553b52f71ecdbc700fa4960df3f61a9f2ae7c7f79a91c873efc8bbcc37c" => :mojave
sha256 "1b371dea9a157ac6148f355e4cc12b08290955df38b6a85063a49022f49e70e8" => :high_sierra
sha256 "836b5eb5e60478e73d89598ff2fb21d9100f4758d433209b1c9b73d675a3613a" => :sierra
end
depends_on "pkg-config" => :build
depends_on :arch => :x86_64
depends_on "gdbm"
# pypy does not find system libffi, and its location cannot be given
# as a build option
depends_on "libffi" if DevelopmentTools.clang_build_version >= 1000
depends_on "openssl@1.1"
depends_on "sqlite"
resource "bootstrap" do
url "https://bitbucket.org/pypy/pypy/downloads/pypy2.7-v7.0.0-osx64.tar.bz2"
version "7.0.0"
sha256 "e7ecb029d9c7a59388838fc4820a50a2f5bee6536010031060e3dfa882730dc8"
end
resource "setuptools" do
url "https://files.pythonhosted.org/packages/source/s/setuptools/setuptools-41.0.1.zip"
sha256 "a222d126f5471598053c9a77f4b5d4f26eaa1f150ad6e01dcf1a42e185d05613"
end
resource "pip" do
url "https://files.pythonhosted.org/packages/source/p/pip/pip-19.1.1.tar.gz"
sha256 "44d3d7d3d30a1eb65c7e5ff1173cdf8f7467850605ac7cc3707b6064bddd0958"
end
def install
ENV.append "CFLAGS", "-I#{MacOS.sdk_path}/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers"
# Having PYTHONPATH set can cause the build to fail if another
# Python is present, e.g. a Homebrew-provided Python 2.x
# See https://github.com/Homebrew/homebrew/issues/24364
ENV["PYTHONPATH"] = ""
ENV["PYPY_USESSION_DIR"] = buildpath
resource("bootstrap").stage buildpath/"bootstrap"
python = buildpath/"bootstrap/bin/pypy"
cd "pypy/goal" do
system python, buildpath/"rpython/bin/rpython",
"-Ojit", "--shared", "--cc", ENV.cc, "--verbose",
"--make-jobs", ENV.make_jobs, "targetpypystandalone.py"
end
libexec.mkpath
cd "pypy/tool/release" do
package_args = %w[--archive-name pypy --targetdir .]
system python, "package.py", *package_args
system "tar", "-C", libexec.to_s, "--strip-components", "1", "-xf", "pypy.tar.bz2"
end
(libexec/"lib").install libexec/"bin/libpypy-c.dylib"
MachO::Tools.change_install_name("#{libexec}/bin/pypy",
"@rpath/libpypy-c.dylib",
"#{libexec}/lib/libpypy-c.dylib")
# The PyPy binary install instructions suggest installing somewhere
# (like /opt) and symlinking in binaries as needed. Specifically,
# we want to avoid putting PyPy's Python.h somewhere that configure
# scripts will find it.
bin.install_symlink libexec/"bin/pypy"
lib.install_symlink libexec/"lib/libpypy-c.dylib"
end
def post_install
# Post-install, fix up the site-packages and install-scripts folders
# so that user-installed Python software survives minor updates, such
# as going from 1.7.0 to 1.7.1.
# Create a site-packages in the prefix.
prefix_site_packages.mkpath
# Symlink the prefix site-packages into the cellar.
unless (libexec/"site-packages").symlink?
# fix the case where libexec/site-packages/site-packages was installed
rm_rf libexec/"site-packages/site-packages"
mv Dir[libexec/"site-packages/*"], prefix_site_packages
rm_rf libexec/"site-packages"
end
libexec.install_symlink prefix_site_packages
# Tell distutils-based installers where to put scripts
scripts_folder.mkpath
(distutils+"distutils.cfg").atomic_write <<~EOS
[install]
install-scripts=#{scripts_folder}
EOS
%w[setuptools pip].each do |pkg|
resource(pkg).stage do
system bin/"pypy", "-s", "setup.py", "--no-user-cfg", "install",
"--force", "--verbose"
end
end
# Symlinks to easy_install_pypy and pip_pypy
bin.install_symlink scripts_folder/"easy_install" => "easy_install_pypy"
bin.install_symlink scripts_folder/"pip" => "pip_pypy"
# post_install happens after linking
%w[easy_install_pypy pip_pypy].each { |e| (HOMEBREW_PREFIX/"bin").install_symlink bin/e }
end
def caveats; <<~EOS
A "distutils.cfg" has been written to:
#{distutils}
specifying the install-scripts folder as:
#{scripts_folder}
If you install Python packages via "pypy setup.py install", easy_install_pypy,
or pip_pypy, any provided scripts will go into the install-scripts folder
above, so you may want to add it to your PATH *after* #{HOMEBREW_PREFIX}/bin
so you don't overwrite tools from CPython.
Setuptools and pip have been installed, so you can use easy_install_pypy and
pip_pypy.
To update setuptools and pip between pypy releases, run:
pip_pypy install --upgrade pip setuptools
See: https://docs.brew.sh/Homebrew-and-Python
EOS
end
# The HOMEBREW_PREFIX location of site-packages
def prefix_site_packages
HOMEBREW_PREFIX+"lib/pypy/site-packages"
end
# Where setuptools will install executable scripts
def scripts_folder
HOMEBREW_PREFIX+"share/pypy"
end
# The Cellar location of distutils
def distutils
libexec+"lib-python/2.7/distutils"
end
test do
system bin/"pypy", "-c", "print('Hello, world!')"
system bin/"pypy", "-c", "import time; time.clock()"
system scripts_folder/"pip", "list"
end
end
|
class Pyqt < Formula
desc "Python bindings for v5 of Qt"
homepage "https://www.riverbankcomputing.com/software/pyqt/download5"
url "https://downloads.sourceforge.net/project/pyqt/PyQt5/PyQt-5.9.2/PyQt5_gpl-5.9.2.tar.gz"
sha256 "c190dac598c97b0113ca5e7a37c71c623f02d1d713088addfacac4acfa4b8394"
revision 1
bottle do
sha256 "54bef599d86f1ab94f4d5bb934ee273d7b2d39fe4fefffe60227bf985186eaa8" => :high_sierra
sha256 "9b0504fc1c37cc0fb6d9786e532827e76dab80676c3c988355502a42669f68a4" => :sierra
sha256 "c910f2b11ada0c796f730e13e35812c60f6c4e68ed21338646575bb2c17a335c" => :el_capitan
end
option "with-debug", "Build with debug symbols"
option "with-docs", "Install HTML documentation and python examples"
deprecated_option "enable-debug" => "with-debug"
depends_on "qt"
depends_on "sip"
depends_on :python => :recommended
depends_on :python3 => :recommended
def install
# Reduce memory usage below 4 GB for Circle CI.
ENV["MAKEFLAGS"] = "-j16" if ENV["CIRCLECI"]
if build.without?("python3") && build.without?("python")
odie "pyqt: --with-python3 must be specified when using --without-python"
end
Language::Python.each_python(build) do |python, version|
args = ["--confirm-license",
"--bindir=#{bin}",
"--destdir=#{lib}/python#{version}/site-packages",
"--stubsdir=#{lib}/python#{version}/site-packages/PyQt5",
"--sipdir=#{share}/sip/Qt5",
# sip.h could not be found automatically
"--sip-incdir=#{Formula["sip"].opt_include}",
"--qmake=#{Formula["qt"].bin}/qmake",
# Force deployment target to avoid libc++ issues
"QMAKE_MACOSX_DEPLOYMENT_TARGET=#{MacOS.version}",
"--qml-plugindir=#{pkgshare}/plugins",
"--verbose"]
args << "--debug" if build.with? "debug"
system python, "configure.py", *args
system "make"
system "make", "install"
system "make", "clean"
end
doc.install "doc/html", "examples" if build.with? "docs"
end
test do
system "#{bin}/pyuic5", "--version"
system "#{bin}/pylupdate5", "-version"
Language::Python.each_python(build) do |python, _version|
system python, "-c", "import PyQt5"
m = %w[
Gui
Location
Multimedia
Network
Quick
Svg
Widgets
Xml
]
m << "WebEngineWidgets" if OS.mac?
m.each { |mod| system python, "-c", "import PyQt5.Qt#{mod}" }
end
end
end
pyqt: update 5.9.2_1 bottle for Linuxbrew
class Pyqt < Formula
desc "Python bindings for v5 of Qt"
homepage "https://www.riverbankcomputing.com/software/pyqt/download5"
url "https://downloads.sourceforge.net/project/pyqt/PyQt5/PyQt-5.9.2/PyQt5_gpl-5.9.2.tar.gz"
sha256 "c190dac598c97b0113ca5e7a37c71c623f02d1d713088addfacac4acfa4b8394"
revision 1
bottle do
sha256 "54bef599d86f1ab94f4d5bb934ee273d7b2d39fe4fefffe60227bf985186eaa8" => :high_sierra
sha256 "9b0504fc1c37cc0fb6d9786e532827e76dab80676c3c988355502a42669f68a4" => :sierra
sha256 "c910f2b11ada0c796f730e13e35812c60f6c4e68ed21338646575bb2c17a335c" => :el_capitan
sha256 "24334d7d27d87c96a37cdd2292bde08f26ff768890b938fdad649179dd57ab4f" => :x86_64_linux
end
option "with-debug", "Build with debug symbols"
option "with-docs", "Install HTML documentation and python examples"
deprecated_option "enable-debug" => "with-debug"
depends_on "qt"
depends_on "sip"
depends_on :python => :recommended
depends_on :python3 => :recommended
def install
# Reduce memory usage below 4 GB for Circle CI.
ENV["MAKEFLAGS"] = "-j16" if ENV["CIRCLECI"]
if build.without?("python3") && build.without?("python")
odie "pyqt: --with-python3 must be specified when using --without-python"
end
Language::Python.each_python(build) do |python, version|
args = ["--confirm-license",
"--bindir=#{bin}",
"--destdir=#{lib}/python#{version}/site-packages",
"--stubsdir=#{lib}/python#{version}/site-packages/PyQt5",
"--sipdir=#{share}/sip/Qt5",
# sip.h could not be found automatically
"--sip-incdir=#{Formula["sip"].opt_include}",
"--qmake=#{Formula["qt"].bin}/qmake",
# Force deployment target to avoid libc++ issues
"QMAKE_MACOSX_DEPLOYMENT_TARGET=#{MacOS.version}",
"--qml-plugindir=#{pkgshare}/plugins",
"--verbose"]
args << "--debug" if build.with? "debug"
system python, "configure.py", *args
system "make"
system "make", "install"
system "make", "clean"
end
doc.install "doc/html", "examples" if build.with? "docs"
end
test do
system "#{bin}/pyuic5", "--version"
system "#{bin}/pylupdate5", "-version"
Language::Python.each_python(build) do |python, _version|
system python, "-c", "import PyQt5"
m = %w[
Gui
Location
Multimedia
Network
Quick
Svg
Widgets
Xml
]
m << "WebEngineWidgets" if OS.mac?
m.each { |mod| system python, "-c", "import PyQt5.Qt#{mod}" }
end
end
end
|
class Qemu < Formula
desc "Emulator for x86 and PowerPC"
homepage "https://www.qemu.org/"
url "https://download.qemu.org/qemu-6.1.0.tar.xz"
sha256 "eebc089db3414bbeedf1e464beda0a7515aad30f73261abc246c9b27503a3c96"
license "GPL-2.0-only"
head "https://git.qemu.org/git/qemu.git", branch: "master"
bottle do
sha256 arm64_big_sur: "09773cd9881a40b27ad2599eb869443c04f9b1bb5cbbf741c2b562c188e8a6b3"
sha256 big_sur: "13387458a7dda4c91fadd9274968f0d496171708fc950d4161a32a4d5c6a2a7c"
sha256 catalina: "aaef3209e70171353a841992ffffb28a73e65a8762041cb23b0363bd3dc4ad07"
sha256 mojave: "b611de8493acf94662ec19df3bea1bec9acad6215baca6d0e485efa32e99dacf"
sha256 x86_64_linux: "0257fe7bf5ad82ff9f2cbc5d6dc111e315db5cb5f84b6d9dd9c3aee29bd777ed"
end
depends_on "libtool" => :build
depends_on "meson" => :build
depends_on "ninja" => :build
depends_on "pkg-config" => :build
depends_on "glib"
depends_on "gnutls"
depends_on "jpeg"
depends_on "libpng"
depends_on "libslirp"
depends_on "libssh"
depends_on "libusb"
depends_on "lzo"
depends_on "ncurses"
depends_on "nettle"
depends_on "pixman"
depends_on "snappy"
depends_on "vde"
on_linux do
depends_on "gcc" => :build
end
fails_with gcc: "5"
# 820KB floppy disk image file of FreeDOS 1.2, used to test QEMU
resource "test-image" do
url "https://www.ibiblio.org/pub/micro/pc-stuff/freedos/files/distributions/1.2/FD12FLOPPY.zip"
sha256 "81237c7b42dc0ffc8b32a2f5734e3480a3f9a470c50c14a9c4576a2561a35807"
end
def install
ENV["LIBTOOL"] = "glibtool"
args = %W[
--prefix=#{prefix}
--cc=#{ENV.cc}
--host-cc=#{ENV.cc}
--disable-bsd-user
--disable-guest-agent
--enable-curses
--enable-libssh
--enable-slirp=system
--enable-vde
--extra-cflags=-DNCURSES_WIDECHAR=1
--disable-sdl
--disable-gtk
]
# Sharing Samba directories in QEMU requires the samba.org smbd which is
# incompatible with the macOS-provided version. This will lead to
# silent runtime failures, so we set it to a Homebrew path in order to
# obtain sensible runtime errors. This will also be compatible with
# Samba installations from external taps.
args << "--smbd=#{HOMEBREW_PREFIX}/sbin/samba-dot-org-smbd"
on_macos do
args << "--enable-cocoa"
end
system "./configure", *args
system "make", "V=1", "install"
end
test do
expected = build.stable? ? version.to_s : "QEMU Project"
assert_match expected, shell_output("#{bin}/qemu-system-aarch64 --version")
assert_match expected, shell_output("#{bin}/qemu-system-alpha --version")
assert_match expected, shell_output("#{bin}/qemu-system-arm --version")
assert_match expected, shell_output("#{bin}/qemu-system-cris --version")
assert_match expected, shell_output("#{bin}/qemu-system-hppa --version")
assert_match expected, shell_output("#{bin}/qemu-system-i386 --version")
assert_match expected, shell_output("#{bin}/qemu-system-m68k --version")
assert_match expected, shell_output("#{bin}/qemu-system-microblaze --version")
assert_match expected, shell_output("#{bin}/qemu-system-microblazeel --version")
assert_match expected, shell_output("#{bin}/qemu-system-mips --version")
assert_match expected, shell_output("#{bin}/qemu-system-mips64 --version")
assert_match expected, shell_output("#{bin}/qemu-system-mips64el --version")
assert_match expected, shell_output("#{bin}/qemu-system-mipsel --version")
assert_match expected, shell_output("#{bin}/qemu-system-nios2 --version")
assert_match expected, shell_output("#{bin}/qemu-system-or1k --version")
assert_match expected, shell_output("#{bin}/qemu-system-ppc --version")
assert_match expected, shell_output("#{bin}/qemu-system-ppc64 --version")
assert_match expected, shell_output("#{bin}/qemu-system-riscv32 --version")
assert_match expected, shell_output("#{bin}/qemu-system-riscv64 --version")
assert_match expected, shell_output("#{bin}/qemu-system-rx --version")
assert_match expected, shell_output("#{bin}/qemu-system-s390x --version")
assert_match expected, shell_output("#{bin}/qemu-system-sh4 --version")
assert_match expected, shell_output("#{bin}/qemu-system-sh4eb --version")
assert_match expected, shell_output("#{bin}/qemu-system-sparc --version")
assert_match expected, shell_output("#{bin}/qemu-system-sparc64 --version")
assert_match expected, shell_output("#{bin}/qemu-system-tricore --version")
assert_match expected, shell_output("#{bin}/qemu-system-x86_64 --version")
assert_match expected, shell_output("#{bin}/qemu-system-xtensa --version")
assert_match expected, shell_output("#{bin}/qemu-system-xtensaeb --version")
resource("test-image").stage testpath
assert_match "file format: raw", shell_output("#{bin}/qemu-img info FLOPPY.img")
end
end
qemu: make gcc a runtime dependency on Linux (#84079)
See discussion at #83905.
class Qemu < Formula
desc "Emulator for x86 and PowerPC"
homepage "https://www.qemu.org/"
url "https://download.qemu.org/qemu-6.1.0.tar.xz"
sha256 "eebc089db3414bbeedf1e464beda0a7515aad30f73261abc246c9b27503a3c96"
license "GPL-2.0-only"
head "https://git.qemu.org/git/qemu.git", branch: "master"
bottle do
sha256 arm64_big_sur: "09773cd9881a40b27ad2599eb869443c04f9b1bb5cbbf741c2b562c188e8a6b3"
sha256 big_sur: "13387458a7dda4c91fadd9274968f0d496171708fc950d4161a32a4d5c6a2a7c"
sha256 catalina: "aaef3209e70171353a841992ffffb28a73e65a8762041cb23b0363bd3dc4ad07"
sha256 mojave: "b611de8493acf94662ec19df3bea1bec9acad6215baca6d0e485efa32e99dacf"
sha256 x86_64_linux: "0257fe7bf5ad82ff9f2cbc5d6dc111e315db5cb5f84b6d9dd9c3aee29bd777ed"
end
depends_on "libtool" => :build
depends_on "meson" => :build
depends_on "ninja" => :build
depends_on "pkg-config" => :build
depends_on "glib"
depends_on "gnutls"
depends_on "jpeg"
depends_on "libpng"
depends_on "libslirp"
depends_on "libssh"
depends_on "libusb"
depends_on "lzo"
depends_on "ncurses"
depends_on "nettle"
depends_on "pixman"
depends_on "snappy"
depends_on "vde"
on_linux do
depends_on "gcc"
end
fails_with gcc: "5"
# 820KB floppy disk image file of FreeDOS 1.2, used to test QEMU
resource "test-image" do
url "https://www.ibiblio.org/pub/micro/pc-stuff/freedos/files/distributions/1.2/FD12FLOPPY.zip"
sha256 "81237c7b42dc0ffc8b32a2f5734e3480a3f9a470c50c14a9c4576a2561a35807"
end
def install
ENV["LIBTOOL"] = "glibtool"
args = %W[
--prefix=#{prefix}
--cc=#{ENV.cc}
--host-cc=#{ENV.cc}
--disable-bsd-user
--disable-guest-agent
--enable-curses
--enable-libssh
--enable-slirp=system
--enable-vde
--extra-cflags=-DNCURSES_WIDECHAR=1
--disable-sdl
--disable-gtk
]
# Sharing Samba directories in QEMU requires the samba.org smbd which is
# incompatible with the macOS-provided version. This will lead to
# silent runtime failures, so we set it to a Homebrew path in order to
# obtain sensible runtime errors. This will also be compatible with
# Samba installations from external taps.
args << "--smbd=#{HOMEBREW_PREFIX}/sbin/samba-dot-org-smbd"
on_macos do
args << "--enable-cocoa"
end
system "./configure", *args
system "make", "V=1", "install"
end
test do
expected = build.stable? ? version.to_s : "QEMU Project"
assert_match expected, shell_output("#{bin}/qemu-system-aarch64 --version")
assert_match expected, shell_output("#{bin}/qemu-system-alpha --version")
assert_match expected, shell_output("#{bin}/qemu-system-arm --version")
assert_match expected, shell_output("#{bin}/qemu-system-cris --version")
assert_match expected, shell_output("#{bin}/qemu-system-hppa --version")
assert_match expected, shell_output("#{bin}/qemu-system-i386 --version")
assert_match expected, shell_output("#{bin}/qemu-system-m68k --version")
assert_match expected, shell_output("#{bin}/qemu-system-microblaze --version")
assert_match expected, shell_output("#{bin}/qemu-system-microblazeel --version")
assert_match expected, shell_output("#{bin}/qemu-system-mips --version")
assert_match expected, shell_output("#{bin}/qemu-system-mips64 --version")
assert_match expected, shell_output("#{bin}/qemu-system-mips64el --version")
assert_match expected, shell_output("#{bin}/qemu-system-mipsel --version")
assert_match expected, shell_output("#{bin}/qemu-system-nios2 --version")
assert_match expected, shell_output("#{bin}/qemu-system-or1k --version")
assert_match expected, shell_output("#{bin}/qemu-system-ppc --version")
assert_match expected, shell_output("#{bin}/qemu-system-ppc64 --version")
assert_match expected, shell_output("#{bin}/qemu-system-riscv32 --version")
assert_match expected, shell_output("#{bin}/qemu-system-riscv64 --version")
assert_match expected, shell_output("#{bin}/qemu-system-rx --version")
assert_match expected, shell_output("#{bin}/qemu-system-s390x --version")
assert_match expected, shell_output("#{bin}/qemu-system-sh4 --version")
assert_match expected, shell_output("#{bin}/qemu-system-sh4eb --version")
assert_match expected, shell_output("#{bin}/qemu-system-sparc --version")
assert_match expected, shell_output("#{bin}/qemu-system-sparc64 --version")
assert_match expected, shell_output("#{bin}/qemu-system-tricore --version")
assert_match expected, shell_output("#{bin}/qemu-system-x86_64 --version")
assert_match expected, shell_output("#{bin}/qemu-system-xtensa --version")
assert_match expected, shell_output("#{bin}/qemu-system-xtensaeb --version")
resource("test-image").stage testpath
assert_match "file format: raw", shell_output("#{bin}/qemu-img info FLOPPY.img")
end
end
|
class Qemu < Formula
desc "x86 and PowerPC Emulator"
homepage "http://wiki.qemu.org"
url "http://wiki.qemu-project.org/download/qemu-2.6.0.tar.bz2"
mirror "http://ftp.osuosl.org/pub/blfs/conglomeration/qemu/qemu-2.6.0.tar.bz2"
sha256 "c9ac4a651b273233d21b8bec32e30507cb9cce7900841febc330956a1a8434ec"
head "git://git.qemu-project.org/qemu.git"
bottle do
sha256 "bc9faeed43aa6c6e8a5212cf983468d4c3e55f99c812e9c66ce80d0d0436cb56" => :el_capitan
sha256 "d32bc574ae7489ac4ae981247eb3e7e980de30b684f080ec29b56e21d81a29f3" => :yosemite
sha256 "e60b1ffe823022f680d3dcb38bbd621bfd73b8a794e53bc78e6ac3f3991d6af5" => :mavericks
end
depends_on "pkg-config" => :build
depends_on "libtool" => :build
depends_on "jpeg"
depends_on "libpng" => :recommended
depends_on "gnutls"
depends_on "glib"
depends_on "pixman"
depends_on "vde" => :optional
depends_on "sdl" => :optional
depends_on "gtk+" => :optional
depends_on "libssh2" => :optional
fails_with :gcc_4_0 do
cause "qemu requires a compiler with support for the __thread specifier"
end
fails_with :gcc do
cause "qemu requires a compiler with support for the __thread specifier"
end
# 3.2MB working disc-image file hosted on upstream's servers for people to use to test qemu functionality.
resource "armtest" do
url "http://wiki.qemu.org/download/arm-test-0.2.tar.gz"
sha256 "4b4c2dce4c055f0a2adb93d571987a3d40c96c6cbfd9244d19b9708ce5aea454"
end
def install
ENV["LIBTOOL"] = "glibtool"
args = %W[
--prefix=#{prefix}
--cc=#{ENV.cc}
--host-cc=#{ENV.cc}
--disable-bsd-user
--disable-guest-agent
]
# Cocoa and SDL UIs cannot both be enabled at once.
if build.with? "sdl"
args << "--enable-sdl" << "--disable-cocoa"
else
args << "--enable-cocoa" << "--disable-sdl"
end
args << (build.with?("vde") ? "--enable-vde" : "--disable-vde")
args << (build.with?("gtk+") ? "--enable-gtk" : "--disable-gtk")
args << (build.with?("libssh2") ? "--enable-libssh2" : "--disable-libssh2")
system "./configure", *args
system "make", "V=1", "install"
end
test do
system "#{bin}/qemu-system-i386", "--version"
resource("armtest").stage testpath
assert_match "file format: raw", shell_output("#{bin}/qemu-img info arm_root.img")
end
end
qemu: update 2.6.0 bottle.
class Qemu < Formula
desc "x86 and PowerPC Emulator"
homepage "http://wiki.qemu.org"
url "http://wiki.qemu-project.org/download/qemu-2.6.0.tar.bz2"
mirror "http://ftp.osuosl.org/pub/blfs/conglomeration/qemu/qemu-2.6.0.tar.bz2"
sha256 "c9ac4a651b273233d21b8bec32e30507cb9cce7900841febc330956a1a8434ec"
head "git://git.qemu-project.org/qemu.git"
bottle do
sha256 "3315fd7c6093169133497b4eae48f82f22919f41286adf28b666a3da894764b5" => :el_capitan
sha256 "41c8a897ab1296ac0724e49e617b8fe319bcc35c66718c5375e22bca4aa71d81" => :yosemite
sha256 "060e7a83fb5e2d270b9b306188ea536524b42ee4dc6b8203c8c98f9b9ddddcae" => :mavericks
end
depends_on "pkg-config" => :build
depends_on "libtool" => :build
depends_on "jpeg"
depends_on "libpng" => :recommended
depends_on "gnutls"
depends_on "glib"
depends_on "pixman"
depends_on "vde" => :optional
depends_on "sdl" => :optional
depends_on "gtk+" => :optional
depends_on "libssh2" => :optional
fails_with :gcc_4_0 do
cause "qemu requires a compiler with support for the __thread specifier"
end
fails_with :gcc do
cause "qemu requires a compiler with support for the __thread specifier"
end
# 3.2MB working disc-image file hosted on upstream's servers for people to use to test qemu functionality.
resource "armtest" do
url "http://wiki.qemu.org/download/arm-test-0.2.tar.gz"
sha256 "4b4c2dce4c055f0a2adb93d571987a3d40c96c6cbfd9244d19b9708ce5aea454"
end
def install
ENV["LIBTOOL"] = "glibtool"
args = %W[
--prefix=#{prefix}
--cc=#{ENV.cc}
--host-cc=#{ENV.cc}
--disable-bsd-user
--disable-guest-agent
]
# Cocoa and SDL UIs cannot both be enabled at once.
if build.with? "sdl"
args << "--enable-sdl" << "--disable-cocoa"
else
args << "--enable-cocoa" << "--disable-sdl"
end
args << (build.with?("vde") ? "--enable-vde" : "--disable-vde")
args << (build.with?("gtk+") ? "--enable-gtk" : "--disable-gtk")
args << (build.with?("libssh2") ? "--enable-libssh2" : "--disable-libssh2")
system "./configure", *args
system "make", "V=1", "install"
end
test do
system "#{bin}/qemu-system-i386", "--version"
resource("armtest").stage testpath
assert_match "file format: raw", shell_output("#{bin}/qemu-img info arm_root.img")
end
end
|
class Qpdf < Formula
desc "Tools for and transforming and inspecting PDF files"
homepage "https://github.com/qpdf/qpdf"
url "https://github.com/qpdf/qpdf/releases/download/release-qpdf-10.6.1/qpdf-10.6.1.tar.gz"
sha256 "4c56328e1eeedea3d87eb79e1fe09374a923fe28756f7a56bcff58523617f05f"
license "Apache-2.0"
bottle do
sha256 cellar: :any, arm64_monterey: "aa0ba418a528f636469bcdf305a77dd88f89026a6e6e123a98eee0c84cede879"
sha256 cellar: :any, arm64_big_sur: "f629f8f3aea95e5a3b2e52af7e989f57fd09183424ed9095febc38b0c25b49aa"
sha256 cellar: :any, monterey: "aa5db4a61ad465bde40d0939acb6b086e74e636eb422ce5f50ef23ea7bb63138"
sha256 cellar: :any, big_sur: "ca43e4b70db69d92c8b4fa6952ac944f33f205542c68de3dfea1fc96974b3aac"
sha256 cellar: :any, catalina: "07c23b2aaaecb7926f44b082ceb1055731c91a0dc735f35e3f320fb879593e5e"
sha256 cellar: :any_skip_relocation, x86_64_linux: "ce469c051067588983229dcf201e1491419c63738f2c99ddeaf5682abf18372e"
end
depends_on "jpeg"
depends_on "openssl@1.1"
uses_from_macos "zlib"
def install
system "./configure", "--prefix=#{prefix}"
system "make"
system "make", "install"
end
test do
system "#{bin}/qpdf", "--version"
end
end
qpdf: update 10.6.1 bottle.
class Qpdf < Formula
desc "Tools for and transforming and inspecting PDF files"
homepage "https://github.com/qpdf/qpdf"
url "https://github.com/qpdf/qpdf/releases/download/release-qpdf-10.6.1/qpdf-10.6.1.tar.gz"
sha256 "4c56328e1eeedea3d87eb79e1fe09374a923fe28756f7a56bcff58523617f05f"
license "Apache-2.0"
bottle do
sha256 cellar: :any, arm64_monterey: "365dc91f990f83a7a63116ebf3d58766555752d546632e8ad65a1380f7509c11"
sha256 cellar: :any, arm64_big_sur: "a2cab776d352e83a86ed526a0051d6e16e3fd83a42f41010b0fa9b27e74e9fe2"
sha256 cellar: :any, monterey: "adb76f57bcacbd8b7322f0f0e79c6cb8922a17f51ada9bfb7d35672600e239b0"
sha256 cellar: :any, big_sur: "b96113b17f4689a64be5b5a0ca84e18d661d45fe37bcba77c5154a6886f41b0b"
sha256 cellar: :any, catalina: "386fc704b7021d7a0ae74d0cd4dcefc33f95eac036db9eaba696516a6dd5646f"
sha256 cellar: :any_skip_relocation, x86_64_linux: "5b283b7eb55707a42ad6e290f6be454d489d4f11ac01996773e7d961c355ad2e"
end
depends_on "jpeg"
depends_on "openssl@1.1"
uses_from_macos "zlib"
def install
system "./configure", "--prefix=#{prefix}"
system "make"
system "make", "install"
end
test do
system "#{bin}/qpdf", "--version"
end
end
|
New formula quvi
quvi is a command line tool for parsing video download links. It supports
Youtube and other similar video websites.
require 'formula'
class Quvi <Formula
url 'http://quvi.googlecode.com/files/quvi-0.1.4.tar.bz2'
homepage 'http://code.google.com/p/quvi/'
md5 '976c07dcf3cab275c93f7b5bc3424b02'
depends_on 'pkg-config'
depends_on 'pcre'
def install
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--prefix=#{prefix}",
"--enable-smut",
"--enable-broken"
system "make install"
end
end
|
class Redo < Formula
include Language::Python::Virtualenv
desc "Implements djb's redo: an alternative to make"
homepage "https://redo.rtfd.io/"
url "https://github.com/apenwarr/redo/archive/redo-0.42a.tar.gz"
sha256 "0ff0fd29f2767fe33374cfac97fd13b3dd27207bdacbeb5e02039b992d4fb815"
depends_on "python@3.8"
resource "Markdown" do
url "https://files.pythonhosted.org/packages/98/79/ce6984767cb9478e6818bd0994283db55c423d733cc62a88a3ffb8581e11/Markdown-3.2.1.tar.gz"
sha256 "90fee683eeabe1a92e149f7ba74e5ccdc81cd397bd6c516d93a8da0ef90b6902"
end
resource "beautifulsoup4" do
url "https://files.pythonhosted.org/packages/3b/e4/7cfc641f11e0eef60123912611a5c9ee7d4638da7325878b695b9ae4bb6f/beautifulsoup4-4.9.0.tar.gz"
sha256 "594ca51a10d2b3443cbac41214e12dbb2a1cd57e1a7344659849e2e20ba6a8d8"
end
def install
venv = virtualenv_create(libexec, Formula["python@3.8"].opt_bin/"python3")
venv.pip_install resources
# Set the interpreter so that ./do install can find the pip installed
# resources
ENV["DESTDIR"] = ""
ENV["PREFIX"] = prefix
system "./do", "install"
man1.install Dir["docs/*.1"]
end
test do
assert_equal version.to_s, shell_output("#{bin}/redo --version").strip
# Test is based on https://redo.readthedocs.io/en/latest/cookbook/hello/
(testpath/"hello.c").write <<~EOS
#include <stdio.h>
int main() {
printf(\"Hello, world!\\n\");
return 0;
}
EOS
(testpath/"hello.do").write <<~EOS
redo-ifchange hello.c
cc -o $3 hello.c -Wall
EOS
assert_equal "redo hello", shell_output("redo hello 2>&1").strip
assert_predicate testpath/"hello", :exist?
assert_equal "Hello, world!\n", shell_output("./hello")
assert_equal "redo hello", shell_output("redo hello 2>&1").strip
assert_equal "", shell_output("redo-ifchange hello 2>&1").strip
touch "hello.c"
assert_equal "redo hello", shell_output("redo-ifchange hello 2>&1").strip
(testpath/"all.do").write("redo-ifchange hello")
(testpath/"hello").delete
assert_equal "redo all\nredo hello", shell_output("redo 2>&1").strip
end
end
redo: add 0.42a bottle.
class Redo < Formula
include Language::Python::Virtualenv
desc "Implements djb's redo: an alternative to make"
homepage "https://redo.rtfd.io/"
url "https://github.com/apenwarr/redo/archive/redo-0.42a.tar.gz"
sha256 "0ff0fd29f2767fe33374cfac97fd13b3dd27207bdacbeb5e02039b992d4fb815"
bottle do
cellar :any_skip_relocation
sha256 "6969cbd2833a19d8af5d95e74afdd6cb64998dc27d216989b5b4696965956610" => :catalina
sha256 "b9bfebfc669160a22dc5262bb4ab7845ef0774aa9bba82385e8fd58e6fb9726e" => :mojave
sha256 "b7308d0a6341f3e70922fffb9dcbcede4ca4257ecb553a28b8ea4da2a869382f" => :high_sierra
end
depends_on "python@3.8"
resource "Markdown" do
url "https://files.pythonhosted.org/packages/98/79/ce6984767cb9478e6818bd0994283db55c423d733cc62a88a3ffb8581e11/Markdown-3.2.1.tar.gz"
sha256 "90fee683eeabe1a92e149f7ba74e5ccdc81cd397bd6c516d93a8da0ef90b6902"
end
resource "beautifulsoup4" do
url "https://files.pythonhosted.org/packages/3b/e4/7cfc641f11e0eef60123912611a5c9ee7d4638da7325878b695b9ae4bb6f/beautifulsoup4-4.9.0.tar.gz"
sha256 "594ca51a10d2b3443cbac41214e12dbb2a1cd57e1a7344659849e2e20ba6a8d8"
end
def install
venv = virtualenv_create(libexec, Formula["python@3.8"].opt_bin/"python3")
venv.pip_install resources
# Set the interpreter so that ./do install can find the pip installed
# resources
ENV["DESTDIR"] = ""
ENV["PREFIX"] = prefix
system "./do", "install"
man1.install Dir["docs/*.1"]
end
test do
assert_equal version.to_s, shell_output("#{bin}/redo --version").strip
# Test is based on https://redo.readthedocs.io/en/latest/cookbook/hello/
(testpath/"hello.c").write <<~EOS
#include <stdio.h>
int main() {
printf(\"Hello, world!\\n\");
return 0;
}
EOS
(testpath/"hello.do").write <<~EOS
redo-ifchange hello.c
cc -o $3 hello.c -Wall
EOS
assert_equal "redo hello", shell_output("redo hello 2>&1").strip
assert_predicate testpath/"hello", :exist?
assert_equal "Hello, world!\n", shell_output("./hello")
assert_equal "redo hello", shell_output("redo hello 2>&1").strip
assert_equal "", shell_output("redo-ifchange hello 2>&1").strip
touch "hello.c"
assert_equal "redo hello", shell_output("redo-ifchange hello 2>&1").strip
(testpath/"all.do").write("redo-ifchange hello")
(testpath/"hello").delete
assert_equal "redo all\nredo hello", shell_output("redo 2>&1").strip
end
end
|
class Rgxg < Formula
desc "C library and command-line tool to generate (extended) regular expressions"
homepage "https://rgxg.github.io"
url "https://github.com/rgxg/rgxg/releases/download/v0.1.2/rgxg-0.1.2.tar.gz"
sha256 "554741f95dcc320459875c248e2cc347b99f809d9555c957d763d3d844e917c6"
license "Zlib"
bottle do
cellar :any
sha256 "37ed8cafce126a6ab77b1e367dbe2a72a68c6556569694366e16844b18071dce" => :big_sur
sha256 "4a07550d93bedfa3b2ac3cb77a8484951321697ca9384d2c2a0301ea261aa954" => :catalina
sha256 "b410fe9ea150e0fb52326e4f7ce6642f946098b0713c5741c64699de3f55f762" => :mojave
sha256 "286318be76fc55c094da739c44176d5babd814df1e4f0462711aea283db042f5" => :high_sierra
end
def install
system "./configure", "--prefix=#{prefix}"
system "make", "install"
end
test do
system bin/"rgxg", "range", "1", "10"
end
end
rgxg: update 0.1.2 bottle.
class Rgxg < Formula
desc "C library and command-line tool to generate (extended) regular expressions"
homepage "https://rgxg.github.io"
url "https://github.com/rgxg/rgxg/releases/download/v0.1.2/rgxg-0.1.2.tar.gz"
sha256 "554741f95dcc320459875c248e2cc347b99f809d9555c957d763d3d844e917c6"
license "Zlib"
bottle do
cellar :any
sha256 "37ed8cafce126a6ab77b1e367dbe2a72a68c6556569694366e16844b18071dce" => :big_sur
sha256 "42b3f11c2a0fe78d84df3ae4ef3bcf9d3dd4cb04a5f8ac9a2c2196c7ef7b904b" => :arm64_big_sur
sha256 "4a07550d93bedfa3b2ac3cb77a8484951321697ca9384d2c2a0301ea261aa954" => :catalina
sha256 "b410fe9ea150e0fb52326e4f7ce6642f946098b0713c5741c64699de3f55f762" => :mojave
sha256 "286318be76fc55c094da739c44176d5babd814df1e4f0462711aea283db042f5" => :high_sierra
end
def install
system "./configure", "--prefix=#{prefix}"
system "make", "install"
end
test do
system bin/"rgxg", "range", "1", "10"
end
end
|
class Ruby < Formula
desc "Powerful, clean, object-oriented scripting language"
homepage "https://www.ruby-lang.org/"
url "https://cache.ruby-lang.org/pub/ruby/2.5/ruby-2.5.3.tar.xz"
sha256 "1cc9d0359a8ea35fc6111ec830d12e60168f3b9b305a3c2578357d360fcf306f"
bottle do
sha256 "6c620464fee701978124bdb9ef12179fb55ba62e73222ed42d59e6c07d25a04a" => :mojave
sha256 "4973d5cabcb8b53ab892a331e6c02b8230e9c8ef7a69f6a96d0aec69d3099831" => :high_sierra
sha256 "df8aabed70a29a81ca6f1d5e6a4fcbc0de999cab09b6377b1f61b9dde29b5b21" => :sierra
end
devel do
url "https://cache.ruby-lang.org/pub/ruby/2.6/ruby-2.6.0-preview2.tar.xz"
version "2.6.0-preview2"
sha256 "00ddfb5e33dee24469dd0b203597f7ecee66522ebb496f620f5815372ea2d3ec"
end
head do
url "https://github.com/ruby/ruby.git"
depends_on "autoconf" => :build
end
depends_on "pkg-config" => :build
depends_on "libyaml"
depends_on "openssl"
depends_on "readline"
depends_on "zlib" unless OS.mac?
# Should be updated only when Ruby is updated (if an update is available).
# The exception is Rubygem security fixes, which mandate updating this
# formula & the versioned equivalents and bumping the revisions.
resource "rubygems" do
url "https://rubygems.org/rubygems/rubygems-2.7.7.tgz"
sha256 "4cb2c9a36c0e4a3d5c20eb6795638632858fd72236d281963140221946ab55cb"
end
def api_version
Utils.popen_read("#{bin}/ruby -e 'print Gem.ruby_api_version'")
end
def rubygems_bindir
HOMEBREW_PREFIX/"bin"
end
def install
if OS.linux? && build.bottle?
# The compiler used to build Ruby is stored in the bottle.
# See ruby <<<'print RbConfig::CONFIG["CC"]'
ENV["CC"] = "cc"
ENV["CXX"] = "c++"
end
# otherwise `gem` command breaks
ENV.delete("SDKROOT")
system "autoconf" if build.head?
paths = %w[libyaml openssl readline].map { |f| Formula[f].opt_prefix }
args = %W[
--prefix=#{prefix}
--enable-shared
--disable-silent-rules
--with-sitedir=#{HOMEBREW_PREFIX}/lib/ruby/site_ruby
--with-vendordir=#{HOMEBREW_PREFIX}/lib/ruby/vendor_ruby
--with-opt-dir=#{paths.join(":")}
]
args << "--disable-dtrace" if OS.mac? && !MacOS::CLT.installed?
system "./configure", *args
# Ruby has been configured to look in the HOMEBREW_PREFIX for the
# sitedir and vendordir directories; however we don't actually want to create
# them during the install.
#
# These directories are empty on install; sitedir is used for non-rubygems
# third party libraries, and vendordir is used for packager-provided libraries.
inreplace "tool/rbinstall.rb" do |s|
s.gsub! 'prepare "extension scripts", sitelibdir', ""
s.gsub! 'prepare "extension scripts", vendorlibdir', ""
s.gsub! 'prepare "extension objects", sitearchlibdir', ""
s.gsub! 'prepare "extension objects", vendorarchlibdir', ""
end
system "make"
system "make", "install"
# A newer version of ruby-mode.el is shipped with Emacs
elisp.install Dir["misc/*.el"].reject { |f| f == "misc/ruby-mode.el" }
# This is easier than trying to keep both current & versioned Ruby
# formulae repeatedly updated with Rubygem patches.
resource("rubygems").stage do
ENV.prepend_path "PATH", bin
system "#{bin}/ruby", "setup.rb", "--prefix=#{buildpath}/vendor_gem"
rg_in = lib/"ruby/#{api_version}"
# Remove bundled Rubygem version.
rm_rf rg_in/"rubygems"
rm_f rg_in/"rubygems.rb"
rm_f rg_in/"ubygems.rb"
rm_f bin/"gem"
# Drop in the new version.
rg_in.install Dir[buildpath/"vendor_gem/lib/*"]
bin.install buildpath/"vendor_gem/bin/gem" => "gem"
(libexec/"gembin").install buildpath/"vendor_gem/bin/bundle" => "bundle"
(libexec/"gembin").install_symlink "bundle" => "bundler"
end
end
def post_install
# Since Gem ships Bundle we want to provide that full/expected installation
# but to do so we need to handle the case where someone has previously
# installed bundle manually via `gem install`.
rm_f %W[
#{rubygems_bindir}/bundle
#{rubygems_bindir}/bundler
]
rm_rf Dir[HOMEBREW_PREFIX/"lib/ruby/gems/#{api_version}/gems/bundler-*"]
rubygems_bindir.install_symlink Dir[libexec/"gembin/*"]
# Customize rubygems to look/install in the global gem directory
# instead of in the Cellar, making gems last across reinstalls
config_file = lib/"ruby/#{api_version}/rubygems/defaults/operating_system.rb"
config_file.unlink if config_file.exist?
config_file.write rubygems_config(api_version)
# Create the sitedir and vendordir that were skipped during install
%w[sitearchdir vendorarchdir].each do |dir|
mkdir_p `#{bin}/ruby -rrbconfig -e 'print RbConfig::CONFIG["#{dir}"]'`
end
end
def rubygems_config(api_version); <<~EOS
module Gem
class << self
alias :old_default_dir :default_dir
alias :old_default_path :default_path
alias :old_default_bindir :default_bindir
alias :old_ruby :ruby
end
def self.default_dir
path = [
"#{HOMEBREW_PREFIX}",
"lib",
"ruby",
"gems",
"#{api_version}"
]
@default_dir ||= File.join(*path)
end
def self.private_dir
path = if defined? RUBY_FRAMEWORK_VERSION then
[
File.dirname(RbConfig::CONFIG['sitedir']),
'Gems',
RbConfig::CONFIG['ruby_version']
]
elsif RbConfig::CONFIG['rubylibprefix'] then
[
RbConfig::CONFIG['rubylibprefix'],
'gems',
RbConfig::CONFIG['ruby_version']
]
else
[
RbConfig::CONFIG['libdir'],
ruby_engine,
'gems',
RbConfig::CONFIG['ruby_version']
]
end
@private_dir ||= File.join(*path)
end
def self.default_path
if Gem.user_home && File.exist?(Gem.user_home)
[user_dir, default_dir, private_dir]
else
[default_dir, private_dir]
end
end
def self.default_bindir
"#{rubygems_bindir}"
end
def self.ruby
"#{opt_bin}/ruby"
end
end
EOS
end
test do
hello_text = shell_output("#{bin}/ruby -e 'puts :hello'")
assert_equal "hello\n", hello_text
ENV["GEM_HOME"] = testpath
system "#{bin}/gem", "install", "json"
(testpath/"Gemfile").write <<~EOS
source 'https://rubygems.org'
gem 'gemoji'
EOS
system rubygems_bindir/"bundle", "install", "--binstubs=#{testpath}/bin"
assert_predicate testpath/"bin/gemoji", :exist?, "gemoji is not installed in #{testpath}/bin"
end
end
ruby: update 2.5.3 bottle for Linuxbrew.
class Ruby < Formula
desc "Powerful, clean, object-oriented scripting language"
homepage "https://www.ruby-lang.org/"
url "https://cache.ruby-lang.org/pub/ruby/2.5/ruby-2.5.3.tar.xz"
sha256 "1cc9d0359a8ea35fc6111ec830d12e60168f3b9b305a3c2578357d360fcf306f"
bottle do
sha256 "6c620464fee701978124bdb9ef12179fb55ba62e73222ed42d59e6c07d25a04a" => :mojave
sha256 "4973d5cabcb8b53ab892a331e6c02b8230e9c8ef7a69f6a96d0aec69d3099831" => :high_sierra
sha256 "df8aabed70a29a81ca6f1d5e6a4fcbc0de999cab09b6377b1f61b9dde29b5b21" => :sierra
sha256 "e332dc3c870d23afb867162147e4e4840d65e72594e8d232d3558f61e109973e" => :x86_64_linux
end
devel do
url "https://cache.ruby-lang.org/pub/ruby/2.6/ruby-2.6.0-preview2.tar.xz"
version "2.6.0-preview2"
sha256 "00ddfb5e33dee24469dd0b203597f7ecee66522ebb496f620f5815372ea2d3ec"
end
head do
url "https://github.com/ruby/ruby.git"
depends_on "autoconf" => :build
end
depends_on "pkg-config" => :build
depends_on "libyaml"
depends_on "openssl"
depends_on "readline"
depends_on "zlib" unless OS.mac?
# Should be updated only when Ruby is updated (if an update is available).
# The exception is Rubygem security fixes, which mandate updating this
# formula & the versioned equivalents and bumping the revisions.
resource "rubygems" do
url "https://rubygems.org/rubygems/rubygems-2.7.7.tgz"
sha256 "4cb2c9a36c0e4a3d5c20eb6795638632858fd72236d281963140221946ab55cb"
end
def api_version
Utils.popen_read("#{bin}/ruby -e 'print Gem.ruby_api_version'")
end
def rubygems_bindir
HOMEBREW_PREFIX/"bin"
end
def install
if OS.linux? && build.bottle?
# The compiler used to build Ruby is stored in the bottle.
# See ruby <<<'print RbConfig::CONFIG["CC"]'
ENV["CC"] = "cc"
ENV["CXX"] = "c++"
end
# otherwise `gem` command breaks
ENV.delete("SDKROOT")
system "autoconf" if build.head?
paths = %w[libyaml openssl readline].map { |f| Formula[f].opt_prefix }
args = %W[
--prefix=#{prefix}
--enable-shared
--disable-silent-rules
--with-sitedir=#{HOMEBREW_PREFIX}/lib/ruby/site_ruby
--with-vendordir=#{HOMEBREW_PREFIX}/lib/ruby/vendor_ruby
--with-opt-dir=#{paths.join(":")}
]
args << "--disable-dtrace" if OS.mac? && !MacOS::CLT.installed?
system "./configure", *args
# Ruby has been configured to look in the HOMEBREW_PREFIX for the
# sitedir and vendordir directories; however we don't actually want to create
# them during the install.
#
# These directories are empty on install; sitedir is used for non-rubygems
# third party libraries, and vendordir is used for packager-provided libraries.
inreplace "tool/rbinstall.rb" do |s|
s.gsub! 'prepare "extension scripts", sitelibdir', ""
s.gsub! 'prepare "extension scripts", vendorlibdir', ""
s.gsub! 'prepare "extension objects", sitearchlibdir', ""
s.gsub! 'prepare "extension objects", vendorarchlibdir', ""
end
system "make"
system "make", "install"
# A newer version of ruby-mode.el is shipped with Emacs
elisp.install Dir["misc/*.el"].reject { |f| f == "misc/ruby-mode.el" }
# This is easier than trying to keep both current & versioned Ruby
# formulae repeatedly updated with Rubygem patches.
resource("rubygems").stage do
ENV.prepend_path "PATH", bin
system "#{bin}/ruby", "setup.rb", "--prefix=#{buildpath}/vendor_gem"
rg_in = lib/"ruby/#{api_version}"
# Remove bundled Rubygem version.
rm_rf rg_in/"rubygems"
rm_f rg_in/"rubygems.rb"
rm_f rg_in/"ubygems.rb"
rm_f bin/"gem"
# Drop in the new version.
rg_in.install Dir[buildpath/"vendor_gem/lib/*"]
bin.install buildpath/"vendor_gem/bin/gem" => "gem"
(libexec/"gembin").install buildpath/"vendor_gem/bin/bundle" => "bundle"
(libexec/"gembin").install_symlink "bundle" => "bundler"
end
end
def post_install
# Since Gem ships Bundle we want to provide that full/expected installation
# but to do so we need to handle the case where someone has previously
# installed bundle manually via `gem install`.
rm_f %W[
#{rubygems_bindir}/bundle
#{rubygems_bindir}/bundler
]
rm_rf Dir[HOMEBREW_PREFIX/"lib/ruby/gems/#{api_version}/gems/bundler-*"]
rubygems_bindir.install_symlink Dir[libexec/"gembin/*"]
# Customize rubygems to look/install in the global gem directory
# instead of in the Cellar, making gems last across reinstalls
config_file = lib/"ruby/#{api_version}/rubygems/defaults/operating_system.rb"
config_file.unlink if config_file.exist?
config_file.write rubygems_config(api_version)
# Create the sitedir and vendordir that were skipped during install
%w[sitearchdir vendorarchdir].each do |dir|
mkdir_p `#{bin}/ruby -rrbconfig -e 'print RbConfig::CONFIG["#{dir}"]'`
end
end
def rubygems_config(api_version); <<~EOS
module Gem
class << self
alias :old_default_dir :default_dir
alias :old_default_path :default_path
alias :old_default_bindir :default_bindir
alias :old_ruby :ruby
end
def self.default_dir
path = [
"#{HOMEBREW_PREFIX}",
"lib",
"ruby",
"gems",
"#{api_version}"
]
@default_dir ||= File.join(*path)
end
def self.private_dir
path = if defined? RUBY_FRAMEWORK_VERSION then
[
File.dirname(RbConfig::CONFIG['sitedir']),
'Gems',
RbConfig::CONFIG['ruby_version']
]
elsif RbConfig::CONFIG['rubylibprefix'] then
[
RbConfig::CONFIG['rubylibprefix'],
'gems',
RbConfig::CONFIG['ruby_version']
]
else
[
RbConfig::CONFIG['libdir'],
ruby_engine,
'gems',
RbConfig::CONFIG['ruby_version']
]
end
@private_dir ||= File.join(*path)
end
def self.default_path
if Gem.user_home && File.exist?(Gem.user_home)
[user_dir, default_dir, private_dir]
else
[default_dir, private_dir]
end
end
def self.default_bindir
"#{rubygems_bindir}"
end
def self.ruby
"#{opt_bin}/ruby"
end
end
EOS
end
test do
hello_text = shell_output("#{bin}/ruby -e 'puts :hello'")
assert_equal "hello\n", hello_text
ENV["GEM_HOME"] = testpath
system "#{bin}/gem", "install", "json"
(testpath/"Gemfile").write <<~EOS
source 'https://rubygems.org'
gem 'gemoji'
EOS
system rubygems_bindir/"bundle", "install", "--binstubs=#{testpath}/bin"
assert_predicate testpath/"bin/gemoji", :exist?, "gemoji is not installed in #{testpath}/bin"
end
end
|
class Ruby < Formula
desc "Powerful, clean, object-oriented scripting language"
homepage "https://www.ruby-lang.org/"
url "https://cache.ruby-lang.org/pub/ruby/2.5/ruby-2.5.1.tar.xz"
sha256 "886ac5eed41e3b5fc699be837b0087a6a5a3d10f464087560d2d21b3e71b754d"
bottle do
sha256 "8e0435a0c5b066866799464e6603ceb2afe20f5dc92ed98e1057dd5a319f5cc2" => :high_sierra
sha256 "3bfecdbe9caf5cf8e13bfccdfb2cf1ad1f8d1ce6efb62152d73717ac63479eaf" => :sierra
sha256 "91f06a229b8f8a89cdb3870517d1f5d22a4ba915e43bc7c2b20d3224778492cd" => :el_capitan
end
devel do
url "https://cache.ruby-lang.org/pub/ruby/2.6/ruby-2.6.0-preview2.tar.xz"
version "2.6.0-preview2"
sha256 "00ddfb5e33dee24469dd0b203597f7ecee66522ebb496f620f5815372ea2d3ec"
end
head do
url "https://svn.ruby-lang.org/repos/ruby/trunk/"
depends_on "autoconf" => :build
end
depends_on "pkg-config" => :build
depends_on "libyaml"
depends_on "openssl"
depends_on "readline"
# Should be updated only when Ruby is updated (if an update is available).
# The exception is Rubygem security fixes, which mandate updating this
# formula & the versioned equivalents and bumping the revisions.
resource "rubygems" do
url "https://rubygems.org/rubygems/rubygems-2.7.6.tgz"
sha256 "67f714a582a9ce471bbbcb417374ea9cf9c061271c865dbb0d093f3bc3371eeb"
end
def api_version
Utils.popen_read("#{bin}/ruby -e 'print Gem.ruby_api_version'")
end
def rubygems_bindir
HOMEBREW_PREFIX/"bin"
end
def install
# otherwise `gem` command breaks
ENV.delete("SDKROOT")
system "autoconf" if build.head?
paths = %w[libyaml openssl readline].map { |f| Formula[f].opt_prefix }
args = %W[
--prefix=#{prefix}
--enable-shared
--disable-silent-rules
--with-sitedir=#{HOMEBREW_PREFIX}/lib/ruby/site_ruby
--with-vendordir=#{HOMEBREW_PREFIX}/lib/ruby/vendor_ruby
--with-opt-dir=#{paths.join(":")}
]
args << "--disable-dtrace" unless MacOS::CLT.installed?
system "./configure", *args
# Ruby has been configured to look in the HOMEBREW_PREFIX for the
# sitedir and vendordir directories; however we don't actually want to create
# them during the install.
#
# These directories are empty on install; sitedir is used for non-rubygems
# third party libraries, and vendordir is used for packager-provided libraries.
inreplace "tool/rbinstall.rb" do |s|
s.gsub! 'prepare "extension scripts", sitelibdir', ""
s.gsub! 'prepare "extension scripts", vendorlibdir', ""
s.gsub! 'prepare "extension objects", sitearchlibdir', ""
s.gsub! 'prepare "extension objects", vendorarchlibdir', ""
end
system "make"
system "make", "install"
# A newer version of ruby-mode.el is shipped with Emacs
elisp.install Dir["misc/*.el"].reject { |f| f == "misc/ruby-mode.el" }
# This is easier than trying to keep both current & versioned Ruby
# formulae repeatedly updated with Rubygem patches.
resource("rubygems").stage do
ENV.prepend_path "PATH", bin
system "#{bin}/ruby", "setup.rb", "--prefix=#{buildpath}/vendor_gem"
rg_in = lib/"ruby/#{api_version}"
# Remove bundled Rubygem version.
rm_rf rg_in/"rubygems"
rm_f rg_in/"rubygems.rb"
rm_f rg_in/"ubygems.rb"
rm_f bin/"gem"
# Drop in the new version.
rg_in.install Dir[buildpath/"vendor_gem/lib/*"]
bin.install buildpath/"vendor_gem/bin/gem" => "gem"
(libexec/"gembin").install buildpath/"vendor_gem/bin/bundle" => "bundle"
(libexec/"gembin").install_symlink "bundle" => "bundler"
end
end
def post_install
# Since Gem ships Bundle we want to provide that full/expected installation
# but to do so we need to handle the case where someone has previously
# installed bundle manually via `gem install`.
rm_f %W[
#{rubygems_bindir}/bundle
#{rubygems_bindir}/bundler
]
rm_rf Dir[HOMEBREW_PREFIX/"lib/ruby/gems/#{api_version}/gems/bundler-*"]
rubygems_bindir.install_symlink Dir[libexec/"gembin/*"]
# Customize rubygems to look/install in the global gem directory
# instead of in the Cellar, making gems last across reinstalls
config_file = lib/"ruby/#{api_version}/rubygems/defaults/operating_system.rb"
config_file.unlink if config_file.exist?
config_file.write rubygems_config(api_version)
# Create the sitedir and vendordir that were skipped during install
%w[sitearchdir vendorarchdir].each do |dir|
mkdir_p `#{bin}/ruby -rrbconfig -e 'print RbConfig::CONFIG["#{dir}"]'`
end
end
def rubygems_config(api_version); <<~EOS
module Gem
class << self
alias :old_default_dir :default_dir
alias :old_default_path :default_path
alias :old_default_bindir :default_bindir
alias :old_ruby :ruby
end
def self.default_dir
path = [
"#{HOMEBREW_PREFIX}",
"lib",
"ruby",
"gems",
"#{api_version}"
]
@default_dir ||= File.join(*path)
end
def self.private_dir
path = if defined? RUBY_FRAMEWORK_VERSION then
[
File.dirname(RbConfig::CONFIG['sitedir']),
'Gems',
RbConfig::CONFIG['ruby_version']
]
elsif RbConfig::CONFIG['rubylibprefix'] then
[
RbConfig::CONFIG['rubylibprefix'],
'gems',
RbConfig::CONFIG['ruby_version']
]
else
[
RbConfig::CONFIG['libdir'],
ruby_engine,
'gems',
RbConfig::CONFIG['ruby_version']
]
end
@private_dir ||= File.join(*path)
end
def self.default_path
if Gem.user_home && File.exist?(Gem.user_home)
[user_dir, default_dir, private_dir]
else
[default_dir, private_dir]
end
end
def self.default_bindir
"#{rubygems_bindir}"
end
def self.ruby
"#{opt_bin}/ruby"
end
end
EOS
end
test do
hello_text = shell_output("#{bin}/ruby -e 'puts :hello'")
assert_equal "hello\n", hello_text
ENV["GEM_HOME"] = testpath
system "#{bin}/gem", "install", "json"
(testpath/"Gemfile").write <<~EOS
source 'https://rubygems.org'
gem 'gemoji'
EOS
system rubygems_bindir/"bundle", "install", "--binstubs=#{testpath}/bin"
assert_predicate testpath/"bin/gemoji", :exist?, "gemoji is not installed in #{testpath}/bin"
end
end
ruby: update 2.5.1 bottle.
class Ruby < Formula
desc "Powerful, clean, object-oriented scripting language"
homepage "https://www.ruby-lang.org/"
url "https://cache.ruby-lang.org/pub/ruby/2.5/ruby-2.5.1.tar.xz"
sha256 "886ac5eed41e3b5fc699be837b0087a6a5a3d10f464087560d2d21b3e71b754d"
bottle do
sha256 "57ca0ee728d545e4a3e8b91955e4f19733098d017739727394381a7edb42686b" => :mojave
sha256 "8e0435a0c5b066866799464e6603ceb2afe20f5dc92ed98e1057dd5a319f5cc2" => :high_sierra
sha256 "3bfecdbe9caf5cf8e13bfccdfb2cf1ad1f8d1ce6efb62152d73717ac63479eaf" => :sierra
sha256 "91f06a229b8f8a89cdb3870517d1f5d22a4ba915e43bc7c2b20d3224778492cd" => :el_capitan
end
devel do
url "https://cache.ruby-lang.org/pub/ruby/2.6/ruby-2.6.0-preview2.tar.xz"
version "2.6.0-preview2"
sha256 "00ddfb5e33dee24469dd0b203597f7ecee66522ebb496f620f5815372ea2d3ec"
end
head do
url "https://svn.ruby-lang.org/repos/ruby/trunk/"
depends_on "autoconf" => :build
end
depends_on "pkg-config" => :build
depends_on "libyaml"
depends_on "openssl"
depends_on "readline"
# Should be updated only when Ruby is updated (if an update is available).
# The exception is Rubygem security fixes, which mandate updating this
# formula & the versioned equivalents and bumping the revisions.
resource "rubygems" do
url "https://rubygems.org/rubygems/rubygems-2.7.6.tgz"
sha256 "67f714a582a9ce471bbbcb417374ea9cf9c061271c865dbb0d093f3bc3371eeb"
end
def api_version
Utils.popen_read("#{bin}/ruby -e 'print Gem.ruby_api_version'")
end
def rubygems_bindir
HOMEBREW_PREFIX/"bin"
end
def install
# otherwise `gem` command breaks
ENV.delete("SDKROOT")
system "autoconf" if build.head?
paths = %w[libyaml openssl readline].map { |f| Formula[f].opt_prefix }
args = %W[
--prefix=#{prefix}
--enable-shared
--disable-silent-rules
--with-sitedir=#{HOMEBREW_PREFIX}/lib/ruby/site_ruby
--with-vendordir=#{HOMEBREW_PREFIX}/lib/ruby/vendor_ruby
--with-opt-dir=#{paths.join(":")}
]
args << "--disable-dtrace" unless MacOS::CLT.installed?
system "./configure", *args
# Ruby has been configured to look in the HOMEBREW_PREFIX for the
# sitedir and vendordir directories; however we don't actually want to create
# them during the install.
#
# These directories are empty on install; sitedir is used for non-rubygems
# third party libraries, and vendordir is used for packager-provided libraries.
inreplace "tool/rbinstall.rb" do |s|
s.gsub! 'prepare "extension scripts", sitelibdir', ""
s.gsub! 'prepare "extension scripts", vendorlibdir', ""
s.gsub! 'prepare "extension objects", sitearchlibdir', ""
s.gsub! 'prepare "extension objects", vendorarchlibdir', ""
end
system "make"
system "make", "install"
# A newer version of ruby-mode.el is shipped with Emacs
elisp.install Dir["misc/*.el"].reject { |f| f == "misc/ruby-mode.el" }
# This is easier than trying to keep both current & versioned Ruby
# formulae repeatedly updated with Rubygem patches.
resource("rubygems").stage do
ENV.prepend_path "PATH", bin
system "#{bin}/ruby", "setup.rb", "--prefix=#{buildpath}/vendor_gem"
rg_in = lib/"ruby/#{api_version}"
# Remove bundled Rubygem version.
rm_rf rg_in/"rubygems"
rm_f rg_in/"rubygems.rb"
rm_f rg_in/"ubygems.rb"
rm_f bin/"gem"
# Drop in the new version.
rg_in.install Dir[buildpath/"vendor_gem/lib/*"]
bin.install buildpath/"vendor_gem/bin/gem" => "gem"
(libexec/"gembin").install buildpath/"vendor_gem/bin/bundle" => "bundle"
(libexec/"gembin").install_symlink "bundle" => "bundler"
end
end
def post_install
# Since Gem ships Bundle we want to provide that full/expected installation
# but to do so we need to handle the case where someone has previously
# installed bundle manually via `gem install`.
rm_f %W[
#{rubygems_bindir}/bundle
#{rubygems_bindir}/bundler
]
rm_rf Dir[HOMEBREW_PREFIX/"lib/ruby/gems/#{api_version}/gems/bundler-*"]
rubygems_bindir.install_symlink Dir[libexec/"gembin/*"]
# Customize rubygems to look/install in the global gem directory
# instead of in the Cellar, making gems last across reinstalls
config_file = lib/"ruby/#{api_version}/rubygems/defaults/operating_system.rb"
config_file.unlink if config_file.exist?
config_file.write rubygems_config(api_version)
# Create the sitedir and vendordir that were skipped during install
%w[sitearchdir vendorarchdir].each do |dir|
mkdir_p `#{bin}/ruby -rrbconfig -e 'print RbConfig::CONFIG["#{dir}"]'`
end
end
def rubygems_config(api_version); <<~EOS
module Gem
class << self
alias :old_default_dir :default_dir
alias :old_default_path :default_path
alias :old_default_bindir :default_bindir
alias :old_ruby :ruby
end
def self.default_dir
path = [
"#{HOMEBREW_PREFIX}",
"lib",
"ruby",
"gems",
"#{api_version}"
]
@default_dir ||= File.join(*path)
end
def self.private_dir
path = if defined? RUBY_FRAMEWORK_VERSION then
[
File.dirname(RbConfig::CONFIG['sitedir']),
'Gems',
RbConfig::CONFIG['ruby_version']
]
elsif RbConfig::CONFIG['rubylibprefix'] then
[
RbConfig::CONFIG['rubylibprefix'],
'gems',
RbConfig::CONFIG['ruby_version']
]
else
[
RbConfig::CONFIG['libdir'],
ruby_engine,
'gems',
RbConfig::CONFIG['ruby_version']
]
end
@private_dir ||= File.join(*path)
end
def self.default_path
if Gem.user_home && File.exist?(Gem.user_home)
[user_dir, default_dir, private_dir]
else
[default_dir, private_dir]
end
end
def self.default_bindir
"#{rubygems_bindir}"
end
def self.ruby
"#{opt_bin}/ruby"
end
end
EOS
end
test do
hello_text = shell_output("#{bin}/ruby -e 'puts :hello'")
assert_equal "hello\n", hello_text
ENV["GEM_HOME"] = testpath
system "#{bin}/gem", "install", "json"
(testpath/"Gemfile").write <<~EOS
source 'https://rubygems.org'
gem 'gemoji'
EOS
system rubygems_bindir/"bundle", "install", "--binstubs=#{testpath}/bin"
assert_predicate testpath/"bin/gemoji", :exist?, "gemoji is not installed in #{testpath}/bin"
end
end
|
class Ruby < Formula
desc "Powerful, clean, object-oriented scripting language"
homepage "https://www.ruby-lang.org/"
url "https://cache.ruby-lang.org/pub/ruby/2.7/ruby-2.7.1.tar.xz"
sha256 "b224f9844646cc92765df8288a46838511c1cec5b550d8874bd4686a904fcee7"
revision 1
bottle do
sha256 "6eb292b04eff387c224ad7325c8b1b17d849af611e67a3dfae9af6e50551668b" => :catalina
sha256 "1ddc699cc9630468dc21bcd56f326c18981eaf435c73a844dd7b4c059e7f05f0" => :mojave
sha256 "db64bf12f44269864d5f26f75528306361fda314ec9de8a2c76b9b6d47a2baae" => :high_sierra
end
head do
url "https://github.com/ruby/ruby.git", :branch => "trunk"
depends_on "autoconf" => :build
end
keg_only :provided_by_macos
depends_on "pkg-config" => :build
depends_on "libyaml"
depends_on "openssl@1.1"
depends_on "readline"
uses_from_macos "zlib"
# Should be updated only when Ruby is updated (if an update is available).
# The exception is Rubygem security fixes, which mandate updating this
# formula & the versioned equivalents and bumping the revisions.
resource "rubygems" do
url "https://rubygems.org/rubygems/rubygems-3.1.2.tgz"
sha256 "edd1a6bca6e780a3f65019bbcb0bbfe36c65a9809c0d43e7b52f23792591f140"
end
def api_version
Utils.popen_read("#{bin}/ruby -e 'print Gem.ruby_api_version'")
end
def rubygems_bindir
HOMEBREW_PREFIX/"lib/ruby/gems/#{api_version}/bin"
end
def install
# otherwise `gem` command breaks
ENV.delete("SDKROOT")
system "autoconf" if build.head?
paths = %w[libyaml openssl@1.1 readline].map { |f| Formula[f].opt_prefix }
args = %W[
--prefix=#{prefix}
--enable-shared
--disable-silent-rules
--with-sitedir=#{HOMEBREW_PREFIX}/lib/ruby/site_ruby
--with-vendordir=#{HOMEBREW_PREFIX}/lib/ruby/vendor_ruby
--with-opt-dir=#{paths.join(":")}
--without-gmp
]
args << "--disable-dtrace" unless MacOS::CLT.installed?
# Correct MJIT_CC to not use superenv shim
args << "MJIT_CC=/usr/bin/clang"
system "./configure", *args
# Ruby has been configured to look in the HOMEBREW_PREFIX for the
# sitedir and vendordir directories; however we don't actually want to create
# them during the install.
#
# These directories are empty on install; sitedir is used for non-rubygems
# third party libraries, and vendordir is used for packager-provided libraries.
inreplace "tool/rbinstall.rb" do |s|
s.gsub! 'prepare "extension scripts", sitelibdir', ""
s.gsub! 'prepare "extension scripts", vendorlibdir', ""
s.gsub! 'prepare "extension objects", sitearchlibdir', ""
s.gsub! 'prepare "extension objects", vendorarchlibdir', ""
end
system "make"
system "make", "install"
# A newer version of ruby-mode.el is shipped with Emacs
elisp.install Dir["misc/*.el"].reject { |f| f == "misc/ruby-mode.el" }
# This is easier than trying to keep both current & versioned Ruby
# formulae repeatedly updated with Rubygem patches.
resource("rubygems").stage do
ENV.prepend_path "PATH", bin
system "#{bin}/ruby", "setup.rb", "--prefix=#{buildpath}/vendor_gem"
rg_in = lib/"ruby/#{api_version}"
# Remove bundled Rubygem version.
rm_rf rg_in/"rubygems"
rm_f rg_in/"rubygems.rb"
rm_f rg_in/"ubygems.rb"
rm_f bin/"gem"
# Drop in the new version.
rg_in.install Dir[buildpath/"vendor_gem/lib/*"]
bin.install buildpath/"vendor_gem/bin/gem" => "gem"
(libexec/"gembin").install buildpath/"vendor_gem/bin/bundle" => "bundle"
(libexec/"gembin").install_symlink "bundle" => "bundler"
end
end
def post_install
# Since Gem ships Bundle we want to provide that full/expected installation
# but to do so we need to handle the case where someone has previously
# installed bundle manually via `gem install`.
rm_f %W[
#{rubygems_bindir}/bundle
#{rubygems_bindir}/bundler
]
rm_rf Dir[HOMEBREW_PREFIX/"lib/ruby/gems/#{api_version}/gems/bundler-*"]
rubygems_bindir.install_symlink Dir[libexec/"gembin/*"]
# Customize rubygems to look/install in the global gem directory
# instead of in the Cellar, making gems last across reinstalls
config_file = lib/"ruby/#{api_version}/rubygems/defaults/operating_system.rb"
config_file.unlink if config_file.exist?
config_file.write rubygems_config(api_version)
# Create the sitedir and vendordir that were skipped during install
%w[sitearchdir vendorarchdir].each do |dir|
mkdir_p `#{bin}/ruby -rrbconfig -e 'print RbConfig::CONFIG["#{dir}"]'`
end
end
def rubygems_config(api_version)
<<~EOS
module Gem
class << self
alias :old_default_dir :default_dir
alias :old_default_path :default_path
alias :old_default_bindir :default_bindir
alias :old_ruby :ruby
alias :old_default_specifications_dir :default_specifications_dir
end
def self.default_dir
path = [
"#{HOMEBREW_PREFIX}",
"lib",
"ruby",
"gems",
"#{api_version}"
]
@homebrew_path ||= File.join(*path)
end
def self.private_dir
path = if defined? RUBY_FRAMEWORK_VERSION then
[
File.dirname(RbConfig::CONFIG['sitedir']),
'Gems',
RbConfig::CONFIG['ruby_version']
]
elsif RbConfig::CONFIG['rubylibprefix'] then
[
RbConfig::CONFIG['rubylibprefix'],
'gems',
RbConfig::CONFIG['ruby_version']
]
else
[
RbConfig::CONFIG['libdir'],
ruby_engine,
'gems',
RbConfig::CONFIG['ruby_version']
]
end
@private_dir ||= File.join(*path)
end
def self.default_path
if Gem.user_home && File.exist?(Gem.user_home)
[user_dir, default_dir, old_default_dir, private_dir]
else
[default_dir, old_default_dir, private_dir]
end
end
def self.default_bindir
"#{rubygems_bindir}"
end
def self.ruby
"#{opt_bin}/ruby"
end
# https://github.com/Homebrew/homebrew-core/issues/40872#issuecomment-542092547
# https://github.com/Homebrew/homebrew-core/pull/48329#issuecomment-584418161
def self.default_specifications_dir
File.join(Gem.old_default_dir, "specifications", "default")
end
end
EOS
end
def caveats
<<~EOS
By default, binaries installed by gem will be placed into:
#{rubygems_bindir}
You may want to add this to your PATH.
EOS
end
test do
hello_text = shell_output("#{bin}/ruby -e 'puts :hello'")
assert_equal "hello\n", hello_text
ENV["GEM_HOME"] = testpath
system "#{bin}/gem", "install", "json"
(testpath/"Gemfile").write <<~EOS
source 'https://rubygems.org'
gem 'gemoji'
EOS
system bin/"bundle", "install", "--binstubs=#{testpath}/bin"
assert_predicate testpath/"bin/gemoji", :exist?, "gemoji is not installed in #{testpath}/bin"
end
end
ruby: correctly replace bundled bundler
Fixes #53247.
Closes #53267.
Signed-off-by: Bo Anderson <1d6e1cf70ec6f9ab28d3ea4b27a49a77654d370e@boanderson.me>
class Ruby < Formula
desc "Powerful, clean, object-oriented scripting language"
homepage "https://www.ruby-lang.org/"
url "https://cache.ruby-lang.org/pub/ruby/2.7/ruby-2.7.1.tar.xz"
sha256 "b224f9844646cc92765df8288a46838511c1cec5b550d8874bd4686a904fcee7"
revision 2
bottle do
sha256 "6eb292b04eff387c224ad7325c8b1b17d849af611e67a3dfae9af6e50551668b" => :catalina
sha256 "1ddc699cc9630468dc21bcd56f326c18981eaf435c73a844dd7b4c059e7f05f0" => :mojave
sha256 "db64bf12f44269864d5f26f75528306361fda314ec9de8a2c76b9b6d47a2baae" => :high_sierra
end
head do
url "https://github.com/ruby/ruby.git", :branch => "trunk"
depends_on "autoconf" => :build
end
keg_only :provided_by_macos
depends_on "pkg-config" => :build
depends_on "libyaml"
depends_on "openssl@1.1"
depends_on "readline"
uses_from_macos "zlib"
# Should be updated only when Ruby is updated (if an update is available).
# The exception is Rubygem security fixes, which mandate updating this
# formula & the versioned equivalents and bumping the revisions.
resource "rubygems" do
url "https://rubygems.org/rubygems/rubygems-3.1.2.tgz"
sha256 "edd1a6bca6e780a3f65019bbcb0bbfe36c65a9809c0d43e7b52f23792591f140"
end
def api_version
Utils.popen_read("#{bin}/ruby -e 'print Gem.ruby_api_version'")
end
def rubygems_bindir
HOMEBREW_PREFIX/"lib/ruby/gems/#{api_version}/bin"
end
def install
# otherwise `gem` command breaks
ENV.delete("SDKROOT")
system "autoconf" if build.head?
paths = %w[libyaml openssl@1.1 readline].map { |f| Formula[f].opt_prefix }
args = %W[
--prefix=#{prefix}
--enable-shared
--disable-silent-rules
--with-sitedir=#{HOMEBREW_PREFIX}/lib/ruby/site_ruby
--with-vendordir=#{HOMEBREW_PREFIX}/lib/ruby/vendor_ruby
--with-opt-dir=#{paths.join(":")}
--without-gmp
]
args << "--disable-dtrace" unless MacOS::CLT.installed?
# Correct MJIT_CC to not use superenv shim
args << "MJIT_CC=/usr/bin/clang"
system "./configure", *args
# Ruby has been configured to look in the HOMEBREW_PREFIX for the
# sitedir and vendordir directories; however we don't actually want to create
# them during the install.
#
# These directories are empty on install; sitedir is used for non-rubygems
# third party libraries, and vendordir is used for packager-provided libraries.
inreplace "tool/rbinstall.rb" do |s|
s.gsub! 'prepare "extension scripts", sitelibdir', ""
s.gsub! 'prepare "extension scripts", vendorlibdir', ""
s.gsub! 'prepare "extension objects", sitearchlibdir', ""
s.gsub! 'prepare "extension objects", vendorarchlibdir', ""
end
system "make"
system "make", "install"
# A newer version of ruby-mode.el is shipped with Emacs
elisp.install Dir["misc/*.el"].reject { |f| f == "misc/ruby-mode.el" }
# This is easier than trying to keep both current & versioned Ruby
# formulae repeatedly updated with Rubygem patches.
resource("rubygems").stage do
ENV.prepend_path "PATH", bin
system "#{bin}/ruby", "setup.rb", "--prefix=#{buildpath}/vendor_gem"
rg_in = lib/"ruby/#{api_version}"
# Remove bundled Rubygem and Bundler
rm_rf rg_in/"bundler"
rm_rf rg_in/"rubygems"
rm_f rg_in/"rubygems.rb"
rm_f rg_in/"ubygems.rb"
rm_f bin/"gem"
# Drop in the new version.
rg_in.install Dir[buildpath/"vendor_gem/lib/*"]
bin.install buildpath/"vendor_gem/bin/gem" => "gem"
(libexec/"gembin").install buildpath/"vendor_gem/bin/bundle" => "bundle"
(libexec/"gembin").install_symlink "bundle" => "bundler"
end
end
def post_install
# Since Gem ships Bundle we want to provide that full/expected installation
# but to do so we need to handle the case where someone has previously
# installed bundle manually via `gem install`.
rm_f %W[
#{rubygems_bindir}/bundle
#{rubygems_bindir}/bundler
]
rm_rf Dir[HOMEBREW_PREFIX/"lib/ruby/gems/#{api_version}/gems/bundler-*"]
rubygems_bindir.install_symlink Dir[libexec/"gembin/*"]
# Customize rubygems to look/install in the global gem directory
# instead of in the Cellar, making gems last across reinstalls
config_file = lib/"ruby/#{api_version}/rubygems/defaults/operating_system.rb"
config_file.unlink if config_file.exist?
config_file.write rubygems_config(api_version)
# Create the sitedir and vendordir that were skipped during install
%w[sitearchdir vendorarchdir].each do |dir|
mkdir_p `#{bin}/ruby -rrbconfig -e 'print RbConfig::CONFIG["#{dir}"]'`
end
end
def rubygems_config(api_version)
<<~EOS
module Gem
class << self
alias :old_default_dir :default_dir
alias :old_default_path :default_path
alias :old_default_bindir :default_bindir
alias :old_ruby :ruby
alias :old_default_specifications_dir :default_specifications_dir
end
def self.default_dir
path = [
"#{HOMEBREW_PREFIX}",
"lib",
"ruby",
"gems",
"#{api_version}"
]
@homebrew_path ||= File.join(*path)
end
def self.private_dir
path = if defined? RUBY_FRAMEWORK_VERSION then
[
File.dirname(RbConfig::CONFIG['sitedir']),
'Gems',
RbConfig::CONFIG['ruby_version']
]
elsif RbConfig::CONFIG['rubylibprefix'] then
[
RbConfig::CONFIG['rubylibprefix'],
'gems',
RbConfig::CONFIG['ruby_version']
]
else
[
RbConfig::CONFIG['libdir'],
ruby_engine,
'gems',
RbConfig::CONFIG['ruby_version']
]
end
@private_dir ||= File.join(*path)
end
def self.default_path
if Gem.user_home && File.exist?(Gem.user_home)
[user_dir, default_dir, old_default_dir, private_dir]
else
[default_dir, old_default_dir, private_dir]
end
end
def self.default_bindir
"#{rubygems_bindir}"
end
def self.ruby
"#{opt_bin}/ruby"
end
# https://github.com/Homebrew/homebrew-core/issues/40872#issuecomment-542092547
# https://github.com/Homebrew/homebrew-core/pull/48329#issuecomment-584418161
def self.default_specifications_dir
File.join(Gem.old_default_dir, "specifications", "default")
end
end
EOS
end
def caveats
<<~EOS
By default, binaries installed by gem will be placed into:
#{rubygems_bindir}
You may want to add this to your PATH.
EOS
end
test do
hello_text = shell_output("#{bin}/ruby -e 'puts :hello'")
assert_equal "hello\n", hello_text
ENV["GEM_HOME"] = testpath
system "#{bin}/gem", "install", "json"
(testpath/"Gemfile").write <<~EOS
source 'https://rubygems.org'
gem 'gemoji'
EOS
system bin/"bundle", "exec", "ls" # https://github.com/Homebrew/homebrew-core/issues/53247
system bin/"bundle", "install", "--binstubs=#{testpath}/bin"
assert_predicate testpath/"bin/gemoji", :exist?, "gemoji is not installed in #{testpath}/bin"
end
end
|
sdcv 0.4.3
Closes Homebrew/homebrew#16481.
Signed-off-by: Adam Vandenberg <34c2b6407fd5a10249a15d699d40f9ed1782e98c@gmail.com>
require 'formula'
class Sdcv < Formula
homepage 'http://sdcv.sourceforge.net/'
# MacPorts uses this revision and version number
url 'https://sdcv.svn.sourceforge.net/svnroot/sdcv/trunk', :revision => '38'
version '0.4.3'
# Always needs a newer autotools, even on Snow Leopard.
depends_on 'automake' => :build
depends_on 'autoconf' => :build
depends_on 'pkg-config' => :build
depends_on 'gettext'
depends_on 'glib'
depends_on 'readline'
fails_with :clang do
build 421
cause <<-EOS.undent
In C++, clang supports variable length arrays in very limited
circumstances, the element type of a variable length array must
be a POD ("plain old data") type.
More detail here: http://clang.llvm.org/compatibility.html
EOS
end
def patches
{ :p0 =>
"https://trac.macports.org/export/100327/trunk/dports/textproc/sdcv/files/patch-setlocale.diff"
}
end
def install
# Compatibility with Automake 1.13+
inreplace 'configure.ac', 'AM_CONFIG_HEADER', 'AC_CONFIG_HEADERS'
system "autoreconf -vfi"
system "./configure", "--prefix=#{prefix}"
system "make install"
end
end
|
class Sdcv < Formula
desc "StarDict Console Version"
homepage "https://dushistov.github.io/sdcv/"
url "https://github.com/Dushistov/sdcv/archive/v0.5.2.tar.gz"
sha256 "ec08dc084a0748d5a89df01a20bbf294f09b0366295cd418000f15d2e043c4f7"
revision 2
version_scheme 1
head "https://github.com/Dushistov/sdcv.git"
bottle do
sha256 "8284b957b698321f81c7dec19e07a97422f75a5c06b1842216443535024c7c98" => :mojave
sha256 "ab5c72c084c63e3346ec1f55a9faa9e199d455e5c9cc75bf83ae8e92bfbe9518" => :high_sierra
sha256 "c30525f5718a726954d88fb28c3fce7a951c0e4f2af34ddf8ab87cbd81ecf046" => :sierra
end
depends_on "cmake" => :build
depends_on "pkg-config" => :build
depends_on "gettext"
depends_on "glib"
depends_on "readline"
def install
mkdir "build" do
system "cmake", "..", *std_cmake_args
system "make", "lang"
system "make", "install"
end
end
test do
system bin/"sdcv", "-h"
end
end
sdcv: update 0.5.2_2 bottle.
class Sdcv < Formula
desc "StarDict Console Version"
homepage "https://dushistov.github.io/sdcv/"
url "https://github.com/Dushistov/sdcv/archive/v0.5.2.tar.gz"
sha256 "ec08dc084a0748d5a89df01a20bbf294f09b0366295cd418000f15d2e043c4f7"
revision 2
version_scheme 1
head "https://github.com/Dushistov/sdcv.git"
bottle do
sha256 "d40dc4d63326ca5268f5b1d75a8a64ecc0081fe6e35d6279ee937774b39cfb33" => :mojave
sha256 "322ec61f8ae7914f8a8f5da7fac01ef0ee69aa9f9844e1c876168f9fdf54887a" => :high_sierra
sha256 "e0aa6779b49ae274e5a9da62a12caceaf2149b587d96ce051bd5c7d735c81fa4" => :sierra
end
depends_on "cmake" => :build
depends_on "pkg-config" => :build
depends_on "gettext"
depends_on "glib"
depends_on "readline"
def install
mkdir "build" do
system "cmake", "..", *std_cmake_args
system "make", "lang"
system "make", "install"
end
end
test do
system bin/"sdcv", "-h"
end
end
|
class Serd < Formula
desc "C library for RDF syntax"
homepage "https://drobilla.net/software/serd/"
url "https://download.drobilla.net/serd-0.30.4.tar.bz2"
sha256 "0c95616a6587bee5e728e026190f4acd5ab6e2400e8890d5c2a93031eab01999"
license "ISC"
bottle do
cellar :any
sha256 "3361f452fbde6a02d8dfe77fdd53c6c5ff99e0bcb9df4504526674641cc4b24e" => :catalina
sha256 "e511ee4c7bb634cef312c139535c537aaafd70bbf2c62900a2b2950901f9eebf" => :mojave
sha256 "6d5a775d35f00fca2fb98c9177616322e3a868204c2c3f93614102e5ece3237f" => :high_sierra
end
depends_on "pkg-config" => :build
def install
system "./waf", "configure", "--prefix=#{prefix}"
system "./waf"
system "./waf", "install"
end
test do
pipe_output("serdi -", "() a <http://example.org/List> .", 0)
end
end
serd: update 0.30.4 bottle.
class Serd < Formula
desc "C library for RDF syntax"
homepage "https://drobilla.net/software/serd/"
url "https://download.drobilla.net/serd-0.30.4.tar.bz2"
sha256 "0c95616a6587bee5e728e026190f4acd5ab6e2400e8890d5c2a93031eab01999"
license "ISC"
bottle do
cellar :any
sha256 "1e37820a695b8146fd21d544816b2e413cf93d7865ccabfd96d562ae4e006ee4" => :big_sur
sha256 "3361f452fbde6a02d8dfe77fdd53c6c5ff99e0bcb9df4504526674641cc4b24e" => :catalina
sha256 "e511ee4c7bb634cef312c139535c537aaafd70bbf2c62900a2b2950901f9eebf" => :mojave
sha256 "6d5a775d35f00fca2fb98c9177616322e3a868204c2c3f93614102e5ece3237f" => :high_sierra
end
depends_on "pkg-config" => :build
def install
system "./waf", "configure", "--prefix=#{prefix}"
system "./waf"
system "./waf", "install"
end
test do
pipe_output("serdi -", "() a <http://example.org/List> .", 0)
end
end
|
class Serf < Formula
desc "Service orchestration and management tool"
homepage "https://serfdom.io/"
url "https://github.com/hashicorp/serf.git",
:tag => "v0.8.3",
:revision => "15cfd05de3dffb3664aa37b06e91f970b825e380"
head "https://github.com/hashicorp/serf.git"
bottle do
cellar :any_skip_relocation
sha256 "692266b0fa6ba7a7772849938ba42dc9246d1f117a216bdcb8bd1a130181a814" => :mojave
sha256 "979604efa2ecf8c34e88d7060c84ffb003fe9eeafd26871bbc3cc94a77e0eede" => :high_sierra
sha256 "e6578320d01e78c038df703f072ef26b9a340ce00146cd96ae1b9585331fa48b" => :sierra
end
depends_on "go" => :build
depends_on "govendor" => :build
depends_on "gox" => :build
def install
contents = Dir["*"]
gopath = buildpath/"gopath"
(gopath/"src/github.com/hashicorp/serf").install contents
ENV["GOPATH"] = gopath
ENV["XC_ARCH"] = "amd64"
ENV["XC_OS"] = "darwin"
(gopath/"bin").mkpath
cd gopath/"src/github.com/hashicorp/serf" do
system "make", "bin"
bin.install "bin/serf"
prefix.install_metafiles
end
end
test do
begin
pid = fork do
exec "#{bin}/serf", "agent"
end
sleep 1
assert_match /:7946.*alive$/, shell_output("#{bin}/serf members")
ensure
system "#{bin}/serf", "leave"
Process.kill "SIGINT", pid
Process.wait pid
end
end
end
serf 0.8.4
Closes #44429.
Signed-off-by: Igor Kapkov <0d4df9d1b72c344619dd6fe70145cbea1d37d4ef@me.com>
class Serf < Formula
desc "Service orchestration and management tool"
homepage "https://serfdom.io/"
url "https://github.com/hashicorp/serf.git",
:tag => "v0.8.4",
:revision => "d0144799968225d12af441bef64e45c9740b95eb"
head "https://github.com/hashicorp/serf.git"
bottle do
cellar :any_skip_relocation
sha256 "692266b0fa6ba7a7772849938ba42dc9246d1f117a216bdcb8bd1a130181a814" => :mojave
sha256 "979604efa2ecf8c34e88d7060c84ffb003fe9eeafd26871bbc3cc94a77e0eede" => :high_sierra
sha256 "e6578320d01e78c038df703f072ef26b9a340ce00146cd96ae1b9585331fa48b" => :sierra
end
depends_on "go" => :build
depends_on "govendor" => :build
depends_on "gox" => :build
def install
contents = Dir["*"]
gopath = buildpath/"gopath"
(gopath/"src/github.com/hashicorp/serf").install contents
ENV["GOPATH"] = gopath
ENV["XC_ARCH"] = "amd64"
ENV["XC_OS"] = "darwin"
(gopath/"bin").mkpath
cd gopath/"src/github.com/hashicorp/serf" do
system "make", "bin"
bin.install "bin/serf"
prefix.install_metafiles
end
end
test do
begin
pid = fork do
exec "#{bin}/serf", "agent"
end
sleep 1
assert_match /:7946.*alive$/, shell_output("#{bin}/serf members")
ensure
system "#{bin}/serf", "leave"
Process.kill "SIGINT", pid
Process.wait pid
end
end
end
|
class Sha2 < Formula
desc "Implementation of SHA-256, SHA-384, and SHA-512 hash algorithms"
homepage "https://www.aarongifford.com/computers/sha.html"
url "https://www.aarongifford.com/computers/sha2-1.0.1.tgz"
sha256 "67bc662955c6ca2fa6a0ce372c4794ec3d0cd2c1e50b124e7a75af7e23dd1d0c"
bottle do
cellar :any_skip_relocation
rebuild 3
sha256 "133588f831b1848abef49c88fd7587052990ad4b7133dc300a5c6aed806b1801" => :sierra
sha256 "84ce281185ba415257d8507e9b16ba8dc3189ec8b8414d21a6421d5979a025d2" => :el_capitan
sha256 "da63b7e9be95c91bcdc3290e3c6caee12016c5d59960144ea26f8c6438dfe680" => :yosemite
sha256 "34650fbb427aa57f452acc23a338696756792907bd7e127d7b495a7fd7e4573a" => :mavericks
end
option "without-test", "Skip compile-time tests"
deprecated_option "without-check" => "without-test"
def install
system ENV.cc, "-o", "sha2", "sha2prog.c", "sha2.c"
system "perl", "sha2test.pl" if build.with? "test"
bin.install "sha2"
end
test do
(testpath/"checkme.txt").write "homebrew"
output = "12c87370d1b5472793e67682596b60efe2c6038d63d04134a1a88544509737b4"
assert_match output, pipe_output("#{bin}/sha2 -q -256 #{testpath}/checkme.txt")
end
end
sha2: update 1.0.1 bottle.
class Sha2 < Formula
desc "Implementation of SHA-256, SHA-384, and SHA-512 hash algorithms"
homepage "https://www.aarongifford.com/computers/sha.html"
url "https://www.aarongifford.com/computers/sha2-1.0.1.tgz"
sha256 "67bc662955c6ca2fa6a0ce372c4794ec3d0cd2c1e50b124e7a75af7e23dd1d0c"
bottle do
cellar :any_skip_relocation
rebuild 3
sha256 "ae8fb4e03f1272bd6d323669b311ddffd021a945e0beba52ae288f1fa7d4639b" => :high_sierra
sha256 "133588f831b1848abef49c88fd7587052990ad4b7133dc300a5c6aed806b1801" => :sierra
sha256 "84ce281185ba415257d8507e9b16ba8dc3189ec8b8414d21a6421d5979a025d2" => :el_capitan
sha256 "da63b7e9be95c91bcdc3290e3c6caee12016c5d59960144ea26f8c6438dfe680" => :yosemite
sha256 "34650fbb427aa57f452acc23a338696756792907bd7e127d7b495a7fd7e4573a" => :mavericks
end
option "without-test", "Skip compile-time tests"
deprecated_option "without-check" => "without-test"
def install
system ENV.cc, "-o", "sha2", "sha2prog.c", "sha2.c"
system "perl", "sha2test.pl" if build.with? "test"
bin.install "sha2"
end
test do
(testpath/"checkme.txt").write "homebrew"
output = "12c87370d1b5472793e67682596b60efe2c6038d63d04134a1a88544509737b4"
assert_match output, pipe_output("#{bin}/sha2 -q -256 #{testpath}/checkme.txt")
end
end
|
require "language/go"
class Sift < Formula
desc "Fast and powerful open source alternative to grep"
homepage "https://sift-tool.org"
url "https://github.com/svent/sift/archive/v0.7.1.tar.gz"
sha256 "b812edc2b439b00d45a1b588f7478723cfd77f3c56a82c3d39f29c7be0725c80"
bottle do
cellar :any_skip_relocation
sha256 "6dae9b20f62d634243e40a2ffd321756fa5012bf5b628ad4ffc65beac336e65a" => :el_capitan
sha256 "d6d0721dd56ed477a264954305b04c64b948804b1d4e00252613f2ebe35e7ada" => :yosemite
sha256 "dc900b64ddf7c4b757fe978d45f984dfc26dc51835880efb76662a1bf8573492" => :mavericks
end
depends_on "go" => :build
go_resource "github.com/svent/go-flags" do
url "https://github.com/svent/go-flags.git", :revision => "4bcbad344f0318adaf7aabc16929701459009aa3"
end
go_resource "github.com/svent/go-nbreader" do
url "https://github.com/svent/go-nbreader.git", :revision => "7cef48da76dca6a496faa7fe63e39ed665cbd219"
end
go_resource "github.com/svent/sift" do
url "https://github.com/svent/sift.git", :revision => "4cd25ceddf7bf39a180e835a689c5c8a1157707a"
end
go_resource "golang.org/x/crypto" do
url "https://go.googlesource.com/crypto.git", :revision => "3760e016850398b85094c4c99e955b8c3dea5711"
end
def install
ENV["GOPATH"] = buildpath
Language::Go.stage_deps resources, buildpath/"src"
system "go", "build", "-o", bin/"sift"
end
test do
(testpath/"test.txt").write "where is foo"
assert_match(/where is foo/, shell_output("#{bin/"sift"} foo #{testpath}"))
end
end
sift 0.8.0
Closes Homebrew/homebrew#48998.
Signed-off-by: Dominyk Tiller <53e438f55903875d07efdd98a8aaf887e7208dd3@gmail.com>
require "language/go"
class Sift < Formula
desc "Fast and powerful open source alternative to grep"
homepage "https://sift-tool.org"
url "https://github.com/svent/sift/archive/v0.8.0.tar.gz"
sha256 "8686e560771392dde526b12b684015c5b1ca52089119011342f8073513c40751"
bottle do
cellar :any_skip_relocation
sha256 "6dae9b20f62d634243e40a2ffd321756fa5012bf5b628ad4ffc65beac336e65a" => :el_capitan
sha256 "d6d0721dd56ed477a264954305b04c64b948804b1d4e00252613f2ebe35e7ada" => :yosemite
sha256 "dc900b64ddf7c4b757fe978d45f984dfc26dc51835880efb76662a1bf8573492" => :mavericks
end
depends_on "go" => :build
go_resource "github.com/svent/go-flags" do
url "https://github.com/svent/go-flags.git",
:revision => "4bcbad344f0318adaf7aabc16929701459009aa3"
end
go_resource "github.com/svent/go-nbreader" do
url "https://github.com/svent/go-nbreader.git",
:revision => "7cef48da76dca6a496faa7fe63e39ed665cbd219"
end
go_resource "github.com/svent/sift" do
url "https://github.com/svent/sift.git",
:revision => "2d175c4137cad933fa40e0af69020bd658ef5fb3"
end
go_resource "golang.org/x/crypto" do
url "https://go.googlesource.com/crypto.git",
:revision => "1f22c0103821b9390939b6776727195525381532"
end
def install
ENV["GOPATH"] = buildpath
Language::Go.stage_deps resources, buildpath/"src"
system "go", "build", "-o", bin/"sift"
end
test do
(testpath/"test.txt").write "where is foo"
assert_match(/where is foo/, shell_output("#{bin/"sift"} foo #{testpath}"))
end
end
|
class Sipp < Formula
desc "Traffic generator for the SIP protocol"
homepage "https://sipp.sourceforge.io/"
url "https://github.com/SIPp/sipp/releases/download/v3.6.1/sipp-3.6.1.tar.gz"
sha256 "6a560e83aff982f331ddbcadfb3bd530c5896cd5b757dd6eb682133cc860ecb1"
license "BSD-3-Clause"
bottle do
cellar :any_skip_relocation
sha256 "b5363f025eb4ab69bd4a5d255396115d16ec5740a7de7cc810cffaed2b6e8b7a" => :catalina
sha256 "43d25e09e529be8802eca6fcc67ea3a9b50927acf71ecc3095a074b8f693afb5" => :mojave
sha256 "41183e24e41ad9d05017652d0e1ed94e3aeb74883daa165210eafc7f6e034ab7" => :high_sierra
end
depends_on "cmake" => :build
def install
system "cmake", ".", *std_cmake_args
system "make", "install"
end
test do
assert_match "SIPp v#{version}", shell_output("#{bin}/sipp -v", 99)
end
end
sipp: update 3.6.1 bottle.
class Sipp < Formula
desc "Traffic generator for the SIP protocol"
homepage "https://sipp.sourceforge.io/"
url "https://github.com/SIPp/sipp/releases/download/v3.6.1/sipp-3.6.1.tar.gz"
sha256 "6a560e83aff982f331ddbcadfb3bd530c5896cd5b757dd6eb682133cc860ecb1"
license "BSD-3-Clause"
bottle do
cellar :any_skip_relocation
sha256 "334632e3c7eb535151bb272f1dd3b5f8679682ed6930313fc91f51366a2cebe6" => :big_sur
sha256 "b5363f025eb4ab69bd4a5d255396115d16ec5740a7de7cc810cffaed2b6e8b7a" => :catalina
sha256 "43d25e09e529be8802eca6fcc67ea3a9b50927acf71ecc3095a074b8f693afb5" => :mojave
sha256 "41183e24e41ad9d05017652d0e1ed94e3aeb74883daa165210eafc7f6e034ab7" => :high_sierra
end
depends_on "cmake" => :build
def install
system "cmake", ".", *std_cmake_args
system "make", "install"
end
test do
assert_match "SIPp v#{version}", shell_output("#{bin}/sipp -v", 99)
end
end
|
class Soci < Formula
desc "Database access library for C++"
homepage "https://soci.sourceforge.io/"
url "https://downloads.sourceforge.net/project/soci/soci/soci-4.0.2/soci-4.0.2.zip"
sha256 "3c8a456579320dc828cace5aa20d4d10690b273a50997e9c195d0b270fa668ba"
license "BSL-1.0"
bottle do
sha256 arm64_big_sur: "6ab0518edb52f96d06c28fa20fe21eb29551bc933216f36588c87d8f535966fa"
sha256 big_sur: "34a4e4e20bdd5bb3c6d5c8a61badd4d7fc45f99acddb4f8c37ce29eb00dff378"
sha256 catalina: "eaf4f958498990043369a8af4395ff592c58717bc08b38f2905e3d4b4be6e94f"
sha256 mojave: "0cecd3377c20b8bfbd1129d2e10f2aaa8382586881716a7f3b3fb00fc041dc12"
end
depends_on "cmake" => :build
depends_on "sqlite"
def install
args = std_cmake_args + %w[
-DSOCI_TESTS:BOOL=OFF
-DWITH_SQLITE3:BOOL=ON
-DWITH_BOOST:BOOL=OFF
-DWITH_MYSQL:BOOL=OFF
-DWITH_ODBC:BOOL=OFF
-DWITH_ORACLE:BOOL=OFF
-DWITH_POSTGRESQL:BOOL=OFF
]
mkdir "build" do
system "cmake", "..", *args
system "make", "install"
end
end
test do
(testpath/"test.cxx").write <<~EOS
#include "soci/soci.h"
#include "soci/empty/soci-empty.h"
#include <string>
using namespace soci;
std::string connectString = "";
backend_factory const &backEnd = *soci::factory_empty();
int main(int argc, char* argv[])
{
soci::session sql(backEnd, connectString);
}
EOS
system ENV.cxx, "-o", "test", "test.cxx", "-std=c++11", "-L#{lib}", "-lsoci_core", "-lsoci_empty"
system "./test"
end
end
soci 4.0.3
class Soci < Formula
desc "Database access library for C++"
homepage "https://soci.sourceforge.io/"
url "https://downloads.sourceforge.net/project/soci/soci/soci-4.0.3/soci-4.0.3.zip"
sha256 "598abf573252caf71790af5ff15beca20af548440b610e70468edfd3c12d47b0"
license "BSL-1.0"
bottle do
sha256 arm64_big_sur: "6ab0518edb52f96d06c28fa20fe21eb29551bc933216f36588c87d8f535966fa"
sha256 big_sur: "34a4e4e20bdd5bb3c6d5c8a61badd4d7fc45f99acddb4f8c37ce29eb00dff378"
sha256 catalina: "eaf4f958498990043369a8af4395ff592c58717bc08b38f2905e3d4b4be6e94f"
sha256 mojave: "0cecd3377c20b8bfbd1129d2e10f2aaa8382586881716a7f3b3fb00fc041dc12"
end
depends_on "cmake" => :build
depends_on "sqlite"
def install
args = std_cmake_args + %w[
-DSOCI_TESTS:BOOL=OFF
-DWITH_SQLITE3:BOOL=ON
-DWITH_BOOST:BOOL=OFF
-DWITH_MYSQL:BOOL=OFF
-DWITH_ODBC:BOOL=OFF
-DWITH_ORACLE:BOOL=OFF
-DWITH_POSTGRESQL:BOOL=OFF
]
mkdir "build" do
system "cmake", "..", *args
system "make", "install"
end
end
test do
(testpath/"test.cxx").write <<~EOS
#include "soci/soci.h"
#include "soci/empty/soci-empty.h"
#include <string>
using namespace soci;
std::string connectString = "";
backend_factory const &backEnd = *soci::factory_empty();
int main(int argc, char* argv[])
{
soci::session sql(backEnd, connectString);
}
EOS
system ENV.cxx, "-o", "test", "test.cxx", "-std=c++11", "-L#{lib}", "-lsoci_core", "-lsoci_empty"
system "./test"
end
end
|
class Sqlc < Formula
desc "Generate type safe Go from SQL"
homepage "https://sqlc.dev/"
url "https://github.com/kyleconroy/sqlc/archive/v1.6.0.tar.gz"
sha256 "a95a123f29a71f5a2eea0811e4590d59cbc92eccd407abe93c110c738fc4740b"
license "MIT"
head "https://github.com/kyleconroy/sqlc.git"
bottle do
rebuild 1
sha256 cellar: :any_skip_relocation, arm64_big_sur: "0e3aefdd8b650ac9e29021a2ab29188902a1d3296eaa63f7150c22da26474de1"
sha256 cellar: :any_skip_relocation, big_sur: "67ec941540b1c125e991d493eb418cddadda8a0c4cebd6b7f4ac9e32947b1fea"
sha256 cellar: :any_skip_relocation, catalina: "5463145e573a3c4e79fb4b8a5ba22432962bf28e8f4594ca8914dfa18ba62b56"
sha256 cellar: :any_skip_relocation, mojave: "8ecd01378e5828f38cc5a2082a2a3e5e586a68d7046e3ef0008687a2fd7fc095"
end
depends_on "go" => :build
def install
system "go", "build", *std_go_args, "-ldflags", "-s -w", "./cmd/sqlc"
end
test do
(testpath/"sqlc.json").write <<~SQLC
{
"version": "1",
"packages": [
{
"name": "db",
"path": ".",
"queries": "query.sql",
"schema": "query.sql",
"engine": "postgresql"
}
]
}
SQLC
(testpath/"query.sql").write <<~EOS
CREATE TABLE foo (bar text);
-- name: SelectFoo :many
SELECT * FROM foo;
EOS
system bin/"sqlc", "generate"
assert_predicate testpath/"db.go", :exist?
assert_predicate testpath/"models.go", :exist?
assert_match "// Code generated by sqlc. DO NOT EDIT.", File.read(testpath/"query.sql.go")
end
end
sqlc 1.7.0
Closes #72206.
Signed-off-by: Dustin Rodrigues <bb8ef414f2e67efe7ad38cfa83d7e2ec855def2b@gmail.com>
Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com>
class Sqlc < Formula
desc "Generate type safe Go from SQL"
homepage "https://sqlc.dev/"
url "https://github.com/kyleconroy/sqlc/archive/v1.7.0.tar.gz"
sha256 "bdd425c6087d8115b622a1e0f9251a2d7c645ac2b1a3519621e4a39983a57387"
license "MIT"
head "https://github.com/kyleconroy/sqlc.git"
bottle do
rebuild 1
sha256 cellar: :any_skip_relocation, arm64_big_sur: "0e3aefdd8b650ac9e29021a2ab29188902a1d3296eaa63f7150c22da26474de1"
sha256 cellar: :any_skip_relocation, big_sur: "67ec941540b1c125e991d493eb418cddadda8a0c4cebd6b7f4ac9e32947b1fea"
sha256 cellar: :any_skip_relocation, catalina: "5463145e573a3c4e79fb4b8a5ba22432962bf28e8f4594ca8914dfa18ba62b56"
sha256 cellar: :any_skip_relocation, mojave: "8ecd01378e5828f38cc5a2082a2a3e5e586a68d7046e3ef0008687a2fd7fc095"
end
depends_on "go" => :build
def install
system "go", "build", *std_go_args, "-ldflags", "-s -w", "./cmd/sqlc"
end
test do
(testpath/"sqlc.json").write <<~SQLC
{
"version": "1",
"packages": [
{
"name": "db",
"path": ".",
"queries": "query.sql",
"schema": "query.sql",
"engine": "postgresql"
}
]
}
SQLC
(testpath/"query.sql").write <<~EOS
CREATE TABLE foo (bar text);
-- name: SelectFoo :many
SELECT * FROM foo;
EOS
system bin/"sqlc", "generate"
assert_predicate testpath/"db.go", :exist?
assert_predicate testpath/"models.go", :exist?
assert_match "// Code generated by sqlc. DO NOT EDIT.", File.read(testpath/"query.sql.go")
end
end
|
class Step < Formula
desc "Crypto and x509 Swiss-Army-Knife"
homepage "https://smallstep.com"
url "https://github.com/smallstep/cli/releases/download/v0.19.0/step_0.19.0.tar.gz"
sha256 "2cef308e984f3369840e270e40cfc946a70555611aa46401df562c2e6321eb53"
license "Apache-2.0"
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "7d2a4f80e1a73cebb9211fb68cfa4b94636a0f3bfeab7e1d4495d1fcae5eaf3c"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "0bc081a5f3d24eb141c6b633aac5b4b72abb841228087bd5c64b6032f3413757"
sha256 cellar: :any_skip_relocation, monterey: "b667394a539da97bde5118c7db4c5be9a28a8aa9ee3f8dc0f42798b051a7994c"
sha256 cellar: :any_skip_relocation, big_sur: "afd1dcbf198b61424dee57092bb0078a84fcc2e8041c6f514c965bccb7c738f5"
sha256 cellar: :any_skip_relocation, catalina: "6b8a76017d021319bcef6aec9e9fa1b4bfc1f7cb03a25be09eccb996f806dc67"
sha256 cellar: :any_skip_relocation, x86_64_linux: "3011f0ea56ad958711e53bf72ef17bda60eea358b0bcef13b5b8a088080e294a"
end
depends_on "go" => :build
resource "certificates" do
url "https://github.com/smallstep/certificates/releases/download/v0.19.0/step-ca_0.19.0.tar.gz"
sha256 "af2073671a5774a4fa9ae3038996976764a3040f999c38e38f0fa6c58134159f"
end
def install
ENV["VERSION"] = version.to_s
ENV["CGO_OVERRIDE"] = "CGO_ENABLED=1"
system "make", "build"
bin.install "bin/step" => "step"
bash_completion.install "autocomplete/bash_autocomplete" => "step"
zsh_completion.install "autocomplete/zsh_autocomplete" => "_step"
resource("certificates").stage do |r|
ENV["VERSION"] = r.version.to_s
ENV["CGO_OVERRIDE"] = "CGO_ENABLED=1"
system "make", "build"
bin.install "bin/step-ca" => "step-ca"
end
end
test do
# Generate a public / private key pair. Creates foo.pub and foo.priv.
system "#{bin}/step", "crypto", "keypair", "foo.pub", "foo.priv", "--no-password", "--insecure"
assert_predicate testpath/"foo.pub", :exist?
assert_predicate testpath/"foo.priv", :exist?
# Generate a root certificate and private key with subject baz written to baz.crt and baz.key.
system "#{bin}/step", "certificate", "create", "--profile", "root-ca",
"--no-password", "--insecure", "baz", "baz.crt", "baz.key"
assert_predicate testpath/"baz.crt", :exist?
assert_predicate testpath/"baz.key", :exist?
baz_crt = File.read(testpath/"baz.crt")
assert_match(/^-----BEGIN CERTIFICATE-----.*/, baz_crt)
assert_match(/.*-----END CERTIFICATE-----$/, baz_crt)
baz_key = File.read(testpath/"baz.key")
assert_match(/^-----BEGIN EC PRIVATE KEY-----.*/, baz_key)
assert_match(/.*-----END EC PRIVATE KEY-----$/, baz_key)
shell_output("#{bin}/step certificate inspect --format json baz.crt > baz_crt.json")
baz_crt_json = JSON.parse(File.read(testpath/"baz_crt.json"))
assert_equal "CN=baz", baz_crt_json["subject_dn"]
assert_equal "CN=baz", baz_crt_json["issuer_dn"]
# Generate a leaf certificate signed by the previously created root.
system "#{bin}/step", "certificate", "create", "--profile", "intermediate-ca",
"--no-password", "--insecure", "--ca", "baz.crt", "--ca-key", "baz.key",
"zap", "zap.crt", "zap.key"
assert_predicate testpath/"zap.crt", :exist?
assert_predicate testpath/"zap.key", :exist?
zap_crt = File.read(testpath/"zap.crt")
assert_match(/^-----BEGIN CERTIFICATE-----.*/, zap_crt)
assert_match(/.*-----END CERTIFICATE-----$/, zap_crt)
zap_key = File.read(testpath/"zap.key")
assert_match(/^-----BEGIN EC PRIVATE KEY-----.*/, zap_key)
assert_match(/.*-----END EC PRIVATE KEY-----$/, zap_key)
shell_output("#{bin}/step certificate inspect --format json zap.crt > zap_crt.json")
zap_crt_json = JSON.parse(File.read(testpath/"zap_crt.json"))
assert_equal "CN=zap", zap_crt_json["subject_dn"]
assert_equal "CN=baz", zap_crt_json["issuer_dn"]
# Initialize a PKI and step-ca configuration, boot the CA, and create a
# certificate using the API.
(testpath/"password.txt").write("password")
steppath = "#{testpath}/.step"
Dir.mkdir(steppath) unless File.exist?(steppath)
ENV["STEPPATH"] = steppath
system "#{bin}/step", "ca", "init", "--address", "127.0.0.1:8081",
"--dns", "127.0.0.1", "--password-file", "#{testpath}/password.txt",
"--provisioner-password-file", "#{testpath}/password.txt", "--name",
"homebrew-smallstep-test", "--provisioner", "brew"
begin
pid = fork do
exec "#{bin}/step-ca", "--password-file", "#{testpath}/password.txt",
"#{steppath}/config/ca.json"
end
sleep 2
shell_output("#{bin}/step ca health > health_response.txt")
assert_match(/^ok$/, File.read(testpath/"health_response.txt"))
shell_output("#{bin}/step ca token --password-file #{testpath}/password.txt " \
"homebrew-smallstep-leaf > token.txt")
token = File.read(testpath/"token.txt")
system "#{bin}/step", "ca", "certificate", "--token", token,
"homebrew-smallstep-leaf", "brew.crt", "brew.key"
assert_predicate testpath/"brew.crt", :exist?
assert_predicate testpath/"brew.key", :exist?
brew_crt = File.read(testpath/"brew.crt")
assert_match(/^-----BEGIN CERTIFICATE-----.*/, brew_crt)
assert_match(/.*-----END CERTIFICATE-----$/, brew_crt)
brew_key = File.read(testpath/"brew.key")
assert_match(/^-----BEGIN EC PRIVATE KEY-----.*/, brew_key)
assert_match(/.*-----END EC PRIVATE KEY-----$/, brew_key)
shell_output("#{bin}/step certificate inspect --format json brew.crt > brew_crt.json")
brew_crt_json = JSON.parse(File.read(testpath/"brew_crt.json"))
assert_equal "CN=homebrew-smallstep-leaf", brew_crt_json["subject_dn"]
assert_equal "O=homebrew-smallstep-test, CN=homebrew-smallstep-test Intermediate CA", brew_crt_json["issuer_dn"]
ensure
Process.kill(9, pid)
Process.wait(pid)
end
end
end
step 0.20.0
Closes #102351.
Signed-off-by: Rui Chen <907c7afd57be493757f13ccd1dd45dddf02db069@chenrui.dev>
Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com>
class Step < Formula
desc "Crypto and x509 Swiss-Army-Knife"
homepage "https://smallstep.com"
url "https://github.com/smallstep/cli/releases/download/v0.20.0/step_0.20.0.tar.gz"
sha256 "28c1a3f59f625992454328e466672d3974acbe67bb666a959d57331496b2042c"
license "Apache-2.0"
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "7d2a4f80e1a73cebb9211fb68cfa4b94636a0f3bfeab7e1d4495d1fcae5eaf3c"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "0bc081a5f3d24eb141c6b633aac5b4b72abb841228087bd5c64b6032f3413757"
sha256 cellar: :any_skip_relocation, monterey: "b667394a539da97bde5118c7db4c5be9a28a8aa9ee3f8dc0f42798b051a7994c"
sha256 cellar: :any_skip_relocation, big_sur: "afd1dcbf198b61424dee57092bb0078a84fcc2e8041c6f514c965bccb7c738f5"
sha256 cellar: :any_skip_relocation, catalina: "6b8a76017d021319bcef6aec9e9fa1b4bfc1f7cb03a25be09eccb996f806dc67"
sha256 cellar: :any_skip_relocation, x86_64_linux: "3011f0ea56ad958711e53bf72ef17bda60eea358b0bcef13b5b8a088080e294a"
end
depends_on "go" => :build
resource "certificates" do
url "https://github.com/smallstep/certificates/releases/download/v0.20.0/step-ca_0.20.0.tar.gz"
sha256 "89751704be475ebfee6dba322fc8d31afca02b8993a33cfe9c7dba92d06b1b00"
end
def install
ENV["VERSION"] = version.to_s
ENV["CGO_OVERRIDE"] = "CGO_ENABLED=1"
system "make", "build"
bin.install "bin/step" => "step"
bash_completion.install "autocomplete/bash_autocomplete" => "step"
zsh_completion.install "autocomplete/zsh_autocomplete" => "_step"
resource("certificates").stage do |r|
ENV["VERSION"] = r.version.to_s
ENV["CGO_OVERRIDE"] = "CGO_ENABLED=1"
system "make", "build"
bin.install "bin/step-ca" => "step-ca"
end
end
test do
# Generate a public / private key pair. Creates foo.pub and foo.priv.
system "#{bin}/step", "crypto", "keypair", "foo.pub", "foo.priv", "--no-password", "--insecure"
assert_predicate testpath/"foo.pub", :exist?
assert_predicate testpath/"foo.priv", :exist?
# Generate a root certificate and private key with subject baz written to baz.crt and baz.key.
system "#{bin}/step", "certificate", "create", "--profile", "root-ca",
"--no-password", "--insecure", "baz", "baz.crt", "baz.key"
assert_predicate testpath/"baz.crt", :exist?
assert_predicate testpath/"baz.key", :exist?
baz_crt = File.read(testpath/"baz.crt")
assert_match(/^-----BEGIN CERTIFICATE-----.*/, baz_crt)
assert_match(/.*-----END CERTIFICATE-----$/, baz_crt)
baz_key = File.read(testpath/"baz.key")
assert_match(/^-----BEGIN EC PRIVATE KEY-----.*/, baz_key)
assert_match(/.*-----END EC PRIVATE KEY-----$/, baz_key)
shell_output("#{bin}/step certificate inspect --format json baz.crt > baz_crt.json")
baz_crt_json = JSON.parse(File.read(testpath/"baz_crt.json"))
assert_equal "CN=baz", baz_crt_json["subject_dn"]
assert_equal "CN=baz", baz_crt_json["issuer_dn"]
# Generate a leaf certificate signed by the previously created root.
system "#{bin}/step", "certificate", "create", "--profile", "intermediate-ca",
"--no-password", "--insecure", "--ca", "baz.crt", "--ca-key", "baz.key",
"zap", "zap.crt", "zap.key"
assert_predicate testpath/"zap.crt", :exist?
assert_predicate testpath/"zap.key", :exist?
zap_crt = File.read(testpath/"zap.crt")
assert_match(/^-----BEGIN CERTIFICATE-----.*/, zap_crt)
assert_match(/.*-----END CERTIFICATE-----$/, zap_crt)
zap_key = File.read(testpath/"zap.key")
assert_match(/^-----BEGIN EC PRIVATE KEY-----.*/, zap_key)
assert_match(/.*-----END EC PRIVATE KEY-----$/, zap_key)
shell_output("#{bin}/step certificate inspect --format json zap.crt > zap_crt.json")
zap_crt_json = JSON.parse(File.read(testpath/"zap_crt.json"))
assert_equal "CN=zap", zap_crt_json["subject_dn"]
assert_equal "CN=baz", zap_crt_json["issuer_dn"]
# Initialize a PKI and step-ca configuration, boot the CA, and create a
# certificate using the API.
(testpath/"password.txt").write("password")
steppath = "#{testpath}/.step"
Dir.mkdir(steppath) unless File.exist?(steppath)
ENV["STEPPATH"] = steppath
system "#{bin}/step", "ca", "init", "--address", "127.0.0.1:8081",
"--dns", "127.0.0.1", "--password-file", "#{testpath}/password.txt",
"--provisioner-password-file", "#{testpath}/password.txt", "--name",
"homebrew-smallstep-test", "--provisioner", "brew"
begin
pid = fork do
exec "#{bin}/step-ca", "--password-file", "#{testpath}/password.txt",
"#{steppath}/config/ca.json"
end
sleep 2
shell_output("#{bin}/step ca health > health_response.txt")
assert_match(/^ok$/, File.read(testpath/"health_response.txt"))
shell_output("#{bin}/step ca token --password-file #{testpath}/password.txt " \
"homebrew-smallstep-leaf > token.txt")
token = File.read(testpath/"token.txt")
system "#{bin}/step", "ca", "certificate", "--token", token,
"homebrew-smallstep-leaf", "brew.crt", "brew.key"
assert_predicate testpath/"brew.crt", :exist?
assert_predicate testpath/"brew.key", :exist?
brew_crt = File.read(testpath/"brew.crt")
assert_match(/^-----BEGIN CERTIFICATE-----.*/, brew_crt)
assert_match(/.*-----END CERTIFICATE-----$/, brew_crt)
brew_key = File.read(testpath/"brew.key")
assert_match(/^-----BEGIN EC PRIVATE KEY-----.*/, brew_key)
assert_match(/.*-----END EC PRIVATE KEY-----$/, brew_key)
shell_output("#{bin}/step certificate inspect --format json brew.crt > brew_crt.json")
brew_crt_json = JSON.parse(File.read(testpath/"brew_crt.json"))
assert_equal "CN=homebrew-smallstep-leaf", brew_crt_json["subject_dn"]
assert_equal "O=homebrew-smallstep-test, CN=homebrew-smallstep-test Intermediate CA", brew_crt_json["issuer_dn"]
ensure
Process.kill(9, pid)
Process.wait(pid)
end
end
end
|
class Swig < Formula
desc "Generate scripting interfaces to C/C++ code"
homepage "http://www.swig.org/"
url "https://downloads.sourceforge.net/project/swig/swig/swig-4.0.2/swig-4.0.2.tar.gz"
sha256 "d53be9730d8d58a16bf0cbd1f8ac0c0c3e1090573168bfa151b01eb47fa906fc"
license "GPL-3.0"
bottle do
sha256 arm64_big_sur: "918c070202e0138b64b2e27f262aae3a72ab9f273f14842802d1fbe9169e66fc"
sha256 big_sur: "f198353656b61cb35b5c28ed6c9cb10689d2a0fc69529cfbcbc0fbd75a027e27"
sha256 catalina: "530e80b7e7dcd28469b52fc3b668683a97b72642ebf2b6d4e6708d14f05e7286"
sha256 mojave: "50afb5930cb37af2e400f0369f6da15b1d4922c1f72f45d13e7e3f8bd9d6d27b"
sha256 high_sierra: "8bab440005b048ce454a3dd50ba608e1f85391edd73e9e40510269e923cad238"
sha256 x86_64_linux: "39c044d1f12dfc0fd0f6cb02eb4a7a3830f91f252c09fe82fe3c03379f3635d1"
end
head do
url "https://github.com/swig/swig.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
end
depends_on "pcre"
uses_from_macos "ruby" => :test
def install
system "./autogen.sh" if build.head?
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make"
system "make", "install"
end
test do
(testpath/"test.c").write <<~EOS
int add(int x, int y)
{
return x + y;
}
EOS
(testpath/"test.i").write <<~EOS
%module test
%inline %{
extern int add(int x, int y);
%}
EOS
(testpath/"run.rb").write <<~EOS
require "./test"
puts Test.add(1, 1)
EOS
system "#{bin}/swig", "-ruby", "test.i"
if OS.mac?
system ENV.cc, "-c", "test.c"
system ENV.cc, "-c", "test_wrap.c",
"-I#{MacOS.sdk_path}/System/Library/Frameworks/Ruby.framework/Headers/"
system ENV.cc, "-bundle", "-undefined", "dynamic_lookup", "test.o", "test_wrap.o", "-o", "test.bundle"
assert_equal "2", shell_output("/usr/bin/ruby run.rb").strip
else
include_dir1 = "#{Formula["ruby"].opt_include}/ruby-2.7.0"
include_dir2 = "#{Formula["ruby"].opt_include}/ruby-2.7.0/x86_64-linux/"
args = Utils.safe_popen_read(
Formula["ruby"].opt_bin/"ruby", "-e", "'puts RbConfig::CONFIG[\"LIBRUBYARG\"]'"
).chomp
system ENV.cc, "-c", "-fPIC", "test.c"
system ENV.cc, "-c", "-fPIC", "test_wrap.c",
"-I#{include_dir1}", "-I#{include_dir2}"
system ENV.cc, "-shared", "test.o", "test_wrap.o", "-o", "test.so",
*args.delete("'").split
assert_equal "2", shell_output("ruby run.rb").strip
end
end
end
swig: update test for ruby 3
class Swig < Formula
desc "Generate scripting interfaces to C/C++ code"
homepage "http://www.swig.org/"
url "https://downloads.sourceforge.net/project/swig/swig/swig-4.0.2/swig-4.0.2.tar.gz"
sha256 "d53be9730d8d58a16bf0cbd1f8ac0c0c3e1090573168bfa151b01eb47fa906fc"
license "GPL-3.0"
bottle do
sha256 arm64_big_sur: "918c070202e0138b64b2e27f262aae3a72ab9f273f14842802d1fbe9169e66fc"
sha256 big_sur: "f198353656b61cb35b5c28ed6c9cb10689d2a0fc69529cfbcbc0fbd75a027e27"
sha256 catalina: "530e80b7e7dcd28469b52fc3b668683a97b72642ebf2b6d4e6708d14f05e7286"
sha256 mojave: "50afb5930cb37af2e400f0369f6da15b1d4922c1f72f45d13e7e3f8bd9d6d27b"
sha256 high_sierra: "8bab440005b048ce454a3dd50ba608e1f85391edd73e9e40510269e923cad238"
sha256 x86_64_linux: "39c044d1f12dfc0fd0f6cb02eb4a7a3830f91f252c09fe82fe3c03379f3635d1"
end
head do
url "https://github.com/swig/swig.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
end
depends_on "pcre"
uses_from_macos "ruby" => :test
def install
system "./autogen.sh" if build.head?
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make"
system "make", "install"
end
test do
(testpath/"test.c").write <<~EOS
int add(int x, int y)
{
return x + y;
}
EOS
(testpath/"test.i").write <<~EOS
%module test
%inline %{
extern int add(int x, int y);
%}
EOS
(testpath/"run.rb").write <<~EOS
require "./test"
puts Test.add(1, 1)
EOS
system "#{bin}/swig", "-ruby", "test.i"
if OS.mac?
system ENV.cc, "-c", "test.c"
system ENV.cc, "-c", "test_wrap.c",
"-I#{MacOS.sdk_path}/System/Library/Frameworks/Ruby.framework/Headers/"
system ENV.cc, "-bundle", "-undefined", "dynamic_lookup", "test.o", "test_wrap.o", "-o", "test.bundle"
assert_equal "2", shell_output("/usr/bin/ruby run.rb").strip
else
ruby = Formula["ruby"]
args = Utils.safe_popen_read(
ruby.opt_bin/"ruby", "-e", "'puts RbConfig::CONFIG[\"LIBRUBYARG\"]'"
).chomp
system ENV.cc, "-c", "-fPIC", "test.c"
system ENV.cc, "-c", "-fPIC", "test_wrap.c",
"-I#{ruby.opt_include}/ruby-#{ruby.version.major_minor}.0",
"-I#{ruby.opt_include}/ruby-#{ruby.version.major_minor}.0/x86_64-linux/"
system ENV.cc, "-shared", "test.o", "test_wrap.o", "-o", "test.so",
*args.delete("'").split
assert_equal "2", shell_output("ruby run.rb").strip
end
end
end
|
require 'formula'
class TaskwarriorDownloadStrategy < GitDownloadStrategy
# CMakeLists.txt requires presence of .git to generate commit.h
# (version information), otherwise make fails.
def support_depth?
false
end
end
class Task < Formula
homepage 'http://www.taskwarrior.org/'
url 'http://www.taskwarrior.org/download/task-2.3.0.tar.gz'
sha1 'b5390a1c1232bcb727f5a595ac1141184810d09d'
head 'git://tasktools.org/task.git', :branch => '2.4.0',
:using => TaskwarriorDownloadStrategy
depends_on "cmake" => :build
depends_on "gnutls" => :optional
def install
system "cmake", ".", *std_cmake_args
system "make install"
bash_completion.install 'scripts/bash/task.sh'
zsh_completion.install 'scripts/zsh/_task'
end
test do
system "#{bin}/task", "--version"
end
end
task: remove obsoleted download strategy
require 'formula'
class Task < Formula
homepage 'http://www.taskwarrior.org/'
url 'http://www.taskwarrior.org/download/task-2.3.0.tar.gz'
sha1 'b5390a1c1232bcb727f5a595ac1141184810d09d'
head 'git://tasktools.org/task.git', :branch => '2.4.0', :shallow => false
depends_on "cmake" => :build
depends_on "gnutls" => :optional
def install
system "cmake", ".", *std_cmake_args
system "make install"
bash_completion.install 'scripts/bash/task.sh'
zsh_completion.install 'scripts/zsh/_task'
end
test do
system "#{bin}/task", "--version"
end
end
|
class Tctl < Formula
desc "Temporal CLI (tctl)"
homepage "https://temporal.io/"
url "https://github.com/temporalio/temporal/archive/v1.11.1.tar.gz"
sha256 "9dc1914fed125af123cc2240a96a1df1b59fa7aa88ac4c5ce6ef154d55561ca7"
license "MIT"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "232636a789873fd1388522d20128b9a737ef10f8d0b39017ed1ee1e8192a02a0"
sha256 cellar: :any_skip_relocation, big_sur: "2cec0fdb9aa3711b252cb4c6f799001882933bacf3fcafd7b5c577df032677a7"
sha256 cellar: :any_skip_relocation, catalina: "3e5510a225655a11ed98f875ede9d259fc12f7a0b62eba971a5f56157398bf1e"
sha256 cellar: :any_skip_relocation, mojave: "65d28884892c3ce1da8203f0013c2629d46f1fe37c323e2875140e9544e5172d"
sha256 cellar: :any_skip_relocation, x86_64_linux: "42f0ceb0920d53106e21815a4b388c3f61ab604550fbb8c0d42e1d6917c4524a"
end
depends_on "go" => :build
def install
system "go", "build", *std_go_args(ldflags: "-s -w"), "./cmd/tools/cli/main.go"
system "go", "build", *std_go_args(ldflags: "-s -w"), "-o", bin/"tctl-authorization-plugin",
"./cmd/tools/cli/plugins/authorization/main.go"
end
test do
# Given tctl is pointless without a server, not much intersting to test here.
run_output = shell_output("#{bin}/tctl --version 2>&1")
assert_match "tctl version", run_output
run_output = shell_output("#{bin}/tctl --ad 192.0.2.0:1234 n l 2>&1", 1)
assert_match "rpc error", run_output
end
end
tctl 1.11.2
Closes #81756.
Signed-off-by: Sean Molenaar <2b250e3fea88cfef248b497ad5fc17f7dc435154@users.noreply.github.com>
Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com>
class Tctl < Formula
desc "Temporal CLI (tctl)"
homepage "https://temporal.io/"
url "https://github.com/temporalio/temporal/archive/v1.11.2.tar.gz"
sha256 "9ee41abe22bfeb6d54a91307506699b8d36069344c5535479640876ca946fa64"
license "MIT"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "232636a789873fd1388522d20128b9a737ef10f8d0b39017ed1ee1e8192a02a0"
sha256 cellar: :any_skip_relocation, big_sur: "2cec0fdb9aa3711b252cb4c6f799001882933bacf3fcafd7b5c577df032677a7"
sha256 cellar: :any_skip_relocation, catalina: "3e5510a225655a11ed98f875ede9d259fc12f7a0b62eba971a5f56157398bf1e"
sha256 cellar: :any_skip_relocation, mojave: "65d28884892c3ce1da8203f0013c2629d46f1fe37c323e2875140e9544e5172d"
sha256 cellar: :any_skip_relocation, x86_64_linux: "42f0ceb0920d53106e21815a4b388c3f61ab604550fbb8c0d42e1d6917c4524a"
end
depends_on "go" => :build
def install
system "go", "build", *std_go_args(ldflags: "-s -w"), "./cmd/tools/cli/main.go"
system "go", "build", *std_go_args(ldflags: "-s -w"), "-o", bin/"tctl-authorization-plugin",
"./cmd/tools/cli/plugins/authorization/main.go"
end
test do
# Given tctl is pointless without a server, not much intersting to test here.
run_output = shell_output("#{bin}/tctl --version 2>&1")
assert_match "tctl version", run_output
run_output = shell_output("#{bin}/tctl --ad 192.0.2.0:1234 n l 2>&1", 1)
assert_match "rpc error", run_output
end
end
|
class Tgui < Formula
desc "GUI library for use with sfml"
homepage "https://tgui.eu"
url "https://github.com/texus/TGUI/archive/0.7.2.tar.gz"
sha256 "850195a90fcff3d7d61d276c3ec3fdfc8cd09c60201d49163b0b3cddfac78164"
bottle do
cellar :any
sha256 "e127b6e58855cfad8b3f021b8dd064750f69d57abc8ae4103082ae0c73507f6c" => :sierra
sha256 "7f23b1539f15402f31a753e73227595c2022a46783bdd1f486263b7238e70ac0" => :el_capitan
sha256 "1a9bfb60a3766835e974a775a2e559c20a0b4231b5486f971235aea0aca37d67" => :yosemite
sha256 "0ebb747dc89fdd3a1e14e83fe7ff55a9b6025a33f09e30ebe73a5be040f43eeb" => :mavericks
end
depends_on "cmake" => :build
depends_on "sfml"
def install
system "cmake", ".", *std_cmake_args
system "make", "install"
end
test do
(testpath/"test.cpp").write <<-EOS.undent
#include <TGUI/TGUI.hpp>
int main()
{
sf::Text text;
text.setString("Hello World");
return 0;
}
EOS
system ENV.cxx, "test.cpp", "-std=c++1y", "-I#{include}",
"-L#{lib}", "-L#{Formula["sfml"].opt_lib}",
"-ltgui", "-lsfml-graphics", "-lsfml-system", "-lsfml-window",
"-o", "test"
system "./test"
end
end
tgui: update 0.7.2 bottle.
class Tgui < Formula
desc "GUI library for use with sfml"
homepage "https://tgui.eu"
url "https://github.com/texus/TGUI/archive/0.7.2.tar.gz"
sha256 "850195a90fcff3d7d61d276c3ec3fdfc8cd09c60201d49163b0b3cddfac78164"
bottle do
cellar :any
sha256 "d1c89be0da213b401eb714f1431ecc63e7c604d2be71a64a07b7a5d0cdbc8315" => :sierra
sha256 "ca13481dcec1a959a0be91e7674aa13449fc72277162466d257614967ef6dc48" => :el_capitan
sha256 "ea357bbd9e0fe2f9e5ad5a71896fa337fa32e3001acae48d9b9ac490bf770200" => :yosemite
end
depends_on "cmake" => :build
depends_on "sfml"
def install
system "cmake", ".", *std_cmake_args
system "make", "install"
end
test do
(testpath/"test.cpp").write <<-EOS.undent
#include <TGUI/TGUI.hpp>
int main()
{
sf::Text text;
text.setString("Hello World");
return 0;
}
EOS
system ENV.cxx, "test.cpp", "-std=c++1y", "-I#{include}",
"-L#{lib}", "-L#{Formula["sfml"].opt_lib}",
"-ltgui", "-lsfml-graphics", "-lsfml-system", "-lsfml-window",
"-o", "test"
system "./test"
end
end
|
class Vala < Formula
desc "Compiler for the GObject type system"
homepage "https://wiki.gnome.org/Projects/Vala"
url "https://download.gnome.org/sources/vala/0.46/vala-0.46.3.tar.xz"
sha256 "e29c2b1f108dc22c91bb501975a77c938aef079ca7875e1fbf41191e22cc57e3"
bottle do
sha256 "8aee03bb3645aff691e834261cf2f8e3b44db1ad1475bc86db78e87dc83bf5a2" => :catalina
sha256 "93b241ec1d81455e97b19e45d188ccaeaba3e3c13e1074d2431e3ad56c3b3367" => :mojave
sha256 "2ed380ac26b4e585766b923275c5ffa0db334fa70ef72d165525235d74c11aee" => :high_sierra
end
depends_on "gettext"
depends_on "glib"
depends_on "graphviz"
depends_on "pkg-config"
unless OS.mac?
depends_on "bison" => :build
depends_on "flex" => :build
end
def install
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}"
system "make" # Fails to compile as a single step
system "make", "install"
end
test do
ENV.prepend_path "PKG_CONFIG_PATH", Formula["libffi"].opt_lib/"pkgconfig"
test_string = "Hello Homebrew\n"
path = testpath/"hello.vala"
path.write <<~EOS
void main () {
print ("#{test_string}");
}
EOS
valac_args = [
# Build with debugging symbols.
"-g",
# Use Homebrew's default C compiler.
"--cc=#{ENV.cc}",
# Save generated C source code.
"--save-temps",
# Vala source code path.
path.to_s,
]
system "#{bin}/valac", *valac_args
assert_predicate testpath/"hello.c", :exist?
assert_equal test_string, shell_output("#{testpath}/hello")
end
end
vala: update 0.46.3 bottle.
Closes #16089.
Signed-off-by: Dawid Dziurla <c4a7db180859322ef5630a1dfc2805b5bc97fc25@gmail.com>
class Vala < Formula
desc "Compiler for the GObject type system"
homepage "https://wiki.gnome.org/Projects/Vala"
url "https://download.gnome.org/sources/vala/0.46/vala-0.46.3.tar.xz"
sha256 "e29c2b1f108dc22c91bb501975a77c938aef079ca7875e1fbf41191e22cc57e3"
bottle do
sha256 "8aee03bb3645aff691e834261cf2f8e3b44db1ad1475bc86db78e87dc83bf5a2" => :catalina
sha256 "93b241ec1d81455e97b19e45d188ccaeaba3e3c13e1074d2431e3ad56c3b3367" => :mojave
sha256 "2ed380ac26b4e585766b923275c5ffa0db334fa70ef72d165525235d74c11aee" => :high_sierra
sha256 "83688c6067ba0b21f1a9848eb76cfd66bd28958a0d512ecbbb4c3ab589473968" => :x86_64_linux
end
depends_on "gettext"
depends_on "glib"
depends_on "graphviz"
depends_on "pkg-config"
unless OS.mac?
depends_on "bison" => :build
depends_on "flex" => :build
end
def install
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}"
system "make" # Fails to compile as a single step
system "make", "install"
end
test do
ENV.prepend_path "PKG_CONFIG_PATH", Formula["libffi"].opt_lib/"pkgconfig"
test_string = "Hello Homebrew\n"
path = testpath/"hello.vala"
path.write <<~EOS
void main () {
print ("#{test_string}");
}
EOS
valac_args = [
# Build with debugging symbols.
"-g",
# Use Homebrew's default C compiler.
"--cc=#{ENV.cc}",
# Save generated C source code.
"--save-temps",
# Vala source code path.
path.to_s,
]
system "#{bin}/valac", *valac_args
assert_predicate testpath/"hello.c", :exist?
assert_equal test_string, shell_output("#{testpath}/hello")
end
end
|
class Vala < Formula
desc "Compiler for the GObject type system"
homepage "https://wiki.gnome.org/Projects/Vala"
url "https://download.gnome.org/sources/vala/0.48/vala-0.48.11.tar.xz"
sha256 "54fd1bb356d69824009691955c885bae357eec4eaced6c2e2d038180322e306a"
license "LGPL-2.1-or-later"
livecheck do
url :stable
end
bottle do
sha256 "cb21133addf409d424f488c8cc859f1f1002fc92daeaf3e6fa0c749315e46b60" => :catalina
sha256 "1b36a7bbe5c7253445ecbeb99cca3a9815751d151ae105ef7f1ded61ec0e32fd" => :mojave
sha256 "1cc06100d8aa160afa31dae8c6583bad2824945812214d07b4b363e910670fb9" => :high_sierra
end
depends_on "gettext"
depends_on "glib"
depends_on "graphviz"
depends_on "pkg-config"
uses_from_macos "bison" => :build
uses_from_macos "flex" => :build
def install
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}"
system "make" # Fails to compile as a single step
system "make", "install"
end
test do
ENV.prepend_path "PKG_CONFIG_PATH", Formula["libffi"].opt_lib/"pkgconfig"
test_string = "Hello Homebrew\n"
path = testpath/"hello.vala"
path.write <<~EOS
void main () {
print ("#{test_string}");
}
EOS
valac_args = [
# Build with debugging symbols.
"-g",
# Use Homebrew's default C compiler.
"--cc=#{ENV.cc}",
# Save generated C source code.
"--save-temps",
# Vala source code path.
path.to_s,
]
system "#{bin}/valac", *valac_args
assert_predicate testpath/"hello.c", :exist?
assert_equal test_string, shell_output("#{testpath}/hello")
end
end
vala: update 0.48.11 bottle.
class Vala < Formula
desc "Compiler for the GObject type system"
homepage "https://wiki.gnome.org/Projects/Vala"
url "https://download.gnome.org/sources/vala/0.48/vala-0.48.11.tar.xz"
sha256 "54fd1bb356d69824009691955c885bae357eec4eaced6c2e2d038180322e306a"
license "LGPL-2.1-or-later"
livecheck do
url :stable
end
bottle do
sha256 "d8042afa508bf07fc2997febac00f15f68dea0c3171540fc69e78d7dae14e893" => :big_sur
sha256 "cb21133addf409d424f488c8cc859f1f1002fc92daeaf3e6fa0c749315e46b60" => :catalina
sha256 "1b36a7bbe5c7253445ecbeb99cca3a9815751d151ae105ef7f1ded61ec0e32fd" => :mojave
sha256 "1cc06100d8aa160afa31dae8c6583bad2824945812214d07b4b363e910670fb9" => :high_sierra
end
depends_on "gettext"
depends_on "glib"
depends_on "graphviz"
depends_on "pkg-config"
uses_from_macos "bison" => :build
uses_from_macos "flex" => :build
def install
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}"
system "make" # Fails to compile as a single step
system "make", "install"
end
test do
ENV.prepend_path "PKG_CONFIG_PATH", Formula["libffi"].opt_lib/"pkgconfig"
test_string = "Hello Homebrew\n"
path = testpath/"hello.vala"
path.write <<~EOS
void main () {
print ("#{test_string}");
}
EOS
valac_args = [
# Build with debugging symbols.
"-g",
# Use Homebrew's default C compiler.
"--cc=#{ENV.cc}",
# Save generated C source code.
"--save-temps",
# Vala source code path.
path.to_s,
]
system "#{bin}/valac", *valac_args
assert_predicate testpath/"hello.c", :exist?
assert_equal test_string, shell_output("#{testpath}/hello")
end
end
|
class Vala < Formula
desc "Compiler for the GObject type system"
homepage "https://wiki.gnome.org/Projects/Vala"
url "https://download.gnome.org/sources/vala/0.42/vala-0.42.3.tar.xz"
sha256 "5fc73dd1e683dc7391bb96d02b2f671aa8289411a48611a05265629e0048587d"
bottle do
sha256 "e901a77a3ae7ec135562e57ddcaba96d41572487ee405009ebbb969ec07ede62" => :mojave
sha256 "c534ae2bf694890851ac84eab6256b6239f89f9c41ba190f059449d28376b92d" => :high_sierra
sha256 "66e977ba42959cac5921a1a8a75af1afaacb69340e2e35b713b6d0b38899112b" => :sierra
end
depends_on "gettext"
depends_on "glib"
depends_on "graphviz"
depends_on "pkg-config"
def install
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}"
system "make" # Fails to compile as a single step
system "make", "install"
end
test do
test_string = "Hello Homebrew\n"
path = testpath/"hello.vala"
path.write <<~EOS
void main () {
print ("#{test_string}");
}
EOS
valac_args = [
# Build with debugging symbols.
"-g",
# Use Homebrew's default C compiler.
"--cc=#{ENV.cc}",
# Save generated C source code.
"--save-temps",
# Vala source code path.
path.to_s,
]
system "#{bin}/valac", *valac_args
assert_predicate testpath/"hello.c", :exist?
assert_equal test_string, shell_output("#{testpath}/hello")
end
end
vala: update 0.42.3 bottle.
class Vala < Formula
desc "Compiler for the GObject type system"
homepage "https://wiki.gnome.org/Projects/Vala"
url "https://download.gnome.org/sources/vala/0.42/vala-0.42.3.tar.xz"
sha256 "5fc73dd1e683dc7391bb96d02b2f671aa8289411a48611a05265629e0048587d"
bottle do
sha256 "6bdece14d41b29361b2980ceec80bbfee9339559d4e693da8ab413cd8bc67a7f" => :mojave
sha256 "358e8821ab2bc0a4544546a0f3d752ff8cdb8409b523fd1c73d1edeacbf5fb68" => :high_sierra
sha256 "c781eaec3be5b22ca61e901e0ac2e6ebb2dbbf0059016cf7c10cb447996b4b24" => :sierra
end
depends_on "gettext"
depends_on "glib"
depends_on "graphviz"
depends_on "pkg-config"
def install
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}"
system "make" # Fails to compile as a single step
system "make", "install"
end
test do
test_string = "Hello Homebrew\n"
path = testpath/"hello.vala"
path.write <<~EOS
void main () {
print ("#{test_string}");
}
EOS
valac_args = [
# Build with debugging symbols.
"-g",
# Use Homebrew's default C compiler.
"--cc=#{ENV.cc}",
# Save generated C source code.
"--save-temps",
# Vala source code path.
path.to_s,
]
system "#{bin}/valac", *valac_args
assert_predicate testpath/"hello.c", :exist?
assert_equal test_string, shell_output("#{testpath}/hello")
end
end
|
class Vala < Formula
desc "Compiler for the GObject type system"
homepage "https://wiki.gnome.org/Projects/Vala"
url "https://download.gnome.org/sources/vala/0.52/vala-0.52.3.tar.xz"
sha256 "037ea1a92bf0f1ab04a71b52a01d50aca1945ad1017b6189d9614f84f5c9b2d9"
license "LGPL-2.1-or-later"
bottle do
sha256 arm64_big_sur: "3605397486262d57e3b6796b089109ab00571d9d3b600ee02a168cc4dcb9f578"
sha256 big_sur: "5ccb07c2adb88e1dd744fd73be423e594ecf22c0767c2d3f7277ee3d4917f513"
sha256 catalina: "550e6d05e894e564ea38204a5b5e89a3a7b33cfea89b12db24a88ca38e9827e1"
sha256 mojave: "ed18ebc142d30bfab9bf5c6cdd1d3a814d7e7795d0e857c6be9bd241aa11a44a"
end
depends_on "gettext"
depends_on "glib"
depends_on "graphviz"
depends_on "pkg-config"
uses_from_macos "bison" => :build
uses_from_macos "flex" => :build
on_linux do
depends_on "libx11"
end
def install
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}"
system "make" # Fails to compile as a single step
system "make", "install"
end
test do
ENV.prepend_path "PKG_CONFIG_PATH", Formula["libffi"].opt_lib/"pkgconfig"
test_string = "Hello Homebrew\n"
path = testpath/"hello.vala"
path.write <<~EOS
void main () {
print ("#{test_string}");
}
EOS
valac_args = [
# Build with debugging symbols.
"-g",
# Use Homebrew's default C compiler.
"--cc=#{ENV.cc}",
# Save generated C source code.
"--save-temps",
# Vala source code path.
path.to_s,
]
system "#{bin}/valac", *valac_args
assert_predicate testpath/"hello.c", :exist?
assert_equal test_string, shell_output("#{testpath}/hello")
end
end
vala: update 0.52.3 bottle.
class Vala < Formula
desc "Compiler for the GObject type system"
homepage "https://wiki.gnome.org/Projects/Vala"
url "https://download.gnome.org/sources/vala/0.52/vala-0.52.3.tar.xz"
sha256 "037ea1a92bf0f1ab04a71b52a01d50aca1945ad1017b6189d9614f84f5c9b2d9"
license "LGPL-2.1-or-later"
bottle do
sha256 arm64_big_sur: "3605397486262d57e3b6796b089109ab00571d9d3b600ee02a168cc4dcb9f578"
sha256 big_sur: "5ccb07c2adb88e1dd744fd73be423e594ecf22c0767c2d3f7277ee3d4917f513"
sha256 catalina: "550e6d05e894e564ea38204a5b5e89a3a7b33cfea89b12db24a88ca38e9827e1"
sha256 mojave: "ed18ebc142d30bfab9bf5c6cdd1d3a814d7e7795d0e857c6be9bd241aa11a44a"
sha256 x86_64_linux: "c70ff73c0a78e8169f8cdcf89cf0a9f9c7726d294ab4d64c7343aab62738712e"
end
depends_on "gettext"
depends_on "glib"
depends_on "graphviz"
depends_on "pkg-config"
uses_from_macos "bison" => :build
uses_from_macos "flex" => :build
on_linux do
depends_on "libx11"
end
def install
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}"
system "make" # Fails to compile as a single step
system "make", "install"
end
test do
ENV.prepend_path "PKG_CONFIG_PATH", Formula["libffi"].opt_lib/"pkgconfig"
test_string = "Hello Homebrew\n"
path = testpath/"hello.vala"
path.write <<~EOS
void main () {
print ("#{test_string}");
}
EOS
valac_args = [
# Build with debugging symbols.
"-g",
# Use Homebrew's default C compiler.
"--cc=#{ENV.cc}",
# Save generated C source code.
"--save-temps",
# Vala source code path.
path.to_s,
]
system "#{bin}/valac", *valac_args
assert_predicate testpath/"hello.c", :exist?
assert_equal test_string, shell_output("#{testpath}/hello")
end
end
|
class Vips < Formula
desc "Image processing library"
homepage "https://github.com/jcupitt/libvips"
url "https://github.com/jcupitt/libvips/releases/download/v8.6.0/vips-8.6.0.tar.gz"
sha256 "37d21ba87aa33519574093b9688fe755d00f6bb6905ed9ffcd7a1e2fbe32227c"
bottle do
sha256 "366cb92f9fe2d25f38233d5ad6a72bebd892d54dfc1664119669da965645f695" => :high_sierra
sha256 "4a58ca3c72d9109000a07c0cab7e99f233100a3b3919d47761c6cc3aeb843db7" => :sierra
sha256 "6a5f0bf7e6bb646286756f3dbefc510a762de831e0abb443d75701f074a054b2" => :el_capitan
end
depends_on "pkg-config" => :build
depends_on "fontconfig"
depends_on "gettext"
depends_on "giflib"
depends_on "glib"
depends_on "gobject-introspection"
depends_on "jpeg"
depends_on "libexif"
depends_on "libgsf"
depends_on "libpng"
depends_on "librsvg"
depends_on "libtiff"
depends_on "little-cms2"
depends_on "orc"
depends_on "pango"
depends_on "pygobject3"
depends_on "fftw" => :recommended
depends_on "poppler" => :recommended
depends_on "graphicsmagick" => :optional
depends_on "imagemagick" => :optional
depends_on "jpeg-turbo" => :optional
depends_on "mozjpeg" => :optional
depends_on "openexr" => :optional
depends_on "openslide" => :optional
depends_on "webp" => :optional
def install
args = %W[
--disable-dependency-tracking
--prefix=#{prefix}
]
if build.with? "graphicsmagick"
args << "--with-magick" << "--with-magickpackage=GraphicsMagick"
end
args << "--without-libwebp" if build.without? "webp"
system "./configure", *args
system "make", "install"
end
test do
system "#{bin}/vips", "-l"
cmd = "#{bin}/vipsheader -f width #{test_fixtures("test.png")}"
assert_equal "8", shell_output(cmd).chomp
end
end
vips: update 8.6.0 bottle.
class Vips < Formula
desc "Image processing library"
homepage "https://github.com/jcupitt/libvips"
url "https://github.com/jcupitt/libvips/releases/download/v8.6.0/vips-8.6.0.tar.gz"
sha256 "37d21ba87aa33519574093b9688fe755d00f6bb6905ed9ffcd7a1e2fbe32227c"
bottle do
sha256 "99949b900ffe3b260187ff17d22fa46e73204129f8347c3287066151f1af07a6" => :high_sierra
sha256 "5f4f10fbe19a81c85825c5fd124b6e002875ee07cf154f4a1ad5e1224f4d59c8" => :sierra
sha256 "2a41fc07077362bd2eeb0f9af8b870f5e4e5369bd367686e0a69e1fb3b20c051" => :el_capitan
end
depends_on "pkg-config" => :build
depends_on "fontconfig"
depends_on "gettext"
depends_on "giflib"
depends_on "glib"
depends_on "gobject-introspection"
depends_on "jpeg"
depends_on "libexif"
depends_on "libgsf"
depends_on "libpng"
depends_on "librsvg"
depends_on "libtiff"
depends_on "little-cms2"
depends_on "orc"
depends_on "pango"
depends_on "pygobject3"
depends_on "fftw" => :recommended
depends_on "poppler" => :recommended
depends_on "graphicsmagick" => :optional
depends_on "imagemagick" => :optional
depends_on "jpeg-turbo" => :optional
depends_on "mozjpeg" => :optional
depends_on "openexr" => :optional
depends_on "openslide" => :optional
depends_on "webp" => :optional
def install
args = %W[
--disable-dependency-tracking
--prefix=#{prefix}
]
if build.with? "graphicsmagick"
args << "--with-magick" << "--with-magickpackage=GraphicsMagick"
end
args << "--without-libwebp" if build.without? "webp"
system "./configure", *args
system "make", "install"
end
test do
system "#{bin}/vips", "-l"
cmd = "#{bin}/vipsheader -f width #{test_fixtures("test.png")}"
assert_equal "8", shell_output(cmd).chomp
end
end
|
class Visp < Formula
desc "Visual Servoing Platform library"
homepage "https://visp.inria.fr/"
url "https://gforge.inria.fr/frs/download.php/latestfile/475/visp-3.2.0.tar.gz"
sha256 "072237ed5c6fcbc6a87300fa036014ec574fd081724907e41ae2d6fb5a222fbc"
revision 2
bottle do
sha256 "a757a056b336ec61af0a4fff50e4450e34b7ae9a0a58898cf57b8de2ac672a85" => :mojave
sha256 "0c618abe1e923b8063e4a09ebc02120a659cf6b376380061d87f2c751ae3e5ab" => :high_sierra
sha256 "22dcf5e1add32b7838adccc9da76d2132c7fd9d0ce600b3c649824ccabbf72e7" => :sierra
end
depends_on "cmake" => :build
depends_on "pkg-config" => :build
depends_on "eigen"
depends_on "gsl"
depends_on "jpeg"
depends_on "libdc1394"
depends_on "libpng"
depends_on "opencv"
depends_on "pcl"
depends_on "zbar"
def install
ENV.cxx11
sdk = MacOS::CLT.installed? ? "" : MacOS.sdk_path
system "cmake", ".", "-DBUILD_DEMOS=OFF",
"-DBUILD_EXAMPLES=OFF",
"-DBUILD_TESTS=OFF",
"-DBUILD_TUTORIALS=OFF",
"-DUSE_DC1394=ON",
"-DDC1394_INCLUDE_DIR=#{Formula["libdc1394"].opt_include}",
"-DDC1394_LIBRARY=#{Formula["libdc1394"].opt_lib}/libdc1394.dylib",
"-DUSE_EIGEN3=ON",
"-DEigen3_DIR=#{Formula["eigen"].opt_share}/eigen3/cmake",
"-DUSE_GSL=ON",
"-DGSL_INCLUDE_DIR=#{Formula["gsl"].opt_include}",
"-DGSL_cblas_LIBRARY=#{Formula["gsl"].opt_lib}/libgslcblas.dylib",
"-DGSL_gsl_LIBRARY=#{Formula["gsl"].opt_lib}/libgsl.dylib",
"-DUSE_JPEG=ON",
"-DJPEG_INCLUDE_DIR=#{Formula["jpeg"].opt_include}",
"-DJPEG_LIBRARY=#{Formula["jpeg"].opt_lib}/libjpeg.dylib",
"-DUSE_LAPACK=ON",
"-DUSE_LIBUSB_1=OFF",
"-DUSE_OPENCV=ON",
"-DOpenCV_DIR=#{Formula["opencv"].opt_share}/OpenCV",
"-DUSE_PCL=ON",
"-DUSE_PNG=ON",
"-DPNG_PNG_INCLUDE_DIR=#{Formula["libpng"].opt_include}",
"-DPNG_LIBRARY_RELEASE=#{Formula["libpng"].opt_lib}/libpng.dylib",
"-DUSE_PTHREAD=ON",
"-DPTHREAD_INCLUDE_DIR=#{sdk}/usr/include",
"-DPTHREAD_LIBRARY=/usr/lib/libpthread.dylib",
"-DUSE_PYLON=OFF",
"-DUSE_REALSENSE=OFF",
"-DUSE_REALSENSE2=OFF",
"-DUSE_X11=OFF",
"-DUSE_XML2=ON",
"-DXML2_INCLUDE_DIR=#{sdk}/usr/include/libxml2",
"-DXML2_LIBRARY=/usr/lib/libxml2.dylib",
"-DUSE_ZBAR=ON",
"-DZBAR_INCLUDE_DIRS=#{Formula["zbar"].opt_include}",
"-DZBAR_LIBRARIES=#{Formula["zbar"].opt_lib}/libzbar.dylib",
"-DUSE_ZLIB=ON",
"-DZLIB_INCLUDE_DIR=#{sdk}/usr/include",
"-DZLIB_LIBRARY_RELEASE=/usr/lib/libz.dylib",
*std_cmake_args
system "make", "install"
end
test do
(testpath/"test.cpp").write <<~EOS
#include <visp3/core/vpConfig.h>
#include <iostream>
int main()
{
std::cout << VISP_VERSION_MAJOR << "." << VISP_VERSION_MINOR <<
"." << VISP_VERSION_PATCH << std::endl;
return 0;
}
EOS
system ENV.cxx, "test.cpp", "-I#{include}", "-L#{lib}", "-o", "test"
assert_equal version.to_s, shell_output("./test").chomp
end
end
visp: update 3.2.0_2 bottle.
class Visp < Formula
desc "Visual Servoing Platform library"
homepage "https://visp.inria.fr/"
url "https://gforge.inria.fr/frs/download.php/latestfile/475/visp-3.2.0.tar.gz"
sha256 "072237ed5c6fcbc6a87300fa036014ec574fd081724907e41ae2d6fb5a222fbc"
revision 2
bottle do
sha256 "bd803bfb559a6e8ba2badca841a200e52aa69db4a1d1e63fe304488d37cb2b8d" => :mojave
sha256 "4329473cbdc69529c11c51f33cd26ad1ed9654794e949439e95db9067457ccbf" => :high_sierra
sha256 "0d552de7f50cd4cad800f457149a737b2004e23193b4ef725c0c82b8ae9244ef" => :sierra
end
depends_on "cmake" => :build
depends_on "pkg-config" => :build
depends_on "eigen"
depends_on "gsl"
depends_on "jpeg"
depends_on "libdc1394"
depends_on "libpng"
depends_on "opencv"
depends_on "pcl"
depends_on "zbar"
def install
ENV.cxx11
sdk = MacOS::CLT.installed? ? "" : MacOS.sdk_path
system "cmake", ".", "-DBUILD_DEMOS=OFF",
"-DBUILD_EXAMPLES=OFF",
"-DBUILD_TESTS=OFF",
"-DBUILD_TUTORIALS=OFF",
"-DUSE_DC1394=ON",
"-DDC1394_INCLUDE_DIR=#{Formula["libdc1394"].opt_include}",
"-DDC1394_LIBRARY=#{Formula["libdc1394"].opt_lib}/libdc1394.dylib",
"-DUSE_EIGEN3=ON",
"-DEigen3_DIR=#{Formula["eigen"].opt_share}/eigen3/cmake",
"-DUSE_GSL=ON",
"-DGSL_INCLUDE_DIR=#{Formula["gsl"].opt_include}",
"-DGSL_cblas_LIBRARY=#{Formula["gsl"].opt_lib}/libgslcblas.dylib",
"-DGSL_gsl_LIBRARY=#{Formula["gsl"].opt_lib}/libgsl.dylib",
"-DUSE_JPEG=ON",
"-DJPEG_INCLUDE_DIR=#{Formula["jpeg"].opt_include}",
"-DJPEG_LIBRARY=#{Formula["jpeg"].opt_lib}/libjpeg.dylib",
"-DUSE_LAPACK=ON",
"-DUSE_LIBUSB_1=OFF",
"-DUSE_OPENCV=ON",
"-DOpenCV_DIR=#{Formula["opencv"].opt_share}/OpenCV",
"-DUSE_PCL=ON",
"-DUSE_PNG=ON",
"-DPNG_PNG_INCLUDE_DIR=#{Formula["libpng"].opt_include}",
"-DPNG_LIBRARY_RELEASE=#{Formula["libpng"].opt_lib}/libpng.dylib",
"-DUSE_PTHREAD=ON",
"-DPTHREAD_INCLUDE_DIR=#{sdk}/usr/include",
"-DPTHREAD_LIBRARY=/usr/lib/libpthread.dylib",
"-DUSE_PYLON=OFF",
"-DUSE_REALSENSE=OFF",
"-DUSE_REALSENSE2=OFF",
"-DUSE_X11=OFF",
"-DUSE_XML2=ON",
"-DXML2_INCLUDE_DIR=#{sdk}/usr/include/libxml2",
"-DXML2_LIBRARY=/usr/lib/libxml2.dylib",
"-DUSE_ZBAR=ON",
"-DZBAR_INCLUDE_DIRS=#{Formula["zbar"].opt_include}",
"-DZBAR_LIBRARIES=#{Formula["zbar"].opt_lib}/libzbar.dylib",
"-DUSE_ZLIB=ON",
"-DZLIB_INCLUDE_DIR=#{sdk}/usr/include",
"-DZLIB_LIBRARY_RELEASE=/usr/lib/libz.dylib",
*std_cmake_args
system "make", "install"
end
test do
(testpath/"test.cpp").write <<~EOS
#include <visp3/core/vpConfig.h>
#include <iostream>
int main()
{
std::cout << VISP_VERSION_MAJOR << "." << VISP_VERSION_MINOR <<
"." << VISP_VERSION_PATCH << std::endl;
return 0;
}
EOS
system ENV.cxx, "test.cpp", "-I#{include}", "-L#{lib}", "-o", "test"
assert_equal version.to_s, shell_output("./test").chomp
end
end
|
class Volt < Formula
desc "Meta-level vim package manager"
homepage "https://github.com/vim-volt/volt"
url "https://github.com/vim-volt/volt.git",
:tag => "v0.3.5a",
:revision => "dd1a16c77faf9887408744b146efc2d0bfdf500c"
head "https://github.com/vim-volt/volt.git"
depends_on "go" => :build
def install
mkdir_p buildpath/"src/github.com/vim-volt"
ln_s buildpath, buildpath/"src/github.com/vim-volt/volt"
ENV["GOPATH"] = buildpath
system "make", "BIN_DIR=#{bin}"
bash_completion.install "_contrib/completion/bash" => "volt"
end
test do
mkdir_p testpath/"volt/repos/localhost/foo/bar/plugin"
File.write(testpath/"volt/repos/localhost/foo/bar/plugin/baz.vim", "qux")
system bin/"volt", "get", "localhost/foo/bar"
assert_equal File.read(testpath/".vim/pack/volt/opt/localhost_foo_bar/plugin/baz.vim"), "qux"
end
end
volt: add 0.3.5 bottle.
class Volt < Formula
desc "Meta-level vim package manager"
homepage "https://github.com/vim-volt/volt"
url "https://github.com/vim-volt/volt.git",
:tag => "v0.3.5a",
:revision => "dd1a16c77faf9887408744b146efc2d0bfdf500c"
head "https://github.com/vim-volt/volt.git"
bottle do
cellar :any_skip_relocation
sha256 "bef81710d05a2defe04b4890f5ac9a8dd42c143994756b72e6ab7ceaa30e08e6" => :mojave
sha256 "cfe9f4dd24c96516de480a5d498b93f7b94740284b2ffb59219c5d632b915ad5" => :high_sierra
sha256 "b503cbf438b2e4ec9f72339672970fd92ead4a74965b0f5ffb6ca8120cdf71d7" => :sierra
end
depends_on "go" => :build
def install
mkdir_p buildpath/"src/github.com/vim-volt"
ln_s buildpath, buildpath/"src/github.com/vim-volt/volt"
ENV["GOPATH"] = buildpath
system "make", "BIN_DIR=#{bin}"
bash_completion.install "_contrib/completion/bash" => "volt"
end
test do
mkdir_p testpath/"volt/repos/localhost/foo/bar/plugin"
File.write(testpath/"volt/repos/localhost/foo/bar/plugin/baz.vim", "qux")
system bin/"volt", "get", "localhost/foo/bar"
assert_equal File.read(testpath/".vim/pack/volt/opt/localhost_foo_bar/plugin/baz.vim"), "qux"
end
end
|
class Waon < Formula
desc "Wave-to-notes transcriber"
homepage "https://kichiki.github.io/WaoN/"
url "https://github.com/kichiki/WaoN/archive/v0.11.tar.gz"
sha256 "75d5c1721632afee55a54bcbba1a444e53b03f4224b03da29317e98aa223c30b"
license "GPL-2.0"
bottle do
sha256 cellar: :any, arm64_big_sur: "5c2460bd2671fbb035d30f61a80c470caca47d2cc2b84b103b1d9d25540dd233"
sha256 cellar: :any, big_sur: "1fb554284ace79c0c8eae1d7dc9b9e9ce9d7d90e35e97ad318f5cf7dcdaa059c"
sha256 cellar: :any, catalina: "47eaaeeea5b323dced48d444ffc21c2f16b86443271952bceac22abd788ebd8f"
sha256 cellar: :any, mojave: "22b3f3cc1a0796db2bf6b808b7157a2e1cacf30b6437998a9f5bdc9482bbfbf8"
sha256 cellar: :any, high_sierra: "5c3c49f0740bfcf9d34fd9468af3d9caa8f19c53ee1d25f8d69442d63859c9ab"
sha256 cellar: :any, sierra: "d7fd9859544bf3ccb739942f0db00928469356f4d82ab7848cdba2ae5c5e99e9"
sha256 cellar: :any, el_capitan: "6f09559eaf287022f280991b44b5f4e86435fafda167c97a78239602183a3758"
sha256 cellar: :any, yosemite: "a16c4df918f59a71396d7c4a5806bafe4bda4a89d3aeb2a52d8dfd41ce6c0432"
sha256 cellar: :any, mavericks: "7469ec9aa8f549c1294ddb362f8ec2473466c5b027007f3c14fb49984353d813"
end
depends_on "pkg-config" => :build
depends_on "fftw"
depends_on "libsndfile"
def install
system "make", "-f", "Makefile.waon", "waon"
bin.install "waon"
man1.install "waon.1"
end
test do
system "say", "check one two", "-o", testpath/"test.aiff"
system "#{bin}/waon", "-i", testpath/"test.aiff", "-o", testpath/"output.midi"
assert_predicate testpath/"output.midi", :exist?
end
end
waon: remove mavericks bottle.
We haven't supported Mavericks for a while.
class Waon < Formula
desc "Wave-to-notes transcriber"
homepage "https://kichiki.github.io/WaoN/"
url "https://github.com/kichiki/WaoN/archive/v0.11.tar.gz"
sha256 "75d5c1721632afee55a54bcbba1a444e53b03f4224b03da29317e98aa223c30b"
license "GPL-2.0"
bottle do
sha256 cellar: :any, arm64_big_sur: "5c2460bd2671fbb035d30f61a80c470caca47d2cc2b84b103b1d9d25540dd233"
sha256 cellar: :any, big_sur: "1fb554284ace79c0c8eae1d7dc9b9e9ce9d7d90e35e97ad318f5cf7dcdaa059c"
sha256 cellar: :any, catalina: "47eaaeeea5b323dced48d444ffc21c2f16b86443271952bceac22abd788ebd8f"
sha256 cellar: :any, mojave: "22b3f3cc1a0796db2bf6b808b7157a2e1cacf30b6437998a9f5bdc9482bbfbf8"
sha256 cellar: :any, high_sierra: "5c3c49f0740bfcf9d34fd9468af3d9caa8f19c53ee1d25f8d69442d63859c9ab"
sha256 cellar: :any, sierra: "d7fd9859544bf3ccb739942f0db00928469356f4d82ab7848cdba2ae5c5e99e9"
sha256 cellar: :any, el_capitan: "6f09559eaf287022f280991b44b5f4e86435fafda167c97a78239602183a3758"
sha256 cellar: :any, yosemite: "a16c4df918f59a71396d7c4a5806bafe4bda4a89d3aeb2a52d8dfd41ce6c0432"
end
depends_on "pkg-config" => :build
depends_on "fftw"
depends_on "libsndfile"
def install
system "make", "-f", "Makefile.waon", "waon"
bin.install "waon"
man1.install "waon.1"
end
test do
system "say", "check one two", "-o", testpath/"test.aiff"
system "#{bin}/waon", "-i", testpath/"test.aiff", "-o", testpath/"output.midi"
assert_predicate testpath/"output.midi", :exist?
end
end
|
class Werf < Formula
desc "Consistent delivery tool for Kubernetes"
homepage "https://werf.io/"
url "https://github.com/werf/werf/archive/refs/tags/v1.2.105.tar.gz"
sha256 "3e7bc64d5e0e4589d72e3506927d0ba2b640e67fef04593d08ca4ebb1733c2ea"
license "Apache-2.0"
head "https://github.com/werf/werf.git", branch: "main"
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "657b4c5e673f4825b6c9d5ba3808efd57f71735b6b6e1f455bca06c1095143e4"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "95f05409673b0dfb9c2e20a78a00145801123bda4209b005e0bd7bf9996d5663"
sha256 cellar: :any_skip_relocation, monterey: "62228a952a330f03f942da50eebae4b7a2b00ba9c807c47117129104c9c979b2"
sha256 cellar: :any_skip_relocation, big_sur: "39104b1471b2b393872af80c4ebb42837d5f3fd4aecfbce9b046885168905ade"
sha256 cellar: :any_skip_relocation, catalina: "ced8b6e19b73c262e619e4ad97e186cc38409ea231767ea95d87d01a8cb6cd3c"
end
depends_on "go" => :build
# due to missing libbtrfs headers, only supports macos at the moment
depends_on :macos
def install
ldflags = "-s -w -X github.com/werf/werf/pkg/werf.Version=#{version}"
tags = "dfrunmount dfssh containers_image_openpgp"
system "go", "build", *std_go_args(ldflags: ldflags), "-tags", tags, "./cmd/werf"
bash_output = Utils.safe_popen_read(bin/"werf", "completion", "bash")
(bash_completion/"werf").write bash_output
zsh_output = Utils.safe_popen_read(bin/"werf", "completion", "zsh")
(zsh_completion/"_werf").write zsh_output
fish_output = Utils.safe_popen_read(bin/"werf", "completion", "fish")
(fish_completion/"werf.fish").write fish_output
end
test do
werf_config = testpath/"werf.yaml"
werf_config.write <<~EOS
configVersion: 1
project: quickstart-application
---
image: vote
dockerfile: Dockerfile
context: vote
---
image: result
dockerfile: Dockerfile
context: result
---
image: worker
dockerfile: Dockerfile
context: worker
EOS
output = <<~EOS
- image: vote
- image: result
- image: worker
EOS
system "git", "init"
system "git", "add", werf_config
system "git", "commit", "-m", "Initial commit"
assert_equal output, shell_output("#{bin}/werf config graph")
assert_match version.to_s, shell_output("#{bin}/werf version")
end
end
werf 1.2.106
Closes #102288.
Signed-off-by: Rui Chen <907c7afd57be493757f13ccd1dd45dddf02db069@chenrui.dev>
Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com>
class Werf < Formula
desc "Consistent delivery tool for Kubernetes"
homepage "https://werf.io/"
url "https://github.com/werf/werf/archive/refs/tags/v1.2.106.tar.gz"
sha256 "3ba20ce1138f3a96e90c4e4b030cae04098c46bd7a17d110390f8809f7df6d70"
license "Apache-2.0"
head "https://github.com/werf/werf.git", branch: "main"
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "657b4c5e673f4825b6c9d5ba3808efd57f71735b6b6e1f455bca06c1095143e4"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "95f05409673b0dfb9c2e20a78a00145801123bda4209b005e0bd7bf9996d5663"
sha256 cellar: :any_skip_relocation, monterey: "62228a952a330f03f942da50eebae4b7a2b00ba9c807c47117129104c9c979b2"
sha256 cellar: :any_skip_relocation, big_sur: "39104b1471b2b393872af80c4ebb42837d5f3fd4aecfbce9b046885168905ade"
sha256 cellar: :any_skip_relocation, catalina: "ced8b6e19b73c262e619e4ad97e186cc38409ea231767ea95d87d01a8cb6cd3c"
end
depends_on "go" => :build
# due to missing libbtrfs headers, only supports macos at the moment
depends_on :macos
def install
ldflags = "-s -w -X github.com/werf/werf/pkg/werf.Version=#{version}"
tags = "dfrunmount dfssh containers_image_openpgp"
system "go", "build", *std_go_args(ldflags: ldflags), "-tags", tags, "./cmd/werf"
bash_output = Utils.safe_popen_read(bin/"werf", "completion", "bash")
(bash_completion/"werf").write bash_output
zsh_output = Utils.safe_popen_read(bin/"werf", "completion", "zsh")
(zsh_completion/"_werf").write zsh_output
fish_output = Utils.safe_popen_read(bin/"werf", "completion", "fish")
(fish_completion/"werf.fish").write fish_output
end
test do
werf_config = testpath/"werf.yaml"
werf_config.write <<~EOS
configVersion: 1
project: quickstart-application
---
image: vote
dockerfile: Dockerfile
context: vote
---
image: result
dockerfile: Dockerfile
context: result
---
image: worker
dockerfile: Dockerfile
context: worker
EOS
output = <<~EOS
- image: vote
- image: result
- image: worker
EOS
system "git", "init"
system "git", "add", werf_config
system "git", "commit", "-m", "Initial commit"
assert_equal output, shell_output("#{bin}/werf config graph")
assert_match version.to_s, shell_output("#{bin}/werf version")
end
end
|
class When < Formula
desc "Tiny personal calendar"
homepage "https://www.lightandmatter.com/when/when.html"
url "https://github.com/bcrowell/when/archive/1.1.40.tar.gz"
sha256 "1363d48c32c4bb528514abf012ae0a61e7c686504a047ce870e72e791447c3d1"
head "https://github.com/bcrowell/when.git"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "cdde93a2d4051259f3b693d3ef55b11f52765bb789b592e0622ae7b42e1e7100"
sha256 cellar: :any_skip_relocation, big_sur: "c92678460a5deb08ee3c85dc76650914f691a3cd2e43ccb7424ba62882489947"
sha256 cellar: :any_skip_relocation, catalina: "88a5d4653d7062e0ac6d9913d35390126c1739fe04f0f458624f0199046d0fcd"
sha256 cellar: :any_skip_relocation, mojave: "18c0460162e7dcb98d499fb8622a471162897a91f4f844fe46f42a52182cc69e"
sha256 cellar: :any_skip_relocation, high_sierra: "a0623fd31e458f82217956bd98e72964634f5d632025336386e824a27fe654ae"
sha256 cellar: :any_skip_relocation, x86_64_linux: "288a68c66a0e7e0403bf63b48cd13243bd0df9d2ee9d42bbc2933107df0479e5"
end
def install
system "make", "prefix=#{prefix}", "install"
end
test do
(testpath/".when/preferences").write <<~EOS
calendar = #{testpath}/calendar
EOS
(testpath/"calendar").write "2015 April 1, stay off the internet"
system bin/"when", "i"
end
end
when: add `head` branch
Signed-off-by: Rui Chen <907c7afd57be493757f13ccd1dd45dddf02db069@chenrui.dev>
class When < Formula
desc "Tiny personal calendar"
homepage "https://www.lightandmatter.com/when/when.html"
url "https://github.com/bcrowell/when/archive/1.1.40.tar.gz"
sha256 "1363d48c32c4bb528514abf012ae0a61e7c686504a047ce870e72e791447c3d1"
head "https://github.com/bcrowell/when.git", branch: "master"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "cdde93a2d4051259f3b693d3ef55b11f52765bb789b592e0622ae7b42e1e7100"
sha256 cellar: :any_skip_relocation, big_sur: "c92678460a5deb08ee3c85dc76650914f691a3cd2e43ccb7424ba62882489947"
sha256 cellar: :any_skip_relocation, catalina: "88a5d4653d7062e0ac6d9913d35390126c1739fe04f0f458624f0199046d0fcd"
sha256 cellar: :any_skip_relocation, mojave: "18c0460162e7dcb98d499fb8622a471162897a91f4f844fe46f42a52182cc69e"
sha256 cellar: :any_skip_relocation, high_sierra: "a0623fd31e458f82217956bd98e72964634f5d632025336386e824a27fe654ae"
sha256 cellar: :any_skip_relocation, x86_64_linux: "288a68c66a0e7e0403bf63b48cd13243bd0df9d2ee9d42bbc2933107df0479e5"
end
def install
system "make", "prefix=#{prefix}", "install"
end
test do
(testpath/".when/preferences").write <<~EOS
calendar = #{testpath}/calendar
EOS
(testpath/"calendar").write "2015 April 1, stay off the internet"
system bin/"when", "i"
end
end
|
class Woof < Formula
include Language::Python::Shebang
desc "Ad-hoc single-file webserver"
homepage "http://www.home.unix-ag.org/simon/woof.html"
url "https://github.com/simon-budig/woof/archive/woof-20220202.tar.gz"
sha256 "cf29214aca196a1778e2f5df1f5cc653da9bee8fc2b19f01439c750c41ae83c1"
license "GPL-2.0-or-later"
bottle do
sha256 cellar: :any_skip_relocation, all: "0b65de07c5c918fb82b3c7a047c4c22c2771ef3897cd2f3c1abb64a76a7a867d"
end
depends_on "python@3.10"
def install
rewrite_shebang detected_python_shebang, "woof"
bin.install "woof"
end
test do
port = free_port
pid = fork do
exec "#{bin}/woof", "-s", "-p", port.to_s
end
sleep 2
begin
read = (bin/"woof").read
assert_equal read, shell_output("curl localhost:#{port}/woof")
ensure
Process.kill("SIGINT", pid)
Process.wait(pid)
end
end
end
woof: migrate to `python@3.11`
Closes #114954.
Signed-off-by: Dustin Rodrigues <bb8ef414f2e67efe7ad38cfa83d7e2ec855def2b@gmail.com>
Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com>
class Woof < Formula
include Language::Python::Shebang
desc "Ad-hoc single-file webserver"
homepage "http://www.home.unix-ag.org/simon/woof.html"
url "https://github.com/simon-budig/woof/archive/woof-20220202.tar.gz"
sha256 "cf29214aca196a1778e2f5df1f5cc653da9bee8fc2b19f01439c750c41ae83c1"
license "GPL-2.0-or-later"
bottle do
sha256 cellar: :any_skip_relocation, all: "0b65de07c5c918fb82b3c7a047c4c22c2771ef3897cd2f3c1abb64a76a7a867d"
end
depends_on "python@3.11"
def install
rewrite_shebang detected_python_shebang, "woof"
bin.install "woof"
end
test do
port = free_port
pid = fork do
exec "#{bin}/woof", "-s", "-p", port.to_s
end
sleep 2
begin
read = (bin/"woof").read
assert_equal read, shell_output("curl localhost:#{port}/woof")
ensure
Process.kill("SIGINT", pid)
Process.wait(pid)
end
end
end
|
class Xplr < Formula
desc "Hackable, minimal, fast TUI file explorer"
homepage "https://github.com/sayanarijit/xplr"
url "https://github.com/sayanarijit/xplr/archive/v0.5.13.tar.gz"
sha256 "cc705c0f3eedf88ec8c22adb4d8629e66a8bf5ad55ccb4e24a1d6d4a7de6d29f"
license "MIT"
head "https://github.com/sayanarijit/xplr.git", branch: "main"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "b5bbf884dbf3af12770877f643ff1401bcfe597919262bcb5353213e5371e00a"
sha256 cellar: :any_skip_relocation, big_sur: "3a852acc80a2cf98acda6b119fe47fe849a7632166914f8d97c44cb1a067ffc9"
sha256 cellar: :any_skip_relocation, catalina: "fc0143c374106e3b83b72e769b8cd62aa2d8eae3247dde92901cc0b22a293b62"
sha256 cellar: :any_skip_relocation, mojave: "7db04e3ff062b1d9458ee82cf977b76f2ce637ea66f2b65a36e2f7a611226f72"
end
depends_on "rust" => :build
def install
system "cargo", "install", *std_cargo_args
end
test do
input, = Open3.popen2 "SHELL=/bin/sh script -q output.txt"
input.puts "stty rows 80 cols 130"
input.puts "#{bin}/xplr"
input.putc "q"
input.puts "exit"
sleep 5
File.open(testpath/"output.txt", "r:ISO-8859-7") do |f|
contents = f.read
assert_match testpath.to_s, contents
end
end
end
xplr: update 0.5.13 bottle.
class Xplr < Formula
desc "Hackable, minimal, fast TUI file explorer"
homepage "https://github.com/sayanarijit/xplr"
url "https://github.com/sayanarijit/xplr/archive/v0.5.13.tar.gz"
sha256 "cc705c0f3eedf88ec8c22adb4d8629e66a8bf5ad55ccb4e24a1d6d4a7de6d29f"
license "MIT"
head "https://github.com/sayanarijit/xplr.git", branch: "main"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "efc4e8379a39b7743b5ce02c60291c3fe5d7729304dddc5629afb0951ea51832"
sha256 cellar: :any_skip_relocation, big_sur: "fa38e0a94d6e12dac7216d509adfeb811aeabdf2129c8ae7b7f304021d874bf2"
sha256 cellar: :any_skip_relocation, catalina: "7667e5718bc358d16923535017927791ed21a408b4784db3ec58a6a4fa77ac20"
sha256 cellar: :any_skip_relocation, mojave: "309933ea1629c04a940854ebeec22c17ecbe2135ee28aec7f08f1227c2e926bd"
end
depends_on "rust" => :build
def install
system "cargo", "install", *std_cargo_args
end
test do
input, = Open3.popen2 "SHELL=/bin/sh script -q output.txt"
input.puts "stty rows 80 cols 130"
input.puts "#{bin}/xplr"
input.putc "q"
input.puts "exit"
sleep 5
File.open(testpath/"output.txt", "r:ISO-8859-7") do |f|
contents = f.read
assert_match testpath.to_s, contents
end
end
end
|
class Yajl < Formula
desc "Yet Another JSON Library"
homepage "https://lloyd.github.io/yajl/"
url "https://github.com/lloyd/yajl/archive/2.1.0.tar.gz"
sha256 "3fb73364a5a30efe615046d07e6db9d09fd2b41c763c5f7d3bfb121cd5c5ac5a"
bottle do
cellar :any
rebuild 4
sha256 "1f97e0bbc6680ad4735f0c7ecac20ec87531456c3ab1c93c480c5c5a93a33e1c" => :sierra
sha256 "5cfd83bfdbd7c92402f1cecc6b66788e6db0c195880a40263365d8130e47db2f" => :el_capitan
sha256 "600fec6352ac23a66795cce22cb0a555df43eb464c87693299cb4fc2a1307833" => :yosemite
sha256 "d44363e381f2f353387374167520ed166f3c0c756887dab6e015961bd9ba5ff3" => :mavericks
sha256 "d35963d9d40c22e83a878a98a470f88405abf13efa61c7a3a999d7d79724b525" => :mountain_lion
end
# Configure uses cmake internally
depends_on "cmake" => :build
def install
ENV.deparallelize
system "cmake", ".", *std_cmake_args
system "make", "install"
(include/"yajl").install Dir["src/api/*.h"]
end
test do
output = pipe_output("#{bin}/json_verify", "[0,1,2,3]").strip
assert_equal "JSON is valid", output
end
end
yajl: update 2.1.0 bottle.
class Yajl < Formula
desc "Yet Another JSON Library"
homepage "https://lloyd.github.io/yajl/"
url "https://github.com/lloyd/yajl/archive/2.1.0.tar.gz"
sha256 "3fb73364a5a30efe615046d07e6db9d09fd2b41c763c5f7d3bfb121cd5c5ac5a"
bottle do
cellar :any
rebuild 4
sha256 "3213f11462b3c60a33209c4f5d36c96caf1a9409103012ffb427dd51770ac120" => :high_sierra
sha256 "1f97e0bbc6680ad4735f0c7ecac20ec87531456c3ab1c93c480c5c5a93a33e1c" => :sierra
sha256 "5cfd83bfdbd7c92402f1cecc6b66788e6db0c195880a40263365d8130e47db2f" => :el_capitan
sha256 "600fec6352ac23a66795cce22cb0a555df43eb464c87693299cb4fc2a1307833" => :yosemite
sha256 "d44363e381f2f353387374167520ed166f3c0c756887dab6e015961bd9ba5ff3" => :mavericks
sha256 "d35963d9d40c22e83a878a98a470f88405abf13efa61c7a3a999d7d79724b525" => :mountain_lion
end
# Configure uses cmake internally
depends_on "cmake" => :build
def install
ENV.deparallelize
system "cmake", ".", *std_cmake_args
system "make", "install"
(include/"yajl").install Dir["src/api/*.h"]
end
test do
output = pipe_output("#{bin}/json_verify", "[0,1,2,3]").strip
assert_equal "JSON is valid", output
end
end
|
require "language/node"
class Yarn < Formula
desc "Javascript package manager"
homepage "https://yarnpkg.com/"
url "https://yarnpkg.com/downloads/0.16.0/yarn-v0.16.0.tar.gz"
sha256 "cd1d7eeb8eb2518441d99c914e5fd18b68e2759743d212dfd8f00574a1de6da8"
head "https://github.com/yarnpkg/yarn.git"
bottle do
cellar :any_skip_relocation
sha256 "01d2ee1cc47677f420cf0d4677ba022fa44c012260795943d663dffceb81dfd1" => :sierra
sha256 "7cbc394d634efaecb016de9be29f800baea3541521e268e9f9cdc513978f964b" => :el_capitan
sha256 "028842707bc0270f77a651a2fd82cd37cd1a2a30d653e487ead4c5a8edb81a76" => :yosemite
end
depends_on "node"
def install
system "npm", "install", *Language::Node.std_npm_install_args(libexec)
bin.install_symlink Dir["#{libexec}/bin/*"]
end
test do
(testpath/"package.json").write('{"name": "test"}')
system bin/"yarn", "add", "jquery"
end
end
yarn 0.16.1
Closes #6127.
Signed-off-by: Andrew Janke <02e0a999c50b1f88df7a8f5a04e1b76b35ea6a88@apjanke.net>
require "language/node"
class Yarn < Formula
desc "Javascript package manager"
homepage "https://yarnpkg.com/"
url "https://yarnpkg.com/downloads/0.16.1/yarn-v0.16.1.tar.gz"
sha256 "73be27c34ef1dd4217fec23cdfb6b800cd995e9079d4c4764724ef98e98fec07"
head "https://github.com/yarnpkg/yarn.git"
bottle do
cellar :any_skip_relocation
sha256 "01d2ee1cc47677f420cf0d4677ba022fa44c012260795943d663dffceb81dfd1" => :sierra
sha256 "7cbc394d634efaecb016de9be29f800baea3541521e268e9f9cdc513978f964b" => :el_capitan
sha256 "028842707bc0270f77a651a2fd82cd37cd1a2a30d653e487ead4c5a8edb81a76" => :yosemite
end
depends_on "node"
def install
system "npm", "install", *Language::Node.std_npm_install_args(libexec)
bin.install_symlink Dir["#{libexec}/bin/*"]
end
test do
(testpath/"package.json").write('{"name": "test"}')
system bin/"yarn", "add", "jquery"
end
end
|
class Yarn < Formula
desc "JavaScript package manager"
homepage "https://yarnpkg.com/"
url "https://yarnpkg.com/downloads/1.3.2/yarn-v1.3.2.tar.gz"
sha256 "6cfe82e530ef0837212f13e45c1565ba53f5199eec2527b85ecbcd88bf26821d"
bottle :unneeded
depends_on "node" => :recommended
def install
libexec.install Dir["*"]
(bin/"yarn").write_env_script "#{libexec}/bin/yarn.js", :PREFIX => HOMEBREW_PREFIX
(bin/"yarnpkg").write_env_script "#{libexec}/bin/yarn.js", :PREFIX => HOMEBREW_PREFIX
inreplace "#{libexec}/package.json", '"installationMethod": "tar"', '"installationMethod": "homebrew"'
end
test do
(testpath/"package.json").write('{"name": "test"}')
system bin/"yarn", "add", "jquery"
end
end
yarn: conflicts with hadoop
Both install `yarn` binaries.
class Yarn < Formula
desc "JavaScript package manager"
homepage "https://yarnpkg.com/"
url "https://yarnpkg.com/downloads/1.3.2/yarn-v1.3.2.tar.gz"
sha256 "6cfe82e530ef0837212f13e45c1565ba53f5199eec2527b85ecbcd88bf26821d"
bottle :unneeded
depends_on "node" => :recommended
conflicts_with "hadoop", :because => "both install `yarn` binaries"
def install
libexec.install Dir["*"]
(bin/"yarn").write_env_script "#{libexec}/bin/yarn.js", :PREFIX => HOMEBREW_PREFIX
(bin/"yarnpkg").write_env_script "#{libexec}/bin/yarn.js", :PREFIX => HOMEBREW_PREFIX
inreplace "#{libexec}/package.json", '"installationMethod": "tar"', '"installationMethod": "homebrew"'
end
test do
(testpath/"package.json").write('{"name": "test"}')
system bin/"yarn", "add", "jquery"
end
end
|
require 'formula'
class Yeti < Formula
homepage 'http://mth.github.io/yeti/'
url 'https://github.com/mth/yeti/archive/v0.9.7.tar.gz'
sha1 'ae1f86f7e18ee05cb6f9a9f1320d7f833d0bdd56'
head 'https://github.com/mth/yeti.git'
def install
system "ant jar"
prefix.install "yeti.jar"
(bin+'yeti').write <<-EOS.undent
#!/bin/sh
YETI=#{prefix}/yeti.jar
java -server -jar "$YETI" "$@"
EOS
end
end
yeti v0.9.8
Signed-off-by: Adam Vandenberg <34c2b6407fd5a10249a15d699d40f9ed1782e98c@gmail.com>
require 'formula'
class Yeti < Formula
homepage 'http://mth.github.io/yeti/'
url 'https://github.com/mth/yeti/archive/v0.9.8.tar.gz'
sha1 '64e6174f765fd1444eff70c4a96ae76b2daa6c79'
head 'https://github.com/mth/yeti.git'
def install
system "ant jar"
prefix.install "yeti.jar"
(bin+'yeti').write <<-EOS.undent
#!/bin/sh
YETI=#{prefix}/yeti.jar
java -server -jar "$YETI" "$@"
EOS
end
end
|
class Zbar < Formula
desc "Suite of barcodes-reading tools"
homepage "https://github.com/mchehab/zbar"
url "https://github.com/mchehab/zbar/archive/0.23.1.tar.gz"
sha256 "297439f8859089d2248f55ab95b2a90bba35687975365385c87364c77fdb19f3"
license "LGPL-2.1-only"
revision OS.mac? ? 12 : 13
head "https://github.com/mchehab/zbar.git"
livecheck do
url :stable
regex(/^v?(\d+(?:\.\d+)+)$/i)
end
bottle do
sha256 arm64_big_sur: "6326e5663dc3ff4a15d2b1da61280f58878a7340990e065c5c3ac020046951b2"
sha256 big_sur: "f331d1b54eeabaa2fac58568eb5eb75dbc1958cfa30898cf2270ea4847c1e96b"
sha256 catalina: "b55d61b6b252c0591ca14881ea2cd8d2e008fdd1be0822be2c18a9d7c537230b"
sha256 mojave: "60a4c4fe9de4b65381c4a69e7bbf469ebc8a5c13f0581ba8dbbe2262218b235f"
end
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "gettext" => :build
depends_on "libtool" => :build
depends_on "pkg-config" => :build
depends_on "xmlto" => :build
depends_on "freetype"
depends_on "imagemagick"
depends_on "jpeg"
depends_on "libtool"
depends_on "ufraw"
depends_on "xz"
on_linux do
depends_on "dbus"
end
def install
system "autoreconf", "-fvi"
args = %W[
--disable-dependency-tracking
--prefix=#{prefix}
--without-python
--without-qt
--disable-video
--without-gtk
--without-x
]
system "./configure", *args
system "make", "install"
end
test do
system bin/"zbarimg", "-h"
end
end
zbar: update 0.23.1_13 bottle.
class Zbar < Formula
desc "Suite of barcodes-reading tools"
homepage "https://github.com/mchehab/zbar"
url "https://github.com/mchehab/zbar/archive/0.23.1.tar.gz"
sha256 "297439f8859089d2248f55ab95b2a90bba35687975365385c87364c77fdb19f3"
license "LGPL-2.1-only"
revision OS.mac? ? 12 : 13
head "https://github.com/mchehab/zbar.git"
livecheck do
url :stable
regex(/^v?(\d+(?:\.\d+)+)$/i)
end
bottle do
sha256 arm64_big_sur: "6326e5663dc3ff4a15d2b1da61280f58878a7340990e065c5c3ac020046951b2"
sha256 big_sur: "f331d1b54eeabaa2fac58568eb5eb75dbc1958cfa30898cf2270ea4847c1e96b"
sha256 catalina: "b55d61b6b252c0591ca14881ea2cd8d2e008fdd1be0822be2c18a9d7c537230b"
sha256 mojave: "60a4c4fe9de4b65381c4a69e7bbf469ebc8a5c13f0581ba8dbbe2262218b235f"
sha256 x86_64_linux: "6120d77d77617190c0f445f7d8f2cbf90e0565f6e0a65e6d77c4a94617de8a8f"
end
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "gettext" => :build
depends_on "libtool" => :build
depends_on "pkg-config" => :build
depends_on "xmlto" => :build
depends_on "freetype"
depends_on "imagemagick"
depends_on "jpeg"
depends_on "libtool"
depends_on "ufraw"
depends_on "xz"
on_linux do
depends_on "dbus"
end
def install
system "autoreconf", "-fvi"
args = %W[
--disable-dependency-tracking
--prefix=#{prefix}
--without-python
--without-qt
--disable-video
--without-gtk
--without-x
]
system "./configure", *args
system "make", "install"
end
test do
system bin/"zbarimg", "-h"
end
end
|
class Zbar < Formula
desc "Suite of barcodes-reading tools"
homepage "https://zbar.sourceforge.io"
revision 5
stable do
url "https://downloads.sourceforge.net/project/zbar/zbar/0.10/zbar-0.10.tar.bz2"
sha256 "234efb39dbbe5cef4189cc76f37afbe3cfcfb45ae52493bfe8e191318bdbadc6"
# Fix JPEG handling using patch from
# https://sourceforge.net/p/zbar/discussion/664596/thread/58b8d79b#8f67
# already applied upstream but not present in the 0.10 release
patch :DATA
end
bottle do
cellar :any
sha256 "3e6dc5f4f2d734287286677241c7d0580f4b2f786bbc8ce9a13d728fa4b54499" => :sierra
sha256 "84e0feef90dfe6f75a28f27a625030d68ab7a029e14055717bbc4622e63c4f0a" => :el_capitan
sha256 "e0dd76519a36dba47248616b8aa4f5cbe6b2b7df54529d36794de4e8488bbf1b" => :yosemite
end
head do
url "https://github.com/ZBar/ZBar.git"
depends_on "gettext" => :build
depends_on "automake" => :build
depends_on "autoconf" => :build
depends_on "libtool" => :build
depends_on "xmlto" => :build
end
depends_on :x11 => :optional
depends_on "pkg-config" => :build
depends_on "jpeg"
depends_on "imagemagick"
depends_on "ufraw"
depends_on "xz"
depends_on "freetype"
depends_on "libtool" => :run
def install
if build.head?
inreplace "configure.ac", "-Werror", ""
gettext = Formula["gettext"]
system "autoreconf", "-fvi", "-I", "#{gettext.opt_share}/aclocal"
end
# ImageMagick 7 compatibility
# Reported 20 Jun 2016 https://sourceforge.net/p/zbar/support-requests/156/
inreplace ["configure", "zbarimg/zbarimg.c"],
"wand/MagickWand.h",
"ImageMagick-7/MagickWand/MagickWand.h"
args = %W[
--disable-dependency-tracking
--prefix=#{prefix}
--without-python
--without-qt
--disable-video
--without-gtk
]
if build.with? "x11"
args << "--with-x"
else
args << "--without-x"
end
system "./configure", *args
system "make", "install"
end
test do
system bin/"zbarimg", "-h"
end
end
__END__
diff --git a/zbar/jpeg.c b/zbar/jpeg.c
index fb566f4..d1c1fb2 100644
--- a/zbar/jpeg.c
+++ b/zbar/jpeg.c
@@ -79,8 +79,15 @@ int fill_input_buffer (j_decompress_ptr cinfo)
void skip_input_data (j_decompress_ptr cinfo,
long num_bytes)
{
- cinfo->src->next_input_byte = NULL;
- cinfo->src->bytes_in_buffer = 0;
+ if (num_bytes > 0) {
+ if (num_bytes < cinfo->src->bytes_in_buffer) {
+ cinfo->src->next_input_byte += num_bytes;
+ cinfo->src->bytes_in_buffer -= num_bytes;
+ }
+ else {
+ fill_input_buffer(cinfo);
+ }
+ }
}
void term_source (j_decompress_ptr cinfo)
zbar: revision for jpeg
class Zbar < Formula
desc "Suite of barcodes-reading tools"
homepage "https://zbar.sourceforge.io"
revision 6
stable do
url "https://downloads.sourceforge.net/project/zbar/zbar/0.10/zbar-0.10.tar.bz2"
sha256 "234efb39dbbe5cef4189cc76f37afbe3cfcfb45ae52493bfe8e191318bdbadc6"
# Fix JPEG handling using patch from
# https://sourceforge.net/p/zbar/discussion/664596/thread/58b8d79b#8f67
# already applied upstream but not present in the 0.10 release
patch :DATA
end
bottle do
cellar :any
sha256 "3e6dc5f4f2d734287286677241c7d0580f4b2f786bbc8ce9a13d728fa4b54499" => :sierra
sha256 "84e0feef90dfe6f75a28f27a625030d68ab7a029e14055717bbc4622e63c4f0a" => :el_capitan
sha256 "e0dd76519a36dba47248616b8aa4f5cbe6b2b7df54529d36794de4e8488bbf1b" => :yosemite
end
head do
url "https://github.com/ZBar/ZBar.git"
depends_on "gettext" => :build
depends_on "automake" => :build
depends_on "autoconf" => :build
depends_on "libtool" => :build
depends_on "xmlto" => :build
end
depends_on :x11 => :optional
depends_on "pkg-config" => :build
depends_on "jpeg"
depends_on "imagemagick"
depends_on "ufraw"
depends_on "xz"
depends_on "freetype"
depends_on "libtool" => :run
def install
if build.head?
inreplace "configure.ac", "-Werror", ""
gettext = Formula["gettext"]
system "autoreconf", "-fvi", "-I", "#{gettext.opt_share}/aclocal"
end
# ImageMagick 7 compatibility
# Reported 20 Jun 2016 https://sourceforge.net/p/zbar/support-requests/156/
inreplace ["configure", "zbarimg/zbarimg.c"],
"wand/MagickWand.h",
"ImageMagick-7/MagickWand/MagickWand.h"
args = %W[
--disable-dependency-tracking
--prefix=#{prefix}
--without-python
--without-qt
--disable-video
--without-gtk
]
if build.with? "x11"
args << "--with-x"
else
args << "--without-x"
end
system "./configure", *args
system "make", "install"
end
test do
system bin/"zbarimg", "-h"
end
end
__END__
diff --git a/zbar/jpeg.c b/zbar/jpeg.c
index fb566f4..d1c1fb2 100644
--- a/zbar/jpeg.c
+++ b/zbar/jpeg.c
@@ -79,8 +79,15 @@ int fill_input_buffer (j_decompress_ptr cinfo)
void skip_input_data (j_decompress_ptr cinfo,
long num_bytes)
{
- cinfo->src->next_input_byte = NULL;
- cinfo->src->bytes_in_buffer = 0;
+ if (num_bytes > 0) {
+ if (num_bytes < cinfo->src->bytes_in_buffer) {
+ cinfo->src->next_input_byte += num_bytes;
+ cinfo->src->bytes_in_buffer -= num_bytes;
+ }
+ else {
+ fill_input_buffer(cinfo);
+ }
+ }
}
void term_source (j_decompress_ptr cinfo)
|
class Zboy < Formula
desc "GameBoy emulator"
homepage "https://zboy.sourceforge.io/"
url "https://downloads.sourceforge.net/project/zboy/zBoy%20v0.60/zboy-0.60.tar.gz"
sha256 "f81e61433a5b74c61ab84cac33da598deb03e49699f3d65dcb983151a6f1c749"
head "https://svn.code.sf.net/p/zboy/code/trunk"
bottle do
cellar :any
sha256 "591314e1270d822230b89e64e7d6b4ca5602e77c10c13ae034e7eed347fb2bb0" => :mojave
sha256 "5eb884e02583dd9b50e554a6dfae805849dbd620bb90d10b721937cb4f35fa50" => :high_sierra
sha256 "85d55fa04126008eb3a72d8cba9afa52b64231807306340c70414649ec56aca1" => :sierra
sha256 "3eada5e4cb665257ea7f4dc244e8fe4dac54f279cc9ab2bd4ccfce486b010356" => :el_capitan
sha256 "ea5ce73b9e6dccb7e96e7a9eb8e7f7c75c54b89d00bded0a0f13bccbc22a7808" => :yosemite
end
depends_on "sdl2"
def install
sdl2 = Formula["sdl2"]
ENV.append_to_cflags "-std=gnu89 -D__zboy4linux__ -DNETPLAY -DLFNAVAIL -I#{sdl2.include} -L#{sdl2.lib}"
system "make", "-f", "Makefile.linux", "CFLAGS=#{ENV.cflags}"
bin.install "zboy"
end
test do
system "#{bin}/zboy", "--help"
end
end
zboy: adjust svn URL
class Zboy < Formula
desc "GameBoy emulator"
homepage "https://zboy.sourceforge.io/"
url "https://downloads.sourceforge.net/project/zboy/zBoy%20v0.60/zboy-0.60.tar.gz"
sha256 "f81e61433a5b74c61ab84cac33da598deb03e49699f3d65dcb983151a6f1c749"
head "http://svn.code.sf.net/p/zboy/code/trunk"
bottle do
cellar :any
sha256 "591314e1270d822230b89e64e7d6b4ca5602e77c10c13ae034e7eed347fb2bb0" => :mojave
sha256 "5eb884e02583dd9b50e554a6dfae805849dbd620bb90d10b721937cb4f35fa50" => :high_sierra
sha256 "85d55fa04126008eb3a72d8cba9afa52b64231807306340c70414649ec56aca1" => :sierra
sha256 "3eada5e4cb665257ea7f4dc244e8fe4dac54f279cc9ab2bd4ccfce486b010356" => :el_capitan
sha256 "ea5ce73b9e6dccb7e96e7a9eb8e7f7c75c54b89d00bded0a0f13bccbc22a7808" => :yosemite
end
depends_on "sdl2"
def install
sdl2 = Formula["sdl2"]
ENV.append_to_cflags "-std=gnu89 -D__zboy4linux__ -DNETPLAY -DLFNAVAIL -I#{sdl2.include} -L#{sdl2.lib}"
system "make", "-f", "Makefile.linux", "CFLAGS=#{ENV.cflags}"
bin.install "zboy"
end
test do
system "#{bin}/zboy", "--help"
end
end
|
## This is the rakegem gemspec template. Make sure you read and understand
## all of the comments. Some sections require modification, and others can
## be deleted if you don't need them. Once you understand the contents of
## this file, feel free to delete any comments that begin with two hash marks.
## You can find comprehensive Gem::Specification documentation, at
## http://docs.rubygems.org/read/chapter/20
Gem::Specification.new do |s|
s.specification_version = 2 if s.respond_to? :specification_version=
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.rubygems_version = '1.3.5'
## Leave these as is they will be modified for you by the rake gemspec task.
## If your rubyforge_project name is different, then edit it and comment out
## the sub! line in the Rakefile
s.name = 'formatador'
s.version = '0.2.4'
s.date = '2012-10-26'
s.rubyforge_project = 'formatador'
## Make sure your summary is short. The description may be as long
## as you like.
s.summary = "Ruby STDOUT text formatting"
s.description = "STDOUT text formatting"
## List the primary authors. If there are a bunch of authors, it's probably
## better to set the email to an email list or something. If you don't have
## a custom homepage, consider using your GitHub URL or the like.
s.authors = ["geemus (Wesley Beary)"]
s.email = 'geemus@gmail.com'
s.homepage = "http://github.com/geemus/#{s.name}"
## This gets added to the $LOAD_PATH so that 'lib/NAME.rb' can be required as
## require 'NAME.rb' or'/lib/NAME/file.rb' can be as require 'NAME/file.rb'
s.require_paths = %w[lib]
## This sections is only necessary if you have C extensions.
# s.require_paths << 'ext'
# s.extensions = %w[ext/extconf.rb]
## If your gem includes any executables, list them here.
# s.executables = ["name"]
# s.default_executable = 'name'
## Specify any RDoc options here. You'll want to add your README and
## LICENSE files to the extra_rdoc_files list.
s.rdoc_options = ["--charset=UTF-8"]
s.extra_rdoc_files = %w[README.rdoc]
## List your runtime dependencies here. Runtime dependencies are those
## that are needed for an end user to actually USE your code.
# s.add_dependency('DEPNAME', [">= 1.1.0", "< 2.0.0"])
## List your development dependencies here. Development dependencies are
## those that are only needed during development
s.add_development_dependency('rake')
s.add_development_dependency('shindo')
## Leave this section as-is. It will be automatically generated from the
## contents of your Git repository via the gemspec task. DO NOT REMOVE
## THE MANIFEST COMMENTS, they are used as delimiters by the task.
# = MANIFEST =
s.files = %w[
Gemfile
README.rdoc
Rakefile
changelog.txt
formatador.gemspec
lib/formatador.rb
lib/formatador/progressbar.rb
lib/formatador/table.rb
tests/basic_tests.rb
tests/table_tests.rb
tests/tests_helper.rb
]
# = MANIFEST =
## Test files will be grabbed from the file list. Make sure the path glob
## matches what you actually use.
s.test_files = s.files.select { |path| path =~ /^[spec|tests]\/.*_[spec|tests]\.rb/ }
end
Release 0.2.5
## This is the rakegem gemspec template. Make sure you read and understand
## all of the comments. Some sections require modification, and others can
## be deleted if you don't need them. Once you understand the contents of
## this file, feel free to delete any comments that begin with two hash marks.
## You can find comprehensive Gem::Specification documentation, at
## http://docs.rubygems.org/read/chapter/20
Gem::Specification.new do |s|
s.specification_version = 2 if s.respond_to? :specification_version=
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.rubygems_version = '1.3.5'
## Leave these as is they will be modified for you by the rake gemspec task.
## If your rubyforge_project name is different, then edit it and comment out
## the sub! line in the Rakefile
s.name = 'formatador'
s.version = '0.2.5'
s.date = '2014-05-23'
s.rubyforge_project = 'formatador'
## Make sure your summary is short. The description may be as long
## as you like.
s.summary = "Ruby STDOUT text formatting"
s.description = "STDOUT text formatting"
## List the primary authors. If there are a bunch of authors, it's probably
## better to set the email to an email list or something. If you don't have
## a custom homepage, consider using your GitHub URL or the like.
s.authors = ["geemus (Wesley Beary)"]
s.email = 'geemus@gmail.com'
s.homepage = "http://github.com/geemus/#{s.name}"
## This gets added to the $LOAD_PATH so that 'lib/NAME.rb' can be required as
## require 'NAME.rb' or'/lib/NAME/file.rb' can be as require 'NAME/file.rb'
s.require_paths = %w[lib]
## This sections is only necessary if you have C extensions.
# s.require_paths << 'ext'
# s.extensions = %w[ext/extconf.rb]
## If your gem includes any executables, list them here.
# s.executables = ["name"]
# s.default_executable = 'name'
## Specify any RDoc options here. You'll want to add your README and
## LICENSE files to the extra_rdoc_files list.
s.rdoc_options = ["--charset=UTF-8"]
s.extra_rdoc_files = %w[README.rdoc]
## List your runtime dependencies here. Runtime dependencies are those
## that are needed for an end user to actually USE your code.
# s.add_dependency('DEPNAME', [">= 1.1.0", "< 2.0.0"])
## List your development dependencies here. Development dependencies are
## those that are only needed during development
s.add_development_dependency('rake')
s.add_development_dependency('shindo')
## Leave this section as-is. It will be automatically generated from the
## contents of your Git repository via the gemspec task. DO NOT REMOVE
## THE MANIFEST COMMENTS, they are used as delimiters by the task.
# = MANIFEST =
s.files = %w[
CONTRIBUTING.md
CONTRIBUTORS.md
Gemfile
LICENSE.md
README.rdoc
Rakefile
changelog.txt
formatador.gemspec
lib/formatador.rb
lib/formatador/progressbar.rb
lib/formatador/table.rb
tests/basic_tests.rb
tests/table_tests.rb
tests/tests_helper.rb
]
# = MANIFEST =
## Test files will be grabbed from the file list. Make sure the path glob
## matches what you actually use.
s.test_files = s.files.select { |path| path =~ /^[spec|tests]\/.*_[spec|tests]\.rb/ }
end
|
# encoding: utf-8
$:.push File.expand_path("../lib", __FILE__)
require "formtastic/version"
Gem::Specification.new do |s|
s.name = %q{formtastic}
s.version = Formtastic::VERSION
s.platform = Gem::Platform::RUBY
s.authors = [%q{Justin French}]
s.email = [%q{justin@indent.com.au}]
s.homepage = %q{http://github.com/justinfrench/formtastic}
s.summary = %q{A Rails form builder plugin/gem with semantically rich and accessible markup}
s.description = %q{A Rails form builder plugin/gem with semantically rich and accessible markup}
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
s.rdoc_options = ["--charset=UTF-8"]
s.extra_rdoc_files = ["README.textile"]
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.rubygems_version = %q{1.3.6}
s.add_dependency(%q<actionpack>, [">= 3.0"])
s.add_development_dependency(%q<nokogiri>, ["< 1.6.0"]) # 1.6 requires Ruby 1.9.2, drop in v3.0
s.add_development_dependency(%q<rspec-rails>, ["~> 2.12.0"])
s.add_development_dependency(%q<rspec_tag_matchers>, [">= 1.0.0"])
s.add_development_dependency(%q<hpricot>, ["~> 0.8.3"])
s.add_development_dependency(%q<BlueCloth>) # for YARD
s.add_development_dependency(%q<yard>, ["~> 0.6"])
s.add_development_dependency(%q<colored>)
s.add_development_dependency(%q<tzinfo>)
s.add_development_dependency(%q<ammeter>, ["0.2.5"])
s.add_development_dependency(%q<appraisal>)
s.add_development_dependency(%q<rake>)
s.add_development_dependency(%q<activemodel>)
end
Add license information to gemspec
This increases the discoverability of what license this gem uses. See rubygems/rubygems.org#363 for more info.
# encoding: utf-8
$:.push File.expand_path("../lib", __FILE__)
require "formtastic/version"
Gem::Specification.new do |s|
s.name = %q{formtastic}
s.version = Formtastic::VERSION
s.platform = Gem::Platform::RUBY
s.authors = [%q{Justin French}]
s.email = [%q{justin@indent.com.au}]
s.homepage = %q{http://github.com/justinfrench/formtastic}
s.summary = %q{A Rails form builder plugin/gem with semantically rich and accessible markup}
s.description = %q{A Rails form builder plugin/gem with semantically rich and accessible markup}
s.license = 'MIT'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
s.rdoc_options = ["--charset=UTF-8"]
s.extra_rdoc_files = ["README.textile"]
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.rubygems_version = %q{1.3.6}
s.add_dependency(%q<actionpack>, [">= 3.0"])
s.add_development_dependency(%q<nokogiri>, ["< 1.6.0"]) # 1.6 requires Ruby 1.9.2, drop in v3.0
s.add_development_dependency(%q<rspec-rails>, ["~> 2.12.0"])
s.add_development_dependency(%q<rspec_tag_matchers>, [">= 1.0.0"])
s.add_development_dependency(%q<hpricot>, ["~> 0.8.3"])
s.add_development_dependency(%q<BlueCloth>) # for YARD
s.add_development_dependency(%q<yard>, ["~> 0.6"])
s.add_development_dependency(%q<colored>)
s.add_development_dependency(%q<tzinfo>)
s.add_development_dependency(%q<ammeter>, ["0.2.5"])
s.add_development_dependency(%q<appraisal>)
s.add_development_dependency(%q<rake>)
s.add_development_dependency(%q<activemodel>)
end
|
# -*- encoding: utf-8 -*-
# stub: framecurve 2.2.2 ruby lib
require File.dirname(__FILE__) + '/lib/framecurve/version'
Gem::Specification.new do |s|
s.name = "framecurve"
s.version = Framecurve::VERSION
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib"]
s.authors = ["Julik"]
s.date = Time.now.utc.strftime("%Y-%m-%d")
s.description = "Framecurve parser, validation and interpolation"
s.email = "me@julik.nl"
s.executables = ["framecurve_from_fcp_xml", "framecurve_validator"]
s.extra_rdoc_files = [
"LICENSE.txt",
"README.rdoc"
]
s.files = `git ls-files -z`.split("\x0")
s.homepage = "http://github.com/guerilla-di/framecurve"
s.licenses = ["MIT"]
s.rubygems_version = "2.2.2"
s.summary = "Handles Framecurve files"
s.specification_version = 4
s.add_development_dependency('rake')
s.add_development_dependency('cli_test')
s.add_development_dependency('test-unit')
end
Limit Rake to 10
# -*- encoding: utf-8 -*-
# stub: framecurve 2.2.2 ruby lib
require File.dirname(__FILE__) + '/lib/framecurve/version'
Gem::Specification.new do |s|
s.name = "framecurve"
s.version = Framecurve::VERSION
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib"]
s.authors = ["Julik"]
s.date = Time.now.utc.strftime("%Y-%m-%d")
s.description = "Framecurve parser, validation and interpolation"
s.email = "me@julik.nl"
s.executables = ["framecurve_from_fcp_xml", "framecurve_validator"]
s.extra_rdoc_files = [
"LICENSE.txt",
"README.rdoc"
]
s.files = `git ls-files -z`.split("\x0")
s.homepage = "http://github.com/guerilla-di/framecurve"
s.licenses = ["MIT"]
s.rubygems_version = "2.2.2"
s.summary = "Handles Framecurve files"
s.specification_version = 4
s.add_development_dependency('rake', '~> 10')
s.add_development_dependency('cli_test')
s.add_development_dependency('test-unit')
end
|
# **Life** is a class that implements [Conway's Game of life][gl],
# a simple [cellular automaton][ca].
#
# The Game of Life is "played" on a two-dimensional grid of square cells, each
# of which is in one of two possible states, alive or dead.
#
# The game plays out in time-steps called ticks. At every tick, each cell
# interacts with its eight neighours. At each step, the following
# transitions occur:
#
# * Any live cell with fewer than two live neighbours dies.
# * Any live cell with two or three live neighbours lives.
# * Any live cell with more than three live neighbours dies.
# * Any dead cell with exactly three live neighbours becomes a live cell.
#
# I have implemented this code in a [Test Driven][td] manner in order to
# practice TDD and to play with the new Ruby testing library [Minitest][mt].
# The tests can be found [here](test_life.html).
#
# There is also a simple [Shoes app for visualizing the game](shoes_life.rb).
#
# The code has been tested using Ruby 1.9.2 and 1.8.7.
#
# [gl]: http://en.wikipedia.org/wiki/Conway's_Game_of_Life
# [ca]: http://en.wikipedia.org/wiki/Cellular_automaton
# [td]: http://en.wikipedia.org/wiki/Test-driven_development
# [mt]: http://github.com/seattlerb/minitest
### In the Beginning was the Word
# Our `Life` class has three public getters. One for retrieving the array
# of live cells, the other two for the grid dimensions. Unlike the 'pure'
# definition of the game, our grid is not infinite in size.
class Life
attr_reader :cells, :width, :height
# `OutOfBoundsError` is a custom Exception that can be thrown by the
# `neighbours` method.
class OutOfBoundsError < ArgumentError; end
# When constructing a `Life` object we need to supply an array of cells
# along with the dimensions of the grid. The array of cells represents only
# live cells. Each cell contains the 2d coordinates of the cell.
#
# So, for example, if you had two live cells in the grid, one at x=1 and y=0
# and another at x=2 and y=3, the array would be:
#
# `[[1, 0], [2, 3]]`
#
# _**Side Note:** Based on the number of times `x,y` appears in the code, this
# array of arrays should likely be an array of cell objects, or an array of
# structs._
def initialize(cells, width, height)
@cells = cells
@width = width
@height = height
end
###These are the People in Your Neighbourhood
# Given two sets of x, y coordinates, are they `neighbours?`
def neighbour?(x1, y1, x2, y2)
# Remember, you are not your own neighbour!
return false if x1 == x2 && y1 == y2
# A neighbour is an adjecent cell. In otherwords, neither our delta x or our
# delta y can be greater than one.
(x1 - x2).abs <= 1 && (y1 - y2).abs <= 1
end
# The `neighbours` method returns the number of neigbouring live cells for any
# x, y coordinate in the grid.
def neighbours(x, y)
# If the x, y arguments are out of bounds we raise our custom `OutOfBoundError`.
raise OutOfBoundsError if out_of_bounds x, y
neighbours_found = 0
# This method is compuationally expensive. As such, the performance degrades
# as our cells count grows.
@cells.each do |cx, cy|
neighbours_found += 1 if neighbour? cx, cy, x, y
end
neighbours_found
end
### Life, The Next Generation
# The `next_gen` method generates the game state of the next tick.
def next_gen
# We start with an empty cell array...
@next_cells = []
@height.times do |y|
@width.times do |x|
# ...and we add cells depending on the rules of the game.
@next_cells << [x,y] if should_remain_alive?(x, y) ||
should_come_to_life?(x, y)
end
end
# Finally we return a new Life object instantiated with the next generation
# of cells.
Life.new @next_cells, @width, @height
end
### The Rules of Life
# Cells that are alive should remain so if they have 2 or 3 neighbours.
def should_remain_alive?(x,y)
alive?(x,y) && (2..3).include?(neighbours(x,y))
end
# Cells that are dead should come to life if they have exactly 3 neighbours.
def should_come_to_life?(x, y)
dead?(x,y) && neighbours(x,y) == 3
end
### Helper Methods
# A cell at a particular x,y coordinate is alive if it can be found in our
# array of `@cells`.
def alive?(x, y)
@cells.include?([x, y])
end
# A cell at a particular x,y coordinate is dead if it is not alive. :)
def dead?(x,y)
!alive?(x, y)
end
# Allow us to bring specific cells to life, as long as they aren't already alive.
def set_cell_alive(x, y)
@cells << [x, y] if !alive?(x,y)
end
# Our grid bounaries are zero-based and depend on our `@width` and `@height`.
def out_of_bounds(x, y)
x < 0 || x >= @width || y < 0 || y >= @height
end
# Our Life object can output a string representation of itself. Live cells are
# shown as asteriks and dead cells as minus signs.
def to_s
output = ""
@height.times do |y|
@width.times do |x|
output << (@cells.include?([x,y]) ? '*' : '-')
end
output << "\n"
end
output
end
end
#### UNLICENSE
# _This is free and unencumbered software released into the public domain._
Added link to github repo in the docs
# **Life** is a class that implements [Conway's Game of life][gl],
# a simple [cellular automaton][ca].
#
# The Game of Life is "played" on a two-dimensional grid of square cells, each
# of which is in one of two possible states, alive or dead.
#
# The game plays out in time-steps called ticks. At every tick, each cell
# interacts with its eight neighours. At each step, the following
# transitions occur:
#
# * Any live cell with fewer than two live neighbours dies.
# * Any live cell with two or three live neighbours lives.
# * Any live cell with more than three live neighbours dies.
# * Any dead cell with exactly three live neighbours becomes a live cell.
#
# I have implemented this code in a [Test Driven][td] manner in order to
# practice TDD and to play with the new Ruby testing library [Minitest][mt].
# The tests can be found [here](test_life.html).
#
# There is also a simple [Shoes app for visualizing the game](shoes_life.rb).
#
# The code has been tested using Ruby 1.9.2 and 1.8.7.
#
# Github Repo: [/stungeye/tdd_gam_of_life][gh]
#
# [gl]: http://en.wikipedia.org/wiki/Conway's_Game_of_Life
# [ca]: http://en.wikipedia.org/wiki/Cellular_automaton
# [td]: http://en.wikipedia.org/wiki/Test-driven_development
# [mt]: http://github.com/seattlerb/minitest
# [gh]: https://github.com/stungeye/tdd_game_of_life/
### In the Beginning was the Word
# Our `Life` class has three public getters. One for retrieving the array
# of live cells, the other two for the grid dimensions. Unlike the 'pure'
# definition of the game, our grid is not infinite in size.
class Life
attr_reader :cells, :width, :height
# `OutOfBoundsError` is a custom Exception that can be thrown by the
# `neighbours` method.
class OutOfBoundsError < ArgumentError; end
# When constructing a `Life` object we need to supply an array of cells
# along with the dimensions of the grid. The array of cells represents only
# live cells. Each cell contains the 2d coordinates of the cell.
#
# So, for example, if you had two live cells in the grid, one at x=1 and y=0
# and another at x=2 and y=3, the array would be:
#
# `[[1, 0], [2, 3]]`
#
# _**Side Note:** Based on the number of times `x,y` appears in the code, this
# array of arrays should likely be an array of cell objects, or an array of
# structs._
def initialize(cells, width, height)
@cells = cells
@width = width
@height = height
end
###These are the People in Your Neighbourhood
# Given two sets of x, y coordinates, are they `neighbours?`
def neighbour?(x1, y1, x2, y2)
# Remember, you are not your own neighbour!
return false if x1 == x2 && y1 == y2
# A neighbour is an adjecent cell. In otherwords, neither our delta x or our
# delta y can be greater than one.
(x1 - x2).abs <= 1 && (y1 - y2).abs <= 1
end
# The `neighbours` method returns the number of neigbouring live cells for any
# x, y coordinate in the grid.
def neighbours(x, y)
# If the x, y arguments are out of bounds we raise our custom `OutOfBoundError`.
raise OutOfBoundsError if out_of_bounds x, y
neighbours_found = 0
# This method is compuationally expensive. As such, the performance degrades
# as our cells count grows.
@cells.each do |cx, cy|
neighbours_found += 1 if neighbour? cx, cy, x, y
end
neighbours_found
end
### Life, The Next Generation
# The `next_gen` method generates the game state of the next tick.
def next_gen
# We start with an empty cell array...
@next_cells = []
@height.times do |y|
@width.times do |x|
# ...and we add cells depending on the rules of the game.
@next_cells << [x,y] if should_remain_alive?(x, y) ||
should_come_to_life?(x, y)
end
end
# Finally we return a new Life object instantiated with the next generation
# of cells.
Life.new @next_cells, @width, @height
end
### The Rules of Life
# Cells that are alive should remain so if they have 2 or 3 neighbours.
def should_remain_alive?(x,y)
alive?(x,y) && (2..3).include?(neighbours(x,y))
end
# Cells that are dead should come to life if they have exactly 3 neighbours.
def should_come_to_life?(x, y)
dead?(x,y) && neighbours(x,y) == 3
end
### Helper Methods
# A cell at a particular x,y coordinate is alive if it can be found in our
# array of `@cells`.
def alive?(x, y)
@cells.include?([x, y])
end
# A cell at a particular x,y coordinate is dead if it is not alive. :)
def dead?(x,y)
!alive?(x, y)
end
# Allow us to bring specific cells to life, as long as they aren't already alive.
def set_cell_alive(x, y)
@cells << [x, y] if !alive?(x,y)
end
# Our grid bounaries are zero-based and depend on our `@width` and `@height`.
def out_of_bounds(x, y)
x < 0 || x >= @width || y < 0 || y >= @height
end
# Our Life object can output a string representation of itself. Live cells are
# shown as asteriks and dead cells as minus signs.
def to_s
output = ""
@height.times do |y|
@width.times do |x|
output << (@cells.include?([x,y]) ? '*' : '-')
end
output << "\n"
end
output
end
end
#### UNLICENSE
# _This is free and unencumbered software released into the public domain._
|
#
# Be sure to run `pod lib lint GeoJSON.podspec' to ensure this is a
# valid spec and remove all comments before submitting the spec.
#
# Any lines starting with a # are optional, but encouraged
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = "GeoJSON"
s.version = "0.1.0"
s.summary = "A GeoJSON model for Swift 1.2."
s.homepage = "https://github.com/bryx-inc/GeoJSON.swift"
s.license = 'MIT'
s.author = { "Harlan Haskins" => "harlan@harlanhaskins.com" }
s.source = { :git => "https://github.com/bryx-inc/GeoJSON.swift.git", :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.platform = :ios, '8.0'
s.requires_arc = true
s.source_files = 'Pod/Classes/**/*'
s.resource_bundles = {
'GeoJSON' => ['Pod/Assets/*.png']
}
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
Updated podspec
#
# Be sure to run `pod lib lint GeoJSON.podspec' to ensure this is a
# valid spec and remove all comments before submitting the spec.
#
# Any lines starting with a # are optional, but encouraged
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = "GeoJSON"
s.version = "0.2.0"
s.summary = "A GeoJSON model for Swift 2.0."
s.homepage = "https://github.com/bryx-inc/GeoJSON.swift"
s.license = 'MIT'
s.author = { "Harlan Haskins" => "harlan@harlanhaskins.com" }
s.source = { :git => "https://github.com/bryx-inc/GeoJSON.swift.git", :tag => s.version.to_s }
s.platform = :ios, '8.0'
s.requires_arc = true
s.source_files = 'Pod/Classes/**/*'
s.resource_bundles = {
'GeoJSON' => ['Pod/Assets/*.png']
}
end
|
module ActionSubscriber
VERSION = "5.1.5"
end
Bump version to 5.2.0
This version includes a new default behavior to automatically
resubscribe to a queue should one be deleted or a cluster fails and a
cancel event is sent to the consumer. See README for the new config. You
can disable the feature by setting it to false.
module ActionSubscriber
VERSION = "5.2.0"
end
|
Pod::Spec.new do |spec|
spec.name = 'HBShare'
spec.version = '0.0.1'
spec.license = 'MIT'
spec.homepage = 'http://github.com/lzyy/HBShare'
spec.author = 'limboy'
spec.summary = 'HBShare is a simple share helper built on UIActivityViewController with WeChat support'
spec.source = { :git => "https://github.com/lzyy/HBShare.git", :tag => "#{spec.version}" }
spec.source_files = 'HBShare/Classes/*.{h,m}', 'HBShare/Vendors/*.h'
spec.requires_arc = true
spec.ios.deployment_target = '6.0'
spec.ios.vendored_library = 'HBShare/Vendors/libWeChatSDK.a'
spec.requires_arc = true
spec.ios.deployment_target = '6.0'
end
update podspec
Pod::Spec.new do |spec|
spec.name = 'HBShare'
spec.version = '0.0.1'
spec.license = { :type => 'MIT', :file => 'LICENSE' }
spec.homepage = 'http://github.com/lzyy/HBShare'
spec.author = 'limboy'
spec.summary = 'HBShare is a simple share helper built on UIActivityViewController with WeChat support'
spec.source = { :git => "https://github.com/lzyy/HBShare.git", :tag => "#{spec.version}" }
spec.source_files = 'HBShare/Classes/*.{h,m}', 'HBShare/Vendors/*.h'
spec.requires_arc = true
spec.ios.deployment_target = '6.0'
spec.ios.vendored_library = 'HBShare/Vendors/libWeChatSDK.a'
spec.requires_arc = true
spec.ios.deployment_target = '6.0'
end
|
module ActiveAdmin
module Iconic
ICONS = {
arrow_down: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M32,16.016l-5.672-5.664c0,0-3.18,3.18-6.312,6.312V0h-8.023v16.664l-6.32-6.32L0,16.016L16,32 L32,16.016z"/></svg>',
arrow_down_alt1: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><path fill="{fill}" d="M32,16c0-8.835-7.164-16-16-16S0,7.165,0,16c0,8.837,7.164,16,16,16S32,24.837,32,16z M8,16.031h6V8h4v8.031 h5.969L16,24L8,16.031z"/></svg>',
arrow_down_alt2: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="arrow_x5F_up_x5F_alt2_x5F_32x32"> <path fill="{fill}"d="M32,16c0-8.836-7.165-16-16-16C7.163,0,0,7.164,0,16s7.163,16,16,16C24.835,32,32,24.836,32,16z M12,22h2V6h4v16h2l-4,4 L12,22z"/></g></svg>',
arrow_left: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M15.984,32l5.672-5.672c0,0-3.18-3.18-6.312-6.312H32v-8.023H15.344l6.312-6.32L15.984,0L0,16 L15.984,32z"/></svg>',
arrow_left_alt1: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><path fill="{fill}" d="M16,32.001c8.834,0,16-7.164,16-16c0-8.836-7.165-16-16-16c-8.837,0-16,7.164-16,16 C0,24.837,7.164,32.001,16,32.001z M15.969,8v6H24v4h-8.031v5.969L8,16L15.969,8z"/></svg>',
arrow_left_alt2: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="arrow_x5F_left_x5F_alt2_x5F_32x32"> <path fill="{fill}"d="M16,32c8.837,0,16-7.164,16-16S24.837,0,16,0C7.165,0,0,7.164,0,16S7.165,32,16,32z M10,12v2h16v4H10v2l-4-4L10,12z"/></g></svg>',
arrow_right: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 31.999" style="enable-background:new 0 0 32 31.999;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M16.016,0l-5.668,5.672c0,0,3.18,3.18,6.312,6.312H0v8.023h16.66l-6.316,6.319l5.672,5.672L32,16 L16.016,0z"/></svg>',
arrow_right_alt1: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><path fill="{fill}" d="M16.001,0.002c-8.834,0-16,7.164-16,16s7.165,16,16,16c8.837,0,16-7.163,16-16S24.838,0.002,16.001,0.002z M16.032,24.003v-6H8.001v-4.001h8.031V8.033l7.969,7.969L16.032,24.003z"/></svg>',
arrow_right_alt2: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="arrow_x5F_right_x5F_alt2_x5F_32x32"> <path fill="{fill}"d="M16,0C7.165,0,0,7.164,0,16s7.165,16,16,16c8.837,0,16-7.164,16-16S24.837,0,16,0z M22,20v-2H6v-4h16v-2l4,4L22,20z"/></g></svg>',
arrow_up: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32.005" style="enable-background:new 0 0 32 32.005;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M0,15.984l5.672,5.667c0,0,3.18-3.178,6.312-6.315v16.669h8.023V15.336l6.32,6.325L32,15.984L16,0 L0,15.984z"/></svg>',
arrow_up_alt1: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><path fill="{fill}" d="M0.001,16.002c0,8.834,7.164,16,16,16c8.836,0,15.999-7.165,15.999-16c0-8.837-7.163-16-15.999-16 C7.166,0.002,0.001,7.166,0.001,16.002z M24.002,15.971h-6v8.031h-4v-8.031H8.033l7.969-7.969L24.002,15.971z"/></svg>',
arrow_up_alt2: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="arrow_x5F_down_x5F_alt2_x5F_32x32"> <path fill="{fill}"d="M0,16c0,8.836,7.163,16,16,16c8.835,0,16-7.164,16-16S24.835,0,16,0C7.163,0,0,7.164,0,16z M20,10h-2v16h-4V10h-2l4-4 L20,10z"/></g></svg>',
article: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <polygon style="{style}" points="32,4 0,4 0,0 32,0 32,4 "/> <polygon style="{style}" points="20,12 0,12 0,8 20,8 20,12 "/> <polygon style="{style}" points="32,24 0,24 0,20 32,20 32,24 "/> <polygon style="{style}" points="24,32 0,32 0,28 24,28 24,32 "/> <path fill="{fill}"style="{style}" d="M32,30c0,1.104-0.898,2-2,2c-1.109,0-2.004-0.896-2.004-2s0.895-2,2.004-2 C31.102,28,32,28.896,32,30z"/></g></svg>',
at: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="ampersand_x5F_32x32"> <path fill="{fill}" d="M29.844,24C31.214,21.646,32,18.922,32,16c0-8.836-7.164-16-16-16S0,7.164,0,16s7.164,16,16,16 c4.417,0,8.417-1.789,11.312-4.688l-2.833-2.833C22.308,26.656,19.308,28,16,28C9.383,28,4,22.617,4,16S9.383,4,16,4 s12,5.383,12,12c0,1.422-0.273,2.781-0.734,4.047L27.234,20H24V8.042h-8c-4.422,0-8,3.583-8,8c0,4.419,3.578,8,8,8 c1.836,0,3.508-0.644,4.859-1.683C21.586,23.328,22.695,24,24,24H29.844z M20,14.008v2.034c0,2.208-1.797,4-4,4s-4-1.792-4-4 c0-2.206,1.797-4,4-4h4V14.008z"/></g></svg>',
battery_charging: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 16" enable-background="new 0 0 32 16" xml:space="preserve"><path fill="{fill}"d="M28,4V2c0-1.099-0.897-2-2-2H2C0.899,0,0,0.901,0,2v4.043h6.391c0.821-2.324,3.02-4,5.629-4V4h3.984v2H12.02v4h4.067v2 H12.02v2.043c-2.609,0-4.808-1.676-5.629-4H0V14c0,1.1,0.899,2,2,2h24c1.103,0,2-0.9,2-2v-2h4V4H28z"/></svg>',
battery_empty: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 16" enable-background="new 0 0 32 16" xml:space="preserve"><path fill="{fill}"d="M32,4h-4V2c0-1.099-0.897-2-2-2H2C0.899,0,0,0.901,0,2v12c0,1.099,0.899,2,2,2h24c1.103,0,2-0.901,2-2v-2h4V4z M24,12H4V4 h20V12z"/></svg>',
battery_full: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 16" enable-background="new 0 0 32 16" xml:space="preserve"><path fill="{fill}"d="M32,4h-4V2c0-1.099-0.897-2-2-2H2C0.899,0,0,0.901,0,2v12c0,1.102,0.899,2,2,2h24c1.103,0,2-0.898,2-2v-2h4V4z"/></svg>',
battery_half: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 16" enable-background="new 0 0 32 16" xml:space="preserve"><path fill="{fill}"d="M32,4h-4V2c0-1.099-0.897-2-2-2H2C0.899,0,0,0.901,0,2v12c0,1.1,0.899,2,2,2h24c1.103,0,2-0.9,2-2v-2h4V4z M24,12h-8V4h8V12 z"/></svg>',
beaker: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 16 32" style="enable-background:new 0 0 16 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M14,0H2C0.895,0,0,0.896,0,2v22c0,4.417,3.582,8,8,8s8-3.583,8-8V2C16,0.896,15.105,0,14,0z M10,24 c-1.105,0-2-0.896-2-2s0.895-2,2-2s2,0.896,2,2S11.105,24,10,24z M12,16h-1.945c-0.016-1.104-0.914-2-2.023-2s-2.008,0.896-2.023,2 H4V4h8V16z"/></svg>',
beaker_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 16 32" style="enable-background:new 0 0 16 32;" xml:space="preserve"><g> <circle style="{style}" cx="9" cy="9" r="0.969"/> <path fill="{fill}"style="{style}" d="M14,0H2C0.895,0,0,0.896,0,2v22c0,4.417,3.582,8,8,8s8-3.583,8-8V2C16,0.896,15.105,0,14,0z M5.031,20c-0.535,0-0.969-0.433-0.969-0.969s0.434-0.969,0.969-0.969S6,18.495,6,19.031S5.566,20,5.031,20z M10,24 c-1.105,0-2-0.896-2-2s0.895-2,2-2s2,0.896,2,2S11.105,24,10,24z M12,16h-1.945c-0.016-1.104-0.914-2-2.023-2s-2.008,0.896-2.023,2 H4V4h8V16z"/></g></svg>',
bolt: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="bolt_x5F_32x32"> <polygon fill="{fill}" points="32,0 8,16 14,20 0,32 24,20 18,16 "/></g></svg>',
book: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 28 32" style="enable-background:new 0 0 28 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M4,0C1.792,0,0,1.792,0,4v24c0,2.209,1.792,4,4,4h24V0H4z M24,28H8V4h3.984v8.039l4-4l4.031,4.031V4 H24V28z"/></svg>',
book_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 31.969" style="enable-background:new 0 0 32 31.969;" xml:space="preserve"><g> <rect x="11.99" y="7.992" style="{style}" width="7.99" height="4.028"/> <path fill="{fill}"style="{style}" d="M27.975,8.039L32,4.011h-4.025V0H3.996C1.787,0,0,1.789,0,3.995v23.979 c0,2.206,1.787,3.995,3.996,3.995h23.979V12.036h3.994L27.975,8.039z M23.975,27.974H7.99V3.995h15.984V27.974z"/></g></svg>',
box: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="box_x5F_32x32"> <g> <rect y="12" fill="{fill}" width="32" height="20"/> <polygon fill="{fill}" points="18,8 32,8 28,0 18,0 "/> <polygon fill="{fill}" points="14,0 4,0 0,8 14,8 "/> </g></g></svg>',
calendar: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <polygon style="{style}" points="23.918,4 23.918,0 19.918,0 19.918,4 11.918,4 11.918,0 7.918,0 7.918,4 0,4 0,8 7.918,8 11.918,8 19.918,8 23.918,8 32,8 32,4 "/> <rect x="4" y="20" style="{style}" width="24" height="4"/> <rect x="4" y="12" style="{style}" width="24" height="4"/> <polygon style="{style}" points="24,32 4,32 4,28 28,28 "/></g></svg>',
calendar_alt_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M26,4v2.047c0,2.211-1.789,4-4,4s-4-1.789-4-4V4h-4v2.047c0,2.211-1.789,4-4,4s-4-1.789-4-4V4H0v28 h32V4H26z M10,28H6v-4h4V28z M10,20H6v-4h4V20z M18,28h-4v-4h4V28z M18,20.008h-4v-4h4V20.008z M22,28v-4h4L22,28z M26,20h-4v-4h4 V20z"/> <path fill="{fill}"style="{style}" d="M8,6V2c0-1.104,0.895-2,2-2s2,0.896,2,2v4c0,1.104-0.895,2-2,2S8,7.104,8,6z"/> <path fill="{fill}"style="{style}" d="M20,6V2c0-1.104,0.895-2,2-2s2,0.896,2,2v4c0,1.104-0.895,2-2,2S20,7.104,20,6z"/></g></svg>',
calendar_alt_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <polygon style="{style}" points="32,32 0,32 0,4 4,4 4,28 28,28 28,4 32,4 32,32 "/> <rect x="6" y="12" style="{style}" width="4" height="4"/> <rect x="14" y="12.008" style="{style}" width="4" height="4"/> <rect x="22" y="12" style="{style}" width="4" height="4"/> <rect x="6" y="20" style="{style}" width="4" height="4"/> <rect x="14" y="20" style="{style}" width="4" height="4"/> <polygon style="{style}" points="22,24 22,20 26,20 "/> <path fill="{fill}"style="{style}" d="M8,6V2c0-1.104,0.895-2,2-2s2,0.896,2,2v4c0,1.104-0.895,2-2,2S8,7.104,8,6z"/> <path fill="{fill}"style="{style}" d="M20,6V2c0-1.104,0.895-2,2-2s2,0.896,2,2v4c0,1.104-0.895,2-2,2S20,7.104,20,6z"/></g></svg>',
cd: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <g> <path fill="{fill}"style="{style}" d="M16,0C7.164,0,0,7.164,0,16s7.164,16,16,16s16-7.164,16-16S24.836,0,16,0z M16.031,19.934 c-2.188,0-3.965-1.773-3.965-3.965c0-2.195,1.777-3.969,3.965-3.969C18.227,12,20,13.773,20,15.969 C20,18.16,18.227,19.934,16.031,19.934z"/> </g></g></svg>',
chat: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="chat_x5F_32x32"> <path fill="{fill}" d="M24,12V8c0-5.523-4-8-8-8H8C4,0,0,2.125,0,8c0,5.75,4,8,8,8h0.926C8.359,17.099,8,18.406,8,20v4 c0,4.418,3.582,8,8,8c0-2.209,1.797-4,4-4h4c4,0,8-2.25,8-8C32,14.125,28,12,24,12z M8,12c-4,0-4-3.012-4-4c0-1.199,0-4,4-4h8 c1.5,0,4,0.52,4,4v4c0,1.307-0.625,2.471-1.609,3.2C16.931,13.258,14.609,12,12,12H8z M24,24h-4c-2.609,0-4.938,1.258-6.397,3.199 C12.629,26.469,12,25.305,12,24v-4c0-1.831,0.91-2.941,1.816-3.512C15.098,17.156,16,18.457,16,20c2.957,0,5.509-1.621,6.895-4.004 c-0.004,0.001-0.004,0.001-0.004,0.004H24c4,0,4,2.802,4,4C28,20.989,28,24,24,24z M23.719,13.994 c-0.027,0.092-0.059,0.182-0.085,0.271C23.66,14.176,23.696,14.086,23.719,13.994z"/></g></svg>',
chat_alt_fill: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="chat_x5F_alt_x5F_fill_x5F_32x32"> <g> <g> <path fill="{fill}" d="M24,12c0,4.418-3.578,8-8,8c0-2.207-1.793-4-4-4H8c-4,0-8-2.25-8-8c0-5.875,4-8,8-8h8c4,0,8,2.479,8,8V12 z"/> </g> <path fill="{fill}" d="M12,12"/> <path fill="{fill}" d="M12,12"/> <g> <g> <path fill="{fill}" d="M25.984,12.213C25.863,17.625,21.438,22,16,22h-2v-2c0-1.104-0.897-2-2-2H8.203 C8.078,18.619,8,19.281,8,20v4c0,4.418,3.582,8,8,8c0-2.209,1.797-4,4-4h4c4,0,8-2.25,8-8C32,15.106,29.219,12.84,25.984,12.213 z"/> </g> </g> </g></g></svg>',
chat_alt_stroke: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="chat_x5F_alt_x5F_stroke_x5F_32x32"> <g> <g> <path fill="{fill}" d="M25.978,12.213c-0.024,1.386-0.337,2.695-0.884,3.889C27.978,16.582,28,18.93,28,20c0,0.989,0,4-3.996,4 H20c-2.605,0-4.938,1.258-6.397,3.2C12.634,26.471,12,25.307,12,24v-4c0-0.792,0.141-1.414,0.359-1.928 C12.243,18.051,12.125,18,12,18H8.203c-0.125,0.619-0.199,1.281-0.199,2v4c0,4.418,3.578,8,7.996,8c0-2.209,1.79-4,4-4h4.004 C28,28,32,25.75,32,20C32,15.106,29.219,12.84,25.978,12.213z"/> </g> <path fill="{fill}" d="M16,4c1.493,0,4,0.52,4,4v4c0,1.309-0.632,2.471-1.601,3.2C16.938,13.26,14.609,12,12,12H8.004 C4,12,4,8.989,4,8c0-1.195,0-4,4.004-4H16 M16,0H8.004C4,0,0,2.125,0,8c0,5.75,4,8,8.004,8H12c2.212,0,4,1.793,4,4 c4.422,0,8.004-3.582,8.004-8V8C24.004,2.479,20,0,16,0L16,0z"/> </g></g></svg>',
check: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 25.754" style="enable-background:new 0 0 32 25.754;" xml:space="preserve"><g> <polygon style="{style}" points="11.941,25.754 0,13.812 5.695,8.117 11.941,14.363 26.305,0 32,5.695 11.941,25.754 "/></g></svg>',
check_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M16,0C7.164,0,0,7.164,0,16s7.164,16,16,16s16-7.164,16-16S24.836,0,16,0z M13.52,23.383L6.16,16.02 l2.828-2.828l4.532,4.535l9.617-9.618l2.828,2.828L13.52,23.383z"/></svg>',
clock: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M16,4c6.617,0,12,5.383,12,12s-5.383,12-12,12S4,22.617,4,16S9.383,4,16,4 M16,0 C7.164,0,0,7.164,0,16s7.164,16,16,16s16-7.164,16-16S24.836,0,16,0L16,0z"/> <path fill="{fill}"style="{style}" d="M21.422,18.578L18,15.152V8h-4.023v7.992c0,0.602,0.277,1.122,0.695,1.493l3.922,3.922 L21.422,18.578z"/></g></svg>',
cloud: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 20" enable-background="new 0 0 32 20" xml:space="preserve"><path fill="{fill}" d="M24,4c-0.379,0-0.738,0.062-1.103,0.11C21.507,1.648,18.929,0,16,0c-2.988,0-5.566,1.665-6.941,4.101 C8.71,4.054,8.355,4,8,4c-4.41,0-8,3.586-8,8c0,4.414,3.59,8,8,8h16c4.413,0,8-3.586,8-8C32,7.586,28.413,4,24,4z M24,16H8 c-2.207,0-4-1.797-4-4c0-2.195,1.944-3.883,4.007-3.945C8.012,9,8.179,9.922,8.507,10.797l3.743-1.399C12.085,8.953,12,8.484,12,8 c0-2.204,1.793-4,4-4c1.293,0,2.465,0.641,3.199,1.64C17.272,7.101,16,9.395,16,12h4c0-2.204,1.793-4,4-4c2.21,0,4,1.796,4,4 C28,14.203,26.21,16,24,16z"/></svg>',
cog: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M32,20v-8h-4.734c-0.141-0.391-0.289-0.771-0.469-1.146l3.344-3.339l-5.656-5.661l-3.344,3.344 C20.777,5.026,20.375,4.933,20,4.792V0h-8v4.792c-0.383,0.141-0.781,0.234-1.145,0.406l-3.34-3.344l-5.66,5.661l3.34,3.339 C5.02,11.229,4.871,11.609,4.734,12H0v8h4.734c0.137,0.391,0.285,0.771,0.461,1.146l-3.34,3.339l5.66,5.661l3.34-3.344 c0.363,0.172,0.762,0.266,1.145,0.406V32h8v-4.792c0.375-0.141,0.777-0.234,1.141-0.406l3.344,3.344l5.656-5.661l-3.344-3.339 c0.18-0.375,0.328-0.755,0.469-1.146H32z M16,20.083c-2.211,0-4-1.791-4-4c0-2.208,1.789-4,4-4c2.207,0,4,1.792,4,4 C20,18.292,18.207,20.083,16,20.083z"/></svg>',
cog_alt: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="cog_x5F_alt_x5F_32x32"> <path fill="{fill}" d="M32,17.969v-4l-4.781-1.992c-0.133-0.375-0.273-0.737-0.445-1.094l1.93-4.805L25.875,3.25l-4.763,1.961 c-0.362-0.175-0.734-0.323-1.117-0.461L17.969,0h-4l-1.977,4.734c-0.398,0.141-0.781,0.289-1.161,0.469L6.078,3.294L3.25,6.122 l1.938,4.711C5,11.219,4.847,11.614,4.703,12.021L0,14.031v4l4.706,1.961c0.146,0.406,0.302,0.802,0.489,1.188l-1.903,4.742 L6.12,28.75l4.724-1.945c0.378,0.18,0.766,0.325,1.164,0.461L14.031,32h4l1.979-4.758c0.38-0.141,0.755-0.289,1.114-0.461 l4.797,1.922l2.828-2.828l-1.969-4.773c0.167-0.359,0.305-0.722,0.438-1.094L32,17.969z M15.969,22c-3.312,0-6-2.688-6-6 s2.688-6,6-6s6,2.688,6,6S19.281,22,15.969,22z"/></g></svg>',
comment_alt1_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M0,19.992C0,26.626,5.375,32,12.008,32v-4.015c0-2.203,1.789-4,4-4h3.996 C26.625,23.985,32,18.624,32,11.999S26.625,0,20.004,0h-9.996c-5.52,0-9.996,4.47-9.996,9.999v9.993H0z"/></g></svg>',
comment_alt1_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M20.004,8c2.203,0,4,1.789,4,3.995c0,2.203-1.797,3.997-4,3.997h-3.996c-3.07,0-5.875,1.164-8,3.062 v-9.06c0-1.104,0.898-1.995,2-1.995H20.004 M20.004,0h-9.996c-5.52,0-9.996,4.477-9.996,9.995v9.997H0C0,26.625,5.375,32,12.008,32 v-4.008c0-2.211,1.789-4,4-4h3.996C26.625,23.992,32,18.617,32,11.995C32,5.37,26.625,0,20.004,0L20.004,0z"/></svg>',
comment_alt2_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32.001 24.002" style="enable-background:new 0 0 32.001 24.002;" xml:space="preserve"><g> <g> <path fill="{fill}"style="{style}" d="M29.938,20.002c0,0,2.062-4.001,2.062-8.001C32.001,2,24.005,0,16.005,0 C-6.37,0,0.011,20.002,4.011,24.002c4-4,4-4,9.996-4H29.938z"/> </g></g></svg>',
comment_alt2_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" style="enable-background:new 0 0 32 24;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M16,4c11.074,0,12,4.129,12,8c0,1.344-0.359,2.805-0.75,4H14c-4.703,0-6.734,0.195-9,1.758 c-0.938-2.572-1.535-6.046-0.375-8.84C5.975,5.656,9.803,4,16,4 M16,0C-6.369,0,0.012,20,4.006,24c4-4,4-4,9.994-4h15.938 c0,0,2.062-4,2.062-8C32,2,24,0,16,0L16,0z"/></g></svg>',
comment_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 28" style="enable-background:new 0 0 32 28;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M0,20c0,4.417,3.586,8,8,8c0-2.211,1.792-4,4-4h8c6.629,0,12-5.375,12-12S26.629,0,20,0H10 C4.477,0,0,4.477,0,10V20z"/></g></svg>',
comment_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 28" style="enable-background:new 0 0 32 28;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M20,4c4.414,0,8,3.586,8,8s-3.586,8-8,8h-8c-2.609,0-4.933,1.258-6.394,3.203 C4.633,22.469,4,21.305,4,20V10c0-3.308,2.695-6,6-6H20 M20,0H10C4.477,0,0,4.477,0,10v10c0,4.417,3.586,8,8,8c0-2.211,1.793-4,4-4 h8c6.629,0,12-5.375,12-12S26.629,0,20,0L20,0z"/></svg>',
compass: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g> <path fill="{fill}"d="M16,4c6.618,0,12,5.383,12,12s-5.382,12-12,12C9.384,28,4,22.617,4,16S9.384,4,16,4 M16,0C7.165,0,0,7.164,0,16 s7.165,16,16,16c8.837,0,16-7.164,16-16S24.837,0,16,0L16,0z"/> <g> <path fill="{fill}"d="M18.125,13.879c0.797,0.798,1.009,1.93,0.719,2.944L24,8l-8.703,5.138C16.281,12.896,17.359,13.109,18.125,13.879z"/> <path fill="{fill}"d="M13.884,18.121c-0.774-0.771-0.984-1.85-0.743-2.836L8,24l8.832-5.16C15.816,19.133,14.688,18.922,13.884,18.121z"/> </g></g></svg>',
cursor: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="cursor_x5F_32x32"> <polygon fill="{fill}" points="32,28 18,14 24,8 0,0 8,23.995 14,17.995 28,32 "/></g></svg>',
denied: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M16,0C7.164,0,0,7.164,0,16s7.164,16,16,16s16-7.164,16-16S24.836,0,16,0z M16,4 c2.59,0,4.973,0.844,6.934,2.242L6.238,22.93C4.84,20.969,4,18.586,4,16C4,9.383,9.383,4,16,4z M16,28 c-2.59,0-4.973-0.844-6.934-2.242L25.762,9.07C27.16,11.031,28,13.414,28,16C28,22.617,22.617,28,16,28z"/></svg>',
denied_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M16,0C7.164,0,0,7.164,0,16c0,8.836,7.164,16,16,16s16-7.164,16-16C32,7.164,24.836,0,16,0z M16,8 c0.711,0,1.387,0.121,2.043,0.297l-9.742,9.75C8.121,17.391,8,16.71,8,16C8,11.586,11.59,8,16,8z M16,24 c-0.711,0-1.387-0.125-2.043-0.297l9.742-9.75C23.879,14.609,24,15.289,24,16C24,20.414,20.41,24,16,24z"/></svg>',
dial: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 31.828" enable-background="new 0 0 32 31.828" xml:space="preserve"><g id="{id}"></g><g id="dial_x5F_32x32"> <g> <path fill="{fill}" d="M16,11.828c-2.21,0-4,1.79-4,4c0,2.208,1.79,4,4,4c2.212,0,4-1.793,4-4C20,13.617,18.212,11.828,16,11.828 z"/> <path fill="{fill}" d="M28.556,6.047c-0.344,0.281-0.766,0.469-1.243,0.469c-1.101,0-2-0.895-2-2 c0-0.488,0.196-0.918,0.484-1.266c-2.219-1.711-4.906-2.864-7.835-3.227C17.859,1.031,17.04,1.828,16,1.828 c-1.038,0-1.871-0.808-1.96-1.828c-2.969,0.382-5.672,1.555-7.911,3.324C6.384,3.66,6.562,4.062,6.562,4.516c0,1.105-0.891,2-2,2 c-0.444,0-0.844-0.176-1.179-0.426C1.297,8.796,0,12.145,0,15.828c0,8.836,7.165,16,16,16c8.837,0,16-7.164,16-16 C32,12.113,30.688,8.746,28.556,6.047z M16,23.828c-4.418,0-8-3.582-8-8c0-2.211,0.895-4.208,2.344-5.657L16,4.515l5.649,5.645 C23.103,11.613,24,13.613,24,15.828C24,20.246,20.415,23.828,16,23.828z"/> </g></g></svg>',
document_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M21.609,0H0v32l7.977-6.641L15.992,32L24,25.37L32,32V10.301L21.609,0z M18,14V4l10,10H18z"/></svg>',
document_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32.023" style="enable-background:new 0 0 32 32.023;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M22.016,0H0v31.961l8.053-6.582l8.016,6.645l8.016-6.637L32,32.008v-22L22.016,0z M28.021,23.955 l-3.953-3.229c0,0-0.041,0.034-0.104,0.086l-7.896,6.535L8.09,20.734l-4.084,3.221c0,0,0-17.373,0-20.016c2.1,0,7.807,0,12.006,0 v12.01h12.01C28.021,18.682,28.021,23.955,28.021,23.955z M20.016,11.945c0-1.543,0-5.918,0-8.006 c1.615,1.619,6.402,6.404,8.006,8.006C25.975,11.945,21.568,11.945,20.016,11.945z"/></svg>',
eject: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <polygon style="{style}" points="0,20 16,0 32,20 "/> <rect y="24" style="{style}" width="31.955" height="8"/></g></svg>',
equalizer: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M20,20h-2V2c0-1.105-0.891-2-2-2c-1.102,0-2,0.895-2,2v18h-2v4h2v6c0,1.105,0.898,2,2,2 c1.109,0,2-0.895,2-2v-6h2V20z"/> <path fill="{fill}"style="{style}" d="M32,8h-2V2c0-1.105-0.891-2-2-2c-1.102,0-2,0.895-2,2v6h-2v4h2v18c0,1.105,0.898,2,2,2 c1.109,0,2-0.895,2-2V12h2V8z"/> <path fill="{fill}"style="{style}" d="M8,12H6V2c0-1.105-0.891-2-2-2C2.898,0,2,0.895,2,2v10H0v4h2v14c0,1.105,0.898,2,2,2 c1.109,0,2-0.895,2-2V16h2V12z"/></g></svg>',
eyedropper: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="eyedropper_x5F_32x32"> <path fill="{fill}" d="M29.658,13.684c3.123-3.118,3.123-8.18,0-11.297c-1.555-1.559-3.602-2.34-5.643-2.34 c-2.045,0-4.092,0.781-5.649,2.34l-0.592,0.59L14.798,0l-2.82,2.823l2.977,2.974L0,20.761v7.247L3.931,32h7.414l14.907-14.906 l2.875,2.878l2.82-2.82l-2.875-2.878L29.658,13.684z M10.321,27.365c0.047-1.511-0.477-3.033-1.627-4.186 c-1.061-1.06-2.443-1.582-3.834-1.629L17.782,8.628l5.642,5.638L10.321,27.365z"/></g></svg>',
first: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <polygon style="{style}" points="32,32 8,16 32,0 "/> <rect y="4" style="{style}" width="8" height="24"/></g></svg>',
folder_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g> <path fill="{fill}" d="M32,30c0,1.105-0.891,2-2,2H2c-1.105,0-2-0.895-2-2V12h32V30z"/> <polygon fill="{fill}" points="12,4.003 12,0 0,0 0,8 32,8 32,4.003 "/></g></svg>',
folder_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><path fill="{fill}" d="M16,4V0H0v12.004v3.375V28c0,2.211,1.79,4,4,4h24c2.207,0,4-1.789,4-4V16.004v-4V4H16z M12,4L12,4v4h4h12v4 H4V4H12z M28,28H4V16h24v0.004V28z"/></svg>',
fork: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 28 32" enable-background="new 0 0 28 32" xml:space="preserve"><g> <path fill="{fill}"d="M20,0v3.875c0,1.602-0.625,3.109-1.755,4.239L6.93,19.367C5.141,21.151,4.156,23.495,4.047,26H0l6,6l6-6H8.042 c0.106-1.438,0.685-2.773,1.708-3.805l11.32-11.25C22.961,9.055,24,6.547,24,3.875V0H20z"/> <path fill="{fill}"d="M23.953,26c-0.109-2.505-1.099-4.849-2.891-6.641l-2.227-2.214L16,19.964l2.242,2.231c1.031,1.028,1.609,2.367,1.711,3.805 H16l6,6l6-6H23.953z"/></g></svg>',
fullscreen: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="fullscreen_x5F_32x32"> <g> <polygon fill="{fill}" points="27.414,24.586 22.828,20 20,22.828 24.586,27.414 20,32 32,32 32,20 "/> <polygon fill="{fill}" points="12,0 0,0 0,12 4.586,7.414 9.125,11.953 11.953,9.125 7.414,4.586 "/> <polygon fill="{fill}" points="12,22.828 9.172,20 4.586,24.586 0,20 0,32 12,32 7.414,27.414 "/> <polygon fill="{fill}" points="32,0 20,0 24.586,4.586 20.042,9.125 22.87,11.953 27.414,7.414 32,12 "/> </g></g></svg>',
fullscreen_alt: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="fullscreen_x5F_alt_x5F_32x32"> <g> <polygon fill="{fill}" points="29.414,26.586 22.828,20 20,22.828 26.586,29.414 24,32 32,32 32,24 "/> <polygon fill="{fill}" points="2.586,5.414 9.172,12 12,9.172 5.414,2.586 8,0 0,0 0,8 "/> <polygon fill="{fill}" points="26.586,2.586 20,9.172 22.828,12 29.414,5.414 32,8 32,0 24,0 "/> <polygon fill="{fill}" points="12,22.828 9.172,20 2.586,26.586 0,24 0,32 8,32 5.414,29.414 "/> </g></g></svg>',
fullscreen_exit: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="fullscreen_x5F_exit_x5F_32x32"> <g> <polygon fill="{fill}" points="24.586,27.414 29.172,32 32,29.172 27.414,24.586 32,20 20,20 20,32 "/> <polygon fill="{fill}" points="0,12 12,12 12,0 7.414,4.586 2.875,0.043 0.047,2.871 4.586,7.414 "/> <polygon fill="{fill}" points="0,29.172 2.828,32 7.414,27.414 12,32 12,20 0,20 4.586,24.586 "/> <polygon fill="{fill}" points="20,12 32,12 27.414,7.414 31.961,2.871 29.133,0.043 24.586,4.586 20,0 "/> </g></g></svg>',
fullscreen_exit_alt: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="fullscreen_x5F_exit_x5F_alt_x5F_32x32"> <g> <polygon fill="{fill}" points="22.586,25.414 29.172,32 32,29.172 25.414,22.586 28,20 20,20 20,28 "/> <polygon fill="{fill}" points="6.547,9.371 4,12 11.961,11.957 12,4 9.375,6.543 2.828,0 0,2.828 "/> <polygon fill="{fill}" points="0,29.172 2.828,32 9.414,25.414 12,28 12,20 4,20 6.586,22.586 "/> <polygon fill="{fill}" points="28.031,12 25.438,9.404 32,2.838 29.164,0 22.594,6.566 20,3.971 20,12 "/> </g></g></svg>',
headphones: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 28" style="enable-background:new 0 0 32 28;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M30,16h-2v-4c0-6.627-5.375-12-12-12S4,5.373,4,12v4H2c-1.105,0-2,0.895-2,2v8c0,1.105,0.895,2,2,2h6 V16v-4c0-4.411,3.586-8,8-8s8,3.589,8,8v4v12h6c1.104,0,2-0.895,2-2v-8C32,16.895,31.104,16,30,16z"/></svg>',
heart_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 28" style="enable-background:new 0 0 32 28;" xml:space="preserve"><g> <g> <path fill="{fill}"style="{style}" d="M16,3.844C14.387,1.578,11.871,0,8.887,0C3.984,0,0,3.992,0,8.891v0.734L16.006,28L32,9.625V8.891 C32,3.992,28.016,0,23.115,0C20.131,0,17.615,1.578,16,3.844z"/> </g></g></svg>',
heart_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 28" style="enable-background:new 0 0 32 28;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M23.115,4c2.453,0,4.49,1.82,4.834,4.188L16.006,21.906L4.053,8.188C4.396,5.82,6.428,4,8.887,4 c2.016,0,3.854,2.164,3.854,2.164L16,9.625l3.256-3.461C19.256,6.164,21.1,4,23.115,4 M23.115,0c-2.984,0-5.5,1.578-7.115,3.844 C14.387,1.578,11.871,0,8.887,0C3.984,0,0,3.992,0,8.891v0.734L16.006,28L32,9.625V8.891C32,3.992,28.016,0,23.115,0L23.115,0z"/></g></svg>',
home: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="home_x5F_32x32"> <path fill="{fill}" d="M16,0L0,16h4v16h24V16h4L16,0z M24,28h-6v-6h-4v6H8V13.656L16,8l8,5.656V28z"/></g></svg>',
image: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <polygon style="{style}" points="8,24 8,16 12,12 16,16 24,8 32,16 32,24 "/> <polygon style="{style}" points="4,28 4,0 0,4 0,28 0,32 4,32 28,32 32,28 "/></g></svg>',
info: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 16 32" enable-background="new 0 0 16 32" xml:space="preserve"><g id="{id}"></g><g id="Layer_21"> <g> <path fill="{fill}" d="M2,16c1.104,0,2,0.895,2,2v8c0,1.105-0.896,2-2,2H0v4h16v-4h-1.992c-1.102,0-2-0.895-2-2L12,12H0v4H2z"/> <circle fill="{fill}" cx="8" cy="4" r="4"/> </g></g></svg>',
iphone: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 24 32" style="enable-background:new 0 0 24 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M16,0H8C3.582,0,0,3.582,0,8v16c0,4.418,3.582,8,8,8h8c4.418,0,8-3.582,8-8V8C24,3.582,20.418,0,16,0 z M12,30.062c-1.138,0-2.062-0.924-2.062-2.062s0.924-2.062,2.062-2.062c1.139,0,2.062,0.924,2.062,2.062S13.139,30.062,12,30.062z M20,24H4V8c0-2.206,1.794-4,4-4h8c2.205,0,4,1.794,4,4V24z"/></svg>',
key_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <g> <path fill="{fill}"style="{style}" d="M22,0c-5.523,0-10,4.477-10,10c0,0.623,0.074,1.227,0.184,1.816L0,24v8h12v-4h4v-4h4v-4 l0.184-0.184C20.773,19.926,21.379,20,22,20c5.523,0,10-4.477,10-10S27.523,0,22,0z M22.008,12c-1.105,0-2-0.895-2-2s0.895-2,2-2 s2,0.895,2,2S23.113,12,22.008,12z"/> </g></g></svg>',
key_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M22,4c3.309,0,6,2.691,6,6s-2.691,6-6,6c-0.312,0-0.658-0.039-1.088-0.117L18.844,15.5l-1.488,1.488 l-0.184,0.184L16,18.344V20h-4v4H8v4H4v-2.344l11.012-11.012l1.488-1.488l-0.383-2.07C16.038,10.657,16,10.312,16,10 C16,6.691,18.691,4,22,4 M22,0c-5.523,0-10,4.477-10,10c0,0.625,0.074,1.227,0.184,1.816L0,24v8h12v-4h4v-4h4v-4l0.184-0.184 C20.773,19.926,21.377,20,22,20c5.523,0,10-4.477,10-10S27.523,0,22,0L22,0z"/> <circle style="{style}" cx="22.008" cy="10" r="2"/></g></svg>',
last: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <polygon style="{style}" points="0,0 24,16 0,32 "/> <rect x="24" y="4" style="{style}" width="8" height="24"/></g></svg>',
left_quote: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" enable-background="new 0 0 32 24" xml:space="preserve"><g id="{id}"></g><g id="left_x5F_quote_x5F_32x32"> <g> <path fill="{fill}" d="M32,24V12h-8c0-4.411,3.587-8,8-8V0c-6.616,0-12,5.383-12,12v12H32z"/> <path fill="{fill}" d="M12,24V12H4c0-4.411,3.587-8,8-8V0C5.384,0,0,5.383,0,12v12H12z"/> </g></g></svg>',
left_quote_alt: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" enable-background="new 0 0 32 24" xml:space="preserve"><g id="{id}"></g><g id="left_x5F_quote_x5F_alt_x5F_32x32"> <g> <polygon fill="{fill}" points="32,24 32,0 20,12 20,24 "/> <polygon fill="{fill}" points="12,24 12,0 0,12 0,24 "/> </g></g></svg>',
lightbulb: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 20.051 32" style="enable-background:new 0 0 20.051 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M10.024,4.007c3.32,0,6.019,2.7,6.019,6.017c0,1.894-0.867,3.636-2.379,4.773 c-2.266,1.707-3.18,3.593-3.496,5.179H9.883c-0.313-1.586-1.23-3.473-3.493-5.179c-1.515-1.137-2.382-2.879-2.382-4.773 C4.008,6.707,6.707,4.007,10.024,4.007 M10.024,0C4.488,0,0,4.488,0,10.024c0,3.28,1.547,6.147,3.977,7.976 c1.121,0.844,2.042,1.93,2.042,3.43v2.555h8.012V21.43c0-1.5,0.922-2.586,2.043-3.43c2.43-1.829,3.977-4.696,3.977-7.976 C20.051,4.488,15.562,0,10.024,0L10.024,0z"/> <rect x="6.02" y="27.992" style="{style}" width="8.012" height="4.008"/></g></svg>',
link: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="link_x5F_32x32"> <g> <path fill="{fill}" d="M31.414,0.586c-0.781-0.781-2.047-0.781-2.828,0l-4.071,4.073C22.847,3.553,20.921,3,18.999,3 c-2.559,0-5.116,0.977-7.069,2.93l-6,6c-3.422,3.42-3.844,8.703-1.274,12.584l-4.069,4.072c-0.781,0.781-0.781,2.047,0,2.828 C0.977,31.805,1.487,32,1.999,32c0.516,0,1.024-0.195,1.415-0.586l4.069-4.072C9.155,28.447,11.077,29,12.999,29 c2.562,0,5.118-0.977,7.071-2.93l6-6c3.422-3.419,3.844-8.703,1.272-12.583l4.071-4.073C32.195,2.633,32.195,1.367,31.414,0.586z M24.999,13c0,1.602-0.625,3.109-1.757,4.242l-6,6C16.108,24.375,14.602,25,12.999,25c-0.906,0-1.772-0.221-2.569-0.602 l2.984-2.984c0.781-0.781,0.781-2.047,0-2.828s-2.047-0.781-2.828,0L7.602,21.57C7.218,20.775,6.999,19.908,6.999,19 c0-1.602,0.625-3.109,1.759-4.242l6-6C15.89,7.625,17.398,7,18.999,7c0.906,0,1.774,0.221,2.571,0.602l-3.047,3.047 c-0.781,0.781-0.781,2.047,0,2.828c0.391,0.391,0.901,0.586,1.413,0.586c0.516,0,1.024-0.195,1.415-0.586l3.047-3.047 C24.78,11.225,24.999,12.092,24.999,13z"/> </g></g></svg>',
lock_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 24.006 32" style="enable-background:new 0 0 24.006 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M14.006,0c-5.508,0-10,4.485-10,10v2H0v14c0,3.309,2.693,6,6,6h12.006c3.307,0,6-2.691,6-6V10 C24.006,4.485,19.516,0,14.006,0z M12,24c-1.104,0-2-0.895-2-2s0.896-2,2-2c1.107,0,2,0.895,2,2S13.107,24,12,24z M20.006,12h-12v-2 c0-3.309,2.695-6,6-6c3.307,0,6,2.691,6,6V12z"/></svg>',
lock_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 24.008 32" style="enable-background:new 0 0 24.008 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M14.008,0c-5.512,0-10,4.484-10,10v2H0v14c0,3.305,2.695,6,6,6h12.008c3.312,0,6-2.695,6-6V10 C24.008,4.484,19.523,0,14.008,0z M8.008,10c0-3.312,2.695-6,6-6c3.312,0,6,2.688,6,6v2h-12V10z M18.008,28H6c-1.102,0-2-0.898-2-2 V16h16.008v10C20.008,27.102,19.113,28,18.008,28z"/> <path fill="{fill}"style="{style}" d="M14.008,22c0,1.102-0.898,2-2,2c-1.109,0-2-0.898-2-2c0-1.109,0.891-2,2-2 C13.109,20,14.008,20.891,14.008,22z"/></g></svg>',
loop: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 31.999 32" style="enable-background:new 0 0 31.999 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M9.804,3.677l-5.803,5.8V3.841H0v11.997h12.001v-4H7.298l5.335-5.333 c3.387-3.391,9.307-3.391,12.701,0l2.828-2.828C23.261-1.229,14.708-1.222,9.804,3.677z"/> <path fill="{fill}"style="{style}" d="M19.999,16.033v4h4.703l-5.336,5.338c-3.389,3.395-9.307,3.395-12.701,0l-2.829,2.824 C6.287,30.648,9.55,32,13.021,32c3.469,0,6.725-1.352,9.174-3.805l5.805-5.803v5.639h4V16.033H19.999z"/></g></svg>',
loop_alt1: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" enable-background="new 0 0 32 24" xml:space="preserve"><g> <path fill="{fill}"d="M26,12l-6,6h4c0,1.102-0.897,2-2,2H10c-1.101,0-2-0.898-2-2v-2H4v2c0,3.308,2.691,6,6,6h12c3.312,0,6-2.692,6-6h4L26,12z" /> <path fill="{fill}"d="M22,0H10C6.691,0,4,2.692,4,6v0.062H0L6,12l6-5.938H8V6c0-1.102,0.899-2,2-2h12c1.103,0,2,0.898,2,2v2h4V6 C28,2.692,25.312,0,22,0z"/></g></svg>',
loop_alt2: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 28" enable-background="new 0 0 32 28" xml:space="preserve"><g> <path fill="{fill}"d="M19.946,20l6.007-8L32,20h-4v2c0,3.308-2.688,6-6,6H10c-3.309,0-6-2.692-6-6v-2h4v2c0,1.102,0.899,2,2,2h12 c1.103,0,2-0.898,2-2v-2H19.946z"/> <path fill="{fill}"d="M12.056,8l-6.009,8L0,8h4V6c0-3.308,2.691-6,6-6h12c3.312,0,6,2.692,6,6v2h-4V6c0-1.102-0.897-2-2-2H10 C8.899,4,8,4.898,8,6v2H12.056z"/></g></svg>',
loop_alt3: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" enable-background="new 0 0 32 24" xml:space="preserve"><g> <path fill="{fill}"d="M28,12v2c0,1.102-0.897,2-2,2H12v-4l-8,6l8,6v-4h14c3.312,0,6-2.695,6-6v-2H28z"/> <path fill="{fill}"d="M4,10c0-1.104,0.899-2,2-2h14v4l7.993-6L20,0v4H6c-3.309,0-6,2.688-6,6v2h4V10z"/></g></svg>',
loop_alt4: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" enable-background="new 0 0 32 24" xml:space="preserve"><g> <path fill="{fill}"d="M28,14c0,1.102-0.899,2-2,2H7.991v-4L0,18l7.991,6v-4H26c3.309,0,6-2.695,6-6H28z"/> <path fill="{fill}"d="M6,8h18v4l8-6l-8-6v4H6c-3.306,0-6,2.688-6,6h4C4,8.896,4.897,8,6,8z"/></g></svg>',
magnifying_glass: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M20.135,0C13.594,0,8.273,5.32,8.273,11.864c0,1.565,0.32,3.05,0.867,4.422L0,25.43L6.572,32 l9.146-9.148c1.367,0.555,2.854,0.875,4.416,0.875c6.537,0,11.865-5.32,11.865-11.862C32,5.32,26.672,0,20.135,0z M6.572,26.352 c-0.432-0.438-0.494-0.492-0.922-0.922c1.271-1.269,3.828-3.836,5.686-5.688c0.289,0.328,0.596,0.633,0.914,0.922 C10.4,22.516,7.844,25.078,6.572,26.352z M20.135,19.729c-4.338,0-7.869-3.526-7.869-7.865c0-4.338,3.531-7.869,7.869-7.869 c4.334,0,7.865,3.531,7.865,7.869C28,16.203,24.469,19.729,20.135,19.729z"/></svg>',
magnifying_glass_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 31.992 32" style="enable-background:new 0 0 31.992 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M20.127,0C13.594,0,8.268,5.32,8.268,11.864c0,1.565,0.326,3.05,0.873,4.417L0,25.427L6.57,32 l9.148-9.151c1.361,0.553,2.846,0.875,4.408,0.875c6.545,0,11.865-5.322,11.865-11.859C31.992,5.32,26.672,0,20.127,0z M20.127,19.727c-4.33,0-7.861-3.531-7.861-7.862c0-4.338,3.531-7.869,7.861-7.869c4.342,0,7.873,3.531,7.873,7.869 C28,16.195,24.469,19.727,20.127,19.727z"/></g></svg>',
mail: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" style="enable-background:new 0 0 32 24;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M0,0v24h32V0H0z M24.859,4l-7.445,7.445c-0.781,0.781-2.047,0.781-2.828,0L7.141,4H24.859z M4,20 V6.516l7.758,7.758c1.172,1.172,2.703,1.758,4.242,1.758s3.07-0.586,4.242-1.758L28,6.516V20H4z"/></svg>',
mail_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" enable-background="new 0 0 32 24" xml:space="preserve"><g> <polygon fill="{fill}" points="16.078,11.457 32,3.918 32,0 0,0 0,3.903 "/> <polygon fill="{fill}" points="16.087,15.879 0,8.322 0,24 32,24 32,8.344 "/></g></svg>',
map_pin_fill: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 20 32" enable-background="new 0 0 20 32" xml:space="preserve"><g id="{id}"></g><g id="map_x5F_pin_x5F_fill_x5F_32x32"> <g> <g> <path fill="{fill}" d="M17.07,2.93c-3.906-3.906-10.234-3.906-14.141,0c-3.906,3.904-3.906,10.237,0,14.141 C2.93,17.07,10,24,10,32c0-8,7.07-14.93,7.07-14.93C20.977,13.167,20.977,6.833,17.07,2.93z M10,14.005c-2.211,0-4-1.789-4-4 s1.789-4,4-4s4,1.789,4,4S12.211,14.005,10,14.005z"/> </g> </g></g></svg>',
map_pin_stroke: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 20 32" enable-background="new 0 0 20 32" xml:space="preserve"><g id="{id}"></g><g id="map_x5F_pin_x5F_stroke_x5F_32x32"> <g> <path fill="{fill}" d="M10,4c1.602,0,3.109,0.625,4.242,1.76C15.375,6.891,16,8.398,16,10s-0.625,3.109-1.734,4.213 c-0.164,0.166-2.234,2.224-4.266,5.441c-2.023-3.211-4.086-5.261-4.242-5.415C4.625,13.109,4,11.602,4,10s0.625-3.109,1.758-4.242 S8.398,4,10,4 M10,0C7.438,0,4.883,0.977,2.93,2.93c-3.906,3.904-3.906,10.237,0,14.141C2.93,17.07,10,24,10,32 c0-8,7.07-14.93,7.07-14.93c3.906-3.904,3.906-10.237,0-14.141C15.117,0.977,12.558,0,10,0L10,0z"/> <path fill="{fill}" d="M12,10c0,1.105-0.896,2-2,2c-1.109,0-2-0.895-2-2s0.891-2,2-2C11.104,8,12,8.895,12,10z"/> </g></g></svg>',
minus: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 8" style="enable-background:new 0 0 32 8;" xml:space="preserve"><rect style="{style}" width="32" height="8"/></svg>',
minus_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><path fill="{fill}" d="M16,0C7.165,0,0,7.164,0,16s7.165,16,16,16c8.837,0,16-7.164,16-16S24.837,0,16,0z M24,18H8v-4h16V18z"/></svg>',
moon_fill: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="moon_x5F_fill_x5F_32x32"> <g> <path fill="{fill}" d="M24.633,22.184c-8.188,0-14.82-6.637-14.82-14.82c0-2.695,0.773-5.188,2.031-7.363 C5.016,1.969,0,8.188,0,15.645C0,24.676,7.32,32,16.352,32c7.456,0,13.68-5.023,15.648-11.844 C29.82,21.41,27.328,22.184,24.633,22.184z"/> </g></g></svg>',
moon_stroke: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="moon_x5F_stroke_x5F_32x32"> <path fill="{fill}" d="M5.891,9.148c0.852,8.959,8,16.109,16.961,16.953C20.938,27.311,18.698,28,16.352,28 C9.539,28,4,22.459,4,15.646C4,13.3,4.688,11.059,5.891,9.148 M11.844,0C5.016,1.969,0,8.19,0,15.646C0,24.678,7.32,32,16.352,32 c7.456,0,13.68-5.021,15.648-11.844c-2.18,1.256-4.672,2.029-7.367,2.029c-8.188,0-14.82-6.636-14.82-14.82 C9.812,4.67,10.586,2.178,11.844,0L11.844,0z"/></g></svg>',
move: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="move_x5F_32x32"> <g> <polygon fill="{fill}" points="18,20 18,26 22,26 16,32 10,26 14,26 14,20 "/> <polygon fill="{fill}" points="14,12 14,6 10,6 16,0 22,6 18,6 18,12 "/> <polygon fill="{fill}" points="12,18 6,18 6,22 0,16 6,10 6,14 12,14 "/> <polygon fill="{fill}" points="20,14 26,14 26,10 32,16 26,22 26,18 20,18 "/> </g></g></svg>',
move_alt1: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="move_x5F_alt1_x5F_32x32"> <g> <polygon fill="{fill}" points="16,22 18,20 18,26 22,26 16,32 10,26 14,26 14,20 "/> <polygon fill="{fill}" points="16,10.062 14,12 14,6 10,6 16,0 22,6 18,6 18,12 "/> <polygon fill="{fill}" points="10,16 12,18 6,18 6,22 0,16 6,10 6,14 12,14 "/> <polygon fill="{fill}" points="21.938,16 20,14 26,14 26,10 32,16 26,22 26,18 20,18 "/> </g></g></svg>',
move_alt2: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="move_x5F_alt2_x5F_32x32"> <path fill="{fill}"fill="5E6469" d="M16,0C7.165,0,0,7.164,0,16s7.165,16,16,16c8.837,0,16-7.164,16-16S24.837,0,16,0z M22,20v-2h-4v4h2l-4,4l-4-4h2v-4h-4v2 l-4-4l4-4v2h4v-4h-2l4-4l4,4h-2v4h4v-2l4,4L22,20z"/></g></svg>',
move_horizontal: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 12" enable-background="new 0 0 32 12" xml:space="preserve"><g id="Layer_1_1_"></g><g id="move_x5F_horizontal_x5F_12x32"> <g> <polygon fill="{fill}" points="12,8 6,8 6,12 0,6 6,0 6,4 12,4 "/> <polygon fill="{fill}" points="20,4 26,4 26,0 32,6 26,12 26,8 20,8 "/> </g></g></svg>',
move_horizontal_alt1: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 12" enable-background="new 0 0 32 12" xml:space="preserve"><g id="{id}"></g><g id="move_x5F_horizontal_x5F_alt1_x5F_12x32"> <g> <polygon fill="{fill}" points="10,6 12,8 6,8 6,12 0,6 6,0 6,4 12,4 "/> <polygon fill="{fill}" points="21.938,6 20,4 26,4 26,0 32,6 26,12 26,8 20,8 "/> </g></g></svg>',
move_horizontal_alt2: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="move_x5F_horizontal_x5F_alt2_x5F_32x32"> <path fill="{fill}" d="M32,16c0-8.836-7.163-16-16-16C7.165,0,0,7.164,0,16s7.165,16,16,16C24.837,32,32,24.836,32,16z M10,18v2 l-4-4l4-4v2h12v-2l4,4l-4,4v-2H10z"/></g></svg>',
move_vertical: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 12 32" enable-background="new 0 0 12 32" xml:space="preserve"><g id="{id}"></g><g id="move_x5F_vertical_x5F_12x32"> <g> <polygon fill="{fill}" points="8,20 8,26 12,26 6,32 0,26 4,26 4,20 "/> <polygon fill="{fill}" points="4,12 4,6 0,6 6,0 12,6 8,6 8,12 "/> </g></g></svg>',
move_vertical_alt1: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 12 32" enable-background="new 0 0 12 32" xml:space="preserve"><g id="{id}"></g><g id="move_x5F_vertical_x5F_alt1_x5F_12x32"> <g> <polygon fill="{fill}" points="6,22 8,20 8,26 12,26 6,32 0,26 4,26 4,20 "/> <polygon fill="{fill}" points="6,10.062 4,12 4,6 0,6 6,0 12,6 8,6 8,12 "/> </g></g></svg>',
move_vertical_alt2: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="move_x5F_vertical_x5F_alt2_x5F_32x32"> <path fill="{fill}" d="M16,0C7.165,0,0,7.164,0,16s7.165,16,16,16c8.837,0,16-7.164,16-16S24.837,0,16,0z M18,22h2l-4,4l-4-4h2V10 h-2l4-4l4,4h-2V22z"/></g></svg>',
movie: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><path fill="{fill}"d="M27.977,8h-3.95L28,4.016L24.073,0h-5.565l3.987,3.984L18.409,8h-4.722l4.058-3.984L13.734,0H8.078l3.984,3.984L7.977,8 H3.969l4.062-3.984L4.016,0H0v32h32V0h-3.922L32,4L27.977,8z M28,27.958H4v-4h24V27.958z M28,20H4v-4h24V20z"/></svg>',
new_window: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M32,0H8v7.998c-2.906,0-8,0-8,0.002v24h24v-8h8V0z M20,28H4V16h4v8h12C20,25.791,20,27.998,20,28z M28,20H12V8h16V20z"/></svg>',
pause: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 24 32" style="enable-background:new 0 0 24 32;" xml:space="preserve"><g> <rect style="{style}" width="8" height="32"/> <rect x="16" style="{style}" width="8" height="32"/></g></svg>',
pen: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32.004" style="enable-background:new 0 0 32 32.004;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M29.656,2.344C28.1,0.781,26.053,0,24,0c-2.047,0-4.094,0.781-5.656,2.344L0.031,20.657L0,32.004 h11.312l18.344-18.347C32.781,10.535,32.781,5.468,29.656,2.344z M9.656,28.001H8v-4H4.021l0.006-1.681L21.172,5.172l0,0 l5.656,5.656v0L9.656,28.001z"/></svg>',
pen_alt_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32.002" style="enable-background:new 0 0 32 32.002;" xml:space="preserve"><g> <g> <path fill="{fill}"style="{style}" d="M29.656,2.344c-3.119-3.125-8.191-3.125-11.312,0L0.031,20.656L0,32.002h11.312l18.344-18.346 C32.781,10.534,32.781,5.467,29.656,2.344z M9.609,28.002H3.953v-5.689c1.562-1.562,4.094-1.562,5.656,0 C11.172,23.877,11.172,26.439,9.609,28.002z M26.756,10.828L21.1,5.172c1.562-1.562,4.094-1.562,5.656,0 S28.318,9.266,26.756,10.828z"/> </g></g></svg>',
pen_alt_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32.002" style="enable-background:new 0 0 32 32.002;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M29.656,2.344C28.094,0.781,26.047,0,24,0s-4.094,0.781-5.656,2.344L0.031,20.656L0,32.002h11.312 l18.344-18.346C32.781,10.534,32.781,5.466,29.656,2.344z M9.656,28H9.609c1.562-1.562,1.562-4.125,0-5.688 c-1.494-1.496-3.859-1.517-5.426-0.149L21.137,5.211l5.656,5.655L9.656,28z"/></svg>',
pin: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="pin_x5F_32x32"> <path fill="{fill}" d="M32,8c0-4.417-3.585-8-8-8c-2.984,0-5.562,1.659-6.938,4.086c0-0.002,0.004-0.004,0.004-0.005 c-0.363-0.036-0.723-0.112-1.098-0.112c-6.625,0-12,5.371-12,12c0,2.527,0.79,4.865,2.125,6.799L0,32l9.29-6.064 c1.913,1.283,4.21,2.033,6.679,2.033c6.629,0,12-5.371,12-12c0-0.346-0.069-0.669-0.101-1.008C30.321,13.594,32,11.005,32,8z M15.969,23.969c-4.413,0-8-3.588-8-8c0-4.412,3.587-8,8-8c0.016,0,0.024,0.004,0.031,0.004c0-0.008,0.004-0.014,0.004-0.02 C16.004,7.969,16,7.984,16,8c0,0.695,0.118,1.355,0.281,1.998l-3.172,3.174c-1.562,1.562-1.562,4.094,0,5.656s4.094,1.562,5.656,0 l3.141-3.141c0.66,0.18,1.344,0.305,2.062,0.309C23.953,20.396,20.375,23.969,15.969,23.969z M24,12c-2.203,0-4-1.794-4-4 s1.797-4,4-4s4,1.794,4,4S26.203,12,24,12z"/></g></svg>',
play: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 24 32" style="enable-background:new 0 0 24 32;" xml:space="preserve"><polygon style="{style}" points="0,0 24,16 0,32 "/></svg>',
play_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M16,0C7.164,0,0,7.164,0,16s7.164,16,16,16s16-7.164,16-16S24.836,0,16,0z M10,24V8l16.008,8L10,24z" /></svg>',
plus: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><polygon style="{style}" points="32,12 20,12 20,0 12,0 12,12 0,12 0,20 12,20 12,32 20,32 20,20 32,20 "/></svg>',
plus_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><path fill="{fill}" d="M16,0C7.165,0,0,7.164,0,16s7.165,16,16,16c8.837,0,16-7.164,16-16S24.837,0,16,0z M24,18h-6v6h-4v-6H8v-4h6 V8h4v6h6V18z"/></svg>',
read_more: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <polygon style="{style}" points="32,4 0,4 0,0 32,0 32,4 "/> <polygon style="{style}" points="20,12 0,12 0,8 20,8 20,12 "/> <polygon style="{style}" points="32,20.086 0,20.086 0,16.086 32,16.086 32,20.086 "/> <circle style="{style}" cx="2" cy="30" r="2"/> <path fill="{fill}"style="{style}" d="M12,30c0,1.104-0.898,2-2,2c-1.109,0-2.004-0.896-2.004-2S8.891,28,10,28C11.102,28,12,28.896,12,30 z"/> <circle style="{style}" cx="18" cy="30" r="2"/></g></svg>',
reload: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 24 28" style="enable-background:new 0 0 24 28;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M20,16c0,4.41-3.586,8-8,8s-8-3.59-8-8s3.586-8,8-8l2.359,0.027l-1.164,1.164l2.828,2.828L22.035,6 l-6.012-6l-2.828,2.828L14.375,4H12C5.375,4,0,9.371,0,16s5.375,12,12,12s12-5.371,12-12H20z"/></g></svg>',
reload_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 24 28" style="enable-background:new 0 0 24 28;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M20,16c0,4.414-3.586,8-8,8s-8-3.586-8-8s3.586-8,8-8l4.023,0.043v3.977L22.035,6l-6.012-6v4H12 C5.375,4,0,9.375,0,16s5.375,12,12,12s12-5.375,12-12H20z"/></g></svg>',
right_quote: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" enable-background="new 0 0 32 24" xml:space="preserve"><g id="{id}"></g><g id="right_x5F_quote_x5F_32x32"> <g> <path fill="{fill}" d="M0,0v12h8c0,4.411-3.585,8-8,8v4c6.618,0,12-5.383,12-12V0H0z"/> <path fill="{fill}" d="M20,0v12h8c0,4.411-3.585,8-8,8v4c6.618,0,12-5.383,12-12V0H20z"/> </g></g></svg>',
right_quote_alt: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" enable-background="new 0 0 32 24" xml:space="preserve"><g id="{id}"></g><g id="right_x5F_quote_x5F_alt_x5F_32x32"> <g> <polygon fill="{fill}" points="0,0 0,24 12,12 12,0 "/> <polygon fill="{fill}" points="20,0 20,24 32,12 32,0 "/> </g></g></svg>',
rss: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <circle style="{style}" cx="4.001" cy="28" r="4.001"/> <g> <path fill="{fill}"style="{style}" d="M6.023,20.004c3.309,0,6,2.691,6,6.004h4.001C16.025,20.492,11.538,16,6.023,16V20.004z"/> </g> <g> <path fill="{fill}"style="{style}" d="M5.996,12c7.719,0,14.002,6.285,14.002,14.007h4C23.998,16.078,15.923,8,5.996,8V12z"/> </g> <g> <path fill="{fill}"style="{style}" d="M5.996,4C18.129,4,28,13.871,28,26.008h4C32,11.665,20.334,0,5.996,0V4z"/> </g></g></svg>',
rss_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g> <path fill="{fill}"d="M32,32h-4.569C27.431,16.875,15.125,4.573,0,4.573V0C17.641,0,32,14.355,32,32L32,32z"/> <path fill="{fill}"d="M22.859,32h-4.574c0-10.082-8.207-18.285-18.285-18.285V9.143C12.603,9.143,22.859,19.398,22.859,32L22.859,32z"/> <path fill="{fill}"d="M13.719,32H9.141c0-5.043-4.094-9.143-9.141-9.143v-4.572C7.562,18.285,13.719,24.438,13.719,32L13.719,32z"/> <path fill="{fill}"d="M4.571,32c0-2.523-2.04-4.57-4.571-4.57V32H4.571z"/></g></svg>',
spin: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 28 32" enable-background="new 0 0 28 32" xml:space="preserve"><g id="{id}"></g><g id="reload_x5F_alt2_x5F_28x32"> <g> <path fill="{fill}"d="M23.883,6.086l-2.82,2.831C22.953,10.808,24,13.323,24,16c0,5.516-4.484,10-10,10v-2l-4,4l4,4v-2c7.719,0,14-6.281,14-14 C28,12.255,26.539,8.734,23.883,6.086z"/> <path fill="{fill}"d="M18,4l-4-4v2C6.281,2,0,8.281,0,16c0,3.745,1.461,7.266,4.117,9.914l2.82-2.831C5.047,21.192,4,18.677,4,16 C4,10.484,8.484,6,14,6v2L18,4z"/> </g></g></svg>',
spin_alt: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="reload_x5F_alt3_x5F_32x32"> <g> <path fill="{fill}"d="M4.688,27.32C1.664,24.297,0,20.281,0,16C0,7.18,7.172,0,16,0l2,2l-2,2C9.383,4,4,9.383,4,16 c0,3.211,1.25,6.227,3.516,8.492l-2.453,0.32L4.688,27.32L4.688,27.32z"/> <path fill="{fill}"d="M16,32l-2-1.992L16,28c6.617,0,12-5.383,12-12c0-3.203-1.25-6.219-3.523-8.489l2.461-0.323l0.367-2.505 C30.328,7.708,32,11.727,32,16C32,24.82,24.82,32,16,32L16,32z"/> </g></g></svg>',
star: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="star_x5F_32x32"> <g> <polygon fill="{fill}" points="22.136,19.625 32,12 20,12 16,0 12,12 0,12 9.875,19.594 6,32 16.016,24.32 26.008,32 "/> </g></g></svg>',
stop: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><rect style="{style}" width="32" height="32"/></svg>',
sun: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="sun_x5F_32x32"> <g> <path fill="{fill}" d="M24,16c0,4.417-3.585,8-8,8c-4.422,0-8-3.583-8-8s3.578-8,8-8C20.415,8,24,11.583,24,16z"/> <path fill="{fill}" d="M16,3.312c1.384,0,2.691,0.276,3.938,0.688H20l-4-4l-4,4h0.056C13.306,3.589,14.613,3.312,16,3.312z"/> <path fill="{fill}" d="M16,28.688c-1.387,0-2.694-0.276-3.944-0.688H12l4,4l4-4h-0.062C18.691,28.411,17.384,28.688,16,28.688z" /> <path fill="{fill}" d="M28.688,16c0,1.383-0.281,2.695-0.688,3.942V20l4-4l-4-4v0.058C28.406,13.305,28.688,14.617,28.688,16z"/> <path fill="{fill}" d="M3.312,16c0-1.383,0.274-2.695,0.688-3.942V12l-4,4l4,4v-0.058C3.587,18.695,3.312,17.383,3.312,16z"/> <path fill="{fill}" d="M24.969,24.969c-0.976,0.984-2.101,1.711-3.272,2.305l-0.04,0.039h5.656v-5.656l-0.043,0.042 C26.681,22.87,25.953,23.992,24.969,24.969z"/> <path fill="{fill}" d="M7.031,7.031c0.978-0.984,2.094-1.711,3.266-2.305l0.047-0.039H4.688v5.656l0.04-0.042 C5.321,9.13,6.047,8.008,7.031,7.031z"/> <path fill="{fill}" d="M7.031,24.969c-0.984-0.977-1.71-2.099-2.304-3.271l-0.04-0.042v5.656h5.656l-0.047-0.039 C9.125,26.68,8.009,25.953,7.031,24.969z"/> <path fill="{fill}" d="M24.969,7.031c0.984,0.977,1.712,2.099,2.301,3.271l0.043,0.042V4.688h-5.656l0.04,0.039 C22.868,5.32,23.993,6.047,24.969,7.031z"/> </g></g></svg>',
tag_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M13.277,0H0v13.277L18.719,32V18.723H32L13.277,0z M7.312,11.121c-2.102,0-3.805-1.703-3.805-3.805 s1.703-3.805,3.805-3.805s3.805,1.703,3.805,3.805S9.414,11.121,7.312,11.121z"/></svg>',
tag_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M11.699,8.613c0,1.703-1.383,3.086-3.082,3.086c-1.703,0-3.086-1.383-3.086-3.086 c0-1.699,1.383-3.078,3.086-3.078C10.316,5.535,11.699,6.914,11.699,8.613z"/> <g> <path fill="{fill}"style="{style}" d="M0,0v13.273L18.727,32c0,0,0-10.793,0-13.27c2.477,0,13.273,0,13.273,0L13.273,0H0z M11.797,3.562 c0.773,0.77,7.879,7.883,11.602,11.605c-3.102,0-8.234,0-8.234,0s0,5.133,0,8.227C11.441,19.676,4.336,12.566,3.562,11.801 c0-1.055,0-5.961,0-8.238C5.84,3.562,10.742,3.562,11.797,3.562z"/> </g></g></svg>',
trash_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M28,4h-4c0-2.211-1.789-4-4-4h-8C9.789,0,8,1.789,8,4H4H0v4h4v18c0,3.312,2.688,6,6,6h12 c3.312,0,6-2.688,6-6V8h4V4H28z M12,24c-1.105,0-2-0.896-2-2s0.895-2,2-2s2,0.896,2,2S13.105,24,12,24z M12,16c-1.105,0-2-0.896-2-2 s0.895-2,2-2s2,0.896,2,2S13.105,16,12,16z M20,24c-1.105,0-2-0.896-2-2s0.895-2,2-2s2,0.896,2,2S21.105,24,20,24z M20,16 c-1.105,0-2-0.896-2-2s0.895-2,2-2s2,0.896,2,2S21.105,16,20,16z"/></svg>',
trash_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M32,4h-4h-4c0-2.211-1.789-4-4-4h-8C9.789,0,8,1.789,8,4H4H0v4h4v18c0,3.312,2.688,6,6,6h12 c3.312,0,6-2.688,6-6V8h4V4z M24,26c0,1.102-0.898,2-2,2H10c-1.102,0-2-0.898-2-2V8h16V26z"/> <circle style="{style}" cx="12" cy="22" r="2"/> <circle style="{style}" cx="12" cy="14" r="2"/> <circle style="{style}" cx="20" cy="22" r="2"/> <circle style="{style}" cx="20" cy="14" r="2"/></g></svg>',
undo: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 31.985" style="enable-background:new 0 0 32 31.985;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M28.156,3.72c-4.957-4.958-13.604-4.961-18.557,0L4,9.32V4.001H0v12h12v-4H6.975l5.453-5.453 c3.447-3.445,9.453-3.445,12.9,0.007C27.053,8.274,28,10.563,28,13.001s-0.947,4.727-2.672,6.453l-3.016,3.008l2.828,2.828 l3.016-3.008C30.631,19.805,32,16.508,32,13.001C32,9.493,30.631,6.196,28.156,3.72z"/> <rect x="16.449" y="27.157" transform="matrix(0.7071 0.7071 -0.7071 0.7071 26.0209 -4.5056)" style="{style}" width="4" height="4"/></g></svg>',
unlock_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 24.008 32" style="enable-background:new 0 0 24.008 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M14.008,0c-5.516,0-10,4.487-10,10h4c0-3.309,2.688-6,6-6c3.305,0,6,2.691,6,6v2H0v14 c0,3.308,2.695,6,6,6h12.008c3.305,0,6-2.692,6-6V10C24.008,4.487,19.518,0,14.008,0z M12,24c-1.102,0-2-0.896-2-2 c0-1.105,0.898-2,2-2c1.109,0,2,0.895,2,2C14,23.104,13.109,24,12,24z"/></svg>',
unlock_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 24.008 32" style="enable-background:new 0 0 24.008 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M14.008,0c-5.516,0-10,4.489-10,10h4c0-3.305,2.691-6,6-6s6,2.695,6,6v2H0v14c0,3.312,2.691,6,6,6 h12.008c3.309,0,6-2.688,6-6V10C24.008,4.489,19.523,0,14.008,0z M18.008,28H6c-1.102,0-2-0.896-2-2V16h16.008v10 C20.008,27.104,19.109,28,18.008,28z"/> <path fill="{fill}"style="{style}" d="M14.004,22c0,1.109-0.895,2-2,2s-2-0.891-2-2c0-1.102,0.895-2,2-2S14.004,20.898,14.004,22z"/></g></svg>',
user: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 24 32" style="enable-background:new 0 0 24 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M12,16C5.375,16,0,21.372,0,28c0,2.208,1.789,4,4,4h16c2.211,0,4-1.792,4-4 C24,21.372,18.625,16,12,16z"/> <circle style="{style}" cx="12" cy="6" r="6"/></g></svg>',
volume: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" style="enable-background:new 0 0 32 24;" xml:space="preserve"><g> <g> <path fill="{fill}"style="{style}" d="M8,20c-4.416,0-8-3.579-8-8s3.584-8,8-8V20z"/> </g> <g> <polygon style="{style}" points="12,4 20,0 20,24 12,20 "/> </g> <path fill="{fill}"style="{style}" d="M24.006,19.999v-4c0.328,0,0.666-0.046,1-0.125C26.762,15.423,28,13.829,28,12 s-1.238-3.422-3.01-3.874c-0.318-0.078-0.656-0.118-0.984-0.118v-4c0.656,0,1.312,0.085,1.953,0.241C29.521,5.155,32,8.336,32,12 c0,3.671-2.479,6.858-6.025,7.751C25.309,19.914,24.652,19.999,24.006,19.999L24.006,19.999z"/></g></svg>',
volume_mute: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" style="enable-background:new 0 0 32 24;" xml:space="preserve"><g> <g> <path fill="{fill}"style="{style}" d="M8,20c-4.418,0-8-3.583-8-8s3.582-8,8-8V20z"/> </g> <g> <polygon style="{style}" points="12,4 20,0 20,24 12,20 "/> </g> <polygon style="{style}" points="32,14 24,14 24,10 32,10 32,14 "/></g></svg>',
x: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 28 28" style="enable-background:new 0 0 28 28;" xml:space="preserve"><g> <polygon style="{style}" points="28,22.398 19.594,14 28,5.602 22.398,0 14,8.402 5.598,0 0,5.602 8.398,14 0,22.398 5.598,28 14,19.598 22.398,28 "/></g></svg>',
x_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M16,0C7.164,0,0,7.164,0,16s7.164,16,16,16s16-7.164,16-16S24.836,0,16,0z M23.914,21.086 l-2.828,2.828L16,18.828l-5.086,5.086l-2.828-2.828L13.172,16l-5.086-5.086l2.828-2.828L16,13.172l5.086-5.086l2.828,2.828 L18.828,16L23.914,21.086z"/></svg>',
}
end
end
align all SVG strings
module ActiveAdmin
module Iconic
ICONS = {
arrow_down: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M32,16.016l-5.672-5.664c0,0-3.18,3.18-6.312,6.312V0h-8.023v16.664l-6.32-6.32L0,16.016L16,32 L32,16.016z"/></svg>',
arrow_down_alt1: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><path fill="{fill}" d="M32,16c0-8.835-7.164-16-16-16S0,7.165,0,16c0,8.837,7.164,16,16,16S32,24.837,32,16z M8,16.031h6V8h4v8.031 h5.969L16,24L8,16.031z"/></svg>',
arrow_down_alt2: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="arrow_x5F_up_x5F_alt2_x5F_32x32"> <path fill="{fill}"d="M32,16c0-8.836-7.165-16-16-16C7.163,0,0,7.164,0,16s7.163,16,16,16C24.835,32,32,24.836,32,16z M12,22h2V6h4v16h2l-4,4 L12,22z"/></g></svg>',
arrow_left: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M15.984,32l5.672-5.672c0,0-3.18-3.18-6.312-6.312H32v-8.023H15.344l6.312-6.32L15.984,0L0,16 L15.984,32z"/></svg>',
arrow_left_alt1: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><path fill="{fill}" d="M16,32.001c8.834,0,16-7.164,16-16c0-8.836-7.165-16-16-16c-8.837,0-16,7.164-16,16 C0,24.837,7.164,32.001,16,32.001z M15.969,8v6H24v4h-8.031v5.969L8,16L15.969,8z"/></svg>',
arrow_left_alt2: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="arrow_x5F_left_x5F_alt2_x5F_32x32"> <path fill="{fill}"d="M16,32c8.837,0,16-7.164,16-16S24.837,0,16,0C7.165,0,0,7.164,0,16S7.165,32,16,32z M10,12v2h16v4H10v2l-4-4L10,12z"/></g></svg>',
arrow_right: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 31.999" style="enable-background:new 0 0 32 31.999;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M16.016,0l-5.668,5.672c0,0,3.18,3.18,6.312,6.312H0v8.023h16.66l-6.316,6.319l5.672,5.672L32,16 L16.016,0z"/></svg>',
arrow_right_alt1: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><path fill="{fill}" d="M16.001,0.002c-8.834,0-16,7.164-16,16s7.165,16,16,16c8.837,0,16-7.163,16-16S24.838,0.002,16.001,0.002z M16.032,24.003v-6H8.001v-4.001h8.031V8.033l7.969,7.969L16.032,24.003z"/></svg>',
arrow_right_alt2: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="arrow_x5F_right_x5F_alt2_x5F_32x32"> <path fill="{fill}"d="M16,0C7.165,0,0,7.164,0,16s7.165,16,16,16c8.837,0,16-7.164,16-16S24.837,0,16,0z M22,20v-2H6v-4h16v-2l4,4L22,20z"/></g></svg>',
arrow_up: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32.005" style="enable-background:new 0 0 32 32.005;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M0,15.984l5.672,5.667c0,0,3.18-3.178,6.312-6.315v16.669h8.023V15.336l6.32,6.325L32,15.984L16,0 L0,15.984z"/></svg>',
arrow_up_alt1: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><path fill="{fill}" d="M0.001,16.002c0,8.834,7.164,16,16,16c8.836,0,15.999-7.165,15.999-16c0-8.837-7.163-16-15.999-16 C7.166,0.002,0.001,7.166,0.001,16.002z M24.002,15.971h-6v8.031h-4v-8.031H8.033l7.969-7.969L24.002,15.971z"/></svg>',
arrow_up_alt2: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="arrow_x5F_down_x5F_alt2_x5F_32x32"> <path fill="{fill}"d="M0,16c0,8.836,7.163,16,16,16c8.835,0,16-7.164,16-16S24.835,0,16,0C7.163,0,0,7.164,0,16z M20,10h-2v16h-4V10h-2l4-4 L20,10z"/></g></svg>',
article: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <polygon style="{style}" points="32,4 0,4 0,0 32,0 32,4 "/> <polygon style="{style}" points="20,12 0,12 0,8 20,8 20,12 "/> <polygon style="{style}" points="32,24 0,24 0,20 32,20 32,24 "/> <polygon style="{style}" points="24,32 0,32 0,28 24,28 24,32 "/> <path fill="{fill}"style="{style}" d="M32,30c0,1.104-0.898,2-2,2c-1.109,0-2.004-0.896-2.004-2s0.895-2,2.004-2 C31.102,28,32,28.896,32,30z"/></g></svg>',
at: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="ampersand_x5F_32x32"> <path fill="{fill}" d="M29.844,24C31.214,21.646,32,18.922,32,16c0-8.836-7.164-16-16-16S0,7.164,0,16s7.164,16,16,16 c4.417,0,8.417-1.789,11.312-4.688l-2.833-2.833C22.308,26.656,19.308,28,16,28C9.383,28,4,22.617,4,16S9.383,4,16,4 s12,5.383,12,12c0,1.422-0.273,2.781-0.734,4.047L27.234,20H24V8.042h-8c-4.422,0-8,3.583-8,8c0,4.419,3.578,8,8,8 c1.836,0,3.508-0.644,4.859-1.683C21.586,23.328,22.695,24,24,24H29.844z M20,14.008v2.034c0,2.208-1.797,4-4,4s-4-1.792-4-4 c0-2.206,1.797-4,4-4h4V14.008z"/></g></svg>',
battery_charging: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 16" enable-background="new 0 0 32 16" xml:space="preserve"><path fill="{fill}"d="M28,4V2c0-1.099-0.897-2-2-2H2C0.899,0,0,0.901,0,2v4.043h6.391c0.821-2.324,3.02-4,5.629-4V4h3.984v2H12.02v4h4.067v2 H12.02v2.043c-2.609,0-4.808-1.676-5.629-4H0V14c0,1.1,0.899,2,2,2h24c1.103,0,2-0.9,2-2v-2h4V4H28z"/></svg>',
battery_empty: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 16" enable-background="new 0 0 32 16" xml:space="preserve"><path fill="{fill}"d="M32,4h-4V2c0-1.099-0.897-2-2-2H2C0.899,0,0,0.901,0,2v12c0,1.099,0.899,2,2,2h24c1.103,0,2-0.901,2-2v-2h4V4z M24,12H4V4 h20V12z"/></svg>',
battery_full: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 16" enable-background="new 0 0 32 16" xml:space="preserve"><path fill="{fill}"d="M32,4h-4V2c0-1.099-0.897-2-2-2H2C0.899,0,0,0.901,0,2v12c0,1.102,0.899,2,2,2h24c1.103,0,2-0.898,2-2v-2h4V4z"/></svg>',
battery_half: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 16" enable-background="new 0 0 32 16" xml:space="preserve"><path fill="{fill}"d="M32,4h-4V2c0-1.099-0.897-2-2-2H2C0.899,0,0,0.901,0,2v12c0,1.1,0.899,2,2,2h24c1.103,0,2-0.9,2-2v-2h4V4z M24,12h-8V4h8V12 z"/></svg>',
beaker: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 16 32" style="enable-background:new 0 0 16 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M14,0H2C0.895,0,0,0.896,0,2v22c0,4.417,3.582,8,8,8s8-3.583,8-8V2C16,0.896,15.105,0,14,0z M10,24 c-1.105,0-2-0.896-2-2s0.895-2,2-2s2,0.896,2,2S11.105,24,10,24z M12,16h-1.945c-0.016-1.104-0.914-2-2.023-2s-2.008,0.896-2.023,2 H4V4h8V16z"/></svg>',
beaker_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 16 32" style="enable-background:new 0 0 16 32;" xml:space="preserve"><g> <circle style="{style}" cx="9" cy="9" r="0.969"/> <path fill="{fill}"style="{style}" d="M14,0H2C0.895,0,0,0.896,0,2v22c0,4.417,3.582,8,8,8s8-3.583,8-8V2C16,0.896,15.105,0,14,0z M5.031,20c-0.535,0-0.969-0.433-0.969-0.969s0.434-0.969,0.969-0.969S6,18.495,6,19.031S5.566,20,5.031,20z M10,24 c-1.105,0-2-0.896-2-2s0.895-2,2-2s2,0.896,2,2S11.105,24,10,24z M12,16h-1.945c-0.016-1.104-0.914-2-2.023-2s-2.008,0.896-2.023,2 H4V4h8V16z"/></g></svg>',
bolt: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="bolt_x5F_32x32"> <polygon fill="{fill}" points="32,0 8,16 14,20 0,32 24,20 18,16 "/></g></svg>',
book: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 28 32" style="enable-background:new 0 0 28 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M4,0C1.792,0,0,1.792,0,4v24c0,2.209,1.792,4,4,4h24V0H4z M24,28H8V4h3.984v8.039l4-4l4.031,4.031V4 H24V28z"/></svg>',
book_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 31.969" style="enable-background:new 0 0 32 31.969;" xml:space="preserve"><g> <rect x="11.99" y="7.992" style="{style}" width="7.99" height="4.028"/> <path fill="{fill}"style="{style}" d="M27.975,8.039L32,4.011h-4.025V0H3.996C1.787,0,0,1.789,0,3.995v23.979 c0,2.206,1.787,3.995,3.996,3.995h23.979V12.036h3.994L27.975,8.039z M23.975,27.974H7.99V3.995h15.984V27.974z"/></g></svg>',
box: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="box_x5F_32x32"> <g> <rect y="12" fill="{fill}" width="32" height="20"/> <polygon fill="{fill}" points="18,8 32,8 28,0 18,0 "/> <polygon fill="{fill}" points="14,0 4,0 0,8 14,8 "/> </g></g></svg>',
calendar: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <polygon style="{style}" points="23.918,4 23.918,0 19.918,0 19.918,4 11.918,4 11.918,0 7.918,0 7.918,4 0,4 0,8 7.918,8 11.918,8 19.918,8 23.918,8 32,8 32,4 "/> <rect x="4" y="20" style="{style}" width="24" height="4"/> <rect x="4" y="12" style="{style}" width="24" height="4"/> <polygon style="{style}" points="24,32 4,32 4,28 28,28 "/></g></svg>',
calendar_alt_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M26,4v2.047c0,2.211-1.789,4-4,4s-4-1.789-4-4V4h-4v2.047c0,2.211-1.789,4-4,4s-4-1.789-4-4V4H0v28 h32V4H26z M10,28H6v-4h4V28z M10,20H6v-4h4V20z M18,28h-4v-4h4V28z M18,20.008h-4v-4h4V20.008z M22,28v-4h4L22,28z M26,20h-4v-4h4 V20z"/> <path fill="{fill}"style="{style}" d="M8,6V2c0-1.104,0.895-2,2-2s2,0.896,2,2v4c0,1.104-0.895,2-2,2S8,7.104,8,6z"/> <path fill="{fill}"style="{style}" d="M20,6V2c0-1.104,0.895-2,2-2s2,0.896,2,2v4c0,1.104-0.895,2-2,2S20,7.104,20,6z"/></g></svg>',
calendar_alt_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <polygon style="{style}" points="32,32 0,32 0,4 4,4 4,28 28,28 28,4 32,4 32,32 "/> <rect x="6" y="12" style="{style}" width="4" height="4"/> <rect x="14" y="12.008" style="{style}" width="4" height="4"/> <rect x="22" y="12" style="{style}" width="4" height="4"/> <rect x="6" y="20" style="{style}" width="4" height="4"/> <rect x="14" y="20" style="{style}" width="4" height="4"/> <polygon style="{style}" points="22,24 22,20 26,20 "/> <path fill="{fill}"style="{style}" d="M8,6V2c0-1.104,0.895-2,2-2s2,0.896,2,2v4c0,1.104-0.895,2-2,2S8,7.104,8,6z"/> <path fill="{fill}"style="{style}" d="M20,6V2c0-1.104,0.895-2,2-2s2,0.896,2,2v4c0,1.104-0.895,2-2,2S20,7.104,20,6z"/></g></svg>',
cd: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <g> <path fill="{fill}"style="{style}" d="M16,0C7.164,0,0,7.164,0,16s7.164,16,16,16s16-7.164,16-16S24.836,0,16,0z M16.031,19.934 c-2.188,0-3.965-1.773-3.965-3.965c0-2.195,1.777-3.969,3.965-3.969C18.227,12,20,13.773,20,15.969 C20,18.16,18.227,19.934,16.031,19.934z"/> </g></g></svg>',
chat: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="chat_x5F_32x32"> <path fill="{fill}" d="M24,12V8c0-5.523-4-8-8-8H8C4,0,0,2.125,0,8c0,5.75,4,8,8,8h0.926C8.359,17.099,8,18.406,8,20v4 c0,4.418,3.582,8,8,8c0-2.209,1.797-4,4-4h4c4,0,8-2.25,8-8C32,14.125,28,12,24,12z M8,12c-4,0-4-3.012-4-4c0-1.199,0-4,4-4h8 c1.5,0,4,0.52,4,4v4c0,1.307-0.625,2.471-1.609,3.2C16.931,13.258,14.609,12,12,12H8z M24,24h-4c-2.609,0-4.938,1.258-6.397,3.199 C12.629,26.469,12,25.305,12,24v-4c0-1.831,0.91-2.941,1.816-3.512C15.098,17.156,16,18.457,16,20c2.957,0,5.509-1.621,6.895-4.004 c-0.004,0.001-0.004,0.001-0.004,0.004H24c4,0,4,2.802,4,4C28,20.989,28,24,24,24z M23.719,13.994 c-0.027,0.092-0.059,0.182-0.085,0.271C23.66,14.176,23.696,14.086,23.719,13.994z"/></g></svg>',
chat_alt_fill: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="chat_x5F_alt_x5F_fill_x5F_32x32"> <g> <g> <path fill="{fill}" d="M24,12c0,4.418-3.578,8-8,8c0-2.207-1.793-4-4-4H8c-4,0-8-2.25-8-8c0-5.875,4-8,8-8h8c4,0,8,2.479,8,8V12 z"/> </g> <path fill="{fill}" d="M12,12"/> <path fill="{fill}" d="M12,12"/> <g> <g> <path fill="{fill}" d="M25.984,12.213C25.863,17.625,21.438,22,16,22h-2v-2c0-1.104-0.897-2-2-2H8.203 C8.078,18.619,8,19.281,8,20v4c0,4.418,3.582,8,8,8c0-2.209,1.797-4,4-4h4c4,0,8-2.25,8-8C32,15.106,29.219,12.84,25.984,12.213 z"/> </g> </g> </g></g></svg>',
chat_alt_stroke: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="chat_x5F_alt_x5F_stroke_x5F_32x32"> <g> <g> <path fill="{fill}" d="M25.978,12.213c-0.024,1.386-0.337,2.695-0.884,3.889C27.978,16.582,28,18.93,28,20c0,0.989,0,4-3.996,4 H20c-2.605,0-4.938,1.258-6.397,3.2C12.634,26.471,12,25.307,12,24v-4c0-0.792,0.141-1.414,0.359-1.928 C12.243,18.051,12.125,18,12,18H8.203c-0.125,0.619-0.199,1.281-0.199,2v4c0,4.418,3.578,8,7.996,8c0-2.209,1.79-4,4-4h4.004 C28,28,32,25.75,32,20C32,15.106,29.219,12.84,25.978,12.213z"/> </g> <path fill="{fill}" d="M16,4c1.493,0,4,0.52,4,4v4c0,1.309-0.632,2.471-1.601,3.2C16.938,13.26,14.609,12,12,12H8.004 C4,12,4,8.989,4,8c0-1.195,0-4,4.004-4H16 M16,0H8.004C4,0,0,2.125,0,8c0,5.75,4,8,8.004,8H12c2.212,0,4,1.793,4,4 c4.422,0,8.004-3.582,8.004-8V8C24.004,2.479,20,0,16,0L16,0z"/> </g></g></svg>',
check: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 25.754" style="enable-background:new 0 0 32 25.754;" xml:space="preserve"><g> <polygon style="{style}" points="11.941,25.754 0,13.812 5.695,8.117 11.941,14.363 26.305,0 32,5.695 11.941,25.754 "/></g></svg>',
check_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M16,0C7.164,0,0,7.164,0,16s7.164,16,16,16s16-7.164,16-16S24.836,0,16,0z M13.52,23.383L6.16,16.02 l2.828-2.828l4.532,4.535l9.617-9.618l2.828,2.828L13.52,23.383z"/></svg>',
clock: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M16,4c6.617,0,12,5.383,12,12s-5.383,12-12,12S4,22.617,4,16S9.383,4,16,4 M16,0 C7.164,0,0,7.164,0,16s7.164,16,16,16s16-7.164,16-16S24.836,0,16,0L16,0z"/> <path fill="{fill}"style="{style}" d="M21.422,18.578L18,15.152V8h-4.023v7.992c0,0.602,0.277,1.122,0.695,1.493l3.922,3.922 L21.422,18.578z"/></g></svg>',
cloud: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 20" enable-background="new 0 0 32 20" xml:space="preserve"><path fill="{fill}" d="M24,4c-0.379,0-0.738,0.062-1.103,0.11C21.507,1.648,18.929,0,16,0c-2.988,0-5.566,1.665-6.941,4.101 C8.71,4.054,8.355,4,8,4c-4.41,0-8,3.586-8,8c0,4.414,3.59,8,8,8h16c4.413,0,8-3.586,8-8C32,7.586,28.413,4,24,4z M24,16H8 c-2.207,0-4-1.797-4-4c0-2.195,1.944-3.883,4.007-3.945C8.012,9,8.179,9.922,8.507,10.797l3.743-1.399C12.085,8.953,12,8.484,12,8 c0-2.204,1.793-4,4-4c1.293,0,2.465,0.641,3.199,1.64C17.272,7.101,16,9.395,16,12h4c0-2.204,1.793-4,4-4c2.21,0,4,1.796,4,4 C28,14.203,26.21,16,24,16z"/></svg>',
cog: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M32,20v-8h-4.734c-0.141-0.391-0.289-0.771-0.469-1.146l3.344-3.339l-5.656-5.661l-3.344,3.344 C20.777,5.026,20.375,4.933,20,4.792V0h-8v4.792c-0.383,0.141-0.781,0.234-1.145,0.406l-3.34-3.344l-5.66,5.661l3.34,3.339 C5.02,11.229,4.871,11.609,4.734,12H0v8h4.734c0.137,0.391,0.285,0.771,0.461,1.146l-3.34,3.339l5.66,5.661l3.34-3.344 c0.363,0.172,0.762,0.266,1.145,0.406V32h8v-4.792c0.375-0.141,0.777-0.234,1.141-0.406l3.344,3.344l5.656-5.661l-3.344-3.339 c0.18-0.375,0.328-0.755,0.469-1.146H32z M16,20.083c-2.211,0-4-1.791-4-4c0-2.208,1.789-4,4-4c2.207,0,4,1.792,4,4 C20,18.292,18.207,20.083,16,20.083z"/></svg>',
cog_alt: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="cog_x5F_alt_x5F_32x32"> <path fill="{fill}" d="M32,17.969v-4l-4.781-1.992c-0.133-0.375-0.273-0.737-0.445-1.094l1.93-4.805L25.875,3.25l-4.763,1.961 c-0.362-0.175-0.734-0.323-1.117-0.461L17.969,0h-4l-1.977,4.734c-0.398,0.141-0.781,0.289-1.161,0.469L6.078,3.294L3.25,6.122 l1.938,4.711C5,11.219,4.847,11.614,4.703,12.021L0,14.031v4l4.706,1.961c0.146,0.406,0.302,0.802,0.489,1.188l-1.903,4.742 L6.12,28.75l4.724-1.945c0.378,0.18,0.766,0.325,1.164,0.461L14.031,32h4l1.979-4.758c0.38-0.141,0.755-0.289,1.114-0.461 l4.797,1.922l2.828-2.828l-1.969-4.773c0.167-0.359,0.305-0.722,0.438-1.094L32,17.969z M15.969,22c-3.312,0-6-2.688-6-6 s2.688-6,6-6s6,2.688,6,6S19.281,22,15.969,22z"/></g></svg>',
comment_alt1_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M0,19.992C0,26.626,5.375,32,12.008,32v-4.015c0-2.203,1.789-4,4-4h3.996 C26.625,23.985,32,18.624,32,11.999S26.625,0,20.004,0h-9.996c-5.52,0-9.996,4.47-9.996,9.999v9.993H0z"/></g></svg>',
comment_alt1_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M20.004,8c2.203,0,4,1.789,4,3.995c0,2.203-1.797,3.997-4,3.997h-3.996c-3.07,0-5.875,1.164-8,3.062 v-9.06c0-1.104,0.898-1.995,2-1.995H20.004 M20.004,0h-9.996c-5.52,0-9.996,4.477-9.996,9.995v9.997H0C0,26.625,5.375,32,12.008,32 v-4.008c0-2.211,1.789-4,4-4h3.996C26.625,23.992,32,18.617,32,11.995C32,5.37,26.625,0,20.004,0L20.004,0z"/></svg>',
comment_alt2_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32.001 24.002" style="enable-background:new 0 0 32.001 24.002;" xml:space="preserve"><g> <g> <path fill="{fill}"style="{style}" d="M29.938,20.002c0,0,2.062-4.001,2.062-8.001C32.001,2,24.005,0,16.005,0 C-6.37,0,0.011,20.002,4.011,24.002c4-4,4-4,9.996-4H29.938z"/> </g></g></svg>',
comment_alt2_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" style="enable-background:new 0 0 32 24;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M16,4c11.074,0,12,4.129,12,8c0,1.344-0.359,2.805-0.75,4H14c-4.703,0-6.734,0.195-9,1.758 c-0.938-2.572-1.535-6.046-0.375-8.84C5.975,5.656,9.803,4,16,4 M16,0C-6.369,0,0.012,20,4.006,24c4-4,4-4,9.994-4h15.938 c0,0,2.062-4,2.062-8C32,2,24,0,16,0L16,0z"/></g></svg>',
comment_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 28" style="enable-background:new 0 0 32 28;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M0,20c0,4.417,3.586,8,8,8c0-2.211,1.792-4,4-4h8c6.629,0,12-5.375,12-12S26.629,0,20,0H10 C4.477,0,0,4.477,0,10V20z"/></g></svg>',
comment_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 28" style="enable-background:new 0 0 32 28;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M20,4c4.414,0,8,3.586,8,8s-3.586,8-8,8h-8c-2.609,0-4.933,1.258-6.394,3.203 C4.633,22.469,4,21.305,4,20V10c0-3.308,2.695-6,6-6H20 M20,0H10C4.477,0,0,4.477,0,10v10c0,4.417,3.586,8,8,8c0-2.211,1.793-4,4-4 h8c6.629,0,12-5.375,12-12S26.629,0,20,0L20,0z"/></svg>',
compass: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g> <path fill="{fill}"d="M16,4c6.618,0,12,5.383,12,12s-5.382,12-12,12C9.384,28,4,22.617,4,16S9.384,4,16,4 M16,0C7.165,0,0,7.164,0,16 s7.165,16,16,16c8.837,0,16-7.164,16-16S24.837,0,16,0L16,0z"/> <g> <path fill="{fill}"d="M18.125,13.879c0.797,0.798,1.009,1.93,0.719,2.944L24,8l-8.703,5.138C16.281,12.896,17.359,13.109,18.125,13.879z"/> <path fill="{fill}"d="M13.884,18.121c-0.774-0.771-0.984-1.85-0.743-2.836L8,24l8.832-5.16C15.816,19.133,14.688,18.922,13.884,18.121z"/> </g></g></svg>',
cursor: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="cursor_x5F_32x32"> <polygon fill="{fill}" points="32,28 18,14 24,8 0,0 8,23.995 14,17.995 28,32 "/></g></svg>',
denied: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M16,0C7.164,0,0,7.164,0,16s7.164,16,16,16s16-7.164,16-16S24.836,0,16,0z M16,4 c2.59,0,4.973,0.844,6.934,2.242L6.238,22.93C4.84,20.969,4,18.586,4,16C4,9.383,9.383,4,16,4z M16,28 c-2.59,0-4.973-0.844-6.934-2.242L25.762,9.07C27.16,11.031,28,13.414,28,16C28,22.617,22.617,28,16,28z"/></svg>',
denied_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M16,0C7.164,0,0,7.164,0,16c0,8.836,7.164,16,16,16s16-7.164,16-16C32,7.164,24.836,0,16,0z M16,8 c0.711,0,1.387,0.121,2.043,0.297l-9.742,9.75C8.121,17.391,8,16.71,8,16C8,11.586,11.59,8,16,8z M16,24 c-0.711,0-1.387-0.125-2.043-0.297l9.742-9.75C23.879,14.609,24,15.289,24,16C24,20.414,20.41,24,16,24z"/></svg>',
dial: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 31.828" enable-background="new 0 0 32 31.828" xml:space="preserve"><g id="{id}"></g><g id="dial_x5F_32x32"> <g> <path fill="{fill}" d="M16,11.828c-2.21,0-4,1.79-4,4c0,2.208,1.79,4,4,4c2.212,0,4-1.793,4-4C20,13.617,18.212,11.828,16,11.828 z"/> <path fill="{fill}" d="M28.556,6.047c-0.344,0.281-0.766,0.469-1.243,0.469c-1.101,0-2-0.895-2-2 c0-0.488,0.196-0.918,0.484-1.266c-2.219-1.711-4.906-2.864-7.835-3.227C17.859,1.031,17.04,1.828,16,1.828 c-1.038,0-1.871-0.808-1.96-1.828c-2.969,0.382-5.672,1.555-7.911,3.324C6.384,3.66,6.562,4.062,6.562,4.516c0,1.105-0.891,2-2,2 c-0.444,0-0.844-0.176-1.179-0.426C1.297,8.796,0,12.145,0,15.828c0,8.836,7.165,16,16,16c8.837,0,16-7.164,16-16 C32,12.113,30.688,8.746,28.556,6.047z M16,23.828c-4.418,0-8-3.582-8-8c0-2.211,0.895-4.208,2.344-5.657L16,4.515l5.649,5.645 C23.103,11.613,24,13.613,24,15.828C24,20.246,20.415,23.828,16,23.828z"/> </g></g></svg>',
document_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M21.609,0H0v32l7.977-6.641L15.992,32L24,25.37L32,32V10.301L21.609,0z M18,14V4l10,10H18z"/></svg>',
document_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32.023" style="enable-background:new 0 0 32 32.023;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M22.016,0H0v31.961l8.053-6.582l8.016,6.645l8.016-6.637L32,32.008v-22L22.016,0z M28.021,23.955 l-3.953-3.229c0,0-0.041,0.034-0.104,0.086l-7.896,6.535L8.09,20.734l-4.084,3.221c0,0,0-17.373,0-20.016c2.1,0,7.807,0,12.006,0 v12.01h12.01C28.021,18.682,28.021,23.955,28.021,23.955z M20.016,11.945c0-1.543,0-5.918,0-8.006 c1.615,1.619,6.402,6.404,8.006,8.006C25.975,11.945,21.568,11.945,20.016,11.945z"/></svg>',
eject: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <polygon style="{style}" points="0,20 16,0 32,20 "/> <rect y="24" style="{style}" width="31.955" height="8"/></g></svg>',
equalizer: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M20,20h-2V2c0-1.105-0.891-2-2-2c-1.102,0-2,0.895-2,2v18h-2v4h2v6c0,1.105,0.898,2,2,2 c1.109,0,2-0.895,2-2v-6h2V20z"/> <path fill="{fill}"style="{style}" d="M32,8h-2V2c0-1.105-0.891-2-2-2c-1.102,0-2,0.895-2,2v6h-2v4h2v18c0,1.105,0.898,2,2,2 c1.109,0,2-0.895,2-2V12h2V8z"/> <path fill="{fill}"style="{style}" d="M8,12H6V2c0-1.105-0.891-2-2-2C2.898,0,2,0.895,2,2v10H0v4h2v14c0,1.105,0.898,2,2,2 c1.109,0,2-0.895,2-2V16h2V12z"/></g></svg>',
eyedropper: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="eyedropper_x5F_32x32"> <path fill="{fill}" d="M29.658,13.684c3.123-3.118,3.123-8.18,0-11.297c-1.555-1.559-3.602-2.34-5.643-2.34 c-2.045,0-4.092,0.781-5.649,2.34l-0.592,0.59L14.798,0l-2.82,2.823l2.977,2.974L0,20.761v7.247L3.931,32h7.414l14.907-14.906 l2.875,2.878l2.82-2.82l-2.875-2.878L29.658,13.684z M10.321,27.365c0.047-1.511-0.477-3.033-1.627-4.186 c-1.061-1.06-2.443-1.582-3.834-1.629L17.782,8.628l5.642,5.638L10.321,27.365z"/></g></svg>',
first: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <polygon style="{style}" points="32,32 8,16 32,0 "/> <rect y="4" style="{style}" width="8" height="24"/></g></svg>',
folder_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g> <path fill="{fill}" d="M32,30c0,1.105-0.891,2-2,2H2c-1.105,0-2-0.895-2-2V12h32V30z"/> <polygon fill="{fill}" points="12,4.003 12,0 0,0 0,8 32,8 32,4.003 "/></g></svg>',
folder_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><path fill="{fill}" d="M16,4V0H0v12.004v3.375V28c0,2.211,1.79,4,4,4h24c2.207,0,4-1.789,4-4V16.004v-4V4H16z M12,4L12,4v4h4h12v4 H4V4H12z M28,28H4V16h24v0.004V28z"/></svg>',
fork: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 28 32" enable-background="new 0 0 28 32" xml:space="preserve"><g> <path fill="{fill}"d="M20,0v3.875c0,1.602-0.625,3.109-1.755,4.239L6.93,19.367C5.141,21.151,4.156,23.495,4.047,26H0l6,6l6-6H8.042 c0.106-1.438,0.685-2.773,1.708-3.805l11.32-11.25C22.961,9.055,24,6.547,24,3.875V0H20z"/> <path fill="{fill}"d="M23.953,26c-0.109-2.505-1.099-4.849-2.891-6.641l-2.227-2.214L16,19.964l2.242,2.231c1.031,1.028,1.609,2.367,1.711,3.805 H16l6,6l6-6H23.953z"/></g></svg>',
fullscreen: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="fullscreen_x5F_32x32"> <g> <polygon fill="{fill}" points="27.414,24.586 22.828,20 20,22.828 24.586,27.414 20,32 32,32 32,20 "/> <polygon fill="{fill}" points="12,0 0,0 0,12 4.586,7.414 9.125,11.953 11.953,9.125 7.414,4.586 "/> <polygon fill="{fill}" points="12,22.828 9.172,20 4.586,24.586 0,20 0,32 12,32 7.414,27.414 "/> <polygon fill="{fill}" points="32,0 20,0 24.586,4.586 20.042,9.125 22.87,11.953 27.414,7.414 32,12 "/> </g></g></svg>',
fullscreen_alt: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="fullscreen_x5F_alt_x5F_32x32"> <g> <polygon fill="{fill}" points="29.414,26.586 22.828,20 20,22.828 26.586,29.414 24,32 32,32 32,24 "/> <polygon fill="{fill}" points="2.586,5.414 9.172,12 12,9.172 5.414,2.586 8,0 0,0 0,8 "/> <polygon fill="{fill}" points="26.586,2.586 20,9.172 22.828,12 29.414,5.414 32,8 32,0 24,0 "/> <polygon fill="{fill}" points="12,22.828 9.172,20 2.586,26.586 0,24 0,32 8,32 5.414,29.414 "/> </g></g></svg>',
fullscreen_exit: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="fullscreen_x5F_exit_x5F_32x32"> <g> <polygon fill="{fill}" points="24.586,27.414 29.172,32 32,29.172 27.414,24.586 32,20 20,20 20,32 "/> <polygon fill="{fill}" points="0,12 12,12 12,0 7.414,4.586 2.875,0.043 0.047,2.871 4.586,7.414 "/> <polygon fill="{fill}" points="0,29.172 2.828,32 7.414,27.414 12,32 12,20 0,20 4.586,24.586 "/> <polygon fill="{fill}" points="20,12 32,12 27.414,7.414 31.961,2.871 29.133,0.043 24.586,4.586 20,0 "/> </g></g></svg>',
fullscreen_exit_alt: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="fullscreen_x5F_exit_x5F_alt_x5F_32x32"> <g> <polygon fill="{fill}" points="22.586,25.414 29.172,32 32,29.172 25.414,22.586 28,20 20,20 20,28 "/> <polygon fill="{fill}" points="6.547,9.371 4,12 11.961,11.957 12,4 9.375,6.543 2.828,0 0,2.828 "/> <polygon fill="{fill}" points="0,29.172 2.828,32 9.414,25.414 12,28 12,20 4,20 6.586,22.586 "/> <polygon fill="{fill}" points="28.031,12 25.438,9.404 32,2.838 29.164,0 22.594,6.566 20,3.971 20,12 "/> </g></g></svg>',
headphones: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 28" style="enable-background:new 0 0 32 28;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M30,16h-2v-4c0-6.627-5.375-12-12-12S4,5.373,4,12v4H2c-1.105,0-2,0.895-2,2v8c0,1.105,0.895,2,2,2h6 V16v-4c0-4.411,3.586-8,8-8s8,3.589,8,8v4v12h6c1.104,0,2-0.895,2-2v-8C32,16.895,31.104,16,30,16z"/></svg>',
heart_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 28" style="enable-background:new 0 0 32 28;" xml:space="preserve"><g> <g> <path fill="{fill}"style="{style}" d="M16,3.844C14.387,1.578,11.871,0,8.887,0C3.984,0,0,3.992,0,8.891v0.734L16.006,28L32,9.625V8.891 C32,3.992,28.016,0,23.115,0C20.131,0,17.615,1.578,16,3.844z"/> </g></g></svg>',
heart_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 28" style="enable-background:new 0 0 32 28;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M23.115,4c2.453,0,4.49,1.82,4.834,4.188L16.006,21.906L4.053,8.188C4.396,5.82,6.428,4,8.887,4 c2.016,0,3.854,2.164,3.854,2.164L16,9.625l3.256-3.461C19.256,6.164,21.1,4,23.115,4 M23.115,0c-2.984,0-5.5,1.578-7.115,3.844 C14.387,1.578,11.871,0,8.887,0C3.984,0,0,3.992,0,8.891v0.734L16.006,28L32,9.625V8.891C32,3.992,28.016,0,23.115,0L23.115,0z"/></g></svg>',
home: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="home_x5F_32x32"> <path fill="{fill}" d="M16,0L0,16h4v16h24V16h4L16,0z M24,28h-6v-6h-4v6H8V13.656L16,8l8,5.656V28z"/></g></svg>',
image: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <polygon style="{style}" points="8,24 8,16 12,12 16,16 24,8 32,16 32,24 "/> <polygon style="{style}" points="4,28 4,0 0,4 0,28 0,32 4,32 28,32 32,28 "/></g></svg>',
info: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 16 32" enable-background="new 0 0 16 32" xml:space="preserve"><g id="{id}"></g><g id="Layer_21"> <g> <path fill="{fill}" d="M2,16c1.104,0,2,0.895,2,2v8c0,1.105-0.896,2-2,2H0v4h16v-4h-1.992c-1.102,0-2-0.895-2-2L12,12H0v4H2z"/> <circle fill="{fill}" cx="8" cy="4" r="4"/> </g></g></svg>',
iphone: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 24 32" style="enable-background:new 0 0 24 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M16,0H8C3.582,0,0,3.582,0,8v16c0,4.418,3.582,8,8,8h8c4.418,0,8-3.582,8-8V8C24,3.582,20.418,0,16,0 z M12,30.062c-1.138,0-2.062-0.924-2.062-2.062s0.924-2.062,2.062-2.062c1.139,0,2.062,0.924,2.062,2.062S13.139,30.062,12,30.062z M20,24H4V8c0-2.206,1.794-4,4-4h8c2.205,0,4,1.794,4,4V24z"/></svg>',
key_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <g> <path fill="{fill}"style="{style}" d="M22,0c-5.523,0-10,4.477-10,10c0,0.623,0.074,1.227,0.184,1.816L0,24v8h12v-4h4v-4h4v-4 l0.184-0.184C20.773,19.926,21.379,20,22,20c5.523,0,10-4.477,10-10S27.523,0,22,0z M22.008,12c-1.105,0-2-0.895-2-2s0.895-2,2-2 s2,0.895,2,2S23.113,12,22.008,12z"/> </g></g></svg>',
key_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M22,4c3.309,0,6,2.691,6,6s-2.691,6-6,6c-0.312,0-0.658-0.039-1.088-0.117L18.844,15.5l-1.488,1.488 l-0.184,0.184L16,18.344V20h-4v4H8v4H4v-2.344l11.012-11.012l1.488-1.488l-0.383-2.07C16.038,10.657,16,10.312,16,10 C16,6.691,18.691,4,22,4 M22,0c-5.523,0-10,4.477-10,10c0,0.625,0.074,1.227,0.184,1.816L0,24v8h12v-4h4v-4h4v-4l0.184-0.184 C20.773,19.926,21.377,20,22,20c5.523,0,10-4.477,10-10S27.523,0,22,0L22,0z"/> <circle style="{style}" cx="22.008" cy="10" r="2"/></g></svg>',
last: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <polygon style="{style}" points="0,0 24,16 0,32 "/> <rect x="24" y="4" style="{style}" width="8" height="24"/></g></svg>',
left_quote: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" enable-background="new 0 0 32 24" xml:space="preserve"><g id="{id}"></g><g id="left_x5F_quote_x5F_32x32"> <g> <path fill="{fill}" d="M32,24V12h-8c0-4.411,3.587-8,8-8V0c-6.616,0-12,5.383-12,12v12H32z"/> <path fill="{fill}" d="M12,24V12H4c0-4.411,3.587-8,8-8V0C5.384,0,0,5.383,0,12v12H12z"/> </g></g></svg>',
left_quote_alt: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" enable-background="new 0 0 32 24" xml:space="preserve"><g id="{id}"></g><g id="left_x5F_quote_x5F_alt_x5F_32x32"> <g> <polygon fill="{fill}" points="32,24 32,0 20,12 20,24 "/> <polygon fill="{fill}" points="12,24 12,0 0,12 0,24 "/> </g></g></svg>',
lightbulb: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 20.051 32" style="enable-background:new 0 0 20.051 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M10.024,4.007c3.32,0,6.019,2.7,6.019,6.017c0,1.894-0.867,3.636-2.379,4.773 c-2.266,1.707-3.18,3.593-3.496,5.179H9.883c-0.313-1.586-1.23-3.473-3.493-5.179c-1.515-1.137-2.382-2.879-2.382-4.773 C4.008,6.707,6.707,4.007,10.024,4.007 M10.024,0C4.488,0,0,4.488,0,10.024c0,3.28,1.547,6.147,3.977,7.976 c1.121,0.844,2.042,1.93,2.042,3.43v2.555h8.012V21.43c0-1.5,0.922-2.586,2.043-3.43c2.43-1.829,3.977-4.696,3.977-7.976 C20.051,4.488,15.562,0,10.024,0L10.024,0z"/> <rect x="6.02" y="27.992" style="{style}" width="8.012" height="4.008"/></g></svg>',
link: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="link_x5F_32x32"> <g> <path fill="{fill}" d="M31.414,0.586c-0.781-0.781-2.047-0.781-2.828,0l-4.071,4.073C22.847,3.553,20.921,3,18.999,3 c-2.559,0-5.116,0.977-7.069,2.93l-6,6c-3.422,3.42-3.844,8.703-1.274,12.584l-4.069,4.072c-0.781,0.781-0.781,2.047,0,2.828 C0.977,31.805,1.487,32,1.999,32c0.516,0,1.024-0.195,1.415-0.586l4.069-4.072C9.155,28.447,11.077,29,12.999,29 c2.562,0,5.118-0.977,7.071-2.93l6-6c3.422-3.419,3.844-8.703,1.272-12.583l4.071-4.073C32.195,2.633,32.195,1.367,31.414,0.586z M24.999,13c0,1.602-0.625,3.109-1.757,4.242l-6,6C16.108,24.375,14.602,25,12.999,25c-0.906,0-1.772-0.221-2.569-0.602 l2.984-2.984c0.781-0.781,0.781-2.047,0-2.828s-2.047-0.781-2.828,0L7.602,21.57C7.218,20.775,6.999,19.908,6.999,19 c0-1.602,0.625-3.109,1.759-4.242l6-6C15.89,7.625,17.398,7,18.999,7c0.906,0,1.774,0.221,2.571,0.602l-3.047,3.047 c-0.781,0.781-0.781,2.047,0,2.828c0.391,0.391,0.901,0.586,1.413,0.586c0.516,0,1.024-0.195,1.415-0.586l3.047-3.047 C24.78,11.225,24.999,12.092,24.999,13z"/> </g></g></svg>',
lock_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 24.006 32" style="enable-background:new 0 0 24.006 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M14.006,0c-5.508,0-10,4.485-10,10v2H0v14c0,3.309,2.693,6,6,6h12.006c3.307,0,6-2.691,6-6V10 C24.006,4.485,19.516,0,14.006,0z M12,24c-1.104,0-2-0.895-2-2s0.896-2,2-2c1.107,0,2,0.895,2,2S13.107,24,12,24z M20.006,12h-12v-2 c0-3.309,2.695-6,6-6c3.307,0,6,2.691,6,6V12z"/></svg>',
lock_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 24.008 32" style="enable-background:new 0 0 24.008 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M14.008,0c-5.512,0-10,4.484-10,10v2H0v14c0,3.305,2.695,6,6,6h12.008c3.312,0,6-2.695,6-6V10 C24.008,4.484,19.523,0,14.008,0z M8.008,10c0-3.312,2.695-6,6-6c3.312,0,6,2.688,6,6v2h-12V10z M18.008,28H6c-1.102,0-2-0.898-2-2 V16h16.008v10C20.008,27.102,19.113,28,18.008,28z"/> <path fill="{fill}"style="{style}" d="M14.008,22c0,1.102-0.898,2-2,2c-1.109,0-2-0.898-2-2c0-1.109,0.891-2,2-2 C13.109,20,14.008,20.891,14.008,22z"/></g></svg>',
loop: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 31.999 32" style="enable-background:new 0 0 31.999 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M9.804,3.677l-5.803,5.8V3.841H0v11.997h12.001v-4H7.298l5.335-5.333 c3.387-3.391,9.307-3.391,12.701,0l2.828-2.828C23.261-1.229,14.708-1.222,9.804,3.677z"/> <path fill="{fill}"style="{style}" d="M19.999,16.033v4h4.703l-5.336,5.338c-3.389,3.395-9.307,3.395-12.701,0l-2.829,2.824 C6.287,30.648,9.55,32,13.021,32c3.469,0,6.725-1.352,9.174-3.805l5.805-5.803v5.639h4V16.033H19.999z"/></g></svg>',
loop_alt1: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" enable-background="new 0 0 32 24" xml:space="preserve"><g> <path fill="{fill}"d="M26,12l-6,6h4c0,1.102-0.897,2-2,2H10c-1.101,0-2-0.898-2-2v-2H4v2c0,3.308,2.691,6,6,6h12c3.312,0,6-2.692,6-6h4L26,12z" /> <path fill="{fill}"d="M22,0H10C6.691,0,4,2.692,4,6v0.062H0L6,12l6-5.938H8V6c0-1.102,0.899-2,2-2h12c1.103,0,2,0.898,2,2v2h4V6 C28,2.692,25.312,0,22,0z"/></g></svg>',
loop_alt2: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 28" enable-background="new 0 0 32 28" xml:space="preserve"><g> <path fill="{fill}"d="M19.946,20l6.007-8L32,20h-4v2c0,3.308-2.688,6-6,6H10c-3.309,0-6-2.692-6-6v-2h4v2c0,1.102,0.899,2,2,2h12 c1.103,0,2-0.898,2-2v-2H19.946z"/> <path fill="{fill}"d="M12.056,8l-6.009,8L0,8h4V6c0-3.308,2.691-6,6-6h12c3.312,0,6,2.692,6,6v2h-4V6c0-1.102-0.897-2-2-2H10 C8.899,4,8,4.898,8,6v2H12.056z"/></g></svg>',
loop_alt3: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" enable-background="new 0 0 32 24" xml:space="preserve"><g> <path fill="{fill}"d="M28,12v2c0,1.102-0.897,2-2,2H12v-4l-8,6l8,6v-4h14c3.312,0,6-2.695,6-6v-2H28z"/> <path fill="{fill}"d="M4,10c0-1.104,0.899-2,2-2h14v4l7.993-6L20,0v4H6c-3.309,0-6,2.688-6,6v2h4V10z"/></g></svg>',
loop_alt4: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" enable-background="new 0 0 32 24" xml:space="preserve"><g> <path fill="{fill}"d="M28,14c0,1.102-0.899,2-2,2H7.991v-4L0,18l7.991,6v-4H26c3.309,0,6-2.695,6-6H28z"/> <path fill="{fill}"d="M6,8h18v4l8-6l-8-6v4H6c-3.306,0-6,2.688-6,6h4C4,8.896,4.897,8,6,8z"/></g></svg>',
magnifying_glass: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M20.135,0C13.594,0,8.273,5.32,8.273,11.864c0,1.565,0.32,3.05,0.867,4.422L0,25.43L6.572,32 l9.146-9.148c1.367,0.555,2.854,0.875,4.416,0.875c6.537,0,11.865-5.32,11.865-11.862C32,5.32,26.672,0,20.135,0z M6.572,26.352 c-0.432-0.438-0.494-0.492-0.922-0.922c1.271-1.269,3.828-3.836,5.686-5.688c0.289,0.328,0.596,0.633,0.914,0.922 C10.4,22.516,7.844,25.078,6.572,26.352z M20.135,19.729c-4.338,0-7.869-3.526-7.869-7.865c0-4.338,3.531-7.869,7.869-7.869 c4.334,0,7.865,3.531,7.865,7.869C28,16.203,24.469,19.729,20.135,19.729z"/></svg>',
magnifying_glass_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 31.992 32" style="enable-background:new 0 0 31.992 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M20.127,0C13.594,0,8.268,5.32,8.268,11.864c0,1.565,0.326,3.05,0.873,4.417L0,25.427L6.57,32 l9.148-9.151c1.361,0.553,2.846,0.875,4.408,0.875c6.545,0,11.865-5.322,11.865-11.859C31.992,5.32,26.672,0,20.127,0z M20.127,19.727c-4.33,0-7.861-3.531-7.861-7.862c0-4.338,3.531-7.869,7.861-7.869c4.342,0,7.873,3.531,7.873,7.869 C28,16.195,24.469,19.727,20.127,19.727z"/></g></svg>',
mail: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" style="enable-background:new 0 0 32 24;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M0,0v24h32V0H0z M24.859,4l-7.445,7.445c-0.781,0.781-2.047,0.781-2.828,0L7.141,4H24.859z M4,20 V6.516l7.758,7.758c1.172,1.172,2.703,1.758,4.242,1.758s3.07-0.586,4.242-1.758L28,6.516V20H4z"/></svg>',
mail_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" enable-background="new 0 0 32 24" xml:space="preserve"><g> <polygon fill="{fill}" points="16.078,11.457 32,3.918 32,0 0,0 0,3.903 "/> <polygon fill="{fill}" points="16.087,15.879 0,8.322 0,24 32,24 32,8.344 "/></g></svg>',
map_pin_fill: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 20 32" enable-background="new 0 0 20 32" xml:space="preserve"><g id="{id}"></g><g id="map_x5F_pin_x5F_fill_x5F_32x32"> <g> <g> <path fill="{fill}" d="M17.07,2.93c-3.906-3.906-10.234-3.906-14.141,0c-3.906,3.904-3.906,10.237,0,14.141 C2.93,17.07,10,24,10,32c0-8,7.07-14.93,7.07-14.93C20.977,13.167,20.977,6.833,17.07,2.93z M10,14.005c-2.211,0-4-1.789-4-4 s1.789-4,4-4s4,1.789,4,4S12.211,14.005,10,14.005z"/> </g> </g></g></svg>',
map_pin_stroke: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 20 32" enable-background="new 0 0 20 32" xml:space="preserve"><g id="{id}"></g><g id="map_x5F_pin_x5F_stroke_x5F_32x32"> <g> <path fill="{fill}" d="M10,4c1.602,0,3.109,0.625,4.242,1.76C15.375,6.891,16,8.398,16,10s-0.625,3.109-1.734,4.213 c-0.164,0.166-2.234,2.224-4.266,5.441c-2.023-3.211-4.086-5.261-4.242-5.415C4.625,13.109,4,11.602,4,10s0.625-3.109,1.758-4.242 S8.398,4,10,4 M10,0C7.438,0,4.883,0.977,2.93,2.93c-3.906,3.904-3.906,10.237,0,14.141C2.93,17.07,10,24,10,32 c0-8,7.07-14.93,7.07-14.93c3.906-3.904,3.906-10.237,0-14.141C15.117,0.977,12.558,0,10,0L10,0z"/> <path fill="{fill}" d="M12,10c0,1.105-0.896,2-2,2c-1.109,0-2-0.895-2-2s0.891-2,2-2C11.104,8,12,8.895,12,10z"/> </g></g></svg>',
minus: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 8" style="enable-background:new 0 0 32 8;" xml:space="preserve"><rect style="{style}" width="32" height="8"/></svg>',
minus_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><path fill="{fill}" d="M16,0C7.165,0,0,7.164,0,16s7.165,16,16,16c8.837,0,16-7.164,16-16S24.837,0,16,0z M24,18H8v-4h16V18z"/></svg>',
moon_fill: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="moon_x5F_fill_x5F_32x32"> <g> <path fill="{fill}" d="M24.633,22.184c-8.188,0-14.82-6.637-14.82-14.82c0-2.695,0.773-5.188,2.031-7.363 C5.016,1.969,0,8.188,0,15.645C0,24.676,7.32,32,16.352,32c7.456,0,13.68-5.023,15.648-11.844 C29.82,21.41,27.328,22.184,24.633,22.184z"/> </g></g></svg>',
moon_stroke: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="moon_x5F_stroke_x5F_32x32"> <path fill="{fill}" d="M5.891,9.148c0.852,8.959,8,16.109,16.961,16.953C20.938,27.311,18.698,28,16.352,28 C9.539,28,4,22.459,4,15.646C4,13.3,4.688,11.059,5.891,9.148 M11.844,0C5.016,1.969,0,8.19,0,15.646C0,24.678,7.32,32,16.352,32 c7.456,0,13.68-5.021,15.648-11.844c-2.18,1.256-4.672,2.029-7.367,2.029c-8.188,0-14.82-6.636-14.82-14.82 C9.812,4.67,10.586,2.178,11.844,0L11.844,0z"/></g></svg>',
move: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="move_x5F_32x32"> <g> <polygon fill="{fill}" points="18,20 18,26 22,26 16,32 10,26 14,26 14,20 "/> <polygon fill="{fill}" points="14,12 14,6 10,6 16,0 22,6 18,6 18,12 "/> <polygon fill="{fill}" points="12,18 6,18 6,22 0,16 6,10 6,14 12,14 "/> <polygon fill="{fill}" points="20,14 26,14 26,10 32,16 26,22 26,18 20,18 "/> </g></g></svg>',
move_alt1: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="move_x5F_alt1_x5F_32x32"> <g> <polygon fill="{fill}" points="16,22 18,20 18,26 22,26 16,32 10,26 14,26 14,20 "/> <polygon fill="{fill}" points="16,10.062 14,12 14,6 10,6 16,0 22,6 18,6 18,12 "/> <polygon fill="{fill}" points="10,16 12,18 6,18 6,22 0,16 6,10 6,14 12,14 "/> <polygon fill="{fill}" points="21.938,16 20,14 26,14 26,10 32,16 26,22 26,18 20,18 "/> </g></g></svg>',
move_alt2: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="move_x5F_alt2_x5F_32x32"> <path fill="{fill}"fill="5E6469" d="M16,0C7.165,0,0,7.164,0,16s7.165,16,16,16c8.837,0,16-7.164,16-16S24.837,0,16,0z M22,20v-2h-4v4h2l-4,4l-4-4h2v-4h-4v2 l-4-4l4-4v2h4v-4h-2l4-4l4,4h-2v4h4v-2l4,4L22,20z"/></g></svg>',
move_horizontal: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 12" enable-background="new 0 0 32 12" xml:space="preserve"><g id="Layer_1_1_"></g><g id="move_x5F_horizontal_x5F_12x32"> <g> <polygon fill="{fill}" points="12,8 6,8 6,12 0,6 6,0 6,4 12,4 "/> <polygon fill="{fill}" points="20,4 26,4 26,0 32,6 26,12 26,8 20,8 "/> </g></g></svg>',
move_horizontal_alt1: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 12" enable-background="new 0 0 32 12" xml:space="preserve"><g id="{id}"></g><g id="move_x5F_horizontal_x5F_alt1_x5F_12x32"> <g> <polygon fill="{fill}" points="10,6 12,8 6,8 6,12 0,6 6,0 6,4 12,4 "/> <polygon fill="{fill}" points="21.938,6 20,4 26,4 26,0 32,6 26,12 26,8 20,8 "/> </g></g></svg>',
move_horizontal_alt2: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="move_x5F_horizontal_x5F_alt2_x5F_32x32"> <path fill="{fill}" d="M32,16c0-8.836-7.163-16-16-16C7.165,0,0,7.164,0,16s7.165,16,16,16C24.837,32,32,24.836,32,16z M10,18v2 l-4-4l4-4v2h12v-2l4,4l-4,4v-2H10z"/></g></svg>',
move_vertical: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 12 32" enable-background="new 0 0 12 32" xml:space="preserve"><g id="{id}"></g><g id="move_x5F_vertical_x5F_12x32"> <g> <polygon fill="{fill}" points="8,20 8,26 12,26 6,32 0,26 4,26 4,20 "/> <polygon fill="{fill}" points="4,12 4,6 0,6 6,0 12,6 8,6 8,12 "/> </g></g></svg>',
move_vertical_alt1: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 12 32" enable-background="new 0 0 12 32" xml:space="preserve"><g id="{id}"></g><g id="move_x5F_vertical_x5F_alt1_x5F_12x32"> <g> <polygon fill="{fill}" points="6,22 8,20 8,26 12,26 6,32 0,26 4,26 4,20 "/> <polygon fill="{fill}" points="6,10.062 4,12 4,6 0,6 6,0 12,6 8,6 8,12 "/> </g></g></svg>',
move_vertical_alt2: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="move_x5F_vertical_x5F_alt2_x5F_32x32"> <path fill="{fill}" d="M16,0C7.165,0,0,7.164,0,16s7.165,16,16,16c8.837,0,16-7.164,16-16S24.837,0,16,0z M18,22h2l-4,4l-4-4h2V10 h-2l4-4l4,4h-2V22z"/></g></svg>',
movie: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><path fill="{fill}"d="M27.977,8h-3.95L28,4.016L24.073,0h-5.565l3.987,3.984L18.409,8h-4.722l4.058-3.984L13.734,0H8.078l3.984,3.984L7.977,8 H3.969l4.062-3.984L4.016,0H0v32h32V0h-3.922L32,4L27.977,8z M28,27.958H4v-4h24V27.958z M28,20H4v-4h24V20z"/></svg>',
new_window: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M32,0H8v7.998c-2.906,0-8,0-8,0.002v24h24v-8h8V0z M20,28H4V16h4v8h12C20,25.791,20,27.998,20,28z M28,20H12V8h16V20z"/></svg>',
pause: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 24 32" style="enable-background:new 0 0 24 32;" xml:space="preserve"><g> <rect style="{style}" width="8" height="32"/> <rect x="16" style="{style}" width="8" height="32"/></g></svg>',
pen: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32.004" style="enable-background:new 0 0 32 32.004;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M29.656,2.344C28.1,0.781,26.053,0,24,0c-2.047,0-4.094,0.781-5.656,2.344L0.031,20.657L0,32.004 h11.312l18.344-18.347C32.781,10.535,32.781,5.468,29.656,2.344z M9.656,28.001H8v-4H4.021l0.006-1.681L21.172,5.172l0,0 l5.656,5.656v0L9.656,28.001z"/></svg>',
pen_alt_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32.002" style="enable-background:new 0 0 32 32.002;" xml:space="preserve"><g> <g> <path fill="{fill}"style="{style}" d="M29.656,2.344c-3.119-3.125-8.191-3.125-11.312,0L0.031,20.656L0,32.002h11.312l18.344-18.346 C32.781,10.534,32.781,5.467,29.656,2.344z M9.609,28.002H3.953v-5.689c1.562-1.562,4.094-1.562,5.656,0 C11.172,23.877,11.172,26.439,9.609,28.002z M26.756,10.828L21.1,5.172c1.562-1.562,4.094-1.562,5.656,0 S28.318,9.266,26.756,10.828z"/> </g></g></svg>',
pen_alt_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32.002" style="enable-background:new 0 0 32 32.002;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M29.656,2.344C28.094,0.781,26.047,0,24,0s-4.094,0.781-5.656,2.344L0.031,20.656L0,32.002h11.312 l18.344-18.346C32.781,10.534,32.781,5.466,29.656,2.344z M9.656,28H9.609c1.562-1.562,1.562-4.125,0-5.688 c-1.494-1.496-3.859-1.517-5.426-0.149L21.137,5.211l5.656,5.655L9.656,28z"/></svg>',
pin: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="pin_x5F_32x32"> <path fill="{fill}" d="M32,8c0-4.417-3.585-8-8-8c-2.984,0-5.562,1.659-6.938,4.086c0-0.002,0.004-0.004,0.004-0.005 c-0.363-0.036-0.723-0.112-1.098-0.112c-6.625,0-12,5.371-12,12c0,2.527,0.79,4.865,2.125,6.799L0,32l9.29-6.064 c1.913,1.283,4.21,2.033,6.679,2.033c6.629,0,12-5.371,12-12c0-0.346-0.069-0.669-0.101-1.008C30.321,13.594,32,11.005,32,8z M15.969,23.969c-4.413,0-8-3.588-8-8c0-4.412,3.587-8,8-8c0.016,0,0.024,0.004,0.031,0.004c0-0.008,0.004-0.014,0.004-0.02 C16.004,7.969,16,7.984,16,8c0,0.695,0.118,1.355,0.281,1.998l-3.172,3.174c-1.562,1.562-1.562,4.094,0,5.656s4.094,1.562,5.656,0 l3.141-3.141c0.66,0.18,1.344,0.305,2.062,0.309C23.953,20.396,20.375,23.969,15.969,23.969z M24,12c-2.203,0-4-1.794-4-4 s1.797-4,4-4s4,1.794,4,4S26.203,12,24,12z"/></g></svg>',
play: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 24 32" style="enable-background:new 0 0 24 32;" xml:space="preserve"><polygon style="{style}" points="0,0 24,16 0,32 "/></svg>',
play_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M16,0C7.164,0,0,7.164,0,16s7.164,16,16,16s16-7.164,16-16S24.836,0,16,0z M10,24V8l16.008,8L10,24z" /></svg>',
plus: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><polygon style="{style}" points="32,12 20,12 20,0 12,0 12,12 0,12 0,20 12,20 12,32 20,32 20,20 32,20 "/></svg>',
plus_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><path fill="{fill}" d="M16,0C7.165,0,0,7.164,0,16s7.165,16,16,16c8.837,0,16-7.164,16-16S24.837,0,16,0z M24,18h-6v6h-4v-6H8v-4h6 V8h4v6h6V18z"/></svg>',
read_more: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <polygon style="{style}" points="32,4 0,4 0,0 32,0 32,4 "/> <polygon style="{style}" points="20,12 0,12 0,8 20,8 20,12 "/> <polygon style="{style}" points="32,20.086 0,20.086 0,16.086 32,16.086 32,20.086 "/> <circle style="{style}" cx="2" cy="30" r="2"/> <path fill="{fill}"style="{style}" d="M12,30c0,1.104-0.898,2-2,2c-1.109,0-2.004-0.896-2.004-2S8.891,28,10,28C11.102,28,12,28.896,12,30 z"/> <circle style="{style}" cx="18" cy="30" r="2"/></g></svg>',
reload: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 24 28" style="enable-background:new 0 0 24 28;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M20,16c0,4.41-3.586,8-8,8s-8-3.59-8-8s3.586-8,8-8l2.359,0.027l-1.164,1.164l2.828,2.828L22.035,6 l-6.012-6l-2.828,2.828L14.375,4H12C5.375,4,0,9.371,0,16s5.375,12,12,12s12-5.371,12-12H20z"/></g></svg>',
reload_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 24 28" style="enable-background:new 0 0 24 28;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M20,16c0,4.414-3.586,8-8,8s-8-3.586-8-8s3.586-8,8-8l4.023,0.043v3.977L22.035,6l-6.012-6v4H12 C5.375,4,0,9.375,0,16s5.375,12,12,12s12-5.375,12-12H20z"/></g></svg>',
right_quote: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" enable-background="new 0 0 32 24" xml:space="preserve"><g id="{id}"></g><g id="right_x5F_quote_x5F_32x32"> <g> <path fill="{fill}" d="M0,0v12h8c0,4.411-3.585,8-8,8v4c6.618,0,12-5.383,12-12V0H0z"/> <path fill="{fill}" d="M20,0v12h8c0,4.411-3.585,8-8,8v4c6.618,0,12-5.383,12-12V0H20z"/> </g></g></svg>',
right_quote_alt: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" enable-background="new 0 0 32 24" xml:space="preserve"><g id="{id}"></g><g id="right_x5F_quote_x5F_alt_x5F_32x32"> <g> <polygon fill="{fill}" points="0,0 0,24 12,12 12,0 "/> <polygon fill="{fill}" points="20,0 20,24 32,12 32,0 "/> </g></g></svg>',
rss: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <circle style="{style}" cx="4.001" cy="28" r="4.001"/> <g> <path fill="{fill}"style="{style}" d="M6.023,20.004c3.309,0,6,2.691,6,6.004h4.001C16.025,20.492,11.538,16,6.023,16V20.004z"/> </g> <g> <path fill="{fill}"style="{style}" d="M5.996,12c7.719,0,14.002,6.285,14.002,14.007h4C23.998,16.078,15.923,8,5.996,8V12z"/> </g> <g> <path fill="{fill}"style="{style}" d="M5.996,4C18.129,4,28,13.871,28,26.008h4C32,11.665,20.334,0,5.996,0V4z"/> </g></g></svg>',
rss_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g> <path fill="{fill}"d="M32,32h-4.569C27.431,16.875,15.125,4.573,0,4.573V0C17.641,0,32,14.355,32,32L32,32z"/> <path fill="{fill}"d="M22.859,32h-4.574c0-10.082-8.207-18.285-18.285-18.285V9.143C12.603,9.143,22.859,19.398,22.859,32L22.859,32z"/> <path fill="{fill}"d="M13.719,32H9.141c0-5.043-4.094-9.143-9.141-9.143v-4.572C7.562,18.285,13.719,24.438,13.719,32L13.719,32z"/> <path fill="{fill}"d="M4.571,32c0-2.523-2.04-4.57-4.571-4.57V32H4.571z"/></g></svg>',
spin: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 28 32" enable-background="new 0 0 28 32" xml:space="preserve"><g id="{id}"></g><g id="reload_x5F_alt2_x5F_28x32"> <g> <path fill="{fill}"d="M23.883,6.086l-2.82,2.831C22.953,10.808,24,13.323,24,16c0,5.516-4.484,10-10,10v-2l-4,4l4,4v-2c7.719,0,14-6.281,14-14 C28,12.255,26.539,8.734,23.883,6.086z"/> <path fill="{fill}"d="M18,4l-4-4v2C6.281,2,0,8.281,0,16c0,3.745,1.461,7.266,4.117,9.914l2.82-2.831C5.047,21.192,4,18.677,4,16 C4,10.484,8.484,6,14,6v2L18,4z"/> </g></g></svg>',
spin_alt: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="reload_x5F_alt3_x5F_32x32"> <g> <path fill="{fill}"d="M4.688,27.32C1.664,24.297,0,20.281,0,16C0,7.18,7.172,0,16,0l2,2l-2,2C9.383,4,4,9.383,4,16 c0,3.211,1.25,6.227,3.516,8.492l-2.453,0.32L4.688,27.32L4.688,27.32z"/> <path fill="{fill}"d="M16,32l-2-1.992L16,28c6.617,0,12-5.383,12-12c0-3.203-1.25-6.219-3.523-8.489l2.461-0.323l0.367-2.505 C30.328,7.708,32,11.727,32,16C32,24.82,24.82,32,16,32L16,32z"/> </g></g></svg>',
star: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="star_x5F_32x32"> <g> <polygon fill="{fill}" points="22.136,19.625 32,12 20,12 16,0 12,12 0,12 9.875,19.594 6,32 16.016,24.32 26.008,32 "/> </g></g></svg>',
stop: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><rect style="{style}" width="32" height="32"/></svg>',
sun: '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" enable-background="new 0 0 32 32" xml:space="preserve"><g id="{id}"></g><g id="sun_x5F_32x32"> <g> <path fill="{fill}" d="M24,16c0,4.417-3.585,8-8,8c-4.422,0-8-3.583-8-8s3.578-8,8-8C20.415,8,24,11.583,24,16z"/> <path fill="{fill}" d="M16,3.312c1.384,0,2.691,0.276,3.938,0.688H20l-4-4l-4,4h0.056C13.306,3.589,14.613,3.312,16,3.312z"/> <path fill="{fill}" d="M16,28.688c-1.387,0-2.694-0.276-3.944-0.688H12l4,4l4-4h-0.062C18.691,28.411,17.384,28.688,16,28.688z" /> <path fill="{fill}" d="M28.688,16c0,1.383-0.281,2.695-0.688,3.942V20l4-4l-4-4v0.058C28.406,13.305,28.688,14.617,28.688,16z"/> <path fill="{fill}" d="M3.312,16c0-1.383,0.274-2.695,0.688-3.942V12l-4,4l4,4v-0.058C3.587,18.695,3.312,17.383,3.312,16z"/> <path fill="{fill}" d="M24.969,24.969c-0.976,0.984-2.101,1.711-3.272,2.305l-0.04,0.039h5.656v-5.656l-0.043,0.042 C26.681,22.87,25.953,23.992,24.969,24.969z"/> <path fill="{fill}" d="M7.031,7.031c0.978-0.984,2.094-1.711,3.266-2.305l0.047-0.039H4.688v5.656l0.04-0.042 C5.321,9.13,6.047,8.008,7.031,7.031z"/> <path fill="{fill}" d="M7.031,24.969c-0.984-0.977-1.71-2.099-2.304-3.271l-0.04-0.042v5.656h5.656l-0.047-0.039 C9.125,26.68,8.009,25.953,7.031,24.969z"/> <path fill="{fill}" d="M24.969,7.031c0.984,0.977,1.712,2.099,2.301,3.271l0.043,0.042V4.688h-5.656l0.04,0.039 C22.868,5.32,23.993,6.047,24.969,7.031z"/> </g></g></svg>',
tag_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M13.277,0H0v13.277L18.719,32V18.723H32L13.277,0z M7.312,11.121c-2.102,0-3.805-1.703-3.805-3.805 s1.703-3.805,3.805-3.805s3.805,1.703,3.805,3.805S9.414,11.121,7.312,11.121z"/></svg>',
tag_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M11.699,8.613c0,1.703-1.383,3.086-3.082,3.086c-1.703,0-3.086-1.383-3.086-3.086 c0-1.699,1.383-3.078,3.086-3.078C10.316,5.535,11.699,6.914,11.699,8.613z"/> <g> <path fill="{fill}"style="{style}" d="M0,0v13.273L18.727,32c0,0,0-10.793,0-13.27c2.477,0,13.273,0,13.273,0L13.273,0H0z M11.797,3.562 c0.773,0.77,7.879,7.883,11.602,11.605c-3.102,0-8.234,0-8.234,0s0,5.133,0,8.227C11.441,19.676,4.336,12.566,3.562,11.801 c0-1.055,0-5.961,0-8.238C5.84,3.562,10.742,3.562,11.797,3.562z"/> </g></g></svg>',
trash_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M28,4h-4c0-2.211-1.789-4-4-4h-8C9.789,0,8,1.789,8,4H4H0v4h4v18c0,3.312,2.688,6,6,6h12 c3.312,0,6-2.688,6-6V8h4V4H28z M12,24c-1.105,0-2-0.896-2-2s0.895-2,2-2s2,0.896,2,2S13.105,24,12,24z M12,16c-1.105,0-2-0.896-2-2 s0.895-2,2-2s2,0.896,2,2S13.105,16,12,16z M20,24c-1.105,0-2-0.896-2-2s0.895-2,2-2s2,0.896,2,2S21.105,24,20,24z M20,16 c-1.105,0-2-0.896-2-2s0.895-2,2-2s2,0.896,2,2S21.105,16,20,16z"/></svg>',
trash_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M32,4h-4h-4c0-2.211-1.789-4-4-4h-8C9.789,0,8,1.789,8,4H4H0v4h4v18c0,3.312,2.688,6,6,6h12 c3.312,0,6-2.688,6-6V8h4V4z M24,26c0,1.102-0.898,2-2,2H10c-1.102,0-2-0.898-2-2V8h16V26z"/> <circle style="{style}" cx="12" cy="22" r="2"/> <circle style="{style}" cx="12" cy="14" r="2"/> <circle style="{style}" cx="20" cy="22" r="2"/> <circle style="{style}" cx="20" cy="14" r="2"/></g></svg>',
undo: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 31.985" style="enable-background:new 0 0 32 31.985;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M28.156,3.72c-4.957-4.958-13.604-4.961-18.557,0L4,9.32V4.001H0v12h12v-4H6.975l5.453-5.453 c3.447-3.445,9.453-3.445,12.9,0.007C27.053,8.274,28,10.563,28,13.001s-0.947,4.727-2.672,6.453l-3.016,3.008l2.828,2.828 l3.016-3.008C30.631,19.805,32,16.508,32,13.001C32,9.493,30.631,6.196,28.156,3.72z"/> <rect x="16.449" y="27.157" transform="matrix(0.7071 0.7071 -0.7071 0.7071 26.0209 -4.5056)" style="{style}" width="4" height="4"/></g></svg>',
unlock_fill: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 24.008 32" style="enable-background:new 0 0 24.008 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M14.008,0c-5.516,0-10,4.487-10,10h4c0-3.309,2.688-6,6-6c3.305,0,6,2.691,6,6v2H0v14 c0,3.308,2.695,6,6,6h12.008c3.305,0,6-2.692,6-6V10C24.008,4.487,19.518,0,14.008,0z M12,24c-1.102,0-2-0.896-2-2 c0-1.105,0.898-2,2-2c1.109,0,2,0.895,2,2C14,23.104,13.109,24,12,24z"/></svg>',
unlock_stroke: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 24.008 32" style="enable-background:new 0 0 24.008 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M14.008,0c-5.516,0-10,4.489-10,10h4c0-3.305,2.691-6,6-6s6,2.695,6,6v2H0v14c0,3.312,2.691,6,6,6 h12.008c3.309,0,6-2.688,6-6V10C24.008,4.489,19.523,0,14.008,0z M18.008,28H6c-1.102,0-2-0.896-2-2V16h16.008v10 C20.008,27.104,19.109,28,18.008,28z"/> <path fill="{fill}"style="{style}" d="M14.004,22c0,1.109-0.895,2-2,2s-2-0.891-2-2c0-1.102,0.895-2,2-2S14.004,20.898,14.004,22z"/></g></svg>',
user: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 24 32" style="enable-background:new 0 0 24 32;" xml:space="preserve"><g> <path fill="{fill}"style="{style}" d="M12,16C5.375,16,0,21.372,0,28c0,2.208,1.789,4,4,4h16c2.211,0,4-1.792,4-4 C24,21.372,18.625,16,12,16z"/> <circle style="{style}" cx="12" cy="6" r="6"/></g></svg>',
volume: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" style="enable-background:new 0 0 32 24;" xml:space="preserve"><g> <g> <path fill="{fill}"style="{style}" d="M8,20c-4.416,0-8-3.579-8-8s3.584-8,8-8V20z"/> </g> <g> <polygon style="{style}" points="12,4 20,0 20,24 12,20 "/> </g> <path fill="{fill}"style="{style}" d="M24.006,19.999v-4c0.328,0,0.666-0.046,1-0.125C26.762,15.423,28,13.829,28,12 s-1.238-3.422-3.01-3.874c-0.318-0.078-0.656-0.118-0.984-0.118v-4c0.656,0,1.312,0.085,1.953,0.241C29.521,5.155,32,8.336,32,12 c0,3.671-2.479,6.858-6.025,7.751C25.309,19.914,24.652,19.999,24.006,19.999L24.006,19.999z"/></g></svg>',
volume_mute: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 24" style="enable-background:new 0 0 32 24;" xml:space="preserve"><g> <g> <path fill="{fill}"style="{style}" d="M8,20c-4.418,0-8-3.583-8-8s3.582-8,8-8V20z"/> </g> <g> <polygon style="{style}" points="12,4 20,0 20,24 12,20 "/> </g> <polygon style="{style}" points="32,14 24,14 24,10 32,10 32,14 "/></g></svg>',
x: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 28 28" style="enable-background:new 0 0 28 28;" xml:space="preserve"><g> <polygon style="{style}" points="28,22.398 19.594,14 28,5.602 22.398,0 14,8.402 5.598,0 0,5.602 8.398,14 0,22.398 5.598,28 14,19.598 22.398,28 "/></g></svg>',
x_alt: '<svg version="1.1" id="{id}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="{width}" height="{height}" viewBox="0 0 32 32" style="enable-background:new 0 0 32 32;" xml:space="preserve"><path fill="{fill}"style="{style}" d="M16,0C7.164,0,0,7.164,0,16s7.164,16,16,16s16-7.164,16-16S24.836,0,16,0z M23.914,21.086 l-2.828,2.828L16,18.828l-5.086,5.086l-2.828-2.828L13.172,16l-5.086-5.086l2.828-2.828L16,13.172l5.086-5.086l2.828,2.828 L18.828,16L23.914,21.086z"/></svg>',
}
end
end
|
#
# Be sure to run `pod spec lint HTTPIDL.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
# ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# These will help people to find your library, and whilst it
# can feel like a chore to fill in it's definitely to your advantage. The
# summary should be tweet-length, and the description more in depth.
#
s.name = "HTTPIDL"
s.version = "0.1.1"
s.summary = "http idl"
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
HTTP message generator for Swift 3
DESC
s.homepage = "https://github.com/cikelengfeng/HTTPIDL"
# s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif"
# ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Licensing your code is important. See http://choosealicense.com for more info.
# CocoaPods will detect a license file if there is a named LICENSE*
# Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'.
#
#s.license = "MIT (example)"
s.license = { :type => "MIT", :file => "LICENSE" }
# ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the authors of the library, with email addresses. Email addresses
# of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also
# accepts just a name if you'd rather not provide an email address.
#
# Specify a social_media_url where others can refer to, for example a twitter
# profile URL.
#
s.author = { "DongXu" => "cikelengfeng@gmail.com" }
# Or just: s.author = "DongXu"
# s.authors = { "DongXu" => "cikelengfeng@gmail.com" }
# s.social_media_url = "http://twitter.com/DongXu"
# ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If this Pod runs only on iOS or OS X, then specify the platform and
# the deployment target. You can optionally include the target after the platform.
#
# s.platform = :ios
s.platform = :ios, "8.0"
# When using multiple platforms
# s.ios.deployment_target = "5.0"
# s.osx.deployment_target = "10.7"
# s.watchos.deployment_target = "2.0"
# s.tvos.deployment_target = "9.0"
# ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the location from where the source should be retrieved.
# Supports git, hg, bzr, svn and HTTP.
#
s.source = { :git => "https://github.com/cikelengfeng/HTTPIDL.git", :tag => s.version.to_s }
# ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# CocoaPods is smart about how it includes source code. For source files
# giving a folder will include any swift, h, m, mm, c & cpp files.
# For header files it will include any header in the folder.
# Not including the public_header_files will make all headers public.
#
s.source_files = "Sources/Runtime/**/*.swift"
s.exclude_files = "Sources/Exclude"
# s.public_header_files = "Classes/**/*.h"
# ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# A list of resources included with the Pod. These are copied into the
# target bundle with a build phase script. Anything else will be cleaned.
# You can preserve files from being cleaned, please don't preserve
# non-essential files like tests, examples and documentation.
#
# s.resource = "icon.png"
# s.resources = "Resources/*.png"
s.preserve_paths = "Sources/Compiler/*.py", "Sources/Compiler/**/*.{py,tokens}"
# ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Link your library with frameworks, or libraries. Libraries do not include
# the lib prefix of their name.
#
# s.framework = "SomeFramework"
# s.frameworks = "SomeFramework", "AnotherFramework"
# s.library = "iconv"
# s.libraries = "iconv", "xml2"
# ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If your library depends on compiler flags you can set them in the xcconfig hash
# where they will only apply to your library. If you depend on other Podspecs
# you can include multiple dependencies to ensure it works.
# s.requires_arc = true
# s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
# s.dependency "JSONKit", "~> 1.4"
s.dependency "Alamofire"
s.dependency "GzipSwift"
end
[MOD] version
#
# Be sure to run `pod spec lint HTTPIDL.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
# ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# These will help people to find your library, and whilst it
# can feel like a chore to fill in it's definitely to your advantage. The
# summary should be tweet-length, and the description more in depth.
#
s.name = "HTTPIDL"
s.version = "0.2.0"
s.summary = "http idl"
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
HTTP message generator for Swift 3
DESC
s.homepage = "https://github.com/cikelengfeng/HTTPIDL"
# s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif"
# ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Licensing your code is important. See http://choosealicense.com for more info.
# CocoaPods will detect a license file if there is a named LICENSE*
# Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'.
#
#s.license = "MIT (example)"
s.license = { :type => "MIT", :file => "LICENSE" }
# ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the authors of the library, with email addresses. Email addresses
# of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also
# accepts just a name if you'd rather not provide an email address.
#
# Specify a social_media_url where others can refer to, for example a twitter
# profile URL.
#
s.author = { "DongXu" => "cikelengfeng@gmail.com" }
# Or just: s.author = "DongXu"
# s.authors = { "DongXu" => "cikelengfeng@gmail.com" }
# s.social_media_url = "http://twitter.com/DongXu"
# ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If this Pod runs only on iOS or OS X, then specify the platform and
# the deployment target. You can optionally include the target after the platform.
#
# s.platform = :ios
s.platform = :ios, "8.0"
# When using multiple platforms
# s.ios.deployment_target = "5.0"
# s.osx.deployment_target = "10.7"
# s.watchos.deployment_target = "2.0"
# s.tvos.deployment_target = "9.0"
# ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the location from where the source should be retrieved.
# Supports git, hg, bzr, svn and HTTP.
#
s.source = { :git => "https://github.com/cikelengfeng/HTTPIDL.git", :tag => s.version.to_s }
# ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# CocoaPods is smart about how it includes source code. For source files
# giving a folder will include any swift, h, m, mm, c & cpp files.
# For header files it will include any header in the folder.
# Not including the public_header_files will make all headers public.
#
s.source_files = "Sources/Runtime/**/*.swift"
s.exclude_files = "Sources/Exclude"
# s.public_header_files = "Classes/**/*.h"
# ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# A list of resources included with the Pod. These are copied into the
# target bundle with a build phase script. Anything else will be cleaned.
# You can preserve files from being cleaned, please don't preserve
# non-essential files like tests, examples and documentation.
#
# s.resource = "icon.png"
# s.resources = "Resources/*.png"
s.preserve_paths = "Sources/Compiler/*.py", "Sources/Compiler/**/*.{py,tokens}"
# ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Link your library with frameworks, or libraries. Libraries do not include
# the lib prefix of their name.
#
# s.framework = "SomeFramework"
# s.frameworks = "SomeFramework", "AnotherFramework"
# s.library = "iconv"
# s.libraries = "iconv", "xml2"
# ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If your library depends on compiler flags you can set them in the xcconfig hash
# where they will only apply to your library. If you depend on other Podspecs
# you can include multiple dependencies to ensure it works.
# s.requires_arc = true
# s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
# s.dependency "JSONKit", "~> 1.4"
s.dependency "Alamofire"
s.dependency "GzipSwift"
end
|
# encoding: utf-8
require 'rchardet'
module ActiveAdminImport
class Model
include ActiveModel::Model
include ActiveModel::Validations
include ActiveModel::Validations::Callbacks
validates :file, presence: {
message: ->(*_){ I18n.t("active_admin_import.no_file_error") }
}, unless: ->(me){ me.new_record? }
validate :correct_content_type, if: ->(me) { me.file.present? }
validate :file_contents_present, if: ->(me) { me.file.present? }
before_validation :unzip_file, if: ->(me) { me.archive? && me.allow_archive? }
before_validation :encode_file, if: ->(me) { me.force_encoding? && me.file.present? }
attr_reader :attributes
def initialize(args={})
@new_record = true
@attributes = {}
assign_attributes(default_attributes.merge(args), true)
end
def assign_attributes(args = {}, new_record = false)
@attributes.merge!(args)
@new_record = new_record
args.keys.each do |key|
define_methods_for(key.to_sym)
end if args.is_a?(Hash)
end
def read_attribute_for_validation(key)
@attributes[key.to_sym]
end
def default_attributes
{
allow_archive: true,
csv_headers: [],
file: nil,
force_encoding: "UTF-8",
hint: ""
}
end
def allow_archive?
!!attributes[:allow_archive]
end
def new_record?
!!@new_record
end
def force_encoding?
!!attributes[:force_encoding]
end
def persisted?
false
end
def archive?
file_type == 'application/zip'
end
alias :to_hash :attributes
protected
def file_path
if file.is_a? ActionDispatch::Http::UploadedFile
file.tempfile.path
else
file.path
end
end
def encode_file
data = File.read(file_path)
File.open(file_path, 'w') do |f|
f.write(encode(data))
end
end
def unzip_file
Zip::File.open(file_path) do |zip_file|
self.file = Tempfile.new('active-admin-import-unzipped')
data = zip_file.entries.select { |f| f.file? }.first.get_input_stream.read
self.file << data
self.file.close
end
end
def csv_allowed_types
[
'text/csv',
'text/x-csv',
'text/comma-separated-values',
'application/csv',
'application/vnd.ms-excel',
'application/vnd.msexcel'
]
end
def correct_content_type
unless file.blank? || file.is_a?(Tempfile)
errors.add(:file, I18n.t('active_admin_import.file_format_error')) unless csv_allowed_types.include? file_type
end
end
def file_contents_present
errors.add(:file, I18n.t('active_admin_import.file_empty_error')) if File.zero?(file_path)
end
def file_type
if file.is_a? ActionDispatch::Http::UploadedFile
file.content_type.chomp
else
''
end
end
protected
def define_methods_for(attr_name)
#generate methods for instance object by attributes
singleton_class.class_eval do
define_set_method(attr_name)
define_get_method(attr_name)
end
end
def encode(data)
data = content_encode(data) if force_encoding?
data = data.encode('UTF-8',
invalid: :replace, undef: :replace)
begin
data.sub("\xEF\xBB\xBF", '') # bom
rescue StandardError => _
data
end
end
def detect_encoding?
force_encoding == :auto
end
def dynamic_encoding(data)
CharDet.detect(data)['encoding']
end
def content_encode(data)
encoding_name = if detect_encoding?
dynamic_encoding(data)
else
force_encoding.to_s
end
data.force_encoding(encoding_name)
end
class <<self
def define_set_method(attr_name)
define_method(attr_name) { self.attributes[attr_name] } unless method_defined? attr_name
end
def define_get_method(attr_name)
define_method("#{attr_name}=") { |new_value| @attributes[attr_name] = new_value } unless method_defined? "#{attr_name}="
end
end
end
end
universal_newline - Replaces \rn and \r with \n
# encoding: utf-8
require 'rchardet'
module ActiveAdminImport
class Model
include ActiveModel::Model
include ActiveModel::Validations
include ActiveModel::Validations::Callbacks
validates :file, presence: {
message: ->(*_){ I18n.t("active_admin_import.no_file_error") }
}, unless: ->(me){ me.new_record? }
validate :correct_content_type, if: ->(me) { me.file.present? }
validate :file_contents_present, if: ->(me) { me.file.present? }
before_validation :unzip_file, if: ->(me) { me.archive? && me.allow_archive? }
before_validation :encode_file, if: ->(me) { me.force_encoding? && me.file.present? }
attr_reader :attributes
def initialize(args={})
@new_record = true
@attributes = {}
assign_attributes(default_attributes.merge(args), true)
end
def assign_attributes(args = {}, new_record = false)
@attributes.merge!(args)
@new_record = new_record
args.keys.each do |key|
define_methods_for(key.to_sym)
end if args.is_a?(Hash)
end
def read_attribute_for_validation(key)
@attributes[key.to_sym]
end
def default_attributes
{
allow_archive: true,
csv_headers: [],
file: nil,
force_encoding: "UTF-8",
hint: ""
}
end
def allow_archive?
!!attributes[:allow_archive]
end
def new_record?
!!@new_record
end
def force_encoding?
!!attributes[:force_encoding]
end
def persisted?
false
end
def archive?
file_type == 'application/zip'
end
alias :to_hash :attributes
protected
def file_path
if file.is_a? ActionDispatch::Http::UploadedFile
file.tempfile.path
else
file.path
end
end
def encode_file
data = File.read(file_path)
File.open(file_path, 'w') do |f|
f.write(encode(data))
end
end
def unzip_file
Zip::File.open(file_path) do |zip_file|
self.file = Tempfile.new('active-admin-import-unzipped')
data = zip_file.entries.select { |f| f.file? }.first.get_input_stream.read
self.file << data
self.file.close
end
end
def csv_allowed_types
[
'text/csv',
'text/x-csv',
'text/comma-separated-values',
'application/csv',
'application/vnd.ms-excel',
'application/vnd.msexcel'
]
end
def correct_content_type
unless file.blank? || file.is_a?(Tempfile)
errors.add(:file, I18n.t('active_admin_import.file_format_error')) unless csv_allowed_types.include? file_type
end
end
def file_contents_present
errors.add(:file, I18n.t('active_admin_import.file_empty_error')) if File.zero?(file_path)
end
def file_type
if file.is_a? ActionDispatch::Http::UploadedFile
file.content_type.chomp
else
''
end
end
protected
def define_methods_for(attr_name)
#generate methods for instance object by attributes
singleton_class.class_eval do
define_set_method(attr_name)
define_get_method(attr_name)
end
end
def encode(data)
data = content_encode(data) if force_encoding?
data = data.encode(
'UTF-8',
invalid: :replace, undef: :replace, universal_newline: true
)
begin
data.sub("\xEF\xBB\xBF", '') # bom
rescue StandardError => _
data
end
end
def detect_encoding?
force_encoding == :auto
end
def dynamic_encoding(data)
CharDet.detect(data)['encoding']
end
def content_encode(data)
encoding_name = if detect_encoding?
dynamic_encoding(data)
else
force_encoding.to_s
end
data.force_encoding(encoding_name)
end
class <<self
def define_set_method(attr_name)
define_method(attr_name) { self.attributes[attr_name] } unless method_defined? attr_name
end
def define_get_method(attr_name)
define_method("#{attr_name}=") { |new_value| @attributes[attr_name] = new_value } unless method_defined? "#{attr_name}="
end
end
end
end
|
module ActiveAdminParanoia
module DSL
def active_admin_paranoia
controller do
def find_resource
resource_class.to_s.camelize.constantize.with_deleted.where(id: params[:id]).first!
end
end
batch_action :destroy, confirm: proc{ I18n.t('active_admin.batch_actions.delete_confirmation', plural_model: resource_class.to_s.downcase.pluralize) }, if: proc{ authorized?(ActiveAdmin::Auth::DESTROY, resource_class) && params[:scope] != 'archived' } do |ids|
resource_class.to_s.camelize.constantize.where(id: ids).destroy_all
redirect_to :back, notice: I18n.t('active_admin.batch_actions.succesfully_destroyed', count: ids.count, model: resource_class.to_s.camelize.constantize.model_name, plural_model: resource_class.to_s.downcase.pluralize)
end
batch_action :restore, confirm: proc{ I18n.t('active_admin_paranoia.batch_actions.restore_confirmation', plural_model: resource_class.to_s.downcase.pluralize) }, if: proc{ authorized?(ActiveAdminParanoia::Auth::RESTORE, resource_class) && params[:scope] == 'archived' } do |ids|
resource_class.to_s.camelize.constantize.restore(ids, recursive: true)
redirect_to :back, notice: I18n.t('active_admin_paranoia.batch_actions.succesfully_restored', count: ids.count, model: resource_class.to_s.camelize.constantize.model_name, plural_model: resource_class.to_s.downcase.pluralize)
end
member_action :restore, method: :put, confirm: proc{ I18n.t('active_admin_paranoia.restore_confirmation') }, if: proc{ authorized?(ActiveAdminParanoia::Auth::RESTORE, resource_class) } do
resource.restore
redirect_to :back, notice: I18n.t('active_admin_paranoia.batch_actions.succesfully_restored', count: 1, model: resource_class.to_s.camelize.constantize.model_name, plural_model: resource_class.to_s.downcase.pluralize)
end
scope(I18n.t('active_admin_paranoia.non_archived'), default: true) { |scope| scope.where(resource_class.to_s.camelize.constantize.paranoia_column => resource_class.to_s.camelize.constantize.paranoia_sentinel_value) }
scope(I18n.t('active_admin_paranoia.archived')) { |scope| scope.unscope(:where => resource_class.to_s.camelize.constantize.paranoia_column).where.not(resource_class.to_s.camelize.constantize.paranoia_column => resource_class.to_s.camelize.constantize.paranoia_sentinel_value) }
end
end
end
module ActiveAdmin
module Views
class IndexAsTable < ActiveAdmin::Component
class IndexTableFor < ::ActiveAdmin::Views::TableFor
alias_method :orig_defaults, :defaults
def defaults(resource, options = {})
if resource.deleted?
if controller.action_methods.include?('restore') && authorized?(ActiveAdminParanoia::Auth::RESTORE, resource_class)
# TODO: find a way to use the correct path helper
item I18n.t('active_admin_paranoia.restore'), "#{resource_path(resource)}/restore", method: :put, class: "restore_link #{options[:css_class]}",
data: {confirm: I18n.t('active_admin_paranoia.restore_confirmation')}
end
else
orig_defaults(resource, options)
end
end
end
end
end
end
Restore recursive in member action
module ActiveAdminParanoia
module DSL
def active_admin_paranoia
controller do
def find_resource
resource_class.to_s.camelize.constantize.with_deleted.where(id: params[:id]).first!
end
end
batch_action :destroy, confirm: proc{ I18n.t('active_admin.batch_actions.delete_confirmation', plural_model: resource_class.to_s.downcase.pluralize) }, if: proc{ authorized?(ActiveAdmin::Auth::DESTROY, resource_class) && params[:scope] != 'archived' } do |ids|
resource_class.to_s.camelize.constantize.where(id: ids).destroy_all
redirect_to :back, notice: I18n.t('active_admin.batch_actions.succesfully_destroyed', count: ids.count, model: resource_class.to_s.camelize.constantize.model_name, plural_model: resource_class.to_s.downcase.pluralize)
end
batch_action :restore, confirm: proc{ I18n.t('active_admin_paranoia.batch_actions.restore_confirmation', plural_model: resource_class.to_s.downcase.pluralize) }, if: proc{ authorized?(ActiveAdminParanoia::Auth::RESTORE, resource_class) && params[:scope] == 'archived' } do |ids|
resource_class.to_s.camelize.constantize.restore(ids, recursive: true)
redirect_to :back, notice: I18n.t('active_admin_paranoia.batch_actions.succesfully_restored', count: ids.count, model: resource_class.to_s.camelize.constantize.model_name, plural_model: resource_class.to_s.downcase.pluralize)
end
member_action :restore, method: :put, confirm: proc{ I18n.t('active_admin_paranoia.restore_confirmation') }, if: proc{ authorized?(ActiveAdminParanoia::Auth::RESTORE, resource_class) } do
resource.restore(recursive: true)
redirect_to :back, notice: I18n.t('active_admin_paranoia.batch_actions.succesfully_restored', count: 1, model: resource_class.to_s.camelize.constantize.model_name, plural_model: resource_class.to_s.downcase.pluralize)
end
scope(I18n.t('active_admin_paranoia.non_archived'), default: true) { |scope| scope.where(resource_class.to_s.camelize.constantize.paranoia_column => resource_class.to_s.camelize.constantize.paranoia_sentinel_value) }
scope(I18n.t('active_admin_paranoia.archived')) { |scope| scope.unscope(:where => resource_class.to_s.camelize.constantize.paranoia_column).where.not(resource_class.to_s.camelize.constantize.paranoia_column => resource_class.to_s.camelize.constantize.paranoia_sentinel_value) }
end
end
end
module ActiveAdmin
module Views
class IndexAsTable < ActiveAdmin::Component
class IndexTableFor < ::ActiveAdmin::Views::TableFor
alias_method :orig_defaults, :defaults
def defaults(resource, options = {})
if resource.deleted?
if controller.action_methods.include?('restore') && authorized?(ActiveAdminParanoia::Auth::RESTORE, resource_class)
# TODO: find a way to use the correct path helper
item I18n.t('active_admin_paranoia.restore'), "#{resource_path(resource)}/restore", method: :put, class: "restore_link #{options[:css_class]}",
data: {confirm: I18n.t('active_admin_paranoia.restore_confirmation')}
end
else
orig_defaults(resource, options)
end
end
end
end
end
end
|
module ActiveInteraction
class InteractionInvalid < ::StandardError; end
class InvalidDefaultValue < ::StandardError; end
class InvalidNestedValue < ::StandardError; end
class InvalidValue < ::StandardError; end
class MissingValue < ::StandardError; end
end
Clean up error definitions
module ActiveInteraction
InteractionInvalid = Class.new(StandardError)
InvalidDefaultValue = Class.new(StandardError)
InvalidNestedValue = Class.new(StandardError)
InvalidValue = Class.new(StandardError)
MissingValue = Class.new(StandardError)
end
|
module ActiveRecord::AttrHidden
def self.included(base)
base.instance_variable_set("@hidden_attributes", [])
class << base
#
# Hide any number of attributes in a model.
# This is expecially useful for Single Table Inheritance.
#
# Subclasses of the model in which attr_hidden is called will
# hide the attributes too (which is a desiderable behaviour in an
# object hierarchy), and can hide further attributes.
#
# usage:
#
# attr_hidden :attr1, :attr2, ...
#
def attr_hidden(*attrs)
@hidden_attributes += attrs.map(&:to_s)
end
#
# If you want to show attributes in a subclass and you have hidden
# them in its superclass, you can unhide it using:
#
# attr_not_hidden :attr1, :attr2, ...
#
def attr_not_hidden(*attrs)
@hidden_attributes -= attrs.map(&:to_s)
end
# list of attribute hidden in a model
attr_reader :hidden_attributes
def columns_with_attr_hidden
columns_without_attr_hidden.delete_if{|c|@hidden_attributes.include?(c.name)}
end
alias_method_chain :columns, :attr_hidden
#
# convenience methods to hide/unhide attributes *only* in all subclasses
# without hiding/unhiding them in the current class;
#
# this behaviour hiding/unhiding can be then overridden in single subclasses
# calling attr_hidden / attr_unhidden as appropriate
#
[:attr_hidden, :attr_not_hidden].each do |macro|
define_method "#{macro}_in_subclasses" do |*attrs|
(class << self; self; end).class_eval do
private
define_method "inherited_with_#{macro}_in_subclasses" do |subklass|
send("inherited_without_#{macro}_in_subclasses", subklass)
subklass.class_eval { send(*attrs.unshift(macro)) }
end
alias_method_chain :inherited, :"#{macro}_in_subclasses"
end
end
end
private
def instantiate_with_attr_hidden(record)
instantiate_without_attr_hidden(record.delete_if{|k,v|@hidden_attributes.include?(k)})
end
alias_method_chain :instantiate, :attr_hidden
# allow subclasses to inherit the attr_hidden of their superclass
def inherited_with_attr_hidden(subclass)
subclass.instance_variable_set("@hidden_attributes", @hidden_attributes)
end
alias_method_chain :inherited, :attr_hidden
end
end
end
added comment on the new feature
which I should later transform in an unit test,
as soon as I have learnt how to correctly do unit
tests in active record plugins :)
I currently test it in a "mock" rails application
(tests not included in this plugin)
module ActiveRecord::AttrHidden
def self.included(base)
base.instance_variable_set("@hidden_attributes", [])
class << base
#
# Hide any number of attributes in a model.
# This is expecially useful for Single Table Inheritance.
#
# Subclasses of the model in which attr_hidden is called will
# hide the attributes too (which is a desiderable behaviour in an
# object hierarchy), and can hide further attributes.
#
# usage:
#
# attr_hidden :attr1, :attr2, ...
#
def attr_hidden(*attrs)
@hidden_attributes += attrs.map(&:to_s)
end
#
# If you want to show attributes in a subclass and you have hidden
# them in its superclass, you can unhide it using:
#
# attr_not_hidden :attr1, :attr2, ...
#
def attr_not_hidden(*attrs)
@hidden_attributes -= attrs.map(&:to_s)
end
# list of attribute hidden in a model
attr_reader :hidden_attributes
def columns_with_attr_hidden
columns_without_attr_hidden.delete_if{|c|@hidden_attributes.include?(c.name)}
end
alias_method_chain :columns, :attr_hidden
#
# convenience methods to hide/unhide attributes *only* in all subclasses
# without hiding/unhiding them in the current class;
#
# this behaviour hiding/unhiding can be then overridden in single subclasses
# calling attr_hidden / attr_unhidden as appropriate
#
# example usage
# table column list: a1, a2, a3
#
# class A; attr_hidden :a1; end => hidden a1 / visible a2, a3
# class B<A; attr_hidden :a2; end => hidden a1, a2 / visible a3
# class D<B; attr_not_hidden; :a2; end => hidden a1 / visible a2, a3
# class C<B; end => hidden a1, a2 / visible a3
#
# class D<A; attr_hidden_in_subclasses :a3; end => hidden a1, a2 / visible a3, a4
# class E<D; end => hidden a1, a2, a3 / visible a4
#
# * known issue of the current implementation: *
#
# that overrides of ..._in_subclasses are by default not inherited in its subclasses
#
# class F<D; attr_not_hidden :a3; end => hidden a1, a2 / visible a3, a4
# class G<F; end => hidden a1, a2, a3 / visible a4 (!!!!)
#
# the inheritability must be explicitly specified this way:
#
# class H<D; attr_not_hidden :a3; attr_not_hidden_in_subclasses; end => hidden a1, a2 / visible a3, a4
# class I<H; end => hidden a1, a2 / visible a3, a4
#
[:attr_hidden, :attr_not_hidden].each do |macro|
define_method "#{macro}_in_subclasses" do |*attrs|
(class << self; self; end).class_eval do
private
define_method "inherited_with_#{macro}_in_subclasses" do |subklass|
send("inherited_without_#{macro}_in_subclasses", subklass)
subklass.class_eval { send(*attrs.unshift(macro)) }
end
alias_method_chain :inherited, :"#{macro}_in_subclasses"
end
end
end
private
def instantiate_with_attr_hidden(record)
instantiate_without_attr_hidden(record.delete_if{|k,v|@hidden_attributes.include?(k)})
end
alias_method_chain :instantiate, :attr_hidden
# allow subclasses to inherit the attr_hidden of their superclass
def inherited_with_attr_hidden(subclass)
subclass.instance_variable_set("@hidden_attributes", @hidden_attributes)
end
alias_method_chain :inherited, :attr_hidden
end
end
end
|
class ActiveScaffold::Tableless < ActiveRecord::Base
class AssociationScope < ActiveRecord::Associations::AssociationScope
def column_for(table_name, column_name)
if table_name == klass.table_name
klass.columns_hash[column_name]
else
super
end
end
end
module Association
def self.included(base)
base.alias_method_chain :association_scope, :tableless
end
def association_scope_with_tableless
@association_scope ||= AssociationScope.new(self).scope if klass < ActiveScaffold::Tableless
association_scope_without_tableless
end
end
class Relation < ActiveRecord::Relation
attr_reader :conditions
def initialize(klass, table)
super
@conditions ||= []
end
def initialize_copy(other)
@conditions = @conditions.dup
super
end
def where(opts, *rest)
unless opts.blank?
opts = opts.with_indifferent_access if opts.is_a? Hash
@conditions << (rest.empty? ? opts : [opts, *rest])
end
self
end
def merge(r)
super.tap do |merged|
merged.conditions.concat r.conditions unless r.nil? || r.is_a?(Array)
end
end
def except(*skips)
super.tap do |new_relation|
new_relation.conditions = conditions unless skips.include? :where
end
end
def to_a
@klass.find_all(self)
end
def find_one(id)
@klass.find_one(id, self) or raise ActiveRecord::RecordNotFound
end
def execute_simple_calculation(operation, column_name, distinct)
@klass.execute_simple_calculation(self, operation, column_name, distinct)
end
end
def self.columns; @columns ||= []; end
def self.table_name; @table_name ||= ActiveModel::Naming.plural(self); end
def self.table_exists?; true; end
self.abstract_class = true
class << self
private
def relation
ActiveScaffold::Tableless::Relation.new(self, arel_table)
end
end
def self.column(name, sql_type = nil, options = {})
column = ActiveRecord::ConnectionAdapters::Column.new(name.to_s, options[:default], sql_type.to_s, options.has_key?(:null) ? options[:null] : true)
column.tap { columns << column }
end
def self.find_all(relation)
raise 'self.find_all must be implemented in a Tableless model'
end
def self.find_one(id, relation)
raise 'self.find_one must be implemented in a Tableless model'
end
def self.execute_simple_calculation(relation, operation, column_name, distinct)
if operation == 'count' && [relation.klass.primary_key, :all].include?(column_name)
find_all(relation).size
else
raise "self.execute_simple_calculation must be implemented in a Tableless model to support #{operation} #{column_name}#{' distinct' if distinct} columns"
end
end
def destroy
raise 'destroy must be implemented in a Tableless model'
end
def create #:nodoc:
run_callbacks(:create) {}
end
def update(*) #:nodoc:
run_callbacks(:update) {}
end
end
fix tableless for rails 4.0.1
class ActiveScaffold::Tableless < ActiveRecord::Base
class AssociationScope < ActiveRecord::Associations::AssociationScope
def column_for(table_name, column_name)
if table_name == klass.table_name
klass.columns_hash[column_name]
else
super
end
end
end
module Association
def self.included(base)
base.alias_method_chain :association_scope, :tableless
base.alias_method_chain :target_scope, :tableless
end
def association_scope_with_tableless
@association_scope ||= AssociationScope.new(self).scope if klass < ActiveScaffold::Tableless
association_scope_without_tableless
end
def target_scope_with_tableless
target_scope_without_tableless.tap do |scope|
if klass < ActiveScaffold::Tableless
class << scope; include RelationExtension; end
end
end
end
end
module RelationExtension
def conditions
@conditions
end
def initialize(klass, table)
super
@conditions ||= []
end
def initialize_copy(other)
@conditions = @conditions.dup
super
end
def where(opts, *rest)
unless opts.blank?
opts = opts.with_indifferent_access if opts.is_a? Hash
@conditions << (rest.empty? ? opts : [opts, *rest])
end
self
end
def merge(r)
super.tap do |merged|
merged.conditions.concat r.conditions unless r.nil? || r.is_a?(Array)
end
end
def except(*skips)
super.tap do |new_relation|
new_relation.conditions = conditions unless skips.include? :where
end
end
def to_a
@klass.find_all(self)
end
def find_one(id)
@klass.find_one(id, self) or raise ActiveRecord::RecordNotFound
end
def execute_simple_calculation(operation, column_name, distinct)
@klass.execute_simple_calculation(self, operation, column_name, distinct)
end
end
# For rails3
class Relation < ActiveRecord::Relation
include RelationExtension
end
def self.columns; @columns ||= []; end
def self.table_name; @table_name ||= ActiveModel::Naming.plural(self); end
def self.table_exists?; true; end
self.abstract_class = true
# For rails3
class << self
private
def relation
ActiveScaffold::Tableless::Relation.new(self, arel_table)
end
end
def self.column(name, sql_type = nil, options = {})
column = ActiveRecord::ConnectionAdapters::Column.new(name.to_s, options[:default], sql_type.to_s, options.has_key?(:null) ? options[:null] : true)
column.tap { columns << column }
end
def self.find_all(relation)
raise 'self.find_all must be implemented in a Tableless model'
end
def self.find_one(id, relation)
raise 'self.find_one must be implemented in a Tableless model'
end
def self.execute_simple_calculation(relation, operation, column_name, distinct)
if operation == 'count' && [relation.klass.primary_key, :all].include?(column_name)
find_all(relation).size
else
raise "self.execute_simple_calculation must be implemented in a Tableless model to support #{operation} #{column_name}#{' distinct' if distinct} columns"
end
end
def destroy
raise 'destroy must be implemented in a Tableless model'
end
def create #:nodoc:
run_callbacks(:create) {}
end
def update(*) #:nodoc:
run_callbacks(:update) {}
end
end
|
module ActsAsMessageable
module Model
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
mattr_accessor :messages_class_name
# Method make ActiveRecord::Base object messageable
# @param [Symbol] :table_name - table name for messages
def acts_as_messageable(options = {})
has_many :received_messages_relation,
:as => :received_messageable,
:class_name => options[:class_name] || "ActsAsMessageable::Message",
:dependent => :nullify
has_many :sent_messages_relation,
:as => :sent_messageable,
:class_name => options[:class_name] || "ActsAsMessageable::Message",
:dependent => :nullify
self.messages_class_name = (options[:class_name] || "ActsAsMessageable::Message").constantize
if self.messages_class_name.respond_to?(:table_name=)
self.messages_class_name.table_name = (options[:table_name] || "messages")
else
self.messages_class_name.set_table_name(options[:table_name] || "messages")
ActiveSupport::Deprecation.warn("Calling set_table_name is deprecated. Please use `self.table_name = 'the_name'` instead.")
end
if options[:required].is_a? Symbol
self.messages_class_name.required = [options[:required]]
elsif options[:required].is_a? Array
self.messages_class_name.required = options[:required]
else
self.messages_class_name.required = [:topic, :body]
end
self.messages_class_name.validates_presence_of self.messages_class_name.required
include ActsAsMessageable::Model::InstanceMethods
end
def resolve_active_record_ancestor
self.reflect_on_association(:received_messages_relation).active_record
end
end
module InstanceMethods
# Get all messages connected with user
# @return [ActiveRecord::Relation] all messages connected with user
def messages(trash = false)
result = self.class.messages_class_name.connected_with(self, trash)
result.relation_context = self
result
end
def received_messages
result = received_messages_relation.scoped.where(:recipient_delete => false)
result.relation_context = self
result
end
def sent_messages
result = sent_messages_relation.scoped.where(:sender_delete => false)
result.relation_context = self
result
end
def deleted_messages
messages true
end
# Method sens message to another user
# @param [ActiveRecord::Base] to
# @param [String] topic
# @param [String] body
#
# @return [ActsAsMessageable::Message] the message object
def send_message(to, *args)
case args.first
when String
message_attributes = {}
self.class.messages_class_name.required.each_with_index do |attribute, index|
message_attributes[attribute] = args[index]
end
when Hash
message_attributes = args.first
end
message = self.class.messages_class_name.create message_attributes
self.sent_messages_relation << message
to.received_messages_relation << message
message
end
def reply_to(message, *args)
current_user = self
if message.participant?(current_user)
reply_message = send_message(message.from, *args)
reply_message.parent = message
reply_message.save
reply_message
end
end
def delete_message(message)
current_user = self
if message.received_messageable == current_user
unless message.recipient_delete
message.update_attributes!(:recipient_delete => true)
else
message.update_attributes!(:recipient_permanent_delete => true)
end
elsif message.sent_messageable == current_user
unless message.sender_delete
message.update_attributes!(:sender_delete => true)
else
message.update_attributes!(:sender_permanent_delete => true)
end
end
end
end
end
end
Use Array.wrap to fetch required arguments.
module ActsAsMessageable
module Model
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
mattr_accessor :messages_class_name
# Method make ActiveRecord::Base object messageable
# @param [Symbol] :table_name - table name for messages
def acts_as_messageable(options = {})
has_many :received_messages_relation,
:as => :received_messageable,
:class_name => options[:class_name] || "ActsAsMessageable::Message",
:dependent => :nullify
has_many :sent_messages_relation,
:as => :sent_messageable,
:class_name => options[:class_name] || "ActsAsMessageable::Message",
:dependent => :nullify
self.messages_class_name = (options[:class_name] || "ActsAsMessageable::Message").constantize
if self.messages_class_name.respond_to?(:table_name=)
self.messages_class_name.table_name = (options[:table_name] || "messages")
else
self.messages_class_name.set_table_name(options[:table_name] || "messages")
ActiveSupport::Deprecation.warn("Calling set_table_name is deprecated. Please use `self.table_name = 'the_name'` instead.")
end
self.messages_class_name.required = Array.wrap(options[:required] || [:topic, :body])
self.messages_class_name.validates_presence_of self.messages_class_name.required
include ActsAsMessageable::Model::InstanceMethods
end
def resolve_active_record_ancestor
self.reflect_on_association(:received_messages_relation).active_record
end
end
module InstanceMethods
# Get all messages connected with user
# @return [ActiveRecord::Relation] all messages connected with user
def messages(trash = false)
result = self.class.messages_class_name.connected_with(self, trash)
result.relation_context = self
result
end
def received_messages
result = received_messages_relation.scoped.where(:recipient_delete => false)
result.relation_context = self
result
end
def sent_messages
result = sent_messages_relation.scoped.where(:sender_delete => false)
result.relation_context = self
result
end
def deleted_messages
messages true
end
# Method sens message to another user
# @param [ActiveRecord::Base] to
# @param [String] topic
# @param [String] body
#
# @return [ActsAsMessageable::Message] the message object
def send_message(to, *args)
case args.first
when String
message_attributes = {}
self.class.messages_class_name.required.each_with_index do |attribute, index|
message_attributes[attribute] = args[index]
end
when Hash
message_attributes = args.first
end
message = self.class.messages_class_name.create message_attributes
self.sent_messages_relation << message
to.received_messages_relation << message
message
end
def reply_to(message, *args)
current_user = self
if message.participant?(current_user)
reply_message = send_message(message.from, *args)
reply_message.parent = message
reply_message.save
reply_message
end
end
def delete_message(message)
current_user = self
if message.received_messageable == current_user
unless message.recipient_delete
message.update_attributes!(:recipient_delete => true)
else
message.update_attributes!(:recipient_permanent_delete => true)
end
elsif message.sent_messageable == current_user
unless message.sender_delete
message.update_attributes!(:sender_delete => true)
else
message.update_attributes!(:sender_permanent_delete => true)
end
end
end
end
end
end
|
require 'i2c/i2c'
include AdafruitServoDriver
class PWM
# Registers
MODE1 = 0x00
MODE2 = 0x01
SUBADR1 = 0x02
SUBADR2 = 0x03
SUBADR3 = 0x04
PRESCALE = 0xFE
LED0_ON_L = 0x06
LED0_ON_H = 0x07
LED0_OFF_L = 0x08
LED0_OFF_H = 0x09
ALL_LED_ON_L = 0xFA
ALL_LED_ON_H = 0xFB
ALL_LED_OFF_L = 0xFC
ALL_LED_OFF_H = 0xFD
# Bits
RESTART = 0x80
SLEEP = 0x10
ALLCALL = 0x01
INVRT = 0x10
OUTDRV = 0x04
def initialize(address=0x40, debug=false)
@address = address
@i2c = I2C.create(I2CDevice.detect)
@debug = debug
puts 'Reseting PCA9685 MODE1 (without SLEEP) and MODE2' if @debug
setAllPWM(0, 0)
@i2c.write(@address, MODE2, OUTDRV)
@i2c.write(@address, MODE1, ALLCALL)
sleep(0.005) # wait for oscillator
mode1 = @i2c.read(@address, 8, MODE1).unpack('C').first
@i2c.write(@address, MODE1, ALLCALL)
mode1 = mode1 & ~SLEEP # wake up (reset sleep)
@i2c.write(@address, MODE1, mode1)
sleep(0.005) # wait for oscillator
end
def set_pwm_freq(freq)
prescaleval = 25000000.0 # 25MHz
prescaleval /= 4096.0 # 12-bit
prescaleval /= Float(freq)
prescaleval -= 1.0
if @debug
puts "Setting PWM frequency to #{freq} Hz"
puts "Estimated pre-scale: #{prescaleval}"
end
prescale = (prescaleval + 0.5).floor
if @debug
puts "Final pre-scale: #{prescale}"
end
oldmode = @i2c.read(@address, 8, MODE1).unpack('C').first
newmode = (oldmode & 0x7F) | 0x10 # sleep
@i2c.write(@address, MODE1, newmode) # go to sleep
@i2c.write(@address, PRESCALE, prescale)
@i2c.write(@address, MODE1, oldmode)
sleep(0.005)
@i2c.write(@address, MODE1, oldmode | RESTART)
end
alias_method :setPWMFreq, :set_pwm_freq
def set_pwm(channel, on, off)
@i2c.write(@address, LED0_ON_L+4*channel, on & 0xFF)
@i2c.write(@address, LED0_ON_H+4*channel, on >> 8)
@i2c.write(@address, LED0_OFF_L+4*channel, off & 0xFF)
@i2c.write(@address, LED0_OFF_H+4*channel, off >> 8)
end
alias_method :setPWM, :set_pwm
def set_all_pwm(on, off)
@i2c.write(@address, ALL_LED_ON_L, on & 0xFF)
@i2c.write(@address, ALL_LED_ON_H, on >> 8)
@i2c.write(@address, ALL_LED_OFF_L, off & 0xFF)
@i2c.write(@address, ALL_LED_OFF_H, off >> 8)
end
alias_method :setAllPWM, :set_all_pwm
end
move prescale value calculation
require 'i2c/i2c'
include AdafruitServoDriver
class PWM
# Registers
MODE1 = 0x00
MODE2 = 0x01
SUBADR1 = 0x02
SUBADR2 = 0x03
SUBADR3 = 0x04
PRESCALE = 0xFE
LED0_ON_L = 0x06
LED0_ON_H = 0x07
LED0_OFF_L = 0x08
LED0_OFF_H = 0x09
ALL_LED_ON_L = 0xFA
ALL_LED_ON_H = 0xFB
ALL_LED_OFF_L = 0xFC
ALL_LED_OFF_H = 0xFD
# Bits
RESTART = 0x80
SLEEP = 0x10
ALLCALL = 0x01
INVRT = 0x10
OUTDRV = 0x04
def initialize(address=0x40, debug=false)
@address = address
@i2c = I2C.create(I2CDevice.detect)
@debug = debug
puts 'Reseting PCA9685 MODE1 (without SLEEP) and MODE2' if @debug
setAllPWM(0, 0)
@i2c.write(@address, MODE2, OUTDRV)
@i2c.write(@address, MODE1, ALLCALL)
sleep(0.005) # wait for oscillator
mode1 = @i2c.read(@address, 8, MODE1).unpack('C').first
@i2c.write(@address, MODE1, ALLCALL)
mode1 = mode1 & ~SLEEP # wake up (reset sleep)
@i2c.write(@address, MODE1, mode1)
sleep(0.005) # wait for oscillator
end
def set_pwm_freq(freq)
if @debug
puts "Setting PWM frequency to #{freq} Hz"
puts "Estimated pre-scale: #{prescale_val}"
end
prescale = (prescale_val + 0.5).floor
if @debug
puts "Final pre-scale: #{prescale}"
end
oldmode = @i2c.read(@address, 8, MODE1).unpack('C').first
newmode = (oldmode & 0x7F) | 0x10 # sleep
@i2c.write(@address, MODE1, newmode) # go to sleep
@i2c.write(@address, PRESCALE, prescale)
@i2c.write(@address, MODE1, oldmode)
sleep(0.005)
@i2c.write(@address, MODE1, oldmode | RESTART)
end
alias_method :setPWMFreq, :set_pwm_freq
def set_pwm(channel, on, off)
@i2c.write(@address, LED0_ON_L+4*channel, on & 0xFF)
@i2c.write(@address, LED0_ON_H+4*channel, on >> 8)
@i2c.write(@address, LED0_OFF_L+4*channel, off & 0xFF)
@i2c.write(@address, LED0_OFF_H+4*channel, off >> 8)
end
alias_method :setPWM, :set_pwm
def set_all_pwm(on, off)
@i2c.write(@address, ALL_LED_ON_L, on & 0xFF)
@i2c.write(@address, ALL_LED_ON_H, on >> 8)
@i2c.write(@address, ALL_LED_OFF_L, off & 0xFF)
@i2c.write(@address, ALL_LED_OFF_H, off >> 8)
end
alias_method :setAllPWM, :set_all_pwm
private
def prescale_val
@prescale_val ||= calculate_prescale_val
end
def calculate_prescale_val
prescaleval = 25000000.0 # 25MHz
prescaleval /= 4096.0 # 12-bit
prescaleval /= Float(freq)
prescaleval -= 1.0
end
end
|
module Alephant
module Renderer
VERSION = "1.0.5"
end
end
Major Release 2.0.0
module Alephant
module Renderer
VERSION = "2.0.0"
end
end
|
module ActsAsRelatingTo
VERSION = "0.0.20"
end
bump 0.0.21
module ActsAsRelatingTo
VERSION = "0.0.21"
end
|
module AnyLogin
module Strategy
module Devise
module Controller
def any_login_sign_in
@loginable = AnyLogin.klass.find(params[:selected_id].presence || params[:id])
sign_in @loginable
redirect_to main_app.send(AnyLogin.redirect_path_after_login)
end
end
end
end
end
AnyLogin.strategy = AnyLogin::Strategy::Devise
Set scope for devise
module AnyLogin
module Strategy
module Devise
module Controller
def any_login_sign_in
@loginable = AnyLogin.klass.find(params[:selected_id].presence || params[:id])
sign_in AnyLogin.klass.to_s.underscore.to_sym, @loginable
redirect_to main_app.send(AnyLogin.redirect_path_after_login)
end
end
end
end
end
AnyLogin.strategy = AnyLogin::Strategy::Devise |
class ApplicationGroupBuilder
attr_reader :application_group
def initialize(param, person_mapper)
@is_update = true # we assume that this is a update existing application group workflow
@applicants_params = param[:applicants]
param = param.slice(:e_case_id, :submitted_at, :e_status_code, :application_type)
@person_mapper = person_mapper
@application_group = ApplicationGroup.where(e_case_id:param[:e_case_id]).first
if @application_group.nil?
@application_group = ApplicationGroup.new(param) #we create a new application group from the xml
@is_update = false # means this is a create
end
@application_group.updated_by = "curam_system_service"
get_household
add_irsgroup # we need a atleast 1 irsgroup hence adding a blank one
end
def add_applicant(applicant_params)
if @application_group.applicants.map(&:person_id).include? applicant_params[:person].id
applicant = @application_group.applicants.where(person_id:applicant_params[:person].id).first
else
applicant = @application_group.applicants.build(filter_applicant_params(applicant_params))
end
applicant
end
def filter_applicant_params(applicant_params)
applicant_params = applicant_params.slice(
:is_primary_applicant,
:is_coverage_applicant,
:is_head_of_household,
:person_demographics,
:person)
applicant_params.delete_if do |k, v|
v.nil?
end
end
def get_household
return @household if @household
puts "households #{self.application_group.households.inspect}"
if !@is_update
puts "Updating"
@household = self.application_group.households.build #if new application group then create new household
elsif have_applicants_changed?
puts "have_applicants_changed?"
@household = self.application_group.households.build #if applicants have changed then create new household
else
puts "else?"
#TODO to use .is_active household instead of .last
@household = self.application_group.latest_coverage_household #if update and applicants haven't changed then use the latest household in use
end
puts "households #{self.application_group.households.inspect}"
return @household
end
def have_applicants_changed?
if @application_group.applicants.map(&:id).sort == @applicants_params.map do |applicants_param| applicants_param[:applicant_id] end.sort
return false
else
return true
end
end
def add_coverage_household
coverage_household = @household.coverage_households.build({submitted_at: Time.now})
@application_group.applicants.each do |applicant|
coverage_household.coverage_household_members << applicant if applicant.is_coverage_applicant
end
end
def add_hbx_enrollment
@application_group.primary_applicant.person.policies.each do |policy|
hbx_enrollement = @household.hbx_enrollments.build
hbx_enrollement.policy = policy
hbx_enrollement.employer = Employer.find(policy.employer_id) unless policy.employer_id.blank?
hbx_enrollement.broker = Broker.find(policy.broker_id) unless policy.broker_id.blank?
#hbx_enrollement.primary_applicant = alpha_person
#hbx_enrollement.allocated_aptc_in_dollars = policy.allocated_aptc
hbx_enrollement.enrollment_group_id = policy.eg_id
hbx_enrollement.elected_aptc_in_dollars = policy.elected_aptc
hbx_enrollement.applied_aptc_in_dollars = policy.applied_aptc
hbx_enrollement.submitted_at = Time.now
hbx_enrollement.kind = "employer_sponsored" unless policy.employer_id.blank?
hbx_enrollement.kind = "unassisted_qhp" if (hbx_enrollement.applied_aptc_in_cents == 0 && policy.employer.blank?)
hbx_enrollement.kind = "insurance_assisted_qhp" if (hbx_enrollement.applied_aptc_in_cents > 0 && policy.employer.blank?)
policy.enrollees.each do |enrollee|
begin
person = Person.find_for_member_id(enrollee.m_id)
@application_group.applicants << Applicant.new(person: person) unless @application_group.person_is_applicant?(person)
applicant = @application_group.find_applicant_by_person(person)
hbx_enrollement_member = hbx_enrollement.hbx_enrollment_members.build({applicant: applicant,
premium_amount_in_dollars: enrollee.pre_amt})
hbx_enrollement_member.is_subscriber = true if (enrollee.rel_code == "self")
rescue FloatDomainError
puts "Error: invalid premium amount for enrollee: #{enrollee.inspect}"
next
end
end
end
end
def add_irsgroup
@application_group.irs_groups.build()
end
#TODO - method not implemented properly using .build(params)
def add_irsgroups(irs_groups_params)
irs_groups = irs_groups_params.map do |irs_group_params|
IrsGroup.new(irs_group_params)
end
@application_group.irs_groups = irs_groups
end
def add_tax_households(tax_households_params, eligibility_determinations_params)
tax_households_params.map do |tax_household_params|
#tax_household = @household.tax_households.build(tax_household_params.slice(:id, :primary_applicant_id,
# :total_count, :total_incomes_by_year))
tax_household = @household.tax_households.build(filter_tax_household_params(tax_household_params))
tax_household_params[:tax_household_members].map do |tax_household_member_params|
tax_household_member = tax_household.tax_household_members.build(filter_tax_household_member_params(tax_household_member_params))
person_uri = @person_mapper.alias_map[tax_household_member_params[:id]]
person_obj = @person_mapper.people_map[person_uri].first
new_applicant = get_applicant(person_obj)
tax_household_member.applicant_id = new_applicant.id
tax_household_member.applicant = new_applicant
end
end
eligibility_determinations_params.each do |eligibility_determination_params|
#TODO assuming only 1tax_household. needs to be corrected later
@household.tax_households.first.eligibility_determinations.build(eligibility_determination_params)
end
end
def filter_tax_household_member_params(tax_household_member_params)
tax_household_member_params.delete_if do |k, v|
v.nil?
end
end
def filter_tax_household_params(tax_household_params)
tax_household_params = tax_household_params.slice(:id, :primary_applicant_id, :total_count, :total_incomes_by_year)
tax_household_params.delete_if do |k, v|
v.nil?
end
end
def get_applicant(person_obj)
new_applicant = self.application_group.applicants.find do |applicant|
applicant.id == @person_mapper.applicant_map[person_obj.id].id
end
new_applicant = @person_mapper.applicant_map[person_obj.id] unless new_applicant
end
def add_financial_statements(applicants_params)
applicants_params.map do |applicant_params|
applicant_params[:financial_statements].each do |financial_statement_params|
tax_household_member = find_tax_household_member(@person_mapper.applicant_map[applicant_params[:person].id])
financial_statement = tax_household_member.financial_statements.build(filter_financial_statement_params(financial_statement_params))
financial_statement_params[:incomes].each do |income_params|
financial_statement.incomes.build(income_params)
end
financial_statement_params[:deductions].each do |deduction_params|
financial_statement.deductions.build(deduction_params)
end
financial_statement_params[:alternative_benefits].each do |alternative_benefit_params|
financial_statement.alternate_benefits.build(alternative_benefit_params)
end
end
end
end
def filter_financial_statement_params(financial_statement_params)
financial_statement_params.delete_if do |k, v|
v.nil?
end
end
def find_tax_household_member(applicant)
tax_household_members = self.application_group.households.flat_map(&:tax_households).flat_map(&:tax_household_members)
tax_household_member = tax_household_members.find do |tax_household_member|
tax_household_member.applicant_id == applicant.id
end
tax_household_member
end
end
1) using save_list to saved embedded docs
2) moving person_demographics from applicant to member
3) assigning applicant_id to coverage_household_member
class ApplicationGroupBuilder
attr_reader :application_group
attr_reader :save_list
def initialize(param, person_mapper)
@save_list = []
@is_update = true # we assume that this is a update existing application group workflow
@applicants_params = param[:applicants]
param = param.slice(:e_case_id, :submitted_at, :e_status_code, :application_type)
@person_mapper = person_mapper
@application_group = ApplicationGroup.where(e_case_id:param[:e_case_id]).first
if @application_group.nil?
@application_group = ApplicationGroup.new(param) #we create a new application group from the xml
@is_update = false # means this is a create
add_irsgroup # we need a atleast 1 irsgroup hence adding a blank one
end
@application_group.updated_by = "curam_system_service"
get_household
end
def add_applicant(applicant_params)
if @application_group.applicants.map(&:person_id).include? applicant_params[:person].id
puts "Added already existing applicant"
applicant = @application_group.applicants.where(person_id:applicant_params[:person].id).first
else
puts "Added a new applicant"
applicant = @application_group.applicants.build(filter_applicant_params(applicant_params))
member = applicant.person.members.select do |m| m.authority? end.first
set_person_demographics(member, applicant_params[:person_demographics])
@save_list << member
@save_list << applicant
end
applicant
end
def set_person_demographics(member, person_demographics_params)
member.dob = person_demographics_params["dob"] if person_demographics_params["dob"]
member.death_date = person_demographics_params["death_date"] if person_demographics_params["death_date"]
member.ssn = person_demographics_params["ssn"] if person_demographics_params["ssn"]
member.gender = person_demographics_params["gender"] if person_demographics_params["gender"]
member.ethnicity = person_demographics_params["ethnicity"] if person_demographics_params["ethnicity"]
member.race = person_demographics_params["race"] if person_demographics_params["race"]
member.marital_status = person_demographics_params["marital_status"] if person_demographics_params["marital_status"]
end
def filter_applicant_params(applicant_params)
applicant_params = applicant_params.slice(
:is_primary_applicant,
:is_coverage_applicant,
:is_head_of_household,
:person)
applicant_params.delete_if do |k, v|
v.nil?
end
end
def get_household
return @household if @household
if !@is_update
puts "New Application Group Case"
@household = self.application_group.households.build #if new application group then create new household
@save_list << @household
elsif have_applicants_changed?
puts "Update Application Group Case - Applicants have changed. Creating new household"
@household = self.application_group.households.build #if applicants have changed then create new household
@save_list << @household
else
puts "Update Application Group Case. Using latest household."
#TODO to use .is_active household instead of .last
@household = self.application_group.households.last #if update and applicants haven't changed then use the latest household in use
end
return @household
end
def have_applicants_changed?
current_list = @application_group.applicants.map do |applicant| applicant.person_id end.sort
new_list = @applicants_params.map do |applicants_param| applicants_param[:person].id end.sort
puts current_list.inspect
puts new_list.inspect
if current_list == new_list
return false
else
return true
end
end
def add_coverage_household
coverage_household = @household.coverage_households.build({submitted_at: Time.now})
@application_group.applicants.each do |applicant|
if applicant.is_coverage_applicant
coverage_household_member = coverage_household.coverage_household_members.build
coverage_household_member.applicant_id = applicant.id
end
end
end
def add_hbx_enrollment
@application_group.primary_applicant.person.policies.each do |policy|
hbx_enrollement = @household.hbx_enrollments.build
hbx_enrollement.policy = policy
#hbx_enrollement.employer = Employer.find(policy.employer_id) unless policy.employer_id.blank?
#hbx_enrollement.broker = Broker.find(policy.broker_id) unless policy.broker_id.blank?
#hbx_enrollement.primary_applicant = alpha_person
#hbx_enrollement.allocated_aptc_in_dollars = policy.allocated_aptc
hbx_enrollement.enrollment_group_id = policy.eg_id
hbx_enrollement.elected_aptc_in_dollars = policy.elected_aptc
hbx_enrollement.applied_aptc_in_dollars = policy.applied_aptc
hbx_enrollement.submitted_at = Time.now
hbx_enrollement.kind = "employer_sponsored" unless policy.employer_id.blank?
hbx_enrollement.kind = "unassisted_qhp" if (hbx_enrollement.applied_aptc_in_cents == 0 && policy.employer.blank?)
hbx_enrollement.kind = "insurance_assisted_qhp" if (hbx_enrollement.applied_aptc_in_cents > 0 && policy.employer.blank?)
policy.enrollees.each do |enrollee|
begin
person = Person.find_for_member_id(enrollee.m_id)
@application_group.applicants << Applicant.new(person: person) unless @application_group.person_is_applicant?(person)
applicant = @application_group.find_applicant_by_person(person)
hbx_enrollement_member = hbx_enrollement.hbx_enrollment_members.build({applicant: applicant,
premium_amount_in_cents: enrollee.pre_amt})
hbx_enrollement_member.is_subscriber = true if (enrollee.rel_code == "self")
rescue FloatDomainError
puts "Error: invalid premium amount for enrollee: #{enrollee.inspect}"
next
end
end
end
end
def add_irsgroup
@application_group.irs_groups.build()
end
#TODO - method not implemented properly using .build(params)
def add_irsgroups(irs_groups_params)
irs_groups = irs_groups_params.map do |irs_group_params|
IrsGroup.new(irs_group_params)
end
@application_group.irs_groups = irs_groups
end
def add_tax_households(tax_households_params, eligibility_determinations_params)
tax_households_params.map do |tax_household_params|
#tax_household = @household.tax_households.build(tax_household_params.slice(:id, :primary_applicant_id,
# :total_count, :total_incomes_by_year))
tax_household = @household.tax_households.build(filter_tax_household_params(tax_household_params))
tax_household_params[:tax_household_members].map do |tax_household_member_params|
tax_household_member = tax_household.tax_household_members.build(filter_tax_household_member_params(tax_household_member_params))
person_uri = @person_mapper.alias_map[tax_household_member_params[:id]]
person_obj = @person_mapper.people_map[person_uri].first
new_applicant = get_applicant(person_obj)
tax_household_member.applicant_id = new_applicant.id
tax_household_member.applicant = new_applicant
end
end
eligibility_determinations_params.each do |eligibility_determination_params|
#TODO assuming only 1tax_household. needs to be corrected later
@household.tax_households.first.eligibility_determinations.build(eligibility_determination_params)
end
end
def filter_tax_household_member_params(tax_household_member_params)
tax_household_member_params.delete_if do |k, v|
v.nil?
end
end
def filter_tax_household_params(tax_household_params)
tax_household_params = tax_household_params.slice(:id, :primary_applicant_id, :total_count, :total_incomes_by_year)
tax_household_params.delete_if do |k, v|
v.nil?
end
end
def get_applicant(person_obj)
new_applicant = self.application_group.applicants.find do |applicant|
applicant.id == @person_mapper.applicant_map[person_obj.id].id
end
new_applicant = @person_mapper.applicant_map[person_obj.id] unless new_applicant
end
def add_financial_statements(applicants_params)
applicants_params.map do |applicant_params|
applicant_params[:financial_statements].each do |financial_statement_params|
tax_household_member = find_tax_household_member(@person_mapper.applicant_map[applicant_params[:person].id])
financial_statement = tax_household_member.financial_statements.build(filter_financial_statement_params(financial_statement_params))
financial_statement_params[:incomes].each do |income_params|
financial_statement.incomes.build(income_params)
end
financial_statement_params[:deductions].each do |deduction_params|
financial_statement.deductions.build(deduction_params)
end
financial_statement_params[:alternative_benefits].each do |alternative_benefit_params|
financial_statement.alternate_benefits.build(alternative_benefit_params)
end
end
end
end
def filter_financial_statement_params(financial_statement_params)
financial_statement_params.delete_if do |k, v|
v.nil?
end
end
def find_tax_household_member(applicant)
tax_household_members = self.application_group.households.flat_map(&:tax_households).flat_map(&:tax_household_members)
tax_household_member = tax_household_members.find do |tax_household_member|
tax_household_member.applicant_id == applicant.id
end
tax_household_member
end
end |
class ApplicationGroupBuilder
attr_reader :application_group
attr_reader :save_list
def initialize(param, person_mapper)
@save_list = []
@is_update = true # we assume that this is a update existing application group workflow
@applicants_params = param[:applicants]
filtered_param = param.slice(:e_case_id, :submitted_at, :e_status_code, :application_type)
@person_mapper = person_mapper
@application_group = ApplicationGroup.where(e_case_id: filtered_param[:e_case_id]).first
if @application_group.nil?
@application_group = ApplicationGroup.new(filtered_param) #we create a new application group from the xml
@is_update = false # means this is a create
end
add_irsgroups([{}]) # we need a atleast 1 irsgroup hence adding a blank one
@application_group.updated_by = "curam_system_service"
get_household
end
def add_applicant(applicant_params)
# puts "applicant_params[:is_primary_applicant] #{applicant_params[:is_primary_applicant]}"
if @application_group.applicants.map(&:person_id).include? applicant_params[:person].id
# puts "Added already existing applicant"
applicant = @application_group.applicants.where(person_id: applicant_params[:person].id).first
else
# puts "Added a new applicant"
if applicant_params[:is_primary_applicant] == "true"
reset_exisiting_primary_applicant
end
applicant = @application_group.applicants.build(filter_applicant_params(applicant_params))
member = applicant.person.members.select do |m|
m.authority?
end.first
set_person_demographics(member, applicant_params[:person_demographics])
@save_list << member
@save_list << applicant
# puts "applicant_params[:is_primary_applicant] #{applicant_params[:is_primary_applicant]} @application_group.applicants #{applicant.inspect}"
end
applicant
end
def reset_exisiting_primary_applicant
@application_group.applicants.each do |applicant|
applicant.is_primary_applicant = false
end
end
def set_person_demographics(member, person_demographics_params)
member.dob = person_demographics_params["dob"] if person_demographics_params["dob"]
member.death_date = person_demographics_params["death_date"] if person_demographics_params["death_date"]
member.ssn = person_demographics_params["ssn"] if person_demographics_params["ssn"]
member.gender = person_demographics_params["gender"] if person_demographics_params["gender"]
member.ethnicity = person_demographics_params["ethnicity"] if person_demographics_params["ethnicity"]
member.race = person_demographics_params["race"] if person_demographics_params["race"]
member.marital_status = person_demographics_params["marital_status"] if person_demographics_params["marital_status"]
end
def filter_applicant_params(applicant_params)
applicant_params = applicant_params.slice(
:is_primary_applicant,
:is_coverage_applicant,
:person)
applicant_params.delete_if do |k, v|
v.nil?
end
end
def get_household
return @household if @household
if !@is_update
# puts "New Application Group Case"
@household = self.application_group.households.build #if new application group then create new household
@save_list << @household
elsif have_applicants_changed?
# puts "Update Application Group Case - Applicants have changed. Creating new household"
@household = self.application_group.households.build #if applicants have changed then create new household
@save_list << @household
else
# puts "Update Application Group Case. Using latest household."
#TODO to use .is_active household instead of .last
@household = self.application_group.households.last #if update and applicants haven't changed then use the latest household in use
end
# puts "return @household"
return @household
end
def have_applicants_changed?
current_list = @application_group.applicants.map do |applicant|
applicant.person_id
end.sort
new_list = @applicants_params.map do |applicants_param|
applicants_param[:person].id
end.sort
if current_list == new_list
return false
else
return true
end
end
def add_coverage_household
coverage_household = @household.coverage_households.build({submitted_at: Time.now})
@application_group.applicants.each do |applicant|
if applicant.is_coverage_applicant
coverage_household_member = coverage_household.coverage_household_members.build
coverage_household_member.applicant_id = applicant.id
end
end
end
def primary_applicant_employee_applicant
employee_applicant = @application_group.primary_applicant.employee_applicant
employee_applicant = @application_group.primary_applicant.employee_applicant.build unless employee_applicant
employee_applicant.employer = @application_group.primary_applicant.person.employer
end
def add_hbx_enrollment
# puts @application_group.primary_applicant
@application_group.primary_applicant.person.policies.each do |policy|
hbx_enrollement = @household.hbx_enrollments.build
hbx_enrollement.policy = policy
@application_group.primary_applicant.broker_id = Broker.find(policy.broker_id) unless policy.broker_id.blank?
#hbx_enrollement.employer = Employer.find(policy.employer_id) unless policy.employer_id.blank?
#hbx_enrollement.broker = Broker.find(policy.broker_id) unless policy.broker_id.blank?
#hbx_enrollement.primary_applicant = alpha_person
#hbx_enrollement.allocated_aptc_in_dollars = policy.allocated_aptc
hbx_enrollement.enrollment_group_id = policy.eg_id
hbx_enrollement.elected_aptc_in_dollars = policy.elected_aptc
hbx_enrollement.applied_aptc_in_dollars = policy.applied_aptc
hbx_enrollement.submitted_at = Time.now
hbx_enrollement.kind = "employer_sponsored" unless policy.employer_id.blank?
hbx_enrollement.kind = "unassisted_qhp" if (hbx_enrollement.applied_aptc_in_cents == 0 && policy.employer.blank?)
hbx_enrollement.kind = "insurance_assisted_qhp" if (hbx_enrollement.applied_aptc_in_cents > 0 && policy.employer.blank?)
policy.enrollees.each do |enrollee|
begin
person = Person.find_for_member_id(enrollee.m_id)
@application_group.applicants << Applicant.new(person: person) unless @application_group.person_is_applicant?(person)
applicant = @application_group.find_applicant_by_person(person)
hbx_enrollement_member = hbx_enrollement.hbx_enrollment_members.build({applicant: applicant,
premium_amount_in_cents: enrollee.pre_amt})
hbx_enrollement_member.is_subscriber = true if (enrollee.rel_code == "self")
rescue FloatDomainError
# puts "Error: invalid premium amount for enrollee: #{enrollee.inspect}"
next
end
end
end
end
def add_irsgroup(irs_group_params)
puts irs_group_params.inspect
@application_group.irs_groups.build(irs_group_params)
end
#TODO - method not implemented properly using .build(params)
def add_irsgroups(irs_groups_params)
irs_groups_params.map do |irs_group_params|
add_irsgroup(irs_group_params)
end
end
def add_tax_households(tax_households_params)
tax_households_params.map do |tax_household_params|
tax_household = @household.tax_households.build(filter_tax_household_params(tax_household_params))
eligibility_determinations_params = tax_household_params[:eligibility_determinations]
eligibility_determinations_params.each do |eligibility_determination_params|
tax_household.eligibility_determinations.build(eligibility_determination_params)
end
tax_household_params[:tax_household_members].map do |tax_household_member_params|
tax_household_member = tax_household.tax_household_members.build(filter_tax_household_member_params(tax_household_member_params))
person_uri = @person_mapper.alias_map[tax_household_member_params[:person_id]]
person_obj = @person_mapper.people_map[person_uri].first
new_applicant = get_applicant(person_obj)
new_applicant = verify_person_id(new_applicant)
tax_household_member.applicant_id = new_applicant.id
tax_household_member.applicant = new_applicant
end
end
end
def verify_person_id(applicant)
if applicant.id.to_s.include? "concern_role"
end
applicant
end
def filter_tax_household_member_params(tax_household_member_params)
tax_household_member_params_clone = tax_household_member_params.clone
tax_household_member_params_clone = tax_household_member_params_clone.slice(:is_ia_eligible, :is_medicaid_chip_eligible, :is_subscriber)
tax_household_member_params_clone.delete_if do |k, v|
v.nil?
end
tax_household_member_params_clone
end
def filter_tax_household_params(tax_household_params)
tax_household_params = tax_household_params.slice(:id, :total_count, :total_incomes_by_year)
tax_household_params.delete_if do |k, v|
v.nil?
end
end
## Fetches the applicant object either from application_group or person_mapper
def get_applicant(person_obj)
new_applicant = self.application_group.applicants.find do |applicant|
applicant.id == @person_mapper.applicant_map[person_obj.id].id
end
new_applicant = @person_mapper.applicant_map[person_obj.id] unless new_applicant
end
def add_financial_statements(applicants_params)
applicants_params.map do |applicant_params|
applicant_params[:financial_statements].each do |financial_statement_params|
tax_household_member = find_tax_household_member(@person_mapper.applicant_map[applicant_params[:person].id])
financial_statement = tax_household_member.financial_statements.build(filter_financial_statement_params(financial_statement_params))
financial_statement_params[:incomes].each do |income_params|
financial_statement.incomes.build(income_params)
end
financial_statement_params[:deductions].each do |deduction_params|
financial_statement.deductions.build(deduction_params)
end
financial_statement_params[:alternative_benefits].each do |alternative_benefit_params|
financial_statement.alternate_benefits.build(alternative_benefit_params)
end
end
end
end
def filter_financial_statement_params(financial_statement_params)
financial_statement_params = financial_statement_params.slice(:type, :is_tax_filing_together, :tax_filing_status)
financial_statement_params.delete_if do |k, v|
v.nil?
end
end
def find_tax_household_member(applicant)
tax_household_members = self.application_group.households.flat_map(&:tax_households).flat_map(&:tax_household_members)
tax_household_member = tax_household_members.find do |tax_household_member|
tax_household_member.applicant_id == applicant.id
end
tax_household_member
end
def save
#primary_applicant_employee_applicant
id = @application_group.save!
save_save_list
@application_group.id #return the id of saved application group
end
#save objects in save list
def save_save_list
save_list.each do |obj|
obj.save!
end
end
end
setting tax_household_member.is_primary_applicant
class ApplicationGroupBuilder
attr_reader :application_group
attr_reader :save_list
def initialize(param, person_mapper)
@save_list = []
@is_update = true # we assume that this is a update existing application group workflow
@applicants_params = param[:applicants]
filtered_param = param.slice(:e_case_id, :submitted_at, :e_status_code, :application_type)
@person_mapper = person_mapper
@application_group = ApplicationGroup.where(e_case_id: filtered_param[:e_case_id]).first
if @application_group.nil?
@application_group = ApplicationGroup.new(filtered_param) #we create a new application group from the xml
@is_update = false # means this is a create
end
add_irsgroups([{}]) # we need a atleast 1 irsgroup hence adding a blank one
@application_group.updated_by = "curam_system_service"
get_household
end
def add_applicant(applicant_params)
# puts "applicant_params[:is_primary_applicant] #{applicant_params[:is_primary_applicant]}"
if @application_group.applicants.map(&:person_id).include? applicant_params[:person].id
# puts "Added already existing applicant"
applicant = @application_group.applicants.where(person_id: applicant_params[:person].id).first
else
# puts "Added a new applicant"
if applicant_params[:is_primary_applicant] == "true"
reset_exisiting_primary_applicant
end
applicant = @application_group.applicants.build(filter_applicant_params(applicant_params))
member = applicant.person.members.select do |m|
m.authority?
end.first
set_person_demographics(member, applicant_params[:person_demographics])
@save_list << member
@save_list << applicant
# puts "applicant_params[:is_primary_applicant] #{applicant_params[:is_primary_applicant]} @application_group.applicants #{applicant.inspect}"
end
applicant
end
def reset_exisiting_primary_applicant
@application_group.applicants.each do |applicant|
applicant.is_primary_applicant = false
end
end
def set_person_demographics(member, person_demographics_params)
member.dob = person_demographics_params["dob"] if person_demographics_params["dob"]
member.death_date = person_demographics_params["death_date"] if person_demographics_params["death_date"]
member.ssn = person_demographics_params["ssn"] if person_demographics_params["ssn"]
member.gender = person_demographics_params["gender"] if person_demographics_params["gender"]
member.ethnicity = person_demographics_params["ethnicity"] if person_demographics_params["ethnicity"]
member.race = person_demographics_params["race"] if person_demographics_params["race"]
member.marital_status = person_demographics_params["marital_status"] if person_demographics_params["marital_status"]
end
def filter_applicant_params(applicant_params)
applicant_params = applicant_params.slice(
:is_primary_applicant,
:is_coverage_applicant,
:person)
applicant_params.delete_if do |k, v|
v.nil?
end
end
def get_household
return @household if @household
if !@is_update
# puts "New Application Group Case"
@household = self.application_group.households.build #if new application group then create new household
@save_list << @household
elsif have_applicants_changed?
# puts "Update Application Group Case - Applicants have changed. Creating new household"
@household = self.application_group.households.build #if applicants have changed then create new household
@save_list << @household
else
# puts "Update Application Group Case. Using latest household."
#TODO to use .is_active household instead of .last
@household = self.application_group.households.last #if update and applicants haven't changed then use the latest household in use
end
# puts "return @household"
return @household
end
def have_applicants_changed?
current_list = @application_group.applicants.map do |applicant|
applicant.person_id
end.sort
new_list = @applicants_params.map do |applicants_param|
applicants_param[:person].id
end.sort
if current_list == new_list
return false
else
return true
end
end
def add_coverage_household
coverage_household = @household.coverage_households.build({submitted_at: Time.now})
@application_group.applicants.each do |applicant|
if applicant.is_coverage_applicant
coverage_household_member = coverage_household.coverage_household_members.build
coverage_household_member.applicant_id = applicant.id
end
end
end
def primary_applicant_employee_applicant
employee_applicant = @application_group.primary_applicant.employee_applicants
employee_applicant = @application_group.primary_applicant.employee_applicants.build unless employee_applicant
employee_applicant.employer = @application_group.primary_applicant.person.employer
end
def add_hbx_enrollment
# puts @application_group.primary_applicant
@application_group.primary_applicant.person.policies.each do |policy|
hbx_enrollement = @household.hbx_enrollments.build
hbx_enrollement.policy = policy
@application_group.primary_applicant.broker_id = Broker.find(policy.broker_id) unless policy.broker_id.blank?
#hbx_enrollement.employer = Employer.find(policy.employer_id) unless policy.employer_id.blank?
#hbx_enrollement.broker = Broker.find(policy.broker_id) unless policy.broker_id.blank?
#hbx_enrollement.primary_applicant = alpha_person
#hbx_enrollement.allocated_aptc_in_dollars = policy.allocated_aptc
hbx_enrollement.enrollment_group_id = policy.eg_id
hbx_enrollement.elected_aptc_in_dollars = policy.elected_aptc
hbx_enrollement.applied_aptc_in_dollars = policy.applied_aptc
hbx_enrollement.submitted_at = Time.now
hbx_enrollement.kind = "employer_sponsored" unless policy.employer_id.blank?
hbx_enrollement.kind = "unassisted_qhp" if (hbx_enrollement.applied_aptc_in_cents == 0 && policy.employer.blank?)
hbx_enrollement.kind = "insurance_assisted_qhp" if (hbx_enrollement.applied_aptc_in_cents > 0 && policy.employer.blank?)
policy.enrollees.each do |enrollee|
begin
person = Person.find_for_member_id(enrollee.m_id)
@application_group.applicants << Applicant.new(person: person) unless @application_group.person_is_applicant?(person)
applicant = @application_group.find_applicant_by_person(person)
hbx_enrollement_member = hbx_enrollement.hbx_enrollment_members.build({applicant: applicant,
premium_amount_in_cents: enrollee.pre_amt})
hbx_enrollement_member.is_subscriber = true if (enrollee.rel_code == "self")
rescue FloatDomainError
# puts "Error: invalid premium amount for enrollee: #{enrollee.inspect}"
next
end
end
end
end
def add_irsgroup(irs_group_params)
@application_group.irs_groups.build(irs_group_params)
end
#TODO - method not implemented properly using .build(params)
def add_irsgroups(irs_groups_params)
irs_groups_params.map do |irs_group_params|
add_irsgroup(irs_group_params)
end
end
def add_tax_households(tax_households_params)
tax_households_params.map do |tax_household_params|
tax_household = @household.tax_households.build(filter_tax_household_params(tax_household_params))
eligibility_determinations_params = tax_household_params[:eligibility_determinations]
eligibility_determinations_params.each do |eligibility_determination_params|
tax_household.eligibility_determinations.build(eligibility_determination_params)
end
tax_household_params[:tax_household_members].map do |tax_household_member_params|
tax_household_member = tax_household.tax_household_members.build(filter_tax_household_member_params(tax_household_member_params))
person_uri = @person_mapper.alias_map[tax_household_member_params[:person_id]]
person_obj = @person_mapper.people_map[person_uri].first
new_applicant = get_applicant(person_obj)
new_applicant = verify_person_id(new_applicant)
tax_household_member.applicant_id = new_applicant.id
tax_household_member.applicant = new_applicant
tax_household_member.is_primary_applicant = true if tax_household_member.applicant.is_primary_applicant
end
end
end
def verify_person_id(applicant)
if applicant.id.to_s.include? "concern_role"
end
applicant
end
def filter_tax_household_member_params(tax_household_member_params)
tax_household_member_params_clone = tax_household_member_params.clone
tax_household_member_params_clone = tax_household_member_params_clone.slice(:is_ia_eligible, :is_medicaid_chip_eligible, :is_subscriber)
tax_household_member_params_clone.delete_if do |k, v|
v.nil?
end
tax_household_member_params_clone
end
def filter_tax_household_params(tax_household_params)
tax_household_params = tax_household_params.slice(:id, :total_count, :total_incomes_by_year)
tax_household_params.delete_if do |k, v|
v.nil?
end
end
## Fetches the applicant object either from application_group or person_mapper
def get_applicant(person_obj)
new_applicant = self.application_group.applicants.find do |applicant|
applicant.id == @person_mapper.applicant_map[person_obj.id].id
end
new_applicant = @person_mapper.applicant_map[person_obj.id] unless new_applicant
end
def add_financial_statements(applicants_params)
applicants_params.map do |applicant_params|
applicant_params[:financial_statements].each do |financial_statement_params|
tax_household_member = find_tax_household_member(@person_mapper.applicant_map[applicant_params[:person].id])
financial_statement = tax_household_member.financial_statements.build(filter_financial_statement_params(financial_statement_params))
financial_statement_params[:incomes].each do |income_params|
financial_statement.incomes.build(income_params)
end
financial_statement_params[:deductions].each do |deduction_params|
financial_statement.deductions.build(deduction_params)
end
financial_statement_params[:alternative_benefits].each do |alternative_benefit_params|
financial_statement.alternate_benefits.build(alternative_benefit_params)
end
end
end
end
def filter_financial_statement_params(financial_statement_params)
financial_statement_params = financial_statement_params.slice(:type, :is_tax_filing_together, :tax_filing_status)
financial_statement_params.delete_if do |k, v|
v.nil?
end
end
def find_tax_household_member(applicant)
tax_household_members = self.application_group.households.flat_map(&:tax_households).flat_map(&:tax_household_members)
tax_household_member = tax_household_members.find do |tax_household_member|
tax_household_member.applicant_id == applicant.id
end
tax_household_member
end
def save
#primary_applicant_employee_applicant
id = @application_group.save!
save_save_list
@application_group.id #return the id of saved application group
end
#save objects in save list
def save_save_list
save_list.each do |obj|
obj.save!
end
end
end
|
# frozen_string_literal: true
require_relative 'formatted_text'
require_relative 'index_catalog'
require_relative 'pdfmark'
require_relative 'roman_numeral'
require_relative 'section_info_by_page'
autoload :StringIO, 'stringio'
autoload :Tempfile, 'tempfile'
module Asciidoctor
module PDF
class Converter < ::Prawn::Document
include ::Asciidoctor::Converter
include ::Asciidoctor::Logging
include ::Asciidoctor::Writer
include ::Asciidoctor::Prawn::Extensions
register_for 'pdf'
attr_reader :allow_uri_read
attr_reader :cache_uri
attr_accessor :font_color
attr_accessor :font_scale
attr_reader :root_font_size
attr_reader :index
attr_reader :theme
attr_reader :text_decoration_width
# NOTE require_library doesn't support require_relative and we don't modify the load path for this gem
CodeRayRequirePath = ::File.join __dir__, 'ext/prawn/coderay_encoder'
RougeRequirePath = ::File.join __dir__, 'ext/rouge'
PygmentsRequirePath = ::File.join __dir__, 'ext/pygments'
OptimizerRequirePath = ::File.join __dir__, 'optimizer'
AdmonitionIcons = {
caution: { name: 'fas-fire', stroke_color: 'BF3400', size: 24 },
important: { name: 'fas-exclamation-circle', stroke_color: 'BF0000', size: 24 },
note: { name: 'fas-info-circle', stroke_color: '19407C', size: 24 },
tip: { name: 'far-lightbulb', stroke_color: '111111', size: 24 },
warning: { name: 'fas-exclamation-triangle', stroke_color: 'BF6900', size: 24 },
}
TextAlignmentNames = %w(justify left center right)
TextAlignmentRoles = %w(text-justify text-left text-center text-right)
TextDecorationStyleTable = { 'underline' => :underline, 'line-through' => :strikethrough }
FontKerningTable = { 'normal' => true, 'none' => false }
BlockAlignmentNames = %w(left center right)
(AlignmentTable = { '<' => :left, '=' => :center, '>' => :right }).default = :left
ColumnPositions = [:left, :center, :right]
PageLayouts = [:portrait, :landscape]
(PageModes = {
'fullscreen' => [:FullScreen, :UseOutlines],
'fullscreen none' => [:FullScreen, :UseNone],
'fullscreen outline' => [:FullScreen, :UseOutlines],
'fullscreen thumbs' => [:FullScreen, :UseThumbs],
'none' => :UseNone,
'outline' => :UseOutlines,
'thumbs' => :UseThumbs,
}).default = :UseOutlines
PageSides = [:recto, :verso]
(PDFVersions = { '1.3' => 1.3, '1.4' => 1.4, '1.5' => 1.5, '1.6' => 1.6, '1.7' => 1.7 }).default = 1.4
AuthorAttributeNames = %w(author authorinitials firstname middlename lastname email)
LF = ?\n
DoubleLF = LF * 2
TAB = ?\t
InnerIndent = LF + ' '
# a no-break space is used to replace a leading space to prevent Prawn from trimming indentation
# a leading zero-width space can't be used as it gets dropped when calculating the line width
GuardedIndent = ?\u00a0
GuardedInnerIndent = LF + GuardedIndent
TabRx = /\t/
TabIndentRx = /^\t+/
NoBreakSpace = ?\u00a0
ZeroWidthSpace = ?\u200b
DummyText = ?\u0000
DotLeaderTextDefault = '. '
EmDash = ?\u2014
RightPointer = ?\u25ba
LowercaseGreekA = ?\u03b1
Bullets = {
disc: ?\u2022,
circle: ?\u25e6,
square: ?\u25aa,
none: '',
}
# NOTE Default theme font uses ballot boxes from FontAwesome
BallotBox = {
checked: ?\u2611,
unchecked: ?\u2610,
}
ConumSets = {
'circled' => (?\u2460..?\u2473).to_a,
'filled' => (?\u2776..?\u277f).to_a + (?\u24eb..?\u24f4).to_a,
}
SimpleAttributeRefRx = /(?<!\\)\{\w+(?:[\-]\w+)*\}/
MeasurementRxt = '\\d+(?:\\.\\d+)?(?:in|cm|mm|p[txc])?'
MeasurementPartsRx = /^(\d+(?:\.\d+)?)(in|mm|cm|p[txc])?$/
PageSizeRx = /^(?:\[(#{MeasurementRxt}), ?(#{MeasurementRxt})\]|(#{MeasurementRxt})(?: x |x)(#{MeasurementRxt})|\S+)$/
CalloutExtractRx = /(?:(?:\/\/|#|--|;;) ?)?(\\)?<!?(|--)(\d+|\.)\2> ?(?=(?:\\?<!?\2(?:\d+|\.)\2>)*$)/
ImageAttributeValueRx = /^image:{1,2}(.*?)\[(.*?)\]$/
StopPunctRx = /[.!?;:]$/
UriBreakCharsRx = /(?:\/|\?|&|#)(?!$)/
UriBreakCharRepl = %(\\&#{ZeroWidthSpace})
UriSchemeBoundaryRx = /(?<=:\/\/)/
LineScanRx = /\n|.+/
BlankLineRx = /\n{2,}/
CjkLineBreakRx = /(?=[\u3000\u30a0-\u30ff\u3040-\u309f\p{Han}\uff00-\uffef])/
WhitespaceChars = ' ' + TAB + LF
ValueSeparatorRx = /;|,/
HexColorRx = /^#[a-fA-F0-9]{6}$/
VimeoThumbnailRx = /<thumbnail_large>(.*?)<\/thumbnail_large>/
SourceHighlighters = %w(coderay pygments rouge).to_set
ViewportWidth = ::Module.new
(TitleStyles = {
'toc' => [:numbered_title],
'basic' => [:title],
}).default = [:numbered_title, formal: true]
def initialize backend, opts
super
basebackend 'html'
filetype 'pdf'
htmlsyntax 'html'
outfilesuffix '.pdf'
if (doc = opts[:document])
# NOTE enabling data-uri forces Asciidoctor Diagram to produce absolute image paths
doc.attributes['data-uri'] = (doc.instance_variable_get :@attribute_overrides)['data-uri'] = ''
end
@initial_instance_variables = [:@initial_instance_variables] + instance_variables
end
def convert node, name = nil, _opts = {}
method_name = %(convert_#{name ||= node.node_name})
if respond_to? method_name
result = send method_name, node
else
# TODO: delegate to convert_method_missing
logger.warn %(missing convert handler for #{name} node in #{@backend} backend) unless scratch?
end
# NOTE: inline nodes generate pseudo-HTML strings; the remainder write directly to PDF object
::Asciidoctor::Inline === node ? result : self
end
def traverse node, opts = {}
# NOTE converter instance in scratch document gets duplicated; must be rewired to this one
if self == (prev_converter = node.document.converter)
prev_converter = nil
else
node.document.instance_variable_set :@converter, self
end
if node.blocks?
node.content
elsif node.content_model != :compound && (string = node.content)
# TODO: this content could be cached on repeat invocations!
layout_prose string, (opts.merge hyphenate: true)
end
ensure
node.document.instance_variable_set :@converter, prev_converter if prev_converter
end
def convert_document doc
init_pdf doc
# set default value for outline and pagenums if not otherwise set
doc.attributes['outline'] = '' unless (doc.attribute_locked? 'outline') || ((doc.instance_variable_get :@attributes_modified).include? 'outline')
doc.attributes['pagenums'] = '' unless (doc.attribute_locked? 'pagenums') || ((doc.instance_variable_get :@attributes_modified).include? 'pagenums')
#assign_missing_section_ids doc
# promote anonymous preface (defined using preamble block) to preface section
# FIXME: this should be done in core
if doc.doctype == 'book' && (blk0 = doc.blocks[0]) && blk0.context == :preamble && blk0.title? &&
!blk0.title.nil_or_empty? && blk0.blocks[0].style != 'abstract' && (blk1 = doc.blocks[1]) && blk1.context == :section
preface = Section.new doc, blk1.level, false, attributes: { 1 => 'preface', 'style' => 'preface' }
preface.special = true
preface.sectname = 'preface'
preface.title = blk0.instance_variable_get :@title
# QUESTION should ID be generated from raw or converted title? core is not clear about this
preface.id = preface.generate_id
preface.blocks.replace blk0.blocks.map {|b| b.parent = preface; b } # rubocop:disable Style/Semicolon
doc.blocks[0] = preface
blk0 = blk1 = preface = nil # rubocop:disable Lint/UselessAssignment
end
on_page_create(&(method :init_page))
marked_page_number = page_number
# NOTE: a new page will already be started (page_number = 2) if the front cover image is a PDF
layout_cover_page doc, :front
has_front_cover = page_number > marked_page_number
if (use_title_page = doc.doctype == 'book' || (doc.attr? 'title-page'))
layout_title_page doc
has_title_page = page_number == (has_front_cover ? 2 : 1)
end
@page_margin_by_side[:cover] = @page_margin_by_side[:recto] if @media == 'prepress' && page_number == 0
# NOTE: font must be set before content is written to the main or scratch document
start_new_page unless page.empty?
font @theme.base_font_family, size: @root_font_size, style: (@theme.base_font_style || :normal).to_sym
unless use_title_page
body_start_page_number = page_number
theme_font :heading, level: 1 do
layout_heading doc.doctitle, align: (@theme.heading_h1_align || :center).to_sym, level: 1
end if doc.header? && !doc.notitle
end
num_front_matter_pages = toc_page_nums = toc_num_levels = nil
indent_section do
toc_num_levels = (doc.attr 'toclevels', 2).to_i
if (insert_toc = (doc.attr? 'toc') && !(doc.attr? 'toc-placement', 'macro') && doc.sections?)
start_new_page if @ppbook && verso_page?
add_dest_for_block doc, 'toc'
allocate_toc doc, toc_num_levels, @y, use_title_page
else
@toc_extent = nil
end
start_new_page if @ppbook && verso_page?
if use_title_page
zero_page_offset = has_front_cover ? 1 : 0
first_page_offset = has_title_page ? zero_page_offset.next : zero_page_offset
body_offset = (body_start_page_number = page_number) - 1
if ::Integer === (running_content_start_at = @theme.running_content_start_at || 'body')
running_content_body_offset = body_offset + [running_content_start_at.pred, 1].max
running_content_start_at = 'body'
else
running_content_body_offset = body_offset
running_content_start_at = 'toc' if running_content_start_at == 'title' && !has_title_page
running_content_start_at = 'body' if running_content_start_at == 'toc' && !insert_toc
end
if ::Integer === (page_numbering_start_at = @theme.page_numbering_start_at || 'body')
page_numbering_body_offset = body_offset + [page_numbering_start_at.pred, 1].max
page_numbering_start_at = 'body'
else
page_numbering_body_offset = body_offset
page_numbering_start_at = 'toc' if page_numbering_start_at == 'title' && !has_title_page
page_numbering_start_at = 'body' if page_numbering_start_at == 'toc' && !insert_toc
end
front_matter_sig = [running_content_start_at, page_numbering_start_at]
# table values are number of pages to skip before starting running content and page numbering, respectively
num_front_matter_pages = {
%w(title title) => [zero_page_offset, zero_page_offset],
%w(title toc) => [zero_page_offset, first_page_offset],
%w(title body) => [zero_page_offset, page_numbering_body_offset],
%w(toc title) => [first_page_offset, zero_page_offset],
%w(toc toc) => [first_page_offset, first_page_offset],
%w(toc body) => [first_page_offset, page_numbering_body_offset],
%w(body title) => [running_content_body_offset, zero_page_offset],
%w(body toc) => [running_content_body_offset, first_page_offset],
}[front_matter_sig] || [running_content_body_offset, page_numbering_body_offset]
else
body_offset = body_start_page_number - 1
if ::Integer === (running_content_start_at = @theme.running_content_start_at || 'body')
running_content_body_offset = body_offset + [running_content_start_at.pred, 1].max
else
running_content_body_offset = body_offset
end
if ::Integer === (page_numbering_start_at = @theme.page_numbering_start_at || 'body')
page_numbering_body_offset = body_offset + [page_numbering_start_at.pred, 1].max
else
page_numbering_body_offset = body_offset
end
num_front_matter_pages = [running_content_body_offset, page_numbering_body_offset]
end
@index.start_page_number = num_front_matter_pages[1] + 1
doc.set_attr 'pdf-anchor', (doc_anchor = derive_anchor_from_id doc.id, 'top')
add_dest_for_block doc, doc_anchor
convert_section generate_manname_section doc if doc.doctype == 'manpage' && (doc.attr? 'manpurpose')
traverse doc
# NOTE: for a book, these are leftover footnotes; for an article this is everything
outdent_section { layout_footnotes doc }
toc_page_nums = @toc_extent ? (layout_toc doc, toc_num_levels, @toc_extent[:page_nums].first, @toc_extent[:start_y], num_front_matter_pages[1]) : []
# NOTE: delete orphaned page (a page was created but there was no additional content)
# QUESTION should we delete page if document is empty? (leaving no pages?)
delete_page if page_count > 1 && page.empty?
end
unless page_count < body_start_page_number
layout_running_content :header, doc, skip: num_front_matter_pages, body_start_page_number: body_start_page_number unless doc.noheader || @theme.header_height.to_f == 0
layout_running_content :footer, doc, skip: num_front_matter_pages, body_start_page_number: body_start_page_number unless doc.nofooter || @theme.footer_height.to_f == 0
end
add_outline doc, (doc.attr 'outlinelevels', toc_num_levels), toc_page_nums, num_front_matter_pages[1], has_front_cover
if (initial_zoom = @theme.page_initial_zoom)
case initial_zoom.to_sym
when :Fit
catalog.data[:OpenAction] = dest_fit state.pages[0]
when :FitV
catalog.data[:OpenAction] = dest_fit_vertically 0, state.pages[0]
when :FitH
catalog.data[:OpenAction] = dest_fit_horizontally page_height, state.pages[0]
end
end
catalog.data[:ViewerPreferences] = { DisplayDocTitle: true }
stamp_foreground_image doc, has_front_cover
layout_cover_page doc, :back
nil
end
# NOTE: embedded only makes sense if perhaps we are building
# on an existing Prawn::Document instance; for now, just treat
# it the same as a full document.
alias convert_embedded convert_document
def init_pdf doc
(instance_variables - @initial_instance_variables).each {|ivar| remove_instance_variable ivar } if state
pdf_opts = build_pdf_options doc, (theme = load_theme doc)
# QUESTION should page options be preserved? (otherwise, not readily available)
#@page_opts = { size: pdf_opts[:page_size], layout: pdf_opts[:page_layout] }
((::Prawn::Document.instance_method :initialize).bind self).call pdf_opts
renderer.min_version (@pdf_version = PDFVersions[doc.attr 'pdf-version'])
@page_margin_by_side = { recto: page_margin, verso: page_margin, cover: page_margin }
if (@media = doc.attr 'media', 'screen') == 'prepress'
@ppbook = doc.doctype == 'book'
page_margin_recto = @page_margin_by_side[:recto]
if (page_margin_outer = theme.page_margin_outer)
page_margin_recto[1] = @page_margin_by_side[:verso][3] = page_margin_outer
end
if (page_margin_inner = theme.page_margin_inner)
page_margin_recto[3] = @page_margin_by_side[:verso][1] = page_margin_inner
end
# NOTE: prepare scratch document to use page margin from recto side (which has same width as verso side)
set_page_margin page_margin_recto unless page_margin_recto == page_margin
else
@ppbook = nil
end
# QUESTION should ThemeLoader handle registering fonts instead?
register_fonts theme.font_catalog, (doc.attr 'pdf-fontsdir', 'GEM_FONTS_DIR')
default_kerning theme.base_font_kerning != 'none'
@fallback_fonts = [*theme.font_fallbacks]
@allow_uri_read = doc.attr? 'allow-uri-read'
@cache_uri = doc.attr? 'cache-uri'
@tmp_files = {}
if (bg_image = resolve_background_image doc, theme, 'page-background-image') && bg_image[0]
@page_bg_image = { verso: bg_image, recto: bg_image }
else
@page_bg_image = { verso: nil, recto: nil }
end
if (bg_image = resolve_background_image doc, theme, 'page-background-image-verso')
@page_bg_image[:verso] = bg_image[0] && bg_image
end
if (bg_image = resolve_background_image doc, theme, 'page-background-image-recto')
@page_bg_image[:recto] = bg_image[0] && bg_image
end
@page_bg_color = resolve_theme_color :page_background_color, 'FFFFFF'
@root_font_size = theme.base_font_size || 12
@font_scale = 1
@font_color = theme.base_font_color || '000000'
@text_decoration_width = theme.base_text_decoration_width
@base_align = (align = doc.attr 'text-align') && (TextAlignmentNames.include? align) ? align : theme.base_align
@cjk_line_breaks = doc.attr? 'scripts', 'cjk'
if (hyphen_lang = doc.attr 'hyphens') &&
((defined? ::Text::Hyphen::VERSION) || !(Helpers.require_library 'text/hyphen', 'text-hyphen', :warn).nil?)
hyphen_lang = doc.attr 'lang' if hyphen_lang.empty?
hyphen_lang = 'en_us' if hyphen_lang.nil_or_empty? || hyphen_lang == 'en'
hyphen_lang = (hyphen_lang.tr '-', '_').downcase
@hyphenator = ::Text::Hyphen.new language: hyphen_lang
end
@text_transform = nil
@list_numerals = []
@list_bullets = []
@rendered_footnotes = []
@conum_glyphs = ConumSets[@theme.conum_glyphs || 'circled'] || (@theme.conum_glyphs.split ',').map {|r|
from, to = r.rstrip.split '-', 2
to ? ((get_char from)..(get_char to)).to_a : [(get_char from)]
}.flatten
@section_indent = (val = @theme.section_indent) && (expand_indent_value val)
@toc_max_pagenum_digits = (doc.attr 'toc-max-pagenum-digits', 3).to_i
@disable_running_content = {}
@index ||= IndexCatalog.new
# NOTE: we have to init Pdfmark class here while we have reference to the doc
@pdfmark = (doc.attr? 'pdfmark') ? (Pdfmark.new doc) : nil
@optimize = doc.attr 'optimize'
init_scratch_prototype
self
end
def load_theme doc
@theme ||= begin # rubocop:disable Naming/MemoizedInstanceVariableName
if (theme = doc.options[:pdf_theme])
@themesdir = ::File.expand_path theme.__dir__ || (doc.attr 'pdf-themesdir') || (doc.attr 'pdf-stylesdir') || ::Dir.pwd
elsif (theme_name = (doc.attr 'pdf-theme') || (doc.attr 'pdf-style'))
theme = ThemeLoader.load_theme theme_name, (user_themesdir = (doc.attr 'pdf-themesdir') || (doc.attr 'pdf-stylesdir'))
@themesdir = theme.__dir__
else
@themesdir = (theme = ThemeLoader.load_theme).__dir__
end
theme
rescue
if user_themesdir
message = %(could not locate or load the pdf theme `#{theme_name}' in #{user_themesdir})
else
message = %(could not locate or load the built-in pdf theme `#{theme_name}')
end
message += %( because of #{$!.class} #{$!.message}) unless ::SystemCallError === $!
logger.error %(#{message}; reverting to default theme)
@themesdir = (theme = ThemeLoader.load_theme).__dir__
theme
end
end
def build_pdf_options doc, theme
case (page_margin = (doc.attr 'pdf-page-margin') || theme.page_margin)
when ::Array
if page_margin.empty?
page_margin = nil
else
page_margin = page_margin.slice 0, 4 if page_margin.length > 4
page_margin = page_margin.map {|v| ::Numeric === v ? v : (str_to_pt v.to_s) }
end
when ::Numeric
page_margin = [page_margin]
when ::String
if page_margin.empty?
page_margin = nil
elsif (page_margin.start_with? '[') && (page_margin.end_with? ']')
if (page_margin = (page_margin.slice 1, page_margin.length - 2).rstrip).empty?
page_margin = nil
else
if (page_margin = page_margin.split ',', -1).length > 4
page_margin = page_margin.slice 0, 4
end
page_margin = page_margin.map {|v| str_to_pt v.rstrip }
end
else
page_margin = [(str_to_pt page_margin)]
end
else
page_margin = nil
end
if (doc.attr? 'pdf-page-size') && PageSizeRx =~ (doc.attr 'pdf-page-size')
# e.g, [8.5in, 11in]
if $1
page_size = [$1, $2]
# e.g, 8.5in x 11in
elsif $3
page_size = [$3, $4]
# e.g, A4
else
page_size = $&
end
else
page_size = theme.page_size
end
case page_size
when ::String, ::Symbol
# TODO: extract helper method to check for named page size
page_size = page_size.to_s.upcase
page_size = nil unless ::PDF::Core::PageGeometry::SIZES.key? page_size
when ::Array
if page_size.empty?
page_size = nil
else
page_size[1] ||= page_size[0]
page_size = (page_size.slice 0, 2).map do |dim|
if ::Numeric === dim
# dimension cannot be less than 0
dim > 0 ? dim : break
elsif ::String === dim && MeasurementPartsRx =~ dim
# NOTE: truncate to max precision retained by PDF::Core
(dim = (to_pt $1.to_f, $2).truncate 4) > 0 ? dim : break
else
break
end
end
end
else
page_size = nil
end
if (page_layout = (doc.attr 'pdf-page-layout') || theme.page_layout).nil_or_empty? ||
!PageLayouts.include?(page_layout = page_layout.to_sym)
page_layout = nil
end
{
margin: (page_margin || 36),
page_size: (page_size || 'A4'),
page_layout: (page_layout || :portrait),
info: (build_pdf_info doc),
compress: (doc.attr? 'compress'),
skip_page_creation: true,
text_formatter: (FormattedText::Formatter.new theme: theme),
}
end
# FIXME: Pdfmark should use the PDF info result
def build_pdf_info doc
info = {}
if (doctitle = doc.header? ? doc.doctitle : (doc.attr 'untitled-label'))
info[:Title] = (sanitize doctitle).as_pdf
end
info[:Author] = (sanitize doc.attr 'authors').as_pdf if doc.attr? 'authors'
info[:Subject] = (sanitize doc.attr 'subject').as_pdf if doc.attr? 'subject'
info[:Keywords] = (sanitize doc.attr 'keywords').as_pdf if doc.attr? 'keywords'
info[:Producer] = (sanitize doc.attr 'publisher').as_pdf if doc.attr? 'publisher'
if doc.attr? 'reproducible'
info[:Creator] = 'Asciidoctor PDF, based on Prawn'.as_pdf
info[:Producer] ||= (info[:Author] || info[:Creator])
else
info[:Creator] = %(Asciidoctor PDF #{::Asciidoctor::PDF::VERSION}, based on Prawn #{::Prawn::VERSION}).as_pdf
info[:Producer] ||= (info[:Author] || info[:Creator])
# NOTE: since we don't track the creation date of the input file, we map the ModDate header to the last modified
# date of the input document and the CreationDate header to the date the PDF was produced by the converter.
info[:ModDate] = (::Time.parse doc.attr 'docdatetime') rescue (now ||= ::Time.now)
info[:CreationDate] = (::Time.parse doc.attr 'localdatetime') rescue (now || ::Time.now)
end
info
end
# NOTE: init_page is called within a float context
# NOTE: init_page is not called for imported pages, front and back cover pages, and other image pages
def init_page *_args
# NOTE: we assume in prepress that physical page number reflects page side
if @media == 'prepress' &&
(next_page_margin = @page_margin_by_side[page_number == 1 ? :cover : page_side]) != page_margin
set_page_margin next_page_margin
end
unless @page_bg_color == 'FFFFFF'
tare = true
fill_absolute_bounds @page_bg_color
end
if (bg_image = @page_bg_image[page_side])
tare = true
# NOTE: float is necessary since prawn-svg may mess with cursor position
float { canvas { image bg_image[0], ({ position: :center, vposition: :center }.merge bg_image[1]) } }
end
page.tare_content_stream if tare
end
def convert_section sect, _opts = {}
if sect.sectname == 'abstract'
# HACK: cheat a bit to hide this section from TOC; TOC should filter these sections
sect.context = :open
return convert_abstract sect
elsif (index_section = sect.sectname == 'index')
return if @index.empty?
end
type = nil
title = sect.numbered_title formal: true
sep = (sect.attr 'separator') || (sect.document.attr 'title-separator') || ''
if !sep.empty? && title.include?(sep = %(#{sep} ))
title, _, subtitle = title.rpartition sep
title = %(#{title}\n<em class="subtitle">#{subtitle}</em>)
end
theme_font :heading, level: (hlevel = sect.level + 1) do
align = (@theme[%(heading_h#{hlevel}_align)] || @theme.heading_align || @base_align).to_sym
if sect.part_or_chapter?
if sect.chapter?
type = :chapter
if @theme.heading_chapter_break_before == 'auto'
start_new_chapter sect if @theme.heading_part_break_after == 'always' && sect == sect.parent.sections[0]
else
start_new_chapter sect
end
else
type = :part
start_new_part sect unless @theme.heading_part_break_before == 'auto'
end
end
unless at_page_top?
# FIXME: this height doesn't account for impact of text transform or inline formatting
heading_height =
(height_of_typeset_text title, line_height: (@theme[%(heading_h#{hlevel}_line_height)] || @theme.heading_line_height)) +
(@theme[%(heading_h#{hlevel}_margin_top)] || @theme.heading_margin_top || 0) +
(@theme[%(heading_h#{hlevel}_margin_bottom)] || @theme.heading_margin_bottom || 0)
heading_height += (@theme.heading_min_height_after || 0) if sect.blocks?
start_new_page unless cursor > heading_height
end
# QUESTION should we store pdf-page-start, pdf-anchor & pdf-destination in internal map?
sect.set_attr 'pdf-page-start', (start_pgnum = page_number)
# QUESTION should we just assign the section this generated id?
# NOTE: section must have pdf-anchor in order to be listed in the TOC
sect.set_attr 'pdf-anchor', (sect_anchor = derive_anchor_from_id sect.id, %(#{start_pgnum}-#{y.ceil}))
add_dest_for_block sect, sect_anchor
if type == :part
layout_part_title sect, title, align: align, level: hlevel
elsif type == :chapter
layout_chapter_title sect, title, align: align, level: hlevel
else
layout_heading title, align: align, level: hlevel, outdent: true
end
end
if index_section
outdent_section { convert_index_section sect }
else
traverse sect
end
outdent_section { layout_footnotes sect } if type == :chapter
sect.set_attr 'pdf-page-end', page_number
end
def indent_section
if (values = @section_indent)
indent(values[0], values[1]) { yield }
else
yield
end
end
def outdent_section enabled = true
if enabled && (values = @section_indent)
indent(-values[0], -values[1]) { yield }
else
yield
end
end
# QUESTION if a footnote ref appears in a separate chapter, should the footnote def be duplicated?
def layout_footnotes node
return if (fns = (doc = node.document).footnotes - @rendered_footnotes).empty?
theme_margin :footnotes, :top
theme_font :footnotes do
(title = doc.attr 'footnotes-title') && (layout_caption title, category: :footnotes)
item_spacing = @theme.footnotes_item_spacing || 0
index_offset = @rendered_footnotes.length
sect_xreftext = node.context == :section && (node.xreftext node.document.attr 'xrefstyle')
fns.each do |fn|
label = (index = fn.index) - index_offset
if sect_xreftext
fn.singleton_class.send :attr_accessor, :label unless fn.respond_to? :label=
fn.label = %(#{label} - #{sect_xreftext})
end
layout_prose %(<a id="_footnotedef_#{index}">#{DummyText}</a>[<a anchor="_footnoteref_#{index}">#{label}</a>] #{fn.text}), margin_bottom: item_spacing, hyphenate: true
end
@rendered_footnotes += fns
end
nil
end
def convert_floating_title node
add_dest_for_block node if node.id
hlevel = node.level.next
unless (align = resolve_alignment_from_role node.roles)
align = (@theme[%(heading_h#{hlevel}_align)] || @theme.heading_align || @base_align).to_sym
end
# QUESTION should we decouple styles from section titles?
theme_font :heading, level: hlevel do
layout_heading node.title, align: align, level: hlevel, outdent: (node.parent.context == :section)
end
end
def convert_abstract node
add_dest_for_block node if node.id
outdent_section do
pad_box @theme.abstract_padding do
theme_font :abstract_title do
layout_prose node.title, align: (@theme.abstract_title_align || @base_align).to_sym, margin_top: (@theme.heading_margin_top || 0), margin_bottom: (@theme.heading_margin_bottom || 0), line_height: @theme.heading_line_height
end if node.title?
theme_font :abstract do
prose_opts = { line_height: @theme.abstract_line_height, align: (@theme.abstract_align || @base_align).to_sym, hyphenate: true }
if (text_indent = @theme.prose_text_indent || 0) > 0
prose_opts[:indent_paragraphs] = text_indent
end
# FIXME: allow theme to control more first line options
if (line1_font_style = @theme.abstract_first_line_font_style) && line1_font_style.to_sym != font_style
first_line_options = { styles: [font_style, line1_font_style.to_sym] }
end
if (line1_font_color = @theme.abstract_first_line_font_color)
(first_line_options ||= {})[:color] = line1_font_color
end
prose_opts[:first_line_options] = first_line_options if first_line_options
# FIXME: make this cleaner!!
if node.blocks?
node.blocks.each do |child|
if child.context == :paragraph
child.document.playback_attributes child.attributes
layout_prose child.content, ((align = resolve_alignment_from_role child.roles) ? (prose_opts.merge align: align) : prose_opts.dup)
prose_opts.delete :first_line_options
else
# FIXME: this could do strange things if the wrong kind of content shows up
child.convert
end
end
elsif node.content_model != :compound && (string = node.content)
if (align = resolve_alignment_from_role node.roles)
prose_opts[:align] = align
end
layout_prose string, prose_opts
end
end
end
# QUESTION should we be adding margin below the abstract??
#theme_margin :block, :bottom
end
end
def convert_preamble node
# FIXME: core should not be promoting paragraph to preamble if there are no sections
if node.blocks? && (first_block = node.blocks[0]).context == :paragraph && node.document.sections?
first_block.add_role 'lead' unless first_block.role?
end
traverse node
end
def convert_paragraph node
add_dest_for_block node if node.id
prose_opts = { margin_bottom: 0, hyphenate: true }
lead = (roles = node.roles).include? 'lead'
if (align = resolve_alignment_from_role roles)
prose_opts[:align] = align
end
if (text_indent = @theme.prose_text_indent || 0) > 0
prose_opts[:indent_paragraphs] = text_indent
end
# TODO: check if we're within one line of the bottom of the page
# and advance to the next page if so (similar to logic for section titles)
layout_caption node, labeled: false if node.title?
if lead
theme_font :lead do
layout_prose node.content, prose_opts
end
else
layout_prose node.content, prose_opts
end
if (margin_inner_val = @theme.prose_margin_inner) &&
(next_block = (siblings = node.parent.blocks)[(siblings.index node) + 1]) && next_block.context == :paragraph
margin_bottom margin_inner_val
else
margin_bottom @theme.prose_margin_bottom
end
end
def convert_admonition node
add_dest_for_block node if node.id
theme_margin :block, :top
type = node.attr 'name'
label_align = (@theme.admonition_label_align || :center).to_sym
# TODO: allow vertical_align to be a number
if (label_valign = (@theme.admonition_label_vertical_align || :middle).to_sym) == :middle
label_valign = :center
end
if (label_min_width = @theme.admonition_label_min_width)
label_min_width = label_min_width.to_f
end
icons = ((doc = node.document).attr? 'icons') ? (doc.attr 'icons') : nil
if (data_uri_enabled = doc.attr? 'data-uri')
doc.remove_attr 'data-uri'
end
if icons == 'font' && !(node.attr? 'icon')
label_text = type.to_sym
icon_data = admonition_icon_data label_text
icon_size = icon_data[:size] || 24
label_width = label_min_width || (icon_size * 1.5)
# NOTE: icon_uri will consider icon attribute on node first, then type
# QUESTION should we use resolve_image_path here?
elsif icons && (icon_path = node.icon_uri type) &&
(icon_path = node.normalize_system_path icon_path, nil, nil, target_name: 'admonition icon') &&
(::File.readable? icon_path)
icons = true
# TODO: introduce @theme.admonition_image_width? or use size key from admonition_icon_<name>?
label_width = label_min_width || 36.0
else
if icons
icons = nil
logger.warn %(admonition icon not found or not readable: #{icon_path}) unless scratch?
end
label_text = sanitize node.caption
theme_font :admonition_label do
theme_font %(admonition_label_#{type}) do
label_text = transform_text label_text, @text_transform if @text_transform
label_width = rendered_width_of_string label_text
label_width = label_min_width if label_min_width && label_min_width > label_width
end
end
end
doc.set_attr 'data-uri', '' if data_uri_enabled
unless ::Array === (cpad = @theme.admonition_padding)
cpad = ::Array.new 4, cpad
end
unless ::Array === (lpad = @theme.admonition_label_padding || cpad)
lpad = ::Array.new 4, lpad
end
# FIXME: this shift stuff is a real hack until we have proper margin collapsing
shift_base = @theme.prose_margin_bottom
shift_top = shift_base / 3.0
shift_bottom = (shift_base * 2) / 3.0
keep_together do |box_height = nil|
push_scratch doc if scratch?
theme_fill_and_stroke_block :admonition, box_height if box_height
pad_box [0, cpad[1], 0, lpad[3]] do
if box_height
label_height = [box_height, cursor].min
if (rule_color = @theme.admonition_column_rule_color) &&
(rule_width = @theme.admonition_column_rule_width || @theme.base_border_width) && rule_width > 0
float do
rule_height = box_height
while rule_height > 0
rule_segment_height = [rule_height, cursor].min
bounding_box [0, cursor], width: label_width + lpad[1], height: rule_segment_height do
stroke_vertical_rule rule_color,
at: bounds.right,
line_style: (@theme.admonition_column_rule_style || :solid).to_sym,
line_width: rule_width
end
advance_page if (rule_height -= rule_segment_height) > 0
end
end
end
float do
bounding_box [0, cursor], width: label_width, height: label_height do
if icons == 'font'
# FIXME: we assume icon is square
icon_size = fit_icon_to_bounds icon_size
# NOTE: Prawn's vertical center is not reliable, so calculate it manually
if label_valign == :center
label_valign = :top
if (vcenter_pos = (label_height - icon_size) * 0.5) > 0
move_down vcenter_pos
end
end
icon icon_data[:name],
valign: label_valign,
align: label_align,
color: (icon_data[:stroke_color] || font_color),
size: icon_size
elsif icons
if (::Asciidoctor::Image.format icon_path) == 'svg'
begin
svg_obj = ::Prawn::SVG::Interface.new ::File.read(icon_path, mode: 'r:UTF-8'), self,
position: label_align,
vposition: label_valign,
width: label_width,
height: label_height,
fallback_font_name: fallback_svg_font_name,
enable_web_requests: allow_uri_read ? (method :load_open_uri).to_proc : false,
enable_file_requests_with_root: (::File.dirname icon_path),
cache_images: cache_uri
if (icon_height = (svg_size = svg_obj.document.sizing).output_height) > label_height
icon_width = (svg_obj.resize height: (icon_height = label_height)).output_width
else
icon_width = svg_size.output_width
end
svg_obj.draw
svg_obj.document.warnings.each do |icon_warning|
logger.warn %(problem encountered in image: #{icon_path}; #{icon_warning})
end unless scratch?
rescue
logger.warn %(could not embed admonition icon: #{icon_path}; #{$!.message}) unless scratch?
end
else
begin
image_obj, image_info = ::File.open(icon_path, 'rb') {|fd| build_image_object fd }
icon_aspect_ratio = image_info.width.fdiv image_info.height
# NOTE: don't scale image up if smaller than label_width
icon_width = [(to_pt image_info.width, :px), label_width].min
if (icon_height = icon_width * (1 / icon_aspect_ratio)) > label_height
icon_width *= label_height / icon_height
icon_height = label_height # rubocop:disable Lint/UselessAssignment
end
embed_image image_obj, image_info, width: icon_width, position: label_align, vposition: label_valign
rescue
# QUESTION should we show the label in this case?
logger.warn %(could not embed admonition icon: #{icon_path}; #{$!.message}) unless scratch?
end
end
else
# IMPORTANT the label must fit in the alotted space or it shows up on another page!
# QUESTION anyway to prevent text overflow in the case it doesn't fit?
theme_font :admonition_label do
theme_font %(admonition_label_#{type}) do
# NOTE: Prawn's vertical center is not reliable, so calculate it manually
if label_valign == :center
label_valign = :top
if (vcenter_pos = (label_height - (height_of_typeset_text label_text, line_height: 1)) * 0.5) > 0
move_down vcenter_pos
end
end
@text_transform = nil # already applied to label
layout_prose label_text,
align: label_align,
valign: label_valign,
line_height: 1,
margin: 0,
inline_format: false # already replaced character references
end
end
end
end
end
end
pad_box [cpad[0], 0, cpad[2], label_width + lpad[1] + cpad[3]] do
move_down shift_top
layout_caption node, category: :admonition, labeled: false if node.title?
theme_font :admonition do
traverse node
end
# FIXME: HACK compensate for margin bottom of admonition content
move_up shift_bottom unless at_page_top?
end
end
pop_scratch doc if scratch?
end
theme_margin :block, :bottom
end
def convert_example node
return convert_open node if node.option? 'collapsible'
add_dest_for_block node if node.id
theme_margin :block, :top
caption_height = node.title? ? (layout_caption node, category: :example, dry_run: true) : 0
keep_together do |box_height = nil|
push_scratch node.document if scratch?
if box_height
theme_fill_and_stroke_block :example, box_height, caption_node: node
else
move_down caption_height
end
pad_box @theme.example_padding do
theme_font :example do
traverse node
end
end
pop_scratch node.document if scratch?
end
theme_margin :block, :bottom
end
def convert_open node
return convert_abstract node if node.style == 'abstract'
doc = node.document
keep_together_if node.option? 'unbreakable' do
push_scratch doc if scratch?
add_dest_for_block node if node.id
node.context == :example ? (layout_caption %(\u25bc #{node.title})) : (layout_caption node, labeled: false) if node.title?
traverse node
pop_scratch doc if scratch?
end
end
def convert_quote_or_verse node
add_dest_for_block node if node.id
theme_margin :block, :top
category = node.context == :quote ? :blockquote : :verse
# NOTE: b_width and b_left_width are mutually exclusive
unless (b_left_width = @theme[%(#{category}_border_left_width)]) && b_left_width > 0
b_left_width = nil
if (b_width = @theme[%(#{category}_border_width)])
b_width = nil unless b_width > 0
end
end
keep_together do |box_height = nil|
push_scratch node.document if scratch?
theme_fill_and_stroke_block category, box_height, border_width: b_width if box_height && (b_width || @theme[%(#{category}_background_color)])
start_page_number = page_number
start_cursor = cursor
caption_height = node.title? ? (layout_caption node, category: category, labeled: false) : 0
pad_box @theme[%(#{category}_padding)] do
theme_font category do
if category == :blockquote
traverse node
else # verse
content = guard_indentation node.content
layout_prose content, normalize: false, align: :left, hyphenate: true
end
end
if node.attr? 'attribution'
theme_font %(#{category}_cite) do
# NOTE temporary workaround to allow bare & to be used without having to wrap value in single quotes
attribution = node.attr 'attribution'
attribution = escape_amp attribution if attribution.include? '&'
attribution_parts = [attribution]
if (citetitle = node.attr 'citetitle')
citetitle = escape_amp citetitle if citetitle.include? '&'
attribution_parts << citetitle
end
layout_prose %(#{EmDash} #{attribution_parts.join ', '}), align: :left, normalize: false
end
end
end
# FIXME: we want to draw graphics before content, but box_height is not reliable when spanning pages
# FIXME: border extends to bottom of content area if block terminates at bottom of page
if box_height && b_left_width
b_color = @theme[%(#{category}_border_color)]
page_spread = page_number - start_page_number + 1
end_cursor = cursor
go_to_page start_page_number
move_cursor_to start_cursor
page_spread.times do |i|
if i == 0
y_draw = cursor
b_height = page_spread > 1 ? y_draw : (y_draw - end_cursor)
else
bounds.move_past_bottom
y_draw = cursor
b_height = page_spread - 1 == i ? (y_draw - end_cursor) : y_draw
end
# NOTE: skip past caption if present
if caption_height > 0
if caption_height > cursor
caption_height -= cursor
next # keep skipping, caption is on next page
end
y_draw -= caption_height
b_height -= caption_height
caption_height = 0
end
# NOTE: b_height is 0 when block terminates at bottom of page
next if b_height == 0
bounding_box [0, y_draw], width: bounds.width, height: b_height do
stroke_vertical_rule b_color, line_width: b_left_width, at: b_left_width * 0.5
end
end
end
pop_scratch node.document if scratch?
end
theme_margin :block, :bottom
end
alias convert_quote convert_quote_or_verse
alias convert_verse convert_quote_or_verse
def convert_sidebar node
add_dest_for_block node if node.id
theme_margin :block, :top
keep_together do |box_height = nil|
push_scratch node.document if scratch?
theme_fill_and_stroke_block :sidebar, box_height if box_height
pad_box @theme.sidebar_padding do
theme_font :sidebar_title do
# QUESTION should we allow margins of sidebar title to be customized?
layout_prose node.title, align: (@theme.sidebar_title_align || @base_align).to_sym, margin_top: 0, margin_bottom: (@theme.heading_margin_bottom || 0), line_height: @theme.heading_line_height
end if node.title?
theme_font :sidebar do
traverse node
end
end
pop_scratch node.document if scratch?
end
theme_margin :block, :bottom
end
def convert_colist node
# HACK: undo the margin below previous listing or literal block
# TODO: allow this to be set using colist_margin_top
if (self_idx = node.parent.blocks.index node) && self_idx > 0 &&
[:listing, :literal].include?(node.parent.blocks[self_idx - 1].context)
move_up @theme.block_margin_bottom - @theme.outline_list_item_spacing
end unless at_page_top?
add_dest_for_block node if node.id
@list_numerals << 1
line_metrics = theme_font(:conum) { calc_line_metrics @theme.base_line_height }
node.items.each do |item|
allocate_space_for_list_item line_metrics
convert_colist_item item
end
@list_numerals.pop
# correct bottom margin of last item
list_margin_bottom = @theme.prose_margin_bottom
margin_bottom list_margin_bottom - @theme.outline_list_item_spacing
end
def convert_colist_item node
marker_width = nil
@list_numerals << (index = @list_numerals.pop).next
theme_font :conum do
marker_width = rendered_width_of_string %(#{marker = conum_glyph index}x)
float do
bounding_box [0, cursor], width: marker_width do
theme_font :conum do
layout_prose marker, align: :center, line_height: @theme.conum_line_height, inline_format: false, margin: 0
end
end
end
end
indent marker_width do
traverse_list_item node, :colist, margin_bottom: @theme.outline_list_item_spacing, normalize_line_height: true
end
end
def convert_dlist node
add_dest_for_block node if node.id
case (style = node.style)
when 'unordered', 'ordered'
if style == 'unordered'
list_style = :ulist
(markers = @list_bullets) << :disc
else
list_style = :olist
(markers = @list_numerals) << 1
end
list = List.new node.parent, list_style
stack_subject = node.has_role? 'stack'
subject_stop = node.attr 'subject-stop', (stack_subject ? nil : ':')
node.items.each do |subjects, dd|
subject = [*subjects].first.text
if dd
list_item_text = %(+++<strong>#{subject}#{(StopPunctRx.match? sanitize subject) ? '' : subject_stop}</strong>#{dd.text? ? "#{stack_subject ? '<br>' : ' '}#{dd.text}" : ''}+++)
list_item = ListItem.new list, list_item_text
dd.blocks.each {|it| list_item << it } if dd.blocks?
else
list_item = ListItem.new list, %(+++<strong>#{subject}</strong>+++)
end
list << list_item
end
convert_outline_list list
markers.pop
when 'horizontal'
table_data = []
term_padding = desc_padding = term_line_metrics = term_inline_format = term_kerning = nil
max_term_width = 0
theme_font :description_list_term do
term_inline_format = (term_font_styles = font_styles).empty? ? true : [inherited: { styles: term_font_styles }]
term_line_metrics = calc_line_metrics @theme.description_list_term_line_height || @theme.base_line_height
term_padding = [term_line_metrics.padding_top, 10, (@theme.prose_margin_bottom || 0) * 0.5 + term_line_metrics.padding_bottom, 10]
desc_padding = [0, 10, (@theme.prose_margin_bottom || 0) * 0.5, 10]
term_kerning = default_kerning?
end
node.items.each do |terms, desc|
term_text = terms.map(&:text).join ?\n
if (term_width = width_of term_text, inline_format: term_inline_format, kerning: term_kerning) > max_term_width
max_term_width = term_width
end
row_data = [{
text_color: @font_color,
kerning: term_kerning,
content: term_text,
inline_format: term_inline_format,
padding: term_padding,
leading: term_line_metrics.leading,
# FIXME: prawn-table doesn't have support for final_gap option
#final_gap: term_line_metrics.final_gap,
valign: :top,
}]
if desc
desc_container = Block.new desc, :open
desc_container << (Block.new desc_container, :paragraph, source: (desc.instance_variable_get :@text), subs: :default) if desc.text?
desc.blocks.each {|b| desc_container << b } if desc.blocks?
row_data << {
content: (::Prawn::Table::Cell::AsciiDoc.new self, content: desc_container, text_color: @font_color, padding: desc_padding, valign: :top),
}
else
row_data << {}
end
table_data << row_data
end
max_term_width += (term_padding[1] + term_padding[3])
term_column_width = [max_term_width, bounds.width * 0.5].min
table table_data, position: :left, cell_style: { border_width: 0 }, column_widths: [term_column_width] do
@pdf.layout_table_caption node if node.title?
end
margin_bottom (@theme.prose_margin_bottom || 0) * 0.5
when 'qanda'
@list_numerals << '1'
convert_outline_list node
@list_numerals.pop
else
# TODO: check if we're within one line of the bottom of the page
# and advance to the next page if so (similar to logic for section titles)
layout_caption node, category: :description_list, labeled: false if node.title?
term_line_height = @theme.description_list_term_line_height || @theme.base_line_height
line_metrics = theme_font(:description_list_term) { calc_line_metrics term_line_height }
node.items.each do |terms, desc|
# NOTE: don't orphan the terms (keep together terms and at least one line of content)
allocate_space_for_list_item line_metrics, (terms.size + 1), ((@theme.description_list_term_spacing || 0) + 0.05)
theme_font :description_list_term do
if (term_font_styles = font_styles).empty?
term_font_styles = nil
end
terms.each do |term|
# QUESTION should we pass down styles in other calls to layout_prose
layout_prose term.text, margin_top: 0, margin_bottom: @theme.description_list_term_spacing, align: :left, line_height: term_line_height, normalize_line_height: true, styles: term_font_styles
end
end
indent(@theme.description_list_description_indent || 0) do
traverse_list_item desc, :dlist_desc, normalize_line_height: true
end if desc
end
end
end
def convert_olist node
add_dest_for_block node if node.id
# TODO: move list_numeral resolve to a method
case node.style
when 'arabic'
list_numeral = 1
when 'decimal'
list_numeral = '01'
when 'loweralpha'
list_numeral = 'a'
when 'upperalpha'
list_numeral = 'A'
when 'lowerroman'
list_numeral = RomanNumeral.new 'i'
when 'upperroman'
list_numeral = RomanNumeral.new 'I'
when 'lowergreek'
list_numeral = LowercaseGreekA
when 'unstyled', 'unnumbered', 'no-bullet'
list_numeral = nil
when 'none'
list_numeral = ''
else
list_numeral = 1
end
if list_numeral && list_numeral != '' &&
(start = (node.attr 'start') || ((node.option? 'reversed') ? node.items.size : nil))
if (start = start.to_i) > 1
(start - 1).times { list_numeral = list_numeral.next }
elsif start < 1 && !(::String === list_numeral)
(start - 1).abs.times { list_numeral = list_numeral.pred }
end
end
@list_numerals << list_numeral
convert_outline_list node
@list_numerals.pop
end
def convert_ulist node
add_dest_for_block node if node.id
# TODO: move bullet_type to method on List (or helper method)
if node.option? 'checklist'
@list_bullets << :checkbox
else
if (style = node.style)
case style
when 'bibliography'
bullet_type = :square
when 'unstyled', 'no-bullet'
bullet_type = nil
else
candidate = style.to_sym
if Bullets.key? candidate
bullet_type = candidate
else
logger.warn %(unknown unordered list style: #{candidate}) unless scratch?
bullet_type = :disc
end
end
else
case node.outline_level
when 1
bullet_type = :disc
when 2
bullet_type = :circle
else
bullet_type = :square
end
end
@list_bullets << bullet_type
end
convert_outline_list node
@list_bullets.pop
end
def convert_outline_list node
# TODO: check if we're within one line of the bottom of the page
# and advance to the next page if so (similar to logic for section titles)
layout_caption node, category: :outline_list, labeled: false if node.title?
opts = {}
if (align = resolve_alignment_from_role node.roles)
opts[:align] = align
elsif node.style == 'bibliography'
opts[:align] = :left
elsif (align = @theme.outline_list_text_align)
# NOTE: theme setting only affects alignment of list text (not nested blocks)
opts[:align] = align.to_sym
end
line_metrics = calc_line_metrics @theme.base_line_height
#complex = false
# ...or if we want to give all items in the list the same treatment
#complex = node.items.find(&:compound?) ? true : false
if (node.context == :ulist && !@list_bullets[-1]) || (node.context == :olist && !@list_numerals[-1])
if node.style == 'unstyled'
# unstyled takes away all indentation
list_indent = 0
elsif (list_indent = @theme.outline_list_indent || 0) > 0
# no-bullet aligns text with left-hand side of bullet position (as though there's no bullet)
list_indent = [list_indent - (rendered_width_of_string %(#{node.context == :ulist ? ?\u2022 : '1.'}x)), 0].max
end
else
list_indent = @theme.outline_list_indent || 0
end
indent list_indent do
node.items.each do |item|
allocate_space_for_list_item line_metrics
convert_outline_list_item item, node, opts
end
end
# NOTE: children will provide the necessary bottom margin if last item is complex.
# However, don't leave gap at the bottom if list is nested in an outline list
#unless complex || (node.nested? && node.parent.parent.outline?)
unless node.nested? && node.parent.parent.outline?
# correct bottom margin of last item
margin_bottom((@theme.prose_margin_bottom || 0) - (@theme.outline_list_item_spacing || 0))
end
end
def convert_outline_list_item node, list, opts = {}
# TODO: move this to a draw_bullet (or draw_marker) method
marker_style = {}
marker_style[:font_color] = @theme.outline_list_marker_font_color || @font_color
marker_style[:font_family] = font_family
marker_style[:font_size] = font_size
marker_style[:line_height] = @theme.base_line_height
case (list_type = list.context)
when :dlist
# NOTE: list.style is 'qanda'
complex = node[1]&.compound?
@list_numerals << (index = @list_numerals.pop).next
marker = %(#{index}.)
when :olist
complex = node.compound?
if (index = @list_numerals.pop)
if index == ''
marker = ''
else
marker = %(#{index}.)
dir = (node.parent.option? 'reversed') ? :pred : :next
@list_numerals << (index.public_send dir)
end
end
else # :ulist
complex = node.compound?
if (marker_type = @list_bullets[-1])
if marker_type == :checkbox
# QUESTION should we remove marker indent if not a checkbox?
if node.attr? 'checkbox'
marker_type = (node.attr? 'checked') ? :checked : :unchecked
marker = @theme[%(ulist_marker_#{marker_type}_content)] || BallotBox[marker_type]
end
else
marker = @theme[%(ulist_marker_#{marker_type}_content)] || Bullets[marker_type]
end
[:font_color, :font_family, :font_size, :line_height].each do |prop|
marker_style[prop] = @theme[%(ulist_marker_#{marker_type}_#{prop})] || @theme[%(ulist_marker_#{prop})] || marker_style[prop]
end if marker
end
end
if marker
if marker_style[:font_family] == 'fa'
logger.info 'deprecated fa icon set found in theme; use fas, far, or fab instead' unless scratch?
marker_style[:font_family] = FontAwesomeIconSets.find {|candidate| (icon_font_data candidate).yaml[candidate].value? marker } || 'fas'
end
marker_gap = rendered_width_of_char 'x'
font marker_style[:font_family], size: marker_style[:font_size] do
marker_width = rendered_width_of_string marker
# NOTE compensate if character_spacing is not applied to first character
# see https://github.com/prawnpdf/prawn/commit/c61c5d48841910aa11b9e3d6f0e01b68ce435329
character_spacing_correction = 0
character_spacing(-0.5) do
character_spacing_correction = 0.5 if (rendered_width_of_char 'x', character_spacing: -0.5) == marker_gap
end
marker_height = height_of_typeset_text marker, line_height: marker_style[:line_height], single_line: true
start_position = -marker_width + -marker_gap + character_spacing_correction
float do
start_new_page if @media == 'prepress' && cursor < marker_height
flow_bounding_box start_position, width: marker_width do
layout_prose marker,
align: :right,
character_spacing: -0.5,
color: marker_style[:font_color],
inline_format: false,
line_height: marker_style[:line_height],
margin: 0,
normalize: false,
single_line: true
end
end
end
end
if complex
traverse_list_item node, list_type, (opts.merge normalize_line_height: true)
else
traverse_list_item node, list_type, (opts.merge margin_bottom: @theme.outline_list_item_spacing, normalize_line_height: true)
end
end
def traverse_list_item node, list_type, opts = {}
if list_type == :dlist # qanda
terms, desc = node
terms.each {|term| layout_prose %(<em>#{term.text}</em>), (opts.merge margin_top: 0, margin_bottom: @theme.description_list_term_spacing) }
if desc
layout_prose desc.text, (opts.merge hyphenate: true) if desc.text?
traverse desc
end
else
if (primary_text = node.text).nil_or_empty?
layout_prose DummyText, opts unless node.blocks?
else
layout_prose primary_text, (opts.merge hyphenate: true)
end
traverse node
end
end
def allocate_space_for_list_item line_metrics, number = 1, additional_gap = 0
advance_page if !at_page_top? && cursor < (line_metrics.height + line_metrics.leading + line_metrics.padding_top + additional_gap) * number
end
def convert_image node, opts = {}
node.extend ::Asciidoctor::Image unless ::Asciidoctor::Image === node
target, image_format = node.target_and_format
if image_format == 'gif' && !(defined? ::GMagick::Image)
logger.warn %(GIF image format not supported. Install the prawn-gmagick gem or convert #{target} to PNG.) unless scratch?
image_path = nil
elsif ::Base64 === target
image_path = target
elsif (image_path = resolve_image_path node, target, image_format, (opts.fetch :relative_to_imagesdir, true))
if image_format == 'pdf'
if ::File.readable? image_path
if (id = node.id)
add_dest_block = proc do
node.set_attr 'pdf-destination', (node_dest = dest_top)
add_dest id, node_dest
end
end
# NOTE: import_page automatically advances to next page afterwards
# QUESTION should we add destination to top of imported page?
if (pgnums = node.attr 'pages')
(resolve_pagenums pgnums).each_with_index do |pgnum, idx|
if idx == 0
import_page image_path, page: pgnum, replace: page.empty?, &add_dest_block
else
import_page image_path, page: pgnum, replace: true
end
end
else
import_page image_path, page: [(node.attr 'page', nil, 1).to_i, 1].max, replace: page.empty?, &add_dest_block
end
return
else
logger.warn %(pdf to insert not found or not readable: #{image_path}) unless scratch?
image_path = nil
end
elsif !(::File.readable? image_path)
logger.warn %(image to embed not found or not readable: #{image_path}) unless scratch?
image_path = nil
end
end
theme_margin :block, :top unless (pinned = opts[:pinned])
return on_image_error :missing, node, target, opts unless image_path
alignment = ((node.attr 'align') || (resolve_alignment_from_role node.roles) || @theme.image_align || :left).to_sym
# TODO: support cover (aka canvas) image layout using "canvas" (or "cover") role
width = resolve_explicit_width node.attributes, bounds_width: (available_w = bounds.width), support_vw: true, use_fallback: true, constrain_to_bounds: true
# TODO: add `to_pt page_width` method to ViewportWidth type
width = (width.to_f / 100) * page_width if ViewportWidth === width
# NOTE: if width is not set explicitly and max-width is fit-content, caption height may not be accurate
caption_h = node.title? ? (layout_caption node, category: :image, side: :bottom, block_align: alignment, block_width: width, max_width: @theme.image_caption_max_width, dry_run: true) : 0
align_to_page = node.option? 'align-to-page'
begin
rendered_w = nil
span_page_width_if align_to_page do
if image_format == 'svg'
if ::Base64 === image_path
svg_data = ::Base64.decode64 image_path
file_request_root = false
else
svg_data = ::File.read image_path, mode: 'r:UTF-8'
file_request_root = ::File.dirname image_path
end
svg_obj = ::Prawn::SVG::Interface.new svg_data, self,
position: alignment,
width: width,
fallback_font_name: fallback_svg_font_name,
enable_web_requests: allow_uri_read ? (method :load_open_uri).to_proc : false,
enable_file_requests_with_root: file_request_root,
cache_images: cache_uri
rendered_w = (svg_size = svg_obj.document.sizing).output_width
if !width && (svg_obj.document.root.attributes.key? 'width')
# NOTE: restrict width to available width (prawn-svg already coerces to pixels)
svg_size = svg_obj.resize width: (rendered_w = available_w) if rendered_w > available_w
end
# NOTE: shrink image so it fits within available space; group image & caption
if (rendered_h = svg_size.output_height) > (available_h = cursor - caption_h)
unless pinned || at_page_top?
advance_page
available_h = cursor - caption_h
end
rendered_w = (svg_obj.resize height: (rendered_h = available_h)).output_width if rendered_h > available_h
end
image_y = y
image_cursor = cursor
add_dest_for_block node if node.id
# NOTE: workaround to fix Prawn not adding fill and stroke commands on page that only has an image;
# breakage occurs when running content (stamps) are added to page
# seems to be resolved as of Prawn 2.2.2
#update_colors if graphic_state.color_space.empty?
# NOTE: prawn-svg 0.24.0, 0.25.0, & 0.25.1 didn't restore font after call to draw (see mogest/prawn-svg#80)
# NOTE: cursor advances automatically
svg_obj.draw
svg_obj.document.warnings.each do |img_warning|
logger.warn %(problem encountered in image: #{image_path}; #{img_warning})
end unless scratch?
draw_image_border image_cursor, rendered_w, rendered_h, alignment unless node.role? && (node.has_role? 'noborder')
if (link = node.attr 'link')
add_link_to_image link, { width: rendered_w, height: rendered_h }, position: alignment, y: image_y
end
else
# FIXME: this code really needs to be better organized!
# NOTE: use low-level API to access intrinsic dimensions; build_image_object caches image data previously loaded
image_obj, image_info = ::Base64 === image_path ?
::StringIO.open((::Base64.decode64 image_path), 'rb') {|fd| build_image_object fd } :
::File.open(image_path, 'rb') {|fd| build_image_object fd }
# NOTE: if width is not specified, scale native width & height from px to pt and restrict width to available width
rendered_w, rendered_h = image_info.calc_image_dimensions width: (width || [available_w, (to_pt image_info.width, :px)].min)
# NOTE: shrink image so it fits within available space; group image & caption
if rendered_h > (available_h = cursor - caption_h)
unless pinned || at_page_top?
advance_page
available_h = cursor - caption_h
end
rendered_w, rendered_h = image_info.calc_image_dimensions height: available_h if rendered_h > available_h
end
image_y = y
image_cursor = cursor
add_dest_for_block node if node.id
# NOTE: workaround to fix Prawn not adding fill and stroke commands on page that only has an image;
# breakage occurs when running content (stamps) are added to page
# seems to be resolved as of Prawn 2.2.2
#update_colors if graphic_state.color_space.empty?
# NOTE: specify both width and height to avoid recalculation
embed_image image_obj, image_info, width: rendered_w, height: rendered_h, position: alignment
draw_image_border image_cursor, rendered_w, rendered_h, alignment unless node.role? && (node.has_role? 'noborder')
if (link = node.attr 'link')
add_link_to_image link, { width: rendered_w, height: rendered_h }, position: alignment, y: image_y
end
# NOTE: Asciidoctor disables automatic advancement of cursor for raster images, so move cursor manually
move_down rendered_h if y == image_y
end
end
layout_caption node, category: :image, side: :bottom, block_align: alignment, block_width: rendered_w, max_width: @theme.image_caption_max_width if node.title?
theme_margin :block, :bottom unless pinned
rescue
on_image_error :exception, node, target, (opts.merge message: %(could not embed image: #{image_path}; #{$!.message}#{::Prawn::Errors::UnsupportedImageType === $! && !(defined? ::GMagick::Image) ? '; install prawn-gmagick gem to add support' : ''}))
end
end
def draw_image_border top, w, h, alignment
if (@theme.image_border_width || 0) > 0 && @theme.image_border_color
if (@theme.image_border_fit || 'content') == 'auto'
bb_width = bounds.width
elsif alignment == :center
bb_x = (bounds.width - w) * 0.5
elsif alignment == :right
bb_x = bounds.width - w
end
bounding_box [(bb_x || 0), top], width: (bb_width || w), height: h, position: alignment do
theme_fill_and_stroke_bounds :image
end
true
end
end
def on_image_error _reason, node, target, opts = {}
logger.warn opts[:message] if (opts.key? :message) && !scratch?
alt_text_vars = { alt: (node.attr 'alt'), target: target }
alt_text_template = @theme.image_alt_content || '%{link}[%{alt}]%{/link} | <em>%{target}</em>'
return if alt_text_template.empty?
if (link = node.attr 'link')
alt_text_vars[:link] = %(<a href="#{link}">)
alt_text_vars[:'/link'] = '</a>'
else
alt_text_vars[:link] = ''
alt_text_vars[:'/link'] = ''
end
theme_font :image_alt do
layout_prose alt_text_template % alt_text_vars,
align: ((node.attr 'align') || @theme.image_align).to_sym,
margin: 0,
normalize: false,
single_line: true
end
layout_caption node, category: :image, side: :bottom if node.title?
theme_margin :block, :bottom unless opts[:pinned]
nil
end
def convert_audio node
add_dest_for_block node if node.id
theme_margin :block, :top
audio_path = node.media_uri node.attr 'target'
play_symbol = (node.document.attr? 'icons', 'font') ? %(<font name="fas">#{(icon_font_data 'fas').unicode 'play'}</font>) : RightPointer
layout_prose %(#{play_symbol}#{NoBreakSpace}<a href="#{audio_path}">#{audio_path}</a> <em>(audio)</em>), normalize: false, margin: 0, single_line: true
layout_caption node, labeled: false, side: :bottom if node.title?
theme_margin :block, :bottom
end
def convert_video node
case (poster = node.attr 'poster')
when 'youtube'
video_path = %(https://www.youtube.com/watch?v=#{video_id = node.attr 'target'})
# see http://stackoverflow.com/questions/2068344/how-do-i-get-a-youtube-video-thumbnail-from-the-youtube-api
poster = allow_uri_read ? %(https://img.youtube.com/vi/#{video_id}/maxresdefault.jpg) : nil
type = 'YouTube video'
when 'vimeo'
video_path = %(https://vimeo.com/#{video_id = node.attr 'target'})
poster = allow_uri_read ? load_open_uri.open_uri(%(http://vimeo.com/api/v2/video/#{video_id}.xml), 'r') {|f| VimeoThumbnailRx =~ f.read && $1 } : nil
type = 'Vimeo video'
else
video_path = node.media_uri node.attr 'target'
type = 'video'
end
if poster.nil_or_empty?
add_dest_for_block node if node.id
theme_margin :block, :top
play_symbol = (node.document.attr? 'icons', 'font') ? %(<font name="fas">#{(icon_font_data 'fas').unicode 'play'}</font>) : RightPointer
layout_prose %(#{play_symbol}#{NoBreakSpace}<a href="#{video_path}">#{video_path}</a> <em>(#{type})</em>), normalize: false, margin: 0, single_line: true
layout_caption node, labeled: false, side: :bottom if node.title?
theme_margin :block, :bottom
else
original_attributes = node.attributes.dup
begin
node.update_attributes 'target' => poster, 'link' => video_path
#node.set_attr 'pdfwidth', '100%' unless (node.attr? 'width') || (node.attr? 'pdfwidth')
convert_image node
ensure
node.attributes.replace original_attributes
end
end
end
# QUESTION can we avoid arranging fragments multiple times (conums & autofit) by eagerly preparing arranger?
def convert_listing_or_literal node
add_dest_for_block node if node.id
wrap_ext = source_chunks = bg_color_override = font_color_override = adjusted_font_size = nil
theme_font :code do
# HACK: disable built-in syntax highlighter; must be done before calling node.content!
if node.style == 'source' && (highlighter = (syntax_hl = node.document.syntax_highlighter) && syntax_hl.highlight? && syntax_hl.name)
case highlighter
when 'coderay'
unless defined? ::Asciidoctor::Prawn::CodeRayEncoder
highlighter = nil if (Helpers.require_library CodeRayRequirePath, 'coderay', :warn).nil?
end
when 'pygments'
unless defined? ::Pygments::Ext::BlockStyles
highlighter = nil if (Helpers.require_library PygmentsRequirePath, 'pygments.rb', :warn).nil?
end
when 'rouge'
unless defined? ::Rouge::Formatters::Prawn
highlighter = nil if (Helpers.require_library RougeRequirePath, 'rouge', :warn).nil?
end
else
highlighter = nil
end
prev_subs = (subs = node.subs).dup
callouts_enabled = subs.include? :callouts
# NOTE: the highlight sub is only set for coderay, rouge, and pygments atm
highlight_idx = subs.index :highlight
# NOTE: scratch? here only applies if listing block is nested inside another block
if !highlighter || scratch?
highlighter = nil
if highlight_idx
# switch the :highlight sub back to :specialcharacters
subs[highlight_idx] = :specialcharacters
else
prev_subs = nil
end
source_string = guard_indentation node.content
elsif highlight_idx
# NOTE: the source highlighter logic below handles the highlight and callouts subs
subs.replace subs - [:highlight, :callouts]
# NOTE: indentation guards will be added by the source highlighter logic
source_string = expand_tabs node.content
else
highlighter = prev_subs = nil
source_string = guard_indentation node.content
end
else
highlighter = nil
source_string = guard_indentation node.content
end
case highlighter
when 'coderay'
source_string, conum_mapping = extract_conums source_string if callouts_enabled
srclang = node.attr 'language', 'text'
begin
::CodeRay::Scanners[(srclang = (srclang.start_with? 'html+') ? (srclang.slice 5, srclang.length).to_sym : srclang.to_sym)]
rescue ::ArgumentError
srclang = :text
end
fragments = (::CodeRay.scan source_string, srclang).to_prawn
source_chunks = conum_mapping ? (restore_conums fragments, conum_mapping) : fragments
when 'pygments'
style = (node.document.attr 'pygments-style') || 'pastie'
# QUESTION allow border color to be set by theme for highlighted block?
pg_block_styles = ::Pygments::Ext::BlockStyles.for style
bg_color_override = pg_block_styles[:background_color]
font_color_override = pg_block_styles[:font_color]
if source_string.empty?
source_chunks = []
else
lexer = (::Pygments::Lexer.find_by_alias node.attr 'language', 'text') || (::Pygments::Lexer.find_by_mimetype 'text/plain')
lexer_opts = { nowrap: true, noclasses: true, stripnl: false, style: style }
lexer_opts[:startinline] = !(node.option? 'mixed') if lexer.name == 'PHP'
source_string, conum_mapping = extract_conums source_string if callouts_enabled
# NOTE: highlight can return nil if something goes wrong; fallback to encoded source string if this happens
result = (lexer.highlight source_string, options: lexer_opts) || (node.apply_subs source_string, [:specialcharacters])
if node.attr? 'highlight'
if (highlight_lines = node.resolve_lines_to_highlight source_string, (node.attr 'highlight')).empty?
highlight_lines = nil
else
pg_highlight_bg_color = pg_block_styles[:highlight_background_color]
highlight_lines = highlight_lines.map {|linenum| [linenum, pg_highlight_bg_color] }.to_h
end
end
if node.attr? 'linenums'
linenums = (node.attr 'start', 1).to_i
@theme.code_linenum_font_color ||= '999999'
postprocess = true
wrap_ext = FormattedText::SourceWrap
elsif conum_mapping || highlight_lines
postprocess = true
end
fragments = text_formatter.format result
fragments = restore_conums fragments, conum_mapping, linenums, highlight_lines if postprocess
source_chunks = guard_indentation_in_fragments fragments
end
when 'rouge'
formatter = (@rouge_formatter ||= ::Rouge::Formatters::Prawn.new theme: (node.document.attr 'rouge-style'), line_gap: @theme.code_line_gap, highlight_background_color: @theme.code_highlight_background_color)
# QUESTION allow border color to be set by theme for highlighted block?
bg_color_override = formatter.background_color
if source_string.empty?
source_chunks = []
else
if node.attr? 'linenums'
formatter_opts = { line_numbers: true, start_line: (node.attr 'start', 1).to_i }
wrap_ext = FormattedText::SourceWrap
else
formatter_opts = {}
end
if (srclang = node.attr 'language')
if srclang.include? '?'
if (lexer = ::Rouge::Lexer.find_fancy srclang)
unless lexer.tag != 'php' || (node.option? 'mixed') || ((lexer_opts = lexer.options).key? 'start_inline')
lexer = lexer.class.new lexer_opts.merge 'start_inline' => true
end
end
elsif (lexer = ::Rouge::Lexer.find srclang)
lexer = lexer.new start_inline: true if lexer.tag == 'php' && !(node.option? 'mixed')
end
end
lexer ||= ::Rouge::Lexers::PlainText
source_string, conum_mapping = extract_conums source_string if callouts_enabled
if node.attr? 'highlight'
unless (hl_lines = (node.resolve_lines_to_highlight source_string, (node.attr 'highlight'))).empty?
formatter_opts[:highlight_lines] = hl_lines.map {|linenum| [linenum, true] }.to_h
end
end
fragments = formatter.format (lexer.lex source_string), formatter_opts
source_chunks = conum_mapping ? (restore_conums fragments, conum_mapping) : fragments
end
else
# NOTE: only format if we detect a need (callouts or inline formatting)
source_chunks = (XMLMarkupRx.match? source_string) ? (text_formatter.format source_string) : [text: source_string]
end
node.subs.replace prev_subs if prev_subs
adjusted_font_size = ((node.option? 'autofit') || (node.document.attr? 'autofit-option')) ? (compute_autofit_font_size source_chunks, :code) : nil
end
theme_margin :block, :top
keep_together do |box_height = nil|
caption_height = node.title? ? (layout_caption node, category: :code) : 0
theme_font :code do
theme_fill_and_stroke_block :code, (box_height - caption_height), background_color: bg_color_override, split_from_top: false if box_height
pad_box @theme.code_padding do
::Prawn::Text::Formatted::Box.extensions << wrap_ext if wrap_ext
typeset_formatted_text source_chunks, (calc_line_metrics @theme.code_line_height || @theme.base_line_height),
color: (font_color_override || @theme.code_font_color || @font_color),
size: adjusted_font_size
::Prawn::Text::Formatted::Box.extensions.pop if wrap_ext
end
end
end
theme_margin :block, :bottom
end
alias convert_listing convert_listing_or_literal
alias convert_literal convert_listing_or_literal
def convert_pass node
node = node.dup
(subs = node.subs.dup).unshift :specialcharacters
node.instance_variable_set :@subs, subs.uniq
convert_listing_or_literal node
end
alias convert_stem convert_listing_or_literal
# Extract callout marks from string, indexed by 0-based line number
# Return an Array with the processed string as the first argument
# and the mapping of lines to conums as the second.
def extract_conums string
conum_mapping = {}
auto_num = 0
string = string.split(LF).map.with_index {|line, line_num|
# FIXME: we get extra spaces before numbers if more than one on a line
if line.include? '<'
line = line.gsub CalloutExtractRx do
# honor the escape
if $1 == ?\\
$&.sub $1, ''
else
(conum_mapping[line_num] ||= []) << ($3 == '.' ? (auto_num += 1) : $3.to_i)
''
end
end
# NOTE use first position to store space that precedes conums
if (conum_mapping.key? line_num) && (line.end_with? ' ')
trimmed_line = line.rstrip
conum_mapping[line_num].unshift line.slice trimmed_line.length, line.length
line = trimmed_line
end
end
line
}.join LF
conum_mapping = nil if conum_mapping.empty?
[string, conum_mapping]
end
# Restore the conums into the Array of formatted text fragments
#--
# QUESTION can this be done more efficiently?
# QUESTION can we reuse arrange_fragments_by_line?
def restore_conums fragments, conum_mapping, linenums = nil, highlight_lines = nil
lines = []
line_num = 0
# reorganize the fragments into an array of lines
fragments.each do |fragment|
line = (lines[line_num] ||= [])
if (text = fragment[:text]) == LF
lines[line_num += 1] ||= []
elsif text.include? LF
text.split(LF, -1).each_with_index do |line_in_fragment, idx|
line = (lines[line_num += 1] ||= []) unless idx == 0
line << (fragment.merge text: line_in_fragment) unless line_in_fragment.empty?
end
else
line << fragment
end
end
conum_font_color = @theme.conum_font_color
if (conum_font_name = @theme.conum_font_family) == font_name
conum_font_name = nil
end
last_line_num = lines.size - 1
if linenums
pad_size = (last_line_num + 1).to_s.length
linenum_color = @theme.code_linenum_font_color
end
# append conums to appropriate lines, then flatten to an array of fragments
lines.flat_map.with_index do |line, cur_line_num|
last_line = cur_line_num == last_line_num
visible_line_num = cur_line_num + (linenums || 1)
if highlight_lines && (highlight_bg_color = highlight_lines[visible_line_num])
line.unshift text: DummyText, background_color: highlight_bg_color, highlight: true, inline_block: true, extend: true, width: 0, callback: [FormattedText::TextBackgroundAndBorderRenderer]
end
line.unshift text: %(#{visible_line_num.to_s.rjust pad_size} ), linenum: visible_line_num, color: linenum_color if linenums
if conum_mapping && (conums = conum_mapping.delete cur_line_num)
line << { text: conums.shift } if ::String === conums[0]
conum_text = conums.map {|num| conum_glyph num }.join ' '
conum_fragment = { text: conum_text }
conum_fragment[:color] = conum_font_color if conum_font_color
conum_fragment[:font] = conum_font_name if conum_font_name
line << conum_fragment
end
line << { text: LF } unless last_line
line
end
end
def conum_glyph number
@conum_glyphs[number - 1]
end
def convert_table node
add_dest_for_block node if node.id
# TODO: we could skip a lot of the logic below when num_rows == 0
num_rows = node.attr 'rowcount'
num_cols = node.columns.size
table_header_size = false
theme = @theme
tbl_bg_color = resolve_theme_color :table_background_color
# QUESTION should we fallback to page background color? (which is never transparent)
#tbl_bg_color = resolve_theme_color :table_background_color, @page_bg_color
# ...and if so, should we try to be helpful and use @page_bg_color for tables nested in blocks?
#unless tbl_bg_color
# tbl_bg_color = @page_bg_color unless [:section, :document].include? node.parent.context
#end
# NOTE: emulate table bg color by using it as a fallback value for each element
head_bg_color = resolve_theme_color :table_head_background_color, tbl_bg_color
foot_bg_color = resolve_theme_color :table_foot_background_color, tbl_bg_color
body_bg_color = resolve_theme_color :table_body_background_color, tbl_bg_color
body_stripe_bg_color = resolve_theme_color :table_body_stripe_background_color, tbl_bg_color
base_header_cell_data = nil
header_cell_line_metrics = nil
table_data = []
theme_font :table do
head_rows = node.rows[:head]
body_rows = node.rows[:body]
#if (hrows = node.attr 'hrows') && (shift_rows = hrows.to_i - head_rows.size) > 0
# head_rows = head_rows.dup
# body_rows = body_rows.dup
# shift_rows.times { head_rows << body_rows.shift unless body_rows.empty? }
#end
theme_font :table_head do
table_header_size = head_rows.size
head_font_info = font_info
head_line_metrics = calc_line_metrics theme.base_line_height
head_cell_padding = theme.table_head_cell_padding || theme.table_cell_padding
head_cell_padding = ::Array === head_cell_padding && head_cell_padding.size == 4 ? head_cell_padding.dup : (expand_padding_value head_cell_padding)
head_cell_padding[0] += head_line_metrics.padding_top
head_cell_padding[2] += head_line_metrics.padding_bottom
# QUESTION why doesn't text transform inherit from table?
head_transform = resolve_text_transform :table_head_text_transform, nil
base_cell_data = {
inline_format: [normalize: true],
background_color: head_bg_color,
text_color: @font_color,
size: head_font_info[:size],
font: head_font_info[:family],
font_style: head_font_info[:style],
kerning: default_kerning?,
padding: head_cell_padding,
leading: head_line_metrics.leading,
# TODO: patch prawn-table to pass through final_gap option
#final_gap: head_line_metrics.final_gap,
}
head_rows.each do |row|
table_data << (row.map do |cell|
cell_text = head_transform ? (transform_text cell.text.strip, head_transform) : cell.text.strip
cell_text = hyphenate_text cell_text, @hyphenator if defined? @hyphenator
base_cell_data.merge \
content: cell_text,
colspan: cell.colspan || 1,
align: (cell.attr 'halign').to_sym,
valign: (val = cell.attr 'valign') == 'middle' ? :center : val.to_sym
end)
end
end unless head_rows.empty?
base_cell_data = {
font: (body_font_info = font_info)[:family],
font_style: body_font_info[:style],
size: body_font_info[:size],
kerning: default_kerning?,
text_color: @font_color,
}
body_cell_line_metrics = calc_line_metrics theme.base_line_height
(body_rows + node.rows[:foot]).each do |row|
table_data << (row.map do |cell|
cell_data = base_cell_data.merge \
colspan: cell.colspan || 1,
rowspan: cell.rowspan || 1,
align: (cell.attr 'halign').to_sym,
valign: (val = cell.attr 'valign') == 'middle' ? :center : val.to_sym
cell_line_metrics = body_cell_line_metrics
case cell.style
when :emphasis
cell_data[:font_style] = :italic
when :strong
cell_data[:font_style] = :bold
when :header
unless base_header_cell_data
theme_font :table_head do
theme_font :table_header_cell do
header_cell_font_info = font_info
base_header_cell_data = {
text_color: @font_color,
font: header_cell_font_info[:family],
size: header_cell_font_info[:size],
font_style: header_cell_font_info[:style],
text_transform: @text_transform,
}
header_cell_line_metrics = calc_line_metrics theme.base_line_height
end
end
if (val = resolve_theme_color :table_header_cell_background_color, head_bg_color)
base_header_cell_data[:background_color] = val
end
end
cell_data.update base_header_cell_data
cell_transform = cell_data.delete :text_transform
cell_line_metrics = header_cell_line_metrics
when :monospaced
cell_data.delete :font_style
theme_font :literal do
mono_cell_font_info = font_info
cell_data[:font] = mono_cell_font_info[:family]
cell_data[:size] = mono_cell_font_info[:size]
cell_data[:text_color] = @font_color
cell_line_metrics = calc_line_metrics theme.base_line_height
end
when :literal
# NOTE: we want the raw AsciiDoc in this case
cell_data[:content] = guard_indentation cell.instance_variable_get :@text
# NOTE: the absence of the inline_format option implies it's disabled
cell_data.delete :font_style
# QUESTION should we use literal_font_*, code_font_*, or introduce another category?
theme_font :code do
literal_cell_font_info = font_info
cell_data[:font] = literal_cell_font_info[:family]
cell_data[:size] = literal_cell_font_info[:size] * (cell_data[:size].to_f / @root_font_size)
cell_data[:text_color] = @font_color
cell_line_metrics = calc_line_metrics theme.base_line_height
end
when :asciidoc
cell_data.delete :kerning
if theme.table_asciidoc_cell_style == 'initial'
cell_data.delete :font
cell_data.delete :font_style
cell_data.delete :size
cell_data.delete :text_color
end
cell_line_metrics = nil
asciidoc_cell = ::Prawn::Table::Cell::AsciiDoc.new self, (cell_data.merge content: cell.inner_document, padding: theme.table_cell_padding)
cell_data = { content: asciidoc_cell }
end
if cell_line_metrics
cell_padding = ::Array === (cell_padding = theme.table_cell_padding) && cell_padding.size == 4 ? cell_padding.dup : (expand_padding_value cell_padding)
cell_padding[0] += cell_line_metrics.padding_top
cell_padding[2] += cell_line_metrics.padding_bottom
cell_data[:leading] = cell_line_metrics.leading
# TODO: patch prawn-table to pass through final_gap option
#cell_data[:final_gap] = cell_line_metrics.final_gap
cell_data[:padding] = cell_padding
end
unless cell_data.key? :content
cell_text = cell.text.strip
cell_text = transform_text cell_text, cell_transform if cell_transform
cell_text = hyphenate_text cell_text, @hyphenator if defined? @hyphenator
cell_text = cell_text.gsub CjkLineBreakRx, ZeroWidthSpace if @cjk_line_breaks
if cell_text.include? DoubleLF
# FIXME: hard breaks not quite the same result as separate paragraphs; need custom cell impl here
cell_data[:content] = (cell_text.split BlankLineRx).map {|l| l.tr_s WhitespaceChars, ' ' }.join DoubleLF
cell_data[:inline_format] = true
else
cell_data[:content] = cell_text
cell_data[:inline_format] = [normalize: true]
end
end
if node.document.attr? 'cellbgcolor'
if (cell_bg_color = node.document.attr 'cellbgcolor') == 'transparent'
cell_data[:background_color] = body_bg_color
elsif (cell_bg_color.start_with? '#') && (HexColorRx.match? cell_bg_color)
cell_data[:background_color] = cell_bg_color.slice 1, cell_bg_color.length
end
end
cell_data
end)
end
end
# NOTE: Prawn aborts if table data is empty, so ensure there's at least one row
if table_data.empty?
logger.warn message_with_context 'no rows found in table', source_location: node.source_location unless scratch?
table_data << ::Array.new([node.columns.size, 1].max) { { content: '' } }
end
border_width = {}
table_border_color = theme.table_border_color || theme.table_grid_color || theme.base_border_color
table_border_style = (theme.table_border_style || :solid).to_sym
table_border_width = theme.table_border_width
if table_header_size
head_border_bottom_color = theme.table_head_border_bottom_color || table_border_color
head_border_bottom_style = (theme.table_head_border_bottom_style || table_border_style).to_sym
head_border_bottom_width = theme.table_head_border_bottom_width || table_border_width
end
[:top, :bottom, :left, :right].each {|edge| border_width[edge] = table_border_width }
table_grid_color = theme.table_grid_color || table_border_color
table_grid_style = (theme.table_grid_style || table_border_style).to_sym
table_grid_width = theme.table_grid_width || theme.table_border_width
[:cols, :rows].each {|edge| border_width[edge] = table_grid_width }
case (grid = node.attr 'grid', 'all', 'table-grid')
when 'all'
# keep inner borders
when 'cols'
border_width[:rows] = 0
when 'rows'
border_width[:cols] = 0
else # none
border_width[:rows] = border_width[:cols] = 0
end
case (frame = node.attr 'frame', 'all', 'table-frame')
when 'all'
# keep outer borders
when 'topbot', 'ends'
border_width[:left] = border_width[:right] = 0
when 'sides'
border_width[:top] = border_width[:bottom] = 0
else # none
border_width[:top] = border_width[:right] = border_width[:bottom] = border_width[:left] = 0
end
if node.option? 'autowidth'
table_width = (node.attr? 'width') ? bounds.width * ((node.attr 'tablepcwidth') / 100.0) :
(((node.has_role? 'stretch') || (node.has_role? 'spread')) ? bounds.width : nil)
column_widths = []
else
table_width = bounds.width * ((node.attr 'tablepcwidth') / 100.0)
column_widths = node.columns.map {|col| ((col.attr 'colpcwidth') * table_width) / 100.0 }
end
if ((alignment = node.attr 'align') && (BlockAlignmentNames.include? alignment)) ||
(alignment = (node.roles & BlockAlignmentNames)[-1])
alignment = alignment.to_sym
else
alignment = (theme.table_align || :left).to_sym
end
caption_side = (theme.table_caption_side || :top).to_sym
caption_max_width = theme.table_caption_max_width || 'fit-content'
table_settings = {
header: table_header_size,
# NOTE: position is handled by this method
position: :left,
cell_style: {
# NOTE: the border color and style of the outer frame is set later
border_color: table_grid_color,
border_lines: [table_grid_style],
# NOTE: the border width is set later
border_width: 0,
},
width: table_width,
column_widths: column_widths,
}
# QUESTION should we support nth; should we support sequence of roles?
case node.attr 'stripes', nil, 'table-stripes'
when 'all'
table_settings[:row_colors] = [body_stripe_bg_color]
when 'even'
table_settings[:row_colors] = [body_bg_color, body_stripe_bg_color]
when 'odd'
table_settings[:row_colors] = [body_stripe_bg_color, body_bg_color]
else # none
table_settings[:row_colors] = [body_bg_color]
end
theme_margin :block, :top
left_padding = right_padding = nil
table table_data, table_settings do
# NOTE: call width to capture resolved table width
table_width = width
@pdf.layout_table_caption node, alignment, table_width, caption_max_width if node.title? && caption_side == :top
# NOTE align using padding instead of bounding_box as prawn-table does
# using a bounding_box across pages mangles the margin box of subsequent pages
if alignment != :left && table_width != (this_bounds = @pdf.bounds).width
if alignment == :center
left_padding = right_padding = (this_bounds.width - width) * 0.5
this_bounds.add_left_padding left_padding
this_bounds.add_right_padding right_padding
else # :right
left_padding = this_bounds.width - width
this_bounds.add_left_padding left_padding
end
end
if grid == 'none' && frame == 'none'
rows(table_header_size - 1).tap do |r|
r.border_bottom_color = head_border_bottom_color
r.border_bottom_line = head_border_bottom_style
r.border_bottom_width = head_border_bottom_width
end if table_header_size
else
# apply the grid setting first across all cells
cells.border_width = [border_width[:rows], border_width[:cols], border_width[:rows], border_width[:cols]]
if table_header_size
rows(table_header_size - 1).tap do |r|
r.border_bottom_color = head_border_bottom_color
r.border_bottom_line = head_border_bottom_style
r.border_bottom_width = head_border_bottom_width
end
rows(table_header_size).tap do |r|
r.border_top_color = head_border_bottom_color
r.border_top_line = head_border_bottom_style
r.border_top_width = head_border_bottom_width
end if num_rows > table_header_size
end
# top edge of table
rows(0).tap do |r|
r.border_top_color, r.border_top_line, r.border_top_width = table_border_color, table_border_style, border_width[:top]
end
# right edge of table
columns(num_cols - 1).tap do |r|
r.border_right_color, r.border_right_line, r.border_right_width = table_border_color, table_border_style, border_width[:right]
end
# bottom edge of table
rows(num_rows - 1).tap do |r|
r.border_bottom_color, r.border_bottom_line, r.border_bottom_width = table_border_color, table_border_style, border_width[:bottom]
end
# left edge of table
columns(0).tap do |r|
r.border_left_color, r.border_left_line, r.border_left_width = table_border_color, table_border_style, border_width[:left]
end
end
# QUESTION should cell padding be configurable for foot row cells?
unless node.rows[:foot].empty?
foot_row = row num_rows.pred
foot_row.background_color = foot_bg_color
# FIXME: find a way to do this when defining the cells
foot_row.text_color = theme.table_foot_font_color if theme.table_foot_font_color
foot_row.size = theme.table_foot_font_size if theme.table_foot_font_size
foot_row.font = theme.table_foot_font_family if theme.table_foot_font_family
foot_row.font_style = theme.table_foot_font_style.to_sym if theme.table_foot_font_style
# HACK: we should do this transformation when creating the cell
#if (foot_transform = resolve_text_transform :table_foot_text_transform, nil)
# foot_row.each {|c| c.content = (transform_text c.content, foot_transform) if c.content }
#end
end
end
if left_padding
bounds.subtract_left_padding left_padding
bounds.subtract_right_padding right_padding if right_padding
end
layout_table_caption node, alignment, table_width, caption_max_width, caption_side if node.title? && caption_side == :bottom
theme_margin :block, :bottom
end
def convert_thematic_break _node
theme_margin :thematic_break, :top
stroke_horizontal_rule @theme.thematic_break_border_color, line_width: @theme.thematic_break_border_width, line_style: (@theme.thematic_break_border_style || :solid).to_sym
theme_margin :thematic_break, :bottom
end
def convert_toc node
if ((doc = node.document).attr? 'toc-placement', 'macro') && doc.sections?
if (is_book = doc.doctype == 'book')
start_new_page unless at_page_top?
start_new_page if @ppbook && verso_page? && !(node.option? 'nonfacing')
end
add_dest_for_block node, (node.id || 'toc')
allocate_toc doc, (doc.attr 'toclevels', 2).to_i, @y, (is_book || (doc.attr? 'title-page'))
@disable_running_content[:header] = (@disable_running_content[:header] || ::Set.new) + @toc_extent[:page_nums] if node.option? 'noheader'
@disable_running_content[:footer] = (@disable_running_content[:footer] || ::Set.new) + @toc_extent[:page_nums] if node.option? 'nofooter'
end
nil
end
# NOTE to insert sequential page breaks, you must put {nbsp} between page breaks
def convert_page_break node
if (page_layout = node.attr 'page-layout').nil_or_empty?
unless node.role? && (page_layout = (node.roles.map(&:to_sym) & PageLayouts)[-1])
page_layout = nil
end
elsif !PageLayouts.include?(page_layout = page_layout.to_sym)
page_layout = nil
end
if at_page_top?
if page_layout && page_layout != page.layout && page.empty?
delete_page
advance_page layout: page_layout
end
elsif page_layout
advance_page layout: page_layout
else
advance_page
end
end
def convert_index_section _node
space_needed_for_category = @theme.description_list_term_spacing + (2 * (height_of_typeset_text 'A'))
column_box [0, cursor], columns: (@theme.index_columns || 2), width: bounds.width, reflow_margins: true do
@index.categories.each do |category|
# NOTE cursor method always returns 0 inside column_box; breaks reference_bounds.move_past_bottom
bounds.move_past_bottom if space_needed_for_category > y - reference_bounds.absolute_bottom
layout_prose category.name,
align: :left,
inline_format: false,
margin_top: 0,
margin_bottom: @theme.description_list_term_spacing,
style: @theme.description_list_term_font_style.to_sym
category.terms.each do |term|
convert_index_list_item term
end
if @theme.prose_margin_bottom > y - reference_bounds.absolute_bottom
bounds.move_past_bottom
else
move_down @theme.prose_margin_bottom
end
end
end
nil
end
def convert_index_list_item term
text = escape_xml term.name
unless term.container?
if @media == 'screen'
pagenums = term.dests.map {|dest| %(<a anchor="#{dest[:anchor]}">#{dest[:page]}</a>) }
else
pagenums = consolidate_ranges term.dests.uniq {|dest| dest[:page] }.map {|dest| dest[:page] }
end
text = %(#{text}, #{pagenums.join ', '})
end
subterm_indent = @theme.description_list_description_indent
layout_prose text, align: :left, margin: 0, hanging_indent: subterm_indent * 2
indent subterm_indent do
term.subterms.each do |subterm|
convert_index_list_item subterm
end
end unless term.leaf?
end
def convert_inline_anchor node
doc = node.document
target = node.target
case node.type
when :link
anchor = node.id ? %(<a id="#{node.id}">#{DummyText}</a>) : ''
attrs = []
if (role = node.role)
attrs << %( class="#{role}")
end
if (@media ||= doc.attr 'media', 'screen') != 'screen' && (target.start_with? 'mailto:') && (doc.attr? 'hide-uri-scheme')
bare_target = target.slice 7, target.length
node.add_role 'bare' if (text = node.text) == bare_target
else
bare_target = target
text = node.text
end
if (role = node.attr 'role') && (role == 'bare' || ((role.split ' ').include? 'bare'))
# QUESTION should we insert breakable chars into URI when building fragment instead?
%(#{anchor}<a href="#{target}"#{attrs.join}>#{breakable_uri text}</a>)
# NOTE @media may not be initialized if method is called before convert phase
elsif @media != 'screen' || (doc.attr? 'show-link-uri')
# QUESTION should we insert breakable chars into URI when building fragment instead?
# TODO: allow style of printed link to be controlled by theme
%(#{anchor}<a href="#{target}"#{attrs.join}>#{text}</a> [<font size="0.85em">#{breakable_uri bare_target}</font>])
else
%(#{anchor}<a href="#{target}"#{attrs.join}>#{text}</a>)
end
when :xref
# NOTE non-nil path indicates this is an inter-document xref that's not included in current document
if (path = node.attributes['path'])
# NOTE we don't use local as that doesn't work on the web
%(<a href="#{target}">#{node.text || path}</a>)
elsif (refid = node.attributes['refid'])
unless (text = node.text)
refs = doc.catalog[:refs]
if ::Asciidoctor::AbstractNode === (ref = refs[refid])
text = ref.xreftext node.attr 'xrefstyle', nil, true
end
end
%(<a anchor="#{derive_anchor_from_id refid}">#{text || "[#{refid}]"}</a>).gsub ']', ']'
else
%(<a anchor="#{doc.attr 'pdf-anchor'}">#{node.text || '[^top]'}</a>)
end
when :ref
# NOTE destination is created inside callback registered by FormattedTextTransform#build_fragment
%(<a id="#{node.id}">#{DummyText}</a>)
when :bibref
# NOTE destination is created inside callback registered by FormattedTextTransform#build_fragment
# NOTE technically node.text should be node.reftext, but subs have already been applied to text
reftext = (reftext = node.reftext) ? %([#{reftext}]) : %([#{node.id}])
%(<a id="#{node.id}">#{DummyText}</a>#{reftext})
else
logger.warn %(unknown anchor type: #{node.type.inspect}) unless scratch?
end
end
def convert_inline_break node
%(#{node.text}<br>)
end
def convert_inline_button node
%(<button>#{((load_theme node.document).button_content || '%s').sub '%s', node.text}</button>)
end
def convert_inline_callout node
if (conum_font_family = @theme.conum_font_family) != font_name
result = %(<font name="#{conum_font_family}">#{conum_glyph node.text.to_i}</font>)
else
result = conum_glyph node.text.to_i
end
if (conum_font_color = @theme.conum_font_color)
# NOTE CMYK value gets flattened here, but is restored by formatted text parser
result = %(<color rgb="#{conum_font_color}">#{result}</font>)
end
result
end
def convert_inline_footnote node
if (index = node.attr 'index') && (fn = node.document.footnotes.find {|candidate| candidate.index == index })
anchor = node.type == :xref ? '' : %(<a id="_footnoteref_#{index}">#{DummyText}</a>)
if defined? @rendered_footnotes
label = (@rendered_footnotes.include? fn) ? fn.label : (index - @rendered_footnotes.length)
else
label = index
end
%(#{anchor}<sup>[<a anchor="_footnotedef_#{index}">#{label}</a>]</sup>)
elsif node.type == :xref
# NOTE footnote reference not found
%(<sup><color rgb="FF0000">[#{node.text}]</color></sup>)
end
end
def convert_inline_icon node
if node.document.attr? 'icons', 'font'
if (icon_name = node.target).include? '@'
icon_name, icon_set = icon_name.split '@', 2
explicit_icon_set = true
elsif (icon_set = node.attr 'set')
explicit_icon_set = true
else
icon_set = node.document.attr 'icon-set', 'fa'
end
if icon_set == 'fa' || !(IconSets.include? icon_set)
icon_set = 'fa'
# legacy name from Font Awesome < 5
if (remapped_icon_name = resolve_legacy_icon_name icon_name)
requested_icon_name = icon_name
icon_set, icon_name = remapped_icon_name.split '-', 2
glyph = (icon_font_data icon_set).unicode icon_name
logger.info { %(#{requested_icon_name} icon found in deprecated fa icon set; using #{icon_name} from #{icon_set} icon set instead) } unless scratch?
# new name in Font Awesome >= 5 (but document is configured to use fa icon set)
else
font_data = nil
if (resolved_icon_set = FontAwesomeIconSets.find {|candidate| (font_data = icon_font_data candidate).unicode icon_name rescue nil })
icon_set = resolved_icon_set
glyph = font_data.unicode icon_name
logger.info { %(#{icon_name} icon not found in deprecated fa icon set; using match found in #{resolved_icon_set} icon set instead) } unless scratch?
end
end
else
glyph = (icon_font_data icon_set).unicode icon_name rescue nil
end
unless glyph || explicit_icon_set || !icon_name.start_with?(*IconSetPrefixes)
icon_set, icon_name = icon_name.split '-', 2
glyph = (icon_font_data icon_set).unicode icon_name rescue nil
end
if glyph
if node.attr? 'size'
case (size = node.attr 'size')
when 'lg'
size_attr = ' size="1.333em"'
when 'fw'
size_attr = ' width="1em"'
else
size_attr = %( size="#{size.sub 'x', 'em'}")
end
else
size_attr = ''
end
class_attr = node.role? ? %( class="#{node.role}") : ''
# TODO: support rotate and flip attributes
%(<font name="#{icon_set}"#{size_attr}#{class_attr}>#{glyph}</font>)
else
logger.warn %(#{icon_name} is not a valid icon name in the #{icon_set} icon set) unless scratch?
%([#{node.attr 'alt'}])
end
else
%([#{node.attr 'alt'}])
end
end
def convert_inline_image node
if node.type == 'icon'
convert_inline_icon node
else
node.extend ::Asciidoctor::Image unless ::Asciidoctor::Image === node
target, image_format = node.target_and_format
if image_format == 'gif' && !(defined? ::GMagick::Image)
logger.warn %(GIF image format not supported. Install the prawn-gmagick gem or convert #{target} to PNG.) unless scratch?
img = %([#{node.attr 'alt'}])
# NOTE an image with a data URI is handled using a temporary file
elsif (image_path = resolve_image_path node, target, image_format, true)
if ::File.readable? image_path
width_attr = (width = resolve_explicit_width node.attributes) ? %( width="#{width}") : ''
fit_attr = (fit = node.attr 'fit') ? %( fit="#{fit}") : ''
img = %(<img src="#{image_path}" format="#{image_format}" alt="[#{encode_quotes node.attr 'alt'}]"#{width_attr}#{fit_attr}>)
else
logger.warn %(image to embed not found or not readable: #{image_path}) unless scratch?
img = %([#{node.attr 'alt'}])
end
else
img = %([#{node.attr 'alt'}])
end
(node.attr? 'link') ? %(<a href="#{node.attr 'link'}">#{img}</a>) : img
end
end
def convert_inline_indexterm node
if scratch?
node.type == :visible ? node.text : ''
else
# NOTE initialize index in case converter is called before PDF is initialized
@index ||= IndexCatalog.new
# NOTE page number (:page key) is added by InlineDestinationMarker
dest = { anchor: (anchor_name = @index.next_anchor_name) }
anchor = %(<a id="#{anchor_name}" type="indexterm">#{DummyText}</a>)
if node.type == :visible
visible_term = node.text
@index.store_primary_term (sanitize visible_term), dest
%(#{anchor}#{visible_term})
else
@index.store_term((node.attr 'terms').map {|term| sanitize term }, dest)
anchor
end
end
end
def convert_inline_kbd node
if (keys = node.attr 'keys').size == 1
%(<key>#{keys[0]}</key>)
else
keys.map {|key| %(<key>#{key}</key>) }.join (load_theme node.document).key_separator || '+'
end
end
def convert_inline_menu node
menu = node.attr 'menu'
caret = (load_theme node.document).menu_caret_content || %( \u203a )
if !(submenus = node.attr 'submenus').empty?
%(<strong>#{[menu, *submenus, (node.attr 'menuitem')].join caret}</strong>)
elsif (menuitem = node.attr 'menuitem')
%(<strong>#{menu}#{caret}#{menuitem}</strong>)
else
%(<strong>#{menu}</strong>)
end
end
def convert_inline_quoted node
case node.type
when :emphasis
open, close, is_tag = ['<em>', '</em>', true]
when :strong
open, close, is_tag = ['<strong>', '</strong>', true]
when :monospaced, :asciimath, :latexmath
open, close, is_tag = ['<code>', '</code>', true]
when :superscript
open, close, is_tag = ['<sup>', '</sup>', true]
when :subscript
open, close, is_tag = ['<sub>', '</sub>', true]
when :double
open, close, is_tag = ['“', '”', false]
when :single
open, close, is_tag = ['‘', '’', false]
when :mark
open, close, is_tag = ['<mark>', '</mark>', true]
else
open, close, is_tag = [nil, nil, false]
end
inner_text = node.text
if (role = node.role)
if (text_transform = (load_theme node.document)[%(role_#{role}_text_transform)])
inner_text = transform_text inner_text, text_transform
end
quoted_text = is_tag ? %(#{open.chop} class="#{role}">#{inner_text}#{close}) : %(<span class="#{role}">#{open}#{inner_text}#{close}</span>)
else
quoted_text = %(#{open}#{inner_text}#{close})
end
# NOTE destination is created inside callback registered by FormattedTextTransform#build_fragment
node.id ? %(<a id="#{node.id}">#{DummyText}</a>#{quoted_text}) : quoted_text
end
def layout_title_page doc
return unless doc.header? && !doc.notitle
# NOTE a new page may have already been started at this point, so decide what to do with it
if page.empty?
page.reset_content if (recycle = @ppbook ? recto_page? : true)
elsif @ppbook && page_number > 0 && recto_page?
start_new_page
end
side = recycle ? page_side : (page_side page_number + 1)
prev_bg_image = @page_bg_image[side]
prev_bg_color = @page_bg_color
if (bg_image = resolve_background_image doc, @theme, 'title-page-background-image')
@page_bg_image[side] = bg_image[0] && bg_image
end
if (bg_color = resolve_theme_color :title_page_background_color)
@page_bg_color = bg_color
end
recycle ? (init_page self) : start_new_page
@page_bg_image[side] = prev_bg_image if bg_image
@page_bg_color = prev_bg_color if bg_color
# IMPORTANT this is the first page created, so we need to set the base font
font @theme.base_font_family, size: @root_font_size
# QUESTION allow alignment per element on title page?
title_align = (@theme.title_page_align || @base_align).to_sym
# FIXME: disallow .pdf as image type
if @theme.title_page_logo_display != 'none' && (logo_image_path = (doc.attr 'title-logo-image') || (logo_image_from_theme = @theme.title_page_logo_image))
if (logo_image_path.include? ':') && logo_image_path =~ ImageAttributeValueRx
logo_image_attrs = (AttributeList.new $2).parse %w(alt width height)
if logo_image_from_theme
relative_to_imagesdir = false
logo_image_path = sub_attributes_discretely doc, $1
logo_image_path = ThemeLoader.resolve_theme_asset logo_image_path, @themesdir unless doc.is_uri? logo_image_path
else
relative_to_imagesdir = true
logo_image_path = $1
end
else
logo_image_attrs = {}
relative_to_imagesdir = false
if logo_image_from_theme
logo_image_path = sub_attributes_discretely doc, logo_image_path
logo_image_path = ThemeLoader.resolve_theme_asset logo_image_path, @themesdir unless doc.is_uri? logo_image_path
end
end
logo_image_attrs['target'] = logo_image_path
# NOTE at the very least, title_align will be a valid alignment value
logo_image_attrs['align'] = [(logo_image_attrs.delete 'align'), @theme.title_page_logo_align, title_align.to_s].find {|val| (BlockAlignmentNames.include? val) }
if (logo_image_top = logo_image_attrs['top'] || @theme.title_page_logo_top)
initial_y, @y = @y, (resolve_top logo_image_top)
end
# FIXME: add API to Asciidoctor for creating blocks like this (extract from extensions module?)
image_block = ::Asciidoctor::Block.new doc, :image, content_model: :empty, attributes: logo_image_attrs
# NOTE pinned option keeps image on same page
indent (@theme.title_page_logo_margin_left || 0), (@theme.title_page_logo_margin_right || 0) do
convert_image image_block, relative_to_imagesdir: relative_to_imagesdir, pinned: true
end
@y = initial_y if initial_y
end
# TODO: prevent content from spilling to next page
theme_font :title_page do
if (title_top = @theme.title_page_title_top)
@y = resolve_top title_top
end
unless @theme.title_page_title_display == 'none'
doctitle = doc.doctitle partition: true
move_down(@theme.title_page_title_margin_top || 0)
indent (@theme.title_page_title_margin_left || 0), (@theme.title_page_title_margin_right || 0) do
theme_font :title_page_title do
layout_prose doctitle.main,
align: title_align,
margin: 0,
line_height: @theme.title_page_title_line_height
end
end
move_down(@theme.title_page_title_margin_bottom || 0)
end
if @theme.title_page_subtitle_display != 'none' && (subtitle = (doctitle || (doc.doctitle partition: true)).subtitle)
move_down(@theme.title_page_subtitle_margin_top || 0)
indent (@theme.title_page_subtitle_margin_left || 0), (@theme.title_page_subtitle_margin_right || 0) do
theme_font :title_page_subtitle do
layout_prose subtitle,
align: title_align,
margin: 0,
line_height: @theme.title_page_subtitle_line_height
end
end
move_down(@theme.title_page_subtitle_margin_bottom || 0)
end
if @theme.title_page_authors_display != 'none' && (doc.attr? 'authors')
move_down(@theme.title_page_authors_margin_top || 0)
indent (@theme.title_page_authors_margin_left || 0), (@theme.title_page_authors_margin_right || 0) do
generic_authors_content = @theme.title_page_authors_content
authors_content = {
name_only: @theme.title_page_authors_content_name_only || generic_authors_content,
with_email: @theme.title_page_authors_content_with_email || generic_authors_content,
with_url: @theme.title_page_authors_content_with_url || generic_authors_content,
}
# TODO: provide an API in core to get authors as an array
authors = (1..(doc.attr 'authorcount', 1).to_i).map {|idx|
promote_author doc, idx do
author_content_key = (url = doc.attr 'url') ? ((url.start_with? 'mailto:') ? :with_email : :with_url) : :name_only
if (author_content = authors_content[author_content_key])
apply_subs_discretely doc, author_content, drop_lines_with_unresolved_attributes: true
else
doc.attr 'author'
end
end
}.join (@theme.title_page_authors_delimiter || ', ')
theme_font :title_page_authors do
layout_prose authors,
align: title_align,
margin: 0,
normalize: true
end
end
move_down(@theme.title_page_authors_margin_bottom || 0)
end
unless @theme.title_page_revision_display == 'none' || (revision_info = [(doc.attr? 'revnumber') ? %(#{doc.attr 'version-label'} #{doc.attr 'revnumber'}) : nil, (doc.attr 'revdate')].compact).empty?
move_down(@theme.title_page_revision_margin_top || 0)
revision_text = revision_info.join (@theme.title_page_revision_delimiter || ', ')
if (revremark = doc.attr 'revremark')
revision_text = %(#{revision_text}: #{revremark})
end
indent (@theme.title_page_revision_margin_left || 0), (@theme.title_page_revision_margin_right || 0) do
theme_font :title_page_revision do
layout_prose revision_text,
align: title_align,
margin: 0,
normalize: false
end
end
move_down(@theme.title_page_revision_margin_bottom || 0)
end
end
layout_prose DummyText, margin: 0, line_height: 1, normalize: false if page.empty?
end
def layout_cover_page doc, face
bg_image = resolve_background_image doc, @theme, %(#{face}-cover-image), theme_key: %(cover_#{face}_image).to_sym, symbolic_paths: ['', '~']
if bg_image && bg_image[0]
image_path, image_opts = bg_image
if image_path.empty?
go_to_page page_count if face == :back
start_new_page_discretely
# NOTE open graphics state to prevent page from being reused
open_graphics_state if face == :front
return
elsif image_path == '~'
@page_margin_by_side[:cover] = @page_margin_by_side[:recto] if @media == 'prepress'
return
end
go_to_page page_count if face == :back
if image_opts[:format] == 'pdf'
import_page image_path, (image_opts.merge advance: face != :back)
else
image_page image_path, (image_opts.merge canvas: true)
end
end
end
def stamp_foreground_image doc, has_front_cover
pages = state.pages
if (first_page = (has_front_cover ? (pages.slice 1, pages.size) : pages).find {|it| !it.imported_page? }) &&
(first_page_num = (pages.index first_page) + 1) &&
(fg_image = resolve_background_image doc, @theme, 'page-foreground-image') && fg_image[0]
go_to_page first_page_num
create_stamp 'foreground-image' do
canvas { image fg_image[0], ({ position: :center, vposition: :center }.merge fg_image[1]) }
end
stamp 'foreground-image'
(first_page_num.next..page_count).each do |num|
go_to_page num
stamp 'foreground-image' unless page.imported_page?
end
end
end
def start_new_chapter chapter
start_new_page unless at_page_top?
# TODO: must call update_colors before advancing to next page if start_new_page is called in layout_chapter_title
start_new_page if @ppbook && verso_page? && !(chapter.option? 'nonfacing')
end
alias start_new_part start_new_chapter
def layout_chapter_title _node, title, opts = {}
layout_heading title, (opts.merge outdent: true)
end
alias layout_part_title layout_chapter_title
# NOTE layout_heading doesn't set the theme font because it's used for various types of headings
# QUESTION why doesn't layout_heading accept a node?
def layout_heading string, opts = {}
hlevel = opts[:level]
unless (top_margin = (margin = (opts.delete :margin)) || (opts.delete :margin_top))
if at_page_top?
if hlevel && (top_margin = @theme[%(heading_h#{hlevel}_margin_page_top)] || @theme.heading_margin_page_top || 0) > 0
move_down top_margin
end
top_margin = 0
else
top_margin = (hlevel ? @theme[%(heading_h#{hlevel}_margin_top)] : nil) || @theme.heading_margin_top
end
end
bot_margin = margin || (opts.delete :margin_bottom) || (hlevel ? @theme[%(heading_h#{hlevel}_margin_bottom)] : nil) || @theme.heading_margin_bottom
if (transform = resolve_text_transform opts)
string = transform_text string, transform
end
outdent_section opts.delete :outdent do
margin_top top_margin
# QUESTION should we move inherited styles to typeset_text?
if (inherited = apply_text_decoration font_styles, :heading, hlevel).empty?
inline_format_opts = true
else
inline_format_opts = [{ inherited: inherited }]
end
typeset_text string, calc_line_metrics((opts.delete :line_height) || (hlevel ? @theme[%(heading_h#{hlevel}_line_height)] : nil) || @theme.heading_line_height || @theme.base_line_height), {
color: @font_color,
inline_format: inline_format_opts,
align: @base_align.to_sym,
}.merge(opts)
margin_bottom bot_margin
end
end
# NOTE inline_format is true by default
def layout_prose string, opts = {}
top_margin = (margin = (opts.delete :margin)) || (opts.delete :margin_top) || @theme.prose_margin_top
bot_margin = margin || (opts.delete :margin_bottom) || @theme.prose_margin_bottom
if (transform = resolve_text_transform opts)
string = transform_text string, transform
end
string = hyphenate_text string, @hyphenator if (opts.delete :hyphenate) && (defined? @hyphenator)
# NOTE used by extensions; ensures linked text gets formatted using the link styles
if (anchor = opts.delete :anchor)
string = %(<a anchor="#{anchor}">#{string}</a>)
end
margin_top top_margin
# NOTE normalize makes endlines soft (replaces "\n" with ' ')
inline_format_opts = { normalize: (opts.delete :normalize) != false }
if (styles = opts.delete :styles)
inline_format_opts[:inherited] = { styles: styles }
end
typeset_text string, calc_line_metrics((opts.delete :line_height) || @theme.base_line_height), {
color: @font_color,
inline_format: [inline_format_opts],
align: @base_align.to_sym,
}.merge(opts)
margin_bottom bot_margin
end
def generate_manname_section node
title = node.attr 'manname-title', 'Name'
if (next_section = node.sections[0]) && (next_section_title = next_section.title) == next_section_title.upcase
title = title.upcase
end
sect = Section.new node, 1
sect.sectname = 'section'
sect.id = node.attr 'manname-id'
sect.title = title
sect << (Block.new sect, :paragraph, source: %(#{node.attr 'manname'} - #{node.attr 'manpurpose'}), subs: :normal)
sect
end
# Render the caption and return the height of the rendered content
#
# The subject argument can either be a String or an AbstractNode. If
# subject is an AbstractNode, only call this method if the node has a
# title (i.e., subject.title? return true).
#--
# TODO: allow margin to be zeroed
def layout_caption subject, opts = {}
if opts.delete :dry_run
height = nil
dry_run do
move_down 0.001 # HACK: force top margin to be applied
height = layout_caption subject, opts
end
return height
end
mark = { cursor: cursor, page_number: page_number }
if ::Asciidoctor::AbstractBlock === subject
string = (opts.delete :labeled) == false ? subject.title : subject.captioned_title
else
string = subject.to_s
end
category_caption = (category = opts[:category]) ? %(#{category}_caption) : 'caption'
container_width = bounds.width
block_align = opts.delete :block_align
if (align = @theme[%(#{category_caption}_align)] || @theme.caption_align)
align = align == 'inherit' ? (block_align || @base_align) : align.to_sym
else
align = @base_align.to_sym
end
if (text_align = @theme[%(#{category_caption}_text_align)] || @theme.caption_text_align)
text_align = text_align == 'inherit' ? align : text_align.to_sym
else
text_align = align
end
indent_by = [0, 0]
block_width = opts.delete :block_width
if (max_width = opts.delete :max_width) && max_width != 'none'
if ::String === max_width
if max_width.start_with? 'fit-content'
if max_width.end_with? 't', '()'
max_width = block_width || container_width
else
max_width = (block_width || container_width) * (max_width.slice 12, max_width.length - 1).to_f / 100.0
end
elsif max_width.end_with? '%'
max_width = [max_width.to_f / 100 * bounds.width, bounds.width].min
block_align = align
else
max_width = [max_width.to_f, bounds.width].min
block_align = align
end
else
max_width = [max_width, bounds.width].min
block_align = align
end
if (remainder = container_width - max_width) > 0
case block_align
when :right
indent_by = [remainder, 0]
when :center
indent_by = [(side_margin = remainder * 0.5), side_margin]
else # :left, nil
indent_by = [0, remainder]
end
end
end
theme_font :caption do
theme_font category_caption do
caption_margin_outside = @theme[%(#{category_caption}_margin_outside)] || @theme.caption_margin_outside
caption_margin_inside = @theme[%(#{category_caption}_margin_inside)] || @theme.caption_margin_inside
if ((opts.delete :side) || :top) == :top
margin = { top: caption_margin_outside, bottom: caption_margin_inside }
else
margin = { top: caption_margin_inside, bottom: caption_margin_outside }
end
indent(*indent_by) do
layout_prose string, {
margin_top: margin[:top],
margin_bottom: margin[:bottom],
align: text_align,
normalize: false,
normalize_line_height: true,
hyphenate: true,
}.merge(opts)
end
end
end
# NOTE we assume we don't clear more than one page
if page_number > mark[:page_number]
mark[:cursor] + (bounds.top - cursor)
else
mark[:cursor] - cursor
end
end
# Render the caption for a table and return the height of the rendered content
def layout_table_caption node, table_alignment = :left, table_width = nil, max_width = nil, side = :top
layout_caption node, category: :table, side: side, block_align: table_alignment, block_width: table_width, max_width: max_width
end
def allocate_toc doc, toc_num_levels, toc_start_y, use_title_page
toc_page_nums = page_number
toc_end = nil
dry_run do
toc_page_nums = layout_toc doc, toc_num_levels, toc_page_nums, toc_start_y
move_down @theme.block_margin_bottom unless use_title_page
toc_end = @y
end
# NOTE reserve pages for the toc; leaves cursor on page after last page in toc
if use_title_page
toc_page_nums.each { start_new_page }
else
(toc_page_nums.size - 1).times { start_new_page }
@y = toc_end
end
@toc_extent = { page_nums: toc_page_nums, start_y: toc_start_y }
end
# NOTE num_front_matter_pages is not used during a dry run
def layout_toc doc, num_levels = 2, toc_page_number = 2, start_y = @y, num_front_matter_pages = 0
go_to_page toc_page_number unless (page_number == toc_page_number) || scratch?
start_page_number = page_number
@y = start_y
unless (toc_title = doc.attr 'toc-title').nil_or_empty?
theme_font :heading, level: 2 do
theme_font :toc_title do
toc_title_align = (@theme.toc_title_align || @theme.heading_h2_align || @theme.heading_align || @base_align).to_sym
layout_heading toc_title, align: toc_title_align, level: 2, outdent: true
end
end
end
# QUESTION should we skip this whole method if num_levels < 0?
unless num_levels < 0
dot_leader = theme_font :toc do
# TODO: we could simplify by using nested theme_font :toc_dot_leader
if (dot_leader_font_style = (@theme.toc_dot_leader_font_style || :normal).to_sym) != font_style
font_style dot_leader_font_style
end
{
font_color: @theme.toc_dot_leader_font_color || @font_color,
font_style: dot_leader_font_style,
levels: ((dot_leader_l = @theme.toc_dot_leader_levels) == 'none' ? ::Set.new :
(dot_leader_l && dot_leader_l != 'all' ? dot_leader_l.to_s.split.map(&:to_i).to_set : (0..num_levels).to_set)),
text: (dot_leader_text = @theme.toc_dot_leader_content || DotLeaderTextDefault),
width: dot_leader_text.empty? ? 0 : (rendered_width_of_string dot_leader_text),
# TODO: spacer gives a little bit of room between dots and page number
spacer: { text: NoBreakSpace, size: (spacer_font_size = @font_size * 0.25) },
spacer_width: (rendered_width_of_char NoBreakSpace, size: spacer_font_size),
}
end
line_metrics = calc_line_metrics @theme.toc_line_height
theme_margin :toc, :top
layout_toc_level doc.sections, num_levels, line_metrics, dot_leader, num_front_matter_pages
end
# NOTE range must be calculated relative to toc_page_number; absolute page number in scratch document is arbitrary
toc_page_numbers = (toc_page_number..(toc_page_number + (page_number - start_page_number)))
go_to_page page_count unless scratch?
toc_page_numbers
end
def layout_toc_level sections, num_levels, line_metrics, dot_leader, num_front_matter_pages = 0
# NOTE font options aren't always reliable, so store size separately
toc_font_info = theme_font :toc do
{ font: font, size: @font_size }
end
hanging_indent = @theme.toc_hanging_indent || 0
sections.each do |sect|
next if (num_levels_for_sect = (sect.attr 'toclevels', num_levels).to_i) < sect.level
theme_font :toc, level: (sect.level + 1) do
sect_title = @text_transform ? (transform_text sect.numbered_title, @text_transform) : sect.numbered_title
pgnum_label_placeholder_width = rendered_width_of_string '0' * @toc_max_pagenum_digits
# NOTE only write section title (excluding dots and page number) if this is a dry run
if scratch?
indent 0, pgnum_label_placeholder_width do
# FIXME: use layout_prose
# NOTE must wrap title in empty anchor element in case links are styled with different font family / size
typeset_text %(<a>#{sect_title}</a>), line_metrics, inline_format: true, hanging_indent: hanging_indent, normalize_line_height: true
end
else
physical_pgnum = sect.attr 'pdf-page-start'
virtual_pgnum = physical_pgnum - num_front_matter_pages
pgnum_label = (virtual_pgnum < 1 ? (RomanNumeral.new physical_pgnum, :lower) : virtual_pgnum).to_s
start_page_number = page_number
start_cursor = cursor
start_dots = nil
sect_title_inherited = (apply_text_decoration ::Set.new, :toc, sect.level.next).merge anchor: (sect_anchor = sect.attr 'pdf-anchor'), color: @font_color
# NOTE use text formatter to add anchor overlay to avoid using inline format with synthetic anchor tag
sect_title_fragments = text_formatter.format sect_title, inherited: sect_title_inherited
indent 0, pgnum_label_placeholder_width do
sect_title_fragments[-1][:callback] = (last_fragment_pos = ::Asciidoctor::PDF::FormattedText::FragmentPositionRenderer.new)
typeset_formatted_text sect_title_fragments, line_metrics, hanging_indent: hanging_indent, normalize_line_height: true
start_dots = last_fragment_pos.right + hanging_indent
last_fragment_cursor = last_fragment_pos.top + line_metrics.padding_top
if (last_fragment_page_number = last_fragment_pos.page_number) > start_page_number ||
(start_cursor - last_fragment_cursor) > line_metrics.height
start_page_number = last_fragment_page_number
start_cursor = last_fragment_cursor
end
end
end_page_number = page_number
end_cursor = cursor
# TODO: it would be convenient to have a cursor mark / placement utility that took page number into account
go_to_page start_page_number if start_page_number != end_page_number
move_cursor_to start_cursor
if dot_leader[:width] > 0 && (dot_leader[:levels].include? sect.level)
pgnum_label_width = rendered_width_of_string pgnum_label
pgnum_label_font_settings = { color: @font_color, font: font_family, size: @font_size, styles: font_styles }
save_font do
# NOTE the same font is used for dot leaders throughout toc
set_font toc_font_info[:font], toc_font_info[:size]
font_style dot_leader[:font_style]
num_dots = ((bounds.width - start_dots - dot_leader[:spacer_width] - pgnum_label_width) / dot_leader[:width]).floor
# FIXME: dots don't line up in columns if width of page numbers differ
typeset_formatted_text [
{ text: (dot_leader[:text] * (num_dots < 0 ? 0 : num_dots)), color: dot_leader[:font_color] },
dot_leader[:spacer],
{ text: pgnum_label, anchor: sect_anchor }.merge(pgnum_label_font_settings),
], line_metrics, align: :right
end
else
typeset_formatted_text [{ text: pgnum_label, color: @font_color, anchor: sect_anchor }], line_metrics, align: :right
end
go_to_page end_page_number if page_number != end_page_number
move_cursor_to end_cursor
end
end
indent @theme.toc_indent do
layout_toc_level sect.sections, num_levels_for_sect, line_metrics, dot_leader, num_front_matter_pages
end if num_levels_for_sect > sect.level
end
end
# Reduce icon height to fit inside bounds.height. Icons will not render
# properly if they are larger than the current bounds.height.
def fit_icon_to_bounds preferred_size = 24
(max_height = bounds.height) < preferred_size ? max_height : preferred_size
end
def admonition_icon_data key
if (icon_data = @theme[%(admonition_icon_#{key})])
icon_data = (AdmonitionIcons[key] || {}).merge icon_data
if (icon_name = icon_data[:name])
unless icon_name.start_with?(*IconSetPrefixes)
logger.info { %(#{key} admonition in theme uses icon from deprecated fa icon set; use fas, far, or fab instead) } unless scratch?
icon_data[:name] = %(fa-#{icon_name}) unless icon_name.start_with? 'fa-'
end
else
icon_data[:name] = AdmonitionIcons[:note][:name]
end
else
(icon_data = AdmonitionIcons[key] || {})[:name] ||= AdmonitionIcons[:note][:name]
end
icon_data
end
# TODO: delegate to layout_page_header and layout_page_footer per page
def layout_running_content periphery, doc, opts = {}
skip, skip_pagenums = opts[:skip] || [1, 1]
body_start_page_number = opts[:body_start_page_number] || 1
# NOTE find and advance to first non-imported content page to use as model page
return unless (content_start_page = state.pages[skip..-1].index {|it| !it.imported_page? })
content_start_page += (skip + 1)
num_pages = page_count
prev_page_number = page_number
go_to_page content_start_page
# FIXME: probably need to treat doctypes differently
is_book = doc.doctype == 'book'
header = doc.header? ? doc.header : nil
sectlevels = (@theme[%(#{periphery}_sectlevels)] || 2).to_i
sections = doc.find_by(context: :section) {|sect| sect.level <= sectlevels && sect != header }
if (toc_page_nums = @toc_extent && @toc_extent[:page_nums])
toc_title = (doc.attr 'toc-title') || ''
end
disable_on_pages = @disable_running_content[periphery]
title_method = TitleStyles[@theme[%(#{periphery}_title_style)]]
# FIXME: we need a proper model for all this page counting
# FIXME: we make a big assumption that part & chapter start on new pages
# index parts, chapters and sections by the physical page number on which they start
part_start_pages = {}
chapter_start_pages = {}
section_start_pages = {}
trailing_section_start_pages = {}
sections.each do |sect|
pgnum = (sect.attr 'pdf-page-start').to_i
if is_book && ((sect_is_part = sect.part?) || sect.chapter?)
if sect_is_part
part_start_pages[pgnum] ||= sect
else
chapter_start_pages[pgnum] ||= sect
# FIXME: need a better way to indicate that part has ended
part_start_pages[pgnum] = '' if sect.sectname == 'appendix' && !part_start_pages.empty?
end
else
trailing_section_start_pages[pgnum] = sect
section_start_pages[pgnum] ||= sect
end
end
# index parts, chapters, and sections by the physical page number on which they appear
parts_by_page = SectionInfoByPage.new title_method
chapters_by_page = SectionInfoByPage.new title_method
sections_by_page = SectionInfoByPage.new title_method
# QUESTION should the default part be the doctitle?
last_part = nil
# QUESTION should we enforce that the preamble is a preface?
last_chap = is_book ? :pre : nil
last_sect = nil
sect_search_threshold = 1
(1..num_pages).each do |pgnum|
if (part = part_start_pages[pgnum])
last_part = part
last_chap = nil
last_sect = nil
end
if (chap = chapter_start_pages[pgnum])
last_chap = chap
last_sect = nil
end
if (sect = section_start_pages[pgnum])
last_sect = sect
elsif part || chap
sect_search_threshold = pgnum
# NOTE we didn't find a section on this page; look back to find last section started
elsif last_sect
(sect_search_threshold..(pgnum - 1)).reverse_each do |prev|
if (sect = trailing_section_start_pages[prev])
last_sect = sect
break
end
end
end
parts_by_page[pgnum] = last_part
if toc_page_nums && (toc_page_nums.cover? pgnum)
if is_book
chapters_by_page[pgnum] = toc_title
sections_by_page[pgnum] = nil
else
chapters_by_page[pgnum] = nil
sections_by_page[pgnum] = section_start_pages[pgnum] || toc_title
end
toc_page_nums = nil if toc_page_nums.end == pgnum
elsif last_chap == :pre
chapters_by_page[pgnum] = pgnum < body_start_page_number ? doc.doctitle : (doc.attr 'preface-title', 'Preface')
sections_by_page[pgnum] = last_sect
else
chapters_by_page[pgnum] = last_chap
sections_by_page[pgnum] = last_sect
end
end
doctitle = doc.doctitle partition: true, use_fallback: true
# NOTE set doctitle again so it's properly escaped
doc.set_attr 'doctitle', doctitle.combined
doc.set_attr 'document-title', doctitle.main
doc.set_attr 'document-subtitle', doctitle.subtitle
doc.set_attr 'page-count', (num_pages - skip_pagenums)
pagenums_enabled = doc.attr? 'pagenums'
case @media == 'prepress' ? 'physical' : (doc.attr 'pdf-folio-placement')
when 'physical'
folio_basis, invert_folio = :physical, false
when 'physical-inverted'
folio_basis, invert_folio = :physical, true
when 'virtual-inverted'
folio_basis, invert_folio = :virtual, true
else
folio_basis, invert_folio = :virtual, false
end
periphery_layout_cache = {}
# NOTE: this block is invoked during PDF generation, after convert_document has returned
repeat (content_start_page..num_pages), dynamic: true do
pgnum = page_number
# NOTE: don't write on pages which are imported / inserts (otherwise we can get a corrupt PDF)
next if page.imported_page? || (disable_on_pages && (disable_on_pages.include? pgnum))
virtual_pgnum = pgnum - skip_pagenums
pgnum_label = (virtual_pgnum < 1 ? (RomanNumeral.new pgnum, :lower) : virtual_pgnum).to_s
side = page_side((folio_basis == :physical ? pgnum : virtual_pgnum), invert_folio)
doc.set_attr 'page-layout', page.layout.to_s
# NOTE: running content is cached per page layout
# QUESTION: should allocation be per side?
trim_styles, colspec_dict, content_dict, stamp_names = allocate_running_content_layout doc, page, periphery, periphery_layout_cache
# FIXME: we need to have a content setting for chapter pages
content_by_position, colspec_by_position = content_dict[side], colspec_dict[side]
doc.set_attr 'page-number', pgnum_label if pagenums_enabled
# QUESTION should the fallback value be nil instead of empty string? or should we remove attribute if no value?
doc.set_attr 'part-title', ((part_info = parts_by_page[pgnum])[:title] || '')
if (part_numeral = part_info[:numeral])
doc.set_attr 'part-numeral', part_numeral
else
doc.remove_attr 'part-numeral'
end
doc.set_attr 'chapter-title', ((chap_info = chapters_by_page[pgnum])[:title] || '')
if (chap_numeral = chap_info[:numeral])
doc.set_attr 'chapter-numeral', chap_numeral
else
doc.remove_attr 'chapter-numeral'
end
doc.set_attr 'section-title', ((sect_info = sections_by_page[pgnum])[:title] || '')
doc.set_attr 'section-or-chapter-title', (sect_info[:title] || chap_info[:title] || '')
stamp stamp_names[side] if stamp_names
theme_font periphery do
canvas do
bounding_box [trim_styles[:content_left][side], trim_styles[:top][side]], width: trim_styles[:content_width][side], height: trim_styles[:height] do
if (trim_column_rule_width = trim_styles[:column_rule_width]) > 0
trim_column_rule_spacing = trim_styles[:column_rule_spacing]
else
trim_column_rule_width = nil
end
prev_position = nil
ColumnPositions.each do |position|
next unless (content = content_by_position[position])
next unless (colspec = colspec_by_position[position])[:width] > 0
left, colwidth = colspec[:x], colspec[:width]
if trim_column_rule_width && colwidth < bounds.width
if (trim_column_rule = prev_position)
left += (trim_column_rule_spacing * 0.5)
colwidth -= trim_column_rule_spacing
else
colwidth -= (trim_column_rule_spacing * 0.5)
end
end
# FIXME: we need to have a content setting for chapter pages
if ::Array === content
# NOTE float ensures cursor position is restored and returns us to current page if we overrun
float do
# NOTE bounding_box is redundant if both vertical padding and border width are 0
bounding_box [left, bounds.top - trim_styles[:padding][side][0] - trim_styles[:content_offset]], width: colwidth, height: trim_styles[:content_height][side] do
# NOTE image vposition respects padding; use negative image_vertical_align value to revert
image_opts = content[1].merge position: colspec[:align], vposition: trim_styles[:img_valign]
begin
image_info = image content[0], image_opts
if (image_link = content[2])
image_info = { width: image_info.scaled_width, height: image_info.scaled_height } unless image_opts[:format] == 'svg'
add_link_to_image image_link, image_info, image_opts
end
rescue
logger.warn %(could not embed image in running content: #{content[0]}; #{$!.message})
end
end
end
else
theme_font %(#{periphery}_#{side}_#{position}) do
# NOTE minor optimization
if content == '{page-number}'
content = pagenums_enabled ? pgnum_label : nil
else
content = apply_subs_discretely doc, content, drop_lines_with_unresolved_attributes: true
content = transform_text content, @text_transform if @text_transform
end
formatted_text_box parse_text(content, color: @font_color, inline_format: [normalize: true]),
at: [left, bounds.top - trim_styles[:padding][side][0] - trim_styles[:content_offset] + ((Array trim_styles[:valign])[0] == :center ? font.descender * 0.5 : 0)],
width: colwidth,
height: trim_styles[:prose_content_height][side],
align: colspec[:align],
valign: trim_styles[:valign],
leading: trim_styles[:line_metrics].leading,
final_gap: false,
overflow: :truncate
end
end
bounding_box [colspec[:x], bounds.top - trim_styles[:padding][side][0] - trim_styles[:content_offset]], width: colspec[:width], height: trim_styles[:content_height][side] do
stroke_vertical_rule trim_styles[:column_rule_color], at: bounds.left, line_style: trim_styles[:column_rule_style], line_width: trim_column_rule_width
end if trim_column_rule
prev_position = position
end
end
end
end
end
go_to_page prev_page_number
nil
end
def allocate_running_content_layout doc, page, periphery, cache
cache[layout = page.layout] ||= begin
page_margin_recto = @page_margin_by_side[:recto]
trim_margin_recto = @theme[%(#{periphery}_recto_margin)] || @theme[%(#{periphery}_margin)] || [0, 'inherit', 0, 'inherit']
trim_margin_recto = (expand_margin_value trim_margin_recto).map.with_index {|v, i| i.odd? && v == 'inherit' ? page_margin_recto[i] : v.to_f }
trim_content_margin_recto = @theme[%(#{periphery}_recto_content_margin)] || @theme[%(#{periphery}_content_margin)] || [0, 'inherit', 0, 'inherit']
trim_content_margin_recto = (expand_margin_value trim_content_margin_recto).map.with_index {|v, i| i.odd? && v == 'inherit' ? page_margin_recto[i] - trim_margin_recto[i] : v.to_f }
if (trim_padding_recto = @theme[%(#{periphery}_recto_padding)] || @theme[%(#{periphery}_padding)])
trim_padding_recto = (expand_margin_value trim_padding_recto).map.with_index {|v, i| v + trim_content_margin_recto[i] }
else
trim_padding_recto = trim_content_margin_recto
end
page_margin_verso = @page_margin_by_side[:verso]
trim_margin_verso = @theme[%(#{periphery}_verso_margin)] || @theme[%(#{periphery}_margin)] || [0, 'inherit', 0, 'inherit']
trim_margin_verso = (expand_margin_value trim_margin_verso).map.with_index {|v, i| i.odd? && v == 'inherit' ? page_margin_verso[i] : v.to_f }
trim_content_margin_verso = @theme[%(#{periphery}_verso_content_margin)] || @theme[%(#{periphery}_content_margin)] || [0, 'inherit', 0, 'inherit']
trim_content_margin_verso = (expand_margin_value trim_content_margin_verso).map.with_index {|v, i| i.odd? && v == 'inherit' ? page_margin_verso[i] - trim_margin_verso[i] : v.to_f }
if (trim_padding_verso = @theme[%(#{periphery}_verso_padding)] || @theme[%(#{periphery}_padding)])
trim_padding_verso = (expand_margin_value trim_padding_verso).map.with_index {|v, i| v + trim_content_margin_verso[i] }
else
trim_padding_verso = trim_content_margin_verso
end
valign, valign_offset = @theme[%(#{periphery}_vertical_align)]
if (valign = (valign || :middle).to_sym) == :middle
valign = :center
end
trim_styles = {
line_metrics: (trim_line_metrics = calc_line_metrics @theme[%(#{periphery}_line_height)] || @theme.base_line_height),
# NOTE we've already verified this property is set
height: (trim_height = @theme[%(#{periphery}_height)]),
bg_color: (resolve_theme_color %(#{periphery}_background_color).to_sym),
border_color: (trim_border_color = resolve_theme_color %(#{periphery}_border_color).to_sym),
border_style: (@theme[%(#{periphery}_border_style)] || :solid).to_sym,
border_width: (trim_border_width = trim_border_color ? @theme[%(#{periphery}_border_width)] || @theme.base_border_width || 0 : 0),
column_rule_color: (trim_column_rule_color = resolve_theme_color %(#{periphery}_column_rule_color).to_sym),
column_rule_style: (@theme[%(#{periphery}_column_rule_style)] || :solid).to_sym,
column_rule_width: (trim_column_rule_color ? @theme[%(#{periphery}_column_rule_width)] || 0 : 0),
column_rule_spacing: (@theme[%(#{periphery}_column_rule_spacing)] || 0),
valign: valign_offset ? [valign, valign_offset] : valign,
img_valign: @theme[%(#{periphery}_image_vertical_align)],
top: {
recto: periphery == :header ? page_height - trim_margin_recto[0] : trim_height + trim_margin_recto[2],
verso: periphery == :header ? page_height - trim_margin_verso[0] : trim_height + trim_margin_verso[2],
},
left: {
recto: (trim_left_recto = trim_margin_recto[3]),
verso: (trim_left_verso = trim_margin_verso[3]),
},
width: {
recto: (trim_width_recto = page_width - trim_left_recto - trim_margin_recto[1]),
verso: (trim_width_verso = page_width - trim_left_verso - trim_margin_verso[1]),
},
padding: {
recto: trim_padding_recto,
verso: trim_padding_verso,
},
content_left: {
recto: trim_left_recto + trim_padding_recto[3],
verso: trim_left_verso + trim_padding_verso[3],
},
content_width: (trim_content_width = {
recto: trim_width_recto - trim_padding_recto[1] - trim_padding_recto[3],
verso: trim_width_verso - trim_padding_verso[1] - trim_padding_verso[3],
}),
content_height: (trim_content_height = {
recto: trim_height - trim_padding_recto[0] - trim_padding_recto[2] - (trim_border_width * 0.5),
verso: trim_height - trim_padding_verso[0] - trim_padding_verso[2] - (trim_border_width * 0.5),
}),
prose_content_height: {
recto: trim_content_height[:recto] - trim_line_metrics.padding_top - trim_line_metrics.padding_bottom,
verso: trim_content_height[:verso] - trim_line_metrics.padding_top - trim_line_metrics.padding_bottom,
},
# NOTE content offset adjusts y position to account for border
content_offset: (periphery == :footer ? trim_border_width * 0.5 : 0),
}
case trim_styles[:img_valign]
when nil
trim_styles[:img_valign] = valign
when 'middle'
trim_styles[:img_valign] = :center
when 'top', 'center', 'bottom'
trim_styles[:img_valign] = trim_styles[:img_valign].to_sym
end
if (trim_bg_image_recto = resolve_background_image doc, @theme, %(#{periphery}_background_image).to_sym, container_size: [trim_width_recto, trim_height]) && trim_bg_image_recto[0]
trim_bg_image = { recto: trim_bg_image_recto }
if trim_width_recto == trim_width_verso
trim_bg_image[:verso] = trim_bg_image_recto
else
trim_bg_image[:verso] = resolve_background_image doc, @theme, %(#{periphery}_background_image).to_sym, container_size: [trim_width_verso, trim_height]
end
end
colspec_dict = PageSides.each_with_object({}) do |side, acc|
side_trim_content_width = trim_content_width[side]
if (custom_colspecs = @theme[%(#{periphery}_#{side}_columns)] || @theme[%(#{periphery}_columns)])
case (colspecs = (custom_colspecs.to_s.tr ',', ' ').split).size
when 0, 1
colspecs = { left: '0', center: colspecs[0] || '100', right: '0' }
when 2
colspecs = { left: colspecs[0], center: '0', right: colspecs[1] }
else # 3
colspecs = { left: colspecs[0], center: colspecs[1], right: colspecs[2] }
end
tot_width = 0
side_colspecs = colspecs.map {|col, spec|
if (alignment_char = spec.chr).to_i.to_s != alignment_char
alignment = AlignmentTable[alignment_char]
rel_width = (spec.slice 1, spec.length).to_f
else
alignment = :left
rel_width = spec.to_f
end
tot_width += rel_width
[col, { align: alignment, width: rel_width, x: 0 }]
}.to_h
# QUESTION should we allow the columns to overlap (capping width at 100%)?
side_colspecs.each {|_, colspec| colspec[:width] = (colspec[:width] / tot_width) * side_trim_content_width }
side_colspecs[:right][:x] = (side_colspecs[:center][:x] = side_colspecs[:left][:width]) + side_colspecs[:center][:width]
acc[side] = side_colspecs
else
acc[side] = {
left: { align: :left, width: side_trim_content_width, x: 0 },
center: { align: :center, width: side_trim_content_width, x: 0 },
right: { align: :right, width: side_trim_content_width, x: 0 },
}
end
end
content_dict = PageSides.each_with_object({}) do |side, acc|
side_content = {}
ColumnPositions.each do |position|
next if (val = @theme[%(#{periphery}_#{side}_#{position}_content)]).nil_or_empty?
val = val.to_s unless ::String === val
if (val.include? ':') && val =~ ImageAttributeValueRx
attrlist = $2
image_attrs = (AttributeList.new attrlist).parse %w(alt width)
image_path, image_format = ::Asciidoctor::Image.target_and_format $1, image_attrs
if (image_path = resolve_image_path doc, image_path, image_format, @themesdir) && (::File.readable? image_path)
image_opts = resolve_image_options image_path, image_format, image_attrs, container_size: [colspec_dict[side][position][:width], trim_content_height[side]]
side_content[position] = [image_path, image_opts, image_attrs['link']]
else
# NOTE allows inline image handler to report invalid reference and replace with alt text
side_content[position] = %(image:#{image_path}[#{attrlist}])
end
else
side_content[position] = val
end
end
acc[side] = side_content
end
if (trim_bg_color = trim_styles[:bg_color]) || trim_bg_image || trim_border_width > 0
stamp_names = { recto: %(#{layout}_#{periphery}_recto), verso: %(#{layout}_#{periphery}_verso) }
PageSides.each do |side|
create_stamp stamp_names[side] do
canvas do
bounding_box [trim_styles[:left][side], trim_styles[:top][side]], width: trim_styles[:width][side], height: trim_height do
fill_bounds trim_bg_color if trim_bg_color
# NOTE: must draw line before image or SVG will cause border to disappear
stroke_horizontal_rule trim_styles[:border_color], line_width: trim_border_width, line_style: trim_styles[:border_style], at: (periphery == :header ? bounds.height : 0) if trim_border_width > 0
image trim_bg_image[side][0], ({ position: :center, vposition: :center }.merge trim_bg_image[side][1]) if trim_bg_image
end
end
end
end
end
[trim_styles, colspec_dict, content_dict, stamp_names]
end
end
def add_outline doc, num_levels = 2, toc_page_nums = [], num_front_matter_pages = 0, has_front_cover = false
if ::String === num_levels
if num_levels.include? ':'
num_levels, expand_levels = num_levels.split ':', 2
num_levels = num_levels.empty? ? (doc.attr 'toclevels', 2).to_i : num_levels.to_i
expand_levels = expand_levels.to_i
else
num_levels = expand_levels = num_levels.to_i
end
else
expand_levels = num_levels
end
front_matter_counter = RomanNumeral.new 0, :lower
pagenum_labels = {}
num_front_matter_pages.times do |n|
pagenum_labels[n] = { P: (::PDF::Core::LiteralString.new front_matter_counter.next!.to_s) }
end
# add labels for each content page, which is required for reader's page navigator to work correctly
(num_front_matter_pages..(page_count - 1)).each_with_index do |n, i|
pagenum_labels[n] = { P: (::PDF::Core::LiteralString.new (i + 1).to_s) }
end
unless toc_page_nums.none? || (toc_title = doc.attr 'toc-title').nil_or_empty?
toc_section = insert_toc_section doc, toc_title, toc_page_nums
end
outline.define do
initial_pagenum = has_front_cover ? 2 : 1
# FIXME: use sanitize: :plain_text once available
if document.page_count >= initial_pagenum && (doctitle = doc.header? ? doc.doctitle : (doc.attr 'untitled-label'))
page title: (document.sanitize doctitle), destination: (document.dest_top has_front_cover ? 2 : 1)
end
# QUESTION is there any way to get add_outline_level to invoke in the context of the outline?
document.add_outline_level self, doc.sections, num_levels, expand_levels
end if doc.attr? 'outline'
toc_section.parent.blocks.delete toc_section if toc_section
catalog.data[:PageLabels] = state.store.ref Nums: pagenum_labels.flatten
primary_page_mode, secondary_page_mode = PageModes[(doc.attr 'pdf-page-mode') || @theme.page_mode]
catalog.data[:PageMode] = primary_page_mode
catalog.data[:NonFullScreenPageMode] = secondary_page_mode if secondary_page_mode
nil
end
def add_outline_level outline, sections, num_levels, expand_levels
sections.each do |sect|
sect_title = sanitize sect.numbered_title formal: true
sect_destination = sect.attr 'pdf-destination'
if (level = sect.level) == num_levels || !sect.sections?
outline.page title: sect_title, destination: sect_destination
elsif level <= num_levels
outline.section sect_title, destination: sect_destination, closed: expand_levels < 1 do
add_outline_level outline, sect.sections, num_levels, (expand_levels - 1)
end
end
end
end
def insert_toc_section doc, toc_title, toc_page_nums
if (doc.attr? 'toc-placement', 'macro') && (toc_node = (doc.find_by context: :toc)[0])
if (parent_section = toc_node.parent).context == :section
grandparent_section = parent_section.parent
toc_level = parent_section.level
insert_idx = (grandparent_section.blocks.index parent_section) + 1
else
grandparent_section = doc
toc_level = doc.sections[0].level
insert_idx = 0
end
toc_dest = toc_node.attr 'pdf-destination'
else
grandparent_section = doc
toc_level = doc.sections[0].level
insert_idx = 0
toc_dest = dest_top toc_page_nums.first
end
toc_section = Section.new grandparent_section, toc_level, false, attributes: { 'pdf-destination' => toc_dest }
toc_section.title = toc_title
grandparent_section.blocks.insert insert_idx, toc_section
toc_section
end
def write pdf_doc, target
if target.respond_to? :write
target = ::QuantifiableStdout.new STDOUT if target == STDOUT
pdf_doc.render target
else
pdf_doc.render_file target
# QUESTION restore attributes first?
@pdfmark&.generate_file target
(Optimizer.new @optimize, pdf_doc.min_version).generate_file target if @optimize && ((defined? ::Asciidoctor::PDF::Optimizer) || !(Helpers.require_library OptimizerRequirePath, 'rghost', :warn).nil?)
to_file = true
end
if !ENV['KEEP_ARTIFACTS']
remove_tmp_files
elsif to_file
scratch_target = (target.slice 0, target.length - (target_ext = ::File.extname target).length) + '-scratch' + target_ext
get_scratch_document.render_file scratch_target
end
clear_scratch
nil
end
def register_fonts font_catalog, fonts_dir
return unless font_catalog
dirs = (fonts_dir.split ValueSeparatorRx, -1).map do |dir|
dir == 'GEM_FONTS_DIR' || dir.empty? ? ThemeLoader::FontsDir : dir
end
font_catalog.each do |key, styles|
styles = styles.each_with_object({}) do |(style, path), accum|
found = dirs.find do |dir|
resolved_font_path = font_path path, dir
if ::File.readable? resolved_font_path
accum[style.to_sym] = resolved_font_path
true
end
end
raise ::Errno::ENOENT, ((File.absolute_path? path) ? %(#{path} not found) : %(#{path} not found in #{fonts_dir.gsub ValueSeparatorRx, ' or '})) unless found
end
register_font key => styles
end
end
def font_path font_file, fonts_dir
# resolve relative to built-in font dir unless path is absolute
::File.absolute_path font_file, fonts_dir
end
def fallback_svg_font_name
@theme.svg_fallback_font_family || @theme.svg_font_family || @theme.base_font_family
end
def apply_text_decoration styles, category, level = nil
if (text_decoration_style = TextDecorationStyleTable[(level && @theme[%(#{category}_h#{level}_text_decoration)]) || @theme[%(#{category}_text_decoration)]])
{
styles: (styles << text_decoration_style),
text_decoration_color: (level && @theme[%(#{category}_h#{level}_text_decoration_color)]) || @theme[%(#{category}_text_decoration_color)],
text_decoration_width: (level && @theme[%(#{category}_h#{level}_text_decoration_width)]) || @theme[%(#{category}_text_decoration_width)],
}.compact
else
styles.empty? ? {} : { styles: styles }
end
end
def resolve_text_transform key, use_fallback = true
if (transform = ::Hash === key ? (key.delete :text_transform) : @theme[key.to_s])
transform == 'none' ? nil : transform
elsif use_fallback
@text_transform
end
end
# QUESTION should we pass a category as an argument?
# QUESTION should we make this a method on the theme ostruct? (e.g., @theme.resolve_color key, fallback)
def resolve_theme_color key, fallback_color = nil
if (color = @theme[key.to_s]) && color != 'transparent'
color
else
fallback_color
end
end
def resolve_font_kerning keyword, fallback = default_kerning?
keyword && (FontKerningTable.key? keyword) ? FontKerningTable[keyword] : fallback
end
def theme_fill_and_stroke_bounds category, opts = {}
fill_and_stroke_bounds opts[:background_color], @theme[%(#{category}_border_color)],
line_width: (@theme[%(#{category}_border_width)] || 0),
line_style: (@theme[%(#{category}_border_style)] || :solid).to_sym,
radius: @theme[%(#{category}_border_radius)]
end
def theme_fill_and_stroke_block category, block_height, opts = {}
if (b_width = (opts.key? :border_width) ? opts[:border_width] : @theme[%(#{category}_border_width)])
if ::Array === b_width
b_width = b_width[0] || 0
b_radius = 0
end
b_width = nil unless b_width > 0
end
if (bg_color = opts[:background_color] || @theme[%(#{category}_background_color)]) == 'transparent'
bg_color = nil
end
unless b_width || bg_color
(node = opts[:caption_node]) && node.title? && (layout_caption node, category: category)
return
end
if (b_color = @theme[%(#{category}_border_color)]) == 'transparent'
b_color = @page_bg_color
end
b_radius ||= (@theme[%(#{category}_border_radius)] || 0) + (b_width || 0)
if b_width && b_color
if b_color == @page_bg_color # let page background cut into block background
b_gap_color, b_shift = @page_bg_color, (b_width * 0.5)
elsif (b_gap_color = bg_color) && b_gap_color != b_color
b_shift = 0
else # let page background cut into border
b_gap_color, b_shift = @page_bg_color, 0
end
else # let page background cut into block background
b_shift, b_gap_color = (b_width ||= 0.5) * 0.5, @page_bg_color
end
# FIXME: due to the calculation error logged in #789, we must advance page even when content is split across pages
advance_page if (opts.fetch :split_from_top, true) && block_height > cursor && !at_page_top?
caption_height = (node = opts[:caption_node]) && node.title? ? (layout_caption node, category: category) : 0
float do
remaining_height = block_height - caption_height
initial_page = true
while remaining_height > 0
advance_page unless initial_page
chunk_height = [(available_height = cursor), remaining_height].min
bounding_box [0, available_height], width: bounds.width, height: chunk_height do
theme_fill_and_stroke_bounds category, background_color: bg_color
# NOTE b_width is always set; if no border is set, split indicator is cut into background
indent b_radius, b_radius do
# dashed line indicates continuation from previous page; swell line slightly to cover background
stroke_horizontal_rule b_gap_color, line_width: b_width * 1.2, line_style: :dashed, at: b_shift
end unless initial_page
if remaining_height > chunk_height
move_down chunk_height - b_shift
indent b_radius, b_radius do
# dashed line indicates continuation from previous page; swell line slightly to cover background
stroke_horizontal_rule b_gap_color, line_width: b_width * 1.2, line_style: :dashed
end
end
end
initial_page = false
remaining_height -= chunk_height
end
end
end
# Insert a top margin equal to amount if cursor is not at the top of the
# page. Start a new page instead if amount is greater than the remaining
# space on the page.
def margin_top amount
margin amount, :top
end
# Insert a bottom margin equal to amount unless cursor is at the top of the
# page (not likely). Start a new page instead if amount is greater than the
# remaining space on the page.
def margin_bottom amount
margin amount, :bottom
end
# Insert a margin at the specified side if the cursor is not at the top of
# the page. Start a new page if amount is greater than the remaining space on
# the page.
def margin amount, _side
unless (amount || 0) == 0 || at_page_top?
# NOTE use low-level cursor calculation to workaround cursor bug in column_box context
if y - reference_bounds.absolute_bottom > amount
move_down amount
else
# set cursor at top of next page
reference_bounds.move_past_bottom
end
end
end
# Lookup margin for theme element and side, then delegate to margin method.
# If margin value is not found, assume:
# - 0 when side == :top
# - @theme.vertical_spacing when side == :bottom
def theme_margin category, side
margin((@theme[%(#{category}_margin_#{side})] || (side == :bottom ? @theme.vertical_spacing : 0)), side)
end
def theme_font category, opts = {}
result = nil
# TODO: inheriting from generic category should be an option
if opts.key? :level
hlevel_category = %(#{category}_h#{opts[:level]})
family = @theme[%(#{hlevel_category}_font_family)] || @theme[%(#{category}_font_family)] || @theme.base_font_family || font_family
size = @theme[%(#{hlevel_category}_font_size)] || @theme[%(#{category}_font_size)] || @root_font_size
style = @theme[%(#{hlevel_category}_font_style)] || @theme[%(#{category}_font_style)]
color = @theme[%(#{hlevel_category}_font_color)] || @theme[%(#{category}_font_color)]
kerning = resolve_font_kerning @theme[%(#{hlevel_category}_font_kerning)] || @theme[%(#{category}_font_kerning)], nil
# NOTE global text_transform is not currently supported
transform = @theme[%(#{hlevel_category}_text_transform)] || @theme[%(#{category}_text_transform)]
else
inherited_font = font_info
family = @theme[%(#{category}_font_family)] || inherited_font[:family]
size = @theme[%(#{category}_font_size)] || inherited_font[:size]
style = @theme[%(#{category}_font_style)] || inherited_font[:style]
color = @theme[%(#{category}_font_color)]
kerning = resolve_font_kerning @theme[%(#{category}_font_kerning)], nil
# NOTE global text_transform is not currently supported
transform = @theme[%(#{category}_text_transform)]
end
prev_color, @font_color = @font_color, color if color
prev_kerning, self.default_kerning = default_kerning?, kerning unless kerning.nil?
prev_transform, @text_transform = @text_transform, (transform == 'none' ? nil : transform) if transform
font family, size: size * @font_scale, style: (style && style.to_sym) do
result = yield
end
@font_color = prev_color if color
default_kerning prev_kerning unless kerning.nil?
@text_transform = prev_transform if transform
result
end
# Calculate the font size (down to the minimum font size) that would allow
# all the specified fragments to fit in the available width without wrapping lines.
#
# Return the calculated font size if an adjustment is necessary or nil if no
# font size adjustment is necessary.
def compute_autofit_font_size fragments, category
arranger = arrange_fragments_by_line fragments
# NOTE finalizing the line here generates fragments & calculates their widths using the current font settings
# CAUTION it also removes zero-width spaces
arranger.finalize_line
actual_width = width_of_fragments arranger.fragments
unless ::Array === (padding = @theme[%(#{category}_padding)])
padding = ::Array.new 4, padding
end
available_width = bounds.width - (padding[3] || 0) - (padding[1] || 0)
if actual_width > available_width
adjusted_font_size = ((available_width * font_size).to_f / actual_width).truncate 4
if (min = @theme[%(#{category}_font_size_min)] || @theme.base_font_size_min) && adjusted_font_size < min
min
else
adjusted_font_size
end
end
end
# Arrange fragments by line in an arranger and return an unfinalized arranger.
#
# Finalizing the arranger is deferred since it must be done in the context of
# the global font settings you want applied to each fragment.
def arrange_fragments_by_line fragments, _opts = {}
arranger = ::Prawn::Text::Formatted::Arranger.new self
by_line = arranger.consumed = []
fragments.each do |fragment|
if (text = fragment[:text]) == LF
by_line << fragment
elsif text.include? LF
text.scan LineScanRx do |line|
by_line << (line == LF ? { text: LF } : (fragment.merge text: line))
end
else
by_line << fragment
end
end
arranger
end
# Calculate the width that is needed to print all the
# fragments without wrapping any lines.
#
# This method assumes endlines are represented as discrete entries in the
# fragments array.
def width_of_fragments fragments
line_widths = [0]
fragments.each do |fragment|
if fragment.text == LF
line_widths << 0
else
line_widths[-1] += fragment.width
end
end
line_widths.max
end
# Compute the rendered width of a string, taking fallback fonts into account
def rendered_width_of_string str, opts = {}
opts = opts.merge kerning: default_kerning?
if str.length == 1
rendered_width_of_char str, opts
elsif (chars = str.each_char).all? {|char| font.glyph_present? char }
width_of_string str, opts
else
char_widths = chars.map {|char| rendered_width_of_char char, opts }
char_widths.sum + (char_widths.length * (opts[:character_spacing] || character_spacing))
end
end
# Compute the rendered width of a char, taking fallback fonts into account
def rendered_width_of_char char, opts = {}
unless @fallback_fonts.empty? || (font.glyph_present? char)
@fallback_fonts.each do |fallback_font|
font fallback_font do
return width_of_string char, opts if font.glyph_present? char
end
end
end
width_of_string char, opts
end
# TODO: document me, esp the first line formatting functionality
def typeset_text string, line_metrics, opts = {}
move_down line_metrics.padding_top
opts = { leading: line_metrics.leading, final_gap: line_metrics.final_gap }.merge opts
string = string.gsub CjkLineBreakRx, ZeroWidthSpace if @cjk_line_breaks
if (hanging_indent = (opts.delete :hanging_indent) || 0) > 0
indent hanging_indent do
text string, (opts.merge indent_paragraphs: -hanging_indent)
end
elsif (first_line_opts = opts.delete :first_line_options)
# TODO: good candidate for Prawn enhancement!
text_with_formatted_first_line string, first_line_opts, opts
else
text string, opts
end
move_down line_metrics.padding_bottom
end
# QUESTION combine with typeset_text?
def typeset_formatted_text fragments, line_metrics, opts = {}
move_down line_metrics.padding_top
opts = { leading: line_metrics.leading, final_gap: line_metrics.final_gap }.merge opts
if (hanging_indent = (opts.delete :hanging_indent) || 0) > 0
indent hanging_indent do
formatted_text fragments, (opts.merge indent_paragraphs: -hanging_indent)
end
else
formatted_text fragments, opts
end
move_down line_metrics.padding_bottom
end
def height_of_typeset_text string, opts = {}
line_metrics = (calc_line_metrics opts[:line_height] || @theme.base_line_height)
(height_of string, leading: line_metrics.leading, final_gap: line_metrics.final_gap) + line_metrics.padding_top + (opts[:single_line] ? 0 : line_metrics.padding_bottom)
end
# NOTE only used when tabsize attribute is not specified
# tabs must always be replaced with spaces in order for the indentation guards to work
def expand_tabs string
if string.nil_or_empty?
''
elsif string.include? TAB
full_tab_space = ' ' * (tab_size = 4)
(string.split LF, -1).map {|line|
if line.empty?
line
elsif (tab_idx = line.index TAB)
if tab_idx == 0
leading_tabs = 0
line.each_byte do |b|
break unless b == 9
leading_tabs += 1
end
line = %(#{full_tab_space * leading_tabs}#{rest = line.slice leading_tabs, line.length})
next line unless rest.include? TAB
end
# keeps track of how many spaces were added to adjust offset in match data
spaces_added = 0
idx = 0
result = ''
line.each_char do |c|
if c == TAB
# calculate how many spaces this tab represents, then replace tab with spaces
if (offset = idx + spaces_added) % tab_size == 0
spaces_added += (tab_size - 1)
result += full_tab_space
else
unless (spaces = tab_size - offset % tab_size) == 1
spaces_added += (spaces - 1)
end
result += (' ' * spaces)
end
else
result += c
end
idx += 1
end
result
else
line
end
}.join LF
else
string
end
end
# Add an indentation guard at the start of indented lines.
# Expand tabs to spaces if tabs are present
def guard_indentation string
unless (string = expand_tabs string).empty?
string[0] = GuardedIndent if string.start_with? ' '
string.gsub! InnerIndent, GuardedInnerIndent if string.include? InnerIndent
end
string
end
def guard_indentation_in_fragments fragments
start_of_line = true
fragments.each do |fragment|
next if (text = fragment[:text]).empty?
if start_of_line && (text.start_with? ' ')
fragment[:text] = GuardedIndent + (((text = text.slice 1, text.length).include? InnerIndent) ? (text.gsub InnerIndent, GuardedInnerIndent) : text)
elsif text.include? InnerIndent
fragment[:text] = text.gsub InnerIndent, GuardedInnerIndent
end
start_of_line = text.end_with? LF
end
fragments
end
# Derive a PDF-safe, ASCII-only anchor name from the given value.
# Encodes value into hex if it contains characters outside the ASCII range.
# If value is nil, derive an anchor name from the default_value, if given.
def derive_anchor_from_id value, default_value = nil
if value
value.ascii_only? ? value : %(0x#{::PDF::Core.string_to_hex value})
else
%(__anchor-#{default_value})
end
end
# If an id is provided or the node passed as the first argument has an id,
# add a named destination to the document equivalent to the node id at the
# current y position. If the node does not have an id and an id is not
# specified, do nothing.
#
# If the node is a section, and the current y position is the top of the
# page, set the y position equal to the page height to improve the navigation
# experience. If the current x position is at or inside the left margin, set
# the x position equal to 0 (left edge of page) to improve the navigation
# experience.
def add_dest_for_block node, id = nil
if !scratch? && (id ||= node.id)
dest_x = bounds.absolute_left.truncate 4
# QUESTION when content is aligned to left margin, should we keep precise x value or just use 0?
dest_x = 0 if dest_x <= page_margin_left
dest_y = at_page_top? && (node.context == :section || node.context == :document) ? page_height : y
# TODO: find a way to store only the ref of the destination; look it up when we need it
node.set_attr 'pdf-destination', (node_dest = (dest_xyz dest_x, dest_y))
add_dest id, node_dest
end
nil
end
def resolve_alignment_from_role roles
if (align_role = roles.reverse.find {|r| TextAlignmentRoles.include? r })
(align_role.slice 5, align_role.length).to_sym
end
end
# QUESTION is this method still necessary?
def resolve_imagesdir doc
if (imagesdir = doc.attr 'imagesdir').nil_or_empty? || (imagesdir = imagesdir.chomp '/') == '.'
nil
else
imagesdir
end
end
# Resolve the system path of the specified image path.
#
# Resolve and normalize the absolute system path of the specified image,
# taking into account the imagesdir attribute. If an image path is not
# specified, the path is read from the target attribute of the specified
# document node.
#
# If the target is a URI and the allow-uri-read attribute is set on the
# document, read the file contents to a temporary file and return the path to
# the temporary file. If the target is a URI and the allow-uri-read attribute
# is not set, or the URI cannot be read, this method returns a nil value.
#
# When a temporary file is used, the file is stored in @tmp_files to be cleaned up after conversion.
def resolve_image_path node, image_path, image_format, relative_to = true
doc = node.document
imagesdir = relative_to == true ? (resolve_imagesdir doc) : relative_to
#image_format ||= ::Asciidoctor::Image.format image_path, (::Asciidoctor::Image === node ? node.attributes : nil)
# NOTE base64 logic currently used for inline images
if ::Base64 === image_path
return @tmp_files[image_path] if @tmp_files.key? image_path
tmp_image = ::Tempfile.create ['image-', image_format && %(.#{image_format})]
tmp_image.binmode unless image_format == 'svg'
begin
tmp_image.write ::Base64.decode64 image_path
tmp_image.close
@tmp_files[image_path] = tmp_image.path
rescue
@tmp_files[image_path] = nil
tmp_image.close
unlink_tmp_file tmp_image.path
nil
end
# handle case when image is a URI
elsif (node.is_uri? image_path) ||
(imagesdir && (node.is_uri? imagesdir) && (image_path = node.normalize_web_path image_path, imagesdir, false))
unless allow_uri_read
logger.warn %(allow-uri-read is not enabled; cannot embed remote image: #{image_path}) unless scratch?
return
end
return @tmp_files[image_path] if @tmp_files.key? image_path
tmp_image = ::Tempfile.create ['image-', image_format && %(.#{image_format})]
tmp_image.binmode if (binary = image_format != 'svg')
begin
load_open_uri.open_uri(image_path, (binary ? 'rb' : 'r')) {|fd| tmp_image.write fd.read }
tmp_image.close
@tmp_files[image_path] = tmp_image.path
rescue
@tmp_files[image_path] = nil
logger.warn %(could not retrieve remote image: #{image_path}; #{$!.message}) unless scratch?
tmp_image.close
unlink_tmp_file tmp_image.path
nil
end
# handle case when image is a local file
else
node.normalize_system_path image_path, imagesdir, nil, target_name: 'image'
end
end
# Resolve the path and sizing of the background image either from a document attribute or theme key.
#
# Returns the argument list for the image method if the document attribute or theme key is found. Otherwise,
# nothing. The first argument in the argument list is the image path. If that value is nil, the background
# image is disabled. The second argument is the options hash to specify the dimensions, such as width and fit.
def resolve_background_image doc, theme, key, opts = {}
if ::String === key
theme_key = opts.delete :theme_key
image_path = (doc.attr key) || (from_theme = theme[theme_key || (key.tr '-', '_').to_sym])
else
image_path = from_theme = theme[key]
end
symbolic_paths = opts.delete :symbolic_paths
if image_path
if symbolic_paths && (symbolic_paths.include? image_path)
return [image_path, {}]
elsif image_path == 'none'
return []
elsif (image_path.include? ':') && image_path =~ ImageAttributeValueRx
image_attrs = (AttributeList.new $2).parse %w(alt width)
if from_theme
image_path = sub_attributes_discretely doc, $1
image_relative_to = @themesdir
else
image_path = $1
image_relative_to = true
end
elsif from_theme
image_path = sub_attributes_discretely doc, image_path
image_relative_to = @themesdir
end
image_path, image_format = ::Asciidoctor::Image.target_and_format image_path, image_attrs
image_path = resolve_image_path doc, image_path, image_format, image_relative_to
return unless image_path
unless ::File.readable? image_path
logger.warn %(#{key.to_s.tr '-_', ' '} not found or readable: #{image_path})
return
end
if image_format == 'pdf'
[image_path, page: [((image_attrs || {})['page']).to_i, 1].max, format: image_format]
else
[image_path, (resolve_image_options image_path, image_format, image_attrs, (opts.merge background: true))]
end
end
end
def resolve_image_options image_path, image_format, image_attrs, opts = {}
if image_format == 'svg'
image_opts = {
enable_file_requests_with_root: (::File.dirname image_path),
enable_web_requests: allow_uri_read ? (method :load_open_uri).to_proc : false,
cache_images: cache_uri,
fallback_font_name: fallback_svg_font_name,
format: 'svg',
}
else
image_opts = {}
end
background = opts[:background]
container_size = opts[:container_size] || (background ? [page_width, page_height] : [bounds.width, bounds.height])
if image_attrs
if background && (image_pos = image_attrs['position']) && (image_pos = resolve_background_position image_pos, nil)
image_opts.update image_pos
end
if (image_fit = image_attrs['fit'] || (background ? 'contain' : nil))
image_fit = 'contain' if image_format == 'svg' && image_fit == 'fill'
container_width, container_height = container_size
case image_fit
when 'none'
if (image_width = resolve_explicit_width image_attrs, bounds_width: container_width)
image_opts[:width] = image_width
end
when 'scale-down'
# NOTE if width and height aren't set in SVG, real width and height are computed after stretching viewbox to fit page
if (image_width = resolve_explicit_width image_attrs, bounds_width: container_width) && image_width > container_width
image_opts[:fit] = container_size
elsif (image_size = intrinsic_image_dimensions image_path, image_format) &&
(image_width ? image_width * (image_size[:height].to_f / image_size[:width]) > container_height : (to_pt image_size[:width], :px) > container_width || (to_pt image_size[:height], :px) > container_height)
image_opts[:fit] = container_size
elsif image_width
image_opts[:width] = image_width
end
when 'cover'
# QUESTION should we take explicit width into account?
image_size = intrinsic_image_dimensions image_path, image_format
if container_width * (image_size[:height].to_f / image_size[:width]) < container_height
image_opts[:height] = container_height
else
image_opts[:width] = container_width
end
when 'fill'
image_opts[:width] = container_width
image_opts[:height] = container_height
else # when 'contain'
image_opts[:fit] = container_size
end
elsif (image_width = resolve_explicit_width image_attrs, bounds_width: container_size[0])
image_opts[:width] = image_width
else # default to fit=contain if sizing is not specified
image_opts[:fit] = container_size
end
else
image_opts[:fit] = container_size
end
image_opts
end
# Resolves the explicit width, if specified, as a PDF pt value.
#
# Resolves the explicit width, first considering the pdfwidth attribute, then the scaledwidth
# attribute, then the theme default (if enabled by the :use_fallback option), and finally the
# width attribute. If the specified value is in pixels, the value is scaled by 75% to perform
# approximate CSS px to PDF pt conversion. If the value is a percentage, and the
# bounds_width option is given, the percentage of the bounds_width value is returned.
# Otherwise, the percentage width is returned.
#--
# QUESTION should we enforce positive result?
def resolve_explicit_width attrs, opts = {}
bounds_width = opts[:bounds_width]
# QUESTION should we restrict width to bounds_width for pdfwidth?
if attrs.key? 'pdfwidth'
if (width = attrs['pdfwidth']).end_with? '%'
bounds_width ? (width.to_f / 100) * bounds_width : width
elsif opts[:support_vw] && (width.end_with? 'vw')
(width.chomp 'vw').extend ViewportWidth
else
str_to_pt width
end
elsif attrs.key? 'scaledwidth'
# NOTE the parser automatically appends % if value is unitless
if (width = attrs['scaledwidth']).end_with? '%'
bounds_width ? (width.to_f / 100) * bounds_width : width
else
str_to_pt width
end
elsif opts[:use_fallback] && (width = @theme.image_width)
if ::Numeric === width
width
elsif (width = width.to_s).end_with? '%'
bounds_width ? (width.to_f / 100) * bounds_width : bounds_width
elsif opts[:support_vw] && (width.end_with? 'vw')
(width.chomp 'vw').extend ViewportWidth
else
str_to_pt width
end
elsif attrs.key? 'width'
if (width = attrs['width']).end_with? '%'
width = (width.to_f / 100) * bounds_width if bounds_width
else
width = to_pt width.to_f, :px
end
bounds_width && opts[:constrain_to_bounds] ? [bounds_width, width].min : width
end
end
def resolve_background_position value, default_value = {}
if value.include? ' '
result = {}
center = nil
(value.split ' ', 2).each do |keyword|
if keyword == 'left' || keyword == 'right'
result[:position] = keyword.to_sym
elsif keyword == 'top' || keyword == 'bottom'
result[:vposition] = keyword.to_sym
elsif keyword == 'center'
center = true
end
end
if center
result[:position] ||= :center
result[:vposition] ||= :center
result
elsif (result.key? :position) && (result.key? :vposition)
result
else
default_value
end
elsif value == 'left' || value == 'right' || value == 'center'
{ position: value.to_sym, vposition: :center }
elsif value == 'top' || value == 'bottom'
{ position: :center, vposition: value.to_sym }
else
default_value
end
end
def resolve_top val
if val.end_with? 'vh'
page_height * (1 - (val.to_f / 100))
elsif val.end_with? '%'
@y - effective_page_height * (val.to_f / 100)
else
@y - (str_to_pt val)
end
end
def add_link_to_image uri, image_info, image_opts
image_width = image_info[:width]
image_height = image_info[:height]
case image_opts[:position]
when :center
image_x = bounds.left_side + (bounds.width - image_width) * 0.5
when :right
image_x = bounds.right_side - image_width
else # :left or not set
image_x = bounds.left_side
end
case image_opts[:vposition]
when :top
image_y = bounds.absolute_top
when :center
image_y = bounds.absolute_top - (bounds.height - image_height) * 0.5
when :bottom
image_y = bounds.absolute_bottom + image_height
else
image_y = y - image_opts[:vposition]
end unless (image_y = image_opts[:y])
link_annotation [image_x, (image_y - image_height), (image_x + image_width), image_y], Border: [0, 0, 0], A: { Type: :Action, S: :URI, URI: uri.as_pdf }
end
def load_open_uri
if @cache_uri && !(defined? ::OpenURI::Cache)
if (Helpers.require_library 'open-uri/cached', 'open-uri-cached', :warn).nil?
@cache_uri = false # disable since it failed to load
end
end
::OpenURI
end
def remove_tmp_files
@tmp_files.reject! {|_, path| path ? (unlink_tmp_file path) : true }
end
def unlink_tmp_file path
::File.unlink path if ::File.exist? path
true
rescue
logger.warn %(could not delete temporary file: #{path}; #{$!.message}) unless scratch?
false
end
def apply_subs_discretely doc, value, opts = {}
imagesdir = doc.attr 'imagesdir'
doc.set_attr 'imagesdir', @themesdir
# FIXME: get sub_attributes to handle drop-line w/o a warning
doc.set_attr 'attribute-missing', 'skip' unless (attribute_missing = doc.attr 'attribute-missing') == 'skip'
value = value.gsub '\{', '\\\\\\{' if (escaped_attr_ref = value.include? '\{')
value = doc.apply_subs value
value = (value.split LF).delete_if {|line| SimpleAttributeRefRx.match? line }.join LF if opts[:drop_lines_with_unresolved_attributes] && (value.include? '{')
value = value.gsub '\{', '{' if escaped_attr_ref
doc.set_attr 'attribute-missing', attribute_missing unless attribute_missing == 'skip'
if imagesdir
doc.set_attr 'imagesdir', imagesdir
else
doc.remove_attr 'imagesdir'
end
value
end
def sub_attributes_discretely doc, value
doc.set_attr 'attribute-missing', 'skip' unless (attribute_missing = doc.attr 'attribute-missing') == 'skip'
value = doc.apply_subs value, [:attributes]
doc.set_attr 'attribute-missing', attribute_missing unless attribute_missing == 'skip'
value
end
def promote_author doc, idx
doc.remove_attr 'url' if (original_url = doc.attr 'url')
email = nil
if idx > 1
original_attrs = AuthorAttributeNames.each_with_object({}) do |name, accum|
accum[name] = doc.attr name
if (val = doc.attr %(#{name}_#{idx}))
doc.set_attr name, val
# NOTE email holds url as well
email = val if name == 'email'
else
doc.remove_attr name
end
end
doc.set_attr 'url', ((email.include? '@') ? %(mailto:#{email}) : email) if email
result = yield
original_attrs.each {|name, val| val ? (doc.set_attr name, val) : (doc.remove_attr name) }
else
if (email = doc.attr 'email')
doc.set_attr 'url', ((email.include? '@') ? %(mailto:#{email}) : email)
end
result = yield
end
if original_url
doc.set_attr 'url', original_url
elsif email
doc.remove_attr 'url'
end
result
end
# NOTE assume URL is escaped (i.e., contains character references such as &)
def breakable_uri uri
scheme, address = uri.split UriSchemeBoundaryRx, 2
address, scheme = scheme, address unless address
unless address.nil_or_empty?
address = address.gsub UriBreakCharsRx, UriBreakCharRepl
# NOTE require at least two characters after a break
address.slice!(-2) if address[-2] == ZeroWidthSpace
end
%(#{scheme}#{address})
end
def consolidate_ranges nums
if nums.size > 1
prev = nil
nums.each_with_object([]) {|num, accum|
if prev && (prev.to_i + 1) == num.to_i
accum[-1][1] = num
else
accum << [num]
end
prev = num
}.map {|range| range.join '-' }
else
nums
end
end
def resolve_pagenums val
pgnums = []
((val.include? ',') ? (val.split ',') : (val.split ';')).each do |entry|
if entry.include? '..'
from, _, to = entry.partition '..'
pgnums += ([from.to_i, 1].max..[to.to_i, 1].max).to_a
else
pgnums << entry.to_i
end
end
pgnums
end
def get_char code
(code.start_with? '\u') ? ([((code.slice 2, code.length).to_i 16)].pack 'U1') : code
end
# QUESTION move to prawn/extensions.rb?
def init_scratch_prototype
@save_state = nil
@scratch_depth = 0
# NOTE don't need background image in scratch document; can cause marshal error anyway
saved_page_bg_image, @page_bg_image = @page_bg_image, { verso: nil, recto: nil }
# IMPORTANT don't set font before using Marshal, it causes serialization to fail
@prototype = ::Marshal.load ::Marshal.dump self
@page_bg_image = saved_page_bg_image
@prototype.state.store.info.data[:Scratch] = @prototype.text_formatter.scratch = true
# NOTE we're now starting a new page each time, so no need to do it here
#@prototype.start_new_page if @prototype.page_number == 0
end
def push_scratch doc
if (@scratch_depth += 1) == 1
@save_state = {
catalog: {}.tap {|accum| doc.catalog.each {|k, v| accum[k] = v.dup } },
attributes: doc.attributes.dup,
}
end
end
def pop_scratch doc
if (@scratch_depth -= 1) == 0
doc.catalog.replace @save_state[:catalog]
doc.attributes.replace @save_state[:attributes]
@save_state = nil
end
end
def clear_scratch
@scratch_depth = 0
@save_state = @prototype = @scratch = nil
end
end
end
end
simplify condition to find previous sibling in colist converter method
# frozen_string_literal: true
require_relative 'formatted_text'
require_relative 'index_catalog'
require_relative 'pdfmark'
require_relative 'roman_numeral'
require_relative 'section_info_by_page'
autoload :StringIO, 'stringio'
autoload :Tempfile, 'tempfile'
module Asciidoctor
module PDF
class Converter < ::Prawn::Document
include ::Asciidoctor::Converter
include ::Asciidoctor::Logging
include ::Asciidoctor::Writer
include ::Asciidoctor::Prawn::Extensions
register_for 'pdf'
attr_reader :allow_uri_read
attr_reader :cache_uri
attr_accessor :font_color
attr_accessor :font_scale
attr_reader :root_font_size
attr_reader :index
attr_reader :theme
attr_reader :text_decoration_width
# NOTE require_library doesn't support require_relative and we don't modify the load path for this gem
CodeRayRequirePath = ::File.join __dir__, 'ext/prawn/coderay_encoder'
RougeRequirePath = ::File.join __dir__, 'ext/rouge'
PygmentsRequirePath = ::File.join __dir__, 'ext/pygments'
OptimizerRequirePath = ::File.join __dir__, 'optimizer'
AdmonitionIcons = {
caution: { name: 'fas-fire', stroke_color: 'BF3400', size: 24 },
important: { name: 'fas-exclamation-circle', stroke_color: 'BF0000', size: 24 },
note: { name: 'fas-info-circle', stroke_color: '19407C', size: 24 },
tip: { name: 'far-lightbulb', stroke_color: '111111', size: 24 },
warning: { name: 'fas-exclamation-triangle', stroke_color: 'BF6900', size: 24 },
}
TextAlignmentNames = %w(justify left center right)
TextAlignmentRoles = %w(text-justify text-left text-center text-right)
TextDecorationStyleTable = { 'underline' => :underline, 'line-through' => :strikethrough }
FontKerningTable = { 'normal' => true, 'none' => false }
BlockAlignmentNames = %w(left center right)
(AlignmentTable = { '<' => :left, '=' => :center, '>' => :right }).default = :left
ColumnPositions = [:left, :center, :right]
PageLayouts = [:portrait, :landscape]
(PageModes = {
'fullscreen' => [:FullScreen, :UseOutlines],
'fullscreen none' => [:FullScreen, :UseNone],
'fullscreen outline' => [:FullScreen, :UseOutlines],
'fullscreen thumbs' => [:FullScreen, :UseThumbs],
'none' => :UseNone,
'outline' => :UseOutlines,
'thumbs' => :UseThumbs,
}).default = :UseOutlines
PageSides = [:recto, :verso]
(PDFVersions = { '1.3' => 1.3, '1.4' => 1.4, '1.5' => 1.5, '1.6' => 1.6, '1.7' => 1.7 }).default = 1.4
AuthorAttributeNames = %w(author authorinitials firstname middlename lastname email)
LF = ?\n
DoubleLF = LF * 2
TAB = ?\t
InnerIndent = LF + ' '
# a no-break space is used to replace a leading space to prevent Prawn from trimming indentation
# a leading zero-width space can't be used as it gets dropped when calculating the line width
GuardedIndent = ?\u00a0
GuardedInnerIndent = LF + GuardedIndent
TabRx = /\t/
TabIndentRx = /^\t+/
NoBreakSpace = ?\u00a0
ZeroWidthSpace = ?\u200b
DummyText = ?\u0000
DotLeaderTextDefault = '. '
EmDash = ?\u2014
RightPointer = ?\u25ba
LowercaseGreekA = ?\u03b1
Bullets = {
disc: ?\u2022,
circle: ?\u25e6,
square: ?\u25aa,
none: '',
}
# NOTE Default theme font uses ballot boxes from FontAwesome
BallotBox = {
checked: ?\u2611,
unchecked: ?\u2610,
}
ConumSets = {
'circled' => (?\u2460..?\u2473).to_a,
'filled' => (?\u2776..?\u277f).to_a + (?\u24eb..?\u24f4).to_a,
}
SimpleAttributeRefRx = /(?<!\\)\{\w+(?:[\-]\w+)*\}/
MeasurementRxt = '\\d+(?:\\.\\d+)?(?:in|cm|mm|p[txc])?'
MeasurementPartsRx = /^(\d+(?:\.\d+)?)(in|mm|cm|p[txc])?$/
PageSizeRx = /^(?:\[(#{MeasurementRxt}), ?(#{MeasurementRxt})\]|(#{MeasurementRxt})(?: x |x)(#{MeasurementRxt})|\S+)$/
CalloutExtractRx = /(?:(?:\/\/|#|--|;;) ?)?(\\)?<!?(|--)(\d+|\.)\2> ?(?=(?:\\?<!?\2(?:\d+|\.)\2>)*$)/
ImageAttributeValueRx = /^image:{1,2}(.*?)\[(.*?)\]$/
StopPunctRx = /[.!?;:]$/
UriBreakCharsRx = /(?:\/|\?|&|#)(?!$)/
UriBreakCharRepl = %(\\&#{ZeroWidthSpace})
UriSchemeBoundaryRx = /(?<=:\/\/)/
LineScanRx = /\n|.+/
BlankLineRx = /\n{2,}/
CjkLineBreakRx = /(?=[\u3000\u30a0-\u30ff\u3040-\u309f\p{Han}\uff00-\uffef])/
WhitespaceChars = ' ' + TAB + LF
ValueSeparatorRx = /;|,/
HexColorRx = /^#[a-fA-F0-9]{6}$/
VimeoThumbnailRx = /<thumbnail_large>(.*?)<\/thumbnail_large>/
SourceHighlighters = %w(coderay pygments rouge).to_set
ViewportWidth = ::Module.new
(TitleStyles = {
'toc' => [:numbered_title],
'basic' => [:title],
}).default = [:numbered_title, formal: true]
def initialize backend, opts
super
basebackend 'html'
filetype 'pdf'
htmlsyntax 'html'
outfilesuffix '.pdf'
if (doc = opts[:document])
# NOTE enabling data-uri forces Asciidoctor Diagram to produce absolute image paths
doc.attributes['data-uri'] = (doc.instance_variable_get :@attribute_overrides)['data-uri'] = ''
end
@initial_instance_variables = [:@initial_instance_variables] + instance_variables
end
def convert node, name = nil, _opts = {}
method_name = %(convert_#{name ||= node.node_name})
if respond_to? method_name
result = send method_name, node
else
# TODO: delegate to convert_method_missing
logger.warn %(missing convert handler for #{name} node in #{@backend} backend) unless scratch?
end
# NOTE: inline nodes generate pseudo-HTML strings; the remainder write directly to PDF object
::Asciidoctor::Inline === node ? result : self
end
def traverse node, opts = {}
# NOTE converter instance in scratch document gets duplicated; must be rewired to this one
if self == (prev_converter = node.document.converter)
prev_converter = nil
else
node.document.instance_variable_set :@converter, self
end
if node.blocks?
node.content
elsif node.content_model != :compound && (string = node.content)
# TODO: this content could be cached on repeat invocations!
layout_prose string, (opts.merge hyphenate: true)
end
ensure
node.document.instance_variable_set :@converter, prev_converter if prev_converter
end
def convert_document doc
init_pdf doc
# set default value for outline and pagenums if not otherwise set
doc.attributes['outline'] = '' unless (doc.attribute_locked? 'outline') || ((doc.instance_variable_get :@attributes_modified).include? 'outline')
doc.attributes['pagenums'] = '' unless (doc.attribute_locked? 'pagenums') || ((doc.instance_variable_get :@attributes_modified).include? 'pagenums')
#assign_missing_section_ids doc
# promote anonymous preface (defined using preamble block) to preface section
# FIXME: this should be done in core
if doc.doctype == 'book' && (blk0 = doc.blocks[0]) && blk0.context == :preamble && blk0.title? &&
!blk0.title.nil_or_empty? && blk0.blocks[0].style != 'abstract' && (blk1 = doc.blocks[1]) && blk1.context == :section
preface = Section.new doc, blk1.level, false, attributes: { 1 => 'preface', 'style' => 'preface' }
preface.special = true
preface.sectname = 'preface'
preface.title = blk0.instance_variable_get :@title
# QUESTION should ID be generated from raw or converted title? core is not clear about this
preface.id = preface.generate_id
preface.blocks.replace blk0.blocks.map {|b| b.parent = preface; b } # rubocop:disable Style/Semicolon
doc.blocks[0] = preface
blk0 = blk1 = preface = nil # rubocop:disable Lint/UselessAssignment
end
on_page_create(&(method :init_page))
marked_page_number = page_number
# NOTE: a new page will already be started (page_number = 2) if the front cover image is a PDF
layout_cover_page doc, :front
has_front_cover = page_number > marked_page_number
if (use_title_page = doc.doctype == 'book' || (doc.attr? 'title-page'))
layout_title_page doc
has_title_page = page_number == (has_front_cover ? 2 : 1)
end
@page_margin_by_side[:cover] = @page_margin_by_side[:recto] if @media == 'prepress' && page_number == 0
# NOTE: font must be set before content is written to the main or scratch document
start_new_page unless page.empty?
font @theme.base_font_family, size: @root_font_size, style: (@theme.base_font_style || :normal).to_sym
unless use_title_page
body_start_page_number = page_number
theme_font :heading, level: 1 do
layout_heading doc.doctitle, align: (@theme.heading_h1_align || :center).to_sym, level: 1
end if doc.header? && !doc.notitle
end
num_front_matter_pages = toc_page_nums = toc_num_levels = nil
indent_section do
toc_num_levels = (doc.attr 'toclevels', 2).to_i
if (insert_toc = (doc.attr? 'toc') && !(doc.attr? 'toc-placement', 'macro') && doc.sections?)
start_new_page if @ppbook && verso_page?
add_dest_for_block doc, 'toc'
allocate_toc doc, toc_num_levels, @y, use_title_page
else
@toc_extent = nil
end
start_new_page if @ppbook && verso_page?
if use_title_page
zero_page_offset = has_front_cover ? 1 : 0
first_page_offset = has_title_page ? zero_page_offset.next : zero_page_offset
body_offset = (body_start_page_number = page_number) - 1
if ::Integer === (running_content_start_at = @theme.running_content_start_at || 'body')
running_content_body_offset = body_offset + [running_content_start_at.pred, 1].max
running_content_start_at = 'body'
else
running_content_body_offset = body_offset
running_content_start_at = 'toc' if running_content_start_at == 'title' && !has_title_page
running_content_start_at = 'body' if running_content_start_at == 'toc' && !insert_toc
end
if ::Integer === (page_numbering_start_at = @theme.page_numbering_start_at || 'body')
page_numbering_body_offset = body_offset + [page_numbering_start_at.pred, 1].max
page_numbering_start_at = 'body'
else
page_numbering_body_offset = body_offset
page_numbering_start_at = 'toc' if page_numbering_start_at == 'title' && !has_title_page
page_numbering_start_at = 'body' if page_numbering_start_at == 'toc' && !insert_toc
end
front_matter_sig = [running_content_start_at, page_numbering_start_at]
# table values are number of pages to skip before starting running content and page numbering, respectively
num_front_matter_pages = {
%w(title title) => [zero_page_offset, zero_page_offset],
%w(title toc) => [zero_page_offset, first_page_offset],
%w(title body) => [zero_page_offset, page_numbering_body_offset],
%w(toc title) => [first_page_offset, zero_page_offset],
%w(toc toc) => [first_page_offset, first_page_offset],
%w(toc body) => [first_page_offset, page_numbering_body_offset],
%w(body title) => [running_content_body_offset, zero_page_offset],
%w(body toc) => [running_content_body_offset, first_page_offset],
}[front_matter_sig] || [running_content_body_offset, page_numbering_body_offset]
else
body_offset = body_start_page_number - 1
if ::Integer === (running_content_start_at = @theme.running_content_start_at || 'body')
running_content_body_offset = body_offset + [running_content_start_at.pred, 1].max
else
running_content_body_offset = body_offset
end
if ::Integer === (page_numbering_start_at = @theme.page_numbering_start_at || 'body')
page_numbering_body_offset = body_offset + [page_numbering_start_at.pred, 1].max
else
page_numbering_body_offset = body_offset
end
num_front_matter_pages = [running_content_body_offset, page_numbering_body_offset]
end
@index.start_page_number = num_front_matter_pages[1] + 1
doc.set_attr 'pdf-anchor', (doc_anchor = derive_anchor_from_id doc.id, 'top')
add_dest_for_block doc, doc_anchor
convert_section generate_manname_section doc if doc.doctype == 'manpage' && (doc.attr? 'manpurpose')
traverse doc
# NOTE: for a book, these are leftover footnotes; for an article this is everything
outdent_section { layout_footnotes doc }
toc_page_nums = @toc_extent ? (layout_toc doc, toc_num_levels, @toc_extent[:page_nums].first, @toc_extent[:start_y], num_front_matter_pages[1]) : []
# NOTE: delete orphaned page (a page was created but there was no additional content)
# QUESTION should we delete page if document is empty? (leaving no pages?)
delete_page if page_count > 1 && page.empty?
end
unless page_count < body_start_page_number
layout_running_content :header, doc, skip: num_front_matter_pages, body_start_page_number: body_start_page_number unless doc.noheader || @theme.header_height.to_f == 0
layout_running_content :footer, doc, skip: num_front_matter_pages, body_start_page_number: body_start_page_number unless doc.nofooter || @theme.footer_height.to_f == 0
end
add_outline doc, (doc.attr 'outlinelevels', toc_num_levels), toc_page_nums, num_front_matter_pages[1], has_front_cover
if (initial_zoom = @theme.page_initial_zoom)
case initial_zoom.to_sym
when :Fit
catalog.data[:OpenAction] = dest_fit state.pages[0]
when :FitV
catalog.data[:OpenAction] = dest_fit_vertically 0, state.pages[0]
when :FitH
catalog.data[:OpenAction] = dest_fit_horizontally page_height, state.pages[0]
end
end
catalog.data[:ViewerPreferences] = { DisplayDocTitle: true }
stamp_foreground_image doc, has_front_cover
layout_cover_page doc, :back
nil
end
# NOTE: embedded only makes sense if perhaps we are building
# on an existing Prawn::Document instance; for now, just treat
# it the same as a full document.
alias convert_embedded convert_document
def init_pdf doc
(instance_variables - @initial_instance_variables).each {|ivar| remove_instance_variable ivar } if state
pdf_opts = build_pdf_options doc, (theme = load_theme doc)
# QUESTION should page options be preserved? (otherwise, not readily available)
#@page_opts = { size: pdf_opts[:page_size], layout: pdf_opts[:page_layout] }
((::Prawn::Document.instance_method :initialize).bind self).call pdf_opts
renderer.min_version (@pdf_version = PDFVersions[doc.attr 'pdf-version'])
@page_margin_by_side = { recto: page_margin, verso: page_margin, cover: page_margin }
if (@media = doc.attr 'media', 'screen') == 'prepress'
@ppbook = doc.doctype == 'book'
page_margin_recto = @page_margin_by_side[:recto]
if (page_margin_outer = theme.page_margin_outer)
page_margin_recto[1] = @page_margin_by_side[:verso][3] = page_margin_outer
end
if (page_margin_inner = theme.page_margin_inner)
page_margin_recto[3] = @page_margin_by_side[:verso][1] = page_margin_inner
end
# NOTE: prepare scratch document to use page margin from recto side (which has same width as verso side)
set_page_margin page_margin_recto unless page_margin_recto == page_margin
else
@ppbook = nil
end
# QUESTION should ThemeLoader handle registering fonts instead?
register_fonts theme.font_catalog, (doc.attr 'pdf-fontsdir', 'GEM_FONTS_DIR')
default_kerning theme.base_font_kerning != 'none'
@fallback_fonts = [*theme.font_fallbacks]
@allow_uri_read = doc.attr? 'allow-uri-read'
@cache_uri = doc.attr? 'cache-uri'
@tmp_files = {}
if (bg_image = resolve_background_image doc, theme, 'page-background-image') && bg_image[0]
@page_bg_image = { verso: bg_image, recto: bg_image }
else
@page_bg_image = { verso: nil, recto: nil }
end
if (bg_image = resolve_background_image doc, theme, 'page-background-image-verso')
@page_bg_image[:verso] = bg_image[0] && bg_image
end
if (bg_image = resolve_background_image doc, theme, 'page-background-image-recto')
@page_bg_image[:recto] = bg_image[0] && bg_image
end
@page_bg_color = resolve_theme_color :page_background_color, 'FFFFFF'
@root_font_size = theme.base_font_size || 12
@font_scale = 1
@font_color = theme.base_font_color || '000000'
@text_decoration_width = theme.base_text_decoration_width
@base_align = (align = doc.attr 'text-align') && (TextAlignmentNames.include? align) ? align : theme.base_align
@cjk_line_breaks = doc.attr? 'scripts', 'cjk'
if (hyphen_lang = doc.attr 'hyphens') &&
((defined? ::Text::Hyphen::VERSION) || !(Helpers.require_library 'text/hyphen', 'text-hyphen', :warn).nil?)
hyphen_lang = doc.attr 'lang' if hyphen_lang.empty?
hyphen_lang = 'en_us' if hyphen_lang.nil_or_empty? || hyphen_lang == 'en'
hyphen_lang = (hyphen_lang.tr '-', '_').downcase
@hyphenator = ::Text::Hyphen.new language: hyphen_lang
end
@text_transform = nil
@list_numerals = []
@list_bullets = []
@rendered_footnotes = []
@conum_glyphs = ConumSets[@theme.conum_glyphs || 'circled'] || (@theme.conum_glyphs.split ',').map {|r|
from, to = r.rstrip.split '-', 2
to ? ((get_char from)..(get_char to)).to_a : [(get_char from)]
}.flatten
@section_indent = (val = @theme.section_indent) && (expand_indent_value val)
@toc_max_pagenum_digits = (doc.attr 'toc-max-pagenum-digits', 3).to_i
@disable_running_content = {}
@index ||= IndexCatalog.new
# NOTE: we have to init Pdfmark class here while we have reference to the doc
@pdfmark = (doc.attr? 'pdfmark') ? (Pdfmark.new doc) : nil
@optimize = doc.attr 'optimize'
init_scratch_prototype
self
end
def load_theme doc
@theme ||= begin # rubocop:disable Naming/MemoizedInstanceVariableName
if (theme = doc.options[:pdf_theme])
@themesdir = ::File.expand_path theme.__dir__ || (doc.attr 'pdf-themesdir') || (doc.attr 'pdf-stylesdir') || ::Dir.pwd
elsif (theme_name = (doc.attr 'pdf-theme') || (doc.attr 'pdf-style'))
theme = ThemeLoader.load_theme theme_name, (user_themesdir = (doc.attr 'pdf-themesdir') || (doc.attr 'pdf-stylesdir'))
@themesdir = theme.__dir__
else
@themesdir = (theme = ThemeLoader.load_theme).__dir__
end
theme
rescue
if user_themesdir
message = %(could not locate or load the pdf theme `#{theme_name}' in #{user_themesdir})
else
message = %(could not locate or load the built-in pdf theme `#{theme_name}')
end
message += %( because of #{$!.class} #{$!.message}) unless ::SystemCallError === $!
logger.error %(#{message}; reverting to default theme)
@themesdir = (theme = ThemeLoader.load_theme).__dir__
theme
end
end
def build_pdf_options doc, theme
case (page_margin = (doc.attr 'pdf-page-margin') || theme.page_margin)
when ::Array
if page_margin.empty?
page_margin = nil
else
page_margin = page_margin.slice 0, 4 if page_margin.length > 4
page_margin = page_margin.map {|v| ::Numeric === v ? v : (str_to_pt v.to_s) }
end
when ::Numeric
page_margin = [page_margin]
when ::String
if page_margin.empty?
page_margin = nil
elsif (page_margin.start_with? '[') && (page_margin.end_with? ']')
if (page_margin = (page_margin.slice 1, page_margin.length - 2).rstrip).empty?
page_margin = nil
else
if (page_margin = page_margin.split ',', -1).length > 4
page_margin = page_margin.slice 0, 4
end
page_margin = page_margin.map {|v| str_to_pt v.rstrip }
end
else
page_margin = [(str_to_pt page_margin)]
end
else
page_margin = nil
end
if (doc.attr? 'pdf-page-size') && PageSizeRx =~ (doc.attr 'pdf-page-size')
# e.g, [8.5in, 11in]
if $1
page_size = [$1, $2]
# e.g, 8.5in x 11in
elsif $3
page_size = [$3, $4]
# e.g, A4
else
page_size = $&
end
else
page_size = theme.page_size
end
case page_size
when ::String, ::Symbol
# TODO: extract helper method to check for named page size
page_size = page_size.to_s.upcase
page_size = nil unless ::PDF::Core::PageGeometry::SIZES.key? page_size
when ::Array
if page_size.empty?
page_size = nil
else
page_size[1] ||= page_size[0]
page_size = (page_size.slice 0, 2).map do |dim|
if ::Numeric === dim
# dimension cannot be less than 0
dim > 0 ? dim : break
elsif ::String === dim && MeasurementPartsRx =~ dim
# NOTE: truncate to max precision retained by PDF::Core
(dim = (to_pt $1.to_f, $2).truncate 4) > 0 ? dim : break
else
break
end
end
end
else
page_size = nil
end
if (page_layout = (doc.attr 'pdf-page-layout') || theme.page_layout).nil_or_empty? ||
!PageLayouts.include?(page_layout = page_layout.to_sym)
page_layout = nil
end
{
margin: (page_margin || 36),
page_size: (page_size || 'A4'),
page_layout: (page_layout || :portrait),
info: (build_pdf_info doc),
compress: (doc.attr? 'compress'),
skip_page_creation: true,
text_formatter: (FormattedText::Formatter.new theme: theme),
}
end
# FIXME: Pdfmark should use the PDF info result
def build_pdf_info doc
info = {}
if (doctitle = doc.header? ? doc.doctitle : (doc.attr 'untitled-label'))
info[:Title] = (sanitize doctitle).as_pdf
end
info[:Author] = (sanitize doc.attr 'authors').as_pdf if doc.attr? 'authors'
info[:Subject] = (sanitize doc.attr 'subject').as_pdf if doc.attr? 'subject'
info[:Keywords] = (sanitize doc.attr 'keywords').as_pdf if doc.attr? 'keywords'
info[:Producer] = (sanitize doc.attr 'publisher').as_pdf if doc.attr? 'publisher'
if doc.attr? 'reproducible'
info[:Creator] = 'Asciidoctor PDF, based on Prawn'.as_pdf
info[:Producer] ||= (info[:Author] || info[:Creator])
else
info[:Creator] = %(Asciidoctor PDF #{::Asciidoctor::PDF::VERSION}, based on Prawn #{::Prawn::VERSION}).as_pdf
info[:Producer] ||= (info[:Author] || info[:Creator])
# NOTE: since we don't track the creation date of the input file, we map the ModDate header to the last modified
# date of the input document and the CreationDate header to the date the PDF was produced by the converter.
info[:ModDate] = (::Time.parse doc.attr 'docdatetime') rescue (now ||= ::Time.now)
info[:CreationDate] = (::Time.parse doc.attr 'localdatetime') rescue (now || ::Time.now)
end
info
end
# NOTE: init_page is called within a float context
# NOTE: init_page is not called for imported pages, front and back cover pages, and other image pages
def init_page *_args
# NOTE: we assume in prepress that physical page number reflects page side
if @media == 'prepress' &&
(next_page_margin = @page_margin_by_side[page_number == 1 ? :cover : page_side]) != page_margin
set_page_margin next_page_margin
end
unless @page_bg_color == 'FFFFFF'
tare = true
fill_absolute_bounds @page_bg_color
end
if (bg_image = @page_bg_image[page_side])
tare = true
# NOTE: float is necessary since prawn-svg may mess with cursor position
float { canvas { image bg_image[0], ({ position: :center, vposition: :center }.merge bg_image[1]) } }
end
page.tare_content_stream if tare
end
def convert_section sect, _opts = {}
if sect.sectname == 'abstract'
# HACK: cheat a bit to hide this section from TOC; TOC should filter these sections
sect.context = :open
return convert_abstract sect
elsif (index_section = sect.sectname == 'index')
return if @index.empty?
end
type = nil
title = sect.numbered_title formal: true
sep = (sect.attr 'separator') || (sect.document.attr 'title-separator') || ''
if !sep.empty? && title.include?(sep = %(#{sep} ))
title, _, subtitle = title.rpartition sep
title = %(#{title}\n<em class="subtitle">#{subtitle}</em>)
end
theme_font :heading, level: (hlevel = sect.level + 1) do
align = (@theme[%(heading_h#{hlevel}_align)] || @theme.heading_align || @base_align).to_sym
if sect.part_or_chapter?
if sect.chapter?
type = :chapter
if @theme.heading_chapter_break_before == 'auto'
start_new_chapter sect if @theme.heading_part_break_after == 'always' && sect == sect.parent.sections[0]
else
start_new_chapter sect
end
else
type = :part
start_new_part sect unless @theme.heading_part_break_before == 'auto'
end
end
unless at_page_top?
# FIXME: this height doesn't account for impact of text transform or inline formatting
heading_height =
(height_of_typeset_text title, line_height: (@theme[%(heading_h#{hlevel}_line_height)] || @theme.heading_line_height)) +
(@theme[%(heading_h#{hlevel}_margin_top)] || @theme.heading_margin_top || 0) +
(@theme[%(heading_h#{hlevel}_margin_bottom)] || @theme.heading_margin_bottom || 0)
heading_height += (@theme.heading_min_height_after || 0) if sect.blocks?
start_new_page unless cursor > heading_height
end
# QUESTION should we store pdf-page-start, pdf-anchor & pdf-destination in internal map?
sect.set_attr 'pdf-page-start', (start_pgnum = page_number)
# QUESTION should we just assign the section this generated id?
# NOTE: section must have pdf-anchor in order to be listed in the TOC
sect.set_attr 'pdf-anchor', (sect_anchor = derive_anchor_from_id sect.id, %(#{start_pgnum}-#{y.ceil}))
add_dest_for_block sect, sect_anchor
if type == :part
layout_part_title sect, title, align: align, level: hlevel
elsif type == :chapter
layout_chapter_title sect, title, align: align, level: hlevel
else
layout_heading title, align: align, level: hlevel, outdent: true
end
end
if index_section
outdent_section { convert_index_section sect }
else
traverse sect
end
outdent_section { layout_footnotes sect } if type == :chapter
sect.set_attr 'pdf-page-end', page_number
end
def indent_section
if (values = @section_indent)
indent(values[0], values[1]) { yield }
else
yield
end
end
def outdent_section enabled = true
if enabled && (values = @section_indent)
indent(-values[0], -values[1]) { yield }
else
yield
end
end
# QUESTION if a footnote ref appears in a separate chapter, should the footnote def be duplicated?
def layout_footnotes node
return if (fns = (doc = node.document).footnotes - @rendered_footnotes).empty?
theme_margin :footnotes, :top
theme_font :footnotes do
(title = doc.attr 'footnotes-title') && (layout_caption title, category: :footnotes)
item_spacing = @theme.footnotes_item_spacing || 0
index_offset = @rendered_footnotes.length
sect_xreftext = node.context == :section && (node.xreftext node.document.attr 'xrefstyle')
fns.each do |fn|
label = (index = fn.index) - index_offset
if sect_xreftext
fn.singleton_class.send :attr_accessor, :label unless fn.respond_to? :label=
fn.label = %(#{label} - #{sect_xreftext})
end
layout_prose %(<a id="_footnotedef_#{index}">#{DummyText}</a>[<a anchor="_footnoteref_#{index}">#{label}</a>] #{fn.text}), margin_bottom: item_spacing, hyphenate: true
end
@rendered_footnotes += fns
end
nil
end
def convert_floating_title node
add_dest_for_block node if node.id
hlevel = node.level.next
unless (align = resolve_alignment_from_role node.roles)
align = (@theme[%(heading_h#{hlevel}_align)] || @theme.heading_align || @base_align).to_sym
end
# QUESTION should we decouple styles from section titles?
theme_font :heading, level: hlevel do
layout_heading node.title, align: align, level: hlevel, outdent: (node.parent.context == :section)
end
end
def convert_abstract node
add_dest_for_block node if node.id
outdent_section do
pad_box @theme.abstract_padding do
theme_font :abstract_title do
layout_prose node.title, align: (@theme.abstract_title_align || @base_align).to_sym, margin_top: (@theme.heading_margin_top || 0), margin_bottom: (@theme.heading_margin_bottom || 0), line_height: @theme.heading_line_height
end if node.title?
theme_font :abstract do
prose_opts = { line_height: @theme.abstract_line_height, align: (@theme.abstract_align || @base_align).to_sym, hyphenate: true }
if (text_indent = @theme.prose_text_indent || 0) > 0
prose_opts[:indent_paragraphs] = text_indent
end
# FIXME: allow theme to control more first line options
if (line1_font_style = @theme.abstract_first_line_font_style) && line1_font_style.to_sym != font_style
first_line_options = { styles: [font_style, line1_font_style.to_sym] }
end
if (line1_font_color = @theme.abstract_first_line_font_color)
(first_line_options ||= {})[:color] = line1_font_color
end
prose_opts[:first_line_options] = first_line_options if first_line_options
# FIXME: make this cleaner!!
if node.blocks?
node.blocks.each do |child|
if child.context == :paragraph
child.document.playback_attributes child.attributes
layout_prose child.content, ((align = resolve_alignment_from_role child.roles) ? (prose_opts.merge align: align) : prose_opts.dup)
prose_opts.delete :first_line_options
else
# FIXME: this could do strange things if the wrong kind of content shows up
child.convert
end
end
elsif node.content_model != :compound && (string = node.content)
if (align = resolve_alignment_from_role node.roles)
prose_opts[:align] = align
end
layout_prose string, prose_opts
end
end
end
# QUESTION should we be adding margin below the abstract??
#theme_margin :block, :bottom
end
end
def convert_preamble node
# FIXME: core should not be promoting paragraph to preamble if there are no sections
if node.blocks? && (first_block = node.blocks[0]).context == :paragraph && node.document.sections?
first_block.add_role 'lead' unless first_block.role?
end
traverse node
end
def convert_paragraph node
add_dest_for_block node if node.id
prose_opts = { margin_bottom: 0, hyphenate: true }
lead = (roles = node.roles).include? 'lead'
if (align = resolve_alignment_from_role roles)
prose_opts[:align] = align
end
if (text_indent = @theme.prose_text_indent || 0) > 0
prose_opts[:indent_paragraphs] = text_indent
end
# TODO: check if we're within one line of the bottom of the page
# and advance to the next page if so (similar to logic for section titles)
layout_caption node, labeled: false if node.title?
if lead
theme_font :lead do
layout_prose node.content, prose_opts
end
else
layout_prose node.content, prose_opts
end
if (margin_inner_val = @theme.prose_margin_inner) &&
(next_block = (siblings = node.parent.blocks)[(siblings.index node) + 1]) && next_block.context == :paragraph
margin_bottom margin_inner_val
else
margin_bottom @theme.prose_margin_bottom
end
end
def convert_admonition node
add_dest_for_block node if node.id
theme_margin :block, :top
type = node.attr 'name'
label_align = (@theme.admonition_label_align || :center).to_sym
# TODO: allow vertical_align to be a number
if (label_valign = (@theme.admonition_label_vertical_align || :middle).to_sym) == :middle
label_valign = :center
end
if (label_min_width = @theme.admonition_label_min_width)
label_min_width = label_min_width.to_f
end
icons = ((doc = node.document).attr? 'icons') ? (doc.attr 'icons') : nil
if (data_uri_enabled = doc.attr? 'data-uri')
doc.remove_attr 'data-uri'
end
if icons == 'font' && !(node.attr? 'icon')
label_text = type.to_sym
icon_data = admonition_icon_data label_text
icon_size = icon_data[:size] || 24
label_width = label_min_width || (icon_size * 1.5)
# NOTE: icon_uri will consider icon attribute on node first, then type
# QUESTION should we use resolve_image_path here?
elsif icons && (icon_path = node.icon_uri type) &&
(icon_path = node.normalize_system_path icon_path, nil, nil, target_name: 'admonition icon') &&
(::File.readable? icon_path)
icons = true
# TODO: introduce @theme.admonition_image_width? or use size key from admonition_icon_<name>?
label_width = label_min_width || 36.0
else
if icons
icons = nil
logger.warn %(admonition icon not found or not readable: #{icon_path}) unless scratch?
end
label_text = sanitize node.caption
theme_font :admonition_label do
theme_font %(admonition_label_#{type}) do
label_text = transform_text label_text, @text_transform if @text_transform
label_width = rendered_width_of_string label_text
label_width = label_min_width if label_min_width && label_min_width > label_width
end
end
end
doc.set_attr 'data-uri', '' if data_uri_enabled
unless ::Array === (cpad = @theme.admonition_padding)
cpad = ::Array.new 4, cpad
end
unless ::Array === (lpad = @theme.admonition_label_padding || cpad)
lpad = ::Array.new 4, lpad
end
# FIXME: this shift stuff is a real hack until we have proper margin collapsing
shift_base = @theme.prose_margin_bottom
shift_top = shift_base / 3.0
shift_bottom = (shift_base * 2) / 3.0
keep_together do |box_height = nil|
push_scratch doc if scratch?
theme_fill_and_stroke_block :admonition, box_height if box_height
pad_box [0, cpad[1], 0, lpad[3]] do
if box_height
label_height = [box_height, cursor].min
if (rule_color = @theme.admonition_column_rule_color) &&
(rule_width = @theme.admonition_column_rule_width || @theme.base_border_width) && rule_width > 0
float do
rule_height = box_height
while rule_height > 0
rule_segment_height = [rule_height, cursor].min
bounding_box [0, cursor], width: label_width + lpad[1], height: rule_segment_height do
stroke_vertical_rule rule_color,
at: bounds.right,
line_style: (@theme.admonition_column_rule_style || :solid).to_sym,
line_width: rule_width
end
advance_page if (rule_height -= rule_segment_height) > 0
end
end
end
float do
bounding_box [0, cursor], width: label_width, height: label_height do
if icons == 'font'
# FIXME: we assume icon is square
icon_size = fit_icon_to_bounds icon_size
# NOTE: Prawn's vertical center is not reliable, so calculate it manually
if label_valign == :center
label_valign = :top
if (vcenter_pos = (label_height - icon_size) * 0.5) > 0
move_down vcenter_pos
end
end
icon icon_data[:name],
valign: label_valign,
align: label_align,
color: (icon_data[:stroke_color] || font_color),
size: icon_size
elsif icons
if (::Asciidoctor::Image.format icon_path) == 'svg'
begin
svg_obj = ::Prawn::SVG::Interface.new ::File.read(icon_path, mode: 'r:UTF-8'), self,
position: label_align,
vposition: label_valign,
width: label_width,
height: label_height,
fallback_font_name: fallback_svg_font_name,
enable_web_requests: allow_uri_read ? (method :load_open_uri).to_proc : false,
enable_file_requests_with_root: (::File.dirname icon_path),
cache_images: cache_uri
if (icon_height = (svg_size = svg_obj.document.sizing).output_height) > label_height
icon_width = (svg_obj.resize height: (icon_height = label_height)).output_width
else
icon_width = svg_size.output_width
end
svg_obj.draw
svg_obj.document.warnings.each do |icon_warning|
logger.warn %(problem encountered in image: #{icon_path}; #{icon_warning})
end unless scratch?
rescue
logger.warn %(could not embed admonition icon: #{icon_path}; #{$!.message}) unless scratch?
end
else
begin
image_obj, image_info = ::File.open(icon_path, 'rb') {|fd| build_image_object fd }
icon_aspect_ratio = image_info.width.fdiv image_info.height
# NOTE: don't scale image up if smaller than label_width
icon_width = [(to_pt image_info.width, :px), label_width].min
if (icon_height = icon_width * (1 / icon_aspect_ratio)) > label_height
icon_width *= label_height / icon_height
icon_height = label_height # rubocop:disable Lint/UselessAssignment
end
embed_image image_obj, image_info, width: icon_width, position: label_align, vposition: label_valign
rescue
# QUESTION should we show the label in this case?
logger.warn %(could not embed admonition icon: #{icon_path}; #{$!.message}) unless scratch?
end
end
else
# IMPORTANT the label must fit in the alotted space or it shows up on another page!
# QUESTION anyway to prevent text overflow in the case it doesn't fit?
theme_font :admonition_label do
theme_font %(admonition_label_#{type}) do
# NOTE: Prawn's vertical center is not reliable, so calculate it manually
if label_valign == :center
label_valign = :top
if (vcenter_pos = (label_height - (height_of_typeset_text label_text, line_height: 1)) * 0.5) > 0
move_down vcenter_pos
end
end
@text_transform = nil # already applied to label
layout_prose label_text,
align: label_align,
valign: label_valign,
line_height: 1,
margin: 0,
inline_format: false # already replaced character references
end
end
end
end
end
end
pad_box [cpad[0], 0, cpad[2], label_width + lpad[1] + cpad[3]] do
move_down shift_top
layout_caption node, category: :admonition, labeled: false if node.title?
theme_font :admonition do
traverse node
end
# FIXME: HACK compensate for margin bottom of admonition content
move_up shift_bottom unless at_page_top?
end
end
pop_scratch doc if scratch?
end
theme_margin :block, :bottom
end
def convert_example node
return convert_open node if node.option? 'collapsible'
add_dest_for_block node if node.id
theme_margin :block, :top
caption_height = node.title? ? (layout_caption node, category: :example, dry_run: true) : 0
keep_together do |box_height = nil|
push_scratch node.document if scratch?
if box_height
theme_fill_and_stroke_block :example, box_height, caption_node: node
else
move_down caption_height
end
pad_box @theme.example_padding do
theme_font :example do
traverse node
end
end
pop_scratch node.document if scratch?
end
theme_margin :block, :bottom
end
def convert_open node
return convert_abstract node if node.style == 'abstract'
doc = node.document
keep_together_if node.option? 'unbreakable' do
push_scratch doc if scratch?
add_dest_for_block node if node.id
node.context == :example ? (layout_caption %(\u25bc #{node.title})) : (layout_caption node, labeled: false) if node.title?
traverse node
pop_scratch doc if scratch?
end
end
def convert_quote_or_verse node
add_dest_for_block node if node.id
theme_margin :block, :top
category = node.context == :quote ? :blockquote : :verse
# NOTE: b_width and b_left_width are mutually exclusive
unless (b_left_width = @theme[%(#{category}_border_left_width)]) && b_left_width > 0
b_left_width = nil
if (b_width = @theme[%(#{category}_border_width)])
b_width = nil unless b_width > 0
end
end
keep_together do |box_height = nil|
push_scratch node.document if scratch?
theme_fill_and_stroke_block category, box_height, border_width: b_width if box_height && (b_width || @theme[%(#{category}_background_color)])
start_page_number = page_number
start_cursor = cursor
caption_height = node.title? ? (layout_caption node, category: category, labeled: false) : 0
pad_box @theme[%(#{category}_padding)] do
theme_font category do
if category == :blockquote
traverse node
else # verse
content = guard_indentation node.content
layout_prose content, normalize: false, align: :left, hyphenate: true
end
end
if node.attr? 'attribution'
theme_font %(#{category}_cite) do
# NOTE temporary workaround to allow bare & to be used without having to wrap value in single quotes
attribution = node.attr 'attribution'
attribution = escape_amp attribution if attribution.include? '&'
attribution_parts = [attribution]
if (citetitle = node.attr 'citetitle')
citetitle = escape_amp citetitle if citetitle.include? '&'
attribution_parts << citetitle
end
layout_prose %(#{EmDash} #{attribution_parts.join ', '}), align: :left, normalize: false
end
end
end
# FIXME: we want to draw graphics before content, but box_height is not reliable when spanning pages
# FIXME: border extends to bottom of content area if block terminates at bottom of page
if box_height && b_left_width
b_color = @theme[%(#{category}_border_color)]
page_spread = page_number - start_page_number + 1
end_cursor = cursor
go_to_page start_page_number
move_cursor_to start_cursor
page_spread.times do |i|
if i == 0
y_draw = cursor
b_height = page_spread > 1 ? y_draw : (y_draw - end_cursor)
else
bounds.move_past_bottom
y_draw = cursor
b_height = page_spread - 1 == i ? (y_draw - end_cursor) : y_draw
end
# NOTE: skip past caption if present
if caption_height > 0
if caption_height > cursor
caption_height -= cursor
next # keep skipping, caption is on next page
end
y_draw -= caption_height
b_height -= caption_height
caption_height = 0
end
# NOTE: b_height is 0 when block terminates at bottom of page
next if b_height == 0
bounding_box [0, y_draw], width: bounds.width, height: b_height do
stroke_vertical_rule b_color, line_width: b_left_width, at: b_left_width * 0.5
end
end
end
pop_scratch node.document if scratch?
end
theme_margin :block, :bottom
end
alias convert_quote convert_quote_or_verse
alias convert_verse convert_quote_or_verse
def convert_sidebar node
add_dest_for_block node if node.id
theme_margin :block, :top
keep_together do |box_height = nil|
push_scratch node.document if scratch?
theme_fill_and_stroke_block :sidebar, box_height if box_height
pad_box @theme.sidebar_padding do
theme_font :sidebar_title do
# QUESTION should we allow margins of sidebar title to be customized?
layout_prose node.title, align: (@theme.sidebar_title_align || @base_align).to_sym, margin_top: 0, margin_bottom: (@theme.heading_margin_bottom || 0), line_height: @theme.heading_line_height
end if node.title?
theme_font :sidebar do
traverse node
end
end
pop_scratch node.document if scratch?
end
theme_margin :block, :bottom
end
def convert_colist node
# HACK: undo the margin below previous listing or literal block
# TODO: allow this to be set using colist_margin_top
if (self_idx = (node.parent.blocks.index node) || -1) > 0 &&
[:listing, :literal].include?(node.parent.blocks[self_idx - 1].context)
move_up @theme.block_margin_bottom - @theme.outline_list_item_spacing
end unless at_page_top?
add_dest_for_block node if node.id
@list_numerals << 1
line_metrics = theme_font(:conum) { calc_line_metrics @theme.base_line_height }
node.items.each do |item|
allocate_space_for_list_item line_metrics
convert_colist_item item
end
@list_numerals.pop
# correct bottom margin of last item
list_margin_bottom = @theme.prose_margin_bottom
margin_bottom list_margin_bottom - @theme.outline_list_item_spacing
end
def convert_colist_item node
marker_width = nil
@list_numerals << (index = @list_numerals.pop).next
theme_font :conum do
marker_width = rendered_width_of_string %(#{marker = conum_glyph index}x)
float do
bounding_box [0, cursor], width: marker_width do
theme_font :conum do
layout_prose marker, align: :center, line_height: @theme.conum_line_height, inline_format: false, margin: 0
end
end
end
end
indent marker_width do
traverse_list_item node, :colist, margin_bottom: @theme.outline_list_item_spacing, normalize_line_height: true
end
end
def convert_dlist node
add_dest_for_block node if node.id
case (style = node.style)
when 'unordered', 'ordered'
if style == 'unordered'
list_style = :ulist
(markers = @list_bullets) << :disc
else
list_style = :olist
(markers = @list_numerals) << 1
end
list = List.new node.parent, list_style
stack_subject = node.has_role? 'stack'
subject_stop = node.attr 'subject-stop', (stack_subject ? nil : ':')
node.items.each do |subjects, dd|
subject = [*subjects].first.text
if dd
list_item_text = %(+++<strong>#{subject}#{(StopPunctRx.match? sanitize subject) ? '' : subject_stop}</strong>#{dd.text? ? "#{stack_subject ? '<br>' : ' '}#{dd.text}" : ''}+++)
list_item = ListItem.new list, list_item_text
dd.blocks.each {|it| list_item << it } if dd.blocks?
else
list_item = ListItem.new list, %(+++<strong>#{subject}</strong>+++)
end
list << list_item
end
convert_outline_list list
markers.pop
when 'horizontal'
table_data = []
term_padding = desc_padding = term_line_metrics = term_inline_format = term_kerning = nil
max_term_width = 0
theme_font :description_list_term do
term_inline_format = (term_font_styles = font_styles).empty? ? true : [inherited: { styles: term_font_styles }]
term_line_metrics = calc_line_metrics @theme.description_list_term_line_height || @theme.base_line_height
term_padding = [term_line_metrics.padding_top, 10, (@theme.prose_margin_bottom || 0) * 0.5 + term_line_metrics.padding_bottom, 10]
desc_padding = [0, 10, (@theme.prose_margin_bottom || 0) * 0.5, 10]
term_kerning = default_kerning?
end
node.items.each do |terms, desc|
term_text = terms.map(&:text).join ?\n
if (term_width = width_of term_text, inline_format: term_inline_format, kerning: term_kerning) > max_term_width
max_term_width = term_width
end
row_data = [{
text_color: @font_color,
kerning: term_kerning,
content: term_text,
inline_format: term_inline_format,
padding: term_padding,
leading: term_line_metrics.leading,
# FIXME: prawn-table doesn't have support for final_gap option
#final_gap: term_line_metrics.final_gap,
valign: :top,
}]
if desc
desc_container = Block.new desc, :open
desc_container << (Block.new desc_container, :paragraph, source: (desc.instance_variable_get :@text), subs: :default) if desc.text?
desc.blocks.each {|b| desc_container << b } if desc.blocks?
row_data << {
content: (::Prawn::Table::Cell::AsciiDoc.new self, content: desc_container, text_color: @font_color, padding: desc_padding, valign: :top),
}
else
row_data << {}
end
table_data << row_data
end
max_term_width += (term_padding[1] + term_padding[3])
term_column_width = [max_term_width, bounds.width * 0.5].min
table table_data, position: :left, cell_style: { border_width: 0 }, column_widths: [term_column_width] do
@pdf.layout_table_caption node if node.title?
end
margin_bottom (@theme.prose_margin_bottom || 0) * 0.5
when 'qanda'
@list_numerals << '1'
convert_outline_list node
@list_numerals.pop
else
# TODO: check if we're within one line of the bottom of the page
# and advance to the next page if so (similar to logic for section titles)
layout_caption node, category: :description_list, labeled: false if node.title?
term_line_height = @theme.description_list_term_line_height || @theme.base_line_height
line_metrics = theme_font(:description_list_term) { calc_line_metrics term_line_height }
node.items.each do |terms, desc|
# NOTE: don't orphan the terms (keep together terms and at least one line of content)
allocate_space_for_list_item line_metrics, (terms.size + 1), ((@theme.description_list_term_spacing || 0) + 0.05)
theme_font :description_list_term do
if (term_font_styles = font_styles).empty?
term_font_styles = nil
end
terms.each do |term|
# QUESTION should we pass down styles in other calls to layout_prose
layout_prose term.text, margin_top: 0, margin_bottom: @theme.description_list_term_spacing, align: :left, line_height: term_line_height, normalize_line_height: true, styles: term_font_styles
end
end
indent(@theme.description_list_description_indent || 0) do
traverse_list_item desc, :dlist_desc, normalize_line_height: true
end if desc
end
end
end
def convert_olist node
add_dest_for_block node if node.id
# TODO: move list_numeral resolve to a method
case node.style
when 'arabic'
list_numeral = 1
when 'decimal'
list_numeral = '01'
when 'loweralpha'
list_numeral = 'a'
when 'upperalpha'
list_numeral = 'A'
when 'lowerroman'
list_numeral = RomanNumeral.new 'i'
when 'upperroman'
list_numeral = RomanNumeral.new 'I'
when 'lowergreek'
list_numeral = LowercaseGreekA
when 'unstyled', 'unnumbered', 'no-bullet'
list_numeral = nil
when 'none'
list_numeral = ''
else
list_numeral = 1
end
if list_numeral && list_numeral != '' &&
(start = (node.attr 'start') || ((node.option? 'reversed') ? node.items.size : nil))
if (start = start.to_i) > 1
(start - 1).times { list_numeral = list_numeral.next }
elsif start < 1 && !(::String === list_numeral)
(start - 1).abs.times { list_numeral = list_numeral.pred }
end
end
@list_numerals << list_numeral
convert_outline_list node
@list_numerals.pop
end
def convert_ulist node
add_dest_for_block node if node.id
# TODO: move bullet_type to method on List (or helper method)
if node.option? 'checklist'
@list_bullets << :checkbox
else
if (style = node.style)
case style
when 'bibliography'
bullet_type = :square
when 'unstyled', 'no-bullet'
bullet_type = nil
else
candidate = style.to_sym
if Bullets.key? candidate
bullet_type = candidate
else
logger.warn %(unknown unordered list style: #{candidate}) unless scratch?
bullet_type = :disc
end
end
else
case node.outline_level
when 1
bullet_type = :disc
when 2
bullet_type = :circle
else
bullet_type = :square
end
end
@list_bullets << bullet_type
end
convert_outline_list node
@list_bullets.pop
end
def convert_outline_list node
# TODO: check if we're within one line of the bottom of the page
# and advance to the next page if so (similar to logic for section titles)
layout_caption node, category: :outline_list, labeled: false if node.title?
opts = {}
if (align = resolve_alignment_from_role node.roles)
opts[:align] = align
elsif node.style == 'bibliography'
opts[:align] = :left
elsif (align = @theme.outline_list_text_align)
# NOTE: theme setting only affects alignment of list text (not nested blocks)
opts[:align] = align.to_sym
end
line_metrics = calc_line_metrics @theme.base_line_height
#complex = false
# ...or if we want to give all items in the list the same treatment
#complex = node.items.find(&:compound?) ? true : false
if (node.context == :ulist && !@list_bullets[-1]) || (node.context == :olist && !@list_numerals[-1])
if node.style == 'unstyled'
# unstyled takes away all indentation
list_indent = 0
elsif (list_indent = @theme.outline_list_indent || 0) > 0
# no-bullet aligns text with left-hand side of bullet position (as though there's no bullet)
list_indent = [list_indent - (rendered_width_of_string %(#{node.context == :ulist ? ?\u2022 : '1.'}x)), 0].max
end
else
list_indent = @theme.outline_list_indent || 0
end
indent list_indent do
node.items.each do |item|
allocate_space_for_list_item line_metrics
convert_outline_list_item item, node, opts
end
end
# NOTE: children will provide the necessary bottom margin if last item is complex.
# However, don't leave gap at the bottom if list is nested in an outline list
#unless complex || (node.nested? && node.parent.parent.outline?)
unless node.nested? && node.parent.parent.outline?
# correct bottom margin of last item
margin_bottom((@theme.prose_margin_bottom || 0) - (@theme.outline_list_item_spacing || 0))
end
end
def convert_outline_list_item node, list, opts = {}
# TODO: move this to a draw_bullet (or draw_marker) method
marker_style = {}
marker_style[:font_color] = @theme.outline_list_marker_font_color || @font_color
marker_style[:font_family] = font_family
marker_style[:font_size] = font_size
marker_style[:line_height] = @theme.base_line_height
case (list_type = list.context)
when :dlist
# NOTE: list.style is 'qanda'
complex = node[1]&.compound?
@list_numerals << (index = @list_numerals.pop).next
marker = %(#{index}.)
when :olist
complex = node.compound?
if (index = @list_numerals.pop)
if index == ''
marker = ''
else
marker = %(#{index}.)
dir = (node.parent.option? 'reversed') ? :pred : :next
@list_numerals << (index.public_send dir)
end
end
else # :ulist
complex = node.compound?
if (marker_type = @list_bullets[-1])
if marker_type == :checkbox
# QUESTION should we remove marker indent if not a checkbox?
if node.attr? 'checkbox'
marker_type = (node.attr? 'checked') ? :checked : :unchecked
marker = @theme[%(ulist_marker_#{marker_type}_content)] || BallotBox[marker_type]
end
else
marker = @theme[%(ulist_marker_#{marker_type}_content)] || Bullets[marker_type]
end
[:font_color, :font_family, :font_size, :line_height].each do |prop|
marker_style[prop] = @theme[%(ulist_marker_#{marker_type}_#{prop})] || @theme[%(ulist_marker_#{prop})] || marker_style[prop]
end if marker
end
end
if marker
if marker_style[:font_family] == 'fa'
logger.info 'deprecated fa icon set found in theme; use fas, far, or fab instead' unless scratch?
marker_style[:font_family] = FontAwesomeIconSets.find {|candidate| (icon_font_data candidate).yaml[candidate].value? marker } || 'fas'
end
marker_gap = rendered_width_of_char 'x'
font marker_style[:font_family], size: marker_style[:font_size] do
marker_width = rendered_width_of_string marker
# NOTE compensate if character_spacing is not applied to first character
# see https://github.com/prawnpdf/prawn/commit/c61c5d48841910aa11b9e3d6f0e01b68ce435329
character_spacing_correction = 0
character_spacing(-0.5) do
character_spacing_correction = 0.5 if (rendered_width_of_char 'x', character_spacing: -0.5) == marker_gap
end
marker_height = height_of_typeset_text marker, line_height: marker_style[:line_height], single_line: true
start_position = -marker_width + -marker_gap + character_spacing_correction
float do
start_new_page if @media == 'prepress' && cursor < marker_height
flow_bounding_box start_position, width: marker_width do
layout_prose marker,
align: :right,
character_spacing: -0.5,
color: marker_style[:font_color],
inline_format: false,
line_height: marker_style[:line_height],
margin: 0,
normalize: false,
single_line: true
end
end
end
end
if complex
traverse_list_item node, list_type, (opts.merge normalize_line_height: true)
else
traverse_list_item node, list_type, (opts.merge margin_bottom: @theme.outline_list_item_spacing, normalize_line_height: true)
end
end
def traverse_list_item node, list_type, opts = {}
if list_type == :dlist # qanda
terms, desc = node
terms.each {|term| layout_prose %(<em>#{term.text}</em>), (opts.merge margin_top: 0, margin_bottom: @theme.description_list_term_spacing) }
if desc
layout_prose desc.text, (opts.merge hyphenate: true) if desc.text?
traverse desc
end
else
if (primary_text = node.text).nil_or_empty?
layout_prose DummyText, opts unless node.blocks?
else
layout_prose primary_text, (opts.merge hyphenate: true)
end
traverse node
end
end
def allocate_space_for_list_item line_metrics, number = 1, additional_gap = 0
advance_page if !at_page_top? && cursor < (line_metrics.height + line_metrics.leading + line_metrics.padding_top + additional_gap) * number
end
def convert_image node, opts = {}
node.extend ::Asciidoctor::Image unless ::Asciidoctor::Image === node
target, image_format = node.target_and_format
if image_format == 'gif' && !(defined? ::GMagick::Image)
logger.warn %(GIF image format not supported. Install the prawn-gmagick gem or convert #{target} to PNG.) unless scratch?
image_path = nil
elsif ::Base64 === target
image_path = target
elsif (image_path = resolve_image_path node, target, image_format, (opts.fetch :relative_to_imagesdir, true))
if image_format == 'pdf'
if ::File.readable? image_path
if (id = node.id)
add_dest_block = proc do
node.set_attr 'pdf-destination', (node_dest = dest_top)
add_dest id, node_dest
end
end
# NOTE: import_page automatically advances to next page afterwards
# QUESTION should we add destination to top of imported page?
if (pgnums = node.attr 'pages')
(resolve_pagenums pgnums).each_with_index do |pgnum, idx|
if idx == 0
import_page image_path, page: pgnum, replace: page.empty?, &add_dest_block
else
import_page image_path, page: pgnum, replace: true
end
end
else
import_page image_path, page: [(node.attr 'page', nil, 1).to_i, 1].max, replace: page.empty?, &add_dest_block
end
return
else
logger.warn %(pdf to insert not found or not readable: #{image_path}) unless scratch?
image_path = nil
end
elsif !(::File.readable? image_path)
logger.warn %(image to embed not found or not readable: #{image_path}) unless scratch?
image_path = nil
end
end
theme_margin :block, :top unless (pinned = opts[:pinned])
return on_image_error :missing, node, target, opts unless image_path
alignment = ((node.attr 'align') || (resolve_alignment_from_role node.roles) || @theme.image_align || :left).to_sym
# TODO: support cover (aka canvas) image layout using "canvas" (or "cover") role
width = resolve_explicit_width node.attributes, bounds_width: (available_w = bounds.width), support_vw: true, use_fallback: true, constrain_to_bounds: true
# TODO: add `to_pt page_width` method to ViewportWidth type
width = (width.to_f / 100) * page_width if ViewportWidth === width
# NOTE: if width is not set explicitly and max-width is fit-content, caption height may not be accurate
caption_h = node.title? ? (layout_caption node, category: :image, side: :bottom, block_align: alignment, block_width: width, max_width: @theme.image_caption_max_width, dry_run: true) : 0
align_to_page = node.option? 'align-to-page'
begin
rendered_w = nil
span_page_width_if align_to_page do
if image_format == 'svg'
if ::Base64 === image_path
svg_data = ::Base64.decode64 image_path
file_request_root = false
else
svg_data = ::File.read image_path, mode: 'r:UTF-8'
file_request_root = ::File.dirname image_path
end
svg_obj = ::Prawn::SVG::Interface.new svg_data, self,
position: alignment,
width: width,
fallback_font_name: fallback_svg_font_name,
enable_web_requests: allow_uri_read ? (method :load_open_uri).to_proc : false,
enable_file_requests_with_root: file_request_root,
cache_images: cache_uri
rendered_w = (svg_size = svg_obj.document.sizing).output_width
if !width && (svg_obj.document.root.attributes.key? 'width')
# NOTE: restrict width to available width (prawn-svg already coerces to pixels)
svg_size = svg_obj.resize width: (rendered_w = available_w) if rendered_w > available_w
end
# NOTE: shrink image so it fits within available space; group image & caption
if (rendered_h = svg_size.output_height) > (available_h = cursor - caption_h)
unless pinned || at_page_top?
advance_page
available_h = cursor - caption_h
end
rendered_w = (svg_obj.resize height: (rendered_h = available_h)).output_width if rendered_h > available_h
end
image_y = y
image_cursor = cursor
add_dest_for_block node if node.id
# NOTE: workaround to fix Prawn not adding fill and stroke commands on page that only has an image;
# breakage occurs when running content (stamps) are added to page
# seems to be resolved as of Prawn 2.2.2
#update_colors if graphic_state.color_space.empty?
# NOTE: prawn-svg 0.24.0, 0.25.0, & 0.25.1 didn't restore font after call to draw (see mogest/prawn-svg#80)
# NOTE: cursor advances automatically
svg_obj.draw
svg_obj.document.warnings.each do |img_warning|
logger.warn %(problem encountered in image: #{image_path}; #{img_warning})
end unless scratch?
draw_image_border image_cursor, rendered_w, rendered_h, alignment unless node.role? && (node.has_role? 'noborder')
if (link = node.attr 'link')
add_link_to_image link, { width: rendered_w, height: rendered_h }, position: alignment, y: image_y
end
else
# FIXME: this code really needs to be better organized!
# NOTE: use low-level API to access intrinsic dimensions; build_image_object caches image data previously loaded
image_obj, image_info = ::Base64 === image_path ?
::StringIO.open((::Base64.decode64 image_path), 'rb') {|fd| build_image_object fd } :
::File.open(image_path, 'rb') {|fd| build_image_object fd }
# NOTE: if width is not specified, scale native width & height from px to pt and restrict width to available width
rendered_w, rendered_h = image_info.calc_image_dimensions width: (width || [available_w, (to_pt image_info.width, :px)].min)
# NOTE: shrink image so it fits within available space; group image & caption
if rendered_h > (available_h = cursor - caption_h)
unless pinned || at_page_top?
advance_page
available_h = cursor - caption_h
end
rendered_w, rendered_h = image_info.calc_image_dimensions height: available_h if rendered_h > available_h
end
image_y = y
image_cursor = cursor
add_dest_for_block node if node.id
# NOTE: workaround to fix Prawn not adding fill and stroke commands on page that only has an image;
# breakage occurs when running content (stamps) are added to page
# seems to be resolved as of Prawn 2.2.2
#update_colors if graphic_state.color_space.empty?
# NOTE: specify both width and height to avoid recalculation
embed_image image_obj, image_info, width: rendered_w, height: rendered_h, position: alignment
draw_image_border image_cursor, rendered_w, rendered_h, alignment unless node.role? && (node.has_role? 'noborder')
if (link = node.attr 'link')
add_link_to_image link, { width: rendered_w, height: rendered_h }, position: alignment, y: image_y
end
# NOTE: Asciidoctor disables automatic advancement of cursor for raster images, so move cursor manually
move_down rendered_h if y == image_y
end
end
layout_caption node, category: :image, side: :bottom, block_align: alignment, block_width: rendered_w, max_width: @theme.image_caption_max_width if node.title?
theme_margin :block, :bottom unless pinned
rescue
on_image_error :exception, node, target, (opts.merge message: %(could not embed image: #{image_path}; #{$!.message}#{::Prawn::Errors::UnsupportedImageType === $! && !(defined? ::GMagick::Image) ? '; install prawn-gmagick gem to add support' : ''}))
end
end
def draw_image_border top, w, h, alignment
if (@theme.image_border_width || 0) > 0 && @theme.image_border_color
if (@theme.image_border_fit || 'content') == 'auto'
bb_width = bounds.width
elsif alignment == :center
bb_x = (bounds.width - w) * 0.5
elsif alignment == :right
bb_x = bounds.width - w
end
bounding_box [(bb_x || 0), top], width: (bb_width || w), height: h, position: alignment do
theme_fill_and_stroke_bounds :image
end
true
end
end
def on_image_error _reason, node, target, opts = {}
logger.warn opts[:message] if (opts.key? :message) && !scratch?
alt_text_vars = { alt: (node.attr 'alt'), target: target }
alt_text_template = @theme.image_alt_content || '%{link}[%{alt}]%{/link} | <em>%{target}</em>'
return if alt_text_template.empty?
if (link = node.attr 'link')
alt_text_vars[:link] = %(<a href="#{link}">)
alt_text_vars[:'/link'] = '</a>'
else
alt_text_vars[:link] = ''
alt_text_vars[:'/link'] = ''
end
theme_font :image_alt do
layout_prose alt_text_template % alt_text_vars,
align: ((node.attr 'align') || @theme.image_align).to_sym,
margin: 0,
normalize: false,
single_line: true
end
layout_caption node, category: :image, side: :bottom if node.title?
theme_margin :block, :bottom unless opts[:pinned]
nil
end
def convert_audio node
add_dest_for_block node if node.id
theme_margin :block, :top
audio_path = node.media_uri node.attr 'target'
play_symbol = (node.document.attr? 'icons', 'font') ? %(<font name="fas">#{(icon_font_data 'fas').unicode 'play'}</font>) : RightPointer
layout_prose %(#{play_symbol}#{NoBreakSpace}<a href="#{audio_path}">#{audio_path}</a> <em>(audio)</em>), normalize: false, margin: 0, single_line: true
layout_caption node, labeled: false, side: :bottom if node.title?
theme_margin :block, :bottom
end
def convert_video node
case (poster = node.attr 'poster')
when 'youtube'
video_path = %(https://www.youtube.com/watch?v=#{video_id = node.attr 'target'})
# see http://stackoverflow.com/questions/2068344/how-do-i-get-a-youtube-video-thumbnail-from-the-youtube-api
poster = allow_uri_read ? %(https://img.youtube.com/vi/#{video_id}/maxresdefault.jpg) : nil
type = 'YouTube video'
when 'vimeo'
video_path = %(https://vimeo.com/#{video_id = node.attr 'target'})
poster = allow_uri_read ? load_open_uri.open_uri(%(http://vimeo.com/api/v2/video/#{video_id}.xml), 'r') {|f| VimeoThumbnailRx =~ f.read && $1 } : nil
type = 'Vimeo video'
else
video_path = node.media_uri node.attr 'target'
type = 'video'
end
if poster.nil_or_empty?
add_dest_for_block node if node.id
theme_margin :block, :top
play_symbol = (node.document.attr? 'icons', 'font') ? %(<font name="fas">#{(icon_font_data 'fas').unicode 'play'}</font>) : RightPointer
layout_prose %(#{play_symbol}#{NoBreakSpace}<a href="#{video_path}">#{video_path}</a> <em>(#{type})</em>), normalize: false, margin: 0, single_line: true
layout_caption node, labeled: false, side: :bottom if node.title?
theme_margin :block, :bottom
else
original_attributes = node.attributes.dup
begin
node.update_attributes 'target' => poster, 'link' => video_path
#node.set_attr 'pdfwidth', '100%' unless (node.attr? 'width') || (node.attr? 'pdfwidth')
convert_image node
ensure
node.attributes.replace original_attributes
end
end
end
# QUESTION can we avoid arranging fragments multiple times (conums & autofit) by eagerly preparing arranger?
def convert_listing_or_literal node
add_dest_for_block node if node.id
wrap_ext = source_chunks = bg_color_override = font_color_override = adjusted_font_size = nil
theme_font :code do
# HACK: disable built-in syntax highlighter; must be done before calling node.content!
if node.style == 'source' && (highlighter = (syntax_hl = node.document.syntax_highlighter) && syntax_hl.highlight? && syntax_hl.name)
case highlighter
when 'coderay'
unless defined? ::Asciidoctor::Prawn::CodeRayEncoder
highlighter = nil if (Helpers.require_library CodeRayRequirePath, 'coderay', :warn).nil?
end
when 'pygments'
unless defined? ::Pygments::Ext::BlockStyles
highlighter = nil if (Helpers.require_library PygmentsRequirePath, 'pygments.rb', :warn).nil?
end
when 'rouge'
unless defined? ::Rouge::Formatters::Prawn
highlighter = nil if (Helpers.require_library RougeRequirePath, 'rouge', :warn).nil?
end
else
highlighter = nil
end
prev_subs = (subs = node.subs).dup
callouts_enabled = subs.include? :callouts
# NOTE: the highlight sub is only set for coderay, rouge, and pygments atm
highlight_idx = subs.index :highlight
# NOTE: scratch? here only applies if listing block is nested inside another block
if !highlighter || scratch?
highlighter = nil
if highlight_idx
# switch the :highlight sub back to :specialcharacters
subs[highlight_idx] = :specialcharacters
else
prev_subs = nil
end
source_string = guard_indentation node.content
elsif highlight_idx
# NOTE: the source highlighter logic below handles the highlight and callouts subs
subs.replace subs - [:highlight, :callouts]
# NOTE: indentation guards will be added by the source highlighter logic
source_string = expand_tabs node.content
else
highlighter = prev_subs = nil
source_string = guard_indentation node.content
end
else
highlighter = nil
source_string = guard_indentation node.content
end
case highlighter
when 'coderay'
source_string, conum_mapping = extract_conums source_string if callouts_enabled
srclang = node.attr 'language', 'text'
begin
::CodeRay::Scanners[(srclang = (srclang.start_with? 'html+') ? (srclang.slice 5, srclang.length).to_sym : srclang.to_sym)]
rescue ::ArgumentError
srclang = :text
end
fragments = (::CodeRay.scan source_string, srclang).to_prawn
source_chunks = conum_mapping ? (restore_conums fragments, conum_mapping) : fragments
when 'pygments'
style = (node.document.attr 'pygments-style') || 'pastie'
# QUESTION allow border color to be set by theme for highlighted block?
pg_block_styles = ::Pygments::Ext::BlockStyles.for style
bg_color_override = pg_block_styles[:background_color]
font_color_override = pg_block_styles[:font_color]
if source_string.empty?
source_chunks = []
else
lexer = (::Pygments::Lexer.find_by_alias node.attr 'language', 'text') || (::Pygments::Lexer.find_by_mimetype 'text/plain')
lexer_opts = { nowrap: true, noclasses: true, stripnl: false, style: style }
lexer_opts[:startinline] = !(node.option? 'mixed') if lexer.name == 'PHP'
source_string, conum_mapping = extract_conums source_string if callouts_enabled
# NOTE: highlight can return nil if something goes wrong; fallback to encoded source string if this happens
result = (lexer.highlight source_string, options: lexer_opts) || (node.apply_subs source_string, [:specialcharacters])
if node.attr? 'highlight'
if (highlight_lines = node.resolve_lines_to_highlight source_string, (node.attr 'highlight')).empty?
highlight_lines = nil
else
pg_highlight_bg_color = pg_block_styles[:highlight_background_color]
highlight_lines = highlight_lines.map {|linenum| [linenum, pg_highlight_bg_color] }.to_h
end
end
if node.attr? 'linenums'
linenums = (node.attr 'start', 1).to_i
@theme.code_linenum_font_color ||= '999999'
postprocess = true
wrap_ext = FormattedText::SourceWrap
elsif conum_mapping || highlight_lines
postprocess = true
end
fragments = text_formatter.format result
fragments = restore_conums fragments, conum_mapping, linenums, highlight_lines if postprocess
source_chunks = guard_indentation_in_fragments fragments
end
when 'rouge'
formatter = (@rouge_formatter ||= ::Rouge::Formatters::Prawn.new theme: (node.document.attr 'rouge-style'), line_gap: @theme.code_line_gap, highlight_background_color: @theme.code_highlight_background_color)
# QUESTION allow border color to be set by theme for highlighted block?
bg_color_override = formatter.background_color
if source_string.empty?
source_chunks = []
else
if node.attr? 'linenums'
formatter_opts = { line_numbers: true, start_line: (node.attr 'start', 1).to_i }
wrap_ext = FormattedText::SourceWrap
else
formatter_opts = {}
end
if (srclang = node.attr 'language')
if srclang.include? '?'
if (lexer = ::Rouge::Lexer.find_fancy srclang)
unless lexer.tag != 'php' || (node.option? 'mixed') || ((lexer_opts = lexer.options).key? 'start_inline')
lexer = lexer.class.new lexer_opts.merge 'start_inline' => true
end
end
elsif (lexer = ::Rouge::Lexer.find srclang)
lexer = lexer.new start_inline: true if lexer.tag == 'php' && !(node.option? 'mixed')
end
end
lexer ||= ::Rouge::Lexers::PlainText
source_string, conum_mapping = extract_conums source_string if callouts_enabled
if node.attr? 'highlight'
unless (hl_lines = (node.resolve_lines_to_highlight source_string, (node.attr 'highlight'))).empty?
formatter_opts[:highlight_lines] = hl_lines.map {|linenum| [linenum, true] }.to_h
end
end
fragments = formatter.format (lexer.lex source_string), formatter_opts
source_chunks = conum_mapping ? (restore_conums fragments, conum_mapping) : fragments
end
else
# NOTE: only format if we detect a need (callouts or inline formatting)
source_chunks = (XMLMarkupRx.match? source_string) ? (text_formatter.format source_string) : [text: source_string]
end
node.subs.replace prev_subs if prev_subs
adjusted_font_size = ((node.option? 'autofit') || (node.document.attr? 'autofit-option')) ? (compute_autofit_font_size source_chunks, :code) : nil
end
theme_margin :block, :top
keep_together do |box_height = nil|
caption_height = node.title? ? (layout_caption node, category: :code) : 0
theme_font :code do
theme_fill_and_stroke_block :code, (box_height - caption_height), background_color: bg_color_override, split_from_top: false if box_height
pad_box @theme.code_padding do
::Prawn::Text::Formatted::Box.extensions << wrap_ext if wrap_ext
typeset_formatted_text source_chunks, (calc_line_metrics @theme.code_line_height || @theme.base_line_height),
color: (font_color_override || @theme.code_font_color || @font_color),
size: adjusted_font_size
::Prawn::Text::Formatted::Box.extensions.pop if wrap_ext
end
end
end
theme_margin :block, :bottom
end
alias convert_listing convert_listing_or_literal
alias convert_literal convert_listing_or_literal
def convert_pass node
node = node.dup
(subs = node.subs.dup).unshift :specialcharacters
node.instance_variable_set :@subs, subs.uniq
convert_listing_or_literal node
end
alias convert_stem convert_listing_or_literal
# Extract callout marks from string, indexed by 0-based line number
# Return an Array with the processed string as the first argument
# and the mapping of lines to conums as the second.
def extract_conums string
conum_mapping = {}
auto_num = 0
string = string.split(LF).map.with_index {|line, line_num|
# FIXME: we get extra spaces before numbers if more than one on a line
if line.include? '<'
line = line.gsub CalloutExtractRx do
# honor the escape
if $1 == ?\\
$&.sub $1, ''
else
(conum_mapping[line_num] ||= []) << ($3 == '.' ? (auto_num += 1) : $3.to_i)
''
end
end
# NOTE use first position to store space that precedes conums
if (conum_mapping.key? line_num) && (line.end_with? ' ')
trimmed_line = line.rstrip
conum_mapping[line_num].unshift line.slice trimmed_line.length, line.length
line = trimmed_line
end
end
line
}.join LF
conum_mapping = nil if conum_mapping.empty?
[string, conum_mapping]
end
# Restore the conums into the Array of formatted text fragments
#--
# QUESTION can this be done more efficiently?
# QUESTION can we reuse arrange_fragments_by_line?
def restore_conums fragments, conum_mapping, linenums = nil, highlight_lines = nil
lines = []
line_num = 0
# reorganize the fragments into an array of lines
fragments.each do |fragment|
line = (lines[line_num] ||= [])
if (text = fragment[:text]) == LF
lines[line_num += 1] ||= []
elsif text.include? LF
text.split(LF, -1).each_with_index do |line_in_fragment, idx|
line = (lines[line_num += 1] ||= []) unless idx == 0
line << (fragment.merge text: line_in_fragment) unless line_in_fragment.empty?
end
else
line << fragment
end
end
conum_font_color = @theme.conum_font_color
if (conum_font_name = @theme.conum_font_family) == font_name
conum_font_name = nil
end
last_line_num = lines.size - 1
if linenums
pad_size = (last_line_num + 1).to_s.length
linenum_color = @theme.code_linenum_font_color
end
# append conums to appropriate lines, then flatten to an array of fragments
lines.flat_map.with_index do |line, cur_line_num|
last_line = cur_line_num == last_line_num
visible_line_num = cur_line_num + (linenums || 1)
if highlight_lines && (highlight_bg_color = highlight_lines[visible_line_num])
line.unshift text: DummyText, background_color: highlight_bg_color, highlight: true, inline_block: true, extend: true, width: 0, callback: [FormattedText::TextBackgroundAndBorderRenderer]
end
line.unshift text: %(#{visible_line_num.to_s.rjust pad_size} ), linenum: visible_line_num, color: linenum_color if linenums
if conum_mapping && (conums = conum_mapping.delete cur_line_num)
line << { text: conums.shift } if ::String === conums[0]
conum_text = conums.map {|num| conum_glyph num }.join ' '
conum_fragment = { text: conum_text }
conum_fragment[:color] = conum_font_color if conum_font_color
conum_fragment[:font] = conum_font_name if conum_font_name
line << conum_fragment
end
line << { text: LF } unless last_line
line
end
end
def conum_glyph number
@conum_glyphs[number - 1]
end
def convert_table node
add_dest_for_block node if node.id
# TODO: we could skip a lot of the logic below when num_rows == 0
num_rows = node.attr 'rowcount'
num_cols = node.columns.size
table_header_size = false
theme = @theme
tbl_bg_color = resolve_theme_color :table_background_color
# QUESTION should we fallback to page background color? (which is never transparent)
#tbl_bg_color = resolve_theme_color :table_background_color, @page_bg_color
# ...and if so, should we try to be helpful and use @page_bg_color for tables nested in blocks?
#unless tbl_bg_color
# tbl_bg_color = @page_bg_color unless [:section, :document].include? node.parent.context
#end
# NOTE: emulate table bg color by using it as a fallback value for each element
head_bg_color = resolve_theme_color :table_head_background_color, tbl_bg_color
foot_bg_color = resolve_theme_color :table_foot_background_color, tbl_bg_color
body_bg_color = resolve_theme_color :table_body_background_color, tbl_bg_color
body_stripe_bg_color = resolve_theme_color :table_body_stripe_background_color, tbl_bg_color
base_header_cell_data = nil
header_cell_line_metrics = nil
table_data = []
theme_font :table do
head_rows = node.rows[:head]
body_rows = node.rows[:body]
#if (hrows = node.attr 'hrows') && (shift_rows = hrows.to_i - head_rows.size) > 0
# head_rows = head_rows.dup
# body_rows = body_rows.dup
# shift_rows.times { head_rows << body_rows.shift unless body_rows.empty? }
#end
theme_font :table_head do
table_header_size = head_rows.size
head_font_info = font_info
head_line_metrics = calc_line_metrics theme.base_line_height
head_cell_padding = theme.table_head_cell_padding || theme.table_cell_padding
head_cell_padding = ::Array === head_cell_padding && head_cell_padding.size == 4 ? head_cell_padding.dup : (expand_padding_value head_cell_padding)
head_cell_padding[0] += head_line_metrics.padding_top
head_cell_padding[2] += head_line_metrics.padding_bottom
# QUESTION why doesn't text transform inherit from table?
head_transform = resolve_text_transform :table_head_text_transform, nil
base_cell_data = {
inline_format: [normalize: true],
background_color: head_bg_color,
text_color: @font_color,
size: head_font_info[:size],
font: head_font_info[:family],
font_style: head_font_info[:style],
kerning: default_kerning?,
padding: head_cell_padding,
leading: head_line_metrics.leading,
# TODO: patch prawn-table to pass through final_gap option
#final_gap: head_line_metrics.final_gap,
}
head_rows.each do |row|
table_data << (row.map do |cell|
cell_text = head_transform ? (transform_text cell.text.strip, head_transform) : cell.text.strip
cell_text = hyphenate_text cell_text, @hyphenator if defined? @hyphenator
base_cell_data.merge \
content: cell_text,
colspan: cell.colspan || 1,
align: (cell.attr 'halign').to_sym,
valign: (val = cell.attr 'valign') == 'middle' ? :center : val.to_sym
end)
end
end unless head_rows.empty?
base_cell_data = {
font: (body_font_info = font_info)[:family],
font_style: body_font_info[:style],
size: body_font_info[:size],
kerning: default_kerning?,
text_color: @font_color,
}
body_cell_line_metrics = calc_line_metrics theme.base_line_height
(body_rows + node.rows[:foot]).each do |row|
table_data << (row.map do |cell|
cell_data = base_cell_data.merge \
colspan: cell.colspan || 1,
rowspan: cell.rowspan || 1,
align: (cell.attr 'halign').to_sym,
valign: (val = cell.attr 'valign') == 'middle' ? :center : val.to_sym
cell_line_metrics = body_cell_line_metrics
case cell.style
when :emphasis
cell_data[:font_style] = :italic
when :strong
cell_data[:font_style] = :bold
when :header
unless base_header_cell_data
theme_font :table_head do
theme_font :table_header_cell do
header_cell_font_info = font_info
base_header_cell_data = {
text_color: @font_color,
font: header_cell_font_info[:family],
size: header_cell_font_info[:size],
font_style: header_cell_font_info[:style],
text_transform: @text_transform,
}
header_cell_line_metrics = calc_line_metrics theme.base_line_height
end
end
if (val = resolve_theme_color :table_header_cell_background_color, head_bg_color)
base_header_cell_data[:background_color] = val
end
end
cell_data.update base_header_cell_data
cell_transform = cell_data.delete :text_transform
cell_line_metrics = header_cell_line_metrics
when :monospaced
cell_data.delete :font_style
theme_font :literal do
mono_cell_font_info = font_info
cell_data[:font] = mono_cell_font_info[:family]
cell_data[:size] = mono_cell_font_info[:size]
cell_data[:text_color] = @font_color
cell_line_metrics = calc_line_metrics theme.base_line_height
end
when :literal
# NOTE: we want the raw AsciiDoc in this case
cell_data[:content] = guard_indentation cell.instance_variable_get :@text
# NOTE: the absence of the inline_format option implies it's disabled
cell_data.delete :font_style
# QUESTION should we use literal_font_*, code_font_*, or introduce another category?
theme_font :code do
literal_cell_font_info = font_info
cell_data[:font] = literal_cell_font_info[:family]
cell_data[:size] = literal_cell_font_info[:size] * (cell_data[:size].to_f / @root_font_size)
cell_data[:text_color] = @font_color
cell_line_metrics = calc_line_metrics theme.base_line_height
end
when :asciidoc
cell_data.delete :kerning
if theme.table_asciidoc_cell_style == 'initial'
cell_data.delete :font
cell_data.delete :font_style
cell_data.delete :size
cell_data.delete :text_color
end
cell_line_metrics = nil
asciidoc_cell = ::Prawn::Table::Cell::AsciiDoc.new self, (cell_data.merge content: cell.inner_document, padding: theme.table_cell_padding)
cell_data = { content: asciidoc_cell }
end
if cell_line_metrics
cell_padding = ::Array === (cell_padding = theme.table_cell_padding) && cell_padding.size == 4 ? cell_padding.dup : (expand_padding_value cell_padding)
cell_padding[0] += cell_line_metrics.padding_top
cell_padding[2] += cell_line_metrics.padding_bottom
cell_data[:leading] = cell_line_metrics.leading
# TODO: patch prawn-table to pass through final_gap option
#cell_data[:final_gap] = cell_line_metrics.final_gap
cell_data[:padding] = cell_padding
end
unless cell_data.key? :content
cell_text = cell.text.strip
cell_text = transform_text cell_text, cell_transform if cell_transform
cell_text = hyphenate_text cell_text, @hyphenator if defined? @hyphenator
cell_text = cell_text.gsub CjkLineBreakRx, ZeroWidthSpace if @cjk_line_breaks
if cell_text.include? DoubleLF
# FIXME: hard breaks not quite the same result as separate paragraphs; need custom cell impl here
cell_data[:content] = (cell_text.split BlankLineRx).map {|l| l.tr_s WhitespaceChars, ' ' }.join DoubleLF
cell_data[:inline_format] = true
else
cell_data[:content] = cell_text
cell_data[:inline_format] = [normalize: true]
end
end
if node.document.attr? 'cellbgcolor'
if (cell_bg_color = node.document.attr 'cellbgcolor') == 'transparent'
cell_data[:background_color] = body_bg_color
elsif (cell_bg_color.start_with? '#') && (HexColorRx.match? cell_bg_color)
cell_data[:background_color] = cell_bg_color.slice 1, cell_bg_color.length
end
end
cell_data
end)
end
end
# NOTE: Prawn aborts if table data is empty, so ensure there's at least one row
if table_data.empty?
logger.warn message_with_context 'no rows found in table', source_location: node.source_location unless scratch?
table_data << ::Array.new([node.columns.size, 1].max) { { content: '' } }
end
border_width = {}
table_border_color = theme.table_border_color || theme.table_grid_color || theme.base_border_color
table_border_style = (theme.table_border_style || :solid).to_sym
table_border_width = theme.table_border_width
if table_header_size
head_border_bottom_color = theme.table_head_border_bottom_color || table_border_color
head_border_bottom_style = (theme.table_head_border_bottom_style || table_border_style).to_sym
head_border_bottom_width = theme.table_head_border_bottom_width || table_border_width
end
[:top, :bottom, :left, :right].each {|edge| border_width[edge] = table_border_width }
table_grid_color = theme.table_grid_color || table_border_color
table_grid_style = (theme.table_grid_style || table_border_style).to_sym
table_grid_width = theme.table_grid_width || theme.table_border_width
[:cols, :rows].each {|edge| border_width[edge] = table_grid_width }
case (grid = node.attr 'grid', 'all', 'table-grid')
when 'all'
# keep inner borders
when 'cols'
border_width[:rows] = 0
when 'rows'
border_width[:cols] = 0
else # none
border_width[:rows] = border_width[:cols] = 0
end
case (frame = node.attr 'frame', 'all', 'table-frame')
when 'all'
# keep outer borders
when 'topbot', 'ends'
border_width[:left] = border_width[:right] = 0
when 'sides'
border_width[:top] = border_width[:bottom] = 0
else # none
border_width[:top] = border_width[:right] = border_width[:bottom] = border_width[:left] = 0
end
if node.option? 'autowidth'
table_width = (node.attr? 'width') ? bounds.width * ((node.attr 'tablepcwidth') / 100.0) :
(((node.has_role? 'stretch') || (node.has_role? 'spread')) ? bounds.width : nil)
column_widths = []
else
table_width = bounds.width * ((node.attr 'tablepcwidth') / 100.0)
column_widths = node.columns.map {|col| ((col.attr 'colpcwidth') * table_width) / 100.0 }
end
if ((alignment = node.attr 'align') && (BlockAlignmentNames.include? alignment)) ||
(alignment = (node.roles & BlockAlignmentNames)[-1])
alignment = alignment.to_sym
else
alignment = (theme.table_align || :left).to_sym
end
caption_side = (theme.table_caption_side || :top).to_sym
caption_max_width = theme.table_caption_max_width || 'fit-content'
table_settings = {
header: table_header_size,
# NOTE: position is handled by this method
position: :left,
cell_style: {
# NOTE: the border color and style of the outer frame is set later
border_color: table_grid_color,
border_lines: [table_grid_style],
# NOTE: the border width is set later
border_width: 0,
},
width: table_width,
column_widths: column_widths,
}
# QUESTION should we support nth; should we support sequence of roles?
case node.attr 'stripes', nil, 'table-stripes'
when 'all'
table_settings[:row_colors] = [body_stripe_bg_color]
when 'even'
table_settings[:row_colors] = [body_bg_color, body_stripe_bg_color]
when 'odd'
table_settings[:row_colors] = [body_stripe_bg_color, body_bg_color]
else # none
table_settings[:row_colors] = [body_bg_color]
end
theme_margin :block, :top
left_padding = right_padding = nil
table table_data, table_settings do
# NOTE: call width to capture resolved table width
table_width = width
@pdf.layout_table_caption node, alignment, table_width, caption_max_width if node.title? && caption_side == :top
# NOTE align using padding instead of bounding_box as prawn-table does
# using a bounding_box across pages mangles the margin box of subsequent pages
if alignment != :left && table_width != (this_bounds = @pdf.bounds).width
if alignment == :center
left_padding = right_padding = (this_bounds.width - width) * 0.5
this_bounds.add_left_padding left_padding
this_bounds.add_right_padding right_padding
else # :right
left_padding = this_bounds.width - width
this_bounds.add_left_padding left_padding
end
end
if grid == 'none' && frame == 'none'
rows(table_header_size - 1).tap do |r|
r.border_bottom_color = head_border_bottom_color
r.border_bottom_line = head_border_bottom_style
r.border_bottom_width = head_border_bottom_width
end if table_header_size
else
# apply the grid setting first across all cells
cells.border_width = [border_width[:rows], border_width[:cols], border_width[:rows], border_width[:cols]]
if table_header_size
rows(table_header_size - 1).tap do |r|
r.border_bottom_color = head_border_bottom_color
r.border_bottom_line = head_border_bottom_style
r.border_bottom_width = head_border_bottom_width
end
rows(table_header_size).tap do |r|
r.border_top_color = head_border_bottom_color
r.border_top_line = head_border_bottom_style
r.border_top_width = head_border_bottom_width
end if num_rows > table_header_size
end
# top edge of table
rows(0).tap do |r|
r.border_top_color, r.border_top_line, r.border_top_width = table_border_color, table_border_style, border_width[:top]
end
# right edge of table
columns(num_cols - 1).tap do |r|
r.border_right_color, r.border_right_line, r.border_right_width = table_border_color, table_border_style, border_width[:right]
end
# bottom edge of table
rows(num_rows - 1).tap do |r|
r.border_bottom_color, r.border_bottom_line, r.border_bottom_width = table_border_color, table_border_style, border_width[:bottom]
end
# left edge of table
columns(0).tap do |r|
r.border_left_color, r.border_left_line, r.border_left_width = table_border_color, table_border_style, border_width[:left]
end
end
# QUESTION should cell padding be configurable for foot row cells?
unless node.rows[:foot].empty?
foot_row = row num_rows.pred
foot_row.background_color = foot_bg_color
# FIXME: find a way to do this when defining the cells
foot_row.text_color = theme.table_foot_font_color if theme.table_foot_font_color
foot_row.size = theme.table_foot_font_size if theme.table_foot_font_size
foot_row.font = theme.table_foot_font_family if theme.table_foot_font_family
foot_row.font_style = theme.table_foot_font_style.to_sym if theme.table_foot_font_style
# HACK: we should do this transformation when creating the cell
#if (foot_transform = resolve_text_transform :table_foot_text_transform, nil)
# foot_row.each {|c| c.content = (transform_text c.content, foot_transform) if c.content }
#end
end
end
if left_padding
bounds.subtract_left_padding left_padding
bounds.subtract_right_padding right_padding if right_padding
end
layout_table_caption node, alignment, table_width, caption_max_width, caption_side if node.title? && caption_side == :bottom
theme_margin :block, :bottom
end
def convert_thematic_break _node
theme_margin :thematic_break, :top
stroke_horizontal_rule @theme.thematic_break_border_color, line_width: @theme.thematic_break_border_width, line_style: (@theme.thematic_break_border_style || :solid).to_sym
theme_margin :thematic_break, :bottom
end
def convert_toc node
if ((doc = node.document).attr? 'toc-placement', 'macro') && doc.sections?
if (is_book = doc.doctype == 'book')
start_new_page unless at_page_top?
start_new_page if @ppbook && verso_page? && !(node.option? 'nonfacing')
end
add_dest_for_block node, (node.id || 'toc')
allocate_toc doc, (doc.attr 'toclevels', 2).to_i, @y, (is_book || (doc.attr? 'title-page'))
@disable_running_content[:header] = (@disable_running_content[:header] || ::Set.new) + @toc_extent[:page_nums] if node.option? 'noheader'
@disable_running_content[:footer] = (@disable_running_content[:footer] || ::Set.new) + @toc_extent[:page_nums] if node.option? 'nofooter'
end
nil
end
# NOTE to insert sequential page breaks, you must put {nbsp} between page breaks
def convert_page_break node
if (page_layout = node.attr 'page-layout').nil_or_empty?
unless node.role? && (page_layout = (node.roles.map(&:to_sym) & PageLayouts)[-1])
page_layout = nil
end
elsif !PageLayouts.include?(page_layout = page_layout.to_sym)
page_layout = nil
end
if at_page_top?
if page_layout && page_layout != page.layout && page.empty?
delete_page
advance_page layout: page_layout
end
elsif page_layout
advance_page layout: page_layout
else
advance_page
end
end
def convert_index_section _node
space_needed_for_category = @theme.description_list_term_spacing + (2 * (height_of_typeset_text 'A'))
column_box [0, cursor], columns: (@theme.index_columns || 2), width: bounds.width, reflow_margins: true do
@index.categories.each do |category|
# NOTE cursor method always returns 0 inside column_box; breaks reference_bounds.move_past_bottom
bounds.move_past_bottom if space_needed_for_category > y - reference_bounds.absolute_bottom
layout_prose category.name,
align: :left,
inline_format: false,
margin_top: 0,
margin_bottom: @theme.description_list_term_spacing,
style: @theme.description_list_term_font_style.to_sym
category.terms.each do |term|
convert_index_list_item term
end
if @theme.prose_margin_bottom > y - reference_bounds.absolute_bottom
bounds.move_past_bottom
else
move_down @theme.prose_margin_bottom
end
end
end
nil
end
def convert_index_list_item term
text = escape_xml term.name
unless term.container?
if @media == 'screen'
pagenums = term.dests.map {|dest| %(<a anchor="#{dest[:anchor]}">#{dest[:page]}</a>) }
else
pagenums = consolidate_ranges term.dests.uniq {|dest| dest[:page] }.map {|dest| dest[:page] }
end
text = %(#{text}, #{pagenums.join ', '})
end
subterm_indent = @theme.description_list_description_indent
layout_prose text, align: :left, margin: 0, hanging_indent: subterm_indent * 2
indent subterm_indent do
term.subterms.each do |subterm|
convert_index_list_item subterm
end
end unless term.leaf?
end
def convert_inline_anchor node
doc = node.document
target = node.target
case node.type
when :link
anchor = node.id ? %(<a id="#{node.id}">#{DummyText}</a>) : ''
attrs = []
if (role = node.role)
attrs << %( class="#{role}")
end
if (@media ||= doc.attr 'media', 'screen') != 'screen' && (target.start_with? 'mailto:') && (doc.attr? 'hide-uri-scheme')
bare_target = target.slice 7, target.length
node.add_role 'bare' if (text = node.text) == bare_target
else
bare_target = target
text = node.text
end
if (role = node.attr 'role') && (role == 'bare' || ((role.split ' ').include? 'bare'))
# QUESTION should we insert breakable chars into URI when building fragment instead?
%(#{anchor}<a href="#{target}"#{attrs.join}>#{breakable_uri text}</a>)
# NOTE @media may not be initialized if method is called before convert phase
elsif @media != 'screen' || (doc.attr? 'show-link-uri')
# QUESTION should we insert breakable chars into URI when building fragment instead?
# TODO: allow style of printed link to be controlled by theme
%(#{anchor}<a href="#{target}"#{attrs.join}>#{text}</a> [<font size="0.85em">#{breakable_uri bare_target}</font>])
else
%(#{anchor}<a href="#{target}"#{attrs.join}>#{text}</a>)
end
when :xref
# NOTE non-nil path indicates this is an inter-document xref that's not included in current document
if (path = node.attributes['path'])
# NOTE we don't use local as that doesn't work on the web
%(<a href="#{target}">#{node.text || path}</a>)
elsif (refid = node.attributes['refid'])
unless (text = node.text)
refs = doc.catalog[:refs]
if ::Asciidoctor::AbstractNode === (ref = refs[refid])
text = ref.xreftext node.attr 'xrefstyle', nil, true
end
end
%(<a anchor="#{derive_anchor_from_id refid}">#{text || "[#{refid}]"}</a>).gsub ']', ']'
else
%(<a anchor="#{doc.attr 'pdf-anchor'}">#{node.text || '[^top]'}</a>)
end
when :ref
# NOTE destination is created inside callback registered by FormattedTextTransform#build_fragment
%(<a id="#{node.id}">#{DummyText}</a>)
when :bibref
# NOTE destination is created inside callback registered by FormattedTextTransform#build_fragment
# NOTE technically node.text should be node.reftext, but subs have already been applied to text
reftext = (reftext = node.reftext) ? %([#{reftext}]) : %([#{node.id}])
%(<a id="#{node.id}">#{DummyText}</a>#{reftext})
else
logger.warn %(unknown anchor type: #{node.type.inspect}) unless scratch?
end
end
def convert_inline_break node
%(#{node.text}<br>)
end
def convert_inline_button node
%(<button>#{((load_theme node.document).button_content || '%s').sub '%s', node.text}</button>)
end
def convert_inline_callout node
if (conum_font_family = @theme.conum_font_family) != font_name
result = %(<font name="#{conum_font_family}">#{conum_glyph node.text.to_i}</font>)
else
result = conum_glyph node.text.to_i
end
if (conum_font_color = @theme.conum_font_color)
# NOTE CMYK value gets flattened here, but is restored by formatted text parser
result = %(<color rgb="#{conum_font_color}">#{result}</font>)
end
result
end
def convert_inline_footnote node
if (index = node.attr 'index') && (fn = node.document.footnotes.find {|candidate| candidate.index == index })
anchor = node.type == :xref ? '' : %(<a id="_footnoteref_#{index}">#{DummyText}</a>)
if defined? @rendered_footnotes
label = (@rendered_footnotes.include? fn) ? fn.label : (index - @rendered_footnotes.length)
else
label = index
end
%(#{anchor}<sup>[<a anchor="_footnotedef_#{index}">#{label}</a>]</sup>)
elsif node.type == :xref
# NOTE footnote reference not found
%(<sup><color rgb="FF0000">[#{node.text}]</color></sup>)
end
end
def convert_inline_icon node
if node.document.attr? 'icons', 'font'
if (icon_name = node.target).include? '@'
icon_name, icon_set = icon_name.split '@', 2
explicit_icon_set = true
elsif (icon_set = node.attr 'set')
explicit_icon_set = true
else
icon_set = node.document.attr 'icon-set', 'fa'
end
if icon_set == 'fa' || !(IconSets.include? icon_set)
icon_set = 'fa'
# legacy name from Font Awesome < 5
if (remapped_icon_name = resolve_legacy_icon_name icon_name)
requested_icon_name = icon_name
icon_set, icon_name = remapped_icon_name.split '-', 2
glyph = (icon_font_data icon_set).unicode icon_name
logger.info { %(#{requested_icon_name} icon found in deprecated fa icon set; using #{icon_name} from #{icon_set} icon set instead) } unless scratch?
# new name in Font Awesome >= 5 (but document is configured to use fa icon set)
else
font_data = nil
if (resolved_icon_set = FontAwesomeIconSets.find {|candidate| (font_data = icon_font_data candidate).unicode icon_name rescue nil })
icon_set = resolved_icon_set
glyph = font_data.unicode icon_name
logger.info { %(#{icon_name} icon not found in deprecated fa icon set; using match found in #{resolved_icon_set} icon set instead) } unless scratch?
end
end
else
glyph = (icon_font_data icon_set).unicode icon_name rescue nil
end
unless glyph || explicit_icon_set || !icon_name.start_with?(*IconSetPrefixes)
icon_set, icon_name = icon_name.split '-', 2
glyph = (icon_font_data icon_set).unicode icon_name rescue nil
end
if glyph
if node.attr? 'size'
case (size = node.attr 'size')
when 'lg'
size_attr = ' size="1.333em"'
when 'fw'
size_attr = ' width="1em"'
else
size_attr = %( size="#{size.sub 'x', 'em'}")
end
else
size_attr = ''
end
class_attr = node.role? ? %( class="#{node.role}") : ''
# TODO: support rotate and flip attributes
%(<font name="#{icon_set}"#{size_attr}#{class_attr}>#{glyph}</font>)
else
logger.warn %(#{icon_name} is not a valid icon name in the #{icon_set} icon set) unless scratch?
%([#{node.attr 'alt'}])
end
else
%([#{node.attr 'alt'}])
end
end
def convert_inline_image node
if node.type == 'icon'
convert_inline_icon node
else
node.extend ::Asciidoctor::Image unless ::Asciidoctor::Image === node
target, image_format = node.target_and_format
if image_format == 'gif' && !(defined? ::GMagick::Image)
logger.warn %(GIF image format not supported. Install the prawn-gmagick gem or convert #{target} to PNG.) unless scratch?
img = %([#{node.attr 'alt'}])
# NOTE an image with a data URI is handled using a temporary file
elsif (image_path = resolve_image_path node, target, image_format, true)
if ::File.readable? image_path
width_attr = (width = resolve_explicit_width node.attributes) ? %( width="#{width}") : ''
fit_attr = (fit = node.attr 'fit') ? %( fit="#{fit}") : ''
img = %(<img src="#{image_path}" format="#{image_format}" alt="[#{encode_quotes node.attr 'alt'}]"#{width_attr}#{fit_attr}>)
else
logger.warn %(image to embed not found or not readable: #{image_path}) unless scratch?
img = %([#{node.attr 'alt'}])
end
else
img = %([#{node.attr 'alt'}])
end
(node.attr? 'link') ? %(<a href="#{node.attr 'link'}">#{img}</a>) : img
end
end
def convert_inline_indexterm node
if scratch?
node.type == :visible ? node.text : ''
else
# NOTE initialize index in case converter is called before PDF is initialized
@index ||= IndexCatalog.new
# NOTE page number (:page key) is added by InlineDestinationMarker
dest = { anchor: (anchor_name = @index.next_anchor_name) }
anchor = %(<a id="#{anchor_name}" type="indexterm">#{DummyText}</a>)
if node.type == :visible
visible_term = node.text
@index.store_primary_term (sanitize visible_term), dest
%(#{anchor}#{visible_term})
else
@index.store_term((node.attr 'terms').map {|term| sanitize term }, dest)
anchor
end
end
end
def convert_inline_kbd node
if (keys = node.attr 'keys').size == 1
%(<key>#{keys[0]}</key>)
else
keys.map {|key| %(<key>#{key}</key>) }.join (load_theme node.document).key_separator || '+'
end
end
def convert_inline_menu node
menu = node.attr 'menu'
caret = (load_theme node.document).menu_caret_content || %( \u203a )
if !(submenus = node.attr 'submenus').empty?
%(<strong>#{[menu, *submenus, (node.attr 'menuitem')].join caret}</strong>)
elsif (menuitem = node.attr 'menuitem')
%(<strong>#{menu}#{caret}#{menuitem}</strong>)
else
%(<strong>#{menu}</strong>)
end
end
def convert_inline_quoted node
case node.type
when :emphasis
open, close, is_tag = ['<em>', '</em>', true]
when :strong
open, close, is_tag = ['<strong>', '</strong>', true]
when :monospaced, :asciimath, :latexmath
open, close, is_tag = ['<code>', '</code>', true]
when :superscript
open, close, is_tag = ['<sup>', '</sup>', true]
when :subscript
open, close, is_tag = ['<sub>', '</sub>', true]
when :double
open, close, is_tag = ['“', '”', false]
when :single
open, close, is_tag = ['‘', '’', false]
when :mark
open, close, is_tag = ['<mark>', '</mark>', true]
else
open, close, is_tag = [nil, nil, false]
end
inner_text = node.text
if (role = node.role)
if (text_transform = (load_theme node.document)[%(role_#{role}_text_transform)])
inner_text = transform_text inner_text, text_transform
end
quoted_text = is_tag ? %(#{open.chop} class="#{role}">#{inner_text}#{close}) : %(<span class="#{role}">#{open}#{inner_text}#{close}</span>)
else
quoted_text = %(#{open}#{inner_text}#{close})
end
# NOTE destination is created inside callback registered by FormattedTextTransform#build_fragment
node.id ? %(<a id="#{node.id}">#{DummyText}</a>#{quoted_text}) : quoted_text
end
def layout_title_page doc
return unless doc.header? && !doc.notitle
# NOTE a new page may have already been started at this point, so decide what to do with it
if page.empty?
page.reset_content if (recycle = @ppbook ? recto_page? : true)
elsif @ppbook && page_number > 0 && recto_page?
start_new_page
end
side = recycle ? page_side : (page_side page_number + 1)
prev_bg_image = @page_bg_image[side]
prev_bg_color = @page_bg_color
if (bg_image = resolve_background_image doc, @theme, 'title-page-background-image')
@page_bg_image[side] = bg_image[0] && bg_image
end
if (bg_color = resolve_theme_color :title_page_background_color)
@page_bg_color = bg_color
end
recycle ? (init_page self) : start_new_page
@page_bg_image[side] = prev_bg_image if bg_image
@page_bg_color = prev_bg_color if bg_color
# IMPORTANT this is the first page created, so we need to set the base font
font @theme.base_font_family, size: @root_font_size
# QUESTION allow alignment per element on title page?
title_align = (@theme.title_page_align || @base_align).to_sym
# FIXME: disallow .pdf as image type
if @theme.title_page_logo_display != 'none' && (logo_image_path = (doc.attr 'title-logo-image') || (logo_image_from_theme = @theme.title_page_logo_image))
if (logo_image_path.include? ':') && logo_image_path =~ ImageAttributeValueRx
logo_image_attrs = (AttributeList.new $2).parse %w(alt width height)
if logo_image_from_theme
relative_to_imagesdir = false
logo_image_path = sub_attributes_discretely doc, $1
logo_image_path = ThemeLoader.resolve_theme_asset logo_image_path, @themesdir unless doc.is_uri? logo_image_path
else
relative_to_imagesdir = true
logo_image_path = $1
end
else
logo_image_attrs = {}
relative_to_imagesdir = false
if logo_image_from_theme
logo_image_path = sub_attributes_discretely doc, logo_image_path
logo_image_path = ThemeLoader.resolve_theme_asset logo_image_path, @themesdir unless doc.is_uri? logo_image_path
end
end
logo_image_attrs['target'] = logo_image_path
# NOTE at the very least, title_align will be a valid alignment value
logo_image_attrs['align'] = [(logo_image_attrs.delete 'align'), @theme.title_page_logo_align, title_align.to_s].find {|val| (BlockAlignmentNames.include? val) }
if (logo_image_top = logo_image_attrs['top'] || @theme.title_page_logo_top)
initial_y, @y = @y, (resolve_top logo_image_top)
end
# FIXME: add API to Asciidoctor for creating blocks like this (extract from extensions module?)
image_block = ::Asciidoctor::Block.new doc, :image, content_model: :empty, attributes: logo_image_attrs
# NOTE pinned option keeps image on same page
indent (@theme.title_page_logo_margin_left || 0), (@theme.title_page_logo_margin_right || 0) do
convert_image image_block, relative_to_imagesdir: relative_to_imagesdir, pinned: true
end
@y = initial_y if initial_y
end
# TODO: prevent content from spilling to next page
theme_font :title_page do
if (title_top = @theme.title_page_title_top)
@y = resolve_top title_top
end
unless @theme.title_page_title_display == 'none'
doctitle = doc.doctitle partition: true
move_down(@theme.title_page_title_margin_top || 0)
indent (@theme.title_page_title_margin_left || 0), (@theme.title_page_title_margin_right || 0) do
theme_font :title_page_title do
layout_prose doctitle.main,
align: title_align,
margin: 0,
line_height: @theme.title_page_title_line_height
end
end
move_down(@theme.title_page_title_margin_bottom || 0)
end
if @theme.title_page_subtitle_display != 'none' && (subtitle = (doctitle || (doc.doctitle partition: true)).subtitle)
move_down(@theme.title_page_subtitle_margin_top || 0)
indent (@theme.title_page_subtitle_margin_left || 0), (@theme.title_page_subtitle_margin_right || 0) do
theme_font :title_page_subtitle do
layout_prose subtitle,
align: title_align,
margin: 0,
line_height: @theme.title_page_subtitle_line_height
end
end
move_down(@theme.title_page_subtitle_margin_bottom || 0)
end
if @theme.title_page_authors_display != 'none' && (doc.attr? 'authors')
move_down(@theme.title_page_authors_margin_top || 0)
indent (@theme.title_page_authors_margin_left || 0), (@theme.title_page_authors_margin_right || 0) do
generic_authors_content = @theme.title_page_authors_content
authors_content = {
name_only: @theme.title_page_authors_content_name_only || generic_authors_content,
with_email: @theme.title_page_authors_content_with_email || generic_authors_content,
with_url: @theme.title_page_authors_content_with_url || generic_authors_content,
}
# TODO: provide an API in core to get authors as an array
authors = (1..(doc.attr 'authorcount', 1).to_i).map {|idx|
promote_author doc, idx do
author_content_key = (url = doc.attr 'url') ? ((url.start_with? 'mailto:') ? :with_email : :with_url) : :name_only
if (author_content = authors_content[author_content_key])
apply_subs_discretely doc, author_content, drop_lines_with_unresolved_attributes: true
else
doc.attr 'author'
end
end
}.join (@theme.title_page_authors_delimiter || ', ')
theme_font :title_page_authors do
layout_prose authors,
align: title_align,
margin: 0,
normalize: true
end
end
move_down(@theme.title_page_authors_margin_bottom || 0)
end
unless @theme.title_page_revision_display == 'none' || (revision_info = [(doc.attr? 'revnumber') ? %(#{doc.attr 'version-label'} #{doc.attr 'revnumber'}) : nil, (doc.attr 'revdate')].compact).empty?
move_down(@theme.title_page_revision_margin_top || 0)
revision_text = revision_info.join (@theme.title_page_revision_delimiter || ', ')
if (revremark = doc.attr 'revremark')
revision_text = %(#{revision_text}: #{revremark})
end
indent (@theme.title_page_revision_margin_left || 0), (@theme.title_page_revision_margin_right || 0) do
theme_font :title_page_revision do
layout_prose revision_text,
align: title_align,
margin: 0,
normalize: false
end
end
move_down(@theme.title_page_revision_margin_bottom || 0)
end
end
layout_prose DummyText, margin: 0, line_height: 1, normalize: false if page.empty?
end
def layout_cover_page doc, face
bg_image = resolve_background_image doc, @theme, %(#{face}-cover-image), theme_key: %(cover_#{face}_image).to_sym, symbolic_paths: ['', '~']
if bg_image && bg_image[0]
image_path, image_opts = bg_image
if image_path.empty?
go_to_page page_count if face == :back
start_new_page_discretely
# NOTE open graphics state to prevent page from being reused
open_graphics_state if face == :front
return
elsif image_path == '~'
@page_margin_by_side[:cover] = @page_margin_by_side[:recto] if @media == 'prepress'
return
end
go_to_page page_count if face == :back
if image_opts[:format] == 'pdf'
import_page image_path, (image_opts.merge advance: face != :back)
else
image_page image_path, (image_opts.merge canvas: true)
end
end
end
def stamp_foreground_image doc, has_front_cover
pages = state.pages
if (first_page = (has_front_cover ? (pages.slice 1, pages.size) : pages).find {|it| !it.imported_page? }) &&
(first_page_num = (pages.index first_page) + 1) &&
(fg_image = resolve_background_image doc, @theme, 'page-foreground-image') && fg_image[0]
go_to_page first_page_num
create_stamp 'foreground-image' do
canvas { image fg_image[0], ({ position: :center, vposition: :center }.merge fg_image[1]) }
end
stamp 'foreground-image'
(first_page_num.next..page_count).each do |num|
go_to_page num
stamp 'foreground-image' unless page.imported_page?
end
end
end
def start_new_chapter chapter
start_new_page unless at_page_top?
# TODO: must call update_colors before advancing to next page if start_new_page is called in layout_chapter_title
start_new_page if @ppbook && verso_page? && !(chapter.option? 'nonfacing')
end
alias start_new_part start_new_chapter
def layout_chapter_title _node, title, opts = {}
layout_heading title, (opts.merge outdent: true)
end
alias layout_part_title layout_chapter_title
# NOTE layout_heading doesn't set the theme font because it's used for various types of headings
# QUESTION why doesn't layout_heading accept a node?
def layout_heading string, opts = {}
hlevel = opts[:level]
unless (top_margin = (margin = (opts.delete :margin)) || (opts.delete :margin_top))
if at_page_top?
if hlevel && (top_margin = @theme[%(heading_h#{hlevel}_margin_page_top)] || @theme.heading_margin_page_top || 0) > 0
move_down top_margin
end
top_margin = 0
else
top_margin = (hlevel ? @theme[%(heading_h#{hlevel}_margin_top)] : nil) || @theme.heading_margin_top
end
end
bot_margin = margin || (opts.delete :margin_bottom) || (hlevel ? @theme[%(heading_h#{hlevel}_margin_bottom)] : nil) || @theme.heading_margin_bottom
if (transform = resolve_text_transform opts)
string = transform_text string, transform
end
outdent_section opts.delete :outdent do
margin_top top_margin
# QUESTION should we move inherited styles to typeset_text?
if (inherited = apply_text_decoration font_styles, :heading, hlevel).empty?
inline_format_opts = true
else
inline_format_opts = [{ inherited: inherited }]
end
typeset_text string, calc_line_metrics((opts.delete :line_height) || (hlevel ? @theme[%(heading_h#{hlevel}_line_height)] : nil) || @theme.heading_line_height || @theme.base_line_height), {
color: @font_color,
inline_format: inline_format_opts,
align: @base_align.to_sym,
}.merge(opts)
margin_bottom bot_margin
end
end
# NOTE inline_format is true by default
def layout_prose string, opts = {}
top_margin = (margin = (opts.delete :margin)) || (opts.delete :margin_top) || @theme.prose_margin_top
bot_margin = margin || (opts.delete :margin_bottom) || @theme.prose_margin_bottom
if (transform = resolve_text_transform opts)
string = transform_text string, transform
end
string = hyphenate_text string, @hyphenator if (opts.delete :hyphenate) && (defined? @hyphenator)
# NOTE used by extensions; ensures linked text gets formatted using the link styles
if (anchor = opts.delete :anchor)
string = %(<a anchor="#{anchor}">#{string}</a>)
end
margin_top top_margin
# NOTE normalize makes endlines soft (replaces "\n" with ' ')
inline_format_opts = { normalize: (opts.delete :normalize) != false }
if (styles = opts.delete :styles)
inline_format_opts[:inherited] = { styles: styles }
end
typeset_text string, calc_line_metrics((opts.delete :line_height) || @theme.base_line_height), {
color: @font_color,
inline_format: [inline_format_opts],
align: @base_align.to_sym,
}.merge(opts)
margin_bottom bot_margin
end
def generate_manname_section node
title = node.attr 'manname-title', 'Name'
if (next_section = node.sections[0]) && (next_section_title = next_section.title) == next_section_title.upcase
title = title.upcase
end
sect = Section.new node, 1
sect.sectname = 'section'
sect.id = node.attr 'manname-id'
sect.title = title
sect << (Block.new sect, :paragraph, source: %(#{node.attr 'manname'} - #{node.attr 'manpurpose'}), subs: :normal)
sect
end
# Render the caption and return the height of the rendered content
#
# The subject argument can either be a String or an AbstractNode. If
# subject is an AbstractNode, only call this method if the node has a
# title (i.e., subject.title? return true).
#--
# TODO: allow margin to be zeroed
def layout_caption subject, opts = {}
if opts.delete :dry_run
height = nil
dry_run do
move_down 0.001 # HACK: force top margin to be applied
height = layout_caption subject, opts
end
return height
end
mark = { cursor: cursor, page_number: page_number }
if ::Asciidoctor::AbstractBlock === subject
string = (opts.delete :labeled) == false ? subject.title : subject.captioned_title
else
string = subject.to_s
end
category_caption = (category = opts[:category]) ? %(#{category}_caption) : 'caption'
container_width = bounds.width
block_align = opts.delete :block_align
if (align = @theme[%(#{category_caption}_align)] || @theme.caption_align)
align = align == 'inherit' ? (block_align || @base_align) : align.to_sym
else
align = @base_align.to_sym
end
if (text_align = @theme[%(#{category_caption}_text_align)] || @theme.caption_text_align)
text_align = text_align == 'inherit' ? align : text_align.to_sym
else
text_align = align
end
indent_by = [0, 0]
block_width = opts.delete :block_width
if (max_width = opts.delete :max_width) && max_width != 'none'
if ::String === max_width
if max_width.start_with? 'fit-content'
if max_width.end_with? 't', '()'
max_width = block_width || container_width
else
max_width = (block_width || container_width) * (max_width.slice 12, max_width.length - 1).to_f / 100.0
end
elsif max_width.end_with? '%'
max_width = [max_width.to_f / 100 * bounds.width, bounds.width].min
block_align = align
else
max_width = [max_width.to_f, bounds.width].min
block_align = align
end
else
max_width = [max_width, bounds.width].min
block_align = align
end
if (remainder = container_width - max_width) > 0
case block_align
when :right
indent_by = [remainder, 0]
when :center
indent_by = [(side_margin = remainder * 0.5), side_margin]
else # :left, nil
indent_by = [0, remainder]
end
end
end
theme_font :caption do
theme_font category_caption do
caption_margin_outside = @theme[%(#{category_caption}_margin_outside)] || @theme.caption_margin_outside
caption_margin_inside = @theme[%(#{category_caption}_margin_inside)] || @theme.caption_margin_inside
if ((opts.delete :side) || :top) == :top
margin = { top: caption_margin_outside, bottom: caption_margin_inside }
else
margin = { top: caption_margin_inside, bottom: caption_margin_outside }
end
indent(*indent_by) do
layout_prose string, {
margin_top: margin[:top],
margin_bottom: margin[:bottom],
align: text_align,
normalize: false,
normalize_line_height: true,
hyphenate: true,
}.merge(opts)
end
end
end
# NOTE we assume we don't clear more than one page
if page_number > mark[:page_number]
mark[:cursor] + (bounds.top - cursor)
else
mark[:cursor] - cursor
end
end
# Render the caption for a table and return the height of the rendered content
def layout_table_caption node, table_alignment = :left, table_width = nil, max_width = nil, side = :top
layout_caption node, category: :table, side: side, block_align: table_alignment, block_width: table_width, max_width: max_width
end
def allocate_toc doc, toc_num_levels, toc_start_y, use_title_page
toc_page_nums = page_number
toc_end = nil
dry_run do
toc_page_nums = layout_toc doc, toc_num_levels, toc_page_nums, toc_start_y
move_down @theme.block_margin_bottom unless use_title_page
toc_end = @y
end
# NOTE reserve pages for the toc; leaves cursor on page after last page in toc
if use_title_page
toc_page_nums.each { start_new_page }
else
(toc_page_nums.size - 1).times { start_new_page }
@y = toc_end
end
@toc_extent = { page_nums: toc_page_nums, start_y: toc_start_y }
end
# NOTE num_front_matter_pages is not used during a dry run
def layout_toc doc, num_levels = 2, toc_page_number = 2, start_y = @y, num_front_matter_pages = 0
go_to_page toc_page_number unless (page_number == toc_page_number) || scratch?
start_page_number = page_number
@y = start_y
unless (toc_title = doc.attr 'toc-title').nil_or_empty?
theme_font :heading, level: 2 do
theme_font :toc_title do
toc_title_align = (@theme.toc_title_align || @theme.heading_h2_align || @theme.heading_align || @base_align).to_sym
layout_heading toc_title, align: toc_title_align, level: 2, outdent: true
end
end
end
# QUESTION should we skip this whole method if num_levels < 0?
unless num_levels < 0
dot_leader = theme_font :toc do
# TODO: we could simplify by using nested theme_font :toc_dot_leader
if (dot_leader_font_style = (@theme.toc_dot_leader_font_style || :normal).to_sym) != font_style
font_style dot_leader_font_style
end
{
font_color: @theme.toc_dot_leader_font_color || @font_color,
font_style: dot_leader_font_style,
levels: ((dot_leader_l = @theme.toc_dot_leader_levels) == 'none' ? ::Set.new :
(dot_leader_l && dot_leader_l != 'all' ? dot_leader_l.to_s.split.map(&:to_i).to_set : (0..num_levels).to_set)),
text: (dot_leader_text = @theme.toc_dot_leader_content || DotLeaderTextDefault),
width: dot_leader_text.empty? ? 0 : (rendered_width_of_string dot_leader_text),
# TODO: spacer gives a little bit of room between dots and page number
spacer: { text: NoBreakSpace, size: (spacer_font_size = @font_size * 0.25) },
spacer_width: (rendered_width_of_char NoBreakSpace, size: spacer_font_size),
}
end
line_metrics = calc_line_metrics @theme.toc_line_height
theme_margin :toc, :top
layout_toc_level doc.sections, num_levels, line_metrics, dot_leader, num_front_matter_pages
end
# NOTE range must be calculated relative to toc_page_number; absolute page number in scratch document is arbitrary
toc_page_numbers = (toc_page_number..(toc_page_number + (page_number - start_page_number)))
go_to_page page_count unless scratch?
toc_page_numbers
end
def layout_toc_level sections, num_levels, line_metrics, dot_leader, num_front_matter_pages = 0
# NOTE font options aren't always reliable, so store size separately
toc_font_info = theme_font :toc do
{ font: font, size: @font_size }
end
hanging_indent = @theme.toc_hanging_indent || 0
sections.each do |sect|
next if (num_levels_for_sect = (sect.attr 'toclevels', num_levels).to_i) < sect.level
theme_font :toc, level: (sect.level + 1) do
sect_title = @text_transform ? (transform_text sect.numbered_title, @text_transform) : sect.numbered_title
pgnum_label_placeholder_width = rendered_width_of_string '0' * @toc_max_pagenum_digits
# NOTE only write section title (excluding dots and page number) if this is a dry run
if scratch?
indent 0, pgnum_label_placeholder_width do
# FIXME: use layout_prose
# NOTE must wrap title in empty anchor element in case links are styled with different font family / size
typeset_text %(<a>#{sect_title}</a>), line_metrics, inline_format: true, hanging_indent: hanging_indent, normalize_line_height: true
end
else
physical_pgnum = sect.attr 'pdf-page-start'
virtual_pgnum = physical_pgnum - num_front_matter_pages
pgnum_label = (virtual_pgnum < 1 ? (RomanNumeral.new physical_pgnum, :lower) : virtual_pgnum).to_s
start_page_number = page_number
start_cursor = cursor
start_dots = nil
sect_title_inherited = (apply_text_decoration ::Set.new, :toc, sect.level.next).merge anchor: (sect_anchor = sect.attr 'pdf-anchor'), color: @font_color
# NOTE use text formatter to add anchor overlay to avoid using inline format with synthetic anchor tag
sect_title_fragments = text_formatter.format sect_title, inherited: sect_title_inherited
indent 0, pgnum_label_placeholder_width do
sect_title_fragments[-1][:callback] = (last_fragment_pos = ::Asciidoctor::PDF::FormattedText::FragmentPositionRenderer.new)
typeset_formatted_text sect_title_fragments, line_metrics, hanging_indent: hanging_indent, normalize_line_height: true
start_dots = last_fragment_pos.right + hanging_indent
last_fragment_cursor = last_fragment_pos.top + line_metrics.padding_top
if (last_fragment_page_number = last_fragment_pos.page_number) > start_page_number ||
(start_cursor - last_fragment_cursor) > line_metrics.height
start_page_number = last_fragment_page_number
start_cursor = last_fragment_cursor
end
end
end_page_number = page_number
end_cursor = cursor
# TODO: it would be convenient to have a cursor mark / placement utility that took page number into account
go_to_page start_page_number if start_page_number != end_page_number
move_cursor_to start_cursor
if dot_leader[:width] > 0 && (dot_leader[:levels].include? sect.level)
pgnum_label_width = rendered_width_of_string pgnum_label
pgnum_label_font_settings = { color: @font_color, font: font_family, size: @font_size, styles: font_styles }
save_font do
# NOTE the same font is used for dot leaders throughout toc
set_font toc_font_info[:font], toc_font_info[:size]
font_style dot_leader[:font_style]
num_dots = ((bounds.width - start_dots - dot_leader[:spacer_width] - pgnum_label_width) / dot_leader[:width]).floor
# FIXME: dots don't line up in columns if width of page numbers differ
typeset_formatted_text [
{ text: (dot_leader[:text] * (num_dots < 0 ? 0 : num_dots)), color: dot_leader[:font_color] },
dot_leader[:spacer],
{ text: pgnum_label, anchor: sect_anchor }.merge(pgnum_label_font_settings),
], line_metrics, align: :right
end
else
typeset_formatted_text [{ text: pgnum_label, color: @font_color, anchor: sect_anchor }], line_metrics, align: :right
end
go_to_page end_page_number if page_number != end_page_number
move_cursor_to end_cursor
end
end
indent @theme.toc_indent do
layout_toc_level sect.sections, num_levels_for_sect, line_metrics, dot_leader, num_front_matter_pages
end if num_levels_for_sect > sect.level
end
end
# Reduce icon height to fit inside bounds.height. Icons will not render
# properly if they are larger than the current bounds.height.
def fit_icon_to_bounds preferred_size = 24
(max_height = bounds.height) < preferred_size ? max_height : preferred_size
end
def admonition_icon_data key
if (icon_data = @theme[%(admonition_icon_#{key})])
icon_data = (AdmonitionIcons[key] || {}).merge icon_data
if (icon_name = icon_data[:name])
unless icon_name.start_with?(*IconSetPrefixes)
logger.info { %(#{key} admonition in theme uses icon from deprecated fa icon set; use fas, far, or fab instead) } unless scratch?
icon_data[:name] = %(fa-#{icon_name}) unless icon_name.start_with? 'fa-'
end
else
icon_data[:name] = AdmonitionIcons[:note][:name]
end
else
(icon_data = AdmonitionIcons[key] || {})[:name] ||= AdmonitionIcons[:note][:name]
end
icon_data
end
# TODO: delegate to layout_page_header and layout_page_footer per page
def layout_running_content periphery, doc, opts = {}
skip, skip_pagenums = opts[:skip] || [1, 1]
body_start_page_number = opts[:body_start_page_number] || 1
# NOTE find and advance to first non-imported content page to use as model page
return unless (content_start_page = state.pages[skip..-1].index {|it| !it.imported_page? })
content_start_page += (skip + 1)
num_pages = page_count
prev_page_number = page_number
go_to_page content_start_page
# FIXME: probably need to treat doctypes differently
is_book = doc.doctype == 'book'
header = doc.header? ? doc.header : nil
sectlevels = (@theme[%(#{periphery}_sectlevels)] || 2).to_i
sections = doc.find_by(context: :section) {|sect| sect.level <= sectlevels && sect != header }
if (toc_page_nums = @toc_extent && @toc_extent[:page_nums])
toc_title = (doc.attr 'toc-title') || ''
end
disable_on_pages = @disable_running_content[periphery]
title_method = TitleStyles[@theme[%(#{periphery}_title_style)]]
# FIXME: we need a proper model for all this page counting
# FIXME: we make a big assumption that part & chapter start on new pages
# index parts, chapters and sections by the physical page number on which they start
part_start_pages = {}
chapter_start_pages = {}
section_start_pages = {}
trailing_section_start_pages = {}
sections.each do |sect|
pgnum = (sect.attr 'pdf-page-start').to_i
if is_book && ((sect_is_part = sect.part?) || sect.chapter?)
if sect_is_part
part_start_pages[pgnum] ||= sect
else
chapter_start_pages[pgnum] ||= sect
# FIXME: need a better way to indicate that part has ended
part_start_pages[pgnum] = '' if sect.sectname == 'appendix' && !part_start_pages.empty?
end
else
trailing_section_start_pages[pgnum] = sect
section_start_pages[pgnum] ||= sect
end
end
# index parts, chapters, and sections by the physical page number on which they appear
parts_by_page = SectionInfoByPage.new title_method
chapters_by_page = SectionInfoByPage.new title_method
sections_by_page = SectionInfoByPage.new title_method
# QUESTION should the default part be the doctitle?
last_part = nil
# QUESTION should we enforce that the preamble is a preface?
last_chap = is_book ? :pre : nil
last_sect = nil
sect_search_threshold = 1
(1..num_pages).each do |pgnum|
if (part = part_start_pages[pgnum])
last_part = part
last_chap = nil
last_sect = nil
end
if (chap = chapter_start_pages[pgnum])
last_chap = chap
last_sect = nil
end
if (sect = section_start_pages[pgnum])
last_sect = sect
elsif part || chap
sect_search_threshold = pgnum
# NOTE we didn't find a section on this page; look back to find last section started
elsif last_sect
(sect_search_threshold..(pgnum - 1)).reverse_each do |prev|
if (sect = trailing_section_start_pages[prev])
last_sect = sect
break
end
end
end
parts_by_page[pgnum] = last_part
if toc_page_nums && (toc_page_nums.cover? pgnum)
if is_book
chapters_by_page[pgnum] = toc_title
sections_by_page[pgnum] = nil
else
chapters_by_page[pgnum] = nil
sections_by_page[pgnum] = section_start_pages[pgnum] || toc_title
end
toc_page_nums = nil if toc_page_nums.end == pgnum
elsif last_chap == :pre
chapters_by_page[pgnum] = pgnum < body_start_page_number ? doc.doctitle : (doc.attr 'preface-title', 'Preface')
sections_by_page[pgnum] = last_sect
else
chapters_by_page[pgnum] = last_chap
sections_by_page[pgnum] = last_sect
end
end
doctitle = doc.doctitle partition: true, use_fallback: true
# NOTE set doctitle again so it's properly escaped
doc.set_attr 'doctitle', doctitle.combined
doc.set_attr 'document-title', doctitle.main
doc.set_attr 'document-subtitle', doctitle.subtitle
doc.set_attr 'page-count', (num_pages - skip_pagenums)
pagenums_enabled = doc.attr? 'pagenums'
case @media == 'prepress' ? 'physical' : (doc.attr 'pdf-folio-placement')
when 'physical'
folio_basis, invert_folio = :physical, false
when 'physical-inverted'
folio_basis, invert_folio = :physical, true
when 'virtual-inverted'
folio_basis, invert_folio = :virtual, true
else
folio_basis, invert_folio = :virtual, false
end
periphery_layout_cache = {}
# NOTE: this block is invoked during PDF generation, after convert_document has returned
repeat (content_start_page..num_pages), dynamic: true do
pgnum = page_number
# NOTE: don't write on pages which are imported / inserts (otherwise we can get a corrupt PDF)
next if page.imported_page? || (disable_on_pages && (disable_on_pages.include? pgnum))
virtual_pgnum = pgnum - skip_pagenums
pgnum_label = (virtual_pgnum < 1 ? (RomanNumeral.new pgnum, :lower) : virtual_pgnum).to_s
side = page_side((folio_basis == :physical ? pgnum : virtual_pgnum), invert_folio)
doc.set_attr 'page-layout', page.layout.to_s
# NOTE: running content is cached per page layout
# QUESTION: should allocation be per side?
trim_styles, colspec_dict, content_dict, stamp_names = allocate_running_content_layout doc, page, periphery, periphery_layout_cache
# FIXME: we need to have a content setting for chapter pages
content_by_position, colspec_by_position = content_dict[side], colspec_dict[side]
doc.set_attr 'page-number', pgnum_label if pagenums_enabled
# QUESTION should the fallback value be nil instead of empty string? or should we remove attribute if no value?
doc.set_attr 'part-title', ((part_info = parts_by_page[pgnum])[:title] || '')
if (part_numeral = part_info[:numeral])
doc.set_attr 'part-numeral', part_numeral
else
doc.remove_attr 'part-numeral'
end
doc.set_attr 'chapter-title', ((chap_info = chapters_by_page[pgnum])[:title] || '')
if (chap_numeral = chap_info[:numeral])
doc.set_attr 'chapter-numeral', chap_numeral
else
doc.remove_attr 'chapter-numeral'
end
doc.set_attr 'section-title', ((sect_info = sections_by_page[pgnum])[:title] || '')
doc.set_attr 'section-or-chapter-title', (sect_info[:title] || chap_info[:title] || '')
stamp stamp_names[side] if stamp_names
theme_font periphery do
canvas do
bounding_box [trim_styles[:content_left][side], trim_styles[:top][side]], width: trim_styles[:content_width][side], height: trim_styles[:height] do
if (trim_column_rule_width = trim_styles[:column_rule_width]) > 0
trim_column_rule_spacing = trim_styles[:column_rule_spacing]
else
trim_column_rule_width = nil
end
prev_position = nil
ColumnPositions.each do |position|
next unless (content = content_by_position[position])
next unless (colspec = colspec_by_position[position])[:width] > 0
left, colwidth = colspec[:x], colspec[:width]
if trim_column_rule_width && colwidth < bounds.width
if (trim_column_rule = prev_position)
left += (trim_column_rule_spacing * 0.5)
colwidth -= trim_column_rule_spacing
else
colwidth -= (trim_column_rule_spacing * 0.5)
end
end
# FIXME: we need to have a content setting for chapter pages
if ::Array === content
# NOTE float ensures cursor position is restored and returns us to current page if we overrun
float do
# NOTE bounding_box is redundant if both vertical padding and border width are 0
bounding_box [left, bounds.top - trim_styles[:padding][side][0] - trim_styles[:content_offset]], width: colwidth, height: trim_styles[:content_height][side] do
# NOTE image vposition respects padding; use negative image_vertical_align value to revert
image_opts = content[1].merge position: colspec[:align], vposition: trim_styles[:img_valign]
begin
image_info = image content[0], image_opts
if (image_link = content[2])
image_info = { width: image_info.scaled_width, height: image_info.scaled_height } unless image_opts[:format] == 'svg'
add_link_to_image image_link, image_info, image_opts
end
rescue
logger.warn %(could not embed image in running content: #{content[0]}; #{$!.message})
end
end
end
else
theme_font %(#{periphery}_#{side}_#{position}) do
# NOTE minor optimization
if content == '{page-number}'
content = pagenums_enabled ? pgnum_label : nil
else
content = apply_subs_discretely doc, content, drop_lines_with_unresolved_attributes: true
content = transform_text content, @text_transform if @text_transform
end
formatted_text_box parse_text(content, color: @font_color, inline_format: [normalize: true]),
at: [left, bounds.top - trim_styles[:padding][side][0] - trim_styles[:content_offset] + ((Array trim_styles[:valign])[0] == :center ? font.descender * 0.5 : 0)],
width: colwidth,
height: trim_styles[:prose_content_height][side],
align: colspec[:align],
valign: trim_styles[:valign],
leading: trim_styles[:line_metrics].leading,
final_gap: false,
overflow: :truncate
end
end
bounding_box [colspec[:x], bounds.top - trim_styles[:padding][side][0] - trim_styles[:content_offset]], width: colspec[:width], height: trim_styles[:content_height][side] do
stroke_vertical_rule trim_styles[:column_rule_color], at: bounds.left, line_style: trim_styles[:column_rule_style], line_width: trim_column_rule_width
end if trim_column_rule
prev_position = position
end
end
end
end
end
go_to_page prev_page_number
nil
end
def allocate_running_content_layout doc, page, periphery, cache
cache[layout = page.layout] ||= begin
page_margin_recto = @page_margin_by_side[:recto]
trim_margin_recto = @theme[%(#{periphery}_recto_margin)] || @theme[%(#{periphery}_margin)] || [0, 'inherit', 0, 'inherit']
trim_margin_recto = (expand_margin_value trim_margin_recto).map.with_index {|v, i| i.odd? && v == 'inherit' ? page_margin_recto[i] : v.to_f }
trim_content_margin_recto = @theme[%(#{periphery}_recto_content_margin)] || @theme[%(#{periphery}_content_margin)] || [0, 'inherit', 0, 'inherit']
trim_content_margin_recto = (expand_margin_value trim_content_margin_recto).map.with_index {|v, i| i.odd? && v == 'inherit' ? page_margin_recto[i] - trim_margin_recto[i] : v.to_f }
if (trim_padding_recto = @theme[%(#{periphery}_recto_padding)] || @theme[%(#{periphery}_padding)])
trim_padding_recto = (expand_margin_value trim_padding_recto).map.with_index {|v, i| v + trim_content_margin_recto[i] }
else
trim_padding_recto = trim_content_margin_recto
end
page_margin_verso = @page_margin_by_side[:verso]
trim_margin_verso = @theme[%(#{periphery}_verso_margin)] || @theme[%(#{periphery}_margin)] || [0, 'inherit', 0, 'inherit']
trim_margin_verso = (expand_margin_value trim_margin_verso).map.with_index {|v, i| i.odd? && v == 'inherit' ? page_margin_verso[i] : v.to_f }
trim_content_margin_verso = @theme[%(#{periphery}_verso_content_margin)] || @theme[%(#{periphery}_content_margin)] || [0, 'inherit', 0, 'inherit']
trim_content_margin_verso = (expand_margin_value trim_content_margin_verso).map.with_index {|v, i| i.odd? && v == 'inherit' ? page_margin_verso[i] - trim_margin_verso[i] : v.to_f }
if (trim_padding_verso = @theme[%(#{periphery}_verso_padding)] || @theme[%(#{periphery}_padding)])
trim_padding_verso = (expand_margin_value trim_padding_verso).map.with_index {|v, i| v + trim_content_margin_verso[i] }
else
trim_padding_verso = trim_content_margin_verso
end
valign, valign_offset = @theme[%(#{periphery}_vertical_align)]
if (valign = (valign || :middle).to_sym) == :middle
valign = :center
end
trim_styles = {
line_metrics: (trim_line_metrics = calc_line_metrics @theme[%(#{periphery}_line_height)] || @theme.base_line_height),
# NOTE we've already verified this property is set
height: (trim_height = @theme[%(#{periphery}_height)]),
bg_color: (resolve_theme_color %(#{periphery}_background_color).to_sym),
border_color: (trim_border_color = resolve_theme_color %(#{periphery}_border_color).to_sym),
border_style: (@theme[%(#{periphery}_border_style)] || :solid).to_sym,
border_width: (trim_border_width = trim_border_color ? @theme[%(#{periphery}_border_width)] || @theme.base_border_width || 0 : 0),
column_rule_color: (trim_column_rule_color = resolve_theme_color %(#{periphery}_column_rule_color).to_sym),
column_rule_style: (@theme[%(#{periphery}_column_rule_style)] || :solid).to_sym,
column_rule_width: (trim_column_rule_color ? @theme[%(#{periphery}_column_rule_width)] || 0 : 0),
column_rule_spacing: (@theme[%(#{periphery}_column_rule_spacing)] || 0),
valign: valign_offset ? [valign, valign_offset] : valign,
img_valign: @theme[%(#{periphery}_image_vertical_align)],
top: {
recto: periphery == :header ? page_height - trim_margin_recto[0] : trim_height + trim_margin_recto[2],
verso: periphery == :header ? page_height - trim_margin_verso[0] : trim_height + trim_margin_verso[2],
},
left: {
recto: (trim_left_recto = trim_margin_recto[3]),
verso: (trim_left_verso = trim_margin_verso[3]),
},
width: {
recto: (trim_width_recto = page_width - trim_left_recto - trim_margin_recto[1]),
verso: (trim_width_verso = page_width - trim_left_verso - trim_margin_verso[1]),
},
padding: {
recto: trim_padding_recto,
verso: trim_padding_verso,
},
content_left: {
recto: trim_left_recto + trim_padding_recto[3],
verso: trim_left_verso + trim_padding_verso[3],
},
content_width: (trim_content_width = {
recto: trim_width_recto - trim_padding_recto[1] - trim_padding_recto[3],
verso: trim_width_verso - trim_padding_verso[1] - trim_padding_verso[3],
}),
content_height: (trim_content_height = {
recto: trim_height - trim_padding_recto[0] - trim_padding_recto[2] - (trim_border_width * 0.5),
verso: trim_height - trim_padding_verso[0] - trim_padding_verso[2] - (trim_border_width * 0.5),
}),
prose_content_height: {
recto: trim_content_height[:recto] - trim_line_metrics.padding_top - trim_line_metrics.padding_bottom,
verso: trim_content_height[:verso] - trim_line_metrics.padding_top - trim_line_metrics.padding_bottom,
},
# NOTE content offset adjusts y position to account for border
content_offset: (periphery == :footer ? trim_border_width * 0.5 : 0),
}
case trim_styles[:img_valign]
when nil
trim_styles[:img_valign] = valign
when 'middle'
trim_styles[:img_valign] = :center
when 'top', 'center', 'bottom'
trim_styles[:img_valign] = trim_styles[:img_valign].to_sym
end
if (trim_bg_image_recto = resolve_background_image doc, @theme, %(#{periphery}_background_image).to_sym, container_size: [trim_width_recto, trim_height]) && trim_bg_image_recto[0]
trim_bg_image = { recto: trim_bg_image_recto }
if trim_width_recto == trim_width_verso
trim_bg_image[:verso] = trim_bg_image_recto
else
trim_bg_image[:verso] = resolve_background_image doc, @theme, %(#{periphery}_background_image).to_sym, container_size: [trim_width_verso, trim_height]
end
end
colspec_dict = PageSides.each_with_object({}) do |side, acc|
side_trim_content_width = trim_content_width[side]
if (custom_colspecs = @theme[%(#{periphery}_#{side}_columns)] || @theme[%(#{periphery}_columns)])
case (colspecs = (custom_colspecs.to_s.tr ',', ' ').split).size
when 0, 1
colspecs = { left: '0', center: colspecs[0] || '100', right: '0' }
when 2
colspecs = { left: colspecs[0], center: '0', right: colspecs[1] }
else # 3
colspecs = { left: colspecs[0], center: colspecs[1], right: colspecs[2] }
end
tot_width = 0
side_colspecs = colspecs.map {|col, spec|
if (alignment_char = spec.chr).to_i.to_s != alignment_char
alignment = AlignmentTable[alignment_char]
rel_width = (spec.slice 1, spec.length).to_f
else
alignment = :left
rel_width = spec.to_f
end
tot_width += rel_width
[col, { align: alignment, width: rel_width, x: 0 }]
}.to_h
# QUESTION should we allow the columns to overlap (capping width at 100%)?
side_colspecs.each {|_, colspec| colspec[:width] = (colspec[:width] / tot_width) * side_trim_content_width }
side_colspecs[:right][:x] = (side_colspecs[:center][:x] = side_colspecs[:left][:width]) + side_colspecs[:center][:width]
acc[side] = side_colspecs
else
acc[side] = {
left: { align: :left, width: side_trim_content_width, x: 0 },
center: { align: :center, width: side_trim_content_width, x: 0 },
right: { align: :right, width: side_trim_content_width, x: 0 },
}
end
end
content_dict = PageSides.each_with_object({}) do |side, acc|
side_content = {}
ColumnPositions.each do |position|
next if (val = @theme[%(#{periphery}_#{side}_#{position}_content)]).nil_or_empty?
val = val.to_s unless ::String === val
if (val.include? ':') && val =~ ImageAttributeValueRx
attrlist = $2
image_attrs = (AttributeList.new attrlist).parse %w(alt width)
image_path, image_format = ::Asciidoctor::Image.target_and_format $1, image_attrs
if (image_path = resolve_image_path doc, image_path, image_format, @themesdir) && (::File.readable? image_path)
image_opts = resolve_image_options image_path, image_format, image_attrs, container_size: [colspec_dict[side][position][:width], trim_content_height[side]]
side_content[position] = [image_path, image_opts, image_attrs['link']]
else
# NOTE allows inline image handler to report invalid reference and replace with alt text
side_content[position] = %(image:#{image_path}[#{attrlist}])
end
else
side_content[position] = val
end
end
acc[side] = side_content
end
if (trim_bg_color = trim_styles[:bg_color]) || trim_bg_image || trim_border_width > 0
stamp_names = { recto: %(#{layout}_#{periphery}_recto), verso: %(#{layout}_#{periphery}_verso) }
PageSides.each do |side|
create_stamp stamp_names[side] do
canvas do
bounding_box [trim_styles[:left][side], trim_styles[:top][side]], width: trim_styles[:width][side], height: trim_height do
fill_bounds trim_bg_color if trim_bg_color
# NOTE: must draw line before image or SVG will cause border to disappear
stroke_horizontal_rule trim_styles[:border_color], line_width: trim_border_width, line_style: trim_styles[:border_style], at: (periphery == :header ? bounds.height : 0) if trim_border_width > 0
image trim_bg_image[side][0], ({ position: :center, vposition: :center }.merge trim_bg_image[side][1]) if trim_bg_image
end
end
end
end
end
[trim_styles, colspec_dict, content_dict, stamp_names]
end
end
def add_outline doc, num_levels = 2, toc_page_nums = [], num_front_matter_pages = 0, has_front_cover = false
if ::String === num_levels
if num_levels.include? ':'
num_levels, expand_levels = num_levels.split ':', 2
num_levels = num_levels.empty? ? (doc.attr 'toclevels', 2).to_i : num_levels.to_i
expand_levels = expand_levels.to_i
else
num_levels = expand_levels = num_levels.to_i
end
else
expand_levels = num_levels
end
front_matter_counter = RomanNumeral.new 0, :lower
pagenum_labels = {}
num_front_matter_pages.times do |n|
pagenum_labels[n] = { P: (::PDF::Core::LiteralString.new front_matter_counter.next!.to_s) }
end
# add labels for each content page, which is required for reader's page navigator to work correctly
(num_front_matter_pages..(page_count - 1)).each_with_index do |n, i|
pagenum_labels[n] = { P: (::PDF::Core::LiteralString.new (i + 1).to_s) }
end
unless toc_page_nums.none? || (toc_title = doc.attr 'toc-title').nil_or_empty?
toc_section = insert_toc_section doc, toc_title, toc_page_nums
end
outline.define do
initial_pagenum = has_front_cover ? 2 : 1
# FIXME: use sanitize: :plain_text once available
if document.page_count >= initial_pagenum && (doctitle = doc.header? ? doc.doctitle : (doc.attr 'untitled-label'))
page title: (document.sanitize doctitle), destination: (document.dest_top has_front_cover ? 2 : 1)
end
# QUESTION is there any way to get add_outline_level to invoke in the context of the outline?
document.add_outline_level self, doc.sections, num_levels, expand_levels
end if doc.attr? 'outline'
toc_section.parent.blocks.delete toc_section if toc_section
catalog.data[:PageLabels] = state.store.ref Nums: pagenum_labels.flatten
primary_page_mode, secondary_page_mode = PageModes[(doc.attr 'pdf-page-mode') || @theme.page_mode]
catalog.data[:PageMode] = primary_page_mode
catalog.data[:NonFullScreenPageMode] = secondary_page_mode if secondary_page_mode
nil
end
def add_outline_level outline, sections, num_levels, expand_levels
sections.each do |sect|
sect_title = sanitize sect.numbered_title formal: true
sect_destination = sect.attr 'pdf-destination'
if (level = sect.level) == num_levels || !sect.sections?
outline.page title: sect_title, destination: sect_destination
elsif level <= num_levels
outline.section sect_title, destination: sect_destination, closed: expand_levels < 1 do
add_outline_level outline, sect.sections, num_levels, (expand_levels - 1)
end
end
end
end
def insert_toc_section doc, toc_title, toc_page_nums
if (doc.attr? 'toc-placement', 'macro') && (toc_node = (doc.find_by context: :toc)[0])
if (parent_section = toc_node.parent).context == :section
grandparent_section = parent_section.parent
toc_level = parent_section.level
insert_idx = (grandparent_section.blocks.index parent_section) + 1
else
grandparent_section = doc
toc_level = doc.sections[0].level
insert_idx = 0
end
toc_dest = toc_node.attr 'pdf-destination'
else
grandparent_section = doc
toc_level = doc.sections[0].level
insert_idx = 0
toc_dest = dest_top toc_page_nums.first
end
toc_section = Section.new grandparent_section, toc_level, false, attributes: { 'pdf-destination' => toc_dest }
toc_section.title = toc_title
grandparent_section.blocks.insert insert_idx, toc_section
toc_section
end
def write pdf_doc, target
if target.respond_to? :write
target = ::QuantifiableStdout.new STDOUT if target == STDOUT
pdf_doc.render target
else
pdf_doc.render_file target
# QUESTION restore attributes first?
@pdfmark&.generate_file target
(Optimizer.new @optimize, pdf_doc.min_version).generate_file target if @optimize && ((defined? ::Asciidoctor::PDF::Optimizer) || !(Helpers.require_library OptimizerRequirePath, 'rghost', :warn).nil?)
to_file = true
end
if !ENV['KEEP_ARTIFACTS']
remove_tmp_files
elsif to_file
scratch_target = (target.slice 0, target.length - (target_ext = ::File.extname target).length) + '-scratch' + target_ext
get_scratch_document.render_file scratch_target
end
clear_scratch
nil
end
def register_fonts font_catalog, fonts_dir
return unless font_catalog
dirs = (fonts_dir.split ValueSeparatorRx, -1).map do |dir|
dir == 'GEM_FONTS_DIR' || dir.empty? ? ThemeLoader::FontsDir : dir
end
font_catalog.each do |key, styles|
styles = styles.each_with_object({}) do |(style, path), accum|
found = dirs.find do |dir|
resolved_font_path = font_path path, dir
if ::File.readable? resolved_font_path
accum[style.to_sym] = resolved_font_path
true
end
end
raise ::Errno::ENOENT, ((File.absolute_path? path) ? %(#{path} not found) : %(#{path} not found in #{fonts_dir.gsub ValueSeparatorRx, ' or '})) unless found
end
register_font key => styles
end
end
def font_path font_file, fonts_dir
# resolve relative to built-in font dir unless path is absolute
::File.absolute_path font_file, fonts_dir
end
def fallback_svg_font_name
@theme.svg_fallback_font_family || @theme.svg_font_family || @theme.base_font_family
end
def apply_text_decoration styles, category, level = nil
if (text_decoration_style = TextDecorationStyleTable[(level && @theme[%(#{category}_h#{level}_text_decoration)]) || @theme[%(#{category}_text_decoration)]])
{
styles: (styles << text_decoration_style),
text_decoration_color: (level && @theme[%(#{category}_h#{level}_text_decoration_color)]) || @theme[%(#{category}_text_decoration_color)],
text_decoration_width: (level && @theme[%(#{category}_h#{level}_text_decoration_width)]) || @theme[%(#{category}_text_decoration_width)],
}.compact
else
styles.empty? ? {} : { styles: styles }
end
end
def resolve_text_transform key, use_fallback = true
if (transform = ::Hash === key ? (key.delete :text_transform) : @theme[key.to_s])
transform == 'none' ? nil : transform
elsif use_fallback
@text_transform
end
end
# QUESTION should we pass a category as an argument?
# QUESTION should we make this a method on the theme ostruct? (e.g., @theme.resolve_color key, fallback)
def resolve_theme_color key, fallback_color = nil
if (color = @theme[key.to_s]) && color != 'transparent'
color
else
fallback_color
end
end
def resolve_font_kerning keyword, fallback = default_kerning?
keyword && (FontKerningTable.key? keyword) ? FontKerningTable[keyword] : fallback
end
def theme_fill_and_stroke_bounds category, opts = {}
fill_and_stroke_bounds opts[:background_color], @theme[%(#{category}_border_color)],
line_width: (@theme[%(#{category}_border_width)] || 0),
line_style: (@theme[%(#{category}_border_style)] || :solid).to_sym,
radius: @theme[%(#{category}_border_radius)]
end
def theme_fill_and_stroke_block category, block_height, opts = {}
if (b_width = (opts.key? :border_width) ? opts[:border_width] : @theme[%(#{category}_border_width)])
if ::Array === b_width
b_width = b_width[0] || 0
b_radius = 0
end
b_width = nil unless b_width > 0
end
if (bg_color = opts[:background_color] || @theme[%(#{category}_background_color)]) == 'transparent'
bg_color = nil
end
unless b_width || bg_color
(node = opts[:caption_node]) && node.title? && (layout_caption node, category: category)
return
end
if (b_color = @theme[%(#{category}_border_color)]) == 'transparent'
b_color = @page_bg_color
end
b_radius ||= (@theme[%(#{category}_border_radius)] || 0) + (b_width || 0)
if b_width && b_color
if b_color == @page_bg_color # let page background cut into block background
b_gap_color, b_shift = @page_bg_color, (b_width * 0.5)
elsif (b_gap_color = bg_color) && b_gap_color != b_color
b_shift = 0
else # let page background cut into border
b_gap_color, b_shift = @page_bg_color, 0
end
else # let page background cut into block background
b_shift, b_gap_color = (b_width ||= 0.5) * 0.5, @page_bg_color
end
# FIXME: due to the calculation error logged in #789, we must advance page even when content is split across pages
advance_page if (opts.fetch :split_from_top, true) && block_height > cursor && !at_page_top?
caption_height = (node = opts[:caption_node]) && node.title? ? (layout_caption node, category: category) : 0
float do
remaining_height = block_height - caption_height
initial_page = true
while remaining_height > 0
advance_page unless initial_page
chunk_height = [(available_height = cursor), remaining_height].min
bounding_box [0, available_height], width: bounds.width, height: chunk_height do
theme_fill_and_stroke_bounds category, background_color: bg_color
# NOTE b_width is always set; if no border is set, split indicator is cut into background
indent b_radius, b_radius do
# dashed line indicates continuation from previous page; swell line slightly to cover background
stroke_horizontal_rule b_gap_color, line_width: b_width * 1.2, line_style: :dashed, at: b_shift
end unless initial_page
if remaining_height > chunk_height
move_down chunk_height - b_shift
indent b_radius, b_radius do
# dashed line indicates continuation from previous page; swell line slightly to cover background
stroke_horizontal_rule b_gap_color, line_width: b_width * 1.2, line_style: :dashed
end
end
end
initial_page = false
remaining_height -= chunk_height
end
end
end
# Insert a top margin equal to amount if cursor is not at the top of the
# page. Start a new page instead if amount is greater than the remaining
# space on the page.
def margin_top amount
margin amount, :top
end
# Insert a bottom margin equal to amount unless cursor is at the top of the
# page (not likely). Start a new page instead if amount is greater than the
# remaining space on the page.
def margin_bottom amount
margin amount, :bottom
end
# Insert a margin at the specified side if the cursor is not at the top of
# the page. Start a new page if amount is greater than the remaining space on
# the page.
def margin amount, _side
unless (amount || 0) == 0 || at_page_top?
# NOTE use low-level cursor calculation to workaround cursor bug in column_box context
if y - reference_bounds.absolute_bottom > amount
move_down amount
else
# set cursor at top of next page
reference_bounds.move_past_bottom
end
end
end
# Lookup margin for theme element and side, then delegate to margin method.
# If margin value is not found, assume:
# - 0 when side == :top
# - @theme.vertical_spacing when side == :bottom
def theme_margin category, side
margin((@theme[%(#{category}_margin_#{side})] || (side == :bottom ? @theme.vertical_spacing : 0)), side)
end
def theme_font category, opts = {}
result = nil
# TODO: inheriting from generic category should be an option
if opts.key? :level
hlevel_category = %(#{category}_h#{opts[:level]})
family = @theme[%(#{hlevel_category}_font_family)] || @theme[%(#{category}_font_family)] || @theme.base_font_family || font_family
size = @theme[%(#{hlevel_category}_font_size)] || @theme[%(#{category}_font_size)] || @root_font_size
style = @theme[%(#{hlevel_category}_font_style)] || @theme[%(#{category}_font_style)]
color = @theme[%(#{hlevel_category}_font_color)] || @theme[%(#{category}_font_color)]
kerning = resolve_font_kerning @theme[%(#{hlevel_category}_font_kerning)] || @theme[%(#{category}_font_kerning)], nil
# NOTE global text_transform is not currently supported
transform = @theme[%(#{hlevel_category}_text_transform)] || @theme[%(#{category}_text_transform)]
else
inherited_font = font_info
family = @theme[%(#{category}_font_family)] || inherited_font[:family]
size = @theme[%(#{category}_font_size)] || inherited_font[:size]
style = @theme[%(#{category}_font_style)] || inherited_font[:style]
color = @theme[%(#{category}_font_color)]
kerning = resolve_font_kerning @theme[%(#{category}_font_kerning)], nil
# NOTE global text_transform is not currently supported
transform = @theme[%(#{category}_text_transform)]
end
prev_color, @font_color = @font_color, color if color
prev_kerning, self.default_kerning = default_kerning?, kerning unless kerning.nil?
prev_transform, @text_transform = @text_transform, (transform == 'none' ? nil : transform) if transform
font family, size: size * @font_scale, style: (style && style.to_sym) do
result = yield
end
@font_color = prev_color if color
default_kerning prev_kerning unless kerning.nil?
@text_transform = prev_transform if transform
result
end
# Calculate the font size (down to the minimum font size) that would allow
# all the specified fragments to fit in the available width without wrapping lines.
#
# Return the calculated font size if an adjustment is necessary or nil if no
# font size adjustment is necessary.
def compute_autofit_font_size fragments, category
arranger = arrange_fragments_by_line fragments
# NOTE finalizing the line here generates fragments & calculates their widths using the current font settings
# CAUTION it also removes zero-width spaces
arranger.finalize_line
actual_width = width_of_fragments arranger.fragments
unless ::Array === (padding = @theme[%(#{category}_padding)])
padding = ::Array.new 4, padding
end
available_width = bounds.width - (padding[3] || 0) - (padding[1] || 0)
if actual_width > available_width
adjusted_font_size = ((available_width * font_size).to_f / actual_width).truncate 4
if (min = @theme[%(#{category}_font_size_min)] || @theme.base_font_size_min) && adjusted_font_size < min
min
else
adjusted_font_size
end
end
end
# Arrange fragments by line in an arranger and return an unfinalized arranger.
#
# Finalizing the arranger is deferred since it must be done in the context of
# the global font settings you want applied to each fragment.
def arrange_fragments_by_line fragments, _opts = {}
arranger = ::Prawn::Text::Formatted::Arranger.new self
by_line = arranger.consumed = []
fragments.each do |fragment|
if (text = fragment[:text]) == LF
by_line << fragment
elsif text.include? LF
text.scan LineScanRx do |line|
by_line << (line == LF ? { text: LF } : (fragment.merge text: line))
end
else
by_line << fragment
end
end
arranger
end
# Calculate the width that is needed to print all the
# fragments without wrapping any lines.
#
# This method assumes endlines are represented as discrete entries in the
# fragments array.
def width_of_fragments fragments
line_widths = [0]
fragments.each do |fragment|
if fragment.text == LF
line_widths << 0
else
line_widths[-1] += fragment.width
end
end
line_widths.max
end
# Compute the rendered width of a string, taking fallback fonts into account
def rendered_width_of_string str, opts = {}
opts = opts.merge kerning: default_kerning?
if str.length == 1
rendered_width_of_char str, opts
elsif (chars = str.each_char).all? {|char| font.glyph_present? char }
width_of_string str, opts
else
char_widths = chars.map {|char| rendered_width_of_char char, opts }
char_widths.sum + (char_widths.length * (opts[:character_spacing] || character_spacing))
end
end
# Compute the rendered width of a char, taking fallback fonts into account
def rendered_width_of_char char, opts = {}
unless @fallback_fonts.empty? || (font.glyph_present? char)
@fallback_fonts.each do |fallback_font|
font fallback_font do
return width_of_string char, opts if font.glyph_present? char
end
end
end
width_of_string char, opts
end
# TODO: document me, esp the first line formatting functionality
def typeset_text string, line_metrics, opts = {}
move_down line_metrics.padding_top
opts = { leading: line_metrics.leading, final_gap: line_metrics.final_gap }.merge opts
string = string.gsub CjkLineBreakRx, ZeroWidthSpace if @cjk_line_breaks
if (hanging_indent = (opts.delete :hanging_indent) || 0) > 0
indent hanging_indent do
text string, (opts.merge indent_paragraphs: -hanging_indent)
end
elsif (first_line_opts = opts.delete :first_line_options)
# TODO: good candidate for Prawn enhancement!
text_with_formatted_first_line string, first_line_opts, opts
else
text string, opts
end
move_down line_metrics.padding_bottom
end
# QUESTION combine with typeset_text?
def typeset_formatted_text fragments, line_metrics, opts = {}
move_down line_metrics.padding_top
opts = { leading: line_metrics.leading, final_gap: line_metrics.final_gap }.merge opts
if (hanging_indent = (opts.delete :hanging_indent) || 0) > 0
indent hanging_indent do
formatted_text fragments, (opts.merge indent_paragraphs: -hanging_indent)
end
else
formatted_text fragments, opts
end
move_down line_metrics.padding_bottom
end
def height_of_typeset_text string, opts = {}
line_metrics = (calc_line_metrics opts[:line_height] || @theme.base_line_height)
(height_of string, leading: line_metrics.leading, final_gap: line_metrics.final_gap) + line_metrics.padding_top + (opts[:single_line] ? 0 : line_metrics.padding_bottom)
end
# NOTE only used when tabsize attribute is not specified
# tabs must always be replaced with spaces in order for the indentation guards to work
def expand_tabs string
if string.nil_or_empty?
''
elsif string.include? TAB
full_tab_space = ' ' * (tab_size = 4)
(string.split LF, -1).map {|line|
if line.empty?
line
elsif (tab_idx = line.index TAB)
if tab_idx == 0
leading_tabs = 0
line.each_byte do |b|
break unless b == 9
leading_tabs += 1
end
line = %(#{full_tab_space * leading_tabs}#{rest = line.slice leading_tabs, line.length})
next line unless rest.include? TAB
end
# keeps track of how many spaces were added to adjust offset in match data
spaces_added = 0
idx = 0
result = ''
line.each_char do |c|
if c == TAB
# calculate how many spaces this tab represents, then replace tab with spaces
if (offset = idx + spaces_added) % tab_size == 0
spaces_added += (tab_size - 1)
result += full_tab_space
else
unless (spaces = tab_size - offset % tab_size) == 1
spaces_added += (spaces - 1)
end
result += (' ' * spaces)
end
else
result += c
end
idx += 1
end
result
else
line
end
}.join LF
else
string
end
end
# Add an indentation guard at the start of indented lines.
# Expand tabs to spaces if tabs are present
def guard_indentation string
unless (string = expand_tabs string).empty?
string[0] = GuardedIndent if string.start_with? ' '
string.gsub! InnerIndent, GuardedInnerIndent if string.include? InnerIndent
end
string
end
def guard_indentation_in_fragments fragments
start_of_line = true
fragments.each do |fragment|
next if (text = fragment[:text]).empty?
if start_of_line && (text.start_with? ' ')
fragment[:text] = GuardedIndent + (((text = text.slice 1, text.length).include? InnerIndent) ? (text.gsub InnerIndent, GuardedInnerIndent) : text)
elsif text.include? InnerIndent
fragment[:text] = text.gsub InnerIndent, GuardedInnerIndent
end
start_of_line = text.end_with? LF
end
fragments
end
# Derive a PDF-safe, ASCII-only anchor name from the given value.
# Encodes value into hex if it contains characters outside the ASCII range.
# If value is nil, derive an anchor name from the default_value, if given.
def derive_anchor_from_id value, default_value = nil
if value
value.ascii_only? ? value : %(0x#{::PDF::Core.string_to_hex value})
else
%(__anchor-#{default_value})
end
end
# If an id is provided or the node passed as the first argument has an id,
# add a named destination to the document equivalent to the node id at the
# current y position. If the node does not have an id and an id is not
# specified, do nothing.
#
# If the node is a section, and the current y position is the top of the
# page, set the y position equal to the page height to improve the navigation
# experience. If the current x position is at or inside the left margin, set
# the x position equal to 0 (left edge of page) to improve the navigation
# experience.
def add_dest_for_block node, id = nil
if !scratch? && (id ||= node.id)
dest_x = bounds.absolute_left.truncate 4
# QUESTION when content is aligned to left margin, should we keep precise x value or just use 0?
dest_x = 0 if dest_x <= page_margin_left
dest_y = at_page_top? && (node.context == :section || node.context == :document) ? page_height : y
# TODO: find a way to store only the ref of the destination; look it up when we need it
node.set_attr 'pdf-destination', (node_dest = (dest_xyz dest_x, dest_y))
add_dest id, node_dest
end
nil
end
def resolve_alignment_from_role roles
if (align_role = roles.reverse.find {|r| TextAlignmentRoles.include? r })
(align_role.slice 5, align_role.length).to_sym
end
end
# QUESTION is this method still necessary?
def resolve_imagesdir doc
if (imagesdir = doc.attr 'imagesdir').nil_or_empty? || (imagesdir = imagesdir.chomp '/') == '.'
nil
else
imagesdir
end
end
# Resolve the system path of the specified image path.
#
# Resolve and normalize the absolute system path of the specified image,
# taking into account the imagesdir attribute. If an image path is not
# specified, the path is read from the target attribute of the specified
# document node.
#
# If the target is a URI and the allow-uri-read attribute is set on the
# document, read the file contents to a temporary file and return the path to
# the temporary file. If the target is a URI and the allow-uri-read attribute
# is not set, or the URI cannot be read, this method returns a nil value.
#
# When a temporary file is used, the file is stored in @tmp_files to be cleaned up after conversion.
def resolve_image_path node, image_path, image_format, relative_to = true
doc = node.document
imagesdir = relative_to == true ? (resolve_imagesdir doc) : relative_to
#image_format ||= ::Asciidoctor::Image.format image_path, (::Asciidoctor::Image === node ? node.attributes : nil)
# NOTE base64 logic currently used for inline images
if ::Base64 === image_path
return @tmp_files[image_path] if @tmp_files.key? image_path
tmp_image = ::Tempfile.create ['image-', image_format && %(.#{image_format})]
tmp_image.binmode unless image_format == 'svg'
begin
tmp_image.write ::Base64.decode64 image_path
tmp_image.close
@tmp_files[image_path] = tmp_image.path
rescue
@tmp_files[image_path] = nil
tmp_image.close
unlink_tmp_file tmp_image.path
nil
end
# handle case when image is a URI
elsif (node.is_uri? image_path) ||
(imagesdir && (node.is_uri? imagesdir) && (image_path = node.normalize_web_path image_path, imagesdir, false))
unless allow_uri_read
logger.warn %(allow-uri-read is not enabled; cannot embed remote image: #{image_path}) unless scratch?
return
end
return @tmp_files[image_path] if @tmp_files.key? image_path
tmp_image = ::Tempfile.create ['image-', image_format && %(.#{image_format})]
tmp_image.binmode if (binary = image_format != 'svg')
begin
load_open_uri.open_uri(image_path, (binary ? 'rb' : 'r')) {|fd| tmp_image.write fd.read }
tmp_image.close
@tmp_files[image_path] = tmp_image.path
rescue
@tmp_files[image_path] = nil
logger.warn %(could not retrieve remote image: #{image_path}; #{$!.message}) unless scratch?
tmp_image.close
unlink_tmp_file tmp_image.path
nil
end
# handle case when image is a local file
else
node.normalize_system_path image_path, imagesdir, nil, target_name: 'image'
end
end
# Resolve the path and sizing of the background image either from a document attribute or theme key.
#
# Returns the argument list for the image method if the document attribute or theme key is found. Otherwise,
# nothing. The first argument in the argument list is the image path. If that value is nil, the background
# image is disabled. The second argument is the options hash to specify the dimensions, such as width and fit.
def resolve_background_image doc, theme, key, opts = {}
if ::String === key
theme_key = opts.delete :theme_key
image_path = (doc.attr key) || (from_theme = theme[theme_key || (key.tr '-', '_').to_sym])
else
image_path = from_theme = theme[key]
end
symbolic_paths = opts.delete :symbolic_paths
if image_path
if symbolic_paths && (symbolic_paths.include? image_path)
return [image_path, {}]
elsif image_path == 'none'
return []
elsif (image_path.include? ':') && image_path =~ ImageAttributeValueRx
image_attrs = (AttributeList.new $2).parse %w(alt width)
if from_theme
image_path = sub_attributes_discretely doc, $1
image_relative_to = @themesdir
else
image_path = $1
image_relative_to = true
end
elsif from_theme
image_path = sub_attributes_discretely doc, image_path
image_relative_to = @themesdir
end
image_path, image_format = ::Asciidoctor::Image.target_and_format image_path, image_attrs
image_path = resolve_image_path doc, image_path, image_format, image_relative_to
return unless image_path
unless ::File.readable? image_path
logger.warn %(#{key.to_s.tr '-_', ' '} not found or readable: #{image_path})
return
end
if image_format == 'pdf'
[image_path, page: [((image_attrs || {})['page']).to_i, 1].max, format: image_format]
else
[image_path, (resolve_image_options image_path, image_format, image_attrs, (opts.merge background: true))]
end
end
end
def resolve_image_options image_path, image_format, image_attrs, opts = {}
if image_format == 'svg'
image_opts = {
enable_file_requests_with_root: (::File.dirname image_path),
enable_web_requests: allow_uri_read ? (method :load_open_uri).to_proc : false,
cache_images: cache_uri,
fallback_font_name: fallback_svg_font_name,
format: 'svg',
}
else
image_opts = {}
end
background = opts[:background]
container_size = opts[:container_size] || (background ? [page_width, page_height] : [bounds.width, bounds.height])
if image_attrs
if background && (image_pos = image_attrs['position']) && (image_pos = resolve_background_position image_pos, nil)
image_opts.update image_pos
end
if (image_fit = image_attrs['fit'] || (background ? 'contain' : nil))
image_fit = 'contain' if image_format == 'svg' && image_fit == 'fill'
container_width, container_height = container_size
case image_fit
when 'none'
if (image_width = resolve_explicit_width image_attrs, bounds_width: container_width)
image_opts[:width] = image_width
end
when 'scale-down'
# NOTE if width and height aren't set in SVG, real width and height are computed after stretching viewbox to fit page
if (image_width = resolve_explicit_width image_attrs, bounds_width: container_width) && image_width > container_width
image_opts[:fit] = container_size
elsif (image_size = intrinsic_image_dimensions image_path, image_format) &&
(image_width ? image_width * (image_size[:height].to_f / image_size[:width]) > container_height : (to_pt image_size[:width], :px) > container_width || (to_pt image_size[:height], :px) > container_height)
image_opts[:fit] = container_size
elsif image_width
image_opts[:width] = image_width
end
when 'cover'
# QUESTION should we take explicit width into account?
image_size = intrinsic_image_dimensions image_path, image_format
if container_width * (image_size[:height].to_f / image_size[:width]) < container_height
image_opts[:height] = container_height
else
image_opts[:width] = container_width
end
when 'fill'
image_opts[:width] = container_width
image_opts[:height] = container_height
else # when 'contain'
image_opts[:fit] = container_size
end
elsif (image_width = resolve_explicit_width image_attrs, bounds_width: container_size[0])
image_opts[:width] = image_width
else # default to fit=contain if sizing is not specified
image_opts[:fit] = container_size
end
else
image_opts[:fit] = container_size
end
image_opts
end
# Resolves the explicit width, if specified, as a PDF pt value.
#
# Resolves the explicit width, first considering the pdfwidth attribute, then the scaledwidth
# attribute, then the theme default (if enabled by the :use_fallback option), and finally the
# width attribute. If the specified value is in pixels, the value is scaled by 75% to perform
# approximate CSS px to PDF pt conversion. If the value is a percentage, and the
# bounds_width option is given, the percentage of the bounds_width value is returned.
# Otherwise, the percentage width is returned.
#--
# QUESTION should we enforce positive result?
def resolve_explicit_width attrs, opts = {}
bounds_width = opts[:bounds_width]
# QUESTION should we restrict width to bounds_width for pdfwidth?
if attrs.key? 'pdfwidth'
if (width = attrs['pdfwidth']).end_with? '%'
bounds_width ? (width.to_f / 100) * bounds_width : width
elsif opts[:support_vw] && (width.end_with? 'vw')
(width.chomp 'vw').extend ViewportWidth
else
str_to_pt width
end
elsif attrs.key? 'scaledwidth'
# NOTE the parser automatically appends % if value is unitless
if (width = attrs['scaledwidth']).end_with? '%'
bounds_width ? (width.to_f / 100) * bounds_width : width
else
str_to_pt width
end
elsif opts[:use_fallback] && (width = @theme.image_width)
if ::Numeric === width
width
elsif (width = width.to_s).end_with? '%'
bounds_width ? (width.to_f / 100) * bounds_width : bounds_width
elsif opts[:support_vw] && (width.end_with? 'vw')
(width.chomp 'vw').extend ViewportWidth
else
str_to_pt width
end
elsif attrs.key? 'width'
if (width = attrs['width']).end_with? '%'
width = (width.to_f / 100) * bounds_width if bounds_width
else
width = to_pt width.to_f, :px
end
bounds_width && opts[:constrain_to_bounds] ? [bounds_width, width].min : width
end
end
def resolve_background_position value, default_value = {}
if value.include? ' '
result = {}
center = nil
(value.split ' ', 2).each do |keyword|
if keyword == 'left' || keyword == 'right'
result[:position] = keyword.to_sym
elsif keyword == 'top' || keyword == 'bottom'
result[:vposition] = keyword.to_sym
elsif keyword == 'center'
center = true
end
end
if center
result[:position] ||= :center
result[:vposition] ||= :center
result
elsif (result.key? :position) && (result.key? :vposition)
result
else
default_value
end
elsif value == 'left' || value == 'right' || value == 'center'
{ position: value.to_sym, vposition: :center }
elsif value == 'top' || value == 'bottom'
{ position: :center, vposition: value.to_sym }
else
default_value
end
end
def resolve_top val
if val.end_with? 'vh'
page_height * (1 - (val.to_f / 100))
elsif val.end_with? '%'
@y - effective_page_height * (val.to_f / 100)
else
@y - (str_to_pt val)
end
end
def add_link_to_image uri, image_info, image_opts
image_width = image_info[:width]
image_height = image_info[:height]
case image_opts[:position]
when :center
image_x = bounds.left_side + (bounds.width - image_width) * 0.5
when :right
image_x = bounds.right_side - image_width
else # :left or not set
image_x = bounds.left_side
end
case image_opts[:vposition]
when :top
image_y = bounds.absolute_top
when :center
image_y = bounds.absolute_top - (bounds.height - image_height) * 0.5
when :bottom
image_y = bounds.absolute_bottom + image_height
else
image_y = y - image_opts[:vposition]
end unless (image_y = image_opts[:y])
link_annotation [image_x, (image_y - image_height), (image_x + image_width), image_y], Border: [0, 0, 0], A: { Type: :Action, S: :URI, URI: uri.as_pdf }
end
def load_open_uri
if @cache_uri && !(defined? ::OpenURI::Cache)
if (Helpers.require_library 'open-uri/cached', 'open-uri-cached', :warn).nil?
@cache_uri = false # disable since it failed to load
end
end
::OpenURI
end
def remove_tmp_files
@tmp_files.reject! {|_, path| path ? (unlink_tmp_file path) : true }
end
def unlink_tmp_file path
::File.unlink path if ::File.exist? path
true
rescue
logger.warn %(could not delete temporary file: #{path}; #{$!.message}) unless scratch?
false
end
def apply_subs_discretely doc, value, opts = {}
imagesdir = doc.attr 'imagesdir'
doc.set_attr 'imagesdir', @themesdir
# FIXME: get sub_attributes to handle drop-line w/o a warning
doc.set_attr 'attribute-missing', 'skip' unless (attribute_missing = doc.attr 'attribute-missing') == 'skip'
value = value.gsub '\{', '\\\\\\{' if (escaped_attr_ref = value.include? '\{')
value = doc.apply_subs value
value = (value.split LF).delete_if {|line| SimpleAttributeRefRx.match? line }.join LF if opts[:drop_lines_with_unresolved_attributes] && (value.include? '{')
value = value.gsub '\{', '{' if escaped_attr_ref
doc.set_attr 'attribute-missing', attribute_missing unless attribute_missing == 'skip'
if imagesdir
doc.set_attr 'imagesdir', imagesdir
else
doc.remove_attr 'imagesdir'
end
value
end
def sub_attributes_discretely doc, value
doc.set_attr 'attribute-missing', 'skip' unless (attribute_missing = doc.attr 'attribute-missing') == 'skip'
value = doc.apply_subs value, [:attributes]
doc.set_attr 'attribute-missing', attribute_missing unless attribute_missing == 'skip'
value
end
def promote_author doc, idx
doc.remove_attr 'url' if (original_url = doc.attr 'url')
email = nil
if idx > 1
original_attrs = AuthorAttributeNames.each_with_object({}) do |name, accum|
accum[name] = doc.attr name
if (val = doc.attr %(#{name}_#{idx}))
doc.set_attr name, val
# NOTE email holds url as well
email = val if name == 'email'
else
doc.remove_attr name
end
end
doc.set_attr 'url', ((email.include? '@') ? %(mailto:#{email}) : email) if email
result = yield
original_attrs.each {|name, val| val ? (doc.set_attr name, val) : (doc.remove_attr name) }
else
if (email = doc.attr 'email')
doc.set_attr 'url', ((email.include? '@') ? %(mailto:#{email}) : email)
end
result = yield
end
if original_url
doc.set_attr 'url', original_url
elsif email
doc.remove_attr 'url'
end
result
end
# NOTE assume URL is escaped (i.e., contains character references such as &)
def breakable_uri uri
scheme, address = uri.split UriSchemeBoundaryRx, 2
address, scheme = scheme, address unless address
unless address.nil_or_empty?
address = address.gsub UriBreakCharsRx, UriBreakCharRepl
# NOTE require at least two characters after a break
address.slice!(-2) if address[-2] == ZeroWidthSpace
end
%(#{scheme}#{address})
end
def consolidate_ranges nums
if nums.size > 1
prev = nil
nums.each_with_object([]) {|num, accum|
if prev && (prev.to_i + 1) == num.to_i
accum[-1][1] = num
else
accum << [num]
end
prev = num
}.map {|range| range.join '-' }
else
nums
end
end
def resolve_pagenums val
pgnums = []
((val.include? ',') ? (val.split ',') : (val.split ';')).each do |entry|
if entry.include? '..'
from, _, to = entry.partition '..'
pgnums += ([from.to_i, 1].max..[to.to_i, 1].max).to_a
else
pgnums << entry.to_i
end
end
pgnums
end
def get_char code
(code.start_with? '\u') ? ([((code.slice 2, code.length).to_i 16)].pack 'U1') : code
end
# QUESTION move to prawn/extensions.rb?
def init_scratch_prototype
@save_state = nil
@scratch_depth = 0
# NOTE don't need background image in scratch document; can cause marshal error anyway
saved_page_bg_image, @page_bg_image = @page_bg_image, { verso: nil, recto: nil }
# IMPORTANT don't set font before using Marshal, it causes serialization to fail
@prototype = ::Marshal.load ::Marshal.dump self
@page_bg_image = saved_page_bg_image
@prototype.state.store.info.data[:Scratch] = @prototype.text_formatter.scratch = true
# NOTE we're now starting a new page each time, so no need to do it here
#@prototype.start_new_page if @prototype.page_number == 0
end
def push_scratch doc
if (@scratch_depth += 1) == 1
@save_state = {
catalog: {}.tap {|accum| doc.catalog.each {|k, v| accum[k] = v.dup } },
attributes: doc.attributes.dup,
}
end
end
def pop_scratch doc
if (@scratch_depth -= 1) == 0
doc.catalog.replace @save_state[:catalog]
doc.attributes.replace @save_state[:attributes]
@save_state = nil
end
end
def clear_scratch
@scratch_depth = 0
@save_state = @prototype = @scratch = nil
end
end
end
end
|
=begin
Copyright 2010-2012 Tasos Laskos <tasos.laskos@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=end
opts = Arachni::Options.instance
require opts.dir['lib'] + 'parser/element/base'
class Arachni::Parser::Element::Form < Arachni::Parser::Element::Base
ORIGINAL_VALUES = '__original_values__'
SAMPLE_VALUES = '__sample_values__'
#
# Creates a new Form element from a URL and auditable data.
#
# @param [String] url owner URL -- URL of the page which contained the
# @param [Hash] raw
# If empty, the element will be initialized without auditable inputs.
#
# If a full +Hash+ is passed, it will look for an actionable URL
# +String+ in the following keys:
# * 'href'
# * :href
# * 'action'
# * :action
#
# For an method +String+ in:
# * 'method'
# * :method
#
# For an auditable inputs +Hash+ in:
# * 'inputs'
# * :inputs
# * 'auditable'
#
# these should contain inputs in name=>value pairs.
#
def initialize( url, raw = {} )
super( url, raw )
was_opts_hash = false
begin
self.action = @raw['action'] || @raw[:action] || @raw['attrs']['action']
was_opts_hash = true
rescue
self.action = self.url
end
begin
self.method = @raw['method'] || @raw[:method] || @raw['attrs']['method']
was_opts_hash = true
rescue
self.method = 'post'
end
if !was_opts_hash && (@raw.keys & [:inputs, 'inputs', 'auditable']).empty?
self.auditable = @raw
else
self.auditable = @raw[:inputs] || @raw['inputs'] || simple['auditable']
end
self.auditable ||= {}
@orig = self.auditable.dup
@orig.freeze
end
#
# @return [String, nil] name of the form if it has one
#
def name
@raw['attrs']['name'] if @raw['attrs'].is_a?( Hash )
end
#
# @return [String] unique form ID
#
def id
id = simple['attrs'].to_s
auditable.each do |name, _|
next if name.substring?( seed )
id += name
end
id
end
#
# @return [Hash] a simple representation of self including attributes and auditables
#
def simple
form = {}
form['auditable'] = {}
if @raw['auditable'] && !@raw['auditable'].empty?
@raw['auditable'].each do |item|
next if !item['name']
form['auditable'][item['name']] = item['value']
end
end
if @raw['attrs']
form['attrs'] = @raw['attrs']
else
form['attrs'] = {
'method' => @method,
'action' => @action
}
end
if form['auditable'].empty? && @auditable && !@auditable.empty?
form['auditable'] = @auditable
end
form.dup
end
# @return [Bool] +true+ if the element has not been mutated, +false+ otherwise.
def original?
self.altered == ORIGINAL_VALUES
end
# @return [Bool] +true+ if the element has been populated with sample values,
# +false+ otherwise.
def sample?
self.altered == SAMPLE_VALUES
end
#
# Overrides {Arachni::Parser::Element::Mutable#mutations} adding support
# for mutations with:
# * sample values (filled by {Arachni::Module::KeyFiller.fill})
# * original values
# * password fields with identical values (in order to pass server-side validation)
#
# @return [Array<Form>]
#
# @see Arachni::Parser::Element::Mutable#mutations
# @see Arachni::Module::KeyFiller.fill
#
def mutations( injection_str, opts = {} )
opts = MUTATION_OPTIONS.merge( opts )
var_combo = super( injection_str, opts )
if !opts[:skip_orig]
if !audited?( audit_id( ORIGINAL_VALUES ) )
# this is the original hash, in case the default values
# are valid and present us with new attack vectors
elem = self.dup
elem.altered = ORIGINAL_VALUES
var_combo << elem
end
if !audited?( audit_id( SAMPLE_VALUES ) )
elem = self.dup
elem.auditable = Arachni::Module::KeyFiller.fill( auditable.dup )
elem.altered = SAMPLE_VALUES
var_combo << elem
end
end
return var_combo.uniq if !@raw['auditable']
# if there are two password type fields in the form there's a good
# chance that it's a 'please retype your password' thing so make sure
# that we have a variation which has identical password values
filled_auditables = Arachni::Module::KeyFiller.fill( auditable.dup )
delem = self.dup
found_passwords = false
@raw['auditable'].each do |input|
if input['type'] == 'password'
delem.altered = input['name']
opts[:format].each do |format|
filled_auditables[input['name']] =
format_str( injection_str, filled_auditables[input['name']], format )
end
found_passwords = true
end
end
if found_passwords
delem.auditable = filled_auditables
var_combo << delem
end
var_combo.uniq
end
# @return [String] 'form'
def type
Arachni::Module::Auditor::Element::FORM
end
#
# Returns an array of forms by parsing the body of an HTTP response.
#
# @param [Typhoeus::Response] response
#
# @return [Array<Form>]
#
def self.from_response( response )
from_document( response.effective_url, response.body )
end
#
# Returns an array of forms from an HTML document.
#
# @param [String] url request URL
# @param [String, Nokogiri::HTML::Document] document
#
# @return [Array<Form>]
#
def self.from_document( url, document )
document = Nokogiri::HTML( document.to_s ) if !document.is_a?( Nokogiri::HTML::Document )
base_url = url
begin
base_url = document.search( '//base[@href]' )[0]['href']
rescue
base_url = url
end
document.search( '//form' ).map do |form|
form = form_from_element( base_url, form )
form.url = url
form
end.compact
end
private
def self.form_from_element( url, form )
utilities = Arachni::Utilities
c_form = {}
c_form['attrs'] = attributes_to_hash( form.attributes )
if !c_form['attrs'] || !c_form['attrs']['action']
action = url.to_s
else
action = utilities.url_sanitize( c_form['attrs']['action'] )
end
begin
action = utilities.to_absolute( action.dup, url ).to_s
rescue
end
c_form['attrs']['action'] = action
if !c_form['attrs']['method']
c_form['attrs']['method'] = 'get'
else
c_form['attrs']['method'] = c_form['attrs']['method'].downcase
end
%w(textarea input select).each do |attr|
c_form[attr] ||= []
form.search( ".//#{attr}" ).each do |elem|
elem_attrs = attributes_to_hash( elem.attributes )
c_form[elem.name] ||= []
if elem.name != 'select'
c_form[elem.name] << elem_attrs
else
auditables = elem.children.map do |child|
h = attributes_to_hash( child.attributes )
h['value'] ||= child.text
h
end
c_form[elem.name] << {
'attrs' => elem_attrs,
'options' => auditables
}
end
end
end
# merge the form elements to make auditing easier
c_form['auditable'] = c_form['input'] | c_form['textarea']
c_form['auditable'] =
merge_select_with_input( c_form['auditable'], c_form['select'] )
new( url, c_form )
end
def self.attributes_to_hash( attributes )
attributes.inject( {} ){ |h, (k, v)| h[k] = v.to_s; h }
end
#
# Merges an array of form inputs with an array of form selects
#
# @param [Array] inputs
# @param [Array] selects
#
# @return [Array] merged array
#
def self.merge_select_with_input( inputs, selects )
selected = nil
inputs | selects.map do |select|
select['options'].each do |option|
if option.include?( 'selected' )
selected = option['value']
break
end
end
select['attrs']['value'] = selected || select['options'].first['value']
select['attrs']
end
end
def audit_id( injection_str = '', opts = {} )
str = if original?
ORIGINAL_VALUES
opts[:no_auditor] = true
elsif sample?
SAMPLE_VALUES
opts[:no_auditor] = true
else
injection_str
end
super( str, opts )
end
def http_request( opts, &block )
if (original? || sample?) && !audited?( audit_id )
state = original? ? 'original' : 'sample'
print_debug( "Submitting form with #{state} values; overriding trainer option." )
opts[:train] = true
print_debug_trainer( opts )
end
@method.downcase.to_s != 'get' ?
http.post( @action, opts, &block ) : http.get( @action, opts, &block )
end
end
#audit_id made public again
=begin
Copyright 2010-2012 Tasos Laskos <tasos.laskos@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=end
opts = Arachni::Options.instance
require opts.dir['lib'] + 'parser/element/base'
class Arachni::Parser::Element::Form < Arachni::Parser::Element::Base
ORIGINAL_VALUES = '__original_values__'
SAMPLE_VALUES = '__sample_values__'
#
# Creates a new Form element from a URL and auditable data.
#
# @param [String] url owner URL -- URL of the page which contained the
# @param [Hash] raw
# If empty, the element will be initialized without auditable inputs.
#
# If a full +Hash+ is passed, it will look for an actionable URL
# +String+ in the following keys:
# * 'href'
# * :href
# * 'action'
# * :action
#
# For an method +String+ in:
# * 'method'
# * :method
#
# For an auditable inputs +Hash+ in:
# * 'inputs'
# * :inputs
# * 'auditable'
#
# these should contain inputs in name=>value pairs.
#
def initialize( url, raw = {} )
super( url, raw )
was_opts_hash = false
begin
self.action = @raw['action'] || @raw[:action] || @raw['attrs']['action']
was_opts_hash = true
rescue
self.action = self.url
end
begin
self.method = @raw['method'] || @raw[:method] || @raw['attrs']['method']
was_opts_hash = true
rescue
self.method = 'post'
end
if !was_opts_hash && (@raw.keys & [:inputs, 'inputs', 'auditable']).empty?
self.auditable = @raw
else
self.auditable = @raw[:inputs] || @raw['inputs'] || simple['auditable']
end
self.auditable ||= {}
@orig = self.auditable.dup
@orig.freeze
end
#
# @return [String, nil] name of the form if it has one
#
def name
@raw['attrs']['name'] if @raw['attrs'].is_a?( Hash )
end
#
# @return [String] unique form ID
#
def id
id = simple['attrs'].to_s
auditable.each do |name, _|
next if name.substring?( seed )
id += name
end
id
end
#
# @return [Hash] a simple representation of self including attributes and auditables
#
def simple
form = {}
form['auditable'] = {}
if @raw['auditable'] && !@raw['auditable'].empty?
@raw['auditable'].each do |item|
next if !item['name']
form['auditable'][item['name']] = item['value']
end
end
if @raw['attrs']
form['attrs'] = @raw['attrs']
else
form['attrs'] = {
'method' => @method,
'action' => @action
}
end
if form['auditable'].empty? && @auditable && !@auditable.empty?
form['auditable'] = @auditable
end
form.dup
end
# @return [Bool] +true+ if the element has not been mutated, +false+ otherwise.
def original?
self.altered == ORIGINAL_VALUES
end
# @return [Bool] +true+ if the element has been populated with sample values,
# +false+ otherwise.
def sample?
self.altered == SAMPLE_VALUES
end
#
# Overrides {Arachni::Parser::Element::Mutable#mutations} adding support
# for mutations with:
# * sample values (filled by {Arachni::Module::KeyFiller.fill})
# * original values
# * password fields with identical values (in order to pass server-side validation)
#
# @return [Array<Form>]
#
# @see Arachni::Parser::Element::Mutable#mutations
# @see Arachni::Module::KeyFiller.fill
#
def mutations( injection_str, opts = {} )
opts = MUTATION_OPTIONS.merge( opts )
var_combo = super( injection_str, opts )
if !opts[:skip_orig]
if !audited?( audit_id( ORIGINAL_VALUES ) )
# this is the original hash, in case the default values
# are valid and present us with new attack vectors
elem = self.dup
elem.altered = ORIGINAL_VALUES
var_combo << elem
end
if !audited?( audit_id( SAMPLE_VALUES ) )
elem = self.dup
elem.auditable = Arachni::Module::KeyFiller.fill( auditable.dup )
elem.altered = SAMPLE_VALUES
var_combo << elem
end
end
return var_combo.uniq if !@raw['auditable']
# if there are two password type fields in the form there's a good
# chance that it's a 'please retype your password' thing so make sure
# that we have a variation which has identical password values
filled_auditables = Arachni::Module::KeyFiller.fill( auditable.dup )
delem = self.dup
found_passwords = false
@raw['auditable'].each do |input|
if input['type'] == 'password'
delem.altered = input['name']
opts[:format].each do |format|
filled_auditables[input['name']] =
format_str( injection_str, filled_auditables[input['name']], format )
end
found_passwords = true
end
end
if found_passwords
delem.auditable = filled_auditables
var_combo << delem
end
var_combo.uniq
end
# @return [String] 'form'
def type
Arachni::Module::Auditor::Element::FORM
end
#
# Returns an array of forms by parsing the body of an HTTP response.
#
# @param [Typhoeus::Response] response
#
# @return [Array<Form>]
#
def self.from_response( response )
from_document( response.effective_url, response.body )
end
#
# Returns an array of forms from an HTML document.
#
# @param [String] url request URL
# @param [String, Nokogiri::HTML::Document] document
#
# @return [Array<Form>]
#
def self.from_document( url, document )
document = Nokogiri::HTML( document.to_s ) if !document.is_a?( Nokogiri::HTML::Document )
base_url = url
begin
base_url = document.search( '//base[@href]' )[0]['href']
rescue
base_url = url
end
document.search( '//form' ).map do |form|
form = form_from_element( base_url, form )
form.url = url
form
end.compact
end
def audit_id( injection_str = '', opts = {} )
str = if original?
ORIGINAL_VALUES
opts[:no_auditor] = true
elsif sample?
SAMPLE_VALUES
opts[:no_auditor] = true
else
injection_str
end
super( str, opts )
end
private
def self.form_from_element( url, form )
utilities = Arachni::Utilities
c_form = {}
c_form['attrs'] = attributes_to_hash( form.attributes )
if !c_form['attrs'] || !c_form['attrs']['action']
action = url.to_s
else
action = utilities.url_sanitize( c_form['attrs']['action'] )
end
begin
action = utilities.to_absolute( action.dup, url ).to_s
rescue
end
c_form['attrs']['action'] = action
if !c_form['attrs']['method']
c_form['attrs']['method'] = 'get'
else
c_form['attrs']['method'] = c_form['attrs']['method'].downcase
end
%w(textarea input select).each do |attr|
c_form[attr] ||= []
form.search( ".//#{attr}" ).each do |elem|
elem_attrs = attributes_to_hash( elem.attributes )
c_form[elem.name] ||= []
if elem.name != 'select'
c_form[elem.name] << elem_attrs
else
auditables = elem.children.map do |child|
h = attributes_to_hash( child.attributes )
h['value'] ||= child.text
h
end
c_form[elem.name] << {
'attrs' => elem_attrs,
'options' => auditables
}
end
end
end
# merge the form elements to make auditing easier
c_form['auditable'] = c_form['input'] | c_form['textarea']
c_form['auditable'] =
merge_select_with_input( c_form['auditable'], c_form['select'] )
new( url, c_form )
end
def self.attributes_to_hash( attributes )
attributes.inject( {} ){ |h, (k, v)| h[k] = v.to_s; h }
end
#
# Merges an array of form inputs with an array of form selects
#
# @param [Array] inputs
# @param [Array] selects
#
# @return [Array] merged array
#
def self.merge_select_with_input( inputs, selects )
selected = nil
inputs | selects.map do |select|
select['options'].each do |option|
if option.include?( 'selected' )
selected = option['value']
break
end
end
select['attrs']['value'] = selected || select['options'].first['value']
select['attrs']
end
end
def http_request( opts, &block )
if (original? || sample?) && !audited?( audit_id )
state = original? ? 'original' : 'sample'
print_debug( "Submitting form with #{state} values; overriding trainer option." )
opts[:train] = true
print_debug_trainer( opts )
end
@method.downcase.to_s != 'get' ?
http.post( @action, opts, &block ) : http.get( @action, opts, &block )
end
end
|
module CollectiveIdea
module Acts #:nodoc:
# This module provides some helpers for the model classes using acts_as_nested_set.
# It is included by default in all views. If you need to remove it, edit the last line
# of init.rb.
#
module NestedSetHelper
# Returns options for select.
# You can exclude some items from the tree.
# You can pass a block receiving an item and returning the string displayed in the select.
#
# == Usage
# Default is to use the whole tree and to print the first string column of your model.
# You can tweak this by passing your parameters, or better, pass a block that will receive
# an item from your nested set tree and that should return the line with the link.
#
# nested_set_options_for_select(Category) {|i| "#{'–' * i.level} #{i.name}" }
#
# == Params
# * +class_or_item+ - Class name or top level times
# * +&block+ - a block that will be used to display: { |item| ... item.name }
def nested_set_options_for_select(class_or_item)
class_or_item = class_or_item.roots if class_or_item.is_a?(Class)
items = Array(class_or_item)
result = []
items.each {|i| result += i.self_and_descendants.map {|i| [yield(i), i.id] } }
result
end
# This variation of nested_set_options_for_select takes a mover node and won't show
# any nodes that the mover can't move to.
def nested_set_options_for_select_without_impossible_moves(class_or_item, mover)
class_or_item = class_or_item.roots if class_or_item.is_a?(Class)
items = Array(class_or_item)
result = []
items.each {|i| result += i.self_and_descendants.map {|i| [yield(i), i.id] if mover.new_record? || mover.move_possible?(i)}.compact }
result
end
end
end
end
make the view helpers a little more railish
module CollectiveIdea
module Acts #:nodoc:
# This module provides some helpers for the model classes using acts_as_nested_set.
# It is included by default in all views. If you need to remove it, edit the last line
# of init.rb.
#
module NestedSetHelper
# Returns options for select.
# You can exclude some items from the tree.
# You can pass a block receiving an item and returning the string displayed in the select.
#
# == Usage
# Default is to use the whole tree and to print the first string column of your model.
# You can tweak this by passing your parameters, or better, pass a block that will receive
# an item from your nested set tree and that should return the line with the link.
#
# nested_set_options_for_select(Category) {|i| "#{'–' * i.level} #{i.name}" }
#
# == Params
# * +class_or_item+ - Class name or top level times
# * +&block+ - a block that will be used to display: { |item| ... item.name }
def nested_set_options_for_select(class_or_item)
class_or_item = class_or_item.roots if class_or_item.is_a?(Class)
items = Array(class_or_item)
returning [] do |result|
items.each {|i| result += i.self_and_descendants.map {|i| [yield(i), i.id] } }
end
end
# This variation of nested_set_options_for_select takes a mover node and won't show
# any nodes that the mover can't move to.
def nested_set_options_for_select_without_impossible_moves(class_or_item, mover)
class_or_item = class_or_item.roots if class_or_item.is_a?(Class)
items = Array(class_or_item)
returning [] do |result|
items.each {|i| result << i.self_and_descendants.map {|i| [yield(i), i.id] if mover.new_record? || mover.move_possible?(i)}.compact }
end
end
end
end
end
|
module Asteroids
class PlayState < GameState
def initialize
@background = Gosu::Image.new($window,
Utils.get_image_path('background.png'), false)
end
def draw
@background.draw(0, 0, 0)
end
def update
end
def button_down(id)
end
end
end
Add code to swich from play state to menu state.
module Asteroids
class PlayState < GameState
def initialize
@background = Gosu::Image.new($window,
Utils.get_image_path('background.png'), false)
end
def draw
@background.draw(0, 0, 0)
end
def update
end
def button_down(id)
if id == Gosu::KbEscape
Asteroids::GameState.switch(Asteroids::MenuState.instance)
end
end
end
end |
module Awspec::Generator
module Spec
class Acm
include Awspec::Helper::Finder
def generate_all
certificates = select_all_certificates
raise 'Not Found Certificates' if certificates.empty?
ERB.new(acm_spec_template, nil, '-').result(binding).chomp
end
def acm_spec_template
template = <<-'EOF'
<% certificates.each do |certificate| %>
describe acm('<%= certificate.domain_name %>') do
it { should exist }
<%- if certificate.status == 'ISSUED' -%>
it { should be_issued }
<% end -%>
its(:type) { should eq '<%= certificate.type %>' }
end
<% end %>
EOF
template
end
end
end
end
Add acm domain_validation_option generate
module Awspec::Generator
module Spec
class Acm
include Awspec::Helper::Finder
def generate_all
certificates = select_all_certificates
raise 'Not Found Certificates' if certificates.empty?
ERB.new(acm_spec_template, nil, '-').result(binding).chomp
end
def acm_spec_template
template = <<-'EOF'
<% certificates.each do |certificate| %>
describe acm('<%= certificate.domain_name %>') do
it { should exist }
<%- if certificate.status == 'ISSUED' -%>
it { should be_issued }
<% end -%>
its(:type) { should eq '<%= certificate.type %>' }
<%- certificate.domain_validation_options.each do |domain_validation_option| -%>
<%- unless domain_validation_option.validation_status.nil? -%>
it { should have_domain_validation_option(domain_name: '<%= domain_validation_option.domain_name %>', validation_method: '<%= domain_validation_option.validation_method%>', validation_status: '<%= domain_validation_option.validation_status %>') }
<%- else -%>
it { should have_domain_validation_option(domain_name: '<%= domain_validation_option.domain_name %>', validation_method: '<%= domain_validation_option.validation_method%>') }
<%- end -%>
<%- end -%>
end
<% end %>
EOF
template
end
end
end
end
|
# frozen_string_literal: true
module Attributor
module Flatpack
VERSION = '1.4.1'
end
end
Prep 1.4.2
# frozen_string_literal: true
module Attributor
module Flatpack
VERSION = '1.4.2'
end
end
|
require 'cgi'
require 'net/http/post/multipart'
module AzkabanScheduler
class Session
attr_accessor :id
def self.start(client, username, password)
params = {'action' => 'login', 'username' => username, 'password' => password}
response = client.post('/', params)
response.error! unless response.kind_of?(Net::HTTPSuccess)
result = JSON.parse(response.body)
unless result["status"] == "success"
error_message = result["error"]
if error_message == "Incorrect Login. Username\/Password not found."
raise AuthenticationError, error_message
end
raise AzkabanError, error_message
end
new(client, result['session.id'])
end
def initialize(client, id)
@client = client
@id = id
end
def create_project(project)
response = @client.post('/manager', {
'session.id' => @id,
'action' => 'create',
'name' => project.name,
'description' => project.description,
})
response.error! unless response.kind_of?(Net::HTTPSuccess)
result = JSON.parse(response.body)
if result['status'] != 'success'
error_message = result['message']
if error_message == "Active project with name #{project.name} already exists in db."
raise ProjectExistsError, error_message
elsif error_message == "Project names must start with a letter, followed by any number of letters, digits, '-' or '_'."
raise InvalidProjectNameError, error_message
elsif error_message == "Description cannot be empty."
raise ProjectDescriptionEmptyError, error_message
end
raise AzkabanError, error_message
end
result
end
def upload_project(project)
response = @client.multipart_post('/manager', {
'session.id' => @id,
'ajax' => 'upload',
'project' => project.name,
'file' => UploadIO.new(project.build, 'application/zip', 'file.zip'),
})
response.error! unless response.kind_of?(Net::HTTPSuccess)
result = JSON.parse(response.body)
if error_message = result['error']
if error_message == "Installation Failed. Project '#{project.name}' doesn't exist."
raise ProjectNotFoundError, error_message
end
raise AzkabanError, error_message
end
project.id = result['projectId']
project.version = result['version']
result
end
def delete_project(project_name)
response = @client.get('/manager', {
'session.id' => @id,
'project' => project_name,
'delete' => 'true',
})
response.error! unless response.kind_of?(Net::HTTPSuccess) || response.kind_of?(Net::HTTPRedirection)
cookies = response_cookies(response)
unless cookies['azkaban.success.message']
error_message = cookies['azkaban.failure.message']
if error_message == "Project #{project_name} doesn't exist."
return false
end
raise AzkabanError, error_message
end
true
end
def list_schedules
response = @client.post('/schedule', { 'ajax' => 'loadFlow' }, session_id_cookie)
response.error! unless response.kind_of?(Net::HTTPSuccess)
result = JSON.parse(response.body)
result['items'] || []
end
def remove_schedule(schedule_id)
response = @client.post('/schedule', {
'action' => 'removeSched',
'scheduleId' => schedule_id,
}, session_id_cookie)
response.error! unless response.kind_of?(Net::HTTPSuccess)
result = JSON.parse(response.body)
unless result['status'] == 'success'
error_message = result['message']
return false if error_message == "Schedule with ID #{schedule_id} does not exist"
raise AzkabanError, error_message
end
true
end
def remove_all_schedules(project_name)
list_schedules.each do |schedule|
next unless schedule['projectname'] == project_name
schedule_id = schedule['scheduleid']
remove_schedule(schedule_id)
end
end
def post_schedule(project_id, project_name, flow, start_time, options={})
response = @client.post('/schedule', {
'ajax' => 'scheduleFlow',
'project' => project_name,
'projectName' => project_name,
'projectId' => project_id,
'flow' => flow,
'disabled' => options[:disabled] || '[]',
'period' => options[:period] || "1d",
'scheduleTime' => start_time.utc.strftime("%I,%M,%p,UTC"),
'scheduleDate' => start_time.utc.strftime("%m/%d/%Y"),
'is_recurring' => options[:period] ? 'on' : 'off',
'concurrentOption' => options[:concurrent_option] || 'skip',
'failureEmailsOverride' => (!!options[:failure_emails_override]).to_s,
'successEmailsOverride' => (!!options[:success_emails_override]).to_s,
'failureAction' => options[:failure_action] || 'finishCurrent',
'failureEmails' => Array(options[:failure_emails]).join(', '),
'successEmails' => Array(options[:success_emails]).join(', '),
'notifyFailureFirst' => (!!options[:notify_failure_first]).to_s,
'notifyFailureLast' => (!!options[:notify_failure_last]).to_s,
}, session_id_cookie)
response.error! unless response.kind_of?(Net::HTTPSuccess)
result = JSON.parse(response.body)
unless result['status'] == 'success'
raise AzkabanError, result['message']
end
nil
end
private
def response_cookies(response)
response['Set-Cookie'].split(',').each_with_object({}) do |cookie, hash|
name, value = cookie.split(';')[0].split('=', 2)
value = value.to_s.strip
value = value[1...-1] if value[0] == '"'.freeze && value[-1] == '"'.freeze
hash[name.strip] = value
end
end
def session_id_cookie
{ 'Cookie' => "azkaban.browser.session.id=#{@id}" }
end
end
end
Add ability to fetch project id, flow names and flow executions.
require 'cgi'
require 'net/http/post/multipart'
module AzkabanScheduler
class Session
attr_accessor :id
def self.start(client, username, password)
params = {'action' => 'login', 'username' => username, 'password' => password}
response = client.post('/', params)
response.error! unless response.kind_of?(Net::HTTPSuccess)
result = JSON.parse(response.body)
unless result["status"] == "success"
error_message = result["error"]
if error_message == "Incorrect Login. Username\/Password not found."
raise AuthenticationError, error_message
end
raise AzkabanError, error_message
end
new(client, result['session.id'])
end
def initialize(client, id)
@client = client
@id = id
end
def create_project(project)
response = @client.post('/manager', {
'session.id' => @id,
'action' => 'create',
'name' => project.name,
'description' => project.description,
})
response.error! unless response.kind_of?(Net::HTTPSuccess)
result = JSON.parse(response.body)
if result['status'] != 'success'
error_message = result['message']
if error_message == "Active project with name #{project.name} already exists in db."
raise ProjectExistsError, error_message
elsif error_message == "Project names must start with a letter, followed by any number of letters, digits, '-' or '_'."
raise InvalidProjectNameError, error_message
elsif error_message == "Description cannot be empty."
raise ProjectDescriptionEmptyError, error_message
end
raise AzkabanError, error_message
end
result
end
def upload_project(project)
response = @client.multipart_post('/manager', {
'session.id' => @id,
'ajax' => 'upload',
'project' => project.name,
'file' => UploadIO.new(project.build, 'application/zip', 'file.zip'),
})
response.error! unless response.kind_of?(Net::HTTPSuccess)
result = JSON.parse(response.body)
if error_message = result['error']
if error_message == "Installation Failed. Project '#{project.name}' doesn't exist."
raise ProjectNotFoundError, error_message
end
raise AzkabanError, error_message
end
project.id = result['projectId']
project.version = result['version']
result
end
def delete_project(project_name)
response = @client.get('/manager', {
'session.id' => @id,
'project' => project_name,
'delete' => 'true',
})
response.error! unless response.kind_of?(Net::HTTPSuccess) || response.kind_of?(Net::HTTPRedirection)
cookies = response_cookies(response)
unless cookies['azkaban.success.message']
error_message = cookies['azkaban.failure.message']
if error_message == "Project #{project_name} doesn't exist."
return false
end
raise AzkabanError, error_message
end
true
end
def get_project_id(project_name)
result = fetch_project_flows(project_name)
result['projectId']
end
def list_flow_ids(project_name)
result = fetch_project_flows(project_name)
result['flows'].map{ |flow| flow['flowId'] }
end
def fetch_project_flows(project_name)
response = @client.get('/manager', {
'session.id' => @id,
'ajax' => 'fetchprojectflows',
'project' => project_name,
})
response.error! unless response.kind_of?(Net::HTTPSuccess)
JSON.parse(response.body)
end
def fetch_flow_executions(project_name, flow_id, offset=0, limit=10)
response = @client.get('/manager', {
'session.id' => @id,
'ajax' => 'fetchFlowExecutions',
'project' => project_name,
'flow' => flow_id,
'start' => offset,
'length' => limit,
})
response.error! unless response.kind_of?(Net::HTTPSuccess)
JSON.parse(response.body)
end
def list_schedules
response = @client.post('/schedule', { 'ajax' => 'loadFlow' }, session_id_cookie)
response.error! unless response.kind_of?(Net::HTTPSuccess)
result = JSON.parse(response.body)
result['items'] || []
end
def remove_schedule(schedule_id)
response = @client.post('/schedule', {
'action' => 'removeSched',
'scheduleId' => schedule_id,
}, session_id_cookie)
response.error! unless response.kind_of?(Net::HTTPSuccess)
result = JSON.parse(response.body)
unless result['status'] == 'success'
error_message = result['message']
return false if error_message == "Schedule with ID #{schedule_id} does not exist"
raise AzkabanError, error_message
end
true
end
def remove_all_schedules(project_name)
list_schedules.each do |schedule|
next unless schedule['projectname'] == project_name
schedule_id = schedule['scheduleid']
remove_schedule(schedule_id)
end
end
def post_schedule(project_id, project_name, flow, start_time, options={})
response = @client.post('/schedule', {
'ajax' => 'scheduleFlow',
'project' => project_name,
'projectName' => project_name,
'projectId' => project_id,
'flow' => flow,
'disabled' => options[:disabled] || '[]',
'period' => options[:period] || "1d",
'scheduleTime' => start_time.utc.strftime("%I,%M,%p,UTC"),
'scheduleDate' => start_time.utc.strftime("%m/%d/%Y"),
'is_recurring' => options[:period] ? 'on' : 'off',
'concurrentOption' => options[:concurrent_option] || 'skip',
'failureEmailsOverride' => (!!options[:failure_emails_override]).to_s,
'successEmailsOverride' => (!!options[:success_emails_override]).to_s,
'failureAction' => options[:failure_action] || 'finishCurrent',
'failureEmails' => Array(options[:failure_emails]).join(', '),
'successEmails' => Array(options[:success_emails]).join(', '),
'notifyFailureFirst' => (!!options[:notify_failure_first]).to_s,
'notifyFailureLast' => (!!options[:notify_failure_last]).to_s,
}, session_id_cookie)
response.error! unless response.kind_of?(Net::HTTPSuccess)
result = JSON.parse(response.body)
unless result['status'] == 'success'
raise AzkabanError, result['message']
end
nil
end
private
def response_cookies(response)
response['Set-Cookie'].split(',').each_with_object({}) do |cookie, hash|
name, value = cookie.split(';')[0].split('=', 2)
value = value.to_s.strip
value = value[1...-1] if value[0] == '"'.freeze && value[-1] == '"'.freeze
hash[name.strip] = value
end
end
def session_id_cookie
{ 'Cookie' => "azkaban.browser.session.id=#{@id}" }
end
end
end
|
require 'aws/core/util'
require 'aws/core/request'
require 'aws/core/connection'
module AWS
module CallTypes
##
# Implement call handling to work with the ?Action param, signing the message
# according to whatever Signing module is included along side this module
##
module ActionParam
##
# For any undefined methods, try to convert them into valid AWS
# actions and return the results
##
def method_missing(name, *args)
request = AWS::Request.new :post, self.uri, "/"
request.params["Action"] = AWS::Util.camelcase(name.to_s)
if args.any? && args.first.is_a?(Hash)
insert_params_from request, args.first
end
send_request request
end
protected
def send_request(request)
connection = AWS::Connection.new
connection.call finish_and_sign_request(request)
end
def insert_params_from(request, args = {})
args.each do |key, value|
request.params[key] = value
end
end
end
end
end
Add details to ActionParam call type
require 'aws/core/util'
require 'aws/core/request'
require 'aws/core/connection'
module AWS
module CallTypes
##
# Implement call handling to work with the ?Action param, signing the message
# according to whatever Signing module is included along side this module.
#
# This module hooks up the `method_missing` functionality as described in the
# {README}. To call methods on APIs including this module, simply call a method
# with either the Ruby-fied name, or the full CamelCase name, and pass in
# options required as the parameters.
#
# All responses will be wrapped up in an {AWS::Response AWS::Response} object.
##
module ActionParam
##
# For any undefined methods, try to convert them into valid AWS
# actions and return the results
##
def method_missing(name, *args)
request = AWS::Request.new :post, self.uri, "/"
request.params["Action"] = AWS::Util.camelcase(name.to_s)
if args.any? && args.first.is_a?(Hash)
insert_params_from request, args.first
end
send_request request
end
protected
def send_request(request)
connection = AWS::Connection.new
connection.call finish_and_sign_request(request)
end
def insert_params_from(request, args = {})
args.each do |key, value|
request.params[key] = value
end
end
end
end
end
|
module RailsMoney
def method_missing( method_id, *args )
method_name = method_id.to_s
setter = method_name.chomp!("=")
method_name = "#{method_name}_in_cents"
if @attributes.include?(method_name)
if setter
money = args.first.kind_of?(Money) ? args.first : Money.new(args.first)
write_attribute(method_name,money.cents)
else
Money.create_from_cents(read_attribute(method_name))
end
else
super
end
end
def respond_to?( method, include_private = false )
method_name = method.to_s.chomp("=")
@attributes.include?("#{method_name}_in_cents") || super
end
end
ActiveRecord::Base.send :include, RailsMoney
* With these changes database column names do not
need to be changed
* Works through Associations & regular object
pulls from the find methods
* Will require each model that
has Money Fields to update the model with
(Example: money_format :rate_in_cents,
:expense_in_cents)
* Now a developer can see the public methods for
the "field"_in_cents on the model when typing
model.public_methods
(Should show "field" and "field=")
class ActiveRecord::Base
def self.money_format(*fields)
fields.each do |field|
temp_field = field.to_s.sub(/(_in_cents)/,"")
define_method("#{temp_field}=") do |value|
money = value.kind_of?(Money) ? value : Money.new(value)
return self.send("#{temp_field}_in_cents=",money.cents)
end
define_method("#{temp_field}") do
return Money.create_from_cents(self.send("#{temp_field}_in_cents"))
end
end
end
end
|
#-------------------------------------------------------------------------
# Copyright 2012 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#--------------------------------------------------------------------------
require 'azure/service/storage_service'
require 'azure/entity/serialization'
module Azure
module Service
class QueueService < StorageService
def initialize
super()
@host = Azure.config.queue_host
@default_timeout = 30
end
# Public: Get a list of Queues from the server
# options - Hash. Optional parameters.
#
# Accepted key/value pairs in options parameter are:
# :prefix - String. Filters the results to return only containers
# whose name begins with the specified prefix. (optional)
#
# :marker - String. An identifier the specifies the portion of the
# list to be returned. This value comes from the property
# Azure::Entity::Blob::EnumerationResults.marker when there
# are more containers available than were returned. The
# marker value may then be used here to request the next set
# of list items. (optional)
#
# :max_results - Integer. Specifies the maximum number of containers to return.
# If max_results is not specified, or is a value greater than
# 5,000, the server will return up to 5,000 items. If it is set
# to a value less than or equal to zero, the server will return
# status code 400 (Bad Request). (optional)
#
# :timeout - Integer. A timeout in seconds. (optional)
#
# :metadata - Boolean. Specifies wether or not to return the container metadata.
# (optional, Default=false)
#
# NOTE: Metadata requested with the :metadata parameter must have been stored in
# accordance with the naming restrictions imposed by the 2009-09-19 version of the Blob
# service. Beginning with that version, all metadata names must adhere to the naming
# conventions for C# identifiers.
#
# See http://msdn.microsoft.com/en-us/library/windowsazure/dd179466
#
# Any metadata with invalid names which were previously stored, will be returned with the
# key "x-ms-invalid-name" in the metadata hash. This may contain multiple values and be an
# Array (vs a String if it only contains a single value).
#
# Returns an Azure::Entity::Blob::QueueEnumerationResults
def list_queues(options={})
query = {}
query["prefix"] = options[:prefix] if options[:prefix]
query["marker"] = options[:marker] if options[:marker]
query["maxresults"] = options[:max_results].to_s if options[:max_results]
query["include"] = "metadata" if options[:metadata] == true
query["timeout"] = options[:timeout].to_s if options[:timeout]
uri = collection_uri(query)
response = call(:get, uri)
Azure::Entity::Serialization.queue_enumeration_results_from_xml(response.body)
end
# Public: Clears all messages from the queue.
#
# If a queue contains a large number of messages, Clear Messages may time out
# before all messages have been deleted. In this case the Queue service will
# return status code 500 (Internal Server Error), with the additional error
# code OperationTimedOut. If the operation times out, the client should
# continue to retry Clear Messages until it succeeds, to ensure that all
# messages have been deleted.
#
# queue_name - String. The name of the queue.
#
# See http://msdn.microsoft.com/en-us/library/windowsazure/dd179454
#
# Returns true on success
def clear_messages(queue_name)
uri = messages_uri(queue_name)
response = call(:delete, uri)
response.success?
end
# Public: Creates a new queue under the storage account.
#
# queue_name - String. The queue name.
# metadata - Hash. A hash of user defined metadata (optional)
#
# See http://msdn.microsoft.com/en-us/library/windowsazure/dd179342
#
# Returns true on success
def create_queue(queue_name, metadata=nil)
uri = queue_uri(queue_name)
headers = {}
add_metadata_to_headers(metadata || {}, headers)
response = call(:put, uri, nil, headers)
response.success?
end
# Public: Deletes a queue.
#
# queue_name - String. The queue name.
#
# See http://msdn.microsoft.com/en-us/library/windowsazure/dd179436
#
# Returns true on success
def delete_queue(queue_name)
uri = queue_uri(queue_name)
response = call(:delete, uri)
response.success?
end
# Public: Returns queue properties, including user-defined metadata.
#
# queue_name - String. The queue name.
#
# See http://msdn.microsoft.com/en-us/library/windowsazure/dd179384
#
# Returns a tuple of (approximate_message_count, metadata)
# approximate_messages_count - Integer. The approximate number of messages in the queue. This number is not
# lower than the actual number of messages in the queue, but could be higher.
# metadata - Hash. The queue metadata (Default: {})
#
def get_queue_metadata(queue_name)
uri = queue_uri(queue_name, { "comp" => "metadata" })
response = call(:get, uri)
approximate_messages_count = response.headers["x-ms-approximate-messages-count"]
metadata = Azure::Entity::Serialization.metadata_from_headers(response.headers)
return approximate_messages_count, metadata
end
# Public: Sets user-defined metadata on the queue. To delete queue metadata, call
# this API with an empty hash in the metadata parameter.
#
# queue_name - String. The queue name.
# metadata - Hash. A hash of user defined metadata
#
# See http://msdn.microsoft.com/en-us/library/windowsazure/dd179348
#
# Returns true on success
def set_queue_metadata(queue_name, metadata)
uri = queue_uri(queue_name, { "comp" => "metadata" })
headers ={}
add_metadata_to_headers(metadata || {}, headers)
response = call(:put, uri, nil, headers)
response.success?
end
# Public: Gets the access control list (ACL) for the queue.
#
# queue_name - String. The queue name.
#
# See http://msdn.microsoft.com/en-us/library/windowsazure/jj159101
#
# Returns a list of Azure::Entity::SignedIdentifier instances
def get_queue_acl(queue_name)
response = call(:get, queue_uri(queue_name, {"comp"=>"acl"}))
signed_identifiers = []
signed_identifiers = Azure::Entity::Serialization.signed_identifiers_from_xml(response.body) unless response.body == nil or response.body.length < 1
signed_identifiers
end
# Public: Sets the access control list (ACL) for the queue.
#
# queue_name - String. The queue name.
# signed_identifiers - Array. A list of Azure::Entity::SignedIdentifier instances
#
# See http://msdn.microsoft.com/en-us/library/windowsazure/jj159099
#
# Returns true on success
def set_queue_acl(queue_name, signed_identifiers=[])
uri =queue_uri(queue_name, {"comp"=>"acl"})
body = nil
body = Azure::Entity::Serialization.signed_identifiers_to_xml(signed_identifiers) if signed_identifiers && signed_identifiers.length > 0
response = call(:put, uri, body, {})
response.success?
end
# Public: Adds a message to the queue and optionally sets a visibility timeout for the message.
#
# queue_name - String. The queue name.
# message_text - String. The message contents. Note that the message content must be in a format that may be encoded with UTF-8.
# options - Hash. Optional parameters:
# :visibility_timeout - Integer. Specifies the new visibility timeout value, in seconds, relative to server
# time. The new value must be larger than or equal to 0, and cannot be larger than 7
# days. The visibility timeout of a message cannot be set to a value later than the
# expiry time. :visibility_timeout should be set to a value smaller than the
# time-to-live value. If not specified, the default value is 0.
#
# :message_ttl - Integer. Specifies the time-to-live interval for the message, in seconds. The maximum
# time-to-live allowed is 7 days. If not specified, the default time-to-live is 7 days.
#
# See http://msdn.microsoft.com/en-us/library/windowsazure/dd179346
#
# Returns true on success
def create_message(queue_name, message_text, options=nil)
query = {}
if options
query["visibilitytimeout"] = options[:visibility_timeout] if options[:visibility_timeout]
query["messagettl"] = options[:message_ttl] if options[:message_ttl]
end
uri = messages_uri(queue_name, query)
body = Azure::Entity::Serialization.message_to_xml(message_text)
response = call(:post, uri, body, {})
response.success?
end
# Public: Generate the URI for the collection of queues.
#
# query - A Hash of query parameters (default: {}).
#
# Returns a URI.
def collection_uri(query={})
query.update(comp: 'list', include: 'metadata')
generate_uri(host, "", query)
end
# Public: Generate the URI for a given queue.
#
# queue_name - The name of the queue.
# query - A Hash of query parameters (default: {}).
#
# Returns a URI.
def queue_uri(queue_name, query={})
return queue_name if name.kind_of? ::URI
generate_uri(host, queue_name, query)
end
# Public: Generate the messages URI for the given queue.
#
# queue_name - The name of the queue.
# query - A Hash of query parameters (default: {}).
#
# Returns a URI.
def messages_uri(queue_name, query={})
generate_uri(host, "#{queue_name}/messages", query)
end
# Public: Generate the URI for a given message
#
# queue_name - The name of the queue.
# message_id - The id of the message.
# query - A Hash of query parameters (default: {}).
#
# Returns a URI.
def message_uri(queue_name, message_id, query={})
generate_uri("#{queue_name}/messages/#{message_id}", query)
end
end
end
end
implement QueueService.delete_messsage
#-------------------------------------------------------------------------
# Copyright 2012 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#--------------------------------------------------------------------------
require 'azure/service/storage_service'
require 'azure/entity/serialization'
module Azure
module Service
class QueueService < StorageService
def initialize
super()
@host = Azure.config.queue_host
@default_timeout = 30
end
# Public: Get a list of Queues from the server
# options - Hash. Optional parameters.
#
# Accepted key/value pairs in options parameter are:
# :prefix - String. Filters the results to return only containers
# whose name begins with the specified prefix. (optional)
#
# :marker - String. An identifier the specifies the portion of the
# list to be returned. This value comes from the property
# Azure::Entity::Blob::EnumerationResults.marker when there
# are more containers available than were returned. The
# marker value may then be used here to request the next set
# of list items. (optional)
#
# :max_results - Integer. Specifies the maximum number of containers to return.
# If max_results is not specified, or is a value greater than
# 5,000, the server will return up to 5,000 items. If it is set
# to a value less than or equal to zero, the server will return
# status code 400 (Bad Request). (optional)
#
# :timeout - Integer. A timeout in seconds. (optional)
#
# :metadata - Boolean. Specifies wether or not to return the container metadata.
# (optional, Default=false)
#
# NOTE: Metadata requested with the :metadata parameter must have been stored in
# accordance with the naming restrictions imposed by the 2009-09-19 version of the Blob
# service. Beginning with that version, all metadata names must adhere to the naming
# conventions for C# identifiers.
#
# See http://msdn.microsoft.com/en-us/library/windowsazure/dd179466
#
# Any metadata with invalid names which were previously stored, will be returned with the
# key "x-ms-invalid-name" in the metadata hash. This may contain multiple values and be an
# Array (vs a String if it only contains a single value).
#
# Returns an Azure::Entity::Blob::QueueEnumerationResults
def list_queues(options={})
query = {}
query["prefix"] = options[:prefix] if options[:prefix]
query["marker"] = options[:marker] if options[:marker]
query["maxresults"] = options[:max_results].to_s if options[:max_results]
query["include"] = "metadata" if options[:metadata] == true
query["timeout"] = options[:timeout].to_s if options[:timeout]
uri = collection_uri(query)
response = call(:get, uri)
Azure::Entity::Serialization.queue_enumeration_results_from_xml(response.body)
end
# Public: Clears all messages from the queue.
#
# If a queue contains a large number of messages, Clear Messages may time out
# before all messages have been deleted. In this case the Queue service will
# return status code 500 (Internal Server Error), with the additional error
# code OperationTimedOut. If the operation times out, the client should
# continue to retry Clear Messages until it succeeds, to ensure that all
# messages have been deleted.
#
# queue_name - String. The name of the queue.
#
# See http://msdn.microsoft.com/en-us/library/windowsazure/dd179454
#
# Returns true on success
def clear_messages(queue_name)
uri = messages_uri(queue_name)
response = call(:delete, uri)
response.success?
end
# Public: Creates a new queue under the storage account.
#
# queue_name - String. The queue name.
# metadata - Hash. A hash of user defined metadata (optional)
#
# See http://msdn.microsoft.com/en-us/library/windowsazure/dd179342
#
# Returns true on success
def create_queue(queue_name, metadata=nil)
uri = queue_uri(queue_name)
headers = {}
add_metadata_to_headers(metadata || {}, headers)
response = call(:put, uri, nil, headers)
response.success?
end
# Public: Deletes a queue.
#
# queue_name - String. The queue name.
#
# See http://msdn.microsoft.com/en-us/library/windowsazure/dd179436
#
# Returns true on success
def delete_queue(queue_name)
uri = queue_uri(queue_name)
response = call(:delete, uri)
response.success?
end
# Public: Returns queue properties, including user-defined metadata.
#
# queue_name - String. The queue name.
#
# See http://msdn.microsoft.com/en-us/library/windowsazure/dd179384
#
# Returns a tuple of (approximate_message_count, metadata)
# approximate_messages_count - Integer. The approximate number of messages in the queue. This number is not
# lower than the actual number of messages in the queue, but could be higher.
# metadata - Hash. The queue metadata (Default: {})
#
def get_queue_metadata(queue_name)
uri = queue_uri(queue_name, { "comp" => "metadata" })
response = call(:get, uri)
approximate_messages_count = response.headers["x-ms-approximate-messages-count"]
metadata = Azure::Entity::Serialization.metadata_from_headers(response.headers)
return approximate_messages_count, metadata
end
# Public: Sets user-defined metadata on the queue. To delete queue metadata, call
# this API with an empty hash in the metadata parameter.
#
# queue_name - String. The queue name.
# metadata - Hash. A hash of user defined metadata
#
# See http://msdn.microsoft.com/en-us/library/windowsazure/dd179348
#
# Returns true on success
def set_queue_metadata(queue_name, metadata)
uri = queue_uri(queue_name, { "comp" => "metadata" })
headers ={}
add_metadata_to_headers(metadata || {}, headers)
response = call(:put, uri, nil, headers)
response.success?
end
# Public: Gets the access control list (ACL) for the queue.
#
# queue_name - String. The queue name.
#
# See http://msdn.microsoft.com/en-us/library/windowsazure/jj159101
#
# Returns a list of Azure::Entity::SignedIdentifier instances
def get_queue_acl(queue_name)
response = call(:get, queue_uri(queue_name, {"comp"=>"acl"}))
signed_identifiers = []
signed_identifiers = Azure::Entity::Serialization.signed_identifiers_from_xml(response.body) unless response.body == nil or response.body.length < 1
signed_identifiers
end
# Public: Sets the access control list (ACL) for the queue.
#
# queue_name - String. The queue name.
# signed_identifiers - Array. A list of Azure::Entity::SignedIdentifier instances
#
# See http://msdn.microsoft.com/en-us/library/windowsazure/jj159099
#
# Returns true on success
def set_queue_acl(queue_name, signed_identifiers=[])
uri =queue_uri(queue_name, {"comp"=>"acl"})
body = nil
body = Azure::Entity::Serialization.signed_identifiers_to_xml(signed_identifiers) if signed_identifiers && signed_identifiers.length > 0
response = call(:put, uri, body, {})
response.success?
end
# Public: Adds a message to the queue and optionally sets a visibility timeout for the message.
#
# queue_name - String. The queue name.
# message_text - String. The message contents. Note that the message content must be in a format that may be encoded with UTF-8.
# options - Hash. Optional parameters:
# :visibility_timeout - Integer. Specifies the new visibility timeout value, in seconds, relative to server
# time. The new value must be larger than or equal to 0, and cannot be larger than 7
# days. The visibility timeout of a message cannot be set to a value later than the
# expiry time. :visibility_timeout should be set to a value smaller than the
# time-to-live value. If not specified, the default value is 0.
#
# :message_ttl - Integer. Specifies the time-to-live interval for the message, in seconds. The maximum
# time-to-live allowed is 7 days. If not specified, the default time-to-live is 7 days.
#
# See http://msdn.microsoft.com/en-us/library/windowsazure/dd179346
#
# Returns true on success
def create_message(queue_name, message_text, options=nil)
query = {}
if options
query["visibilitytimeout"] = options[:visibility_timeout] if options[:visibility_timeout]
query["messagettl"] = options[:message_ttl] if options[:message_ttl]
end
uri = messages_uri(queue_name, query)
body = Azure::Entity::Serialization.message_to_xml(message_text)
response = call(:post, uri, body, {})
response.success?
end
# Public: Deletes a specified message from the queue.
#
# queue_name - String. The name of the queue.
# message_id - String. The id of the message.
# pop_receipt - String. The valid pop receipt value returned from an earlier call to the Get Messages or
# Update Message operation.
#
# See http://msdn.microsoft.com/en-us/library/windowsazure/dd179347
#
# Returns true on success
#
# Remarks:
#
# When a message is successfully deleted, it is immediately marked for deletion and is no longer accessible to
# clients. The message is later removed from the queue during garbage collection.
#
# After a client retrieves a message with the Get Messages operation, the client is expected to process and
# delete the message. To delete the message, you must have two items of data returned in the response body of
# the Get Messages operation:
#
# - The message ID, an opaque GUID value that identifies the message in the queue.
#
# - A valid pop receipt, an opaque value that indicates that the message has been retrieved.
#
# The message ID is returned from the previous Get Messages operation. The pop receipt is returned from the most
# recent Get Messages or Update Message operation. In order for the Delete Message operation to succeed, the pop
# receipt specified on the request must match the pop receipt returned from the Get Messages or Update Message
# operation.
#
# Pop receipts remain valid until one of the following events occurs:
#
# - The message has expired.
#
# - The message has been deleted using the last pop receipt received either from Get Messages or Update Message.
#
# - The invisibility time has elapsed and the message has been dequeued by a Get Messages request. When the
# invisibility time elapses, the message becomes visible again. If it is retrieved by another Get Messages
# request, the returned pop receipt can be used to delete or update the message.
#
# - The message has been updated with a new visibility timeout. When the message is updated, a new pop receipt
# will be returned.
#
# If the message has already been deleted when Delete Message is called, the Queue service returns status code
# 404 (Not Found).
#
# If a message with a matching pop receipt is not found, the service returns status code 400 (Bad Request), with
# additional error information indicating that the cause of the failure was a mismatched pop receipt.
#
def delete_message(queue_name, message_id, pop_receipt)
uri = message_uri(queue_name, message_id, { "popreceipt" => pop_receipt })
response = call(:delete, uri)
response.success?
end
# Public: Generate the URI for the collection of queues.
#
# query - A Hash of query parameters (default: {}).
#
# Returns a URI.
def collection_uri(query={})
query.update(comp: 'list', include: 'metadata')
generate_uri(host, "", query)
end
# Public: Generate the URI for a given queue.
#
# queue_name - The name of the queue.
# query - A Hash of query parameters (default: {}).
#
# Returns a URI.
def queue_uri(queue_name, query={})
return queue_name if name.kind_of? ::URI
generate_uri(host, queue_name, query)
end
# Public: Generate the messages URI for the given queue.
#
# queue_name - The name of the queue.
# query - A Hash of query parameters (default: {}).
#
# Returns a URI.
def messages_uri(queue_name, query={})
generate_uri(host, "#{queue_name}/messages", query)
end
# Public: Generate the URI for a given message
#
# queue_name - The name of the queue.
# message_id - The id of the message.
# query - A Hash of query parameters (default: {}).
#
# Returns a URI.
def message_uri(queue_name, message_id, query={})
generate_uri("#{queue_name}/messages/#{message_id}", query)
end
end
end
end |
# Módulo Bibliográfico
module Bibliografia
# Clase Referencia para gestionar las de una Bibliografía
class Referencia
include Comparable
# Getters + Setters
attr_accessor :autores, :titulo, :serie, :editorial, :num_edicion, :fecha_publicacion, :num_isbns
# Constructor
def initialize(autores, titulo, serie, editorial, num_edicion, fecha_publicacion, num_isbns)
@autores = autores
@titulo = titulo
@serie = serie
@editorial = editorial
@num_edicion = num_edicion
@fecha_publicacion = fecha_publicacion
@num_isbns = num_isbns
end
# Muestra lista de autores
def print_autor
count = 0
lista = ""
autores.each do |autor|
count += 1
lista += autor
lista += ", " if count != autores.size
end
lista
end
# Muestra lista de isbn
def print_isbn
lista = ""
num_isbns.each do |isbn|
count = 0
lista += "ISBN-" + isbn.delete('^0-9').size.to_s + ": " + isbn
lista += "\n" if count != num_isbns.size
end
lista
end
# Para método puts
def to_s
"#{print_autor}\n#{titulo}\n#{serie}\n#{editorial}; #{num_edicion} #{fecha_publicacion}\n#{print_isbn}"
end
# Guerra de las galaxias
def <=>(other)
@fecha_publicacion <=> other.fecha_publicacion
end
end
class Libro < Referencia
#Constructor
def initialize(*parametros)
super
end
end # clase
class Articulo_revista < Referencia
# Getter + Setter
attr_accessor :num_issns
# Constructor
def initialize(*parametros, num_issns)
super(*parametros)
@num_issns = num_issns
end
end
class Articulo_periodico < Referencia
# Getter + Setter
attr_accessor :num_columnas
# Constructor
def initialize(*parametros, num_columnas)
super(*parametros)
@num_columnas = num_columnas
end
end
class Documento_electronico < Referencia
# Getter + Setter
attr_accessor :url
# Constructor
def initialize(*parametros, url)
super(*parametros)
@url = url
end
end
end
Para arrancar travis
# Módulo Bibliográfico
module Bibliografia
# Clase Referencia para gestionar las de una Bibliografía
class Referencia
include Comparable
# Getters + Setters
attr_accessor :autores, :titulo, :serie, :editorial, :num_edicion, :fecha_publicacion, :num_isbns
# Constructor
def initialize(autores, titulo, serie, editorial, num_edicion, fecha_publicacion, num_isbns)
@autores = autores
@titulo = titulo
@serie = serie
@editorial = editorial
@num_edicion = num_edicion
@fecha_publicacion = fecha_publicacion
@num_isbns = num_isbns
end
# Muestra lista de autores
def print_autor
count = 0
lista = ""
autores.each do |autor|
count += 1
lista += autor
lista += ", " if count != autores.size
end
lista
end
# Muestra lista de isbn
def print_isbn
lista = ""
num_isbns.each do |isbn|
count = 0
lista += "ISBN-" + isbn.delete('^0-9').size.to_s + ": " + isbn
lista += "\n" if count != num_isbns.size
end
lista
end
# Para método puts
def to_s
"#{print_autor}\n#{titulo}\n#{serie}\n#{editorial}; #{num_edicion} #{fecha_publicacion}\n#{print_isbn}"
end
# Guerra de las galaxias
def <=>(other)
@fecha_publicacion <=> other.fecha_publicacion
end
end
class Libro < Referencia
#Constructor
def initialize(*parametros)
super
end
end # clase
class Articulo_revista < Referencia
# Getter + Setter
attr_accessor :num_issns
# Constructor
def initialize(*parametros, num_issns)
super(*parametros)
@num_issns = num_issns
end
end
class Articulo_periodico < Referencia
# Getter + Setter
attr_accessor :num_columnas
# Constructor
def initialize(*parametros, num_columnas)
super(*parametros)
@num_columnas = num_columnas
end
end
class Documento_electronico < Referencia
# Getter + Setter
attr_accessor :url
# Constructor
def initialize(*parametros, url)
super(*parametros)
@url = url
end
end
end
|
require 'alephant/renderer/views/html'
require 'alephant/renderer/views/json'
require 'alephant/renderer/view_mapper'
require 'alephant/support/parser'
require 'alephant/preview/template/base'
require 'sinatra/base'
require "sinatra/reloader"
require 'faraday'
require 'json'
require 'uri'
module Alephant
module Preview
class Server < Sinatra::Base
register Sinatra::Reloader
also_reload 'components/*/models/*.rb'
BASE_LOCATION = "#{(ENV['BASE_LOCATION'] || Dir.pwd)}/components"
get '/preview/:id/:template/:region/?:fixture?' do
render_preview
end
get '/component/:id/:template/?:fixture?' do
render_component
end
get '/component/:template/?:fixture?' do
params['id'] = find_id_from_template params['template']
params['fixture'] = 'responsive'
render_component
end
get '/status' do
'ok'
end
def find_id_from_template(template)
files = Dir.glob(BASE_LOCATION + '/**/models/*')
file = files.select! { |file| file.include? "/#{template}.rb" }.pop
result = /#{BASE_LOCATION}\/(\w+)/.match(file)
result[1]
end
def render_preview
Template::Base.new(
{ region => render_component },
preview_template_location
).render
end
def render_component
view_mapper.generate(fixture_data)[template].render
end
private
def model
require model_location
Alephant::Renderer::Views.get_registered_class(template).new(fixture_data)
end
def base_path
File.join(BASE_LOCATION, id)
end
def model_location
File.join(base_path, 'models', "#{template}.rb")
end
def template
params['template']
end
def region
params['region']
end
def id
params['id']
end
def fixture
params['fixture'] || id
end
def fixture_data
msg = Struct.new(:body)
.new(raw_fixture_data)
parser.parse msg
end
def raw_fixture_data
File.open(fixture_location).read
end
def parser
@parser ||= ::Alephant::Support::Parser.new
end
def fixture_location
"#{base_path}/fixtures/#{fixture}.json"
end
def preview_template_location
"#{Template.path}/templates/preview.mustache"
end
def view_mapper
Alephant::Renderer::ViewMapper.new(id, BASE_LOCATION)
end
end
end
end
Binds the previewer on all ports
require 'alephant/renderer/views/html'
require 'alephant/renderer/views/json'
require 'alephant/renderer/view_mapper'
require 'alephant/support/parser'
require 'alephant/preview/template/base'
require 'sinatra/base'
require "sinatra/reloader"
require 'faraday'
require 'json'
require 'uri'
module Alephant
module Preview
class Server < Sinatra::Base
set :bind, '0.0.0.0'
register Sinatra::Reloader
also_reload 'components/*/models/*.rb'
BASE_LOCATION = "#{(ENV['BASE_LOCATION'] || Dir.pwd)}/components"
get '/preview/:id/:template/:region/?:fixture?' do
render_preview
end
get '/component/:id/:template/?:fixture?' do
render_component
end
get '/component/:template/?:fixture?' do
params['id'] = find_id_from_template params['template']
params['fixture'] = 'responsive'
render_component
end
get '/status' do
'ok'
end
def find_id_from_template(template)
files = Dir.glob(BASE_LOCATION + '/**/models/*')
file = files.select! { |file| file.include? "/#{template}.rb" }.pop
result = /#{BASE_LOCATION}\/(\w+)/.match(file)
result[1]
end
def render_preview
Template::Base.new(
{ region => render_component },
preview_template_location
).render
end
def render_component
view_mapper.generate(fixture_data)[template].render
end
private
def model
require model_location
Alephant::Renderer::Views.get_registered_class(template).new(fixture_data)
end
def base_path
File.join(BASE_LOCATION, id)
end
def model_location
File.join(base_path, 'models', "#{template}.rb")
end
def template
params['template']
end
def region
params['region']
end
def id
params['id']
end
def fixture
params['fixture'] || id
end
def fixture_data
msg = Struct.new(:body)
.new(raw_fixture_data)
parser.parse msg
end
def raw_fixture_data
File.open(fixture_location).read
end
def parser
@parser ||= ::Alephant::Support::Parser.new
end
def fixture_location
"#{base_path}/fixtures/#{fixture}.json"
end
def preview_template_location
"#{Template.path}/templates/preview.mustache"
end
def view_mapper
Alephant::Renderer::ViewMapper.new(id, BASE_LOCATION)
end
end
end
end
|
module Battlenet
module WOW
class Spell < Battlenet::APIResponse
def initialize(options={})
@realm = options.delete(:spell)
@endpoint = "/item/#{@spell}"
super(options)
end
def details
get_data(@endpoint, {})
end
end
end
end
Update spell.rb
module Battlenet
module WOW
class Spell < Battlenet::APIResponse
def initialize(options={})
@spell = options.delete(:spell)
@endpoint = "/spell/#{@spell}"
super(options)
end
def details
get_data(@endpoint, {})
end
end
end
end
|
Pod::Spec.new do |s|
s.name = "JRMPush"
s.version = "0.1.0"
s.summary = "Show a web page when a push is received with a URL in its metadata."
s.homepage = "https://github.com/davidolesch/JRMPush"
s.screenshots = "https://raw.githubusercontent.com/davidolesch/JRMPush/master/ClassAnnouncement.gif"
s.license = 'MIT'
s.author = { "David Olesch" => "david@jackrabbitmobile.com" }
s.source = { :git => "https://github.com/davidolesch/JRMPush.git", :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/davidolesch'
s.platform = :ios, '6.0'
s.requires_arc = true
s.source_files = 'Pod/Classes/*.{h,m}'
s.public_header_files = 'Pod/Classes/*.h'
s.dependency 'SVWebViewController', '~> 1.0'
end
bumped version number in the podspec
Pod::Spec.new do |s|
s.name = "JRMPush"
s.version = "0.1.1"
s.summary = "Show a web page when a push is received with a URL in its metadata."
s.homepage = "https://github.com/davidolesch/JRMPush"
s.screenshots = "https://raw.githubusercontent.com/davidolesch/JRMPush/master/ClassAnnouncement.gif"
s.license = 'MIT'
s.author = { "David Olesch" => "david@jackrabbitmobile.com" }
s.source = { :git => "https://github.com/davidolesch/JRMPush.git", :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/davidolesch'
s.platform = :ios, '6.0'
s.requires_arc = true
s.source_files = 'Pod/Classes/*.{h,m}'
s.public_header_files = 'Pod/Classes/*.h'
s.dependency 'SVWebViewController', '~> 1.0'
end
|
module AlexaGenerator
VERSION = '0.1.0'
end
update version
module AlexaGenerator
VERSION = '0.1.1'
end
|
class Jeweler
class Generator
class Options < Hash
attr_reader :opts, :orig_args
def initialize(args)
super()
@orig_args = args.clone
self[:testing_framework] = :shoulda
self[:documentation_framework] = :rdoc
self[:use_bundler] = true
git_config = if Pathname.new("~/.gitconfig").expand_path.exist?
Git.global_config
else
{}
end
self[:user_name] = ENV['GIT_AUTHOR_NAME'] || ENV['GIT_COMMITTER_NAME'] || git_config['user.name']
self[:user_email] = ENV['GIT_AUTHOR_EMAIL'] || ENV['GIT_COMMITTER_EMAIL'] || git_config['user.email']
self[:github_username] = git_config['github.user']
self[:github_token] = git_config['github.token']
require 'optparse'
@opts = OptionParser.new do |o|
o.banner = "Usage: #{File.basename($0)} [options] reponame\ne.g. #{File.basename($0)} the-perfect-gem"
o.on('--directory [DIRECTORY]', 'specify the directory to generate into') do |directory|
self[:directory] = directory
end
o.separator "These options are for BioGem"
#TODO: Scrivere le altre opzioni
o.on("--with-bin", 'create the bin directory for your eecutable scripts') do
self[:biogem_bin] = true
end
o.on("--with-db", 'create the database directory for a db application-library') do
self[:biogem_db] = true
end
o.on("--with-test-data",'create the data directory inside the test directory if the user need to set up a test with its own dataset') do
self[:biogem_test_data] = true
end
o.separator "These options are for Jeweler"
o.on('--rspec', 'generate rspec code examples') do
self[:testing_framework] = :rspec
end
o.on('--shoulda', 'generate shoulda tests') do
self[:testing_framework] = :shoulda
end
o.on('--testunit', 'generate test/unit tests') do
self[:testing_framework] = :testunit
end
o.on('--bacon', 'generate bacon specifications') do
self[:testing_framework] = :bacon
end
o.on('--testspec', 'generate test/spec tests') do
self[:testing_framework] = :testspec
end
o.on('--minitest', 'generate minitest tests') do
self[:testing_framework] = :minitest
end
o.on('--micronaut', 'generate micronaut examples') do
self[:testing_framework] = :micronaut
end
o.on('--riot', 'generate riot tests') do
self[:testing_framework] = :riot
end
o.on('--shindo', 'generate shindo tests') do
self[:testing_framework] = :shindo
end
o.separator ""
o.on('--[no-]bundler', 'use bundler for managing dependencies') do |v|
self[:use_bundler] = v
end
o.on('--cucumber', 'generate cucumber stories in addition to the other tests') do
self[:use_cucumber] = true
end
o.separator ""
o.on('--reek', 'generate rake task for reek') do
self[:use_reek] = true
end
o.on('--roodi', 'generate rake task for roodi') do
self[:use_roodi] = true
end
o.separator ""
o.on('--summary [SUMMARY]', 'specify the summary of the project') do |summary|
self[:summary] = summary
end
o.on('--description [DESCRIPTION]', 'specify a description of the project') do |description|
self[:description] = description
end
o.separator ""
o.on('--user-name [USER_NAME]', "the user's name, ie that is credited in the LICENSE") do |user_name|
self[:user_name] = user_name
end
o.on('--user-email [USER_EMAIL]', "the user's email, ie that is credited in the Gem specification") do |user_email|
self[:user_email] = user_email
end
o.separator ""
o.on('--github-username [GITHUB_USERNAME]', "name of the user on GitHub to set the project up under") do |github_username|
self[:github_username] = github_username
end
o.on('--github-token [GITHUB_TOKEN]', "GitHub token to use for interacting with the GitHub API") do |github_token|
self[:github_token] = github_token
end
o.on('--git-remote [GIT_REMOTE]', 'URI to set the git origin remote to') do |git_remote|
self[:git_remote] = git_remote
end
o.on('--homepage [HOMEPAGE]', "the homepage for your project (defaults to the GitHub repo)") do |homepage|
self[:homepage] = homepage
end
o.on('--create-repo', 'create the repository on GitHub') do
self[:create_repo] = true
end
o.separator ""
o.on('--yard', 'use yard for documentation') do
self[:documentation_framework] = :yard
end
o.on('--rdoc', 'use rdoc for documentation') do
self[:documentation_framework] = :rdoc
end
o.on_tail('-h', '--help', 'display this help and exit') do
self[:show_help] = true
end
end
begin
@opts.parse!(args)
self[:project_name] = args.shift
rescue OptionParser::InvalidOption => e
self[:invalid_argument] = e.message
end
end
def merge(other)
self.class.new(@orig_args + other.orig_args)
end
end #Options
end #Generator
end #Jeweler
fix bin option description
class Jeweler
class Generator
class Options < Hash
attr_reader :opts, :orig_args
def initialize(args)
super()
@orig_args = args.clone
self[:testing_framework] = :shoulda
self[:documentation_framework] = :rdoc
self[:use_bundler] = true
git_config = if Pathname.new("~/.gitconfig").expand_path.exist?
Git.global_config
else
{}
end
self[:user_name] = ENV['GIT_AUTHOR_NAME'] || ENV['GIT_COMMITTER_NAME'] || git_config['user.name']
self[:user_email] = ENV['GIT_AUTHOR_EMAIL'] || ENV['GIT_COMMITTER_EMAIL'] || git_config['user.email']
self[:github_username] = git_config['github.user']
self[:github_token] = git_config['github.token']
require 'optparse'
@opts = OptionParser.new do |o|
o.banner = "Usage: #{File.basename($0)} [options] reponame\ne.g. #{File.basename($0)} the-perfect-gem"
o.on('--directory [DIRECTORY]', 'specify the directory to generate into') do |directory|
self[:directory] = directory
end
o.separator "These options are for BioGem"
#TODO: Scrivere le altre opzioni
o.on("--with-bin", 'create the bin directory and an executable template script called bioreponame') do
self[:biogem_bin] = true
end
o.on("--with-db", 'create the database directory for a db application-library') do
self[:biogem_db] = true
end
o.on("--with-test-data",'create the data directory inside the test directory if the user need to set up a test with its own dataset') do
self[:biogem_test_data] = true
end
o.separator "These options are for Jeweler"
o.on('--rspec', 'generate rspec code examples') do
self[:testing_framework] = :rspec
end
o.on('--shoulda', 'generate shoulda tests') do
self[:testing_framework] = :shoulda
end
o.on('--testunit', 'generate test/unit tests') do
self[:testing_framework] = :testunit
end
o.on('--bacon', 'generate bacon specifications') do
self[:testing_framework] = :bacon
end
o.on('--testspec', 'generate test/spec tests') do
self[:testing_framework] = :testspec
end
o.on('--minitest', 'generate minitest tests') do
self[:testing_framework] = :minitest
end
o.on('--micronaut', 'generate micronaut examples') do
self[:testing_framework] = :micronaut
end
o.on('--riot', 'generate riot tests') do
self[:testing_framework] = :riot
end
o.on('--shindo', 'generate shindo tests') do
self[:testing_framework] = :shindo
end
o.separator ""
o.on('--[no-]bundler', 'use bundler for managing dependencies') do |v|
self[:use_bundler] = v
end
o.on('--cucumber', 'generate cucumber stories in addition to the other tests') do
self[:use_cucumber] = true
end
o.separator ""
o.on('--reek', 'generate rake task for reek') do
self[:use_reek] = true
end
o.on('--roodi', 'generate rake task for roodi') do
self[:use_roodi] = true
end
o.separator ""
o.on('--summary [SUMMARY]', 'specify the summary of the project') do |summary|
self[:summary] = summary
end
o.on('--description [DESCRIPTION]', 'specify a description of the project') do |description|
self[:description] = description
end
o.separator ""
o.on('--user-name [USER_NAME]', "the user's name, ie that is credited in the LICENSE") do |user_name|
self[:user_name] = user_name
end
o.on('--user-email [USER_EMAIL]', "the user's email, ie that is credited in the Gem specification") do |user_email|
self[:user_email] = user_email
end
o.separator ""
o.on('--github-username [GITHUB_USERNAME]', "name of the user on GitHub to set the project up under") do |github_username|
self[:github_username] = github_username
end
o.on('--github-token [GITHUB_TOKEN]', "GitHub token to use for interacting with the GitHub API") do |github_token|
self[:github_token] = github_token
end
o.on('--git-remote [GIT_REMOTE]', 'URI to set the git origin remote to') do |git_remote|
self[:git_remote] = git_remote
end
o.on('--homepage [HOMEPAGE]', "the homepage for your project (defaults to the GitHub repo)") do |homepage|
self[:homepage] = homepage
end
o.on('--create-repo', 'create the repository on GitHub') do
self[:create_repo] = true
end
o.separator ""
o.on('--yard', 'use yard for documentation') do
self[:documentation_framework] = :yard
end
o.on('--rdoc', 'use rdoc for documentation') do
self[:documentation_framework] = :rdoc
end
o.on_tail('-h', '--help', 'display this help and exit') do
self[:show_help] = true
end
end
begin
@opts.parse!(args)
self[:project_name] = args.shift
rescue OptionParser::InvalidOption => e
self[:invalid_argument] = e.message
end
end
def merge(other)
self.class.new(@orig_args + other.orig_args)
end
end #Options
end #Generator
end #Jeweler |
class BladeRunner::TestResults
include BladeRunner::Knife
attr_reader :browser, :status, :results, :passes, :failures
def initialize(browser)
@browser = browser
reset
subscribe("/tests") do |details|
if details["browser"] == browser.name
process_test_result(details)
end
end
end
def reset
@results, @passes, @failures = [], [], []
@status = "pending"
@total = nil
end
def process_test_result(details)
case details["event"]
when "begin"
reset
@status = "running"
@total = details["total"]
publish("/results", event: "running", browser: browser.name)
when "result"
klass = details["result"] ? Pass : Failure
record_result(klass.new("#{browser.name} - #{details["name"]}", details["message"]))
when "end"
publish("/results", event: "finished", browser: browser.name)
if @failures.any?
@status = "failed"
else
@status = "finished"
end
end
end
def record_result(result)
@results << result
case result
when Failure
@failures << result
publish("/results", result: false, browser: browser.name)
when Pass
@passes << result
publish("/results", result: true, browser: browser.name)
end
end
def total
if @total
@total
elsif status == "finished"
results.size
end
end
def to_tap
lines = results.map(&:to_tap)
lines = lines.unshift("1..#{total}}") if total
lines.join("\n")
end
class Pass
def initialize(name, message)
@name = name
@message = message
end
def to_tap(number = nil)
["ok", number, @name, message].compact.join(" ")
end
def message
unless @message.nil?
"\n" + @message.gsub(/^/, "# ").chomp
end
end
end
class Failure < Pass
def to_tap(*args)
"not #{super}"
end
end
class Combiner
attr_reader :all_test_results
def initialize(all_test_results)
@all_test_results = all_test_results
end
def total
totals = all_test_results.map(&:total)
if totals.all?
totals.inject(0) { |sum, total| sum + total }
end
end
def sorted_results
passes, failures = [], []
all_test_results.each do |test_results|
passes.push(*test_results.passes)
failures.push(*test_results.failures)
end
passes + failures
end
def to_tap
lines = []
sorted_results.each_with_index do |result, index|
lines << result.to_tap(index + 1)
end
lines = lines.unshift("1..#{total}") if total
lines.join("\n")
end
end
end
Remove stray bracket
class BladeRunner::TestResults
include BladeRunner::Knife
attr_reader :browser, :status, :results, :passes, :failures
def initialize(browser)
@browser = browser
reset
subscribe("/tests") do |details|
if details["browser"] == browser.name
process_test_result(details)
end
end
end
def reset
@results, @passes, @failures = [], [], []
@status = "pending"
@total = nil
end
def process_test_result(details)
case details["event"]
when "begin"
reset
@status = "running"
@total = details["total"]
publish("/results", event: "running", browser: browser.name)
when "result"
klass = details["result"] ? Pass : Failure
record_result(klass.new("#{browser.name} - #{details["name"]}", details["message"]))
when "end"
publish("/results", event: "finished", browser: browser.name)
if @failures.any?
@status = "failed"
else
@status = "finished"
end
end
end
def record_result(result)
@results << result
case result
when Failure
@failures << result
publish("/results", result: false, browser: browser.name)
when Pass
@passes << result
publish("/results", result: true, browser: browser.name)
end
end
def total
if @total
@total
elsif status == "finished"
results.size
end
end
def to_tap
lines = results.map(&:to_tap)
lines = lines.unshift("1..#{total}") if total
lines.join("\n")
end
class Pass
def initialize(name, message)
@name = name
@message = message
end
def to_tap(number = nil)
["ok", number, @name, message].compact.join(" ")
end
def message
unless @message.nil?
"\n" + @message.gsub(/^/, "# ").chomp
end
end
end
class Failure < Pass
def to_tap(*args)
"not #{super}"
end
end
class Combiner
attr_reader :all_test_results
def initialize(all_test_results)
@all_test_results = all_test_results
end
def total
totals = all_test_results.map(&:total)
if totals.all?
totals.inject(0) { |sum, total| sum + total }
end
end
def sorted_results
passes, failures = [], []
all_test_results.each do |test_results|
passes.push(*test_results.passes)
failures.push(*test_results.failures)
end
passes + failures
end
def to_tap
lines = []
sorted_results.each_with_index do |result, index|
lines << result.to_tap(index + 1)
end
lines = lines.unshift("1..#{total}") if total
lines.join("\n")
end
end
end
|
##############################################################################
# File:: generate.rb
# Purpose:: Generate command
#
# Author:: Jeff McAffee 06/21/2014
# Copyright:: Copyright (c) 2014, kTech Systems LLC. All rights reserved.
# Website:: http://ktechsystems.com
##############################################################################
require 'thor'
require 'ams_layout/client'
module AmsLayout
class Generate < Thor
desc "layout [PATH]", "write layout data to a file"
long_desc <<-LD
Generate layout data file.
File will be named layout.yml and placed in the directory (PATH)
you specify.
Directory must already exist or an error will be thrown.
LD
option :env, :banner => "dev", :aliases => :e
def layout(path)
env = AmsLayout.configuration.default_environment
env = options[:env] if options[:env]
user, pass = credentials env
client.login(user, pass)
client.write_layout path, false
client.logout
end
desc "cls <opts> [PATH] [LAYOUT_PATH]", "write layout class to a file"
long_desc <<-LD
Generate layout class.
Options:
-n ClassName specify name of layout class (default: LoanEntryFields)
Arguments:
[PATH] Path to directory where layout class will be created.
[LAYOUT_PATH] Path to directory containing layout data (layout.yml)
Directories must already exist or an error will be thrown.
LD
option :name, :banner => "ClassName", :aliases => :n
def cls(path, layout_path)
if options[:name]
client.layout_class_name = options[:name]
end
client.write_layout_class path, layout_path
end
desc "delegate <opts> [PATH] [LAYOUT_PATH]", "write delegate class to a file"
long_desc <<-LD
Generate delegate class.
Options:
-d ClassName specify name of delegate class (default: DelegateLoanEntryFields)
Arguments:
[PATH] Path to directory where delegate class will be created.
[LAYOUT_PATH] Path to directory containing layout data (layout.yml)
Directories must already exist or an error will be thrown.
LD
option :delegate, :banner => "DelegateClassName", :aliases => :d
def delegate(path, layout_path)
if options[:delegate]
client.delegate_class_name = options[:delegate]
end
client.write_delegate_class path, layout_path
end
desc "all <opts> [PATH]", "write layout data, layout class, and delegate class files to a path"
long_desc <<-LD
Generate layout data file (layout.yml), layout class, and delegate layout class.
Options:
-n ClassName specify name of layout class (default: LoanEntryFields)
-d ClassName specify name of delegate class (default: DelegateLoanEntryFields)
Arguments:
[PATH] Path to directory where files will be created.
Directory must already exist or an error will be thrown.
LD
option :name, :banner => "ClassName", :aliases => :n
option :delegate, :banner => "DelegateClassName", :aliases => :d
def all(path)
# Generate layout file
client.login('user', 'pass')
client.write_layout path, false
client.logout
# Generate layout class
if options[:name]
client.layout_class_name = options[:name]
end
client.write_layout_class path, path
# Generate delegate class
if options[:delegate]
client.delegate_class_name = options[:delegate]
end
client.write_delegate_class path, path
end
private
def client
AmsLayout.client
end
def credentials env
user, pass = AmsLayout.configuration.credentials[env]
if user.nil? || pass.nil?
user = ask "username for #{env} environment:"
pass = ask "password:"
end
[user, pass]
end
end
end # AmsLayout
Add credentials request to "all" command
##############################################################################
# File:: generate.rb
# Purpose:: Generate command
#
# Author:: Jeff McAffee 06/21/2014
# Copyright:: Copyright (c) 2014, kTech Systems LLC. All rights reserved.
# Website:: http://ktechsystems.com
##############################################################################
require 'thor'
require 'ams_layout/client'
module AmsLayout
class Generate < Thor
desc "layout [PATH]", "write layout data to a file"
long_desc <<-LD
Generate layout data file.
File will be named layout.yml and placed in the directory (PATH)
you specify.
Directory must already exist or an error will be thrown.
LD
option :env, :banner => "dev", :aliases => :e
def layout(path)
env = AmsLayout.configuration.default_environment
env = options[:env] if options[:env]
user, pass = credentials env
client.login(user, pass)
client.write_layout path, false
client.logout
end
desc "cls <opts> [PATH] [LAYOUT_PATH]", "write layout class to a file"
long_desc <<-LD
Generate layout class.
Options:
-n ClassName specify name of layout class (default: LoanEntryFields)
Arguments:
[PATH] Path to directory where layout class will be created.
[LAYOUT_PATH] Path to directory containing layout data (layout.yml)
Directories must already exist or an error will be thrown.
LD
option :name, :banner => "ClassName", :aliases => :n
def cls(path, layout_path)
if options[:name]
client.layout_class_name = options[:name]
end
client.write_layout_class path, layout_path
end
desc "delegate <opts> [PATH] [LAYOUT_PATH]", "write delegate class to a file"
long_desc <<-LD
Generate delegate class.
Options:
-d ClassName specify name of delegate class (default: DelegateLoanEntryFields)
Arguments:
[PATH] Path to directory where delegate class will be created.
[LAYOUT_PATH] Path to directory containing layout data (layout.yml)
Directories must already exist or an error will be thrown.
LD
option :delegate, :banner => "DelegateClassName", :aliases => :d
def delegate(path, layout_path)
if options[:delegate]
client.delegate_class_name = options[:delegate]
end
client.write_delegate_class path, layout_path
end
desc "all <opts> [PATH]", "write layout data, layout class, and delegate class files to a path"
long_desc <<-LD
Generate layout data file (layout.yml), layout class, and delegate layout class.
Options:
-n ClassName specify name of layout class (default: LoanEntryFields)
-d ClassName specify name of delegate class (default: DelegateLoanEntryFields)
Arguments:
[PATH] Path to directory where files will be created.
Directory must already exist or an error will be thrown.
LD
option :name, :banner => "ClassName", :aliases => :n
option :delegate, :banner => "DelegateClassName", :aliases => :d
option :env, :banner => "dev", :aliases => :e
def all(path)
env = AmsLayout.configuration.default_environment
env = options[:env] if options[:env]
user, pass = credentials env
# Generate layout file
client.login(user, pass)
client.write_layout path, false
client.logout
# Generate layout class
if options[:name]
client.layout_class_name = options[:name]
end
client.write_layout_class path, path
# Generate delegate class
if options[:delegate]
client.delegate_class_name = options[:delegate]
end
client.write_delegate_class path, path
end
private
def client
AmsLayout.client
end
def credentials env
user, pass = AmsLayout.configuration.credentials[env]
if user.nil? || pass.nil?
user = ask "username for #{env} environment:"
pass = ask "password:"
end
[user, pass]
end
end
end # AmsLayout
|
require_relative 'helpers/bootstrap'
module BootstrapForm
class FormBuilder < ActionView::Helpers::FormBuilder
include BootstrapForm::Helpers::Bootstrap
attr_reader :layout, :label_col, :control_col, :has_error, :inline_errors, :label_errors, :acts_like_form_tag
FIELD_HELPERS = %w{color_field date_field datetime_field datetime_local_field
email_field month_field number_field password_field phone_field
range_field search_field telephone_field text_area text_field time_field
url_field week_field}
DATE_SELECT_HELPERS = %w{date_select time_select datetime_select}
delegate :content_tag, :capture, :concat, to: :@template
def initialize(object_name, object, template, options)
@layout = options[:layout]
@label_col = options[:label_col] || default_label_col
@control_col = options[:control_col] || default_control_col
@label_errors = options[:label_errors] || false
@inline_errors = if options[:inline_errors].nil?
@label_errors != true
else
options[:inline_errors] != false
end
@acts_like_form_tag = options[:acts_like_form_tag]
@size = options[:size] || false
super
end
FIELD_HELPERS.each do |method_name|
# with_method_name = "#{method_name}_with_bootstrap"
# without_method_name = "#{method_name}_without_bootstrap"
#
# define_method(with_method_name) do |name, options = {}|
define_method(method_name) do |name, options = {}|
form_group_builder(name, options) do
prepend_and_append_input(options) do
send(without_method_name, name, options)
#super(name, options)
end
end
end
alias_method_chain method_name, :bootstrap
end
DATE_SELECT_HELPERS.each do |method_name|
# with_method_name = "#{method_name}_with_bootstrap"
# without_method_name = "#{method_name}_without_bootstrap"
#
define_method(with_method_name) do |name, options = {}, html_options = {}|
# define_method(method_name) do |name, options = {}, html_options = {}|
form_group_builder(name, options, html_options) do
content_tag(:div, send(without_method_name, name, options, html_options), class: control_specific_class(method_name))
#content_tag(:div, super(name, options, html_options), class: control_specific_class(method_name))
end
end
alias_method_chain method_name, :bootstrap
end
def file_field_with_bootstrap(name, options = {})
#def file_field(name, options = {})
form_group_builder(name, options.reverse_merge(control_class: nil)) do
file_field_without_bootstrap(name, options)
#super(name, options)
end
end
alias_method_chain :file_field, :bootstrap
def select_with_bootstrap(method, choices, options = {}, html_options = {})
#def select(method, choices, options = {}, html_options = {})
form_group_builder(method, options, html_options) do
select_without_bootstrap(method, choices, options, html_options)
#super(method, choices, options, html_options)
end
end
alias_method_chain :select, :bootstrap
def collection_select_with_bootstrap(method, collection, value_method, text_method, options = {}, html_options = {})
# def collection_select(method, collection, value_method, text_method, options = {}, html_options = {})
form_group_builder(method, options, html_options) do
collection_select_without_bootstrap(method, collection, value_method, text_method, options, html_options)
#super(method, collection, value_method, text_method, options, html_options)
end
end
alias_method_chain :collection_select, :bootstrap
def grouped_collection_select_with_bootstrap(method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})
#def grouped_collection_select(method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})
form_group_builder(method, options, html_options) do
grouped_collection_select_without_bootstrap(method, collection, group_method, group_label_method, option_key_method, option_value_method, options, html_options)
#super(method, collection, group_method, group_label_method, option_key_method, option_value_method, options, html_options)
end
end
alias_method_chain :grouped_collection_select, :bootstrap
def time_zone_select_with_bootstrap(method, priority_zones = nil, options = {}, html_options = {})
#def time_zone_select(method, priority_zones = nil, options = {}, html_options = {})
form_group_builder(method, options, html_options) do
time_zone_select_without_bootstrap(method, priority_zones, options, html_options)
#super(method, priority_zones, options, html_options)
end
end
alias_method_chain :time_zone_select, :bootstrap
def check_box_with_bootstrap(name, options = {}, checked_value = "1", unchecked_value = "0", &block)
#def check_box(name, options = {}, checked_value = "1", unchecked_value = "0", &block)
options = options.symbolize_keys!
check_box_options = options.except(:label, :label_class, :help, :inline)
html = check_box_without_bootstrap(name, check_box_options, checked_value, unchecked_value)
#html = super(name, check_box_options, checked_value, unchecked_value)
label_content = block_given? ? capture(&block) : options[:label]
html.concat(" ").concat(label_content || (object && object.class.human_attribute_name(name)) || name.to_s.humanize)
label_name = name
label_name = "#{name}_#{checked_value}" if options[:multiple]
disabled_class = " disabled" if options[:disabled]
label_class = options[:label_class]
if options[:inline]
label_class = " #{label_class}" if label_class
label(label_name, html, class: "checkbox-inline#{disabled_class}#{label_class}")
else
content_tag(:div, class: "checkbox#{disabled_class}") do
label(label_name, html, class: label_class)
end
end
end
alias_method_chain :check_box, :bootstrap
def radio_button_with_bootstrap(name, value, *args)
# def radio_button(name, value, *args)
options = args.extract_options!.symbolize_keys!
args << options.except(:label, :label_class, :help, :inline)
html = radio_button_without_bootstrap(name, value, *args) + " " + options[:label]
# html = super(name, value, *args) + " " + options[:label]
disabled_class = " disabled" if options[:disabled]
label_class = options[:label_class]
if options[:inline]
label_class = " #{label_class}" if label_class
label(name, html, class: "radio-inline#{disabled_class}#{label_class}", value: value)
else
content_tag(:div, class: "radio#{disabled_class}") do
label(name, html, value: value, class: label_class)
end
end
end
alias_method_chain :radio_button, :bootstrap
def collection_check_boxes_with_bootstrap(*args)
#def collection_check_boxes(*args)
html = inputs_collection(*args) do |name, value, options|
options[:multiple] = true
check_box(name, options, value, nil)
end
hidden_field(args.first,{value: "", multiple: true}).concat(html)
end
alias_method_chain :collection_check_boxes, :bootstrap
def collection_radio_buttons_with_bootstrap(*args)
#def collection_radio_buttons(*args)
inputs_collection(*args) do |name, value, options|
radio_button(name, value, options)
end
end
alias_method_chain :collection_radio_buttons, :bootstrap
def check_boxes_collection(*args)
warn "'BootstrapForm#check_boxes_collection' is deprecated, use 'BootstrapForm#collection_check_boxes' instead"
collection_check_boxes(*args)
end
def radio_buttons_collection(*args)
warn "'BootstrapForm#radio_buttons_collection' is deprecated, use 'BootstrapForm#collection_radio_buttons' instead"
collection_radio_buttons(*args)
end
def form_group(*args, &block)
options = args.extract_options!
name = args.first
size = 'form-group'
if @size
case @size
when :sm
size = 'form-group-sm'
when :lg
size = 'form-group-lg'
end
end
options[:class] = [size, options[:class]].compact.join(' ')
options[:class] << " #{error_class}" if has_error?(name)
options[:class] << " #{feedback_class}" if options[:icon]
content_tag(:div, options.except(:id, :label, :help, :icon, :label_col, :control_col, :layout)) do
label = generate_label(options[:id], name, options[:label], options[:label_col], options[:layout]) if options[:label]
control = capture(&block).to_s
control.concat(generate_help(name, options[:help]).to_s)
control.concat(generate_icon(options[:icon])) if options[:icon]
if get_group_layout(options[:layout]) == :horizontal
control_class = (options[:control_col] || control_col.clone)
unless options[:label]
control_offset = offset_col(/([0-9]+)$/.match(options[:label_col] || @label_col))
control_class.concat(" #{control_offset}")
end
control = content_tag(:div, control, class: control_class)
end
concat(label).concat(control)
end
end
def fields_for_with_bootstrap(record_name, record_object = nil, fields_options = {}, &block)
#def fields_for(record_name, record_object = nil, fields_options = {}, &block)
fields_options, record_object = record_object, nil if record_object.is_a?(Hash) && record_object.extractable_options?
fields_options[:layout] ||= options[:layout]
fields_options[:label_col] = fields_options[:label_col].present? ? "#{fields_options[:label_col]} #{label_class}" : options[:label_col]
fields_options[:control_col] ||= options[:control_col]
fields_options[:inline_errors] ||= options[:inline_errors]
fields_options[:label_errors] ||= options[:label_errors]
fields_for_without_bootstrap(record_name, record_object, fields_options, &block)
# super(record_name, record_object, fields_options, &block)
end
alias_method_chain :fields_for, :bootstrap
private
def horizontal?
layout == :horizontal
end
def get_group_layout(group_layout)
group_layout || layout
end
def default_label_col
"col-sm-2"
end
def offset_col(offset)
"col-sm-offset-#{offset}"
end
def default_control_col
"col-sm-10"
end
def hide_class
"sr-only" # still accessible for screen readers
end
def control_class
"form-control"
end
def label_class
"control-label"
end
def error_class
"has-error"
end
def feedback_class
"has-feedback"
end
def control_specific_class(method)
"rails-bootstrap-forms-#{method.gsub(/_/, "-")}"
end
def has_error?(name)
object.respond_to?(:errors) && !(name.nil? || object.errors[name].empty?)
end
def required_attribute?(obj, attribute)
return false unless obj and attribute
target = (obj.class == Class) ? obj : obj.class
# target_validators = if target.respond_to? :validators_on
# target.validators_on(attribute).map(&:class)
# else
# []
# end
target_validators = target.validators_on(attribute).map(&:class)
has_presence_validator = target_validators.include?(
ActiveModel::Validations::PresenceValidator)
if defined? ActiveRecord::Validations::PresenceValidator
has_presence_validator |= target_validators.include?(
ActiveRecord::Validations::PresenceValidator)
end
has_presence_validator
end
def form_group_builder(method, options, html_options = nil)
options.symbolize_keys!
html_options.symbolize_keys! if html_options
# Add control_class; allow it to be overridden by :control_class option
css_options = html_options || options
control_classes = css_options.delete(:control_class) { control_class }
css_options[:class] = [control_classes, css_options[:class]].compact.join(" ")
options = convert_form_tag_options(method, options) if acts_like_form_tag
wrapper_class = css_options.delete(:wrapper_class)
wrapper_options = css_options.delete(:wrapper)
help = options.delete(:help)
icon = options.delete(:icon)
label_col = options.delete(:label_col)
control_col = options.delete(:control_col)
layout = get_group_layout(options.delete(:layout))
form_group_options = {
id: options[:id],
help: help,
icon: icon,
label_col: label_col,
control_col: control_col,
layout: layout,
class: wrapper_class
}
if wrapper_options.is_a?(Hash)
form_group_options.merge!(wrapper_options)
end
unless options.delete(:skip_label)
label_class = hide_class if options.delete(:hide_label)
label_class ||= options.delete(:label_class)
form_group_options.reverse_merge!(label: {
text: options.delete(:label),
class: label_class
})
end
form_group(method, form_group_options) do
yield
end
end
def convert_form_tag_options(method, options = {})
options[:name] ||= method
options[:id] ||= method
options
end
def generate_label(id, name, options, custom_label_col, group_layout)
options[:for] = id if acts_like_form_tag
classes = [options[:class], label_class]
classes << (custom_label_col || label_col) if get_group_layout(group_layout) == :horizontal
classes << "required" if required_attribute?(object, name)
options[:class] = classes.compact.join(" ")
if label_errors && has_error?(name)
error_messages = get_error_messages(name)
label_text = (options[:text] || object.class.human_attribute_name(name)).to_s.concat(" #{error_messages}")
label(name, label_text, options.except(:text))
else
label(name, options[:text], options.except(:text))
end
end
def generate_help(name, help_text)
help_text = get_error_messages(name) if has_error?(name) && inline_errors
return if help_text === false
help_text ||= get_help_text_by_i18n_key(name)
content_tag(:span, help_text, class: 'help-block') if help_text.present?
end
def generate_icon(icon)
content_tag(:span, "", class: "glyphicon glyphicon-#{icon} form-control-feedback")
end
def get_error_messages(name)
object.errors[name].join(", ")
end
def inputs_collection(name, collection, value, text, options = {}, &block)
form_group_builder(name, options) do
inputs = ""
collection.each do |obj|
input_options = options.merge(label: text.respond_to?(:call) ? text.call(obj) : obj.send(text))
input_value = value.respond_to?(:call) ? value.call(obj) : obj.send(value)
if checked = input_options[:checked]
input_options[:checked] = checked == input_value ||
Array(checked).try(:include?, input_value) ||
checked == obj ||
Array(checked).try(:include?, obj)
end
input_options.delete(:class)
inputs << block.call(name, input_value, input_options)
end
inputs.html_safe
end
end
def get_help_text_by_i18n_key(name)
underscored_scope = "activerecord.help.#{object.class.name.underscore}"
downcased_scope = "activerecord.help.#{object.class.name.downcase}"
help_text = I18n.t(name, scope: underscored_scope, default: '').presence
help_text ||= if text = I18n.t(name, scope: downcased_scope, default: '').presence
warn "I18n key '#{downcased_scope}.#{name}' is deprecated, use '#{underscored_scope}.#{name}' instead"
text
end
help_text
end
end
end
made a mistake in reverting
require_relative 'helpers/bootstrap'
module BootstrapForm
class FormBuilder < ActionView::Helpers::FormBuilder
include BootstrapForm::Helpers::Bootstrap
attr_reader :layout, :label_col, :control_col, :has_error, :inline_errors, :label_errors, :acts_like_form_tag
FIELD_HELPERS = %w{color_field date_field datetime_field datetime_local_field
email_field month_field number_field password_field phone_field
range_field search_field telephone_field text_area text_field time_field
url_field week_field}
DATE_SELECT_HELPERS = %w{date_select time_select datetime_select}
delegate :content_tag, :capture, :concat, to: :@template
def initialize(object_name, object, template, options)
@layout = options[:layout]
@label_col = options[:label_col] || default_label_col
@control_col = options[:control_col] || default_control_col
@label_errors = options[:label_errors] || false
@inline_errors = if options[:inline_errors].nil?
@label_errors != true
else
options[:inline_errors] != false
end
@acts_like_form_tag = options[:acts_like_form_tag]
@size = options[:size] || false
super
end
FIELD_HELPERS.each do |method_name|
# with_method_name = "#{method_name}_with_bootstrap"
# without_method_name = "#{method_name}_without_bootstrap"
#
define_method(with_method_name) do |name, options = {}|
#define_method(method_name) do |name, options = {}|
form_group_builder(name, options) do
prepend_and_append_input(options) do
send(without_method_name, name, options)
#super(name, options)
end
end
end
alias_method_chain method_name, :bootstrap
end
DATE_SELECT_HELPERS.each do |method_name|
# with_method_name = "#{method_name}_with_bootstrap"
# without_method_name = "#{method_name}_without_bootstrap"
#
define_method(with_method_name) do |name, options = {}, html_options = {}|
# define_method(method_name) do |name, options = {}, html_options = {}|
form_group_builder(name, options, html_options) do
content_tag(:div, send(without_method_name, name, options, html_options), class: control_specific_class(method_name))
#content_tag(:div, super(name, options, html_options), class: control_specific_class(method_name))
end
end
alias_method_chain method_name, :bootstrap
end
def file_field_with_bootstrap(name, options = {})
#def file_field(name, options = {})
form_group_builder(name, options.reverse_merge(control_class: nil)) do
file_field_without_bootstrap(name, options)
#super(name, options)
end
end
alias_method_chain :file_field, :bootstrap
def select_with_bootstrap(method, choices, options = {}, html_options = {})
#def select(method, choices, options = {}, html_options = {})
form_group_builder(method, options, html_options) do
select_without_bootstrap(method, choices, options, html_options)
#super(method, choices, options, html_options)
end
end
alias_method_chain :select, :bootstrap
def collection_select_with_bootstrap(method, collection, value_method, text_method, options = {}, html_options = {})
# def collection_select(method, collection, value_method, text_method, options = {}, html_options = {})
form_group_builder(method, options, html_options) do
collection_select_without_bootstrap(method, collection, value_method, text_method, options, html_options)
#super(method, collection, value_method, text_method, options, html_options)
end
end
alias_method_chain :collection_select, :bootstrap
def grouped_collection_select_with_bootstrap(method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})
#def grouped_collection_select(method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})
form_group_builder(method, options, html_options) do
grouped_collection_select_without_bootstrap(method, collection, group_method, group_label_method, option_key_method, option_value_method, options, html_options)
#super(method, collection, group_method, group_label_method, option_key_method, option_value_method, options, html_options)
end
end
alias_method_chain :grouped_collection_select, :bootstrap
def time_zone_select_with_bootstrap(method, priority_zones = nil, options = {}, html_options = {})
#def time_zone_select(method, priority_zones = nil, options = {}, html_options = {})
form_group_builder(method, options, html_options) do
time_zone_select_without_bootstrap(method, priority_zones, options, html_options)
#super(method, priority_zones, options, html_options)
end
end
alias_method_chain :time_zone_select, :bootstrap
def check_box_with_bootstrap(name, options = {}, checked_value = "1", unchecked_value = "0", &block)
#def check_box(name, options = {}, checked_value = "1", unchecked_value = "0", &block)
options = options.symbolize_keys!
check_box_options = options.except(:label, :label_class, :help, :inline)
html = check_box_without_bootstrap(name, check_box_options, checked_value, unchecked_value)
#html = super(name, check_box_options, checked_value, unchecked_value)
label_content = block_given? ? capture(&block) : options[:label]
html.concat(" ").concat(label_content || (object && object.class.human_attribute_name(name)) || name.to_s.humanize)
label_name = name
label_name = "#{name}_#{checked_value}" if options[:multiple]
disabled_class = " disabled" if options[:disabled]
label_class = options[:label_class]
if options[:inline]
label_class = " #{label_class}" if label_class
label(label_name, html, class: "checkbox-inline#{disabled_class}#{label_class}")
else
content_tag(:div, class: "checkbox#{disabled_class}") do
label(label_name, html, class: label_class)
end
end
end
alias_method_chain :check_box, :bootstrap
def radio_button_with_bootstrap(name, value, *args)
# def radio_button(name, value, *args)
options = args.extract_options!.symbolize_keys!
args << options.except(:label, :label_class, :help, :inline)
html = radio_button_without_bootstrap(name, value, *args) + " " + options[:label]
# html = super(name, value, *args) + " " + options[:label]
disabled_class = " disabled" if options[:disabled]
label_class = options[:label_class]
if options[:inline]
label_class = " #{label_class}" if label_class
label(name, html, class: "radio-inline#{disabled_class}#{label_class}", value: value)
else
content_tag(:div, class: "radio#{disabled_class}") do
label(name, html, value: value, class: label_class)
end
end
end
alias_method_chain :radio_button, :bootstrap
def collection_check_boxes_with_bootstrap(*args)
#def collection_check_boxes(*args)
html = inputs_collection(*args) do |name, value, options|
options[:multiple] = true
check_box(name, options, value, nil)
end
hidden_field(args.first,{value: "", multiple: true}).concat(html)
end
alias_method_chain :collection_check_boxes, :bootstrap
def collection_radio_buttons_with_bootstrap(*args)
#def collection_radio_buttons(*args)
inputs_collection(*args) do |name, value, options|
radio_button(name, value, options)
end
end
alias_method_chain :collection_radio_buttons, :bootstrap
def check_boxes_collection(*args)
warn "'BootstrapForm#check_boxes_collection' is deprecated, use 'BootstrapForm#collection_check_boxes' instead"
collection_check_boxes(*args)
end
def radio_buttons_collection(*args)
warn "'BootstrapForm#radio_buttons_collection' is deprecated, use 'BootstrapForm#collection_radio_buttons' instead"
collection_radio_buttons(*args)
end
def form_group(*args, &block)
options = args.extract_options!
name = args.first
size = 'form-group'
if @size
case @size
when :sm
size = 'form-group-sm'
when :lg
size = 'form-group-lg'
end
end
options[:class] = [size, options[:class]].compact.join(' ')
options[:class] << " #{error_class}" if has_error?(name)
options[:class] << " #{feedback_class}" if options[:icon]
content_tag(:div, options.except(:id, :label, :help, :icon, :label_col, :control_col, :layout)) do
label = generate_label(options[:id], name, options[:label], options[:label_col], options[:layout]) if options[:label]
control = capture(&block).to_s
control.concat(generate_help(name, options[:help]).to_s)
control.concat(generate_icon(options[:icon])) if options[:icon]
if get_group_layout(options[:layout]) == :horizontal
control_class = (options[:control_col] || control_col.clone)
unless options[:label]
control_offset = offset_col(/([0-9]+)$/.match(options[:label_col] || @label_col))
control_class.concat(" #{control_offset}")
end
control = content_tag(:div, control, class: control_class)
end
concat(label).concat(control)
end
end
def fields_for_with_bootstrap(record_name, record_object = nil, fields_options = {}, &block)
#def fields_for(record_name, record_object = nil, fields_options = {}, &block)
fields_options, record_object = record_object, nil if record_object.is_a?(Hash) && record_object.extractable_options?
fields_options[:layout] ||= options[:layout]
fields_options[:label_col] = fields_options[:label_col].present? ? "#{fields_options[:label_col]} #{label_class}" : options[:label_col]
fields_options[:control_col] ||= options[:control_col]
fields_options[:inline_errors] ||= options[:inline_errors]
fields_options[:label_errors] ||= options[:label_errors]
fields_for_without_bootstrap(record_name, record_object, fields_options, &block)
# super(record_name, record_object, fields_options, &block)
end
alias_method_chain :fields_for, :bootstrap
private
def horizontal?
layout == :horizontal
end
def get_group_layout(group_layout)
group_layout || layout
end
def default_label_col
"col-sm-2"
end
def offset_col(offset)
"col-sm-offset-#{offset}"
end
def default_control_col
"col-sm-10"
end
def hide_class
"sr-only" # still accessible for screen readers
end
def control_class
"form-control"
end
def label_class
"control-label"
end
def error_class
"has-error"
end
def feedback_class
"has-feedback"
end
def control_specific_class(method)
"rails-bootstrap-forms-#{method.gsub(/_/, "-")}"
end
def has_error?(name)
object.respond_to?(:errors) && !(name.nil? || object.errors[name].empty?)
end
def required_attribute?(obj, attribute)
return false unless obj and attribute
target = (obj.class == Class) ? obj : obj.class
# target_validators = if target.respond_to? :validators_on
# target.validators_on(attribute).map(&:class)
# else
# []
# end
target_validators = target.validators_on(attribute).map(&:class)
has_presence_validator = target_validators.include?(
ActiveModel::Validations::PresenceValidator)
if defined? ActiveRecord::Validations::PresenceValidator
has_presence_validator |= target_validators.include?(
ActiveRecord::Validations::PresenceValidator)
end
has_presence_validator
end
def form_group_builder(method, options, html_options = nil)
options.symbolize_keys!
html_options.symbolize_keys! if html_options
# Add control_class; allow it to be overridden by :control_class option
css_options = html_options || options
control_classes = css_options.delete(:control_class) { control_class }
css_options[:class] = [control_classes, css_options[:class]].compact.join(" ")
options = convert_form_tag_options(method, options) if acts_like_form_tag
wrapper_class = css_options.delete(:wrapper_class)
wrapper_options = css_options.delete(:wrapper)
help = options.delete(:help)
icon = options.delete(:icon)
label_col = options.delete(:label_col)
control_col = options.delete(:control_col)
layout = get_group_layout(options.delete(:layout))
form_group_options = {
id: options[:id],
help: help,
icon: icon,
label_col: label_col,
control_col: control_col,
layout: layout,
class: wrapper_class
}
if wrapper_options.is_a?(Hash)
form_group_options.merge!(wrapper_options)
end
unless options.delete(:skip_label)
label_class = hide_class if options.delete(:hide_label)
label_class ||= options.delete(:label_class)
form_group_options.reverse_merge!(label: {
text: options.delete(:label),
class: label_class
})
end
form_group(method, form_group_options) do
yield
end
end
def convert_form_tag_options(method, options = {})
options[:name] ||= method
options[:id] ||= method
options
end
def generate_label(id, name, options, custom_label_col, group_layout)
options[:for] = id if acts_like_form_tag
classes = [options[:class], label_class]
classes << (custom_label_col || label_col) if get_group_layout(group_layout) == :horizontal
classes << "required" if required_attribute?(object, name)
options[:class] = classes.compact.join(" ")
if label_errors && has_error?(name)
error_messages = get_error_messages(name)
label_text = (options[:text] || object.class.human_attribute_name(name)).to_s.concat(" #{error_messages}")
label(name, label_text, options.except(:text))
else
label(name, options[:text], options.except(:text))
end
end
def generate_help(name, help_text)
help_text = get_error_messages(name) if has_error?(name) && inline_errors
return if help_text === false
help_text ||= get_help_text_by_i18n_key(name)
content_tag(:span, help_text, class: 'help-block') if help_text.present?
end
def generate_icon(icon)
content_tag(:span, "", class: "glyphicon glyphicon-#{icon} form-control-feedback")
end
def get_error_messages(name)
object.errors[name].join(", ")
end
def inputs_collection(name, collection, value, text, options = {}, &block)
form_group_builder(name, options) do
inputs = ""
collection.each do |obj|
input_options = options.merge(label: text.respond_to?(:call) ? text.call(obj) : obj.send(text))
input_value = value.respond_to?(:call) ? value.call(obj) : obj.send(value)
if checked = input_options[:checked]
input_options[:checked] = checked == input_value ||
Array(checked).try(:include?, input_value) ||
checked == obj ||
Array(checked).try(:include?, obj)
end
input_options.delete(:class)
inputs << block.call(name, input_value, input_options)
end
inputs.html_safe
end
end
def get_help_text_by_i18n_key(name)
underscored_scope = "activerecord.help.#{object.class.name.underscore}"
downcased_scope = "activerecord.help.#{object.class.name.downcase}"
help_text = I18n.t(name, scope: underscored_scope, default: '').presence
help_text ||= if text = I18n.t(name, scope: downcased_scope, default: '').presence
warn "I18n key '#{downcased_scope}.#{name}' is deprecated, use '#{underscored_scope}.#{name}' instead"
text
end
help_text
end
end
end
|
# -*- encoding: utf-8 -*-
#
# Sicredi
# Documentação: http://www.shapeness.net.br/upload//Sicredi_240.pdf
#
module Brcobranca
module Boleto
class Sicredi < Base # Banco SICREDI
# <b>REQUERIDO</b>: Código do posto da cooperativa de crédito
attr_accessor :posto
# <b>REQUERIDO</b>: Byte de identificação do cedente do bloqueto utilizado para compor o nosso número.
attr_accessor :byte_idt
validates_length_of :agencia, :maximum => 4, :message => 'deve ser menor ou igual a 4 dígitos.'
validates_length_of :numero_documento, :maximum => 5, :message => 'deve ser menor ou igual a 5 dígitos.'
validates_length_of :conta_corrente, :maximum => 5, :message => 'deve ser menor ou igual a 5 dígitos.'
validates_length_of :carteira, :maximum => 2, :message => 'deve ser menor ou igual a 2 dígitos.'
validates_length_of :byte_idt, :is => 1, :message => 'deve ser 1 se o numero foi gerado pela agencia ou 2-9 se foi gerado pelo cedente'
# Nova instancia do Bradesco
# @param (see Brcobranca::Boleto::Base#initialize)
def initialize(campos={})
campos = {:carteira => "03", :especie_documento => "A"}.merge!(campos)
super(campos)
end
# Codigo do banco emissor (3 dígitos sempre)
#
# @return [String] 3 caracteres numéricos.
def banco
"748"
end
# Carteira
#
# @return [String] 2 caracteres numéricos.
def carteira=(valor)
@carteira = valor.to_s.rjust(2,'0') if valor
end
# Posto
#
# @return [String] 2 caracteres numéricos.
def posto=(valor)
@posto = valor.to_s.rjust(2, '0') if valor
end
# Número da conta corrente
# @return [String] 5 caracteres numéricos.
def conta_corrente=(valor)
@conta_corrente = valor.to_s.rjust(5,'0') if valor
end
# Dígito verificador do banco
# @return [String] 1 caractere.
def banco_dv
'X'
end
# Nosso número para exibir no boleto.
# @return [String]
# @example
# boleto.nosso_numero_boleto #=> "14/200022-5"
def nosso_numero_boleto
"#{numero_documento_with_byte_idt[0..1]}/#{numero_documento_with_byte_idt[2..-1]}-#{self.nosso_numero_dv}"
end
def numero_documento_with_byte_idt
"#{self.data_documento.strftime('%y')}#{self.byte_idt}#{self.numero_documento}"
end
# Número seqüencial utilizado para identificar o boleto.
# @return [String] 5 caracteres numéricos.
def numero_documento=(valor)
@numero_documento = valor.to_s.rjust(5,'0') if valor
end
# Codigo referente ao tipo de cobrança
# @return [String]: 1 caractere numérico
def tipo_cobranca
"3"
end
# Codigo referente ao tipo de carteira
# @return [String]: 1 caractere numérico
def tipo_carteira
if self.carteira == "03"
"1"
end
end
# Dígito verificador do nosso número
# @return [Integer] 1 caracteres numéricos.
def nosso_numero_dv
"#{agencia_posto_conta}#{numero_documento_with_byte_idt}".modulo11_9to2
end
def agencia_conta_boleto
"#{self.agencia}.#{self.posto}.#{conta_corrente}"
end
def agencia_posto_conta
"#{self.agencia}#{self.posto}#{conta_corrente}"
end
# Segunda parte do código de barras.
def codigo_barras_segunda_parte
campo_livre = "#{self.tipo_cobranca}#{self.tipo_carteira}#{self.nosso_numero_boleto.gsub(/\D/, '')}#{self.agencia_posto_conta}10"
campo_livre + campo_livre.modulo11_9to2_10_como_zero.to_s
end
end
end
end
fixing sicredit validation message to use the new BACEN terminology
# -*- encoding: utf-8 -*-
#
# Sicredi
# Documentação: http://www.shapeness.net.br/upload//Sicredi_240.pdf
#
module Brcobranca
module Boleto
class Sicredi < Base # Banco SICREDI
# <b>REQUERIDO</b>: Código do posto da cooperativa de crédito
attr_accessor :posto
# <b>REQUERIDO</b>: Byte de identificação do cedente do bloqueto utilizado para compor o nosso número.
attr_accessor :byte_idt
validates_length_of :agencia, :maximum => 4, :message => 'deve ser menor ou igual a 4 dígitos.'
validates_length_of :numero_documento, :maximum => 5, :message => 'deve ser menor ou igual a 5 dígitos.'
validates_length_of :conta_corrente, :maximum => 5, :message => 'deve ser menor ou igual a 5 dígitos.'
validates_length_of :carteira, :maximum => 2, :message => 'deve ser menor ou igual a 2 dígitos.'
validates_length_of :byte_idt, :is => 1, :message => 'deve ser 1 se o numero foi gerado pela agencia ou 2-9 se foi gerado pelo beneficiário'
# Nova instancia do Bradesco
# @param (see Brcobranca::Boleto::Base#initialize)
def initialize(campos={})
campos = {:carteira => "03", :especie_documento => "A"}.merge!(campos)
super(campos)
end
# Codigo do banco emissor (3 dígitos sempre)
#
# @return [String] 3 caracteres numéricos.
def banco
"748"
end
# Carteira
#
# @return [String] 2 caracteres numéricos.
def carteira=(valor)
@carteira = valor.to_s.rjust(2,'0') if valor
end
# Posto
#
# @return [String] 2 caracteres numéricos.
def posto=(valor)
@posto = valor.to_s.rjust(2, '0') if valor
end
# Número da conta corrente
# @return [String] 5 caracteres numéricos.
def conta_corrente=(valor)
@conta_corrente = valor.to_s.rjust(5,'0') if valor
end
# Dígito verificador do banco
# @return [String] 1 caractere.
def banco_dv
'X'
end
# Nosso número para exibir no boleto.
# @return [String]
# @example
# boleto.nosso_numero_boleto #=> "14/200022-5"
def nosso_numero_boleto
"#{numero_documento_with_byte_idt[0..1]}/#{numero_documento_with_byte_idt[2..-1]}-#{self.nosso_numero_dv}"
end
def numero_documento_with_byte_idt
"#{self.data_documento.strftime('%y')}#{self.byte_idt}#{self.numero_documento}"
end
# Número seqüencial utilizado para identificar o boleto.
# @return [String] 5 caracteres numéricos.
def numero_documento=(valor)
@numero_documento = valor.to_s.rjust(5,'0') if valor
end
# Codigo referente ao tipo de cobrança
# @return [String]: 1 caractere numérico
def tipo_cobranca
"3"
end
# Codigo referente ao tipo de carteira
# @return [String]: 1 caractere numérico
def tipo_carteira
if self.carteira == "03"
"1"
end
end
# Dígito verificador do nosso número
# @return [Integer] 1 caracteres numéricos.
def nosso_numero_dv
"#{agencia_posto_conta}#{numero_documento_with_byte_idt}".modulo11_9to2
end
def agencia_conta_boleto
"#{self.agencia}.#{self.posto}.#{conta_corrente}"
end
def agencia_posto_conta
"#{self.agencia}#{self.posto}#{conta_corrente}"
end
# Segunda parte do código de barras.
def codigo_barras_segunda_parte
campo_livre = "#{self.tipo_cobranca}#{self.tipo_carteira}#{self.nosso_numero_boleto.gsub(/\D/, '')}#{self.agencia_posto_conta}10"
campo_livre + campo_livre.modulo11_9to2_10_como_zero.to_s
end
end
end
end
|
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
BuildrPlus::FeatureManager.feature(:libs) do |f|
f.enhance(:Config) do
def giggle
'org.realityforge.giggle:giggle-compiler:jar:all:0.08'
end
def mustache
%w(com.github.spullara.mustache.java:compiler:jar:0.9.6) + self.guava
end
def javacsv
%w(net.sourceforge.javacsv:javacsv:jar:2.1)
end
def geotools_for_geolatte
%w(org.geotools:gt-main:jar:9.4 org.geotools:gt-metadata:jar:9.4 org.geotools:gt-api:jar:9.4 org.geotools:gt-epsg-wkt:jar:9.4 org.geotools:gt-opengis:jar:9.4 org.geotools:gt-transform:jar:9.4 org.geotools:gt-geometry:jar:9.4 org.geotools:gt-jts-wrapper:jar:9.4 org.geotools:gt-referencing:jar:9.4 net.java.dev.jsr-275:jsr-275:jar:1.0-beta-2 java3d:vecmath:jar:1.3.2 javax.media:jai_core:jar:1.1.3)
end
def jts
%w(com.vividsolutions:jts:jar:1.13)
end
# Support geo libraries for geolatte
def geolatte_support
self.jts + self.slf4j
end
def geolatte_geom
%w(org.geolatte:geolatte-geom:jar:0.13)
end
def geolatte_geom_jpa
%w(org.realityforge.geolatte.jpa:geolatte-geom-jpa:jar:0.2)
end
def jetbrains_annotations
%w(org.realityforge.org.jetbrains.annotations:org.jetbrains.annotations:jar:1.5.0)
end
def javax_annotations
%w(org.realityforge.javax.annotation:javax.annotation:jar:1.0.1)
end
def spotbugs_provided
%w(com.github.spotbugs:spotbugs-annotations:jar:3.1.5 net.jcip:jcip-annotations:jar:1.0) + self.javax_annotations
end
def ee_provided
%w(javax:javaee-api:jar:8.0.1) + self.spotbugs_provided + self.jetbrains_annotations
end
def glassfish_embedded
%w(fish.payara.extras:payara-embedded-all:jar:5.201)
end
def eclipselink
'org.eclipse.persistence:eclipselink:jar:2.7.4'
end
def mockito
%w(org.mockito:mockito-all:jar:1.10.19)
end
def jackson_annotations
%w(com.fasterxml.jackson.core:jackson-annotations:jar:2.9.9)
end
def jackson_core
%w(com.fasterxml.jackson.core:jackson-core:jar:2.9.9)
end
def jackson_databind
%w(com.fasterxml.jackson.core:jackson-databind:jar:2.9.9)
end
def jackson_datatype_jdk8
%w(com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar:2.9.9)
end
def jackson_datatype_jsr310
%w(com.fasterxml.jackson.datatype:jackson-datatype-jsr310:jar:2.9.9)
end
def jackson_gwt_support
self.jackson_core + self.jackson_databind + self.jackson_annotations
end
def braincheck
%w(org.realityforge.braincheck:braincheck:jar:1.29.0)
end
def jsinterop
%w(com.google.jsinterop:jsinterop-annotations:jar:2.0.0)
end
def jsinterop_base
%w(com.google.jsinterop:base:jar:1.0.0) + self.jsinterop
end
def elemental2_version
'2.27'
end
def elemental2_group_id
'org.realityforge.com.google.elemental2'
end
def elemental2_core
%W(#{elemental2_group_id}:elemental2-core:jar:#{elemental2_version}) + self.jsinterop_base
end
def elemental2_dom
%W(#{elemental2_group_id}:elemental2-dom:jar:#{elemental2_version}) + self.elemental2_promise
end
def elemental2_promise
%W(#{elemental2_group_id}:elemental2-promise:jar:#{elemental2_version}) + self.elemental2_core
end
def elemental2_webstorage
%W(#{elemental2_group_id}:elemental2-webstorage:jar:#{elemental2_version}) + self.elemental2_dom
end
def gwt_user
%w(com.google.gwt:gwt-user:jar:2.9.0 org.w3c.css:sac:jar:1.3) + self.jsinterop
end
def gwt_servlet
%w(com.google.gwt:gwt-servlet:jar:2.9.0)
end
def gwt_dev
'com.google.gwt:gwt-dev:jar:2.9.0'
end
def javax_inject
%w(javax.inject:javax.inject:jar:1)
end
def javax_inject_gwt
%w(javax.inject:javax.inject:jar:sources:1) + self.javax_inject
end
def gwt_serviceworker
%w(org.realityforge.gwt.serviceworker:gwt-serviceworker-linker:jar:0.02)
end
def gwt_cache_filter
%w(org.realityforge.gwt.cache-filter:gwt-cache-filter:jar:0.9)
end
def field_filter
%w(org.realityforge.rest.field_filter:rest-field-filter:jar:0.4)
end
def timeservice
%w(org.realityforge.timeservice:timeservice:jar:0.02)
end
def graphql_java
%w(com.graphql-java:graphql-java:jar:13.0) + self.slf4j + self.antlr4_runtime + self.graphql_java_dataloader
end
def graphql_java_dataloader
%w(com.graphql-java:java-dataloader:jar:2.1.1 org.reactivestreams:reactive-streams:jar:1.0.2)
end
def graphql_java_servlet
%w(com.graphql-java-kickstart:graphql-java-servlet:jar:8.0.0) +
self.graphql_java +
self.jackson_annotations +
self.jackson_core +
self.jackson_databind +
self.jackson_datatype_jdk8 +
self.guava # Expected 24.1.1-jre
end
def graphql_java_scalars
%w(org.realityforge.graphql.scalars:graphql-java-scalars:jar:0.01)
end
def antlr4_runtime
%w(org.antlr:antlr4-runtime:jar:4.7.2)
end
def rest_criteria
%w(org.realityforge.rest.criteria:rest-criteria:jar:0.9.6) +
self.antlr4_runtime +
self.field_filter
end
def commons_logging
%w(commons-logging:commons-logging:jar:1.2)
end
def commons_codec
%w(commons-codec:commons-codec:jar:1.9)
end
def bouncycastle
%w(org.bouncycastle:bcprov-jdk15on:jar:1.52 org.bouncycastle:bcpkix-jdk15on:jar:1.52)
end
def proxy_servlet
self.httpclient + %w(org.realityforge.proxy-servlet:proxy-servlet:jar:0.2.0)
end
def httpclient
%w(org.apache.httpcomponents:httpclient:jar:4.5 org.apache.httpcomponents:httpcore:jar:4.4.1) +
self.commons_logging + self.commons_codec
end
def failsafe
%w(net.jodah:failsafe:jar:1.0.3)
end
def keycloak_gwt
%w(org.realityforge.gwt.keycloak:gwt-keycloak:jar:0.7) + self.elemental2_webstorage
end
def keycloak_domgen_support
%w(org.realityforge.keycloak.domgen:keycloak-domgen-support:jar:1.4)
end
def keycloak_authfilter
%w(org.realityforge.keycloak.client.authfilter:keycloak-jaxrs-client-authfilter:jar:1.02)
end
def keycloak_converger
'org.realityforge.keycloak.converger:keycloak-converger:jar:1.8'
end
def jboss_logging
%w(org.jboss.logging:jboss-logging:jar:3.3.0.Final)
end
def keycloak_core
%w(
org.keycloak:keycloak-core:jar:2.0.0.Final
org.keycloak:keycloak-common:jar:2.0.0.Final
) + self.bouncycastle
end
def keycloak
%w(
org.keycloak:keycloak-servlet-filter-adapter:jar:2.0.0.Final
org.keycloak:keycloak-adapter-spi:jar:2.0.0.Final
org.keycloak:keycloak-adapter-core:jar:2.0.0.Final
org.realityforge.org.keycloak:keycloak-servlet-adapter-spi:jar:2.0.0.Final
) + self.keycloak_core + self.keycloak_domgen_support + self.httpclient + self.jboss_logging
end
def simple_keycloak_service
%w(org.realityforge.keycloak.sks:simple-keycloak-service:jar:0.1)
end
def guava
%w(com.google.guava:guava:jar:27.1-jre)
end
def arez_version
'0.182'
end
def arez
%W(org.realityforge.arez:arez-core:jar:#{arez_version}) + self.braincheck
end
def arez_processor
%W(org.realityforge.arez:arez-processor:jar:#{arez_version})
end
def arez_spytools
%w(org.realityforge.arez.spytools:arez-spytools:jar:0.109)
end
def arez_testng
%w(org.realityforge.arez.testng:arez-testng:jar:0.14)
end
def arez_dom
%w(org.realityforge.arez.dom:arez-dom:jar:0.69)
end
def arez_persist_version
'0.09'
end
def arez_persist_core
%W(org.realityforge.arez.persist:arez-persist-core:jar:#{arez_persist_version})
end
def arez_persist_processor
%W(org.realityforge.arez.persist:arez-persist-processor:jar:#{arez_persist_version})
end
def grim_annotations
%w(org.realityforge.grim:grim-annotations:jar:0.04)
end
def router_fu_version
'0.27'
end
def router_fu
%W(org.realityforge.router.fu:router-fu-core:jar:#{router_fu_version}) + self.braincheck
end
def router_fu_processor
%W(org.realityforge.router.fu:router-fu-processor:jar:#{router_fu_version})
end
def sting_version
'0.16'
end
def sting_core
%W(org.realityforge.sting:sting-core:jar:#{sting_version})
end
def sting_processor
%W(org.realityforge.sting:sting-processor:jar:#{sting_version})
end
def react4j_version
'0.163'
end
def react4j
%W(
org.realityforge.react4j:react4j-core:jar:#{react4j_version}
org.realityforge.react4j:react4j-dom:jar:#{react4j_version}
) + self.elemental2_dom
end
def react4j_processor
%W(org.realityforge.react4j:react4j-processor:jar:#{react4j_version})
end
def replicant_version
'6.94'
end
def replicant_client
%W(org.realityforge.replicant:replicant-client:jar:#{replicant_version}) + self.elemental2_webstorage
end
def replicant_server
%W(org.realityforge.replicant:replicant-server:jar:#{replicant_version}) + self.gwt_rpc
end
def gwt_rpc
self.jackson_gwt_support + self.gwt_servlet
end
def guice
%w(aopalliance:aopalliance:jar:1.0 org.ow2.asm:asm:jar:7.1 au.com.stocksoftware.com.google.inject:guice:jar:4.1.1-stock)
end
def awaitility
%w(org.awaitility:awaitility:jar:2.0.0)
end
def testng_version
'6.11'
end
def testng
%W(org.testng:testng:jar:#{testng_version})
end
def jndikit
%w(org.realityforge.jndikit:jndikit:jar:1.4)
end
def guiceyloops
self.mockito + self.testng + %w(org.realityforge.guiceyloops:guiceyloops:jar:0.106) + self.guice + self.glassfish_embedded
end
def glassfish_timers_domain
%W(org.realityforge.glassfish.timers#{BuildrPlus::Db.pgsql? ? '.pg' : ''}:glassfish-timers-domain:json:0.7)
end
def glassfish_timers_db
%W(org.realityforge.glassfish.timers#{BuildrPlus::Db.pgsql? ? '.pg' : ''}:glassfish-timers-db:jar:0.7)
end
def slf4j
%w(org.slf4j:slf4j-api:jar:1.7.25 org.slf4j:slf4j-jdk14:jar:1.7.25)
end
def greenmail
%w(com.icegreen:greenmail:jar:1.4.1) + self.slf4j
end
def greenmail_server
'com.icegreen:greenmail-webapp:war:1.4.1'
end
def jtds
%w(net.sourceforge.jtds:jtds:jar:1.3.1)
end
def postgresql
%w(org.postgresql:postgresql:jar:9.2-1003-jdbc4)
end
def postgis
%w(org.postgis:postgis-jdbc:jar:1.3.3)
end
def db_drivers
return self.jtds if BuildrPlus::Db.mssql?
return self.postgresql + (BuildrPlus::FeatureManager.activated?(:geolatte) ? self.postgis : []) if BuildrPlus::Db.pgsql?
[]
end
end
end
Bump react4j version
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
BuildrPlus::FeatureManager.feature(:libs) do |f|
f.enhance(:Config) do
def giggle
'org.realityforge.giggle:giggle-compiler:jar:all:0.08'
end
def mustache
%w(com.github.spullara.mustache.java:compiler:jar:0.9.6) + self.guava
end
def javacsv
%w(net.sourceforge.javacsv:javacsv:jar:2.1)
end
def geotools_for_geolatte
%w(org.geotools:gt-main:jar:9.4 org.geotools:gt-metadata:jar:9.4 org.geotools:gt-api:jar:9.4 org.geotools:gt-epsg-wkt:jar:9.4 org.geotools:gt-opengis:jar:9.4 org.geotools:gt-transform:jar:9.4 org.geotools:gt-geometry:jar:9.4 org.geotools:gt-jts-wrapper:jar:9.4 org.geotools:gt-referencing:jar:9.4 net.java.dev.jsr-275:jsr-275:jar:1.0-beta-2 java3d:vecmath:jar:1.3.2 javax.media:jai_core:jar:1.1.3)
end
def jts
%w(com.vividsolutions:jts:jar:1.13)
end
# Support geo libraries for geolatte
def geolatte_support
self.jts + self.slf4j
end
def geolatte_geom
%w(org.geolatte:geolatte-geom:jar:0.13)
end
def geolatte_geom_jpa
%w(org.realityforge.geolatte.jpa:geolatte-geom-jpa:jar:0.2)
end
def jetbrains_annotations
%w(org.realityforge.org.jetbrains.annotations:org.jetbrains.annotations:jar:1.5.0)
end
def javax_annotations
%w(org.realityforge.javax.annotation:javax.annotation:jar:1.0.1)
end
def spotbugs_provided
%w(com.github.spotbugs:spotbugs-annotations:jar:3.1.5 net.jcip:jcip-annotations:jar:1.0) + self.javax_annotations
end
def ee_provided
%w(javax:javaee-api:jar:8.0.1) + self.spotbugs_provided + self.jetbrains_annotations
end
def glassfish_embedded
%w(fish.payara.extras:payara-embedded-all:jar:5.201)
end
def eclipselink
'org.eclipse.persistence:eclipselink:jar:2.7.4'
end
def mockito
%w(org.mockito:mockito-all:jar:1.10.19)
end
def jackson_annotations
%w(com.fasterxml.jackson.core:jackson-annotations:jar:2.9.9)
end
def jackson_core
%w(com.fasterxml.jackson.core:jackson-core:jar:2.9.9)
end
def jackson_databind
%w(com.fasterxml.jackson.core:jackson-databind:jar:2.9.9)
end
def jackson_datatype_jdk8
%w(com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar:2.9.9)
end
def jackson_datatype_jsr310
%w(com.fasterxml.jackson.datatype:jackson-datatype-jsr310:jar:2.9.9)
end
def jackson_gwt_support
self.jackson_core + self.jackson_databind + self.jackson_annotations
end
def braincheck
%w(org.realityforge.braincheck:braincheck:jar:1.29.0)
end
def jsinterop
%w(com.google.jsinterop:jsinterop-annotations:jar:2.0.0)
end
def jsinterop_base
%w(com.google.jsinterop:base:jar:1.0.0) + self.jsinterop
end
def elemental2_version
'2.27'
end
def elemental2_group_id
'org.realityforge.com.google.elemental2'
end
def elemental2_core
%W(#{elemental2_group_id}:elemental2-core:jar:#{elemental2_version}) + self.jsinterop_base
end
def elemental2_dom
%W(#{elemental2_group_id}:elemental2-dom:jar:#{elemental2_version}) + self.elemental2_promise
end
def elemental2_promise
%W(#{elemental2_group_id}:elemental2-promise:jar:#{elemental2_version}) + self.elemental2_core
end
def elemental2_webstorage
%W(#{elemental2_group_id}:elemental2-webstorage:jar:#{elemental2_version}) + self.elemental2_dom
end
def gwt_user
%w(com.google.gwt:gwt-user:jar:2.9.0 org.w3c.css:sac:jar:1.3) + self.jsinterop
end
def gwt_servlet
%w(com.google.gwt:gwt-servlet:jar:2.9.0)
end
def gwt_dev
'com.google.gwt:gwt-dev:jar:2.9.0'
end
def javax_inject
%w(javax.inject:javax.inject:jar:1)
end
def javax_inject_gwt
%w(javax.inject:javax.inject:jar:sources:1) + self.javax_inject
end
def gwt_serviceworker
%w(org.realityforge.gwt.serviceworker:gwt-serviceworker-linker:jar:0.02)
end
def gwt_cache_filter
%w(org.realityforge.gwt.cache-filter:gwt-cache-filter:jar:0.9)
end
def field_filter
%w(org.realityforge.rest.field_filter:rest-field-filter:jar:0.4)
end
def timeservice
%w(org.realityforge.timeservice:timeservice:jar:0.02)
end
def graphql_java
%w(com.graphql-java:graphql-java:jar:13.0) + self.slf4j + self.antlr4_runtime + self.graphql_java_dataloader
end
def graphql_java_dataloader
%w(com.graphql-java:java-dataloader:jar:2.1.1 org.reactivestreams:reactive-streams:jar:1.0.2)
end
def graphql_java_servlet
%w(com.graphql-java-kickstart:graphql-java-servlet:jar:8.0.0) +
self.graphql_java +
self.jackson_annotations +
self.jackson_core +
self.jackson_databind +
self.jackson_datatype_jdk8 +
self.guava # Expected 24.1.1-jre
end
def graphql_java_scalars
%w(org.realityforge.graphql.scalars:graphql-java-scalars:jar:0.01)
end
def antlr4_runtime
%w(org.antlr:antlr4-runtime:jar:4.7.2)
end
def rest_criteria
%w(org.realityforge.rest.criteria:rest-criteria:jar:0.9.6) +
self.antlr4_runtime +
self.field_filter
end
def commons_logging
%w(commons-logging:commons-logging:jar:1.2)
end
def commons_codec
%w(commons-codec:commons-codec:jar:1.9)
end
def bouncycastle
%w(org.bouncycastle:bcprov-jdk15on:jar:1.52 org.bouncycastle:bcpkix-jdk15on:jar:1.52)
end
def proxy_servlet
self.httpclient + %w(org.realityforge.proxy-servlet:proxy-servlet:jar:0.2.0)
end
def httpclient
%w(org.apache.httpcomponents:httpclient:jar:4.5 org.apache.httpcomponents:httpcore:jar:4.4.1) +
self.commons_logging + self.commons_codec
end
def failsafe
%w(net.jodah:failsafe:jar:1.0.3)
end
def keycloak_gwt
%w(org.realityforge.gwt.keycloak:gwt-keycloak:jar:0.7) + self.elemental2_webstorage
end
def keycloak_domgen_support
%w(org.realityforge.keycloak.domgen:keycloak-domgen-support:jar:1.4)
end
def keycloak_authfilter
%w(org.realityforge.keycloak.client.authfilter:keycloak-jaxrs-client-authfilter:jar:1.02)
end
def keycloak_converger
'org.realityforge.keycloak.converger:keycloak-converger:jar:1.8'
end
def jboss_logging
%w(org.jboss.logging:jboss-logging:jar:3.3.0.Final)
end
def keycloak_core
%w(
org.keycloak:keycloak-core:jar:2.0.0.Final
org.keycloak:keycloak-common:jar:2.0.0.Final
) + self.bouncycastle
end
def keycloak
%w(
org.keycloak:keycloak-servlet-filter-adapter:jar:2.0.0.Final
org.keycloak:keycloak-adapter-spi:jar:2.0.0.Final
org.keycloak:keycloak-adapter-core:jar:2.0.0.Final
org.realityforge.org.keycloak:keycloak-servlet-adapter-spi:jar:2.0.0.Final
) + self.keycloak_core + self.keycloak_domgen_support + self.httpclient + self.jboss_logging
end
def simple_keycloak_service
%w(org.realityforge.keycloak.sks:simple-keycloak-service:jar:0.1)
end
def guava
%w(com.google.guava:guava:jar:27.1-jre)
end
def arez_version
'0.182'
end
def arez
%W(org.realityforge.arez:arez-core:jar:#{arez_version}) + self.braincheck
end
def arez_processor
%W(org.realityforge.arez:arez-processor:jar:#{arez_version})
end
def arez_spytools
%w(org.realityforge.arez.spytools:arez-spytools:jar:0.109)
end
def arez_testng
%w(org.realityforge.arez.testng:arez-testng:jar:0.14)
end
def arez_dom
%w(org.realityforge.arez.dom:arez-dom:jar:0.69)
end
def arez_persist_version
'0.09'
end
def arez_persist_core
%W(org.realityforge.arez.persist:arez-persist-core:jar:#{arez_persist_version})
end
def arez_persist_processor
%W(org.realityforge.arez.persist:arez-persist-processor:jar:#{arez_persist_version})
end
def grim_annotations
%w(org.realityforge.grim:grim-annotations:jar:0.04)
end
def router_fu_version
'0.27'
end
def router_fu
%W(org.realityforge.router.fu:router-fu-core:jar:#{router_fu_version}) + self.braincheck
end
def router_fu_processor
%W(org.realityforge.router.fu:router-fu-processor:jar:#{router_fu_version})
end
def sting_version
'0.16'
end
def sting_core
%W(org.realityforge.sting:sting-core:jar:#{sting_version})
end
def sting_processor
%W(org.realityforge.sting:sting-processor:jar:#{sting_version})
end
def react4j_version
'0.164'
end
def react4j
%W(
org.realityforge.react4j:react4j-core:jar:#{react4j_version}
org.realityforge.react4j:react4j-dom:jar:#{react4j_version}
) + self.elemental2_dom
end
def react4j_processor
%W(org.realityforge.react4j:react4j-processor:jar:#{react4j_version})
end
def replicant_version
'6.94'
end
def replicant_client
%W(org.realityforge.replicant:replicant-client:jar:#{replicant_version}) + self.elemental2_webstorage
end
def replicant_server
%W(org.realityforge.replicant:replicant-server:jar:#{replicant_version}) + self.gwt_rpc
end
def gwt_rpc
self.jackson_gwt_support + self.gwt_servlet
end
def guice
%w(aopalliance:aopalliance:jar:1.0 org.ow2.asm:asm:jar:7.1 au.com.stocksoftware.com.google.inject:guice:jar:4.1.1-stock)
end
def awaitility
%w(org.awaitility:awaitility:jar:2.0.0)
end
def testng_version
'6.11'
end
def testng
%W(org.testng:testng:jar:#{testng_version})
end
def jndikit
%w(org.realityforge.jndikit:jndikit:jar:1.4)
end
def guiceyloops
self.mockito + self.testng + %w(org.realityforge.guiceyloops:guiceyloops:jar:0.106) + self.guice + self.glassfish_embedded
end
def glassfish_timers_domain
%W(org.realityforge.glassfish.timers#{BuildrPlus::Db.pgsql? ? '.pg' : ''}:glassfish-timers-domain:json:0.7)
end
def glassfish_timers_db
%W(org.realityforge.glassfish.timers#{BuildrPlus::Db.pgsql? ? '.pg' : ''}:glassfish-timers-db:jar:0.7)
end
def slf4j
%w(org.slf4j:slf4j-api:jar:1.7.25 org.slf4j:slf4j-jdk14:jar:1.7.25)
end
def greenmail
%w(com.icegreen:greenmail:jar:1.4.1) + self.slf4j
end
def greenmail_server
'com.icegreen:greenmail-webapp:war:1.4.1'
end
def jtds
%w(net.sourceforge.jtds:jtds:jar:1.3.1)
end
def postgresql
%w(org.postgresql:postgresql:jar:9.2-1003-jdbc4)
end
def postgis
%w(org.postgis:postgis-jdbc:jar:1.3.3)
end
def db_drivers
return self.jtds if BuildrPlus::Db.mssql?
return self.postgresql + (BuildrPlus::FeatureManager.activated?(:geolatte) ? self.postgis : []) if BuildrPlus::Db.pgsql?
[]
end
end
end
|
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
BuildrPlus::Roles.role(:container) do
project.publish = false
default_testng_args = []
default_testng_args << '-ea'
default_testng_args << '-Xmx2024M'
default_testng_args << '-XX:MaxPermSize=364M'
if BuildrPlus::Roles.project_with_role?(:integration_tests)
server_project = project(BuildrPlus::Roles.project_with_role(:server).name)
war_package = server_project.package(:war)
war_dir = File.dirname(war_package.to_s)
default_testng_args << "-Dembedded.glassfish.artifacts=#{BuildrPlus::Guiceyloops.glassfish_spec_list}"
default_testng_args << "-Dwar.dir=#{war_dir}"
end
if BuildrPlus::FeatureManager.activated?(:db)
default_testng_args << "-javaagent:#{BuildrPlus::Libs.eclipselink.to_s}"
if BuildrPlus::FeatureManager.activated?(:dbt)
old_environment = Dbt::Config.environment
begin
Dbt.repository.load_configuration_data
Dbt.database_keys.each do |database_key|
database = Dbt.database_for_key(database_key)
next unless database.enable_rake_integration? || database.packaged? || !database.managed?
next if BuildrPlus::Dbt.manual_testing_only_database?(database_key)
prefix = Dbt::Config.default_database?(database_key) ? '' : "#{database_key}."
jdbc_url = Dbt.configuration_for_key(database_key).build_jdbc_url(:credentials_inline => true)
catalog_name = Dbt.configuration_for_key(database_key).catalog_name
default_testng_args << "-D#{prefix}test.db.url=#{jdbc_url}"
default_testng_args << "-D#{prefix}test.db.name=#{catalog_name}"
end
ensure
Dbt::Config.environment = old_environment
end
end
end
ipr.add_default_testng_configuration(:jvm_args => default_testng_args.join(' '))
# Need to use definitions as projects have yet to be when resolving
# container project which is typically the root project
if BuildrPlus::Roles.project_with_role?(:server)
server_project = project(BuildrPlus::Roles.project_with_role(:server).name)
model_project =
BuildrPlus::Roles.project_with_role?(:model) ?
project(BuildrPlus::Roles.project_with_role(:model).name) :
nil
shared_project =
BuildrPlus::Roles.project_with_role?(:shared) ?
project(BuildrPlus::Roles.project_with_role(:shared).name) :
nil
dependencies = [server_project, model_project, shared_project].compact
dependencies << Object.const_get(:PACKAGED_DEPS) if Object.const_defined?(:PACKAGED_DEPS)
war_module_names = [server_project.iml.name]
jpa_module_names = []
jpa_module_names << model_project.iml.name if model_project
ejb_module_names = [server_project.iml.name]
ejb_module_names << model_project.iml.name if model_project
ipr.add_exploded_war_artifact(project,
:dependencies => dependencies,
:war_module_names => war_module_names,
:jpa_module_names => jpa_module_names,
:ejb_module_names => ejb_module_names)
remote_packaged_apps = BuildrPlus::Glassfish.non_remote_only_packaged_apps.dup.merge(BuildrPlus::Glassfish.packaged_apps)
local_packaged_apps = BuildrPlus::Glassfish.remote_only_packaged_apps.dup.merge(BuildrPlus::Glassfish.packaged_apps)
ipr.add_glassfish_remote_configuration(project,
:server_name => 'Payara 4.1.1.154',
:exploded => [project.name],
:packaged => remote_packaged_apps)
ipr.add_glassfish_configuration(project,
:server_name => 'Payara 4.1.1.154',
:exploded => [project.name],
:packaged => local_packaged_apps)
if BuildrPlus::FeatureManager.activated?(:user_experience)
BuildrPlus::Roles.buildr_projects_with_role(:user_experience).each do |p|
candidate = p.guess_gwt_module_name('Dev')
if p.gwt_module?(candidate)
ipr.add_gwt_configuration(p,
:gwt_module => candidate,
:vm_parameters => '-Xmx3G',
:shell_parameters => '-port 8888',
:launch_page => "http://127.0.0.1:8080/#{p.root_project.name}" )
end
end
end
end
end
Correctly configure the javaagent
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
BuildrPlus::Roles.role(:container) do
project.publish = false
default_testng_args = []
default_testng_args << '-ea'
default_testng_args << '-Xmx2024M'
default_testng_args << '-XX:MaxPermSize=364M'
if BuildrPlus::Roles.project_with_role?(:integration_tests)
server_project = project(BuildrPlus::Roles.project_with_role(:server).name)
war_package = server_project.package(:war)
war_dir = File.dirname(war_package.to_s)
default_testng_args << "-Dembedded.glassfish.artifacts=#{BuildrPlus::Guiceyloops.glassfish_spec_list}"
default_testng_args << "-Dwar.dir=#{war_dir}"
end
if BuildrPlus::FeatureManager.activated?(:db)
default_testng_args << "-javaagent:#{Buildr.artifact(BuildrPlus::Libs.eclipselink).to_s}"
if BuildrPlus::FeatureManager.activated?(:dbt)
old_environment = Dbt::Config.environment
begin
Dbt.repository.load_configuration_data
Dbt.database_keys.each do |database_key|
database = Dbt.database_for_key(database_key)
next unless database.enable_rake_integration? || database.packaged? || !database.managed?
next if BuildrPlus::Dbt.manual_testing_only_database?(database_key)
prefix = Dbt::Config.default_database?(database_key) ? '' : "#{database_key}."
jdbc_url = Dbt.configuration_for_key(database_key).build_jdbc_url(:credentials_inline => true)
catalog_name = Dbt.configuration_for_key(database_key).catalog_name
default_testng_args << "-D#{prefix}test.db.url=#{jdbc_url}"
default_testng_args << "-D#{prefix}test.db.name=#{catalog_name}"
end
ensure
Dbt::Config.environment = old_environment
end
end
end
ipr.add_default_testng_configuration(:jvm_args => default_testng_args.join(' '))
# Need to use definitions as projects have yet to be when resolving
# container project which is typically the root project
if BuildrPlus::Roles.project_with_role?(:server)
server_project = project(BuildrPlus::Roles.project_with_role(:server).name)
model_project =
BuildrPlus::Roles.project_with_role?(:model) ?
project(BuildrPlus::Roles.project_with_role(:model).name) :
nil
shared_project =
BuildrPlus::Roles.project_with_role?(:shared) ?
project(BuildrPlus::Roles.project_with_role(:shared).name) :
nil
dependencies = [server_project, model_project, shared_project].compact
dependencies << Object.const_get(:PACKAGED_DEPS) if Object.const_defined?(:PACKAGED_DEPS)
war_module_names = [server_project.iml.name]
jpa_module_names = []
jpa_module_names << model_project.iml.name if model_project
ejb_module_names = [server_project.iml.name]
ejb_module_names << model_project.iml.name if model_project
ipr.add_exploded_war_artifact(project,
:dependencies => dependencies,
:war_module_names => war_module_names,
:jpa_module_names => jpa_module_names,
:ejb_module_names => ejb_module_names)
remote_packaged_apps = BuildrPlus::Glassfish.non_remote_only_packaged_apps.dup.merge(BuildrPlus::Glassfish.packaged_apps)
local_packaged_apps = BuildrPlus::Glassfish.remote_only_packaged_apps.dup.merge(BuildrPlus::Glassfish.packaged_apps)
ipr.add_glassfish_remote_configuration(project,
:server_name => 'Payara 4.1.1.154',
:exploded => [project.name],
:packaged => remote_packaged_apps)
ipr.add_glassfish_configuration(project,
:server_name => 'Payara 4.1.1.154',
:exploded => [project.name],
:packaged => local_packaged_apps)
if BuildrPlus::FeatureManager.activated?(:user_experience)
BuildrPlus::Roles.buildr_projects_with_role(:user_experience).each do |p|
candidate = p.guess_gwt_module_name('Dev')
if p.gwt_module?(candidate)
ipr.add_gwt_configuration(p,
:gwt_module => candidate,
:vm_parameters => '-Xmx3G',
:shell_parameters => '-port 8888',
:launch_page => "http://127.0.0.1:8080/#{p.root_project.name}" )
end
end
end
end
end
|
#
# Be sure to run `pod spec lint JrmfStandardDemo.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
s.name = "JrmfLib"
s.version = "1.0.0"
s.summary = "some sources of jrmf360"
s.homepage = "http://weibo.com/vamCriss"
s.license = 'MIT'
s.author = { "criss" => "ericluo0114@hotmail.com" }
s.platform = :ios, "8.0"
s.source = { :git => "https://github.com/VamCriss/JrmfLib.git", :tag => s.version }
s.resource = 'jrmfLib/*.{bundle,cer,framework}'
s.requires_arc = true
s.subspec 'AlipayLib' do |ss|
ss.resource = 'jrmfLib/AlipayLib/**'
ss.frameworks = 'SystemConfiguration', 'CoreGraphics', 'QuartzCore', 'CoreText', 'CoreGraphics', 'UIKit', 'Foundation', 'CFNetwork', 'CoreMotion'
ss.libraries = 'z', 'c++'
end
s.subspec 'WeChatSDK' do |ss|
ss.frameworks = 'AVFoundation', 'Security', 'SystemConfiguration', 'CoreTelephony', 'CFNetwork'
ss.libraries = 'sqlite3.0', 'stdc++', 'z.1.2.5'
ss.subspec 'WXSDK' do |sss|
sss.vendored_libraries = 'jrmfLib/WeChatSDK/WXSDK/libWeChatSDK.a'
sss.source_files = 'jrmfLib/WeChatSDK/WXSDK/*.h'
end
ss.subspec 'SPaySDK' do |sss|
sss.frameworks = 'Foundation', 'UIKit', 'CoreMotion', 'CoreTelephony', 'SystemConfiguration', 'CoreGraphics'
sss.source_files = 'jrmfLib/WeChatSDK/SPaySDK/*.{a, h}'
sss.resource = 'jrmfLib/WeChatSDK/SPaySDK/SPaySDKResource.bundle'
end
end
end
做了点小修改
#
# Be sure to run `pod spec lint JrmfStandardDemo.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
s.name = "JrmfLib"
s.version = "1.0.1"
s.summary = "some sources of jrmf360"
s.homepage = "http://weibo.com/vamCriss"
s.license = 'MIT'
s.author = { "criss" => "ericluo0114@hotmail.com" }
s.platform = :ios, "8.0"
s.source = { :git => "https://github.com/VamCriss/JrmfLib.git", :tag => s.version }
s.resource = 'jrmfLib/*.{bundle,cer,framework}'
s.requires_arc = true
s.subspec 'AlipayLib' do |ss|
ss.resource = 'jrmfLib/AlipayLib/**'
ss.frameworks = 'SystemConfiguration', 'CoreGraphics', 'QuartzCore', 'CoreText', 'CoreGraphics', 'UIKit', 'Foundation', 'CFNetwork', 'CoreMotion'
ss.libraries = 'z', 'c++'
end
s.subspec 'WeChatSDK' do |ss|
ss.frameworks = 'AVFoundation', 'Security', 'SystemConfiguration', 'CoreTelephony', 'CFNetwork'
ss.libraries = 'sqlite3.0', 'stdc++', 'z.1.2.5'
ss.subspec 'WXSDK' do |sss|
sss.vendored_libraries = 'jrmfLib/WeChatSDK/WXSDK/libWeChatSDK.a'
sss.source_files = 'jrmfLib/WeChatSDK/WXSDK/*.h'
end
ss.subspec 'SPaySDK' do |sss|
sss.frameworks = 'Foundation', 'UIKit', 'CoreMotion', 'CoreTelephony', 'SystemConfiguration', 'CoreGraphics'
sss.source_files = 'jrmfLib/WeChatSDK/SPaySDK/*.{a, h}'
sss.resource = 'jrmfLib/WeChatSDK/SPaySDK/SPaySDKResource.bundle'
end
end
end
|
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
BuildrPlus::FeatureManager.feature(:libs) do |f|
f.enhance(:Config) do
def mustache
%w(com.github.spullara.mustache.java:compiler:jar:0.8.15)
end
def javacsv
%w(net.sourceforge.javacsv:javacsv:jar:2.1)
end
def geotools_for_geolatte
%w(org.geotools:gt-main:jar:9.4 org.geotools:gt-metadata:jar:9.4 org.geotools:gt-api:jar:9.4 org.geotools:gt-epsg-wkt:jar:9.4 org.geotools:gt-opengis:jar:9.4 org.geotools:gt-transform:jar:9.4 org.geotools:gt-geometry:jar:9.4 org.geotools:gt-jts-wrapper:jar:9.4 org.geotools:gt-referencing:jar:9.4 net.java.dev.jsr-275:jsr-275:jar:1.0-beta-2 java3d:vecmath:jar:1.3.2 javax.media:jai_core:jar:1.1.3)
end
def jts
%w(com.vividsolutions:jts:jar:1.13)
end
# Support geo libraries for geolatte
def geolatte_support
self.jts + self.slf4j
end
def geolatte_geom
%w(org.geolatte:geolatte-geom:jar:0.13)
end
def geolatte_geom_jpa
%w(org.realityforge.geolatte.jpa:geolatte-geom-jpa:jar:0.2)
end
def findbugs_provided
%w(com.google.code.findbugs:jsr305:jar:3.0.0 com.google.code.findbugs:annotations:jar:3.0.0)
end
def ee_provided
%w(javax:javaee-api:jar:7.0) + self.findbugs_provided
end
def glassfish_embedded
%w(fish.payara.extras:payara-embedded-all:jar:4.1.1.164)
end
def eclipselink
'org.eclipse.persistence:eclipselink:jar:2.6.0'
end
def mockito
%w(org.mockito:mockito-all:jar:1.10.19)
end
def jackson_annotations
%w(com.fasterxml.jackson.core:jackson-annotations:jar:2.5.4)
end
def jackson_core
%w(com.fasterxml.jackson.core:jackson-core:jar:2.5.4)
end
def jackson_databind
%w(com.fasterxml.jackson.core:jackson-databind:jar:2.5.4)
end
def jackson_gwt_support
self.jackson_core + self.jackson_databind + self.jackson_annotations
end
def jsinterop
%w(com.google.jsinterop:jsinterop-annotations:jar:1.0.1 com.google.jsinterop:jsinterop-annotations:jar:sources:1.0.1)
end
def gwt_user
%w(com.google.gwt:gwt-user:jar:2.8.0 org.w3c.css:sac:jar:1.3) + self.jsinterop
end
def gwt_servlet
%w(com.google.gwt:gwt-servlet:jar:2.8.0)
end
def gwt_dev
'com.google.gwt:gwt-dev:jar:2.8.0'
end
def javax_inject
%w(javax.inject:javax.inject:jar:1)
end
def gwt_gin
%w(com.google.gwt.inject:gin:jar:2.1.2) + self.javax_inject + self.guice + self.gwt_user
end
def gwt_property_source
%w(org.realityforge.gwt.property-source:gwt-property-source:jar:0.2)
end
def gwt_webpoller
%w(org.realityforge.gwt.webpoller:gwt-webpoller:jar:0.9.2)
end
def gwt_datatypes
%w(org.realityforge.gwt.datatypes:gwt-datatypes:jar:0.8)
end
def gwt_ga
%w(org.realityforge.gwt.ga:gwt-ga:jar:0.5)
end
def gwt_mmvp
%w(org.realityforge.gwt.mmvp:gwt-mmvp:jar:0.5)
end
def gwt_lognice
%w(org.realityforge.gwt.lognice:gwt-lognice:jar:0.4)
end
def gwt_appcache_client
%w(org.realityforge.gwt.appcache:gwt-appcache-client:jar:1.0.9 org.realityforge.gwt.appcache:gwt-appcache-linker:jar:1.0.9)
end
def gwt_appcache_server
%w(org.realityforge.gwt.appcache:gwt-appcache-server:jar:1.0.9)
end
# The appcache code required to exist on gwt path during compilation
def gwt_appcache
self.gwt_appcache_client + self.gwt_appcache_server
end
def gwt_cache_filter
%w(org.realityforge.gwt.cache-filter:gwt-cache-filter:jar:0.7)
end
def simple_session_filter
%w(org.realityforge.ssf:simple-session-filter:jar:0.7)
end
def field_filter
%w(org.realityforge.rest.field_filter:rest-field-filter:jar:0.4)
end
def rest_criteria
%w(org.realityforge.rest.criteria:rest-criteria:jar:0.9.4 org.antlr:antlr4-runtime:jar:4.3 org.antlr:antlr4-annotations:jar:4.3) + self.field_filter
end
def commons_logging
%w(commons-logging:commons-logging:jar:1.2)
end
def commons_codec
%w(commons-codec:commons-codec:jar:1.9)
end
def bouncycastle
%w(org.bouncycastle:bcprov-jdk15on:jar:1.52 org.bouncycastle:bcpkix-jdk15on:jar:1.52)
end
def proxy_servlet
self.httpclient + %w(org.realityforge.proxy-servlet:proxy-servlet:jar:0.2.0)
end
def httpclient
%w(org.apache.httpcomponents:httpclient:jar:4.5 org.apache.httpcomponents:httpcore:jar:4.4.1) +
self.commons_logging + self.commons_codec
end
def keycloak_gwt
%w(org.realityforge.gwt.keycloak:gwt-keycloak:jar:0.1)
end
def keycloak_domgen_support
%w(org.realityforge.keycloak.domgen:keycloak-domgen-support:jar:1.3)
end
def jboss_logging
%w(org.jboss.logging:jboss-logging:jar:3.3.0.Final)
end
def keycloak_core
%w(
org.keycloak:keycloak-core:jar:2.0.0.Final
org.keycloak:keycloak-common:jar:2.0.0.Final
) + self.bouncycastle
end
def keycloak
%w(
org.keycloak:keycloak-servlet-filter-adapter:jar:2.0.0.Final
org.keycloak:keycloak-adapter-spi:jar:2.0.0.Final
org.keycloak:keycloak-adapter-core:jar:2.0.0.Final
org.realityforge.org.keycloak:keycloak-servlet-adapter-spi:jar:2.0.0.Final
) + self.keycloak_core + self.keycloak_domgen_support + self.httpclient + self.jboss_logging
end
def replicant_version
'0.5.71'
end
def replicant_shared
%W(org.realityforge.replicant:replicant-shared:jar:#{replicant_version})
end
def replicant_client_common
%W(org.realityforge.replicant:replicant-client-common:jar:#{replicant_version}) + self.replicant_shared + self.gwt_webpoller + self.gwt_datatypes
end
def replicant_client_qa_support
%W(org.realityforge.replicant:replicant-client-qa-support:jar:#{replicant_version}) + self.guiceyloops_gwt
end
def replicant_ee_client
%W(org.realityforge.replicant:replicant-client-ee:jar:#{replicant_version}) + self.replicant_client_common
end
def replicant_gwt_client
%W(org.realityforge.replicant:replicant-client-gwt:jar:#{replicant_version}) + self.replicant_client_common + self.gwt_property_source
end
def replicant_server
%W(org.realityforge.replicant:replicant-server:jar:#{replicant_version}) + self.replicant_shared + self.simple_session_filter + self.gwt_rpc + self.field_filter
end
def gwt_rpc
self.gwt_datatypes + self.jackson_gwt_support + self.gwt_servlet
end
def guice
%w(aopalliance:aopalliance:jar:1.0 com.google.inject:guice:jar:3.0 com.google.inject.extensions:guice-assistedinject:jar:3.0)
end
def awaitility
%w(org.awaitility:awaitility:jar:2.0.0)
end
def testng
%w(org.testng:testng:jar:6.8)
end
def jndikit
%w(org.realityforge.jndikit:jndikit:jar:1.4)
end
def guiceyloops
self.glassfish_embedded + self.guiceyloops_gwt
end
def guiceyloops_lib
'org.realityforge.guiceyloops:guiceyloops:jar:0.82'
end
def guiceyloops_gwt
[guiceyloops_lib] + self.mockito + self.guice + self.testng
end
def glassfish_timers_domain
%W(org.realityforge.glassfish.timers#{BuildrPlus::Db.pgsql? ? '.pg' : ''}:glassfish-timers-domain:json:0.4)
end
def glassfish_timers_db
%W(org.realityforge.glassfish.timers#{BuildrPlus::Db.pgsql? ? '.pg' : ''}:glassfish-timers-db:jar:0.4)
end
def slf4j
%w(org.slf4j:slf4j-api:jar:1.6.6 org.slf4j:slf4j-jdk14:jar:1.6.6)
end
def greenmail
%w(com.icegreen:greenmail:jar:1.4.1) + self.slf4j
end
def greenmail_server
'com.icegreen:greenmail-webapp:war:1.4.1'
end
def jtds
%w(net.sourceforge.jtds:jtds:jar:1.3.1)
end
def postgresql
%w(org.postgresql:postgresql:jar:9.2-1003-jdbc4)
end
def postgis
%w(org.postgis:postgis-jdbc:jar:1.3.3)
end
def db_drivers
return self.jtds if BuildrPlus::Db.mssql?
return self.postgresql + (BuildrPlus::FeatureManager.activated?(:geolatte) ? self.postgis : []) if BuildrPlus::Db.pgsql?
[]
end
end
end
Bump guiceyloops version
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
BuildrPlus::FeatureManager.feature(:libs) do |f|
f.enhance(:Config) do
def mustache
%w(com.github.spullara.mustache.java:compiler:jar:0.8.15)
end
def javacsv
%w(net.sourceforge.javacsv:javacsv:jar:2.1)
end
def geotools_for_geolatte
%w(org.geotools:gt-main:jar:9.4 org.geotools:gt-metadata:jar:9.4 org.geotools:gt-api:jar:9.4 org.geotools:gt-epsg-wkt:jar:9.4 org.geotools:gt-opengis:jar:9.4 org.geotools:gt-transform:jar:9.4 org.geotools:gt-geometry:jar:9.4 org.geotools:gt-jts-wrapper:jar:9.4 org.geotools:gt-referencing:jar:9.4 net.java.dev.jsr-275:jsr-275:jar:1.0-beta-2 java3d:vecmath:jar:1.3.2 javax.media:jai_core:jar:1.1.3)
end
def jts
%w(com.vividsolutions:jts:jar:1.13)
end
# Support geo libraries for geolatte
def geolatte_support
self.jts + self.slf4j
end
def geolatte_geom
%w(org.geolatte:geolatte-geom:jar:0.13)
end
def geolatte_geom_jpa
%w(org.realityforge.geolatte.jpa:geolatte-geom-jpa:jar:0.2)
end
def findbugs_provided
%w(com.google.code.findbugs:jsr305:jar:3.0.0 com.google.code.findbugs:annotations:jar:3.0.0)
end
def ee_provided
%w(javax:javaee-api:jar:7.0) + self.findbugs_provided
end
def glassfish_embedded
%w(fish.payara.extras:payara-embedded-all:jar:4.1.1.164)
end
def eclipselink
'org.eclipse.persistence:eclipselink:jar:2.6.0'
end
def mockito
%w(org.mockito:mockito-all:jar:1.10.19)
end
def jackson_annotations
%w(com.fasterxml.jackson.core:jackson-annotations:jar:2.5.4)
end
def jackson_core
%w(com.fasterxml.jackson.core:jackson-core:jar:2.5.4)
end
def jackson_databind
%w(com.fasterxml.jackson.core:jackson-databind:jar:2.5.4)
end
def jackson_gwt_support
self.jackson_core + self.jackson_databind + self.jackson_annotations
end
def jsinterop
%w(com.google.jsinterop:jsinterop-annotations:jar:1.0.1 com.google.jsinterop:jsinterop-annotations:jar:sources:1.0.1)
end
def gwt_user
%w(com.google.gwt:gwt-user:jar:2.8.0 org.w3c.css:sac:jar:1.3) + self.jsinterop
end
def gwt_servlet
%w(com.google.gwt:gwt-servlet:jar:2.8.0)
end
def gwt_dev
'com.google.gwt:gwt-dev:jar:2.8.0'
end
def javax_inject
%w(javax.inject:javax.inject:jar:1)
end
def gwt_gin
%w(com.google.gwt.inject:gin:jar:2.1.2) + self.javax_inject + self.guice + self.gwt_user
end
def gwt_property_source
%w(org.realityforge.gwt.property-source:gwt-property-source:jar:0.2)
end
def gwt_webpoller
%w(org.realityforge.gwt.webpoller:gwt-webpoller:jar:0.9.2)
end
def gwt_datatypes
%w(org.realityforge.gwt.datatypes:gwt-datatypes:jar:0.8)
end
def gwt_ga
%w(org.realityforge.gwt.ga:gwt-ga:jar:0.5)
end
def gwt_mmvp
%w(org.realityforge.gwt.mmvp:gwt-mmvp:jar:0.5)
end
def gwt_lognice
%w(org.realityforge.gwt.lognice:gwt-lognice:jar:0.4)
end
def gwt_appcache_client
%w(org.realityforge.gwt.appcache:gwt-appcache-client:jar:1.0.9 org.realityforge.gwt.appcache:gwt-appcache-linker:jar:1.0.9)
end
def gwt_appcache_server
%w(org.realityforge.gwt.appcache:gwt-appcache-server:jar:1.0.9)
end
# The appcache code required to exist on gwt path during compilation
def gwt_appcache
self.gwt_appcache_client + self.gwt_appcache_server
end
def gwt_cache_filter
%w(org.realityforge.gwt.cache-filter:gwt-cache-filter:jar:0.7)
end
def simple_session_filter
%w(org.realityforge.ssf:simple-session-filter:jar:0.7)
end
def field_filter
%w(org.realityforge.rest.field_filter:rest-field-filter:jar:0.4)
end
def rest_criteria
%w(org.realityforge.rest.criteria:rest-criteria:jar:0.9.4 org.antlr:antlr4-runtime:jar:4.3 org.antlr:antlr4-annotations:jar:4.3) + self.field_filter
end
def commons_logging
%w(commons-logging:commons-logging:jar:1.2)
end
def commons_codec
%w(commons-codec:commons-codec:jar:1.9)
end
def bouncycastle
%w(org.bouncycastle:bcprov-jdk15on:jar:1.52 org.bouncycastle:bcpkix-jdk15on:jar:1.52)
end
def proxy_servlet
self.httpclient + %w(org.realityforge.proxy-servlet:proxy-servlet:jar:0.2.0)
end
def httpclient
%w(org.apache.httpcomponents:httpclient:jar:4.5 org.apache.httpcomponents:httpcore:jar:4.4.1) +
self.commons_logging + self.commons_codec
end
def keycloak_gwt
%w(org.realityforge.gwt.keycloak:gwt-keycloak:jar:0.1)
end
def keycloak_domgen_support
%w(org.realityforge.keycloak.domgen:keycloak-domgen-support:jar:1.3)
end
def jboss_logging
%w(org.jboss.logging:jboss-logging:jar:3.3.0.Final)
end
def keycloak_core
%w(
org.keycloak:keycloak-core:jar:2.0.0.Final
org.keycloak:keycloak-common:jar:2.0.0.Final
) + self.bouncycastle
end
def keycloak
%w(
org.keycloak:keycloak-servlet-filter-adapter:jar:2.0.0.Final
org.keycloak:keycloak-adapter-spi:jar:2.0.0.Final
org.keycloak:keycloak-adapter-core:jar:2.0.0.Final
org.realityforge.org.keycloak:keycloak-servlet-adapter-spi:jar:2.0.0.Final
) + self.keycloak_core + self.keycloak_domgen_support + self.httpclient + self.jboss_logging
end
def replicant_version
'0.5.71'
end
def replicant_shared
%W(org.realityforge.replicant:replicant-shared:jar:#{replicant_version})
end
def replicant_client_common
%W(org.realityforge.replicant:replicant-client-common:jar:#{replicant_version}) + self.replicant_shared + self.gwt_webpoller + self.gwt_datatypes
end
def replicant_client_qa_support
%W(org.realityforge.replicant:replicant-client-qa-support:jar:#{replicant_version}) + self.guiceyloops_gwt
end
def replicant_ee_client
%W(org.realityforge.replicant:replicant-client-ee:jar:#{replicant_version}) + self.replicant_client_common
end
def replicant_gwt_client
%W(org.realityforge.replicant:replicant-client-gwt:jar:#{replicant_version}) + self.replicant_client_common + self.gwt_property_source
end
def replicant_server
%W(org.realityforge.replicant:replicant-server:jar:#{replicant_version}) + self.replicant_shared + self.simple_session_filter + self.gwt_rpc + self.field_filter
end
def gwt_rpc
self.gwt_datatypes + self.jackson_gwt_support + self.gwt_servlet
end
def guice
%w(aopalliance:aopalliance:jar:1.0 com.google.inject:guice:jar:3.0 com.google.inject.extensions:guice-assistedinject:jar:3.0)
end
def awaitility
%w(org.awaitility:awaitility:jar:2.0.0)
end
def testng
%w(org.testng:testng:jar:6.8)
end
def jndikit
%w(org.realityforge.jndikit:jndikit:jar:1.4)
end
def guiceyloops
self.glassfish_embedded + self.guiceyloops_gwt
end
def guiceyloops_lib
'org.realityforge.guiceyloops:guiceyloops:jar:0.83'
end
def guiceyloops_gwt
[guiceyloops_lib] + self.mockito + self.guice + self.testng
end
def glassfish_timers_domain
%W(org.realityforge.glassfish.timers#{BuildrPlus::Db.pgsql? ? '.pg' : ''}:glassfish-timers-domain:json:0.4)
end
def glassfish_timers_db
%W(org.realityforge.glassfish.timers#{BuildrPlus::Db.pgsql? ? '.pg' : ''}:glassfish-timers-db:jar:0.4)
end
def slf4j
%w(org.slf4j:slf4j-api:jar:1.6.6 org.slf4j:slf4j-jdk14:jar:1.6.6)
end
def greenmail
%w(com.icegreen:greenmail:jar:1.4.1) + self.slf4j
end
def greenmail_server
'com.icegreen:greenmail-webapp:war:1.4.1'
end
def jtds
%w(net.sourceforge.jtds:jtds:jar:1.3.1)
end
def postgresql
%w(org.postgresql:postgresql:jar:9.2-1003-jdbc4)
end
def postgis
%w(org.postgis:postgis-jdbc:jar:1.3.3)
end
def db_drivers
return self.jtds if BuildrPlus::Db.mssql?
return self.postgresql + (BuildrPlus::FeatureManager.activated?(:geolatte) ? self.postgis : []) if BuildrPlus::Db.pgsql?
[]
end
end
end
|
require File.dirname(__FILE__) + '/../capistrano-helpers' if ! defined?(CapistranoHelpers)
begin
# Campfire API gem for deploy notifications.
gem 'tinder', '>= 1.4.0'
require 'tinder'
rescue LoadError
abort "The campfire helper requires the tinder gem. Install it with: sudo gem install tinder"
end
CapistranoHelpers.with_configuration do
namespace :deploy do
desc 'Make a post to campfire to tell everyone about this deployment.'
task :post_to_campfire do
if !exists?(:application)
puts "You should set :application to the name of this app."
end
username = `whoami`.chomp
config_file = fetch(:campfire_config, 'config/campfire.yml')
config = YAML::load_file(config_file)
campfire = Tinder::Campfire.new(config['account'], :username => config['email'], :password => config['password'])
room = campfire.find_room_by_name(config['room'])
room.speak("#{username} just deployed #{application} #{branch} to #{stage}")
room.leave
end
end
after "deploy:restart", "deploy:post_to_campfire"
end
Tolerate a missing campfire.yml.
require File.dirname(__FILE__) + '/../capistrano-helpers' if ! defined?(CapistranoHelpers)
begin
# Campfire API gem for deploy notifications.
gem 'tinder', '>= 1.4.0'
require 'tinder'
rescue LoadError
abort "The campfire helper requires the tinder gem. Install it with: sudo gem install tinder"
end
CapistranoHelpers.with_configuration do
namespace :deploy do
desc 'Make a post to campfire to tell everyone about this deployment.'
task :post_to_campfire do
if !exists?(:application)
puts "You should set :application to the name of this app."
end
username = `whoami`.chomp
config_file = fetch(:campfire_config, 'config/campfire.yml')
begin
config = YAML::load_file(config_file)
campfire = Tinder::Campfire.new(config['account'], :username => config['email'], :password => config['password'])
room = campfire.find_room_by_name(config['room'])
room.speak("#{username} just deployed #{application} #{branch} to #{stage}")
room.leave
rescue Errno::ENOENT
puts "Could not open config/campfire.yml. Skipping campfire notification."
end
end
end
after "deploy:restart", "deploy:post_to_campfire"
end |
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
BuildrPlus::FeatureManager.feature(:libs) do |f|
f.enhance(:Config) do
def mustache
%w(com.github.spullara.mustache.java:compiler:jar:0.8.15)
end
def javacsv
%w(net.sourceforge.javacsv:javacsv:jar:2.1)
end
def geotools_for_geolatte
%w(org.geotools:gt-main:jar:9.4 org.geotools:gt-metadata:jar:9.4 org.geotools:gt-api:jar:9.4 org.geotools:gt-epsg-wkt:jar:9.4 org.geotools:gt-opengis:jar:9.4 org.geotools:gt-transform:jar:9.4 org.geotools:gt-geometry:jar:9.4 org.geotools:gt-jts-wrapper:jar:9.4 org.geotools:gt-referencing:jar:9.4 net.java.dev.jsr-275:jsr-275:jar:1.0-beta-2 java3d:vecmath:jar:1.3.2 javax.media:jai_core:jar:1.1.3)
end
def jts
%w(com.vividsolutions:jts:jar:1.13)
end
# Support geo libraries for geolatte
def geolatte_support
self.jts + self.slf4j
end
def geolatte_geom
%w(org.geolatte:geolatte-geom:jar:0.13)
end
def geolatte_geom_jpa
%w(org.realityforge.geolatte.jpa:geolatte-geom-jpa:jar:0.2)
end
def jetbrains_annotations
%w(org.realityforge.org.jetbrains.annotations:org.jetbrains.annotations:jar:1.0.0)
end
def javax_annotations
%w(org.realityforge.javax.annotation:javax.annotation:jar:1.0.0)
end
def spotbugs_provided
%w(com.github.spotbugs:spotbugs-annotations:jar:3.1.5 net.jcip:jcip-annotations:jar:1.0) + self.javax_annotations
end
def ee_provided
%w(javax:javaee-api:jar:7.0) + self.spotbugs_provided + self.jetbrains_annotations
end
def glassfish_embedded
%w(fish.payara.extras:payara-embedded-all:jar:4.1.2.172 fish.payara.api:payara-api:jar:4.1.2.172)
end
def eclipselink
'org.eclipse.persistence:eclipselink:jar:2.6.0'
end
def mockito
%w(org.mockito:mockito-all:jar:1.10.19)
end
def jackson_annotations
%w(com.fasterxml.jackson.core:jackson-annotations:jar:2.8.8)
end
def jackson_core
%w(com.fasterxml.jackson.core:jackson-core:jar:2.8.8)
end
def jackson_databind
%w(com.fasterxml.jackson.core:jackson-databind:jar:2.8.8)
end
def jackson_datatype_jdk8
%w(com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar:2.8.8)
end
def jackson_module_kotlin
%w(com.fasterxml.jackson.module:jackson-module-kotlin:jar:2.8.8)
end
def jackson_gwt_support
self.jackson_core + self.jackson_databind + self.jackson_annotations
end
def braincheck
%w(org.realityforge.braincheck:braincheck:jar:1.16.0)
end
def jsinterop
%w(com.google.jsinterop:jsinterop-annotations:jar:1.0.2)
end
def jsinterop_base
%w(org.realityforge.com.google.jsinterop:base:jar:1.0.0-b2-e6d791f) + self.jsinterop
end
def elemental2_version
'2.23'
end
def elemental2_group_id
'org.realityforge.com.google.elemental2'
end
def elemental2_core
%W(#{elemental2_group_id}:elemental2-core:jar:#{elemental2_version}) + self.jsinterop_base
end
def elemental2_dom
%W(#{elemental2_group_id}:elemental2-dom:jar:#{elemental2_version}) + self.elemental2_promise
end
def elemental2_promise
%W(#{elemental2_group_id}:elemental2-promise:jar:#{elemental2_version}) + self.elemental2_core
end
def elemental2_webstorage
%W(#{elemental2_group_id}:elemental2-webstorage:jar:#{elemental2_version}) + self.elemental2_dom
end
def gwt_user
%w(com.google.gwt:gwt-user:jar:2.8.2 org.w3c.css:sac:jar:1.3) + self.jsinterop
end
def gwt_servlet
%w(com.google.gwt:gwt-servlet:jar:2.8.2)
end
def gwt_dev
'com.google.gwt:gwt-dev:jar:2.8.2'
end
def javax_inject
%w(javax.inject:javax.inject:jar:1)
end
def javax_inject_gwt
%w(javax.inject:javax.inject:jar:sources:1) + self.javax_inject
end
def gwt_appcache_client
%w(org.realityforge.gwt.appcache:gwt-appcache-linker:jar:1.0.12)
end
def gwt_appcache_server
%w(org.realityforge.gwt.appcache:gwt-appcache-server:jar:1.0.12)
end
# The appcache code required to exist on gwt path during compilation
def gwt_appcache
self.gwt_appcache_client + self.gwt_appcache_server
end
def gwt_cache_filter
%w(org.realityforge.gwt.cache-filter:gwt-cache-filter:jar:0.7)
end
def field_filter
%w(org.realityforge.rest.field_filter:rest-field-filter:jar:0.4)
end
def timeservice
%w(org.realityforge.timeservice:timeservice:jar:0.01)
end
def graphql_java
%w(com.graphql-java:graphql-java:jar:3.0.0) + self.slf4j + self.antlr4_runtime
end
def graphql_java_tools
%w(
com.esotericsoftware:reflectasm:jar:1.11.3
com.graphql-java:graphql-java-tools:jar:3.2.1
org.jetbrains.kotlin:kotlin-reflect:jar:1.1.1
org.jetbrains.kotlin:kotlin-stdlib:jar:1.1.1
org.jetbrains.kotlin:kotlin-stdlib:jar:1.1.3-2
org.ow2.asm:asm:jar:5.0.4
ru.vyarus:generics-resolver:jar:2.0.1
) + self.graphql_java +
self.jackson_annotations +
self.jackson_core +
self.jackson_databind +
self.jackson_datatype_jdk8 +
self.jackson_module_kotlin +
self.guava + # Expected 21.0
self.jetbrains_annotations
end
def graphql_java_servlet
%w(
com.graphql-java:graphql-java-servlet:jar:4.0.0
commons-fileupload:commons-fileupload:jar:1.3.3
commons-io:commons-io:jar:2.5
) + self.graphql_java_tools
end
def graphql_domgen_support
%w(org.realityforge.keycloak.domgen:graphql-domgen-support:jar:1.2.0)
end
def antlr4_runtime
%w(org.antlr:antlr4-runtime:jar:4.5.1)
end
def rest_criteria
%w(org.realityforge.rest.criteria:rest-criteria:jar:0.9.6) +
self.antlr4_runtime +
self.field_filter
end
def commons_logging
%w(commons-logging:commons-logging:jar:1.2)
end
def commons_codec
%w(commons-codec:commons-codec:jar:1.9)
end
def bouncycastle
%w(org.bouncycastle:bcprov-jdk15on:jar:1.52 org.bouncycastle:bcpkix-jdk15on:jar:1.52)
end
def proxy_servlet
self.httpclient + %w(org.realityforge.proxy-servlet:proxy-servlet:jar:0.2.0)
end
def httpclient
%w(org.apache.httpcomponents:httpclient:jar:4.5 org.apache.httpcomponents:httpcore:jar:4.4.1) +
self.commons_logging + self.commons_codec
end
def failsafe
%w(net.jodah:failsafe:jar:1.0.3)
end
def keycloak_gwt
%w(org.realityforge.gwt.keycloak:gwt-keycloak:jar:0.4) + self.elemental2_webstorage
end
def keycloak_domgen_support
%w(org.realityforge.keycloak.domgen:keycloak-domgen-support:jar:1.4)
end
def keycloak_authfilter
%w(org.realityforge.keycloak.client.authfilter:keycloak-jaxrs-client-authfilter:jar:0.2)
end
def keycloak_converger
'org.realityforge.keycloak.converger:keycloak-converger:jar:1.8'
end
def jboss_logging
%w(org.jboss.logging:jboss-logging:jar:3.3.0.Final)
end
def keycloak_core
%w(
org.keycloak:keycloak-core:jar:2.0.0.Final
org.keycloak:keycloak-common:jar:2.0.0.Final
) + self.bouncycastle
end
def keycloak
%w(
org.keycloak:keycloak-servlet-filter-adapter:jar:2.0.0.Final
org.keycloak:keycloak-adapter-spi:jar:2.0.0.Final
org.keycloak:keycloak-adapter-core:jar:2.0.0.Final
org.realityforge.org.keycloak:keycloak-servlet-adapter-spi:jar:2.0.0.Final
) + self.keycloak_core + self.keycloak_domgen_support + self.httpclient + self.jboss_logging
end
def simple_keycloak_service
%w(org.realityforge.keycloak.sks:simple-keycloak-service:jar:0.1)
end
def guava
%w(com.google.guava:guava:jar:25.0-jre)
end
def javapoet
%w(com.squareup:javapoet:jar:1.11.1) + self.guava
end
def arez_version
'0.136'
end
def arez
%W(org.realityforge.arez:arez-core:jar:#{arez_version}) + self.braincheck
end
def arez_processor
%W(org.realityforge.arez:arez-processor:jar:#{arez_version})
end
def arez_spytools
%w(org.realityforge.arez.spytools:arez-spytools:jar:0.56)
end
def router_fu_version
'0.17'
end
def router_fu
%W(org.realityforge.router.fu:router-fu-core:jar:#{router_fu_version}) + self.braincheck
end
def router_fu_processor
%W(org.realityforge.router.fu:router-fu-processor:jar:#{router_fu_version})
end
def react4j_version
'0.125'
end
def react4j
%W(
org.realityforge.react4j:react4j-core:jar:#{react4j_version}
org.realityforge.react4j:react4j-dom:jar:#{react4j_version}
) + self.elemental2_dom + self.elemental2_promise
end
def react4j_processor
%W(org.realityforge.react4j:react4j-processor:jar:#{react4j_version})
end
def replicant_version
'6.42'
end
def replicant_client
%W(org.realityforge.replicant:replicant-client:jar:#{replicant_version}) + self.elemental2_webstorage
end
def replicant_server
%W(org.realityforge.replicant:replicant-server:jar:#{replicant_version}) + self.gwt_rpc
end
def gwt_rpc
self.jackson_gwt_support + self.gwt_servlet
end
def guice
%w(aopalliance:aopalliance:jar:1.0 org.ow2.asm:asm:jar:5.0.3 au.com.stocksoftware.com.google.inject:guice:jar:4.1.1-stock)
end
def awaitility
%w(org.awaitility:awaitility:jar:2.0.0)
end
def dagger_version
'2.19'
end
def dagger_compile
%W(com.google.dagger:dagger:jar:#{dagger_version})
end
def dagger
self.dagger_compile + self.javax_inject
end
def dagger_compiler
%W(
com.google.dagger:dagger-spi:jar:#{dagger_version}
com.google.dagger:dagger-producers:jar:#{dagger_version}
com.google.dagger:dagger-compiler:jar:#{dagger_version}
com.google.googlejavaformat:google-java-format:jar:1.5
com.google.errorprone:javac-shaded:jar:9-dev-r4023-3
) + self.javapoet + self.dagger
end
def dagger_gwt
%w(org.realityforge.dagger:dagger-gwt-lite:jar:2.19-rf1) + self.javax_inject_gwt
end
def testng_version
'6.11'
end
def testng
%W(org.testng:testng:jar:#{testng_version})
end
def jndikit
%w(org.realityforge.jndikit:jndikit:jar:1.4)
end
def guiceyloops
self.guiceyloops_gwt + self.glassfish_embedded
end
def guiceyloops_lib
'org.realityforge.guiceyloops:guiceyloops:jar:0.98'
end
def guiceyloops_gwt
[guiceyloops_lib] + self.mockito + self.guice + self.testng
end
def glassfish_timers_domain
%W(org.realityforge.glassfish.timers#{BuildrPlus::Db.pgsql? ? '.pg' : ''}:glassfish-timers-domain:json:0.6)
end
def glassfish_timers_db
%W(org.realityforge.glassfish.timers#{BuildrPlus::Db.pgsql? ? '.pg' : ''}:glassfish-timers-db:jar:0.6)
end
def slf4j
%w(org.slf4j:slf4j-api:jar:1.6.6 org.slf4j:slf4j-jdk14:jar:1.6.6)
end
def greenmail
%w(com.icegreen:greenmail:jar:1.4.1) + self.slf4j
end
def greenmail_server
'com.icegreen:greenmail-webapp:war:1.4.1'
end
def jtds
%w(net.sourceforge.jtds:jtds:jar:1.3.1)
end
def postgresql
%w(org.postgresql:postgresql:jar:9.2-1003-jdbc4)
end
def postgis
%w(org.postgis:postgis-jdbc:jar:1.3.3)
end
def db_drivers
return self.jtds if BuildrPlus::Db.mssql?
return self.postgresql + (BuildrPlus::FeatureManager.activated?(:geolatte) ? self.postgis : []) if BuildrPlus::Db.pgsql?
[]
end
end
end
Update the version of arez
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
BuildrPlus::FeatureManager.feature(:libs) do |f|
f.enhance(:Config) do
def mustache
%w(com.github.spullara.mustache.java:compiler:jar:0.8.15)
end
def javacsv
%w(net.sourceforge.javacsv:javacsv:jar:2.1)
end
def geotools_for_geolatte
%w(org.geotools:gt-main:jar:9.4 org.geotools:gt-metadata:jar:9.4 org.geotools:gt-api:jar:9.4 org.geotools:gt-epsg-wkt:jar:9.4 org.geotools:gt-opengis:jar:9.4 org.geotools:gt-transform:jar:9.4 org.geotools:gt-geometry:jar:9.4 org.geotools:gt-jts-wrapper:jar:9.4 org.geotools:gt-referencing:jar:9.4 net.java.dev.jsr-275:jsr-275:jar:1.0-beta-2 java3d:vecmath:jar:1.3.2 javax.media:jai_core:jar:1.1.3)
end
def jts
%w(com.vividsolutions:jts:jar:1.13)
end
# Support geo libraries for geolatte
def geolatte_support
self.jts + self.slf4j
end
def geolatte_geom
%w(org.geolatte:geolatte-geom:jar:0.13)
end
def geolatte_geom_jpa
%w(org.realityforge.geolatte.jpa:geolatte-geom-jpa:jar:0.2)
end
def jetbrains_annotations
%w(org.realityforge.org.jetbrains.annotations:org.jetbrains.annotations:jar:1.0.0)
end
def javax_annotations
%w(org.realityforge.javax.annotation:javax.annotation:jar:1.0.0)
end
def spotbugs_provided
%w(com.github.spotbugs:spotbugs-annotations:jar:3.1.5 net.jcip:jcip-annotations:jar:1.0) + self.javax_annotations
end
def ee_provided
%w(javax:javaee-api:jar:7.0) + self.spotbugs_provided + self.jetbrains_annotations
end
def glassfish_embedded
%w(fish.payara.extras:payara-embedded-all:jar:4.1.2.172 fish.payara.api:payara-api:jar:4.1.2.172)
end
def eclipselink
'org.eclipse.persistence:eclipselink:jar:2.6.0'
end
def mockito
%w(org.mockito:mockito-all:jar:1.10.19)
end
def jackson_annotations
%w(com.fasterxml.jackson.core:jackson-annotations:jar:2.8.8)
end
def jackson_core
%w(com.fasterxml.jackson.core:jackson-core:jar:2.8.8)
end
def jackson_databind
%w(com.fasterxml.jackson.core:jackson-databind:jar:2.8.8)
end
def jackson_datatype_jdk8
%w(com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar:2.8.8)
end
def jackson_module_kotlin
%w(com.fasterxml.jackson.module:jackson-module-kotlin:jar:2.8.8)
end
def jackson_gwt_support
self.jackson_core + self.jackson_databind + self.jackson_annotations
end
def braincheck
%w(org.realityforge.braincheck:braincheck:jar:1.16.0)
end
def jsinterop
%w(com.google.jsinterop:jsinterop-annotations:jar:1.0.2)
end
def jsinterop_base
%w(org.realityforge.com.google.jsinterop:base:jar:1.0.0-b2-e6d791f) + self.jsinterop
end
def elemental2_version
'2.23'
end
def elemental2_group_id
'org.realityforge.com.google.elemental2'
end
def elemental2_core
%W(#{elemental2_group_id}:elemental2-core:jar:#{elemental2_version}) + self.jsinterop_base
end
def elemental2_dom
%W(#{elemental2_group_id}:elemental2-dom:jar:#{elemental2_version}) + self.elemental2_promise
end
def elemental2_promise
%W(#{elemental2_group_id}:elemental2-promise:jar:#{elemental2_version}) + self.elemental2_core
end
def elemental2_webstorage
%W(#{elemental2_group_id}:elemental2-webstorage:jar:#{elemental2_version}) + self.elemental2_dom
end
def gwt_user
%w(com.google.gwt:gwt-user:jar:2.8.2 org.w3c.css:sac:jar:1.3) + self.jsinterop
end
def gwt_servlet
%w(com.google.gwt:gwt-servlet:jar:2.8.2)
end
def gwt_dev
'com.google.gwt:gwt-dev:jar:2.8.2'
end
def javax_inject
%w(javax.inject:javax.inject:jar:1)
end
def javax_inject_gwt
%w(javax.inject:javax.inject:jar:sources:1) + self.javax_inject
end
def gwt_appcache_client
%w(org.realityforge.gwt.appcache:gwt-appcache-linker:jar:1.0.12)
end
def gwt_appcache_server
%w(org.realityforge.gwt.appcache:gwt-appcache-server:jar:1.0.12)
end
# The appcache code required to exist on gwt path during compilation
def gwt_appcache
self.gwt_appcache_client + self.gwt_appcache_server
end
def gwt_cache_filter
%w(org.realityforge.gwt.cache-filter:gwt-cache-filter:jar:0.7)
end
def field_filter
%w(org.realityforge.rest.field_filter:rest-field-filter:jar:0.4)
end
def timeservice
%w(org.realityforge.timeservice:timeservice:jar:0.01)
end
def graphql_java
%w(com.graphql-java:graphql-java:jar:3.0.0) + self.slf4j + self.antlr4_runtime
end
def graphql_java_tools
%w(
com.esotericsoftware:reflectasm:jar:1.11.3
com.graphql-java:graphql-java-tools:jar:3.2.1
org.jetbrains.kotlin:kotlin-reflect:jar:1.1.1
org.jetbrains.kotlin:kotlin-stdlib:jar:1.1.1
org.jetbrains.kotlin:kotlin-stdlib:jar:1.1.3-2
org.ow2.asm:asm:jar:5.0.4
ru.vyarus:generics-resolver:jar:2.0.1
) + self.graphql_java +
self.jackson_annotations +
self.jackson_core +
self.jackson_databind +
self.jackson_datatype_jdk8 +
self.jackson_module_kotlin +
self.guava + # Expected 21.0
self.jetbrains_annotations
end
def graphql_java_servlet
%w(
com.graphql-java:graphql-java-servlet:jar:4.0.0
commons-fileupload:commons-fileupload:jar:1.3.3
commons-io:commons-io:jar:2.5
) + self.graphql_java_tools
end
def graphql_domgen_support
%w(org.realityforge.keycloak.domgen:graphql-domgen-support:jar:1.2.0)
end
def antlr4_runtime
%w(org.antlr:antlr4-runtime:jar:4.5.1)
end
def rest_criteria
%w(org.realityforge.rest.criteria:rest-criteria:jar:0.9.6) +
self.antlr4_runtime +
self.field_filter
end
def commons_logging
%w(commons-logging:commons-logging:jar:1.2)
end
def commons_codec
%w(commons-codec:commons-codec:jar:1.9)
end
def bouncycastle
%w(org.bouncycastle:bcprov-jdk15on:jar:1.52 org.bouncycastle:bcpkix-jdk15on:jar:1.52)
end
def proxy_servlet
self.httpclient + %w(org.realityforge.proxy-servlet:proxy-servlet:jar:0.2.0)
end
def httpclient
%w(org.apache.httpcomponents:httpclient:jar:4.5 org.apache.httpcomponents:httpcore:jar:4.4.1) +
self.commons_logging + self.commons_codec
end
def failsafe
%w(net.jodah:failsafe:jar:1.0.3)
end
def keycloak_gwt
%w(org.realityforge.gwt.keycloak:gwt-keycloak:jar:0.4) + self.elemental2_webstorage
end
def keycloak_domgen_support
%w(org.realityforge.keycloak.domgen:keycloak-domgen-support:jar:1.4)
end
def keycloak_authfilter
%w(org.realityforge.keycloak.client.authfilter:keycloak-jaxrs-client-authfilter:jar:0.2)
end
def keycloak_converger
'org.realityforge.keycloak.converger:keycloak-converger:jar:1.8'
end
def jboss_logging
%w(org.jboss.logging:jboss-logging:jar:3.3.0.Final)
end
def keycloak_core
%w(
org.keycloak:keycloak-core:jar:2.0.0.Final
org.keycloak:keycloak-common:jar:2.0.0.Final
) + self.bouncycastle
end
def keycloak
%w(
org.keycloak:keycloak-servlet-filter-adapter:jar:2.0.0.Final
org.keycloak:keycloak-adapter-spi:jar:2.0.0.Final
org.keycloak:keycloak-adapter-core:jar:2.0.0.Final
org.realityforge.org.keycloak:keycloak-servlet-adapter-spi:jar:2.0.0.Final
) + self.keycloak_core + self.keycloak_domgen_support + self.httpclient + self.jboss_logging
end
def simple_keycloak_service
%w(org.realityforge.keycloak.sks:simple-keycloak-service:jar:0.1)
end
def guava
%w(com.google.guava:guava:jar:25.0-jre)
end
def javapoet
%w(com.squareup:javapoet:jar:1.11.1) + self.guava
end
def arez_version
'0.137'
end
def arez
%W(org.realityforge.arez:arez-core:jar:#{arez_version}) + self.braincheck
end
def arez_processor
%W(org.realityforge.arez:arez-processor:jar:#{arez_version})
end
def arez_spytools
%w(org.realityforge.arez.spytools:arez-spytools:jar:0.56)
end
def router_fu_version
'0.17'
end
def router_fu
%W(org.realityforge.router.fu:router-fu-core:jar:#{router_fu_version}) + self.braincheck
end
def router_fu_processor
%W(org.realityforge.router.fu:router-fu-processor:jar:#{router_fu_version})
end
def react4j_version
'0.125'
end
def react4j
%W(
org.realityforge.react4j:react4j-core:jar:#{react4j_version}
org.realityforge.react4j:react4j-dom:jar:#{react4j_version}
) + self.elemental2_dom + self.elemental2_promise
end
def react4j_processor
%W(org.realityforge.react4j:react4j-processor:jar:#{react4j_version})
end
def replicant_version
'6.42'
end
def replicant_client
%W(org.realityforge.replicant:replicant-client:jar:#{replicant_version}) + self.elemental2_webstorage
end
def replicant_server
%W(org.realityforge.replicant:replicant-server:jar:#{replicant_version}) + self.gwt_rpc
end
def gwt_rpc
self.jackson_gwt_support + self.gwt_servlet
end
def guice
%w(aopalliance:aopalliance:jar:1.0 org.ow2.asm:asm:jar:5.0.3 au.com.stocksoftware.com.google.inject:guice:jar:4.1.1-stock)
end
def awaitility
%w(org.awaitility:awaitility:jar:2.0.0)
end
def dagger_version
'2.19'
end
def dagger_compile
%W(com.google.dagger:dagger:jar:#{dagger_version})
end
def dagger
self.dagger_compile + self.javax_inject
end
def dagger_compiler
%W(
com.google.dagger:dagger-spi:jar:#{dagger_version}
com.google.dagger:dagger-producers:jar:#{dagger_version}
com.google.dagger:dagger-compiler:jar:#{dagger_version}
com.google.googlejavaformat:google-java-format:jar:1.5
com.google.errorprone:javac-shaded:jar:9-dev-r4023-3
) + self.javapoet + self.dagger
end
def dagger_gwt
%w(org.realityforge.dagger:dagger-gwt-lite:jar:2.19-rf1) + self.javax_inject_gwt
end
def testng_version
'6.11'
end
def testng
%W(org.testng:testng:jar:#{testng_version})
end
def jndikit
%w(org.realityforge.jndikit:jndikit:jar:1.4)
end
def guiceyloops
self.guiceyloops_gwt + self.glassfish_embedded
end
def guiceyloops_lib
'org.realityforge.guiceyloops:guiceyloops:jar:0.98'
end
def guiceyloops_gwt
[guiceyloops_lib] + self.mockito + self.guice + self.testng
end
def glassfish_timers_domain
%W(org.realityforge.glassfish.timers#{BuildrPlus::Db.pgsql? ? '.pg' : ''}:glassfish-timers-domain:json:0.6)
end
def glassfish_timers_db
%W(org.realityforge.glassfish.timers#{BuildrPlus::Db.pgsql? ? '.pg' : ''}:glassfish-timers-db:jar:0.6)
end
def slf4j
%w(org.slf4j:slf4j-api:jar:1.6.6 org.slf4j:slf4j-jdk14:jar:1.6.6)
end
def greenmail
%w(com.icegreen:greenmail:jar:1.4.1) + self.slf4j
end
def greenmail_server
'com.icegreen:greenmail-webapp:war:1.4.1'
end
def jtds
%w(net.sourceforge.jtds:jtds:jar:1.3.1)
end
def postgresql
%w(org.postgresql:postgresql:jar:9.2-1003-jdbc4)
end
def postgis
%w(org.postgis:postgis-jdbc:jar:1.3.3)
end
def db_drivers
return self.jtds if BuildrPlus::Db.mssql?
return self.postgresql + (BuildrPlus::FeatureManager.activated?(:geolatte) ? self.postgis : []) if BuildrPlus::Db.pgsql?
[]
end
end
end
|
module ArduinoFirmata
class Arduino
include EventEmitter
attr_reader :version, :status, :nonblock_io, :eventmachine
def initialize(serialport_name, params)
@serialport_name = serialport_name
@nonblock_io = !!params[:nonblock_io]
@eventmachine = !!params[:eventmachine]
@read_byte_size = eventmachine ? 256 : 9600
@process_input_interval = eventmachine ? 0.0001 : 0.01
@status = Status::CLOSE
@wait_for_data = 0
@execute_multi_byte_command = 0
@multi_byte_channel = 0
@stored_input_data = []
@parsing_sysex = false
@sysex_bytes_read = 0
@digital_output_data = Array.new(16, 0)
@digital_input_data = Array.new(16, 0)
@analog_input_data = Array.new(16, 0)
@version = nil
@serial = SerialPort.new(@serialport_name, params[:bps], params[:bit], params[:stopbit], params[:parity])
@serial.read_timeout = 10
sleep 3 if old_arduino_device?
@status = Status::OPEN
at_exit do
close
end
@thread_status = false
run do
@thread_status = true
while status == Status::OPEN do
process_input
sleep @process_input_interval
end
@thread_status = false
end
loop do
write REPORT_VERSION
sleep 0.5
break if @version
end
sleep 0.5 if old_arduino_device?
(0...6).each do |i|
write(REPORT_ANALOG | i)
write 1
end
(0...2).each do |i|
write(REPORT_DIGITAL | i)
write 1
end
end
def run(&block)
return unless block_given?
if eventmachine
EM::defer &block
else
Thread.new &block
end
end
def old_arduino_device?
File.basename(@serialport_name) =~ /^tty\.usbserial/ ? true : false
end
def close
return if status == Status::CLOSE
@status = Status::CLOSE
@serial.close
loop do
if @serial.closed? and @thread_status != true
break
end
sleep 0.01
end
end
def reset
write SYSTEM_RESET
end
def sysex(command, data=[])
## http://firmata.org/wiki/V2.1ProtocolDetails#Sysex_Message_Format
raise ArgumentError, 'command must be Number' unless command.kind_of? Fixnum
raise ArgumentError, 'data must be 7bit-Number or Those Array' unless [Fixnum, Array].include? data.class
write_data = data.kind_of?(Array) ? data : [data]
write START_SYSEX
write command
write_data.each do |d|
write (d & 0b1111111) # 7bit
end
write END_SYSEX
end
def digital_read(pin)
raise ArgumentError, "invalid pin number (#{pin})" if pin.class != Fixnum or pin < 0
(@digital_input_data[pin >> 3] >> (pin & 0x07)) & 0x01 > 0
end
def analog_read(pin)
raise ArgumentError, "invalid pin number (#{pin})" if pin.class != Fixnum or pin < 0
@analog_input_data[pin]
end
def pin_mode(pin, mode)
raise ArgumentError, "invalid pin number (#{pin})" if pin.class != Fixnum or pin < 0
write SET_PIN_MODE
write pin
mode = case mode
when true
OUTPUT
when false
INPUT
else
mode
end
if write(mode) == 1
return mode
end
end
def digital_write(pin, value)
raise ArgumentError, "invalid pin number (#{pin})" if pin.class != Fixnum or pin < 0
pin_mode pin, OUTPUT
port_num = (pin >> 3) & 0x0F
if value == 0 or value == false
@digital_output_data[port_num] &= ~(1 << (pin & 0x07))
else
@digital_output_data[port_num] |= (1 << (pin & 0x07))
end
write(DIGITAL_MESSAGE | port_num)
write(@digital_output_data[port_num] & 0x7F)
if write(@digital_output_data[port_num] >> 7) == 1
return value
end
end
def analog_write(pin, value)
raise ArgumentError, "invalid pin number (#{pin})" if pin.class != Fixnum or pin < 0
raise ArgumentError, "invalid analog value (#{value})" if value.class != Fixnum or value < 0
pin_mode pin, PWM
write(ANALOG_MESSAGE | (pin & 0x0F))
write(value & 0x7F)
if write(value >> 7) == 1
return value
end
end
def servo_write(pin, angle)
raise ArgumentError, "invalid pin number (#{pin})" if pin.class != Fixnum or pin < 0
raise ArgumentError, "invalid angle (#{angle})" if angle.class != Fixnum or angle < 0
pin_mode pin, SERVO
write(ANALOG_MESSAGE | (pin & 0x0F))
write(angle & 0x7F)
if write(angle >> 7) == 1
return angle
end
end
private
def write(cmd)
return if status == Status::CLOSE
if nonblock_io
begin
@serial.write_nonblock cmd.chr
rescue Errno::EAGAIN
sleep 0.1
retry
end
else
@serial.write cmd.chr
end
end
def read
return if status == Status::CLOSE
data = nil
begin
if nonblock_io
data = @serial.read_nonblock @read_byte_size
else
data = @serial.read @read_byte_size
end
rescue IOError, EOFError => e
end
data
end
def process_input
StringIO.new(String read).each_byte.each do |input_data|
command = nil
if @parsing_sysex
if input_data == END_SYSEX
@parsing_sysex = false
sysex_command = @stored_input_data[0]
sysex_data = @stored_input_data[1...@sysex_bytes_read]
emit :sysex, sysex_command, sysex_data
else
@stored_input_data[@sysex_bytes_read] = input_data
@sysex_bytes_read += 1
end
elsif @wait_for_data > 0 and input_data < 128
@wait_for_data -= 1
@stored_input_data[@wait_for_data] = input_data
if @execute_multi_byte_command != 0 and @wait_for_data == 0
case @execute_multi_byte_command
when DIGITAL_MESSAGE
input_data = (@stored_input_data[0] << 7) + @stored_input_data[1]
diff = @digital_input_data[@multi_byte_channel] ^ input_data
@digital_input_data[@multi_byte_channel] = input_data
0.upto(13).each do |i|
next unless (0x01 << i) & diff > 0
emit :digital_read, i, (input_data & diff > 0)
end
when ANALOG_MESSAGE
analog_value = (@stored_input_data[0] << 7) + @stored_input_data[1]
old = analog_read(@multi_byte_channel)
@analog_input_data[@multi_byte_channel] = analog_value
emit :analog_read, @multi_byte_channel, analog_value if old != analog_value
when REPORT_VERSION
@version = "#{@stored_input_data[1]}.#{@stored_input_data[0]}"
end
end
else
if input_data < 0xF0
command = input_data & 0xF0
@multi_byte_channel = input_data & 0x0F
else
command = input_data
end
if command == START_SYSEX
@parsing_sysex = true
@sysex_bytes_read = 0
elsif [DIGITAL_MESSAGE, ANALOG_MESSAGE, REPORT_VERSION].include? command
@wait_for_data = 2
@execute_multi_byte_command = command
end
end
end
end
end
end
fix regexp of Arduino#old_arduino_device?
module ArduinoFirmata
class Arduino
include EventEmitter
attr_reader :version, :status, :nonblock_io, :eventmachine
def initialize(serialport_name, params)
@serialport_name = serialport_name
@nonblock_io = !!params[:nonblock_io]
@eventmachine = !!params[:eventmachine]
@read_byte_size = eventmachine ? 256 : 9600
@process_input_interval = eventmachine ? 0.0001 : 0.01
@status = Status::CLOSE
@wait_for_data = 0
@execute_multi_byte_command = 0
@multi_byte_channel = 0
@stored_input_data = []
@parsing_sysex = false
@sysex_bytes_read = 0
@digital_output_data = Array.new(16, 0)
@digital_input_data = Array.new(16, 0)
@analog_input_data = Array.new(16, 0)
@version = nil
@serial = SerialPort.new(@serialport_name, params[:bps], params[:bit], params[:stopbit], params[:parity])
@serial.read_timeout = 10
sleep 3 if old_arduino_device?
@status = Status::OPEN
at_exit do
close
end
@thread_status = false
run do
@thread_status = true
while status == Status::OPEN do
process_input
sleep @process_input_interval
end
@thread_status = false
end
loop do
write REPORT_VERSION
sleep 0.5
break if @version
end
sleep 3 if old_arduino_device?
(0...6).each do |i|
write(REPORT_ANALOG | i)
write 1
end
(0...2).each do |i|
write(REPORT_DIGITAL | i)
write 1
end
end
def run(&block)
return unless block_given?
if eventmachine
EM::defer &block
else
Thread.new &block
end
end
def old_arduino_device?
File.basename(@serialport_name) =~ /tty\.usbserial|ttyUSB/ ? true : false
end
def close
return if status == Status::CLOSE
@status = Status::CLOSE
@serial.close
loop do
if @serial.closed? and @thread_status != true
break
end
sleep 0.01
end
end
def reset
write SYSTEM_RESET
end
def sysex(command, data=[])
## http://firmata.org/wiki/V2.1ProtocolDetails#Sysex_Message_Format
raise ArgumentError, 'command must be Number' unless command.kind_of? Fixnum
raise ArgumentError, 'data must be 7bit-Number or Those Array' unless [Fixnum, Array].include? data.class
write_data = data.kind_of?(Array) ? data : [data]
write START_SYSEX
write command
write_data.each do |d|
write (d & 0b1111111) # 7bit
end
write END_SYSEX
end
def digital_read(pin)
raise ArgumentError, "invalid pin number (#{pin})" if pin.class != Fixnum or pin < 0
(@digital_input_data[pin >> 3] >> (pin & 0x07)) & 0x01 > 0
end
def analog_read(pin)
raise ArgumentError, "invalid pin number (#{pin})" if pin.class != Fixnum or pin < 0
@analog_input_data[pin]
end
def pin_mode(pin, mode)
raise ArgumentError, "invalid pin number (#{pin})" if pin.class != Fixnum or pin < 0
write SET_PIN_MODE
write pin
mode = case mode
when true
OUTPUT
when false
INPUT
else
mode
end
if write(mode) == 1
return mode
end
end
def digital_write(pin, value)
raise ArgumentError, "invalid pin number (#{pin})" if pin.class != Fixnum or pin < 0
pin_mode pin, OUTPUT
port_num = (pin >> 3) & 0x0F
if value == 0 or value == false
@digital_output_data[port_num] &= ~(1 << (pin & 0x07))
else
@digital_output_data[port_num] |= (1 << (pin & 0x07))
end
write(DIGITAL_MESSAGE | port_num)
write(@digital_output_data[port_num] & 0x7F)
if write(@digital_output_data[port_num] >> 7) == 1
return value
end
end
def analog_write(pin, value)
raise ArgumentError, "invalid pin number (#{pin})" if pin.class != Fixnum or pin < 0
raise ArgumentError, "invalid analog value (#{value})" if value.class != Fixnum or value < 0
pin_mode pin, PWM
write(ANALOG_MESSAGE | (pin & 0x0F))
write(value & 0x7F)
if write(value >> 7) == 1
return value
end
end
def servo_write(pin, angle)
raise ArgumentError, "invalid pin number (#{pin})" if pin.class != Fixnum or pin < 0
raise ArgumentError, "invalid angle (#{angle})" if angle.class != Fixnum or angle < 0
pin_mode pin, SERVO
write(ANALOG_MESSAGE | (pin & 0x0F))
write(angle & 0x7F)
if write(angle >> 7) == 1
return angle
end
end
private
def write(cmd)
return if status == Status::CLOSE
if nonblock_io
begin
@serial.write_nonblock cmd.chr
rescue Errno::EAGAIN
sleep 0.1
retry
end
else
@serial.write cmd.chr
end
end
def read
return if status == Status::CLOSE
data = nil
begin
if nonblock_io
data = @serial.read_nonblock @read_byte_size
else
data = @serial.read @read_byte_size
end
rescue IOError, EOFError => e
end
data
end
def process_input
StringIO.new(String read).each_byte.each do |input_data|
command = nil
if @parsing_sysex
if input_data == END_SYSEX
@parsing_sysex = false
sysex_command = @stored_input_data[0]
sysex_data = @stored_input_data[1...@sysex_bytes_read]
emit :sysex, sysex_command, sysex_data
else
@stored_input_data[@sysex_bytes_read] = input_data
@sysex_bytes_read += 1
end
elsif @wait_for_data > 0 and input_data < 128
@wait_for_data -= 1
@stored_input_data[@wait_for_data] = input_data
if @execute_multi_byte_command != 0 and @wait_for_data == 0
case @execute_multi_byte_command
when DIGITAL_MESSAGE
input_data = (@stored_input_data[0] << 7) + @stored_input_data[1]
diff = @digital_input_data[@multi_byte_channel] ^ input_data
@digital_input_data[@multi_byte_channel] = input_data
0.upto(13).each do |i|
next unless (0x01 << i) & diff > 0
emit :digital_read, i, (input_data & diff > 0)
end
when ANALOG_MESSAGE
analog_value = (@stored_input_data[0] << 7) + @stored_input_data[1]
old = analog_read(@multi_byte_channel)
@analog_input_data[@multi_byte_channel] = analog_value
emit :analog_read, @multi_byte_channel, analog_value if old != analog_value
when REPORT_VERSION
@version = "#{@stored_input_data[1]}.#{@stored_input_data[0]}"
end
end
else
if input_data < 0xF0
command = input_data & 0xF0
@multi_byte_channel = input_data & 0x0F
else
command = input_data
end
if command == START_SYSEX
@parsing_sysex = true
@sysex_bytes_read = 0
elsif [DIGITAL_MESSAGE, ANALOG_MESSAGE, REPORT_VERSION].include? command
@wait_for_data = 2
@execute_multi_byte_command = command
end
end
end
end
end
end
|
# Librato username
set :librato_username, false
# Librato token
set :librato_token, false
# htpasswd user
set :htpasswd_user, "admin.#{fetch(:application)}"
# htpasswd password
set :htpasswd_user, "lephare"
# htpasswd whitelist
set :htpasswd_whitelist, []
# Tmp folder
set :tmp_dir, "/tmp/#{fetch(:stage)}"
# publish_assets
set :publish_assets, ENV["PUBLISH_ASSETS"] || false
# max db backups
set :keep_db_backups, 5
# database config file
set :database_config_file, -> { "#{fetch(:shared_path)}/app/config/parameters.yml" }
# Rollbar token
set :rollbar_token, false
set :mysqldump_args, "--opt --single-transaction"
set :db_pull_filename, "app/Resources/database/#{fetch(:stage)}.sql.bz2"
set :crontab_file -> { "#{release_path}/app/Resources/crontab" }
fix typo
# Librato username
set :librato_username, false
# Librato token
set :librato_token, false
# htpasswd user
set :htpasswd_user, "admin.#{fetch(:application)}"
# htpasswd password
set :htpasswd_user, "lephare"
# htpasswd whitelist
set :htpasswd_whitelist, []
# Tmp folder
set :tmp_dir, "/tmp/#{fetch(:stage)}"
# publish_assets
set :publish_assets, ENV["PUBLISH_ASSETS"] || false
# max db backups
set :keep_db_backups, 5
# database config file
set :database_config_file, -> { "#{fetch(:shared_path)}/app/config/parameters.yml" }
# Rollbar token
set :rollbar_token, false
set :mysqldump_args, "--opt --single-transaction"
set :db_pull_filename, "app/Resources/database/#{fetch(:stage)}.sql.bz2"
set :crontab_file, -> { "#{release_path}/app/Resources/crontab" }
|
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
BuildrPlus::FeatureManager.feature(:libs) do |f|
f.enhance(:Config) do
def mustache
%w(com.github.spullara.mustache.java:compiler:jar:0.8.15)
end
def javacsv
%w(net.sourceforge.javacsv:javacsv:jar:2.1)
end
def geotools_for_geolatte
%w(org.geotools:gt-main:jar:9.4 org.geotools:gt-metadata:jar:9.4 org.geotools:gt-api:jar:9.4 org.geotools:gt-epsg-wkt:jar:9.4 org.geotools:gt-opengis:jar:9.4 org.geotools:gt-transform:jar:9.4 org.geotools:gt-geometry:jar:9.4 org.geotools:gt-jts-wrapper:jar:9.4 org.geotools:gt-referencing:jar:9.4 net.java.dev.jsr-275:jsr-275:jar:1.0-beta-2 java3d:vecmath:jar:1.3.2 javax.media:jai_core:jar:1.1.3)
end
def jts
%w(com.vividsolutions:jts:jar:1.13)
end
# Support geo libraries for geolatte
def geolatte_support
self.jts + self.slf4j
end
def geolatte_geom
%w(org.geolatte:geolatte-geom:jar:0.13)
end
def geolatte_geom_jpa
%w(org.realityforge.geolatte.jpa:geolatte-geom-jpa:jar:0.2)
end
def jetbrains_annotations
%w(org.realityforge.org.jetbrains.annotations:org.jetbrains.annotations:jar:1.0.0)
end
def javax_annotations
%w(org.realityforge.javax.annotation:javax.annotation:jar:1.0.0)
end
def spotbugs_provided
%w(com.github.spotbugs:spotbugs-annotations:jar:3.1.5 net.jcip:jcip-annotations:jar:1.0) + self.javax_annotations
end
def ee_provided
%w(javax:javaee-api:jar:7.0) + self.spotbugs_provided + self.jetbrains_annotations
end
def glassfish_embedded
%w(fish.payara.extras:payara-embedded-all:jar:4.1.2.172 fish.payara.api:payara-api:jar:4.1.2.172)
end
def eclipselink
'org.eclipse.persistence:eclipselink:jar:2.6.0'
end
def mockito
%w(org.mockito:mockito-all:jar:1.10.19)
end
def jackson_annotations
%w(com.fasterxml.jackson.core:jackson-annotations:jar:2.8.8)
end
def jackson_core
%w(com.fasterxml.jackson.core:jackson-core:jar:2.8.8)
end
def jackson_databind
%w(com.fasterxml.jackson.core:jackson-databind:jar:2.8.8)
end
def jackson_datatype_jdk8
%w(com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar:2.8.8)
end
def jackson_module_kotlin
%w(com.fasterxml.jackson.module:jackson-module-kotlin:jar:2.8.8)
end
def jackson_gwt_support
self.jackson_core + self.jackson_databind + self.jackson_annotations
end
def braincheck
%w(org.realityforge.braincheck:braincheck:jar:1.12.0)
end
def jsinterop
%w(com.google.jsinterop:jsinterop-annotations:jar:1.0.2)
end
def jsinterop_base
%w(com.google.jsinterop:base:jar:1.0.0-RC1) + self.jsinterop
end
def elemental_version
'1.0.0-RC1'
end
def elemental2_core
%W(com.google.elemental2:elemental2-core:jar:#{elemental_version}) + self.jsinterop_base
end
def elemental2_dom
%W(com.google.elemental2:elemental2-dom:jar:#{elemental_version}) + self.elemental2_promise
end
def elemental2_promise
%W(com.google.elemental2:elemental2-promise:jar:#{elemental_version}) + self.elemental2_core
end
def elemental2_webstorage
%W(com.google.elemental2:elemental2-webstorage:jar:#{elemental_version}) + self.elemental2_dom
end
def gwt_user
%w(com.google.gwt:gwt-user:jar:2.8.2 org.w3c.css:sac:jar:1.3) + self.jsinterop
end
def gwt_servlet
%w(com.google.gwt:gwt-servlet:jar:2.8.2)
end
def gwt_dev
'com.google.gwt:gwt-dev:jar:2.8.2'
end
def javax_inject
%w(javax.inject:javax.inject:jar:1)
end
def javax_inject_gwt
%w(javax.inject:javax.inject:jar:sources:1) + self.javax_inject
end
def gwt_webpoller
%w(org.realityforge.gwt.webpoller:gwt-webpoller:jar:0.9.8)
end
def gwt_appcache_client
%w(org.realityforge.gwt.appcache:gwt-appcache-linker:jar:1.0.12)
end
def gwt_appcache_server
%w(org.realityforge.gwt.appcache:gwt-appcache-server:jar:1.0.12)
end
# The appcache code required to exist on gwt path during compilation
def gwt_appcache
self.gwt_appcache_client + self.gwt_appcache_server
end
def gwt_cache_filter
%w(org.realityforge.gwt.cache-filter:gwt-cache-filter:jar:0.7)
end
def field_filter
%w(org.realityforge.rest.field_filter:rest-field-filter:jar:0.4)
end
def graphql_java
%w(com.graphql-java:graphql-java:jar:3.0.0) + self.slf4j + self.antlr4_runtime
end
def graphql_java_tools
%w(
com.esotericsoftware:reflectasm:jar:1.11.3
com.graphql-java:graphql-java-tools:jar:3.2.1
org.jetbrains.kotlin:kotlin-reflect:jar:1.1.1
org.jetbrains.kotlin:kotlin-stdlib:jar:1.1.1
org.jetbrains.kotlin:kotlin-stdlib:jar:1.1.3-2
org.ow2.asm:asm:jar:5.0.4
ru.vyarus:generics-resolver:jar:2.0.1
) + self.graphql_java +
self.jackson_annotations +
self.jackson_core +
self.jackson_databind +
self.jackson_datatype_jdk8 +
self.jackson_module_kotlin +
self.guava + # Expected 21.0
self.jetbrains_annotations
end
def graphql_java_servlet
%w(
com.graphql-java:graphql-java-servlet:jar:4.0.0
commons-fileupload:commons-fileupload:jar:1.3.3
commons-io:commons-io:jar:2.5
) + self.graphql_java_tools
end
def graphql_domgen_support
%w(org.realityforge.keycloak.domgen:graphql-domgen-support:jar:1.2.0)
end
def antlr4_runtime
%w(org.antlr:antlr4-runtime:jar:4.5.1)
end
def rest_criteria
%w(org.realityforge.rest.criteria:rest-criteria:jar:0.9.6) +
self.antlr4_runtime +
self.field_filter
end
def commons_logging
%w(commons-logging:commons-logging:jar:1.2)
end
def commons_codec
%w(commons-codec:commons-codec:jar:1.9)
end
def bouncycastle
%w(org.bouncycastle:bcprov-jdk15on:jar:1.52 org.bouncycastle:bcpkix-jdk15on:jar:1.52)
end
def proxy_servlet
self.httpclient + %w(org.realityforge.proxy-servlet:proxy-servlet:jar:0.2.0)
end
def httpclient
%w(org.apache.httpcomponents:httpclient:jar:4.5 org.apache.httpcomponents:httpcore:jar:4.4.1) +
self.commons_logging + self.commons_codec
end
def failsafe
%w(net.jodah:failsafe:jar:1.0.3)
end
def keycloak_gwt
%w(org.realityforge.gwt.keycloak:gwt-keycloak:jar:0.4) + self.elemental2_webstorage
end
def keycloak_domgen_support
%w(org.realityforge.keycloak.domgen:keycloak-domgen-support:jar:1.4)
end
def keycloak_authfilter
%w(org.realityforge.keycloak.client.authfilter:keycloak-jaxrs-client-authfilter:jar:0.2)
end
def keycloak_converger
'org.realityforge.keycloak.converger:keycloak-converger:jar:1.6'
end
def jboss_logging
%w(org.jboss.logging:jboss-logging:jar:3.3.0.Final)
end
def keycloak_core
%w(
org.keycloak:keycloak-core:jar:2.0.0.Final
org.keycloak:keycloak-common:jar:2.0.0.Final
) + self.bouncycastle
end
def keycloak
%w(
org.keycloak:keycloak-servlet-filter-adapter:jar:2.0.0.Final
org.keycloak:keycloak-adapter-spi:jar:2.0.0.Final
org.keycloak:keycloak-adapter-core:jar:2.0.0.Final
org.realityforge.org.keycloak:keycloak-servlet-adapter-spi:jar:2.0.0.Final
) + self.keycloak_core + self.keycloak_domgen_support + self.httpclient + self.jboss_logging
end
def simple_keycloak_service
%w(org.realityforge.keycloak.sks:simple-keycloak-service:jar:0.1)
end
def guava
%w(com.google.guava:guava:jar:25.0-jre)
end
def javapoet
%w(com.squareup:javapoet:jar:1.11.1) + self.guava
end
def arez_version
'0.123'
end
def arez
%W(org.realityforge.arez:arez-core:jar:#{arez_version}) + self.braincheck
end
def arez_processor
%W(org.realityforge.arez:arez-processor:jar:#{arez_version})
end
def arez_spytools
%w(org.realityforge.arez.spytools:arez-spytools:jar:0.47)
end
def router_fu_version
'0.16'
end
def router_fu
%W(org.realityforge.router.fu:router-fu-core:jar:#{router_fu_version}) + self.braincheck
end
def router_fu_processor
%W(org.realityforge.router.fu:router-fu-processor:jar:#{router_fu_version})
end
def react4j_version
'0.110'
end
def react4j
%W(
org.realityforge.react4j:react4j-core:jar:#{react4j_version}
org.realityforge.react4j:react4j-dom:jar:#{react4j_version}
) + self.elemental2_dom + self.elemental2_promise
end
def react4j_processor
%W(org.realityforge.react4j:react4j-processor:jar:#{react4j_version})
end
def react4j_arez
%W(org.realityforge.react4j:react4j-arez:jar:#{react4j_version})
end
def replicant_version
'6.21'
end
def replicant_client
%W(org.realityforge.replicant:replicant-client:jar:#{replicant_version}) +
self.gwt_webpoller +
self.elemental2_webstorage +
# ee provided is for json API
self.ee_provided
end
def replicant_server
%W(org.realityforge.replicant:replicant-server:jar:#{replicant_version}) + self.gwt_rpc
end
def gwt_rpc
self.jackson_gwt_support + self.gwt_servlet
end
def guice
%w(aopalliance:aopalliance:jar:1.0 org.ow2.asm:asm:jar:5.0.3 au.com.stocksoftware.com.google.inject:guice:jar:4.1.1-stock)
end
def awaitility
%w(org.awaitility:awaitility:jar:2.0.0)
end
def dagger_version
'2.19'
end
def dagger_compile
%W(
com.google.dagger:dagger:jar:#{dagger_version}
)
end
def dagger
self.dagger_compile + self.javax_inject
end
def dagger_compiler
%W(
com.google.dagger:dagger-spi:jar:#{dagger_version}
com.google.dagger:dagger-producers:jar:#{dagger_version}
com.google.dagger:dagger-compiler:jar:#{dagger_version}
com.google.googlejavaformat:google-java-format:jar:1.5
com.google.errorprone:javac-shaded:jar:9-dev-r4023-3
) + self.javapoet + self.dagger
end
def dagger_gwt
%w(org.realityforge.dagger:dagger-gwt-lite:jar:2.19-rf1) + self.javax_inject_gwt
end
def testng_version
'6.11'
end
def testng
%W(org.testng:testng:jar:#{testng_version})
end
def jndikit
%w(org.realityforge.jndikit:jndikit:jar:1.4)
end
def guiceyloops
self.guiceyloops_gwt + self.glassfish_embedded
end
def guiceyloops_lib
'org.realityforge.guiceyloops:guiceyloops:jar:0.96'
end
def guiceyloops_gwt
[guiceyloops_lib] + self.mockito + self.guice + self.testng
end
def glassfish_timers_domain
%W(org.realityforge.glassfish.timers#{BuildrPlus::Db.pgsql? ? '.pg' : ''}:glassfish-timers-domain:json:0.6)
end
def glassfish_timers_db
%W(org.realityforge.glassfish.timers#{BuildrPlus::Db.pgsql? ? '.pg' : ''}:glassfish-timers-db:jar:0.6)
end
def slf4j
%w(org.slf4j:slf4j-api:jar:1.6.6 org.slf4j:slf4j-jdk14:jar:1.6.6)
end
def greenmail
%w(com.icegreen:greenmail:jar:1.4.1) + self.slf4j
end
def greenmail_server
'com.icegreen:greenmail-webapp:war:1.4.1'
end
def jtds
%w(net.sourceforge.jtds:jtds:jar:1.3.1)
end
def postgresql
%w(org.postgresql:postgresql:jar:9.2-1003-jdbc4)
end
def postgis
%w(org.postgis:postgis-jdbc:jar:1.3.3)
end
def db_drivers
return self.jtds if BuildrPlus::Db.mssql?
return self.postgresql + (BuildrPlus::FeatureManager.activated?(:geolatte) ? self.postgis : []) if BuildrPlus::Db.pgsql?
[]
end
end
end
Bump the version of react4j
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
BuildrPlus::FeatureManager.feature(:libs) do |f|
f.enhance(:Config) do
def mustache
%w(com.github.spullara.mustache.java:compiler:jar:0.8.15)
end
def javacsv
%w(net.sourceforge.javacsv:javacsv:jar:2.1)
end
def geotools_for_geolatte
%w(org.geotools:gt-main:jar:9.4 org.geotools:gt-metadata:jar:9.4 org.geotools:gt-api:jar:9.4 org.geotools:gt-epsg-wkt:jar:9.4 org.geotools:gt-opengis:jar:9.4 org.geotools:gt-transform:jar:9.4 org.geotools:gt-geometry:jar:9.4 org.geotools:gt-jts-wrapper:jar:9.4 org.geotools:gt-referencing:jar:9.4 net.java.dev.jsr-275:jsr-275:jar:1.0-beta-2 java3d:vecmath:jar:1.3.2 javax.media:jai_core:jar:1.1.3)
end
def jts
%w(com.vividsolutions:jts:jar:1.13)
end
# Support geo libraries for geolatte
def geolatte_support
self.jts + self.slf4j
end
def geolatte_geom
%w(org.geolatte:geolatte-geom:jar:0.13)
end
def geolatte_geom_jpa
%w(org.realityforge.geolatte.jpa:geolatte-geom-jpa:jar:0.2)
end
def jetbrains_annotations
%w(org.realityforge.org.jetbrains.annotations:org.jetbrains.annotations:jar:1.0.0)
end
def javax_annotations
%w(org.realityforge.javax.annotation:javax.annotation:jar:1.0.0)
end
def spotbugs_provided
%w(com.github.spotbugs:spotbugs-annotations:jar:3.1.5 net.jcip:jcip-annotations:jar:1.0) + self.javax_annotations
end
def ee_provided
%w(javax:javaee-api:jar:7.0) + self.spotbugs_provided + self.jetbrains_annotations
end
def glassfish_embedded
%w(fish.payara.extras:payara-embedded-all:jar:4.1.2.172 fish.payara.api:payara-api:jar:4.1.2.172)
end
def eclipselink
'org.eclipse.persistence:eclipselink:jar:2.6.0'
end
def mockito
%w(org.mockito:mockito-all:jar:1.10.19)
end
def jackson_annotations
%w(com.fasterxml.jackson.core:jackson-annotations:jar:2.8.8)
end
def jackson_core
%w(com.fasterxml.jackson.core:jackson-core:jar:2.8.8)
end
def jackson_databind
%w(com.fasterxml.jackson.core:jackson-databind:jar:2.8.8)
end
def jackson_datatype_jdk8
%w(com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar:2.8.8)
end
def jackson_module_kotlin
%w(com.fasterxml.jackson.module:jackson-module-kotlin:jar:2.8.8)
end
def jackson_gwt_support
self.jackson_core + self.jackson_databind + self.jackson_annotations
end
def braincheck
%w(org.realityforge.braincheck:braincheck:jar:1.12.0)
end
def jsinterop
%w(com.google.jsinterop:jsinterop-annotations:jar:1.0.2)
end
def jsinterop_base
%w(com.google.jsinterop:base:jar:1.0.0-RC1) + self.jsinterop
end
def elemental_version
'1.0.0-RC1'
end
def elemental2_core
%W(com.google.elemental2:elemental2-core:jar:#{elemental_version}) + self.jsinterop_base
end
def elemental2_dom
%W(com.google.elemental2:elemental2-dom:jar:#{elemental_version}) + self.elemental2_promise
end
def elemental2_promise
%W(com.google.elemental2:elemental2-promise:jar:#{elemental_version}) + self.elemental2_core
end
def elemental2_webstorage
%W(com.google.elemental2:elemental2-webstorage:jar:#{elemental_version}) + self.elemental2_dom
end
def gwt_user
%w(com.google.gwt:gwt-user:jar:2.8.2 org.w3c.css:sac:jar:1.3) + self.jsinterop
end
def gwt_servlet
%w(com.google.gwt:gwt-servlet:jar:2.8.2)
end
def gwt_dev
'com.google.gwt:gwt-dev:jar:2.8.2'
end
def javax_inject
%w(javax.inject:javax.inject:jar:1)
end
def javax_inject_gwt
%w(javax.inject:javax.inject:jar:sources:1) + self.javax_inject
end
def gwt_webpoller
%w(org.realityforge.gwt.webpoller:gwt-webpoller:jar:0.9.8)
end
def gwt_appcache_client
%w(org.realityforge.gwt.appcache:gwt-appcache-linker:jar:1.0.12)
end
def gwt_appcache_server
%w(org.realityforge.gwt.appcache:gwt-appcache-server:jar:1.0.12)
end
# The appcache code required to exist on gwt path during compilation
def gwt_appcache
self.gwt_appcache_client + self.gwt_appcache_server
end
def gwt_cache_filter
%w(org.realityforge.gwt.cache-filter:gwt-cache-filter:jar:0.7)
end
def field_filter
%w(org.realityforge.rest.field_filter:rest-field-filter:jar:0.4)
end
def graphql_java
%w(com.graphql-java:graphql-java:jar:3.0.0) + self.slf4j + self.antlr4_runtime
end
def graphql_java_tools
%w(
com.esotericsoftware:reflectasm:jar:1.11.3
com.graphql-java:graphql-java-tools:jar:3.2.1
org.jetbrains.kotlin:kotlin-reflect:jar:1.1.1
org.jetbrains.kotlin:kotlin-stdlib:jar:1.1.1
org.jetbrains.kotlin:kotlin-stdlib:jar:1.1.3-2
org.ow2.asm:asm:jar:5.0.4
ru.vyarus:generics-resolver:jar:2.0.1
) + self.graphql_java +
self.jackson_annotations +
self.jackson_core +
self.jackson_databind +
self.jackson_datatype_jdk8 +
self.jackson_module_kotlin +
self.guava + # Expected 21.0
self.jetbrains_annotations
end
def graphql_java_servlet
%w(
com.graphql-java:graphql-java-servlet:jar:4.0.0
commons-fileupload:commons-fileupload:jar:1.3.3
commons-io:commons-io:jar:2.5
) + self.graphql_java_tools
end
def graphql_domgen_support
%w(org.realityforge.keycloak.domgen:graphql-domgen-support:jar:1.2.0)
end
def antlr4_runtime
%w(org.antlr:antlr4-runtime:jar:4.5.1)
end
def rest_criteria
%w(org.realityforge.rest.criteria:rest-criteria:jar:0.9.6) +
self.antlr4_runtime +
self.field_filter
end
def commons_logging
%w(commons-logging:commons-logging:jar:1.2)
end
def commons_codec
%w(commons-codec:commons-codec:jar:1.9)
end
def bouncycastle
%w(org.bouncycastle:bcprov-jdk15on:jar:1.52 org.bouncycastle:bcpkix-jdk15on:jar:1.52)
end
def proxy_servlet
self.httpclient + %w(org.realityforge.proxy-servlet:proxy-servlet:jar:0.2.0)
end
def httpclient
%w(org.apache.httpcomponents:httpclient:jar:4.5 org.apache.httpcomponents:httpcore:jar:4.4.1) +
self.commons_logging + self.commons_codec
end
def failsafe
%w(net.jodah:failsafe:jar:1.0.3)
end
def keycloak_gwt
%w(org.realityforge.gwt.keycloak:gwt-keycloak:jar:0.4) + self.elemental2_webstorage
end
def keycloak_domgen_support
%w(org.realityforge.keycloak.domgen:keycloak-domgen-support:jar:1.4)
end
def keycloak_authfilter
%w(org.realityforge.keycloak.client.authfilter:keycloak-jaxrs-client-authfilter:jar:0.2)
end
def keycloak_converger
'org.realityforge.keycloak.converger:keycloak-converger:jar:1.6'
end
def jboss_logging
%w(org.jboss.logging:jboss-logging:jar:3.3.0.Final)
end
def keycloak_core
%w(
org.keycloak:keycloak-core:jar:2.0.0.Final
org.keycloak:keycloak-common:jar:2.0.0.Final
) + self.bouncycastle
end
def keycloak
%w(
org.keycloak:keycloak-servlet-filter-adapter:jar:2.0.0.Final
org.keycloak:keycloak-adapter-spi:jar:2.0.0.Final
org.keycloak:keycloak-adapter-core:jar:2.0.0.Final
org.realityforge.org.keycloak:keycloak-servlet-adapter-spi:jar:2.0.0.Final
) + self.keycloak_core + self.keycloak_domgen_support + self.httpclient + self.jboss_logging
end
def simple_keycloak_service
%w(org.realityforge.keycloak.sks:simple-keycloak-service:jar:0.1)
end
def guava
%w(com.google.guava:guava:jar:25.0-jre)
end
def javapoet
%w(com.squareup:javapoet:jar:1.11.1) + self.guava
end
def arez_version
'0.123'
end
def arez
%W(org.realityforge.arez:arez-core:jar:#{arez_version}) + self.braincheck
end
def arez_processor
%W(org.realityforge.arez:arez-processor:jar:#{arez_version})
end
def arez_spytools
%w(org.realityforge.arez.spytools:arez-spytools:jar:0.47)
end
def router_fu_version
'0.16'
end
def router_fu
%W(org.realityforge.router.fu:router-fu-core:jar:#{router_fu_version}) + self.braincheck
end
def router_fu_processor
%W(org.realityforge.router.fu:router-fu-processor:jar:#{router_fu_version})
end
def react4j_version
'0.111'
end
def react4j
%W(
org.realityforge.react4j:react4j-core:jar:#{react4j_version}
org.realityforge.react4j:react4j-dom:jar:#{react4j_version}
) + self.elemental2_dom + self.elemental2_promise
end
def react4j_processor
%W(org.realityforge.react4j:react4j-processor:jar:#{react4j_version})
end
def react4j_arez
%W(org.realityforge.react4j:react4j-arez:jar:#{react4j_version})
end
def replicant_version
'6.21'
end
def replicant_client
%W(org.realityforge.replicant:replicant-client:jar:#{replicant_version}) +
self.gwt_webpoller +
self.elemental2_webstorage +
# ee provided is for json API
self.ee_provided
end
def replicant_server
%W(org.realityforge.replicant:replicant-server:jar:#{replicant_version}) + self.gwt_rpc
end
def gwt_rpc
self.jackson_gwt_support + self.gwt_servlet
end
def guice
%w(aopalliance:aopalliance:jar:1.0 org.ow2.asm:asm:jar:5.0.3 au.com.stocksoftware.com.google.inject:guice:jar:4.1.1-stock)
end
def awaitility
%w(org.awaitility:awaitility:jar:2.0.0)
end
def dagger_version
'2.19'
end
def dagger_compile
%W(
com.google.dagger:dagger:jar:#{dagger_version}
)
end
def dagger
self.dagger_compile + self.javax_inject
end
def dagger_compiler
%W(
com.google.dagger:dagger-spi:jar:#{dagger_version}
com.google.dagger:dagger-producers:jar:#{dagger_version}
com.google.dagger:dagger-compiler:jar:#{dagger_version}
com.google.googlejavaformat:google-java-format:jar:1.5
com.google.errorprone:javac-shaded:jar:9-dev-r4023-3
) + self.javapoet + self.dagger
end
def dagger_gwt
%w(org.realityforge.dagger:dagger-gwt-lite:jar:2.19-rf1) + self.javax_inject_gwt
end
def testng_version
'6.11'
end
def testng
%W(org.testng:testng:jar:#{testng_version})
end
def jndikit
%w(org.realityforge.jndikit:jndikit:jar:1.4)
end
def guiceyloops
self.guiceyloops_gwt + self.glassfish_embedded
end
def guiceyloops_lib
'org.realityforge.guiceyloops:guiceyloops:jar:0.96'
end
def guiceyloops_gwt
[guiceyloops_lib] + self.mockito + self.guice + self.testng
end
def glassfish_timers_domain
%W(org.realityforge.glassfish.timers#{BuildrPlus::Db.pgsql? ? '.pg' : ''}:glassfish-timers-domain:json:0.6)
end
def glassfish_timers_db
%W(org.realityforge.glassfish.timers#{BuildrPlus::Db.pgsql? ? '.pg' : ''}:glassfish-timers-db:jar:0.6)
end
def slf4j
%w(org.slf4j:slf4j-api:jar:1.6.6 org.slf4j:slf4j-jdk14:jar:1.6.6)
end
def greenmail
%w(com.icegreen:greenmail:jar:1.4.1) + self.slf4j
end
def greenmail_server
'com.icegreen:greenmail-webapp:war:1.4.1'
end
def jtds
%w(net.sourceforge.jtds:jtds:jar:1.3.1)
end
def postgresql
%w(org.postgresql:postgresql:jar:9.2-1003-jdbc4)
end
def postgis
%w(org.postgis:postgis-jdbc:jar:1.3.3)
end
def db_drivers
return self.jtds if BuildrPlus::Db.mssql?
return self.postgresql + (BuildrPlus::FeatureManager.activated?(:geolatte) ? self.postgis : []) if BuildrPlus::Db.pgsql?
[]
end
end
end
|
module Asciidoctor
module Pdf
VERSION = '1.5.0.alpha.1'
end
end
prepare for next development iteration
module Asciidoctor
module Pdf
VERSION = '1.5.0.dev'
end
end
|
namespace :deploy do
[:start, :stop, :restart].each do |command|
desc "Run #{command} on servers"
task command do
on roles(:web) do
execute :service, :puma, command, "app=#{current_path}"
end
on roles(:worker) do
execute :service, :sidekiq, command, "index=0 app=#{current_path}"
end
end
namespace :nginx do
task command do
on roles(:web) do
execute :service, :nginx, command
end
end
end
end
after 'deploy:finished', 'deploy:restart'
end
Restart all pumas and sidekiqs thather than specifying by application
namespace :deploy do
[:start, :stop, :restart].each do |command|
desc "Run #{command} on servers"
task command do
on roles(:web) do
sudo :service, 'puma-manager', command
end
on roles(:worker) do
sudo :service, 'sidekiq-manager', command
end
end
namespace :nginx do
task command do
on roles(:web) do
execute :service, :nginx, command
end
end
end
end
after 'deploy:finished', 'deploy:restart'
end
|
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
BuildrPlus::FeatureManager.feature(:libs) do |f|
f.enhance(:Config) do
def mustache
%w(com.github.spullara.mustache.java:compiler:jar:0.8.15)
end
def javacsv
%w(net.sourceforge.javacsv:javacsv:jar:2.1)
end
def geotools_for_geolatte
%w(org.geotools:gt-main:jar:9.4 org.geotools:gt-metadata:jar:9.4 org.geotools:gt-api:jar:9.4 org.geotools:gt-epsg-wkt:jar:9.4 org.geotools:gt-opengis:jar:9.4 org.geotools:gt-transform:jar:9.4 org.geotools:gt-geometry:jar:9.4 org.geotools:gt-jts-wrapper:jar:9.4 org.geotools:gt-referencing:jar:9.4 net.java.dev.jsr-275:jsr-275:jar:1.0-beta-2 java3d:vecmath:jar:1.3.2 javax.media:jai_core:jar:1.1.3)
end
def jts
%w(com.vividsolutions:jts:jar:1.13)
end
# Support geo libraries for geolatte
def geolatte_support
self.jts + self.slf4j
end
def geolatte_geom
%w(org.geolatte:geolatte-geom:jar:0.13)
end
def geolatte_geom_jpa
%w(org.realityforge.geolatte.jpa:geolatte-geom-jpa:jar:0.2)
end
def findbugs_provided
%w(com.google.code.findbugs:jsr305:jar:3.0.0 com.google.code.findbugs:annotations:jar:3.0.0)
end
def ee_provided
%w(javax:javaee-api:jar:7.0) + self.findbugs_provided
end
def glassfish_embedded
%w(fish.payara.extras:payara-embedded-all:jar:4.1.1.162)
end
def eclipselink
'org.eclipse.persistence:eclipselink:jar:2.6.0'
end
def mockito
%w(org.mockito:mockito-all:jar:1.9.5)
end
def jackson_annotations
%w(com.fasterxml.jackson.core:jackson-annotations:jar:2.5.4)
end
def jackson_core
%w(com.fasterxml.jackson.core:jackson-core:jar:2.5.4)
end
def jackson_databind
%w(com.fasterxml.jackson.core:jackson-databind:jar:2.5.4)
end
def jackson_gwt_support
self.jackson_core + self.jackson_databind + self.jackson_annotations
end
def gwt_user
%w(com.google.gwt:gwt-user:jar:2.7.0)
end
def gwt_servlet
%w(com.google.gwt:gwt-servlet:jar:2.7.0)
end
def gwt_dev
'com.google.gwt:gwt-dev:jar:2.7.0'
end
def gwt_gin
%w(com.google.gwt.inject:gin:jar:2.1.2 javax.inject:javax.inject:jar:1) + self.guice + self.gwt_user
end
def replicant
%w(org.realityforge.replicant:replicant:jar:0.5.56)
end
def gwt_property_source
%w(org.realityforge.gwt.property-source:gwt-property-source:jar:0.2)
end
def gwt_webpoller
%w(org.realityforge.gwt.webpoller:gwt-webpoller:jar:0.8)
end
def gwt_datatypes
%w(org.realityforge.gwt.datatypes:gwt-datatypes:jar:0.8)
end
def gwt_ga
%w(org.realityforge.gwt.ga:gwt-ga:jar:0.5)
end
def gwt_mmvp
%w(org.realityforge.gwt.mmvp:gwt-mmvp:jar:0.5)
end
def gwt_lognice
%w(org.realityforge.gwt.lognice:gwt-lognice:jar:0.2)
end
def gwt_appcache_client
%w(org.realityforge.gwt.appcache:gwt-appcache-client:jar:1.0.8 org.realityforge.gwt.appcache:gwt-appcache-linker:jar:1.0.8)
end
def gwt_appcache_server
%w(org.realityforge.gwt.appcache:gwt-appcache-server:jar:1.0.8)
end
# The appcache code required to exist on gwt path during compilation
def gwt_appcache
self.gwt_appcache_client + self.gwt_appcache_server
end
def gwt_cache_filter
%w(org.realityforge.gwt.cache-filter:gwt-cache-filter:jar:0.6)
end
def simple_session_filter
%w(org.realityforge.ssf:simple-session-filter:jar:0.6)
end
def field_filter
%w(org.realityforge.rest.field_filter:rest-field-filter:jar:0.4)
end
def rest_criteria
%w(org.realityforge.rest.criteria:rest-criteria:jar:0.9.3 org.antlr:antlr4-runtime:jar:4.3 org.antlr:antlr4-annotations:jar:4.3) + self.field_filter
end
def commons_logging
%w(commons-logging:commons-logging:jar:1.2)
end
def commons_codec
%w(commons-codec:commons-codec:jar:1.9)
end
def bouncycastle
%w(org.bouncycastle:bcprov-jdk15on:jar:1.52 org.bouncycastle:bcpkix-jdk15on:jar:1.52)
end
def proxy_servlet
self.httpclient + %w(org.realityforge.proxy-servlet:proxy-servlet:jar:0.2.0)
end
def httpclient
%w(org.apache.httpcomponents:httpclient:jar:4.5 org.apache.httpcomponents:httpcore:jar:4.4.1) +
self.commons_logging + self.commons_codec
end
def keycloak_domgen_support
%w(org.realityforge.keycloak.domgen:keycloak-domgen-support:jar:1.1)
end
def jboss_logging
%w(org.jboss.logging:jboss-logging:jar:3.3.0.Final)
end
def keycloak_core
%w(
org.keycloak:keycloak-core:jar:2.0.0.Final
org.keycloak:keycloak-common:jar:2.0.0.Final
) + self.bouncycastle
end
def keycloak
%w(
org.keycloak:keycloak-servlet-filter-adapter:jar:2.0.0.Final
org.keycloak:keycloak-adapter-spi:jar:2.0.0.Final
org.keycloak:keycloak-adapter-core:jar:2.0.0.Final
org.realityforge.org.keycloak:keycloak-servlet-adapter-spi:jar:2.0.0.Final
) + self.keycloak_core + self.keycloak_domgen_support + self.httpclient + self.jboss_logging
end
def replicant_client
self.replicant + self.gwt_property_source + self.gwt_datatypes + self.gwt_webpoller
end
def replicant_server
self.replicant + self.simple_session_filter + self.gwt_rpc + self.field_filter
end
def gwt_rpc
self.gwt_datatypes + self.jackson_gwt_support + self.gwt_servlet
end
def guice
%w(aopalliance:aopalliance:jar:1.0 com.google.inject:guice:jar:3.0 com.google.inject.extensions:guice-assistedinject:jar:3.0)
end
def testng
%w(org.testng:testng:jar:6.8)
end
def jndikit
%w(org.realityforge.jndikit:jndikit:jar:1.4)
end
def guiceyloops
self.glassfish_embedded + self.guiceyloops_gwt
end
def guiceyloops_gwt
%w(org.realityforge.guiceyloops:guiceyloops:jar:0.76) + self.mockito + self.guice + self.testng
end
def glassfish_timers_domain
%W(org.realityforge.glassfish.timers#{BuildrPlus::Db.pgsql? ? '.pg' : ''}:glassfish-timers-domain:json:0.4)
end
def glassfish_timers_db
%W(org.realityforge.glassfish.timers#{BuildrPlus::Db.pgsql? ? '.pg' : ''}:glassfish-timers-db:jar:0.4)
end
def slf4j
%w(org.slf4j:slf4j-api:jar:1.6.6 org.slf4j:slf4j-jdk14:jar:1.6.6)
end
def greenmail
%w(com.icegreen:greenmail:jar:1.4.1) + self.slf4j
end
def greenmail_server
'com.icegreen:greenmail-webapp:war:1.4.1'
end
def jtds
%w(net.sourceforge.jtds:jtds:jar:1.3.1)
end
def postgresql
%w(org.postgresql:postgresql:jar:9.2-1003-jdbc4)
end
def postgis
%w(org.postgis:postgis-jdbc:jar:1.3.3)
end
def db_drivers
return self.jtds if BuildrPlus::Db.mssql?
return self.postgresql + (BuildrPlus::FeatureManager.activated?(:geolatte) ? self.postgis : []) if BuildrPlus::Db.pgsql?
[]
end
end
end
Bump the keycloak-domgen-support library
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
BuildrPlus::FeatureManager.feature(:libs) do |f|
f.enhance(:Config) do
def mustache
%w(com.github.spullara.mustache.java:compiler:jar:0.8.15)
end
def javacsv
%w(net.sourceforge.javacsv:javacsv:jar:2.1)
end
def geotools_for_geolatte
%w(org.geotools:gt-main:jar:9.4 org.geotools:gt-metadata:jar:9.4 org.geotools:gt-api:jar:9.4 org.geotools:gt-epsg-wkt:jar:9.4 org.geotools:gt-opengis:jar:9.4 org.geotools:gt-transform:jar:9.4 org.geotools:gt-geometry:jar:9.4 org.geotools:gt-jts-wrapper:jar:9.4 org.geotools:gt-referencing:jar:9.4 net.java.dev.jsr-275:jsr-275:jar:1.0-beta-2 java3d:vecmath:jar:1.3.2 javax.media:jai_core:jar:1.1.3)
end
def jts
%w(com.vividsolutions:jts:jar:1.13)
end
# Support geo libraries for geolatte
def geolatte_support
self.jts + self.slf4j
end
def geolatte_geom
%w(org.geolatte:geolatte-geom:jar:0.13)
end
def geolatte_geom_jpa
%w(org.realityforge.geolatte.jpa:geolatte-geom-jpa:jar:0.2)
end
def findbugs_provided
%w(com.google.code.findbugs:jsr305:jar:3.0.0 com.google.code.findbugs:annotations:jar:3.0.0)
end
def ee_provided
%w(javax:javaee-api:jar:7.0) + self.findbugs_provided
end
def glassfish_embedded
%w(fish.payara.extras:payara-embedded-all:jar:4.1.1.162)
end
def eclipselink
'org.eclipse.persistence:eclipselink:jar:2.6.0'
end
def mockito
%w(org.mockito:mockito-all:jar:1.9.5)
end
def jackson_annotations
%w(com.fasterxml.jackson.core:jackson-annotations:jar:2.5.4)
end
def jackson_core
%w(com.fasterxml.jackson.core:jackson-core:jar:2.5.4)
end
def jackson_databind
%w(com.fasterxml.jackson.core:jackson-databind:jar:2.5.4)
end
def jackson_gwt_support
self.jackson_core + self.jackson_databind + self.jackson_annotations
end
def gwt_user
%w(com.google.gwt:gwt-user:jar:2.7.0)
end
def gwt_servlet
%w(com.google.gwt:gwt-servlet:jar:2.7.0)
end
def gwt_dev
'com.google.gwt:gwt-dev:jar:2.7.0'
end
def gwt_gin
%w(com.google.gwt.inject:gin:jar:2.1.2 javax.inject:javax.inject:jar:1) + self.guice + self.gwt_user
end
def replicant
%w(org.realityforge.replicant:replicant:jar:0.5.56)
end
def gwt_property_source
%w(org.realityforge.gwt.property-source:gwt-property-source:jar:0.2)
end
def gwt_webpoller
%w(org.realityforge.gwt.webpoller:gwt-webpoller:jar:0.8)
end
def gwt_datatypes
%w(org.realityforge.gwt.datatypes:gwt-datatypes:jar:0.8)
end
def gwt_ga
%w(org.realityforge.gwt.ga:gwt-ga:jar:0.5)
end
def gwt_mmvp
%w(org.realityforge.gwt.mmvp:gwt-mmvp:jar:0.5)
end
def gwt_lognice
%w(org.realityforge.gwt.lognice:gwt-lognice:jar:0.2)
end
def gwt_appcache_client
%w(org.realityforge.gwt.appcache:gwt-appcache-client:jar:1.0.8 org.realityforge.gwt.appcache:gwt-appcache-linker:jar:1.0.8)
end
def gwt_appcache_server
%w(org.realityforge.gwt.appcache:gwt-appcache-server:jar:1.0.8)
end
# The appcache code required to exist on gwt path during compilation
def gwt_appcache
self.gwt_appcache_client + self.gwt_appcache_server
end
def gwt_cache_filter
%w(org.realityforge.gwt.cache-filter:gwt-cache-filter:jar:0.6)
end
def simple_session_filter
%w(org.realityforge.ssf:simple-session-filter:jar:0.6)
end
def field_filter
%w(org.realityforge.rest.field_filter:rest-field-filter:jar:0.4)
end
def rest_criteria
%w(org.realityforge.rest.criteria:rest-criteria:jar:0.9.3 org.antlr:antlr4-runtime:jar:4.3 org.antlr:antlr4-annotations:jar:4.3) + self.field_filter
end
def commons_logging
%w(commons-logging:commons-logging:jar:1.2)
end
def commons_codec
%w(commons-codec:commons-codec:jar:1.9)
end
def bouncycastle
%w(org.bouncycastle:bcprov-jdk15on:jar:1.52 org.bouncycastle:bcpkix-jdk15on:jar:1.52)
end
def proxy_servlet
self.httpclient + %w(org.realityforge.proxy-servlet:proxy-servlet:jar:0.2.0)
end
def httpclient
%w(org.apache.httpcomponents:httpclient:jar:4.5 org.apache.httpcomponents:httpcore:jar:4.4.1) +
self.commons_logging + self.commons_codec
end
def keycloak_domgen_support
%w(org.realityforge.keycloak.domgen:keycloak-domgen-support:jar:1.3)
end
def jboss_logging
%w(org.jboss.logging:jboss-logging:jar:3.3.0.Final)
end
def keycloak_core
%w(
org.keycloak:keycloak-core:jar:2.0.0.Final
org.keycloak:keycloak-common:jar:2.0.0.Final
) + self.bouncycastle
end
def keycloak
%w(
org.keycloak:keycloak-servlet-filter-adapter:jar:2.0.0.Final
org.keycloak:keycloak-adapter-spi:jar:2.0.0.Final
org.keycloak:keycloak-adapter-core:jar:2.0.0.Final
org.realityforge.org.keycloak:keycloak-servlet-adapter-spi:jar:2.0.0.Final
) + self.keycloak_core + self.keycloak_domgen_support + self.httpclient + self.jboss_logging
end
def replicant_client
self.replicant + self.gwt_property_source + self.gwt_datatypes + self.gwt_webpoller
end
def replicant_server
self.replicant + self.simple_session_filter + self.gwt_rpc + self.field_filter
end
def gwt_rpc
self.gwt_datatypes + self.jackson_gwt_support + self.gwt_servlet
end
def guice
%w(aopalliance:aopalliance:jar:1.0 com.google.inject:guice:jar:3.0 com.google.inject.extensions:guice-assistedinject:jar:3.0)
end
def testng
%w(org.testng:testng:jar:6.8)
end
def jndikit
%w(org.realityforge.jndikit:jndikit:jar:1.4)
end
def guiceyloops
self.glassfish_embedded + self.guiceyloops_gwt
end
def guiceyloops_gwt
%w(org.realityforge.guiceyloops:guiceyloops:jar:0.76) + self.mockito + self.guice + self.testng
end
def glassfish_timers_domain
%W(org.realityforge.glassfish.timers#{BuildrPlus::Db.pgsql? ? '.pg' : ''}:glassfish-timers-domain:json:0.4)
end
def glassfish_timers_db
%W(org.realityforge.glassfish.timers#{BuildrPlus::Db.pgsql? ? '.pg' : ''}:glassfish-timers-db:jar:0.4)
end
def slf4j
%w(org.slf4j:slf4j-api:jar:1.6.6 org.slf4j:slf4j-jdk14:jar:1.6.6)
end
def greenmail
%w(com.icegreen:greenmail:jar:1.4.1) + self.slf4j
end
def greenmail_server
'com.icegreen:greenmail-webapp:war:1.4.1'
end
def jtds
%w(net.sourceforge.jtds:jtds:jar:1.3.1)
end
def postgresql
%w(org.postgresql:postgresql:jar:9.2-1003-jdbc4)
end
def postgis
%w(org.postgis:postgis-jdbc:jar:1.3.3)
end
def db_drivers
return self.jtds if BuildrPlus::Db.mssql?
return self.postgresql + (BuildrPlus::FeatureManager.activated?(:geolatte) ? self.postgis : []) if BuildrPlus::Db.pgsql?
[]
end
end
end
|
module AssetsCommonExtension
include Seek::MimeTypes
include Seek::ContentBlobCommon
def download
if self.controller_name=="models"
download_model
else
download_single
end
end
#current model is the only type with multiple content-blobs, this may change in the future
def download_model
# update timestamp in the current Model record
# (this will also trigger timestamp update in the corresponding Asset)
@model.last_used_at = Time.now
@model.save_without_timestamping
handle_download_zip @display_model
end
#for data files, SOPs and presentations, that only have a single content-blob
def download_single
name = self.controller_name.singularize
@asset = eval("@#{name}")
@asset_version = eval("@display_#{name}")
@content_blob = @asset_version.content_blob
@asset.last_used_at = Time.now
@asset.save_without_timestamping
disposition = params[:disposition] || 'attachment'
respond_to do |format|
format.html {handle_download disposition}
end
end
def show_via_url asset, content_blob=nil
content_blob = content_blob.nil? ? asset.content_blob : content_blob
code = url_response_code(content_blob.url)
if (["301","302", "401"].include?(code))
redirect_to(content_blob.url, :target=>"_blank")
elsif code=="404"
flash[:error]="This item is referenced at a remote location, which is currently unavailable"
redirect_to polymorphic_path(asset.parent, {:version=>asset.version})
else
downloader=Seek::RemoteDownloader.new
data_hash = downloader.get_remote_data content_blob.url
send_file data_hash[:data_tmp_path], :filename => data_hash[:filename] || content_blob.original_filename, :content_type => data_hash[:content_type] || content_blob.content_type, :disposition => 'inline'
end
end
def calculate_params symbol
i = 0
local_set = []
url_set = []
original_filename_from_url_set = []
while !params[symbol].blank?
if !params[symbol]['file_'+i.to_s].nil?
if params[symbol]['file_'+i.to_s] != ""
local_set << params[symbol]['file_'+i.to_s]
end
params[symbol].delete 'file_'+i.to_s
end
if !params[symbol]['url_'+i.to_s].nil?
if params[symbol]['url_'+i.to_s] != ""
url_set << params[symbol]['url_'+i.to_s]
end
params[symbol].delete 'url_'+i.to_s
end
if !params[symbol]['original_filename_'+i.to_s].nil?
if params[symbol]['original_filename_'+i.to_s] != ""
original_filename_from_url_set << params[symbol]['original_filename_'+i.to_s]
end
params[symbol].delete 'original_filename_'+i.to_s
end
i += 1
end
return [local_set, url_set, original_filename_from_url_set]
end
def retained_content_blob_ids
if params[:content_blobs] && params[:content_blobs][:id]
params[:content_blobs][:id].keys.collect{|id| id.to_i}
else
[]
end
end
def handle_batch_data render_action_on_error=:new
#FIXME: too many nested if,else and rescue blocks. This method needs refactoring.
c = self.controller_name.downcase
@content_types = []
@original_filenames = []
@tmp_io_objects_localfile = []
@tmp_io_objects_url = []
@data_urls = []
symb = c.singularize.to_sym
object = eval("@#{c.singularize}")
params_files = calculate_params(:content_blob)
params_data = params_files.first
params_url = params_files.second
params_original_filename_from_ulr = params_files.third
params_image_file = params[controller_name.singularize+'_image'].nil? ? nil : params[controller_name.singularize+'_image']['image_file']
params_previous_image = params[:previous_version_image]
#ids of selected content_blobs of previous version, when uploading new version
@retained_content_blob_ids = retained_content_blob_ids
if render_action_on_error==:new || render_action_on_error.nil?
params_files = params_data + params_url
elsif render_action_on_error==:edit
params_files = object.content_blobs
end
if params_files.blank? && params_image_file.blank? && @retained_content_blob_ids.blank? && params_previous_image.blank?
flash.now[:error] = "Please select at least a file/image to upload or provide a URL to the data."
if render_action_on_error
init_asset_for_render params
respond_to do |format|
format.html do
render :action => render_action_on_error
end
end
end
return false
elsif !params_data.blank? && !params_data.detect { |data| data.size == 0 }.nil? && params_url.blank?
flash.now[:error] = "At least one file that you are uploading is empty. Please check your selection and try again!"
if render_action_on_error
init_asset_for_render params
respond_to do |format|
format.html do
render :action => render_action_on_error
end
end
end
return false
else
#upload takes precedence if both params are present
begin
if !params_data.blank?
# store properties and contents of the file temporarily and remove the latter from params[],
# so that when saving main object params[] wouldn't contain the binary data anymore
@content_types = params_data.collect(&:content_type)
@original_filenames = params_data.collect(&:original_filename)
@tmp_io_objects_localfile = params_data
end
if !params_url.blank?
make_local_copy = (params[symb][:local_copy]=="1")
@data_urls=params_url
@data_urls.each_with_index do |data_url,index|
code = url_response_code data_url
if (code == "200")
downloader=Seek::RemoteDownloader.new
data_hash = downloader.get_remote_data data_url, nil, nil, nil, make_local_copy
@tmp_io_objects_url << File.open(data_hash[:data_tmp_path], "r") if make_local_copy
@content_types << data_hash[:content_type]
@original_filenames << (params_original_filename_from_ulr[index] || data_hash[:filename])
elsif (["301","302", "401"].include?(code))
@tmp_io_objects_url << ""
@content_types << ""
@original_filenames << ""
else
flash.now[:error] = "Processing the URL responded with a response code (#{code}), indicating the <a href= \'#{data_url}\'>URL</a> is inaccessible."
if render_action_on_error
init_asset_for_render params
respond_to do |format|
format.html do
render :action => render_action_on_error
end
end
end
return false
end
end
end
rescue Seek::IncompatibleProtocolException=>e
flash.now[:error] = e.message
if render_action_on_error
init_asset_for_render params
respond_to do |format|
format.html do
render :action => render_action_on_error
end
end
end
return false
rescue Exception=>e
flash.now[:error] = "Unable to read from the URL."
flash.now[:error] << e.message
if render_action_on_error
init_asset_for_render params
respond_to do |format|
format.html do
render :action => render_action_on_error
end
end
end
return false
end
params[symb].delete 'data_url'
params[symb].delete 'data'
params[symb].delete 'local_copy'
return true
end
end
def create_content_blobs
asset = eval "@#{self.controller_name.downcase.singularize}"
sym = self.controller_name.downcase.singularize.to_sym
version = asset.version
if asset.respond_to?(:content_blob) && !asset.respond_to?(:content_blobs)
#if request is sent from a browser running on window, take the content type from the filename instead
if request.headers['HTTP_USER_AGENT'].include?('Win')
content_type = content_type_from_filename params[sym][:original_filename]
else
content_type = params[sym][:content_type]
end
# create new /new version
asset.create_content_blob(:tmp_io_object => @tmp_io_object,
:url=>@data_url,
:original_filename=>params[sym][:original_filename],
:content_type=>content_type,
:asset_version=>version
)
elsif asset.respond_to? :content_blobs
# create new /new version
@tmp_io_objects_localfile.each do |tmp_io_object|
#if request is sent from a browser running on window, take the content type from the filename instead
if request.headers['HTTP_USER_AGENT'].include?('Win')
content_type = content_type_from_filename @original_filenames[0]
else
content_type = @content_types[0].to_s
end
asset.content_blobs.create(:tmp_io_object => tmp_io_object,
:original_filename=>@original_filenames[0],
:content_type=>content_type,
:asset_version=>version)
@original_filenames.delete_at(0)
@content_types.delete_at(0)
end
@data_urls.each_with_index do |data_url, index|
asset.content_blobs.create(:tmp_io_object => @tmp_io_objects_url[index],
:url=>data_url,
:original_filename=>@original_filenames[index],
:content_type=>@content_types[index],
:asset_version=>version)
end
#create content_blobs and files, based on previous version chosen content_blobs
previous_version_asset= asset.find_version(version - 1)
if previous_version_asset
previous_version_content_blobs = previous_version_asset.content_blobs
copying_content_blobs = previous_version_content_blobs.select{|cb| @retained_content_blob_ids.include?(cb.id)}
copying_content_blobs.each do |cb|
new_content_blob= asset.content_blobs.create(:url=>cb.url,
:original_filename=>cb.original_filename,
:content_type=>cb.content_type,
:asset_version=>version)
FileUtils.cp(cb.filepath, new_content_blob.filepath) if File.exists?(cb.filepath)
end
end
end
end
def handle_download_zip asset
#get the list of filename and filepath, {:filename => filepath}
files_to_download = {}
#store content_type for the case of 1 file
content_type = nil
if asset.respond_to?(:model_image) && asset.model_image
model_image = asset.model_image
filename = check_and_rename_file files_to_download.keys, model_image.original_filename
files_to_download["#{filename}"] = model_image.file_path
content_type = model_image.content_type
end
asset.content_blobs.each do |content_blob|
if File.exists? content_blob.filepath
filename = check_and_rename_file files_to_download.keys, content_blob.original_filename
files_to_download["#{filename}"] = content_blob.filepath
content_type = content_blob.content_type
elsif !content_blob.url.nil?
downloader=Seek::RemoteDownloader.new
data_hash = downloader.get_remote_data content_blob.url, nil, nil, nil, true
original_filename = get_filename data_hash[:filename], content_blob.original_filename
filename = check_and_rename_file files_to_download.keys, original_filename
files_to_download["#{filename}"] = data_hash[:data_tmp_path]
content_type = data_hash[:content_type] || content_blob.content_type
end
end
content_type ||= "application/octet-stream"
#making and sending zip file if there are more than one file
if files_to_download.count > 1
make_and_send_zip_file files_to_download, asset
else
send_file files_to_download.values.first, :filename => files_to_download.keys.first, :type => content_type
end
end
private
def make_and_send_zip_file files_to_download, asset
t = Tempfile.new("#{Time.now.year}#{Time.now.month}#{Time.now.day}_#{asset.class.name.downcase}_#{asset.id}","#{RAILS_ROOT}/tmp")
# Give the path of the temp file to the zip outputstream, it won't try to open it as an archive.
Zip::ZipOutputStream.open(t.path) do |zos|
files_to_download.each do |filename,filepath|
zos.put_next_entry(filename)
zos.print IO.read(filepath)
end
end
send_file t.path, :type => 'application/zip', :disposition => 'attachment', :filename => "#{asset.title}.zip"
# The temp file will be deleted some time...
t.close
end
def check_and_rename_file filename_list, filename
file = filename.split('.')
file_format = file.last
original_name = file.take(file.size - 1).join('.')
i = 1
while filename_list.include?(filename)
filename = original_name + '_' + i.to_s + '.' + file_format
i += 1
end
filename
end
def content_type_from_filename filename
file_format = filename.split('.').last.try(:strip)
possible_mime_types = mime_types_for_extension file_format
type = possible_mime_types.sort.first || "application/octet-stream"
#FIXME: this is just a quick fix, until http://dev.mygrid.org.uk/issues/browse/SYSMO-1129 is fully resolved
type = type.gsub("image/jpg","image/jpeg") unless type.nil?
type
end
#prioritize filename from data_hash
def get_filename filename_from_data_hash, filename_from_content_blob
if filename_from_data_hash != 'download'
filename = filename_from_data_hash
elsif filename_from_data_hash == 'download' && !filename_from_content_blob.blank?
filename = filename_from_content_blob
else
filename = "download"
end
filename
end
end
Seek::AssetsCommon.module_eval do
include AssetsCommonExtension
end
shouldn't attempt to create a content-blob with both data and a url when the url exists (otherwise it sometimes tries to add an empty string as the data)
module AssetsCommonExtension
include Seek::MimeTypes
include Seek::ContentBlobCommon
def download
if self.controller_name=="models"
download_model
else
download_single
end
end
#current model is the only type with multiple content-blobs, this may change in the future
def download_model
# update timestamp in the current Model record
# (this will also trigger timestamp update in the corresponding Asset)
@model.last_used_at = Time.now
@model.save_without_timestamping
handle_download_zip @display_model
end
#for data files, SOPs and presentations, that only have a single content-blob
def download_single
name = self.controller_name.singularize
@asset = eval("@#{name}")
@asset_version = eval("@display_#{name}")
@content_blob = @asset_version.content_blob
@asset.last_used_at = Time.now
@asset.save_without_timestamping
disposition = params[:disposition] || 'attachment'
respond_to do |format|
format.html {handle_download disposition}
end
end
def show_via_url asset, content_blob=nil
content_blob = content_blob.nil? ? asset.content_blob : content_blob
code = url_response_code(content_blob.url)
if (["301","302", "401"].include?(code))
redirect_to(content_blob.url, :target=>"_blank")
elsif code=="404"
flash[:error]="This item is referenced at a remote location, which is currently unavailable"
redirect_to polymorphic_path(asset.parent, {:version=>asset.version})
else
downloader=Seek::RemoteDownloader.new
data_hash = downloader.get_remote_data content_blob.url
send_file data_hash[:data_tmp_path], :filename => data_hash[:filename] || content_blob.original_filename, :content_type => data_hash[:content_type] || content_blob.content_type, :disposition => 'inline'
end
end
def calculate_params symbol
i = 0
local_set = []
url_set = []
original_filename_from_url_set = []
while !params[symbol].blank?
if !params[symbol]['file_'+i.to_s].nil?
if params[symbol]['file_'+i.to_s] != ""
local_set << params[symbol]['file_'+i.to_s]
end
params[symbol].delete 'file_'+i.to_s
end
if !params[symbol]['url_'+i.to_s].nil?
if params[symbol]['url_'+i.to_s] != ""
url_set << params[symbol]['url_'+i.to_s]
end
params[symbol].delete 'url_'+i.to_s
end
if !params[symbol]['original_filename_'+i.to_s].nil?
if params[symbol]['original_filename_'+i.to_s] != ""
original_filename_from_url_set << params[symbol]['original_filename_'+i.to_s]
end
params[symbol].delete 'original_filename_'+i.to_s
end
i += 1
end
return [local_set, url_set, original_filename_from_url_set]
end
def retained_content_blob_ids
if params[:content_blobs] && params[:content_blobs][:id]
params[:content_blobs][:id].keys.collect{|id| id.to_i}
else
[]
end
end
def handle_batch_data render_action_on_error=:new
#FIXME: too many nested if,else and rescue blocks. This method needs refactoring.
c = self.controller_name.downcase
@content_types = []
@original_filenames = []
@tmp_io_objects_localfile = []
@tmp_io_objects_url = []
@data_urls = []
symb = c.singularize.to_sym
object = eval("@#{c.singularize}")
params_files = calculate_params(:content_blob)
params_data = params_files.first
params_url = params_files.second
params_original_filename_from_ulr = params_files.third
params_image_file = params[controller_name.singularize+'_image'].nil? ? nil : params[controller_name.singularize+'_image']['image_file']
params_previous_image = params[:previous_version_image]
#ids of selected content_blobs of previous version, when uploading new version
@retained_content_blob_ids = retained_content_blob_ids
if render_action_on_error==:new || render_action_on_error.nil?
params_files = params_data + params_url
elsif render_action_on_error==:edit
params_files = object.content_blobs
end
if params_files.blank? && params_image_file.blank? && @retained_content_blob_ids.blank? && params_previous_image.blank?
flash.now[:error] = "Please select at least a file/image to upload or provide a URL to the data."
if render_action_on_error
init_asset_for_render params
respond_to do |format|
format.html do
render :action => render_action_on_error
end
end
end
return false
elsif !params_data.blank? && !params_data.detect { |data| data.size == 0 }.nil? && params_url.blank?
flash.now[:error] = "At least one file that you are uploading is empty. Please check your selection and try again!"
if render_action_on_error
init_asset_for_render params
respond_to do |format|
format.html do
render :action => render_action_on_error
end
end
end
return false
else
#upload takes precedence if both params are present
begin
if !params_data.blank?
# store properties and contents of the file temporarily and remove the latter from params[],
# so that when saving main object params[] wouldn't contain the binary data anymore
@content_types = params_data.collect(&:content_type)
@original_filenames = params_data.collect(&:original_filename)
@tmp_io_objects_localfile = params_data
end
if !params_url.blank?
make_local_copy = (params[symb][:local_copy]=="1")
@data_urls=params_url
@data_urls.each_with_index do |data_url,index|
code = url_response_code data_url
if (code == "200")
downloader=Seek::RemoteDownloader.new
data_hash = downloader.get_remote_data data_url, nil, nil, nil, make_local_copy
@tmp_io_objects_url << File.open(data_hash[:data_tmp_path], "r") if make_local_copy
@content_types << data_hash[:content_type]
@original_filenames << (params_original_filename_from_ulr[index] || data_hash[:filename])
elsif (["301","302", "401"].include?(code))
@tmp_io_objects_url << ""
@content_types << ""
@original_filenames << ""
else
flash.now[:error] = "Processing the URL responded with a response code (#{code}), indicating the <a href= \'#{data_url}\'>URL</a> is inaccessible."
if render_action_on_error
init_asset_for_render params
respond_to do |format|
format.html do
render :action => render_action_on_error
end
end
end
return false
end
end
end
rescue Seek::IncompatibleProtocolException=>e
flash.now[:error] = e.message
if render_action_on_error
init_asset_for_render params
respond_to do |format|
format.html do
render :action => render_action_on_error
end
end
end
return false
rescue Exception=>e
flash.now[:error] = "Unable to read from the URL."
flash.now[:error] << e.message
if render_action_on_error
init_asset_for_render params
respond_to do |format|
format.html do
render :action => render_action_on_error
end
end
end
return false
end
params[symb].delete 'data_url'
params[symb].delete 'data'
params[symb].delete 'local_copy'
return true
end
end
def create_content_blobs
asset = eval "@#{self.controller_name.downcase.singularize}"
sym = self.controller_name.downcase.singularize.to_sym
version = asset.version
if asset.respond_to?(:content_blob) && !asset.respond_to?(:content_blobs)
#if request is sent from a browser running on window, take the content type from the filename instead
if request.headers['HTTP_USER_AGENT'].include?('Win')
content_type = content_type_from_filename params[sym][:original_filename]
else
content_type = params[sym][:content_type]
end
# create new /new version
asset.create_content_blob(:tmp_io_object => @tmp_io_object,
:url=>@data_url,
:original_filename=>params[sym][:original_filename],
:content_type=>content_type,
:asset_version=>version
)
elsif asset.respond_to? :content_blobs
# create new /new version
@tmp_io_objects_localfile.each do |tmp_io_object|
#if request is sent from a browser running on window, take the content type from the filename instead
if request.headers['HTTP_USER_AGENT'].include?('Win')
content_type = content_type_from_filename @original_filenames[0]
else
content_type = @content_types[0].to_s
end
asset.content_blobs.create(:tmp_io_object => tmp_io_object,
:original_filename=>@original_filenames[0],
:content_type=>content_type,
:asset_version=>version)
@original_filenames.delete_at(0)
@content_types.delete_at(0)
end
@data_urls.each_with_index do |data_url, index|
asset.content_blobs.create(:url=>data_url,
:original_filename=>@original_filenames[index],
:content_type=>@content_types[index],
:asset_version=>version)
end
#create content_blobs and files, based on previous version chosen content_blobs
previous_version_asset= asset.find_version(version - 1)
if previous_version_asset
previous_version_content_blobs = previous_version_asset.content_blobs
copying_content_blobs = previous_version_content_blobs.select{|cb| @retained_content_blob_ids.include?(cb.id)}
copying_content_blobs.each do |cb|
new_content_blob= asset.content_blobs.create(:url=>cb.url,
:original_filename=>cb.original_filename,
:content_type=>cb.content_type,
:asset_version=>version)
FileUtils.cp(cb.filepath, new_content_blob.filepath) if File.exists?(cb.filepath)
end
end
end
end
def handle_download_zip asset
#get the list of filename and filepath, {:filename => filepath}
files_to_download = {}
#store content_type for the case of 1 file
content_type = nil
if asset.respond_to?(:model_image) && asset.model_image
model_image = asset.model_image
filename = check_and_rename_file files_to_download.keys, model_image.original_filename
files_to_download["#{filename}"] = model_image.file_path
content_type = model_image.content_type
end
asset.content_blobs.each do |content_blob|
if File.exists? content_blob.filepath
filename = check_and_rename_file files_to_download.keys, content_blob.original_filename
files_to_download["#{filename}"] = content_blob.filepath
content_type = content_blob.content_type
elsif !content_blob.url.nil?
downloader=Seek::RemoteDownloader.new
data_hash = downloader.get_remote_data content_blob.url, nil, nil, nil, true
original_filename = get_filename data_hash[:filename], content_blob.original_filename
filename = check_and_rename_file files_to_download.keys, original_filename
files_to_download["#{filename}"] = data_hash[:data_tmp_path]
content_type = data_hash[:content_type] || content_blob.content_type
end
end
content_type ||= "application/octet-stream"
#making and sending zip file if there are more than one file
if files_to_download.count > 1
make_and_send_zip_file files_to_download, asset
else
send_file files_to_download.values.first, :filename => files_to_download.keys.first, :type => content_type
end
end
private
def make_and_send_zip_file files_to_download, asset
t = Tempfile.new("#{Time.now.year}#{Time.now.month}#{Time.now.day}_#{asset.class.name.downcase}_#{asset.id}","#{RAILS_ROOT}/tmp")
# Give the path of the temp file to the zip outputstream, it won't try to open it as an archive.
Zip::ZipOutputStream.open(t.path) do |zos|
files_to_download.each do |filename,filepath|
zos.put_next_entry(filename)
zos.print IO.read(filepath)
end
end
send_file t.path, :type => 'application/zip', :disposition => 'attachment', :filename => "#{asset.title}.zip"
# The temp file will be deleted some time...
t.close
end
def check_and_rename_file filename_list, filename
file = filename.split('.')
file_format = file.last
original_name = file.take(file.size - 1).join('.')
i = 1
while filename_list.include?(filename)
filename = original_name + '_' + i.to_s + '.' + file_format
i += 1
end
filename
end
def content_type_from_filename filename
file_format = filename.split('.').last.try(:strip)
possible_mime_types = mime_types_for_extension file_format
type = possible_mime_types.sort.first || "application/octet-stream"
#FIXME: this is just a quick fix, until http://dev.mygrid.org.uk/issues/browse/SYSMO-1129 is fully resolved
type = type.gsub("image/jpg","image/jpeg") unless type.nil?
type
end
#prioritize filename from data_hash
def get_filename filename_from_data_hash, filename_from_content_blob
if filename_from_data_hash != 'download'
filename = filename_from_data_hash
elsif filename_from_data_hash == 'download' && !filename_from_content_blob.blank?
filename = filename_from_content_blob
else
filename = "download"
end
filename
end
end
Seek::AssetsCommon.module_eval do
include AssetsCommonExtension
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.