pax_global_header00006660000000000000000000000064131543001670014512gustar00rootroot0000000000000052 comment=040ac4130449a3a18575a8a49c6161472c77ce88 gpick-gpick-0.2.6rc1/000077500000000000000000000000001315430016700143155ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/.gitignore000066400000000000000000000002321315430016700163020ustar00rootroot00000000000000.* *~ *.orig *.diff diff *.save *.old *.bak .*.swp *.out *.pyc *.log *.mo *.msm *.wixobj *.wixpdb *.msi *.pdb installer/files/* user-config.py build tags gpick-gpick-0.2.6rc1/.hgignore000066400000000000000000000002471315430016700161230ustar00rootroot00000000000000syntax: glob .* *~ *.orig *.diff diff *.save *.old *.bak .*.swp *.out *.pyc *.log *.mo *.msm *.wixobj *.wixpdb *.msi *.pdb installer/files/* user-config.py build tags gpick-gpick-0.2.6rc1/LICENSE.txt000066400000000000000000000027501315430016700161440ustar00rootroot00000000000000BSD 3-Clause License Copyright (c) 2009-2016, Albertas Vyšniauskas All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. gpick-gpick-0.2.6rc1/README.md000066400000000000000000000030571315430016700156010ustar00rootroot00000000000000# Gpick - advanced color picker and palette editor. Gpick is an application that allows you to sample any color from anywhere on the desktop, and use it to create palettes (i.e. collections of colors) for use in graphic design applications. Gpick also has other features that help in the creation of color palettes, such as: * The ability to create a palette from an imported image * Automatic naming of colors * Color scheme generator * Import and export from various file formats ## Building from source ### Compiler Some of C++14 features are required. Compilation is currently only tested on gcc version 5.3.1. ### Build dependencies SCons 2.4 or newer: a software construction tool ([http://www.scons.org](http://www.scons.org)). Ragel 6.8 or newer: state machine compiler ([http://www.colm.net/open-source/ragel](http://www.colm.net/open-source/ragel)). ### Dependencies GTK+ 2.24 ([http://www.gtk.org](http://www.gtk.org)). Lua 5.3 or 5.2 ([http://www.lua.org](http://www.lua.org)). Expat ([http://expat.sourceforge.net](http://expat.sourceforge.net)). Boost 1.58 or newer ([http://www.boost.org](http://www.boost.org)). Used libraries: * Filesystem. * System. * Test (only when building/running tests). ### Optional dependencies gettext ([http://www.gnu.org/s/gettext](http://www.gnu.org/s/gettext)). Required if ENABLE\_NLS is enabled. Required by default. ### Building `scons` to compile all files and place executable file in `build/source/`. `scons install` to install executable and resources to `DESTDIR`. By default `DESTDIR` is `/usr/local`. gpick-gpick-0.2.6rc1/SConscript000066400000000000000000000172741315430016700163420ustar00rootroot00000000000000#!/usr/bin/env python import os import string import sys from tools.gpick import * env = GpickEnvironment(ENV=os.environ, BUILDERS = {'WriteNsisVersion' : Builder(action = WriteNsisVersion, suffix = ".nsi")}) vars = Variables(os.path.join(env.GetLaunchDir(), 'user-config.py')) vars.Add('DESTDIR', 'Directory to install under', '/usr/local') vars.Add('LOCALEDIR', 'Path to locale directory', '') vars.Add('DEBARCH', 'Debian package architecture', 'i386') vars.Add(BoolVariable('ENABLE_NLS', 'Compile with gettext support', True)) vars.Add(BoolVariable('DEBUG', 'Compile with debug information', False)) vars.Add('BUILD_TARGET', 'Build target', '') vars.Add('TOOLCHAIN', 'Toolchain', 'gcc') vars.Add(BoolVariable('EXPERIMENTAL_CSS_PARSER', 'Compile with experimental CSS parser', False)) vars.Add('MSVS_VERSION', 'Visual Studio version', '11.0') vars.Add(BoolVariable('PREBUILD_GRAMMAR', 'Use prebuild grammar files', False)) vars.Add(BoolVariable('USE_GTK3', 'Use GTK3 instead of GTK2', False)) vars.Update(env) if env['LOCALEDIR'] == '': env['LOCALEDIR'] = env['DESTDIR'] + '/share/locale' v = Variables(os.path.join(env.GetLaunchDir(), 'version.py')) v.Add('GPICK_BUILD_VERSION', '', '0.0') v.Update(env) if not env['BUILD_TARGET']: env['BUILD_TARGET'] = sys.platform if env['BUILD_TARGET'] == 'win32': if env['TOOLCHAIN'] == 'msvc': env['TARGET_ARCH'] = 'x86' env['MSVS'] = {'VERSION': env['MSVS_VERSION']} env['MSVC_VERSION'] = env['MSVS_VERSION'] env["MSVC_SETUP_RUN"] = False Tool('msvc')(env) else: if sys.platform != 'win32': env.Tool('crossmingw', toolpath = ['tools']) else: env.Tool('mingw') env.AddCustomBuilders() env.GetVersionInfo() try: umask = os.umask(022) except OSError: # ignore on systems that don't support umask pass if os.environ.has_key('CC'): env['CC'] = os.environ['CC'] if os.environ.has_key('CFLAGS'): env['CCFLAGS'] += SCons.Util.CLVar(os.environ['CFLAGS']) if os.environ.has_key('CXX'): env['CXX'] = os.environ['CXX'] if os.environ.has_key('CXXFLAGS'): env['CXXFLAGS'] += SCons.Util.CLVar(os.environ['CXXFLAGS']) if os.environ.has_key('LDFLAGS'): env['LINKFLAGS'] += SCons.Util.CLVar(os.environ['LDFLAGS']) if not env.GetOption('clean'): conf = Configure(env) programs = {} if env['ENABLE_NLS']: programs['GETTEXT'] = {'checks':{'msgfmt':'GETTEXT'}} programs['XGETTEXT'] = {'checks':{'xgettext':'XGETTEXT'}, 'required':False} programs['MSGMERGE'] = {'checks':{'msgmerge':'MSGMERGE'}, 'required':False} programs['MSGCAT'] = {'checks':{'msgcat':'MSGCAT'}, 'required':False} programs['RAGEL'] = {'checks':{'ragel':'RAGEL'}} if env['EXPERIMENTAL_CSS_PARSER'] and not env['PREBUILD_GRAMMAR']: programs['LEMON'] = {'checks':{'lemon':'LEMON'}} programs['FLEX'] = {'checks':{'flex':'FLEX'}} env.ConfirmPrograms(conf, programs) libs = {} if not env['TOOLCHAIN'] == 'msvc': if not env['USE_GTK3']: libs['GTK_PC'] = {'checks':{'gtk+-2.0':'>= 2.24.0'}} libs['GIO_PC'] = {'checks':{'gio-unix-2.0':'>= 2.26.0', 'gio-2.0':'>= 2.26.0'}} else: libs['GTK_PC'] = {'checks':{'gtk+-3.0':'>= 3.0.0'}} libs['LUA_PC'] = {'checks':{'lua5.3':'>= 5.3', 'lua':'>= 5.2', 'lua5.2':'>= 5.2'}} env.ConfirmLibs(conf, libs) env.ConfirmBoost(conf, '1.58') env = conf.Finish() Decider('MD5-timestamp') if not env['TOOLCHAIN'] == 'msvc': if not (os.environ.has_key('CFLAGS') or os.environ.has_key('CXXFLAGS') or os.environ.has_key('LDFLAGS')): if env['DEBUG']: env.Append( CPPFLAGS = ['-Wall', '-g3', '-O0'], CFLAGS = ['-Wall', '-g3', '-O0'], LINKFLAGS = ['-Wl,-as-needed'], ) else: env.Append( CPPDEFINES = ['NDEBUG'], CDEFINES = ['NDEBUG'], CPPFLAGS = ['-Wall', '-O3'], CFLAGS = ['-Wall', '-O3'], LINKFLAGS = ['-Wl,-as-needed', '-s'], ) env.Append( CPPFLAGS = ['-std=c++14'], ) if env['BUILD_TARGET'] == 'win32': env.Append( LINKFLAGS = ['-Wl,--enable-auto-import', '-static-libgcc', '-static-libstdc++'], CPPDEFINES = ['_WIN32_WINNT=0x0501'], ) else: env['LINKCOM'] = [env['LINKCOM'], 'mt.exe -nologo -manifest ${TARGET}.manifest -outputresource:$TARGET;1'] if env['DEBUG']: env.Append( CPPFLAGS = ['/Od', '/EHsc', '/MD', '/Gy', '/Zi', '/TP', '/wd4819'], CPPDEFINES = ['WIN32', '_DEBUG', 'NOMINMAX'], LINKFLAGS = ['/MANIFEST', '/DEBUG'], ) else: env.Append( CPPFLAGS = ['/O2', '/Oi', '/GL', '/EHsc', '/MD', '/Gy', '/Zi', '/TP', '/wd4819'], CPPDEFINES = ['WIN32', 'NDEBUG', 'NOMINMAX'], LINKFLAGS = ['/MANIFEST', '/LTCG'], ) env.Append( CPPPATH = ['#extern'], ) extern_libs = SConscript(['extern/SConscript'], exports='env') executable, tests, parser_files = SConscript(['source/SConscript'], exports='env') env.Alias(target="build", source=[ executable, ]) env.Alias(target="test", source=[ tests, ]) if 'debian' in COMMAND_LINE_TARGETS: SConscript("deb/SConscript", exports='env') if env['ENABLE_NLS']: translations = env.Glob('share/locale/*/LC_MESSAGES/gpick.po') locales = env.Gettext(translations) Depends(executable, locales) stripped_locales = [] for translation in translations: stripped_locales.append(env.Msgcat(translation, File(translation).srcnode(), MSGCAT_FLAGS = ['--no-location', '--sort-output', '--no-wrap', '--to-code=utf-8'])) env.Alias(target = "strip_locales", source = stripped_locales) env.Alias(target = "locales", source = locales) template_c = env.Xgettext("template_c.pot", env.Glob('source/*.cpp') + env.Glob('source/tools/*.cpp') + env.Glob('source/transformation/*.cpp'), XGETTEXT_FLAGS = ['--keyword=N_', '--from-code=UTF-8', '--package-version="$GPICK_BUILD_VERSION"']) template_lua = env.Xgettext("template_lua.pot", env.Glob('share/gpick/*.lua'), XGETTEXT_FLAGS = ['--language=C++', '--keyword=N_', '--from-code=UTF-8', '--package-version="$GPICK_BUILD_VERSION"']) template = env.Msgcat("template.pot", [template_c, template_lua], MSGCAT_FLAGS = ['--use-first']) env.Alias(target = "template", source=[ template ]) env.Alias(target = "install", source=[ env.InstallProgram(dir=env['DESTDIR'] +'/bin', source=[executable]), env.InstallData(dir=env['DESTDIR'] +'/share/appdata', source=['share/appdata/gpick.appdata.xml']), env.InstallData(dir=env['DESTDIR'] +'/share/applications', source=['share/applications/gpick.desktop']), env.InstallData(dir=env['DESTDIR'] +'/share/doc/gpick', source=['share/doc/gpick/copyright']), env.InstallData(dir=env['DESTDIR'] +'/share/gpick', source=[env.Glob('share/gpick/*.png'), env.Glob('share/gpick/*.lua'), env.Glob('share/gpick/*.txt')]), env.InstallData(dir=env['DESTDIR'] +'/share/man/man1', source=['share/man/man1/gpick.1']), env.InstallData(dir=env['DESTDIR'] +'/share/icons/hicolor/48x48/apps/', source=[env.Glob('share/icons/hicolor/48x48/apps/*.png')]), env.InstallData(dir=env['DESTDIR'] +'/share/icons/hicolor/scalable/apps/', source=[env.Glob('share/icons/hicolor/scalable/apps/*.svg')]), env.InstallDataAutoDir(dir=env['DESTDIR'] + '/share/locale/', relative_dir='share/locale/', source=[env.Glob('share/locale/*/LC_MESSAGES/gpick.mo')]), ]) env.Alias(target = "nsis", source = [ env.WriteNsisVersion("version.py") ]) env.Alias(target = "version", source = [ env.Template(target = "#version.txt", source = "version.template"), ]) tarFiles = env.GetSourceFiles( "("+RegexEscape(os.sep)+r"\.)|("+RegexEscape(os.sep)+r"\.svn$)|(^"+RegexEscape(os.sep)+r"build$)", r"(^\.)|(\.pyc$)|(\.orig$)|(~$)|(\.log$)|(\.diff)|(\.mo$)|(\.patch)|(^gpick-.*\.tar\.gz$)|(^user-config\.py$)") for item in parser_files: tarFiles.append(str(item)) if 'TAR' in env: env.Alias(target = "tar", source = [ 'version', env.Append(TARFLAGS = ['-z']), env.Prepend(TARFLAGS = ['--transform', '"s,(^(build/)?),gpick_'+str(env['GPICK_BUILD_VERSION'])+'/,x"']), env.Tar('gpick_'+str(env['GPICK_BUILD_VERSION'])+'.tar.gz', tarFiles) ]) env.Default(executable) gpick-gpick-0.2.6rc1/SConstruct000066400000000000000000000001241315430016700163440ustar00rootroot00000000000000#!/usr/bin/env python SConscript(['SConscript'], variant_dir='build', duplicate=0) gpick-gpick-0.2.6rc1/deb/000077500000000000000000000000001315430016700150475ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/deb/DEBIAN/000077500000000000000000000000001315430016700157715ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/deb/DEBIAN/postinst000077500000000000000000000002021315430016700175740ustar00rootroot00000000000000#!/bin/sh set -e if [ "$1" = "configure" ] && which update-desktop-database >/dev/null 2>&1 ; then update-desktop-database -q fi gpick-gpick-0.2.6rc1/deb/DEBIAN/postrm000077500000000000000000000001771315430016700172500ustar00rootroot00000000000000#!/bin/sh set -e if [ "$1" = "remove" ] && which update-desktop-database >/dev/null 2>&1 ; then update-desktop-database -q fi gpick-gpick-0.2.6rc1/deb/SConscript000066400000000000000000000041351315430016700170640ustar00rootroot00000000000000#!/usr/bin/env python # coding: utf-8 import os import sys import shutil import glob import math import tools.gpick Import('*') DEBNAME = "gpick" DEBVERSION = str(env['GPICK_BUILD_VERSION'])+"-1" DEBMAINT = "Albertas Vyšniauskas " DEBARCH = env['DEBARCH'] DEBDEPENDS = "libgtk2.0-0 (>= 2.24), libc6 (>= 2.13), liblua5.2-0 (>= 5.2), libcairo2 (>=1.8), libglib2.0-0 (>=2.24)" DEBPRIORITY = "optional" DEBSECTION = "graphics" DEBDESC = "Advanced color picker" DEBDESCLONG = """ Gpick is a program used to pick colors from anywhere on the screen, mix them to get new colors, generate shades and tints and export palettes to common file formats or simply copy them to the clipboard """ DEBPACKAGEFILE = '%s_%s_%s.deb' % (DEBNAME, DEBVERSION, DEBARCH) CONTROL_TEMPLATE = """Package: %s Version: %s Section: %s Priority: %s Architecture: %s Depends: %s Installed-Size: %s Maintainer: %s Description: %s %s """ DEBCONTROLDIR = os.path.join(DEBNAME, "DEBIAN") DEBCONTROLFILE = os.path.join(DEBCONTROLDIR, "control") DEBINSTALLDIR = os.path.join('deb' , DEBNAME, 'usr') env['DESTDIR'] = DEBINSTALLDIR #redirect install location def debian_write_control(target=None, source=None, env=None): installed_size = 0 files = tools.gpick.Glob(os.path.join('build', 'deb', DEBNAME, 'usr')) for i in files: installed_size += os.stat(str(i))[6] installed_size = int(math.ceil(installed_size/1024)) control_info = CONTROL_TEMPLATE % ( DEBNAME, DEBVERSION, DEBSECTION, DEBPRIORITY, DEBARCH, DEBDEPENDS, str(installed_size), DEBMAINT, DEBDESC, DEBDESCLONG) f = open(str(target[0]), 'w') f.write(control_info) f.close() return None env.Append(BUILDERS = {'DebianPackage' : Builder(action = "fakeroot dpkg-deb -b %s %s" % ("$SOURCE", "$TARGET") )}) env.Append(BUILDERS = {'DebianControl' : Builder(action = debian_write_control)}) env.Alias(target="debian", source=[ env.Install(dir=DEBCONTROLDIR, source=[env.Glob("DEBIAN/*")]), env.DebianControl(source = env.Alias('install'), target = DEBCONTROLFILE), env.DebianPackage(source = env.Dir(DEBNAME), target = os.path.join('.', DEBPACKAGEFILE)) ]) gpick-gpick-0.2.6rc1/doc/000077500000000000000000000000001315430016700150625ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/doc/Doxyfile000066400000000000000000001776201315430016700166050ustar00rootroot00000000000000# Doxyfile 1.6.2-20100208 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project # # All text after a hash (#) is considered a comment and will be ignored # The format is: # TAG = value [value, ...] # For lists items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (" ") #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # This tag specifies the encoding used for all characters in the config file # that follow. The default is UTF-8 which is also the encoding used for all # text before the first occurrence of this tag. Doxygen uses libiconv (or the # iconv built into libc) for the transcoding. See # http://www.gnu.org/software/libiconv for the list of possible encodings. DOXYFILE_ENCODING = UTF-8 # The PROJECT_NAME tag is a single word (or a sequence of words surrounded # by quotes) that should identify the project. PROJECT_NAME = Gpick # The PROJECT_NUMBER tag can be used to enter a project or revision number. # This could be handy for archiving the generated documentation or # if some version control system is used. PROJECT_NUMBER = # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) # base path where the generated documentation will be put. # If a relative path is entered, it will be relative to the location # where doxygen was started. If left blank the current directory will be used. OUTPUT_DIRECTORY = build/ # If the CREATE_SUBDIRS tag is set to YES, then doxygen will create # 4096 sub-directories (in 2 levels) under the output directory of each output # format and will distribute the generated files over these directories. # Enabling this option can be useful when feeding doxygen a huge amount of # source files, where putting all generated files in the same directory would # otherwise cause performance problems for the file system. CREATE_SUBDIRS = NO # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # The default language is English, other supported languages are: # Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, # Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, # Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English # messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, # Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak, # Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. OUTPUT_LANGUAGE = English # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will # include brief member descriptions after the members that are listed in # the file and class documentation (similar to JavaDoc). # Set to NO to disable this. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend # the brief description of a member or function before the detailed description. # Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. REPEAT_BRIEF = NO # This tag implements a quasi-intelligent brief description abbreviator # that is used to form the text in various listings. Each string # in this list, if found as the leading text of the brief description, will be # stripped from the text and the result after processing the whole list, is # used as the annotated text. Otherwise, the brief description is used as-is. # If left blank, the following values are used ("$name" is automatically # replaced with the name of the entity): "The $name class" "The $name widget" # "The $name file" "is" "provides" "specifies" "contains" # "represents" "a" "an" "the" ABBREVIATE_BRIEF = # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # Doxygen will generate a detailed section even if there is only a brief # description. ALWAYS_DETAILED_SEC = NO # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all # inherited members of a class in the documentation of that class as if those # members were ordinary class members. Constructors, destructors and assignment # operators of the base classes will not be shown. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full # path before files name in the file list and in the header files. If set # to NO the shortest path that makes the file name unique will be used. FULL_PATH_NAMES = YES # If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag # can be used to strip a user-defined part of the path. Stripping is # only done if one of the specified strings matches the left-hand part of # the path. The tag can be used to show relative paths in the file list. # If left blank the directory from which doxygen is run is used as the # path to strip. STRIP_FROM_PATH = # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of # the path mentioned in the documentation of a class, which tells # the reader which header file to include in order to use a class. # If left blank only the name of the header file containing the class # definition is used. Otherwise one should specify the include paths that # are normally passed to the compiler using the -I flag. STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter # (but less readable) file names. This can be useful is your file systems # doesn't support long names like on DOS, Mac, or CD-ROM. SHORT_NAMES = NO # If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen # will interpret the first line (until the first dot) of a JavaDoc-style # comment as the brief description. If set to NO, the JavaDoc # comments will behave just like regular Qt-style comments # (thus requiring an explicit @brief command for a brief description.) JAVADOC_AUTOBRIEF = NO # If the QT_AUTOBRIEF tag is set to YES then Doxygen will # interpret the first line (until the first dot) of a Qt-style # comment as the brief description. If set to NO, the comments # will behave just like regular Qt-style comments (thus requiring # an explicit \brief command for a brief description.) QT_AUTOBRIEF = NO # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen # treat a multi-line C++ special comment block (i.e. a block of //! or /// # comments) as a brief description. This used to be the default behaviour. # The new default is to treat a multi-line C++ comment block as a detailed # description. Set this tag to YES if you prefer the old behaviour instead. MULTILINE_CPP_IS_BRIEF = NO # If the INHERIT_DOCS tag is set to YES (the default) then an undocumented # member inherits the documentation from any documented member that it # re-implements. INHERIT_DOCS = YES # If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce # a new page for each member. If set to NO, the documentation of a member will # be part of the file/class/namespace that contains it. SEPARATE_MEMBER_PAGES = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. # Doxygen uses this value to replace tabs by spaces in code fragments. TAB_SIZE = 4 # This tag can be used to specify a number of aliases that acts # as commands in the documentation. An alias has the form "name=value". # For example adding "sideeffect=\par Side Effects:\n" will allow you to # put the command \sideeffect (or @sideeffect) in the documentation, which # will result in a user-defined paragraph with heading "Side Effects:". # You can put \n's in the value part of an alias to insert newlines. ALIASES = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C # sources only. Doxygen will then generate output that is more tailored for C. # For instance, some of the names that are used will be different. The list # of all members will be omitted, etc. OPTIMIZE_OUTPUT_FOR_C = NO # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java # sources only. Doxygen will then generate output that is more tailored for # Java. For instance, namespaces will be presented as packages, qualified # scopes will look different, etc. OPTIMIZE_OUTPUT_JAVA = NO # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources only. Doxygen will then generate output that is more tailored for # Fortran. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for # VHDL. OPTIMIZE_OUTPUT_VHDL = NO # Doxygen selects the parser to use depending on the extension of the files it parses. # With this tag you can assign which parser to use for a given extension. # Doxygen has a built-in mapping, but you can override or extend it using this tag. # The format is ext=language, where ext is a file extension, and language is one of # the parsers supported by doxygen: IDL, Java, Javascript, C#, C, C++, D, PHP, # Objective-C, Python, Fortran, VHDL, C, C++. For instance to make doxygen treat # .inc files as Fortran files (default is PHP), and .f files as C (default is Fortran), # use: inc=Fortran f=C. Note that for custom extensions you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. EXTENSION_MAPPING = # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should # set this tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); v.s. # func(std::string) {}). This also make the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. BUILTIN_STL_SUPPORT = YES # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. CPP_CLI_SUPPORT = NO # Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. # Doxygen will parse them like normal C++ but will assume all classes use public # instead of private inheritance when no explicit protection keyword is present. SIP_SUPPORT = NO # For Microsoft's IDL there are propget and propput attributes to indicate getter # and setter methods for a property. Setting this option to YES (the default) # will make doxygen to replace the get and set methods by a property in the # documentation. This will only work if the methods are indeed getting or # setting a simple type. If this is not the case, or you want to show the # methods anyway, you should set this option to NO. IDL_PROPERTY_SUPPORT = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES, then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. DISTRIBUTE_GROUP_DOC = NO # Set the SUBGROUPING tag to YES (the default) to allow class member groups of # the same type (for instance a group of public functions) to be put as a # subgroup of that type (e.g. under the Public Functions section). Set it to # NO to prevent subgrouping. Alternatively, this can be done per class using # the \nosubgrouping command. SUBGROUPING = YES # When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum # is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, # namespace, or class. And the struct will be named TypeS. This can typically # be useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. TYPEDEF_HIDES_STRUCT = NO # The SYMBOL_CACHE_SIZE determines the size of the internal cache use to # determine which symbols to keep in memory and which to flush to disk. # When the cache is full, less often used symbols will be written to disk. # For small to medium size projects (<1000 input files) the default value is # probably good enough. For larger projects a too small cache size can cause # doxygen to be busy swapping symbols to and from disk most of the time # causing a significant performance penality. # If the system has enough physical memory increasing the cache will improve the # performance by keeping more symbols in memory. Note that the value works on # a logarithmic scale so increasing the size by one will rougly double the # memory usage. The cache size is given by this formula: # 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, # corresponding to a cache size of 2^16 = 65536 symbols SYMBOL_CACHE_SIZE = 0 #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in # documentation are documented, even if no documentation was available. # Private class members and static file members will be hidden unless # the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES EXTRACT_ALL = NO # If the EXTRACT_PRIVATE tag is set to YES all private members of a class # will be included in the documentation. EXTRACT_PRIVATE = NO # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. EXTRACT_STATIC = YES # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. # If set to NO only classes defined in header files are included. EXTRACT_LOCAL_CLASSES = YES # This flag is only useful for Objective-C code. When set to YES local # methods, which are defined in the implementation section but not in # the interface are included in the documentation. # If set to NO (the default) only methods in the interface are included. EXTRACT_LOCAL_METHODS = NO # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called # 'anonymous_namespace{file}', where file will be replaced with the base # name of the file that contains the anonymous namespace. By default # anonymous namespace are hidden. EXTRACT_ANON_NSPACES = YES # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # undocumented members of documented classes, files or namespaces. # If set to NO (the default) these members will be included in the # various overviews, but no documentation section is generated. # This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. # If set to NO (the default) these classes will be included in the various # overviews. This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all # friend (class|struct|union) declarations. # If set to NO (the default) these declarations will be included in the # documentation. HIDE_FRIEND_COMPOUNDS = NO # If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any # documentation blocks found inside the body of a function. # If set to NO (the default) these blocks will be appended to the # function's detailed documentation block. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation # that is typed after a \internal command is included. If the tag is set # to NO (the default) then the documentation will be excluded. # Set it to YES to include the internal documentation. INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate # file names in lower-case letters. If set to YES upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # and Mac users are advised to set this option to NO. CASE_SENSE_NAMES = YES # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen # will show members with their full class and namespace scopes in the # documentation. If set to YES the scope will be hidden. HIDE_SCOPE_NAMES = NO # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen # will put a list of the files that are included by a file in the documentation # of that file. SHOW_INCLUDE_FILES = YES # If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen # will list include files with double quotes in the documentation # rather than with sharp brackets. FORCE_LOCAL_INCLUDES = NO # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] # is inserted in the documentation for inline members. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen # will sort the (detailed) documentation of file and class members # alphabetically by member name. If set to NO the members will appear in # declaration order. SORT_MEMBER_DOCS = YES # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the # brief documentation of file, namespace and class members alphabetically # by member name. If set to NO (the default) the members will appear in # declaration order. SORT_BRIEF_DOCS = NO # If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the (brief and detailed) documentation of class members so that constructors and destructors are listed first. If set to NO (the default) the constructors will appear in the respective orders defined by SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. SORT_MEMBERS_CTORS_1ST = NO # If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the # hierarchy of group names into alphabetical order. If set to NO (the default) # the group names will appear in their defined order. SORT_GROUP_NAMES = NO # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be # sorted by fully-qualified names, including namespaces. If set to # NO (the default), the class list will be sorted only by class name, # not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the # alphabetical list. SORT_BY_SCOPE_NAME = NO # The GENERATE_TODOLIST tag can be used to enable (YES) or # disable (NO) the todo list. This list is created by putting \todo # commands in the documentation. GENERATE_TODOLIST = YES # The GENERATE_TESTLIST tag can be used to enable (YES) or # disable (NO) the test list. This list is created by putting \test # commands in the documentation. GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable (YES) or # disable (NO) the bug list. This list is created by putting \bug # commands in the documentation. GENERATE_BUGLIST = YES # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or # disable (NO) the deprecated list. This list is created by putting # \deprecated commands in the documentation. GENERATE_DEPRECATEDLIST= YES # The ENABLED_SECTIONS tag can be used to enable conditional # documentation sections, marked by \if sectionname ... \endif. ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines # the initial value of a variable or define consists of for it to appear in # the documentation. If the initializer consists of more lines than specified # here it will be hidden. Use a value of 0 to hide initializers completely. # The appearance of the initializer of individual variables and defines in the # documentation can be controlled using \showinitializer or \hideinitializer # command in the documentation regardless of this setting. MAX_INITIALIZER_LINES = 30 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated # at the bottom of the documentation of classes and structs. If set to YES the # list will mention the files that were used to generate the documentation. SHOW_USED_FILES = YES # If the sources in your project are distributed over multiple directories # then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy # in the documentation. The default is NO. SHOW_DIRECTORIES = YES # Set the SHOW_FILES tag to NO to disable the generation of the Files page. # This will remove the Files entry from the Quick Index and from the # Folder Tree View (if specified). The default is YES. SHOW_FILES = YES # Set the SHOW_NAMESPACES tag to NO to disable the generation of the # Namespaces page. # This will remove the Namespaces entry from the Quick Index # and from the Folder Tree View (if specified). The default is YES. SHOW_NAMESPACES = YES # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via # popen()) the command , where is the value of # the FILE_VERSION_FILTER tag, and is the name of an input file # provided by doxygen. Whatever the program writes to standard output # is used as the file version. See the manual for examples. FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed by # doxygen. The layout file controls the global structure of the generated output files # in an output format independent way. The create the layout file that represents # doxygen's defaults, run doxygen with the -l option. You can optionally specify a # file name after the option, if omitted DoxygenLayout.xml will be used as the name # of the layout file. LAYOUT_FILE = #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated # by doxygen. Possible values are YES and NO. If left blank NO is used. QUIET = NO # The WARNINGS tag can be used to turn on/off the warning messages that are # generated by doxygen. Possible values are YES and NO. If left blank # NO is used. WARNINGS = YES # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings # for undocumented members. If EXTRACT_ALL is set to YES then this flag will # automatically be disabled. WARN_IF_UNDOCUMENTED = YES # If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some # parameters in a documented function, or documenting parameters that # don't exist or using markup commands wrongly. WARN_IF_DOC_ERROR = YES # This WARN_NO_PARAMDOC option can be abled to get warnings for # functions that are documented, but have no documentation for their parameters # or return value. If set to NO (the default) doxygen will only warn about # wrong or incomplete parameter documentation, but not about the absence of # documentation. WARN_NO_PARAMDOC = NO # The WARN_FORMAT tag determines the format of the warning messages that # doxygen can produce. The string should contain the $file, $line, and $text # tags, which will be replaced by the file and line number from which the # warning originated and the warning text. Optionally the format may contain # $version, which will be replaced by the version of the file (if it could # be obtained via FILE_VERSION_FILTER) WARN_FORMAT = "$file:$line: $text" # The WARN_LOGFILE tag can be used to specify a file to which warning # and error messages should be written. If left blank the output is written # to stderr. WARN_LOGFILE = #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag can be used to specify the files and/or directories that contain # documented source files. You may enter file names like "myfile.cpp" or # directories like "/usr/src/myproject". Separate the files or directories # with spaces. INPUT = source/ # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is # also the default input encoding. Doxygen uses libiconv (or the iconv built # into libc) for the transcoding. See http://www.gnu.org/software/libiconv for # the list of possible encodings. INPUT_ENCODING = UTF-8 # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank the following patterns are tested: # *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx # *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90 FILE_PATTERNS = # The RECURSIVE tag can be used to turn specify whether or not subdirectories # should be searched for input files as well. Possible values are YES and NO. # If left blank NO is used. RECURSIVE = YES # The EXCLUDE tag can be used to specify files and/or directories that should # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. EXCLUDE = # The EXCLUDE_SYMLINKS tag can be used select whether or not files or # directories that are symbolic links (a Unix filesystem feature) are excluded # from the input. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. Note that the wildcards are matched # against the file with absolute path, so to exclude all test directories # for example use the pattern */test/* EXCLUDE_PATTERNS = # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the # output. The symbol name can be a fully qualified name, a word, or if the # wildcard * is used, a substring. Examples: ANamespace, AClass, # AClass::ANamespace, ANamespace::*Test EXCLUDE_SYMBOLS = # The EXAMPLE_PATH tag can be used to specify one or more files or # directories that contain example code fragments that are included (see # the \include command). EXAMPLE_PATH = # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. EXAMPLE_PATTERNS = # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude # commands irrespective of the value of the RECURSIVE tag. # Possible values are YES and NO. If left blank NO is used. EXAMPLE_RECURSIVE = NO # The IMAGE_PATH tag can be used to specify one or more files or # directories that contain image that are included in the documentation (see # the \image command). IMAGE_PATH = # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command , where # is the value of the INPUT_FILTER tag, and is the name of an # input file. Doxygen will then use the output that the filter program writes # to standard output. # If FILTER_PATTERNS is specified, this tag will be # ignored. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. # Doxygen will compare the file name with each pattern and apply the # filter if there is a match. # The filters are a list of the form: # pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further # info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER # is applied to all files. FILTER_PATTERNS = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will be used to filter the input files when producing source # files to browse (i.e. when SOURCE_BROWSER is set to YES). FILTER_SOURCE_FILES = NO #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will # be generated. Documented entities will be cross-referenced with these sources. # Note: To get rid of all source code in the generated output, make sure also # VERBATIM_HEADERS is set to NO. SOURCE_BROWSER = NO # Setting the INLINE_SOURCES tag to YES will include the body # of functions and classes directly in the documentation. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct # doxygen to hide any special comment blocks from generated source code # fragments. Normal C and C++ comments will always remain visible. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES # then for each documented function all documented # functions referencing it will be listed. REFERENCED_BY_RELATION = NO # If the REFERENCES_RELATION tag is set to YES # then for each documented function all documented entities # called/used by that function will be listed. REFERENCES_RELATION = NO # If the REFERENCES_LINK_SOURCE tag is set to YES (the default) # and SOURCE_BROWSER tag is set to YES, then the hyperlinks from # functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will # link to the source code. # Otherwise they will link to the documentation. REFERENCES_LINK_SOURCE = YES # If the USE_HTAGS tag is set to YES then the references to source code # will point to the HTML generated by the htags(1) tool instead of doxygen # built-in source browser. The htags tool is part of GNU's global source # tagging system (see http://www.gnu.org/software/global/global.html). You # will need version 4.8.6 or higher. USE_HTAGS = NO # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen # will generate a verbatim copy of the header file for each class for # which an include is specified. Set to NO to disable this. VERBATIM_HEADERS = YES #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index # of all compounds will be generated. Enable this if the project # contains a lot of classes, structs, unions or interfaces. ALPHABETICAL_INDEX = NO # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns # in which this list will be split (can be a number in the range [1..20]) COLS_IN_ALPHA_INDEX = 5 # In case all classes in a project start with a common prefix, all # classes will be put under the same header in the alphabetical index. # The IGNORE_PREFIX tag can be used to specify one or more prefixes that # should be ignored while generating the index headers. IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES (the default) Doxygen will # generate HTML output. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `html' will be used as the default path. HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for # each generated HTML page (for example: .htm,.php,.asp). If it is left blank # doxygen will generate files with .html extension. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a personal HTML header for # each generated HTML page. If it is left blank doxygen will generate a # standard header. HTML_HEADER = # The HTML_FOOTER tag can be used to specify a personal HTML footer for # each generated HTML page. If it is left blank doxygen will generate a # standard footer. HTML_FOOTER = # The HTML_STYLESHEET tag can be used to specify a user-defined cascading # style sheet that is used by each HTML page. It can be used to # fine-tune the look of the HTML output. If the tag is left blank doxygen # will generate a default style sheet. Note that doxygen will try to copy # the style sheet file to the HTML output directory, so don't put your own # stylesheet in the HTML output directory as well, or it will be erased! HTML_STYLESHEET = # If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML # page will contain the date and time when the page was generated. Setting # this to NO can help when comparing the output of multiple runs. HTML_TIMESTAMP = NO # If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, # files or namespaces will be aligned in HTML using tables. If set to # NO a bullet list will be used. HTML_ALIGN_MEMBERS = YES # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML # documentation will contain sections that can be hidden and shown after the # page has loaded. For this to work a browser that supports # JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox # Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). HTML_DYNAMIC_SECTIONS = YES # If the GENERATE_DOCSET tag is set to YES, additional index files # will be generated that can be used as input for Apple's Xcode 3 # integrated development environment, introduced with OSX 10.5 (Leopard). # To create a documentation set, doxygen will generate a Makefile in the # HTML output directory. Running make will produce the docset in that # directory and running "make install" will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find # it at startup. # See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html for more information. GENERATE_DOCSET = NO # When GENERATE_DOCSET tag is set to YES, this tag determines the name of the # feed. A documentation feed provides an umbrella under which multiple # documentation sets from a single provider (such as a company or product suite) # can be grouped. DOCSET_FEEDNAME = "Doxygen generated docs" # When GENERATE_DOCSET tag is set to YES, this tag specifies a string that # should uniquely identify the documentation set bundle. This should be a # reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen # will append .docset to the name. DOCSET_BUNDLE_ID = org.doxygen.Project # If the GENERATE_HTMLHELP tag is set to YES, additional index files # will be generated that can be used as input for tools like the # Microsoft HTML help workshop to generate a compiled HTML help file (.chm) # of the generated HTML documentation. GENERATE_HTMLHELP = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can # be used to specify the file name of the resulting .chm file. You # can add a path in front of the file if the result should not be # written to the html output directory. CHM_FILE = # If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can # be used to specify the location (absolute path including file name) of # the HTML help compiler (hhc.exe). If non-empty doxygen will try to run # the HTML help compiler on the generated index.hhp. HHC_LOCATION = # If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag # controls if a separate .chi index file is generated (YES) or that # it should be included in the master .chm file (NO). GENERATE_CHI = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING # is used to encode HtmlHelp index (hhk), content (hhc) and project file # content. CHM_INDEX_ENCODING = # If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag # controls whether a binary table of contents is generated (YES) or a # normal table of contents (NO) in the .chm file. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members # to the contents of the HTML help documentation and to the tree view. TOC_EXPAND = NO # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and QHP_VIRTUAL_FOLDER # are set, an additional index file will be generated that can be used as input for # Qt's qhelpgenerator to generate a Qt Compressed Help (.qch) of the generated # HTML documentation. GENERATE_QHP = NO # If the QHG_LOCATION tag is specified, the QCH_FILE tag can # be used to specify the file name of the resulting .qch file. # The path specified is relative to the HTML output folder. QCH_FILE = # The QHP_NAMESPACE tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#namespace QHP_NAMESPACE = org.doxygen.Project # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#virtual-folders QHP_VIRTUAL_FOLDER = doc # If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to add. # For more information please see # http://doc.trolltech.com/qthelpproject.html#custom-filters QHP_CUST_FILTER_NAME = # The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the custom filter to add.For more information please see # Qt Help Project / Custom Filters. QHP_CUST_FILTER_ATTRS = # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this project's # filter section matches. # Qt Help Project / Filter Attributes. QHP_SECT_FILTER_ATTRS = # If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can # be used to specify the location of Qt's qhelpgenerator. # If non-empty doxygen will try to run qhelpgenerator on the generated # .qhp file. QHG_LOCATION = # If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files # will be generated, which together with the HTML files, form an Eclipse help # plugin. To install this plugin and make it available under the help contents # menu in Eclipse, the contents of the directory containing the HTML and XML # files needs to be copied into the plugins directory of eclipse. The name of # the directory within the plugins directory should be the same as # the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before the help appears. GENERATE_ECLIPSEHELP = NO # A unique identifier for the eclipse help plugin. When installing the plugin # the directory name containing the HTML and XML files should also have # this name. ECLIPSE_DOC_ID = org.doxygen.Project # The DISABLE_INDEX tag can be used to turn on/off the condensed index at # top of each HTML page. The value NO (the default) enables the index and # the value YES disables it. DISABLE_INDEX = NO # This tag can be used to set the number of enum values (range [1..20]) # that doxygen will group on one line in the generated HTML documentation. ENUM_VALUES_PER_LINE = 4 # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. # If the tag value is set to YES, a side panel will be generated # containing a tree-like index structure (just like the one that # is generated for HTML Help). For this to work a browser that supports # JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). # Windows users are probably better off using the HTML help feature. GENERATE_TREEVIEW = NO # By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, # and Class Hierarchy pages using a tree view instead of an ordered list. USE_INLINE_TREES = NO # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be # used to set the initial width (in pixels) of the frame in which the tree # is shown. TREEVIEW_WIDTH = 250 # Use this tag to change the font size of Latex formulas included # as images in the HTML documentation. The default is 10. Note that # when you change the font size after a successful doxygen run you need # to manually remove any form_*.png images from the HTML output directory # to force them to be regenerated. FORMULA_FONTSIZE = 10 # When the SEARCHENGINE tag is enabled doxygen will generate a search box for the HTML output. The underlying search engine uses javascript # and DHTML and should work on any modern browser. Note that when using HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) there is already a search function so this one should # typically be disabled. For large projects the javascript based search engine # can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. SEARCHENGINE = YES # When the SERVER_BASED_SEARCH tag is enabled the search engine will be implemented using a PHP enabled web server instead of at the web client using Javascript. Doxygen will generate the search PHP script and index # file to put on the web server. The advantage of the server based approach is that it scales better to large projects and allows full text search. The disadvances is that it is more difficult to setup # and does not have live searching capabilities. SERVER_BASED_SEARCH = NO #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will # generate Latex output. GENERATE_LATEX = YES # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `latex' will be used as the default path. LATEX_OUTPUT = latex # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be # invoked. If left blank `latex' will be used as the default command name. # Note that when enabling USE_PDFLATEX this option is only used for # generating bitmaps for formulas in the HTML output, but not in the # Makefile that is written to the output directory. LATEX_CMD_NAME = latex # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to # generate index for LaTeX. If left blank `makeindex' will be used as the # default command name. MAKEINDEX_CMD_NAME = makeindex # If the COMPACT_LATEX tag is set to YES Doxygen generates more compact # LaTeX documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_LATEX = NO # The PAPER_TYPE tag can be used to set the paper type that is used # by the printer. Possible values are: a4, a4wide, letter, legal and # executive. If left blank a4wide will be used. PAPER_TYPE = a4wide # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. EXTRA_PACKAGES = # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until # the first chapter. If it is left blank doxygen will generate a # standard header. Notice: only use this tag if you know what you are doing! LATEX_HEADER = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated # is prepared for conversion to pdf (using ps2pdf). The pdf file will # contain links (just like the HTML output) instead of page references # This makes the output suitable for online browsing using a pdf viewer. PDF_HYPERLINKS = YES # If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of # plain latex in the generated Makefile. Set this option to YES to get a # higher quality PDF documentation. USE_PDFLATEX = YES # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. # command to the generated LaTeX files. This will instruct LaTeX to keep # running if errors occur, instead of asking the user for help. # This option is also used when generating formulas in HTML. LATEX_BATCHMODE = NO # If LATEX_HIDE_INDICES is set to YES then doxygen will not # include the index chapters (such as File Index, Compound Index, etc.) # in the output. LATEX_HIDE_INDICES = NO # If LATEX_SOURCE_CODE is set to YES then doxygen will include source code with syntax highlighting in the LaTeX output. Note that which sources are shown also depends on other settings such as SOURCE_BROWSER. LATEX_SOURCE_CODE = NO #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output # The RTF output is optimized for Word 97 and may not look very pretty with # other RTF readers or editors. GENERATE_RTF = NO # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `rtf' will be used as the default path. RTF_OUTPUT = rtf # If the COMPACT_RTF tag is set to YES Doxygen generates more compact # RTF documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_RTF = NO # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated # will contain hyperlink fields. The RTF file will # contain links (just like the HTML output) instead of page references. # This makes the output suitable for online browsing using WORD or other # programs which support those fields. # Note: wordpad (write) and others do not support links. RTF_HYPERLINKS = NO # Load stylesheet definitions from file. Syntax is similar to doxygen's # config file, i.e. a series of assignments. You only have to provide # replacements, missing definitions are set to their default value. RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an rtf document. # Syntax is similar to doxygen's config file. RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES (the default) Doxygen will # generate man pages GENERATE_MAN = NO # The MAN_OUTPUT tag is used to specify where the man pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `man' will be used as the default path. MAN_OUTPUT = man # The MAN_EXTENSION tag determines the extension that is added to # the generated man pages (default is the subroutine's section .3) MAN_EXTENSION = .3 # If the MAN_LINKS tag is set to YES and Doxygen generates man output, # then it will generate one additional man file for each entity # documented in the real man page(s). These additional files # only source the real man page, but without them the man command # would be unable to find the correct page. The default is NO. MAN_LINKS = NO #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- # If the GENERATE_XML tag is set to YES Doxygen will # generate an XML file that captures the structure of # the code including all documentation. GENERATE_XML = NO # The XML_OUTPUT tag is used to specify where the XML pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `xml' will be used as the default path. XML_OUTPUT = xml # The XML_SCHEMA tag can be used to specify an XML schema, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_SCHEMA = # The XML_DTD tag can be used to specify an XML DTD, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_DTD = # If the XML_PROGRAMLISTING tag is set to YES Doxygen will # dump the program listings (including syntax highlighting # and cross-referencing information) to the XML output. Note that # enabling this will significantly increase the size of the XML output. XML_PROGRAMLISTING = YES #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- # If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will # generate an AutoGen Definitions (see autogen.sf.net) file # that captures the structure of the code including all # documentation. Note that this feature is still experimental # and incomplete at the moment. GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # configuration options related to the Perl module output #--------------------------------------------------------------------------- # If the GENERATE_PERLMOD tag is set to YES Doxygen will # generate a Perl module file that captures the structure of # the code including all documentation. Note that this # feature is still experimental and incomplete at the # moment. GENERATE_PERLMOD = NO # If the PERLMOD_LATEX tag is set to YES Doxygen will generate # the necessary Makefile rules, Perl scripts and LaTeX code to be able # to generate PDF and DVI output from the Perl module output. PERLMOD_LATEX = NO # If the PERLMOD_PRETTY tag is set to YES the Perl module output will be # nicely formatted so it can be parsed by a human reader. # This is useful # if you want to understand what is going on. # On the other hand, if this # tag is set to NO the size of the Perl module output will be much smaller # and Perl will parse it just the same. PERLMOD_PRETTY = YES # The names of the make variables in the generated doxyrules.make file # are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. # This is useful so different doxyrules.make files included by the same # Makefile don't overwrite each other's variables. PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will # evaluate all C-preprocessor directives found in the sources and include # files. ENABLE_PREPROCESSING = YES # If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro # names in the source code. If set to NO (the default) only conditional # compilation will be performed. Macro expansion can be done in a controlled # way by setting EXPAND_ONLY_PREDEF to YES. MACRO_EXPANSION = NO # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED and EXPAND_AS_DEFINED tags. EXPAND_ONLY_PREDEF = NO # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # in the INCLUDE_PATH (see below) will be search if a #include is found. SEARCH_INCLUDES = YES # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by # the preprocessor. INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the # directories. If left blank, the patterns specified with FILE_PATTERNS will # be used. INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that # are defined before the preprocessor is started (similar to the -D option of # gcc). The argument of the tag is a list of macros of the form: name # or name=definition (no spaces). If the definition and the = are # omitted =1 is assumed. To prevent a macro definition from being # undefined via #undef or recursively expanded use the := operator # instead of the = operator. PREDEFINED = # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded. # The macro definition that is found in the sources will be used. # Use the PREDEFINED tag if you want to use a different macro definition. EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then # doxygen's preprocessor will remove all function-like macros that are alone # on a line, have an all uppercase name, and do not end with a semicolon. Such # function macros are typically used for boiler-plate code, and will confuse # the parser if not removed. SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration::additions related to external references #--------------------------------------------------------------------------- # The TAGFILES option can be used to specify one or more tagfiles. # Optionally an initial location of the external documentation # can be added for each tagfile. The format of a tag file without # this location is as follows: # # TAGFILES = file1 file2 ... # Adding location for the tag files is done as follows: # # TAGFILES = file1=loc1 "file2 = loc2" ... # where "loc1" and "loc2" can be relative or absolute paths or # URLs. If a location is present for each tag, the installdox tool # does not have to be run to correct the links. # Note that each tag file must have a unique name # (where the name does NOT include the path) # If a tag file is not located in the directory in which doxygen # is run, you must also specify the path to the tagfile here. TAGFILES = # When a file name is specified after GENERATE_TAGFILE, doxygen will create # a tag file that is based on the input files it reads. GENERATE_TAGFILE = # If the ALLEXTERNALS tag is set to YES all external classes will be listed # in the class index. If set to NO only the inherited external classes # will be listed. ALLEXTERNALS = NO # If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed # in the modules index. If set to NO, only the current project's groups will # be listed. EXTERNAL_GROUPS = YES # The PERL_PATH should be the absolute path and name of the perl script # interpreter (i.e. the result of `which perl'). PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will # generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base # or super classes. Setting the tag to NO turns the diagrams off. Note that # this option is superseded by the HAVE_DOT option below. This is only a # fallback. It is recommended to install and use dot, since it yields more # powerful graphs. CLASS_DIAGRAMS = NO # You can define message sequence charts within doxygen comments using the \msc # command. Doxygen will then run the mscgen tool (see # http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the # documentation. The MSCGEN_PATH tag allows you to specify the directory where # the mscgen tool resides. If left empty the tool is assumed to be found in the # default search path. MSCGEN_PATH = # If set to YES, the inheritance and collaboration graphs will hide # inheritance and usage relations if the target is undocumented # or is not a class. HIDE_UNDOC_RELATIONS = YES # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz, a graph visualization # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) HAVE_DOT = NO # By default doxygen will write a font called FreeSans.ttf to the output # directory and reference it in all dot files that doxygen generates. This # font does not include all possible unicode characters however, so when you need # these (or just want a differently looking font) you can specify the font name # using DOT_FONTNAME. You need need to make sure dot is able to find the font, # which can be done by putting it in a standard location or by setting the # DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory # containing the font. DOT_FONTNAME = FreeSans # The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. # The default size is 10pt. DOT_FONTSIZE = 10 # By default doxygen will tell dot to use the output directory to look for the # FreeSans.ttf font (which doxygen will put there itself). If you specify a # different font using DOT_FONTNAME you can set the path where dot # can find it using this tag. DOT_FONTPATH = # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect inheritance relations. Setting this tag to YES will force the # the CLASS_DIAGRAMS tag to NO. CLASS_GRAPH = YES # If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect implementation dependencies (inheritance, containment, and # class references variables) of the class with other documented classes. COLLABORATION_GRAPH = YES # If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen # will generate a graph for groups, showing the direct groups dependencies GROUP_GRAPHS = YES # If the UML_LOOK tag is set to YES doxygen will generate inheritance and # collaboration diagrams in a style similar to the OMG's Unified Modeling # Language. UML_LOOK = NO # If set to YES, the inheritance and collaboration graphs will show the # relations between templates and their instances. TEMPLATE_RELATIONS = NO # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT # tags are set to YES then doxygen will generate a graph for each documented # file showing the direct and indirect include dependencies of the file with # other documented files. INCLUDE_GRAPH = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and # HAVE_DOT tags are set to YES then doxygen will generate a graph for each # documented header file showing the documented files that directly or # indirectly include this file. INCLUDED_BY_GRAPH = YES # If the CALL_GRAPH and HAVE_DOT options are set to YES then # doxygen will generate a call dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable call graphs # for selected functions only using the \callgraph command. CALL_GRAPH = NO # If the CALLER_GRAPH and HAVE_DOT tags are set to YES then # doxygen will generate a caller dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable caller # graphs for selected functions only using the \callergraph command. CALLER_GRAPH = NO # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen # will graphical hierarchy of all classes instead of a textual one. GRAPHICAL_HIERARCHY = YES # If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES # then doxygen will show the dependencies a directory has on other directories # in a graphical way. The dependency relations are determined by the #include # relations between the files in the directories. DIRECTORY_GRAPH = YES # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images # generated by dot. Possible values are png, jpg, or gif # If left blank png will be used. DOT_IMAGE_FORMAT = png # The tag DOT_PATH can be used to specify the path where the dot tool can be # found. If left blank, it is assumed the dot tool can be found in the path. DOT_PATH = # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the # \dotfile command). DOTFILE_DIRS = # The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of # nodes that will be shown in the graph. If the number of nodes in a graph # becomes larger than this value, doxygen will truncate the graph, which is # visualized by representing a node as a red box. Note that doxygen if the # number of direct children of the root node in a graph is already larger than # DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note # that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. DOT_GRAPH_MAX_NODES = 50 # The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the # graphs generated by dot. A depth value of 3 means that only nodes reachable # from the root by following a path via at most 3 edges will be shown. Nodes # that lay further from the root node will be omitted. Note that setting this # option to 1 or 2 may greatly reduce the computation time needed for large # code bases. Also note that the size of a graph can be further restricted by # DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. MAX_DOT_GRAPH_DEPTH = 0 # Set the DOT_TRANSPARENT tag to YES to generate images with a transparent # background. This is disabled by default, because dot on Windows does not # seem to support this out of the box. Warning: Depending on the platform used, # enabling this option may lead to badly anti-aliased labels on the edges of # a graph (i.e. they become hard to read). DOT_TRANSPARENT = NO # Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output # files in one run (i.e. multiple -o and -T options on the command line). This # makes dot run faster, but since only newer versions of dot (>1.8.10) # support this, this feature is disabled by default. DOT_MULTI_TARGETS = YES # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will # generate a legend page explaining the meaning of the various boxes and # arrows in the dot generated graphs. GENERATE_LEGEND = YES # If the DOT_CLEANUP tag is set to YES (the default) Doxygen will # remove the intermediate dot files that are used to generate # the various graphs. DOT_CLEANUP = YES gpick-gpick-0.2.6rc1/extern/000077500000000000000000000000001315430016700156225ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/extern/SConscript000066400000000000000000000001031315430016700176260ustar00rootroot00000000000000#!/usr/bin/env python Import('*') objects = [] Return('objects') gpick-gpick-0.2.6rc1/extern/lempar.c000066400000000000000000000661751315430016700172650ustar00rootroot00000000000000/* Driver template for the LEMON parser generator. ** The author disclaims copyright to this source code. */ /* First off, code is included that follows the "include" declaration ** in the input grammar file. */ #include %% /* Next is all token values, in a form suitable for use by makeheaders. ** This section will be null unless lemon is run with the -m switch. */ /* ** These constants (all generated automatically by the parser generator) ** specify the various kinds of tokens (terminals) that the parser ** understands. ** ** Each symbol here is a terminal symbol in the grammar. */ %% /* Make sure the INTERFACE macro is defined. */ #ifndef INTERFACE # define INTERFACE 1 #endif /* The next thing included is series of defines which control ** various aspects of the generated parser. ** YYCODETYPE is the data type used for storing terminal ** and nonterminal numbers. "unsigned char" is ** used if there are fewer than 250 terminals ** and nonterminals. "int" is used otherwise. ** YYNOCODE is a number of type YYCODETYPE which corresponds ** to no legal terminal or nonterminal number. This ** number is used to fill in empty slots of the hash ** table. ** YYFALLBACK If defined, this indicates that one or more tokens ** have fall-back values which should be used if the ** original value of the token will not parse. ** YYACTIONTYPE is the data type used for storing terminal ** and nonterminal numbers. "unsigned char" is ** used if there are fewer than 250 rules and ** states combined. "int" is used otherwise. ** ParseTOKENTYPE is the data type used for minor tokens given ** directly to the parser from the tokenizer. ** YYMINORTYPE is the data type used for all minor tokens. ** This is typically a union of many types, one of ** which is ParseTOKENTYPE. The entry in the union ** for base tokens is called "yy0". ** YYSTACKDEPTH is the maximum depth of the parser's stack. If ** zero the stack is dynamically sized using realloc() ** ParseARG_SDECL A static variable declaration for the %extra_argument ** ParseARG_PDECL A parameter declaration for the %extra_argument ** ParseARG_STORE Code to store %extra_argument into yypParser ** ParseARG_FETCH Code to extract %extra_argument from yypParser ** YYNSTATE the combined number of states. ** YYNRULE the number of rules in the grammar ** YYERRORSYMBOL is the code number of the error symbol. If not ** defined, then do no error processing. */ %% #define YY_NO_ACTION (YYNSTATE+YYNRULE+2) #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1) #define YY_ERROR_ACTION (YYNSTATE+YYNRULE) /* The yyzerominor constant is used to initialize instances of ** YYMINORTYPE objects to zero. */ static const YYMINORTYPE yyzerominor = { 0 }; /* Define the yytestcase() macro to be a no-op if is not already defined ** otherwise. ** ** Applications can choose to define yytestcase() in the %include section ** to a macro that can assist in verifying code coverage. For production ** code the yytestcase() macro should be turned off. But it is useful ** for testing. */ #ifndef yytestcase # define yytestcase(X) #endif /* Next are the tables used to determine what action to take based on the ** current state and lookahead token. These tables are used to implement ** functions that take a state number and lookahead value and return an ** action integer. ** ** Suppose the action integer is N. Then the action is determined as ** follows ** ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead ** token onto the stack and goto state N. ** ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE. ** ** N == YYNSTATE+YYNRULE A syntax error has occurred. ** ** N == YYNSTATE+YYNRULE+1 The parser accepts its input. ** ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused ** slots in the yy_action[] table. ** ** The action table is constructed as a single large table named yy_action[]. ** Given state S and lookahead X, the action is computed as ** ** yy_action[ yy_shift_ofst[S] + X ] ** ** If the index value yy_shift_ofst[S]+X is out of range or if the value ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S] ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table ** and that yy_default[S] should be used instead. ** ** The formula above is for computing the action when the lookahead is ** a terminal symbol. If the lookahead is a non-terminal (as occurs after ** a reduce action) then the yy_reduce_ofst[] array is used in place of ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of ** YY_SHIFT_USE_DFLT. ** ** The following are the tables generated in this section: ** ** yy_action[] A single table containing all actions. ** yy_lookahead[] A table containing the lookahead for each entry in ** yy_action. Used to detect hash collisions. ** yy_shift_ofst[] For each state, the offset into yy_action for ** shifting terminals. ** yy_reduce_ofst[] For each state, the offset into yy_action for ** shifting non-terminals after a reduce. ** yy_default[] Default action for each state. */ %% /* The next table maps tokens into fallback tokens. If a construct ** like the following: ** ** %fallback ID X Y Z. ** ** appears in the grammar, then ID becomes a fallback token for X, Y, ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser ** but it does not parse, the type of the token is changed to ID and ** the parse is retried before an error is thrown. */ #ifdef YYFALLBACK static const YYCODETYPE yyFallback[] = { %% }; #endif /* YYFALLBACK */ /* The following structure represents a single element of the ** parser's stack. Information stored includes: ** ** + The state number for the parser at this level of the stack. ** ** + The value of the token stored at this level of the stack. ** (In other words, the "major" token.) ** ** + The semantic value stored at this level of the stack. This is ** the information used by the action routines in the grammar. ** It is sometimes called the "minor" token. */ struct yyStackEntry { YYACTIONTYPE stateno; /* The state-number */ YYCODETYPE major; /* The major token value. This is the code ** number for the token at this stack level */ YYMINORTYPE minor; /* The user-supplied minor token value. This ** is the value of the token */ }; typedef struct yyStackEntry yyStackEntry; /* The state of the parser is completely contained in an instance of ** the following structure */ struct yyParser { int yyidx; /* Index of top element in stack */ #ifdef YYTRACKMAXSTACKDEPTH int yyidxMax; /* Maximum value of yyidx */ #endif int yyerrcnt; /* Shifts left before out of the error */ ParseARG_SDECL /* A place to hold %extra_argument */ #if YYSTACKDEPTH<=0 int yystksz; /* Current side of the stack */ yyStackEntry *yystack; /* The parser's stack */ #else yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */ #endif }; typedef struct yyParser yyParser; #ifndef NDEBUG #include static FILE *yyTraceFILE = 0; static char *yyTracePrompt = 0; #endif /* NDEBUG */ #ifndef NDEBUG /* ** Turn parser tracing on by giving a stream to which to write the trace ** and a prompt to preface each trace message. Tracing is turned off ** by making either argument NULL ** ** Inputs: **
    **
  • A FILE* to which trace output should be written. ** If NULL, then tracing is turned off. **
  • A prefix string written at the beginning of every ** line of trace output. If NULL, then tracing is ** turned off. **
** ** Outputs: ** None. */ void ParseTrace(FILE *TraceFILE, char *zTracePrompt){ yyTraceFILE = TraceFILE; yyTracePrompt = zTracePrompt; if( yyTraceFILE==0 ) yyTracePrompt = 0; else if( yyTracePrompt==0 ) yyTraceFILE = 0; } #endif /* NDEBUG */ #ifndef NDEBUG /* For tracing shifts, the names of all terminals and nonterminals ** are required. The following table supplies these names */ static const char *const yyTokenName[] = { %% }; #endif /* NDEBUG */ #ifndef NDEBUG /* For tracing reduce actions, the names of all rules are required. */ static const char *const yyRuleName[] = { %% }; #endif /* NDEBUG */ #if YYSTACKDEPTH<=0 /* ** Try to increase the size of the parser stack. */ static void yyGrowStack(yyParser *p){ int newSize; yyStackEntry *pNew; newSize = p->yystksz*2 + 100; pNew = realloc(p->yystack, newSize*sizeof(pNew[0])); if( pNew ){ p->yystack = pNew; p->yystksz = newSize; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sStack grows to %d entries!\n", yyTracePrompt, p->yystksz); } #endif } } #endif /* ** This function allocates a new parser. ** The only argument is a pointer to a function which works like ** malloc. ** ** Inputs: ** A pointer to the function used to allocate memory. ** ** Outputs: ** A pointer to a parser. This pointer is used in subsequent calls ** to Parse and ParseFree. */ void *ParseAlloc(void *(*mallocProc)(size_t)){ yyParser *pParser; pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) ); if( pParser ){ pParser->yyidx = -1; #ifdef YYTRACKMAXSTACKDEPTH pParser->yyidxMax = 0; #endif #if YYSTACKDEPTH<=0 pParser->yystack = NULL; pParser->yystksz = 0; yyGrowStack(pParser); #endif } return pParser; } /* The following function deletes the value associated with a ** symbol. The symbol can be either a terminal or nonterminal. ** "yymajor" is the symbol code, and "yypminor" is a pointer to ** the value. */ static void yy_destructor( yyParser *yypParser, /* The parser */ YYCODETYPE yymajor, /* Type code for object to destroy */ YYMINORTYPE *yypminor /* The object to be destroyed */ ){ ParseARG_FETCH; switch( yymajor ){ /* Here is inserted the actions which take place when a ** terminal or non-terminal is destroyed. This can happen ** when the symbol is popped from the stack during a ** reduce or during error processing or when a parser is ** being destroyed before it is finished parsing. ** ** Note: during a reduce, the only symbols destroyed are those ** which appear on the RHS of the rule, but which are not used ** inside the C code. */ %% default: break; /* If no destructor action specified: do nothing */ } } /* ** Pop the parser's stack once. ** ** If there is a destructor routine associated with the token which ** is popped from the stack, then call it. ** ** Return the major token number for the symbol popped. */ static int yy_pop_parser_stack(yyParser *pParser){ YYCODETYPE yymajor; yyStackEntry *yytos = &pParser->yystack[pParser->yyidx]; if( pParser->yyidx<0 ) return 0; #ifndef NDEBUG if( yyTraceFILE && pParser->yyidx>=0 ){ fprintf(yyTraceFILE,"%sPopping %s\n", yyTracePrompt, yyTokenName[yytos->major]); } #endif yymajor = yytos->major; yy_destructor(pParser, yymajor, &yytos->minor); pParser->yyidx--; return yymajor; } /* ** Deallocate and destroy a parser. Destructors are all called for ** all stack elements before shutting the parser down. ** ** Inputs: **
    **
  • A pointer to the parser. This should be a pointer ** obtained from ParseAlloc. **
  • A pointer to a function used to reclaim memory obtained ** from malloc. **
*/ void ParseFree( void *p, /* The parser to be deleted */ void (*freeProc)(void*) /* Function used to reclaim memory */ ){ yyParser *pParser = (yyParser*)p; if( pParser==0 ) return; while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser); #if YYSTACKDEPTH<=0 free(pParser->yystack); #endif (*freeProc)((void*)pParser); } /* ** Return the peak depth of the stack for a parser. */ #ifdef YYTRACKMAXSTACKDEPTH int ParseStackPeak(void *p){ yyParser *pParser = (yyParser*)p; return pParser->yyidxMax; } #endif /* ** Find the appropriate action for a parser given the terminal ** look-ahead token iLookAhead. ** ** If the look-ahead token is YYNOCODE, then check to see if the action is ** independent of the look-ahead. If it is, return the action, otherwise ** return YY_NO_ACTION. */ static int yy_find_shift_action( yyParser *pParser, /* The parser */ YYCODETYPE iLookAhead /* The look-ahead token */ ){ int i; int stateno = pParser->yystack[pParser->yyidx].stateno; if( stateno>YY_SHIFT_COUNT || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){ return yy_default[stateno]; } assert( iLookAhead!=YYNOCODE ); i += iLookAhead; if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ if( iLookAhead>0 ){ #ifdef YYFALLBACK YYCODETYPE iFallback; /* Fallback token */ if( iLookAhead %s\n", yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]); } #endif return yy_find_shift_action(pParser, iFallback); } #endif #ifdef YYWILDCARD { int j = i - iLookAhead + YYWILDCARD; if( #if YY_SHIFT_MIN+YYWILDCARD<0 j>=0 && #endif #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT j %s\n", yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]); } #endif /* NDEBUG */ return yy_action[j]; } } #endif /* YYWILDCARD */ } return yy_default[stateno]; }else{ return yy_action[i]; } } /* ** Find the appropriate action for a parser given the non-terminal ** look-ahead token iLookAhead. ** ** If the look-ahead token is YYNOCODE, then check to see if the action is ** independent of the look-ahead. If it is, return the action, otherwise ** return YY_NO_ACTION. */ static int yy_find_reduce_action( int stateno, /* Current state number */ YYCODETYPE iLookAhead /* The look-ahead token */ ){ int i; #ifdef YYERRORSYMBOL if( stateno>YY_REDUCE_COUNT ){ return yy_default[stateno]; } #else assert( stateno<=YY_REDUCE_COUNT ); #endif i = yy_reduce_ofst[stateno]; assert( i!=YY_REDUCE_USE_DFLT ); assert( iLookAhead!=YYNOCODE ); i += iLookAhead; #ifdef YYERRORSYMBOL if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){ return yy_default[stateno]; } #else assert( i>=0 && iyyidx--; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt); } #endif while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will execute if the parser ** stack every overflows */ %% ParseARG_STORE; /* Suppress warning about unused %extra_argument var */ } /* ** Perform a shift action. */ static void yy_shift( yyParser *yypParser, /* The parser to be shifted */ int yyNewState, /* The new state to shift in */ int yyMajor, /* The major token to shift in */ YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */ ){ yyStackEntry *yytos; yypParser->yyidx++; #ifdef YYTRACKMAXSTACKDEPTH if( yypParser->yyidx>yypParser->yyidxMax ){ yypParser->yyidxMax = yypParser->yyidx; } #endif #if YYSTACKDEPTH>0 if( yypParser->yyidx>=YYSTACKDEPTH ){ yyStackOverflow(yypParser, yypMinor); return; } #else if( yypParser->yyidx>=yypParser->yystksz ){ yyGrowStack(yypParser); if( yypParser->yyidx>=yypParser->yystksz ){ yyStackOverflow(yypParser, yypMinor); return; } } #endif yytos = &yypParser->yystack[yypParser->yyidx]; yytos->stateno = (YYACTIONTYPE)yyNewState; yytos->major = (YYCODETYPE)yyMajor; yytos->minor = *yypMinor; #ifndef NDEBUG if( yyTraceFILE && yypParser->yyidx>0 ){ int i; fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState); fprintf(yyTraceFILE,"%sStack:",yyTracePrompt); for(i=1; i<=yypParser->yyidx; i++) fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]); fprintf(yyTraceFILE,"\n"); } #endif } /* The following table contains information about every rule that ** is used during the reduce. */ static const struct { YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */ unsigned char nrhs; /* Number of right-hand side symbols in the rule */ } yyRuleInfo[] = { %% }; static void yy_accept(yyParser*); /* Forward Declaration */ /* ** Perform a reduce action and the shift that must immediately ** follow the reduce. */ static void yy_reduce( yyParser *yypParser, /* The parser */ int yyruleno /* Number of the rule by which to reduce */ ){ int yygoto; /* The next state */ int yyact; /* The next action */ YYMINORTYPE yygotominor; /* The LHS of the rule reduced */ yyStackEntry *yymsp; /* The top of the parser's stack */ int yysize; /* Amount to pop the stack */ ParseARG_FETCH; yymsp = &yypParser->yystack[yypParser->yyidx]; #ifndef NDEBUG if( yyTraceFILE && yyruleno>=0 && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){ fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt, yyRuleName[yyruleno]); } #endif /* NDEBUG */ /* Silence complaints from purify about yygotominor being uninitialized ** in some cases when it is copied into the stack after the following ** switch. yygotominor is uninitialized when a rule reduces that does ** not set the value of its left-hand side nonterminal. Leaving the ** value of the nonterminal uninitialized is utterly harmless as long ** as the value is never used. So really the only thing this code ** accomplishes is to quieten purify. ** ** 2007-01-16: The wireshark project (www.wireshark.org) reports that ** without this code, their parser segfaults. I'm not sure what there ** parser is doing to make this happen. This is the second bug report ** from wireshark this week. Clearly they are stressing Lemon in ways ** that it has not been previously stressed... (SQLite ticket #2172) */ /*memset(&yygotominor, 0, sizeof(yygotominor));*/ yygotominor = yyzerominor; switch( yyruleno ){ /* Beginning here are the reduction cases. A typical example ** follows: ** case 0: ** #line ** { ... } // User supplied code ** #line ** break; */ %% }; yygoto = yyRuleInfo[yyruleno].lhs; yysize = yyRuleInfo[yyruleno].nrhs; yypParser->yyidx -= yysize; yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto); if( yyact < YYNSTATE ){ #ifdef NDEBUG /* If we are not debugging and the reduce action popped at least ** one element off the stack, then we can push the new element back ** onto the stack here, and skip the stack overflow test in yy_shift(). ** That gives a significant speed improvement. */ if( yysize ){ yypParser->yyidx++; yymsp -= yysize-1; yymsp->stateno = (YYACTIONTYPE)yyact; yymsp->major = (YYCODETYPE)yygoto; yymsp->minor = yygotominor; }else #endif { yy_shift(yypParser,yyact,yygoto,&yygotominor); } }else{ assert( yyact == YYNSTATE + YYNRULE + 1 ); yy_accept(yypParser); } } /* ** The following code executes when the parse fails */ #ifndef YYNOERRORRECOVERY static void yy_parse_failed( yyParser *yypParser /* The parser */ ){ ParseARG_FETCH; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt); } #endif while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will be executed whenever the ** parser fails */ %% ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */ } #endif /* YYNOERRORRECOVERY */ /* ** The following code executes when a syntax error first occurs. */ static void yy_syntax_error( yyParser *yypParser, /* The parser */ int yymajor, /* The major type of the error token */ YYMINORTYPE yyminor /* The minor type of the error token */ ){ ParseARG_FETCH; #define TOKEN (yyminor.yy0) %% ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* ** The following is executed when the parser accepts */ static void yy_accept( yyParser *yypParser /* The parser */ ){ ParseARG_FETCH; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt); } #endif while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will be executed whenever the ** parser accepts */ %% ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* The main parser program. ** The first argument is a pointer to a structure obtained from ** "ParseAlloc" which describes the current state of the parser. ** The second argument is the major token number. The third is ** the minor token. The fourth optional argument is whatever the ** user wants (and specified in the grammar) and is available for ** use by the action routines. ** ** Inputs: **
    **
  • A pointer to the parser (an opaque structure.) **
  • The major token number. **
  • The minor token number. **
  • An option argument of a grammar-specified type. **
** ** Outputs: ** None. */ void Parse( void *yyp, /* The parser */ int yymajor, /* The major token code number */ ParseTOKENTYPE yyminor /* The value for the token */ ParseARG_PDECL /* Optional %extra_argument parameter */ ){ YYMINORTYPE yyminorunion; int yyact; /* The parser action. */ int yyendofinput; /* True if we are at the end of input */ #ifdef YYERRORSYMBOL int yyerrorhit = 0; /* True if yymajor has invoked an error */ #endif yyParser *yypParser; /* The parser */ /* (re)initialize the parser, if necessary */ yypParser = (yyParser*)yyp; if( yypParser->yyidx<0 ){ #if YYSTACKDEPTH<=0 if( yypParser->yystksz <=0 ){ /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/ yyminorunion = yyzerominor; yyStackOverflow(yypParser, &yyminorunion); return; } #endif yypParser->yyidx = 0; yypParser->yyerrcnt = -1; yypParser->yystack[0].stateno = 0; yypParser->yystack[0].major = 0; } yyminorunion.yy0 = yyminor; yyendofinput = (yymajor==0); ParseARG_STORE; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]); } #endif do{ yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor); if( yyactyyerrcnt--; yymajor = YYNOCODE; }else if( yyact < YYNSTATE + YYNRULE ){ yy_reduce(yypParser,yyact-YYNSTATE); }else{ assert( yyact == YY_ERROR_ACTION ); #ifdef YYERRORSYMBOL int yymx; #endif #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt); } #endif #ifdef YYERRORSYMBOL /* A syntax error has occurred. ** The response to an error depends upon whether or not the ** grammar defines an error token "ERROR". ** ** This is what we do if the grammar does define ERROR: ** ** * Call the %syntax_error function. ** ** * Begin popping the stack until we enter a state where ** it is legal to shift the error symbol, then shift ** the error symbol. ** ** * Set the error count to three. ** ** * Begin accepting and shifting new tokens. No new error ** processing will occur until three tokens have been ** shifted successfully. ** */ if( yypParser->yyerrcnt<0 ){ yy_syntax_error(yypParser,yymajor,yyminorunion); } yymx = yypParser->yystack[yypParser->yyidx].major; if( yymx==YYERRORSYMBOL || yyerrorhit ){ #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sDiscard input token %s\n", yyTracePrompt,yyTokenName[yymajor]); } #endif yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion); yymajor = YYNOCODE; }else{ while( yypParser->yyidx >= 0 && yymx != YYERRORSYMBOL && (yyact = yy_find_reduce_action( yypParser->yystack[yypParser->yyidx].stateno, YYERRORSYMBOL)) >= YYNSTATE ){ yy_pop_parser_stack(yypParser); } if( yypParser->yyidx < 0 || yymajor==0 ){ yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); yy_parse_failed(yypParser); yymajor = YYNOCODE; }else if( yymx!=YYERRORSYMBOL ){ YYMINORTYPE u2; u2.YYERRSYMDT = 0; yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2); } } yypParser->yyerrcnt = 3; yyerrorhit = 1; #elif defined(YYNOERRORRECOVERY) /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to ** do any kind of error recovery. Instead, simply invoke the syntax ** error routine and continue going as if nothing had happened. ** ** Applications can set this macro (for example inside %include) if ** they intend to abandon the parse upon the first syntax error seen. */ yy_syntax_error(yypParser,yymajor,yyminorunion); yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); yymajor = YYNOCODE; #else /* YYERRORSYMBOL is not defined */ /* This is what we do if the grammar does not define ERROR: ** ** * Report an error message, and throw away the input token. ** ** * If the input token is $, then fail the parse. ** ** As before, subsequent error messages are suppressed until ** three input tokens have been successfully shifted. */ if( yypParser->yyerrcnt<=0 ){ yy_syntax_error(yypParser,yymajor,yyminorunion); } yypParser->yyerrcnt = 3; yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion); if( yyendofinput ){ yy_parse_failed(yypParser); } yymajor = YYNOCODE; #endif } }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 ); return; } gpick-gpick-0.2.6rc1/installer/000077500000000000000000000000001315430016700163125ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/installer/License.txt000066400000000000000000000027701315430016700204430ustar00rootroot00000000000000Copyright (c) 2009-2013, Albertas Vyniauskas and Gpick developers All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. gpick-gpick-0.2.6rc1/installer/Makefile000066400000000000000000000020661315430016700177560ustar00rootroot00000000000000 VERSION_FULL=$(shell python -c 'import getversion; getversion.getversion("full")') VERSION=$(shell python -c 'import getversion; getversion.getversion("ms")') MSI=gpick_$(VERSION_FULL) HEAT_SRCS=gpick_files.xstl gtk_files.xstl SRCS=gpick.wxs $(HEAT_SRCS:.xstl=.wxs) OBJS=$(SRCS:.wxs=.wixobj) CANDLE=candle.exe LIGHT=light.exe HEAT=heat.exe HEAT_FLAGS=-ag -dr INSTALLDIR -suid -srd -var var.FilePath FLAGS=-dFilePath=files -dVersionFull=$(VERSION_FULL) -dVersion=$(VERSION) LIGHT_FLAGS=-ext WixUtilExtension -ext WixUIExtension $(FLAGS) CANDLE_FLAGS=$(FLAGS) DEPFILES= files/Gpick.exe .SUFFIXES: .wxs .wixobj .xstl all: $(MSI).msi $(MSI).msi: $(OBJS) $(DEPFILES) $(HEAT_SRCS) $(LIGHT) -nologo $(LIGHT_FLAGS) -out $@ $(OBJS) .xstl.wxs: $(HEAT) dir "files" -nologo $(HEAT_FLAGS) -cg C.Files.$(<:.xstl=) -t $< -out $@ .wxs.wixobj: $(CANDLE) -nologo $(CANDLE_FLAGS) -out $@ $^ clean: $(RM) $(MSI).msi $(OBJS) install: $(MSI).msi $(RM) install.log msiexec -i $(MSI).msi -l*v install.log uninstall: msiexec -x $(MSI).msi gpick-gpick-0.2.6rc1/installer/getversion.py000066400000000000000000000005631315430016700210550ustar00rootroot00000000000000import os,sys,re parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0,parentdir) import version def getversion(style): if style == "full": print version.GPICK_BUILD_VERSION else: result = re.match(r"^(\d+\.\d+\.\d+)(.*)$", version.GPICK_BUILD_VERSION) if result: print result.group(1) else: print "invalid_version" gpick-gpick-0.2.6rc1/installer/gpick.wxs000066400000000000000000000224501315430016700201550ustar00rootroot00000000000000 Privileged 1 NOT Installed Installed AND PATCH Installed NOT Installed 1 NOT Installed OR WixUI_InstallMode = "Change" Installed AND NOT PATCH Installed AND PATCH 1 1 1 1 1 gpick-gpick-0.2.6rc1/installer/gpick_files.xstl000066400000000000000000000013241315430016700215050ustar00rootroot00000000000000 gpick-gpick-0.2.6rc1/installer/gtk_files.xstl000066400000000000000000000013661315430016700212030ustar00rootroot00000000000000 gpick-gpick-0.2.6rc1/installer/script.nsi000066400000000000000000000311031315430016700203270ustar00rootroot00000000000000 !include "MUI2.nsh" !include "FileFunc.nsh" ; GetOptions !include ..\build\version.nsi !define PRODUCT_VERSION "${VERSION}" !define PRODUCT_NAME "Gpick" !define PRODUCT_NAME_SMALL "gpick" !define PRODUCT_PUBLISHER "Albertas Vyniauskas" !define PRODUCT_WEB_SITE "http://code.google.com/p/gpick/" !define PRODUCT_UNINST_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}" !define PRODUCT_UNINST_ROOT_KEY "HKLM" !define REGISTRY_APP_PATHS "Software\Microsoft\Windows\CurrentVersion\App Paths" Name "Gpick" OutFile "Gpick_${VERSION}_win32-setup.exe" Caption "Gpick v${VERSION} Setup" SetCompressor /SOLID lzma SetCompressorDictSize 32 InstallDir $PROGRAMFILES\Gpick InstallDirRegKey HKLM "Software\Gpick" "" RequestExecutionLevel admin ; gtk installer name for embedding !define GTK_INSTALLER_EXE "gtk2-runtime-2.24.10-2012-10-10-ash.exe" Var MUI_TEMP Var STARTMENU_FOLDER var install_option_removeold ; uninstall the old version first (if present): yes (default), no. var gtk_mode ; "public", "private" or "none" var gtk_tmp ; temporary variable !define MUI_WELCOMEPAGE !define MUI_LICENSEPAGE !define MUI_DIRECTORYPAGE !define MUI_ABORTWARNING !define MUI_UNINSTALLER !define MUI_UNCONFIRMPAGE !define MUI_FINISHPAGE !insertmacro MUI_PAGE_WELCOME !insertmacro MUI_PAGE_LICENSE "License.txt" !define MUI_PAGE_CUSTOMFUNCTION_LEAVE on_components_page_leave !insertmacro MUI_PAGE_COMPONENTS !insertmacro MUI_PAGE_DIRECTORY !insertmacro MUI_PAGE_STARTMENU Application $STARTMENU_FOLDER !insertmacro MUI_PAGE_INSTFILES !define MUI_FINISHPAGE_NOAUTOCLOSE !define MUI_FINISHPAGE_NOREBOOTSUPPORT !insertmacro MUI_PAGE_FINISH !insertmacro MUI_UNPAGE_CONFIRM !insertmacro MUI_UNPAGE_INSTFILES !insertmacro MUI_LANGUAGE "English" AllowSkipFiles off var gtk_dll_abs_path Section "!Program Files" SecProgramFiles SectionIn RO SetOutPath "$INSTDIR" File ..\build\source\gpick.exe File lua5.2.dll SetOutPath "$INSTDIR\share\gpick" File ..\share\gpick\colors0.txt File ..\share\gpick\colors.txt File ..\share\gpick\gpick-falloff-none.png File ..\share\gpick\gpick-falloff-linear.png File ..\share\gpick\gpick-falloff-quadratic.png File ..\share\gpick\gpick-falloff-cubic.png File ..\share\gpick\gpick-falloff-exponential.png File ..\share\icons\hicolor\48x48\apps\gpick.png File ..\share\gpick\init.lua File ..\share\gpick\helpers.lua File ..\share\gpick\layouts.lua SetOutPath "$INSTDIR" WriteRegStr HKLM "Software\Gpick" "" $INSTDIR SetShellVarContext all ; use all user variables as opposed to current user ; Don't set any paths for this exe if it has a private GTK+ installation. !ifndef NO_GTK StrCmp $gtk_mode "private" skip_exe_PATH !endif ; set a special path for this exe, as GTK may not be in a global path. ReadRegStr $gtk_dll_abs_path HKLM "SOFTWARE\GTK\2.0" "DllPath" WriteRegStr HKLM "${REGISTRY_APP_PATHS}\gpick.exe" "Path" "$gtk_dll_abs_path" !ifndef NO_GTK skip_exe_PATH: !endif !ifndef NO_GTK WriteRegStr HKLM "SOFTWARE\${PRODUCT_NAME}" "GtkInstalledMode" "$gtk_mode" !endif WriteRegStr HKLM "SOFTWARE\${PRODUCT_NAME}" "InstallationDirectory" "$INSTDIR" WriteRegStr HKLM "SOFTWARE\${PRODUCT_NAME}" "Vendor" "${PRODUCT_PUBLISHER}" WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "DisplayName" "${PRODUCT_NAME}" WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "UninstallString" "$INSTDIR\Uninstall.exe" WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "InstallLocation" "$INSTDIR" WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "Publisher" "${PRODUCT_PUBLISHER}" WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "DisplayIcon" "$INSTDIR\gpick.ico" WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "URLInfoAbout" "${PRODUCT_WEB_SITE}" WriteRegStr HKLM "${PRODUCT_UNINST_KEY}" "DisplayVersion" "${PRODUCT_VERSION}" WriteRegDWORD HKLM "${PRODUCT_UNINST_KEY}" "NoModify" 1 WriteRegDWORD HKLM "${PRODUCT_UNINST_KEY}" "NoRepair" 1 WriteUninstaller "$INSTDIR\Uninstall.exe" SectionEnd Section "GTK+ (for this program only)" SecGtkPrivate SectionIn 1 SetShellVarContext all ; use all user variables as opposed to current user AddSize 12200 ; ~ size of unpacked gtk SetOutPath "$INSTDIR" File "${GTK_INSTALLER_EXE}" ; TODO: in the future, when we have translations for this program, ; make the GTK+ translations installation dependent on their installation status. ExecWait '"${GTK_INSTALLER_EXE}" /sideeffects=no /dllpath=root /translations=no /compatdlls=no /S /D=$INSTDIR' Delete "$INSTDIR\${GTK_INSTALLER_EXE}" SectionEnd ; disabled by default Section /o "GTK+ (shared installation)" SecGtkPublic SectionIn 1 SetShellVarContext all ; use all user variables as opposed to current user AddSize 12200 ; ~ size of unpacked gtk SetOutPath "$INSTDIR" File "${GTK_INSTALLER_EXE}" ExecWait '"${GTK_INSTALLER_EXE}"' Delete "$INSTDIR\${GTK_INSTALLER_EXE}" SectionEnd ; Executed on installation start Function .onInit SetShellVarContext all ; use all user variables as opposed to current user ${GetOptions} "$CMDLINE" "/removeold=" $install_option_removeold Call PreventMultipleInstances Call DetectPrevInstallation StrCpy $gtk_mode "private" ; default FunctionEnd function .onselchange !ifndef NO_GTK ; Remember which gtk section was selected. ; Deselect the other section. ; If it was private, we check if public is checked and uncheck private. StrCmp $gtk_mode "private" check_public ; old selection StrCmp $gtk_mode "public" check_private ; old selection goto check_exit check_public: SectionGetFlags ${SecGtkPublic} $gtk_tmp ; see if it's checked IntOp $gtk_tmp $gtk_tmp & ${SF_SELECTED} IntCmp $gtk_tmp ${SF_SELECTED} "" check_exit check_exit SectionGetFlags ${SecGtkPrivate} $gtk_tmp ; unselect the other one IntOp $gtk_tmp $gtk_tmp & ${SECTION_OFF} SectionSetFlags ${SecGtkPrivate} $gtk_tmp goto check_exit check_private: SectionGetFlags ${SecGtkPrivate} $gtk_tmp ; see if it's checked IntOp $gtk_tmp $gtk_tmp & ${SF_SELECTED} IntCmp $gtk_tmp ${SF_SELECTED} "" check_exit check_exit SectionGetFlags ${SecGtkPublic} $gtk_tmp ; unselect the other one IntOp $gtk_tmp $gtk_tmp & ${SECTION_OFF} SectionSetFlags ${SecGtkPublic} $gtk_tmp check_exit: ; store the current mode StrCpy $gtk_mode "none" SectionGetFlags ${SecGtkPrivate} $gtk_tmp IntOp $gtk_tmp $gtk_tmp & ${SF_SELECTED} IntCmp $gtk_tmp ${SF_SELECTED} "" mode_end_private mode_end_private StrCpy $gtk_mode "private" mode_end_private: SectionGetFlags ${SecGtkPublic} $gtk_tmp IntOp $gtk_tmp $gtk_tmp & ${SF_SELECTED} IntCmp $gtk_tmp ${SF_SELECTED} "" mode_end_public mode_end_public StrCpy $gtk_mode "public" mode_end_public: ; MessageBox MB_ICONINFORMATION|MB_OK "gtk_mode: $gtk_mode" /SD IDOK !endif ; !NO_GTK functionend Function on_components_page_leave StrCmp $gtk_mode "none" "" noabort Call AskForGtk noabort: FunctionEnd ; Section descriptions !insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN !insertmacro MUI_DESCRIPTION_TEXT ${SecProgramFiles} "Gpick - Advanced color picker" !insertmacro MUI_DESCRIPTION_TEXT ${SecGtkPrivate} "GTK+ libraries, needed by Gpick. \ This will install a private version of GTK+, usable only by Gpick." !insertmacro MUI_DESCRIPTION_TEXT ${SecGtkPublic} "GTK+ libraries, needed by Gpick. \ This will install a system-wide version of GTK+, shareable with other programs." !insertmacro MUI_FUNCTION_DESCRIPTION_END Section "Desktop Shortcut" SecDesktopShortcut SetOutPath "$INSTDIR" CreateShortCut "$DESKTOP\Gpick.lnk" "$INSTDIR\Gpick.exe" "" SectionEnd Section "-Start Menu Shortcut" SecStartMenu SetOutPath "$INSTDIR" !insertmacro MUI_STARTMENU_WRITE_BEGIN Application CreateDirectory "$SMPROGRAMS\$STARTMENU_FOLDER" CreateShortCut "$SMPROGRAMS\$STARTMENU_FOLDER\Gpick.lnk" "$INSTDIR\Gpick.exe" CreateShortCut "$SMPROGRAMS\$STARTMENU_FOLDER\Uninstall.lnk" "$INSTDIR\Uninstall.exe" !insertmacro MUI_STARTMENU_WRITE_END SectionEnd ; ------------------ POST INSTALL ;Uninstaller Section Section "Uninstall" SetShellVarContext all ; use all user variables as opposed to current user SetAutoClose false ReadRegStr $gtk_mode HKLM "SOFTWARE\${PRODUCT_NAME}" "GtkInstalledMode" StrCmp $gtk_mode "private" "" skip_gtk_remove ; remove private GTK+, specify the same custom options are during installation ExecWait "$INSTDIR\gtk2_runtime_uninst.exe /remove_config=yes /sideeffects=no /dllpath=root /translations=no /compatdlls=no /S" ; _?=$INSTDIR ; Delete "$INSTDIR\gtk2_runtime_uninst.exe" ; If using _? flag, it won't get deleted automatically, do it manually. skip_gtk_remove: DeleteRegKey HKLM "SOFTWARE\${PRODUCT_NAME}" DeleteRegKey HKLM "${PRODUCT_UNINST_KEY}" StrCmp $gtk_mode "private" skip_exe_PATH_remove DeleteRegKey HKLM "${REGISTRY_APP_PATHS}\gpick.exe" skip_exe_PATH_remove: Delete "$INSTDIR\Uninstall.exe" Delete "$INSTDIR\gpick.exe" Delete "$INSTDIR\lua5.2.dll" Delete "$INSTDIR\share\gpick\colors0.txt" Delete "$INSTDIR\share\gpick\colors.txt" Delete "$INSTDIR\share\gpick\gpick-falloff-none.png" Delete "$INSTDIR\share\gpick\gpick-falloff-linear.png" Delete "$INSTDIR\share\gpick\gpick-falloff-quadratic.png" Delete "$INSTDIR\share\gpick\gpick-falloff-cubic.png" Delete "$INSTDIR\share\gpick\gpick-falloff-exponential.png" Delete "$INSTDIR\share\gpick\gpick.png" Delete "$INSTDIR\share\gpick\init.lua" Delete "$INSTDIR\share\gpick\helpers.lua" Delete "$INSTDIR\share\gpick\layouts.lua" RMDir "$INSTDIR\share\gpick" RMDir "$INSTDIR\share\locale" RMDir "$INSTDIR\share" RMDir "$INSTDIR" !insertmacro MUI_STARTMENU_GETFOLDER Application $MUI_TEMP Delete "$SMPROGRAMS\$MUI_TEMP\Gpick.lnk" Delete "$SMPROGRAMS\$MUI_TEMP\Uninstall.lnk" Delete "$DESKTOP\Gpick.lnk" ;Delete empty start menu parent diretories StrCpy $MUI_TEMP "$SMPROGRAMS\$MUI_TEMP" startMenuDeleteLoop: ClearErrors RMDir $MUI_TEMP GetFullPathName $MUI_TEMP "$MUI_TEMP\.." IfErrors startMenuDeleteLoopDone StrCmp $MUI_TEMP $SMPROGRAMS startMenuDeleteLoopDone startMenuDeleteLoop startMenuDeleteLoopDone: DeleteRegKey /ifempty HKLM "Software\Gpick" SectionEnd ; Detect previous installation Function DetectPrevInstallation ; if /removeold=no option is given, don't check anything. StrCmp $install_option_removeold "no" old_detect_done SetShellVarContext all ; use all user variables as opposed to current user push $R0 ; detect previous installation ReadRegStr $R0 HKLM "${PRODUCT_UNINST_KEY}" "UninstallString" StrCmp $R0 "" old_detect_done MessageBox MB_OKCANCEL|MB_ICONEXCLAMATION \ "${PRODUCT_NAME} is already installed. $\n$\nClick `OK` to remove the \ previous version or `Cancel` to continue anyway." \ /SD IDOK IDOK old_uninst ; Abort goto old_detect_done ; Run the old uninstaller old_uninst: ClearErrors IfSilent old_silent_uninst old_nosilent_uninst old_nosilent_uninst: ExecWait '$R0' goto old_uninst_continue old_silent_uninst: ExecWait '$R0 /S _?=$INSTDIR' old_uninst_continue: IfErrors old_no_remove_uninstaller ; You can either use Delete /REBOOTOK in the uninstaller or add some code ; here to remove to remove the uninstaller. Use a registry key to check ; whether the user has chosen to uninstall. If you are using an uninstaller ; components page, make sure all sections are uninstalled. old_no_remove_uninstaller: old_detect_done: ; old installation not found, all ok pop $R0 FunctionEnd ; detect GTK installation (any of available versions) Function AskForGtk SetShellVarContext all ; use all user variables as opposed to current user push $R0 ReadRegStr $R0 HKLM "SOFTWARE\GTK\2.0" "DllPath" StrCmp $R0 "" no_gtk have_gtk no_gtk: MessageBox MB_OKCANCEL|MB_ICONEXCLAMATION \ "GTK2-Runtime is not installed. This product needs it to function properly.$\n\ Please install GTK2-Runtime from http://gtk-win.sf.net/ first.$\n$\n\ Click 'Cancel' to abort the installation \ or 'OK' to continue anyway." \ /SD IDOK IDOK have_gtk ;Abort ; Abort has different meaning from onpage callbacks, so use Quit Quit goto end_gtk_check have_gtk: ; do nothing end_gtk_check: pop $R0 FunctionEnd ; Prevent running multiple instances of the installer Function PreventMultipleInstances Push $R0 System::Call 'kernel32::CreateMutexA(i 0, i 0, t ${PRODUCT_NAME}) ?e' Pop $R0 StrCmp $R0 0 +3 MessageBox MB_OK|MB_ICONEXCLAMATION "The installer is already running." /SD IDOK Abort Pop $R0 FunctionEnd gpick-gpick-0.2.6rc1/res/000077500000000000000000000000001315430016700151065ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/res/falloff-cubic.svg000066400000000000000000000077731315430016700203410ustar00rootroot00000000000000 image/svg+xml gpick-gpick-0.2.6rc1/res/falloff-exponential.svg000066400000000000000000000102021315430016700215570ustar00rootroot00000000000000 image/svg+xml gpick-gpick-0.2.6rc1/res/falloff-linear.svg000066400000000000000000000101611315430016700205070ustar00rootroot00000000000000 image/svg+xml gpick-gpick-0.2.6rc1/res/falloff-none.svg000066400000000000000000000074251315430016700202050ustar00rootroot00000000000000 image/svg+xml gpick-gpick-0.2.6rc1/res/falloff-quadratic.svg000066400000000000000000000077651315430016700212320ustar00rootroot00000000000000 image/svg+xml gpick-gpick-0.2.6rc1/res/gpick.svg000066400000000000000000000225551315430016700167350ustar00rootroot00000000000000 image/svg+xml gpick-gpick-0.2.6rc1/res/gray-pattern.svg000066400000000000000000000075501315430016700202530ustar00rootroot00000000000000 image/svg+xml gpick-gpick-0.2.6rc1/share/000077500000000000000000000000001315430016700154175ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/appdata/000077500000000000000000000000001315430016700170315ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/appdata/gpick.appdata.xml000066400000000000000000000032031315430016700222570ustar00rootroot00000000000000 gpick.desktop CC0-1.0 BSD-3-Clause Gpick Advanced color picker and palette editor

Gpick is an application that allows you to sample any color from anywhere on the desktop, and use it to create palettes (i.e. collections of colors) for use in graphic design applications. Gpick also has other features that help in the creation of color palettes, such as: the ability to create a palette from an imported image, automatic naming of colors, and a scheme generator.

http://static.gpick.org/image/appdata-screenshot-0.2.6.png The main window showing the application in action http://www.gpick.org https://github.com/thezbyg/gpick albertas.vysniauskas@gpick.org Albertas Vyšniauskas http://www.gpick.org/help/donation.html http://www.gpick.org/help.html gpick color picker eye dropper palette scheme http://www.gpick.org/help/translation.html
gpick-gpick-0.2.6rc1/share/applications/000077500000000000000000000000001315430016700201055ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/applications/gpick.desktop000066400000000000000000000004121315430016700225720ustar00rootroot00000000000000[Desktop Entry] Version=1.0 Name=Gpick Comment=Color picker Comment[ru]=Пипетка для снятия цвета GenericName=Color picker Exec=gpick Icon=gpick StartupNotify=true MimeType=text/x-utility; Terminal=false Type=Application Categories=Graphics;GTK; gpick-gpick-0.2.6rc1/share/doc/000077500000000000000000000000001315430016700161645ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/doc/gpick/000077500000000000000000000000001315430016700172615ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/doc/gpick/copyright000066400000000000000000000007361315430016700212220ustar00rootroot00000000000000gpick This package was debianized by Albertas Vyšniauskas The home page of Gpick is at: http://www.gpick.org Upstream Author: Albertas Vyšniauskas This software is copyright (c) 2009-2016 by Albertas Vyšniauskas. You are free to distribute this software under the terms of the BSD License. On Debian systems, the complete text of the BSD license can be found in the file `/usr/share/common-licenses/BSD'. gpick-gpick-0.2.6rc1/share/gpick/000077500000000000000000000000001315430016700165145ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/gpick/color_dictionary_0.txt000066400000000000000000000505011315430016700230400ustar00rootroot00000000000000! Source: http://xkcd.com/color/rgb.txt ! License: http://creativecommons.org/publicdomain/zero/1.0/ 172 194 217 cloudy blue 86 174 87 dark pastel green 178 153 110 dust 168 255 4 electric lime 105 216 79 fresh green 137 69 133 light eggplant 112 178 63 nasty green 212 255 255 really light blue 101 171 124 tea 149 46 143 warm purple 252 252 129 yellowish tan 165 163 145 cement 56 128 4 dark grass green 76 144 133 dusty teal 94 155 138 grey teal 239 180 53 macaroni and cheese 217 155 130 pinkish tan 10 95 56 spruce 12 6 247 strong blue 97 222 42 toxic green 55 120 191 windows blue 34 66 199 blue blue 83 60 198 blue with a hint of purple 155 181 60 booger 5 255 166 bright sea green 31 99 87 dark green blue 1 115 116 deep turquoise 12 181 119 green teal 255 7 137 strong pink 175 168 139 bland 8 120 127 deep aqua 221 133 215 lavender pink 166 200 117 light moss green 167 255 181 light seafoam green 194 183 9 olive yellow 231 142 165 pig pink 150 110 189 deep lilac 204 173 96 desert 172 134 168 dusty lavender 148 126 148 purpley grey 152 63 178 purply 255 99 233 candy pink 178 251 165 light pastel green 99 179 101 boring green 142 229 63 kiwi green 183 225 161 light grey green 255 111 82 orange pink 189 248 163 tea green 211 182 131 very light brown 255 252 196 egg shell 67 5 65 eggplant purple 255 178 208 powder pink 153 117 112 reddish grey 173 144 13 baby shit brown 196 142 253 liliac 80 123 156 stormy blue 125 113 3 ugly brown 255 253 120 custard 218 70 125 darkish pink 65 2 0 deep brown 201 209 121 greenish beige 255 250 134 manilla 86 132 174 off blue 107 124 133 battleship grey 111 108 10 browny green 126 64 113 bruise 0 147 55 kelley green 208 228 41 sickly yellow 255 249 23 sunny yellow 29 93 236 azul 5 73 7 darkgreen 181 206 8 green/yellow 143 182 123 lichen 200 255 176 light light green 253 222 108 pale gold 255 223 34 sun yellow 169 190 112 tan green 104 50 227 burple 253 177 71 butterscotch 199 172 125 toupe 255 243 154 dark cream 133 14 4 indian red 239 192 254 light lavendar 64 253 20 poison green 182 196 6 baby puke green 157 255 0 bright yellow green 60 65 66 charcoal grey 242 171 21 squash 172 79 6 cinnamon 196 254 130 light pea green 44 250 31 radioactive green 154 98 0 raw sienna 202 155 247 baby purple 135 95 66 cocoa 58 46 254 light royal blue 253 141 73 orangeish 139 49 3 rust brown 203 165 96 sand brown 105 131 57 swamp 12 220 115 tealish green 183 82 3 burnt siena 127 143 78 camo 38 83 141 dusk blue 99 169 80 fern 200 127 137 old rose 177 252 153 pale light green 255 154 138 peachy pink 246 104 142 rosy pink 118 253 168 light bluish green 83 254 92 light bright green 78 253 84 light neon green 160 254 191 light seafoam 123 242 218 tiffany blue 188 245 166 washed out green 202 107 2 browny orange 16 122 176 nice blue 33 56 171 sapphire 113 159 145 greyish teal 253 185 21 orangey yellow 254 252 175 parchment 252 246 121 straw 29 2 0 very dark brown 203 104 67 terracota 49 102 138 ugly blue 36 122 253 clear blue 255 255 182 creme 144 253 169 foam green 134 161 125 grey/green 253 220 92 light gold 120 209 182 seafoam blue 19 187 175 topaz 251 95 252 violet pink 32 249 134 wintergreen 255 227 110 yellow tan 157 7 89 dark fuchsia 58 24 177 indigo blue 194 255 137 light yellowish green 215 103 173 pale magenta 114 0 88 rich purple 255 218 3 sunflower yellow 1 192 141 green/blue 172 116 52 leather 1 70 0 racing green 153 0 250 vivid purple 2 6 111 dark royal blue 142 118 24 hazel 209 118 143 muted pink 150 180 3 booger green 253 255 99 canary 149 163 166 cool grey 127 104 78 dark taupe 117 25 115 darkish purple 8 148 4 true green 255 97 99 coral pink 89 133 86 dark sage 33 71 97 dark slate blue 60 115 168 flat blue 186 158 136 mushroom 2 27 249 rich blue 115 74 101 dirty purple 35 196 139 greenblue 143 174 34 icky green 230 242 162 light khaki 75 87 219 warm blue 217 1 102 dark hot pink 1 84 130 deep sea blue 157 2 22 carmine 114 143 2 dark yellow green 255 229 173 pale peach 78 5 80 plum purple 249 188 8 golden rod 255 7 58 neon red 199 121 134 old pink 214 255 254 very pale blue 254 75 3 blood orange 253 89 86 grapefruit 252 225 102 sand yellow 178 113 61 clay brown 31 59 77 dark blue grey 105 157 76 flat green 86 252 162 light green blue 251 85 129 warm pink 62 130 252 dodger blue 160 191 22 gross green 214 255 250 ice 79 115 142 metallic blue 255 177 154 pale salmon 92 139 21 sap green 84 172 104 algae 137 160 176 bluey grey 126 160 122 greeny grey 27 252 6 highlighter green 202 255 251 light light blue 182 255 187 light mint 167 94 9 raw umber 21 46 255 vivid blue 141 94 183 deep lavender 95 158 143 dull teal 99 247 180 light greenish blue 96 102 2 mud green 252 134 170 pinky 140 0 52 red wine 117 128 0 shit green 171 126 76 tan brown 3 7 100 darkblue 254 134 164 rosa 213 23 78 lipstick 254 208 252 pale mauve 104 0 24 claret 254 223 8 dandelion 254 66 15 orangered 111 124 0 poop green 202 1 71 ruby 27 36 49 dark 0 251 176 greenish turquoise 219 88 86 pastel red 221 214 24 piss yellow 65 253 254 bright cyan 207 82 78 dark coral 33 195 111 algae green 169 3 8 darkish red 110 16 5 reddy brown 254 130 140 blush pink 75 97 19 camouflage green 77 164 9 lawn green 190 174 138 putty 3 57 248 vibrant blue 168 143 89 dark sand 93 33 208 purple/blue 254 178 9 saffron 78 81 139 twilight 150 78 2 warm brown 133 163 178 bluegrey 255 105 175 bubble gum pink 195 251 244 duck egg blue 42 254 183 greenish cyan 0 95 106 petrol 12 23 147 royal 255 255 129 butter 240 131 58 dusty orange 241 243 63 off yellow 177 210 123 pale olive green 252 130 74 orangish 113 170 52 leaf 183 201 226 light blue grey 75 1 1 dried blood 165 82 230 lightish purple 175 47 13 rusty red 139 136 248 lavender blue 154 247 100 light grass green 166 251 178 light mint green 255 197 18 sunflower 117 8 81 velvet 193 74 9 brick orange 254 47 74 lightish red 2 3 226 pure blue 10 67 122 twilight blue 165 0 85 violet red 174 139 12 yellowy brown 253 121 143 carnation 191 172 5 muddy yellow 62 175 118 dark seafoam green 199 71 103 deep rose 185 72 78 dusty red 100 125 142 grey/blue 191 254 40 lemon lime 215 37 222 purple/pink 178 151 5 brown yellow 103 58 63 purple brown 168 125 194 wisteria 250 254 75 banana yellow 192 2 47 lipstick red 14 135 204 water blue 141 132 104 brown grey 173 3 222 vibrant purple 140 255 158 baby green 148 172 2 barf green 196 255 247 eggshell blue 253 238 115 sandy yellow 51 184 100 cool green 255 249 208 pale 117 141 163 blue/grey 245 4 201 hot magenta 119 161 181 greyblue 135 86 228 purpley 136 151 23 baby shit green 194 126 121 brownish pink 1 115 113 dark aquamarine 159 131 3 diarrhea 247 213 96 light mustard 189 246 254 pale sky blue 117 184 79 turtle green 156 187 4 bright olive 41 70 91 dark grey blue 105 96 6 greeny brown 173 248 2 lemon green 193 198 252 light periwinkle 53 173 107 seaweed green 255 253 55 sunshine yellow 164 66 160 ugly purple 243 97 150 medium pink 148 119 6 puke brown 255 244 242 very light pink 30 145 103 viridian 181 195 6 bile 254 255 127 faded yellow 207 253 188 very pale green 10 221 8 vibrant green 135 253 5 bright lime 30 248 118 spearmint 123 253 199 light aquamarine 188 236 172 light sage 187 249 15 yellowgreen 171 144 4 baby poo 31 181 122 dark seafoam 0 85 90 deep teal 164 132 172 heather 196 85 8 rust orange 63 130 157 dirty blue 84 141 68 fern green 201 94 251 bright lilac 58 229 127 weird green 1 103 149 peacock blue 135 169 34 avocado green 240 148 77 faded orange 93 20 81 grape purple 37 255 41 hot green 208 254 29 lime yellow 255 166 43 mango 1 180 76 shamrock 255 108 181 bubblegum 107 66 71 purplish brown 199 193 12 vomit yellow 183 255 250 pale cyan 174 255 110 key lime 236 45 1 tomato red 118 255 123 lightgreen 115 0 57 merlot 4 3 72 night blue 223 78 200 purpleish pink 110 203 60 apple 143 152 5 baby poop green 94 220 31 green apple 217 79 245 heliotrope 200 253 61 yellow/green 7 13 13 almost black 73 132 184 cool blue 81 183 59 leafy green 172 126 4 mustard brown 78 84 129 dusk 135 110 75 dull brown 88 188 8 frog green 47 239 16 vivid green 45 254 84 bright light green 10 255 2 fluro green 156 239 67 kiwi 24 209 123 seaweed 53 83 10 navy green 24 5 219 ultramarine blue 98 88 196 iris 255 150 79 pastel orange 255 171 15 yellowish orange 143 140 231 perrywinkle 36 188 168 tealish 63 1 44 dark plum 203 248 95 pear 255 114 76 pinkish orange 40 1 55 midnight purple 179 111 246 light urple 72 192 114 dark mint 188 203 122 greenish tan 168 65 91 light burgundy 6 177 196 turquoise blue 205 117 132 ugly pink 241 218 122 sandy 255 4 144 electric pink 128 91 135 muted purple 80 167 71 mid green 168 164 149 greyish 207 255 4 neon yellow 255 255 126 banana 255 127 167 carnation pink 239 64 38 tomato 60 153 146 sea 136 104 6 muddy brown 4 244 137 turquoise green 254 246 158 buff 207 175 123 fawn 59 113 159 muted blue 253 193 197 pale rose 32 192 115 dark mint green 155 95 192 amethyst 15 155 142 blue/green 116 40 2 chestnut 157 185 44 sick green 164 191 32 pea 205 89 9 rusty orange 173 165 135 stone 190 1 60 rose red 184 255 235 pale aqua 220 77 1 deep orange 162 101 62 earth 99 139 39 mossy green 65 156 3 grassy green 177 255 101 pale lime green 157 188 212 light grey blue 253 253 254 pale grey 119 171 86 asparagus 70 65 150 blueberry 153 1 71 purple red 190 253 115 pale lime 50 191 132 greenish teal 175 111 9 caramel 160 2 92 deep magenta 255 216 177 light peach 127 78 30 milk chocolate 191 155 12 ocher 107 163 83 off green 240 117 230 purply pink 123 200 246 lightblue 71 95 148 dusky blue 245 191 3 golden 255 254 182 light beige 255 253 116 butter yellow 137 91 123 dusky purple 67 107 173 french blue 208 193 1 ugly yellow 198 248 8 greeny yellow 244 54 5 orangish red 2 193 77 shamrock green 178 95 3 orangish brown 42 126 25 tree green 73 6 72 deep violet 83 98 103 gunmetal 90 6 239 blue/purple 207 2 52 cherry 196 166 97 sandy brown 151 138 132 warm grey 31 9 84 dark indigo 3 1 45 midnight 43 177 121 bluey green 195 144 155 grey pink 166 111 181 soft purple 119 0 1 blood 146 43 5 brown red 125 127 124 medium grey 153 15 75 berry 143 115 3 poo 200 60 185 purpley pink 254 169 147 light salmon 172 187 13 snot 192 113 254 easter purple 204 253 127 light yellow green 0 2 46 dark navy blue 130 131 68 drab 255 197 203 light rose 171 18 57 rouge 176 5 75 purplish red 153 204 4 slime green 147 124 0 baby poop 1 149 41 irish green 239 29 231 pink/purple 0 4 53 dark navy 66 179 149 greeny blue 157 87 131 light plum 200 172 169 pinkish grey 200 118 6 dirty orange 170 39 4 rust red 228 203 255 pale lilac 250 66 36 orangey red 8 4 249 primary blue 92 178 0 kermit green 118 66 78 brownish purple 108 122 14 murky green 251 221 126 wheat 42 1 52 very dark purple 4 74 5 bottle green 253 70 89 watermelon 13 117 248 deep sky blue 254 0 2 fire engine red 203 157 6 yellow ochre 251 125 7 pumpkin orange 185 204 129 pale olive 237 200 255 light lilac 97 225 96 lightish green 138 184 254 carolina blue 146 10 78 mulberry 254 2 162 shocking pink 154 48 1 auburn 101 254 8 bright lime green 190 253 183 celadon 177 114 97 pinkish brown 136 95 1 poo brown 2 204 254 bright sky blue 193 253 149 celery 131 101 57 dirt brown 251 41 67 strawberry 132 183 1 dark lime 182 99 37 copper 127 81 18 medium brown 95 160 82 muted green 109 237 253 robin's egg 11 249 234 bright aqua 199 96 255 bright lavender 255 255 203 ivory 246 206 252 very light purple 21 80 132 light navy 245 5 79 pink red 100 84 3 olive brown 122 89 1 poop brown 168 181 4 mustard green 61 153 115 ocean green 0 1 51 very dark blue 118 169 115 dusty green 46 90 136 light navy blue 11 247 125 minty green 189 108 72 adobe 172 29 184 barney 43 175 106 jade green 38 247 253 bright light blue 174 253 108 light lime 155 143 85 dark khaki 255 173 1 orange yellow 198 156 4 ocre 244 208 84 maize 222 157 172 faded pink 5 72 13 british racing green 201 174 116 sandstone 96 70 15 mud brown 152 246 176 light sea green 138 241 254 robin egg blue 46 232 187 aqua marine 17 135 93 dark sea green 253 176 192 soft pink 177 96 2 orangey brown 247 2 42 cherry red 213 171 9 burnt yellow 134 119 95 brownish grey 198 159 89 camel 122 104 127 purplish grey 4 46 96 marine 200 141 148 greyish pink 165 251 213 pale turquoise 255 254 113 pastel yellow 98 65 199 bluey purple 255 254 64 canary yellow 211 73 78 faded red 152 94 43 sepia 166 129 76 coffee 255 8 232 bright magenta 157 118 81 mocha 254 255 202 ecru 152 86 141 purpleish 158 0 58 cranberry 40 124 55 darkish green 185 105 2 brown orange 186 104 115 dusky rose 255 120 85 melon 148 178 28 sickly green 197 201 199 silver 102 26 238 purply blue 97 64 239 purpleish blue 155 229 170 hospital green 123 88 4 shit brown 39 106 179 mid blue 254 179 8 amber 140 253 126 easter green 100 136 234 soft blue 5 110 238 cerulean blue 178 122 1 golden brown 15 254 249 bright turquoise 250 42 85 red pink 130 7 71 red purple 122 106 79 greyish brown 244 50 12 vermillion 161 57 5 russet 111 130 138 steel grey 165 90 244 lighter purple 173 10 253 bright violet 0 69 119 prussian blue 101 141 109 slate green 202 123 128 dirty pink 0 82 73 dark blue green 43 93 52 pine 191 241 40 yellowy green 181 148 16 dark gold 41 118 187 bluish 1 65 130 darkish blue 187 63 63 dull red 252 38 71 pinky red 168 121 0 bronze 130 203 178 pale teal 102 124 62 military green 254 70 165 barbie pink 254 131 204 bubblegum pink 148 166 23 pea soup green 168 137 5 dark mustard 127 95 0 shit 158 67 162 medium purple 6 46 3 very dark green 138 110 69 dirt 204 122 139 dusky pink 158 1 104 red violet 253 255 56 lemon yellow 192 250 139 pistachio 238 220 91 dull yellow 126 189 1 dark lime green 59 91 146 denim blue 1 136 159 teal blue 61 122 253 lightish blue 95 52 231 purpley blue 109 90 207 light indigo 116 133 0 swamp green 112 108 17 brown green 60 0 8 dark maroon 203 0 245 hot purple 0 45 4 dark forest green 101 140 187 faded blue 116 149 81 drab green 185 255 102 light lime green 157 193 0 snot green 250 238 102 yellowish 126 251 179 light blue green 123 0 44 bordeaux 194 146 161 light mauve 1 123 146 ocean 252 192 6 marigold 101 116 50 muddy green 216 134 59 dull orange 115 133 149 steel 170 35 255 electric purple 8 255 8 fluorescent green 155 122 1 yellowish brown 242 158 142 blush 111 194 118 soft green 255 91 0 bright orange 253 255 82 lemon 134 111 133 purple grey 143 254 9 acid green 238 207 254 pale lavender 81 10 201 violet blue 79 145 83 light forest green 159 35 5 burnt red 114 134 57 khaki green 222 12 98 cerise 145 110 153 faded purple 255 177 109 apricot 60 77 3 dark olive green 127 112 83 grey brown 119 146 111 green grey 1 15 204 true blue 206 174 250 pale violet 143 153 251 periwinkle blue 198 252 255 light sky blue 85 57 204 blurple 84 78 3 green brown 1 122 121 bluegreen 1 249 198 bright teal 201 176 3 brownish yellow 146 153 1 pea soup 11 85 9 forest 160 4 152 barney purple 32 0 177 ultramarine 148 86 140 purplish 194 190 14 puke yellow 116 139 151 bluish grey 102 95 209 dark periwinkle 156 109 165 dark lilac 196 66 64 reddish 162 72 87 light maroon 130 95 135 dusty purple 201 100 59 terra cotta 144 177 52 avocado 1 56 106 marine blue 37 163 111 teal green 89 101 109 slate grey 117 253 99 lighter green 33 252 13 electric green 90 134 173 dusty blue 254 198 21 golden yellow 255 253 1 bright yellow 223 197 254 light lavender 178 100 0 umber 127 94 0 poop 222 126 93 dark peach 4 130 67 jungle green 255 255 212 eggshell 59 99 140 denim 183 148 0 yellow brown 132 89 126 dull purple 65 25 0 chocolate brown 123 3 35 wine red 4 217 255 neon blue 102 126 44 dirty green 251 238 172 light tan 215 255 254 ice blue 78 116 150 cadet blue 135 76 98 dark mauve 213 255 255 very light blue 130 109 140 grey purple 255 186 205 pastel pink 209 255 189 very light green 68 142 228 dark sky blue 5 71 42 evergreen 213 134 157 dull pink 61 7 52 aubergine 74 1 0 mahogany 248 72 28 reddish orange 2 89 15 deep green 137 162 3 vomit green 224 63 216 purple pink 213 138 148 dusty pink 123 178 116 faded green 82 101 37 camo green 201 76 190 pinky purple 219 75 218 pink purple 158 54 35 brownish red 181 72 93 dark rose 115 92 18 mud 156 109 87 brownish 2 143 30 emerald green 177 145 110 pale brown 73 117 156 dull blue 160 69 14 burnt umber 57 173 72 medium green 182 106 80 clay 140 255 219 light aqua 164 190 92 light olive green 203 119 35 brownish orange 5 105 107 dark aqua 206 93 174 purplish pink 200 90 83 dark salmon 150 174 141 greenish grey 31 167 116 jade 122 151 3 ugly green 172 147 98 dark beige 1 160 73 emerald 217 84 77 pale red 250 95 247 light magenta 130 202 252 sky 172 255 252 light cyan 252 176 1 yellow orange 145 9 81 reddish purple 254 44 84 reddish pink 200 117 196 orchid 205 197 10 dirty yellow 253 65 30 orange red 154 2 0 deep red 190 100 0 orange brown 3 10 167 cobalt blue 254 1 154 neon pink 247 135 154 rose pink 136 113 145 greyish purple 176 1 73 raspberry 18 225 147 aqua green 254 123 124 salmon pink 255 148 8 tangerine 106 110 9 brownish green 139 46 22 red brown 105 97 18 greenish brown 225 119 1 pumpkin 10 72 30 pine green 52 56 55 charcoal 255 183 206 baby pink 106 121 247 cornflower 93 6 233 blue violet 61 28 2 chocolate 130 166 125 greyish green 190 1 25 scarlet 201 255 39 green yellow 55 62 2 dark olive 169 86 30 sienna 202 160 255 pastel purple 202 102 65 terracotta 2 216 233 aqua blue 136 179 120 sage green 152 0 2 blood red 203 1 98 deep pink 92 172 45 grass 118 153 88 moss 162 191 254 pastel blue 16 166 116 bluish green 6 180 139 green blue 175 136 74 dark tan 11 139 135 greenish blue 255 167 86 pale orange 162 164 21 vomit 21 68 6 forrest green 133 103 152 dark lavender 52 1 63 dark violet 99 45 233 purple blue 10 136 138 dark cyan 111 118 50 olive drab 212 106 126 pinkish 30 72 143 cobalt 188 19 254 neon purple 126 244 204 light turquoise 118 205 38 apple green 116 166 98 dull green 128 1 63 wine 177 209 252 powder blue 255 255 228 off white 6 82 255 electric blue 4 92 90 dark turquoise 87 41 206 blue purple 6 154 243 azure 255 0 13 bright red 241 12 69 pinkish red 81 112 215 cornflower blue 172 191 105 light olive 108 52 97 grape 94 129 157 greyish blue 96 30 249 purplish blue 176 221 22 yellowish green 205 253 2 greenish yellow 44 111 187 medium blue 192 115 122 dusty rose 214 180 252 light violet 2 0 53 midnight blue 112 59 231 bluish purple 253 60 6 red orange 150 0 86 dark magenta 64 163 104 greenish 3 113 156 ocean blue 252 90 80 coral 255 255 194 cream 127 43 10 reddish brown 176 78 15 burnt sienna 160 54 35 brick 135 174 115 sage 120 155 115 grey green 255 255 255 white 152 239 249 robin's egg blue 101 139 56 moss green 90 125 154 steel blue 56 8 53 eggplant 255 254 122 light yellow 92 169 4 leaf green 216 220 214 light grey 165 165 2 puke 214 72 215 pinkish purple 4 116 149 sea blue 183 144 212 pale purple 91 124 153 slate blue 96 124 142 blue grey 11 64 8 hunter green 237 13 217 fuchsia 140 0 15 crimson 255 255 132 pale yellow 191 144 5 ochre 210 189 10 mustard yellow 255 71 76 light red 4 133 209 cerulean 255 207 220 pale pink 4 2 115 deep blue 168 60 9 rust 144 228 193 light teal 81 101 114 slate 250 194 5 goldenrod 213 182 10 dark yellow 54 55 55 dark grey 75 93 22 army green 107 139 164 grey blue 128 249 173 seafoam 165 126 82 puce 169 249 113 spring green 198 81 2 dark orange 226 202 118 sand 176 255 157 pastel green 159 254 176 mint 253 170 72 light orange 254 1 177 bright pink 193 248 10 chartreuse 54 1 63 deep purple 52 28 2 dark brown 185 162 129 taupe 142 171 18 pea green 154 174 7 puke green 2 171 46 kelly green 122 249 171 seafoam green 19 126 109 blue green 170 166 98 khaki 97 0 35 burgundy 1 77 78 dark teal 143 20 2 brick red 75 0 110 royal purple 88 15 65 plum 143 255 159 mint green 219 180 12 gold 162 207 254 baby blue 192 251 45 yellow green 190 3 253 bright purple 132 0 0 dark red 208 254 254 pale blue 63 155 11 grass green 1 21 62 navy 4 216 178 aquamarine 192 78 1 burnt orange 12 255 12 neon green 1 101 252 bright blue 207 98 117 rose 255 209 223 light pink 206 179 1 mustard 56 2 130 indigo 170 255 50 lime 83 252 161 sea green 142 130 254 periwinkle 203 65 107 dark pink 103 122 4 olive green 255 176 124 peach 199 253 181 pale green 173 129 80 light brown 255 2 141 hot pink 0 0 0 black 206 162 253 lilac 0 17 70 navy blue 5 4 170 royal blue 230 218 166 beige 255 121 108 salmon 110 117 14 olive 101 0 33 maroon 1 255 7 bright green 53 6 62 dark purple 174 113 129 mauve 6 71 12 forest green 19 234 201 aqua 0 255 255 cyan 209 178 111 tan 0 3 91 dark blue 199 159 239 lavender 6 194 172 turquoise 3 53 0 dark green 154 14 234 violet 191 119 246 light purple 137 254 5 lime green 146 149 145 grey 117 187 253 sky blue 255 255 20 yellow 194 0 120 magenta 150 249 123 light green 249 115 6 orange 2 147 134 teal 149 208 252 light blue 229 0 0 red 101 55 0 brown 255 129 192 pink 3 67 223 blue 21 176 26 green 126 30 156 purple gpick-gpick-0.2.6rc1/share/gpick/gpick-falloff-cubic.png000066400000000000000000000027421315430016700230160ustar00rootroot00000000000000PNG  IHDR szzsBIT|d pHYs B(xtEXtSoftwarewww.inkscape.org<_IDATX[lE3{vn/ҋjH9MD wB 6Ӡ@@P^%/@DC`Z6-֞r Җn0SZdrforsFT*Z<O>``+Xy涾>̛7ovQQDII_ZZ)**-..[SSӞ?)A9shH&ڵk/-\pd2y&RBJ|Æ 277Wr%Y:{_?}#eX4\afOC^= `F֭[7e˖uuuGg+@XGylWDC#]Zt:=Uno۶)q CpNdc!Xݷ7e=NmƁ~Ylf09i9FjlPPBFKnz:ojj|lҥ/ سgƕ q H0=gj >&$Hڣ?Pvq ٩o:]]]d2.4B2}]Es ɘp-)n7NHR뺋jkk`Z|'DJp)1k!TU2_U7[/\##I$K^ Lx‚'mx2,eqx ܕz6i“֤-dlb5W>00P  i%S O5*0&]hUUU⾾? /4kvdÓVŚTF҂'bUwH8ڜޭrLB ^#+05C&1U)6G,p u8:t~xxxM6Krǂ  A D ĢN9 ;Wky^bJ+zkV (4@F"Z\+!j. Q5q˖N ޜLmspNo#jIENDB`gpick-gpick-0.2.6rc1/share/gpick/gpick-falloff-exponential.png000066400000000000000000000023571315430016700242610ustar00rootroot00000000000000PNG  IHDR szzsBIT|d pHYs B(xtEXtSoftwarewww.inkscape.org<lIDATXoLuݵwɠt5flA[ƀDقD1107آ25j4dpJ1bBVdnSF(c -ݸ{|qmqD ŞIr}>ߟ#"d+&F p%WAYCC7KKK<%%%o[r M%4< HeKKca W25c( !V D0Dh{gXDPWW9@8@ ,ؚ_v^$D"n|d@4]F4fXi} O={voF|[ IЌ ]Y~^ƌ,ѓt Ds^ L|oо;n'hjj =3+Kf` ,oڏ컒"BMMMOB @4ݒ\ 60# ,!B#+d&UU.nkk_hj  88 nQIqZ9y?2uww]v#̭_#:ƙI.1bI@(B Ab(!nքsbb,lۺ%g~]^7r/,,< .\PвD!4FqV(wtuO䣟u +77n.-}U˲|4o[-P($_EfB EL}5bዮ]{4-ٲX&cʱ `@" 2lHdNX%$uhx>{SUֳ<0nUv\K yD$"\w#n7+%T}fS>IENDB`gpick-gpick-0.2.6rc1/share/gpick/gpick-falloff-linear.png000066400000000000000000000024501315430016700231770ustar00rootroot00000000000000PNG  IHDR szzsBIT|d pHYs B(xtEXtSoftwarewww.inkscape.org<IDATX[lUݙ-e{׶)6RDDPp@(bDbb ">(,Z@@ Z 5$B&\ZD -p邰`R]97fXDdr;NfhћA{n&x<ߛT {C ZBN=px;ݷ hzʓn۶m:F& U777/Z' EBaMH pr ZNU2m񹯕*Jid F֙{ ?PXTi|Uk؏?XnQWPW'V"`Q ppb4m ROA4,ԆID,aJfu-՜9bcF -**|pQB* E 6R"R(PHMN0讖}$r8ͣP)W\C,b;B23+?%aq}&OHJv5 =liAAAn'/aRv;90+$ekjÆo qoΝ3 l  $N3(M { nN&RCmr9?m=ơÿuuuwX>} @\GwJO윐ΛhZAF"|z`"ݭJ;5\ ]?η6L 5TY?L%Cbێ?_3gd2 ]GH!` ٰr P*) J ulwP[ly7#&j 1E{\z&ʋ!*|i1iQqΗ^Ĕ8ss@ˌuz" @ !aoM_p o iIENDB`gpick-gpick-0.2.6rc1/share/gpick/gpick-falloff-none.png000066400000000000000000000004711315430016700226650ustar00rootroot00000000000000PNG  IHDR szzsBIT|d pHYs B(xtEXtSoftwarewww.inkscape.org<IDATX1 0"JG+x)/E:9T `!H^HB9jizc388$H@if$i$sg Mp &a!L)S kGN2~Ā٩w] w}^y P;Z-Ǥ @ ZIENDB`gpick-gpick-0.2.6rc1/share/gpick/gpick-falloff-quadratic.png000066400000000000000000000027041315430016700237040ustar00rootroot00000000000000PNG  IHDR szzsBIT|d pHYs B(xtEXtSoftwarewww.inkscape.org<AIDATX[lUƿs;eiݶ-lmZ.+4F/Q1@44iRE#Ei6U!hA#-KCXae;{߇hI̙ߞgfr}]TUp$6s qh4*OقOp78"HLc*++iӦM:4844}w4@CCR8p8L^@#G#;HYJS\),ʉMIKhC/S.xz|>Z[[F"+V q;pn{GI€ bI< { }†h"~5&vPHܹDEE pv?`OP܇30X" (|آ |^m_7kjj^pe%88sOOMʹ-%HǏ7k oift-gIJ=ņ[|۲}%%% I)4ÄS0<μݹ, ~א1>=J6@RE:,XB%5XREG=O+Ǯm݌{/X,k.@:.9@sb 2X&'9R:{Ț41L|13?p“o߰5?0Va zf;J6k3ϵ(Dw>nݺՆaLki'Ya /Jp ΅i0lgM\4>|x.?4tlfSX T7X›XRʁԝϩj-(?Of<@^D,5dr9HrkXF-'A-[lG\0[|4"@<HJ9!%dc l_*\^Ej} B1 L!ysH!` %!6 0R!eg'^{܏ŋp)£?9s !aHP0)RT7hHPwNdvVu$32u~~GmKJtW`I,I²=b^Xa OVa&99:LuJZmڞsrr!L[\P%jCH BC6!8)KTHfC RavKdE`ɄzYҁi}X477݌d_p`~DgIENDB`gpick-gpick-0.2.6rc1/share/gpick/gpick-gray-pattern.png000066400000000000000000000003551315430016700227350ustar00rootroot00000000000000PNG  IHDR szzsBIT|d pHYsvv}ՂtEXtSoftwarewww.inkscape.org<jIDATXԱ 0 DяG+K+@tVzZ~<#IU(UPBePgf/2ʸ;`v;`~C|+IENDB`gpick-gpick-0.2.6rc1/share/gpick/helpers.lua000066400000000000000000000004751315430016700206670ustar00rootroot00000000000000 function suggest(filename) local function p_require() require(filename); end; local function supress_error(err) print(err); end; return xpcall(p_require, supress_error); end; function round(number) if number-math.floor(number)>=0.5 then return math.ceil(number); else return math.floor(number); end; end; gpick-gpick-0.2.6rc1/share/gpick/init.lua000066400000000000000000000235411315430016700201670ustar00rootroot00000000000000 local gpick_module = gpick gpick = {} gpick.converters = {} gpick.user = {} gpick.global = gpick_module gpick.options = {} require('helpers') require('layouts') suggest('user_init') gpick.serialize_web_hex = function(color_object, params) if not color_object then return nil end if not params then return nil end local c = color_object:get_color() if gpick.options.upper_case then return '#' .. string.format('%02X%02X%02X', round(c:red() * 255), round(c:green() * 255), round(c:blue() * 255)) else return '#' .. string.format('%02x%02x%02x', round(c:red() * 255), round(c:green() * 255), round(c:blue() * 255)) end end gpick.deserialize_web_hex = function(text, color_object) local c = color:new() local find_start, find_end, red, green, blue = string.find(text, '#([%x][%x])([%x][%x])([%x][%x])[^%x]?') if find_start~=nil then red = tonumber(red, 16) green = tonumber(green, 16) blue = tonumber(blue, 16) c:red(red / 255) c:green(green / 255) c:blue(blue / 255) color_object:set_color(c) return 1 - (math.atan(find_start - 1)/math.pi) - (math.atan(string.len(text) - find_end) / math.pi) else return -1 end end gpick.serialize_web_hex_no_hash = function(color_object, params) if not color_object then return nil end if not params then return nil end local c = color_object:get_color() if gpick.options.upper_case then return string.format('%02X%02X%02X', round(c:red() * 255), round(c:green() * 255), round(c:blue() * 255)) else return string.format('%02x%02x%02x', round(c:red() * 255), round(c:green() * 255), round(c:blue() * 255)) end end gpick.deserialize_web_hex_no_hash = function (text, color_object) local c = color:new() local find_start, find_end, red, green, blue = string.find(text, '([%x][%x])([%x][%x])([%x][%x])[^%x]?') if find_start ~= nil then red = tonumber(red, 16) green = tonumber(green, 16) blue = tonumber(blue, 16) c:red(red / 255) c:green(green / 255) c:blue(blue / 255) color_object:set_color(c) return 1 - (math.atan(find_start - 1) / math.pi) - (math.atan(string.len(text) - find_end) / math.pi) else return -1 end end gpick.serialize_web_hex_3_digit = function(color_object, params) if not color_object then return nil end if not params then return nil end local c = color_object:get_color() if gpick.options.upper_case then return '#' .. string.format('%01X%01X%01X', round(c:red() * 15), round(c:green() * 15), round(c:blue() * 15)) else return '#' .. string.format('%01x%01x%01x', round(c:red() * 15), round(c:green() * 15), round(c:blue() * 15)) end end gpick.deserialize_web_hex_3_digit = function(text, color_object) local c = color:new() local find_start, find_end, red, green, blue = string.find(text, '#([%x])([%x])([%x])[^%x]?') if find_start ~= nil then red = tonumber(red, 16) green = tonumber(green, 16) blue = tonumber(blue, 16) c:red(red / 15) c:green(green / 15) c:blue(blue / 15) color_object:set_color(c) return 1 - (math.atan(find_start - 1) / math.pi) - (math.atan(string.len(text) - find_end) / math.pi) else return -1 end end gpick.serialize_css_hsl = function (color_object) local c = color_object:get_color() c = c:rgb_to_hsl() return 'hsl(' .. string.format('%d, %d%%, %d%%', round(c:hue() * 360), round(c:saturation() * 100), round(c:lightness() * 100)) .. ')' end gpick.serialize_css_rgb = function (color_object) local c = color_object:get_color() return 'rgb(' .. string.format('%d, %d, %d', round(c:red() * 255), round(c:green() * 255), round(c:blue() * 255)) .. ')' end gpick.serialize_color_css_block = function(color_object, params, position) if not color_object then return nil end if not params then return nil end local c = color_object:get_color() local hsl = c:rgb_to_hsl() local result = ''; if position.first then result = '/**\n * Generated by Gpick ' .. gpick.global.version .. '\n' end local name = color_object:get_name() if not name then name = '' end result = result .. ' * ' .. name .. ': ' if gpick.options.upper_case then result = result .. '#' .. string.format('%02X%02X%02X', round(c:red()*255), round(c:green()*255), round(c:blue()*255)) else result = result .. '#' .. string.format('%02x%02x%02x', round(c:red()*255), round(c:green()*255), round(c:blue()*255)) end result = result .. ', rgb(' .. string.format('%d, %d, %d', round(c:red()*255), round(c:green()*255), round(c:blue()*255)) .. '), hsl(' .. string.format('%d, %d%%, %d%%', round(c:hue()*360), round(c:saturation()*100), round(c:lightness()*100)) .. ')' if position.last then result = result .. '\n */' end return result end gpick.deserialize_css_rgb = function(text, color_object) local c = color:new() local find_start, find_end, red, green, blue = string.find(text, 'rgb%(([%d]*)[%s]*,[%s]*([%d]*)[%s]*,[%s]*([%d]*)%)') if find_start ~= nil then c:rgb(math.min(1, red / 255), math.min(1, green / 255), math.min(1, blue / 255)) color_object:set_color(c) return 1 - (math.atan(find_start - 1) / math.pi) - (math.atan(string.len(text) - find_end) / math.pi) else return -1 end end gpick.serialize_css_color_hex = function(color_object, params) return 'color: ' .. gpick.serialize_web_hex(color_object, params) end gpick.serialize_css_background_color_hex = function(color_object, params) return 'background-color: ' .. gpick.serialize_web_hex(color_object, params) end gpick.serialize_css_border_color_hex = function(color_object, params) return 'border-color: ' .. gpick.serialize_web_hex(color_object, params) end gpick.serialize_css_border_top_color_hex = function(color_object, params) return 'border-top-color: ' .. gpick.serialize_web_hex(color_object, params) end gpick.serialize_css_border_right_color_hex = function(color_object, params) return 'border-right-color: ' .. gpick.serialize_web_hex(color_object, params) end gpick.serialize_css_border_bottom_color_hex = function(color_object, params) return 'border-bottom-color: ' .. gpick.serialize_web_hex(color_object, params) end gpick.serialize_css_border_left_hex = function(color_object, params) return 'border-left-color: ' .. gpick.serialize_web_hex(color_object, params) end gpick.serialize_color_csv = function(color_object) local c = color_object:get_color() os.setlocale("C", "numeric") local r = string.format('%f\t%f\t%f', c:red(), c:green(), c:blue()) os.setlocale("", "numeric") return r end gpick.converters['color_web_hex'] = { human_readable = _("Web: hex code"), serialize = gpick.serialize_web_hex, deserialize = gpick.deserialize_web_hex } gpick.converters['color_web_hex_3_digit'] = { human_readable = _("Web: hex code (3 digits)"), serialize = gpick.serialize_web_hex_3_digit, deserialize = gpick.deserialize_web_hex_3_digit } gpick.converters['color_web_hex_no_hash'] = { human_readable = _("Web: hex code (no hash symbol)"), serialize = gpick.serialize_web_hex_no_hash, deserialize = gpick.deserialize_web_hex_no_hash } gpick.converters['color_css_hsl'] = { human_readable = _("CSS: hue saturation lightness"), serialize = gpick.serialize_css_hsl, deserialize = nil } gpick.converters['color_css_rgb'] = { human_readable = _("CSS: red green blue"), serialize = gpick.serialize_css_rgb, deserialize = gpick.deserialize_css_rgb } gpick.converters['css_color_hex'] = { human_readable = 'CSS(color)', serialize = gpick.serialize_css_color_hex, deserialize = nil } gpick.converters['css_background_color_hex'] = { human_readable = 'CSS(background-color)', serialize = gpick.serialize_css_background_color_hex, deserialize = nil } gpick.converters['css_border_color_hex'] = { human_readable = 'CSS(border-color)', serialize = gpick.serialize_css_border_color_hex, deserialize = nil } gpick.converters['css_border_top_color_hex'] = { human_readable = 'CSS(border-top-color)', serialize = gpick.serialize_css_border_top_color_hex, deserialize = nil } gpick.converters['css_border_right_color_hex'] = { human_readable = 'CSS(border-right-color)', serialize = gpick.serialize_css_border_right_color_hex, deserialize = nil } gpick.converters['css_border_bottom_color_hex'] = { human_readable = 'CSS(border-bottom-color)', serialize = gpick.serialize_css_border_bottom_color_hex, deserialize = nil } gpick.converters['css_border_left_hex'] = { human_readable = 'CSS(border-left-color)', serialize = gpick.serialize_css_border_left_hex, deserialize = nil } gpick.converters['color_csv'] = { human_readable = 'CSV', serialize = gpick.serialize_color_csv, deserialize = nil }; gpick.converters['color_css_block'] = { human_readable = 'CSS block', serialize = gpick.serialize_color_css_block, deserialize = nil }; gpick.color_serialize = function(converter, color_object, params, position) return gpick.converters[converter].serialize(color_object, params, position) end gpick.color_deserialize = function(converter, text, color_object, params) return gpick.converters[converter].deserialize(text, color_object, params) end gpick.component_to_text = function(component_type, color) if component_type == 'rgb' then return {round(color:red()*255) .. '', round(color:green()*255) .. '', round(color:blue()*255) .. ''} end if component_type == 'hsl' then return {round(color:hue()*360) .. '', round(color:saturation()*100) .. '', round(color:lightness()*100) .. ''} end if component_type == 'hsv' then return {round(color:hue()*360) .. '', round(color:saturation()*100) .. '', round(color:value()*100) .. ''} end if component_type == 'cmyk' then return {round(color:cyan()*255) .. '', round(color:magenta()*255) .. '', round(color:yellow()*255) .. '', round(color:key_black()*255) .. ''} end if component_type == 'lab' then return {round(color:lab_lightness()) .. '', round(color:lab_a()) .. '', round(color:lab_b()) .. ''} end if component_type == 'lch' then return {round(color:lch_lightness()) .. '', round(color:lch_chroma()) .. '', round(color:lch_hue()) .. ''} end return {} end gpick.options_update = function(params) gpick.options.upper_case = params:get_string('gpick.options.hex_case', 'upper') == 'upper' end gpick-gpick-0.2.6rc1/share/gpick/layouts.lua000066400000000000000000000201561315430016700207230ustar00rootroot00000000000000 gpick.layouts = {}; layouts = {}; layouts.add_buttons = function (container, buttons, percentage, button_style, text_style, spacing) local root = layout:new_box('', spacing , spacing, 1-spacing*2, percentage-spacing*2); container:add(root); local size = 1/buttons; local padding = size/8; local styles_n = # button_style; local styles_text_n = # text_style; local texts = {_("Homepage"), _("About us"), _("Links to us"), _("Privacy"), _("Terms"), _("Contact us"), _("RSS")}; for i=0,buttons-1 do local button = layout:new_fill("button", padding, i*size+padding, 1-padding*2, size-padding, button_style[i % styles_n + 1] ); button:add(layouts.make_helper(layout:new_text("button_text", 0.25, 0.65, 0.5, 0.3, text_style[i % styles_text_n + 1], button_style[i % styles_n + 1]:humanname()))); button:add(layout:new_text("button_text", 0.25, 0.25, 0.5, 0.5, text_style[i % styles_text_n + 1], texts[i % (# texts) + 1])); root:add(button); end; return container; end; layouts.add_text = function (container, lines, style) local text = color:new(); for i=0,lines-1 do container:add(layout:new_text("content_text", 0.02, i*0.06+0.01, 0.96, 0.06, style, _("The quick brown fox jumps over the lazy dog"))); end; return container; end; layouts.make_helper = function (container) container:helper_only(true); return container; end; layouts.make_locked = function (container) container:locked(true); return container; end; gpick.layouts['std_layout_webpage_1'] = { human_readable = _("Webpage"), mask = 0, build = function (layout_system) local styles = { header = layout_style:new("header_b:" .. _("Header"), color:new(0.2, 0.2, 0.2)), header_text = layout_style:new("header_t:" .. _("Header text"), color:new(1.0, 1.0, 1.0), 1.0), content = layout_style:new("content_b:" .. _("Content"), color:new(0.6, 0.6, 0.6)), content_text = layout_style:new("content_t:" .. _("Content text"), color:new(0.1, 0.1, 0.1), 0.6), sidebar = layout_style:new("sidebar_b:" .. _("Sidebar"), color:new(0.7, 0.7, 0.7)), button = layout_style:new("navitem_b:" .. _("Button"), color:new(0.3, 0.3, 0.3)), button_hover = layout_style:new("navitem_bh:" .. _("Button (hover)"), color:new(0.35, 0.35, 0.35)), button_text = layout_style:new("navitem_t:" .. _("Button text"), color:new(0.8, 0.8, 0.8), 0.95), button_text_hover = layout_style:new("navitem_th:" .. _("Button text (hover)"), color:new(0.9, 0.9, 0.9), 0.95), footer = layout_style:new("footer_b:" .. _("Footer"), color:new(0.1, 0.1, 0.1)), }; for i,v in pairs(styles) do layout_system:addstyle(v); end; local root = layout:new_box("root", 0, 0, 640, 480); layout_system:setbox(root); root:add(layout:new_fill("header", 0, 0, 1, 0.15, styles['header']):add(layout:new_text("header_text", 0.25, 0.25, 0.5, 0.5, styles['header_text'], _("Header")))); root:add(layouts.add_buttons(layout:new_fill("sidebar", 0, 0.15, 0.25, 0.8, styles['sidebar']), 6, 0.7, { styles['button'], styles['button'], styles['button_hover'] }, { styles['button_text'], styles['button_text'], styles['button_text_hover'] }, 0, 0)); root:add(layouts.add_text(layout:new_fill("content", 0.25, 0.15, 0.75, 0.8, styles['content']), 10, styles['content_text'])); root:add(layout:new_fill("footer", 0, 0.95, 1, 0.05, styles['footer']):add(layouts.make_helper(layout:new_text("footer_text", 0.25, 0.5, 0.5, 0.45, nil, styles['footer']:humanname())))); return 1; end; }; gpick.layouts['std_layout_menu_1'] = { human_readable = _("Menu"), mask = 0, build = function (layout_system) local styles = { menu = layout_style:new("menu_b:" .. _("Menu"), color:new(0.7, 0.7, 0.7)), button = layout_style:new("navitem_b:" .. _("Button"), color:new(0.3, 0.3, 0.3)), button_hover = layout_style:new("navitem_bh:" .. _("Button (hover)"), color:new(0.3, 0.3, 0.3)), button_text = layout_style:new("navitem_t:" .. _("Button text"), color:new(0.8, 0.8, 0.8), 1.0), button_text_hover = layout_style:new("navitem_th:" .. _("Button text (hover)"), color:new(0.8, 0.8, 0.8), 1.0), }; for i,v in pairs(styles) do layout_system:addstyle(v); end; local root = layout:new_box("root", 0, 0, 300, 400); layout_system:setbox(root); root:add(layouts.add_buttons(layout:new_fill("menu", 0, 0, 1, 1, styles['menu']), 7, 1, { styles['button'], styles['button'], styles['button_hover'] }, { styles['button_text'], styles['button_text'], styles['button_text_hover'] }, 0.1)); return 1; end; }; gpick.layouts['std_layout_brightness_darkness'] = { human_readable = _("Brightness-Darkness"), mask = 1, build = function (layout_system) local styles = { main = layout_style:new("main:" .. _("main"), color:new(0.7, 0.7, 0.7)), bvar1 = layout_style:new("b1:b1", color:new(0.3, 0.3, 0.3)), bvar2 = layout_style:new("b2:b2", color:new(0.3, 0.3, 0.3)), bvar3 = layout_style:new("b3:b3", color:new(0.3, 0.3, 0.3)), bvar4 = layout_style:new("b4:b4", color:new(0.3, 0.3, 0.3)), cvar1 = layout_style:new("c1:c1", color:new(0.3, 0.3, 0.3)), cvar2 = layout_style:new("c2:c2", color:new(0.3, 0.3, 0.3)), cvar3 = layout_style:new("c3:c3", color:new(0.3, 0.3, 0.3)), cvar4 = layout_style:new("c4:c4", color:new(0.3, 0.3, 0.3)), }; local styles_order = {'cvar4', 'cvar3', 'cvar2','cvar1', 'main', 'bvar1', 'bvar2', 'bvar3', 'bvar4'}; for i,v in ipairs(styles_order) do layout_system:addstyle(styles[v]); end; local root = layout:new_box("root", 0, 0, 320, 128); layout_system:setbox(root); root:add(layouts.make_locked(layout:new_fill("b1", 0.00, 0.00, 0.30, 0.25, styles['bvar1']))); root:add(layouts.make_locked(layout:new_fill("b2", 0.00, 0.25, 0.30, 0.25, styles['bvar2']))); root:add(layouts.make_locked(layout:new_fill("b3", 0.00, 0.50, 0.30, 0.25, styles['bvar3']))); root:add(layouts.make_locked(layout:new_fill("b4", 0.00, 0.75, 0.30, 0.25, styles['bvar4']))); root:add(layouts.make_locked(layout:new_fill("c1", 0.70, 0.00, 0.30, 0.25, styles['cvar1']))); root:add(layouts.make_locked(layout:new_fill("c2", 0.70, 0.25, 0.30, 0.25, styles['cvar2']))); root:add(layouts.make_locked(layout:new_fill("c3", 0.70, 0.50, 0.30, 0.25, styles['cvar3']))); root:add(layouts.make_locked(layout:new_fill("c4", 0.70, 0.75, 0.30, 0.25, styles['cvar4']))); root:add(layout:new_fill("main", 0.30, 0.00, 0.40, 1.00, styles['main'])); return 1; end; }; gpick.layouts['std_layout_grid_1'] = { human_readable = _("Grid (4x3)"), mask = 0, build = function (layout_system) local root = layout:new_box("root", 0, 0, 400, 300); layout_system:setbox(root); for j=0,2 do for i=0,3 do local item_i = 1 + (i + j * 4); local style = layout_style:new("item" .. item_i .. ":" .. _("Item") .. item_i, color:new(0.8, 0.8, 0.8), 1.0); local style_text = layout_style:new("item" .. item_i .. "_text:" .. _("Item text") .. item_i, color:new(0.2, 0.2, 0.2), 0.5); layout_system:addstyle(style); layout_system:addstyle(style_text); local fill = layout:new_fill("b" .. item_i, (1 / 4) * i, (1 / 3) * j, (1 / 4) * 0.95, (1 / 3) * 0.95, style); fill:add(layout:new_text("item_text".. item_i, 0, 0.25, 1, 0.5, style_text, _("Item") .. item_i)); root:add(fill); end; end; return 1; end; }; gpick.layouts['std_layout_grid_2'] = { human_readable = _("Grid (5x4)"), mask = 0, build = function (layout_system) local root = layout:new_box("root", 0, 0, 500, 400); layout_system:setbox(root); for j=0,3 do for i=0,4 do local item_i = 1 + (i + j * 5); local style = layout_style:new("item" .. item_i .. ":" .. _("Item") .. item_i, color:new(0.8, 0.8, 0.8), 1.0); local style_text = layout_style:new("item" .. item_i .. "_text:" .. _("Item text") .. item_i, color:new(0.2, 0.2, 0.2), 0.5); layout_system:addstyle(style); layout_system:addstyle(style_text); local fill = layout:new_fill("b" .. item_i, (1 / 5) * i, (1 / 4) * j, (1 / 5) * 0.95, (1 / 4) * 0.95, style); fill:add(layout:new_text("item_text".. item_i, 0, 0.25, 1, 0.5, style_text, _("Item") .. item_i)); root:add(fill); end; end; return 1; end; }; gpick.layouts_get = function() local layouts = {}; for k,v in pairs(gpick.layouts) do table.insert(layouts, k) end; table.sort(layouts); return layouts; end; gpick-gpick-0.2.6rc1/share/icons/000077500000000000000000000000001315430016700165325ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/icons/hicolor/000077500000000000000000000000001315430016700201715ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/icons/hicolor/48x48/000077500000000000000000000000001315430016700207705ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/icons/hicolor/48x48/apps/000077500000000000000000000000001315430016700217335ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/icons/hicolor/48x48/apps/gpick.png000066400000000000000000000033411315430016700235370ustar00rootroot00000000000000PNG  IHDR00WsBIT|d pHYs B(xtEXtSoftwarewww.inkscape.org<^IDAThmlTerܙig,3mm ZaqaĪՍDLQ]Q1 Uf YdhRiE` ڈFАmS;eZw;N&_~1)k蹉"++Kz(~1Ƣyyy2 IRyJ#TU= KsޣiӡPHI0le)?pP(j"ȉp8ᅯX(& %Q{" -眳.Wh4"] p8䄁x<MC0Dccc oDhyy>M$) Vv Ϸ,\cUV=ֶMQMAMӒ&A0b6Lj^^|w p8xҥ Ec4 $Fqˬx|u |[ @@(2^\\-ÌNvoڴt9sfDxxl6`۽<'''.I҆|g۶m<OשS~? |1&V5eyq \wΝ)yɚIab,/~ $:wFEQ>z#Ź^|""!Ojw쮺tx H7O=|QwkTlb{Z^0ZA |ﱀWUr_a" +?K,` )}=G v1 "qG4T--QT/ =2g_v/PnE`R>kU 9~m{\)Q4-_Xe7#2I5gp4 ~?b̶8R{WSiV9V?79Nx[To= BDT7;9%c}.cao<9w95L ̳_Α  >Vڧ**7+fox`&ʿ~w>FD7w  [[YRJ%/`*v<McFMWȴвj'IENDB`gpick-gpick-0.2.6rc1/share/icons/hicolor/scalable/000077500000000000000000000000001315430016700217375ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/icons/hicolor/scalable/apps/000077500000000000000000000000001315430016700227025ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/icons/hicolor/scalable/apps/gpick.svg000066400000000000000000000226251315430016700245270ustar00rootroot00000000000000 image/svg+xml gpick-gpick-0.2.6rc1/share/locale/000077500000000000000000000000001315430016700166565ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/locale/cs/000077500000000000000000000000001315430016700172635ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/locale/cs/LC_MESSAGES/000077500000000000000000000000001315430016700210505ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/locale/cs/LC_MESSAGES/gpick.po000066400000000000000000000705771315430016700225250ustar00rootroot00000000000000# Pavel Fric , 2013. msgid "" msgstr "" "Project-Id-Version: gpick 0.2.5rc1\n" "POT-Creation-Date: 2013-01-05 16:16+0200\n" "PO-Revision-Date: 2013-06-25 18:37+0200\n" "Last-Translator: Pavel Fric \n" "Language-Team: Czech \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" "Language: cs\n" "X-Generator: Lokalize 1.5\n" #: source/BlendColors.cpp:114 source/BlendColors.cpp:116 msgid "blend node" msgstr "Uzel míchání" #: source/BlendColors.cpp:119 msgid "blend" msgstr "Míchání" #: source/BlendColors.cpp:308 source/BrightnessDarkness.cpp:260 #: source/ColorMixer.cpp:321 source/ColorPicker.cpp:367 #: source/GenerateScheme.cpp:444 source/LayoutPreview.cpp:405 #: source/Variations.cpp:331 source/uiDialogOptions.cpp:215 #: source/uiDialogOptions.cpp:234 msgid "_Add to palette" msgstr "_Přidat do palety" #: source/BlendColors.cpp:314 source/BrightnessDarkness.cpp:265 #: source/ColorMixer.cpp:326 source/ColorPicker.cpp:371 #: source/GenerateScheme.cpp:449 source/LayoutPreview.cpp:410 #: source/Variations.cpp:336 msgid "A_dd all to palette" msgstr "Při_dat všedo palety" #: source/BlendColors.cpp:320 source/BrightnessDarkness.cpp:271 #: source/ColorMixer.cpp:333 source/ColorPicker.cpp:377 #: source/GenerateScheme.cpp:456 source/LayoutPreview.cpp:416 #: source/Variations.cpp:343 source/uiDialogOptions.cpp:220 #: source/uiDialogOptions.cpp:239 msgid "_Copy to clipboard" msgstr "_Kopírovat do schránky" #: source/BlendColors.cpp:374 source/GenerateScheme.cpp:485 msgid "_Reset" msgstr "_Nastavit znovu" #: source/BlendColors.cpp:517 msgid "Start:" msgstr "Začátek:" #: source/BlendColors.cpp:533 msgid "Middle:" msgstr "Střed:" #: source/BlendColors.cpp:551 msgid "End:" msgstr "Konec:" #: source/BlendColors.cpp:568 source/GenerateScheme.cpp:875 #: source/uiDialogGenerate.cpp:237 source/uiDialogMix.cpp:249 #: source/transformation/ColorVisionDeficiency.cpp:363 msgid "Type:" msgstr "Typ:" #: source/BlendColors.cpp:570 source/ColorWheelType.cpp:56 #: source/uiDialogMix.cpp:251 msgid "RGB" msgstr "RGB" #: source/BlendColors.cpp:571 source/uiDialogMix.cpp:252 msgid "HSV" msgstr "HSV" #: source/BlendColors.cpp:572 source/uiDialogMix.cpp:253 msgid "HSV shortest hue distance" msgstr "Nejkratší vzdálenost odstínu HSV" #: source/BlendColors.cpp:573 source/uiDialogMix.cpp:254 msgid "LAB" msgstr "LAB" #: source/BlendColors.cpp:582 msgid "Start steps:" msgstr "Kroky:" #: source/BlendColors.cpp:590 msgid "End steps:" msgstr "Kroky:" #: source/BlendColors.cpp:627 msgid "Blend colors" msgstr "Míchat barvy" #: source/BrightnessDarkness.cpp:86 msgid "brightness darkness" msgstr "jas tma" #: source/BrightnessDarkness.cpp:287 source/ColorMixer.cpp:373 #: source/ColorPicker.cpp:387 source/GenerateScheme.cpp:469 #: source/LayoutPreview.cpp:430 source/Variations.cpp:383 msgid "_Edit..." msgstr "_Upravit..." #: source/BrightnessDarkness.cpp:292 source/ColorMixer.cpp:378 #: source/ColorPicker.cpp:391 source/GenerateScheme.cpp:474 #: source/LayoutPreview.cpp:435 source/Variations.cpp:388 msgid "_Paste" msgstr "_Vložit" #: source/BrightnessDarkness.cpp:385 msgid "Brightness" msgstr "Jas" #: source/BrightnessDarkness.cpp:385 msgid "Darkness" msgstr "Tma" #: source/BrightnessDarkness.cpp:431 msgid "Brightness Darkness" msgstr "Jas - Tma" #: source/ColorMixer.cpp:66 msgid "Normal" msgstr "Normální" #: source/ColorMixer.cpp:67 msgid "Multiply" msgstr "Násobit" #: source/ColorMixer.cpp:68 msgid "Add" msgstr "Přidat" #: source/ColorMixer.cpp:69 msgid "Difference" msgstr "Rozdíl" #: source/ColorMixer.cpp:70 source/ColorPicker.cpp:1180 #: source/ColorPicker.cpp:1194 source/ColorSpaceType.cpp:30 #: source/ColorSpaceType.cpp:37 source/Variations.cpp:66 msgid "Hue" msgstr "Odstín" #: source/ColorMixer.cpp:71 source/ColorPicker.cpp:1180 #: source/ColorPicker.cpp:1194 source/ColorSpaceType.cpp:31 #: source/ColorSpaceType.cpp:38 source/Variations.cpp:67 msgid "Saturation" msgstr "Sytost" #: source/ColorMixer.cpp:72 source/ColorPicker.cpp:1194 #: source/ColorPicker.cpp:1236 source/ColorPicker.cpp:1250 #: source/ColorSpaceType.cpp:39 source/ColorSpaceType.cpp:59 #: source/ColorSpaceType.cpp:66 source/Variations.cpp:68 msgid "Lightness" msgstr "Světlost" #: source/ColorMixer.cpp:114 msgid "color mixer" msgstr "Mísič barev" #: source/ColorMixer.cpp:234 msgid "secondary" msgstr "Doplňkový" #: source/ColorMixer.cpp:238 source/Variations.cpp:229 #, c-format msgid "primary %d" msgstr "Základní %d" #: source/ColorMixer.cpp:244 #, c-format msgid "result %d" msgstr "Výsledek %d" #: source/ColorMixer.cpp:704 msgid "Opacity:" msgstr "Neprůhlednost:" #: source/ColorMixer.cpp:732 msgid "Color mixer" msgstr "Mísič barev" #: source/ColorPicker.cpp:424 msgid "Press Spacebar to sample color under mouse pointer" msgstr "" "Stisknout mezerník pro odebrání vzorku zachycením barvy pod ukazovátkem myši" #: source/ColorPicker.cpp:699 source/uiConverter.cpp:163 msgid "Copy" msgstr "Kopírovat" #: source/ColorPicker.cpp:703 source/uiConverter.cpp:172 msgid "Paste" msgstr "Vložit" #: source/ColorPicker.cpp:709 source/uiColorInput.cpp:119 msgid "Edit" msgstr "Upravit" #: source/ColorPicker.cpp:771 source/uiApp.cpp:1012 #: source/uiDialogSort.cpp:222 msgid "None" msgstr "Žádný" #: source/ColorPicker.cpp:772 msgid "Linear" msgstr "Lineární" #: source/ColorPicker.cpp:773 msgid "Quadratic" msgstr "Kvadratický" #: source/ColorPicker.cpp:774 msgid "Cubic" msgstr "Kubický" #: source/ColorPicker.cpp:775 msgid "Exponential" msgstr "Exponenciální" #: source/ColorPicker.cpp:951 msgid "Click on swatch area to begin adding colors to palette" msgstr "Klepnout na oblast se vzorky pro započetí s přidáváním barev do palety" #: source/ColorPicker.cpp:1143 msgid "Settings" msgstr "Nastavení" #: source/ColorPicker.cpp:1153 msgid "Oversample:" msgstr "Oblast vzorku:" #: source/ColorPicker.cpp:1160 msgid "Falloff:" msgstr "Pokles:" #: source/ColorPicker.cpp:1167 msgid "Zoom:" msgstr "Zvětšení:" #: source/ColorPicker.cpp:1180 source/ColorSpaceType.cpp:32 msgid "Value" msgstr "Hodnota" #: source/ColorPicker.cpp:1208 source/ColorSpaceType.cpp:44 msgid "Red" msgstr "Červená" #: source/ColorPicker.cpp:1208 source/ColorSpaceType.cpp:45 msgid "Green" msgstr "Zelená" #: source/ColorPicker.cpp:1208 source/ColorSpaceType.cpp:46 msgid "Blue" msgstr "Modrá" #: source/ColorPicker.cpp:1222 source/ColorSpaceType.cpp:51 msgid "Cyan" msgstr "Azurová" #: source/ColorPicker.cpp:1222 source/ColorSpaceType.cpp:52 msgid "Magenta" msgstr "Purpurová" #: source/ColorPicker.cpp:1222 source/ColorSpaceType.cpp:53 msgid "Yellow" msgstr "Žlutá" #: source/ColorPicker.cpp:1222 source/ColorSpaceType.cpp:54 msgid "Key" msgstr "Černá (key)" #: source/ColorPicker.cpp:1258 msgid "Info" msgstr "Informace" #: source/ColorPicker.cpp:1267 msgid "Color name:" msgstr "Název barvy:" #: source/ColorPicker.cpp:1280 msgid "Contrast:" msgstr "Kontrast:" #: source/ColorPicker.cpp:1285 source/ColorPicker.cpp:1291 msgid "Sample" msgstr "Vzorek" #: source/ColorPicker.cpp:1324 msgid "Color picker" msgstr "Kapátko" #: source/ColorWheelType.cpp:57 msgid "RYB v1" msgstr "RYB v1" #: source/ColorWheelType.cpp:58 msgid "RYB v2" msgstr "RYB v2" #: source/GenerateScheme.cpp:90 msgid "Complementary" msgstr "Doplňkový" #: source/GenerateScheme.cpp:91 msgid "Analogous" msgstr "Analogový" #: source/GenerateScheme.cpp:92 msgid "Triadic" msgstr "Trojičný" #: source/GenerateScheme.cpp:93 msgid "Split-Complementary" msgstr "Rozdělit - doplňkový" #: source/GenerateScheme.cpp:94 msgid "Rectangle (tetradic)" msgstr "Obdélník (čtverný)" #: source/GenerateScheme.cpp:95 msgid "Square" msgstr "Čtverec" #: source/GenerateScheme.cpp:96 msgid "Neutral" msgstr "Neutrální" #: source/GenerateScheme.cpp:97 msgid "Clash" msgstr "Doplňkový - střetnutí" #: source/GenerateScheme.cpp:98 msgid "Five-Tone" msgstr "Pět tónů" #: source/GenerateScheme.cpp:99 msgid "Six-Tone" msgstr "Šest tónů" #: source/GenerateScheme.cpp:119 source/uiDialogGenerate.cpp:76 msgid "scheme" msgstr "Sada" #: source/GenerateScheme.cpp:292 msgid "_Locked" msgstr "_Uzamknuto" #: source/GenerateScheme.cpp:299 msgid "_Reset scheme" msgstr "_Nastavit sadu znovu" #: source/GenerateScheme.cpp:851 msgid "Hue:" msgstr "Odstín:" #: source/GenerateScheme.cpp:858 source/uiDialogVariations.cpp:171 msgid "Saturation:" msgstr "Sytost:" #: source/GenerateScheme.cpp:866 source/uiDialogVariations.cpp:156 msgid "Lightness:" msgstr "Světlost:" #: source/GenerateScheme.cpp:885 source/uiDialogGenerate.cpp:246 msgid "Color wheel:" msgstr "Kolo barev:" #: source/GenerateScheme.cpp:919 msgid "Scheme generation" msgstr "Vytvoření sady" #: source/LayoutPreview.cpp:78 msgid "layout preview" msgstr "Náhled na rozvržení" #: source/LayoutPreview.cpp:153 msgid "Style item" msgstr "Položka stylu" #: source/LayoutPreview.cpp:162 msgid "CSS selector" msgstr "Volič CSS" #: source/LayoutPreview.cpp:184 msgid "Assign CSS selectors" msgstr "Přiřadit voliče CSS" #: source/LayoutPreview.cpp:547 source/LayoutPreview.cpp:595 #: source/uiApp.cpp:690 source/uiApp.cpp:711 msgid "File could not be saved" msgstr "Soubor se nepodařilo uložit" #: source/LayoutPreview.cpp:558 source/uiExport.cpp:457 #: source/uiExport.cpp:523 msgid "Export" msgstr "Vyvést" #: source/LayoutPreview.cpp:572 msgid "Cascading Style Sheets *.css" msgstr "Listy s kaskádovými styly *.css" #: source/LayoutPreview.cpp:666 msgid "Layout:" msgstr "Rozvržení:" #: source/LayoutPreview.cpp:672 msgid "Export CSS File" msgstr "Vyvést soubor CSS" #: source/LayoutPreview.cpp:673 msgid "Export CSS file" msgstr "Vyvést soubor CSS" #: source/LayoutPreview.cpp:682 msgid "_Export CSS File As..." msgstr "_Vyvést soubor CSS jako..." #: source/LayoutPreview.cpp:686 msgid "_Assign CSS Selectors..." msgstr "_Přiřadit voliče CSS..." #: source/LayoutPreview.cpp:759 msgid "Layout preview" msgstr "Náhled na rozvržení" #: source/ToolColorNaming.cpp:25 msgid "_Empty" msgstr "_Prázdný" #: source/ToolColorNaming.cpp:26 msgid "_Automatic name" msgstr "_Automatický název" #: source/ToolColorNaming.cpp:27 msgid "_Tool specific" msgstr "Zvláštní _nástroj" #: source/Variations.cpp:69 msgid "Lightness (Lab)" msgstr "Světlost (Lab)" #: source/Variations.cpp:110 msgid "variations" msgstr "Obměny" #: source/Variations.cpp:225 msgid "all colors" msgstr "Všechny barvy" #: source/Variations.cpp:239 #, c-format msgid "result %d line %d" msgstr "Výsledek %d řádek %d" #: source/Variations.cpp:717 #: source/transformation/ColorVisionDeficiency.cpp:386 msgid "Strength:" msgstr "Síla:" #: source/Variations.cpp:745 source/uiDialogVariations.cpp:142 msgid "Variations" msgstr "Obměny" #: source/uiAbout.cpp:88 msgid "About Gpick" msgstr "O programu Gpick" #: source/uiAbout.cpp:121 msgid "Advanced color picker" msgstr "Pokročilý sběrač barev" #: source/uiAbout.cpp:126 msgid "Copyrights © 2009-2013, Albertas Vyšniauskas and Gpick development team" msgstr "" "Autorské právo © 2009-2013, Albertas Vyšniauskas a vývojářská skupina pro" "Gpick" #: source/uiAbout.cpp:141 msgid "License" msgstr "Povolení" #: source/uiAbout.cpp:142 msgid "Credits" msgstr "Zásluhy" #: source/uiAbout.cpp:143 msgid "Expat License" msgstr "Licence Expat" #: source/uiAbout.cpp:144 msgid "Lua License" msgstr "Licence Lua" #: source/uiApp.cpp:354 msgid "New palette" msgstr "Nová paleta" #: source/uiApp.cpp:360 msgid "(Imported)" msgstr "(Zavedeno)" #: source/uiApp.cpp:530 source/uiApp.cpp:545 source/uiApp.cpp:563 #: source/uiApp.cpp:641 msgid "File could not be opened" msgstr "Soubor se nepodařilo otevřít" #: source/uiApp.cpp:531 source/uiApp.cpp:546 source/uiApp.cpp:564 #: source/uiApp.cpp:642 msgid "Open" msgstr "Otevřít" #: source/uiApp.cpp:576 source/uiExport.cpp:473 source/uiExport.cpp:587 msgid "Gpick Palette (*.gpa)" msgstr "Paleta Gpick (*.gpa)" #: source/uiApp.cpp:577 source/uiExport.cpp:474 source/uiExport.cpp:588 msgid "GIMP/Inkscape Palette (*.gpl)" msgstr "Paleta GIMP/Inkscape (*.gpl)" #: source/uiApp.cpp:578 source/uiExport.cpp:476 source/uiExport.cpp:589 msgid "Adobe Swatch Exchange (*.ase)" msgstr "Adobe Swatch Exchange (*.ase)" #: source/uiApp.cpp:584 source/uiExport.cpp:598 #: source/tools/PaletteFromImage.cpp:548 msgid "All files" msgstr "Všechny soubory" #: source/uiApp.cpp:589 source/uiExport.cpp:607 msgid "All supported formats" msgstr "Všechny podporované formáty" #: source/uiApp.cpp:610 msgid "Open File" msgstr "Otevřít soubor" #: source/uiApp.cpp:659 source/uiApp.cpp:691 msgid "Save As" msgstr "Uložit jako" #: source/uiApp.cpp:712 msgid "Save" msgstr "Uložit" #: source/uiApp.cpp:771 msgid "Open Last File" msgstr "Otevřít poslední soubor" #: source/uiApp.cpp:916 msgid "Recent _files" msgstr "_Nedávné soubory" #: source/uiApp.cpp:946 msgid "Ex_port..." msgstr "Vy_vést..." #: source/uiApp.cpp:954 msgid "Expo_rt Selected..." msgstr "Vy_vést vybrané..." #: source/uiApp.cpp:962 msgid "_Import..." msgstr "_Zavést..." #: source/uiApp.cpp:977 msgid "_File" msgstr "_Soubor" #: source/uiApp.cpp:985 msgid "Edit _Converters..." msgstr "Upravit _převodníky..." #: source/uiApp.cpp:989 msgid "Display _Filters..." msgstr "Zobrazit _filtry..." #: source/uiApp.cpp:1001 msgid "_Edit" msgstr "Úp_ravy" #: source/uiApp.cpp:1037 msgid "_Secondary View" msgstr "_Doplňkový pohled" #: source/uiApp.cpp:1043 msgid "Palette" msgstr "Paleta" #: source/uiApp.cpp:1049 msgid "_View" msgstr "_Pohled" #: source/uiApp.cpp:1055 msgid "Palette From _Image..." msgstr "Paleta z _obrázku..." #: source/uiApp.cpp:1063 msgid "_Tools" msgstr "_Nástroje" #: source/uiApp.cpp:1078 msgid "_Help" msgstr "Nápo_věda" #: source/uiApp.cpp:1386 msgid "_Copy to Clipboard" msgstr "_Kopírovat do schránky" #: source/uiApp.cpp:1402 msgid "_Mix Colors..." msgstr "_Smíchat barvy..." #: source/uiApp.cpp:1407 msgid "_Variations..." msgstr "_Obměny..." #: source/uiApp.cpp:1412 msgid "_Generate..." msgstr "Vy_tvořit..." #: source/uiApp.cpp:1421 msgid "C_lear names" msgstr "_Smazat názvy" #: source/uiApp.cpp:1427 msgid "Autona_me" msgstr "Po_jmenovat automaticky" #: source/uiApp.cpp:1433 msgid "Auto_number..." msgstr "Čís_lovat automaticky" #: source/uiApp.cpp:1441 msgid "R_everse" msgstr "_Obrátit" #: source/uiApp.cpp:1447 msgid "Group and _sort..." msgstr "Seskupit a třídit" #: source/uiApp.cpp:1455 msgid "_Remove" msgstr "O_dstranit" #: source/uiApp.cpp:1461 msgid "Remove _All" msgstr "Odstranit _vše" #: source/uiApp.cpp:1869 msgid "Color pic_ker" msgstr "Volič _barvy" #: source/uiApp.cpp:1878 msgid "Scheme _generation" msgstr "_Vytvoření sady" #: source/uiApp.cpp:1897 msgid "Lay_out preview" msgstr "Náhled na _rozvržení" #: source/uiApp.cpp:1947 msgid "Pick colors (Ctrl+P)" msgstr "Zvolit si barvu (CTRL+P)" #: source/uiApp.cpp:1956 msgid "" "File is currently in a non-native format, possible loss of precision and/or " "metadata." msgstr "" "Soubor je v současnosti v nenativním formátu. Je možná ztráta přesnosti " "a/nebo popisných dat." #: source/uiColorInput.cpp:45 msgid "Edit color" msgstr "Upravit barvu" #: source/uiColorInput.cpp:69 msgid "Color:" msgstr "Barva:" #: source/uiConverter.cpp:56 msgid "Test color" msgstr "Vyzkoušet barvu" #: source/uiConverter.cpp:74 msgid "error" msgstr "Chyba" #: source/uiConverter.cpp:145 msgid "Function name" msgstr "Název funkce" #: source/uiConverter.cpp:154 msgid "Example" msgstr "Příklad" #: source/uiConverter.cpp:196 msgid "Converters" msgstr "Převodníky" #: source/uiConverter.cpp:224 msgid "Displays:" msgstr "Zobrazení:" #: source/uiConverter.cpp:230 msgid "Color list:" msgstr "Seznam barev:" #: source/uiDialogAutonumber.cpp:108 msgid "Autonumber colors" msgstr "Automatické číslování barev" #: source/uiDialogAutonumber.cpp:122 msgid "Name:" msgstr "Název:" #: source/uiDialogAutonumber.cpp:132 msgid "Decimal places:" msgstr "Desetinná místa:" #: source/uiDialogAutonumber.cpp:139 msgid "Starting number:" msgstr "Počáteční číslo:" #: source/uiDialogAutonumber.cpp:146 msgid "_Decreasing" msgstr "_Klesající" #: source/uiDialogAutonumber.cpp:152 msgid "_Append" msgstr "_Připojit" #: source/uiDialogAutonumber.cpp:158 msgid "Sample:" msgstr "Vzorek:" #: source/uiDialogGenerate.cpp:216 msgid "Generate colors" msgstr "Vytvořit barvy" #: source/uiDialogGenerate.cpp:230 source/tools/PaletteFromImage.cpp:599 msgid "Colors:" msgstr "Barvy:" #: source/uiDialogGenerate.cpp:257 msgid "Chaos:" msgstr "Chaos:" #: source/uiDialogGenerate.cpp:263 msgid "Seed:" msgstr "Semeno:" #: source/uiDialogGenerate.cpp:271 msgid "_Reverse" msgstr "__Otočit" #: source/uiDialogMix.cpp:76 source/uiDialogMix.cpp:78 msgid "mix node" msgstr "Uzel směsi" #: source/uiDialogMix.cpp:81 msgid "mix" msgstr "Směs" #: source/uiDialogMix.cpp:235 msgid "Mix colors" msgstr "Smíchat barvy" #: source/uiDialogMix.cpp:262 source/uiDialogVariations.cpp:186 msgid "Steps:" msgstr "Kroky:" #: source/uiDialogMix.cpp:270 msgid "_Include Endpoints" msgstr "_Zahrnout koncové body" #: source/uiDialogOptions.cpp:117 source/tools/PaletteFromImage.cpp:589 msgid "Options" msgstr "Volby" #: source/uiDialogOptions.cpp:134 msgid "System" msgstr "Systém" #: source/uiDialogOptions.cpp:143 msgid "_Single instance" msgstr "_Jedna instance" #: source/uiDialogOptions.cpp:148 msgid "Save/_Restore palette" msgstr "Uložit/Obnovit paletu" #: source/uiDialogOptions.cpp:154 msgid "System tray" msgstr "Oznamovací oblast panelu" #: source/uiDialogOptions.cpp:162 msgid "_Minimize to system tray" msgstr "_Zmenšit do oznamovací oblasti panelu" #: source/uiDialogOptions.cpp:167 msgid "_Close to system tray" msgstr "Z_avřít do oznamovací oblasti panelu" #: source/uiDialogOptions.cpp:172 msgid "_Start in system tray" msgstr "_Spustit v oznamovací oblasti panelu" #: source/uiDialogOptions.cpp:178 msgid "_Main" msgstr "_Hlavní" #: source/uiDialogOptions.cpp:184 msgid "Display" msgstr "Zobrazení" #: source/uiDialogOptions.cpp:193 msgid "_Refresh rate:" msgstr "_Obnovovací rychlost:" #: source/uiDialogOptions.cpp:201 msgid "_Magnified area size:" msgstr "Velikost z_většené oblasti:" #: source/uiDialogOptions.cpp:207 msgid "Floating picker click behaviour" msgstr "Chování klepnutí u plovoucího sběrače" #: source/uiDialogOptions.cpp:226 msgid "'Spacebar' button behaviour" msgstr "Chování mezerníku" #: source/uiDialogOptions.cpp:244 msgid "_Rotate swatch" msgstr "_Otočit vzorky" #: source/uiDialogOptions.cpp:251 msgid "Enabled color spaces" msgstr "Povoleny barevné prostory" #: source/uiDialogOptions.cpp:266 msgid "Lab settings" msgstr "Nastavení Lab" #: source/uiDialogOptions.cpp:278 msgid "_Illuminant:" msgstr "_Světlo:" #: source/uiDialogOptions.cpp:302 msgid "_Observer:" msgstr "_Pozorovatel:" #: source/uiDialogOptions.cpp:321 msgid "Other settings" msgstr "Jiná nastavení" #: source/uiDialogOptions.cpp:330 msgid "_Mask out of gamut colors" msgstr "Za_krýt barvy mimo rozsah" #: source/uiDialogOptions.cpp:336 msgid "_Picker" msgstr "_Kapátko" #: source/uiDialogOptions.cpp:341 msgid "Color name generation" msgstr "Vytvoření názvu barvy" #: source/uiDialogOptions.cpp:350 msgid "_Imprecision postfix" msgstr "Připojení _nepřesnosti" #: source/uiDialogOptions.cpp:356 msgid "Tool color naming" msgstr "Přiřazení názvu barvy" #: source/uiDialogOptions.cpp:381 msgid "_Color names" msgstr "_Názvy barev" #: source/uiDialogSort.cpp:135 source/uiDialogSort.cpp:223 msgid "RGB Red" msgstr "Červená RGB" #: source/uiDialogSort.cpp:136 source/uiDialogSort.cpp:224 msgid "RGB Green" msgstr "Zelená RGB" #: source/uiDialogSort.cpp:137 source/uiDialogSort.cpp:225 msgid "RGB Blue" msgstr "Modrá RGB" #: source/uiDialogSort.cpp:138 source/uiDialogSort.cpp:226 msgid "RGB Grayscale" msgstr "Odstíny šedé RGB" #: source/uiDialogSort.cpp:139 source/uiDialogSort.cpp:227 msgid "HSL Hue" msgstr "Odstín HSL" #: source/uiDialogSort.cpp:140 source/uiDialogSort.cpp:228 msgid "HSL Saturation" msgstr "Sytost HSL" #: source/uiDialogSort.cpp:141 source/uiDialogSort.cpp:229 msgid "HSL Lightness" msgstr "Světlost HSL" #: source/uiDialogSort.cpp:142 source/uiDialogSort.cpp:230 msgid "Lab Lightness" msgstr "Světlost Lab" #: source/uiDialogSort.cpp:143 source/uiDialogSort.cpp:231 msgid "Lab A" msgstr "Lab A" #: source/uiDialogSort.cpp:144 source/uiDialogSort.cpp:232 msgid "Lab B" msgstr "Lab B" #: source/uiDialogSort.cpp:145 source/uiDialogSort.cpp:233 msgid "LCh Lightness" msgstr "Světlost LCh" #: source/uiDialogSort.cpp:146 source/uiDialogSort.cpp:234 msgid "LCh Chroma" msgstr "Chroma LCh (barevná čistota)" #: source/uiDialogSort.cpp:147 source/uiDialogSort.cpp:235 msgid "LCh Hue" msgstr "Odstín LCh" #: source/uiDialogSort.cpp:556 msgid "Group and sort" msgstr "Seskupit a třídit" #: source/uiDialogSort.cpp:564 msgid "Group type:" msgstr "Typ skupiny:" #: source/uiDialogSort.cpp:574 msgid "Grouping sensitivity:" msgstr "Citlivost seskupení:" #: source/uiDialogSort.cpp:581 msgid "Maximum number of groups:" msgstr "Největší počet skupin:" #: source/uiDialogSort.cpp:588 msgid "Sort type:" msgstr "Typ třídění:" #: source/uiDialogSort.cpp:598 msgid "_Reverse group order" msgstr "O_brácený pořádek skupin" #: source/uiDialogSort.cpp:604 msgid "_Reverse order inside groups" msgstr "O_brácený pořádek skupin uvnitř skupin" #: source/uiDialogVariations.cpp:60 msgid "variation" msgstr "Obměna" #: source/uiDialogVariations.cpp:194 msgid "_Use multiplication" msgstr "_Použít násobení" #: source/uiExport.cpp:475 msgid "Alias/WaveFront Material (*.mtl)" msgstr "Materiál Alias/WaveFront (*.mtl)" #: source/uiExport.cpp:477 msgid "Text file (*.txt)" msgstr "Textový soubor (*.txt)" #: source/uiExport.cpp:522 msgid "File could not be exported" msgstr "Soubor se nepodařilo vyvést" #: source/uiExport.cpp:573 source/uiExport.cpp:654 source/uiExport.cpp:666 msgid "Import" msgstr "Zavést" #: source/uiExport.cpp:653 msgid "File format is not supported" msgstr "Formát souboru není podporován" #: source/uiExport.cpp:665 msgid "File could not be imported" msgstr "Soubor se nepodařilo zavést" #: source/uiListPalette.cpp:158 source/uiListPalette.cpp:160 #, c-format msgid "%d color" msgid_plural "%d colors" msgstr[0] "%d barva" msgstr[1] "%d barev" #: source/uiListPalette.cpp:166 msgid "selected" msgstr "vybráno" #: source/uiListPalette.cpp:172 source/uiListPalette.cpp:174 #, c-format msgid "Total %d color" msgid_plural "Total %d colors" msgstr[0] "Celkem %d barva" msgstr[1] "Celkem %d barev" #: source/uiListPalette.cpp:353 msgid "Preview" msgstr "Náhled" #: source/uiListPalette.cpp:708 source/uiListPalette.cpp:717 msgid "Color" msgstr "Barva" #: source/uiListPalette.cpp:726 source/uiTransformations.cpp:183 msgid "Name" msgstr "Název" #: source/uiStatusIcon.cpp:67 msgid "_Show Main Window" msgstr "_Ukázat hlavní okno" #: source/uiStatusIcon.cpp:74 msgid "_Quit" msgstr "_Ukončit" #: source/uiTransformations.cpp:245 msgid "Display filters" msgstr "Filtry zobrazení" #: source/uiTransformations.cpp:259 msgid "_Enabled" msgstr "_Zapnuto" #: source/tools/PaletteFromImage.cpp:514 msgid "Palette from image" msgstr "Paleta z obrázku" #: source/tools/PaletteFromImage.cpp:527 msgid "Image" msgstr "Obrázek" #: source/tools/PaletteFromImage.cpp:536 msgid "Image file" msgstr "Obrázkový soubor" #: source/tools/PaletteFromImage.cpp:556 msgid "All images" msgstr "Všechny obrázky" #: source/transformation/ColorVisionDeficiency.cpp:41 msgid "Color vision deficiency" msgstr "Nedostatek ve vidění barvy" #: source/transformation/ColorVisionDeficiency.cpp:330 msgid "Protanomaly" msgstr "Částečně bez červené" #: source/transformation/ColorVisionDeficiency.cpp:331 msgid "Deuteranomaly" msgstr "Částečně bez zelené" #: source/transformation/ColorVisionDeficiency.cpp:332 msgid "Tritanomaly" msgstr "Částečně bez modré" #: source/transformation/ColorVisionDeficiency.cpp:333 msgid "Protanopia" msgstr "Bez červené" #: source/transformation/ColorVisionDeficiency.cpp:334 msgid "Deuteranopia" msgstr "Bez zelené" #: source/transformation/ColorVisionDeficiency.cpp:335 msgid "Tritanopia" msgstr "Bez modré" #: source/transformation/ColorVisionDeficiency.cpp:422 msgid "Altered spectral sensitivity of red receptors" msgstr "" "Změněná spektrální citlivost čidel červené barvy. Částečná barvoslepost pro " "červenou barvu" #: source/transformation/ColorVisionDeficiency.cpp:423 msgid "Altered spectral sensitivity of green receptors" msgstr "" "Změněná spektrální citlivost čidel zelené barvy. Částečná barvoslepost pro " "zelenou barvu" #: source/transformation/ColorVisionDeficiency.cpp:424 msgid "Altered spectral sensitivity of blue receptors" msgstr "" "Změněná spektrální citlivost čidel modré barvy. Částečná barvoslepost pro " "modrou barvu" #: source/transformation/ColorVisionDeficiency.cpp:425 msgid "Absence of red receptors" msgstr "Nepřítomnost čidel červené barvy. Barvoslepost na červenou barvu" #: source/transformation/ColorVisionDeficiency.cpp:426 msgid "Absence of green receptors" msgstr "Nepřítomnost čidel zelené barvy. Barvoslepost na zelenou barvu" #: source/transformation/ColorVisionDeficiency.cpp:427 msgid "Absence of blue receptors" msgstr "Nepřítomnost čidel modré barvy. Barvoslepost na modrou barvu" #: source/transformation/GammaModification.cpp:38 msgid "Gamma modification" msgstr "Pozměnění gamy" #: source/transformation/GammaModification.cpp:88 #: source/transformation/Quantization.cpp:96 msgid "Value:" msgstr "Hodnota:" #: source/transformation/Quantization.cpp:40 msgid "Quantization" msgstr "Kvantizace" #: source/transformation/Quantization.cpp:101 msgid "Clip top-end" msgstr "Oříznout horní okraj" #: share/gpick/init.lua:173 msgid "Web: hex code" msgstr "Web: šestnáctkový kód" #: share/gpick/init.lua:178 msgid "Web: hex code (3 digits)" msgstr "Web: šestnáctkový kód (3 číslice)" #: share/gpick/init.lua:183 msgid "Web: hex code (no hash symbol)" msgstr "Web: šestnáctkový kód (žádný hash symbol)" #: share/gpick/init.lua:188 msgid "CSS: hue saturation lightness" msgstr "CSS: odstín sytost světlost" #: share/gpick/init.lua:193 msgid "CSS: red green blue" msgstr "CSS: červená zelená modrá" #: share/gpick/layouts.lua:15 msgid "Homepage" msgstr "Stránky projektu" #: share/gpick/layouts.lua:15 msgid "About us" msgstr "O nás" #: share/gpick/layouts.lua:15 msgid "Links to us" msgstr "Odkazy" #: share/gpick/layouts.lua:15 msgid "Privacy" msgstr "Soukromí" #: share/gpick/layouts.lua:15 msgid "Terms" msgstr "Podmínky" #: share/gpick/layouts.lua:15 msgid "Contact us" msgstr "Spojení" #: share/gpick/layouts.lua:15 msgid "RSS" msgstr "RSS" #: share/gpick/layouts.lua:30 msgid "The quick brown fox jumps over the lazy dog" msgstr "" "Maličká včelka vydávala při letu nad svazenkovým polem bzučivé " "tóny. My také zpíváme a toužíme po krásně chutnajícím medu." #: share/gpick/layouts.lua:46 msgid "Webpage" msgstr "Stránky" #: share/gpick/layouts.lua:51 share/gpick/layouts.lua:73 msgid "Header" msgstr "Záhlaví" #: share/gpick/layouts.lua:52 msgid "Header text" msgstr "Text záhlaví" #: share/gpick/layouts.lua:54 msgid "Content" msgstr "Obsah" #: share/gpick/layouts.lua:55 msgid "Content text" msgstr "Text obsahu" #: share/gpick/layouts.lua:57 msgid "Sidebar" msgstr "Postranní panel" #: share/gpick/layouts.lua:59 share/gpick/layouts.lua:87 msgid "Button" msgstr "Tlačítko" #: share/gpick/layouts.lua:60 share/gpick/layouts.lua:88 msgid "Button (hover)" msgstr "Tlačítko (přejetí)" #: share/gpick/layouts.lua:61 share/gpick/layouts.lua:89 msgid "Button text" msgstr "Text tlačítka" #: share/gpick/layouts.lua:62 share/gpick/layouts.lua:90 msgid "Button text (hover)" msgstr "Text tlačítka (přejetí)" #: share/gpick/layouts.lua:64 msgid "Footer" msgstr "Zápatí" #: share/gpick/layouts.lua:82 share/gpick/layouts.lua:86 msgid "Menu" msgstr "Nabídka" #: share/gpick/layouts.lua:106 msgid "Brightness-Darkness" msgstr "Jas - Tma" #: share/gpick/layouts.lua:110 msgid "main" msgstr "Hlavní" #: share/gpick/layouts.lua:144 msgid "Grid (4x3)" msgstr "Mřížka (4x3)" #: share/gpick/layouts.lua:153 share/gpick/layouts.lua:159 #: share/gpick/layouts.lua:180 share/gpick/layouts.lua:186 msgid "Item" msgstr "Položka" #: share/gpick/layouts.lua:154 share/gpick/layouts.lua:181 msgid "Item text" msgstr "Text položky" #: share/gpick/layouts.lua:171 msgid "Grid (5x4)" msgstr "Mřížka (5x4)" #~ msgid "Edit _Transformations..." #~ msgstr "Editar _Transformaciones..." gpick-gpick-0.2.6rc1/share/locale/es/000077500000000000000000000000001315430016700172655ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/locale/es/LC_MESSAGES/000077500000000000000000000000001315430016700210525ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/locale/es/LC_MESSAGES/gpick.po000066400000000000000000000671231315430016700225200ustar00rootroot00000000000000msgid "" msgstr "" "Project-Id-Version: gpick 0.2.5rc1\n" "POT-Creation-Date: 2013-01-05 16:16+0200\n" "PO-Revision-Date: 2013-01-06 17:59-0300\n" "Last-Translator: Guillermo Espertino \n" "Language-Team: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: source/BlendColors.cpp:114 source/BlendColors.cpp:116 msgid "blend node" msgstr "nodo de mezcla" #: source/BlendColors.cpp:119 msgid "blend" msgstr "mezcla" #: source/BlendColors.cpp:308 source/BrightnessDarkness.cpp:260 #: source/ColorMixer.cpp:321 source/ColorPicker.cpp:367 #: source/GenerateScheme.cpp:444 source/LayoutPreview.cpp:405 #: source/Variations.cpp:331 source/uiDialogOptions.cpp:215 #: source/uiDialogOptions.cpp:234 msgid "_Add to palette" msgstr "_Agregar a la paleta" #: source/BlendColors.cpp:314 source/BrightnessDarkness.cpp:265 #: source/ColorMixer.cpp:326 source/ColorPicker.cpp:371 #: source/GenerateScheme.cpp:449 source/LayoutPreview.cpp:410 #: source/Variations.cpp:336 msgid "A_dd all to palette" msgstr "Agregar to_do a la paleta" #: source/BlendColors.cpp:320 source/BrightnessDarkness.cpp:271 #: source/ColorMixer.cpp:333 source/ColorPicker.cpp:377 #: source/GenerateScheme.cpp:456 source/LayoutPreview.cpp:416 #: source/Variations.cpp:343 source/uiDialogOptions.cpp:220 #: source/uiDialogOptions.cpp:239 msgid "_Copy to clipboard" msgstr "_Copiar al portapapeles" #: source/BlendColors.cpp:374 source/GenerateScheme.cpp:485 msgid "_Reset" msgstr "_Reestablecer" #: source/BlendColors.cpp:517 msgid "Start:" msgstr "Inicio:" #: source/BlendColors.cpp:533 msgid "Middle:" msgstr "Medio:" #: source/BlendColors.cpp:551 msgid "End:" msgstr "Final:" #: source/BlendColors.cpp:568 source/GenerateScheme.cpp:875 #: source/uiDialogGenerate.cpp:237 source/uiDialogMix.cpp:249 #: source/transformation/ColorVisionDeficiency.cpp:363 msgid "Type:" msgstr "Tipo:" #: source/BlendColors.cpp:570 source/ColorWheelType.cpp:56 #: source/uiDialogMix.cpp:251 msgid "RGB" msgstr "RGB" #: source/BlendColors.cpp:571 source/uiDialogMix.cpp:252 msgid "HSV" msgstr "HSV" #: source/BlendColors.cpp:572 source/uiDialogMix.cpp:253 msgid "HSV shortest hue distance" msgstr "HSV distancia de matiz más corta" #: source/BlendColors.cpp:573 source/uiDialogMix.cpp:254 msgid "LAB" msgstr "LAB" #: source/BlendColors.cpp:582 msgid "Start steps:" msgstr "Pasos al inicio:" #: source/BlendColors.cpp:590 msgid "End steps:" msgstr "Pasos al final:" #: source/BlendColors.cpp:627 msgid "Blend colors" msgstr "Mezclar colores" #: source/BrightnessDarkness.cpp:86 msgid "brightness darkness" msgstr "brillo oscuridad" #: source/BrightnessDarkness.cpp:287 source/ColorMixer.cpp:373 #: source/ColorPicker.cpp:387 source/GenerateScheme.cpp:469 #: source/LayoutPreview.cpp:430 source/Variations.cpp:383 msgid "_Edit..." msgstr "_Editar..." #: source/BrightnessDarkness.cpp:292 source/ColorMixer.cpp:378 #: source/ColorPicker.cpp:391 source/GenerateScheme.cpp:474 #: source/LayoutPreview.cpp:435 source/Variations.cpp:388 msgid "_Paste" msgstr "_Pegar" #: source/BrightnessDarkness.cpp:385 msgid "Brightness" msgstr "Brillo" #: source/BrightnessDarkness.cpp:385 msgid "Darkness" msgstr "Oscuridad" #: source/BrightnessDarkness.cpp:431 msgid "Brightness Darkness" msgstr "Brillo - Oscuridad" #: source/ColorMixer.cpp:66 msgid "Normal" msgstr "Normal" #: source/ColorMixer.cpp:67 msgid "Multiply" msgstr "Multiplicar" #: source/ColorMixer.cpp:68 msgid "Add" msgstr "Suma" #: source/ColorMixer.cpp:69 msgid "Difference" msgstr "Diferencia" #: source/ColorMixer.cpp:70 source/ColorPicker.cpp:1180 #: source/ColorPicker.cpp:1194 source/ColorSpaceType.cpp:30 #: source/ColorSpaceType.cpp:37 source/Variations.cpp:66 msgid "Hue" msgstr "Matiz" #: source/ColorMixer.cpp:71 source/ColorPicker.cpp:1180 #: source/ColorPicker.cpp:1194 source/ColorSpaceType.cpp:31 #: source/ColorSpaceType.cpp:38 source/Variations.cpp:67 msgid "Saturation" msgstr "Saturación" #: source/ColorMixer.cpp:72 source/ColorPicker.cpp:1194 #: source/ColorPicker.cpp:1236 source/ColorPicker.cpp:1250 #: source/ColorSpaceType.cpp:39 source/ColorSpaceType.cpp:59 #: source/ColorSpaceType.cpp:66 source/Variations.cpp:68 msgid "Lightness" msgstr "Luminosidad" #: source/ColorMixer.cpp:114 msgid "color mixer" msgstr "mezclador de colores" #: source/ColorMixer.cpp:234 #, fuzzy msgid "secondary" msgstr "Vista _Secundaria" #: source/ColorMixer.cpp:238 source/Variations.cpp:229 #, c-format msgid "primary %d" msgstr "" #: source/ColorMixer.cpp:244 #, c-format msgid "result %d" msgstr "" #: source/ColorMixer.cpp:704 msgid "Opacity:" msgstr "Opacidad:" #: source/ColorMixer.cpp:732 msgid "Color mixer" msgstr "Mezclador de colores" #: source/ColorPicker.cpp:424 msgid "Press Spacebar to sample color under mouse pointer" msgstr "Presione Espacio para capturar el color debajo del puntero" #: source/ColorPicker.cpp:699 source/uiConverter.cpp:163 msgid "Copy" msgstr "Copiar" #: source/ColorPicker.cpp:703 source/uiConverter.cpp:172 msgid "Paste" msgstr "Pegar" #: source/ColorPicker.cpp:709 source/uiColorInput.cpp:119 msgid "Edit" msgstr "Editar" #: source/ColorPicker.cpp:771 source/uiApp.cpp:1012 #: source/uiDialogSort.cpp:222 msgid "None" msgstr "Ninguna" #: source/ColorPicker.cpp:772 msgid "Linear" msgstr "Lineal" #: source/ColorPicker.cpp:773 msgid "Quadratic" msgstr "Cuadrática" #: source/ColorPicker.cpp:774 msgid "Cubic" msgstr "Cúbica" #: source/ColorPicker.cpp:775 msgid "Exponential" msgstr "Exponencial" #: source/ColorPicker.cpp:951 msgid "Click on swatch area to begin adding colors to palette" msgstr "" "Haga click sobre el área de muestras para empezar a agregar colores a la " "paleta" #: source/ColorPicker.cpp:1143 msgid "Settings" msgstr "Ajustes" #: source/ColorPicker.cpp:1153 msgid "Oversample:" msgstr "Sobremuestreo:" #: source/ColorPicker.cpp:1160 msgid "Falloff:" msgstr "Atenuación:" #: source/ColorPicker.cpp:1167 msgid "Zoom:" msgstr "Ampliación:" #: source/ColorPicker.cpp:1180 source/ColorSpaceType.cpp:32 msgid "Value" msgstr "Valor" #: source/ColorPicker.cpp:1208 source/ColorSpaceType.cpp:44 msgid "Red" msgstr "Rojo" #: source/ColorPicker.cpp:1208 source/ColorSpaceType.cpp:45 msgid "Green" msgstr "Verde" #: source/ColorPicker.cpp:1208 source/ColorSpaceType.cpp:46 msgid "Blue" msgstr "Azul" #: source/ColorPicker.cpp:1222 source/ColorSpaceType.cpp:51 msgid "Cyan" msgstr "Cián" #: source/ColorPicker.cpp:1222 source/ColorSpaceType.cpp:52 msgid "Magenta" msgstr "Magenta" #: source/ColorPicker.cpp:1222 source/ColorSpaceType.cpp:53 msgid "Yellow" msgstr "Amarillo" #: source/ColorPicker.cpp:1222 source/ColorSpaceType.cpp:54 msgid "Key" msgstr "Negro (key)" #: source/ColorPicker.cpp:1258 msgid "Info" msgstr "Información" #: source/ColorPicker.cpp:1267 msgid "Color name:" msgstr "Nombre del color:" #: source/ColorPicker.cpp:1280 msgid "Contrast:" msgstr "Contraste:" #: source/ColorPicker.cpp:1285 source/ColorPicker.cpp:1291 msgid "Sample" msgstr "Muestra" #: source/ColorPicker.cpp:1324 msgid "Color picker" msgstr "Selector de color" #: source/ColorWheelType.cpp:57 msgid "RYB v1" msgstr "RYB v1" #: source/ColorWheelType.cpp:58 msgid "RYB v2" msgstr "RYB v2" #: source/GenerateScheme.cpp:90 msgid "Complementary" msgstr "Complementarios" #: source/GenerateScheme.cpp:91 msgid "Analogous" msgstr "Análogos" #: source/GenerateScheme.cpp:92 msgid "Triadic" msgstr "Tríada" #: source/GenerateScheme.cpp:93 msgid "Split-Complementary" msgstr "Complementarios divididos" #: source/GenerateScheme.cpp:94 msgid "Rectangle (tetradic)" msgstr "Rectangular (Tétrada)" #: source/GenerateScheme.cpp:95 msgid "Square" msgstr "Cuadrado" #: source/GenerateScheme.cpp:96 msgid "Neutral" msgstr "Neutros" #: source/GenerateScheme.cpp:97 msgid "Clash" msgstr "Complementarios en tensión" #: source/GenerateScheme.cpp:98 msgid "Five-Tone" msgstr "Cinco Tonos" #: source/GenerateScheme.cpp:99 msgid "Six-Tone" msgstr "Seis Tonos" #: source/GenerateScheme.cpp:119 source/uiDialogGenerate.cpp:76 msgid "scheme" msgstr "armonía" #: source/GenerateScheme.cpp:292 msgid "_Locked" msgstr "_Bloqueado" #: source/GenerateScheme.cpp:299 msgid "_Reset scheme" msgstr "_Reestablecer armonía" #: source/GenerateScheme.cpp:851 msgid "Hue:" msgstr "Matiz:" #: source/GenerateScheme.cpp:858 source/uiDialogVariations.cpp:171 msgid "Saturation:" msgstr "Saturación:" #: source/GenerateScheme.cpp:866 source/uiDialogVariations.cpp:156 msgid "Lightness:" msgstr "Luminosidad:" #: source/GenerateScheme.cpp:885 source/uiDialogGenerate.cpp:246 msgid "Color wheel:" msgstr "Rueda de color:" #: source/GenerateScheme.cpp:919 msgid "Scheme generation" msgstr "Generación de armonías" #: source/LayoutPreview.cpp:78 msgid "layout preview" msgstr "vista previa de diseño" #: source/LayoutPreview.cpp:153 msgid "Style item" msgstr "Ítem de estilo" #: source/LayoutPreview.cpp:162 msgid "CSS selector" msgstr "Selector CSS" #: source/LayoutPreview.cpp:184 msgid "Assign CSS selectors" msgstr "Asignar selectores CSS" #: source/LayoutPreview.cpp:547 source/LayoutPreview.cpp:595 #: source/uiApp.cpp:690 source/uiApp.cpp:711 msgid "File could not be saved" msgstr "El archivo no pudo ser guardado" #: source/LayoutPreview.cpp:558 source/uiExport.cpp:457 #: source/uiExport.cpp:523 msgid "Export" msgstr "Exportar" #: source/LayoutPreview.cpp:572 msgid "Cascading Style Sheets *.css" msgstr "Hojas de Estilos en Cascada *.css" #: source/LayoutPreview.cpp:666 msgid "Layout:" msgstr "Diseño:" #: source/LayoutPreview.cpp:672 msgid "Export CSS File" msgstr "Exportar Archivo CSS" #: source/LayoutPreview.cpp:673 msgid "Export CSS file" msgstr "Exportar archivo CSS" #: source/LayoutPreview.cpp:682 msgid "_Export CSS File As..." msgstr "_Exportar archivo CSS como..." #: source/LayoutPreview.cpp:686 msgid "_Assign CSS Selectors..." msgstr "_Asignar selectores CSS..." #: source/LayoutPreview.cpp:759 msgid "Layout preview" msgstr "Vista previa de diseño" #: source/ToolColorNaming.cpp:25 msgid "_Empty" msgstr "Ninguno" #: source/ToolColorNaming.cpp:26 msgid "_Automatic name" msgstr "Nombre _automático" #: source/ToolColorNaming.cpp:27 msgid "_Tool specific" msgstr "Específico de la herramien_ta" #: source/Variations.cpp:69 msgid "Lightness (Lab)" msgstr "Luminosidad (Lab)" #: source/Variations.cpp:110 msgid "variations" msgstr "variaciones" #: source/Variations.cpp:225 #, fuzzy msgid "all colors" msgstr "Mezclar colores" #: source/Variations.cpp:239 #, c-format msgid "result %d line %d" msgstr "" #: source/Variations.cpp:717 #: source/transformation/ColorVisionDeficiency.cpp:386 msgid "Strength:" msgstr "Intensidad:" #: source/Variations.cpp:745 source/uiDialogVariations.cpp:142 msgid "Variations" msgstr "Variaciones" #: source/uiAbout.cpp:88 msgid "About Gpick" msgstr "Acerca de Gpick" #: source/uiAbout.cpp:121 msgid "Advanced color picker" msgstr "Selector de color avanzado" #: source/uiAbout.cpp:126 msgid "Copyrights © 2009-2013, Albertas Vyšniauskas and Gpick development team" msgstr "" "Copyrights © 2009-2013, Albertas Vyšniauskas y el equipo de desarrollo de " "Gpick" #: source/uiAbout.cpp:141 msgid "License" msgstr "Licencia" #: source/uiAbout.cpp:142 msgid "Credits" msgstr "Créditos" #: source/uiAbout.cpp:143 msgid "Expat License" msgstr "Licencia Expat" #: source/uiAbout.cpp:144 msgid "Lua License" msgstr "Licencia Lua" #: source/uiApp.cpp:354 msgid "New palette" msgstr "Nueva paleta" #: source/uiApp.cpp:360 msgid "(Imported)" msgstr "(Importado)" #: source/uiApp.cpp:530 source/uiApp.cpp:545 source/uiApp.cpp:563 #: source/uiApp.cpp:641 msgid "File could not be opened" msgstr "El archivo no pudo ser abierto" #: source/uiApp.cpp:531 source/uiApp.cpp:546 source/uiApp.cpp:564 #: source/uiApp.cpp:642 msgid "Open" msgstr "Abrir" #: source/uiApp.cpp:576 source/uiExport.cpp:473 source/uiExport.cpp:587 msgid "Gpick Palette (*.gpa)" msgstr "Paleta de Gpick (*.gpa)" #: source/uiApp.cpp:577 source/uiExport.cpp:474 source/uiExport.cpp:588 msgid "GIMP/Inkscape Palette (*.gpl)" msgstr "Paleta de GIMP/Inkscape (*.gpl)" #: source/uiApp.cpp:578 source/uiExport.cpp:476 source/uiExport.cpp:589 msgid "Adobe Swatch Exchange (*.ase)" msgstr "Adobe Swatch Exchange (*.ase)" #: source/uiApp.cpp:584 source/uiExport.cpp:598 #: source/tools/PaletteFromImage.cpp:548 msgid "All files" msgstr "Todos los archivos" #: source/uiApp.cpp:589 source/uiExport.cpp:607 msgid "All supported formats" msgstr "Todos los formatos soportados" #: source/uiApp.cpp:610 msgid "Open File" msgstr "Abrir archivo" #: source/uiApp.cpp:659 source/uiApp.cpp:691 msgid "Save As" msgstr "Guardar como" #: source/uiApp.cpp:712 msgid "Save" msgstr "Guardar" #: source/uiApp.cpp:771 msgid "Open Last File" msgstr "Abrir el último archivo" #: source/uiApp.cpp:916 msgid "Recent _files" msgstr "Archivos _Recientes" #: source/uiApp.cpp:946 msgid "Ex_port..." msgstr "E_xportar..." #: source/uiApp.cpp:954 msgid "Expo_rt Selected..." msgstr "Ex_portar Seleccionados..." #: source/uiApp.cpp:962 msgid "_Import..." msgstr "_Importar..." #: source/uiApp.cpp:977 msgid "_File" msgstr "_Archivo" #: source/uiApp.cpp:985 msgid "Edit _Converters..." msgstr "Editar _Convertidores..." #: source/uiApp.cpp:989 msgid "Display _Filters..." msgstr "Mostrar _Filtros" #: source/uiApp.cpp:1001 msgid "_Edit" msgstr "_Editar" #: source/uiApp.cpp:1037 msgid "_Secondary View" msgstr "Vista _Secundaria" #: source/uiApp.cpp:1043 msgid "Palette" msgstr "Paleta" #: source/uiApp.cpp:1049 msgid "_View" msgstr "_Vista" #: source/uiApp.cpp:1055 msgid "Palette From _Image..." msgstr "Paleta desde _Imagen..." #: source/uiApp.cpp:1063 msgid "_Tools" msgstr "_Herramientas" #: source/uiApp.cpp:1078 msgid "_Help" msgstr "A_yuda" #: source/uiApp.cpp:1386 msgid "_Copy to Clipboard" msgstr "_Copiar al Portapapeles" #: source/uiApp.cpp:1402 msgid "_Mix Colors..." msgstr "_Mezclar Colores..." #: source/uiApp.cpp:1407 msgid "_Variations..." msgstr "_Variaciones..." #: source/uiApp.cpp:1412 msgid "_Generate..." msgstr "_Generar..." #: source/uiApp.cpp:1421 msgid "C_lear names" msgstr "_Limpiar nombres" #: source/uiApp.cpp:1427 msgid "Autona_me" msgstr "No_mbre automático" #: source/uiApp.cpp:1433 msgid "Auto_number..." msgstr "_Numerado automático" #: source/uiApp.cpp:1441 msgid "R_everse" msgstr "_Reverso" #: source/uiApp.cpp:1447 msgid "Group and _sort..." msgstr "Agrupar y ordenar" #: source/uiApp.cpp:1455 msgid "_Remove" msgstr "_Quitar" #: source/uiApp.cpp:1461 msgid "Remove _All" msgstr "Quitar _Todo" #: source/uiApp.cpp:1869 msgid "Color pic_ker" msgstr "Selector de _Color" #: source/uiApp.cpp:1878 msgid "Scheme _generation" msgstr "_Generación de armonías" #: source/uiApp.cpp:1897 msgid "Lay_out preview" msgstr "Vista previa de diseñ_o" #: source/uiApp.cpp:1947 msgid "Pick colors (Ctrl+P)" msgstr "Elegir color (CTRL+P)" #: source/uiApp.cpp:1956 msgid "" "File is currently in a non-native format, possible loss of precision and/or " "metadata." msgstr "" "El archivo está actualmente en un formato no-nativo, posible pérdida de " "precisión y/o metadatos." #: source/uiColorInput.cpp:45 msgid "Edit color" msgstr "Editar color" #: source/uiColorInput.cpp:69 msgid "Color:" msgstr "Color:" #: source/uiConverter.cpp:56 msgid "Test color" msgstr "Probar color" #: source/uiConverter.cpp:74 msgid "error" msgstr "error" #: source/uiConverter.cpp:145 msgid "Function name" msgstr "Nombre de la función" #: source/uiConverter.cpp:154 msgid "Example" msgstr "Ejemplo" #: source/uiConverter.cpp:196 msgid "Converters" msgstr "Convertidores" #: source/uiConverter.cpp:224 msgid "Displays:" msgstr "Visualizaciones:" #: source/uiConverter.cpp:230 msgid "Color list:" msgstr "Lista de colores:" #: source/uiDialogAutonumber.cpp:108 msgid "Autonumber colors" msgstr "Autonumerar colores" #: source/uiDialogAutonumber.cpp:122 msgid "Name:" msgstr "Nombre:" #: source/uiDialogAutonumber.cpp:132 msgid "Decimal places:" msgstr "Lugares decimales:" #: source/uiDialogAutonumber.cpp:139 msgid "Starting number:" msgstr "Número inicial:" #: source/uiDialogAutonumber.cpp:146 msgid "_Decreasing" msgstr "_Decreciente" #: source/uiDialogAutonumber.cpp:152 msgid "_Append" msgstr "_Agregar" #: source/uiDialogAutonumber.cpp:158 msgid "Sample:" msgstr "Muestra:" #: source/uiDialogGenerate.cpp:216 msgid "Generate colors" msgstr "Generar colores" #: source/uiDialogGenerate.cpp:230 source/tools/PaletteFromImage.cpp:599 msgid "Colors:" msgstr "Colores:" #: source/uiDialogGenerate.cpp:257 msgid "Chaos:" msgstr "Caos:" #: source/uiDialogGenerate.cpp:263 msgid "Seed:" msgstr "Semilla:" #: source/uiDialogGenerate.cpp:271 msgid "_Reverse" msgstr "_Reverso" #: source/uiDialogMix.cpp:76 source/uiDialogMix.cpp:78 msgid "mix node" msgstr "nodo de mezcla" #: source/uiDialogMix.cpp:81 msgid "mix" msgstr "mezcla" #: source/uiDialogMix.cpp:235 msgid "Mix colors" msgstr "Mezclar colores" #: source/uiDialogMix.cpp:262 source/uiDialogVariations.cpp:186 msgid "Steps:" msgstr "Pasos:" #: source/uiDialogMix.cpp:270 msgid "_Include Endpoints" msgstr "_incluir extremos" #: source/uiDialogOptions.cpp:117 source/tools/PaletteFromImage.cpp:589 msgid "Options" msgstr "Opciones" #: source/uiDialogOptions.cpp:134 msgid "System" msgstr "Sistema" #: source/uiDialogOptions.cpp:143 msgid "_Single instance" msgstr "In_stancia única" #: source/uiDialogOptions.cpp:148 msgid "Save/_Restore palette" msgstr "Guardar/_Reestablecer paleta" #: source/uiDialogOptions.cpp:154 msgid "System tray" msgstr "Bandeja de sistema" #: source/uiDialogOptions.cpp:162 msgid "_Minimize to system tray" msgstr "_Minimizar a la bandeja de sistema" #: source/uiDialogOptions.cpp:167 msgid "_Close to system tray" msgstr "_Cerrar a la bandeja de sistema" #: source/uiDialogOptions.cpp:172 msgid "_Start in system tray" msgstr "Iniciar en la bandeja de _sistema" #: source/uiDialogOptions.cpp:178 msgid "_Main" msgstr "_Principal" #: source/uiDialogOptions.cpp:184 msgid "Display" msgstr "Visualización" #: source/uiDialogOptions.cpp:193 msgid "_Refresh rate:" msgstr "Tasa de _refresco:" #: source/uiDialogOptions.cpp:201 msgid "_Magnified area size:" msgstr "Tamaño del área _magnificada:" #: source/uiDialogOptions.cpp:207 msgid "Floating picker click behaviour" msgstr "Comportamiento del selector flotante" #: source/uiDialogOptions.cpp:226 msgid "'Spacebar' button behaviour" msgstr "Comportamiento de la barra espaciadora" #: source/uiDialogOptions.cpp:244 msgid "_Rotate swatch" msgstr "_Rotar muestras" #: source/uiDialogOptions.cpp:251 msgid "Enabled color spaces" msgstr "Espacios de color habilitados" #: source/uiDialogOptions.cpp:266 msgid "Lab settings" msgstr "Ajustes Lab" #: source/uiDialogOptions.cpp:278 msgid "_Illuminant:" msgstr "_Iluminante" #: source/uiDialogOptions.cpp:302 msgid "_Observer:" msgstr "_Observador" #: source/uiDialogOptions.cpp:321 msgid "Other settings" msgstr "Otros ajustes" #: source/uiDialogOptions.cpp:330 msgid "_Mask out of gamut colors" msgstr "En_mascarar colores fuera de gamut" #: source/uiDialogOptions.cpp:336 msgid "_Picker" msgstr "_Selector" #: source/uiDialogOptions.cpp:341 msgid "Color name generation" msgstr "Generación de nombres de color" #: source/uiDialogOptions.cpp:350 msgid "_Imprecision postfix" msgstr "Sufijo de _impresición" #: source/uiDialogOptions.cpp:356 msgid "Tool color naming" msgstr "Asignación de nombres de color" #: source/uiDialogOptions.cpp:381 msgid "_Color names" msgstr "Nombre del _color" #: source/uiDialogSort.cpp:135 source/uiDialogSort.cpp:223 msgid "RGB Red" msgstr "Rojo RGB" #: source/uiDialogSort.cpp:136 source/uiDialogSort.cpp:224 msgid "RGB Green" msgstr "Verde RGB" #: source/uiDialogSort.cpp:137 source/uiDialogSort.cpp:225 msgid "RGB Blue" msgstr "Azul RGB" #: source/uiDialogSort.cpp:138 source/uiDialogSort.cpp:226 msgid "RGB Grayscale" msgstr "Escala de grises RGB" #: source/uiDialogSort.cpp:139 source/uiDialogSort.cpp:227 msgid "HSL Hue" msgstr "Matiz HSL" #: source/uiDialogSort.cpp:140 source/uiDialogSort.cpp:228 msgid "HSL Saturation" msgstr "Saturación HSL" #: source/uiDialogSort.cpp:141 source/uiDialogSort.cpp:229 msgid "HSL Lightness" msgstr "Luminosidad HSL" #: source/uiDialogSort.cpp:142 source/uiDialogSort.cpp:230 msgid "Lab Lightness" msgstr "Luminosidad Lab" #: source/uiDialogSort.cpp:143 source/uiDialogSort.cpp:231 msgid "Lab A" msgstr "Lab A" #: source/uiDialogSort.cpp:144 source/uiDialogSort.cpp:232 msgid "Lab B" msgstr "Lab B" #: source/uiDialogSort.cpp:145 source/uiDialogSort.cpp:233 msgid "LCh Lightness" msgstr "Luminosidad LCh" #: source/uiDialogSort.cpp:146 source/uiDialogSort.cpp:234 msgid "LCh Chroma" msgstr "Crominancia LCh" #: source/uiDialogSort.cpp:147 source/uiDialogSort.cpp:235 msgid "LCh Hue" msgstr "Matiz LCh" #: source/uiDialogSort.cpp:556 msgid "Group and sort" msgstr "Agrupar y ordenar" #: source/uiDialogSort.cpp:564 msgid "Group type:" msgstr "Tipo de grupo:" #: source/uiDialogSort.cpp:574 msgid "Grouping sensitivity:" msgstr "Sensibilidad de agrupamiento:" #: source/uiDialogSort.cpp:581 msgid "Maximum number of groups:" msgstr "Número máximo de grupos:" #: source/uiDialogSort.cpp:588 msgid "Sort type:" msgstr "Tipo de ordenamiento:" #: source/uiDialogSort.cpp:598 msgid "_Reverse group order" msgstr "Orden de grupo inve_rso" #: source/uiDialogSort.cpp:604 msgid "_Reverse order inside groups" msgstr "Orden de grupo inve_rso dentro de grupos" #: source/uiDialogVariations.cpp:60 msgid "variation" msgstr "variación" #: source/uiDialogVariations.cpp:194 msgid "_Use multiplication" msgstr "_Usar multiplicación" #: source/uiExport.cpp:475 msgid "Alias/WaveFront Material (*.mtl)" msgstr "Material de Alias/WaveFront (*.mtl)" #: source/uiExport.cpp:477 msgid "Text file (*.txt)" msgstr "Archivo de texto (*.txt)" #: source/uiExport.cpp:522 msgid "File could not be exported" msgstr "El archivo no pudo ser exportado" #: source/uiExport.cpp:573 source/uiExport.cpp:654 source/uiExport.cpp:666 msgid "Import" msgstr "Importar" #: source/uiExport.cpp:653 msgid "File format is not supported" msgstr "El formato de archivo no está soportado" #: source/uiExport.cpp:665 msgid "File could not be imported" msgstr "El archivo no pudo ser importado" #: source/uiListPalette.cpp:158 source/uiListPalette.cpp:160 #, c-format msgid "%d color" msgid_plural "%d colors" msgstr[0] "%d color" msgstr[1] "%d colores" #: source/uiListPalette.cpp:166 msgid "selected" msgstr "seleccionado" #: source/uiListPalette.cpp:172 source/uiListPalette.cpp:174 #, c-format msgid "Total %d color" msgid_plural "Total %d colors" msgstr[0] "Total %d color" msgstr[1] "Total %d colores" #: source/uiListPalette.cpp:353 msgid "Preview" msgstr "Vista previa" #: source/uiListPalette.cpp:708 source/uiListPalette.cpp:717 msgid "Color" msgstr "Color" #: source/uiListPalette.cpp:726 source/uiTransformations.cpp:183 msgid "Name" msgstr "Nombre" #: source/uiStatusIcon.cpp:67 msgid "_Show Main Window" msgstr "Mo_strar Ventana Principal" #: source/uiStatusIcon.cpp:74 msgid "_Quit" msgstr "Salir" #: source/uiTransformations.cpp:245 msgid "Display filters" msgstr "Filtros de visualización" #: source/uiTransformations.cpp:259 msgid "_Enabled" msgstr "_Activado" #: source/tools/PaletteFromImage.cpp:514 msgid "Palette from image" msgstr "Paleta desde imagen" #: source/tools/PaletteFromImage.cpp:527 msgid "Image" msgstr "Imagen" #: source/tools/PaletteFromImage.cpp:536 msgid "Image file" msgstr "Archivo de imagen" #: source/tools/PaletteFromImage.cpp:556 msgid "All images" msgstr "Todas las imágenes" #: source/transformation/ColorVisionDeficiency.cpp:41 msgid "Color vision deficiency" msgstr "Visión de color deficiente" #: source/transformation/ColorVisionDeficiency.cpp:330 msgid "Protanomaly" msgstr "Protanomalía" #: source/transformation/ColorVisionDeficiency.cpp:331 msgid "Deuteranomaly" msgstr "Deuteranomalía" #: source/transformation/ColorVisionDeficiency.cpp:332 msgid "Tritanomaly" msgstr "Tritanomalía" #: source/transformation/ColorVisionDeficiency.cpp:333 msgid "Protanopia" msgstr "Protanopía" #: source/transformation/ColorVisionDeficiency.cpp:334 msgid "Deuteranopia" msgstr "Deuteranopía" #: source/transformation/ColorVisionDeficiency.cpp:335 msgid "Tritanopia" msgstr "Tritanopía" #: source/transformation/ColorVisionDeficiency.cpp:422 msgid "Altered spectral sensitivity of red receptors" msgstr "Sensibilidad espectral alterada en receptores de rojos" #: source/transformation/ColorVisionDeficiency.cpp:423 msgid "Altered spectral sensitivity of green receptors" msgstr "Sensibilidad espectral alterada en receptores de verdes" #: source/transformation/ColorVisionDeficiency.cpp:424 msgid "Altered spectral sensitivity of blue receptors" msgstr "Sensibilidad espectral alterada en receptores de azules" #: source/transformation/ColorVisionDeficiency.cpp:425 msgid "Absence of red receptors" msgstr "Ausencia de receptores de rojo" #: source/transformation/ColorVisionDeficiency.cpp:426 msgid "Absence of green receptors" msgstr "Ausencia de receptores de verde" #: source/transformation/ColorVisionDeficiency.cpp:427 msgid "Absence of blue receptors" msgstr "Ausencia de receptores de azul" #: source/transformation/GammaModification.cpp:38 msgid "Gamma modification" msgstr "Modificación de gamma" #: source/transformation/GammaModification.cpp:88 #: source/transformation/Quantization.cpp:96 msgid "Value:" msgstr "Valor:" #: source/transformation/Quantization.cpp:40 msgid "Quantization" msgstr "Cuantización" #: source/transformation/Quantization.cpp:101 msgid "Clip top-end" msgstr "Recortar límite superior" #: share/gpick/init.lua:173 msgid "Web: hex code" msgstr "" #: share/gpick/init.lua:178 msgid "Web: hex code (3 digits)" msgstr "" #: share/gpick/init.lua:183 msgid "Web: hex code (no hash symbol)" msgstr "" #: share/gpick/init.lua:188 msgid "CSS: hue saturation lightness" msgstr "" #: share/gpick/init.lua:193 msgid "CSS: red green blue" msgstr "" #: share/gpick/layouts.lua:15 msgid "Homepage" msgstr "" #: share/gpick/layouts.lua:15 #, fuzzy msgid "About us" msgstr "Acerca de Gpick" #: share/gpick/layouts.lua:15 msgid "Links to us" msgstr "" #: share/gpick/layouts.lua:15 msgid "Privacy" msgstr "" #: share/gpick/layouts.lua:15 msgid "Terms" msgstr "" #: share/gpick/layouts.lua:15 #, fuzzy msgid "Contact us" msgstr "Contraste:" #: share/gpick/layouts.lua:15 msgid "RSS" msgstr "" #: share/gpick/layouts.lua:30 msgid "The quick brown fox jumps over the lazy dog" msgstr "" #: share/gpick/layouts.lua:46 msgid "Webpage" msgstr "" #: share/gpick/layouts.lua:51 share/gpick/layouts.lua:73 msgid "Header" msgstr "" #: share/gpick/layouts.lua:52 msgid "Header text" msgstr "" #: share/gpick/layouts.lua:54 #, fuzzy msgid "Content" msgstr "Contraste:" #: share/gpick/layouts.lua:55 msgid "Content text" msgstr "" #: share/gpick/layouts.lua:57 msgid "Sidebar" msgstr "" #: share/gpick/layouts.lua:59 share/gpick/layouts.lua:87 msgid "Button" msgstr "" #: share/gpick/layouts.lua:60 share/gpick/layouts.lua:88 msgid "Button (hover)" msgstr "" #: share/gpick/layouts.lua:61 share/gpick/layouts.lua:89 msgid "Button text" msgstr "" #: share/gpick/layouts.lua:62 share/gpick/layouts.lua:90 msgid "Button text (hover)" msgstr "" #: share/gpick/layouts.lua:64 msgid "Footer" msgstr "" #: share/gpick/layouts.lua:82 share/gpick/layouts.lua:86 msgid "Menu" msgstr "" #: share/gpick/layouts.lua:106 #, fuzzy msgid "Brightness-Darkness" msgstr "Brillo - Oscuridad" #: share/gpick/layouts.lua:110 msgid "main" msgstr "" #: share/gpick/layouts.lua:144 msgid "Grid (4x3)" msgstr "" #: share/gpick/layouts.lua:153 share/gpick/layouts.lua:159 #: share/gpick/layouts.lua:180 share/gpick/layouts.lua:186 msgid "Item" msgstr "" #: share/gpick/layouts.lua:154 share/gpick/layouts.lua:181 msgid "Item text" msgstr "" #: share/gpick/layouts.lua:171 msgid "Grid (5x4)" msgstr "" #~ msgid "Edit _Transformations..." #~ msgstr "Editar _Transformaciones..." gpick-gpick-0.2.6rc1/share/locale/lt/000077500000000000000000000000001315430016700172755ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/locale/lt/LC_MESSAGES/000077500000000000000000000000001315430016700210625ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/locale/lt/LC_MESSAGES/gpick.po000066400000000000000000000443221315430016700225240ustar00rootroot00000000000000# msgid "" msgstr "" "Project-Id-Version: gpick 0.2.6\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2017-09-07 19:53+0300\n" "PO-Revision-Date: 2017-09-07 19:54+0300\n" "Last-Translator: Albertas Vyšniauskas \n" "Language-Team: \n" "Language: lt\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "X-Generator: Poedit 2.0.3\n" "X-Poedit-SourceCharset: UTF-8\n" "Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);\n" #, c-format msgid "%d color" msgid_plural "%d colors" msgstr[0] "%d spalva" msgstr[1] "%d spalvos" msgstr[2] "%d spalvų" msgid "'Spacebar' button behaviour" msgstr "'Tarpo' mygtuko elgsena" msgid "(Imported)" msgstr "(Importuotas)" msgid "A_dd all to palette" msgstr "Į_kelti visas į paletę" msgid "About Gpick" msgstr "Apie Gpick" msgid "About us" msgstr "Apie mus" msgid "Absence of blue receptors" msgstr "Mėlynų receptorių nebūvimas" msgid "Absence of green receptors" msgstr "Žalių receptorių nebūvimas" msgid "Absence of red receptors" msgstr "Raudonų receptorių nebūvimas" msgid "Active filters" msgstr "Aktyvūs filtrai" msgid "Add" msgstr "Sudėtis" msgid "Add color dictionary file" msgstr "Pridėti spalvų žodyną" msgid "Adobe Swatch Exchange (*.ase)" msgstr "Adobe Swatch Exchange (*.ase)" msgid "Advanced color picker" msgstr "Pažangi spalvų rinkyklė" msgid "Alias/WaveFront Material (*.mtl)" msgstr "Alias/WaveFront Material (*.mtl)" msgid "All files" msgstr "Visi failai" msgid "All images" msgstr "Visi paveikslėliai" msgid "All supported formats" msgstr "Visi palaikomi formatai" msgid "Altered spectral sensitivity of blue receptors" msgstr "Pakitęs mėlynų receptorių spektro jautrumas" msgid "Altered spectral sensitivity of green receptors" msgstr "Pakitęs žalių receptorių spektro jautrumas" msgid "Altered spectral sensitivity of red receptors" msgstr "Pakitęs raudonų receptorių spektro jautrumas" msgid "Analogous" msgstr "Analogiška" msgid "Assign CSS selectors" msgstr "Priskirti CSS selektorius" msgid "Auto_number..." msgstr "Auto. _numeracija..." msgid "Autona_me" msgstr "Auto. pavadinimai" msgid "Autonumber colors" msgstr "Sunumeruoti spalvas" msgid "Available filters" msgstr "Galimi filtrai" msgid "Background color" msgstr "Fono spalva" msgid "Background:" msgstr "Fonas:" msgid "Big" msgstr "Didelis" msgid "Black" msgstr "Juoda" msgid "Blend colors" msgstr "Sulieti spalvas" msgid "Blue" msgstr "Mėlyna" msgid "Brightness" msgstr "Šviesumas" msgid "Brightness Darkness" msgstr "Šviesumas, tamsumas" msgid "Brightness-Darkness" msgstr "Šviesumas-Tamsumas" msgid "Built in" msgstr "Integruotas" msgid "Button" msgstr "Mygtukas" msgid "Button (hover)" msgstr "Mygtukas (pažymėtas)" msgid "Button text" msgstr "Mygtuko tekstas" msgid "Button text (hover)" msgstr "Mygtuko tekstas (pažymėtas)" msgid "C style multi-line comments" msgstr "C stiliaus kelių eilučių komentarai" msgid "C style single-line comments" msgstr "C stiliaus vienos eilutės komentarai" msgid "CSS selector" msgstr "CSS selectorius" msgid "CSS: hue saturation lightness" msgstr "CSS: atspalvis įsotinimas šviesumas" msgid "CSS: red green blue" msgstr "CSS: raudona žalia mėlyna" msgid "C_lear names" msgstr "I_švalyti pavadinimus" msgid "Cascading Style Sheet (*.css)" msgstr "Cascading Style Sheets (*.css)" msgid "Cascading Style Sheets *.css" msgstr "Cascading Style Sheets *.css" msgid "Chaos:" msgstr "Chaosas:" msgid "Clash" msgstr "Nedarna" msgid "Click on swatch area to begin adding colors to palette" msgstr "Paspauskite mėginio plote norėdami pradėti spalvų rinkimą į paletę" msgid "Clip top-end" msgstr "Apkirpti viršutinę dalį" msgid "Closest colors" msgstr "Artimiausios spalvos" msgid "Color" msgstr "Spalva" msgid "Color Space _Sampler..." msgstr "Spalvų Erdvės _Rinkyklė..." msgid "Color _Dictionaries..." msgstr "_Spalvų Žodynai..." msgid "Color dictionaries" msgstr "_Spalvų žodynai" msgid "Color dictionary file" msgstr "Spalvų žodynas" msgid "Color list:" msgstr "Spalvų sąrašas::" msgid "Color mixer" msgstr "Spalvų maišyklė" msgid "Color name generation" msgstr "Spalvų pavadinimų generavimas" msgid "Color name:" msgstr "Spalvos pavadinimas:" msgid "Color pic_ker" msgstr "Spalvų rin_kyklė" msgid "Color picker" msgstr "Spalvų rinkyklė" msgid "Color space sampler" msgstr "Spalvų erdvės rinkyklė" msgid "Color space:" msgstr "Spalvų erdvė:" msgid "Color vision deficiency" msgstr "Spalvų matymo defektai" msgid "Color wheel:" msgstr "Spalvų ratas:" msgid "Color:" msgstr "Spalva:" msgid "Colors:" msgstr "Spalvos:" msgid "Complementary" msgstr "Papildanti" msgid "Contact us" msgstr "Kontaktai" msgid "Content" msgstr "Turinys" msgid "Content text" msgstr "Turinio tekstas" msgid "Contrast:" msgstr "Kontrastas:" msgid "Converter:" msgstr "Keitėjas:" msgid "Converters" msgstr "Keitėjai" msgid "Cop_y" msgstr "_Kopijuoti" msgid "Copy" msgstr "Kopijavimas" msgid "Copyright © 2009-2016, Albertas Vyšniauskas and Gpick development team" msgstr "Autorinės teisės priklauso © 2009-2016, Albertui Vyšniauskui ir Gpick kūrimo komandai" msgid "Credits" msgstr "Padėkos" msgid "Cubic" msgstr "Kubinis" msgid "Cyan" msgstr "Žydra" msgid "Darkness" msgstr "Tamsumas" msgid "Decimal places:" msgstr "Skaitmenys:" msgid "Default drag action" msgstr "Numatytas pertempimo veiksmas" msgid "Deuteranomaly" msgstr "Deuteranomalija" msgid "Deuteranopia" msgstr "Deuteranopija" msgid "Difference" msgstr "Skirtumas" msgid "Display" msgstr "Rodymas" msgid "Display _Filters..." msgstr "Rodymo _Filtrai..." msgid "Display filters" msgstr "Rodymo filtrai" msgid "Displays:" msgstr "Rodymas:" msgid "Edit" msgstr "Keisti" msgid "Edit _Converters..." msgstr "Keisti _keitėjus..." msgid "Edit color" msgstr "Keisti spalvą" msgid "Enable" msgstr "Įjungti" msgid "Enabled color spaces" msgstr "Aktyvios spalvų erdvės" msgid "End steps:" msgstr "Pabaigos žingsniai:" msgid "End:" msgstr "Pabaiga:" msgid "Ex_port..." msgstr "Eksportuoti..." msgid "Example" msgstr "Pavyzdys" msgid "Expat License" msgstr "Expat licencija" msgid "Expo_rt Selected..." msgstr "Eksportuoti _pažymėtas..." msgid "Exponential" msgstr "Eksponentinis" msgid "Export" msgstr "Eksportuoti" msgid "Export CSS File" msgstr "Eksportuoti CSS failą" msgid "Export CSS file" msgstr "Eksportuoti CSS failą" msgid "Falloff:" msgstr "Nuožulnumas:" msgid "File could not be exported" msgstr "Nepavyko eksportuoti failą" msgid "File could not be imported" msgstr "Nepavyko importuoti failą" msgid "File could not be opened" msgstr "Nepavyko atidaryti failo" msgid "File could not be saved" msgstr "Nepavyko išsaugoti failą" msgid "File format is not supported" msgstr "Failo formatas nėra palaikomas" msgid "File is currently in a non-native format, possible loss of precision and/or metadata." msgstr "Šiuo metu failas išsaugotas ne pagrindiniu formatu, galimas tikslumo ir/ar metaduomenų praradimas." msgid "First color" msgstr "Pirma spalva" msgid "Five-Tone" msgstr "Penki tonai" msgid "Floating picker click behaviour" msgstr "Slankaus rinkėjo elgsena" msgid "Footer" msgstr "Paraštė" msgid "Full hex" msgstr "Pilnas šešioliktainis" msgid "Function name" msgstr "Funkcijos pavadinimas" msgid "GIMP/Inkscape Palette (*.gpl)" msgstr "GIMP/Inkscape paletė (*.gpl)" msgid "Gamma modification" msgstr "Gamos pakeitimas" msgid "Generate colors" msgstr "Generuoti spalvas" msgid "Gpick Palette (*.gpa)" msgstr "Gpick paletė (*.gpa)" msgid "Gray" msgstr "Pilka" msgid "Green" msgstr "Žalia" msgid "Grid (4x3)" msgstr "Tinklas (4x3)" msgid "Grid (5x4)" msgstr "Tinklas (5x4)" msgid "Group and _sort..." msgstr "_Grupavimas ir rūšiavimas..." msgid "Group and sort" msgstr "Grupuoti ir rūšiuoti" msgid "Group type:" msgstr "Grupavimo tipas:" msgid "Grouping sensitivity:" msgstr "Grupavimo jautrumas:" msgid "HSL" msgstr "HSL" msgid "HSL Hue" msgstr "HSL Atspalvis" msgid "HSL Lightness" msgstr "HSL Šviesumas" msgid "HSL Saturation" msgstr "HSL Įsotinimas" msgid "HSV" msgstr "HSV" msgid "Hash single-line comments" msgstr "Grotelių simbolio vienos eilutės komentarai" msgid "Header" msgstr "Antraštė" msgid "Header text" msgstr "Antraštės tekstas" msgid "Hex format" msgstr "Šešioliktainis formatas" msgid "Homepage" msgstr "Namų puslapis" msgid "Hue" msgstr "Atspalvis" msgid "Hue:" msgstr "Atspalvis:" msgid "Hyper Text Markup Language (*.html, *.htm)" msgstr "Hyper Text Markup Language (*.html, *.htm)" msgid "Image" msgstr "Paveikslėlis" msgid "Image file" msgstr "Paveikslėlio failas" msgid "Import" msgstr "Importuoti" msgid "Import _Text File..." msgstr "Importuoti _Tekstinį Failą..." msgid "Import text file" msgstr "Eksportuoti teksto failą" msgid "Include color names" msgstr "Pridėti spalvų pavadinimus" msgid "Info" msgstr "Informacija" msgid "Integer values" msgstr "Sveikieji skaičiai" msgid "Item" msgstr "Lauk." msgid "Item size" msgstr "Elemento dydis" msgid "Item size:" msgstr "Elemento dydis:" msgid "Item text" msgstr "Laukelio tekstas" msgid "Key" msgstr "Juoda" msgid "LAB" msgstr "LAB" msgid "LCH" msgstr "LCH" msgid "LCh Chroma" msgstr "LCh Chroma" msgid "LCh Hue" msgstr "LCh Atspalvis" msgid "LCh Lightness" msgstr "LCh Šviesumas" msgid "Lab A" msgstr "Lab A" msgid "Lab B" msgstr "Lab B" msgid "Lab Lightness" msgstr "Lab Šviesumas" msgid "Lab settings" msgstr "Lab nustatymai" msgid "Last color" msgstr "Paskutinė spalva" msgid "Lay_out preview" msgstr "Maket_o peržiūra" msgid "Layout preview" msgstr "Išdėstymo peržiūra" msgid "Layout:" msgstr "Išdėstymas:" msgid "License" msgstr "Licencija" msgid "Lightness" msgstr "Šviesumas" msgid "Lightness (Lab)" msgstr "Šviesumas (Lab)" msgid "Lightness:" msgstr "Šviesumas:" msgid "Linear" msgstr "Tiesinis" msgid "Links to us" msgstr "Nuorodos" msgid "Lower case" msgstr "Apatinis registras" msgid "Lua License" msgstr "Lua licencija" msgid "M_ove" msgstr "_Perkelti" msgid "Magenta" msgstr "Purpurinė" msgid "Maximal value" msgstr "Maksimali reikšmė" msgid "Maximum number of groups:" msgstr "Maksimalus grupių skaičius:" msgid "Medium" msgstr "Vidutinis" msgid "Menu" msgstr "Meniu" msgid "Middle:" msgstr "Vidurys:" msgid "Minimal value" msgstr "Minimali reikšmė" msgid "Mix colors" msgstr "Maišyti spalvas" msgid "Multiply" msgstr "Daugyba" msgid "Name" msgstr "Pavadinimas" msgid "Name:" msgstr "Pavadinimas:" msgid "Neutral" msgstr "Neutralus" msgid "New palette" msgstr "Nauja paletė" msgid "No filter selected" msgstr "Filtras neparinktas" msgid "None" msgstr "Joks" msgid "Normal" msgstr "Paprastas" msgid "Opacity:" msgstr "Nepermatomumas:" msgid "Open" msgstr "Atidaryti" msgid "Open File" msgstr "Atidaryti failą" msgid "Open Last File" msgstr "Atidaryti vėliausią failą" msgid "Options" msgstr "Nustatymai" msgid "Other settings" msgstr "Kiti nustatymai" msgid "Oversample:" msgstr "Mėginio vidurkis" msgid "Palette" msgstr "Paletė" msgid "Palette From _Image..." msgstr "Paletė iš paveikslėlio..." msgid "Palette from image" msgstr "Paletė iš paveikslėlio" msgid "Paste" msgstr "Įdėjimas" msgid "Path" msgstr "Kelias" msgid "Pick color" msgstr "Rinkti spalvą" msgid "Pick colors (Ctrl+P)" msgstr "Rinkti spalvas (Vald+P)" msgid "Press Spacebar to sample color under mouse pointer" msgstr "Paspauskite Tarpą norėdami gauti spalvą esančią po pelės kursoriu" msgid "Preview" msgstr "Peržiūra" msgid "Privacy" msgstr "Privatumas" msgid "Protanomaly" msgstr "Protanomalija" msgid "Protanopia" msgstr "Protanopija" msgid "Quadratic" msgstr "Kvardatinis" msgid "Quantization" msgstr "Kvantavimas" msgid "RGB" msgstr "RGB" msgid "RGB Blue" msgstr "RGB Mėlyna" msgid "RGB Grayscale" msgstr "RGB Pustonis" msgid "RGB Green" msgstr "RGB Žalia" msgid "RGB Red" msgstr "RGB Raudona" msgid "RSS" msgstr "RSS" msgid "RYB v1" msgstr "RYB v1" msgid "RYB v2" msgstr "RYB v2" msgid "R_everse" msgstr "_Atvirkščiai" msgid "Real values" msgstr "Realūs skaičiai" msgid "Recent _Files" msgstr "Paskutiniai _Failai" msgid "Rectangle (tetradic)" msgstr "Keturkampis (tetrada)" msgid "Red" msgstr "Raudona" msgid "Remove _All" msgstr "Pašalinti _visas" msgid "Rotation:" msgstr "Pasukimas:" msgid "Sample" msgstr "Pavyzdys" msgid "Sample count" msgstr "Mėginių kiekis" msgid "Sample:" msgstr "Pavyzdys:" msgid "Saturation" msgstr "Įsotinimas" msgid "Saturation:" msgstr "Įsotinimas:" msgid "Save" msgstr "Išsaugoti" msgid "Save As" msgstr "Išsaugoti kaip" msgid "Save/_Restore palette" msgstr "Išsaugoti/_Atstatyti paletę" msgid "Scheme _generation" msgstr "Schemos _generavimas" msgid "Scheme generation" msgstr "Schemos generavimas" msgid "Seed:" msgstr "Sėkla:" msgid "Settings" msgstr "Nustatymai" msgid "Short hex" msgstr "Trumpas šešioliktainis" msgid "Sidebar" msgstr "Šonas" msgid "Six-Tone" msgstr "Šeši tonai" msgid "Small" msgstr "Mažas" msgid "Sort type:" msgstr "Rūšiavimo tipas:" msgid "Split-Complementary" msgstr "Perskirtas papildantis" msgid "Square" msgstr "Kvadratas" msgid "Start steps:" msgstr "Pradiniai žingsniai:" msgid "Start:" msgstr "Pradžia:" msgid "Starting number:" msgstr "Pradėti nuo:" msgid "Static" msgstr "Pastovus" msgid "Steps:" msgstr "Žingsniai:" msgid "Strength:" msgstr "Stiprumas:" msgid "Style item" msgstr "Stiliaus objektas" msgid "System" msgstr "Sistema" msgid "System tray" msgstr "Sisteminis dėklas" msgid "Terms" msgstr "Sąlygos" msgid "Test color" msgstr "Testavimo spalva" msgid "Text File (*.txt)" msgstr "Tekstinis failas (*.txt)" msgid "Text file (*.txt)" msgstr "Tekstinis failas (*.txt)" msgid "The quick brown fox jumps over the lazy dog" msgstr "Greita ruda lapė šoka per tingų šunį" msgid "Tool color naming" msgstr "Įrankių spalvų pavadinimai" #, c-format msgid "Total %d color" msgid_plural "Total %d colors" msgstr[0] "Viso %d spalva" msgstr[1] "Viso %d spalvos" msgstr[2] "Viso %d spalvų" msgid "Triadic" msgstr "Triada" msgid "Tritanomaly" msgstr "Tritanomalija" msgid "Tritanopia" msgstr "Tritanopija" msgid "Type:" msgstr "Tipas:" msgid "Upper case" msgstr "Viršutinis registras" msgid "User controllable" msgstr "Varotojo valdomas" msgid "Value" msgstr "Reikšmė" msgid "Value:" msgstr "Reikšmė:" msgid "Variations" msgstr "Pokyčiai" msgid "Web: hex code" msgstr "Tinklas: šešioliktainis kodas" msgid "Web: hex code (3 digits)" msgstr "Tinklas: šešioliktainis kodas (3 skaitmenys)" msgid "Web: hex code (no hash symbol)" msgstr "Tinklas: šešioliktainis kodas (be grotelių simbolio)" msgid "Webpage" msgstr "Puslapis" msgid "White" msgstr "Balta" msgid "X axis" msgstr "X ašis" msgid "Y axis" msgstr "Y ašis" msgid "Yellow" msgstr "Geltona" msgid "Z axis" msgstr "Z ašis" msgid "Zoom:" msgstr "Priartinimas:" msgid "_Add to palette" msgstr "_Įkelti į paletę" msgid "_Append" msgstr "_Pridėti" msgid "_Assign CSS Selectors..." msgstr "_Priskirti CSS selektorius..." msgid "_Automatic name" msgstr "_Automatinis pavadinimas" msgid "_Close to system tray" msgstr "_Uždaryti į sisteminį dėklą" msgid "_Color names" msgstr "_Spalvų pavadinimai" msgid "_Copy to clipboard" msgstr "_Kopijuoti" msgid "_Decreasing" msgstr "Mažėjantis" msgid "_Edit" msgstr "_Keisti" msgid "_Edit..." msgstr "_Keisti..." msgid "_Empty" msgstr "_Tuščia" msgid "_Enable display filters" msgstr "_Įjungti rodymo filtrus" msgid "_Export CSS File As..." msgstr "_Eksportuoti CSS failą kaip..." msgid "_File" msgstr "_Failas" msgid "_Generate..." msgstr "_Generuoti..." msgid "_Help" msgstr "_Pagalba" msgid "_Illuminant:" msgstr "_Apšvietimas:" msgid "_Import..." msgstr "_Importuoti..." msgid "_Imprecision postfix" msgstr "_Netikslumo ženklas" msgid "_Include Endpoints" msgstr "Įtraukti _galinius taškus" msgid "_Linearization" msgstr "_Tiesinimas" msgid "_Linked" msgstr "_Sujungti" msgid "_Magnified area size:" msgstr "_Padidinto ploto dydis:" msgid "_Main" msgstr "_Pagrindiniai" msgid "_Mask out of gamut colors" msgstr "Maskuoti spalvas esančias už gamos ribų" msgid "_Minimize to system tray" msgstr "_Nuleisti į sisteminį dėklą" msgid "_Mix Colors..." msgstr "_Maišyti spalvas..." msgid "_Nearest from palette" msgstr "_Artimiausios iš paletės" msgid "_Observer:" msgstr "_Stebėtojas:" msgid "_Paste" msgstr "_Įdėti" msgid "_Picker" msgstr "_Rinkėjas" msgid "_Quit" msgstr "_Išeiti" msgid "_Refresh rate:" msgstr "_Atnaujinimo dažnis:" msgid "_Remove" msgstr "_Pašalinti" msgid "_Reset" msgstr "_Atstatyti" msgid "_Reset scheme" msgstr "_Atstatyti schemą" msgid "_Reverse" msgstr "_Atvirkščiai" msgid "_Reverse group order" msgstr "_Atvirkščia grupių tvarka" msgid "_Reverse order inside groups" msgstr "_Atvirkščia tvarka grupėse" msgid "_Rotate swatch" msgstr "_Pasukti mėginį" msgid "_Secondary View" msgstr "_Antrinis vaizdas" msgid "_Show Main Window" msgstr "_Rodyti pagrindinį langą" msgid "_Single instance" msgstr "_Vienas egzempliorius" msgid "_Start in system tray" msgstr "_Paleisti sisteminiame dėkle" msgid "_Tool specific" msgstr "_Priklausomai nuo įrankio" msgid "_Tools" msgstr "_Įrankiai" msgid "_Use multiplication" msgstr "_Naudoti daugybą" msgid "_Variations..." msgstr "_Pokyčiai..." msgid "_View" msgstr "_Rodymas" msgid "all colors" msgstr "visos spalvos" msgid "blend" msgstr "suliejimas" msgid "blend node" msgstr "suliejimo mazgas" msgid "brightness darkness" msgstr "šviesumas tamsumas" msgid "closest color" msgstr "artimiausia spalva" msgid "color mixer" msgstr "spalvų maišyklė" msgid "color space" msgstr "spalvų erdvė" msgid "error" msgstr "klaida" msgid "layout preview" msgstr "išdėstymo peržiūra" msgid "main" msgstr "pagrindinis" #, c-format msgid "match %d" msgstr "atitikmuo %d" msgid "mix" msgstr "maišymas" msgid "mix node" msgstr "maišymo mazgas" #, c-format msgid "primary %d" msgstr "pirminė %d" #, c-format msgid "result %d" msgstr "rezultatas %d" #, c-format msgid "result %d line %d" msgstr "rezultatas %d eilutėje %d" msgid "rgb.txt File (rgb.txt)" msgstr "rgb.txt failas (*.txt)" msgid "scheme" msgstr "schema" msgid "secondary" msgstr "antrinė" msgid "selected" msgstr "pasirinkta" msgid "target" msgstr "taikinys" msgid "variation" msgstr "pokyčiai" msgid "variations" msgstr "pokyčiai" gpick-gpick-0.2.6rc1/share/locale/ru/000077500000000000000000000000001315430016700173045ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/locale/ru/LC_MESSAGES/000077500000000000000000000000001315430016700210715ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/locale/ru/LC_MESSAGES/gpick.po000066400000000000000000001000651315430016700225300ustar00rootroot00000000000000# Translation of Gpick into Russian # Александр Прокудин , 2011. # msgid "" msgstr "" "Project-Id-Version: gpick 0.2.5\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2013-01-10 04:26+0400\n" "PO-Revision-Date: 2013-01-10 14:18+0300\n" "Last-Translator: Александр Прокудин \n" "Language-Team: Russian \n" "Language: ru\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2); 10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n" "X-Poedit-Language: Russian\n" "X-Poedit-Country: RUSSIAN FEDERATION\n" #: source/BlendColors.cpp:114 #: source/BlendColors.cpp:116 msgid "blend node" msgstr "основной" #: source/BlendColors.cpp:119 msgid "blend" msgstr "переход" #: source/BlendColors.cpp:308 #: source/BrightnessDarkness.cpp:260 #: source/ColorMixer.cpp:321 #: source/ColorPicker.cpp:367 #: source/GenerateScheme.cpp:444 #: source/LayoutPreview.cpp:405 #: source/Variations.cpp:331 #: source/uiDialogOptions.cpp:215 #: source/uiDialogOptions.cpp:234 msgid "_Add to palette" msgstr "_Добавить в палитру" #: source/BlendColors.cpp:314 #: source/BrightnessDarkness.cpp:265 #: source/ColorMixer.cpp:326 #: source/ColorPicker.cpp:371 #: source/GenerateScheme.cpp:449 #: source/LayoutPreview.cpp:410 #: source/Variations.cpp:336 msgid "A_dd all to palette" msgstr "Доб_авить все в палитру" #: source/BlendColors.cpp:320 #: source/BrightnessDarkness.cpp:271 #: source/ColorMixer.cpp:333 #: source/ColorPicker.cpp:377 #: source/GenerateScheme.cpp:456 #: source/LayoutPreview.cpp:416 #: source/Variations.cpp:343 #: source/uiDialogOptions.cpp:220 #: source/uiDialogOptions.cpp:239 msgid "_Copy to clipboard" msgstr "С_копировать в буфер обмена" #: source/BlendColors.cpp:374 #: source/GenerateScheme.cpp:485 msgid "_Reset" msgstr "С_бросить" #: source/BlendColors.cpp:517 msgid "Start:" msgstr "Начало:" #: source/BlendColors.cpp:533 msgid "Middle:" msgstr "Середина:" #: source/BlendColors.cpp:551 msgid "End:" msgstr "Конец:" #: source/BlendColors.cpp:568 #: source/GenerateScheme.cpp:875 #: source/uiDialogGenerate.cpp:237 #: source/uiDialogMix.cpp:249 #: source/transformation/ColorVisionDeficiency.cpp:363 msgid "Type:" msgstr "Тип:" #: source/BlendColors.cpp:570 #: source/ColorWheelType.cpp:56 #: source/uiDialogMix.cpp:251 msgid "RGB" msgstr "RGB" #: source/BlendColors.cpp:571 #: source/uiDialogMix.cpp:252 msgid "HSV" msgstr "HSV" #: source/BlendColors.cpp:572 #: source/uiDialogMix.cpp:253 msgid "HSV shortest hue distance" msgstr "HSV, кратчайшее расстояние" #: source/BlendColors.cpp:573 #: source/uiDialogMix.cpp:254 msgid "LAB" msgstr "LAB" #: source/BlendColors.cpp:582 msgid "Start steps:" msgstr "Шагов в начале:" #: source/BlendColors.cpp:590 msgid "End steps:" msgstr "Шагов в конце:" #: source/BlendColors.cpp:627 msgid "Blend colors" msgstr "Переход между цветами" #: source/BrightnessDarkness.cpp:86 msgid "brightness darkness" msgstr "Яркость-Темнота" #: source/BrightnessDarkness.cpp:287 #: source/ColorMixer.cpp:373 #: source/ColorPicker.cpp:387 #: source/GenerateScheme.cpp:469 #: source/LayoutPreview.cpp:430 #: source/Variations.cpp:383 msgid "_Edit..." msgstr "_Изменить…" #: source/BrightnessDarkness.cpp:292 #: source/ColorMixer.cpp:378 #: source/ColorPicker.cpp:391 #: source/GenerateScheme.cpp:474 #: source/LayoutPreview.cpp:435 #: source/Variations.cpp:388 msgid "_Paste" msgstr "_Вставить" #: source/BrightnessDarkness.cpp:385 msgid "Brightness" msgstr "Яркость" #: source/BrightnessDarkness.cpp:385 msgid "Darkness" msgstr "Темнота" #: source/BrightnessDarkness.cpp:431 msgid "Brightness Darkness" msgstr "Яркость-Темнота" #: source/ColorMixer.cpp:66 msgid "Normal" msgstr "Нормальный" #: source/ColorMixer.cpp:67 msgid "Multiply" msgstr "Умножение" #: source/ColorMixer.cpp:68 msgid "Add" msgstr "Добавление" #: source/ColorMixer.cpp:69 msgid "Difference" msgstr "Разница" #: source/ColorMixer.cpp:70 #: source/ColorPicker.cpp:1180 #: source/ColorPicker.cpp:1194 #: source/ColorSpaceType.cpp:30 #: source/ColorSpaceType.cpp:37 #: source/Variations.cpp:66 msgid "Hue" msgstr "Тон" #: source/ColorMixer.cpp:71 #: source/ColorPicker.cpp:1180 #: source/ColorPicker.cpp:1194 #: source/ColorSpaceType.cpp:31 #: source/ColorSpaceType.cpp:38 #: source/Variations.cpp:67 msgid "Saturation" msgstr "Насыщенность" #: source/ColorMixer.cpp:72 #: source/ColorPicker.cpp:1194 #: source/ColorPicker.cpp:1236 #: source/ColorPicker.cpp:1250 #: source/ColorSpaceType.cpp:39 #: source/ColorSpaceType.cpp:59 #: source/ColorSpaceType.cpp:66 #: source/Variations.cpp:68 msgid "Lightness" msgstr "Светлота" #: source/ColorMixer.cpp:114 msgid "color mixer" msgstr "Микшер цветов" #: source/ColorMixer.cpp:234 msgid "secondary" msgstr "первичный" #: source/ColorMixer.cpp:238 #: source/Variations.cpp:229 #, c-format msgid "primary %d" msgstr "вторичный %d" #: source/ColorMixer.cpp:244 #, c-format msgid "result %d" msgstr "результат %d" #: source/ColorMixer.cpp:704 msgid "Opacity:" msgstr "Непрозрачность:" #: source/ColorMixer.cpp:732 msgid "Color mixer" msgstr "Микшер цветов" #: source/ColorPicker.cpp:424 msgid "Press Spacebar to sample color under mouse pointer" msgstr "Нажмите пробел для добавления цвета под указателем" #: source/ColorPicker.cpp:699 #: source/uiConverter.cpp:163 msgid "Copy" msgstr "Копирование" #: source/ColorPicker.cpp:703 #: source/uiConverter.cpp:172 msgid "Paste" msgstr "Вставка" #: source/ColorPicker.cpp:709 #: source/uiColorInput.cpp:119 msgid "Edit" msgstr "Изменить" #: source/ColorPicker.cpp:771 #: source/uiApp.cpp:1012 #: source/uiDialogSort.cpp:222 msgid "None" msgstr "Нет" #: source/ColorPicker.cpp:772 msgid "Linear" msgstr "Линейное" #: source/ColorPicker.cpp:773 msgid "Quadratic" msgstr "Квадратичное" #: source/ColorPicker.cpp:774 msgid "Cubic" msgstr "Кубическое" #: source/ColorPicker.cpp:775 msgid "Exponential" msgstr "Экспоненциальное" #: source/ColorPicker.cpp:951 msgid "Click on swatch area to begin adding colors to palette" msgstr "" #: source/ColorPicker.cpp:1143 msgid "Settings" msgstr "Параметры" #: source/ColorPicker.cpp:1153 msgid "Oversample:" msgstr "Оверсэмплинг:" #: source/ColorPicker.cpp:1160 msgid "Falloff:" msgstr "Спадание:" #: source/ColorPicker.cpp:1167 msgid "Zoom:" msgstr "Масштаб:" #: source/ColorPicker.cpp:1180 #: source/ColorSpaceType.cpp:32 msgid "Value" msgstr "Значение" #: source/ColorPicker.cpp:1208 #: source/ColorSpaceType.cpp:44 msgid "Red" msgstr "Красный" #: source/ColorPicker.cpp:1208 #: source/ColorSpaceType.cpp:45 msgid "Green" msgstr "Зелёный" #: source/ColorPicker.cpp:1208 #: source/ColorSpaceType.cpp:46 msgid "Blue" msgstr "Синий" #: source/ColorPicker.cpp:1222 #: source/ColorSpaceType.cpp:51 msgid "Cyan" msgstr "Cyan" #: source/ColorPicker.cpp:1222 #: source/ColorSpaceType.cpp:52 msgid "Magenta" msgstr "Magenta" #: source/ColorPicker.cpp:1222 #: source/ColorSpaceType.cpp:53 msgid "Yellow" msgstr "Yellow" #: source/ColorPicker.cpp:1222 #: source/ColorSpaceType.cpp:54 msgid "Key" msgstr "Key" #: source/ColorPicker.cpp:1258 msgid "Info" msgstr "Информация" #: source/ColorPicker.cpp:1267 msgid "Color name:" msgstr "Название цвета:" #: source/ColorPicker.cpp:1280 msgid "Contrast:" msgstr "Контраст:" #: source/ColorPicker.cpp:1285 #: source/ColorPicker.cpp:1291 msgid "Sample" msgstr "Образец" #: source/ColorPicker.cpp:1324 msgid "Color picker" msgstr "Пипетка" #: source/ColorWheelType.cpp:57 msgid "RYB v1" msgstr "RYB v1" #: source/ColorWheelType.cpp:58 msgid "RYB v2" msgstr "RYB v2" #: source/GenerateScheme.cpp:90 msgid "Complementary" msgstr "Противоположные" #: source/GenerateScheme.cpp:91 msgid "Analogous" msgstr "Аналоговая" #: source/GenerateScheme.cpp:92 msgid "Triadic" msgstr "Триады" #: source/GenerateScheme.cpp:93 msgid "Split-Complementary" msgstr "Разделённые противоположные" #: source/GenerateScheme.cpp:94 msgid "Rectangle (tetradic)" msgstr "Прямоугольник (тетрады)" #: source/GenerateScheme.cpp:95 msgid "Square" msgstr "Квадрат" #: source/GenerateScheme.cpp:96 msgid "Neutral" msgstr "Нейтральная" #: source/GenerateScheme.cpp:97 msgid "Clash" msgstr "Конфликт" #: source/GenerateScheme.cpp:98 msgid "Five-Tone" msgstr "Пять тонов" #: source/GenerateScheme.cpp:99 msgid "Six-Tone" msgstr "Шесть тонов" #: source/GenerateScheme.cpp:119 #: source/uiDialogGenerate.cpp:76 msgid "scheme" msgstr "Схема" #: source/GenerateScheme.cpp:292 msgid "_Locked" msgstr "_Блокировать насыщенность и светлоту" #: source/GenerateScheme.cpp:299 msgid "_Reset scheme" msgstr "_Сбросить изменения" #: source/GenerateScheme.cpp:851 msgid "Hue:" msgstr "Тон:" #: source/GenerateScheme.cpp:858 #: source/uiDialogVariations.cpp:171 msgid "Saturation:" msgstr "Насыщенность:" #: source/GenerateScheme.cpp:866 #: source/uiDialogVariations.cpp:156 msgid "Lightness:" msgstr "Светлота:" #: source/GenerateScheme.cpp:885 #: source/uiDialogGenerate.cpp:246 msgid "Color wheel:" msgstr "Цветовой круг:" #: source/GenerateScheme.cpp:919 msgid "Scheme generation" msgstr "Создание цветовой схемы" #: source/LayoutPreview.cpp:78 msgid "layout preview" msgstr "Просмотр макета" #: source/LayoutPreview.cpp:153 msgid "Style item" msgstr "Объект стиля" #: source/LayoutPreview.cpp:162 msgid "CSS selector" msgstr "Селектор CSS" #: source/LayoutPreview.cpp:184 msgid "Assign CSS selectors" msgstr "Назначить селекторы CSS" #: source/LayoutPreview.cpp:547 #: source/LayoutPreview.cpp:595 #: source/uiApp.cpp:690 #: source/uiApp.cpp:711 msgid "File could not be saved" msgstr "Не удалось сохранить файл" #: source/LayoutPreview.cpp:558 #: source/uiExport.cpp:457 #: source/uiExport.cpp:523 msgid "Export" msgstr "Экспортировать" #: source/LayoutPreview.cpp:572 msgid "Cascading Style Sheets *.css" msgstr "Каскадные таблицы стилей (*.css)" #: source/LayoutPreview.cpp:666 msgid "Layout:" msgstr "Макет:" #: source/LayoutPreview.cpp:672 msgid "Export CSS File" msgstr "Экспортировать файл CSS" #: source/LayoutPreview.cpp:673 msgid "Export CSS file" msgstr "Экспортировать файл CSS" #: source/LayoutPreview.cpp:682 msgid "_Export CSS File As..." msgstr "_Экспортировать файл CSS как…" #: source/LayoutPreview.cpp:686 msgid "_Assign CSS Selectors..." msgstr "_Назначить селекторы CSS…" #: source/LayoutPreview.cpp:759 msgid "Layout preview" msgstr "Просмотр макета" #: source/ToolColorNaming.cpp:25 msgid "_Empty" msgstr "_Без названия" #: source/ToolColorNaming.cpp:26 msgid "_Automatic name" msgstr "_Автоматическое именование" #: source/ToolColorNaming.cpp:27 msgid "_Tool specific" msgstr "_В зависимости от инструмента" #: source/Variations.cpp:69 msgid "Lightness (Lab)" msgstr "Светлота (Lab)" #: source/Variations.cpp:110 msgid "variations" msgstr "Вариации" #: source/Variations.cpp:225 msgid "all colors" msgstr "все цвета" #: source/Variations.cpp:239 #, c-format msgid "result %d line %d" msgstr "результат %d строка %d" #: source/Variations.cpp:717 #: source/transformation/ColorVisionDeficiency.cpp:386 msgid "Strength:" msgstr "Сила:" #: source/Variations.cpp:745 #: source/uiDialogVariations.cpp:142 msgid "Variations" msgstr "Вариации светлоты и насыщенности" #: source/uiAbout.cpp:88 msgid "About Gpick" msgstr "О программе Gpick" #: source/uiAbout.cpp:121 msgid "Advanced color picker" msgstr "Продвинутая цветовая пипетка" #: source/uiAbout.cpp:126 msgid "Copyrights © 2009-2013, Albertas Vyšniauskas and Gpick development team" msgstr "Авторские права © 2009-2013, Albertas Vyšniauskas and Gpick development team" #: source/uiAbout.cpp:141 msgid "License" msgstr "Лицензия" #: source/uiAbout.cpp:142 msgid "Credits" msgstr "Авторы" #: source/uiAbout.cpp:143 msgid "Expat License" msgstr "Лицензия на Expat" #: source/uiAbout.cpp:144 msgid "Lua License" msgstr "Лицензия на Lua" #: source/uiApp.cpp:354 msgid "New palette" msgstr "Новая палитра" #: source/uiApp.cpp:360 msgid "(Imported)" msgstr "(импортировано)" #: source/uiApp.cpp:530 #: source/uiApp.cpp:545 #: source/uiApp.cpp:563 #: source/uiApp.cpp:641 msgid "File could not be opened" msgstr "Не удалось открыть файл" #: source/uiApp.cpp:531 #: source/uiApp.cpp:546 #: source/uiApp.cpp:564 #: source/uiApp.cpp:642 msgid "Open" msgstr "Открыть" #: source/uiApp.cpp:576 #: source/uiExport.cpp:473 #: source/uiExport.cpp:587 msgid "Gpick Palette (*.gpa)" msgstr "Палитры Gpick (*.gpa)" #: source/uiApp.cpp:577 #: source/uiExport.cpp:474 #: source/uiExport.cpp:588 msgid "GIMP/Inkscape Palette (*.gpl)" msgstr "Палитры GIMP/Inkscape (*.gpl)" #: source/uiApp.cpp:578 #: source/uiExport.cpp:476 #: source/uiExport.cpp:589 msgid "Adobe Swatch Exchange (*.ase)" msgstr "Палитры Adobe Swatch Exchange (*.ase)" #: source/uiApp.cpp:584 #: source/uiExport.cpp:598 #: source/tools/PaletteFromImage.cpp:548 msgid "All files" msgstr "Все файлы" #: source/uiApp.cpp:589 #: source/uiExport.cpp:607 msgid "All supported formats" msgstr "Все поддерживаемые форматы" #: source/uiApp.cpp:610 msgid "Open File" msgstr "Открыть файл" #: source/uiApp.cpp:659 #: source/uiApp.cpp:691 msgid "Save As" msgstr "Сохранить как" #: source/uiApp.cpp:712 msgid "Save" msgstr "Сохранить" #: source/uiApp.cpp:771 msgid "Open Last File" msgstr "Открыть последний файл" #: source/uiApp.cpp:916 msgid "Recent _files" msgstr "_Недавние файлы" #: source/uiApp.cpp:946 msgid "Ex_port..." msgstr "_Экспортировать…" #: source/uiApp.cpp:954 msgid "Expo_rt Selected..." msgstr "Экспортировать _выделенное…" #: source/uiApp.cpp:962 msgid "_Import..." msgstr "_Импортировать…" #: source/uiApp.cpp:977 msgid "_File" msgstr "_Файл" #: source/uiApp.cpp:985 msgid "Edit _Converters..." msgstr "_Конвертеры…" #: source/uiApp.cpp:989 msgid "Display _Filters..." msgstr "_Экранные фильтры..." #: source/uiApp.cpp:1001 msgid "_Edit" msgstr "_Правка" #: source/uiApp.cpp:1037 msgid "_Secondary View" msgstr "_Дополнительная панель" #: source/uiApp.cpp:1043 msgid "Palette" msgstr "Палитра цветов" #: source/uiApp.cpp:1049 msgid "_View" msgstr "_Вид" #: source/uiApp.cpp:1055 msgid "Palette From _Image..." msgstr "_Палитра из изображения…" #: source/uiApp.cpp:1063 msgid "_Tools" msgstr "_Инструменты" #: source/uiApp.cpp:1078 msgid "_Help" msgstr "_Справка" #: source/uiApp.cpp:1386 msgid "_Copy to Clipboard" msgstr "С_копировать в буфер обмена" #: source/uiApp.cpp:1402 msgid "_Mix Colors..." msgstr "С_мешать цвета…" #: source/uiApp.cpp:1407 msgid "_Variations..." msgstr "Вариации _светлоты и насыщенности…" #: source/uiApp.cpp:1412 msgid "_Generate..." msgstr "Вариации _тонов…" #: source/uiApp.cpp:1421 msgid "C_lear names" msgstr "Ст_ереть названия" #: source/uiApp.cpp:1427 msgid "Autona_me" msgstr "_Автоматически подобрать названия" #: source/uiApp.cpp:1433 msgid "Auto_number..." msgstr "Автоматически _пронумеровать..." #: source/uiApp.cpp:1441 msgid "R_everse" msgstr "_Развернуть" #: source/uiApp.cpp:1447 msgid "Group and _sort..." msgstr "С_группировать и отсортировать..." #: source/uiApp.cpp:1455 msgid "_Remove" msgstr "_Удалить" #: source/uiApp.cpp:1461 msgid "Remove _All" msgstr "Удалить _все" #: source/uiApp.cpp:1869 msgid "Color pic_ker" msgstr "П_ипетка" #: source/uiApp.cpp:1878 msgid "Scheme _generation" msgstr "Создание _цветовой схемы" #: source/uiApp.cpp:1897 msgid "Lay_out preview" msgstr "Просмотр _макета" #: source/uiApp.cpp:1947 msgid "Pick colors (Ctrl+P)" msgstr "Снять цвет пипеткой (Ctrl+P)" #: source/uiApp.cpp:1956 msgid "File is currently in a non-native format, possible loss of precision and/or metadata." msgstr "Файл сохранён не в собственном формате Gpick, возможны потери точности или метаданных." #: source/uiColorInput.cpp:45 msgid "Edit color" msgstr "Изменить цвет" #: source/uiColorInput.cpp:69 msgid "Color:" msgstr "Цвет:" #: source/uiConverter.cpp:56 msgid "Test color" msgstr "Пробный цвет" #: source/uiConverter.cpp:74 msgid "error" msgstr "Ошибка" #: source/uiConverter.cpp:145 msgid "Function name" msgstr "Название функции" #: source/uiConverter.cpp:154 msgid "Example" msgstr "Пример" #: source/uiConverter.cpp:196 msgid "Converters" msgstr "Конвертеры" #: source/uiConverter.cpp:224 msgid "Displays:" msgstr "Показывает:" #: source/uiConverter.cpp:230 msgid "Color list:" msgstr "Список цветов:" #: source/uiDialogAutonumber.cpp:108 msgid "Autonumber colors" msgstr "Автоматически пронумеровать цвета" #: source/uiDialogAutonumber.cpp:122 msgid "Name:" msgstr "Название:" #: source/uiDialogAutonumber.cpp:132 msgid "Decimal places:" msgstr "Число разрядов:" #: source/uiDialogAutonumber.cpp:139 msgid "Starting number:" msgstr "Начать с цифры:" #: source/uiDialogAutonumber.cpp:146 msgid "_Decreasing" msgstr "По _нисходящей" #: source/uiDialogAutonumber.cpp:152 msgid "_Append" msgstr "_Добавлять поверх" #: source/uiDialogAutonumber.cpp:158 msgid "Sample:" msgstr "Образец:" #: source/uiDialogGenerate.cpp:216 msgid "Generate colors" msgstr "Вариации тонов" #: source/uiDialogGenerate.cpp:230 #: source/tools/PaletteFromImage.cpp:599 msgid "Colors:" msgstr "Цветов:" #: source/uiDialogGenerate.cpp:257 msgid "Chaos:" msgstr "Хаос:" #: source/uiDialogGenerate.cpp:263 msgid "Seed:" msgstr "Зерно:" #: source/uiDialogGenerate.cpp:271 msgid "_Reverse" msgstr "_Развернуть" #: source/uiDialogMix.cpp:76 #: source/uiDialogMix.cpp:78 msgid "mix node" msgstr "" #: source/uiDialogMix.cpp:81 msgid "mix" msgstr "" #: source/uiDialogMix.cpp:235 msgid "Mix colors" msgstr "Смешать цвета" #: source/uiDialogMix.cpp:262 #: source/uiDialogVariations.cpp:186 msgid "Steps:" msgstr "Шагов:" #: source/uiDialogMix.cpp:270 msgid "_Include Endpoints" msgstr "_Включая оконечные цвета" #: source/uiDialogOptions.cpp:117 #: source/tools/PaletteFromImage.cpp:589 msgid "Options" msgstr "Параметры" #: source/uiDialogOptions.cpp:134 msgid "System" msgstr "Системные" #: source/uiDialogOptions.cpp:143 msgid "_Single instance" msgstr "_Запускать лишь одну копию приложения" #: source/uiDialogOptions.cpp:148 msgid "Save/_Restore palette" msgstr "Сохранить/_Восстановить палитру" #: source/uiDialogOptions.cpp:154 msgid "System tray" msgstr "Область уведомления" #: source/uiDialogOptions.cpp:162 msgid "_Minimize to system tray" msgstr "С_ворачивать в область уведомления" #: source/uiDialogOptions.cpp:167 msgid "_Close to system tray" msgstr "_Закрывать в область уведомления" #: source/uiDialogOptions.cpp:172 msgid "_Start in system tray" msgstr "З_апускать в области уведомления" #: source/uiDialogOptions.cpp:178 msgid "_Main" msgstr "О_сновные" #: source/uiDialogOptions.cpp:184 msgid "Display" msgstr "Внешний вид" #: source/uiDialogOptions.cpp:193 msgid "_Refresh rate:" msgstr "_Частота обновления:" #: source/uiDialogOptions.cpp:201 msgid "_Magnified area size:" msgstr "_Размер области увеличения:" #: source/uiDialogOptions.cpp:207 msgid "Floating picker click behaviour" msgstr "Действие по щелчку пипеткой" #: source/uiDialogOptions.cpp:226 msgid "'Spacebar' button behaviour" msgstr "Действие по нажатию пробела" #: source/uiDialogOptions.cpp:244 msgid "_Rotate swatch" msgstr "По_вернуть образец" #: source/uiDialogOptions.cpp:251 msgid "Enabled color spaces" msgstr "Используемые цветовые пространства" #: source/uiDialogOptions.cpp:266 msgid "Lab settings" msgstr "Параметры Lab" #: source/uiDialogOptions.cpp:278 msgid "_Illuminant:" msgstr "Ос_ветитель:" #: source/uiDialogOptions.cpp:302 msgid "_Observer:" msgstr "_Наблюдатель:" #: source/uiDialogOptions.cpp:321 msgid "Other settings" msgstr "Прочие параметры" #: source/uiDialogOptions.cpp:330 msgid "_Mask out of gamut colors" msgstr "_Маскировать цвета вне охвата" #: source/uiDialogOptions.cpp:336 msgid "_Picker" msgstr "_Пипетка" #: source/uiDialogOptions.cpp:341 msgid "Color name generation" msgstr "Подбор названий" #: source/uiDialogOptions.cpp:350 msgid "_Imprecision postfix" msgstr "Помечать _неточное совпадение тильдой" #: source/uiDialogOptions.cpp:356 msgid "Tool color naming" msgstr "Именование снятых цветов" #: source/uiDialogOptions.cpp:381 msgid "_Color names" msgstr "_Названия цветов" #: source/uiDialogSort.cpp:135 #: source/uiDialogSort.cpp:223 msgid "RGB Red" msgstr "Красный в RGB" #: source/uiDialogSort.cpp:136 #: source/uiDialogSort.cpp:224 msgid "RGB Green" msgstr "Зелёный в RGB" #: source/uiDialogSort.cpp:137 #: source/uiDialogSort.cpp:225 msgid "RGB Blue" msgstr "Синий в RGB" #: source/uiDialogSort.cpp:138 #: source/uiDialogSort.cpp:226 msgid "RGB Grayscale" msgstr "Градации серого в RGB" #: source/uiDialogSort.cpp:139 #: source/uiDialogSort.cpp:227 msgid "HSL Hue" msgstr "Тон HSL" #: source/uiDialogSort.cpp:140 #: source/uiDialogSort.cpp:228 msgid "HSL Saturation" msgstr "Насыщенность в HSL" #: source/uiDialogSort.cpp:141 #: source/uiDialogSort.cpp:229 msgid "HSL Lightness" msgstr "Светлота в HSL" #: source/uiDialogSort.cpp:142 #: source/uiDialogSort.cpp:230 msgid "Lab Lightness" msgstr "Светлота в Lab" #: source/uiDialogSort.cpp:143 #: source/uiDialogSort.cpp:231 msgid "Lab A" msgstr "Lab A" #: source/uiDialogSort.cpp:144 #: source/uiDialogSort.cpp:232 msgid "Lab B" msgstr "Lab B" #: source/uiDialogSort.cpp:145 #: source/uiDialogSort.cpp:233 msgid "LCh Lightness" msgstr "Светлота в LCh" #: source/uiDialogSort.cpp:146 #: source/uiDialogSort.cpp:234 msgid "LCh Chroma" msgstr "Цветность в LCh" #: source/uiDialogSort.cpp:147 #: source/uiDialogSort.cpp:235 msgid "LCh Hue" msgstr "Тон в LCh" #: source/uiDialogSort.cpp:556 msgid "Group and sort" msgstr "Сгруппировать и отсортировать" #: source/uiDialogSort.cpp:564 msgid "Group type:" msgstr "Критерий группировки:" #: source/uiDialogSort.cpp:574 msgid "Grouping sensitivity:" msgstr "Чувствительность группировки:" #: source/uiDialogSort.cpp:581 msgid "Maximum number of groups:" msgstr "Предельное количество групп:" #: source/uiDialogSort.cpp:588 msgid "Sort type:" msgstr "Критерий сортировки:" #: source/uiDialogSort.cpp:598 msgid "_Reverse group order" msgstr "О_братить порядок группировки" #: source/uiDialogSort.cpp:604 msgid "_Reverse order inside groups" msgstr "Обратить порядок _внутри группы" #: source/uiDialogVariations.cpp:60 msgid "variation" msgstr "Вариации светлоты и насыщенности" #: source/uiDialogVariations.cpp:194 msgid "_Use multiplication" msgstr "_Использовать умножение" #: source/uiExport.cpp:475 msgid "Alias/WaveFront Material (*.mtl)" msgstr "Материалы Alias/WaveFront (*.mtl)" #: source/uiExport.cpp:477 msgid "Text file (*.txt)" msgstr "Текстовые файлы (*.txt)" #: source/uiExport.cpp:522 msgid "File could not be exported" msgstr "Не удалось экспортировать файл" #: source/uiExport.cpp:573 #: source/uiExport.cpp:654 #: source/uiExport.cpp:666 msgid "Import" msgstr "Импортировать" #: source/uiExport.cpp:653 msgid "File format is not supported" msgstr "Этот формат файлов не поддерживается" #: source/uiExport.cpp:665 msgid "File could not be imported" msgstr "Не удалось импортировать файл" #: source/uiListPalette.cpp:158 #: source/uiListPalette.cpp:160 #, c-format msgid "%d color" msgid_plural "%d colors" msgstr[0] "%d цвет" msgstr[1] "%d цвета" msgstr[2] "%d цветов" #: source/uiListPalette.cpp:166 msgid "selected" msgstr "выбрано" #: source/uiListPalette.cpp:172 #: source/uiListPalette.cpp:174 #, c-format msgid "Total %d color" msgid_plural "Total %d colors" msgstr[0] "Всего %d цвет" msgstr[1] "Всего %d цвета" msgstr[2] "Всего %d цветов" #: source/uiListPalette.cpp:353 msgid "Preview" msgstr "Предпросмотр" #: source/uiListPalette.cpp:708 #: source/uiListPalette.cpp:717 msgid "Color" msgstr "Цвет" #: source/uiListPalette.cpp:726 #: source/uiTransformations.cpp:183 msgid "Name" msgstr "Название" #: source/uiStatusIcon.cpp:67 msgid "_Show Main Window" msgstr "_Показать основное окно" #: source/uiStatusIcon.cpp:74 msgid "_Quit" msgstr "В_ыход" #: source/uiTransformations.cpp:245 msgid "Display filters" msgstr "Экранные фильтры" #: source/uiTransformations.cpp:259 msgid "_Enabled" msgstr "_Применять экранные фильтры" #: source/tools/PaletteFromImage.cpp:514 msgid "Palette from image" msgstr "Палитра из изображения" #: source/tools/PaletteFromImage.cpp:527 msgid "Image" msgstr "Изображение" #: source/tools/PaletteFromImage.cpp:536 msgid "Image file" msgstr "Файл изображения" #: source/tools/PaletteFromImage.cpp:556 msgid "All images" msgstr "Все изображения" #: source/transformation/ColorVisionDeficiency.cpp:41 msgid "Color vision deficiency" msgstr "Цветонеразличение" #: source/transformation/ColorVisionDeficiency.cpp:330 msgid "Protanomaly" msgstr "Протаномалия" #: source/transformation/ColorVisionDeficiency.cpp:331 msgid "Deuteranomaly" msgstr "Дейтераномалия" #: source/transformation/ColorVisionDeficiency.cpp:332 msgid "Tritanomaly" msgstr "Тританомалия" #: source/transformation/ColorVisionDeficiency.cpp:333 msgid "Protanopia" msgstr "Протанопия" #: source/transformation/ColorVisionDeficiency.cpp:334 msgid "Deuteranopia" msgstr "Дейтеранопия" #: source/transformation/ColorVisionDeficiency.cpp:335 msgid "Tritanopia" msgstr "Тританопия" #: source/transformation/ColorVisionDeficiency.cpp:422 msgid "Altered spectral sensitivity of red receptors" msgstr "Слабое восприятие красного цвета" #: source/transformation/ColorVisionDeficiency.cpp:423 msgid "Altered spectral sensitivity of green receptors" msgstr "Слабое восприятие зелёного цвета" #: source/transformation/ColorVisionDeficiency.cpp:424 msgid "Altered spectral sensitivity of blue receptors" msgstr "Слабое восприятие синего цвета" #: source/transformation/ColorVisionDeficiency.cpp:425 msgid "Absence of red receptors" msgstr "Отсутствие рецепторов красного цвета" #: source/transformation/ColorVisionDeficiency.cpp:426 msgid "Absence of green receptors" msgstr "Отсутствие рецепторов зелёного цвета" #: source/transformation/ColorVisionDeficiency.cpp:427 msgid "Absence of blue receptors" msgstr "Отсутствие рецепторов синего цвета" #: source/transformation/GammaModification.cpp:38 msgid "Gamma modification" msgstr "Гамма-коррекция" #: source/transformation/GammaModification.cpp:88 #: source/transformation/Quantization.cpp:96 msgid "Value:" msgstr "Значение:" #: source/transformation/Quantization.cpp:40 msgid "Quantization" msgstr "Квантование" #: source/transformation/Quantization.cpp:101 msgid "Clip top-end" msgstr "" #: share/gpick/init.lua:173 msgid "Web: hex code" msgstr "Web: hex-код" #: share/gpick/init.lua:178 msgid "Web: hex code (3 digits)" msgstr "Web: hex-код (3 знака)" #: share/gpick/init.lua:183 msgid "Web: hex code (no hash symbol)" msgstr "Web: hex-код (без решётки)" #: share/gpick/init.lua:188 msgid "CSS: hue saturation lightness" msgstr "CSS: тон, насыщенность, светлота" #: share/gpick/init.lua:193 msgid "CSS: red green blue" msgstr "CSS: красный, зелёный, синий" #: share/gpick/layouts.lua:15 msgid "Homepage" msgstr "Homepage" #: share/gpick/layouts.lua:15 msgid "About us" msgstr "About us" #: share/gpick/layouts.lua:15 msgid "Links to us" msgstr "Links to us" #: share/gpick/layouts.lua:15 msgid "Privacy" msgstr "Privacy" #: share/gpick/layouts.lua:15 msgid "Terms" msgstr "Terms" #: share/gpick/layouts.lua:15 msgid "Contact us" msgstr "Contact us" #: share/gpick/layouts.lua:15 msgid "RSS" msgstr "RSS" #: share/gpick/layouts.lua:30 msgid "The quick brown fox jumps over the lazy dog" msgstr "" #: share/gpick/layouts.lua:46 msgid "Webpage" msgstr "Webpage" #: share/gpick/layouts.lua:51 #: share/gpick/layouts.lua:73 msgid "Header" msgstr "Header" #: share/gpick/layouts.lua:52 msgid "Header text" msgstr "Header text" #: share/gpick/layouts.lua:54 msgid "Content" msgstr "Content" #: share/gpick/layouts.lua:55 msgid "Content text" msgstr "Content text" #: share/gpick/layouts.lua:57 msgid "Sidebar" msgstr "Sidebar" #: share/gpick/layouts.lua:59 #: share/gpick/layouts.lua:87 msgid "Button" msgstr "Button" #: share/gpick/layouts.lua:60 #: share/gpick/layouts.lua:88 msgid "Button (hover)" msgstr "Button (hover)" #: share/gpick/layouts.lua:61 #: share/gpick/layouts.lua:89 msgid "Button text" msgstr "Button text" #: share/gpick/layouts.lua:62 #: share/gpick/layouts.lua:90 msgid "Button text (hover)" msgstr "Button text (hover)" #: share/gpick/layouts.lua:64 msgid "Footer" msgstr "Footer" #: share/gpick/layouts.lua:82 #: share/gpick/layouts.lua:86 msgid "Menu" msgstr "Menu" #: share/gpick/layouts.lua:106 msgid "Brightness-Darkness" msgstr "Brightness-Darkness" #: share/gpick/layouts.lua:110 msgid "main" msgstr "основной" #: share/gpick/layouts.lua:144 msgid "Grid (4x3)" msgstr "Сетка (4x3)" #: share/gpick/layouts.lua:153 #: share/gpick/layouts.lua:159 #: share/gpick/layouts.lua:180 #: share/gpick/layouts.lua:186 msgid "Item" msgstr "Item" #: share/gpick/layouts.lua:154 #: share/gpick/layouts.lua:181 msgid "Item text" msgstr "Item text" #: share/gpick/layouts.lua:171 msgid "Grid (5x4)" msgstr "Сетка (5x4)" #~ msgid "Edit _Transformations..." #~ msgstr "_Коррекция вывода цвета…" gpick-gpick-0.2.6rc1/share/man/000077500000000000000000000000001315430016700161725ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/man/man1/000077500000000000000000000000001315430016700170265ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/share/man/man1/gpick.1000066400000000000000000000003241315430016700202040ustar00rootroot00000000000000.TH gpick .SH NAME gpick \- advanced color picker .SH SYNOPSIS .B gpick [\fIFILE\fR] .SH DESCRIPTION \fBgpick\fR starts an application and opens FILE if it is specified .SH AUTHOR Written by Albertas Vyšniauskasgpick-gpick-0.2.6rc1/source/000077500000000000000000000000001315430016700156155ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/source/BezierCubicCurve.h000066400000000000000000000041501315430016700211610ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef BEZIERCUBICCURVE_H_ #define BEZIERCUBICCURVE_H_ namespace math{ template class BezierCubicCurve{ public: BezierCubicCurve(const PT &p0_, const PT &p1_, const PT &p2_, const PT &p3_):p0(p0_),p1(p1_),p2(p2_),p3(p3_){ }; PT operator() (const T &t){ T t2 = 1-t; return p0*(t2*t2*t2) + p1*(3*(t2*t2)*t) + p2*(3*t2*t*t) + p3*(t*t*t); }; BezierCubicCurve& operator= (const BezierCubicCurve& curve){ p0 = curve.p0; p1 = curve.p1; p2 = curve.p2; p3 = curve.p3; return *this; }; PT p0; PT p1; PT p2; PT p3; }; } #endif /* BEZIERCUBICCURVE_H_ */ gpick-gpick-0.2.6rc1/source/BlendColors.cpp000066400000000000000000000522731315430016700205400ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "BlendColors.h" #include "ColorObject.h" #include "ColorSource.h" #include "ColorSourceManager.h" #include "ColorUtils.h" #include "uiListPalette.h" #include "uiUtilities.h" #include "MathUtil.h" #include "DynvHelpers.h" #include "GlobalState.h" #include "ToolColorNaming.h" #include "DragDrop.h" #include "ColorList.h" #include "color_names/ColorNames.h" #include "MathUtil.h" #include "ColorRYB.h" #include "gtk/ColorWidget.h" #include "uiColorInput.h" #include "CopyPaste.h" #include "Converter.h" #include "DynvHelpers.h" #include "StandardMenu.h" #include "ToolColorNaming.h" #include "Internationalisation.h" #include #include #include #include #include #ifndef _MSC_VER #include #endif #include using namespace std; typedef struct BlendColorsArgs{ ColorSource source; GtkWidget *main; GtkWidget *mix_type; GtkWidget *steps1; GtkWidget *steps2; GtkWidget *start_color; GtkWidget *middle_color; GtkWidget *end_color; GtkWidget *preview_list; ColorList *preview_color_list; struct dynvSystem *params; GlobalState* gs; }BlendColorsArgs; class BlendColorNameAssigner: public ToolColorNameAssigner { protected: stringstream m_stream; const char *m_color_start; const char *m_color_end; int m_start_percent; int m_end_percent; int m_steps; int m_stage; bool m_is_color_item; public: BlendColorNameAssigner(GlobalState *gs): ToolColorNameAssigner(gs) { m_is_color_item = false; } void setNames(const char *start_color_name, const char *end_color_name) { m_color_start = start_color_name; m_color_end = end_color_name; } void setStepsAndStage(int steps, int stage) { m_steps = steps; m_stage = stage; } void assign(ColorObject *color_object, const Color *color, int step) { m_start_percent = step * 100 / (m_steps - 1); m_end_percent = 100 - (step * 100 / (m_steps - 1)); m_is_color_item = (((step == 0 || step == m_steps - 1) && m_stage == 0) || (m_stage == 1 && step == m_steps - 1)); ToolColorNameAssigner::assign(color_object, color); } void assign(ColorObject *color_object, const Color *color, const char *item_name) { m_color_start = item_name; m_is_color_item = true; ToolColorNameAssigner::assign(color_object, color); } virtual std::string getToolSpecificName(ColorObject *color_object, const Color *color) { m_stream.str(""); if (m_is_color_item){ if (m_end_percent == 100){ m_stream << m_color_end << " " << _("blend node"); }else{ m_stream << m_color_start << " " << _("blend node"); } }else{ m_stream << m_color_start << " " << m_start_percent << " " << _("blend") << " " << m_end_percent << " " << m_color_end; } return m_stream.str(); } }; static int source_get_color(BlendColorsArgs *args, ColorObject** color); static void store(ColorList *color_list, const Color *color, int step, BlendColorNameAssigner &name_assigner) { ColorObject *color_object = color_list_new_color_object(color_list, color); name_assigner.assign(color_object, color, step); color_list_add_color_object(color_list, color_object, 1); color_object->release(); } static void calc(BlendColorsArgs *args, bool preview, int limit) { gint steps1 = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(args->steps1)); gint steps2 = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(args->steps2)); gint type = gtk_combo_box_get_active(GTK_COMBO_BOX(args->mix_type)); Color r; gint step_i; Color a,b; ColorList *color_list; color_list = args->preview_color_list; BlendColorNameAssigner name_assigner(args->gs); int steps; for (int stage = 0; stage < 2; stage++){ if (stage == 0){ steps = steps1 + 1; gtk_color_get_color(GTK_COLOR(args->start_color), &a); gtk_color_get_color(GTK_COLOR(args->middle_color), &b); }else{ steps = steps2 + 1; gtk_color_get_color(GTK_COLOR(args->middle_color), &a); gtk_color_get_color(GTK_COLOR(args->end_color), &b); } string start_name = color_names_get(args->gs->getColorNames(), &a, false); string end_name = color_names_get(args->gs->getColorNames(), &b, false); name_assigner.setNames(start_name.c_str(), end_name.c_str()); name_assigner.setStepsAndStage(steps, stage); if (type == 0){ color_rgb_get_linear(&a, &a); color_rgb_get_linear(&b, &b); } step_i = stage; switch (type){ case 0: for (; step_i < steps; ++step_i){ color_utils::mix(a, b, step_i / (float)(steps - 1), r); color_linear_get_rgb(&r, &r); store(color_list, &r, step_i, name_assigner); } break; case 1: { Color a_hsv, b_hsv, r_hsv; color_rgb_to_hsv(&a, &a_hsv); color_rgb_to_hsv(&b, &b_hsv); if (a_hsv.hsv.hue > b_hsv.hsv.hue){ if (a_hsv.hsv.hue - b_hsv.hsv.hue > 0.5) a_hsv.hsv.hue -= 1; }else{ if (b_hsv.hsv.hue - a_hsv.hsv.hue > 0.5) b_hsv.hsv.hue -= 1; } for (; step_i < steps; ++step_i){ color_utils::mix(a_hsv, b_hsv, step_i / (float)(steps - 1), r_hsv); if (r_hsv.hsv.hue < 0) r_hsv.hsv.hue += 1; color_hsv_to_rgb(&r_hsv, &r); store(color_list, &r, step_i, name_assigner); } } break; case 2: { Color a_lab, b_lab, r_lab; color_rgb_to_lab_d50(&a, &a_lab); color_rgb_to_lab_d50(&b, &b_lab); for (; step_i < steps; ++step_i){ color_utils::mix(a_lab, b_lab, step_i / (float)(steps - 1), r_lab); color_lab_to_rgb_d50(&r_lab, &r); color_rgb_normalize(&r); store(color_list, &r, step_i, name_assigner); } } break; case 3: { Color a_lch, b_lch, r_lch; color_rgb_to_lch_d50(&a, &a_lch); color_rgb_to_lch_d50(&b, &b_lch); if (a_lch.lch.h>b_lch.lch.h){ if (a_lch.lch.h - b_lch.lch.h > 180) a_lch.lch.h -= 360; }else{ if (b_lch.lch.h - a_lch.lch.h > 180) b_lch.lch.h -= 360; } for (; step_i < steps; ++step_i){ color_utils::mix(a_lch, b_lch, step_i / (float)(steps - 1), r_lch); if (r_lch.lch.h < 0) r_lch.lch.h += 360; color_lch_to_rgb_d50(&r_lch, &r); color_rgb_normalize(&r); store(color_list, &r, step_i, name_assigner); } } break; } } } static PaletteListCallbackReturn add_to_palette_cb_helper(ColorObject* color_object, void *userdata) { BlendColorsArgs *args = (BlendColorsArgs*)userdata; color_list_add_color_object(args->gs->getColorList(), color_object, 1); return PALETTE_LIST_CALLBACK_NO_UPDATE; } static gboolean add_to_palette_cb(GtkWidget *widget, BlendColorsArgs *args) { palette_list_foreach_selected(args->preview_list, add_to_palette_cb_helper, args); return true; } static gboolean add_all_to_palette_cb(GtkWidget *widget, BlendColorsArgs *args) { palette_list_foreach(args->preview_list, add_to_palette_cb_helper, args); return true; } static PaletteListCallbackReturn color_list_selected(ColorObject* color_object, void *userdata) { color_list_add_color_object((ColorList *)userdata, color_object, 1); return PALETTE_LIST_CALLBACK_NO_UPDATE; } static gboolean preview_list_button_press_cb(GtkWidget *widget, GdkEventButton *event, BlendColorsArgs *args) { GtkWidget *menu; if (event->button == 1 && event->type == GDK_2BUTTON_PRESS){ //add_to_palette_cb(widget, args); //return true; }else if (event->button == 3 && event->type == GDK_BUTTON_PRESS){ GtkWidget* item ; gint32 button, event_time; menu = gtk_menu_new(); bool selection_avail = palette_list_get_selected_count(widget) != 0; item = gtk_menu_item_new_with_image(_("_Add to palette"), gtk_image_new_from_stock(GTK_STOCK_ADD, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(add_to_palette_cb), args); if (!selection_avail) gtk_widget_set_sensitive(item, false); item = gtk_menu_item_new_with_image(_("A_dd all to palette"), gtk_image_new_from_stock(GTK_STOCK_ADD, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(add_all_to_palette_cb), args); gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); if (selection_avail){ ColorList *color_list = color_list_new(); palette_list_forfirst_selected(args->preview_list, color_list_selected, color_list); if (color_list_get_count(color_list) != 0){ StandardMenu::appendMenu(menu, *color_list->colors.begin(), args->preview_list, args->gs); }else{ StandardMenu::appendMenu(menu); } color_list_destroy(color_list); }else{ StandardMenu::appendMenu(menu); } gtk_widget_show_all(GTK_WIDGET(menu)); button = event->button; event_time = event->time; gtk_menu_popup(GTK_MENU(menu), nullptr, nullptr, nullptr, nullptr, button, event_time); g_object_ref_sink(menu); g_object_unref(menu); return TRUE; } return FALSE; } static void update(GtkWidget *widget, BlendColorsArgs *args) { color_list_remove_all(args->preview_color_list); calc(args, true, 101); } static void reset_middle_color_cb(GtkWidget *widget, BlendColorsArgs *args) { Color a, b; gtk_color_get_color(GTK_COLOR(args->start_color), &a); gtk_color_get_color(GTK_COLOR(args->end_color), &b); color_multiply(&a, 0.5); color_multiply(&b, 0.5); color_add(&a, &b); gtk_color_set_color(GTK_COLOR(args->middle_color), &a, ""); update(0, args); } static gboolean color_button_press_cb(GtkWidget *widget, GdkEventButton *event, BlendColorsArgs *args) { GtkWidget *menu; if (event->button == 3 && event->type == GDK_BUTTON_PRESS){ GtkWidget* item ; gint32 button, event_time; menu = gtk_menu_new(); item = gtk_menu_item_new_with_mnemonic(_("_Reset")); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(reset_middle_color_cb), args); gtk_widget_show_all(GTK_WIDGET(menu)); button = event->button; event_time = event->time; gtk_menu_popup(GTK_MENU(menu), nullptr, nullptr, nullptr, nullptr, button, event_time); g_object_ref_sink(menu); g_object_unref(menu); return TRUE; } return FALSE; } static int set_rgb_color(BlendColorsArgs *args, ColorObject* color_object, uint32_t color_index) { Color color = color_object->getColor(); if (color_index == 1){ gtk_color_set_color(GTK_COLOR(args->start_color), &color, ""); }else if (color_index == 2){ gtk_color_set_color(GTK_COLOR(args->middle_color), &color, ""); }else if (color_index == 3){ gtk_color_set_color(GTK_COLOR(args->end_color), &color, ""); } update(0, args); return 0; } static int get_rgb_color(BlendColorsArgs *args, uint32_t color_index, ColorObject** color) { Color c; if (color_index == 1){ gtk_color_get_color(GTK_COLOR(args->start_color), &c); }else if (color_index == 2){ gtk_color_get_color(GTK_COLOR(args->middle_color), &c); }else if (color_index == 3){ gtk_color_get_color(GTK_COLOR(args->end_color), &c); } *color = color_list_new_color_object(args->gs->getColorList(), &c); BlendColorNameAssigner name_assigner(args->gs); const char *item_name[] = { "start", "middle", "end", }; name_assigner.assign(*color, &c, item_name[color_index - 1]); return 0; } static ColorObject* get_color_object(struct DragDrop* dd) { BlendColorsArgs* args = (BlendColorsArgs*)dd->userdata; ColorObject* color_object; if (get_rgb_color(args, (uintptr_t)dd->userdata2, &color_object) == 0){ return color_object; } return 0; } static int set_color_object_at(struct DragDrop* dd, ColorObject* color_object, int x, int y, bool move) { BlendColorsArgs* args = static_cast(dd->userdata); set_rgb_color(args, color_object, (uintptr_t)dd->userdata2); return 0; } static int source_get_color(BlendColorsArgs *args, ColorObject** color) { return -1; } static int source_set_color(BlendColorsArgs *args, ColorObject* color) { return -1; } static int source_activate(BlendColorsArgs *args) { update(0, args); return 0; } static int source_deactivate(BlendColorsArgs *args) { return 0; } static int source_destroy(BlendColorsArgs *args) { gint steps1 = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(args->steps1)); gint steps2 = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(args->steps2)); gint type = gtk_combo_box_get_active(GTK_COMBO_BOX(args->mix_type)); dynv_set_int32(args->params, "type", type); dynv_set_int32(args->params, "steps1", steps1); dynv_set_int32(args->params, "steps2", steps2); Color c; gtk_color_get_color(GTK_COLOR(args->start_color), &c); dynv_set_color(args->params, "start_color", &c); gtk_color_get_color(GTK_COLOR(args->middle_color), &c); dynv_set_color(args->params, "middle_color", &c); gtk_color_get_color(GTK_COLOR(args->end_color), &c); dynv_set_color(args->params, "end_color", &c); color_list_destroy(args->preview_color_list); dynv_system_release(args->params); gtk_widget_destroy(args->main); delete args; return 0; } static ColorSource* source_implement(ColorSource *source, GlobalState *gs, struct dynvSystem *dynv_namespace) { BlendColorsArgs *args = new BlendColorsArgs; args->params = dynv_system_ref(dynv_namespace); args->gs = gs; color_source_init(&args->source, source->identificator, source->hr_name); args->source.destroy = (int (*)(ColorSource *source))source_destroy; args->source.get_color = (int (*)(ColorSource *source, ColorObject** color))source_get_color; args->source.set_color = (int (*)(ColorSource *source, ColorObject* color))source_set_color; args->source.deactivate = (int (*)(ColorSource *source))source_deactivate; args->source.activate = (int (*)(ColorSource *source))source_activate; GtkWidget *table, *widget; GtkWidget *mix_type, *mix_steps; gint table_y; table = gtk_table_new(6, 2, FALSE); table_y = 0; struct DragDrop dd; dragdrop_init(&dd, gs); dd.userdata = args; dd.get_color_object = get_color_object; dd.set_color_object_at = set_color_object_at; Color c; color_set(&c, 0.5); gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Start:"),0,0,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); args->start_color = widget = gtk_color_new(); gtk_color_set_color(GTK_COLOR(args->start_color), dynv_get_color_wdc(args->params, "start_color", &c), ""); gtk_color_set_rounded(GTK_COLOR(widget), true); gtk_color_set_hcenter(GTK_COLOR(widget), true); gtk_color_set_roundness(GTK_COLOR(widget), 5); gtk_table_attach(GTK_TABLE(table), widget, 1, 2, table_y, table_y + 1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GTK_FILL, 0, 0); gtk_drag_dest_set( widget, GtkDestDefaults(GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_HIGHLIGHT), 0, 0, GDK_ACTION_COPY); gtk_drag_source_set( widget, GDK_BUTTON1_MASK, 0, 0, GDK_ACTION_COPY); dd.handler_map = dynv_system_get_handler_map(gs->getColorList()->params); dd.userdata2 = (void*)1; dragdrop_widget_attach(widget, DragDropFlags(DRAGDROP_SOURCE | DRAGDROP_DESTINATION), &dd); table_y++; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Middle:"),0,0,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); args->middle_color = widget = gtk_color_new(); g_signal_connect(G_OBJECT(widget), "button-press-event", G_CALLBACK(color_button_press_cb), args); gtk_color_set_color(GTK_COLOR(args->middle_color), dynv_get_color_wdc(args->params, "middle_color", &c), ""); gtk_color_set_rounded(GTK_COLOR(widget), true); gtk_color_set_hcenter(GTK_COLOR(widget), true); gtk_color_set_roundness(GTK_COLOR(widget), 5); gtk_table_attach(GTK_TABLE(table), widget, 1, 2, table_y, table_y + 1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GTK_FILL, 0, 0); gtk_drag_dest_set( widget, GtkDestDefaults(GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_HIGHLIGHT), 0, 0, GDK_ACTION_COPY); gtk_drag_source_set( widget, GDK_BUTTON1_MASK, 0, 0, GDK_ACTION_COPY); dd.handler_map = dynv_system_get_handler_map(gs->getColorList()->params); dd.userdata2 = (void*)2; dragdrop_widget_attach(widget, DragDropFlags(DRAGDROP_SOURCE | DRAGDROP_DESTINATION), &dd); table_y++; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("End:"),0,0,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); args->end_color = widget = gtk_color_new(); gtk_color_set_color(GTK_COLOR(args->end_color), dynv_get_color_wdc(args->params, "end_color", &c), ""); gtk_color_set_rounded(GTK_COLOR(widget), true); gtk_color_set_hcenter(GTK_COLOR(widget), true); gtk_color_set_roundness(GTK_COLOR(widget), 5); gtk_table_attach(GTK_TABLE(table), widget, 1, 2, table_y, table_y + 1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GTK_FILL, 0, 0); gtk_drag_dest_set( widget, GtkDestDefaults(GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_HIGHLIGHT), 0, 0, GDK_ACTION_COPY); gtk_drag_source_set( widget, GDK_BUTTON1_MASK, 0, 0, GDK_ACTION_COPY); dd.handler_map = dynv_system_get_handler_map(gs->getColorList()->params); dd.userdata2 = (void*)3; dragdrop_widget_attach(widget, DragDropFlags(DRAGDROP_SOURCE | DRAGDROP_DESTINATION), &dd); table_y = 0; GtkWidget* vbox = gtk_vbox_new(false, 0); gtk_box_pack_start(GTK_BOX(vbox), gtk_label_aligned_new(_("Type:"),0,0,0,0), false, false, 0); args->mix_type = mix_type = gtk_combo_box_text_new(); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(mix_type), _("RGB")); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(mix_type), _("HSV")); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(mix_type), _("LAB")); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(mix_type), _("LCH")); gtk_combo_box_set_active(GTK_COMBO_BOX(mix_type), dynv_get_int32_wd(args->params, "type", 0)); gtk_box_pack_start(GTK_BOX(vbox), mix_type, false, false, 0); g_signal_connect(G_OBJECT(mix_type), "changed", G_CALLBACK(update), args); gtk_table_attach(GTK_TABLE(table), vbox, 4, 5, table_y, table_y+3, GtkAttachOptions(GTK_FILL),GtkAttachOptions(GTK_FILL),5,0); table_y = 0; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Start steps:"),0,0,0,0),2,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); mix_steps = gtk_spin_button_new_with_range(1,255,1); gtk_spin_button_set_value(GTK_SPIN_BUTTON(mix_steps), dynv_get_int32_wd(args->params, "steps1", 3)); gtk_table_attach(GTK_TABLE(table), mix_steps,3,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); table_y++; args->steps1 = mix_steps; g_signal_connect(G_OBJECT(mix_steps), "value-changed", G_CALLBACK(update), args); gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("End steps:"),0,0,0,0),2,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); mix_steps = gtk_spin_button_new_with_range(1,255,1); gtk_spin_button_set_value(GTK_SPIN_BUTTON(mix_steps), dynv_get_int32_wd(args->params, "steps2", 3)); gtk_table_attach(GTK_TABLE(table), mix_steps,3,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); table_y++; args->steps2 = mix_steps; g_signal_connect(G_OBJECT(mix_steps), "value-changed", G_CALLBACK(update), args); table_y = 3; GtkWidget* preview; ColorList* preview_color_list = nullptr; gtk_table_attach(GTK_TABLE(table), preview = palette_list_preview_new(gs, false, false, gs->getColorList(), &preview_color_list), 0, 5, table_y, table_y+1 , GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL | GTK_EXPAND), 5, 5); args->preview_list = palette_list_get_widget(preview_color_list); GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(args->preview_list)); gtk_tree_selection_set_mode(selection, GTK_SELECTION_MULTIPLE); g_signal_connect(G_OBJECT(args->preview_list), "button-press-event", G_CALLBACK(preview_list_button_press_cb), args); table_y++; args->preview_color_list = preview_color_list; update(0, args); gtk_widget_show_all(table); args->main = table; args->source.widget = table; return (ColorSource*)args; } int blend_colors_source_register(ColorSourceManager *csm) { ColorSource *color_source = new ColorSource; color_source_init(color_source, "blend_colors", _("Blend colors")); color_source->implement = (ColorSource* (*)(ColorSource *source, GlobalState *gs, struct dynvSystem *dynv_namespace))source_implement; color_source->default_accelerator = GDK_KEY_b; color_source_manager_add_source(csm, color_source); return 0; } gpick-gpick-0.2.6rc1/source/BlendColors.h000066400000000000000000000033071315430016700201770ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_BLEND_COLORS_H_ #define GPICK_BLEND_COLORS_H_ struct ColorSourceManager; int blend_colors_source_register(ColorSourceManager *csm); #endif /* GPICK_BLEND_COLORS_H_ */ gpick-gpick-0.2.6rc1/source/BrightnessDarkness.cpp000066400000000000000000000350421315430016700221300ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "BrightnessDarkness.h" #include "ColorSource.h" #include "ColorSourceManager.h" #include "DragDrop.h" #include "GlobalState.h" #include "ToolColorNaming.h" #include "uiUtilities.h" #include "ColorList.h" #include "MathUtil.h" #include "ColorRYB.h" #include "gtk/ColorWidget.h" #include "gtk/Range2D.h" #include "uiColorInput.h" #include "CopyPaste.h" #include "Converter.h" #include "DynvHelpers.h" #include "Internationalisation.h" #include "color_names/ColorNames.h" #include "gtk/LayoutPreview.h" #include "layout/Layout.h" #include "layout/Style.h" #include "StandardMenu.h" #include #include #include #include #include #include using namespace std; using namespace layout; typedef struct BrightnessDarknessArgs{ ColorSource source; GtkWidget* main; GtkWidget* statusbar; Color color; GtkWidget *brightness_darkness; GtkWidget *layout_view; System* layout_system; Layouts* layouts; struct dynvSystem *params; GlobalState* gs; }BrightnessDarknessArgs; class BrightnessDarknessColorNameAssigner: public ToolColorNameAssigner { protected: stringstream m_stream; const char *m_ident; public: BrightnessDarknessColorNameAssigner(GlobalState *gs): ToolColorNameAssigner(gs) { } void assign(ColorObject *color_object, Color *color, const char *ident) { m_ident = ident; ToolColorNameAssigner::assign(color_object, color); } virtual std::string getToolSpecificName(ColorObject *color_object, const Color *color) { m_stream.str(""); m_stream << color_names_get(m_gs->getColorNames(), color, false) << " " << _("brightness darkness") << " " << m_ident; return m_stream.str(); } }; static void calc(BrightnessDarknessArgs *args, bool preview, bool save_settings) { double brightness = gtk_range_2d_get_x(GTK_RANGE_2D(args->brightness_darkness)); double darkness = gtk_range_2d_get_y(GTK_RANGE_2D(args->brightness_darkness)); if (save_settings){ dynv_set_float(args->params, "brightness", brightness); dynv_set_float(args->params, "darkness", brightness); } Color color, hsl_orig, hsl, r; color_copy(&args->color, &color); color_rgb_to_hsl(&color, &hsl_orig); Box* box; string name; for (int i = 1; i <= 4; i++){ color_copy(&hsl_orig, &hsl); hsl.hsl.lightness = mix_float(hsl.hsl.lightness, mix_float(hsl.hsl.lightness, 1, brightness), i / 4.0); //clamp_float(hsl.hsl.lightness + brightness / 8.0 * i, 0, 1); color_hsl_to_rgb(&hsl, &r); name = boost::str(boost::format("b%d") % i); box = args->layout_system->GetNamedBox(name.c_str()); if (box && box->style){ color_copy(&r, &box->style->color); } color_copy(&hsl_orig, &hsl); hsl.hsl.lightness = mix_float(hsl.hsl.lightness, mix_float(hsl.hsl.lightness, 0, darkness), i / 4.0); //clamp_float(hsl.hsl.lightness - darkness / 8.0 * i, 0, 1); color_hsl_to_rgb(&hsl, &r); name = boost::str(boost::format("c%d") % i); box = args->layout_system->GetNamedBox(name.c_str()); if (box && box->style){ color_copy(&r, &box->style->color); } } gtk_widget_queue_draw(GTK_WIDGET(args->layout_view)); } static void update(GtkWidget *widget, BrightnessDarknessArgs *args) { calc(args, true, false); } static int source_get_color(BrightnessDarknessArgs *args, ColorObject** color) { Style* style = 0; Color c; if (gtk_layout_preview_get_current_color(GTK_LAYOUT_PREVIEW(args->layout_view), &c) == 0){ if (gtk_layout_preview_get_current_style(GTK_LAYOUT_PREVIEW(args->layout_view), &style) != 0){ return -1; } *color = color_list_new_color_object(args->gs->getColorList(), &c); BrightnessDarknessColorNameAssigner name_assigner(args->gs); name_assigner.assign(*color, &c, style->human_name.c_str()); return 0; } return -1; } static int source_set_color(BrightnessDarknessArgs *args, ColorObject* color_object) { Color color = color_object->getColor(); color_copy(&color, &args->color); gtk_layout_preview_set_color_named(GTK_LAYOUT_PREVIEW(args->layout_view), &color, "main"); calc(args, true, false); return 0; } static ColorObject* get_color_object(struct DragDrop* dd) { BrightnessDarknessArgs* args = (BrightnessDarknessArgs*)dd->userdata; ColorObject* colorobject; if (source_get_color(args, &colorobject) == 0){ return colorobject; } return 0; } static int set_color_object_at(struct DragDrop* dd, ColorObject* color_object, int x, int y, bool move) { BrightnessDarknessArgs* args = (BrightnessDarknessArgs*)dd->userdata; Color color = color_object->getColor(); color_copy(&color, &args->color); gtk_layout_preview_set_color_named(GTK_LAYOUT_PREVIEW(args->layout_view), &color, "main"); calc(args, true, false); return 0; } static bool test_at(struct DragDrop* dd, int x, int y) { BrightnessDarknessArgs* args = (BrightnessDarknessArgs*)dd->userdata; gtk_layout_preview_set_focus_named(GTK_LAYOUT_PREVIEW(args->layout_view), "main"); return gtk_layout_preview_is_selected(GTK_LAYOUT_PREVIEW(args->layout_view)); } static void edit_cb(GtkWidget *widget, gpointer item) { BrightnessDarknessArgs* args = (BrightnessDarknessArgs*)item; ColorObject *color_object; ColorObject* new_color_object = nullptr; if (source_get_color(args, &color_object) == 0){ if (dialog_color_input_show(GTK_WINDOW(gtk_widget_get_toplevel(args->main)), args->gs, color_object, &new_color_object ) == 0){ source_set_color(args, new_color_object); new_color_object->release(); } color_object->release(); } } static void paste_cb(GtkWidget *widget, BrightnessDarknessArgs* args) { ColorObject* color_object; if (copypaste_get_color_object(&color_object, args->gs) == 0){ source_set_color(args, color_object); color_object->release(); } } static void add_to_palette_cb(GtkWidget *widget, gpointer item) { BrightnessDarknessArgs* args = (BrightnessDarknessArgs*)item; ColorObject *color_object; if (source_get_color(args, &color_object) == 0){ color_list_add_color_object(args->gs->getColorList(), color_object, 1); color_object->release(); } } static void add_all_to_palette_cb(GtkWidget *widget, BrightnessDarknessArgs *args) { ColorObject *color_object; BrightnessDarknessColorNameAssigner name_assigner(args->gs); for (list::iterator i = args->layout_system->styles.begin(); i != args->layout_system->styles.end(); i++){ color_object = color_list_new_color_object(args->gs->getColorList(), &(*i)->color); name_assigner.assign(color_object, &(*i)->color, (*i)->human_name.c_str()); color_list_add_color_object(args->gs->getColorList(), color_object, 1); color_object->release(); } } static gboolean button_press_cb(GtkWidget *widget, GdkEventButton *event, BrightnessDarknessArgs* args) { GtkWidget *menu; if (event->button == 1 && event->type == GDK_2BUTTON_PRESS){ ColorObject *color_object; if (source_get_color(args, &color_object) == 0){ color_list_add_color_object(args->gs->getColorList(), color_object, 1); color_object->release(); } return true; }else if (event->button == 3 && event->type == GDK_BUTTON_PRESS){ GtkWidget* item ; gint32 button, event_time; menu = gtk_menu_new(); bool selection_avail = gtk_layout_preview_is_selected(GTK_LAYOUT_PREVIEW(args->layout_view)); bool edit_avail = gtk_layout_preview_is_editable(GTK_LAYOUT_PREVIEW(args->layout_view)); item = gtk_menu_item_new_with_image(_("_Add to palette"), gtk_image_new_from_stock(GTK_STOCK_ADD, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(add_to_palette_cb), args); if (!selection_avail) gtk_widget_set_sensitive(item, false); item = gtk_menu_item_new_with_image(_("A_dd all to palette"), gtk_image_new_from_stock(GTK_STOCK_ADD, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(add_all_to_palette_cb), args); gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); if (selection_avail){ ColorObject* color_object; source_get_color(args, &color_object); StandardMenu::appendMenu(menu, color_object, args->gs); color_object->release(); }else{ StandardMenu::appendMenu(menu); } if (edit_avail){ gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); item = gtk_menu_item_new_with_image(_("_Edit..."), gtk_image_new_from_stock(GTK_STOCK_EDIT, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(edit_cb), args); if (!selection_avail) gtk_widget_set_sensitive(item, false); item = gtk_menu_item_new_with_image(_("_Paste"), gtk_image_new_from_stock(GTK_STOCK_PASTE, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(paste_cb), args); if (!selection_avail) gtk_widget_set_sensitive(item, false); if (copypaste_is_color_object_available(args->gs) != 0){ gtk_widget_set_sensitive(item, false); } } gtk_widget_show_all(GTK_WIDGET(menu)); button = event->button; event_time = event->time; gtk_menu_popup(GTK_MENU(menu), nullptr, nullptr, nullptr, nullptr, button, event_time); g_object_ref_sink(menu); g_object_unref(menu); return TRUE; } return FALSE; } static int source_destroy(BrightnessDarknessArgs *args) { if (args->layout_system) System::unref(args->layout_system); args->layout_system = 0; dynv_system_release(args->params); gtk_widget_destroy(args->main); delete args; return 0; } static int source_activate(BrightnessDarknessArgs *args) { auto chain = args->gs->getTransformationChain(); gtk_layout_preview_set_transformation_chain(GTK_LAYOUT_PREVIEW(args->layout_view), chain); gtk_statusbar_push(GTK_STATUSBAR(args->statusbar), gtk_statusbar_get_context_id(GTK_STATUSBAR(args->statusbar), "empty"), ""); return 0; } static int source_deactivate(BrightnessDarknessArgs *args) { dynv_set_color(args->params, "color", &args->color); calc(args, true, true); return 0; } static ColorSource* source_implement(ColorSource *source, GlobalState *gs, struct dynvSystem *dynv_namespace) { BrightnessDarknessArgs* args = new BrightnessDarknessArgs; args->params = dynv_system_ref(dynv_namespace); args->statusbar = gs->getStatusBar(); color_source_init(&args->source, source->identificator, source->hr_name); args->source.destroy = (int (*)(ColorSource *source))source_destroy; args->source.get_color = (int (*)(ColorSource *source, ColorObject** color))source_get_color; args->source.set_color = (int (*)(ColorSource *source, ColorObject* color))source_set_color; args->source.deactivate = (int (*)(ColorSource *source))source_deactivate; args->source.activate = (int (*)(ColorSource *source))source_activate; auto layouts = gs->getLayouts(); args->layouts = layouts; args->layout_system = 0; GtkWidget *hbox, *widget; hbox = gtk_hbox_new(FALSE, 0); struct DragDrop dd; dragdrop_init(&dd, gs); dd.userdata = args; dd.get_color_object = get_color_object; dd.set_color_object_at = set_color_object_at; dd.test_at = test_at; dd.handler_map = dynv_system_get_handler_map(gs->getColorList()->params); args->brightness_darkness = widget = gtk_range_2d_new(); gtk_range_2d_set_values(GTK_RANGE_2D(widget), dynv_get_float_wd(dynv_namespace, "brightness", 0.5), dynv_get_float_wd(dynv_namespace, "darkness", 0.5)); gtk_range_2d_set_axis(GTK_RANGE_2D(widget), _("Brightness"), _("Darkness")); g_signal_connect(G_OBJECT(widget), "values_changed", G_CALLBACK(update), args); gtk_box_pack_start(GTK_BOX(hbox), widget, false, false, 0); args->layout_view = widget = gtk_layout_preview_new(); g_signal_connect_after(G_OBJECT(widget), "button-press-event", G_CALLBACK(button_press_cb), args); gtk_box_pack_start(GTK_BOX(hbox), widget, false, false, 0); //setup drag&drop gtk_drag_dest_set( widget, GtkDestDefaults(GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_HIGHLIGHT), 0, 0, GDK_ACTION_COPY); gtk_drag_source_set( widget, GDK_BUTTON1_MASK, 0, 0, GDK_ACTION_COPY); dd.handler_map = dynv_system_get_handler_map(gs->getColorList()->params); dd.userdata2 = (void*)-1; dragdrop_widget_attach(widget, DragDropFlags(DRAGDROP_SOURCE | DRAGDROP_DESTINATION), &dd); args->gs = gs; System* layout_system = layouts_get(args->layouts, "std_layout_brightness_darkness"); gtk_layout_preview_set_system(GTK_LAYOUT_PREVIEW(args->layout_view), layout_system); if (args->layout_system) System::unref(args->layout_system); args->layout_system = layout_system; Color c; color_set(&c, 0.5); Color *color = dynv_get_color_wdc(dynv_namespace, "color", &c); color_copy(color, &args->color); gtk_layout_preview_set_color_named(GTK_LAYOUT_PREVIEW(args->layout_view), color, "main"); calc(args, true, false); gtk_widget_show_all(hbox); update(0, args); args->main = hbox; args->source.widget = hbox; return (ColorSource*)args; } int brightness_darkness_source_register(ColorSourceManager *csm) { ColorSource *color_source = new ColorSource; color_source_init(color_source, "brightness_darkness", _("Brightness Darkness")); color_source->implement = (ColorSource* (*)(ColorSource *source, GlobalState *gs, struct dynvSystem *dynv_namespace))source_implement; color_source->default_accelerator = GDK_KEY_d; color_source_manager_add_source(csm, color_source); return 0; } gpick-gpick-0.2.6rc1/source/BrightnessDarkness.h000066400000000000000000000033431315430016700215740ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_BRIGHTNESS_DARKNESS_H_ #define GPICK_BRIGHTNESS_DARKNESS_H_ struct ColorSourceManager; int brightness_darkness_source_register(ColorSourceManager *csm); #endif /* GPICK_BRIGHTNESS_DARKNESS_H_ */ gpick-gpick-0.2.6rc1/source/Clipboard.cpp000066400000000000000000000106601315430016700202230ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Clipboard.h" #include "Converter.h" #include "GlobalState.h" #include "ColorObject.h" #include "Color.h" #include "uiListPalette.h" #include "ColorList.h" #include #include using namespace std; static PaletteListCallbackReturn addToColorList(ColorObject* color_object, ColorList *color_list) { color_list_add_color_object(color_list, color_object, 1); return PALETTE_LIST_CALLBACK_NO_UPDATE; } static Converter *getConverter(Converters *converters, const char *converter_name) { if (converter_name != nullptr){ auto converter = converters_get(converters, converter_name); if (converter != nullptr) return converter; } return converters_get_first(converters, ConverterArrayType::copy); } void Clipboard::set(const std::string &value) { gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), value.c_str(), -1); gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), value.c_str(), -1); } void Clipboard::set(const ColorObject *color_object, GlobalState *gs, Converter *converter) { if (converter == nullptr) converter = converters_get_first(gs->getConverters(), ConverterArrayType::copy); string text_line; ConverterSerializePosition position; if (converters_color_serialize(converter, color_object, position, text_line) == 0){ set(text_line); } } void Clipboard::set(GtkWidget *palette_widget, GlobalState *gs, Converter *converter) { if (converter == nullptr) converter = converters_get_first(gs->getConverters(), ConverterArrayType::copy); stringstream text(ios::out); ColorList *color_list = color_list_new(); palette_list_foreach_selected(palette_widget, (PaletteListCallback)addToColorList, color_list); string text_line; ConverterSerializePosition position(color_list->colors.size()); if (position.count > 0){ for (ColorList::iter i = color_list->colors.begin(); i != color_list->colors.end(); ++i){ if (position.index + 1 == position.count) position.last = true; if (converters_color_serialize(converter, *i, position, text_line) == 0){ if (position.first){ text << text_line; position.first = false; }else{ text << endl << text_line; } position.index++; } } } color_list_destroy(color_list); text_line = text.str(); if (text_line.length() > 0){ set(text_line); } } void Clipboard::set(const Color &color, GlobalState *gs, Converter *converter) { ColorObject color_object("", color); set(&color_object, gs, converter); } void Clipboard::set(const ColorObject *color_object, GlobalState *gs, const char *converter_name) { set(color_object, gs, getConverter(gs->getConverters(), converter_name)); } void Clipboard::set(const Color &color, GlobalState *gs, const char *converter_name) { set(color, gs, getConverter(gs->getConverters(), converter_name)); } void Clipboard::set(GtkWidget *palette_widget, GlobalState *gs, const char *converter_name) { set(palette_widget, gs, getConverter(gs->getConverters(), converter_name)); } gpick-gpick-0.2.6rc1/source/Clipboard.h000066400000000000000000000045331315430016700176720ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_CLIPBOARD_H_ #define GPICK_CLIPBOARD_H_ #include class ColorObject; class GlobalState; class Converter; struct Color; typedef struct _GtkWidget GtkWidget; class Clipboard { public: static void set(const std::string &value); static void set(const ColorObject *color_object, GlobalState *gs, const char *converter_name = nullptr); static void set(const Color &color, GlobalState *gs, const char *converter_name = nullptr); static void set(GtkWidget *palette_widget, GlobalState *gs, const char *converter_name = nullptr); static void set(const ColorObject *color_object, GlobalState *gs, Converter *converter); static void set(const Color &color, GlobalState *gs, Converter *converter); static void set(GtkWidget *palette_widget, GlobalState *gs, Converter *converter); }; #endif /* GPICK_CLIPBOARD_H_ */ gpick-gpick-0.2.6rc1/source/ClosestColors.cpp000066400000000000000000000406311315430016700211230ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ClosestColors.h" #include "ColorObject.h" #include "ColorSource.h" #include "ColorSourceManager.h" #include "DragDrop.h" #include "GlobalState.h" #include "ToolColorNaming.h" #include "uiUtilities.h" #include "ColorList.h" #include "gtk/ColorWidget.h" #include "uiColorInput.h" #include "CopyPaste.h" #include "DynvHelpers.h" #include "Internationalisation.h" #include "color_names/ColorNames.h" #include "StandardMenu.h" #include "Clipboard.h" #include #include #include using namespace std; struct ClosestColorsArgs { ColorSource source; GtkWidget *main, *status_bar, *color, *last_focused_color, *color_previews; GtkWidget *closest_colors[9]; dynvSystem *params; GlobalState* gs; }; class ClosestColorsColorNameAssigner: public ToolColorNameAssigner { protected: stringstream m_stream; const char *m_ident; public: ClosestColorsColorNameAssigner(GlobalState *gs): ToolColorNameAssigner(gs) { } void assign(ColorObject *color_object, const Color *color, const char *ident) { m_ident = ident; ToolColorNameAssigner::assign(color_object, color); } virtual std::string getToolSpecificName(ColorObject *color_object, const Color *color) { m_stream.str(""); m_stream << color_names_get(m_gs->getColorNames(), color, false) << " " << _("closest color") << " " << m_ident; return m_stream.str(); } }; static int source_set_color(ClosestColorsArgs *args, ColorObject *color_object); static void calc(ClosestColorsArgs *args, bool preview, bool save_settings) { Color color; gtk_color_get_color(GTK_COLOR(args->color), &color); vector> colors; color_names_find_nearest(args->gs->getColorNames(), color, 9, colors); for (size_t i = 0; i < 9; ++i){ if (i < colors.size()){ gtk_color_set_color(GTK_COLOR(args->closest_colors[i]), &colors[i].second, colors[i].first); gtk_widget_set_sensitive(args->closest_colors[i], true); }else{ gtk_widget_set_sensitive(args->closest_colors[i], false); } } } static void update(GtkWidget *widget, ClosestColorsArgs *args) { calc(args, true, false); } static void on_color_paste(GtkWidget *widget, ClosestColorsArgs *args) { ColorObject *color_object; if (copypaste_get_color_object(&color_object, args->gs) == 0){ source_set_color(args, color_object); color_object->release(); } } static void on_color_edit(GtkWidget *widget, ClosestColorsArgs *args) { GtkWidget* color_widget = GTK_WIDGET(g_object_get_data(G_OBJECT(widget), "color_widget")); Color c; gtk_color_get_color(GTK_COLOR(color_widget), &c); ColorObject* color_object = color_list_new_color_object(args->gs->getColorList(), &c); ColorObject* new_color_object = nullptr; if (dialog_color_input_show(GTK_WINDOW(gtk_widget_get_toplevel(args->main)), args->gs, color_object, &new_color_object) == 0){ source_set_color(args, color_object); new_color_object->release(); } color_object->release(); } static boost::format format_ignore_arg_errors(const std::string &f_string) { boost::format fmter(f_string); fmter.exceptions(boost::io::all_error_bits ^ (boost::io::too_many_args_bit | boost::io::too_few_args_bit)); return fmter; } static string identify_color_widget(GtkWidget *widget, ClosestColorsArgs *args) { if (args->color == widget){ return _("target"); }else for (int i = 0; i < 9; ++i){ if (args->closest_colors[i] == widget){ try{ return (format_ignore_arg_errors(_("match %d")) % (i + 1)).str(); }catch(const boost::io::format_error &e){ return (format_ignore_arg_errors("match %d") % (i + 1)).str(); } } } return "unknown"; } static void add_color_to_palette(GtkWidget *color_widget, ClosestColorsColorNameAssigner &name_assigner, ClosestColorsArgs *args) { Color c; ColorObject *color_object; string widget_ident; gtk_color_get_color(GTK_COLOR(color_widget), &c); color_object = color_list_new_color_object(args->gs->getColorList(), &c); widget_ident = identify_color_widget(color_widget, args); name_assigner.assign(color_object, &c, widget_ident.c_str()); color_list_add_color_object(args->gs->getColorList(), color_object, 1); color_object->release(); } static void on_color_add_to_palette(GtkWidget *widget, ClosestColorsArgs *args) { GtkWidget *color_widget = GTK_WIDGET(g_object_get_data(G_OBJECT(widget), "color_widget")); ClosestColorsColorNameAssigner name_assigner(args->gs); add_color_to_palette(color_widget, name_assigner, args); } static void on_color_add_all_to_palette(GtkWidget *widget, ClosestColorsArgs *args) { ClosestColorsColorNameAssigner name_assigner(args->gs); add_color_to_palette(args->color, name_assigner, args); for (int i = 0; i < 9; ++i){ add_color_to_palette(args->closest_colors[i], name_assigner, args); } } static gboolean color_focus_in_cb(GtkWidget *widget, GdkEventFocus *event, ClosestColorsArgs *args) { args->last_focused_color = widget; return false; } static void on_color_activate(GtkWidget *widget, ClosestColorsArgs *args) { ClosestColorsColorNameAssigner name_assigner(args->gs); add_color_to_palette(widget, name_assigner, args); } static void color_show_menu(GtkWidget *widget, ClosestColorsArgs *args, GdkEventButton *event) { GtkWidget *menu; GtkWidget* item; menu = gtk_menu_new(); item = gtk_menu_item_new_with_image(_("_Add to palette"), gtk_image_new_from_stock(GTK_STOCK_ADD, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(on_color_add_to_palette), args); g_object_set_data(G_OBJECT(item), "color_widget", widget); item = gtk_menu_item_new_with_image(_("A_dd all to palette"), gtk_image_new_from_stock(GTK_STOCK_ADD, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(on_color_add_all_to_palette), args); g_object_set_data(G_OBJECT(item), "color_widget", widget); gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); Color c; gtk_color_get_color(GTK_COLOR(widget), &c); ColorObject* color_object = color_list_new_color_object(args->gs->getColorList(), &c); StandardMenu::appendMenu(menu, color_object, args->gs); color_object->release(); if (args->color == widget){ gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); item = gtk_menu_item_new_with_image(_("_Edit..."), gtk_image_new_from_stock(GTK_STOCK_EDIT, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(on_color_edit), args); g_object_set_data(G_OBJECT(item), "color_widget", widget); item = gtk_menu_item_new_with_image(_("_Paste"), gtk_image_new_from_stock(GTK_STOCK_PASTE, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(on_color_paste), args); g_object_set_data(G_OBJECT(item), "color_widget", widget); if (copypaste_is_color_object_available(args->gs) != 0){ gtk_widget_set_sensitive(item, false); } } gtk_widget_show_all(GTK_WIDGET(menu)); gint32 button, event_time; if (event){ button = event->button; event_time = event->time; }else{ button = 0; event_time = gtk_get_current_event_time(); } gtk_menu_popup(GTK_MENU(menu), nullptr, nullptr, nullptr, nullptr, button, event_time); g_object_ref_sink(menu); g_object_unref(menu); } static gboolean on_color_button_press(GtkWidget *widget, GdkEventButton *event, ClosestColorsArgs *args) { if (event->button == 3 && event->type == GDK_BUTTON_PRESS){ color_show_menu(widget, args, event); } return false; } static void on_color_popup_menu(GtkWidget *widget, ClosestColorsArgs *args) { color_show_menu(widget, args, nullptr); } static gboolean on_color_key_press(GtkWidget *widget, GdkEventKey *event, ClosestColorsArgs *args) { guint modifiers = gtk_accelerator_get_default_mod_mask(); Color c; ColorObject* color_object; GtkWidget* color_widget = widget; switch (event->keyval){ case GDK_KEY_c: if ((event->state & modifiers) == GDK_CONTROL_MASK){ gtk_color_get_color(GTK_COLOR(color_widget), &c); color_object = color_list_new_color_object(args->gs->getColorList(), &c); Clipboard::set(color_object, args->gs); color_object->release(); return true; } return false; break; case GDK_KEY_v: if ((event->state & modifiers) == GDK_CONTROL_MASK){ if (copypaste_get_color_object(&color_object, args->gs) == 0){ source_set_color(args, color_object); color_object->release(); } return true; } return false; break; default: return false; break; } return false; } static int source_destroy(ClosestColorsArgs *args) { Color c; gtk_color_get_color(GTK_COLOR(args->color), &c); dynv_set_color(args->params, "color", &c); dynv_system_release(args->params); gtk_widget_destroy(args->main); delete args; return 0; } static int source_get_color(ClosestColorsArgs *args, ColorObject **color) { ClosestColorsColorNameAssigner name_assigner(args->gs); Color c; string widget_ident; if (args->last_focused_color){ gtk_color_get_color(GTK_COLOR(args->last_focused_color), &c); widget_ident = identify_color_widget(args->last_focused_color, args); }else{ gtk_color_get_color(GTK_COLOR(args->closest_colors[0]), &c); widget_ident = identify_color_widget(args->closest_colors[0], args); } *color = color_list_new_color_object(args->gs->getColorList(), &c); name_assigner.assign(*color, &c, widget_ident.c_str()); return 0; } static int source_set_color(ClosestColorsArgs *args, ColorObject *color_object) { Color color = color_object->getColor(); gtk_color_set_color(GTK_COLOR(args->color), &color, ""); update(0, args); return 0; } static int source_activate(ClosestColorsArgs *args) { auto chain = args->gs->getTransformationChain(); gtk_color_set_transformation_chain(GTK_COLOR(args->color), chain); for (int i = 0; i < 9; ++i){ gtk_color_set_transformation_chain(GTK_COLOR(args->closest_colors[i]), chain); } gtk_statusbar_push(GTK_STATUSBAR(args->status_bar), gtk_statusbar_get_context_id(GTK_STATUSBAR(args->status_bar), "empty"), ""); return 0; } static int source_deactivate(ClosestColorsArgs *args) { calc(args, true, true); return 0; } static ColorObject* get_color_object(DragDrop* dd) { ClosestColorsArgs *args = static_cast(dd->userdata); ColorObject* color_object; if (source_get_color(args, &color_object) == 0){ return color_object; } return 0; } static int set_color_object_at(DragDrop* dd, ColorObject* color_object, int x, int y, bool move) { ClosestColorsArgs *args = static_cast(dd->userdata); source_set_color(args, color_object); return 0; } ColorSource* source_implement(ColorSource *source, GlobalState *gs, dynvSystem *dynv_namespace) { ClosestColorsArgs *args = new ClosestColorsArgs; args->params = dynv_system_ref(dynv_namespace); args->status_bar = gs->getStatusBar(); color_source_init(&args->source, source->identificator, source->hr_name); args->source.destroy = (int (*)(ColorSource *source))source_destroy; args->source.get_color = (int (*)(ColorSource *source, ColorObject** color))source_get_color; args->source.set_color = (int (*)(ColorSource *source, ColorObject* color))source_set_color; args->source.deactivate = (int (*)(ColorSource *source))source_deactivate; args->source.activate = (int (*)(ColorSource *source))source_activate; GtkWidget *table, *vbox, *hbox, *widget, *hbox2; hbox = gtk_hbox_new(false, 0); vbox = gtk_vbox_new(false, 0); gtk_box_pack_start(GTK_BOX(hbox), vbox, true, true, 5); args->color_previews = gtk_table_new(3, 3, false); gtk_box_pack_start(GTK_BOX(vbox), args->color_previews, true, true, 0); DragDrop dd; dragdrop_init(&dd, gs); dd.userdata = args; dd.get_color_object = get_color_object; dd.set_color_object_at = set_color_object_at; widget = gtk_color_new(); gtk_color_set_rounded(GTK_COLOR(widget), true); gtk_color_set_hcenter(GTK_COLOR(widget), true); gtk_color_set_roundness(GTK_COLOR(widget), 5); gtk_table_attach(GTK_TABLE(args->color_previews), widget, 0, 3, 0, 1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL | GTK_EXPAND), 0, 0); args->color = widget; g_signal_connect(G_OBJECT(widget), "button-press-event", G_CALLBACK(on_color_button_press), args); g_signal_connect(G_OBJECT(widget), "activated", G_CALLBACK(on_color_activate), args); g_signal_connect(G_OBJECT(widget), "key_press_event", G_CALLBACK(on_color_key_press), args); g_signal_connect(G_OBJECT(widget), "popup-menu", G_CALLBACK(on_color_popup_menu), args); g_signal_connect(G_OBJECT(widget), "focus-in-event", G_CALLBACK(color_focus_in_cb), args); gtk_widget_set_size_request(widget, 30, 30); //setup drag&drop gtk_drag_dest_set(widget, GtkDestDefaults(GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_HIGHLIGHT), 0, 0, GDK_ACTION_COPY); gtk_drag_source_set( widget, GDK_BUTTON1_MASK, 0, 0, GDK_ACTION_COPY); dd.handler_map = dynv_system_get_handler_map(gs->getColorList()->params); dd.userdata2 = (void*)-1; dragdrop_widget_attach(widget, DragDropFlags(DRAGDROP_SOURCE | DRAGDROP_DESTINATION), &dd); for (int i = 0; i < 3; ++i){ for (int j = 0; j < 3; ++j){ widget = gtk_color_new(); gtk_color_set_rounded(GTK_COLOR(widget), true); gtk_color_set_hcenter(GTK_COLOR(widget), true); gtk_color_set_roundness(GTK_COLOR(widget), 5); gtk_table_attach(GTK_TABLE(args->color_previews), widget, i, i + 1, j + 1, j + 2, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL | GTK_EXPAND), 0, 0); args->closest_colors[i + j * 3] = widget; g_signal_connect(G_OBJECT(widget), "button-press-event", G_CALLBACK(on_color_button_press), args); g_signal_connect(G_OBJECT(widget), "activated", G_CALLBACK(on_color_activate), args); g_signal_connect(G_OBJECT(widget), "key_press_event", G_CALLBACK(on_color_key_press), args); g_signal_connect(G_OBJECT(widget), "popup-menu", G_CALLBACK(on_color_popup_menu), args); g_signal_connect(G_OBJECT(widget), "focus-in-event", G_CALLBACK(color_focus_in_cb), args); gtk_widget_set_size_request(widget, 30, 30); gtk_drag_source_set(widget, GDK_BUTTON1_MASK, 0, 0, GDK_ACTION_COPY); dd.handler_map = dynv_system_get_handler_map(gs->getColorList()->params); dd.userdata2 = reinterpret_cast(i + j * 3); dragdrop_widget_attach(widget, DragDropFlags(DRAGDROP_SOURCE), &dd); } } Color c; color_set(&c, 0.5); gtk_color_set_color(GTK_COLOR(args->color), dynv_get_color_wdc(args->params, "color", &c), ""); hbox2 = gtk_hbox_new(false, 0); gtk_box_pack_start(GTK_BOX(vbox), hbox2, false, false, 0); table = gtk_table_new(5, 2, false); gtk_box_pack_start(GTK_BOX(hbox2), table, true, true, 0); args->gs = gs; gtk_widget_show_all(hbox); update(0, args); args->main = hbox; args->source.widget = hbox; return (ColorSource*)args; } int closest_colors_source_register(ColorSourceManager *csm) { ColorSource *color_source = new ColorSource; color_source_init(color_source, "closest_colors", _("Closest colors")); color_source->implement = source_implement; color_source->default_accelerator = GDK_KEY_c; color_source_manager_add_source(csm, color_source); return 0; } gpick-gpick-0.2.6rc1/source/ClosestColors.h000066400000000000000000000033151315430016700205660ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_CLOSEST_COLORS_H_ #define GPICK_CLOSEST_COLORS_H_ struct ColorSourceManager; int closest_colors_source_register(ColorSourceManager *csm); #endif /* GPICK_CLOSEST_COLORS_H_ */ gpick-gpick-0.2.6rc1/source/Color.cpp000066400000000000000000000506471315430016700174130ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Color.h" #include #include "MathUtil.h" #include using namespace std; // Constant used for lab->xyz transform. Should be calculated with maximum accuracy possible. #define EPSILON (216.0 / 24389.0) static vector3 references[][2] = { {{{{109.850, 100.000, 35.585}}}, {{{111.144, 100.000, 35.200}}}}, {{{{ 98.074, 100.000, 118.232}}}, {{{ 97.285, 100.000, 116.145}}}}, {{{{ 96.422, 100.000, 82.521}}}, {{{ 96.720, 100.000, 81.427}}}}, {{{{ 95.682, 100.000, 92.149}}}, {{{ 95.799, 100.000, 90.926}}}}, {{{{ 95.047, 100.000, 108.883}}}, {{{ 94.811, 100.000, 107.304}}}}, {{{{ 94.972, 100.000, 122.638}}}, {{{ 94.416, 100.000, 120.641}}}}, {{{{ 99.187, 100.000, 67.395}}}, {{{103.280, 100.000, 69.026}}}}, {{{{ 95.044, 100.000, 108.755}}}, {{{ 95.792, 100.000, 107.687}}}}, {{{{100.966, 100.000, 64.370}}}, {{{103.866, 100.000, 65.627}}}}, }; static matrix3x3 sRGB_transformation; static matrix3x3 sRGB_transformation_inverted; static matrix3x3 d65_d50_adaptation_matrix; static matrix3x3 d50_d65_adaptation_matrix; void color_init() { // constants used below are sRGB working space red, green and blue primaries for D65 reference white color_get_working_space_matrix(0.6400, 0.3300, 0.3000, 0.6000, 0.1500, 0.0600, color_get_reference(REFERENCE_ILLUMINANT_D65, REFERENCE_OBSERVER_2), &sRGB_transformation); matrix3x3_inverse(&sRGB_transformation, &sRGB_transformation_inverted); color_get_chromatic_adaptation_matrix(color_get_reference(REFERENCE_ILLUMINANT_D65, REFERENCE_OBSERVER_2), color_get_reference(REFERENCE_ILLUMINANT_D50, REFERENCE_OBSERVER_2), &d65_d50_adaptation_matrix); color_get_chromatic_adaptation_matrix(color_get_reference(REFERENCE_ILLUMINANT_D50, REFERENCE_OBSERVER_2), color_get_reference(REFERENCE_ILLUMINANT_D65, REFERENCE_OBSERVER_2), &d50_d65_adaptation_matrix); } void color_rgb_to_hsv(const Color* a, Color* b) { float min, max, delta; max = max_float_3(a->rgb.red, a->rgb.green, a->rgb.blue); min = min_float_3(a->rgb.red, a->rgb.green, a->rgb.blue); delta = max - min; b->hsv.value = max; if (max != 0.0f) b->hsv.saturation = delta / max; else b->hsv.saturation = 0.0f; if (b->hsv.saturation == 0.0f) { b->hsv.hue = 0.0f; } else { if (a->rgb.red == max) b->hsv.hue = (a->rgb.green - a->rgb.blue) / delta; else if (a->rgb.green == max) b->hsv.hue = 2.0f + (a->rgb.blue - a->rgb.red) / delta; else if (a->rgb.blue == max) b->hsv.hue = 4.0f + (a->rgb.red - a->rgb.green) / delta; b->hsv.hue /= 6.0f; if (b->hsv.hue < 0.0f) b->hsv.hue += 1.0f; if (b->hsv.hue >= 1.0f) b->hsv.hue -= 1.0f; } } void color_hsv_to_rgb(const Color* a, Color* b) { float h,v, f, x, y, z; int i; v = a->hsv.value; if (a->hsv.saturation == 0.0f) { b->rgb.red = b->rgb.green = b->rgb.blue = a->hsv.value; } else { h = (a->hsv.hue - floor(a->hsv.hue)) * 6.0f; i = int(h); f = h - floor(h); x = v * (1.0f - a->hsv.saturation) ; y = v * (1.0f - (a->hsv.saturation * f)); z = v * (1.0f - (a->hsv.saturation * (1.0f - f))); if (i == 0){ b->rgb.red = v; b->rgb.green = z; b->rgb.blue = x; }else if (i == 1){ b->rgb.red = y; b->rgb.green = v; b->rgb.blue = x; }else if (i == 2){ b->rgb.red = x; b->rgb.green = v; b->rgb.blue = z; }else if (i == 3){ b->rgb.red = x; b->rgb.green = y; b->rgb.blue = v; }else if (i == 4){ b->rgb.red = z; b->rgb.green = x; b->rgb.blue = v; }else{ b->rgb.red = v; b->rgb.green = x; b->rgb.blue = y; } } } void color_rgb_to_xyz(const Color* a, Color* b, const matrix3x3* transformation) { float R=a->rgb.red, G=a->rgb.green, B=a->rgb.blue; if (R>0.04045){ R=pow(((R+0.055)/1.055),2.4); }else{ R=R/12.92; } if (G>0.04045){ G=pow(((G+0.055)/1.055),2.4); }else{ G=G/12.92; } if (B>0.04045){ B=pow(((B+0.055)/1.055),2.4); }else{ B=B/12.92; } vector3 rgb; rgb.x = R; rgb.y = G; rgb.z = B; vector3_multiply_matrix3x3(&rgb, transformation, &rgb); b->xyz.x = rgb.x; b->xyz.y = rgb.y; b->xyz.z = rgb.z; } void color_xyz_to_rgb(const Color* a, Color* b, const matrix3x3* transformation_inverted) { vector3 rgb; float R,G,B; vector3_multiply_matrix3x3((vector3*)a, transformation_inverted, &rgb); R=rgb.x; G=rgb.y; B=rgb.z; if (R>0.0031308){ R=1.055*(pow(R,1/2.4f))-0.055; }else{ R=12.92*R; } if (G>0.0031308){ G=1.055*(pow(G,1/2.4f))-0.055; }else{ G=12.92*G; } if(B>0.0031308){ B=1.055*(pow(B,1/2.4f))-0.055; }else{ B=12.92*B; } b->rgb.red=R; b->rgb.green=G; b->rgb.blue=B; } void color_rgb_to_lab(const Color* a, Color* b, const vector3* reference_white, const matrix3x3* transformation, const matrix3x3* adaptation_matrix) { Color c; color_rgb_to_xyz(a, &c, transformation); color_xyz_chromatic_adaptation(&c, &c, adaptation_matrix); color_xyz_to_lab(&c, b, reference_white); } void color_lab_to_rgb(const Color* a, Color* b, const vector3* reference_white, const matrix3x3* transformation_inverted, const matrix3x3* adaptation_matrix_inverted) { Color c; color_lab_to_xyz(a, &c, reference_white); color_xyz_chromatic_adaptation(&c, &c, adaptation_matrix_inverted); color_xyz_to_rgb(&c, b, transformation_inverted); } void color_copy(const Color* a, Color* b) { b->m.m1 = a->m.m1; b->m.m2 = a->m.m2; b->m.m3 = a->m.m3; b->m.m4 = a->m.m4; } void color_add(Color* a, const Color* b) { a->m.m1 += b->m.m1; a->m.m2 += b->m.m2; a->m.m3 += b->m.m3; a->m.m4 += b->m.m4; } void color_multiply(Color* a, float b) { a->m.m1 *= b; a->m.m2 *= b; a->m.m3 *= b; a->m.m4 *= b; } void color_zero(Color* a) { a->m.m1 = 0; a->m.m2 = 0; a->m.m3 = 0; a->m.m4 = 0; } void color_get_contrasting(const Color* a, Color* b) { Color t; color_rgb_to_lab(a, &t, color_get_reference(REFERENCE_ILLUMINANT_D50, REFERENCE_OBSERVER_2), &sRGB_transformation, &d65_d50_adaptation_matrix); if (t.lab.L > 50){ t.hsv.value=0; }else{ t.hsv.value=1; } t.hsv.saturation=0; t.hsv.hue=0; color_hsv_to_rgb(&t, b); } void color_set(Color* a, float value) { a->rgb.red = a->rgb.green = a->rgb.blue = value; a->ma[3] = 0; } void color_set(Color* a, float red, float green, float blue) { a->rgb.red = red; a->rgb.green = green; a->rgb.blue = blue; a->ma[3] = 0; } void color_set(Color* a, int red, int green, int blue) { a->rgb.red = red / 255.0; a->rgb.green = green / 255.0; a->rgb.blue = blue / 255.0; a->ma[3] = 0; } Color* color_new() { return new Color; } void color_destroy(Color *a) { delete a; } void color_rgb_to_hsl(const Color* a, Color* b) { float min, max, delta; min = min_float_3(a->rgb.red, a->rgb.green, a->rgb.blue); max = max_float_3(a->rgb.red, a->rgb.green, a->rgb.blue); delta = max - min; b->hsl.lightness = (max + min) / 2; if (delta == 0) { b->hsl.hue = 0; b->hsl.saturation = 0; } else { if (b->hsl.lightness < 0.5) { b->hsl.saturation = delta / (max + min); } else { b->hsl.saturation = delta / (2 - max - min); } if (a->rgb.red == max) b->hsv.hue = (a->rgb.green - a->rgb.blue) / delta; else if (a->rgb.green == max) b->hsv.hue = 2.0f + (a->rgb.blue - a->rgb.red) / delta; else if (a->rgb.blue == max) b->hsv.hue = 4.0f + (a->rgb.red - a->rgb.green) / delta; b->hsv.hue /= 6.0f; if (b->hsv.hue < 0.0f) b->hsv.hue += 1.0f; if (b->hsv.hue >= 1.0f) b->hsv.hue -= 1.0f; } } void color_hsl_to_rgb(const Color* a, Color* b) { if (a->hsl.saturation == 0) { b->rgb.red = b->rgb.green = b->rgb.blue = a->hsl.lightness; } else { float q, p, R, G, B; if (a->hsl.lightness < 0.5) q = a->hsl.lightness * (1.0 + a->hsl.saturation); else q = a->hsl.lightness + a->hsl.saturation - a->hsl.lightness * a->hsl.saturation; p = 2 * a->hsl.lightness - q; R = a->hsl.hue+1/3.0; G = a->hsl.hue; B = a->hsl.hue-1/3.0; if (R>1) R-=1; if (B<0) B+=1; if (6.0 * R < 1) b->rgb.red = p + (q - p) * 6.0 * R; else if (2.0 * R < 1) b->rgb.red = q; else if (3.0 * R < 2) b->rgb.red = p + (q - p) * ((2.0 / 3.0) - R) * 6.0; else b->rgb.red = p; if (6.0 * G < 1) b->rgb.green = p + (q - p) * 6.0 * G; else if (2.0 * G < 1) b->rgb.green = q; else if (3.0 * G < 2) b->rgb.green = p + (q - p) * ((2.0 / 3.0) - G) * 6.0; else b->rgb.green = p; if (6.0 * B < 1) b->rgb.blue = p + (q - p) * 6.0 * B; else if (2.0 * B < 1) b->rgb.blue = q; else if (3.0 * B < 2) b->rgb.blue = p + (q - p) * ((2.0 / 3.0) - B) * 6.0; else b->rgb.blue = p; } } void color_lab_to_lch(const Color* a, Color* b) { double H; if (a->lab.a == 0 && a->lab.b == 0){ H = 0; }else{ H = atan2(a->lab.b, a->lab.a); } H *= 180.0 / PI; if (H < 0) H += 360; if (H >= 360) H -= 360; b->lch.L = a->lab.L; b->lch.C = sqrt(a->lab.a * a->lab.a + a->lab.b * a->lab.b); b->lch.h = H; } void color_lch_to_lab(const Color* a, Color* b) { b->lab.L = a->lch.L; b->lab.a = a->lch.C * cos(a->lch.h * PI / 180.0); b->lab.b = a->lch.C * sin(a->lch.h * PI / 180.0); } void color_rgb_to_lch_d50(const Color* a, Color* b) { Color c; color_rgb_to_lab(a, &c, color_get_reference(REFERENCE_ILLUMINANT_D50, REFERENCE_OBSERVER_2), &sRGB_transformation, &d65_d50_adaptation_matrix); color_lab_to_lch(&c, b); } void color_lch_to_rgb_d50(const Color* a, Color* b) { Color c; color_lch_to_lab(a, &c); color_lab_to_rgb(&c, b, color_get_reference(REFERENCE_ILLUMINANT_D50, REFERENCE_OBSERVER_2), &sRGB_transformation_inverted, &d50_d65_adaptation_matrix); } void color_rgb_to_lch(const Color* a, Color* b, const vector3* reference_white, const matrix3x3* transformation, const matrix3x3* adaptation_matrix) { Color c; color_rgb_to_lab(a, &c, reference_white, transformation, adaptation_matrix); color_lab_to_lch(&c, b); } void color_lch_to_rgb(const Color* a, Color* b, const vector3* reference_white, const matrix3x3* transformation_inverted, const matrix3x3* adaptation_matrix_inverted) { Color c; color_lch_to_lab(a, &c); color_lab_to_rgb(&c, b, reference_white, transformation_inverted, adaptation_matrix_inverted); } void color_rgb_to_lab_d50(const Color* a, Color* b) { color_rgb_to_lab(a, b, color_get_reference(REFERENCE_ILLUMINANT_D50, REFERENCE_OBSERVER_2), &sRGB_transformation, &d65_d50_adaptation_matrix); } void color_lab_to_rgb_d50(const Color* a, Color* b) { color_lab_to_rgb(a, b, color_get_reference(REFERENCE_ILLUMINANT_D50, REFERENCE_OBSERVER_2), &sRGB_transformation_inverted, &d50_d65_adaptation_matrix); } #define Kk (24389.0 / 27.0) void color_xyz_to_lab(const Color* a, Color* b, const vector3* reference_white) { float X,Y,Z; X = a->xyz.x / reference_white->x; //95.047f; Y = a->xyz.y / reference_white->y; //100.000f; Z = a->xyz.z / reference_white->z; //108.883f; if (X>EPSILON){ X=pow(X,1.0f/3.0f); }else{ X=(Kk*X+16.0f)/116.0f; } if (Y>EPSILON){ Y=pow(Y,1.0f/3.0f); }else{ Y=(Kk*Y+16.0f)/116.0f; } if (Z>EPSILON){ Z=pow(Z,1.0f/3.0f); }else{ Z=(Kk*Z+16.0f)/116.0f; } b->lab.L=(116*Y)-16; b->lab.a=500*(X-Y); b->lab.b=200*(Y-Z); } void color_lab_to_xyz(const Color* a, Color* b, const vector3* reference_white) { float x, y, z; float fy = (a->lab.L + 16) / 116; float fx = a->lab.a / 500 + fy; float fz = fy - a->lab.b / 200; const double K=(24389.0 / 27.0); if (pow(fx, 3)>EPSILON){ x=pow(fx, 3); }else{ x=(116*fx-16)/K; } if (a->lab.L > K*EPSILON){ y=pow((a->lab.L+16)/116, 3); }else{ y=a->lab.L/K; } if (pow(fz, 3)>EPSILON){ z=pow(fz, 3); }else{ z=(116*fz-16)/K; } b->xyz.x = x * reference_white->x; //95.047f; b->xyz.y = y * reference_white->y; //100.000f; b->xyz.z = z * reference_white->z; //108.883f; } void color_get_working_space_matrix(float xr, float yr, float xg, float yg, float xb, float yb, const vector3* reference_white, matrix3x3* result) { float Xr,Yr,Zr; float Xg,Yg,Zg; float Xb,Yb,Zb; Xr=xr/yr; Yr=1; Zr=(1-xr-yr)/yr; Xg=xg/yg; Yg=1; Zg=(1-xg-yg)/yg; Xb=xb/yb; Yb=1; Zb=(1-xb-yb)/yb; vector3 v; v.x=reference_white->x; v.y=reference_white->y; v.z=reference_white->z; matrix3x3 m_inv; m_inv.m[0][0]=Xr; m_inv.m[1][0]=Yr; m_inv.m[2][0]=Zr; m_inv.m[0][1]=Xg; m_inv.m[1][1]=Yg; m_inv.m[2][1]=Zg; m_inv.m[0][2]=Xb; m_inv.m[1][2]=Yb; m_inv.m[2][2]=Zb; matrix3x3_inverse(&m_inv, &m_inv); vector3_multiply_matrix3x3(&v, &m_inv, &v); result->m[0][0]=Xr*v.x; result->m[1][0]=Yr*v.x; result->m[2][0]=Zr*v.x; result->m[0][1]=Xg*v.y; result->m[1][1]=Yg*v.y; result->m[2][1]=Zg*v.y; result->m[0][2]=Xb*v.z; result->m[1][2]=Yb*v.z; result->m[2][2]=Zb*v.z; } void color_get_chromatic_adaptation_matrix(const vector3* source_reference_white, const vector3* destination_reference_white, matrix3x3* result) { matrix3x3 Ma; //Bradford matrix Ma.m[0][0]= 0.8951; Ma.m[1][0]=-0.7502; Ma.m[2][0]= 0.0389; Ma.m[0][1]= 0.2664; Ma.m[1][1]= 1.7135; Ma.m[2][1]=-0.0685; Ma.m[0][2]=-0.1614; Ma.m[1][2]= 0.0367; Ma.m[2][2]= 1.0296; matrix3x3 Ma_inv; //Bradford inverted matrix Ma_inv.m[0][0]= 0.986993; Ma_inv.m[1][0]= 0.432305; Ma_inv.m[2][0]=-0.008529; Ma_inv.m[0][1]=-0.147054; Ma_inv.m[1][1]= 0.518360; Ma_inv.m[2][1]= 0.040043; Ma_inv.m[0][2]= 0.159963; Ma_inv.m[1][2]= 0.049291; Ma_inv.m[2][2]= 0.968487; vector3 Vs, Vd; vector3_multiply_matrix3x3(source_reference_white, &Ma, &Vs); vector3_multiply_matrix3x3(destination_reference_white, &Ma, &Vd); matrix3x3 M; matrix3x3_identity(&M); M.m[0][0]=Vd.x / Vs.x; M.m[1][1]=Vd.y / Vs.y; M.m[2][2]=Vd.z / Vs.z; matrix3x3_multiply(&Ma, &M, &M); matrix3x3_multiply(&M, &Ma_inv, result); } void color_xyz_chromatic_adaptation(const Color* a, Color* result, const matrix3x3* adaptation) { vector3 x; x.x=a->xyz.x; x.y=a->xyz.y; x.z=a->xyz.z; vector3_multiply_matrix3x3(&x, adaptation, &x); result->xyz.x=x.x; result->xyz.y=x.y; result->xyz.z=x.z; } void color_rgb_to_cmy(const Color* a, Color* b) { b->cmy.c = 1 - a->rgb.red; b->cmy.m = 1 - a->rgb.green; b->cmy.y = 1 - a->rgb.blue; } void color_cmy_to_rgb(const Color* a, Color* b) { b->rgb.red = 1 - a->cmy.c; b->rgb.green = 1 - a->cmy.m; b->rgb.blue = 1 - a->cmy.y; } void color_cmy_to_cmyk(const Color* a, Color* b) { float k = 1; if (a->cmy.c < k) k = a->cmy.c; if (a->cmy.m < k) k = a->cmy.m; if (a->cmy.y < k) k = a->cmy.y; if (k == 1){ b->cmyk.c = b->cmyk.m = b->cmyk.y = 0; }else{ b->cmyk.c = (a->cmy.c - k) / (1 - k); b->cmyk.m = (a->cmy.m - k) / (1 - k); b->cmyk.y = (a->cmy.y - k) / (1 - k); } b->cmyk.k = k; } void color_cmyk_to_cmy(const Color* a, Color* b) { b->cmy.c = (a->cmyk.c * (1 - a->cmyk.k) + a->cmyk.k); b->cmy.m = (a->cmyk.m * (1 - a->cmyk.k) + a->cmyk.k); b->cmy.y = (a->cmyk.y * (1 - a->cmyk.k) + a->cmyk.k); } void color_rgb_to_cmyk(const Color* a, Color* b) { Color c; color_rgb_to_cmy(a, &c); color_cmy_to_cmyk(&c, b); } void color_cmyk_to_rgb(const Color* a, Color* b) { Color c; color_cmyk_to_cmy(a, &c); color_cmy_to_rgb(&c, b); } void color_rgb_normalize(Color* a) { a->rgb.red = clamp_float(a->rgb.red, 0, 1); a->rgb.green = clamp_float(a->rgb.green, 0, 1); a->rgb.blue = clamp_float(a->rgb.blue, 0, 1); a->ma[3] = clamp_float(a->ma[3], 0, 1); } void color_hsl_to_hsv(const Color *a, Color *b) { float l = a->hsl.lightness * 2.0; float s = a->hsl.saturation * ((l <= 1.0) ? (l) : (2.0 - l)); b->hsv.hue = a->hsl.hue; if (l + s == 0){ b->hsv.value = 0; b->hsv.saturation = 1; }else{ b->hsv.value = (l + s) / 2.0; b->hsv.saturation = (2.0 * s) / (l + s); } } void color_hsv_to_hsl(const Color *a, Color *b) { float l = (2.0 - a->hsv.saturation) * a->hsv.value; float s = (a->hsv.saturation * a->hsv.value) / ((l <= 1.0) ? (l) : (2 - l)); if (l == 0) s = 0; b->hsl.hue = a->hsv.hue; b->hsl.saturation = s; b->hsl.lightness = l / 2.0; } void color_rgb_get_linear(const Color* a, Color* b) { if (a->rgb.red > 0.04045f) b->rgb.red = pow((a->rgb.red + 0.055f) / 1.055f, 2.4f); else b->rgb.red = a->rgb.red / 12.92f; if (a->rgb.green > 0.04045f) b->rgb.green = pow((a->rgb.green + 0.055f) / 1.055f, 2.4f); else b->rgb.green = a->rgb.green / 12.92f; if (a->rgb.blue > 0.04045f) b->rgb.blue = pow((a->rgb.blue + 0.055f) / 1.055f, 2.4f); else b->rgb.blue = a->rgb.blue / 12.92f; } void color_linear_get_rgb(const Color* a, Color* b) { if (a->rgb.red > 0.0031308f) b->rgb.red = (1.055f * pow(a->rgb.red, 1.0f / 2.4f)) - 0.055f; else b->rgb.red = a->rgb.red * 12.92f; if (a->rgb.green > 0.0031308f) b->rgb.green = (1.055f * pow(a->rgb.green, 1.0f / 2.4f)) - 0.055f; else b->rgb.green = a->rgb.green * 12.92f; if (a->rgb.blue > 0.0031308f) b->rgb.blue = (1.055f * pow(a->rgb.blue, 1.0f / 2.4f)) - 0.055f; else b->rgb.blue = a->rgb.blue * 12.92f; } const matrix3x3* color_get_sRGB_transformation_matrix() { return &sRGB_transformation; } const matrix3x3* color_get_inverted_sRGB_transformation_matrix() { return &sRGB_transformation_inverted; } const matrix3x3* color_get_d65_d50_adaptation_matrix() { return &d65_d50_adaptation_matrix; } const matrix3x3* color_get_d50_d65_adaptation_matrix() { return &d50_d65_adaptation_matrix; } const vector3* color_get_reference(ReferenceIlluminant illuminant, ReferenceObserver observer) { return &references[illuminant][observer]; } const ReferenceIlluminant color_get_illuminant(const char *illuminant) { const struct{ const char *label; ReferenceIlluminant illuminant; }illuminants[] = { {"A", REFERENCE_ILLUMINANT_A}, {"C", REFERENCE_ILLUMINANT_C}, {"D50", REFERENCE_ILLUMINANT_D50}, {"D55", REFERENCE_ILLUMINANT_D55}, {"D65", REFERENCE_ILLUMINANT_D65}, {"D75", REFERENCE_ILLUMINANT_D75}, {"F2", REFERENCE_ILLUMINANT_F2}, {"F7", REFERENCE_ILLUMINANT_F7}, {"F11", REFERENCE_ILLUMINANT_F11}, {0, REFERENCE_ILLUMINANT_D50}, }; for (int i = 0; illuminants[i].label; i++){ if (string(illuminants[i].label).compare(illuminant) == 0){ return illuminants[i].illuminant; } } return REFERENCE_ILLUMINANT_D50; }; const ReferenceObserver color_get_observer(const char *observer) { const struct{ const char *label; ReferenceObserver observer; }observers[] = { {"2", REFERENCE_OBSERVER_2}, {"10", REFERENCE_OBSERVER_10}, {0, REFERENCE_OBSERVER_2}, }; for (int i = 0; observers[i].label; i++){ if (string(observers[i].label).compare(observer) == 0){ return observers[i].observer; } } return REFERENCE_OBSERVER_2; } bool color_is_rgb_out_of_gamut(const Color* a) { if (a->rgb.red < 0 || a->rgb.red > 1) return true; if (a->rgb.green < 0 || a->rgb.green > 1) return true; if (a->rgb.blue < 0 || a->rgb.blue > 1) return true; return false; } float color_distance(const Color* a, const Color* b) { Color al, bl; color_rgb_get_linear(a, &al); color_rgb_get_linear(b, &bl); return sqrt( pow(bl.rgb.red - al.rgb.red, 2) + pow(bl.rgb.green - al.rgb.green, 2) + pow(bl.rgb.blue - al.rgb.blue, 2) ); } float color_distance_lch(const Color* a, const Color* b) { Color al, bl; color_lab_to_lch(a, &al); color_lab_to_lch(b, &bl); return sqrt( pow((bl.lch.L - al.lch.L) / 1, 2) + pow((bl.lch.C - al.lch.C) / (1 + 0.045 * al.lch.C), 2) + pow((pow(a->lab.a - b->lab.a, 2) + pow(a->lab.b - b->lab.b, 2) - (bl.lch.C - al.lch.C)) / (1 + 0.015 * al.lch.C), 2) ); } bool color_equal(const Color* a, const Color* b) { for (int i = 0; i < 4; i++){ if (abs_float(a->ma[i] - b->ma[i]) > 1e-6) return false; } return true; } gpick-gpick-0.2.6rc1/source/Color.h000066400000000000000000000405451315430016700170540ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_COLOR_H_ #define GPICK_COLOR_H_ #include "MathUtil.h" /** \file source/Color.h * \brief Color structure and functions to convert colors from one color space to another. */ /** \struct Color * \brief Color structure is an union of all available color spaces. */ typedef struct Color{ union{ struct{ float red; /**< Red component */ float green; /**< Green component */ float blue; /**< Blue component */ }rgb; struct{ float hue; float saturation; float value; }hsv; struct{ float hue; float saturation; float lightness; }hsl; struct{ float x; float y; float z; }xyz; struct{ float L; float a; float b; }lab; struct{ float L; float C; float h; }lch; struct{ float c; float m; float y; }cmy; struct{ float c; float m; float y; float k; }cmyk; struct{ float m1; float m2; float m3; float m4; }m; /**< General data access structure */ float ma[4]; /**< General data access array */ }; }Color; /** \enum ReferenceIlluminant * \brief Reference illuminants. */ enum ReferenceIlluminant { REFERENCE_ILLUMINANT_A = 0, REFERENCE_ILLUMINANT_C = 1, REFERENCE_ILLUMINANT_D50 = 2, REFERENCE_ILLUMINANT_D55 = 3, REFERENCE_ILLUMINANT_D65 = 4, REFERENCE_ILLUMINANT_D75 = 5, REFERENCE_ILLUMINANT_F2 = 6, REFERENCE_ILLUMINANT_F7 = 7, REFERENCE_ILLUMINANT_F11 = 8, }; /** \enum ReferenceObserver * \brief Reference observers. */ enum ReferenceObserver { REFERENCE_OBSERVER_2 = 0, REFERENCE_OBSERVER_10 = 1, }; /** * Initialize things needed for color conversion functions. Must be called before using any other functions. */ void color_init(); /** * Convert RGB color space to HSL color space. * @param[in] a Source color in RGB color space. * @param[out] b Destination color in HSL color space. */ void color_rgb_to_hsl(const Color* a, Color* b); /** * Convert HSL color space to RGB color space. * @param[in] a Source color in HSL color space. * @param[out] b Destination color in RGB color space. */ void color_hsl_to_rgb(const Color* a, Color* b); /** * Convert HSL color space to HSV color space. * @param[in] a Source color in HSL color space. * @param[out] b Destination color in HSV color space. */ void color_hsl_to_hsv(const Color *a, Color *b); /** * Convert HSV color space to HSL color space. * @param[in] a Source color in HSV color space. * @param[out] b Destination color in HSL color space. */ void color_hsv_to_hsl(const Color *a, Color *b); /** * Convert RGB color space to HSV color space. * @param[in] a Source color in RGB color space. * @param[out] b Destination color in HSV color space. */ void color_rgb_to_hsv(const Color* a, Color* b); /** * Convert HSV color space to RGB color space. * @param[in] a Source color in HSV color space. * @param[out] b Destination color in RGB color space. */ void color_hsv_to_rgb(const Color* a, Color* b); /** * Convert RGB color space to XYZ color space. * @param[in] a Source color in RGB color space. * @param[out] b Destination color in XYZ color space. * @param[in] transformation Transformation matrix for RGB to XYZ conversion. */ void color_rgb_to_xyz(const Color* a, Color* b, const matrix3x3* transformation); /** * Convert XYZ color space to RGB color space. * @param[in] a Source color in XYZ color space. * @param[out] b Destination color in RGB color space. * @param[in] transformation_inverted Transformation matrix for XYZ to RGB conversion. */ void color_xyz_to_rgb(const Color* a, Color* b, const matrix3x3* transformation_inverted); /** * Convert XYZ color space to Lab color space. * @param[in] a Source color in XYZ color space. * @param[out] b Destination color in Lab color space. * @param[in] reference_white Reference white color values. */ void color_xyz_to_lab(const Color* a, Color* b, const vector3* reference_white); /** * Convert Lab color space to XYZ color space. * @param[in] a Source color in Lab color space. * @param[out] b Destination color in XYZ color space. * @param[in] reference_white Reference white color values. */ void color_lab_to_xyz(const Color* a, Color* b, const vector3* reference_white); /** * Convert RGB color space to Lab color space. * @param[in] a Source color in RGB color space. * @param[out] b Destination color in Lab color space. * @param[in] reference_white Reference white color values. * @param[in] transformation Transformation matrix for RGB to XYZ conversion. * @param[in] adaptation_matrix XYZ chromatic adaptation matrix. */ void color_rgb_to_lab(const Color* a, Color* b, const vector3* reference_white, const matrix3x3* transformation, const matrix3x3* adaptation_matrix); /** * Convert Lab color space to RGB color space. * @param[in] a Source color in Lab color space. * @param[out] b Destination color in RGB color space. * @param[in] reference_white Reference white color values. * @param[in] transformation_inverted Transformation matrix for XYZ to RGB conversion. * @param[in] adaptation_matrix_inverted Inverted XYZ chromatic adaptation matrix. */ void color_lab_to_rgb(const Color* a, Color* b, const vector3* reference_white, const matrix3x3* transformation_inverted, const matrix3x3* adaptation_matrix_inverted); /** * Convert RGB color space to Lab color space with illuminant D50, observer 2, sRGB transformation matrix and D65-D50 adaptation matrix. * @param[in] a Source color in RGB color space. * @param[out] b Destination color in Lab color space. */ void color_rgb_to_lab_d50(const Color* a, Color* b); /** * Convert Lab color space to RGB color space with illuminant D50, observer 2, inverted sRGB transformation matrix and D50-D65 adaptation matrix. * @param[in] a Source color in Lab color space. * @param[out] b Destination color in RGB color space. */ void color_lab_to_rgb_d50(const Color* a, Color* b); /** * Convert Lab color space to LCH color space. * @param[in] a Source color in Lab color space. * @param[out] b Destination color in LCH color space. */ void color_lab_to_lch(const Color* a, Color* b); /** * Convert Lab color space to LCH color space. * @param[in] a Source color in Lab color space. * @param[out] b Destination color in LCH color space. */ void color_lch_to_lab(const Color* a, Color* b); /** * Convert RGB color space to LCH color space. * @param[in] a Source color in RGB color space. * @param[out] b Destination color in LCH color space. * @param[in] reference_white Reference white color values. * @param[in] transformation Transformation matrix for RGB to XYZ conversion. * @param[in] adaptation_matrix XYZ chromatic adaptation matrix. */ void color_rgb_to_lch(const Color* a, Color* b, const vector3* reference_white, const matrix3x3* transformation, const matrix3x3* adaptation_matrix); /** * Convert LCH color space to RGB color space. * @param[in] a Source color in LCH color space. * @param[out] b Destination color in RGB color space. * @param[in] reference_white Reference white color values. * @param[in] transformation_inverted Transformation matrix for XYZ to RGB conversion. * @param[in] adaptation_matrix_inverted Inverted XYZ chromatic adaptation matrix. */ void color_lch_to_rgb(const Color* a, Color* b, const vector3* reference_white, const matrix3x3* transformation_inverted, const matrix3x3* adaptation_matrix_inverted); /** * Convert RGB color space to LCH color space with illuminant D50, observer 2, sRGB transformation matrix and D65-D50 adaptation matrix. * @param[in] a Source color in RGB color space. * @param[out] b Destination color in LCH color space. */ void color_rgb_to_lch_d50(const Color* a, Color* b); /** * Convert LCH color space to RGB color space with illuminant D50, observer 2, inverted sRGB transformation matrix and D50-D65 adaptation matrix. * @param[in] a Source color in LCH color space. * @param[out] b Destination color in RGB color space. */ void color_lch_to_rgb_d50(const Color* a, Color* b); /** * Convert RGB color space to CMY color space. * @param[in] a Source color in RGB color space. * @param[out] b Destination color in CMY color space. */ void color_rgb_to_cmy(const Color* a, Color* b); /** * Convert CMY color space to RGB color space. * @param[in] a Source color in CMY color space. * @param[out] b Destination color in RGB color space. */ void color_cmy_to_rgb(const Color* a, Color* b); /** * Convert CMY color space to CMYK color space. * @param[in] a Source color in CMY color space. * @param[out] b Destination color in CMYK color space. */ void color_cmy_to_cmyk(const Color* a, Color* b); /** * Convert CMYK color space to CMY color space. * @param[in] a Source color in CMYK color space. * @param[out] b Destination color in CMY color space. */ void color_cmyk_to_cmy(const Color* a, Color* b); /** * Convert RGB color space to CMYK color space. * @param[in] a Source color in RGB color space. * @param[out] b Destination color in CMYK color space. */ void color_rgb_to_cmyk(const Color* a, Color* b); /** * Convert CMYK color space to RGB color space. * @param[in] a Source color in CMYK color space. * @param[out] b Destination color in RGB color space. */ void color_cmyk_to_rgb(const Color* a, Color* b); /** * Normalize RGB color values. * @param[in,out] a Color in RGB color space. */ void color_rgb_normalize(Color* a); /** * Check whenever the color contains invalid (out of RGB gamut) value. * @param[in] a Color in RGB color space. * @return True, when color is out of RGB gamut. */ bool color_is_rgb_out_of_gamut(const Color* a); /** * Transform RGB color to linear RGB color. * @param[in] a Color in RGB color space. * @param[out] b Linear color in RGB color space. */ void color_rgb_get_linear(const Color* a, Color* b); /** * Transform linear RGB color to RGB color. * @param[in] a Linear color in RGB color space. * @param[out] b Color in RGB color space. */ void color_linear_get_rgb(const Color* a, Color* b); /** * Copy color. * @param[in] a Source color in any color space. * @param[out] b Destination color. */ void color_copy(const Color* a, Color* b); /** * Add color values. * @param[in,out] a Source color in any color space. * @param[in] b Color values. */ void color_add(Color* a, const Color* b); /** * Multiply color values by specified amount. * @param[in,out] a Source color in any color space. * @param[in] b Multiplier. */ void color_multiply(Color* a, float b); /** * Set all color values to zero. * @param[in,out] a Color to be set. */ void color_zero(Color* a); /** * Create new Color structure. * @return Color structure with unspecified values. */ Color* color_new(); /** * Free memory associated with Color structure. * @param[in] a Color to be freed. */ void color_destroy(Color* a); /** * Set all color values to specified value. * @param[in,out] a Color to be set. * @param[in] value Value which is used. */ void color_set(Color* a, float value); /** * Set color values to specified values. * @param[in,out] a Color to be set. * @param[in] red Red value which is used. * @param[in] green Green value which is used. * @param[in] blue Blue value which is used. */ void color_set(Color* a, float red, float green, float blue); /** * Set color values to specified values. * @param[in,out] a Color to be set. * @param[in] red Red value which is used. * @param[in] green Green value which is used. * @param[in] blue Blue value which is used. */ void color_set(Color* a, int red, int green, int blue); /** * Get either black or white color depending on which has more contrast with specified color. * @param[in] a Source color in RGB color space. * @param[out] b Color with most contrast in RGB color space. */ void color_get_contrasting(const Color* a, Color* b); /** * Calculate working space matrix. * @param[in] xr Red primary in x channel. * @param[in] yr Red primary in y channel. * @param[in] xg Green primary in x channel. * @param[in] yg Green primary in y channel. * @param[in] xb Blue primary in x channel. * @param[in] yb Blue primary in y channel. * @param[in] reference_white Reference white vector. * @param[out] result Calculated working space matrix. */ void color_get_working_space_matrix(float xr, float yr, float xg, float yg, float xb, float yb, const vector3* reference_white, matrix3x3* result); /** * Calculate chromatic adaptation matrix from source and destination reference white vectors. * @param[in] source_reference_white Source reference white vector. * @param[in] destination_reference_white Destination reference white vector. * @param[out] result Calculated chromatic adaptation matrix. */ void color_get_chromatic_adaptation_matrix(const vector3* source_reference_white, const vector3* destination_reference_white, matrix3x3* result); /** * Apply chromatic adaptation matrix to the XYZ color. * @param[in] a Source color in XYZ color space. * @param[out] result Pointer to a Color structure where the result is stored in XYZ color space. * @param[in] adaptation Chromatic adaptation matrix. * @see color_get_chromatic_adaptation_matrix. */ void color_xyz_chromatic_adaptation(const Color* a, Color* result, const matrix3x3* adaptation); /** * Get working space matrix for sRGB. * @return Constant reference to sRGB working space matrix. */ const matrix3x3* color_get_sRGB_transformation_matrix(); /** * Get inverted working space matrix for sRGB. * @return Constant reference to inverted sRGB working space matrix. */ const matrix3x3* color_get_inverted_sRGB_transformation_matrix(); /** * Get D65 to D50 chromatic adaptation matrix. * @return Constant reference to chromatic adaptation matrix. */ const matrix3x3* color_get_d65_d50_adaptation_matrix(); /** * Get D50 to D65 chromatic adaptation matrix. * @return Constant reference to chromatic adaptation matrix. */ const matrix3x3* color_get_d50_d65_adaptation_matrix(); /** * Get reference white vector for specified illuminant and observer. * @param[in] illuminant Illuminant. * @param[in] observer Observer. * @return Reference white vector. */ const vector3* color_get_reference(ReferenceIlluminant illuminant, ReferenceObserver observer); /** * Get illuminant by name. * @param[in] illuminant Illuminant name. * @return Reference illuminant. */ const ReferenceIlluminant color_get_illuminant(const char *illuminant); /** * Get observer by name. * @param[in] observer Observer name. * @return Reference observer. */ const ReferenceObserver color_get_observer(const char *observer); /** * Get distance between two colors. * @param[in] a First color. * @param[in] b Second color. * @return Distance. */ float color_distance(const Color* a, const Color* b); /** * Get distance between two colors using CIE94 color difference calculation. * @param[in] a First color. * @param[in] b Second color. * @return Distance. */ float color_distance_lch(const Color* a, const Color* b); /** * Check if colors are equal. * @param[in] a First color. * @param[in] b Second color. * @return Equality. */ bool color_equal(const Color* a, const Color* b); #endif /* GPICK_COLOR_H_ */ gpick-gpick-0.2.6rc1/source/ColorList.cpp000066400000000000000000000132001315430016700202270ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ColorList.h" #include "ColorObject.h" #include "dynv/DynvSystem.h" #include using namespace std; ColorList* color_list_new() { ColorList* color_list = new ColorList; color_list->params = nullptr; color_list->on_insert = nullptr; color_list->on_change = nullptr; color_list->on_delete = nullptr; color_list->on_clear = nullptr; color_list->on_delete_selected = nullptr; color_list->on_get_positions = nullptr; color_list->userdata = nullptr; return color_list; } ColorList* color_list_new(ColorList *color_list) { ColorList *result = color_list_new(); if (color_list){ dynvHandlerMap *handler_map = dynv_system_get_handler_map(color_list->params); result->params = dynv_system_create(handler_map); dynv_handler_map_release(handler_map); }else{ result->params = nullptr; } return result; } ColorList* color_list_new(struct dynvHandlerMap* handler_map) { ColorList *result = color_list_new(); if (handler_map){ result->params = dynv_system_create(handler_map); }else{ result->params = nullptr; } return result; } ColorList* color_list_new_with_one_color(ColorList *template_color_list, const Color *color) { ColorList *color_list = color_list_new(); ColorObject *color_object = new ColorObject("", *color); color_list_add_color_object(color_list, color_object, 1); return color_list; } void color_list_destroy(ColorList* color_list) { for (auto color_object: color_list->colors){ color_object->release(); } color_list->colors.clear(); if (color_list->params) dynv_system_release(color_list->params); delete color_list; } ColorObject* color_list_new_color_object(ColorList* color_list, const Color *color) { return new ColorObject("", *color); } ColorObject* color_list_add_color(ColorList *color_list, const Color *color) { ColorObject *color_object = new ColorObject("", *color); int r = color_list_add_color_object(color_list, color_object, 1); if (r == 0){ color_object->release(); return color_object; }else{ delete color_object; return 0; } } int color_list_add_color_object(ColorList *color_list, ColorObject *color_object, bool add_to_palette) { color_list->colors.push_back(color_object->reference()); if (add_to_palette && color_list->on_insert) color_list->on_insert(color_list, color_object); return 0; } int color_list_add(ColorList *color_list, ColorList *items, bool add_to_palette) { for (auto color_object: items->colors){ color_list->colors.push_back(color_object->reference()); if (add_to_palette && color_list->on_insert && color_object->isVisible()) color_list->on_insert(color_list, color_object); } return 0; } int color_list_remove_color_object(ColorList *color_list, ColorObject *color_object) { list::iterator i = std::find(color_list->colors.begin(), color_list->colors.end(), color_object); if (i != color_list->colors.end()){ if (color_list->on_delete) color_list->on_delete(color_list, color_object); color_list->colors.erase(i); color_object->release(); return 0; }else return -1; } int color_list_remove_selected(ColorList *color_list) { ColorList::iter i=color_list->colors.begin(); while (i != color_list->colors.end()){ if ((*i)->isSelected()){ (*i)->release(); i = color_list->colors.erase(i); }else ++i; } color_list->on_delete_selected(color_list); return 0; } int color_list_remove_all(ColorList *color_list) { ColorList::iter i; if (color_list->on_clear){ color_list->on_clear(color_list); for (i = color_list->colors.begin(); i != color_list->colors.end(); ++i){ (*i)->release(); } }else{ for (i = color_list->colors.begin(); i != color_list->colors.end(); ++i){ if (color_list->on_delete) color_list->on_delete(color_list, *i); (*i)->release(); } } color_list->colors.clear(); return 0; } size_t color_list_get_count(ColorList *color_list) { return color_list->colors.size(); } int color_list_get_positions(ColorList *color_list) { if (color_list->on_get_positions){ for (auto color: color_list->colors){ color->resetPosition(); } color_list->on_get_positions(color_list); }else{ size_t position = 0; for (auto color: color_list->colors){ color->setPosition(position++); } } return 0; } gpick-gpick-0.2.6rc1/source/ColorList.h000066400000000000000000000061461315430016700177070ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_COLOR_LIST_H_ #define GPICK_COLOR_LIST_H_ class ColorObject; struct dynvSystem; #include "Color.h" #include #include class ColorList { public: std::list colors; typedef std::list::iterator iter; dynvSystem *params; int (*on_insert)(ColorList *color_list, ColorObject *color_object); int (*on_delete)(ColorList *color_list, ColorObject *color_object); int (*on_delete_selected)(ColorList *color_list); int (*on_change)(ColorList *color_list, ColorObject *color_object); int (*on_clear)(ColorList *color_list); int (*on_get_positions)(ColorList *color_list); void* userdata; }; ColorList* color_list_new(); ColorList* color_list_new(struct dynvHandlerMap *handler_map); ColorList* color_list_new(ColorList *color_list); ColorList* color_list_new_with_one_color(ColorList *template_color_list, const Color *color); void color_list_destroy(ColorList *color_list); ColorObject* color_list_new_color_object(ColorList *color_list, const Color *color); ColorObject* color_list_add_color(ColorList *color_list, const Color *color); int color_list_add_color_object(ColorList *color_list, ColorObject *color_object, bool add_to_palette); int color_list_add(ColorList *color_list, ColorList *items, bool add_to_palette); int color_list_remove_color_object(ColorList *color_list, ColorObject *color_object); int color_list_remove_selected(ColorList *color_list); int color_list_remove_all(ColorList *color_list); size_t color_list_get_count(ColorList *color_list); int color_list_get_positions(ColorList *color_list); #endif /* GPICK_COLOR_LIST_H_ */ gpick-gpick-0.2.6rc1/source/ColorMixer.cpp000066400000000000000000000611761315430016700204170ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ColorMixer.h" #include "ColorObject.h" #include "ColorSource.h" #include "ColorSourceManager.h" #include "DragDrop.h" #include "GlobalState.h" #include "ToolColorNaming.h" #include "uiUtilities.h" #include "ColorList.h" #include "MathUtil.h" #include "ColorRYB.h" #include "gtk/ColorWidget.h" #include "gtk/ColorWheel.h" #include "ColorWheelType.h" #include "uiColorInput.h" #include "CopyPaste.h" #include "Converter.h" #include "DynvHelpers.h" #include "Internationalisation.h" #include "color_names/ColorNames.h" #include "StandardMenu.h" #include "Clipboard.h" #include #include #include #include #include #include using namespace std; #define MAX_COLOR_LINES 3 #define MODE_ID_NORMAL 1 #define MODE_ID_MULTIPLY 2 #define MODE_ID_DIFFERENCE 3 #define MODE_ID_ADD 4 #define MODE_ID_HUE 5 #define MODE_ID_SATURATION 6 #define MODE_ID_LIGHTNESS 7 typedef struct ColorMixerType{ const char *name; const char *unique_name; int mode_id; }ColorMixerType; const ColorMixerType color_mixer_types[] = { {N_("Normal"), "normal", MODE_ID_NORMAL}, {N_("Multiply"), "multiply", MODE_ID_MULTIPLY}, {N_("Add"), "add", MODE_ID_ADD}, {N_("Difference"), "difference", MODE_ID_DIFFERENCE}, {N_("Hue"), "hue", MODE_ID_HUE}, {N_("Saturation"), "saturation", MODE_ID_SATURATION}, {N_("Lightness"), "lightness", MODE_ID_LIGHTNESS}, }; typedef struct ColorMixerArgs{ ColorSource source; GtkWidget* main; GtkWidget* statusbar; GtkWidget *secondary_color; GtkWidget *opacity; GtkWidget *last_focused_color; GtkWidget *color_previews; const ColorMixerType *mixer_type; struct{ GtkWidget *input; GtkWidget *output; }color[MAX_COLOR_LINES]; struct dynvSystem *params; ColorList *preview_color_list; GlobalState* gs; }ColorMixerArgs; class ColorMixerColorNameAssigner: public ToolColorNameAssigner { protected: stringstream m_stream; const char *m_ident; public: ColorMixerColorNameAssigner(GlobalState *gs): ToolColorNameAssigner(gs) { } void assign(ColorObject *color_object, const Color *color, const char *ident) { m_ident = ident; ToolColorNameAssigner::assign(color_object, color); } virtual std::string getToolSpecificName(ColorObject *color_object, const Color *color) { m_stream.str(""); m_stream << color_names_get(m_gs->getColorNames(), color, false) << " " << _("color mixer") << " " << m_ident; return m_stream.str(); } }; static int set_rgb_color(ColorMixerArgs *args, ColorObject* color, uint32_t color_index); static int set_rgb_color_by_widget(ColorMixerArgs *args, ColorObject* color, GtkWidget* color_widget); static void calc(ColorMixerArgs *args, bool preview, bool save_settings){ double opacity = gtk_range_get_value(GTK_RANGE(args->opacity)); if (save_settings){ dynv_set_float(args->params, "opacity", opacity); } Color color, color2, r, hsv1, hsv2; gtk_color_get_color(GTK_COLOR(args->secondary_color), &color2); for (int i = 0; i < MAX_COLOR_LINES; ++i){ gtk_color_get_color(GTK_COLOR(args->color[i].input), &color); switch (args->mixer_type->mode_id){ case MODE_ID_NORMAL: r.rgb.red = color2.rgb.red; r.rgb.green = color2.rgb.green; r.rgb.blue = color2.rgb.blue; break; case MODE_ID_MULTIPLY: r.rgb.red = color.rgb.red * color2.rgb.red; r.rgb.green = color.rgb.green * color2.rgb.green; r.rgb.blue = color.rgb.blue * color2.rgb.blue; break; case MODE_ID_ADD: r.rgb.red = clamp_float(color.rgb.red + color2.rgb.red, 0, 1); r.rgb.green = clamp_float(color.rgb.green + color2.rgb.green, 0, 1); r.rgb.blue = clamp_float(color.rgb.blue + color2.rgb.blue, 0, 1); break; case MODE_ID_DIFFERENCE: r.rgb.red = fabs(color.rgb.red - color2.rgb.red); r.rgb.green = fabs(color.rgb.green - color2.rgb.green); r.rgb.blue = fabs(color.rgb.blue - color2.rgb.blue); break; case MODE_ID_HUE: color_rgb_to_hsv(&color, &hsv1); color_rgb_to_hsv(&color2, &hsv2); hsv1.hsv.hue = hsv2.hsv.hue; color_hsv_to_rgb(&hsv1, &r); break; case MODE_ID_SATURATION: color_rgb_to_hsv(&color, &hsv1); color_rgb_to_hsv(&color2, &hsv2); hsv1.hsv.saturation = hsv2.hsv.saturation; color_hsv_to_rgb(&hsv1, &r); break; case MODE_ID_LIGHTNESS: color_rgb_to_hsl(&color, &hsv1); color_rgb_to_hsl(&color2, &hsv2); hsv1.hsl.lightness = hsv2.hsl.lightness; color_hsl_to_rgb(&hsv1, &r); break; } r.rgb.red = (color.rgb.red * (100 - opacity) + r.rgb.red * opacity) / 100; r.rgb.green = (color.rgb.green * (100 - opacity) + r.rgb.green * opacity) / 100; r.rgb.blue = (color.rgb.blue * (100 - opacity) + r.rgb.blue * opacity) / 100; gtk_color_set_color(GTK_COLOR(args->color[i].output), &r, ""); } } static void update(GtkWidget *widget, ColorMixerArgs *args ){ color_list_remove_all(args->preview_color_list); calc(args, true, false); } static void on_color_paste(GtkWidget *widget, ColorMixerArgs *args) { GtkWidget* color_widget = GTK_WIDGET(g_object_get_data(G_OBJECT(widget), "color_widget")); ColorObject* color_object; if (copypaste_get_color_object(&color_object, args->gs) == 0){ set_rgb_color_by_widget(args, color_object, color_widget); color_object->release(); } } static void on_color_edit(GtkWidget *widget, ColorMixerArgs *args) { GtkWidget* color_widget = GTK_WIDGET(g_object_get_data(G_OBJECT(widget), "color_widget")); Color c; gtk_color_get_color(GTK_COLOR(color_widget), &c); ColorObject* color_object = color_list_new_color_object(args->gs->getColorList(), &c); ColorObject* new_color_object = nullptr; if (dialog_color_input_show(GTK_WINDOW(gtk_widget_get_toplevel(args->main)), args->gs, color_object, &new_color_object ) == 0){ set_rgb_color_by_widget(args, new_color_object, color_widget); new_color_object->release(); } color_object->release(); } static boost::format format_ignore_arg_errors(const std::string &f_string) { boost::format fmter(f_string); fmter.exceptions(boost::io::all_error_bits ^ (boost::io::too_many_args_bit | boost::io::too_few_args_bit)); return fmter; } static string identify_color_widget(GtkWidget *widget, ColorMixerArgs *args) { if (args->secondary_color == widget){ return _("secondary"); }else for (int i = 0; i < MAX_COLOR_LINES; ++i){ if (args->color[i].input == widget){ try{ return (format_ignore_arg_errors(_("primary %d")) % (i + 1)).str(); }catch(const boost::io::format_error &e){ return (format_ignore_arg_errors("primary %d") % (i + 1)).str(); } }else if (args->color[i].output == widget){ try{ return (format_ignore_arg_errors(_("result %d")) % (i + 1)).str(); }catch(const boost::io::format_error &e){ return (format_ignore_arg_errors("result %d") % (i + 1)).str(); } } } return "unknown"; } static void add_color_to_palette(GtkWidget *color_widget, ColorMixerColorNameAssigner &name_assigner, ColorMixerArgs *args) { Color c; ColorObject *color_object; string widget_ident; gtk_color_get_color(GTK_COLOR(color_widget), &c); color_object = color_list_new_color_object(args->gs->getColorList(), &c); widget_ident = identify_color_widget(color_widget, args); name_assigner.assign(color_object, &c, widget_ident.c_str()); color_list_add_color_object(args->gs->getColorList(), color_object, 1); color_object->release(); } static void on_color_add_to_palette(GtkWidget *widget, gpointer item) { ColorMixerArgs* args = (ColorMixerArgs*)item; GtkWidget *color_widget = GTK_WIDGET(g_object_get_data(G_OBJECT(widget), "color_widget")); ColorMixerColorNameAssigner name_assigner(args->gs); add_color_to_palette(color_widget, name_assigner, args); } static void on_color_add_all_to_palette(GtkWidget *widget, gpointer item) { ColorMixerArgs* args = (ColorMixerArgs*)item; ColorMixerColorNameAssigner name_assigner(args->gs); for (int i = 0; i < MAX_COLOR_LINES; ++i){ add_color_to_palette(args->color[i].input, name_assigner, args); } add_color_to_palette(args->secondary_color, name_assigner, args); for (int i = 0; i < MAX_COLOR_LINES; ++i){ add_color_to_palette(args->color[i].output, name_assigner, args); } } static gboolean color_focus_in_cb(GtkWidget *widget, GdkEventFocus *event, ColorMixerArgs *args){ args->last_focused_color = widget; return false; } static void on_color_activate(GtkWidget *widget, gpointer item) { ColorMixerArgs* args=(ColorMixerArgs*)item; ColorMixerColorNameAssigner name_assigner(args->gs); add_color_to_palette(widget, name_assigner, args); } static void type_toggled_cb(GtkWidget *widget, ColorMixerArgs *args) { GtkWidget* color_widget = GTK_WIDGET(g_object_get_data(G_OBJECT(widget), "color_widget")); const ColorMixerType *mixer_type = static_cast(g_object_get_data(G_OBJECT(widget), "color_mixer_type")); if (gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(widget))){ args->mixer_type = mixer_type; Color c; gtk_color_get_color(GTK_COLOR(color_widget), &c); gtk_color_set_color(GTK_COLOR(args->secondary_color), &c, _(args->mixer_type->name)); update(0, args); } } static void color_show_menu(GtkWidget* widget, ColorMixerArgs* args, GdkEventButton *event ){ GtkWidget *menu; GtkWidget* item; menu = gtk_menu_new (); item = gtk_menu_item_new_with_image (_("_Add to palette"), gtk_image_new_from_stock(GTK_STOCK_ADD, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK (on_color_add_to_palette), args); g_object_set_data(G_OBJECT(item), "color_widget", widget); item = gtk_menu_item_new_with_image (_("A_dd all to palette"), gtk_image_new_from_stock(GTK_STOCK_ADD, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK (on_color_add_all_to_palette), args); g_object_set_data(G_OBJECT(item), "color_widget", widget); gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); Color c; gtk_color_get_color(GTK_COLOR(widget), &c); ColorObject* color_object = color_list_new_color_object(args->gs->getColorList(), &c); StandardMenu::appendMenu(menu, color_object, args->gs); color_object->release(); int line_id = -1; bool secondary_color = false; if (args->secondary_color == widget){ secondary_color = true; }else for (int i = 0; i < MAX_COLOR_LINES; ++i){ if (args->color[i].input == widget){ line_id = i; } } if (line_id >= 0 || secondary_color){ gtk_menu_shell_append (GTK_MENU_SHELL (menu), gtk_separator_menu_item_new ()); if (secondary_color){ GSList *group = 0; for (uint32_t i = 0; i < sizeof(color_mixer_types) / sizeof(ColorMixerType); i++){ item = gtk_radio_menu_item_new_with_label(group, _(color_mixer_types[i].name)); group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(item)); if (args->mixer_type == &color_mixer_types[i]){ gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item), true); } g_object_set_data(G_OBJECT(item), "color_widget", widget); g_object_set_data(G_OBJECT(item), "color_mixer_type", (void*)&color_mixer_types[i]); g_signal_connect(G_OBJECT(item), "toggled", G_CALLBACK(type_toggled_cb), args); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); } gtk_menu_shell_append (GTK_MENU_SHELL (menu), gtk_separator_menu_item_new ()); } item = gtk_menu_item_new_with_image (_("_Edit..."), gtk_image_new_from_stock(GTK_STOCK_EDIT, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK (on_color_edit), args); g_object_set_data(G_OBJECT(item), "color_widget", widget); item = gtk_menu_item_new_with_image (_("_Paste"), gtk_image_new_from_stock(GTK_STOCK_PASTE, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK (on_color_paste), args); g_object_set_data(G_OBJECT(item), "color_widget", widget); if (copypaste_is_color_object_available(args->gs) != 0){ gtk_widget_set_sensitive(item, false); } } gtk_widget_show_all (GTK_WIDGET(menu)); gint32 button, event_time; if (event){ button = event->button; event_time = event->time; }else{ button = 0; event_time = gtk_get_current_event_time (); } gtk_menu_popup (GTK_MENU (menu), nullptr, nullptr, nullptr, nullptr, button, event_time); g_object_ref_sink(menu); g_object_unref(menu); } static gboolean on_color_button_press (GtkWidget *widget, GdkEventButton *event, ColorMixerArgs* args) { if (event->button == 3 && event->type == GDK_BUTTON_PRESS){ color_show_menu(widget, args, event); } return false; } static void on_color_popup_menu(GtkWidget *widget, ColorMixerArgs* args){ color_show_menu(widget, args, 0); } static gboolean on_color_key_press (GtkWidget *widget, GdkEventKey *event, ColorMixerArgs* args){ guint modifiers = gtk_accelerator_get_default_mod_mask(); Color c; ColorObject* color_object; GtkWidget* color_widget = widget; switch(event->keyval){ case GDK_KEY_c: if ((event->state&modifiers) == GDK_CONTROL_MASK){ gtk_color_get_color(GTK_COLOR(color_widget), &c); color_object = color_list_new_color_object(args->gs->getColorList(), &c); Clipboard::set(color_object, args->gs); color_object->release(); return true; } return false; break; case GDK_KEY_v: if ((event->state&modifiers) == GDK_CONTROL_MASK){ if (copypaste_get_color_object(&color_object, args->gs) == 0){ set_rgb_color_by_widget(args, color_object, color_widget); color_object->release(); } return true; } return false; break; default: return false; break; } return false; } static int source_destroy(ColorMixerArgs *args){ Color c; char tmp[32]; dynv_set_string(args->params, "mixer_type", args->mixer_type->unique_name); for (gint i = 0; i < MAX_COLOR_LINES; ++i){ sprintf(tmp, "color%d", i); gtk_color_get_color(GTK_COLOR(args->color[i].input), &c); dynv_set_color(args->params, tmp, &c); } gtk_color_get_color(GTK_COLOR(args->secondary_color), &c); dynv_set_color(args->params, "secondary_color", &c); color_list_destroy(args->preview_color_list); dynv_system_release(args->params); gtk_widget_destroy(args->main); delete args; return 0; } static int source_get_color(ColorMixerArgs *args, ColorObject** color){ ColorMixerColorNameAssigner name_assigner(args->gs); Color c; string widget_ident; if (args->last_focused_color){ gtk_color_get_color(GTK_COLOR(args->last_focused_color), &c); widget_ident = identify_color_widget(args->last_focused_color, args); }else{ gtk_color_get_color(GTK_COLOR(args->color[0].input), &c); widget_ident = identify_color_widget(args->color[0].input, args); } *color = color_list_new_color_object(args->gs->getColorList(), &c); name_assigner.assign(*color, &c, widget_ident.c_str()); return 0; } static int set_rgb_color_by_widget(ColorMixerArgs *args, ColorObject* color_object, GtkWidget* color_widget) { if (args->secondary_color == color_widget){ set_rgb_color(args, color_object, -1); return 0; }else for (int i = 0; i < MAX_COLOR_LINES; ++i){ if (args->color[i].input == color_widget){ set_rgb_color(args, color_object, i); return 0; }else if (args->color[i].output == color_widget){ set_rgb_color(args, color_object, i); return 0; } } return -1; } static int set_rgb_color(ColorMixerArgs *args, ColorObject* color_object, uint32_t color_index) { Color color = color_object->getColor(); if (color_index == (uint32_t)-1){ gtk_color_set_color(GTK_COLOR(args->secondary_color), &color, _(args->mixer_type->name)); }else{ gtk_color_set_color(GTK_COLOR(args->color[color_index].input), &color, ""); } update(0, args); return 0; } static int source_set_color(ColorMixerArgs *args, ColorObject* color_object) { if (args->last_focused_color){ return set_rgb_color_by_widget(args, color_object, args->last_focused_color); }else{ return set_rgb_color(args, color_object, 0); } } static int source_activate(ColorMixerArgs *args) { auto chain = args->gs->getTransformationChain(); gtk_color_set_transformation_chain(GTK_COLOR(args->secondary_color), chain); for (int i = 0; i < MAX_COLOR_LINES; ++i){ gtk_color_set_transformation_chain(GTK_COLOR(args->color[i].input), chain); gtk_color_set_transformation_chain(GTK_COLOR(args->color[i].output), chain); } gtk_statusbar_push(GTK_STATUSBAR(args->statusbar), gtk_statusbar_get_context_id(GTK_STATUSBAR(args->statusbar), "empty"), ""); return 0; } static int source_deactivate(ColorMixerArgs *args){ color_list_remove_all(args->preview_color_list); calc(args, true, true); return 0; } static ColorObject* get_color_object(DragDrop* dd) { ColorMixerArgs* args = (ColorMixerArgs*)dd->userdata; ColorObject* color_object; if (source_get_color(args, &color_object) == 0){ return color_object; } return 0; } static int set_color_object_at(DragDrop* dd, ColorObject* color_object, int x, int y, bool move) { ColorMixerArgs* args = static_cast(dd->userdata); set_rgb_color(args, color_object, (uintptr_t)dd->userdata2); return 0; } static ColorSource* source_implement(ColorSource *source, GlobalState *gs, dynvSystem *dynv_namespace){ ColorMixerArgs* args = new ColorMixerArgs; args->params = dynv_system_ref(dynv_namespace); args->statusbar = gs->getStatusBar(); color_source_init(&args->source, source->identificator, source->hr_name); args->source.destroy = (int (*)(ColorSource *source))source_destroy; args->source.get_color = (int (*)(ColorSource *source, ColorObject** color))source_get_color; args->source.set_color = (int (*)(ColorSource *source, ColorObject* color))source_set_color; args->source.deactivate = (int (*)(ColorSource *source))source_deactivate; args->source.activate = (int (*)(ColorSource *source))source_activate; GtkWidget *table, *vbox, *hbox, *widget, *hbox2; hbox = gtk_hbox_new(FALSE, 0); vbox = gtk_vbox_new(FALSE, 0); gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 5); args->color_previews = gtk_table_new(MAX_COLOR_LINES, 3, false); gtk_box_pack_start(GTK_BOX(vbox), args->color_previews, true, true, 0); DragDrop dd; dragdrop_init(&dd, gs); dd.userdata = args; dd.get_color_object = get_color_object; dd.set_color_object_at = set_color_object_at; widget = gtk_color_new(); gtk_color_set_rounded(GTK_COLOR(widget), true); gtk_color_set_hcenter(GTK_COLOR(widget), true); gtk_color_set_roundness(GTK_COLOR(widget), 5); gtk_table_attach(GTK_TABLE(args->color_previews), widget, 1, 2, 0, 3, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL), 0, 0); args->secondary_color = widget; g_signal_connect(G_OBJECT(widget), "button-press-event", G_CALLBACK(on_color_button_press), args); g_signal_connect(G_OBJECT(widget), "activated", G_CALLBACK(on_color_activate), args); g_signal_connect(G_OBJECT(widget), "key_press_event", G_CALLBACK(on_color_key_press), args); g_signal_connect(G_OBJECT(widget), "popup-menu", G_CALLBACK(on_color_popup_menu), args); g_signal_connect(G_OBJECT(widget), "focus-in-event", G_CALLBACK(color_focus_in_cb), args); gtk_widget_set_size_request(widget, 50, 50); //setup drag&drop gtk_drag_dest_set( widget, GtkDestDefaults(GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_HIGHLIGHT), 0, 0, GDK_ACTION_COPY); gtk_drag_source_set( widget, GDK_BUTTON1_MASK, 0, 0, GDK_ACTION_COPY); dd.handler_map = dynv_system_get_handler_map(gs->getColorList()->params); dd.userdata2 = (void*)-1; dragdrop_widget_attach(widget, DragDropFlags(DRAGDROP_SOURCE | DRAGDROP_DESTINATION), &dd); for (intptr_t i = 0; i < MAX_COLOR_LINES; ++i){ for (intptr_t j = 0; j < 2; ++j){ widget = gtk_color_new(); gtk_color_set_rounded(GTK_COLOR(widget), true); gtk_color_set_hcenter(GTK_COLOR(widget), true); gtk_color_set_roundness(GTK_COLOR(widget), 5); gtk_table_attach(GTK_TABLE(args->color_previews), widget, j * 2, j * 2 + 1, i, i + 1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(0), 0, 0); if (j){ args->color[i].output = widget; }else{ args->color[i].input = widget; } g_signal_connect(G_OBJECT(widget), "button-press-event", G_CALLBACK(on_color_button_press), args); g_signal_connect(G_OBJECT(widget), "activated", G_CALLBACK(on_color_activate), args); g_signal_connect(G_OBJECT(widget), "key_press_event", G_CALLBACK(on_color_key_press), args); g_signal_connect(G_OBJECT(widget), "popup-menu", G_CALLBACK(on_color_popup_menu), args); g_signal_connect(G_OBJECT(widget), "focus-in-event", G_CALLBACK(color_focus_in_cb), args); if (j == 0){ //setup drag&drop gtk_widget_set_size_request(widget, 30, 30); gtk_drag_dest_set( widget, GtkDestDefaults(GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_HIGHLIGHT), 0, 0, GDK_ACTION_COPY); gtk_drag_source_set( widget, GDK_BUTTON1_MASK, 0, 0, GDK_ACTION_COPY); dd.handler_map = dynv_system_get_handler_map(gs->getColorList()->params); dd.userdata2 = (void*)i; dragdrop_widget_attach(widget, DragDropFlags(DRAGDROP_SOURCE | DRAGDROP_DESTINATION), &dd); }else{ gtk_widget_set_size_request(widget, 30, 30); gtk_drag_source_set( widget, GDK_BUTTON1_MASK, 0, 0, GDK_ACTION_COPY); dd.handler_map = dynv_system_get_handler_map(gs->getColorList()->params); dd.userdata2 = (void*)i; dragdrop_widget_attach(widget, DragDropFlags(DRAGDROP_SOURCE), &dd); } } } Color c; color_set(&c, 0.5); char tmp[32]; const char *type_name = dynv_get_string_wd(args->params, "mixer_type", "normal"); for (uint32_t j = 0; j < sizeof(color_mixer_types) / sizeof(ColorMixerType); j++){ if (g_strcmp0(color_mixer_types[j].unique_name, type_name) == 0){ args->mixer_type = &color_mixer_types[j]; break; } } for (gint i = 0; i < MAX_COLOR_LINES; ++i){ sprintf(tmp, "color%d", i); gtk_color_set_color(GTK_COLOR(args->color[i].input), dynv_get_color_wdc(args->params, tmp, &c), ""); } gtk_color_set_color(GTK_COLOR(args->secondary_color), dynv_get_color_wdc(args->params, "secondary_color", &c), _(args->mixer_type->name)); hbox2 = gtk_hbox_new(FALSE, 0); gtk_box_pack_start(GTK_BOX(vbox), hbox2, false, false, 0); gint table_y; table = gtk_table_new(5, 2, false); gtk_box_pack_start(GTK_BOX(hbox2), table, true, true, 0); table_y = 0; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Opacity:"),0,0.5,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,0,0); args->opacity = gtk_hscale_new_with_range(1, 100, 1); gtk_range_set_value(GTK_RANGE(args->opacity), dynv_get_float_wd(args->params, "opacity", 50)); g_signal_connect(G_OBJECT(args->opacity), "value-changed", G_CALLBACK (update), args); gtk_table_attach(GTK_TABLE(table), args->opacity, 1, 2, table_y, table_y+1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GTK_FILL,0,0); table_y++; struct dynvHandlerMap* handler_map=dynv_system_get_handler_map(gs->getColorList()->params); ColorList* preview_color_list = color_list_new(handler_map); dynv_handler_map_release(handler_map); args->preview_color_list = preview_color_list; args->gs = gs; gtk_widget_show_all(hbox); update(0, args); args->main = hbox; args->source.widget = hbox; return (ColorSource*)args; } int color_mixer_source_register(ColorSourceManager *csm) { ColorSource *color_source = new ColorSource; color_source_init(color_source, "color_mixer", _("Color mixer")); color_source->implement = (ColorSource* (*)(ColorSource *source, GlobalState *gs, struct dynvSystem *dynv_namespace))source_implement; color_source->default_accelerator = GDK_KEY_m; color_source_manager_add_source(csm, color_source); return 0; } gpick-gpick-0.2.6rc1/source/ColorMixer.h000066400000000000000000000033031315430016700200500ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_COLOR_MIXER_H_ #define GPICK_COLOR_MIXER_H_ struct ColorSourceManager; int color_mixer_source_register(ColorSourceManager *csm); #endif /* GPICK_COLOR_MIXER_H_ */ gpick-gpick-0.2.6rc1/source/ColorObject.cpp000066400000000000000000000070621315430016700205330ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ColorObject.h" using namespace std; ColorObject::ColorObject(): m_refcnt(0), m_name(), m_color(), m_position(0), m_position_set(false), m_selected(false), m_visited(false), m_visible(true) { } ColorObject::ColorObject(const char *name, const Color &color): m_refcnt(0), m_name(name), m_color(color), m_position(0), m_position_set(false), m_selected(false), m_visited(false), m_visible(true) { } ColorObject::ColorObject(const std::string &name, const Color &color): m_refcnt(0), m_name(name), m_color(color), m_position(0), m_position_set(false), m_selected(false), m_visited(false), m_visible(true) { } ColorObject *ColorObject::reference() { m_refcnt++; return this; } void ColorObject::release() { if (m_refcnt == 0){ delete this; }else{ m_refcnt--; } } const Color &ColorObject::getColor() const { return m_color; } void ColorObject::setColor(const Color &color) { m_color = color; } const std::string &ColorObject::getName() const { return m_name; } void ColorObject::setName(const std::string &name) { m_name = name; } ColorObject* ColorObject::copy() const { ColorObject *color_object = new ColorObject(); color_object->m_name = m_name; color_object->m_color = m_color; color_object->m_selected = m_selected; color_object->m_visited = m_visited; return color_object; } bool ColorObject::isSelected() const { return m_selected; } bool ColorObject::isVisited() const { return m_visited; } size_t ColorObject::getPosition() const { return m_position; } bool ColorObject::isPositionSet() const { return m_position_set; } bool ColorObject::isVisible() const { return m_visible; } void ColorObject::setPosition(size_t position) { m_position = position; m_position_set = true; } void ColorObject::resetPosition() { m_position_set = false; } void ColorObject::setSelected(bool selected) { m_selected = selected; } void ColorObject::setVisited(bool visited) { m_visited = visited; } void ColorObject::setVisible(bool visible) { m_visible = visible; } size_t ColorObject::getReferenceCount() const { return m_refcnt; } gpick-gpick-0.2.6rc1/source/ColorObject.h000066400000000000000000000050441315430016700201760ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_COLOR_OBJECT_H_ #define GPICK_COLOR_OBJECT_H_ class ColorObject; #include "Color.h" #include class ColorObject { public: ColorObject(); ColorObject(const char *name, const Color &color); ColorObject(const std::string &name, const Color &color); ColorObject *reference(); void release(); const Color &getColor() const; void setColor(const Color &color); const std::string &getName() const; void setName(const std::string &name); ColorObject* copy() const; bool isSelected() const; bool isVisited() const; size_t getPosition() const; bool isPositionSet() const; void setPosition(size_t position); void resetPosition(); void setSelected(bool selected); void setVisited(bool visited); size_t getReferenceCount() const; void setVisible(bool visible); bool isVisible() const; private: size_t m_refcnt; std::string m_name; Color m_color; size_t m_position; bool m_position_set; bool m_selected; bool m_visited; bool m_visible; }; #endif /* GPICK_COLOR_OBJECT_H_ */ gpick-gpick-0.2.6rc1/source/ColorPicker.cpp000066400000000000000000001447121315430016700205460ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ColorPicker.h" #include "ColorObject.h" #include "GlobalState.h" #include "ColorList.h" #include "ColorSource.h" #include "ColorSourceManager.h" #include "DragDrop.h" #include "Converter.h" #include "DynvHelpers.h" #include "CopyPaste.h" #include "FloatingPicker.h" #include "ColorRYB.h" #include "ColorWheelType.h" #include "ColorSpaceType.h" #include "gtk/Swatch.h" #include "gtk/Zoomed.h" #include "gtk/ColorComponent.h" #include "gtk/ColorWidget.h" #include "Clipboard.h" #include "uiUtilities.h" #include "uiColorInput.h" #include "uiConverter.h" #include "CopyMenu.h" #include "StandardMenu.h" #include "Internationalisation.h" #include "color_names/ColorNames.h" #include "ScreenReader.h" #include "Sampler.h" #include #include #ifdef _MSC_VER #define M_PI 3.14159265359 #endif #include #include #include #include #include using namespace std; using namespace math; typedef struct ColorPickerArgs{ ColorSource source; GtkWidget* main; GtkWidget* expanderRGB; GtkWidget* expanderHSV; GtkWidget* expanderHSL; GtkWidget* expanderCMYK; GtkWidget* expanderXYZ; GtkWidget* expanderLAB; GtkWidget* expanderLCH; GtkWidget* expanderInfo; GtkWidget* expanderMain; GtkWidget* expanderSettings; GtkWidget *swatch_display; GtkWidget *zoomed_display; GtkWidget *color_code; GtkWidget *hsl_control; GtkWidget *hsv_control; GtkWidget *rgb_control; GtkWidget *cmyk_control; GtkWidget *lab_control; GtkWidget *lch_control; GtkWidget *color_name; GtkWidget *statusbar; GtkWidget *contrastCheck; GtkWidget *contrastCheckMsg; GtkWidget *pick_button; guint timeout_source_id; FloatingPicker floating_picker; struct dynvSystem *params; struct dynvSystem *global_params; GlobalState* gs; }ColorPickerArgs; struct ColorCompItem{ GtkWidget *widget; GtkColorComponentComp component; int component_id; }; static int source_set_color(ColorPickerArgs *args, ColorObject* color); static int source_set_nth_color(ColorPickerArgs *args, uint32_t color_n, ColorObject* color); static int source_get_nth_color(ColorPickerArgs *args, uint32_t color_n, ColorObject** color); static void updateMainColorNow(ColorPickerArgs* args) { if (!dynv_get_bool_wd(args->params, "zoomed_enabled", true)){ Color c; gtk_swatch_get_active_color(GTK_SWATCH(args->swatch_display), &c); string text; converter_get_text(c, ConverterArrayType::display, args->gs, text); gtk_color_set_color(GTK_COLOR(args->color_code), &c, text.c_str()); gtk_swatch_set_main_color(GTK_SWATCH(args->swatch_display), &c); } } static gboolean updateMainColor( gpointer data ){ ColorPickerArgs* args=(ColorPickerArgs*)data; GdkScreen *screen; GdkModifierType state; int x, y; gdk_display_get_pointer(gdk_display_get_default(), &screen, &x, &y, &state); int monitor = gdk_screen_get_monitor_at_point(screen, x, y); GdkRectangle monitor_geometry; gdk_screen_get_monitor_geometry(screen, monitor, &monitor_geometry); Vec2 pointer(x,y); Rect2 screen_rect(monitor_geometry.x, monitor_geometry.y, monitor_geometry.x + monitor_geometry.width, monitor_geometry.y + monitor_geometry.height); auto screen_reader = args->gs->getScreenReader(); screen_reader_reset_rect(screen_reader); Rect2 sampler_rect, zoomed_rect, final_rect; sampler_get_screen_rect(args->gs->getSampler(), pointer, screen_rect, &sampler_rect); screen_reader_add_rect(screen_reader, screen, sampler_rect); bool zoomed_enabled = dynv_get_bool_wd(args->params, "zoomed_enabled", true); if (zoomed_enabled){ gtk_zoomed_get_screen_rect(GTK_ZOOMED(args->zoomed_display), pointer, screen_rect, &zoomed_rect); screen_reader_add_rect(screen_reader, screen, zoomed_rect); } screen_reader_update_surface(screen_reader, &final_rect); Vec2 offset; offset = Vec2(sampler_rect.getX() - final_rect.getX(), sampler_rect.getY() - final_rect.getY()); Color c; sampler_get_color_sample(args->gs->getSampler(), pointer, screen_rect, offset, &c); string text; converter_get_text(c, ConverterArrayType::display, args->gs, text); gtk_color_set_color(GTK_COLOR(args->color_code), &c, text.c_str()); gtk_swatch_set_main_color(GTK_SWATCH(args->swatch_display), &c); if (zoomed_enabled){ offset = Vec2(zoomed_rect.getX()-final_rect.getX(), zoomed_rect.getY()-final_rect.getY()); gtk_zoomed_update(GTK_ZOOMED(args->zoomed_display), pointer, screen_rect, offset, screen_reader_get_surface(screen_reader)); } return TRUE; } static gboolean updateMainColorTimer(ColorPickerArgs* args) { updateMainColor(args); return true; } static void updateComponentText(ColorPickerArgs *args, GtkColorComponent *component, const char *type) { Color transformed_color; gtk_color_component_get_transformed_color(component, &transformed_color); lua_State* L = args->gs->getLua(); list str = color_space_color_to_text(type, &transformed_color, L); int j = 0; const char *text[4]; memset(text, 0, sizeof(text)); for (list::iterator i = str.begin(); i != str.end(); i++){ text[j] = (*i).c_str(); j++; if (j > 3) break; } gtk_color_component_set_text(component, text); } static void updateDisplays(ColorPickerArgs *args, GtkWidget *except_widget) { updateMainColorNow(args); Color c, c2; gtk_swatch_get_active_color(GTK_SWATCH(args->swatch_display),&c); if (except_widget != args->hsl_control) gtk_color_component_set_color(GTK_COLOR_COMPONENT(args->hsl_control), &c); if (except_widget != args->hsv_control) gtk_color_component_set_color(GTK_COLOR_COMPONENT(args->hsv_control), &c); if (except_widget != args->rgb_control) gtk_color_component_set_color(GTK_COLOR_COMPONENT(args->rgb_control), &c); if (except_widget != args->cmyk_control) gtk_color_component_set_color(GTK_COLOR_COMPONENT(args->cmyk_control), &c); if (except_widget != args->lab_control) gtk_color_component_set_color(GTK_COLOR_COMPONENT(args->lab_control), &c); if (except_widget != args->lch_control) gtk_color_component_set_color(GTK_COLOR_COMPONENT(args->lch_control), &c); updateComponentText(args, GTK_COLOR_COMPONENT(args->hsl_control), "hsl"); updateComponentText(args, GTK_COLOR_COMPONENT(args->hsv_control), "hsv"); updateComponentText(args, GTK_COLOR_COMPONENT(args->rgb_control), "rgb"); updateComponentText(args, GTK_COLOR_COMPONENT(args->cmyk_control), "cmyk"); updateComponentText(args, GTK_COLOR_COMPONENT(args->lab_control), "lab"); updateComponentText(args, GTK_COLOR_COMPONENT(args->lch_control), "lch"); string color_name = color_names_get(args->gs->getColorNames(), &c, true); gtk_entry_set_text(GTK_ENTRY(args->color_name), color_name.c_str()); gtk_color_get_color(GTK_COLOR(args->contrastCheck), &c2); gtk_color_set_text_color(GTK_COLOR(args->contrastCheck), &c); stringstream ss; ss.setf(ios::fixed, ios::floatfield); Color c_lab, c2_lab; color_rgb_to_lab_d50(&c, &c_lab); color_rgb_to_lab_d50(&c2, &c2_lab); const ColorWheelType *wheel = &color_wheel_types_get()[0]; Color hsl1, hsl2; double hue1, hue2; color_rgb_to_hsl(&c, &hsl1); color_rgb_to_hsl(&c2, &hsl2); wheel->rgbhue_to_hue(hsl1.hsl.hue, &hue1); wheel->rgbhue_to_hue(hsl2.hsl.hue, &hue2); double complementary = std::abs(hue1 - hue2); complementary -= std::floor(complementary); complementary *= std::sin(hsl1.hsl.lightness * M_PI) * std::sin(hsl2.hsl.lightness * M_PI); complementary *= std::sin(hsl1.hsl.saturation * M_PI / 2) * std::sin(hsl2.hsl.saturation * M_PI / 2); ss << std::setprecision(1) << std::abs(c_lab.lab.L - c2_lab.lab.L) + complementary * 50 << "%"; gtk_label_set_text(GTK_LABEL(args->contrastCheckMsg), ss.str().c_str()); } static void on_swatch_active_color_changed(GtkWidget *widget, gint32 new_active_color, gpointer data) { ColorPickerArgs* args = (ColorPickerArgs*)data; updateDisplays(args, widget); } static void on_swatch_color_changed(GtkWidget *widget, gpointer data) { ColorPickerArgs* args = (ColorPickerArgs*)data; updateDisplays(args, widget); } static void addToPalette(const Color *color, ColorPickerArgs *args) { ColorObject *color_object = color_list_new_color_object(args->gs->getColorList(), color); string name = color_names_get(args->gs->getColorNames(), color, dynv_get_bool_wd(args->gs->getSettings(), "gpick.color_names.imprecision_postfix", true)); color_object->setName(name); color_list_add_color_object(args->gs->getColorList(), color_object, 1); color_object->release(); } static void on_swatch_menu_add_to_palette(GtkWidget *widget, ColorPickerArgs *args) { Color color; gtk_swatch_get_active_color(GTK_SWATCH(args->swatch_display), &color); addToPalette(&color, args); } static void on_swatch_menu_add_all_to_palette(GtkWidget *widget, ColorPickerArgs *args) { Color color; for (int i = 1; i < 7; ++i){ gtk_swatch_get_color(GTK_SWATCH(args->swatch_display), i, &color); addToPalette(&color, args); } } static void on_swatch_color_activated(GtkWidget *widget, ColorPickerArgs *args) { Color color; gtk_swatch_get_active_color(GTK_SWATCH(widget), &color); addToPalette(&color, args); } static void on_swatch_center_activated(GtkWidget *widget, ColorPickerArgs *args) { floating_picker_activate(args->floating_picker, true, false, nullptr); } static void on_picker_toggled(GtkWidget *widget, ColorPickerArgs *args) { if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget))){ gtk_swatch_set_active(GTK_SWATCH(args->swatch_display), true); }else{ gtk_swatch_set_active(GTK_SWATCH(args->swatch_display), false); } } static void on_swatch_color_edit(GtkWidget *widget, ColorPickerArgs *args) { Color color; gtk_swatch_get_active_color(GTK_SWATCH(args->swatch_display), &color); ColorObject* color_object = color_list_new_color_object(args->gs->getColorList(), &color); ColorObject* new_color_object = nullptr; if (dialog_color_input_show(GTK_WINDOW(gtk_widget_get_toplevel(args->swatch_display)), args->gs, color_object, &new_color_object) == 0){ source_set_color(args, new_color_object); new_color_object->release(); } color_object->release(); } static void paste_cb(GtkWidget *widget, ColorPickerArgs* args) { ColorObject* color_object; if (copypaste_get_color_object(&color_object, args->gs) == 0){ source_set_color(args, color_object); color_object->release(); } } static void swatch_popup_menu_cb(GtkWidget *widget, ColorPickerArgs* args) { GtkWidget *menu; gint32 button, event_time; Color c; updateMainColor(args); gtk_swatch_get_main_color(GTK_SWATCH(args->swatch_display), &c); ColorObject* color_object; color_object = color_list_new_color_object(args->gs->getColorList(), &c); menu = CopyMenu::newMenu(color_object, args->gs); color_object->release(); gtk_widget_show_all(GTK_WIDGET(menu)); button = 0; event_time = gtk_get_current_event_time (); gtk_menu_popup(GTK_MENU(menu), nullptr, nullptr, nullptr, nullptr, button, event_time); g_object_ref_sink(menu); g_object_unref(menu); } static gboolean swatch_button_press_cb(GtkWidget *widget, GdkEventButton *event, ColorPickerArgs* args){ GtkWidget *menu; int color_index = gtk_swatch_get_color_at(GTK_SWATCH(widget), event->x, event->y); if (event->button == 3 && event->type == GDK_BUTTON_PRESS && color_index>0){ GtkWidget* item; gint32 button, event_time; menu = gtk_menu_new(); Color c; gtk_swatch_get_active_color(GTK_SWATCH(args->swatch_display), &c); item = gtk_menu_item_new_with_image(_("_Add to palette"), gtk_image_new_from_stock(GTK_STOCK_ADD, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(on_swatch_menu_add_to_palette), args); item = gtk_menu_item_new_with_image(_("A_dd all to palette"), gtk_image_new_from_stock(GTK_STOCK_ADD, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(on_swatch_menu_add_all_to_palette), args); gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); ColorObject *color_object = color_list_new_color_object(args->gs->getColorList(), &c); StandardMenu::appendMenu(menu, color_object, args->gs); color_object->release(); gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); item = gtk_menu_item_new_with_image(_("_Edit..."), gtk_image_new_from_stock(GTK_STOCK_EDIT, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(on_swatch_color_edit), args); item = gtk_menu_item_new_with_image(_("_Paste"), gtk_image_new_from_stock(GTK_STOCK_PASTE, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(paste_cb), args); if (copypaste_is_color_object_available(args->gs) != 0){ gtk_widget_set_sensitive(item, false); } gtk_widget_show_all(GTK_WIDGET(menu)); if (event){ button = event->button; event_time = event->time; }else{ button = 0; event_time = gtk_get_current_event_time(); } gtk_menu_popup(GTK_MENU(menu), nullptr, nullptr, nullptr, nullptr, button, event_time); g_object_ref_sink(menu); g_object_unref(menu); } return false; } static gboolean on_swatch_focus_change(GtkWidget *widget, GdkEventFocus *event, gpointer data) { ColorPickerArgs* args = (ColorPickerArgs*)data; if (event->in){ gtk_statusbar_push(GTK_STATUSBAR(args->statusbar), gtk_statusbar_get_context_id(GTK_STATUSBAR(args->statusbar), "swatch_focused"), _("Press Spacebar to sample color under mouse pointer")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(args->pick_button), true); gtk_swatch_set_active(GTK_SWATCH(args->swatch_display), true); }else{ gtk_statusbar_pop(GTK_STATUSBAR(args->statusbar), gtk_statusbar_get_context_id(GTK_STATUSBAR(args->statusbar), "swatch_focused")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(args->pick_button), false); gtk_swatch_set_active(GTK_SWATCH(args->swatch_display), false); } return FALSE; } static gboolean on_key_up(GtkWidget *widget, GdkEventKey *event, gpointer data) { ColorPickerArgs* args=(ColorPickerArgs*)data; guint modifiers = gtk_accelerator_get_default_mod_mask(); switch(event->keyval) { case GDK_KEY_m: { int x, y; gdk_display_get_pointer(gdk_display_get_default(), nullptr, &x, &y, nullptr); math::Vec2 position(x, y); if ((event->state&modifiers) == GDK_CONTROL_MASK){ gtk_zoomed_set_mark(GTK_ZOOMED(args->zoomed_display), 1, position); }else{ gtk_zoomed_set_mark(GTK_ZOOMED(args->zoomed_display), 0, position); } } break; case GDK_KEY_c: if ((event->state&modifiers) == GDK_CONTROL_MASK){ Color c; updateMainColor(args); gtk_swatch_get_main_color(GTK_SWATCH(args->swatch_display), &c); Clipboard::set(c, args->gs); return TRUE; } return FALSE; break; case GDK_KEY_1: gtk_swatch_set_active_index(GTK_SWATCH(args->swatch_display), 1); updateDisplays(args, widget); return TRUE; break; case GDK_KEY_2: gtk_swatch_set_active_index(GTK_SWATCH(args->swatch_display), 2); updateDisplays(args, widget); return TRUE; break; case GDK_KEY_3: gtk_swatch_set_active_index(GTK_SWATCH(args->swatch_display), 3); updateDisplays(args, widget); return TRUE; break; case GDK_KEY_4: gtk_swatch_set_active_index(GTK_SWATCH(args->swatch_display), 4); updateDisplays(args, widget); return TRUE; break; case GDK_KEY_5: gtk_swatch_set_active_index(GTK_SWATCH(args->swatch_display), 5); updateDisplays(args, widget); return TRUE; break; case GDK_KEY_6: gtk_swatch_set_active_index(GTK_SWATCH(args->swatch_display), 6); updateDisplays(args, widget); return TRUE; break; case GDK_KEY_Right: gtk_swatch_move_active(GTK_SWATCH(args->swatch_display),1); updateDisplays(args, widget); return TRUE; break; case GDK_KEY_Left: gtk_swatch_move_active(GTK_SWATCH(args->swatch_display),-1); updateDisplays(args, widget); return TRUE; break; case GDK_KEY_space: updateMainColor(args); gtk_swatch_set_color_to_main(GTK_SWATCH(args->swatch_display)); if (dynv_get_bool_wd(args->params, "sampler.add_to_palette", true)){ Color color; gtk_swatch_get_active_color(GTK_SWATCH(args->swatch_display), &color); ColorObject *color_object = color_list_new_color_object(args->gs->getColorList(), &color); string name=color_names_get(args->gs->getColorNames(), &color, dynv_get_bool_wd(args->gs->getSettings(), "gpick.color_names.imprecision_postfix", true)); color_object->setName(name); color_list_add_color_object(args->gs->getColorList(), color_object, 1); color_object->release(); } if (dynv_get_bool_wd(args->params, "sampler.copy_to_clipboard", true)){ Color color; gtk_swatch_get_active_color(GTK_SWATCH(args->swatch_display), &color); Clipboard::set(color, args->gs); } if (dynv_get_bool_wd(args->params, "sampler.rotate_swatch_after_sample", true)){ gtk_swatch_move_active(GTK_SWATCH(args->swatch_display), 1); } updateDisplays(args, widget); return TRUE; break; case GDK_KEY_a: on_swatch_menu_add_all_to_palette(nullptr, args); return TRUE; break; case GDK_KEY_e: on_swatch_color_edit(nullptr, args); return TRUE; break; default: return FALSE; break; } return FALSE; } int color_picker_key_up(ColorSource* color_source, GdkEventKey *event){ return on_key_up(0, event, color_source); } static void on_oversample_value_changed(GtkRange *slider, gpointer data){ ColorPickerArgs* args=(ColorPickerArgs*)data; sampler_set_oversample(args->gs->getSampler(), (int)gtk_range_get_value(GTK_RANGE(slider))); } static void on_zoom_value_changed(GtkRange *slider, gpointer data){ ColorPickerArgs* args=(ColorPickerArgs*)data; gtk_zoomed_set_zoom(GTK_ZOOMED(args->zoomed_display), gtk_range_get_value(GTK_RANGE(slider))); } static void color_component_change_value(GtkWidget *widget, Color* c, ColorPickerArgs* args){ gtk_swatch_set_active_color(GTK_SWATCH(args->swatch_display), c); updateDisplays(args, widget); } static void color_component_input_clicked(GtkWidget *widget, int component_id, ColorPickerArgs* args){ dialog_color_component_input_show(GTK_WINDOW(gtk_widget_get_toplevel(args->main)), GTK_COLOR_COMPONENT(widget), component_id, dynv_get_dynv(args->params, "component_edit")); } static void ser_decimal_get(GtkColorComponentComp component, int component_id, Color* color, const char *text){ double v; stringstream ss(text); ss >> v; switch (component){ case GtkColorComponentComp::hsv: case GtkColorComponentComp::hsl: if (component_id == 0){ color->ma[component_id] = v / 360; }else{ color->ma[component_id] = v / 100; } break; default: color->ma[component_id] = v / 100; } } static string ser_decimal_set(GtkColorComponentComp component, int component_id, Color* color){ stringstream ss; switch (component){ case GtkColorComponentComp::hsv: case GtkColorComponentComp::hsl: if (component_id == 0){ ss << setprecision(0) << fixed << color->ma[component_id] * 360; }else{ ss << setprecision(0) << fixed << color->ma[component_id] * 100; } break; default: ss << setprecision(0) << fixed << color->ma[component_id] * 100; } return ss.str(); } static struct{ const char *name; const char *human_name; void (*get)(GtkColorComponentComp component, int component_id, Color* color, const char *text); string (*set)(GtkColorComponentComp component, int component_id, Color* color); }serial[] = { {"decimal", "Decimal", ser_decimal_get, ser_decimal_set}, }; static void color_component_copy(GtkWidget *widget, ColorPickerArgs* args){ struct ColorCompItem *comp_item = (struct ColorCompItem*)g_object_get_data(G_OBJECT(gtk_widget_get_parent(widget)), "comp_item"); const char *text = gtk_color_component_get_text(GTK_COLOR_COMPONENT(comp_item->widget), comp_item->component_id); if (text){ gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), text, strlen(text)); gtk_clipboard_store(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD)); gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), text, strlen(text)); } } static void color_component_paste(GtkWidget *widget, ColorPickerArgs* args){ Color color; struct ColorCompItem *comp_item = (struct ColorCompItem*)g_object_get_data(G_OBJECT(gtk_widget_get_parent(widget)), "comp_item"); gtk_color_component_get_transformed_color(GTK_COLOR_COMPONENT(comp_item->widget), &color); gchar *text = gtk_clipboard_wait_for_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD)); if (text){ serial[0].get(comp_item->component, comp_item->component_id, &color, text); gtk_color_component_set_transformed_color(GTK_COLOR_COMPONENT(comp_item->widget), &color); g_free(text); gtk_color_component_get_color(GTK_COLOR_COMPONENT(comp_item->widget), &color); gtk_swatch_set_active_color(GTK_SWATCH(args->swatch_display), &color); updateDisplays(args, comp_item->widget); } } static void color_component_edit(GtkWidget *widget, ColorPickerArgs* args){ struct ColorCompItem *comp_item = (struct ColorCompItem*)g_object_get_data(G_OBJECT(gtk_widget_get_parent(widget)), "comp_item"); dialog_color_component_input_show(GTK_WINDOW(gtk_widget_get_toplevel(args->main)), GTK_COLOR_COMPONENT(comp_item->widget), comp_item->component_id, dynv_get_dynv(args->params, "component_edit")); } static void destroy_comp_item(struct ColorCompItem *comp_item){ delete comp_item; } static gboolean color_component_key_up_cb(GtkWidget *widget, GdkEventButton *event, ColorPickerArgs* args){ if ((event->type == GDK_BUTTON_RELEASE) && (event->button == 3)){ GtkWidget *menu; GtkWidget* item; gint32 button, event_time; menu = gtk_menu_new (); struct ColorCompItem *comp_item = new struct ColorCompItem; comp_item->widget = widget; comp_item->component_id = gtk_color_component_get_component_id_at(GTK_COLOR_COMPONENT(widget), event->x, event->y); comp_item->component = gtk_color_component_get_component(GTK_COLOR_COMPONENT(widget)); g_object_set_data_full(G_OBJECT(menu), "comp_item", comp_item, (GDestroyNotify)destroy_comp_item); item = gtk_menu_item_new_with_image(_("Copy"), gtk_image_new_from_stock(GTK_STOCK_COPY, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(color_component_copy), args); item = gtk_menu_item_new_with_image(_("Paste"), gtk_image_new_from_stock(GTK_STOCK_PASTE, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(color_component_paste), args); gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); item = gtk_menu_item_new_with_image(_("Edit"), gtk_image_new_from_stock(GTK_STOCK_EDIT, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(color_component_edit), args); gtk_widget_show_all(GTK_WIDGET(menu)); if (event){ button = event->button; event_time = event->time; }else{ button = 0; event_time = gtk_get_current_event_time (); } gtk_menu_popup(GTK_MENU(menu), nullptr, nullptr, nullptr, nullptr, button, event_time); g_object_ref_sink(menu); g_object_unref(menu); return true; } return false; } static void on_oversample_falloff_changed(GtkWidget *widget, gpointer data) { GtkTreeIter iter; if (gtk_combo_box_get_active_iter(GTK_COMBO_BOX(widget), &iter)) { GtkTreeModel* model = gtk_combo_box_get_model(GTK_COMBO_BOX(widget)); gint32 falloff_id; gtk_tree_model_get(model, &iter, 2, &falloff_id, -1); ColorPickerArgs* args = (ColorPickerArgs*)data; sampler_set_falloff(args->gs->getSampler(), (SamplerFalloff) falloff_id); } } static GtkWidget* create_falloff_type_list() { GtkListStore *store = gtk_list_store_new(3, GDK_TYPE_PIXBUF, G_TYPE_STRING, G_TYPE_INT); GtkWidget *widget = gtk_combo_box_new_with_model(GTK_TREE_MODEL(store)); gtk_combo_box_set_add_tearoffs(GTK_COMBO_BOX(widget), 0); GtkCellRenderer *renderer = gtk_cell_renderer_pixbuf_new(); gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(widget),renderer, 0); gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(widget), renderer, "pixbuf", 0, nullptr); renderer = gtk_cell_renderer_text_new(); gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(widget), renderer, 0); gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(widget), renderer, "text", 1, nullptr); g_object_unref(GTK_TREE_MODEL(store)); struct{ const char *icon; const char *label; SamplerFalloff falloff; }falloff_types[] = { {"gpick-falloff-none", _("None"), SamplerFalloff::none}, {"gpick-falloff-linear", _("Linear"), SamplerFalloff::linear}, {"gpick-falloff-quadratic", _("Quadratic"), SamplerFalloff::quadratic}, {"gpick-falloff-cubic", _("Cubic"), SamplerFalloff::cubic}, {"gpick-falloff-exponential", _("Exponential"), SamplerFalloff::exponential}, }; GtkIconTheme *icon_theme = gtk_icon_theme_get_default(); gint icon_size; gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, 0, &icon_size); for (size_t i = 0; i < sizeof(falloff_types) / sizeof(falloff_types[0]); ++i){ GError *error = nullptr; GdkPixbuf* pixbuf = gtk_icon_theme_load_icon(icon_theme, falloff_types[i].icon, icon_size, GtkIconLookupFlags(0), &error); if (error) g_error_free(error); GtkTreeIter iter1; gtk_list_store_append(store, &iter1); gtk_list_store_set(store, &iter1, 0, pixbuf, 1, falloff_types[i].label, 2, falloff_types[i].falloff, -1); if (pixbuf) g_object_unref (pixbuf); } return widget; } static int source_destroy(ColorPickerArgs *args) { dynv_set_int32(args->params, "swatch.active_color", gtk_swatch_get_active_index(GTK_SWATCH(args->swatch_display))); Color c; char tmp[32]; for (gint i=1; i<7; ++i){ sprintf(tmp, "swatch.color%d", i); gtk_swatch_get_color(GTK_SWATCH(args->swatch_display), i, &c); dynv_set_color(args->params, tmp, &c); } dynv_set_int32(args->params, "sampler.oversample", sampler_get_oversample(args->gs->getSampler())); dynv_set_int32(args->params, "sampler.falloff", static_cast(sampler_get_falloff(args->gs->getSampler()))); dynv_set_float(args->params, "zoom", gtk_zoomed_get_zoom(GTK_ZOOMED(args->zoomed_display))); dynv_set_int32(args->params, "zoom_size", gtk_zoomed_get_size(GTK_ZOOMED(args->zoomed_display))); dynv_set_bool(args->params, "expander.settings", gtk_expander_get_expanded(GTK_EXPANDER(args->expanderSettings))); dynv_set_bool(args->params, "expander.rgb", gtk_expander_get_expanded(GTK_EXPANDER(args->expanderRGB))); dynv_set_bool(args->params, "expander.hsv", gtk_expander_get_expanded(GTK_EXPANDER(args->expanderHSV))); dynv_set_bool(args->params, "expander.hsl", gtk_expander_get_expanded(GTK_EXPANDER(args->expanderHSL))); dynv_set_bool(args->params, "expander.lab", gtk_expander_get_expanded(GTK_EXPANDER(args->expanderLAB))); dynv_set_bool(args->params, "expander.lch", gtk_expander_get_expanded(GTK_EXPANDER(args->expanderLCH))); dynv_set_bool(args->params, "expander.cmyk", gtk_expander_get_expanded(GTK_EXPANDER(args->expanderCMYK))); dynv_set_bool(args->params, "expander.info", gtk_expander_get_expanded(GTK_EXPANDER(args->expanderInfo))); gtk_color_get_color(GTK_COLOR(args->contrastCheck), &c); dynv_set_color(args->params, "contrast.color", &c); gtk_widget_destroy(args->main); dynv_system_release(args->params); dynv_system_release(args->global_params); delete args; return 0; } static int source_get_color(ColorPickerArgs *args, ColorObject** color_object) { Color color; gtk_swatch_get_active_color(GTK_SWATCH(args->swatch_display), &color); ColorObject *new_color_object = color_list_new_color_object(args->gs->getColorList(), &color); string name = color_names_get(args->gs->getColorNames(), &color, dynv_get_bool_wd(args->gs->getSettings(), "gpick.color_names.imprecision_postfix", true)); new_color_object->setName(name); *color_object = new_color_object; return 0; } static int source_set_nth_color(ColorPickerArgs *args, uint32_t color_n, ColorObject* color_object) { if (color_n < 0 || color_n > 6) return -1; Color color = color_object->getColor(); gtk_swatch_set_color(GTK_SWATCH(args->swatch_display), color_n + 1, &color); updateDisplays(args, 0); return 0; } static int source_get_nth_color(ColorPickerArgs *args, uint32_t color_n, ColorObject** color_object) { if (color_n < 0 || color_n > 6) return -1; Color color; gtk_swatch_get_color(GTK_SWATCH(args->swatch_display), color_n + 1, &color); ColorObject *new_color_object = color_list_new_color_object(args->gs->getColorList(), &color); string name = color_names_get(args->gs->getColorNames(), &color, dynv_get_bool_wd(args->gs->getSettings(), "gpick.color_names.imprecision_postfix", true)); new_color_object->setName(name); *color_object = new_color_object; return 0; } static int source_set_color(ColorPickerArgs *args, ColorObject* color_object) { Color color = color_object->getColor(); gtk_swatch_set_active_color(GTK_SWATCH(args->swatch_display), &color); updateDisplays(args, 0); return 0; } static int source_activate(ColorPickerArgs *args) { if (args->timeout_source_id > 0) { g_source_remove(args->timeout_source_id); args->timeout_source_id = 0; } struct{ GtkWidget *widget; const char *setting; }color_spaces[] = { {args->expanderCMYK, "color_space.cmyk"}, {args->expanderHSL, "color_space.hsl"}, {args->expanderHSV, "color_space.hsv"}, {args->expanderLAB, "color_space.lab"}, {args->expanderLCH, "color_space.lch"}, {args->expanderRGB, "color_space.rgb"}, {0, 0}, }; for (int i = 0; color_spaces[i].setting; i++){ if (dynv_get_bool_wd(args->params, color_spaces[i].setting, true)) gtk_widget_show(color_spaces[i].widget); else gtk_widget_hide(color_spaces[i].widget); } bool out_of_gamut_mask = dynv_get_bool_wd(args->params, "out_of_gamut_mask", true); gtk_color_component_set_out_of_gamut_mask(GTK_COLOR_COMPONENT(args->lab_control), out_of_gamut_mask); gtk_color_component_set_lab_illuminant(GTK_COLOR_COMPONENT(args->lab_control), color_get_illuminant(dynv_get_string_wd(args->params, "lab.illuminant", "D50"))); gtk_color_component_set_lab_observer(GTK_COLOR_COMPONENT(args->lab_control), color_get_observer(dynv_get_string_wd(args->params, "lab.observer", "2"))); updateComponentText(args, GTK_COLOR_COMPONENT(args->lab_control), "lab"); gtk_color_component_set_out_of_gamut_mask(GTK_COLOR_COMPONENT(args->lch_control), out_of_gamut_mask); gtk_color_component_set_lab_illuminant(GTK_COLOR_COMPONENT(args->lch_control), color_get_illuminant(dynv_get_string_wd(args->params, "lab.illuminant", "D50"))); gtk_color_component_set_lab_observer(GTK_COLOR_COMPONENT(args->lch_control), color_get_observer(dynv_get_string_wd(args->params, "lab.observer", "2"))); updateComponentText(args, GTK_COLOR_COMPONENT(args->lch_control), "lch"); auto chain = args->gs->getTransformationChain(); gtk_swatch_set_transformation_chain(GTK_SWATCH(args->swatch_display), chain); gtk_color_set_transformation_chain(GTK_COLOR(args->color_code), chain); gtk_color_set_transformation_chain(GTK_COLOR(args->contrastCheck), chain); if (dynv_get_bool_wd(args->params, "zoomed_enabled", true)){ float refresh_rate = dynv_get_float_wd(args->global_params, "refresh_rate", 30); args->timeout_source_id = g_timeout_add_full(G_PRIORITY_DEFAULT_IDLE, 1000/refresh_rate, (GSourceFunc)updateMainColorTimer, args, (GDestroyNotify)nullptr); } gtk_zoomed_set_size(GTK_ZOOMED(args->zoomed_display), dynv_get_int32_wd(args->params, "zoom_size", 150)); gtk_statusbar_push(GTK_STATUSBAR(args->statusbar), gtk_statusbar_get_context_id(GTK_STATUSBAR(args->statusbar), "focus_swatch"), _("Click on swatch area to begin adding colors to palette")); return 0; } static int source_deactivate(ColorPickerArgs *args){ gtk_statusbar_pop(GTK_STATUSBAR(args->statusbar), gtk_statusbar_get_context_id(GTK_STATUSBAR(args->statusbar), "focus_swatch")); if (args->timeout_source_id > 0){ g_source_remove(args->timeout_source_id); args->timeout_source_id = 0; } return 0; } static ColorObject* get_color_object(struct DragDrop* dd){ ColorPickerArgs* args=(ColorPickerArgs*)dd->userdata; ColorObject *color_object; source_get_color(args, &color_object); return color_object; } static int set_color_object_at(struct DragDrop* dd, ColorObject* color_object, int x, int y, bool move) { gint color_index = gtk_swatch_get_color_at(GTK_SWATCH(dd->widget), x, y); Color color = color_object->getColor(); gtk_swatch_set_color(GTK_SWATCH(dd->widget), color_index, &color); updateDisplays((ColorPickerArgs*)dd->userdata, 0); return 0; } static bool test_at(struct DragDrop* dd, int x, int y){ gint color_index = gtk_swatch_get_color_at(GTK_SWATCH(dd->widget), x, y); if (color_index>0) return true; return false; } void color_picker_set_floating_picker(ColorSource *color_source, FloatingPicker floating_picker){ ColorPickerArgs* args = (ColorPickerArgs*)color_source; args->floating_picker = floating_picker; } static ColorObject* get_color_object_contrast(struct DragDrop* dd) { ColorPickerArgs* args = static_cast(dd->userdata); Color color; gtk_color_get_color(GTK_COLOR(dd->widget), &color); string name = color_names_get(args->gs->getColorNames(), &color, dynv_get_bool_wd(args->gs->getSettings(), "gpick.color_names.imprecision_postfix", true)); return new ColorObject(name, color); } static int set_color_object_at_contrast(struct DragDrop* dd, ColorObject* color_object, int x, int y, bool move) { ColorPickerArgs* args = static_cast(dd->userdata); Color color = color_object->getColor(); gtk_color_set_color(GTK_COLOR(args->contrastCheck), &color, "Sample"); updateDisplays((ColorPickerArgs*)dd->userdata, 0); return 0; } static void show_dialog_converter(GtkWidget *widget, ColorPickerArgs *args){ dialog_converter_show(GTK_WINDOW(gtk_widget_get_toplevel(args->main)), args->gs); return; } static void on_zoomed_activate(GtkWidget *widget, ColorPickerArgs *args){ if (dynv_get_bool_wd(args->params, "zoomed_enabled", true)){ gtk_zoomed_set_fade(GTK_ZOOMED(args->zoomed_display), true); dynv_set_bool(args->params, "zoomed_enabled", false); if (args->timeout_source_id > 0){ g_source_remove(args->timeout_source_id); args->timeout_source_id = 0; } }else{ gtk_zoomed_set_fade(GTK_ZOOMED(args->zoomed_display), false); dynv_set_bool(args->params, "zoomed_enabled", true); if (args->timeout_source_id > 0){ g_source_remove(args->timeout_source_id); args->timeout_source_id = 0; } float refresh_rate = dynv_get_float_wd(args->global_params, "refresh_rate", 30); args->timeout_source_id = g_timeout_add_full(G_PRIORITY_DEFAULT_IDLE, 1000/refresh_rate, (GSourceFunc)updateMainColorTimer, args, (GDestroyNotify)nullptr); } return; } static ColorSource* source_implement(ColorSource *source, GlobalState *gs, struct dynvSystem *dynv_namespace){ ColorPickerArgs* args = new ColorPickerArgs; args->params = dynv_system_ref(dynv_namespace); args->global_params = dynv_get_dynv(gs->getSettings(), "gpick.picker"); args->statusbar = gs->getStatusBar(); args->floating_picker = 0; color_source_init(&args->source, source->identificator, source->hr_name); args->source.destroy = (int (*)(ColorSource *source))source_destroy; args->source.get_color = (int (*)(ColorSource *source, ColorObject** color))source_get_color; args->source.set_color = (int (*)(ColorSource *source, ColorObject* color))source_set_color; args->source.get_nth_color = (int (*)(ColorSource *source, size_t color_n, ColorObject** color))source_get_nth_color; args->source.set_nth_color = (int (*)(ColorSource *source, size_t color_n, ColorObject* color))source_set_nth_color; args->source.activate = (int (*)(ColorSource *source))source_activate; args->source.deactivate = (int (*)(ColorSource *source))source_deactivate; args->gs = gs; args->timeout_source_id = 0; GtkWidget *vbox, *widget, *expander, *table, *main_hbox, *scrolled; int table_y; main_hbox = gtk_hbox_new(false, 5); vbox = gtk_vbox_new(false, 0); gtk_box_pack_start(GTK_BOX(main_hbox), vbox, false, false, 0); widget = gtk_toggle_button_new_with_label(_("Pick color")); g_signal_connect(G_OBJECT(widget), "toggled", G_CALLBACK(on_picker_toggled), args); g_signal_connect(G_OBJECT(widget), "key_press_event", G_CALLBACK(on_key_up), args); g_signal_connect(G_OBJECT(widget), "focus-out-event", G_CALLBACK(on_swatch_focus_change), args); gtk_box_pack_start(GTK_BOX(vbox), widget, false, false, 0); args->pick_button = widget; widget = gtk_swatch_new(); gtk_box_pack_start(GTK_BOX(vbox), widget, false, false, 0); g_signal_connect(G_OBJECT(widget), "focus-in-event", G_CALLBACK(on_swatch_focus_change), args); g_signal_connect(G_OBJECT(widget), "focus-out-event", G_CALLBACK(on_swatch_focus_change), args); g_signal_connect(G_OBJECT(widget), "key_press_event", G_CALLBACK(on_key_up), args); g_signal_connect(G_OBJECT(widget), "active_color_changed", G_CALLBACK(on_swatch_active_color_changed), args); g_signal_connect(G_OBJECT(widget), "color_changed", G_CALLBACK(on_swatch_color_changed), args); g_signal_connect(G_OBJECT(widget), "color_activated", G_CALLBACK(on_swatch_color_activated), args); g_signal_connect(G_OBJECT(widget), "center_activated", G_CALLBACK(on_swatch_center_activated), args); g_signal_connect_after(G_OBJECT(widget), "button-press-event",G_CALLBACK(swatch_button_press_cb), args); g_signal_connect(G_OBJECT(widget), "popup-menu", G_CALLBACK(swatch_popup_menu_cb), args); gtk_swatch_set_active_index(GTK_SWATCH(widget), dynv_get_int32_wd(args->params, "swatch.active_color", 1)); args->swatch_display = widget; gtk_drag_dest_set(widget, GtkDestDefaults(GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_HIGHLIGHT), 0, 0, GDK_ACTION_COPY); gtk_drag_source_set(widget, GDK_BUTTON1_MASK, 0, 0, GDK_ACTION_COPY); struct DragDrop dd; dragdrop_init(&dd, gs); dd.userdata = args; dd.get_color_object = get_color_object; dd.set_color_object_at = set_color_object_at; dd.test_at = test_at; dd.handler_map = dynv_system_get_handler_map(gs->getColorList()->params); dragdrop_widget_attach(widget, DragDropFlags(DRAGDROP_SOURCE | DRAGDROP_DESTINATION), &dd); { char tmp[32]; const Color *c; for (gint i=1; i<7; ++i){ sprintf(tmp, "swatch.color%d", i); c = dynv_get_color_wd(args->params, tmp, 0); if (c){ gtk_swatch_set_color(GTK_SWATCH(args->swatch_display), i, (Color*)c); } } } args->color_code = gtk_color_new(); gtk_box_pack_start (GTK_BOX(vbox), args->color_code, false, true, 0); g_signal_connect(G_OBJECT(args->color_code), "activated", G_CALLBACK(show_dialog_converter), args); args->zoomed_display = gtk_zoomed_new(); if (!dynv_get_bool_wd(args->params, "zoomed_enabled", true)){ gtk_zoomed_set_fade(GTK_ZOOMED(args->zoomed_display), true); } gtk_zoomed_set_size(GTK_ZOOMED(args->zoomed_display), dynv_get_int32_wd(args->params, "zoom_size", 150)); gtk_box_pack_start (GTK_BOX(vbox), args->zoomed_display, false, false, 0); g_signal_connect(G_OBJECT(args->zoomed_display), "activated", G_CALLBACK(on_zoomed_activate), args); scrolled = gtk_scrolled_window_new(0, 0); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_box_pack_start (GTK_BOX(main_hbox), scrolled, true, true, 0); vbox = gtk_vbox_new(false, 5); gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(scrolled), vbox); expander=gtk_expander_new(_("Settings")); gtk_expander_set_expanded(GTK_EXPANDER(expander), dynv_get_bool_wd(args->params, "expander.settings", false)); args->expanderSettings=expander; gtk_box_pack_start (GTK_BOX(vbox), expander, FALSE, FALSE, 0); table = gtk_table_new(6, 2, FALSE); table_y=0; gtk_container_add(GTK_CONTAINER(expander), table); gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Oversample:"),0,0.5,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); widget = gtk_hscale_new_with_range (0,16,1); g_signal_connect (G_OBJECT (widget), "value-changed", G_CALLBACK (on_oversample_value_changed), args); gtk_range_set_value(GTK_RANGE(widget), dynv_get_int32_wd(args->params, "sampler.oversample", 0)); gtk_table_attach(GTK_TABLE(table), widget,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); table_y++; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Falloff:"),0,0.5,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); widget = create_falloff_type_list(); g_signal_connect (G_OBJECT (widget), "changed", G_CALLBACK (on_oversample_falloff_changed), args); gtk_combo_box_set_active(GTK_COMBO_BOX(widget), dynv_get_int32_wd(args->params, "sampler.falloff", static_cast(SamplerFalloff::none))); gtk_table_attach(GTK_TABLE(table), widget,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); table_y++; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Zoom:"),0,0.5,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); widget = gtk_hscale_new_with_range (0, 100, 1); g_signal_connect (G_OBJECT (widget), "value-changed", G_CALLBACK (on_zoom_value_changed), args); gtk_range_set_value(GTK_RANGE(widget), dynv_get_float_wd(args->params, "zoom", 20)); gtk_table_attach(GTK_TABLE(table), widget,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); table_y++; expander=gtk_expander_new("HSV"); gtk_expander_set_expanded(GTK_EXPANDER(expander), dynv_get_bool_wd(args->params, "expander.hsv", false)); args->expanderHSV=expander; gtk_box_pack_start(GTK_BOX(vbox), expander, FALSE, FALSE, 0); widget = gtk_color_component_new(GtkColorComponentComp::hsv); const char *hsv_labels[] = {"H", _("Hue"), "S", _("Saturation"), "V", _("Value"), nullptr}; gtk_color_component_set_label(GTK_COLOR_COMPONENT(widget), hsv_labels); args->hsv_control = widget; g_signal_connect(G_OBJECT(widget), "color-changed", G_CALLBACK(color_component_change_value), args); g_signal_connect(G_OBJECT(widget), "button_release_event", G_CALLBACK(color_component_key_up_cb), args); g_signal_connect(G_OBJECT(widget), "input-clicked", G_CALLBACK(color_component_input_clicked), args); gtk_container_add(GTK_CONTAINER(expander), widget); expander=gtk_expander_new("HSL"); gtk_expander_set_expanded(GTK_EXPANDER(expander), dynv_get_bool_wd(args->params, "expander.hsl", false)); args->expanderHSL = expander; gtk_box_pack_start(GTK_BOX(vbox), expander, FALSE, FALSE, 0); widget = gtk_color_component_new(GtkColorComponentComp::hsl); const char *hsl_labels[] = {"H", _("Hue"), "S", _("Saturation"), "L", _("Lightness"), nullptr}; gtk_color_component_set_label(GTK_COLOR_COMPONENT(widget), hsl_labels); args->hsl_control = widget; g_signal_connect(G_OBJECT(widget), "color-changed", G_CALLBACK(color_component_change_value), args); g_signal_connect(G_OBJECT(widget), "button_release_event", G_CALLBACK(color_component_key_up_cb), args); g_signal_connect(G_OBJECT(widget), "input-clicked", G_CALLBACK(color_component_input_clicked), args); gtk_container_add(GTK_CONTAINER(expander), widget); expander=gtk_expander_new("RGB"); gtk_expander_set_expanded(GTK_EXPANDER(expander), dynv_get_bool_wd(args->params, "expander.rgb", false)); args->expanderRGB = expander; gtk_box_pack_start (GTK_BOX(vbox), expander, FALSE, FALSE, 0); widget = gtk_color_component_new(GtkColorComponentComp::rgb); const char *rgb_labels[] = {"R", _("Red"), "G", _("Green"), "B", _("Blue"), nullptr}; gtk_color_component_set_label(GTK_COLOR_COMPONENT(widget), rgb_labels); args->rgb_control = widget; g_signal_connect(G_OBJECT(widget), "color-changed", G_CALLBACK(color_component_change_value), args); g_signal_connect(G_OBJECT(widget), "button_release_event", G_CALLBACK(color_component_key_up_cb), args); g_signal_connect(G_OBJECT(widget), "input-clicked", G_CALLBACK(color_component_input_clicked), args); gtk_container_add(GTK_CONTAINER(expander), widget); expander=gtk_expander_new("CMYK"); gtk_expander_set_expanded(GTK_EXPANDER(expander), dynv_get_bool_wd(args->params, "expander.cmyk", false)); args->expanderCMYK = expander; gtk_box_pack_start(GTK_BOX(vbox), expander, FALSE, FALSE, 0); widget = gtk_color_component_new(GtkColorComponentComp::cmyk); const char *cmyk_labels[] = {"C", _("Cyan"), "M", _("Magenta"), "Y", _("Yellow"), "K", _("Key"), nullptr}; gtk_color_component_set_label(GTK_COLOR_COMPONENT(widget), cmyk_labels); args->cmyk_control = widget; g_signal_connect(G_OBJECT(widget), "color-changed", G_CALLBACK(color_component_change_value), args); g_signal_connect(G_OBJECT(widget), "button_release_event", G_CALLBACK(color_component_key_up_cb), args); g_signal_connect(G_OBJECT(widget), "input-clicked", G_CALLBACK(color_component_input_clicked), args); gtk_container_add(GTK_CONTAINER(expander), widget); expander = gtk_expander_new("Lab"); gtk_expander_set_expanded(GTK_EXPANDER(expander), dynv_get_bool_wd(args->params, "expander.lab", false)); args->expanderLAB = expander; gtk_box_pack_start (GTK_BOX(vbox), expander, FALSE, FALSE, 0); widget = gtk_color_component_new(GtkColorComponentComp::lab); const char *lab_labels[] = {"L", _("Lightness"), "a", "a", "b", "b", nullptr}; gtk_color_component_set_label(GTK_COLOR_COMPONENT(widget), lab_labels); args->lab_control = widget; g_signal_connect(G_OBJECT(widget), "color-changed", G_CALLBACK(color_component_change_value), args); g_signal_connect(G_OBJECT(widget), "button_release_event", G_CALLBACK(color_component_key_up_cb), args); g_signal_connect(G_OBJECT(widget), "input-clicked", G_CALLBACK(color_component_input_clicked), args); gtk_container_add(GTK_CONTAINER(expander), widget); expander = gtk_expander_new("LCH"); gtk_expander_set_expanded(GTK_EXPANDER(expander), dynv_get_bool_wd(args->params, "expander.lch", false)); args->expanderLCH = expander; gtk_box_pack_start (GTK_BOX(vbox), expander, FALSE, FALSE, 0); widget = gtk_color_component_new(GtkColorComponentComp::lch); const char *lch_labels[] = {"L", _("Lightness"), "C", "Chroma", "H", "Hue", nullptr}; gtk_color_component_set_label(GTK_COLOR_COMPONENT(widget), lch_labels); args->lch_control = widget; g_signal_connect(G_OBJECT(widget), "color-changed", G_CALLBACK(color_component_change_value), args); g_signal_connect(G_OBJECT(widget), "button_release_event", G_CALLBACK(color_component_key_up_cb), args); g_signal_connect(G_OBJECT(widget), "input-clicked", G_CALLBACK(color_component_input_clicked), args); gtk_container_add(GTK_CONTAINER(expander), widget); expander=gtk_expander_new(_("Info")); gtk_expander_set_expanded(GTK_EXPANDER(expander), dynv_get_bool_wd(args->params, "expander.info", false)); args->expanderInfo=expander; gtk_box_pack_start (GTK_BOX(vbox), expander, FALSE, FALSE, 0); table = gtk_table_new(3, 2, FALSE); table_y=0; gtk_container_add(GTK_CONTAINER(expander), table); gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Color name:"),0,0.5,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); widget = gtk_entry_new(); gtk_table_attach(GTK_TABLE(table), widget,1,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); gtk_editable_set_editable(GTK_EDITABLE(widget), FALSE); //gtk_widget_set_sensitive(GTK_WIDGET(widget), FALSE); args->color_name = widget; table_y++; dragdrop_init(&dd, gs); dd.userdata = args; dd.get_color_object = get_color_object_contrast; dd.set_color_object_at = set_color_object_at_contrast; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Contrast:"),0,0.5,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); widget = gtk_color_new(); Color *c; if ((c = const_cast(dynv_get_color_wd(args->params, "contrast.color", 0)))){ gtk_color_set_color(GTK_COLOR(widget), c, _("Sample")); }else{ Color c; c.rgb.red = 1; c.rgb.green = 1; c.rgb.blue = 1; gtk_color_set_color(GTK_COLOR(widget), &c, _("Sample")); } gtk_color_set_rounded(GTK_COLOR(widget), true); gtk_color_set_hcenter(GTK_COLOR(widget), true); gtk_color_set_roundness(GTK_COLOR(widget), 5); gtk_table_attach(GTK_TABLE(table), widget,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); args->contrastCheck = widget; gtk_drag_dest_set(widget, GtkDestDefaults(GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_HIGHLIGHT), 0, 0, GDK_ACTION_COPY); gtk_drag_source_set(widget, GDK_BUTTON1_MASK, 0, 0, GDK_ACTION_COPY); dd.handler_map = dynv_system_get_handler_map(gs->getColorList()->params); dd.userdata2 = 0; dragdrop_widget_attach(widget, DragDropFlags(DRAGDROP_SOURCE | DRAGDROP_DESTINATION), &dd); gtk_table_attach(GTK_TABLE(table), args->contrastCheckMsg = gtk_label_new(""),2,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,5); table_y++; updateDisplays(args, 0); args->main = main_hbox; gtk_widget_show_all(main_hbox); args->source.widget = main_hbox; return (ColorSource*)args; } int color_picker_source_register(ColorSourceManager *csm) { ColorSource *color_source = new ColorSource; color_source_init(color_source, "color_picker", _("Color picker")); color_source->implement = (ColorSource* (*)(ColorSource *source, GlobalState *gs, struct dynvSystem *dynv_namespace))source_implement; color_source->single_instance_only = true; color_source->default_accelerator = GDK_KEY_c; color_source_manager_add_source(csm, color_source); return 0; } gpick-gpick-0.2.6rc1/source/ColorPicker.h000066400000000000000000000036671315430016700202160ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_COLOR_PICKER_H_ #define GPICK_COLOR_PICKER_H_ #include "FloatingPicker.h" #include struct ColorSource; struct ColorSourceManager; int color_picker_source_register(ColorSourceManager *csm); int color_picker_key_up(ColorSource* color_source, GdkEventKey *event); void color_picker_set_floating_picker(ColorSource *color_source, FloatingPicker floating_picker); #endif /* GPICK_COLOR_PICKER_H_ */ gpick-gpick-0.2.6rc1/source/ColorRYB.cpp000066400000000000000000000203141315430016700177540ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ColorRYB.h" #include "MathUtil.h" #include "BezierCubicCurve.h" #include "Vector2.h" #include #include #include #include using namespace std; typedef math::Vec2 point; typedef math::BezierCubicCurve bezier; double bezier_eval_at_x(list& channel, double x, double delta){ for (list::iterator i=channel.begin(); i != channel.end(); ++i){ if (x>=(*i)->p0.x && x<=(*i)->p3.x){ double width = ((*i)->p3.x-(*i)->p0.x); double t = (x-(*i)->p0.x)/width; double d; point v; for (int limit=50; limit>0; --limit){ v = (**i)(t); d = v.x - x; if (fabs(d)1) t=1; else if (t<0) t=0; } } } return 0; } static void color_get_ryb_curves(list &red, list &green, list &blue){ static bezier red_v[]={ bezier( point(0.0, 1.0), point(1.0, 1.0), point(13.0, 1.0), point(14.0, 1.0) ), bezier( point(14.0, 1.0), point(16.0, 0.6405), point(16.9, 0.0), point(21.0, 0.0) ), bezier( point(21.0, 0.0), point(28.0, 0.0), point(33.0, 1.0), point(36.0, 1.0) ) }; static bezier green_v[]={ bezier( point(0.0, 0.0), point(4.0, 0.4), point(13.0, 1.0), point(14.0, 1.0) ), bezier( point(14.0, 1.0), point(14.85, 1.0), point(17.05, 0.9525), point(19.0, 0.7) ), bezier( point(19.0, 0.7), point(24.0, 0.05), point(31.0, 0.0), point(36.0, 0.0) ) }; static bezier blue_v[]={ bezier( point(0.0, 0.0), point(1.0, 0.0), point(18.0, 0.0), point(19.0, 0.0) ), bezier( point(19.0, 0.0), point(22.0, 1.0), point(33.0, 1.0), point(36.0, 0.0) ) }; for (uint32_t i=0; i red, green, blue; color_get_ryb_curves(red, green, blue); double hue = rgb_hue; double d; double delta = 1/3600.0; Color color, color2; for (int limit=100; limit>0; --limit){ color.rgb.red = bezier_eval_at_x(red, hue*36, 0.01), color.rgb.green = bezier_eval_at_x(green, hue*36, 0.01), color.rgb.blue = bezier_eval_at_x(blue, hue*36, 0.01); color_rgb_to_hsv(&color, &color2); d = rgb_hue - color2.hsv.hue; if (fabs(d)1) hue=1; else if (hue<0) hue=0; } *ryb_hue = hue; return -1; } double color_rybhue_to_rgbhue_f(double hue){ if (hue>=4.0/6.0 && hue<=6.0/6.0){ return ((285.12*hue*hue)-(81.252*hue)+155.18)/360.0; }else if (hue>=0.0/6.0 && hue<=1.0/6.0){ return ((-544.32*hue*hue)+(301.896*hue))/360.0; }else if (hue>=1.0/6.0 && hue<=3.0/6.0){ return ((609.12*hue*hue)-(153.72*hue)+45.166)/360.0; }else if (hue>=3.0/6.0 && hue<=4.0/6.0){ return ((-1088.64*hue*hue)+(1916.46*hue)-567.45)/360.0; } return 0; } int color_rgbhue_to_rybhue_f(double rgb_hue, double* ryb_hue){ double hue = rgb_hue; double d; double delta = 1/3600.0; for (int limit=100; limit>0; --limit){ d = rgb_hue - color_rybhue_to_rgbhue_f(hue); if (fabs(d)1) hue=1; else if (hue<0) hue=0; } *ryb_hue = hue; return -1; } void color_rybhue_to_rgb(double hue, Color* color){ list red, green, blue; color_get_ryb_curves(red, green, blue); color->rgb.red = bezier_eval_at_x(red, hue*36, 0.01), color->rgb.green = bezier_eval_at_x(green, hue*36, 0.01), color->rgb.blue = bezier_eval_at_x(blue, hue*36, 0.01); } double color_ryb_transform_lightness(double hue1, double hue2){ double t; hue1 = modf(hue1, &t); hue2 = modf(hue2, &t); double values[]={ 0.50000000, 0.50000000, 0.50000000, 0.50000000, 0.50000000, 0.50000000, 0.50000000, 0.50000000, 0.50000000, 0.50000000, 0.50000000, 0.50000000, 0.50000000, 0.46470600, 0.42745101, 0.39215699, 0.37450999, 0.35490200, 0.33725500, 0.35294101, 0.36862749, 0.38431349, 0.37254900, 0.36078450, 0.34901950, 0.34313750, 0.33529401, 0.32941201, 0.32549000, 0.31960800, 0.31568649, 0.33921549, 0.36470601, 0.38823551, 0.42548999, 0.46274501, 0.50000000, }; int32_t samples=sizeof(values)/sizeof(double)-1; double n; return mix_double(values[int(floor(hue2*samples))], values[int(floor(hue2*samples))+1], modf(hue2*samples,&n))/ mix_double(values[int(floor(hue2*samples))], values[int(floor(hue1*samples))+1], modf(hue1*samples,&n)); } double color_ryb_transform_hue(double hue, bool forward){ double values[]={ 0.00000000, 0.02156867, 0.04248367, 0.06405234, 0.07385617, 0.08431367, 0.09411767, 0.10653600, 0.11830067, 0.13071899, 0.14248367, 0.15490200, 0.16666667, 0.18354435, 0.19954120, 0.21666662, 0.25130904, 0.28545108, 0.31976745, 0.38981494, 0.46010628, 0.53061217, 0.54649121, 0.56159425, 0.57771534, 0.60190469, 0.62573093, 0.64980155, 0.68875504, 0.72801632, 0.76708061, 0.80924863, 0.85215056, 0.89478123, 0.92933953, 0.96468931, 1.00000000, 1.00000000, }; int32_t samples=sizeof(values)/sizeof(double)-2; double new_hue; double t; hue = modf(hue, &t); if (!forward){ for (int32_t i=0; i=hue){ int index1, index2; double value1, value2, mix; index1=i; index2=i+1; value1=index1 / (double)samples; value2=index2 / (double)samples; mix = (hue-values[index1])/(values[index2]-values[index1]); new_hue= mix_double(value1, value2, mix); return new_hue; } } return 1; }else{ double value1=values[int(hue*samples)]; double value2=values[int(hue*samples+1)]; double n; double mix = modf(hue*samples, &n); new_hue = mix_double(value1, value2, mix); return new_hue; } return 0; } gpick-gpick-0.2.6rc1/source/ColorRYB.h000066400000000000000000000040021315430016700174150ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef COLORRYB_H_ #define COLORRYB_H_ #include "Color.h" #ifndef _MSC_VER #include #endif #include double color_ryb_transform_lightness(double hue1, double hue2); double color_ryb_transform_hue(double hue, bool forward); void color_rybhue_to_rgb(double hue, Color* color); int color_rgbhue_to_rybhue(double rgb_hue, double* ryb_hue); double color_rybhue_to_rgbhue_f(double hue); int color_rgbhue_to_rybhue_f(double rgb_hue, double* ryb_hue); #endif /* COLORRYB_H_ */ gpick-gpick-0.2.6rc1/source/ColorSource.cpp000066400000000000000000000077501315430016700205710ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ColorSource.h" #include #include using namespace std; int color_source_init(ColorSource* source, const char *identificator, const char *name) { source->identificator = g_strdup(identificator); source->hr_name = g_strdup(name); source->set_color = 0; source->get_color = 0; source->set_nth_color = 0; source->get_nth_color = 0; source->activate = 0; source->deactivate = 0; source->destroy = 0; source->set_slot_color = 0; source->query_slots = 0; source->userdata = 0; source->implement = 0; source->widget = 0; source->single_instance_only = false; source->needs_viewport = true; return 0; } int color_source_activate(ColorSource *source) { if (source->activate) return source->activate(source); return -1; } int color_source_deactivate(ColorSource *source) { if (source->deactivate) return source->deactivate(source); return -1; } int color_source_set_color(ColorSource *source, ColorObject *color) { if (source && source->set_color) return source->set_color(source, color); else if (!source) cerr << "Color source undefined" << endl; return -1; } int color_source_get_color(ColorSource *source, ColorObject **color) { if (source && source->get_color) return source->get_color(source, color); else if (!source) cerr << "Color source undefined" << endl; return -1; } int color_source_set_nth_color(ColorSource *source, size_t color_n, ColorObject *color) { if (source && source->set_nth_color) return source->set_nth_color(source, color_n, color); else if (!source) cerr << "Color source undefined" << endl; return -1; } int color_source_get_nth_color(ColorSource *source, size_t color_n, ColorObject **color) { if (source && source->get_nth_color) return source->get_nth_color(source, color_n, color); else if (!source) cerr << "Color source undefined" << endl; return -1; } int color_source_get_default_accelerator(ColorSource *source) { if (source && source->default_accelerator) return source->default_accelerator; else if (!source) cerr << "Color source undefined" << endl; return 0; } int color_source_destroy(ColorSource* source) { if (source->destroy) return source->destroy(source); g_free(source->identificator); g_free(source->hr_name); delete source; return 0; } ColorSource* color_source_implement(ColorSource* source, GlobalState *gs, struct dynvSystem *dynv_namespace) { return source->implement(source, gs, dynv_namespace); } GtkWidget* color_source_get_widget(ColorSource* source) { return source->widget; } gpick-gpick-0.2.6rc1/source/ColorSource.h000066400000000000000000000066151315430016700202350ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_COLOR_SOURCE_H_ #define GPICK_COLOR_SOURCE_H_ #include class GlobalState; class ColorObject; struct ColorSourceSlot{ const char *identificator; const char *hr_name; size_t id; struct{ bool read; bool write; }supports; }; typedef struct ColorSource{ char *identificator; char *hr_name; int (*set_color)(ColorSource *source, ColorObject *color); int (*get_color)(ColorSource *source, ColorObject **color); int (*set_nth_color)(ColorSource *source, size_t color_n, ColorObject *color); int (*get_nth_color)(ColorSource *source, size_t color_n, ColorObject **color); int (*activate)(ColorSource *source); int (*deactivate)(ColorSource *source); int (*query_slots)(ColorSource *source, ColorSourceSlot *slot); int (*set_slot_color)(ColorSource *source, size_t slot_id, ColorObject *color); ColorSource* (*implement)(ColorSource *source, GlobalState *gs, struct dynvSystem *dynv_namespace); int (*destroy)(ColorSource *source); bool single_instance_only; bool needs_viewport; int default_accelerator; GtkWidget *widget; void* userdata; }ColorSource; int color_source_init(ColorSource* source, const char *identificator, const char *name); int color_source_activate(ColorSource *source); int color_source_deactivate(ColorSource *source); int color_source_set_color(ColorSource *source, ColorObject *color); int color_source_set_nth_color(ColorSource *source, size_t color_n, ColorObject *color); int color_source_get_color(ColorSource *source, ColorObject *color); int color_source_get_nth_color(ColorSource *source, size_t color_n, ColorObject **color); int color_source_get_default_accelerator(ColorSource *source); ColorSource* color_source_implement(ColorSource* source, GlobalState *gs, struct dynvSystem *dynv_namespace); GtkWidget* color_source_get_widget(ColorSource* source); int color_source_destroy(ColorSource* source); #endif /* GPICK_COLOR_SOURCE_H_ */ gpick-gpick-0.2.6rc1/source/ColorSourceManager.cpp000066400000000000000000000054161315430016700220610ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ColorSourceManager.h" #include "ColorSource.h" #include #include using namespace std; ColorSourceManager* color_source_manager_create(){ ColorSourceManager *csm = new ColorSourceManager; return csm; } int color_source_manager_add_source(ColorSourceManager *csm, ColorSource *source){ pair::iterator, bool> r; r = csm->colorsource.insert(pair(source->identificator, source)); return r.second; } ColorSource* color_source_manager_get(ColorSourceManager *csm, const char *name){ map::iterator i = csm->colorsource.find(name); if (i != csm->colorsource.end()){ return (*i).second; } return 0; } vector color_source_manager_get_all(ColorSourceManager *csm){ vector ret; ret.resize(csm->colorsource.size()); size_t j = 0; for (map::iterator i = csm->colorsource.begin(); i != csm->colorsource.end(); ++i){ ret[j] = (*i).second; j++; } return ret; } int color_source_manager_destroy(ColorSourceManager *csm){ for (map::iterator i = csm->colorsource.begin(); i != csm->colorsource.end(); ++i){ color_source_destroy((*i).second); } csm->colorsource.clear(); delete csm; return 0; } gpick-gpick-0.2.6rc1/source/ColorSourceManager.h000066400000000000000000000042041315430016700215200ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_COLOR_SOURCE_MANAGER_H_ #define GPICK_COLOR_SOURCE_MANAGER_H_ #include #include #include struct ColorSource; struct ColorSourceManager{ std::map colorsource; }; ColorSourceManager* color_source_manager_create(); int color_source_manager_add_source(ColorSourceManager *csm, ColorSource *source); ColorSource* color_source_manager_get(ColorSourceManager *csm, const char *name); std::vector color_source_manager_get_all(ColorSourceManager *csm); int color_source_manager_destroy(ColorSourceManager *csm); #endif /* GPICK_COLOR_SOURCE_MANAGER_H_ */ gpick-gpick-0.2.6rc1/source/ColorSpaceType.cpp000066400000000000000000000077531315430016700212310ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ColorSpaceType.h" #include "Internationalisation.h" #include "LuaExt.h" extern "C"{ #include } #include using namespace std; const ColorSpaceType color_space_types[] = { {GtkColorComponentComp::hsv, 3, { {_("Hue"), 360, 0, 360, 0.01}, {_("Saturation"), 100, 0, 100, 0.01}, {_("Value"), 100, 0, 100, 0.01}, }, }, {GtkColorComponentComp::hsl, 3, { {_("Hue"), 360, 0, 360, 0.01}, {_("Saturation"), 100, 0, 100, 0.01}, {_("Lightness"), 100, 0, 100, 0.01}, }, }, {GtkColorComponentComp::rgb, 3, { {_("Red"), 255, 0, 255, 0.01}, {_("Green"), 255, 0, 255, 0.01}, {_("Blue"), 255, 0, 255, 0.01}, }, }, {GtkColorComponentComp::cmyk, 4, { {_("Cyan"), 255, 0, 255, 0.01}, {_("Magenta"), 255, 0, 255, 0.01}, {_("Yellow"), 255, 0, 255, 0.01}, {_("Key"), 255, 0, 255, 0.01} } }, {GtkColorComponentComp::lab, 3, { {_("Lightness"), 1, 0, 100, 0.0001}, {"a", 1, -145, 145, 0.0001}, {"b", 1, -145, 145, 0.0001} } }, {GtkColorComponentComp::lch, 3, { {_("Lightness"), 1, 0, 100, 0.0001}, {"Chroma", 1, 0, 100, 0.0001}, {"Hue", 1, 0, 360, 0.0001} } }, }; const ColorSpaceType* color_space_get_types() { return color_space_types; } size_t color_space_count_types() { return sizeof(color_space_types) / sizeof(ColorSpaceType); } std::list color_space_color_to_text(const char *type, const Color *color, lua_State* L) { list result; int status; int stack_top = lua_gettop(L); lua_getglobal(L, "gpick"); int gpick_namespace = lua_gettop(L); if (lua_type(L, -1) != LUA_TNIL){ lua_pushstring(L, "component_to_text"); lua_gettable(L, gpick_namespace); if (lua_type(L, -1) != LUA_TNIL){ lua_pushstring(L, type); lua_pushcolor(L, color); status = lua_pcall(L, 2, 1, 0); if (status == 0){ if (lua_type(L, -1) == LUA_TTABLE){ for (int i = 0; i < 4; i++){ lua_pushinteger(L, i + 1); lua_gettable(L, -2); if (lua_type(L, -1) == LUA_TSTRING){ const char* converted = lua_tostring(L, -1); result.push_back(string(converted)); } lua_pop(L, 1); } lua_settop(L, stack_top); return result; }else{ cerr << "gpick.component_to_text: returned not a table value, type is \"" << type << "\"" << endl; } }else{ cerr << "gpick.component_to_text: " << lua_tostring (L, -1) << endl; } }else{ cerr << "gpick.component_to_text: no such function" << endl; } } lua_settop(L, stack_top); return result; } gpick-gpick-0.2.6rc1/source/ColorSpaceType.h000066400000000000000000000042011315430016700206570ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_COLOR_SPACE_TYPE_H_ #define GPICK_COLOR_SPACE_TYPE_H_ struct Color; #include "gtk/ColorComponent.h" #include #include #include #include struct lua_State; struct ColorSpaceType { GtkColorComponentComp comp_type; int8_t n_items; struct { const char *name; double raw_scale; double min_value; double max_value; double step; }items[4]; }; const ColorSpaceType* color_space_get_types(); size_t color_space_count_types(); std::list color_space_color_to_text(const char *type, const Color *color, lua_State* L); #endif /* GPICK_COLOR_SPACE_TYPE_H_ */ gpick-gpick-0.2.6rc1/source/ColorUtils.h000066400000000000000000000035301315430016700200660ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_COLOR_UTILS_H_ #define GPICK_COLOR_UTILS_H_ #include "Color.h" namespace color_utils { template void mix(const Color &a, const Color &b, T ratio, Color &result) { for (int i = 0; i < 4; i++){ result.ma[i] = a.ma[i] * (1 - ratio) + b.ma[i] * ratio; } }; } #endif /* GPICK_COLOR_UTILS_H_ */ gpick-gpick-0.2.6rc1/source/ColorWheelType.cpp000066400000000000000000000052131315430016700212270ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ColorWheelType.h" #include "ColorRYB.h" #include "MathUtil.h" #include "Internationalisation.h" static void rgb_hue2hue(double hue, Color* hsl){ hsl->hsl.hue = hue; hsl->hsl.saturation = 1; hsl->hsl.lightness = 0.5; } static void rgb_rgbhue2hue(double rgbhue, double *hue){ *hue = rgbhue; } static void ryb1_hue2hue(double hue, Color* hsl){ Color c; color_rybhue_to_rgb(hue, &c); color_rgb_to_hsl(&c, hsl); } static void ryb1_rgbhue2hue(double rgbhue, double *hue){ color_rgbhue_to_rybhue(rgbhue, hue); } static void ryb2_hue2hue(double hue, Color* hsl){ hsl->hsl.hue = color_rybhue_to_rgbhue_f(hue); hsl->hsl.saturation = 1; hsl->hsl.lightness = 0.5; } static void ryb2_rgbhue2hue(double rgbhue, double *hue){ color_rgbhue_to_rybhue_f(rgbhue, hue); } const ColorWheelType color_wheel_types[]={ {N_("RGB"), rgb_hue2hue, rgb_rgbhue2hue}, {N_("RYB v1"), ryb1_hue2hue, ryb1_rgbhue2hue}, {N_("RYB v2"), ryb2_hue2hue, ryb2_rgbhue2hue}, }; const ColorWheelType* color_wheel_types_get(){ return color_wheel_types; } const uint32_t color_wheel_types_get_n(){ return sizeof(color_wheel_types)/sizeof(ColorWheelType); } gpick-gpick-0.2.6rc1/source/ColorWheelType.h000066400000000000000000000053401315430016700206750ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef COLOR_WHEEL_TYPE_H_ #define COLOR_WHEEL_TYPE_H_ #include "Color.h" #include /** \file source/ColorWheelType.h * \brief Color wheel type description structure and functions */ /** \struct ColorWheelType * \brief ColorWheelType structure contains color wheel type name and conversion functions */ typedef struct ColorWheelType{ const char *name; /**< Name of a color wheel */ /** * Callback used to convert color wheel specific hue into the color in a HSL color space * @param[in] hue Color wheel specific hue value * @param[out] hsl Result as a color in HSL color space */ void (*hue_to_hsl)(double hue, Color* hsl); /** * Callback used to convert HSL color space hue into color wheel specific hue * @param[in] rgbhue HSL color space hue value * @param[out] hue Color wheel specific hue value */ void (*rgbhue_to_hue)(double rgbhue, double *hue); }ColorWheelType; /** * Get available color wheel types * @return Constant array of available color wheel types */ const ColorWheelType* color_wheel_types_get(); /** * Get the number of available color wheel types * @return Number of available color wheel types */ const uint32_t color_wheel_types_get_n(); #endif /* COLOR_WHEEL_TYPE_H_ */ gpick-gpick-0.2.6rc1/source/Converter.cpp000066400000000000000000000404071315430016700202750ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Converter.h" #include "DynvHelpers.h" #include "GlobalState.h" #include "ColorObject.h" #include "LuaExt.h" #include #include #include #include #include #include #include #include #include #include #include using namespace std; extern "C"{ #include #include } class ConverterKeyCompare{ public: bool operator() (const char* const& x, const char* const& y) const; }; bool ConverterKeyCompare::operator() (const char* const& x, const char* const& y) const { return strcmp(x,y)<0; } class Converters{ public: typedef std::map ConverterMap; ConverterMap converters; list all_converters; vector copy_converters; vector paste_converters; Converter* display_converter; Converter* color_list_converter; lua_State *L; struct dynvSystem* params; ~Converters(); }; Converters::~Converters() { Converters::ConverterMap::iterator i; for (i=converters.begin(); i != converters.end(); ++i){ g_free(((*i).second)->human_readable); g_free(((*i).second)->function_name); delete ((*i).second); } converters.clear(); } int converters_color_deserialize(Converters* converters, const char* function, const char* text, ColorObject* color_object, float* conversion_quality) { lua_State* L = converters->L; int status; int stack_top = lua_gettop(L); lua_getglobal(L, "gpick"); int gpick_namespace = lua_gettop(L); if (lua_type(L, -1) != LUA_TNIL){ lua_pushstring(L, "color_deserialize"); lua_gettable(L, gpick_namespace); if (lua_type(L, -1) != LUA_TNIL){ lua_pushstring(L, function); lua_pushstring(L, text); lua_pushcolorobject (L, color_object); lua_pushdynvsystem(L, converters->params); status=lua_pcall(L, 4, 1, 0); dynv_system_release(converters->params); if (status == 0){ if (lua_type(L, -1) == LUA_TNUMBER){ double result = luaL_checknumber(L, -1); *conversion_quality = result; lua_settop(L, stack_top); return 0; }else{ cerr<<"gpick.color_deserialize: returned not a number value \""<converters->L; int status; int stack_top = lua_gettop(L); lua_getglobal(L, "gpick"); int gpick_namespace = lua_gettop(L); if (lua_type(L, -1) != LUA_TNIL){ lua_pushstring(L, "color_deserialize"); lua_gettable(L, gpick_namespace); if (lua_type(L, -1) != LUA_TNIL){ lua_pushstring(L, converter->function_name); lua_pushstring(L, text); lua_pushcolorobject (L, color_object); lua_pushdynvsystem(L, converter->converters->params); status = lua_pcall(L, 4, 1, 0); dynv_system_release(converter->converters->params); if (status == 0){ if (lua_type(L, -1) == LUA_TNUMBER){ double result = luaL_checknumber(L, -1); *conversion_quality = result; lua_settop(L, stack_top); return 0; }else{ cerr<<"gpick.color_deserialize: returned not a number value \""<function_name<<"\""<function_name<<"\""<L; int status; int stack_top = lua_gettop(L); lua_getglobal(L, "gpick"); int gpick_namespace = lua_gettop(L); if (lua_type(L, -1) != LUA_TNIL){ lua_pushstring(L, "color_serialize"); lua_gettable(L, gpick_namespace); if (lua_type(L, -1) != LUA_TNIL){ lua_pushstring(L, function); lua_pushcolorobject(L, const_cast(color_object)); lua_pushdynvsystem(L, converters->params); lua_newtable(L); lua_pushboolean(L, position.first); lua_setfield(L, -2, "first"); lua_pushboolean(L, position.last); lua_setfield(L, -2, "last"); lua_pushinteger(L, position.index); lua_setfield(L, -2, "index"); lua_pushinteger(L, position.count); lua_setfield(L, -2, "count"); status = lua_pcall(L, 4, 1, 0); dynv_system_release(converters->params); if (status == 0){ if (lua_type(L, -1) == LUA_TSTRING){ result = luaL_checkstring(L, -1); lua_settop(L, stack_top); return 0; }else{ cerr << "gpick.color_serialize: returned not a string value \"" << function << "\"" << endl; } }else{ cerr << "gpick.color_serialize: " << lua_tostring(L, -1) << endl; } }else{ cerr << "gpick.color_serialize: no such function \"" << function << "\"" <converters->L; int status; int stack_top = lua_gettop(L); lua_getglobal(L, "gpick"); int gpick_namespace = lua_gettop(L); if (lua_type(L, -1) != LUA_TNIL){ lua_pushstring(L, "color_serialize"); lua_gettable(L, gpick_namespace); if (lua_type(L, -1) != LUA_TNIL){ lua_pushstring(L, converter->function_name); lua_pushcolorobject(L, const_cast(color_object)); lua_pushdynvsystem(L, converter->converters->params); lua_newtable(L); lua_pushboolean(L, position.first); lua_setfield(L, -2, "first"); lua_pushboolean(L, position.last); lua_setfield(L, -2, "last"); lua_pushinteger(L, position.index); lua_setfield(L, -2, "index"); lua_pushinteger(L, position.count); lua_setfield(L, -2, "count"); status = lua_pcall(L, 4, 1, 0); dynv_system_release(converter->converters->params); if (status == 0){ if (lua_type(L, -1) == LUA_TSTRING){ result = luaL_checkstring(L, -1); lua_settop(L, stack_top); return 0; }else{ cerr << "gpick.color_serialize: returned not a string value \"" << converter->function_name << "\"" << endl; } }else{ cerr << "gpick.color_serialize: " << lua_tostring(L, -1) << endl; } }else{ cerr << "gpick.color_serialize: no such function \"" << converter->function_name << "\"" <L = L; converters->display_converter = 0; converters->params = dynv_system_ref(settings); int stack_top = lua_gettop(L); lua_getglobal(L, "gpick"); int gpick_namespace = lua_gettop(L); if (lua_type(L, -1) != LUA_TNIL){ lua_pushstring(L, "converters"); lua_gettable(L, gpick_namespace); int converters_table = lua_gettop(L); lua_pushnil(L); while (lua_next(L, converters_table) != 0){ if (lua_type(L, -2) == LUA_TSTRING){ Converter *converter = new Converter; converter->converters = converters; converter->function_name = g_strdup(lua_tostring(L, -2)); converters->converters[converter->function_name] = converter; converters->all_converters.push_back(converter); lua_pushstring(L, "human_readable"); lua_gettable(L, -2); converter->human_readable = g_strdup(lua_tostring(L, -1)); lua_pop(L, 1); lua_pushstring(L, "serialize"); lua_gettable(L, -2); converter->serialize_available = !lua_isnil(L, -1); converter->copy = false; lua_pop(L, 1); lua_pushstring(L, "deserialize"); lua_gettable(L, -2); converter->deserialize_available = !lua_isnil(L, -1); converter->paste = false; lua_pop(L, 1); } lua_pop(L, 1); //pop value from stack, but leave key } } lua_settop(L, stack_top); return converters; } int converters_term(Converters *converters) { dynv_system_release(converters->params); delete converters; return 0; } Converter* converters_get(Converters *converters, const char* name) { Converters::ConverterMap::iterator i; i=converters->converters.find(name); if (i != converters->converters.end()){ return (*i).second; }else{ return nullptr; } } Converter* converters_get_first(Converters *converters, ConverterArrayType type) { switch (type){ case ConverterArrayType::copy: if (converters->copy_converters.size() > 0) return converters->copy_converters[0]; break; case ConverterArrayType::paste: if (converters->paste_converters.size() > 0) return converters->paste_converters[0]; break; case ConverterArrayType::display: return converters->display_converter; break; case ConverterArrayType::color_list: return converters->color_list_converter; break; } return 0; } Converter** converters_get_all_type(Converters *converters, ConverterArrayType type, size_t *size) { switch (type){ case ConverterArrayType::copy: if (converters->copy_converters.size() > 0){ *size = converters->copy_converters.size(); return &converters->copy_converters[0]; } break; case ConverterArrayType::paste: if (converters->paste_converters.size() > 0){ *size = converters->paste_converters.size(); return &converters->paste_converters[0]; } break; case ConverterArrayType::display: *size = 1; return &converters->display_converter; break; case ConverterArrayType::color_list: *size = 1; return &converters->color_list_converter; break; } return 0; } Converter** converters_get_all(Converters *converters, size_t *size) { size_t total_converters = converters->all_converters.size(); Converter** converter_table = new Converter* [total_converters+1]; size_t table_i = 0; for (list::iterator i=converters->all_converters.begin(); i != converters->all_converters.end(); ++i){ converter_table[table_i] = *i; ++table_i; } if (size) *size = total_converters; return converter_table; } int converters_reorder(Converters *converters, const char** priority_names, size_t priority_names_size) { Converter* c; Converters::ConverterMap used_converters; Converters::ConverterMap::iterator used_i; converters->all_converters.clear(); if (priority_names && priority_names_size>0){ for (size_t i = 0; i < priority_names_size; ++i){ used_i = used_converters.find( priority_names[i] ); if (used_i == used_converters.end()){ if ((c = converters_get(converters, priority_names[i]))){ converters->all_converters.push_back(c); used_converters[c->function_name] = c; } } } } Converters::ConverterMap::iterator i; for (i=converters->converters.begin(); i != converters->converters.end(); ++i){ used_i = used_converters.find( ((*i).second)->function_name ); if (used_i == used_converters.end()){ converters->all_converters.push_back(((*i).second)); used_converters[((*i).second)->function_name] = ((*i).second); } } return 0; } int converters_rebuild_arrays(Converters *converters, ConverterArrayType type) { list::iterator i; switch (type){ case ConverterArrayType::copy: converters->copy_converters.clear(); for (i=converters->all_converters.begin(); i != converters->all_converters.end(); ++i){ if ((*i)->copy && (*i)->serialize_available){ converters->copy_converters.push_back(*i); } } return 0; break; case ConverterArrayType::paste: converters->paste_converters.clear(); for (i=converters->all_converters.begin(); i != converters->all_converters.end(); ++i){ if ((*i)->paste && (*i)->deserialize_available){ converters->paste_converters.push_back(*i); } } return 0; break; default: return -1; } return -1; } int converters_set(Converters *converters, Converter* converter, ConverterArrayType type) { switch (type){ case ConverterArrayType::display: converters->display_converter = converter; break; case ConverterArrayType::color_list: converters->color_list_converter = converter; break; default: return -1; } return 0; } bool converter_get_text(const Color &color, ConverterArrayType type, GlobalState *gs, std::string &text) { auto converters = gs->getConverters(); auto converter = converters_get_first(converters, type); if (converter == nullptr) return ""; ColorObject color_object("", color); ConverterSerializePosition position; return (converters_color_serialize(converter, &color_object, position, text) == 0); } bool converter_get_text(const ColorObject *color_object, ConverterArrayType type, GlobalState *gs, std::string &text) { auto converters = gs->getConverters(); auto converter = converters_get_first(converters, type); if (converter == nullptr) return ""; ConverterSerializePosition position; return (converters_color_serialize(converter, color_object, position, text) == 0); } bool converter_get_text(const ColorObject *color_object, Converter *converter, GlobalState *gs, std::string &text) { if (converter == nullptr) return ""; ConverterSerializePosition position; return (converters_color_serialize(converter, color_object, position, text) == 0); } bool converter_get_color_object(const char *text, GlobalState* gs, ColorObject** output_color_object) { ColorObject color_object; auto converters = gs->getConverters(); typedef multimap > ValidConverters; ValidConverters valid_converters; Converter *converter = converters_get_first(converters, ConverterArrayType::display); if (converter){ if (converter->deserialize_available){ float quality; if (converters_color_deserialize(converter, text, &color_object, &quality) == 0){ if (quality > 0){ valid_converters.insert(make_pair(quality, color_object.copy())); } } } } size_t table_size; Converter **converter_table; if ((converter_table = converters_get_all_type(converters, ConverterArrayType::paste, &table_size))){ for (uint32_t i = 0; i != table_size; ++i){ converter = converter_table[i]; if (converter->deserialize_available){ float quality; if (converters_color_deserialize(converter, text, &color_object, &quality) == 0){ if (quality > 0){ valid_converters.insert(make_pair(quality, color_object.copy())); } } } } } bool first = true; for (ValidConverters::iterator i = valid_converters.begin(); i != valid_converters.end(); ++i){ if (first){ first = false; *output_color_object = (*i).second; }else{ (*i).second->release(); } } if (first){ return false; }else{ return true; } } ConverterSerializePosition::ConverterSerializePosition(): first(true), last(true), index(0), count(1) { } ConverterSerializePosition::ConverterSerializePosition(size_t count): first(true), last(count <= 1), index(0), count(count) { } gpick-gpick-0.2.6rc1/source/Converter.h000066400000000000000000000076721315430016700177510ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_CONVERTER_H_ #define GPICK_CONVERTER_H_ class Converters; struct lua_State; struct dynvSystem; class ColorObject; class GlobalState; struct Color; #include #ifndef _MSC_VER #include #endif #include enum class ConverterArrayType{ copy, paste, display, color_list, }; class Converter { public: char* function_name; char* human_readable; bool copy, serialize_available; bool paste, deserialize_available; Converters *converters; }; Converters* converters_init(lua_State *lua, dynvSystem *settings); int converters_term(Converters *converters); Converter* converters_get(Converters *converters, const char* name); int converters_set(Converters *converters, Converter* converter, ConverterArrayType type); Converter* converters_get_first(Converters *converters, ConverterArrayType type); Converter** converters_get_all_type(Converters *converters, ConverterArrayType type, size_t *size); Converter** converters_get_all(Converters *converters, size_t *size); class ConverterSerializePosition { public: ConverterSerializePosition(); ConverterSerializePosition(size_t count); bool first; bool last; size_t index; size_t count; }; int converters_color_serialize(Converters* converters, const char* function, const ColorObject* color_object, const ConverterSerializePosition &position, std::string& result); int converters_color_serialize(Converter* converter, const ColorObject* color_object, const ConverterSerializePosition &position, std::string& result); int converters_color_deserialize(Converters* converters, const char* function, const char* text, ColorObject* color_object, float* conversion_quality); int converters_color_deserialize(Converter *converter, const char* text, ColorObject *color_object, float* conversion_quality); int converters_rebuild_arrays(Converters *converters, ConverterArrayType type); int converters_reorder(Converters *converters, const char** priority_names, size_t priority_names_size); bool converter_get_text(const Color &color, ConverterArrayType type, GlobalState *gs, std::string &text); bool converter_get_text(const ColorObject *color_object, ConverterArrayType type, GlobalState *gs, std::string &text); bool converter_get_text(const ColorObject *color_object, Converter *converter, GlobalState *gs, std::string &text); bool converter_get_color_object(const char *text, GlobalState* gs, ColorObject** output_color_object); #endif /* GPICK_CONVERTER_H_ */ gpick-gpick-0.2.6rc1/source/CopyMenu.cpp000066400000000000000000000052621315430016700200650ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CopyMenu.h" #include "Converter.h" #include "GlobalState.h" #include "CopyMenuItem.h" GtkWidget* CopyMenu::newMenu(ColorObject *color_object, GtkWidget *palette_widget, GlobalState *gs) { auto converters = gs->getConverters(); GtkWidget *menu; menu = gtk_menu_new(); size_t converter_table_size = 0; Converter** converter_table = converters_get_all_type(converters, ConverterArrayType::copy, &converter_table_size); for (size_t i = 0; i < converter_table_size; ++i){ GtkWidget* item = CopyMenuItem::newItem(color_object, palette_widget, converter_table[i], gs); if (item) gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); } return menu; } GtkWidget* CopyMenu::newMenu(ColorObject *color_object, GlobalState *gs) { auto converters = gs->getConverters(); GtkWidget *menu; menu = gtk_menu_new(); size_t converter_table_size = 0; Converter** converter_table = converters_get_all_type(converters, ConverterArrayType::copy, &converter_table_size); for (size_t i = 0; i < converter_table_size; ++i){ GtkWidget* item = CopyMenuItem::newItem(color_object, converter_table[i], gs); if (item) gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); } return menu; } gpick-gpick-0.2.6rc1/source/CopyMenu.h000066400000000000000000000035551315430016700175350ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_COPY_MENU_H_ #define GPICK_COPY_MENU_H_ #include class ColorObject; class GlobalState; class CopyMenu { public: static GtkWidget* newMenu(ColorObject* color_object, GtkWidget *palette_widget, GlobalState *gs); static GtkWidget* newMenu(ColorObject* color_object, GlobalState *gs); }; #endif /* GPICK_COPY_MENU_H_ */ gpick-gpick-0.2.6rc1/source/CopyMenuItem.cpp000066400000000000000000000152271315430016700207060ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CopyMenuItem.h" #include "ColorObject.h" #include "ColorList.h" #include "Converter.h" #include "GlobalState.h" #include "DynvHelpers.h" #include "uiUtilities.h" #include "uiListPalette.h" #include #include using namespace std; static PaletteListCallbackReturn addToColorList(ColorObject* color_object, ColorList *color_list) { color_list_add_color_object(color_list, color_object, 1); return PALETTE_LIST_CALLBACK_NO_UPDATE; } class CopyMenuItemState { public: CopyMenuItemState(Converter *converter, ColorObject *color_object, GlobalState *gs): m_converter(converter), m_color_object(color_object), m_gs(gs), m_palette_widget(nullptr) { } ~CopyMenuItemState() { m_color_object->release(); } void setPaletteWidget(GtkWidget *palette_widget) { m_palette_widget = palette_widget; } static void onRelease(CopyMenuItemState *copy_menu_item) { delete copy_menu_item; } static void onActivate(GtkWidget *widget, CopyMenuItemState *copy_menu_item_state) { string text_line; if (copy_menu_item_state->m_palette_widget){ stringstream text(ios::out); ColorList *color_list = color_list_new(); palette_list_foreach_selected(copy_menu_item_state->m_palette_widget, (PaletteListCallback)addToColorList, color_list); ConverterSerializePosition position(color_list->colors.size()); if (position.count > 0){ string text_line; for (ColorList::iter i = color_list->colors.begin(); i != color_list->colors.end(); ++i){ if (position.index + 1 == position.count) position.last = true; if (converters_color_serialize(copy_menu_item_state->m_converter, *i, position, text_line) == 0){ if (position.first){ text << text_line; position.first = false; }else{ text << endl << text_line; } position.index++; } } } color_list_destroy(color_list); text_line = text.str(); if (text_line.length() > 0){ gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), text_line.c_str(), -1); gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), text_line.c_str(), -1); } }else{ ConverterSerializePosition position; if (converters_color_serialize(copy_menu_item_state->m_converter, copy_menu_item_state->m_color_object, position, text_line) == 0){ gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), text_line.c_str(), -1); gtk_clipboard_set_text(gtk_clipboard_get(GDK_SELECTION_PRIMARY), text_line.c_str(), -1); } } } Converter *m_converter; ColorObject *m_color_object; GtkWidget *m_palette_widget; GlobalState *m_gs; }; GtkWidget* CopyMenuItem::newItem(ColorObject* color_object, GlobalState *gs, bool include_name) { GtkWidget* item = nullptr; string text_line; ConverterSerializePosition position; auto converters = gs->getConverters(); Converter *converter = converters_get_first(converters, ConverterArrayType::copy); if (converters_color_serialize(converter, color_object, position, text_line) == 0){ if (include_name){ text_line += " - "; text_line += color_object->getName(); } item = gtk_menu_item_new_with_image(text_line.c_str(), gtk_image_new_from_stock(GTK_STOCK_COPY, GTK_ICON_SIZE_MENU)); CopyMenuItemState *copy_menu_item_state = new CopyMenuItemState(converter, color_object->reference(), gs); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(&CopyMenuItemState::onActivate), copy_menu_item_state); g_object_set_data_full(G_OBJECT(item), "item_data", copy_menu_item_state, (GDestroyNotify)&CopyMenuItemState::onRelease); } return item; } GtkWidget* CopyMenuItem::newItem(ColorObject *color_object, Converter *converter, GlobalState *gs) { GtkWidget* item = nullptr; string text_line; ConverterSerializePosition position; if (converters_color_serialize(converter, color_object, position, text_line) == 0){ item = gtk_menu_item_new_with_image(text_line.c_str(), gtk_image_new_from_stock(GTK_STOCK_COPY, GTK_ICON_SIZE_MENU)); CopyMenuItemState *copy_menu_item_state = new CopyMenuItemState(converter, color_object->reference(), gs); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(&CopyMenuItemState::onActivate), copy_menu_item_state); g_object_set_data_full(G_OBJECT(item), "item_data", copy_menu_item_state, (GDestroyNotify)&CopyMenuItemState::onRelease); } return item; } GtkWidget* CopyMenuItem::newItem(ColorObject* color_object, GtkWidget *palette_widget, Converter *converter, GlobalState *gs) { GtkWidget* item = nullptr; string text_line; ConverterSerializePosition position; if (converters_color_serialize(converter, color_object, position, text_line) == 0){ item = gtk_menu_item_new_with_image(text_line.c_str(), gtk_image_new_from_stock(GTK_STOCK_COPY, GTK_ICON_SIZE_MENU)); CopyMenuItemState *copy_menu_item_state = new CopyMenuItemState(converter, color_object->reference(), gs); copy_menu_item_state->setPaletteWidget(palette_widget); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(&CopyMenuItemState::onActivate), copy_menu_item_state); g_object_set_data_full(G_OBJECT(item), "item_data", copy_menu_item_state, (GDestroyNotify)&CopyMenuItemState::onRelease); } return item; } gpick-gpick-0.2.6rc1/source/CopyMenuItem.h000066400000000000000000000040311315430016700203420ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_COPY_MENU_ITEM_H_ #define GPICK_COPY_MENU_ITEM_H_ #include class GlobalState; class ColorObject; class Converter; class CopyMenuItem { public: static GtkWidget* newItem(ColorObject *color_object, GlobalState *gs, bool include_name); static GtkWidget* newItem(ColorObject *color_object, Converter *converter, GlobalState *gs); static GtkWidget* newItem(ColorObject *color_object, GtkWidget *palette_widget, Converter *converter, GlobalState *gs); }; #endif /* GPICK_COPY_MENU_ITEM_H_ */ gpick-gpick-0.2.6rc1/source/CopyPaste.cpp000066400000000000000000000146711315430016700202410ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CopyPaste.h" #include "ColorObject.h" #include "ColorList.h" #include "GlobalState.h" #include "Converter.h" #include #include #include using namespace std; enum { TARGET_STRING = 1, TARGET_ROOTWIN, TARGET_COLOR, TARGET_COLOR_OBJECT, }; static GtkTargetEntry targets[] = { //{ (char*)"colorobject", GTK_TARGET_SAME_APP, TARGET_COLOR_OBJECT }, { (char*)"application/x-color", 0, TARGET_COLOR }, { (char*)"text/plain", 0, TARGET_STRING }, { (char*)"STRING", 0, TARGET_STRING }, //{ (char*)"application/x-rootwin-drop", 0, TARGET_ROOTWIN } }; static guint n_targets = G_N_ELEMENTS (targets); typedef struct CopyPasteArgs{ ColorObject* color_object; GlobalState* gs; }CopyPasteArgs; static void clipboard_get(GtkClipboard *clipboard, GtkSelectionData *selection_data, guint target_type, CopyPasteArgs* args){ g_assert(selection_data != nullptr); Color color; switch (target_type){ case TARGET_COLOR_OBJECT: gtk_selection_data_set (selection_data, gdk_atom_intern ("colorobject", false), 8, (guchar *)&args->color_object, sizeof(ColorObject*)); break; case TARGET_STRING: { string text; converter_get_text(args->color_object, ConverterArrayType::copy, args->gs, text); gtk_selection_data_set_text(selection_data, text.c_str(), text.length() + 1); } break; case TARGET_COLOR: { color = args->color_object->getColor(); guint16 data_color[4]; data_color[0] = int(color.rgb.red * 0xFFFF); data_color[1] = int(color.rgb.green * 0xFFFF); data_color[2] = int(color.rgb.blue * 0xFFFF); data_color[3] = 0xffff; gtk_selection_data_set (selection_data, gdk_atom_intern ("application/x-color", false), 16, (guchar *)data_color, 8); } break; case TARGET_ROOTWIN: g_print ("Dropped on the root window!\n"); break; default: g_assert_not_reached (); } } static void clipboard_clear(GtkClipboard *clipboard, CopyPasteArgs* args){ args->color_object->release(); delete args; } int copypaste_set_color_object(ColorObject* color_object, GlobalState* gs){ CopyPasteArgs* args = new CopyPasteArgs; args->color_object = color_object->reference(); args->gs = gs; if (gtk_clipboard_set_with_data(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), targets, n_targets, (GtkClipboardGetFunc)clipboard_get, (GtkClipboardClearFunc)clipboard_clear, args)){ return 0; } return -1; } int copypaste_get_color_object(ColorObject** out_color_object, GlobalState* gs){ GdkAtom *avail_targets; gint avail_n_targets; GtkClipboard *clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD); if (gtk_clipboard_wait_for_targets(clipboard, &avail_targets, &avail_n_targets)){ for (uint32_t j = 0; j < n_targets; ++j){ for (int32_t i = 0; i < avail_n_targets; ++i){ gchar* atom_name = gdk_atom_name(avail_targets[i]); if (g_strcmp0(targets[j].target, atom_name) == 0){ GtkSelectionData *selection_data = gtk_clipboard_wait_for_contents(clipboard, avail_targets[i]); bool success = false; if (selection_data){ switch (targets[j].info){ case TARGET_COLOR_OBJECT: { ColorObject* color_object; memcpy(&color_object, gtk_selection_data_get_data(selection_data), sizeof(ColorObject*)); *out_color_object = color_object; success = true; } break; case TARGET_STRING: { gchar* data = (gchar*)gtk_selection_data_get_data(selection_data); if (data[gtk_selection_data_get_length(selection_data)] != 0) break; //not null terminated ColorObject* color_object; if (converter_get_color_object(data, gs, &color_object)){ *out_color_object = color_object; success = true; } } break; case TARGET_COLOR: { guint16* data = (guint16*)gtk_selection_data_get_data(selection_data); Color color; color.rgb.red = data[0] / (double)0xFFFF; color.rgb.green = data[1] / (double)0xFFFF; color.rgb.blue = data[2] / (double)0xFFFF; ColorObject* color_object = color_list_new_color_object(gs->getColorList(), &color); *out_color_object = color_object; success = true; } break; default: g_assert_not_reached (); } } if (success){ g_free(atom_name); g_free(avail_targets); return 0; } } g_free(atom_name); } } g_free(avail_targets); } return -1; } int copypaste_is_color_object_available(GlobalState* gs){ GdkAtom *avail_targets; gint avail_n_targets; if (gtk_clipboard_wait_for_targets(gtk_clipboard_get(GDK_SELECTION_CLIPBOARD), &avail_targets, &avail_n_targets)){ for (uint32_t j = 0; j < n_targets; ++j){ for (int32_t i = 0; i < avail_n_targets; ++i){ gchar* atom_name = gdk_atom_name(avail_targets[i]); if (g_strcmp0(targets[j].target, atom_name) == 0){ g_free(atom_name); g_free(avail_targets); return 0; } g_free(atom_name); } } g_free(avail_targets); } return -1; } gpick-gpick-0.2.6rc1/source/CopyPaste.h000066400000000000000000000035441315430016700177030ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_COPY_PASTE_H_ #define GPICK_COPY_PASTE_H_ class ColorObject; class GlobalState; int copypaste_set_color_object(ColorObject* color_object, GlobalState* gs); int copypaste_get_color_object(ColorObject** color_object, GlobalState* gs); int copypaste_is_color_object_available(GlobalState* gs); #endif /* GPICK_COPY_PASTE_H_ */ gpick-gpick-0.2.6rc1/source/DragDrop.cpp000066400000000000000000000514601315430016700200310ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "DragDrop.h" #include "ColorObject.h" #include "DynvHelpers.h" #include "GlobalState.h" #include "gtk/ColorWidget.h" #include "Converter.h" #include "dynv/DynvXml.h" #include #include #include using namespace std; enum { TARGET_STRING = 1, TARGET_ROOTWIN, TARGET_COLOR, TARGET_COLOR_OBJECT_LIST, TARGET_COLOR_OBJECT_LIST_SERIALIZED, }; static GtkTargetEntry targets[] = { { (char*)"color_object-list", GTK_TARGET_SAME_APP, TARGET_COLOR_OBJECT_LIST }, { (char*)"application/x-color_object-list", GTK_TARGET_OTHER_APP, TARGET_COLOR_OBJECT_LIST_SERIALIZED }, { (char*)"application/x-color", 0, TARGET_COLOR }, { (char*)"text/plain", 0, TARGET_STRING }, { (char*)"STRING", 0, TARGET_STRING }, { (char*)"application/x-rootwin-drop", 0, TARGET_ROOTWIN } }; static guint n_targets = G_N_ELEMENTS (targets); static void drag_data_received(GtkWidget *widget, GdkDragContext *context, gint x, gint y, GtkSelectionData *selection_data, guint target_type, guint time, gpointer data); static gboolean drag_motion(GtkWidget *widget, GdkDragContext *context, gint x, gint y, guint t, gpointer user_data); static void drag_leave(GtkWidget *widget, GdkDragContext *context, guint time, gpointer user_data); static gboolean drag_drop(GtkWidget *widget, GdkDragContext *context, gint x, gint y, guint time, gpointer user_data); static void drag_data_delete(GtkWidget *widget, GdkDragContext *context, gpointer user_data); static void drag_data_get(GtkWidget *widget, GdkDragContext *context, GtkSelectionData *selection_data, guint target_type, guint time, gpointer user_data); static void drag_begin(GtkWidget *widget, GdkDragContext *context, gpointer user_data); static void drag_end(GtkWidget *widget, GdkDragContext *context, gpointer user_data); static void drag_destroy(GtkWidget *widget, gpointer user_data); int dragdrop_init(DragDrop* dd, GlobalState *gs){ dd->get_color_object = 0; dd->set_color_object_at = 0; dd->test_at = 0; dd->data_received = 0; dd->data_get = 0; dd->data_delete = 0; dd->drag_end = 0; dd->get_color_object_list = 0; dd->set_color_object_list_at = 0; dd->handler_map = 0; dd->data_type = DragDrop::DATA_TYPE_NONE; memset(&dd->data, 0, sizeof(dd->data)); dd->widget = 0; dd->gs = gs; dd->dragwidget = 0; return 0; } int dragdrop_widget_attach(GtkWidget* widget, DragDropFlags flags, DragDrop *user_dd){ DragDrop* dd=new DragDrop; memcpy(dd, user_dd, sizeof(DragDrop)); dd->widget = widget; if (flags & DRAGDROP_SOURCE){ GtkTargetList *target_list = gtk_drag_source_get_target_list(widget); if (target_list){ gtk_target_list_add_table(target_list, targets, n_targets); }else{ target_list = gtk_target_list_new(targets, n_targets); gtk_drag_source_set_target_list(widget, target_list); } g_signal_connect (widget, "drag-data-get", G_CALLBACK (drag_data_get), dd); g_signal_connect (widget, "drag-data-delete", G_CALLBACK (drag_data_delete), dd); g_signal_connect (widget, "drag-begin", G_CALLBACK (drag_begin), dd); g_signal_connect (widget, "drag-end", G_CALLBACK (drag_end), dd); } if (flags & DRAGDROP_DESTINATION){ GtkTargetList *target_list = gtk_drag_dest_get_target_list(widget); if (target_list){ gtk_target_list_add_table(target_list, targets, n_targets); }else{ target_list = gtk_target_list_new(targets, n_targets); gtk_drag_dest_set_target_list(widget, target_list); } g_signal_connect (widget, "drag-data-received", G_CALLBACK(drag_data_received), dd); g_signal_connect (widget, "drag-leave", G_CALLBACK (drag_leave), dd); g_signal_connect (widget, "drag-motion", G_CALLBACK (drag_motion), dd); g_signal_connect (widget, "drag-drop", G_CALLBACK (drag_drop), dd); } g_signal_connect (widget, "destroy", G_CALLBACK (drag_destroy), dd); return 0; } static void drag_data_received(GtkWidget *widget, GdkDragContext *context, gint x, gint y, GtkSelectionData *selection_data, guint target_type, guint time, gpointer user_data){ bool success = false; if ((selection_data != nullptr) && (gtk_selection_data_get_length(selection_data) >= 0)){ DragDrop *dd = (DragDrop*)user_data; if (dd->data_received){ success = dd->data_received(dd, widget, context, x, y, selection_data, target_type, time); } if (!success) switch (target_type){ case TARGET_COLOR_OBJECT_LIST: { struct ColorObjectList{ uint64_t color_object_n; ColorObject* color_object; }data; memcpy(&data, gtk_selection_data_get_data(selection_data), sizeof(data)); if (data.color_object_n > 1){ ColorObject **color_objects = new ColorObject*[data.color_object_n]; memcpy(color_objects, gtk_selection_data_get_data(selection_data) + offsetof(ColorObjectList, color_object), sizeof(ColorObject*) * data.color_object_n); if (dd->set_color_object_list_at) dd->set_color_object_list_at(dd, color_objects, data.color_object_n, x, y, gdk_drag_context_get_actions(context) & GDK_ACTION_MOVE); else if (dd->set_color_object_at) dd->set_color_object_at(dd, data.color_object, x, y, gdk_drag_context_get_actions(context) & GDK_ACTION_MOVE); }else{ if (dd->set_color_object_at) dd->set_color_object_at(dd, data.color_object, x, y, gdk_drag_context_get_actions(context) & GDK_ACTION_MOVE); } } success = true; break; case TARGET_COLOR_OBJECT_LIST_SERIALIZED: { size_t length = gtk_selection_data_get_length(selection_data); char *buffer = new char [length + 1]; buffer[length] = 0; memcpy(buffer, gtk_selection_data_get_data(selection_data), length); stringstream str(buffer); delete [] buffer; dynvSystem *params = dynv_system_create(dd->handler_map); dynv_xml_deserialize(params, str); uint32_t color_n = 0; dynvSystem **colors = (dynvSystem**)dynv_get_dynv_array_wd(params, "colors", 0, 0, &color_n); if (color_n > 0 && colors){ if (color_n > 1){ if (dd->set_color_object_list_at){ ColorObject **color_objects = new ColorObject*[color_n]; for (uint32_t i = 0; i < color_n; i++){ color_objects[i] = new ColorObject(); color_objects[i]->setName(dynv_get_string_wd(colors[i], "name", "")); Color *color = dynv_get_color_wdc(colors[i], "color", nullptr); if (color != nullptr) color_objects[i]->setColor(*color); } dd->set_color_object_list_at(dd, color_objects, color_n, x, y, false); for (uint32_t i = 0; i < color_n; i++){ color_objects[i]->release(); } delete [] color_objects; }else if (dd->set_color_object_at){ ColorObject* color_object = new ColorObject(); color_object->setName(dynv_get_string_wd(colors[0], "name", "")); Color *color = dynv_get_color_wdc(colors[0], "color", nullptr); if (color != nullptr) color_object->setColor(*color); dd->set_color_object_at(dd, color_object, x, y, false); color_object->release(); } }else{ if (dd->set_color_object_at){ ColorObject* color_object = new ColorObject(); color_object->setName(dynv_get_string_wd(colors[0], "name", "")); Color *color = dynv_get_color_wdc(colors[0], "color", nullptr); if (color != nullptr) color_object->setColor(*color); dd->set_color_object_at(dd, color_object, x, y, false); color_object->release(); } } } if (colors){ for (uint32_t i = 0; i < color_n; i++){ dynv_system_release(colors[i]); } delete [] colors; } } success = true; break; case TARGET_STRING: { gchar* data = (gchar*)gtk_selection_data_get_data(selection_data); if (data[gtk_selection_data_get_length(selection_data)] != 0) break; //not null terminated ColorObject* color_object = nullptr; if (!converter_get_color_object(data, dd->gs, &color_object)){ gtk_drag_finish (context, false, false, time); return; } dd->set_color_object_at(dd, color_object, x, y, gdk_drag_context_get_actions(context) & GDK_ACTION_MOVE); color_object->release(); } success = true; break; case TARGET_COLOR: { guint16* data = (guint16*)gtk_selection_data_get_data(selection_data); Color color; color.rgb.red = data[0] / (double)0xFFFF; color.rgb.green = data[1] / (double)0xFFFF; color.rgb.blue = data[2] / (double)0xFFFF; ColorObject* color_object = new ColorObject("", color); dd->set_color_object_at(dd, color_object, x, y, gdk_drag_context_get_actions(context) & GDK_ACTION_MOVE); color_object->release(); } success = true; break; default: g_assert_not_reached (); } } gtk_drag_finish(context, success, gdk_drag_context_get_actions(context) == GDK_ACTION_MOVE, time); } static gboolean drag_motion(GtkWidget *widget, GdkDragContext *context, gint x, gint y, guint time, gpointer user_data){ DragDrop *dd = (DragDrop*)user_data; GdkDragAction suggested_action; bool suggested_action_set = true; bool dragging_moves = dynv_get_bool_wd(dd->gs->getSettings(), "gpick.main.dragging_moves", true); if (dragging_moves){ if ((gdk_drag_context_get_actions(context) & GDK_ACTION_MOVE) == GDK_ACTION_MOVE) suggested_action = GDK_ACTION_MOVE; else if ((gdk_drag_context_get_actions(context) & GDK_ACTION_COPY) == GDK_ACTION_COPY) suggested_action = GDK_ACTION_COPY; else suggested_action_set = false; }else{ if ((gdk_drag_context_get_actions(context) & GDK_ACTION_COPY) == GDK_ACTION_COPY) suggested_action = GDK_ACTION_COPY; else if ((gdk_drag_context_get_actions(context) & GDK_ACTION_MOVE) == GDK_ACTION_MOVE) suggested_action = GDK_ACTION_MOVE; else suggested_action_set = false; } if (!dd->test_at){ GdkAtom target = gtk_drag_dest_find_target(widget, context, 0); if (target){ gdk_drag_status(context, suggested_action_set ? suggested_action : gdk_drag_context_get_selected_action(context), time); }else{ gdk_drag_status(context, suggested_action_set ? suggested_action : GdkDragAction(0), time); } return TRUE; } if (dd->test_at(dd, x, y)){ GdkAtom target = gtk_drag_dest_find_target(widget, context, 0); if (target){ gdk_drag_status(context, suggested_action_set ? suggested_action : gdk_drag_context_get_selected_action(context), time); }else{ gdk_drag_status(context, suggested_action_set ? suggested_action : GdkDragAction(0), time); } }else{ gdk_drag_status(context, suggested_action_set ? suggested_action : GdkDragAction(0), time); } return TRUE; } static void drag_leave(GtkWidget *widget, GdkDragContext *context, guint time, gpointer user_data){ } static gboolean drag_drop(GtkWidget *widget, GdkDragContext *context, gint x, gint y, guint time, gpointer user_data){ DragDrop *dd = (DragDrop*)user_data; GdkAtom target = gtk_drag_dest_find_target(widget, context, 0); if (target != GDK_NONE){ gtk_drag_get_data(widget, context, target, time); if (dd->drag_end) dd->drag_end(dd, widget, context); return TRUE; } if (dd->drag_end) dd->drag_end(dd, widget, context); return FALSE; } static void drag_data_delete(GtkWidget *widget, GdkDragContext *context, gpointer user_data) { DragDrop *dd = (DragDrop*)user_data; if (dd->data_delete){ dd->data_delete(dd, widget, context); } } static void drag_data_get(GtkWidget *widget, GdkDragContext *context, GtkSelectionData *selection_data, guint target_type, guint time, gpointer user_data) { g_assert (selection_data != nullptr); DragDrop *dd = (DragDrop*)user_data; bool success = false; if (dd->data_get){ success = dd->data_get(dd, widget, context, selection_data, target_type, time); } if (!success){ if (dd->data_type == DragDrop::DATA_TYPE_COLOR_OBJECT){ ColorObject* color_object = dd->data.color_object.color_object; if (!color_object) return; Color color; switch (target_type){ case TARGET_COLOR_OBJECT_LIST: { struct{ uint64_t color_object_n; ColorObject* color_object; }data; data.color_object_n = 1; data.color_object = color_object; gtk_selection_data_set(selection_data, gdk_atom_intern("color_object", TRUE), 8, (guchar *)&data, sizeof(data)); } break; case TARGET_COLOR_OBJECT_LIST_SERIALIZED: { dynvSystem *params = dynv_system_create(dd->handler_map); dynvSystem **colors = new dynvSystem*[1]; colors[0] = dynv_system_create(dd->handler_map); dynv_set_string(colors[0], "name", color_object->getName().c_str()); dynv_set_color(colors[0], "color", &color_object->getColor()); dynv_set_dynv_array(params, "colors", (const dynvSystem**)colors, 1); delete [] colors; stringstream str; str << "" << endl; dynv_xml_serialize(params, str); str << "" << endl; string xml_data = str.str(); gtk_selection_data_set(selection_data, gdk_atom_intern("application/x-color_object-list", TRUE), 8, (guchar *)xml_data.c_str(), xml_data.length()); } break; case TARGET_STRING: { string text; if (converter_get_text(color_object, ConverterArrayType::copy, dd->gs, text)){ gtk_selection_data_set_text(selection_data, text.c_str(), text.length() + 1); } } break; case TARGET_COLOR: { color = color_object->getColor(); guint16 data_color[4]; data_color[0] = int(color.rgb.red * 0xFFFF); data_color[1] = int(color.rgb.green * 0xFFFF); data_color[2] = int(color.rgb.blue * 0xFFFF); data_color[3] = 0xffff; gtk_selection_data_set (selection_data, gdk_atom_intern ("application/x-color", TRUE), 16, (guchar *)data_color, 8); } break; case TARGET_ROOTWIN: g_print ("Dropped on the root window!\n"); break; default: g_assert_not_reached (); } }else if (dd->data_type == DragDrop::DATA_TYPE_COLOR_OBJECTS){ ColorObject** color_objects = dd->data.color_objects.color_objects; uint32_t color_object_n = dd->data.color_objects.color_object_n; if (!color_objects) return; Color color; switch (target_type){ case TARGET_COLOR_OBJECT_LIST: { struct ColorObjectList{ uint64_t color_object_n; ColorObject* color_object[1]; }; uint32_t data_length = sizeof(uint64_t) + sizeof(ColorObject*) * color_object_n; ColorObjectList *data = (ColorObjectList*)new char[data_length]; data->color_object_n = color_object_n; memcpy(&data->color_object[0], color_objects, sizeof(ColorObject*) * color_object_n); gtk_selection_data_set(selection_data, gdk_atom_intern("color_object", TRUE), 8, (guchar *)data, data_length); delete [] (char*)data; } break; case TARGET_COLOR_OBJECT_LIST_SERIALIZED: { dynvSystem *params = dynv_system_create(dd->handler_map); if (color_object_n > 0){ dynvSystem **colors = new dynvSystem*[color_object_n]; for (uint32_t i = 0; i < color_object_n; i++){ colors[i] = dynv_system_create(dd->handler_map); dynv_set_string(colors[i], "name", color_objects[i]->getName().c_str()); dynv_set_color(colors[i], "color", &color_objects[i]->getColor()); } dynv_set_dynv_array(params, "colors", (const dynvSystem**)colors, color_object_n); delete [] colors; } stringstream str; str << "" << endl; dynv_xml_serialize(params, str); str << "" << endl; string xml_data = str.str(); gtk_selection_data_set(selection_data, gdk_atom_intern("application/x-color_object-list", TRUE), 8, (guchar *)xml_data.c_str(), xml_data.length()); } break; case TARGET_STRING: { stringstream ss; string text; for (uint32_t i = 0; i != color_object_n; i++){ if (converter_get_text(color_objects[i], ConverterArrayType::copy, dd->gs, text)){ ss << text << endl; } } text = ss.str(); gtk_selection_data_set_text(selection_data, text.c_str(), text.length() + 1); } break; case TARGET_COLOR: { ColorObject *color_object = color_objects[0]; color = color_object->getColor(); guint16 data_color[4]; data_color[0] = int(color.rgb.red * 0xFFFF); data_color[1] = int(color.rgb.green * 0xFFFF); data_color[2] = int(color.rgb.blue * 0xFFFF); data_color[3] = 0xffff; gtk_selection_data_set (selection_data, gdk_atom_intern ("application/x-color", TRUE), 16, (guchar *)data_color, 8); } break; case TARGET_ROOTWIN: g_print ("Dropped on the root window!\n"); break; default: g_assert_not_reached (); } } } } static void drag_begin(GtkWidget *widget, GdkDragContext *context, gpointer user_data){ DragDrop *dd = (DragDrop*)user_data; if (dd->get_color_object_list){ size_t color_object_n; ColorObject** color_objects = dd->get_color_object_list(dd, &color_object_n); if (color_objects){ dd->data_type = DragDrop::DATA_TYPE_COLOR_OBJECTS; dd->data.color_objects.color_objects = color_objects; dd->data.color_objects.color_object_n = color_object_n; GtkWidget* dragwindow = gtk_window_new(GTK_WINDOW_POPUP); GtkWidget* hbox = gtk_vbox_new(true, 0); gtk_container_add(GTK_CONTAINER(dragwindow), hbox); gtk_window_resize(GTK_WINDOW(dragwindow), 164, 24 * std::min(color_object_n, (size_t)5)); for (size_t i = 0; i < std::min(color_object_n, (size_t)5); i++){ GtkWidget* color_widget = gtk_color_new(); string text; converter_get_text(color_objects[i], ConverterArrayType::display, dd->gs, text); Color color = color_objects[i]->getColor(); gtk_color_set_color(GTK_COLOR(color_widget), &color, text.c_str()); gtk_box_pack_start(GTK_BOX(hbox), color_widget, true, true, 0); } gtk_drag_set_icon_widget(context, dragwindow, 0, 0); gtk_widget_show_all(dragwindow); dd->dragwidget = dragwindow; return; } } if (dd->get_color_object){ ColorObject* color_object = dd->get_color_object(dd); if (color_object){ dd->data_type = DragDrop::DATA_TYPE_COLOR_OBJECT; dd->data.color_object.color_object = color_object; GtkWidget* dragwindow = gtk_window_new(GTK_WINDOW_POPUP); GtkWidget* colorwidget = gtk_color_new(); gtk_container_add(GTK_CONTAINER(dragwindow), colorwidget); gtk_window_resize(GTK_WINDOW(dragwindow), 164, 24); string text; converter_get_text(color_object, ConverterArrayType::display, dd->gs, text); Color color = color_object->getColor(); gtk_color_set_color(GTK_COLOR(colorwidget), &color, text.c_str()); gtk_drag_set_icon_widget(context, dragwindow, 0, 0); gtk_widget_show_all(dragwindow); dd->dragwidget = dragwindow; return; } } } static void drag_end(GtkWidget *widget, GdkDragContext *context, gpointer user_data){ DragDrop *dd = (DragDrop*)user_data; if (dd->data_type == DragDrop::DATA_TYPE_COLOR_OBJECT){ if (dd->data.color_object.color_object){ dd->data.color_object.color_object->release(); memset(&dd->data, 0, sizeof(dd->data)); } dd->data_type = DragDrop::DATA_TYPE_NONE; } if (dd->data_type == DragDrop::DATA_TYPE_COLOR_OBJECTS){ if (dd->data.color_objects.color_objects){ for (uint32_t i = 0; i < dd->data.color_objects.color_object_n; i++){ dd->data.color_objects.color_objects[i]->release(); } delete [] dd->data.color_objects.color_objects; memset(&dd->data, 0, sizeof(dd->data)); } dd->data_type = DragDrop::DATA_TYPE_NONE; } if (dd->dragwidget){ gtk_widget_destroy(dd->dragwidget); dd->dragwidget = 0; } if (dd->drag_end) dd->drag_end(dd, widget, context); } static void drag_destroy(GtkWidget *widget, gpointer user_data){ DragDrop *dd = (DragDrop*)user_data; dynv_handler_map_release(dd->handler_map); delete dd; } gpick-gpick-0.2.6rc1/source/DragDrop.h000066400000000000000000000062011315430016700174670ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_DRAG_DROP_H_ #define GPICK_DRAG_DROP_H_ #include class GlobalState; class ColorObject; struct dynvHandlerMap; enum DragDropFlags{ DRAGDROP_SOURCE = 1<<1, DRAGDROP_DESTINATION = 1<<2, }; struct DragDrop{ GtkWidget* widget; void* userdata; ColorObject* (*get_color_object)(DragDrop* dd); int (*set_color_object_at)(DragDrop* dd, ColorObject* colorobject, int x, int y, bool move); ColorObject** (*get_color_object_list)(DragDrop* dd, size_t *colorobject_n); int (*set_color_object_list_at)(DragDrop* dd, ColorObject** colorobject, size_t colorobject_n, int x, int y, bool move); bool (*test_at)(DragDrop* dd, int x, int y); bool (*data_received)(DragDrop* dd, GtkWidget *widget, GdkDragContext *context, gint x, gint y, GtkSelectionData *selection_data, guint target_type, guint time); bool (*data_get)(DragDrop* dd, GtkWidget *widget, GdkDragContext *context, GtkSelectionData *selection_data, guint target_type, guint time); bool (*data_delete)(DragDrop* dd, GtkWidget *widget, GdkDragContext *context); bool (*drag_end)(DragDrop* dd, GtkWidget *widget, GdkDragContext *context); enum DataType{ DATA_TYPE_NONE, DATA_TYPE_COLOR_OBJECT, DATA_TYPE_COLOR_OBJECTS, }; DataType data_type; union{ struct{ ColorObject* color_object; }color_object; struct{ ColorObject** color_objects; size_t color_object_n; }color_objects; }data; dynvHandlerMap* handler_map; GtkWidget* dragwidget; GlobalState *gs; void* userdata2; }; int dragdrop_init(DragDrop* dd, GlobalState *gs); int dragdrop_widget_attach(GtkWidget* widget, DragDropFlags flags, DragDrop *dd); #endif /* GPICK_DRAG_DROP_H_ */ gpick-gpick-0.2.6rc1/source/DynvHelpers.cpp000066400000000000000000000162561315430016700205760ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "DynvHelpers.h" int32_t dynv_get_int32_wd(struct dynvSystem* dynv_system, const char *path, int32_t default_value){ int error; void* r = dynv_get(dynv_system, "int32", path, &error); if (error){ return default_value; }else return *(int32_t*)r; } float dynv_get_float_wd(struct dynvSystem* dynv_system, const char *path, float default_value){ int error; void* r = dynv_get(dynv_system, "float", path, &error); if (error){ return default_value; }else return *(float*)r; } bool dynv_get_bool_wd(struct dynvSystem* dynv_system, const char *path, bool default_value){ int error; void* r = dynv_get(dynv_system, "bool", path, &error); if (error){ return default_value; }else return *(bool*)r; } const char* dynv_get_string_wd(struct dynvSystem* dynv_system, const char *path, const char* default_value){ int error; void* r = dynv_get(dynv_system, "string", path, &error); if (error){ return default_value; }else return *(const char**)r; } const Color* dynv_get_color_wd(struct dynvSystem* dynv_system, const char *path, const Color* default_value){ int error; void* r = dynv_get(dynv_system, "color", path, &error); if (error){ return default_value; }else return *(const Color**)r; } Color* dynv_get_color_wdc(struct dynvSystem* dynv_system, const char *path, Color* default_value){ int error; void* r = dynv_get(dynv_system, "color", path, &error); if (error){ return default_value; }else return *(Color**)r; } void dynv_set_int32(struct dynvSystem* dynv_system, const char *path, int32_t value){ dynv_set(dynv_system, "int32", path, &value); } void dynv_set_float(struct dynvSystem* dynv_system, const char *path, float value){ dynv_set(dynv_system, "float", path, &value); } void dynv_set_bool(struct dynvSystem* dynv_system, const char *path, bool value){ dynv_set(dynv_system, "bool", path, &value); } void dynv_set_string(struct dynvSystem* dynv_system, const char *path, const char* value){ dynv_set(dynv_system, "string", path, &value); } void dynv_set_color(struct dynvSystem* dynv_system, const char *path, const Color* value){ dynv_set(dynv_system, "color", path, &value); } struct dynvSystem* dynv_get_dynv(struct dynvSystem* dynv_system, const char *path){ int error; void* r = dynv_get(dynv_system, "dynv", path, &error); if (error){ struct dynvHandlerMap* handler_map = dynv_system_get_handler_map(dynv_system); struct dynvSystem* dynv = dynv_system_create(handler_map); dynv_handler_map_release(handler_map); dynv_set(dynv_system, "dynv", path, dynv); return dynv; }else return (struct dynvSystem*)r; } int32_t* dynv_get_int32_array_wd(struct dynvSystem* dynv_system, const char *path, int32_t* default_value, uint32_t default_count, uint32_t *count){ int error; void** r = dynv_get_array(dynv_system, "int32", path, count, &error); if (error){ if (count) *count = default_count; return default_value; }else return (int32_t*)r; } float* dynv_get_float_array_wd(struct dynvSystem* dynv_system, const char *path, float *default_value, uint32_t default_count, uint32_t *count){ int error; void** r = dynv_get_array(dynv_system, "float", path, count, &error); if (error){ if (count) *count = default_count; return default_value; }else return (float*)r; } bool* dynv_get_bool_array_wd(struct dynvSystem* dynv_system, const char *path, bool *default_value, uint32_t default_count, uint32_t *count){ int error; void** r = dynv_get_array(dynv_system, "bool", path, count, &error); if (error){ if (count) *count = default_count; return default_value; }else return (bool*)r; } const char** dynv_get_string_array_wd(struct dynvSystem* dynv_system, const char *path, const char** default_value, uint32_t default_count, uint32_t *count){ int error; void** r = dynv_get_array(dynv_system, "string", path, count, &error); if (error){ if (count) *count = default_count; return default_value; }else return (const char**)r; } const Color** dynv_get_color_array_wd(struct dynvSystem* dynv_system, const char *path, const Color** default_value, uint32_t default_count, uint32_t *count){ int error; void** r = dynv_get_array(dynv_system, "color", path, count, &error); if (error){ if (count) *count = default_count; return default_value; }else return (const Color**)r; } struct dynvSystem** dynv_get_dynv_array_wd(struct dynvSystem* dynv_system, const char *path, struct dynvSystem** default_value, uint32_t default_count, uint32_t *count){ int error; void** r = dynv_get_array(dynv_system, "dynv", path, count, &error); if (error){ if (count) *count = default_count; return default_value; }else return (struct dynvSystem**)r; } void dynv_set_int32_array(struct dynvSystem* dynv_system, const char *path, int32_t* values, uint32_t count){ dynv_set_array(dynv_system, "int32", path, (const void**)values, count); } void dynv_set_float_array(struct dynvSystem* dynv_system, const char *path, float* values, uint32_t count){ dynv_set_array(dynv_system, "float", path, (const void**)values, count); } void dynv_set_bool_array(struct dynvSystem* dynv_system, const char *path, bool* values, uint32_t count){ dynv_set_array(dynv_system, "bool", path, (const void**)values, count); } void dynv_set_string_array(struct dynvSystem* dynv_system, const char *path, const char** values, uint32_t count){ dynv_set_array(dynv_system, "string", path, (const void**)values, count); } void dynv_set_color_array(struct dynvSystem* dynv_system, const char *path, const Color** values, uint32_t count){ dynv_set_array(dynv_system, "color", path, (const void**)values, count); } void dynv_set_dynv_array(struct dynvSystem* dynv_system, const char *path, const struct dynvSystem** values, uint32_t count){ dynv_set_array(dynv_system, "dynv", path, (const void**)values, count); } gpick-gpick-0.2.6rc1/source/DynvHelpers.h000066400000000000000000000105731315430016700202370ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DYNVHELPERS_H_ #define DYNVHELPERS_H_ #include "dynv/DynvSystem.h" #include "Color.h" #include #ifndef _MSC_VER #include #endif int32_t dynv_get_int32_wd(struct dynvSystem* dynv_system, const char *path, int32_t default_value); float dynv_get_float_wd(struct dynvSystem* dynv_system, const char *path, float default_value); bool dynv_get_bool_wd(struct dynvSystem* dynv_system, const char *path, bool default_value); const char* dynv_get_string_wd(struct dynvSystem* dynv_system, const char *path, const char* default_value); const Color* dynv_get_color_wd(struct dynvSystem* dynv_system, const char *path, const Color* default_value); Color* dynv_get_color_wdc(struct dynvSystem* dynv_system, const char *path, Color* default_value); void dynv_set_int32(struct dynvSystem* dynv_system, const char *path, int32_t value); void dynv_set_float(struct dynvSystem* dynv_system, const char *path, float value); void dynv_set_bool(struct dynvSystem* dynv_system, const char *path, bool value); void dynv_set_string(struct dynvSystem* dynv_system, const char *path, const char* value); void dynv_set_color(struct dynvSystem* dynv_system, const char *path, const Color* value); struct dynvSystem* dynv_get_dynv(struct dynvSystem* dynv_system, const char *path); int32_t* dynv_get_int32_array_wd(struct dynvSystem* dynv_system, const char *path, int32_t *default_value, uint32_t default_count, uint32_t *count); float* dynv_get_float_array_wd(struct dynvSystem* dynv_system, const char *path, float *default_value, uint32_t default_count, uint32_t *count); bool* dynv_get_bool_array_wd(struct dynvSystem* dynv_system, const char *path, bool *default_value, uint32_t default_count, uint32_t *count); const char** dynv_get_string_array_wd(struct dynvSystem* dynv_system, const char *path, const char** default_value, uint32_t default_count, uint32_t *count); const Color** dynv_get_color_array_wd(struct dynvSystem* dynv_system, const char *path, const Color** default_value, uint32_t default_count, uint32_t *count); struct dynvSystem** dynv_get_dynv_array_wd(struct dynvSystem* dynv_system, const char *path, struct dynvSystem** default_value, uint32_t default_count, uint32_t *count); void dynv_set_int32_array(struct dynvSystem* dynv_system, const char *path, int32_t* values, uint32_t count); void dynv_set_float_array(struct dynvSystem* dynv_system, const char *path, float* values, uint32_t count); void dynv_set_bool_array(struct dynvSystem* dynv_system, const char *path, bool* values, uint32_t count); void dynv_set_string_array(struct dynvSystem* dynv_system, const char *path, const char** values, uint32_t count); void dynv_set_color_array(struct dynvSystem* dynv_system, const char *path, const Color** values, uint32_t count); void dynv_set_dynv_array(struct dynvSystem* dynv_system, const char *path, const struct dynvSystem** values, uint32_t count); #endif /* DYNVHELPERS_H_ */ gpick-gpick-0.2.6rc1/source/Endian.h000066400000000000000000000061021315430016700171630ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ENDIAN_H_ #define ENDIAN_H_ #include #define BSWAP_64(x) (((uint64_t)(x) << 56) | \ (((uint64_t)(x) << 40) & 0xff000000000000ULL) | \ (((uint64_t)(x) << 24) & 0xff0000000000ULL) | \ (((uint64_t)(x) << 8) & 0xff00000000ULL) | \ (((uint64_t)(x) >> 8) & 0xff000000ULL) | \ (((uint64_t)(x) >> 24) & 0xff0000ULL) | \ (((uint64_t)(x) >> 40) & 0xff00ULL) | \ ((uint64_t)(x) >> 56)) #define BSWAP_32(x) (((uint32_t)(x) << 24) | \ (((uint32_t)(x) << 8) & 0xff0000ULL) | \ (((uint32_t)(x) >> 8) & 0xff00ULL) | \ ((uint32_t)(x) >> 24)) #define BSWAP_16(x) (((uint16_t)(x) << 8) | \ ((uint16_t)(x) >> 8)) #ifdef BIG_ENDIAN_P #define UINT16_TO_LE(x) (BSWAP_16(x)) #define UINT16_FROM_LE(x) (BSWAP_16(x)) #define UINT32_TO_LE(x) (BSWAP_32(x)) #define UINT32_FROM_LE(x) (BSWAP_32(x)) #define UINT64_TO_LE(x) (BSWAP_64(x)) #define UINT64_FROM_LE(x) (BSWAP_64(x)) #define UINT16_TO_BE(x) (x) #define UINT16_FROM_BE(x) (x) #define UINT32_TO_BE(x) (x) #define UINT32_FROM_BE(x) (x) #define UINT64_TO_BE(x) (x) #define UINT64_FROM_BE(x) (x) #warning BigEndian #else #define UINT16_TO_LE(x) (x) #define UINT16_FROM_LE(x) (x) #define UINT32_TO_LE(x) (x) #define UINT32_FROM_LE(x) (x) #define UINT64_TO_LE(x) (x) #define UINT64_FROM_LE(x) (x) #define UINT16_TO_BE(x) (BSWAP_16(x)) #define UINT16_FROM_BE(x) (BSWAP_16(x)) #define UINT32_TO_BE(x) (BSWAP_32(x)) #define UINT32_FROM_BE(x) (BSWAP_32(x)) #define UINT64_TO_BE(x) (BSWAP_64(x)) #define UINT64_FROM_BE(x) (BSWAP_64(x)) #endif #endif /* ENDIAN_H_ */ gpick-gpick-0.2.6rc1/source/FileFormat.cpp000066400000000000000000000201611315430016700203510ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "FileFormat.h" #include "ColorObject.h" #include "ColorList.h" #include "DynvHelpers.h" #include "Endian.h" #include "dynv/DynvSystem.h" #include "dynv/DynvMemoryIO.h" #include #include #include #include #include using namespace std; struct ChunkHeader{ char type[16]; uint64_t size; }; #define CHUNK_TYPE_VERSION "GPA version" #define CHUNK_TYPE_HANDLER_MAP "handler_map" #define CHUNK_TYPE_COLOR_LIST "color_list" #define CHUNK_TYPE_COLOR_POSITIONS "color_positions" #define CHUNK_TYPE_COLOR_ACTIONS "color_actions" static int prepare_chunk_header(struct ChunkHeader* header, const char* type, uint64_t size) { size_t len = strlen(type); if (len >= sizeof(header->type)) len = sizeof(header->type) - 1; memcpy(header->type, type, len); memset(header->type+len, 0, sizeof(header->type) - len); header->size = UINT64_TO_LE(size); return 0; } static int check_chunk_header(struct ChunkHeader* header) { if (header->type[sizeof(header->type)-1] != 0) return -1; return 0; } static bool color_object_position_sort(ColorObject* x, ColorObject* y) { return x->getPosition() < y->getPosition(); } int palette_file_load(const char* filename, ColorList* color_list) { ifstream file(filename, ios::binary); if (file.is_open()){ struct dynvIO* mem_io = dynv_io_memory_new(); struct ChunkHeader header; file.read((char*) &header, sizeof(header)); if (file.fail()){ file.close(); dynv_io_free(mem_io); return -1; } struct dynvHandlerMap* handler_map = dynv_system_get_handler_map(color_list->params); dynvHandlerMap::HandlerVec handler_vec; list color_objects; while (check_chunk_header(&header) == 0){ if (strncmp(CHUNK_TYPE_HANDLER_MAP, header.type, sizeof(header.type)) == 0){ dynv_io_memory_prepare_size(mem_io, header.size); file.read((char*) dynv_io_memory_get_buffer(mem_io), header.size); handler_vec.clear(); dynv_handler_map_deserialize(handler_map, mem_io, handler_vec); }else if (strncmp(CHUNK_TYPE_COLOR_LIST, header.type, sizeof(header.type)) == 0){ dynv_io_memory_prepare_size(mem_io, header.size); file.read((char*) dynv_io_memory_get_buffer(mem_io), header.size); for (;;){ dynvSystem *params = dynv_system_create(handler_map); if (dynv_system_deserialize(params, handler_vec, mem_io) == 0){ auto color_object = new ColorObject(); color_object->setName(dynv_get_string_wd(params, "name", "")); Color *color = dynv_get_color_wdc(params, "color", nullptr); if (color != nullptr) color_object->setColor(*color); color_objects.push_back(color_object); }else{ dynv_system_release(params); break; } dynv_system_release(params); } }else if (strncmp(CHUNK_TYPE_COLOR_POSITIONS, header.type, sizeof(header.type)) == 0){ dynv_io_memory_prepare_size(mem_io, header.size); file.read((char*) dynv_io_memory_get_buffer(mem_io), header.size); uint32_t index, read; for (list::iterator i=color_objects.begin(); i != color_objects.end(); ++i){ if (dynv_io_read(mem_io, &index, sizeof(uint32_t), &read) == 0){ if (read != sizeof(uint32_t)) break; (*i)->setPosition(index); } } color_objects.sort(color_object_position_sort); for (list::iterator i=color_objects.begin(); i != color_objects.end(); ++i){ bool visible = (*i)->getPosition() != ~(size_t)0; (*i)->setVisible(visible); color_list_add_color_object(color_list, *i, visible); (*i)->release(); } }else if (strncmp(CHUNK_TYPE_VERSION, header.type, sizeof(header.type)) == 0){ dynv_io_memory_prepare_size(mem_io, header.size); file.read((char*) dynv_io_memory_get_buffer(mem_io), header.size); uint32_t read; uint32_t version; if (dynv_io_read(mem_io, &version, sizeof(uint32_t), &read) == 0){ version=UINT32_FROM_LE(version); } }else{ file.seekg(header.size, ios_base::cur); if (file.fail() || file.eof()) break; } file.read((char*) &header, sizeof(header)); if (file.fail()) break; } dynv_handler_map_release(handler_map); dynv_io_free(mem_io); file.close(); return 0; } return -1; } int palette_file_save(const char* filename, ColorList* color_list) { if (!filename || !color_list) return -1; ofstream file(filename, ios::binary); if (file.is_open()){ struct dynvIO* mem_io=dynv_io_memory_new(); char* data; uint32_t size; ofstream::pos_type end_pos; struct ChunkHeader header; prepare_chunk_header(&header, CHUNK_TYPE_VERSION, 4); file.write((char*)&header, sizeof(header)); uint32_t version=1*0x10000+0; version=UINT32_TO_LE(version); file.write((char*)&version, sizeof(uint32_t)); ofstream::pos_type handler_map_pos = file.tellp(); file.write((char*)&header, sizeof(header)); struct dynvHandlerMap* handler_map = dynv_system_get_handler_map(color_list->params); dynv_handler_map_serialize(handler_map, mem_io); dynv_io_memory_get_data(mem_io, &data, &size); file.write(data, size); dynv_io_reset(mem_io); end_pos = file.tellp(); file.seekp(handler_map_pos); prepare_chunk_header(&header, CHUNK_TYPE_HANDLER_MAP, end_pos-handler_map_pos-sizeof(struct ChunkHeader)); file.write((char*)&header, sizeof(header)); file.seekp(end_pos); ofstream::pos_type colorlist_pos = file.tellp(); file.write((char*)&header, sizeof(header)); for (auto color_object: color_list->colors){ dynvSystem *params = dynv_system_create(handler_map); dynv_set_string(params, "name", color_object->getName().c_str()); dynv_set_color(params, "color", &color_object->getColor()); dynv_system_serialize(params, mem_io); dynv_system_release(params); dynv_io_memory_get_data(mem_io, &data, &size); file.write(data, size); dynv_io_reset(mem_io); } dynv_handler_map_release(handler_map); dynv_io_free(mem_io); end_pos = file.tellp(); file.seekp(colorlist_pos); prepare_chunk_header(&header, CHUNK_TYPE_COLOR_LIST, end_pos-colorlist_pos-sizeof(struct ChunkHeader)); file.write((char*)&header, sizeof(header)); file.seekp(end_pos); color_list_get_positions(color_list); uint32_t *positions=new uint32_t [color_list->colors.size()]; uint32_t *position=positions; for (ColorList::iter i=color_list->colors.begin(); i != color_list->colors.end(); ++i){ *position = UINT32_TO_LE((*i)->getPosition()); ++position; } prepare_chunk_header(&header, CHUNK_TYPE_COLOR_POSITIONS, color_list->colors.size()*sizeof(uint32_t)); file.write((char*)&header, sizeof(header)); file.write((char*)positions, color_list->colors.size()*sizeof(uint32_t)); delete [] positions; file.close(); return 0; } return -1; } gpick-gpick-0.2.6rc1/source/FileFormat.h000066400000000000000000000034071315430016700200220ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_FILE_FORMAT_H_ #define GPICK_FILE_FORMAT_H_ class ColorList; int palette_file_save(const char* filename, ColorList* color_list); int palette_file_load(const char* filename, ColorList* color_list); #endif /* GPICK_FILE_FORMAT_H_ */ gpick-gpick-0.2.6rc1/source/FloatingPicker.cpp000066400000000000000000000335211315430016700212260ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "FloatingPicker.h" #include "ColorObject.h" #include "ColorList.h" #include "gtk/Zoomed.h" #include "gtk/ColorWidget.h" #include "uiUtilities.h" #include "Clipboard.h" #include "CopyMenu.h" #include "GlobalState.h" #include "ColorPicker.h" #include "Converter.h" #include "DynvHelpers.h" #include "ToolColorNaming.h" #include "ScreenReader.h" #include "Sampler.h" #include "color_names/ColorNames.h" #include #include #include using namespace math; using namespace std; typedef struct FloatingPickerArgs { GtkWidget* window; GtkWidget* zoomed; GtkWidget* color_widget; guint timeout_source_id; ColorSource *color_source; Converter *converter; GlobalState* gs; bool release_mode; bool single_pick_mode; bool click_mode; bool perform_custom_pick_action; bool menu_button_pressed; function custom_pick_action; function custom_done_action; }FloatingPickerArgs; class PickerColorNameAssigner: public ToolColorNameAssigner { protected: stringstream m_stream; public: PickerColorNameAssigner(GlobalState *gs): ToolColorNameAssigner(gs) { } void assign(ColorObject *color_object, const Color *color) { ToolColorNameAssigner::assign(color_object, color); } virtual std::string getToolSpecificName(ColorObject *color_object, const Color *color) { m_stream.str(""); m_stream << color_names_get(m_gs->getColorNames(), color, false); return m_stream.str(); } }; static void get_color_sample(FloatingPickerArgs *args, bool update_widgets, Color* c) { GdkScreen *screen; GdkModifierType state; int x, y; gdk_display_get_pointer(gdk_display_get_default(), &screen, &x, &y, &state); int monitor = gdk_screen_get_monitor_at_point(screen, x, y); GdkRectangle monitor_geometry; gdk_screen_get_monitor_geometry(screen, monitor, &monitor_geometry); Vec2 pointer(x,y); Rect2 screen_rect(monitor_geometry.x, monitor_geometry.y, monitor_geometry.x + monitor_geometry.width, monitor_geometry.y + monitor_geometry.height); auto screen_reader = args->gs->getScreenReader(); screen_reader_reset_rect(screen_reader); Rect2 sampler_rect, zoomed_rect, final_rect; sampler_get_screen_rect(args->gs->getSampler(), pointer, screen_rect, &sampler_rect); screen_reader_add_rect(screen_reader, screen, sampler_rect); if (update_widgets){ gtk_zoomed_get_screen_rect(GTK_ZOOMED(args->zoomed), pointer, screen_rect, &zoomed_rect); screen_reader_add_rect(screen_reader, screen, zoomed_rect); } screen_reader_update_surface(screen_reader, &final_rect); Vec2 offset; offset = Vec2(sampler_rect.getX() - final_rect.getX(), sampler_rect.getY() - final_rect.getY()); sampler_get_color_sample(args->gs->getSampler(), pointer, screen_rect, offset, c); if (update_widgets){ offset = Vec2(zoomed_rect.getX() - final_rect.getX(), zoomed_rect.getY() - final_rect.getY()); gtk_zoomed_update(GTK_ZOOMED(args->zoomed), pointer, screen_rect, offset, screen_reader_get_surface(screen_reader)); } } static gboolean update_display(FloatingPickerArgs *args) { GdkScreen *screen; GdkModifierType state; int x, y; int width, height; gdk_display_get_pointer(gdk_display_get_default(), &screen, &x, &y, &state); width = gdk_screen_get_width(screen); height = gdk_screen_get_height(screen); gint sx, sy; gtk_window_get_size(GTK_WINDOW(args->window), &sx, &sy); if (x + sx + sx / 2 > width){ x -= sx + sx / 2; }else{ x += sx / 2; } if (y + sy + sy / 2 > height){ y -= sy + sy / 2; }else{ y += sy / 2; } if (gtk_window_get_screen(GTK_WINDOW(args->window)) != screen){ gtk_window_set_screen(GTK_WINDOW(args->window), screen); } gtk_window_move(GTK_WINDOW(args->window), x, y); Color c; get_color_sample(args, true, &c); string text; if (args->converter != nullptr){ auto color_object = color_list_new_color_object(args->gs->getColorList(), &c); converter_get_text(color_object, args->converter, args->gs, text); color_object->release(); }else{ converter_get_text(c, ConverterArrayType::display, args->gs, text); } gtk_color_set_color(GTK_COLOR(args->color_widget), &c, text.c_str()); return true; } void floating_picker_activate(FloatingPickerArgs *args, bool hide_on_mouse_release, bool single_pick_mode, const char *converter_name) { #ifndef WIN32 //Pointer grabbing in Windows is broken, disabling floating picker for now if (converter_name != nullptr){ args->converter = converters_get(args->gs->getConverters(), converter_name); }else{ args->converter = nullptr; } args->release_mode = hide_on_mouse_release && !single_pick_mode; args->single_pick_mode = single_pick_mode; args->click_mode = true; GdkCursor* cursor; cursor = gdk_cursor_new(GDK_TCROSS); gtk_zoomed_set_zoom(GTK_ZOOMED(args->zoomed), dynv_get_float_wd(args->gs->getSettings(), "gpick.picker.zoom", 2)); update_display(args); gtk_widget_show(args->window); gdk_pointer_grab(gtk_widget_get_window(args->window), false, GdkEventMask(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK | GDK_BUTTON_PRESS_MASK), nullptr, cursor, GDK_CURRENT_TIME); gdk_keyboard_grab(gtk_widget_get_window(args->window), false, GDK_CURRENT_TIME); float refresh_rate = dynv_get_float_wd(args->gs->getSettings(), "gpick.picker.refresh_rate", 30); args->timeout_source_id = g_timeout_add_full(G_PRIORITY_DEFAULT_IDLE, 1000 / refresh_rate, (GSourceFunc)update_display, args, (GDestroyNotify)nullptr); #if GTK_MAJOR_VERSION >= 3 g_object_unref(cursor); #else gdk_cursor_unref(cursor); #endif #endif } void floating_picker_deactivate(FloatingPickerArgs *args) { gdk_pointer_ungrab(GDK_CURRENT_TIME); gdk_keyboard_ungrab(GDK_CURRENT_TIME); if (args->timeout_source_id > 0){ g_source_remove(args->timeout_source_id); args->timeout_source_id = 0; } gtk_widget_hide(args->window); } static gboolean scroll_event_cb(GtkWidget *widget, GdkEventScroll *event, FloatingPickerArgs *args) { double zoom = gtk_zoomed_get_zoom(GTK_ZOOMED(args->zoomed)); if ((event->direction == GDK_SCROLL_UP) || (event->direction == GDK_SCROLL_RIGHT)){ zoom += 1; }else{ zoom -= 1; } gtk_zoomed_set_zoom(GTK_ZOOMED(args->zoomed), zoom); return TRUE; } static void finish_picking(FloatingPickerArgs *args) { floating_picker_deactivate(args); dynv_set_float(args->gs->getSettings(), "gpick.picker.zoom", gtk_zoomed_get_zoom(GTK_ZOOMED(args->zoomed))); if (args->custom_done_action) args->custom_done_action(args); } static void complete_picking(FloatingPickerArgs *args) { if (args->release_mode || args->click_mode){ Color c; get_color_sample(args, false, &c); if (args->perform_custom_pick_action){ if (args->custom_pick_action) args->custom_pick_action(args, c); }else{ ColorObject* color_object; color_object = color_list_new_color_object(args->gs->getColorList(), &c); if (args->single_pick_mode){ Clipboard::set(color_object, args->gs, args->converter); }else{ if (dynv_get_bool_wd(args->gs->getSettings(), "gpick.picker.sampler.copy_on_release", false)){ Clipboard::set(color_object, args->gs, args->converter); } if (dynv_get_bool_wd(args->gs->getSettings(), "gpick.picker.sampler.add_on_release", false)){ PickerColorNameAssigner name_assigner(args->gs); name_assigner.assign(color_object, &c); color_list_add_color_object(args->gs->getColorList(), color_object, 1); } } color_object->release(); } } } static void show_copy_menu(int button, int event_time, FloatingPickerArgs *args) { Color c; get_color_sample(args, false, &c); GtkWidget *menu; ColorList *color_list = color_list_new_with_one_color(args->gs->getColorList(), &c); menu = CopyMenu::newMenu(*color_list->colors.begin(), args->gs); gtk_widget_show_all(GTK_WIDGET(menu)); gtk_menu_popup(GTK_MENU(menu), nullptr, nullptr, nullptr, nullptr, button, event_time); g_object_ref_sink(menu); g_object_unref(menu); color_list_destroy(color_list); } static gboolean button_release_cb(GtkWidget *widget, GdkEventButton *event, FloatingPickerArgs *args) { if ((event->type == GDK_BUTTON_RELEASE) && (event->button == 1)) { complete_picking(args); finish_picking(args); }else if ((event->type == GDK_BUTTON_RELEASE) && (event->button == 3) && args->menu_button_pressed) { args->menu_button_pressed = false; show_copy_menu(event->button, event->time, args); finish_picking(args); } return false; } static gboolean button_press_cb(GtkWidget *widget, GdkEventButton *event, FloatingPickerArgs *args) { if ((event->type == GDK_BUTTON_PRESS) && (event->button == 3)) { args->menu_button_pressed = true; } return false; } static gboolean key_up_cb(GtkWidget *widget, GdkEventKey *event, FloatingPickerArgs *args) { guint modifiers = gtk_accelerator_get_default_mod_mask(); gint add_x = 0, add_y = 0; switch (event->keyval){ case GDK_KEY_Return: complete_picking(args); finish_picking(args); return TRUE; break; case GDK_KEY_Escape: finish_picking(args); return TRUE; break; case GDK_KEY_m: { int x, y; gdk_display_get_pointer(gdk_display_get_default(), nullptr, &x, &y, nullptr); math::Vec2 position(x, y); if ((event->state & modifiers) == GDK_CONTROL_MASK){ gtk_zoomed_set_mark(GTK_ZOOMED(args->zoomed), 1, position); }else{ gtk_zoomed_set_mark(GTK_ZOOMED(args->zoomed), 0, position); } } break; case GDK_KEY_Left: if ((event->state & modifiers) == GDK_SHIFT_MASK) add_x -= 10; else add_x--; break; case GDK_KEY_Right: if ((event->state & modifiers) == GDK_SHIFT_MASK) add_x += 10; else add_x++; break; case GDK_KEY_Up: if ((event->state & modifiers) == GDK_SHIFT_MASK) add_y -= 10; else add_y--; break; case GDK_KEY_Down: if ((event->state & modifiers) == GDK_SHIFT_MASK) add_y += 10; else add_y++; break; default: if (args->color_source && color_picker_key_up(args->color_source, event)){ args->release_mode = false; //key pressed and color picked, disable copy on mouse button release return TRUE; } } if (add_x || add_y){ gint x, y; GdkDisplay *display = nullptr; GdkScreen *screen = nullptr; display = gdk_display_get_default(); screen = gdk_display_get_default_screen(display); gdk_display_get_pointer(display, nullptr, &x, &y, nullptr); x += add_x; y += add_y; gdk_display_warp_pointer(display, screen, x, y); } return FALSE; } static void destroy_cb(GtkWidget *widget, FloatingPickerArgs *args) { delete args; } FloatingPickerArgs* floating_picker_new(GlobalState *gs) { FloatingPickerArgs *args = new FloatingPickerArgs; args->gs = gs; args->window = gtk_window_new(GTK_WINDOW_POPUP); args->color_source = nullptr; args->perform_custom_pick_action = false; args->menu_button_pressed = false; gtk_window_set_skip_pager_hint(GTK_WINDOW(args->window), true); gtk_window_set_skip_taskbar_hint(GTK_WINDOW(args->window), true); gtk_window_set_decorated(GTK_WINDOW(args->window), false); gtk_widget_set_size_request(args->window, -1, -1); GtkWidget* vbox = gtk_vbox_new(0, 0); gtk_container_add (GTK_CONTAINER(args->window), vbox); gtk_widget_show(vbox); args->zoomed = gtk_zoomed_new(); gtk_widget_show(args->zoomed); gtk_box_pack_start(GTK_BOX(vbox), args->zoomed, false, false, 0); args->color_widget = gtk_color_new(); gtk_widget_show(args->color_widget); gtk_box_pack_start(GTK_BOX(vbox), args->color_widget, true, true, 0); g_signal_connect(G_OBJECT(args->window), "scroll_event", G_CALLBACK(scroll_event_cb), args); g_signal_connect(G_OBJECT(args->window), "button-press-event", G_CALLBACK(button_press_cb), args); g_signal_connect(G_OBJECT(args->window), "button-release-event", G_CALLBACK(button_release_cb), args); g_signal_connect(G_OBJECT(args->window), "key_press_event", G_CALLBACK(key_up_cb), args); g_signal_connect(G_OBJECT(args->window), "destroy", G_CALLBACK(destroy_cb), args); return args; } void floating_picker_set_picker_source(FloatingPickerArgs *args, ColorSource* color_source) { args->color_source = color_source; } void floating_picker_free(FloatingPickerArgs *args) { gtk_widget_destroy(args->window); } void floating_picker_enable_custom_pick_action(FloatingPickerArgs *args) { args->perform_custom_pick_action = true; } void floating_picker_set_custom_pick_action(FloatingPickerArgs *args, std::function action) { args->custom_pick_action = action; } void floating_picker_set_custom_done_action(FloatingPickerArgs *args, std::function action) { args->custom_done_action = action; } gpick-gpick-0.2.6rc1/source/FloatingPicker.h000066400000000000000000000046201315430016700206710ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_FLOATING_PICKER_H_ #define GPICK_FLOATING_PICKER_H_ struct Color; #include class GlobalState; struct ColorSource; typedef struct FloatingPickerArgs* FloatingPicker; FloatingPicker floating_picker_new(GlobalState *gs); void floating_picker_set_picker_source(FloatingPicker fp, ColorSource* color_source); void floating_picker_free(FloatingPicker fp); void floating_picker_activate(FloatingPicker fp, bool hide_on_mouse_release, bool single_pick_mode, const char *converter_name); void floating_picker_deactivate(FloatingPicker fp); void floating_picker_set_custom_pick_action(FloatingPicker fp, std::function action); void floating_picker_set_custom_done_action(FloatingPicker fp, std::function action); void floating_picker_enable_custom_pick_action(FloatingPicker fp); #endif /* GPICK_FLOATING_PICKER_H_ */ gpick-gpick-0.2.6rc1/source/GenerateScheme.cpp000066400000000000000000001015141315430016700212020ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "GenerateScheme.h" #include "ColorObject.h" #include "ColorSourceManager.h" #include "ColorSource.h" #include "DragDrop.h" #include "GlobalState.h" #include "ToolColorNaming.h" #include "uiUtilities.h" #include "ColorList.h" #include "MathUtil.h" #include "ColorRYB.h" #include "gtk/ColorWidget.h" #include "gtk/ColorWheel.h" #include "ColorWheelType.h" #include "uiColorInput.h" #include "CopyPaste.h" #include "Converter.h" #include "DynvHelpers.h" #include "Internationalisation.h" #include "Random.h" #include "color_names/ColorNames.h" #include "Clipboard.h" #include "StandardMenu.h" #include "NearestColorsMenu.h" #include #include #include #include #include #include using namespace std; #define MAX_COLOR_WIDGETS 6 typedef struct GenerateSchemeArgs{ ColorSource source; GtkWidget* main; GtkWidget* statusbar; GtkWidget *gen_type; GtkWidget *wheel_type; GtkWidget *color_wheel; GtkWidget *hue; GtkWidget *saturation; GtkWidget *lightness; GtkWidget *color_previews; GtkWidget *last_focused_color; GtkWidget *colors[MAX_COLOR_WIDGETS]; double color_hue[MAX_COLOR_WIDGETS]; struct{ double orig_hue; double orig_saturation; double orig_value; double hue; double saturation; double value; }mod[MAX_COLOR_WIDGETS]; bool wheel_locked; int colors_visible; struct dynvSystem *params; GlobalState* gs; ColorList *preview_color_list; }GenerateSchemeArgs; const SchemeType scheme_types[]={ {N_("Complementary"), 1, 1, {180}}, {N_("Analogous"), 5, 1, {30}}, {N_("Triadic"), 2, 1, {120}}, {N_("Split-Complementary"), 2, 2, {150, 60}}, {N_("Rectangle (tetradic)"), 3, 2, {60, 120}}, {N_("Square"), 3, 1, {90}}, {N_("Neutral"), 5, 1, {15}}, {N_("Clash"), 2, 2, {90, 180}}, {N_("Five-Tone"), 4, 4, {115, 40, 50, 40}}, {N_("Six-Tone"), 5, 2, {30, 90}}, }; class GenerateSchemeColorNameAssigner: public ToolColorNameAssigner { protected: stringstream m_stream; int32_t m_ident; int32_t m_schemetype; public: GenerateSchemeColorNameAssigner(GlobalState *gs): ToolColorNameAssigner(gs) { } void assign(ColorObject *color_object, const Color *color, const int32_t ident, const int32_t schemetype) { m_ident = ident; m_schemetype = schemetype; ToolColorNameAssigner::assign(color_object, color); } virtual std::string getToolSpecificName(ColorObject *color_object, const Color *color) { m_stream.str(""); m_stream << _("scheme") << " " << _(generate_scheme_get_scheme_type(m_schemetype)->name) << " #" << m_ident << "[" << color_names_get(m_gs->getColorNames(), color, false) << "]"; return m_stream.str(); } }; static int set_rgb_color(GenerateSchemeArgs *args, ColorObject* color, uint32_t color_index); static int set_rgb_color_by_widget(GenerateSchemeArgs *args, ColorObject* color, GtkWidget* color_widget); static void calc(GenerateSchemeArgs *args, bool preview, bool save_settings){ int32_t type = gtk_combo_box_get_active(GTK_COMBO_BOX(args->gen_type)); int32_t wheel_type = gtk_combo_box_get_active(GTK_COMBO_BOX(args->wheel_type)); gtk_color_wheel_set_color_wheel_type(GTK_COLOR_WHEEL(args->color_wheel), &color_wheel_types_get()[wheel_type]); gtk_color_wheel_set_n_colors(GTK_COLOR_WHEEL(args->color_wheel), generate_scheme_get_scheme_type(type)->colors + 1); double hue = gtk_range_get_value(GTK_RANGE(args->hue)); double saturation = gtk_range_get_value(GTK_RANGE(args->saturation)); double lightness = gtk_range_get_value(GTK_RANGE(args->lightness)); if (save_settings){ dynv_set_int32(args->params, "type", type); dynv_set_int32(args->params, "wheel_type", wheel_type); dynv_set_float(args->params, "hue", hue); dynv_set_float(args->params, "saturation", saturation); dynv_set_float(args->params, "lightness", lightness); } hue /= 360.0; saturation /= 100.0; lightness /= 100.0; Color color, hsl, r; gint step_i; ColorList *color_list; if (preview) color_list = args->preview_color_list; else color_list = args->gs->getColorList(); const ColorWheelType *wheel = &color_wheel_types_get()[wheel_type]; float chaos = 0; float hue_offset = 0; float hue_step; Color hsv; for (step_i = 0; step_i <= generate_scheme_get_scheme_type(type)->colors; ++step_i) { wheel->hue_to_hsl(wrap_float(hue + args->mod[step_i].hue), &hsl); hsl.hsl.lightness = clamp_float(hsl.hsl.lightness + lightness, 0, 1); hsl.hsl.saturation = clamp_float(hsl.hsl.saturation * saturation, 0, 1); color_hsl_to_hsv(&hsl, &hsv); args->mod[step_i].orig_hue = hue; args->mod[step_i].orig_saturation = hsv.hsv.saturation; args->mod[step_i].orig_value = hsv.hsv.value; hsv.hsv.saturation = clamp_float(hsv.hsv.saturation + args->mod[step_i].saturation, 0, 1); hsv.hsv.value = clamp_float(hsv.hsv.value + args->mod[step_i].value, 0, 1); color_hsv_to_rgb(&hsv, &r); ColorObject *color_object = color_list_new_color_object(color_list, &r); args->color_hue[step_i] = hue_offset; color_list_add_color_object(color_list, color_object, 1); color_object->release(); gtk_color_wheel_set_hue(GTK_COLOR_WHEEL(args->color_wheel), step_i, wrap_float(hue + args->mod[step_i].hue)); gtk_color_wheel_set_saturation(GTK_COLOR_WHEEL(args->color_wheel), step_i, hsv.hsv.saturation); gtk_color_wheel_set_value(GTK_COLOR_WHEEL(args->color_wheel), step_i, hsv.hsv.value); hue_step = (generate_scheme_get_scheme_type(type)->turn[step_i % generate_scheme_get_scheme_type(type)->turn_types]) / (360.0) + chaos*(((random_get(args->gs->getRandom()) & 0xFFFFFFFF) / (gdouble)0xFFFFFFFF) - 0.5); hue = wrap_float(hue + hue_step); hue_offset = wrap_float(hue_offset + hue_step); } if (preview){ size_t total_colors = generate_scheme_get_scheme_type(type)->colors + 1; if (total_colors > MAX_COLOR_WIDGETS) total_colors = MAX_COLOR_WIDGETS; for (size_t i = args->colors_visible; i > total_colors; --i) gtk_widget_hide(args->colors[i-1]); for (size_t i = args->colors_visible; i < total_colors; ++i) gtk_widget_show(args->colors[i]); args->colors_visible = total_colors; size_t j = 0; for (ColorList::iter i = color_list->colors.begin(); i != color_list->colors.end(); ++i){ color = (*i)->getColor(); string text; converter_get_text(color, ConverterArrayType::display, args->gs, text); gtk_color_set_color(GTK_COLOR(args->colors[j]), &color, text.c_str()); ++j; if (j >= total_colors) break; } } } static void update(GtkWidget *widget, GenerateSchemeArgs *args ){ color_list_remove_all(args->preview_color_list); calc(args, true, false); } static void hue_changed_cb(GtkWidget *widget, gint color_id, GenerateSchemeArgs *args) { if (args->wheel_locked){ double hue = gtk_range_get_value(GTK_RANGE(args->hue)) / 360.0; hue = wrap_float(hue - args->mod[color_id].hue + gtk_color_wheel_get_hue(GTK_COLOR_WHEEL(widget), color_id) - args->mod[color_id].orig_hue); gtk_range_set_value(GTK_RANGE(args->hue), hue * 360.0); }else{ args->mod[color_id].hue = gtk_color_wheel_get_hue(GTK_COLOR_WHEEL(widget), color_id) - args->mod[color_id].orig_hue; update(widget, args); } } static void saturation_value_changed_cb(GtkWidget *widget, gint color_id, GenerateSchemeArgs *args) { if (args->wheel_locked){ double saturation = gtk_range_get_value(GTK_RANGE(args->saturation)) / 100.0; double lightness = gtk_range_get_value(GTK_RANGE(args->lightness)) / 100.0; //lightness = gtk_color_wheel_get_value(GTK_COLOR_WHEEL(widget), color_id); gtk_range_set_value(GTK_RANGE(args->saturation), saturation * 100.0); gtk_range_set_value(GTK_RANGE(args->lightness), lightness * 100.0); }else{ args->mod[color_id].saturation = gtk_color_wheel_get_saturation(GTK_COLOR_WHEEL(widget), color_id) - args->mod[color_id].orig_saturation; args->mod[color_id].value = gtk_color_wheel_get_value(GTK_COLOR_WHEEL(widget), color_id) - args->mod[color_id].orig_value; update(widget, args); } } static void color_wheel_locked_toggled_cb(GtkWidget* widget, GenerateSchemeArgs* args){ args->wheel_locked = gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(widget)); gtk_color_wheel_set_block_editable(GTK_COLOR_WHEEL(args->color_wheel), !args->wheel_locked); } static void color_reset_scheme_cb(GtkWidget *widget, GenerateSchemeArgs *args){ for (int i = 0; i < MAX_COLOR_WIDGETS; ++i){ args->mod[i].hue = 0; args->mod[i].saturation = 0; args->mod[i].value = 0; } update(widget, args); } static void color_wheel_show_menu(GtkWidget* widget, GenerateSchemeArgs* args, GdkEventButton *event ){ GtkWidget *menu; GtkWidget* item; menu = gtk_menu_new(); item = gtk_check_menu_item_new_with_mnemonic(_("_Linked")); gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item), args->wheel_locked); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "toggled", G_CALLBACK(color_wheel_locked_toggled_cb), args); gtk_menu_shell_append (GTK_MENU_SHELL (menu), gtk_separator_menu_item_new ()); item = gtk_menu_item_new_with_image(_("_Reset scheme"), gtk_image_new_from_stock(GTK_STOCK_CANCEL, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT (item), "activate", G_CALLBACK(color_reset_scheme_cb), args); gtk_widget_show_all(GTK_WIDGET(menu)); gint32 button, event_time; if (event){ button = event->button; event_time = event->time; }else{ button = 0; event_time = gtk_get_current_event_time (); } gtk_menu_popup(GTK_MENU(menu), nullptr, nullptr, nullptr, nullptr, button, event_time); g_object_ref_sink(menu); g_object_unref(menu); } static gboolean color_wheel_button_press_cb(GtkWidget *widget, GdkEventButton *event, GenerateSchemeArgs* args) { if (event->button == 3 && event->type == GDK_BUTTON_PRESS){ color_wheel_show_menu(widget, args, event); } return false; } static void color_wheel_popup_menu_cb(GtkWidget *widget, GenerateSchemeArgs* args){ color_wheel_show_menu(widget, args, 0); } static void on_color_paste(GtkWidget *widget, gpointer item) { GenerateSchemeArgs* args=(GenerateSchemeArgs*)item; GtkWidget* color_widget = GTK_WIDGET(g_object_get_data(G_OBJECT(widget), "color_widget")); ColorObject* color_object; if (copypaste_get_color_object(&color_object, args->gs) == 0){ set_rgb_color_by_widget(args, color_object, color_widget); color_object->release(); } } static void color_reset_cb(GtkWidget *widget, GenerateSchemeArgs *args){ GtkWidget* color_widget = GTK_WIDGET(g_object_get_data(G_OBJECT(widget), "color_widget")); for (int i = 0; i < args->colors_visible; ++i){ if (args->colors[i] == color_widget){ args->mod[i].hue = 0; args->mod[i].saturation = 0; args->mod[i].value = 0; update(widget, args); return; } } } static void on_color_edit(GtkWidget *widget, gpointer item) { GenerateSchemeArgs* args=(GenerateSchemeArgs*)item; GtkWidget* color_widget = GTK_WIDGET(g_object_get_data(G_OBJECT(widget), "color_widget")); Color c; gtk_color_get_color(GTK_COLOR(color_widget), &c); ColorObject* color_object = color_list_new_color_object(args->gs->getColorList(), &c); ColorObject* new_color_object = 0; if (dialog_color_input_show(GTK_WINDOW(gtk_widget_get_toplevel(args->main)), args->gs, color_object, &new_color_object ) == 0){ set_rgb_color_by_widget(args, new_color_object, color_widget); new_color_object->release(); } color_object->release(); } static string identify_color_widget(GtkWidget *widget, GenerateSchemeArgs *args) { for (int i = 0; i < MAX_COLOR_WIDGETS; ++i){ if (args->colors[i] == widget){ return "result " + boost::lexical_cast(i + 1); } } return "unknown"; } static void add_color_to_palette(GtkWidget *color_widget, GenerateSchemeColorNameAssigner &name_assigner, GenerateSchemeArgs *args) { Color c; ColorObject *color_object; string widget_ident; int32_t type = gtk_combo_box_get_active(GTK_COMBO_BOX(args->gen_type)); gtk_color_get_color(GTK_COLOR(color_widget), &c); color_object = color_list_new_color_object(args->gs->getColorList(), &c); widget_ident = identify_color_widget(color_widget, args); name_assigner.assign(color_object, &c, atoi(widget_ident.c_str()+7), type); color_list_add_color_object(args->gs->getColorList(), color_object, 1); color_object->release(); } static void on_color_add_to_palette(GtkWidget *widget, gpointer item) { GenerateSchemeArgs* args = (GenerateSchemeArgs*)item; GtkWidget *color_widget = GTK_WIDGET(g_object_get_data(G_OBJECT(widget), "color_widget")); GenerateSchemeColorNameAssigner name_assigner(args->gs); add_color_to_palette(color_widget, name_assigner, args); } static void on_color_add_all_to_palette(GtkWidget *widget, gpointer item) { GenerateSchemeArgs* args = (GenerateSchemeArgs*)item; GenerateSchemeColorNameAssigner name_assigner(args->gs); for (int i = 0; i < args->colors_visible; ++i){ add_color_to_palette(args->colors[i], name_assigner, args); } } static gboolean color_focus_in_cb(GtkWidget *widget, GdkEventFocus *event, GenerateSchemeArgs *args){ args->last_focused_color = widget; for (int i = 0; i < MAX_COLOR_WIDGETS; ++i){ if (widget == args->colors[i]){ gtk_color_wheel_set_selected(GTK_COLOR_WHEEL(args->color_wheel), i); return false; } } return false; } static void on_color_activate(GtkWidget *widget, gpointer item) { GenerateSchemeArgs* args=(GenerateSchemeArgs*)item; GenerateSchemeColorNameAssigner name_assigner(args->gs); add_color_to_palette(widget, name_assigner, args); } static void color_show_menu(GtkWidget* widget, GenerateSchemeArgs* args, GdkEventButton *event ){ GtkWidget *menu; GtkWidget* item; menu = gtk_menu_new (); item = gtk_menu_item_new_with_image (_("_Add to palette"), gtk_image_new_from_stock(GTK_STOCK_ADD, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK (on_color_add_to_palette), args); g_object_set_data(G_OBJECT(item), "color_widget", widget); item = gtk_menu_item_new_with_image (_("A_dd all to palette"), gtk_image_new_from_stock(GTK_STOCK_ADD, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK (on_color_add_all_to_palette), args); g_object_set_data(G_OBJECT(item), "color_widget", widget); gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); Color c; gtk_color_get_color(GTK_COLOR(widget), &c); ColorObject *color_object = color_list_new_color_object(args->gs->getColorList(), &c); StandardMenu::appendMenu(menu, color_object, args->gs); color_object->release(); gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); item = gtk_menu_item_new_with_image (_("_Edit..."), gtk_image_new_from_stock(GTK_STOCK_EDIT, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK (on_color_edit), args); g_object_set_data(G_OBJECT(item), "color_widget", widget); item = gtk_menu_item_new_with_image (_("_Paste"), gtk_image_new_from_stock(GTK_STOCK_PASTE, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK (on_color_paste), args); g_object_set_data(G_OBJECT(item), "color_widget", widget); if (copypaste_is_color_object_available(args->gs) != 0){ gtk_widget_set_sensitive(item, false); } gtk_menu_shell_append (GTK_MENU_SHELL (menu), gtk_separator_menu_item_new ()); item = gtk_menu_item_new_with_image(_("_Reset"), gtk_image_new_from_stock(GTK_STOCK_CANCEL, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT (item), "activate", G_CALLBACK(color_reset_cb), args); g_object_set_data(G_OBJECT(item), "color_widget", widget); gtk_widget_show_all (GTK_WIDGET(menu)); gint32 button, event_time; if (event){ button = event->button; event_time = event->time; }else{ button = 0; event_time = gtk_get_current_event_time (); } gtk_menu_popup (GTK_MENU (menu), nullptr, nullptr, nullptr, nullptr, button, event_time); g_object_ref_sink(menu); g_object_unref(menu); } static gboolean on_color_button_press (GtkWidget *widget, GdkEventButton *event, GenerateSchemeArgs* args) { if (event->button == 3 && event->type == GDK_BUTTON_PRESS){ color_show_menu(widget, args, event); } return false; } static void on_color_popup_menu(GtkWidget *widget, GenerateSchemeArgs* args){ color_show_menu(widget, args, 0); } static gboolean on_color_key_press (GtkWidget *widget, GdkEventKey *event, GenerateSchemeArgs* args){ guint modifiers = gtk_accelerator_get_default_mod_mask(); Color c; ColorObject* color_object; GtkWidget* color_widget = widget; switch(event->keyval){ case GDK_KEY_c: if ((event->state&modifiers) == GDK_CONTROL_MASK){ gtk_color_get_color(GTK_COLOR(color_widget), &c); Clipboard::set(c, args->gs); return true; } return false; break; case GDK_KEY_v: if ((event->state&modifiers) == GDK_CONTROL_MASK){ if (copypaste_get_color_object(&color_object, args->gs) == 0){ set_rgb_color_by_widget(args, color_object, color_widget); color_object->release(); } return true; } return false; break; default: return false; break; } return false; } static gchar* format_saturation_value_cb (GtkScale *scale, gdouble value){ return g_strdup_printf ("%d%%", int(value)); } static gchar* format_lightness_value_cb (GtkScale *scale, gdouble value){ if (value>=0) return g_strdup_printf ("+%d%%", int(value)); else return g_strdup_printf ("-%d%%", -int(value)); } static int source_destroy(GenerateSchemeArgs *args){ color_list_destroy(args->preview_color_list); dynv_system_release(args->params); gtk_widget_destroy(args->main); delete args; return 0; } static int source_get_color(GenerateSchemeArgs *args, ColorObject** color){ GenerateSchemeColorNameAssigner name_assigner(args->gs); Color c; string widget_ident; int32_t type = gtk_combo_box_get_active(GTK_COMBO_BOX(args->gen_type)); if (args->last_focused_color){ gtk_color_get_color(GTK_COLOR(args->last_focused_color), &c); widget_ident = identify_color_widget(args->last_focused_color, args); }else{ gtk_color_get_color(GTK_COLOR(args->colors[0]), &c); widget_ident = identify_color_widget(args->colors[0], args); } *color = color_list_new_color_object(args->gs->getColorList(), &c); name_assigner.assign(*color, &c, atoi(widget_ident.c_str() + 7), type); return 0; } static int set_rgb_color_by_widget(GenerateSchemeArgs *args, ColorObject* color_object, GtkWidget* color_widget){ for (int i=0; icolors_visible; ++i){ if (args->colors[i] == color_widget){ set_rgb_color(args, color_object, i); return 0; } } return -1; } static int set_rgb_color(GenerateSchemeArgs *args, ColorObject* color_object, uint32_t color_index) { Color color = color_object->getColor(); double hue; double saturation; double lightness; double shifted_hue; Color hsl, hsv, hsl_results; color_rgb_to_hsv(&color, &hsv); //hsv.hsv.saturation = clamp_float(hsv.hsv.saturation - args->mod[color_index].saturation, 0, 1); //hsv.hsv.value = clamp_float(hsv.hsv.value - args->mod[color_index].value, 0, 1); color_hsv_to_hsl(&hsv, &hsl); int32_t wheel_type = gtk_combo_box_get_active(GTK_COMBO_BOX(args->wheel_type)); const ColorWheelType *wheel = &color_wheel_types_get()[wheel_type]; wheel->rgbhue_to_hue(hsl.hsl.hue, &hue); //color_rgbhue_to_rybhue(hsl.hsl.hue, &hue); shifted_hue = wrap_float(hue - args->color_hue[color_index] - args->mod[color_index].hue); wheel->hue_to_hsl(hue, &hsl_results); saturation = hsl.hsl.saturation * 1/hsl_results.hsl.saturation; lightness = hsl.hsl.lightness - hsl_results.hsl.lightness; shifted_hue *= 360.0; saturation *= 100.0; lightness *= 100.0; gtk_range_set_value(GTK_RANGE(args->hue), shifted_hue); gtk_range_set_value(GTK_RANGE(args->saturation), saturation); gtk_range_set_value(GTK_RANGE(args->lightness), lightness); return 0; } static int source_set_nth_color(GenerateSchemeArgs *args, uint32_t color_n, ColorObject* color_object) { if (color_n < 0 || color_n > 6) return -1; return set_rgb_color(args, color_object, color_n); } static int source_set_color(GenerateSchemeArgs *args, ColorObject *color_object) { if (args->last_focused_color){ return set_rgb_color_by_widget(args, color_object, args->last_focused_color); }else{ return set_rgb_color(args, color_object, 0); } } static int source_activate(GenerateSchemeArgs *args) { auto chain = args->gs->getTransformationChain(); for (uint32_t i = 0; i < MAX_COLOR_WIDGETS; ++i){ gtk_color_set_transformation_chain(GTK_COLOR(args->colors[i]), chain); } gtk_statusbar_push(GTK_STATUSBAR(args->statusbar), gtk_statusbar_get_context_id(GTK_STATUSBAR(args->statusbar), "empty"), ""); return 0; } static int source_deactivate(GenerateSchemeArgs *args) { color_list_remove_all(args->preview_color_list); calc(args, true, true); dynv_set_bool(args->params, "wheel_locked", args->wheel_locked); float hsv_shift_array[MAX_COLOR_WIDGETS * 3]; for (uint32_t i = 0; i < MAX_COLOR_WIDGETS; ++i){ hsv_shift_array[i * 3 + 0] = args->mod[i].hue; hsv_shift_array[i * 3 + 1] = args->mod[i].saturation; hsv_shift_array[i * 3 + 2] = args->mod[i].value; } dynv_set_float_array(args->params, "hsv_shift", hsv_shift_array, MAX_COLOR_WIDGETS * 3); return 0; } static ColorObject* get_color_object(struct DragDrop* dd){ GenerateSchemeArgs* args = (GenerateSchemeArgs*)dd->userdata; ColorObject* color_object; if (source_get_color(args, &color_object) == 0){ return color_object; } return 0; } static int set_color_object_at(struct DragDrop* dd, ColorObject* color_object, int x, int y, bool move) { GenerateSchemeArgs* args = static_cast(dd->userdata); set_rgb_color(args, color_object, (uintptr_t)dd->userdata2); return 0; } static int set_color_object_at_color_wheel(struct DragDrop* dd, ColorObject* color_object, int x, int y, bool move){ int item = gtk_color_wheel_get_at(GTK_COLOR_WHEEL(dd->widget), x, y); GenerateSchemeArgs* args = static_cast(dd->userdata); if (item == -1){ }else if (item >= 0){ Color color, hsl; double hue; color = color_object->getColor(); color_rgb_to_hsl(&color, &hsl); int32_t wheel_type = gtk_combo_box_get_active(GTK_COMBO_BOX(args->wheel_type)); const ColorWheelType *wheel = &color_wheel_types_get()[wheel_type]; wheel->rgbhue_to_hue(hsl.hsl.hue, &hue); if (args->wheel_locked){ double hue_shift = (hue - args->mod[item].orig_hue) - args->mod[item].hue; hue = wrap_float(gtk_range_get_value(GTK_RANGE(args->hue)) / 360.0 + hue_shift); gtk_range_set_value(GTK_RANGE(args->hue), hue * 360.0); }else{ args->mod[item].hue = hue - args->mod[item].orig_hue; update(dd->widget, args); } } return 0; } static bool test_at_color_wheel(struct DragDrop* dd, int x, int y){ int item = gtk_color_wheel_get_at(GTK_COLOR_WHEEL(dd->widget), x, y); if (item == -1){ }else if (item >= 0){ return true; } return false; } static ColorSource* source_implement(ColorSource *source, GlobalState *gs, struct dynvSystem *dynv_namespace){ GenerateSchemeArgs* args = new GenerateSchemeArgs; args->params = dynv_system_ref(dynv_namespace); args->statusbar = gs->getStatusBar(); color_source_init(&args->source, source->identificator, source->hr_name); args->source.destroy = (int (*)(ColorSource *source))source_destroy; args->source.get_color = (int (*)(ColorSource *source, ColorObject** color))source_get_color; args->source.set_color = (int (*)(ColorSource *source, ColorObject* color))source_set_color; args->source.set_nth_color = (int (*)(ColorSource *source, size_t color_n, ColorObject* color))source_set_nth_color; args->source.deactivate = (int (*)(ColorSource *source))source_deactivate; args->source.activate = (int (*)(ColorSource *source))source_activate; uint32_t hsv_shift_array_size = 0; float *hsv_shift_array = dynv_get_float_array_wd(args->params, "hsv_shift", 0, 0, &hsv_shift_array_size); hsv_shift_array_size /= 3; for (uint32_t i = 0; i < MAX_COLOR_WIDGETS; ++i){ if (i < hsv_shift_array_size){ args->mod[i].hue = hsv_shift_array[i * 3 + 0]; args->mod[i].saturation = hsv_shift_array[i * 3 + 1]; args->mod[i].value = hsv_shift_array[i * 3 + 2]; }else{ args->mod[i].hue = 0; args->mod[i].saturation = 0; args->mod[i].value = 0; } } if (hsv_shift_array) delete [] hsv_shift_array; GtkWidget *table, *vbox, *hbox, *widget, *hbox2; hbox = gtk_hbox_new(FALSE, 5); vbox = gtk_vbox_new(FALSE, 5); gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 5); args->color_previews = gtk_table_new(3, 2, false); gtk_box_pack_start(GTK_BOX(vbox), args->color_previews, true, true, 0); struct DragDrop dd; dragdrop_init(&dd, gs); dd.userdata = args; dd.get_color_object = get_color_object; dd.set_color_object_at = set_color_object_at; for (intptr_t i = 0; i < MAX_COLOR_WIDGETS; ++i){ widget = gtk_color_new(); gtk_color_set_rounded(GTK_COLOR(widget), true); gtk_color_set_roundness(GTK_COLOR(widget), 5); gtk_color_set_hcenter(GTK_COLOR(widget), true); gtk_table_attach(GTK_TABLE(args->color_previews), widget, i % 2, (i % 2) + 1, i / 2, i / 2 + 1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL | GTK_EXPAND), 0, 0); args->colors[i] = widget; g_signal_connect(G_OBJECT(widget), "button-press-event", G_CALLBACK(on_color_button_press), args); g_signal_connect(G_OBJECT(widget), "activated", G_CALLBACK(on_color_activate), args); g_signal_connect(G_OBJECT(widget), "key_press_event", G_CALLBACK(on_color_key_press), args); g_signal_connect(G_OBJECT(widget), "popup-menu", G_CALLBACK(on_color_popup_menu), args); g_signal_connect(G_OBJECT(widget), "focus-in-event", G_CALLBACK(color_focus_in_cb), args); //setup drag&drop gtk_drag_dest_set( widget, GtkDestDefaults(GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_HIGHLIGHT), 0, 0, GDK_ACTION_COPY); gtk_drag_source_set( widget, GDK_BUTTON1_MASK, 0, 0, GDK_ACTION_COPY); dd.handler_map = dynv_system_get_handler_map(gs->getColorList()->params); dd.userdata2 = (void*)i; dragdrop_widget_attach(widget, DragDropFlags(DRAGDROP_SOURCE | DRAGDROP_DESTINATION), &dd); } hbox2 = gtk_hbox_new(FALSE, 5); gtk_box_pack_start(GTK_BOX(vbox), hbox2, false, false, 0); args->color_wheel = gtk_color_wheel_new(); gtk_box_pack_start(GTK_BOX(hbox2), args->color_wheel, false, false, 0); g_signal_connect(G_OBJECT(args->color_wheel), "hue_changed", G_CALLBACK(hue_changed_cb), args); g_signal_connect(G_OBJECT(args->color_wheel), "saturation_value_changed", G_CALLBACK(saturation_value_changed_cb), args); g_signal_connect(G_OBJECT(args->color_wheel), "popup-menu", G_CALLBACK(color_wheel_popup_menu_cb), args); g_signal_connect(G_OBJECT(args->color_wheel), "button-press-event", G_CALLBACK(color_wheel_button_press_cb), args); args->wheel_locked = dynv_get_bool_wd(args->params, "wheel_locked", true); gtk_color_wheel_set_block_editable(GTK_COLOR_WHEEL(args->color_wheel), !args->wheel_locked); gtk_drag_dest_set(args->color_wheel, GtkDestDefaults(GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_HIGHLIGHT), 0, 0, GDK_ACTION_COPY); dd.handler_map = dynv_system_get_handler_map(gs->getColorList()->params); dd.userdata = args; dd.userdata2 = 0; dd.set_color_object_at = set_color_object_at_color_wheel; dd.test_at = test_at_color_wheel; dragdrop_widget_attach(args->color_wheel, DragDropFlags(DRAGDROP_DESTINATION), &dd); gint table_y; table = gtk_table_new(5, 2, false); gtk_box_pack_start(GTK_BOX(hbox2), table, true, true, 0); table_y = 0; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Hue:"),0,0.5,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); args->hue = gtk_hscale_new_with_range(0, 360, 1); gtk_range_set_value(GTK_RANGE(args->hue), dynv_get_float_wd(args->params, "hue", 180)); g_signal_connect (G_OBJECT (args->hue), "value-changed", G_CALLBACK (update), args); gtk_table_attach(GTK_TABLE(table), args->hue,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); table_y++; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Saturation:"),0,0.5,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); args->saturation = gtk_hscale_new_with_range(0, 120, 1); gtk_range_set_value(GTK_RANGE(args->saturation), dynv_get_float_wd(args->params, "saturation", 100)); g_signal_connect (G_OBJECT (args->saturation), "value-changed", G_CALLBACK (update), args); g_signal_connect (G_OBJECT (args->saturation), "format-value", G_CALLBACK (format_saturation_value_cb), args); gtk_table_attach(GTK_TABLE(table), args->saturation,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); table_y++; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Lightness:"),0,0.5,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); args->lightness = gtk_hscale_new_with_range(-50, 80, 1); gtk_range_set_value(GTK_RANGE(args->lightness), dynv_get_float_wd(args->params, "lightness", 0)); g_signal_connect (G_OBJECT (args->lightness), "value-changed", G_CALLBACK (update), args); g_signal_connect (G_OBJECT (args->lightness), "format-value", G_CALLBACK (format_lightness_value_cb), args); gtk_table_attach(GTK_TABLE(table), args->lightness,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); table_y++; //table_y=0; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Type:"),0,0.5,0,0),0,1,table_y,table_y+1, GTK_FILL, GTK_SHRINK, 5, 5); args->gen_type = gtk_combo_box_text_new(); for (size_t i = 0; i < generate_scheme_get_n_scheme_types(); i++){ gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(args->gen_type), _(generate_scheme_get_scheme_type(i)->name)); } gtk_combo_box_set_active(GTK_COMBO_BOX(args->gen_type), dynv_get_int32_wd(args->params, "type", 0)); g_signal_connect (G_OBJECT (args->gen_type), "changed", G_CALLBACK(update), args); gtk_table_attach(GTK_TABLE(table), args->gen_type,1,2,table_y,table_y+1, GTK_FILL, GTK_SHRINK,5,0); table_y++; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Color wheel:"),0,0.5,0,0),0,1,table_y,table_y+1, GTK_FILL, GTK_SHRINK, 5, 5); args->wheel_type = gtk_combo_box_text_new(); for (size_t i = 0; i < color_wheel_types_get_n(); i++){ gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(args->wheel_type), _(color_wheel_types_get()[i].name)); } gtk_combo_box_set_active(GTK_COMBO_BOX(args->wheel_type), dynv_get_int32_wd(args->params, "wheel_type", 0)); g_signal_connect (G_OBJECT (args->wheel_type), "changed", G_CALLBACK(update), args); gtk_table_attach(GTK_TABLE(table), args->wheel_type,1,2,table_y,table_y+1, GTK_FILL, GTK_SHRINK,5,0); table_y++; struct dynvHandlerMap* handler_map=dynv_system_get_handler_map(gs->getColorList()->params); ColorList* preview_color_list = color_list_new(handler_map); dynv_handler_map_release(handler_map); args->preview_color_list = preview_color_list; args->colors_visible = MAX_COLOR_WIDGETS; args->gs = gs; gtk_widget_show_all(hbox); update(0, args); args->main = hbox; args->source.widget = hbox; return (ColorSource*)args; } int generate_scheme_source_register(ColorSourceManager *csm) { ColorSource *color_source = new ColorSource; color_source_init(color_source, "generate_scheme", _("Scheme generation")); color_source->implement = (ColorSource* (*)(ColorSource *source, GlobalState *gs, struct dynvSystem *dynv_namespace))source_implement; color_source->default_accelerator = GDK_KEY_g; color_source_manager_add_source(csm, color_source); return 0; } const SchemeType* generate_scheme_get_scheme_type(size_t index) { if (index >= 0 && index < generate_scheme_get_n_scheme_types()) return &scheme_types[index]; else return 0; } size_t generate_scheme_get_n_scheme_types() { return sizeof(scheme_types) / sizeof(SchemeType); } gpick-gpick-0.2.6rc1/source/GenerateScheme.h000066400000000000000000000036761315430016700206610ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_GENERATE_SCHEME_H_ #define GPICK_GENERATE_SCHEME_H_ #include struct ColorSourceManager; typedef struct SchemeType{ const char *name; int colors; int turn_types; double turn[4]; }SchemeType; int generate_scheme_source_register(ColorSourceManager *csm); const SchemeType* generate_scheme_get_scheme_type(size_t index); size_t generate_scheme_get_n_scheme_types(); #endif /* GPICK_GENERATE_SCHEME_H_ */ gpick-gpick-0.2.6rc1/source/GlobalState.cpp000066400000000000000000000316661315430016700205360ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "GlobalState.h" #include "Paths.h" #include "ScreenReader.h" #include "Converter.h" #include "Random.h" #include "color_names/ColorNames.h" #include "Sampler.h" #include "ColorList.h" #include "layout/LuaBindings.h" #include "layout/Layout.h" #include "transformation/Chain.h" #include "transformation/Factory.h" #include "dynv/DynvMemoryIO.h" #include "dynv/DynvVarString.h" #include "dynv/DynvVarInt32.h" #include "dynv/DynvVarColor.h" #include "dynv/DynvVarPtr.h" #include "dynv/DynvVarFloat.h" #include "dynv/DynvVarDynv.h" #include "dynv/DynvVarBool.h" #include "dynv/DynvXml.h" #include "DynvHelpers.h" #include #include extern "C"{ #include #include } #include #include using namespace std; class GlobalState::Impl { public: ColorNames *m_color_names; Sampler *m_sampler; ScreenReader *m_screen_reader; ColorList *m_color_list; dynvSystem *m_settings; lua_State *m_lua; Random *m_random; Converters *m_converters; layout::Layouts *m_layouts; transformation::Chain *m_transformation_chain; GtkWidget *m_status_bar; ColorSource *m_color_source; Impl(): m_color_names(nullptr), m_sampler(nullptr), m_screen_reader(nullptr), m_color_list(nullptr), m_settings(nullptr), m_lua(nullptr), m_random(nullptr), m_converters(nullptr), m_layouts(nullptr), m_transformation_chain(nullptr), m_status_bar(nullptr), m_color_source(nullptr) { } ~Impl() { if (m_converters != nullptr) converters_term(m_converters); if (m_layouts != nullptr) layout::layouts_term(m_layouts); if (m_transformation_chain != nullptr) delete m_transformation_chain; if (m_color_list != nullptr) color_list_destroy(m_color_list); if (m_random != nullptr) random_destroy(m_random); if (m_color_names != nullptr) color_names_destroy(m_color_names); if (m_sampler != nullptr) sampler_destroy(m_sampler); if (m_screen_reader != nullptr) screen_reader_destroy(m_screen_reader); if (m_settings != nullptr) dynv_system_release(m_settings); if (m_lua) lua_close(m_lua); } bool writeSettings() { gchar* config_file = build_config_path("settings.xml"); ofstream settings_file(config_file); if (!settings_file.is_open()){ g_free(config_file); return false; } settings_file << "" << endl; dynv_xml_serialize(m_settings, settings_file); settings_file << "" << endl; settings_file.close(); g_free(config_file); return true; } bool loadSettings() { if (m_settings != nullptr) return false; struct dynvHandlerMap* handler_map = dynv_handler_map_create(); dynv_handler_map_add_handler(handler_map, dynv_var_string_new()); dynv_handler_map_add_handler(handler_map, dynv_var_int32_new()); dynv_handler_map_add_handler(handler_map, dynv_var_color_new()); dynv_handler_map_add_handler(handler_map, dynv_var_ptr_new()); dynv_handler_map_add_handler(handler_map, dynv_var_float_new()); dynv_handler_map_add_handler(handler_map, dynv_var_dynv_new()); dynv_handler_map_add_handler(handler_map, dynv_var_bool_new()); m_settings = dynv_system_create(handler_map); dynv_handler_map_release(handler_map); gchar* config_file = build_config_path("settings.xml"); ifstream settings_file(config_file); if (!settings_file.is_open()){ g_free(config_file); return false; } dynv_xml_deserialize(m_settings, settings_file); settings_file.close(); g_free(config_file); return true; } bool checkConfigurationDirectory() { //create configuration directory if it doesn't exist GStatBuf st; gchar* config_dir = build_config_path(nullptr); if (g_stat(config_dir, &st) != 0){ #ifndef _MSC_VER g_mkdir(config_dir, S_IRWXU); #else g_mkdir(config_dir, 0); #endif } g_free(config_dir); return true; } bool checkUserInitFile() { //check if user has user_init.lua file, if not, then create empty file gchar *user_init_file = build_config_path("user_init.lua"); ifstream f(user_init_file); if (f.is_open()){ f.close(); g_free(user_init_file); return true; } ofstream new_file(user_init_file); if (!f.is_open()){ g_free(user_init_file); return false; } new_file.close(); g_free(user_init_file); return true; } bool loadColorNames() { if (m_color_names != nullptr) return false; m_color_names = color_names_new(); dynvSystem *params = dynv_get_dynv(m_settings, "gpick"); color_names_load(m_color_names, params); dynv_system_release(params); return true; } bool initializeRandomGenerator() { m_random = random_new("SHR3"); size_t seed_value = time(0) | 1; random_seed(m_random, &seed_value); return true; } bool createColorList() { if (m_color_list != nullptr) return false; //create color list / callbacks must be defined elsewhere struct dynvHandlerMap* handler_map = dynv_system_get_handler_map(m_settings); m_color_list = color_list_new(handler_map); dynv_handler_map_release(handler_map); return true; } bool initializeLua() { lua_State *L = luaL_newstate(); luaL_openlibs(L); int status; char *tmp; lua_ext_colors_openlib(L); layout::lua_ext_layout_openlib(L); gchar* lua_root_path = build_filename("?.lua"); gchar* lua_user_path = build_config_path("?.lua"); gchar* lua_path = g_strjoin(";", lua_root_path, lua_user_path, nullptr); lua_getglobal(L, "package"); lua_pushstring(L, "path"); lua_pushstring(L, lua_path); lua_settable(L, -3); lua_pop(L, 1); g_free(lua_path); g_free(lua_root_path); g_free(lua_user_path); tmp = build_filename("init.lua"); status = luaL_loadfile(L, tmp) || lua_pcall(L, 0, 0, 0); if (status) { cerr << "init script load failed: " << lua_tostring(L, -1) << endl; } g_free(tmp); m_lua = L; return true; } bool loadConverters() { if (m_converters != nullptr) return false; Converters *converters = converters_init(m_lua, m_settings); char** source_array; uint32_t source_array_size; if ((source_array = (char**)dynv_get_string_array_wd(m_settings, "gpick.converters.names", 0, 0, &source_array_size))){ bool* copy_array; uint32_t copy_array_size=0; bool* paste_array; uint32_t paste_array_size=0; copy_array = dynv_get_bool_array_wd(m_settings, "gpick.converters.copy", 0, 0, ©_array_size); paste_array = dynv_get_bool_array_wd(m_settings, "gpick.converters.paste", 0, 0, &paste_array_size); gsize source_array_i = 0; Converter *converter; if (copy_array_size > 0 || paste_array_size > 0){ while (source_array_icopy = converter->serialize_available & copy_array[source_array_i]; if (source_array_ipaste = converter->deserialize_available & paste_array[source_array_i]; } ++source_array_i; } }else{ while (source_array_icopy = converter->serialize_available; converter->paste = converter->deserialize_available; } ++source_array_i; } } if (copy_array) delete [] copy_array; if (paste_array) delete [] paste_array; converters_reorder(converters, (const char**)source_array, source_array_size); if (source_array) delete [] source_array; }else{ //Initialize default values const char* name_array[]={ "color_web_hex", "color_css_rgb", "color_css_hsl", }; source_array_size = sizeof(name_array)/sizeof(name_array[0]); gsize source_array_i = 0; Converter* converter; while (source_array_i < source_array_size){ converter = converters_get(converters, name_array[source_array_i]); if (converter){ converter->copy = converter->serialize_available; converter->paste = converter->deserialize_available; } ++source_array_i; } converters_reorder(converters, name_array, source_array_size); } converters_rebuild_arrays(converters, ConverterArrayType::copy); converters_rebuild_arrays(converters, ConverterArrayType::paste); converters_set(converters, converters_get(converters, dynv_get_string_wd(m_settings, "gpick.converters.display", "color_web_hex")), ConverterArrayType::display); converters_set(converters, converters_get(converters, dynv_get_string_wd(m_settings, "gpick.converters.color_list", "color_web_hex")), ConverterArrayType::color_list); m_converters = converters; return true; } bool loadLayouts() { if (m_layouts != nullptr) return false; m_layouts = layout::layouts_init(m_lua, m_settings); return true; } bool loadTransformationChain() { if (m_transformation_chain != nullptr) return false; transformation::Chain *chain = new transformation::Chain(); chain->setEnabled(dynv_get_bool_wd(m_settings, "gpick.transformations.enabled", false)); struct dynvSystem** config_array; uint32_t config_size; if ((config_array = (struct dynvSystem**)dynv_get_dynv_array_wd(m_settings, "gpick.transformations.items", 0, 0, &config_size))){ for (uint32_t i = 0; i != config_size; i++){ const char *name = dynv_get_string_wd(config_array[i], "name", 0); if (name){ boost::shared_ptr tran = transformation::Factory::create(name); if (tran){ tran->deserialize(config_array[i]); chain->add(tran); } } dynv_system_release(config_array[i]); } delete [] config_array; } m_transformation_chain = chain; return true; } bool loadAll() { checkConfigurationDirectory(); checkUserInitFile(); m_screen_reader = screen_reader_new(); m_sampler = sampler_new(m_screen_reader); initializeRandomGenerator(); loadSettings(); loadColorNames(); createColorList(); initializeLua(); loadConverters(); loadLayouts(); loadTransformationChain(); return true; } }; GlobalState::GlobalState() { m_impl = make_unique(); } GlobalState::~GlobalState() { } bool GlobalState::loadSettings() { return m_impl->loadSettings(); } bool GlobalState::loadAll() { return m_impl->loadAll(); } bool GlobalState::writeSettings() { return m_impl->writeSettings(); } ColorNames *GlobalState::getColorNames() { return m_impl->m_color_names; } Sampler *GlobalState::getSampler() { return m_impl->m_sampler; } ScreenReader *GlobalState::getScreenReader() { return m_impl->m_screen_reader; } ColorList *GlobalState::getColorList() { return m_impl->m_color_list; } dynvSystem *GlobalState::getSettings() { return m_impl->m_settings; } lua_State *GlobalState::getLua() { return m_impl->m_lua; } Random *GlobalState::getRandom() { return m_impl->m_random; } Converters *GlobalState::getConverters() { return m_impl->m_converters; } layout::Layouts *GlobalState::getLayouts() { return m_impl->m_layouts; } transformation::Chain *GlobalState::getTransformationChain() { return m_impl->m_transformation_chain; } GtkWidget *GlobalState::getStatusBar() { return m_impl->m_status_bar; } void GlobalState::setStatusBar(GtkWidget *status_bar) { m_impl->m_status_bar = status_bar; } ColorSource *GlobalState::getCurrentColorSource() { return m_impl->m_color_source; } void GlobalState::setCurrentColorSource(ColorSource *color_source) { m_impl->m_color_source = color_source; } gpick-gpick-0.2.6rc1/source/GlobalState.h000066400000000000000000000050671315430016700201770ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_GLOBAL_STATE_H_ #define GPICK_GLOBAL_STATE_H_ #include struct ColorNames; struct Sampler; struct ScreenReader; class ColorList; struct dynvSystem; struct lua_State; struct Random; class Converters; struct ColorSource; typedef struct _GtkWidget GtkWidget; namespace layout { class Layouts; } namespace transformation { class Chain; } class GlobalState { public: GlobalState(); ~GlobalState(); bool loadSettings(); bool loadAll(); bool writeSettings(); ColorNames *getColorNames(); Sampler *getSampler(); ScreenReader *getScreenReader(); ColorList *getColorList(); dynvSystem *getSettings(); lua_State *getLua(); Random *getRandom(); Converters *getConverters(); layout::Layouts *getLayouts(); transformation::Chain *getTransformationChain(); GtkWidget *getStatusBar(); void setStatusBar(GtkWidget *status_bar); ColorSource *getCurrentColorSource(); void setCurrentColorSource(ColorSource *color_source); private: class Impl; std::unique_ptr m_impl; }; #endif /* GPICK_GLOBAL_STATE_H_ */ gpick-gpick-0.2.6rc1/source/HtmlUtils.cpp000066400000000000000000000077131315430016700202560ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "HtmlUtils.h" #include "Color.h" #include #include #include using namespace std; template OutputIterator copy_zero_terminated_string(InputIterator begin, OutputIterator out) { while (*begin != '\0'){ *out++ = *begin++; } return out; } template OutputIterator escape(InputIterator begin, InputIterator end, OutputIterator out) { const char escape_chars[] = {'&', '"', '\'', '<', '>'}; const char *replacements[] = {"&", """, "'", "<", ">"}; const size_t n_escape_chars = sizeof(escape_chars) / sizeof(const char); for (; begin != end; ++begin){ size_t escape_char_index = distance(escape_chars, find(escape_chars, escape_chars + n_escape_chars, *begin)); if (escape_char_index != n_escape_chars){ out = copy_zero_terminated_string(replacements[escape_char_index], out); }else{ *out++ = *begin; } } return out; } string &escapeHtmlInplace(string &str) { string result; result.reserve(str.size()); escape(str.begin(), str.end(), back_inserter(result)); str.swap(result); return str; } string escapeHtml(const string &str) { string result; result.reserve(str.size()); escape(str.begin(), str.end(), back_inserter(result)); return result; } std::ostream& operator<<(std::ostream& os, const HtmlRGB color) { using boost::math::iround; int r, g, b; r = iround(color.color->rgb.red * 255); g = iround(color.color->rgb.green * 255); b = iround(color.color->rgb.blue * 255); auto flags = os.flags(); os << "rgb(" << dec << r << ", " << g << ", " << b << ")"; os.setf(flags); return os; } std::ostream& operator<<(std::ostream& os, const HtmlHEX color) { using boost::math::iround; int r, g, b; r = iround(color.color->rgb.red * 255); g = iround(color.color->rgb.green * 255); b = iround(color.color->rgb.blue * 255); char fill = os.fill(); auto flags = os.flags(); os << "#" << hex << setfill('0') << setw(2) << r << setw(2) << g << setw(2) << b << setfill(fill); os.setf(flags); return os; } std::ostream& operator<<(std::ostream& os, const HtmlHSL color) { using boost::math::iround; int h, s, l; h = iround(color.color->hsl.hue * 360); s = iround(color.color->hsl.saturation * 100); l = iround(color.color->hsl.lightness * 100); auto flags = os.flags(); os << "hsl(" << dec << h << ", " << s << "%, " << l << "%)"; os.setf(flags); return os; } gpick-gpick-0.2.6rc1/source/HtmlUtils.h000066400000000000000000000040561315430016700177200ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_HTML_UTILS_H_ #define GPICK_HTML_UTILS_H_ #include #include std::string &escapeHtmlInplace(std::string &str); std::string escapeHtml(const std::string &str); struct Color; struct HtmlRGB { Color *color; }; struct HtmlHEX { Color *color; }; struct HtmlHSL { Color *color; }; std::ostream& operator<<(std::ostream& os, const HtmlRGB color); std::ostream& operator<<(std::ostream& os, const HtmlHEX color); std::ostream& operator<<(std::ostream& os, const HtmlHSL color); #endif /* GPICK_HTML_UTILS_H_ */ gpick-gpick-0.2.6rc1/source/ImportExport.cpp000066400000000000000000000634061315430016700210060ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ImportExport.h" #include "ColorObject.h" #include "ColorList.h" #include "FileFormat.h" #include "Converter.h" #include "Endian.h" #include "Internationalisation.h" #include "StringUtils.h" #include "HtmlUtils.h" #include "GlobalState.h" #include "DynvHelpers.h" #include "version/Version.h" #include "parser/TextFile.h" #include #include #include #include #include #include #include #include using namespace std; static bool getOrderedColors(ColorList *color_list, vector &ordered) { color_list_get_positions(color_list); size_t max_index = 0; bool index_set = false; for (auto color: color_list->colors){ if (color->isPositionSet()){ if (!index_set){ max_index = color->getPosition(); index_set = true; }else if (color->getPosition() > max_index){ max_index = color->getPosition(); } } } if (!index_set){ return false; }else{ ordered.resize(max_index + 1); for (auto color: color_list->colors){ if (color->isPositionSet()){ ordered[color->getPosition()] = color; } } return true; } } ImportExport::ImportExport(ColorList *color_list, const char* filename, GlobalState *gs): m_color_list(color_list), m_converter(nullptr), m_converters(nullptr), m_filename(filename), m_item_size(ItemSize::medium), m_background(Background::none), m_gs(gs), m_include_color_names(true), m_last_error(Error::none) { } void ImportExport::setConverter(Converter *converter) { m_converter = converter; } void ImportExport::setConverters(Converters *converters) { m_converters = converters; } void ImportExport::setItemSize(ItemSize item_size) { m_item_size = item_size; } void ImportExport::setItemSize(const char *item_size) { string v(item_size); if (v == "small") m_item_size = ItemSize::small; else if (v == "medium") m_item_size = ItemSize::medium; else if (v == "big") m_item_size = ItemSize::big; else if (v == "controllable") m_item_size = ItemSize::controllable; else m_item_size = ItemSize::medium; } void ImportExport::setBackground(Background background) { m_background = background; } void ImportExport::setBackground(const char *background) { string v(background); if (v == "none") m_background = Background::none; else if (v == "white") m_background = Background::white; else if (v == "gray") m_background = Background::gray; else if (v == "black") m_background = Background::black; else if (v == "first_color") m_background = Background::first_color; else if (v == "last_color") m_background = Background::last_color; else if (v == "controllable") m_background = Background::controllable; else m_background = Background::none; } void ImportExport::setIncludeColorNames(bool include_color_names) { m_include_color_names = include_color_names; } static void gplColor(ColorObject* color_object, ostream &stream) { using boost::math::iround; Color color = color_object->getColor(); stream << iround(color.rgb.red * 255) << "\t" << iround(color.rgb.green * 255) << "\t" << iround(color.rgb.blue * 255) << "\t" << color_object->getName() << endl; } bool ImportExport::exportGPL() { ofstream f(m_filename, ios::out | ios::trunc); if (!f.is_open()){ m_last_error = Error::could_not_open_file; return false; } boost::filesystem::path path(m_filename); f << "GIMP Palette" << endl; f << "Name: " << path.filename().string() << endl; f << "Columns: 1" << endl; f << "#" << endl; vector ordered; getOrderedColors(m_color_list, ordered); for (auto color: ordered){ gplColor(color, f); if (!f.good()){ f.close(); m_last_error = Error::file_write_error; return false; } } f.close(); return true; } bool ImportExport::importGPL() { ifstream f(m_filename, ios::in); if (!f.is_open()){ m_last_error = Error::could_not_open_file; return false; } string line; getline(f, line); if (f.good() && line != "GIMP Palette"){ f.close(); m_last_error = Error::file_read_error; return false; } do{ getline(f, line); }while (f.good() && ((line.size() < 1) || (((line[0] > '9') || (line[0] < '0')) && line[0] != ' '))); int r, g, b; Color c; ColorObject* color_object; string strip_chars = " \t"; for(;;){ if (!f.good()) break; stripLeadingTrailingChars(line, strip_chars); if (line.length() > 0 && line[0] == '#'){ // skip comment lines getline(f, line); continue; } stringstream ss(line); ss >> r >> g >> b; getline(ss, line); if (!f.good()) line = ""; c.rgb.red = r / 255.0; c.rgb.green = g / 255.0; c.rgb.blue = b / 255.0; color_object = color_list_new_color_object(m_color_list, &c); stripLeadingTrailingChars(line, strip_chars); color_object->setName(line); color_list_add_color_object(m_color_list, color_object, true); color_object->release(); getline(f, line); } if (!f.eof()) { f.close(); m_last_error = Error::file_read_error; return false; } f.close(); return true; } bool ImportExport::importGPA() { return palette_file_load(m_filename, m_color_list) == 0; } bool ImportExport::exportGPA() { return palette_file_save(m_filename, m_color_list) == 0; } bool ImportExport::exportTXT() { ofstream f(m_filename, ios::out | ios::trunc); if (!f.is_open()){ m_last_error = Error::could_not_open_file; return false; } vector ordered; getOrderedColors(m_color_list, ordered); ConverterSerializePosition position; position.index = 0; position.count = ordered.size(); position.first = true; position.last = position.count <= 1; for (auto color: ordered){ string line; converters_color_serialize(m_converter, color, position, line); f << line << endl; position.index++; if (position.index + 1 == position.count){ position.last = true; } if (position.first) position.first = false; if (!f.good()){ f.close(); m_last_error = Error::file_write_error; return false; } } f.close(); return true; } bool ImportExport::importTXT() { ifstream f(m_filename, ios::in); if (!f.is_open()){ m_last_error = Error::could_not_open_file; return false; } size_t table_size; Converter *converter = nullptr; Converter **converter_table = converters_get_all_type(m_converters, ConverterArrayType::paste, &table_size); ColorObject* color_object; Color dummy_color; typedef multimap> ValidConverters; ValidConverters valid_converters; string line; string strip_chars = " \t"; bool imported = false; for(;;){ getline(f, line); stripLeadingTrailingChars(line, strip_chars); if (!line.empty()){ for (size_t i = 0; i != table_size; ++i){ converter = converter_table[i]; if (!converter->deserialize_available) continue; color_object = color_list_new_color_object(m_color_list, &dummy_color); float quality; if (converters_color_deserialize(m_converters, converter->function_name, line.c_str(), color_object, &quality) == 0){ if (quality > 0){ valid_converters.insert(make_pair(quality, color_object)); }else{ color_object->release(); } }else{ color_object->release(); } } bool first = true; for (auto result: valid_converters){ if (first){ first = false; color_list_add_color_object(m_color_list, result.second, true); imported = true; } result.second->release(); } valid_converters.clear(); } if (!f.good()) { if (f.eof()) break; f.close(); m_last_error = Error::file_read_error; return false; } } f.close(); if (!imported){ m_last_error = Error::no_colors_imported; } return imported; } static void cssColor(ColorObject* color_object, ostream &stream) { Color color, hsl; color = color_object->getColor(); color_rgb_to_hsl(&color, &hsl); stream << " * " << color_object->getName() << ": " << HtmlHEX{&color} << ", " << HtmlRGB{&color} << ", " << HtmlHSL{&color} << endl; } bool ImportExport::exportCSS() { ofstream f(m_filename, ios::out | ios::trunc); if (!f.is_open()){ m_last_error = Error::could_not_open_file; return false; } f << "/**" << endl << " * Generated by Gpick " << gpick_build_version << endl; vector ordered; getOrderedColors(m_color_list, ordered); for (auto color: ordered){ cssColor(color, f); if (!f.good()){ f.close(); m_last_error = Error::file_write_error; return false; } } f << " */" << endl; if (!f.good()){ f.close(); m_last_error = Error::file_write_error; return false; } f.close(); return true; } static void htmlColor(ColorObject* color_object, bool include_color_name, ostream &stream) { Color color, text_color; color = color_object->getColor(); color_get_contrasting(&color, &text_color); stream << "
"; if (include_color_name){ string name = color_object->getName(); escapeHtmlInplace(name); if (!name.empty()) stream << name << ":
"; } stream << "" << HtmlHEX{&color} << "" << "
"; } static string getHtmlColor(ColorObject* color_object) { Color color = color_object->getColor(); stringstream ss; ss << HtmlRGB{&color}; return ss.str(); } bool ImportExport::exportHTML() { ofstream f(m_filename, ios::out | ios::trunc); if (!f.is_open()){ m_last_error = Error::could_not_open_file; return false; } boost::filesystem::path path(m_filename); vector ordered; getOrderedColors(m_color_list, ordered); int item_size = 64; switch (m_item_size){ case ItemSize::small: item_size = 32; break; case ItemSize::medium: item_size = 64; break; case ItemSize::big: item_size = 96; break; case ItemSize::controllable: break; } string background = ""; switch (m_background){ case Background::none: break; case Background::white: background = "background-color:white;"; break; case Background::gray: background = "background-color:gray;"; break; case Background::black: background = "background-color:black;"; break; case Background::first_color: if (!ordered.empty()) background = "background-color:" + getHtmlColor(ordered.front()) + ";"; break; case Background::last_color: if (!ordered.empty()) background = "background-color:" + getHtmlColor(ordered.back()) + ";"; break; case Background::controllable: break; } f << "" << path.filename().string() << "" << endl << "" << endl << "" << "" << endl << "" << endl; if (m_item_size == ItemSize::controllable || m_background == Background::controllable){ f << "
" << endl; if (m_item_size == ItemSize::controllable){ f << "
" << _("Item size") << ":" << "
" << endl; } if (m_background == Background::controllable){ f << "
" << _("Background color") << ":" << "
" << endl; } f << "
" << endl; } f << "
" << endl; string hex_case = dynv_get_string_wd(m_gs->getSettings(), "gpick.options.hex_case", "upper"); if (hex_case == "upper"){ f << uppercase; }else{ f << nouppercase; } for (auto color: ordered){ htmlColor(color, m_include_color_names, f); if (!f.good()){ f.close(); m_last_error = Error::file_write_error; return false; } } f << "
" << endl; f << ""; f << "" << endl; if (!f.good()){ f.close(); m_last_error = Error::file_write_error; return false; } f.close(); return true; } bool ImportExport::exportType(FileType type) { switch (type){ case FileType::gpa: return exportGPA(); case FileType::gpl: return exportGPL(); case FileType::ase: return exportASE(); case FileType::txt: return exportTXT(); case FileType::mtl: return exportMTL(); case FileType::css: return exportCSS(); case FileType::html: return exportHTML(); case FileType::rgbtxt: case FileType::unknown: return false; } return false; } static void mtlColor(ColorObject* color_object, ostream &stream) { Color color = color_object->getColor(); stream << "newmtl " << color_object->getName() << endl; stream << "Ns 90.000000" << endl; stream << "Ka 0.000000 0.000000 0.000000" << endl; stream << "Kd " << color.rgb.red << " " << color.rgb.green << " " << color.rgb.blue << endl; stream << "Ks 0.500000 0.500000 0.500000" << endl << endl; } bool ImportExport::exportMTL() { ofstream f(m_filename, ios::out | ios::trunc); if (!f.is_open()){ m_last_error = Error::could_not_open_file; return false; } vector ordered; getOrderedColors(m_color_list, ordered); for (auto color: ordered){ mtlColor(color, f); if (!f.good()){ f.close(); m_last_error = Error::file_write_error; return false; } } f.close(); return true; } typedef union FloatInt { float f; uint32_t i; }FloatInt; static void aseColor(ColorObject* color_object, ostream &stream) { Color color = color_object->getColor(); string name = color_object->getName(); glong name_u16_len = 0; gunichar2 *name_u16 = g_utf8_to_utf16(name.c_str(), -1, 0, &name_u16_len, 0); for (glong i = 0; i < name_u16_len; ++i){ name_u16[i] = UINT16_TO_BE(name_u16[i]); } uint16_t color_entry = UINT16_TO_BE(0x0001); stream.write((char*)&color_entry, 2); int32_t block_size = 2 + (name_u16_len + 1) * 2 + 4 + (3 * 4) + 2; //name length + name (zero terminated and 2 bytes per char wide) + color name + 3 float values + color type block_size = UINT32_TO_BE(block_size); stream.write((char*)&block_size, 4); uint16_t name_length = UINT16_TO_BE(uint16_t(name_u16_len + 1)); stream.write((char*)&name_length, 2); stream.write((char*)name_u16, (name_u16_len + 1) * 2); stream << "RGB "; FloatInt r, g, b; r.f = color.rgb.red; g.f = color.rgb.green; b.f = color.rgb.blue; r.i = UINT32_TO_BE(r.i); g.i = UINT32_TO_BE(g.i); b.i = UINT32_TO_BE(b.i); stream.write((char*)&r, 4); stream.write((char*)&g, 4); stream.write((char*)&b, 4); int16_t color_type = UINT16_TO_BE(0); stream.write((char*)&color_type, 2); g_free(name_u16); } bool ImportExport::exportASE() { ofstream f(m_filename, ios::out | ios::trunc | ios::binary); if (!f.is_open()){ m_last_error = Error::could_not_open_file; return false; } f << "ASEF"; //magic header uint32_t version = UINT32_TO_BE(0x00010000); f.write((char*)&version, 4); vector ordered; getOrderedColors(m_color_list, ordered); uint32_t blocks = ordered.size(); blocks = UINT32_TO_BE(blocks); f.write((char*)&blocks, 4); for (auto color: ordered){ aseColor(color, f); if (!f.good()){ f.close(); m_last_error = Error::file_write_error; return false; } } f.close(); return true; } bool ImportExport::importASE() { ifstream f(m_filename, ios::binary); if (!f.is_open()){ m_last_error = Error::could_not_open_file; return false; } char magic[4]; f.read(magic, 4); if (memcmp(magic, "ASEF", 4) != 0){ f.close(); m_last_error = Error::file_read_error; return false; } uint32_t version; f.read((char*)&version, 4); version = UINT32_FROM_BE(version); uint32_t blocks; f.read((char*)&blocks, 4); blocks = UINT32_FROM_BE(blocks); uint16_t block_type; uint32_t block_size; int color_supported; for (uint32_t i = 0; i < blocks; ++i){ f.read((char*)&block_type, 2); block_type = UINT16_FROM_BE(block_type); f.read((char*)&block_size, 4); block_size = UINT32_FROM_BE(block_size); switch (block_type){ case 0x0001: //color block { uint16_t name_length; f.read((char*)&name_length, 2); name_length = UINT16_FROM_BE(name_length); gunichar2 *name_u16 = (gunichar2*)g_malloc(name_length*2); f.read((char*)name_u16, name_length*2); for (uint32_t j = 0; j < name_length; ++j){ name_u16[j] = UINT16_FROM_BE(name_u16[j]); } gchar *name = g_utf16_to_utf8(name_u16, name_length, 0, 0, 0); g_free(name_u16); Color c; char color_space[4]; f.read(color_space, 4); color_supported = 0; if (memcmp(color_space, "RGB ", 4) == 0){ FloatInt rgb[3]; f.read((char*)&rgb[0], 4); f.read((char*)&rgb[1], 4); f.read((char*)&rgb[2], 4); rgb[0].i = UINT32_FROM_BE(rgb[0].i); rgb[1].i = UINT32_FROM_BE(rgb[1].i); rgb[2].i = UINT32_FROM_BE(rgb[2].i); c.rgb.red = rgb[0].f; c.rgb.green = rgb[1].f; c.rgb.blue = rgb[2].f; color_supported = 1; }else if (memcmp(color_space, "CMYK", 4) == 0){ Color c2; FloatInt cmyk[4]; f.read((char*)&cmyk[0], 4); f.read((char*)&cmyk[1], 4); f.read((char*)&cmyk[2], 4); f.read((char*)&cmyk[3], 4); cmyk[0].i = UINT32_FROM_BE(cmyk[0].i); cmyk[1].i = UINT32_FROM_BE(cmyk[1].i); cmyk[2].i = UINT32_FROM_BE(cmyk[2].i); cmyk[3].i = UINT32_FROM_BE(cmyk[3].i); c2.cmyk.c = cmyk[0].f; c2.cmyk.m = cmyk[1].f; c2.cmyk.y = cmyk[2].f; c2.cmyk.k = cmyk[3].f; color_cmyk_to_rgb(&c2, &c); color_supported = 1; }else if (memcmp(color_space, "Gray", 4) == 0){ FloatInt gray; f.read((char*)&gray, 4); gray.i = UINT32_FROM_BE(gray.i); c.rgb.red = c.rgb.green = c.rgb.blue = gray.f; color_supported = 1; }else if (memcmp(color_space, "LAB ", 4) == 0){ Color c2; FloatInt lab[3]; f.read((char*)&lab[0], 4); f.read((char*)&lab[1], 4); f.read((char*)&lab[2], 4); lab[0].i = UINT32_FROM_BE(lab[0].i); lab[1].i = UINT32_FROM_BE(lab[1].i); lab[2].i = UINT32_FROM_BE(lab[2].i); c2.lab.L = lab[0].f*100; c2.lab.a = lab[1].f; c2.lab.b = lab[2].f; color_lab_to_rgb_d50(&c2, &c); c.rgb.red = clamp_float(c.rgb.red, 0, 1); c.rgb.green = clamp_float(c.rgb.green, 0, 1); c.rgb.blue = clamp_float(c.rgb.blue, 0, 1); color_supported = 1; } if (color_supported){ ColorObject* color_object; color_object = color_list_new_color_object(m_color_list, &c); color_object->setName(name); color_list_add_color_object(m_color_list, color_object, true); color_object->release(); } uint16_t color_type; f.read((char*)&color_type, 2); g_free(name); } break; default: f.seekg(block_size, ios::cur); } } f.close(); return true; } static string::size_type rfind_first_of_not(string const& str, string::size_type const pos, string const& chars) { auto start = str.rend() - pos - 1; auto found = std::find_first_of(start, str.rend(), chars.begin(), chars.end()); return found == str.rend() ? string::npos : pos - (found - start); } static int hexToInt(char hex) { if (hex >= '0' && hex <= '9') return hex - '0'; if (hex >= 'a' && hex <= 'f') return hex - 'a' + 10; if (hex >= 'A' && hex <= 'F') return hex - 'A' + 10; return 0; } static int hexPairToInt(const char *hex_pair) { return hexToInt(hex_pair[0]) << 4 | hexToInt(hex_pair[1]); } bool ImportExport::importRGBTXT() { ifstream f(m_filename, ios::in); if (!f.is_open()){ m_last_error = Error::could_not_open_file; return false; } string line; Color c; ColorObject* color_object; string strip_chars = " \t"; for(;;){ getline(f, line); if (!f.good()) break; stripLeadingTrailingChars(line, strip_chars); if (line.length() > 0 && line[0] == '#'){ // skip comment lines continue; } size_t hash_position = line.find('#'); if (hash_position != string::npos){ size_t last_non_space = rfind_first_of_not(line, hash_position, " \t"); c.rgb.red = hexPairToInt(&line.at(hash_position + 1)) / 255.0; c.rgb.green = hexPairToInt(&line.at(hash_position + 3)) / 255.0; c.rgb.blue = hexPairToInt(&line.at(hash_position + 5)) / 255.0; color_object = color_list_new_color_object(m_color_list, &c); if (last_non_space != string::npos){ color_object->setName(line.substr(0, last_non_space)); } color_list_add_color_object(m_color_list, color_object, true); color_object->release(); } } if (!f.eof()) { f.close(); m_last_error = Error::file_read_error; return false; } f.close(); return true; } FileType ImportExport::getFileType(const char *filename) { const struct{ FileType type; const char *extension; bool full_name; }extensions[] = { {FileType::gpa, ".gpa", false}, {FileType::gpl, ".gpl", false}, {FileType::ase, ".ase", false}, {FileType::txt, ".txt", false}, {FileType::mtl, ".mtl", false}, {FileType::css, ".css", false}, {FileType::html, ".html", false}, {FileType::html, ".htm", false}, {FileType::rgbtxt, "rgb.txt", true}, {FileType::unknown, nullptr, false}, }; boost::filesystem::path path(filename); string name = path.filename().string(); boost::algorithm::to_lower(name); for (size_t i = 0; extensions[i].type != FileType::unknown; ++i){ if (extensions[i].full_name && name == extensions[i].extension){ return extensions[i].type; } } string extension = path.extension().string(); if (extension.length() == 0) return FileType::unknown; boost::algorithm::to_lower(extension); for (size_t i = 0; extensions[i].type != FileType::unknown; ++i){ if (!extensions[i].full_name && extension == extensions[i].extension){ return extensions[i].type; } } return FileType::unknown; } bool ImportExport::importType(FileType type) { switch (type){ case FileType::gpa: return importGPA(); case FileType::gpl: return importGPL(); case FileType::ase: return importASE(); case FileType::txt: return importTXT(); case FileType::rgbtxt: return importRGBTXT(); case FileType::mtl: case FileType::css: case FileType::html: case FileType::unknown: return false; } return false; } ImportExport::Error ImportExport::getLastError() const { return m_last_error; } class ImportTextFile: public text_file_parser::TextFile { public: ifstream m_file; list m_colors; bool m_failed; ImportTextFile(const string &filename) { m_failed = false; m_file.open(filename, ios::in); } bool isOpen() { return m_file.is_open(); } virtual ~ImportTextFile() { m_file.close(); } virtual void outOfMemory() { m_failed = true; } virtual void syntaxError(size_t start_line, size_t start_column, size_t end_line, size_t end_colunn) { m_failed = true; } virtual size_t read(char *buffer, size_t length) { m_file.read(buffer, length); size_t bytes = m_file.gcount(); if (bytes > 0) return bytes; if (m_file.eof()) return 0; if (!m_file.good()){ m_failed = true; } return 0; } virtual void addColor(const Color &color) { m_colors.push_back(color); } }; bool ImportExport::importTextFile(const text_file_parser::Configuration &configuration) { ImportTextFile import_text_file(m_filename); if (!import_text_file.isOpen()){ m_last_error = Error::could_not_open_file; return false; } if (!import_text_file.parse(configuration)){ m_last_error = Error::parsing_failed; return false; } if (import_text_file.m_failed){ m_last_error = Error::parsing_failed; return false; } if (import_text_file.m_colors.size() == 0){ m_last_error = Error::no_colors_imported; return false; } for (auto color: import_text_file.m_colors){ auto color_object = new ColorObject("" ,color); color_list_add_color_object(m_color_list, color_object, true); color_object->release(); } return true; } gpick-gpick-0.2.6rc1/source/ImportExport.h000066400000000000000000000064201315430016700204440ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_IMPORT_EXPORT_H_ #define GPICK_IMPORT_EXPORT_H_ class ColorList; class Converter; class Converters; class GlobalState; namespace text_file_parser { class Configuration; } enum class FileType { gpa, gpl, ase, txt, mtl, css, html, rgbtxt, unknown, }; class ImportExport { public: enum class Error { none, could_not_open_file, file_read_error, file_write_error, no_colors_imported, parsing_failed, }; enum class ItemSize { small, medium, big, controllable, }; enum class Background { none, white, gray, black, first_color, last_color, controllable, }; ImportExport(ColorList *color_list, const char* filename, GlobalState *gs); void setConverter(Converter *converter); void setConverters(Converters *converters); void setItemSize(ItemSize item_size); void setItemSize(const char *item_size); void setBackground(Background background); void setBackground(const char *background); void setIncludeColorNames(bool include_color_names); bool exportGPL(); bool importGPL(); bool exportASE(); bool importASE(); bool exportCSS(); bool importTXT(); bool exportTXT(); bool importGPA(); bool exportGPA(); bool exportMTL(); bool exportHTML(); bool importTextFile(const text_file_parser::Configuration &configuration); bool importRGBTXT(); bool importType(FileType type); bool exportType(FileType type); Error getLastError() const; static FileType getFileType(const char *filename); private: ColorList *m_color_list; Converter *m_converter; Converters *m_converters; const char* m_filename; ItemSize m_item_size; Background m_background; GlobalState *m_gs; bool m_include_color_names; Error m_last_error; }; #endif /* GPICK_IMPORT_EXPORT_H_ */ gpick-gpick-0.2.6rc1/source/Internationalisation.h000066400000000000000000000035031315430016700221650ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef INTERNATIONALISATIOM_H_ #define INTERNATIONALISATIOM_H_ #ifdef ENABLE_NLS #include #define _(STRING) gettext(STRING) #define N_(STRING) STRING #else #define _(STRING) STRING #define N_(STRING) STRING #endif void initialize_internationalisation(); #endif /* INTERNATIONALISATIOM_H_ */ gpick-gpick-0.2.6rc1/source/LayoutPreview.cpp000066400000000000000000000630601315430016700211450ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "LayoutPreview.h" #include "ColorSourceManager.h" #include "ColorSource.h" #include "DragDrop.h" #include "uiColorInput.h" #include "CopyPaste.h" #include "Clipboard.h" #include "StandardMenu.h" #include "Converter.h" #include "DynvHelpers.h" #include "Internationalisation.h" #include "color_names/ColorNames.h" #include "GlobalState.h" #include "ToolColorNaming.h" #include "uiUtilities.h" #include "ColorList.h" #include "MathUtil.h" #include #include "gtk/LayoutPreview.h" #include "layout/Layout.h" #include "layout/Style.h" #include #include #include #include #include using namespace std; using namespace layout; typedef struct LayoutPreviewArgs{ ColorSource source; GtkWidget *main; GtkWidget* statusbar; GtkWidget *layout; System* layout_system; Layouts* layouts; string last_filename; struct dynvSystem *params; GlobalState *gs; }LayoutPreviewArgs; class LayoutPreviewColorNameAssigner: public ToolColorNameAssigner { protected: stringstream m_stream; const char *m_ident; public: LayoutPreviewColorNameAssigner(GlobalState *gs):ToolColorNameAssigner(gs){ } void assign(ColorObject *color_object, const Color *color, const char *ident){ m_ident = ident; ToolColorNameAssigner::assign(color_object, color); } virtual std::string getToolSpecificName(ColorObject *color_object, const Color *color){ m_stream.str(""); m_stream << _("layout preview") << " " << m_ident << " [" << color_names_get(m_gs->getColorNames(), color, false) << "]"; return m_stream.str(); } }; typedef enum{ LAYOUTLIST_HUMAN_NAME = 0, LAYOUTLIST_PTR, LAYOUTLIST_N_COLUMNS }LayoutListColumns; typedef enum{ STYLELIST_HUMAN_NAME = 0, STYLELIST_CSS_SELECTOR, STYLELIST_PTR, STYLELIST_N_COLUMNS }StyleListColumns; static void style_cell_edited_cb(GtkCellRendererText *cell, gchar *path, gchar *new_text, GtkListStore *store) { GtkTreeIter iter1; gtk_tree_model_get_iter_from_string(GTK_TREE_MODEL(store), &iter1, path ); gtk_list_store_set(store, &iter1, STYLELIST_CSS_SELECTOR, new_text, -1); } static void load_colors(LayoutPreviewArgs* args) { if (args->layout_system){ struct dynvSystem *assignments_params = dynv_get_dynv(args->params, "css_selectors.assignments"); string ident_selector; for (list::iterator i=args->layout_system->styles.begin(); i != args->layout_system->styles.end(); i++){ ident_selector = (*i)->ident_name + ".color"; const Color *color = dynv_get_color_wd(assignments_params, ident_selector.c_str(), 0); if (color){ color_copy((Color*)color, &(*i)->color); } } dynv_system_release(assignments_params); } } static void save_colors(LayoutPreviewArgs* args) { if (args->layout_system){ struct dynvSystem *assignments_params = dynv_get_dynv(args->params, "css_selectors.assignments"); string ident_selector; for (list::iterator i=args->layout_system->styles.begin(); i != args->layout_system->styles.end(); i++){ ident_selector = (*i)->ident_name + ".color"; dynv_set_color(assignments_params, ident_selector.c_str(), &(*i)->color); } dynv_system_release(assignments_params); } } static GtkWidget* style_list_new(LayoutPreviewArgs *args) { GtkListStore *store; GtkCellRenderer *renderer; GtkTreeViewColumn *col; GtkWidget *view; view = gtk_tree_view_new(); gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), 1); store = gtk_list_store_new(STYLELIST_N_COLUMNS, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_POINTER); col = gtk_tree_view_column_new(); gtk_tree_view_column_set_sizing(col,GTK_TREE_VIEW_COLUMN_AUTOSIZE); gtk_tree_view_column_set_resizable(col, true); gtk_tree_view_column_set_title(col, _("Style item")); renderer = gtk_cell_renderer_text_new(); gtk_tree_view_column_pack_start(col, renderer, true); gtk_tree_view_column_add_attribute(col, renderer, "text", STYLELIST_HUMAN_NAME); gtk_tree_view_append_column(GTK_TREE_VIEW(view), col); col = gtk_tree_view_column_new(); gtk_tree_view_column_set_sizing(col,GTK_TREE_VIEW_COLUMN_AUTOSIZE); gtk_tree_view_column_set_resizable(col, true); gtk_tree_view_column_set_title(col, _("CSS selector")); renderer = gtk_cell_renderer_text_new(); gtk_tree_view_column_pack_start(col, renderer, true); gtk_tree_view_column_add_attribute(col, renderer, "text", STYLELIST_CSS_SELECTOR); gtk_tree_view_append_column(GTK_TREE_VIEW(view), col); g_object_set(renderer, "editable", true, nullptr); g_signal_connect(renderer, "edited", (GCallback)style_cell_edited_cb, store); gtk_tree_view_set_model(GTK_TREE_VIEW(view), GTK_TREE_MODEL(store)); g_object_unref(GTK_TREE_MODEL(store)); return view; } static void assign_css_selectors_cb(GtkWidget *widget, LayoutPreviewArgs* args) { GtkWidget *table; GtkWidget *dialog = gtk_dialog_new_with_buttons(_("Assign CSS selectors"), GTK_WINDOW(gtk_widget_get_toplevel(args->main)), GtkDialogFlags(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OK, GTK_RESPONSE_OK, nullptr); gtk_window_set_default_size(GTK_WINDOW(dialog), dynv_get_int32_wd(args->params, "css_selectors.window.width", -1), dynv_get_int32_wd(args->params, "css_selectors.window.height", -1)); gtk_dialog_set_alternative_button_order(GTK_DIALOG(dialog), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1); gint table_y; table = gtk_table_new(1, 1, FALSE); table_y=0; GtkWidget* list_widget = style_list_new(args); gtk_widget_set_size_request(list_widget, 100, 100); gtk_table_attach(GTK_TABLE(table), list_widget, 0, 1, table_y, table_y+1, GtkAttachOptions(GTK_FILL|GTK_EXPAND), GtkAttachOptions(GTK_FILL|GTK_EXPAND), 5, 0); table_y++; GtkTreeIter iter1; GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(list_widget)); struct dynvSystem *assignments_params = dynv_get_dynv(args->params, "css_selectors.assignments"); string ident_selector; for (list::iterator i = args->layout_system->styles.begin(); i != args->layout_system->styles.end(); i++){ ident_selector = (*i)->ident_name + ".selector"; const char *css_selector = dynv_get_string_wd(assignments_params, ident_selector.c_str(), (*i)->ident_name.c_str()); gtk_list_store_append(GTK_LIST_STORE(model), &iter1); gtk_list_store_set(GTK_LIST_STORE(model), &iter1, STYLELIST_HUMAN_NAME, (*i)->human_name.c_str(), STYLELIST_CSS_SELECTOR, css_selector, STYLELIST_PTR, (*i), -1); } gtk_widget_show_all(table); gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), table); if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK){ gboolean valid; Style *style; char* selector; valid = gtk_tree_model_get_iter_first(model, &iter1); while (valid){ gtk_tree_model_get(model, &iter1, STYLELIST_PTR, &style, STYLELIST_CSS_SELECTOR, &selector, -1); ident_selector = style->ident_name + ".selector"; dynv_set_string(assignments_params, ident_selector.c_str(), selector); g_free(selector); valid = gtk_tree_model_iter_next(model, &iter1); } } dynv_system_release(assignments_params); gint width, height; gtk_window_get_size(GTK_WINDOW(dialog), &width, &height); dynv_set_int32(args->params, "css_selectors.window.width", width); dynv_set_int32(args->params, "css_selectors.window.height", height); gtk_widget_destroy(dialog); } static int source_destroy(LayoutPreviewArgs *args) { save_colors(args); if (args->layout_system) System::unref(args->layout_system); args->layout_system = 0; gtk_widget_destroy(args->main); dynv_system_release(args->params); delete args; return 0; } static int source_get_color(LayoutPreviewArgs *args, ColorObject** color) { Style *style = 0; if (gtk_layout_preview_get_current_style(GTK_LAYOUT_PREVIEW(args->layout), &style) == 0){ ColorObject *color_object = color_list_new_color_object(args->gs->getColorList(), &style->color); LayoutPreviewColorNameAssigner name_assigner(args->gs); name_assigner.assign(color_object, &style->color, style->ident_name.c_str()); *color = color_object; return 0; } return -1; } static int source_set_color(LayoutPreviewArgs *args, ColorObject* color_object) { Color color = color_object->getColor(); gtk_layout_preview_set_current_color(GTK_LAYOUT_PREVIEW(args->layout), &color); return -1; } static int source_deactivate(LayoutPreviewArgs *args) { return 0; } static ColorObject* get_color_object(DragDrop* dd) { LayoutPreviewArgs *args = (LayoutPreviewArgs*)dd->userdata; ColorObject *color_object; if (source_get_color(args, &color_object) == 0){ return color_object; } return 0; } static int set_color_object_at(struct DragDrop* dd, ColorObject* color_object, int x, int y, bool move) { LayoutPreviewArgs* args=(LayoutPreviewArgs*)dd->userdata; Color color = color_object->getColor(); gtk_layout_preview_set_color_at(GTK_LAYOUT_PREVIEW(args->layout), &color, x, y); return 0; } static bool test_at(struct DragDrop* dd, int x, int y) { LayoutPreviewArgs* args=(LayoutPreviewArgs*)dd->userdata; gtk_layout_preview_set_focus_at(GTK_LAYOUT_PREVIEW(args->layout), x, y); return gtk_layout_preview_is_selected(GTK_LAYOUT_PREVIEW(args->layout)); } static GtkWidget* layout_preview_dropdown_new(LayoutPreviewArgs *args, GtkTreeModel *model) { GtkListStore *store = 0; GtkCellRenderer *renderer; GtkWidget *combo; if (model){ combo = gtk_combo_box_new_with_model(model); }else{ store = gtk_list_store_new (LAYOUTLIST_N_COLUMNS, G_TYPE_STRING, G_TYPE_POINTER); combo = gtk_combo_box_new_with_model(GTK_TREE_MODEL(store)); } renderer = gtk_cell_renderer_text_new(); gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combo), renderer, true); gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (combo), renderer, "text", LAYOUTLIST_HUMAN_NAME, nullptr); if (store) g_object_unref (store); return combo; } static void edit_cb(GtkWidget *widget, gpointer item) { LayoutPreviewArgs* args=(LayoutPreviewArgs*)item; ColorObject *color_object; ColorObject* new_color_object = 0; if (source_get_color(args, &color_object) == 0){ if (dialog_color_input_show(GTK_WINDOW(gtk_widget_get_toplevel(args->main)), args->gs, color_object, &new_color_object ) == 0){ source_set_color(args, new_color_object); new_color_object->release(); } color_object->release(); } } static void paste_cb(GtkWidget *widget, LayoutPreviewArgs* args) { ColorObject* color_object; if (copypaste_get_color_object(&color_object, args->gs) == 0){ source_set_color(args, color_object); color_object->release(); } } static void add_color_to_palette(Style *style, LayoutPreviewColorNameAssigner &name_assigner, LayoutPreviewArgs *args) { ColorObject *color_object; color_object = color_list_new_color_object(args->gs->getColorList(), &style->color); name_assigner.assign(color_object, &style->color, style->ident_name.c_str()); color_list_add_color_object(args->gs->getColorList(), color_object, 1); color_object->release(); } static void add_to_palette_cb(GtkWidget *widget, gpointer item) { LayoutPreviewArgs* args = (LayoutPreviewArgs*)item; LayoutPreviewColorNameAssigner name_assigner(args->gs); Style* style = 0; if (gtk_layout_preview_get_current_style(GTK_LAYOUT_PREVIEW(args->layout), &style) == 0){ add_color_to_palette(style, name_assigner, args); } } static void add_all_to_palette_cb(GtkWidget *widget, LayoutPreviewArgs *args) { LayoutPreviewColorNameAssigner name_assigner(args->gs); for (list::iterator i = args->layout_system->styles.begin(); i != args->layout_system->styles.end(); i++){ add_color_to_palette(*i, name_assigner, args); } } static gboolean button_press_cb (GtkWidget *widget, GdkEventButton *event, LayoutPreviewArgs* args) { GtkWidget *menu; if (event->button == 1 && event->type == GDK_2BUTTON_PRESS){ add_to_palette_cb(widget, args); return true; }else if (event->button == 3 && event->type == GDK_BUTTON_PRESS){ GtkWidget* item ; gint32 button, event_time; menu = gtk_menu_new (); bool selection_avail = gtk_layout_preview_is_selected(GTK_LAYOUT_PREVIEW(args->layout)); item = gtk_menu_item_new_with_image(_("_Add to palette"), gtk_image_new_from_stock(GTK_STOCK_ADD, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK (add_to_palette_cb), args); if (!selection_avail) gtk_widget_set_sensitive(item, false); item = gtk_menu_item_new_with_image(_("A_dd all to palette"), gtk_image_new_from_stock(GTK_STOCK_ADD, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK (add_all_to_palette_cb), args); gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); if (selection_avail){ ColorObject *color_object; source_get_color(args, &color_object); StandardMenu::appendMenu(menu, color_object, args->gs); color_object->release(); }else{ StandardMenu::appendMenu(menu); } gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); item = gtk_menu_item_new_with_image (_("_Edit..."), gtk_image_new_from_stock(GTK_STOCK_EDIT, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK (edit_cb), args); if (!selection_avail) gtk_widget_set_sensitive(item, false); item = gtk_menu_item_new_with_image (_("_Paste"), gtk_image_new_from_stock(GTK_STOCK_PASTE, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK (paste_cb), args); if (!selection_avail) gtk_widget_set_sensitive(item, false); if (copypaste_is_color_object_available(args->gs) != 0){ gtk_widget_set_sensitive(item, false); } gtk_widget_show_all (GTK_WIDGET(menu)); button = event->button; event_time = event->time; gtk_menu_popup(GTK_MENU(menu), nullptr, nullptr, nullptr, nullptr, button, event_time); g_object_ref_sink(menu); g_object_unref(menu); return TRUE; } return FALSE; } static void layout_changed_cb(GtkWidget *widget, LayoutPreviewArgs* args) { GtkTreeIter iter; if (gtk_combo_box_get_active_iter(GTK_COMBO_BOX(widget), &iter)){ GtkTreeModel* model = gtk_combo_box_get_model(GTK_COMBO_BOX(widget)); Layout* layout; gtk_tree_model_get(model, &iter, LAYOUTLIST_PTR, &layout, -1); save_colors(args); System* layout_system = layouts_get(args->layouts, layout->name); gtk_layout_preview_set_system(GTK_LAYOUT_PREVIEW(args->layout), layout_system); if (args->layout_system) System::unref(args->layout_system); args->layout_system = layout_system; dynv_set_string(args->params, "layout_name", layout->name); load_colors(args); } } static int save_css_file(const char* filename, LayoutPreviewArgs* args) { ofstream file(filename, ios::out); if (file.is_open()){ auto converters = args->gs->getConverters(); Converter *converter = converters_get_first(converters, ConverterArrayType::copy); ColorObject *co_color, *co_background_color; Color t; co_color = color_list_new_color_object(args->gs->getColorList(), &t); co_background_color = color_list_new_color_object(args->gs->getColorList(), &t); struct dynvSystem *assignments_params = dynv_get_dynv(args->params, "css_selectors.assignments"); string ident_selector; for (list::iterator i=args->layout_system->styles.begin(); i != args->layout_system->styles.end(); i++){ ident_selector = (*i)->ident_name + ".selector"; const char *css_selector = dynv_get_string_wd(assignments_params, ident_selector.c_str(), (*i)->ident_name.c_str()); if (css_selector[0] != 0){ co_color->setColor((*i)->color); string text; converter_get_text(co_color, converter, args->gs, text); file << css_selector << " {" << endl; if ((*i)->style_type == Style::TYPE_BACKGROUND){ file << "\tbackground-color: " << text << ";" << endl; }else if ((*i)->style_type == Style::TYPE_COLOR){ file << "\tcolor: " << text << ";" << endl; }else if ((*i)->style_type == Style::TYPE_BORDER){ file << "\tborder-color: " << text << ";" << endl; } file << "}" << endl << endl; } } dynv_system_release(assignments_params); co_color->release(); co_background_color->release(); file.close(); return 0; } return -1; } static void export_css_cb(GtkWidget *widget, LayoutPreviewArgs* args){ if (!args->last_filename.empty()){ if (save_css_file(args->last_filename.c_str(), args) == 0){ }else{ GtkWidget* message; message=gtk_message_dialog_new(GTK_WINDOW(gtk_widget_get_toplevel(widget)), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, _("File could not be saved")); gtk_dialog_run(GTK_DIALOG(message)); gtk_widget_destroy(message); } return; } GtkWidget *dialog; GtkFileFilter *filter; dialog = gtk_file_chooser_dialog_new(_("Export"), GTK_WINDOW(gtk_widget_get_toplevel(widget)), GTK_FILE_CHOOSER_ACTION_SAVE, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_SAVE, GTK_RESPONSE_OK, nullptr); gtk_dialog_set_alternative_button_order(GTK_DIALOG(dialog), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1); gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog), TRUE); const char* default_path = dynv_get_string_wd(args->params, "export_path", ""); gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), default_path); filter = gtk_file_filter_new(); gtk_file_filter_set_name(filter, _("Cascading Style Sheets *.css")); gtk_file_filter_add_pattern(filter, "*.css"); gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); gtk_file_chooser_set_filter(GTK_FILE_CHOOSER(dialog), filter); gboolean finished = false; while (!finished){ if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK){ gchar *filename; filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); gchar *path; path = gtk_file_chooser_get_current_folder(GTK_FILE_CHOOSER(dialog)); dynv_set_string(args->params, "export_path", path); g_free(path); if (save_css_file(filename, args) == 0){ args->last_filename = filename; finished = true; }else{ GtkWidget* message; message=gtk_message_dialog_new(GTK_WINDOW(dialog), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, _("File could not be saved")); //gtk_window_set_title(GTK_WINDOW(dialog), "Open"); gtk_dialog_run(GTK_DIALOG(message)); gtk_widget_destroy(message); } g_free(filename); }else break; } gtk_widget_destroy (dialog); } static void export_css_as_cb(GtkWidget *widget, LayoutPreviewArgs* args){ args->last_filename=""; export_css_cb(widget, args); } static GtkWidget* attach_label(GtkWidget *widget, const char *label){ GtkWidget* hbox = gtk_hbox_new(false, 5); gtk_box_pack_start(GTK_BOX(hbox), gtk_label_aligned_new(label, 0, 0.5, 0, 0), false, true, 0); gtk_box_pack_start(GTK_BOX(hbox), widget, true, true, 0); return hbox; } static int source_activate(LayoutPreviewArgs *args) { auto chain = args->gs->getTransformationChain(); gtk_layout_preview_set_transformation_chain(GTK_LAYOUT_PREVIEW(args->layout), chain); gtk_statusbar_push(GTK_STATUSBAR(args->statusbar), gtk_statusbar_get_context_id(GTK_STATUSBAR(args->statusbar), "empty"), ""); return 0; } static ColorSource* source_implement(ColorSource *source, GlobalState* gs, struct dynvSystem *dynv_namespace) { LayoutPreviewArgs* args = new LayoutPreviewArgs; args->params = dynv_system_ref(dynv_namespace); args->statusbar = gs->getStatusBar(); args->layout_system = 0; color_source_init(&args->source, source->identificator, source->hr_name); args->source.destroy = (int (*)(ColorSource *source))source_destroy; args->source.get_color = (int (*)(ColorSource *source, ColorObject** color))source_get_color; args->source.set_color = (int (*)(ColorSource *source, ColorObject* color))source_set_color; args->source.deactivate = (int (*)(ColorSource *source))source_deactivate; args->source.activate = (int (*)(ColorSource *source))source_activate; auto layouts = gs->getLayouts(); args->layouts = layouts; GtkWidget *table, *vbox, *hbox; vbox = gtk_vbox_new(false, 10); hbox = gtk_hbox_new(false, 10); gtk_box_pack_start(GTK_BOX(vbox), hbox, true, true, 5); gint table_y; table = gtk_table_new(4, 4, false); gtk_box_pack_start(GTK_BOX(hbox), table, true, true, 5); table_y = 0; GtkToolItem *tool; GtkWidget *toolbar = gtk_toolbar_new(); gtk_table_attach(GTK_TABLE(table), toolbar, 0, 3, table_y, table_y+1, GtkAttachOptions(GTK_FILL), GTK_FILL, 0, 0); table_y++; tool = gtk_tool_item_new(); gtk_tool_item_set_expand(tool, true); GtkWidget *layout_dropdown = layout_preview_dropdown_new(args, 0); gtk_container_add(GTK_CONTAINER(tool), attach_label(layout_dropdown, _("Layout:"))); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), tool, -1); g_signal_connect (G_OBJECT(layout_dropdown), "changed", G_CALLBACK(layout_changed_cb), args); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), gtk_separator_tool_item_new(), -1); tool = gtk_menu_tool_button_new(gtk_image_new_from_stock(GTK_STOCK_SAVE, GTK_ICON_SIZE_BUTTON), _("Export CSS File")); gtk_tool_item_set_tooltip_text(tool, _("Export CSS file")); g_signal_connect(G_OBJECT(tool), "clicked", G_CALLBACK(export_css_cb), args); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), tool, -1); GtkWidget *menu; GtkWidget* item; menu = gtk_menu_new (); item = gtk_menu_item_new_with_image(_("_Export CSS File As..."), gtk_image_new_from_stock(GTK_STOCK_SAVE_AS, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK (export_css_as_cb), args); item = gtk_menu_item_new_with_mnemonic(_("_Assign CSS Selectors...")); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK (assign_css_selectors_cb), args); gtk_widget_show_all(menu); gtk_menu_tool_button_set_menu(GTK_MENU_TOOL_BUTTON(tool), menu); GtkWidget *scrolled = gtk_scrolled_window_new(0, 0); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_table_attach(GTK_TABLE(table), scrolled, 0, 3, table_y, table_y+1 ,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GtkAttachOptions(GTK_FILL | GTK_EXPAND),0,0); gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(scrolled), args->layout = gtk_layout_preview_new()); g_signal_connect_after(G_OBJECT(args->layout), "button-press-event", G_CALLBACK(button_press_cb), args); table_y++; struct DragDrop dd; dragdrop_init(&dd, gs); dd.userdata = args; dd.get_color_object = get_color_object; dd.set_color_object_at = set_color_object_at; dd.test_at = test_at; dd.handler_map = dynv_system_get_handler_map(gs->getColorList()->params); gtk_drag_dest_set(args->layout, GtkDestDefaults(GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_HIGHLIGHT), 0, 0, GDK_ACTION_COPY); gtk_drag_source_set(args->layout, GDK_BUTTON1_MASK, 0, 0, GDK_ACTION_COPY); dragdrop_widget_attach(args->layout, DragDropFlags(DRAGDROP_SOURCE | DRAGDROP_DESTINATION), &dd); args->gs = gs; // Restore settings and fill list const char* layout_name = dynv_get_string_wd(args->params, "layout_name", "std_layout_menu_1"); GtkTreeModel *model = gtk_combo_box_get_model(GTK_COMBO_BOX(layout_dropdown)); size_t n_layouts; Layout** layout_table = layouts_get_all(layouts, &n_layouts); GtkTreeIter iter1; bool layout_found = false; for (size_t i = 0; i != n_layouts; ++i){ if (layout_table[i]->mask != 0) continue; gtk_list_store_append(GTK_LIST_STORE(model), &iter1); gtk_list_store_set(GTK_LIST_STORE(model), &iter1, LAYOUTLIST_HUMAN_NAME, layout_table[i]->human_readable, LAYOUTLIST_PTR, layout_table[i], -1); if (g_strcmp0(layout_name, layout_table[i]->name) == 0){ gtk_combo_box_set_active_iter(GTK_COMBO_BOX(layout_dropdown), &iter1); layout_found = true; } } if (!layout_found){ gtk_combo_box_set_active(GTK_COMBO_BOX(layout_dropdown), 0); } gtk_widget_show_all(vbox); //update(0, args); args->main = vbox; args->source.widget =vbox; return (ColorSource*)args; } int layout_preview_source_register(ColorSourceManager *csm) { ColorSource *color_source = new ColorSource; color_source_init(color_source, "layout_preview", _("Layout preview")); color_source->needs_viewport = false; color_source->implement = (ColorSource* (*)(ColorSource *source, GlobalState *gs, struct dynvSystem *dynv_namespace))source_implement; color_source->default_accelerator = GDK_KEY_l; color_source_manager_add_source(csm, color_source); return 0; } gpick-gpick-0.2.6rc1/source/LayoutPreview.h000066400000000000000000000033171315430016700206110ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_LAYOUT_PREVIEW_H_ #define GPICK_LAYOUT_PREVIEW_H_ struct ColorSourceManager; int layout_preview_source_register(ColorSourceManager *csm); #endif /* GPICK_LAYOUT_PREVIEW_H_ */ gpick-gpick-0.2.6rc1/source/LuaExt.cpp000066400000000000000000000312771315430016700175350ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "LuaExt.h" #include "Color.h" #include "ColorObject.h" #include "DynvHelpers.h" #include #include "Internationalisation.h" #include "version/Version.h" extern "C"{ #include #include #include } #include using namespace std; static int lua_newcolor (lua_State *L) { Color *c = (Color*)lua_newuserdata(L, sizeof(Color)); luaL_getmetatable(L, "color"); lua_setmetatable(L, -2); if (lua_type(L, 2) == LUA_TNUMBER && lua_type(L, 3) == LUA_TNUMBER && lua_type(L, 4) == LUA_TNUMBER ){ c->rgb.red = luaL_checknumber(L, 2); c->rgb.green = luaL_checknumber(L, 3); c->rgb.blue = luaL_checknumber(L, 4); }else{ color_zero(c); } return 1; } Color *lua_checkcolor (lua_State *L, int index) { void *ud = luaL_checkudata(L, index, "color"); luaL_argcheck(L, ud != nullptr, index, "`color' expected"); return (Color *)ud; } int lua_pushcolor (lua_State *L, const Color* color) { Color *c = (Color*)lua_newuserdata(L, sizeof(Color)); luaL_getmetatable(L, "color"); lua_setmetatable(L, -2); color_copy(color, c); return 1; } static int lua_color2string (lua_State *L) { Color *c = lua_checkcolor(L, 1); lua_pushfstring(L, "color(%f, %f, %f)", c->rgb.red, c->rgb.green, c->rgb.blue); return 1; } static int lua_color_rgb (lua_State *L) { Color *c = lua_checkcolor(L, 1); if (lua_type(L, 2) == LUA_TNUMBER && lua_type(L, 3) == LUA_TNUMBER && lua_type(L, 4) == LUA_TNUMBER ){ c->rgb.red = luaL_checknumber(L, 2); c->rgb.green = luaL_checknumber(L, 3); c->rgb.blue = luaL_checknumber(L, 4); } lua_pushnumber(L, c->rgb.red); lua_pushnumber(L, c->rgb.green); lua_pushnumber(L, c->rgb.blue); return 3; } static int lua_color_red (lua_State *L) { Color *c = lua_checkcolor(L, 1); if (lua_type(L, 2) == LUA_TNUMBER){ c->rgb.red=luaL_checknumber(L, 2); } lua_pushnumber(L, c->rgb.red); return 1; } static int lua_color_green (lua_State *L) { Color *c = lua_checkcolor(L, 1); if (lua_type(L, 2) == LUA_TNUMBER){ c->rgb.green=luaL_checknumber(L, 2); } lua_pushnumber(L, c->rgb.green); return 1; } static int lua_color_blue (lua_State *L) { Color *c = lua_checkcolor(L, 1); if (lua_type(L, 2) == LUA_TNUMBER){ c->rgb.blue=luaL_checknumber(L, 2); } lua_pushnumber(L, c->rgb.blue); return 1; } static int lua_color_hsl (lua_State *L) { Color *c = lua_checkcolor(L, 1); if (lua_type(L, 2) == LUA_TNUMBER && lua_type(L, 3) == LUA_TNUMBER && lua_type(L, 4) == LUA_TNUMBER ){ c->hsl.hue = luaL_checknumber(L, 2); c->hsl.saturation = luaL_checknumber(L, 3); c->hsl.lightness = luaL_checknumber(L, 4); } lua_pushnumber(L, c->hsl.hue); lua_pushnumber(L, c->hsl.saturation); lua_pushnumber(L, c->hsl.lightness); return 3; } static int lua_color_hue (lua_State *L) { Color *c = lua_checkcolor(L, 1); if (lua_type(L, 2) == LUA_TNUMBER){ c->hsl.hue=luaL_checknumber(L, 2); } lua_pushnumber(L, c->hsl.hue); return 1; } static int lua_color_saturation (lua_State *L) { Color *c = lua_checkcolor(L, 1); if (lua_type(L, 2) == LUA_TNUMBER){ c->hsl.saturation=luaL_checknumber(L, 2); } lua_pushnumber(L, c->hsl.saturation); return 1; } static int lua_color_lightness (lua_State *L) { Color *c = lua_checkcolor(L, 1); if (lua_type(L, 2) == LUA_TNUMBER){ c->hsl.lightness=luaL_checknumber(L, 2); } lua_pushnumber(L, c->hsl.lightness); return 1; } static int lua_color_cmyk (lua_State *L) { Color *c = lua_checkcolor(L, 1); if (lua_type(L, 2) == LUA_TNUMBER && lua_type(L, 3) == LUA_TNUMBER && lua_type(L, 4) == LUA_TNUMBER && lua_type(L, 5) == LUA_TNUMBER ){ c->cmyk.c = luaL_checknumber(L, 2); c->cmyk.m = luaL_checknumber(L, 3); c->cmyk.y = luaL_checknumber(L, 4); c->cmyk.k = luaL_checknumber(L, 5); } lua_pushnumber(L, c->cmyk.c); lua_pushnumber(L, c->cmyk.m); lua_pushnumber(L, c->cmyk.y); lua_pushnumber(L, c->cmyk.k); return 4; } static int lua_color_cyan (lua_State *L) { Color *c = lua_checkcolor(L, 1); if (lua_type(L, 2) == LUA_TNUMBER){ c->cmyk.c = luaL_checknumber(L, 2); } lua_pushnumber(L, c->cmyk.c); return 1; } static int lua_color_magenta (lua_State *L) { Color *c = lua_checkcolor(L, 1); if (lua_type(L, 2) == LUA_TNUMBER){ c->cmyk.m = luaL_checknumber(L, 2); } lua_pushnumber(L, c->cmyk.m); return 1; } static int lua_color_yellow (lua_State *L) { Color *c = lua_checkcolor(L, 1); if (lua_type(L, 2) == LUA_TNUMBER){ c->cmyk.y = luaL_checknumber(L, 2); } lua_pushnumber(L, c->cmyk.y); return 1; } static int lua_color_key_black (lua_State *L) { Color *c = lua_checkcolor(L, 1); if (lua_type(L, 2) == LUA_TNUMBER){ c->cmyk.k = luaL_checknumber(L, 2); } lua_pushnumber(L, c->cmyk.k); return 1; } static int lua_color_lab_lightness (lua_State *L) { Color *c = lua_checkcolor(L, 1); if (lua_type(L, 2) == LUA_TNUMBER){ c->lab.L = luaL_checknumber(L, 2); } lua_pushnumber(L, c->lab.L); return 1; } static int lua_color_lab_a (lua_State *L) { Color *c = lua_checkcolor(L, 1); if (lua_type(L, 2) == LUA_TNUMBER){ c->lab.a = luaL_checknumber(L, 2); } lua_pushnumber(L, c->lab.a); return 1; } static int lua_color_lab_b (lua_State *L) { Color *c = lua_checkcolor(L, 1); if (lua_type(L, 2) == LUA_TNUMBER){ c->lab.b = luaL_checknumber(L, 2); } lua_pushnumber(L, c->lab.b); return 1; } static int lua_color_rgb_to_hsl (lua_State *L) { Color *c = lua_checkcolor(L, 1); Color c2; color_rgb_to_hsl(c, &c2); lua_pushcolor(L, &c2); return 1; } static int lua_color_hsl_to_rgb (lua_State *L) { Color *c = lua_checkcolor(L, 1); Color c2; color_hsl_to_rgb(c, &c2); lua_pushcolor(L, &c2); return 1; } static int lua_color_rgb_to_cmyk (lua_State *L) { Color *c = lua_checkcolor(L, 1); Color c2, c3; color_rgb_to_cmy(c, &c3); color_cmy_to_cmyk(&c3, &c2); lua_pushcolor(L, &c2); return 1; } static int lua_color_lch_lightness(lua_State *L) { Color *c = lua_checkcolor(L, 1); if (lua_type(L, 2) == LUA_TNUMBER){ c->lch.L = luaL_checknumber(L, 2); } lua_pushnumber(L, c->lch.L); return 1; } static int lua_color_lch_chroma(lua_State *L) { Color *c = lua_checkcolor(L, 1); if (lua_type(L, 2) == LUA_TNUMBER){ c->lch.C = luaL_checknumber(L, 2); } lua_pushnumber(L, c->lch.C); return 1; } static int lua_color_lch_hue(lua_State *L) { Color *c = lua_checkcolor(L, 1); if (lua_type(L, 2) == LUA_TNUMBER){ c->lch.h = luaL_checknumber(L, 2); } lua_pushnumber(L, c->lch.h); return 1; } static const struct luaL_Reg lua_colorlib_f [] = { {"new", lua_newcolor}, {nullptr, nullptr} }; static const struct luaL_Reg lua_colorlib_m [] = { {"__tostring", lua_color2string}, {"red", lua_color_red}, {"green", lua_color_green}, {"blue", lua_color_blue}, {"rgb", lua_color_rgb}, {"hue",lua_color_hue}, {"saturation",lua_color_saturation}, {"lightness",lua_color_lightness}, {"value",lua_color_lightness}, {"hsl",lua_color_hsl}, {"cyan",lua_color_cyan}, {"magenta",lua_color_magenta}, {"yellow",lua_color_yellow}, {"key_black",lua_color_key_black}, {"cmyk",lua_color_cmyk}, {"lab_lightness",lua_color_lab_lightness}, {"lab_a",lua_color_lab_a}, {"lab_b",lua_color_lab_b}, {"lch_lightness",lua_color_lch_lightness}, {"lch_chroma",lua_color_lch_chroma}, {"lch_hue",lua_color_lch_hue}, {"rgb_to_hsl",lua_color_rgb_to_hsl}, {"hsl_to_rgb",lua_color_hsl_to_rgb}, {"rgb_to_cmyk",lua_color_rgb_to_cmyk}, {nullptr, nullptr} }; static int luaopen_color(lua_State *L) { luaL_newmetatable(L, "color"); lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); luaL_setfuncs(L, lua_colorlib_m, 0); lua_pop(L, 1); luaL_newlibtable(L, lua_colorlib_f); luaL_setfuncs(L, lua_colorlib_f, 0); lua_setglobal(L, "color"); return 1; } static int lua_newcolorobject (lua_State *L) { ColorObject** c = (ColorObject**)lua_newuserdata(L, sizeof(ColorObject*)); luaL_getmetatable(L, "colorobject"); lua_setmetatable(L, -2); *c=nullptr; return 1; } ColorObject** lua_checkcolorobject (lua_State *L, int index) { void *ud = luaL_checkudata(L, index, "colorobject"); luaL_argcheck(L, ud != nullptr, index, "`colorobject' expected"); return (ColorObject **)ud; } int lua_pushcolorobject (lua_State *L, ColorObject* color_object) { ColorObject** c = (ColorObject**)lua_newuserdata(L, sizeof(ColorObject*)); luaL_getmetatable(L, "colorobject"); lua_setmetatable(L, -2); *c=color_object; return 1; } int lua_colorobject_get_color(lua_State *L) { ColorObject** color_object = lua_checkcolorobject(L, 1); Color tmp = (*color_object)->getColor(); lua_pushcolor(L, &tmp); return 1; } int lua_colorobject_set_color(lua_State *L) { ColorObject** color_object=lua_checkcolorobject(L, 1); Color *color = lua_checkcolor(L, 2); (*color_object)->setColor(*color); return 0; } int lua_colorobject_get_name(lua_State *L) { ColorObject** color_object = lua_checkcolorobject(L, 1); lua_pushstring(L, (*color_object)->getName().c_str()); return 1; } static const struct luaL_Reg lua_colorobjectlib_f[] = { {"new", lua_newcolorobject}, {nullptr, nullptr} }; static const struct luaL_Reg lua_colorobjectlib_m[] = { {"get_color", lua_colorobject_get_color}, {"set_color", lua_colorobject_set_color}, {"get_name", lua_colorobject_get_name}, {nullptr, nullptr} }; int luaopen_colorobject (lua_State *L) { luaL_newmetatable(L, "colorobject"); lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); luaL_setfuncs(L, lua_colorobjectlib_m, 0); lua_pop(L, 1); luaL_newlibtable(L, lua_colorobjectlib_f); luaL_setfuncs(L, lua_colorobjectlib_f, 0); lua_setglobal(L, "colorobject"); return 1; } int lua_i18n_gettext(lua_State *L) { const char *text = luaL_checkstring(L, 1); lua_pushstring(L, _(text)); return 1; } int luaopen_i18n(lua_State *L) { lua_pushcclosure(L, lua_i18n_gettext, 0); lua_setglobal(L, "_"); return 1; } struct dynvSystem* lua_checkdynvsystem(lua_State *L, int index) { void *ud = luaL_checkudata(L, index, "dynvsystem"); luaL_argcheck(L, ud != nullptr, index, "`dynvsystem' expected"); return dynv_system_ref(*(struct dynvSystem**)ud); } int lua_pushdynvsystem(lua_State *L, struct dynvSystem* params) { struct dynvSystem** c = (struct dynvSystem**)lua_newuserdata(L, sizeof(struct dynvSystem*)); luaL_getmetatable(L, "dynvsystem"); lua_setmetatable(L, -2); *c = dynv_system_ref(params); return 1; } int lua_dynvsystem_get_string(lua_State *L) { struct dynvSystem* params = lua_checkdynvsystem(L, 1); const char *name = luaL_checkstring(L, 2); const char *default_value = luaL_checkstring(L, 3); lua_pushstring(L, dynv_get_string_wd(params, name, default_value)); dynv_system_release(params); return 1; } static const struct luaL_Reg lua_dynvsystemlib_f [] = { {nullptr, nullptr} }; static const struct luaL_Reg lua_dynvsystemlib_m [] = { {"get_string", lua_dynvsystem_get_string}, {nullptr, nullptr} }; int luaopen_dynvsystem(lua_State *L) { luaL_newmetatable(L, "dynvsystem"); lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); luaL_setfuncs(L, lua_dynvsystemlib_m, 0); lua_pop(L, 1); luaL_newlibtable(L, lua_dynvsystemlib_f); luaL_setfuncs(L, lua_dynvsystemlib_f, 0); lua_setglobal(L, "dynvsystem"); return 1; } int luaopen_gpick(lua_State *L) { lua_newtable(L); lua_pushstring(L, gpick_build_version); lua_setfield(L, -2, "version"); lua_setglobal(L, "gpick"); return 1; } int lua_ext_colors_openlib(lua_State *L){ luaopen_color(L); luaopen_colorobject(L); luaopen_dynvsystem(L); luaopen_i18n(L); luaopen_gpick(L); return 0; } gpick-gpick-0.2.6rc1/source/LuaExt.h000066400000000000000000000040721315430016700171730ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_LUA_EXT_H_ #define GPICK_LUA_EXT_H_ class ColorObject; struct dynvSystem; struct lua_State; typedef struct Color Color; int lua_ext_colors_openlib(lua_State *lua); int lua_pushcolorobject(lua_State *L, ColorObject* color_object); ColorObject** lua_checkcolorobject(lua_State *L, int index); int lua_pushdynvsystem(lua_State *L, dynvSystem* params); dynvSystem* lua_checkdynvsystem(lua_State *L, int index); int lua_pushcolor(lua_State *L, const Color* color); Color* lua_checkcolor(lua_State *L, int index); #endif /* GPICK_LUA_EXT_H_ */ gpick-gpick-0.2.6rc1/source/MathUtil.cpp000066400000000000000000000151421315430016700200530ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "MathUtil.h" #include #include float max_float_3(float a, float b, float c) { if (a > b){ if (a > c){ return a; }else{ return c; } }else{ if (b > c){ return b; }else{ return c; } } } float min_float_3(float a, float b, float c) { if (a < b){ if (a < c){ return a; }else{ return c; } }else{ if (b < c){ return b; }else{ return c; } } } float clamp_float(float x, float a, float b) { if (x < a) return a; if (x > b) return b; return x; } int clamp_int(int x, int a, int b) { if (x < a) return a; if (x > b) return b; return x; } int min_int(int a, int b) { if (a > b) return b; return a; } int max_int(int a, int b) { if (a < b) return b; return a; } int abs_int(int a) { if (a < 0) return -a; return a; } float abs_float(float a) { if (a < 0) return -a; return a; } void matrix3x3_identity(matrix3x3* matrix) { int i,j; for (i=0;i<3;++i){ for (j=0;j<3;++j){ matrix->m[i][j]=((i == j)?1:0); } } } void matrix3x3_copy(const matrix3x3* matrix, matrix3x3* result) { memcpy(result, matrix, sizeof(matrix3x3)); } void matrix3x3_multiply(const matrix3x3* matrix1, const matrix3x3* matrix2, matrix3x3* result){ int i,j,k; matrix3x3 matrix_t; if (matrix1 == result){ matrix3x3_copy(matrix1, &matrix_t); matrix1=&matrix_t; }else if (matrix2 == result){ matrix3x3_copy(matrix2, &matrix_t); matrix2=&matrix_t; } for (i=0;i<3;++i){ for (j=0;j<3;++j){ result->m[i][j]=0; for (k=0;k<3;++k){ result->m[i][j] += matrix1->m[k][j]*matrix2->m[i][k]; } } } } double matrix3x3_determinant(const matrix3x3* matrix) { double det=0; double t; int i,j; for (i=0;i<3;++i){ t=1; for (j=0;j<3;++j){ t*=matrix->m[(i+j)%3][j]; } det+=t; } for (i=0;i<3;++i){ t=1; for (j=0;j<3;++j){ t*=matrix->m[(i+2-j)%3][j]; } det-=t; } return det; } void matrix3x3_transpose(const matrix3x3* matrix, matrix3x3* result) { int i,j; matrix3x3 matrix_t; if (matrix == result){ matrix3x3_copy(matrix, &matrix_t); matrix=&matrix_t; } for (i=0;i<3;++i){ for (j=0;j<3;++j){ result->m[j][i]=matrix->m[i][j]; } } } int matrix3x3_inverse(const matrix3x3* matrix, matrix3x3* result){ double det = matrix3x3_determinant(matrix); if (det == 0) return -1; double invdet=1/det; matrix3x3 matrix_t; if (matrix == result){ matrix3x3_copy(matrix, &matrix_t); matrix=&matrix_t; } result->m[0][0] = (matrix->m[1][1] * matrix->m[2][2] - matrix->m[2][1] * matrix->m[1][2]) * invdet; result->m[0][1] = -(matrix->m[0][1] * matrix->m[2][2] - matrix->m[2][1] * matrix->m[0][2]) * invdet; result->m[0][2] = (matrix->m[0][1] * matrix->m[1][2] - matrix->m[1][1] * matrix->m[0][2]) * invdet; result->m[1][0] = -(matrix->m[1][0] * matrix->m[2][2] - matrix->m[2][0] * matrix->m[1][2]) * invdet; result->m[1][1] = (matrix->m[0][0] * matrix->m[2][2] - matrix->m[2][0] * matrix->m[0][2]) * invdet; result->m[1][2] = -(matrix->m[0][0] * matrix->m[1][2] - matrix->m[1][0] * matrix->m[0][2]) * invdet; result->m[2][0] = (matrix->m[1][0] * matrix->m[2][1] - matrix->m[2][0] * matrix->m[1][1]) * invdet; result->m[2][1] = -(matrix->m[0][0] * matrix->m[2][1] - matrix->m[2][0] * matrix->m[0][1]) * invdet; result->m[2][2] = (matrix->m[0][0] * matrix->m[1][1] - matrix->m[1][0] * matrix->m[0][1]) * invdet; return 0; } void vector2_set(vector2* v1, float x, float y) { v1->x = x; v1->y = y; } float vector2_length(const vector2* v1) { return sqrt(v1->x * v1->x + v1->y * v1->y); } void vector2_normalize(const vector2* v1, vector2* r) { float l = vector2_length(v1); r->x = v1->x / l; r->y = v1->y / l; } float vector2_dot(const vector2* v1, const vector2* v2) { return v1->x * v2->x + v1->y * v2->y; } float mix_float(float a, float b, float mix) { return a * (1 - mix) + b * mix; } double mix_double(double a, double b, double mix){ return a * (1 - mix) + b * mix; } float wrap_float(float x) { return x - floor(x); } int wrap_int(int x, int a, int b) { if (x < a){ return b - (a - x) % (b - a); }else if (x >= b){ return a + (x - b) % (b - a); } return x; } void vector3_multiply_matrix3x3(const vector3* vector, const matrix3x3* matrix, vector3* result) { vector3 vector_t; if (vector == result){ vector3_copy(vector, &vector_t); vector=&vector_t; } result->x = vector->x * matrix->m[0][0] + vector->y * matrix->m[0][1] + vector->z * matrix->m[0][2]; result->y = vector->x * matrix->m[1][0] + vector->y * matrix->m[1][1] + vector->z * matrix->m[1][2]; result->z = vector->x * matrix->m[2][0] + vector->y * matrix->m[2][1] + vector->z * matrix->m[2][2]; } void vector3_set(vector3* vector, float x, float y, float z) { vector->x = x; vector->y = y; vector->z = z; } void vector3_copy(const vector3* vector, vector3* result){ memcpy(result, vector, sizeof(vector3)); } float vector3_length(const vector3* vector) { return sqrt(vector->x * vector->x + vector->y * vector->y + vector->z * vector->z); } void vector3_clamp(vector3* vector, float a, float b){ vector->x = clamp_float(vector->x, a, b); vector->y = clamp_float(vector->y, a, b); vector->z = clamp_float(vector->z, a, b); } gpick-gpick-0.2.6rc1/source/MathUtil.h000066400000000000000000000061731315430016700175240ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_MATH_UTIL_H_ #define GPICK_MATH_UTIL_H_ #define PI 3.14159265 float min_float_3(float a, float b, float c); float max_float_3(float a, float b, float c); int min_int(int a, int b); int max_int(int a, int b); int wrap_int(int x, int a, int b); float clamp_float(float x, float a, float b); float wrap_float(float x); float mix_float(float a, float b, float mix); int clamp_int(int x, int a, int b); int abs_int(int a); float abs_float(float a); double mix_double(double a, double b, double mix); typedef struct matrix3x3{ double m[3][3]; }matrix3x3; void matrix3x3_identity(matrix3x3* matrix); void matrix3x3_multiply(const matrix3x3* matrix1, const matrix3x3* matrix2, matrix3x3* result); double matrix3x3_determinant(const matrix3x3* matrix); int matrix3x3_inverse(const matrix3x3* matrix, matrix3x3* result); void matrix3x3_transpose(const matrix3x3* matrix, matrix3x3* result); typedef struct vector2{ float x; float y; }vector2; void vector2_set(vector2* v1, float x, float y); float vector2_length(const vector2* v1); void vector2_normalize(const vector2* v1, vector2* r); float vector2_dot(const vector2* v1, const vector2* v2); typedef struct vector3{ union{ struct{ float x; float y; float z; }; float m[3]; }; }vector3; void vector3_set(vector3* vector, float x, float y, float z); void vector3_copy(const vector3* vector, vector3* result); float vector3_length(const vector3* vector); void vector3_multiply_matrix3x3(const vector3* vector, const matrix3x3* matrix, vector3* result ); void vector3_clamp(vector3* vector, float a, float b); #endif /* GPICK_MATH_UTIL_H_ */ gpick-gpick-0.2.6rc1/source/NearestColorsMenu.cpp000066400000000000000000000045001315430016700217300ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "NearestColorsMenu.h" #include "GlobalState.h" #include "CopyMenuItem.h" #include "Color.h" #include "ColorList.h" #include "ColorObject.h" #include using namespace std; GtkWidget* NearestColorsMenu::newMenu(ColorObject *color_object, GlobalState *gs) { GtkWidget *menu = gtk_menu_new(); multimap color_distances; Color source_color = color_object->getColor(); for (auto color_object: gs->getColorList()->colors){ Color target_color = color_object->getColor(); color_distances.insert(pair(color_distance_lch(&source_color, &target_color), color_object)); } int count = 0; for (auto item: color_distances){ gtk_menu_shell_append(GTK_MENU_SHELL(menu), CopyMenuItem::newItem(item.second, gs, true)); if (++count >= 3) break; } return menu; } gpick-gpick-0.2.6rc1/source/NearestColorsMenu.h000066400000000000000000000034601315430016700214010ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_NEAREST_COLORS_MENU_H_ #define GPICK_NEAREST_COLORS_MENU_H_ #include class ColorObject; class GlobalState; class NearestColorsMenu { public: static GtkWidget* newMenu(ColorObject* color_object, GlobalState *gs); }; #endif /* GPICK_NEAREST_COLORS_MENU_H_ */ gpick-gpick-0.2.6rc1/source/Noise.cpp000066400000000000000000000112271315430016700174010ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include static int permutation[512] = { 151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180, 151,160,137,91,90,15, 131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23, 190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33, 88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166, 77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244, 102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196, 135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123, 5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42, 223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9, 129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228, 251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107, 49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254, 138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180, }; static double fade(double t){ return t * t * t * ( t * (t * 6 - 15) +10); } static double lerp(double t, double a, double b){ return a + t * (b - a); } static double grad(int hash, double x, double y, double z){ int h = hash & 15; double u = h < 8 ? x : y; double v = h < 4 ? y : (h == 12 || h == 14) ? x : z; return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v); } /** * Improved Perlin noise algorithm implemented by using reference Java implementation from. * \see http://mrl.nyu.edu/~perlin/noise/ */ double noise(double x, double y, double z){ int X = (int)floor(x) & 255, Y = (int)floor(y) & 255, Z = (int)floor(z) & 255; x -= floor(x); y -= floor(y); z -= floor(z); double u = fade(x), v = fade(y), w = fade(z); int A = permutation[X]+Y, AA = permutation[A]+Z, AB = permutation[A+1]+Z, B = permutation[X+1]+Y, BA = permutation[B]+Z, BB = permutation[B+1]+Z; return lerp(w, lerp(v, lerp(u, grad(permutation[AA], x, y, z), grad(permutation[BA], x-1, y, z)), lerp(u, grad(permutation[AB], x, y-1, z), grad(permutation[BB], x-1, y-1, z))), lerp(v, lerp(u, grad(permutation[AA+1], x, y, z-1), grad(permutation[BA+1], x-1, y, z-1)), lerp(u, grad(permutation[AB+1], x, y-1, z-1), grad(permutation[BB+1], x-1, y-1, z-1))) ); } gpick-gpick-0.2.6rc1/source/Noise.h000066400000000000000000000035551315430016700170530ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef NOISE_H_ #define NOISE_H_ /** \file source/Noise.h * \brief Improved Perlin noise implementation. */ /** * Returns noise value for specified position. * @param[in] x X coordinate. * @param[in] y y coordinate. * @param[in] z Z coordinate. * @return Noise value. */ double noise(double x, double y, double z); #endif /* NOISE_H_ */ gpick-gpick-0.2.6rc1/source/Paths.cpp000066400000000000000000000053341315430016700174050ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Paths.h" #include static gchar* get_data_dir() { static gchar* data_dir = nullptr; if (data_dir) return data_dir; GList *paths = nullptr, *i = nullptr; gchar *tmp; i = g_list_append(i, (gchar*)"share"); paths = i; i = g_list_append(i, (gchar*)g_get_user_data_dir()); const gchar* const *datadirs = g_get_system_data_dirs(); for (gint datadirs_i = 0; datadirs[datadirs_i]; ++datadirs_i){ i = g_list_append(i, (gchar*)datadirs[datadirs_i]); } i = paths; GStatBuf sb; while (i){ tmp = g_build_filename((gchar*)i->data, "gpick", nullptr); if (g_stat(tmp, &sb) == 0){ data_dir=g_strdup(tmp); g_free(tmp); break; } g_free(tmp); i = g_list_next(i); } g_list_free(paths); if (data_dir == nullptr){ data_dir=g_strdup(""); return data_dir; } return data_dir; } gchar* build_filename(const gchar* filename) { if (filename) return g_build_filename(get_data_dir(), filename, nullptr); else return g_build_filename(get_data_dir(), nullptr); } gchar* build_config_path(const gchar *filename) { if (filename) return g_build_filename(g_get_user_config_dir(), "gpick", filename, nullptr); else return g_build_filename(g_get_user_config_dir(), "gpick", nullptr); } gpick-gpick-0.2.6rc1/source/Paths.h000066400000000000000000000042311315430016700170450ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef PATHS_H_ #define PATHS_H_ #include /** \file source/Paths.h * \brief Data and configuration filename building functions. */ /** * Construct filename to a data file. * @param[in] filename Relative data file name. * @return Filename to the data file. This value must be released by using g_free. */ gchar* build_filename(const gchar* filename); /** * Construct filename to a configuration file. * @param[in] filename Relative configuration file name. * @return Filename to the configuration file. This value must be released by using g_free. */ gchar* build_config_path(const gchar *filename); #endif /* PATHS_H_ */ gpick-gpick-0.2.6rc1/source/Random.cpp000066400000000000000000000074041315430016700175460ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Random.h" #include static unsigned long random_function_znew(struct Random* r, unsigned long seed_offset) { return (r->seed[seed_offset] = 36969 * (r->seed[seed_offset] & 65535) + (r->seed[seed_offset] >> 16)); } static unsigned long random_function_wnew(struct Random* r, unsigned long seed_offset) { return (r->seed[seed_offset] = 18000 * (r->seed[seed_offset] & 65535) + (r->seed[seed_offset] >> 16)); } static unsigned long random_function_MWC(struct Random* r, unsigned long seed_offset) { return (random_function_znew(r, 0) << 16) + random_function_wnew(r, 1); } static unsigned long random_function_SHR3(struct Random* r, unsigned long seed_offset) { r->seed[seed_offset] ^= r->seed[seed_offset] << 17; r->seed[seed_offset] ^= (r->seed[seed_offset] & 0xFFFFFFFF) >> 13; return (r->seed[seed_offset] ^= r->seed[seed_offset] << 5); } struct Random* random_new(const char* random_function) { struct Random* r = new struct Random; struct RandomFunction { const char* name; unsigned long (*function)(struct Random* r, unsigned long seed_offset); unsigned long seed_size; }; struct RandomFunction functions[] = { {"znew", random_function_znew, 1}, {"wnew", random_function_wnew, 1}, {"MWC", random_function_MWC, 2}, {"SHR3", random_function_SHR3, 1}, }; bool found = false; for (unsigned long i = 0; i < sizeof(functions) / sizeof(struct RandomFunction); ++i){ if (strcmp(random_function, functions[i].name) == 0){ r->function = functions[i].function; r->seed_size = functions[i].seed_size; r->seed = new unsigned long [r->seed_size]; found = true; break; } } if (found) return r; delete r; return 0; } struct Random* random_new(const char* random_function, unsigned long seed) { struct Random* random = random_new(random_function); random_seed(random, &seed); random_get(random); return random; } unsigned long random_get(struct Random* r) { if (!r) return 0; return r->function(r, 0); } double random_get_double(struct Random* r) { return (random_get(r) & 0xFFFFFFFF) / (double)0xFFFFFFFF; } void random_seed(struct Random* r, void* seed) { if (!r) return; memcpy(r->seed, seed, r->seed_size * sizeof(unsigned long)); } void random_destroy(struct Random* r) { if (r){ delete [] r->seed; delete r; } } gpick-gpick-0.2.6rc1/source/Random.h000066400000000000000000000040361315430016700172110ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_RANDOM_H_ #define GPICK_RANDOM_H_ struct Random { unsigned long (*function)(struct Random* r, unsigned long seed_offset); unsigned long *seed; unsigned long seed_size; }; struct Random* random_new(const char* random_function); struct Random* random_new(const char* random_function, unsigned long seed); unsigned long random_get(struct Random* r); double random_get_double(struct Random* r); void random_seed(struct Random* r, void* seed); void random_destroy(struct Random* r); #endif /* GPICK_RANDOM_H_ */ gpick-gpick-0.2.6rc1/source/Rect2.h000066400000000000000000000076141315430016700167550ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef RECT2_H_ #define RECT2_H_ namespace math{ template class Rect2{ public: Rect2(){ empty=true; }; Rect2(const T &x1_, const T &y1_, const T &x2_, const T &y2_):x1(x1_),y1(y1_),x2(x2_),y2(y2_){ empty=false; }; const Rect2 operator=(const Rect2 &rect){ x1 = rect.x1; y1 = rect.y1; x2 = rect.x2; y2 = rect.y2; empty = rect.empty; return *this; }; const Rect2 operator+(const Rect2 &rect) const{ if (rect.empty) return *this; if (empty) return rect; Rect2 r; if (x1 < rect.x1) r.x1 = x1; else r.x1 = rect.x1; if (y1 < rect.y1) r.y1 = y1; else r.y1 = rect.y1; if (x2 > rect.x2) r.x2 = x2; else r.x2 = rect.x2; if (y2 > rect.y2) r.y2 = y2; else r.y2 = rect.y2; return r; }; const Rect2 operator+=(const Rect2 &rect){ *this=*this+rect; return *this; }; Rect2 impose(const Rect2 &rect) const{ Rect2 r; r.x1 = rect.x1 + x1 * rect.getWidth(); r.y1 = rect.y1 + y1 * rect.getHeight(); r.x2 = rect.x1 + x2 * rect.getWidth(); r.y2 = rect.y1 + y2 * rect.getHeight(); r.empty = false; return r; } bool isInside(const T &x, const T &y) const{ if (xx2 || yy2) return false; else return true; } bool isInside(const Rect2 &r) const{ if (empty || r.empty) return false; if (x1 < r.x1 || x2 > r.x2) return false; if (y1 < r.y1 || y2 > r.y2) return false; return true; } Rect2 positionInside(const Rect2& rect) const{ Rect2 r; r.empty = false; if (rect.x1 < x1){ r.x1 = x1; r.x2 = x1 + rect.getWidth(); }else if (rect.x2 > x2){ r.x1 = x2 - rect.getWidth(); r.x2 = x2; }else{ r.x1 = rect.x1; r.x2 = rect.x2; } if (rect.y1 < y1){ r.y1 = y1; r.y2 = y1 + rect.getHeight(); }else if (rect.y2 > y2){ r.y1 = y2 - rect.getHeight(); r.y2 = y2; }else{ r.y1 = rect.y1; r.y2 = rect.y2; } return r; } bool isEmpty() const{ return empty; }; const T& getX() const{ return x1; }; const T& getY() const{ return y1; }; T getWidth() const{ return x2-x1; }; T getHeight() const{ return y2-y1; }; T getCenterX() const{ return (x1 + x2) / 2; }; T getCenterY() const{ return (y1 + y2) / 2; }; const T& getLeft() const{ return x1; }; const T& getTop() const{ return y1; }; const T& getRight() const{ return x2; }; const T& getBottom() const{ return y2; }; private: bool empty; T x1, y1, x2, y2; }; } #endif /* RECT2_H_ */ gpick-gpick-0.2.6rc1/source/RegisterSources.cpp000066400000000000000000000041521315430016700214530ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "RegisterSources.h" #include "GenerateScheme.h" #include "ColorPicker.h" #include "LayoutPreview.h" #include "Variations.h" #include "BrightnessDarkness.h" #include "ColorMixer.h" #include "BlendColors.h" #include "ClosestColors.h" int register_sources(ColorSourceManager *csm) { generate_scheme_source_register(csm); color_picker_source_register(csm); layout_preview_source_register(csm); variations_source_register(csm); brightness_darkness_source_register(csm); color_mixer_source_register(csm); blend_colors_source_register(csm); closest_colors_source_register(csm); return 0; } gpick-gpick-0.2.6rc1/source/RegisterSources.h000066400000000000000000000033121315430016700211150ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_REGISTER_SOURCES_H_ #define GPICK_REGISTER_SOURCES_H_ #include "ColorSourceManager.h" int register_sources(ColorSourceManager *csm); #endif /* GPICK_REGISTER_SOURCES_H_ */ gpick-gpick-0.2.6rc1/source/SConscript000066400000000000000000000057771315430016700176470ustar00rootroot00000000000000#!/usr/bin/env python import os import sys from tools.gpick import * Import('*') local_env = env.Clone() if not local_env.GetOption('clean') and not env['TOOLCHAIN'] == 'msvc': local_env.ParseConfig('pkg-config --cflags --libs $GTK_PC') local_env.ParseConfig('pkg-config --cflags --libs $LUA_PC') if local_env['ENABLE_NLS']: local_env.Append( CPPDEFINES = ['ENABLE_NLS'], ) local_env.Append( CPPDEFINES = ['GSEAL_ENABLE'], ) sources = local_env.Glob('*.cpp') + local_env.Glob('transformation/*.cpp') objects = [] objects.append(SConscript(['version/SConscript'], exports='env')) objects.append(SConscript(['gtk/SConscript'], exports='env')) objects.append(SConscript(['layout/SConscript'], exports='env')) objects.append(SConscript(['internationalisation/SConscript'], exports='env')) objects.append(SConscript(['dbus/SConscript'], exports='env')) objects.append(SConscript(['tools/SConscript'], exports='env')) if env['EXPERIMENTAL_CSS_PARSER']: parser_objects, generated_files = SConscript(['cssparser/SConscript'], exports='env') objects.append(parser_objects) else: generated_files = [] objects.append(SConscript(['color_names/SConscript'], exports='env')) if env['TOOLCHAIN'] == 'msvc': local_env.Append(LIBS = ['glib-2.0', 'gtk-win32-2.0', 'gobject-2.0', 'gdk-win32-2.0', 'cairo', 'gdk_pixbuf-2.0', 'lua5.2', 'expat2.1', 'pango-1.0', 'pangocairo-1.0', 'intl']) else: local_env.Append(LIBS = ['boost_filesystem', 'boost_system']) if local_env['BUILD_TARGET'] == 'win32': if not (env['TOOLCHAIN'] == 'msvc'): local_env.Append(LINKFLAGS = '-mwindows') local_env.Append(LIBS=['expat']) else: local_env.Append(LINKFLAGS = ['/SUBSYSTEM:WINDOWS', '/ENTRY:mainCRTStartup'], CPPDEFINES = ['XML_STATIC']) objects.append(SConscript(['winres/SConscript'], exports='env')) elif local_env['BUILD_TARGET'] == 'linux2': local_env.Append(LIBS=['rt', 'expat']) elif local_env['BUILD_TARGET'].startswith('gnu0'): local_env.Append(LIBS=['rt', 'expat']) elif local_env['BUILD_TARGET'].startswith('gnukfreebsd'): local_env.Append(LIBS=['rt', 'expat']) local_env.Append(CPPPATH=['#source']) text_file_parser_objects = local_env.StaticObject(source = ['parser/TextFile.cpp', local_env.Ragel('parser/TextFileParser.rl')]) objects.append(text_file_parser_objects) dynv_objects = local_env.StaticObject(source = local_env.Glob('dynv/*.cpp')) objects.append(dynv_objects) gpick_objects = local_env.StaticObject(source = sources) gpick_object_map = {} for obj in gpick_objects: gpick_object_map[os.path.splitext(obj.name)[0]] = obj objects.append(gpick_objects) executable = local_env.Program('gpick', source = [objects]) test_env = local_env.Clone() test_env.Append(LIBS = ['boost_unit_test_framework']) test_dynv = test_env.Program('test_dynv', source = ['test/DynvTest.cpp', dynv_objects]) test_text_file = test_env.Program('test_text_file', source = ['test/TextFileTest.cpp', text_file_parser_objects, gpick_object_map['Color'], gpick_object_map['MathUtil']]) tests = [test_dynv, test_text_file] Return('executable', 'tests', 'generated_files') gpick-gpick-0.2.6rc1/source/Sampler.cpp000066400000000000000000000132211315430016700177230ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Sampler.h" #include "ScreenReader.h" #include "MathUtil.h" #include #include using namespace math; struct Sampler { int oversample; SamplerFalloff falloff; float (*falloff_fnc)(float distance); ScreenReader* screen_reader; }; static float sampler_falloff_none(float distance) { return 1; } static float sampler_falloff_linear(float distance) { return 1 - distance; } static float sampler_falloff_quadratic(float distance) { return 1 - (distance * distance); } static float sampler_falloff_cubic(float distance) { return 1 - (distance * distance * distance); } static float sampler_falloff_exponential(float distance) { return 1 / exp(5 * distance * distance); } struct Sampler* sampler_new(ScreenReader* screen_reader) { Sampler* sampler = new Sampler; sampler->oversample = 0; sampler_set_falloff(sampler, SamplerFalloff::none); sampler->screen_reader = screen_reader; return sampler; } void sampler_destroy(Sampler *sampler) { delete sampler; } void sampler_set_falloff(Sampler *sampler, SamplerFalloff falloff) { sampler->falloff = falloff; switch (falloff){ case SamplerFalloff::none: sampler->falloff_fnc = sampler_falloff_none; break; case SamplerFalloff::linear: sampler->falloff_fnc = sampler_falloff_linear; break; case SamplerFalloff::quadratic: sampler->falloff_fnc = sampler_falloff_quadratic; break; case SamplerFalloff::cubic: sampler->falloff_fnc = sampler_falloff_cubic; break; case SamplerFalloff::exponential: sampler->falloff_fnc = sampler_falloff_exponential; break; default: sampler->falloff_fnc = 0; } } void sampler_set_oversample(Sampler *sampler, int oversample) { sampler->oversample = oversample; } static void get_pixel(unsigned char *data, int stride, int x, int y, Color* color) { unsigned char *p; p = data + y * stride + x * 4; color->rgb.red = p[2] * (1 / 255.0); color->rgb.green = p[1] * (1 / 255.0); color->rgb.blue = p[0] * (1 / 255.0); } int sampler_get_color_sample(Sampler *sampler, Vec2& pointer, Rect2& screen_rect, Vec2& offset, Color* color) { Color sample, result; float divider = 0; color_zero(&result); cairo_surface_t *surface = screen_reader_get_surface(sampler->screen_reader); int x = pointer.x, y = pointer.y; int left, right, top, bottom; left = max_int(screen_rect.getLeft(), x - sampler->oversample); right = min_int(screen_rect.getRight(), x + sampler->oversample + 1); top = max_int(screen_rect.getTop(), y - sampler->oversample); bottom = min_int(screen_rect.getBottom(), y + sampler->oversample + 1); int width = right - left; int height = bottom - top; int center_x = x - left; int center_y = y - top; float max_distance = 1 / sqrt(2 * pow((double)sampler->oversample, 2)); unsigned char *data = cairo_image_surface_get_data(surface); int stride = cairo_image_surface_get_stride(surface); for (int x=-sampler->oversample; x <= sampler->oversample; ++x){ for (int y=-sampler->oversample; y <= sampler->oversample; ++y){ if ((center_x + x < 0) || (center_y + y < 0)) continue; if ((center_x + x >= width) || (center_y + y >= height)) continue; get_pixel(data, stride, offset.x + center_x + x, offset.y + center_y + y, &sample); float f; if (sampler->oversample){ f = sampler->falloff_fnc(sqrt((double)(x * x + y * y)) * max_distance); }else{ f = 1; } color_multiply(&sample, f); color_add(&result, &sample); divider += f; } } if (divider > 0) color_multiply(&result, 1 / divider); color_copy(&result, color); return 0; } SamplerFalloff sampler_get_falloff(Sampler *sampler) { return sampler->falloff; } int sampler_get_oversample(Sampler *sampler) { return sampler->oversample; } void sampler_get_screen_rect(Sampler *sampler, math::Vec2& pointer, math::Rect2& screen_rect, math::Rect2 *rect) { int left, right, top, bottom; left = max_int(screen_rect.getLeft(), pointer.x - sampler->oversample); right = min_int(screen_rect.getRight(), pointer.x + sampler->oversample + 1); top = max_int(screen_rect.getTop(), pointer.y - sampler->oversample); bottom = min_int(screen_rect.getBottom(), pointer.y + sampler->oversample + 1); *rect = math::Rect2(left, top, right, bottom); } gpick-gpick-0.2.6rc1/source/Sampler.h000066400000000000000000000045771315430016700174060ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_SAMPLER_H_ #define GPICK_SAMPLER_H_ #include "Color.h" #include "Rect2.h" #include "Vector2.h" struct Sampler; struct ScreenReader; enum class SamplerFalloff: int { none = 0, linear = 1, quadratic = 2, cubic = 3, exponential = 4, }; Sampler* sampler_new(ScreenReader* screen_reader); void sampler_set_falloff(Sampler *sampler, SamplerFalloff falloff); void sampler_set_oversample(Sampler *sampler, int oversample); SamplerFalloff sampler_get_falloff(Sampler *sampler); int sampler_get_oversample(Sampler *sampler); void sampler_destroy(Sampler *sampler); int sampler_get_color_sample(Sampler *sampler, math::Vec2& pointer, math::Rect2& screen_rect, math::Vec2& offset, Color* color); void sampler_get_screen_rect(Sampler *sampler, math::Vec2& pointer, math::Rect2& screen_rect, math::Rect2 *rect); #endif /* GPICK_SAMPLER_H_ */ gpick-gpick-0.2.6rc1/source/ScreenReader.cpp000066400000000000000000000073571315430016700206770ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ScreenReader.h" #include "Rect2.h" #include #include #include using namespace math; using namespace std; struct ScreenReader { cairo_surface_t *surface; int max_size; GdkScreen *screen; Rect2 read_area; }; struct ScreenReader* screen_reader_new() { ScreenReader* screen = new ScreenReader; screen->max_size = 0; screen->surface = 0; screen->screen = 0; return screen; } void screen_reader_destroy(ScreenReader *screen) { if (screen->surface) cairo_surface_destroy(screen->surface); delete screen; } void screen_reader_add_rect(ScreenReader *screen, GdkScreen *gdk_screen, Rect2& rect) { if (screen->screen && (screen->screen == gdk_screen)){ screen->read_area += rect; }else{ screen->read_area += rect; screen->screen = gdk_screen; } } void screen_reader_reset_rect(ScreenReader *screen) { screen->read_area = Rect2(); screen->screen = NULL; } void screen_reader_update_surface(ScreenReader *screen, Rect2* update_rect) { if (!screen->screen) return; int left = screen->read_area.getX(); int top = screen->read_area.getY(); int width = screen->read_area.getWidth(); int height = screen->read_area.getHeight(); if (width > screen->max_size || height > screen->max_size){ if (screen->surface) cairo_surface_destroy(screen->surface); screen->max_size = (std::max(width, height) / 150 + 1) * 150; screen->surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, screen->max_size, screen->max_size); } GdkWindow* root_window = gdk_screen_get_root_window(screen->screen); cairo_t *root_cr = gdk_cairo_create(root_window); cairo_surface_t *root_surface = cairo_get_target(root_cr); if (cairo_surface_status(root_surface) != CAIRO_STATUS_SUCCESS){ cerr << "can not get root window surface" << endl; return; } cairo_t *cr = cairo_create(screen->surface); cairo_set_operator(cr, CAIRO_OPERATOR_SOURCE); cairo_set_source_surface(cr, root_surface, -left, -top); cairo_pattern_set_filter(cairo_get_source(cr), CAIRO_FILTER_NEAREST); cairo_rectangle(cr, 0, 0, width, height); cairo_fill(cr); cairo_destroy(cr); cairo_destroy(root_cr); *update_rect = screen->read_area; } cairo_surface_t* screen_reader_get_surface(ScreenReader *screen) { return screen->surface; } gpick-gpick-0.2.6rc1/source/ScreenReader.h000066400000000000000000000040741315430016700203350ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SCREENREADER_H_ #define SCREENREADER_H_ #include #include #include "Rect2.h" struct ScreenReader; ScreenReader* screen_reader_new(); void screen_reader_reset_rect(ScreenReader *screen); void screen_reader_add_rect(ScreenReader *screen, GdkScreen *gdk_screen, math::Rect2& rect); void screen_reader_update_surface(ScreenReader *screen, math::Rect2* update_rect); cairo_surface_t* screen_reader_get_surface(ScreenReader *screen); void screen_reader_destroy(ScreenReader *screen); #endif /* SCREENREADER_H_ */ gpick-gpick-0.2.6rc1/source/StandardMenu.cpp000066400000000000000000000066171315430016700207200ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "StandardMenu.h" #include "CopyMenu.h" #include "NearestColorsMenu.h" #include "Internationalisation.h" #include static void buildMenu(GtkWidget *menu, GtkWidget **copy_to_clipboard, GtkWidget **nearest_from_palette) { GtkAccelGroup *accel_group = gtk_menu_get_accel_group(GTK_MENU(menu)); GtkWidget *item = *copy_to_clipboard = gtk_menu_item_new_with_mnemonic(_("_Copy to clipboard")); if (accel_group) gtk_widget_add_accelerator(item, "activate", accel_group, GDK_KEY_c, GdkModifierType(GDK_CONTROL_MASK), GTK_ACCEL_VISIBLE); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); item = *nearest_from_palette = gtk_menu_item_new_with_mnemonic(_("_Nearest from palette")); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); } void StandardMenu::appendMenu(GtkWidget *menu, ColorObject* color_object, GtkWidget *palette_widget, GlobalState *gs) { GtkWidget *copy_to_clipboard, *nearest_from_palette; buildMenu(menu, ©_to_clipboard, &nearest_from_palette); gtk_menu_item_set_submenu(GTK_MENU_ITEM(copy_to_clipboard), CopyMenu::newMenu(color_object, palette_widget, gs)); gtk_menu_item_set_submenu(GTK_MENU_ITEM(nearest_from_palette), NearestColorsMenu::newMenu(color_object, gs)); } void StandardMenu::appendMenu(GtkWidget *menu, ColorObject* color_object, GlobalState *gs) { GtkWidget *copy_to_clipboard, *nearest_from_palette; buildMenu(menu, ©_to_clipboard, &nearest_from_palette); gtk_menu_item_set_submenu(GTK_MENU_ITEM(copy_to_clipboard), CopyMenu::newMenu(color_object, gs)); gtk_menu_item_set_submenu(GTK_MENU_ITEM(nearest_from_palette), NearestColorsMenu::newMenu(color_object, gs)); } void StandardMenu::appendMenu(GtkWidget *menu) { GtkWidget *copy_to_clipboard, *nearest_from_palette; buildMenu(menu, ©_to_clipboard, &nearest_from_palette); gtk_widget_set_sensitive(copy_to_clipboard, false); gtk_widget_set_sensitive(nearest_from_palette, false); } gpick-gpick-0.2.6rc1/source/StandardMenu.h000066400000000000000000000037041315430016700203570ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_STANDARD_MENU_H_ #define GPICK_STANDARD_MENU_H_ #include class ColorObject; class GlobalState; class StandardMenu { public: static void appendMenu(GtkWidget *menu, ColorObject* color_object, GlobalState *gs); static void appendMenu(GtkWidget *menu, ColorObject* color_object, GtkWidget *palette_widget, GlobalState *gs); static void appendMenu(GtkWidget *menu); }; #endif /* GPICK_STANDARD_MENU_H_ */ gpick-gpick-0.2.6rc1/source/StringUtils.cpp000066400000000000000000000051421315430016700206120ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "StringUtils.h" using namespace std; void split(const std::string &str, char separator, bool skip_empty, std::function function) { size_t start = 0; size_t separator_position = str.find(separator); if (separator_position == string::npos){ if (skip_empty && str.empty()) return; function(str); return; } do{ if (!skip_empty || separator_position - start > 0) function(str.substr(start, separator_position - start)); start = separator_position + 1; separator_position = str.find(separator, start); }while (separator_position != string::npos); if (start != str.length()){ function(str.substr(start, str.length() - start)); }else if (!skip_empty){ function(string()); } } void stripLeadingTrailingChars(std::string &str, const std::string &strip_chars) { if (str.empty()) return; if (strip_chars.empty()) return; size_t start = str.find_first_not_of(strip_chars); size_t end = str.find_last_not_of(strip_chars); if ((start == string::npos) || (end == string::npos)){ str.erase(); return; } str = str.substr(start, end - start + 1); } gpick-gpick-0.2.6rc1/source/StringUtils.h000066400000000000000000000035441315430016700202630ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_STRING_UTILS_H_ #define GPICK_STRING_UTILS_H_ #include #include void split(const std::string &str, char separator, bool skip_empty, std::function function); void stripLeadingTrailingChars(std::string &str, const std::string &strip_chars); #endif /* GPICK_STRING_UTILS_H_ */ gpick-gpick-0.2.6rc1/source/ToolColorNaming.cpp000066400000000000000000000065271315430016700214010ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ToolColorNaming.h" #include "GlobalState.h" #include "DynvHelpers.h" #include "Internationalisation.h" #include "color_names/ColorNames.h" #include "ColorObject.h" #include using namespace std; const ToolColorNamingOption options[] = { {TOOL_COLOR_NAMING_EMPTY, "empty", N_("_Empty")}, {TOOL_COLOR_NAMING_AUTOMATIC_NAME, "automatic_name", N_("_Automatic name")}, {TOOL_COLOR_NAMING_TOOL_SPECIFIC, "tool_specific", N_("_Tool specific")}, {TOOL_COLOR_NAMING_UNKNOWN, 0, 0}, }; const ToolColorNamingOption* tool_color_naming_get_options() { return options; } ToolColorNamingType tool_color_naming_name_to_type(const char *name) { string n = name; int i = 0; while (options[i].name){ if (n.compare(options[i].name) == 0){ return options[i].type; } i++; } return TOOL_COLOR_NAMING_UNKNOWN; } ToolColorNameAssigner::ToolColorNameAssigner(GlobalState *gs): m_gs(gs) { m_color_naming_type = tool_color_naming_name_to_type(dynv_get_string_wd(m_gs->getSettings(), "gpick.color_names.tool_color_naming", "tool_specific")); if (m_color_naming_type == TOOL_COLOR_NAMING_AUTOMATIC_NAME){ m_imprecision_postfix = dynv_get_bool_wd(m_gs->getSettings(), "gpick.color_names.imprecision_postfix", true); }else{ m_imprecision_postfix = false; } } ToolColorNameAssigner::~ToolColorNameAssigner() { } void ToolColorNameAssigner::assign(ColorObject *color_object, const Color *color) { string name; switch (m_color_naming_type){ case TOOL_COLOR_NAMING_UNKNOWN: case TOOL_COLOR_NAMING_EMPTY: color_object->setName(""); break; case TOOL_COLOR_NAMING_AUTOMATIC_NAME: name = color_names_get(m_gs->getColorNames(), color, m_imprecision_postfix); color_object->setName(name); break; case TOOL_COLOR_NAMING_TOOL_SPECIFIC: name = getToolSpecificName(color_object, color); color_object->setName(name); break; } } gpick-gpick-0.2.6rc1/source/ToolColorNaming.h000066400000000000000000000047461315430016700210470ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_TOOL_COLOR_NAMING_H_ #define GPICK_TOOL_COLOR_NAMING_H_ #include class GlobalState; struct Color; class ColorObject; enum ToolColorNamingType { TOOL_COLOR_NAMING_UNKNOWN = 0, TOOL_COLOR_NAMING_EMPTY, TOOL_COLOR_NAMING_AUTOMATIC_NAME, TOOL_COLOR_NAMING_TOOL_SPECIFIC, }; typedef struct ToolColorNamingOption{ ToolColorNamingType type; const char *name; const char *label; }ToolColorNamingOption; const ToolColorNamingOption* tool_color_naming_get_options(); ToolColorNamingType tool_color_naming_name_to_type(const char *name); class ToolColorNameAssigner{ protected: ToolColorNamingType m_color_naming_type; GlobalState* m_gs; bool m_imprecision_postfix; public: ToolColorNameAssigner(GlobalState *gs); virtual ~ToolColorNameAssigner(); void assign(ColorObject *color_object, const Color *color); virtual std::string getToolSpecificName(ColorObject *color_object, const Color *color) = 0; }; #endif /* GPICK_TOOL_COLOR_NAMING_H_ */ gpick-gpick-0.2.6rc1/source/Variations.cpp000066400000000000000000000626231315430016700204510ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Variations.h" #include "ColorObject.h" #include "ColorSource.h" #include "ColorSourceManager.h" #include "DragDrop.h" #include "GlobalState.h" #include "ToolColorNaming.h" #include "uiUtilities.h" #include "ColorList.h" #include "MathUtil.h" #include "ColorRYB.h" #include "gtk/ColorWidget.h" #include "gtk/ColorWheel.h" #include "ColorWheelType.h" #include "uiColorInput.h" #include "CopyPaste.h" #include "Converter.h" #include "DynvHelpers.h" #include "Internationalisation.h" #include "color_names/ColorNames.h" #include "StandardMenu.h" #include "Clipboard.h" #include #include #include #include #include #include using namespace std; #define VAR_COLOR_WIDGETS 8 #define MAX_COLOR_LINES 3 #define COMPONENT_ID_HSL_HUE 1 #define COMPONENT_ID_HSL_SATURATION 2 #define COMPONENT_ID_HSL_LIGHTNESS 3 #define COMPONENT_ID_LAB_LIGHTNESS 4 typedef struct VariationType{ const char *name; const char *symbol; const char *unique_name; int component_id; double strength_mult; }VariationType; const VariationType variation_types[] = { {N_("Hue"), "HHSL", "hsl_hue", COMPONENT_ID_HSL_HUE, 1}, {N_("Saturation"), "SHSL", "hsl_saturation", COMPONENT_ID_HSL_SATURATION, 1}, {N_("Lightness"), "LHSL", "hsl_lightness", COMPONENT_ID_HSL_LIGHTNESS, 1}, {N_("Lightness (Lab)"), "LLab", "lab_lightness", COMPONENT_ID_LAB_LIGHTNESS, 1}, }; typedef struct VariationsArgs{ ColorSource source; GtkWidget* main; GtkWidget* statusbar; GtkWidget *strength; GtkWidget *last_focused_color; GtkWidget *color_previews; GtkWidget *all_colors; struct{ GtkWidget *color; GtkWidget *var_colors[VAR_COLOR_WIDGETS + 1]; const VariationType *type; }color[MAX_COLOR_LINES]; struct dynvSystem *params; ColorList *preview_color_list; GlobalState* gs; }VariationsArgs; class VariationsColorNameAssigner: public ToolColorNameAssigner { protected: stringstream m_stream; const char *m_ident; public: VariationsColorNameAssigner(GlobalState *gs): ToolColorNameAssigner(gs) { } void assign(ColorObject *color_object, const Color *color, const char *ident) { m_ident = ident; ToolColorNameAssigner::assign(color_object, color); } virtual std::string getToolSpecificName(ColorObject *color_object, const Color *color) { m_stream.str(""); m_stream << color_names_get(m_gs->getColorNames(), color, false) << " " << _("variations") << " " << m_ident; return m_stream.str(); } }; static boost::format format_ignore_arg_errors(const std::string &f_string) { boost::format fmter(f_string); fmter.exceptions(boost::io::all_error_bits ^ (boost::io::too_many_args_bit | boost::io::too_few_args_bit)); return fmter; } static int set_rgb_color(VariationsArgs *args, ColorObject* color, uint32_t color_index); static int set_rgb_color_by_widget(VariationsArgs *args, ColorObject* color, GtkWidget* color_widget); static void calc(VariationsArgs *args, bool preview, bool save_settings){ double strength = gtk_range_get_value(GTK_RANGE(args->strength)); if (save_settings){ dynv_set_float(args->params, "strength", strength); } Color color, hsl, lab, r, hsl_mod, lab_mod; for (int i = 0; i < MAX_COLOR_LINES; ++i){ gtk_color_get_color(GTK_COLOR(args->color[i].color), &color); switch (args->color[i].type->component_id){ case COMPONENT_ID_HSL_HUE: case COMPONENT_ID_HSL_SATURATION: case COMPONENT_ID_HSL_LIGHTNESS: color_rgb_to_hsl(&color, &hsl); break; case COMPONENT_ID_LAB_LIGHTNESS: { color_rgb_to_lab_d50(&color, &lab); } break; } for (int j = 0; j < VAR_COLOR_WIDGETS + 1; ++j){ if (j == VAR_COLOR_WIDGETS / 2) continue; switch (args->color[i].type->component_id){ case COMPONENT_ID_HSL_HUE: color_copy(&hsl, &hsl_mod); hsl_mod.hsl.hue = wrap_float(hsl.hsl.hue + (args->color[i].type->strength_mult * strength * (j - VAR_COLOR_WIDGETS / 2)) / 400.0); color_hsl_to_rgb(&hsl_mod, &r); break; case COMPONENT_ID_HSL_SATURATION: color_copy(&hsl, &hsl_mod); hsl_mod.hsl.saturation = clamp_float(hsl.hsl.saturation + (args->color[i].type->strength_mult * strength * (j - VAR_COLOR_WIDGETS / 2)) / 400.0, 0, 1); color_hsl_to_rgb(&hsl_mod, &r); break; case COMPONENT_ID_HSL_LIGHTNESS: color_copy(&hsl, &hsl_mod); hsl_mod.hsl.lightness = clamp_float(hsl.hsl.lightness + (args->color[i].type->strength_mult * strength * (j - VAR_COLOR_WIDGETS / 2)) / 400.0, 0, 1); color_hsl_to_rgb(&hsl_mod, &r); break; case COMPONENT_ID_LAB_LIGHTNESS: color_copy(&lab, &lab_mod); lab_mod.lab.L = clamp_float(lab.lab.L + (args->color[i].type->strength_mult * strength * (j - VAR_COLOR_WIDGETS / 2)) / 4.0, 0, 100); color_lab_to_rgb_d50(&lab_mod, &r); color_rgb_normalize(&r); break; } gtk_color_set_color(GTK_COLOR(args->color[i].var_colors[j]), &r, ""); } } } static void update(GtkWidget *widget, VariationsArgs *args ){ color_list_remove_all(args->preview_color_list); calc(args, true, false); } static void on_color_paste(GtkWidget *widget, gpointer item) { VariationsArgs* args=(VariationsArgs*)item; GtkWidget* color_widget = GTK_WIDGET(g_object_get_data(G_OBJECT(widget), "color_widget")); ColorObject* color_object; if (copypaste_get_color_object(&color_object, args->gs) == 0){ set_rgb_color_by_widget(args, color_object, color_widget); color_object->release(); } } static void on_color_edit(GtkWidget *widget, gpointer item) { VariationsArgs* args=(VariationsArgs*)item; GtkWidget* color_widget = GTK_WIDGET(g_object_get_data(G_OBJECT(widget), "color_widget")); Color c; gtk_color_get_color(GTK_COLOR(color_widget), &c); ColorObject* color_object = color_list_new_color_object(args->gs->getColorList(), &c); ColorObject* new_color_object = 0; if (dialog_color_input_show(GTK_WINDOW(gtk_widget_get_toplevel(args->main)), args->gs, color_object, &new_color_object ) == 0){ set_rgb_color_by_widget(args, new_color_object, color_widget); new_color_object->release(); } color_object->release(); } static string identify_color_widget(GtkWidget *widget, VariationsArgs *args) { if (args->all_colors == widget){ return _("all colors"); }else for (int i = 0; i < MAX_COLOR_LINES; ++i){ if (args->color[i].color == widget){ try{ return (format_ignore_arg_errors(_("primary %d")) % (i + 1)).str(); }catch(const boost::io::format_error &e){ return (format_ignore_arg_errors("primary %d") % (i + 1)).str(); } } for (int j = 0; j <= VAR_COLOR_WIDGETS; ++j){ if (args->color[i].var_colors[j] == widget){ if (j > VAR_COLOR_WIDGETS / 2) j--; try{ return (format_ignore_arg_errors(_("result %d line %d")) % (j + 1) % (i + 1)).str(); }catch(const boost::io::format_error &e){ return (format_ignore_arg_errors("result %d line %d") % (j + 1) % (i + 1)).str(); } } } } return "unknown"; } static void add_color_to_palette(GtkWidget *color_widget, VariationsColorNameAssigner &name_assigner, VariationsArgs *args) { Color c; ColorObject *color_object; string widget_ident; gtk_color_get_color(GTK_COLOR(color_widget), &c); color_object = color_list_new_color_object(args->gs->getColorList(), &c); widget_ident = identify_color_widget(color_widget, args); name_assigner.assign(color_object, &c, widget_ident.c_str()); color_list_add_color_object(args->gs->getColorList(), color_object, 1); color_object->release(); } static void on_color_add_to_palette(GtkWidget *widget, gpointer item) { VariationsArgs* args = (VariationsArgs*)item; GtkWidget *color_widget = GTK_WIDGET(g_object_get_data(G_OBJECT(widget), "color_widget")); VariationsColorNameAssigner name_assigner(args->gs); add_color_to_palette(color_widget, name_assigner, args); } static void on_color_add_all_to_palette(GtkWidget *widget, gpointer item) { VariationsArgs* args = (VariationsArgs*)item; VariationsColorNameAssigner name_assigner(args->gs); for (int i = 0; i < MAX_COLOR_LINES; ++i){ for (int j = 0; j < VAR_COLOR_WIDGETS + 1; ++j){ add_color_to_palette(args->color[i].var_colors[j], name_assigner, args); } } } static gboolean color_focus_in_cb(GtkWidget *widget, GdkEventFocus *event, VariationsArgs *args){ args->last_focused_color = widget; return false; } static void on_color_activate(GtkWidget *widget, VariationsArgs* args) { Color color; gtk_color_get_color(GTK_COLOR(widget), &color); ColorObject *color_object = color_list_new_color_object(args->gs->getColorList(), &color); string name = color_names_get(args->gs->getColorNames(), &color, dynv_get_bool_wd(args->gs->getSettings(), "gpick.color_names.imprecision_postfix", true)); color_object->setName(name); color_list_add_color_object(args->gs->getColorList(), color_object, 1); color_object->release(); } static void type_toggled_cb(GtkWidget *widget, VariationsArgs *args) { GtkWidget* color_widget = GTK_WIDGET(g_object_get_data(G_OBJECT(widget), "color_widget")); const VariationType *var_type = static_cast(g_object_get_data(G_OBJECT(widget), "variation_type")); if (gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(widget))){ int line_id = -1; for (int i = 0; i < MAX_COLOR_LINES; ++i){ if (args->color[i].color == color_widget){ line_id = i; break; } } args->color[line_id].type = var_type; Color c; gtk_color_get_color(GTK_COLOR(color_widget), &c); ColorObject *color_object = color_list_new_color_object(args->gs->getColorList(), &c); set_rgb_color(args, color_object, line_id); color_object->release(); } } static void color_show_menu(GtkWidget* widget, VariationsArgs* args, GdkEventButton *event ){ GtkWidget *menu; GtkWidget* item; menu = gtk_menu_new (); item = gtk_menu_item_new_with_image(_("_Add to palette"), gtk_image_new_from_stock(GTK_STOCK_ADD, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK (on_color_add_to_palette), args); g_object_set_data(G_OBJECT(item), "color_widget", widget); item = gtk_menu_item_new_with_image(_("A_dd all to palette"), gtk_image_new_from_stock(GTK_STOCK_ADD, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK (on_color_add_all_to_palette), args); g_object_set_data(G_OBJECT(item), "color_widget", widget); gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); Color c; gtk_color_get_color(GTK_COLOR(widget), &c); ColorObject *color_object = color_list_new_color_object(args->gs->getColorList(), &c); StandardMenu::appendMenu(menu, color_object, args->gs); color_object->release(); int line_id = -1; bool all_colors = false; if (args->all_colors == widget){ all_colors = true; }else for (int i = 0; i < MAX_COLOR_LINES; ++i){ if (args->color[i].color == widget){ line_id = i; } } if (line_id >= 0 || all_colors){ gtk_menu_shell_append (GTK_MENU_SHELL (menu), gtk_separator_menu_item_new ()); if (!all_colors){ GSList *group = 0; for (uint32_t i = 0; i < sizeof(variation_types) / sizeof(VariationType); i++){ item = gtk_radio_menu_item_new_with_label(group, _(variation_types[i].name)); group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(item)); if (args->color[line_id].type == &variation_types[i]){ gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item), true); } g_object_set_data(G_OBJECT(item), "color_widget", widget); g_object_set_data(G_OBJECT(item), "variation_type", (void*)&variation_types[i]); g_signal_connect(G_OBJECT(item), "toggled", G_CALLBACK(type_toggled_cb), args); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); } gtk_menu_shell_append (GTK_MENU_SHELL (menu), gtk_separator_menu_item_new ()); } item = gtk_menu_item_new_with_image (_("_Edit..."), gtk_image_new_from_stock(GTK_STOCK_EDIT, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK (on_color_edit), args); g_object_set_data(G_OBJECT(item), "color_widget", widget); item = gtk_menu_item_new_with_image (_("_Paste"), gtk_image_new_from_stock(GTK_STOCK_PASTE, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK (on_color_paste), args); g_object_set_data(G_OBJECT(item), "color_widget", widget); if (copypaste_is_color_object_available(args->gs) != 0){ gtk_widget_set_sensitive(item, false); } } gtk_widget_show_all (GTK_WIDGET(menu)); gint32 button, event_time; if (event){ button = event->button; event_time = event->time; }else{ button = 0; event_time = gtk_get_current_event_time (); } gtk_menu_popup (GTK_MENU (menu), nullptr, nullptr, nullptr, nullptr, button, event_time); g_object_ref_sink(menu); g_object_unref(menu); } static gboolean on_color_button_press (GtkWidget *widget, GdkEventButton *event, VariationsArgs* args) { if (event->button == 3 && event->type == GDK_BUTTON_PRESS){ color_show_menu(widget, args, event); } return false; } static void on_color_popup_menu(GtkWidget *widget, VariationsArgs* args){ color_show_menu(widget, args, 0); } static gboolean on_color_key_press (GtkWidget *widget, GdkEventKey *event, VariationsArgs* args){ guint modifiers = gtk_accelerator_get_default_mod_mask(); Color c; ColorObject* color_object; GtkWidget* color_widget = widget; switch(event->keyval){ case GDK_KEY_c: if ((event->state & modifiers) == GDK_CONTROL_MASK){ gtk_color_get_color(GTK_COLOR(color_widget), &c); Clipboard::set(c, args->gs); return true; } return false; break; case GDK_KEY_v: if ((event->state&modifiers) == GDK_CONTROL_MASK){ if (copypaste_get_color_object(&color_object, args->gs) == 0){ set_rgb_color_by_widget(args, color_object, color_widget); color_object->release(); } return true; } return false; break; default: return false; break; } return false; } static int source_destroy(VariationsArgs *args){ Color c; char tmp[32]; for (gint i = 0; i < MAX_COLOR_LINES; ++i){ sprintf(tmp, "type%d", i); dynv_set_string(args->params, tmp, args->color[i].type->unique_name); sprintf(tmp, "color%d", i); gtk_color_get_color(GTK_COLOR(args->color[i].color), &c); dynv_set_color(args->params, tmp, &c); } gtk_color_get_color(GTK_COLOR(args->all_colors), &c); dynv_set_color(args->params, "all_colors", &c); color_list_destroy(args->preview_color_list); dynv_system_release(args->params); gtk_widget_destroy(args->main); delete args; return 0; } static int source_get_color(VariationsArgs *args, ColorObject** color){ VariationsColorNameAssigner name_assigner(args->gs); Color c; string widget_ident; if (args->last_focused_color){ gtk_color_get_color(GTK_COLOR(args->last_focused_color), &c); widget_ident = identify_color_widget(args->last_focused_color, args); }else{ gtk_color_get_color(GTK_COLOR(args->color[0].color), &c); widget_ident = identify_color_widget(args->color[0].color, args); } *color = color_list_new_color_object(args->gs->getColorList(), &c); name_assigner.assign(*color, &c, widget_ident.c_str()); return 0; } static int set_rgb_color_by_widget(VariationsArgs *args, ColorObject* color_object, GtkWidget* color_widget) { if (args->all_colors){ set_rgb_color(args, color_object, -1); return 0; }else for (int i = 0; i < MAX_COLOR_LINES; ++i){ if (args->color[i].color == color_widget){ set_rgb_color(args, color_object, i); return 0; } } return -1; } static int set_rgb_color(VariationsArgs *args, ColorObject* color_object, uint32_t color_index) { Color c = color_object->getColor(); if (color_index == (uint32_t)-1){ gtk_color_set_color(GTK_COLOR(args->all_colors), &c, ""); for (int i = 0; i < MAX_COLOR_LINES; ++i){ gtk_color_set_color(GTK_COLOR(args->color[i].color), &c, args->color[i].type->symbol); } }else{ gtk_color_set_color(GTK_COLOR(args->color[color_index].color), &c, args->color[color_index].type->symbol); } update(0, args); return 0; } static int source_set_color(VariationsArgs *args, ColorObject* color_object) { if (args->last_focused_color){ return set_rgb_color_by_widget(args, color_object, args->last_focused_color); }else{ return set_rgb_color(args, color_object, 0); } } static int source_activate(VariationsArgs *args) { auto chain = args->gs->getTransformationChain(); gtk_color_set_transformation_chain(GTK_COLOR(args->all_colors), chain); for (int i = 0; i < MAX_COLOR_LINES; ++i){ gtk_color_set_transformation_chain(GTK_COLOR(args->color[i].color), chain); for (int j = 0; j < VAR_COLOR_WIDGETS + 1; ++j){ gtk_color_set_transformation_chain(GTK_COLOR(args->color[i].var_colors[j]), chain); } } gtk_statusbar_push(GTK_STATUSBAR(args->statusbar), gtk_statusbar_get_context_id(GTK_STATUSBAR(args->statusbar), "empty"), ""); return 0; } static int source_deactivate(VariationsArgs *args){ color_list_remove_all(args->preview_color_list); calc(args, true, true); return 0; } static ColorObject* get_color_object(struct DragDrop* dd){ VariationsArgs* args = (VariationsArgs*)dd->userdata; ColorObject* color_object; if (source_get_color(args, &color_object) == 0){ return color_object; } return 0; } static int set_color_object_at(struct DragDrop* dd, ColorObject* color_object, int x, int y, bool move){ VariationsArgs* args = static_cast(dd->userdata); set_rgb_color(args, color_object, (uintptr_t)dd->userdata2); return 0; } static ColorSource* source_implement(ColorSource *source, GlobalState *gs, struct dynvSystem *dynv_namespace){ VariationsArgs* args = new VariationsArgs; args->params = dynv_system_ref(dynv_namespace); args->statusbar = gs->getStatusBar(); color_source_init(&args->source, source->identificator, source->hr_name); args->source.destroy = (int (*)(ColorSource *source))source_destroy; args->source.get_color = (int (*)(ColorSource *source, ColorObject** color))source_get_color; args->source.set_color = (int (*)(ColorSource *source, ColorObject* color))source_set_color; args->source.deactivate = (int (*)(ColorSource *source))source_deactivate; args->source.activate = (int (*)(ColorSource *source))source_activate; GtkWidget *table, *vbox, *hbox, *widget, *hbox2; hbox = gtk_hbox_new(FALSE, 0); vbox = gtk_vbox_new(FALSE, 0); gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 5); args->color_previews = gtk_table_new(MAX_COLOR_LINES, VAR_COLOR_WIDGETS + 1, false); gtk_box_pack_start(GTK_BOX(vbox), args->color_previews, true, true, 0); struct DragDrop dd; dragdrop_init(&dd, gs); dd.userdata = args; dd.get_color_object = get_color_object; dd.set_color_object_at = set_color_object_at; widget = gtk_color_new(); gtk_color_set_rounded(GTK_COLOR(widget), true); gtk_color_set_hcenter(GTK_COLOR(widget), true); gtk_color_set_roundness(GTK_COLOR(widget), 5); gtk_table_attach(GTK_TABLE(args->color_previews), widget, VAR_COLOR_WIDGETS / 2, VAR_COLOR_WIDGETS / 2 + 1, 0, 1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(0), 0, 0); args->all_colors = widget; g_signal_connect(G_OBJECT(widget), "button-press-event", G_CALLBACK(on_color_button_press), args); g_signal_connect(G_OBJECT(widget), "activated", G_CALLBACK(on_color_activate), args); g_signal_connect(G_OBJECT(widget), "key_press_event", G_CALLBACK(on_color_key_press), args); g_signal_connect(G_OBJECT(widget), "popup-menu", G_CALLBACK(on_color_popup_menu), args); g_signal_connect(G_OBJECT(widget), "focus-in-event", G_CALLBACK(color_focus_in_cb), args); //setup drag&drop gtk_widget_set_size_request(widget, 50, 20); gtk_drag_dest_set( widget, GtkDestDefaults(GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_HIGHLIGHT), 0, 0, GDK_ACTION_COPY); gtk_drag_source_set( widget, GDK_BUTTON1_MASK, 0, 0, GDK_ACTION_COPY); dd.handler_map = dynv_system_get_handler_map(gs->getColorList()->params); dd.userdata2 = (void*)-1; dragdrop_widget_attach(widget, DragDropFlags(DRAGDROP_SOURCE | DRAGDROP_DESTINATION), &dd); for (intptr_t i = 0; i < MAX_COLOR_LINES; ++i){ for (intptr_t j = 0; j < VAR_COLOR_WIDGETS + 1; ++j){ widget = gtk_color_new(); gtk_color_set_rounded(GTK_COLOR(widget), true); gtk_color_set_hcenter(GTK_COLOR(widget), true); gtk_color_set_roundness(GTK_COLOR(widget), 5); gtk_table_attach(GTK_TABLE(args->color_previews), widget, j, j + 1, i + 1, i + 2, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(0), 0, 0); args->color[i].var_colors[j] = widget; args->color[i].type = &variation_types[i]; g_signal_connect(G_OBJECT(widget), "button-press-event", G_CALLBACK(on_color_button_press), args); g_signal_connect(G_OBJECT(widget), "activated", G_CALLBACK(on_color_activate), args); g_signal_connect(G_OBJECT(widget), "key_press_event", G_CALLBACK(on_color_key_press), args); g_signal_connect(G_OBJECT(widget), "popup-menu", G_CALLBACK(on_color_popup_menu), args); g_signal_connect(G_OBJECT(widget), "focus-in-event", G_CALLBACK(color_focus_in_cb), args); //setup drag&drop if (j == VAR_COLOR_WIDGETS / 2){ gtk_widget_set_size_request(widget, 50, 30); gtk_drag_dest_set( widget, GtkDestDefaults(GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_HIGHLIGHT), 0, 0, GDK_ACTION_COPY); gtk_drag_source_set( widget, GDK_BUTTON1_MASK, 0, 0, GDK_ACTION_COPY); dd.handler_map = dynv_system_get_handler_map(gs->getColorList()->params); dd.userdata2 = (void*)i; dragdrop_widget_attach(widget, DragDropFlags(DRAGDROP_SOURCE | DRAGDROP_DESTINATION), &dd); args->color[i].color = args->color[i].var_colors[j]; }else{ gtk_widget_set_size_request(widget, 30, 25); gtk_drag_source_set( widget, GDK_BUTTON1_MASK, 0, 0, GDK_ACTION_COPY); dd.handler_map = dynv_system_get_handler_map(gs->getColorList()->params); dd.userdata2 = (void*)i; dragdrop_widget_attach(widget, DragDropFlags(DRAGDROP_SOURCE), &dd); } } } Color c; color_set(&c, 0.5); char tmp[32]; for (gint i = 0; i < MAX_COLOR_LINES; ++i){ sprintf(tmp, "type%d", i); const char *type_name = dynv_get_string_wd(args->params, tmp, "lab_lightness"); for (uint32_t j = 0; j < sizeof(variation_types) / sizeof(VariationType); j++){ if (g_strcmp0(variation_types[j].unique_name, type_name) == 0){ args->color[i].type = &variation_types[j]; break; } } sprintf(tmp, "color%d", i); gtk_color_set_color(GTK_COLOR(args->color[i].color), dynv_get_color_wdc(args->params, tmp, &c), args->color[i].type->symbol); } gtk_color_set_color(GTK_COLOR(args->all_colors), dynv_get_color_wdc(args->params, "all_colors", &c), ""); hbox2 = gtk_hbox_new(FALSE, 0); gtk_box_pack_start(GTK_BOX(vbox), hbox2, false, false, 0); gint table_y; table = gtk_table_new(5, 2, false); gtk_box_pack_start(GTK_BOX(hbox2), table, true, true, 0); table_y = 0; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Strength:"),0,0.5,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,0,0); args->strength = gtk_hscale_new_with_range(1, 100, 1); gtk_range_set_value(GTK_RANGE(args->strength), dynv_get_float_wd(args->params, "strength", 30)); g_signal_connect(G_OBJECT(args->strength), "value-changed", G_CALLBACK (update), args); gtk_table_attach(GTK_TABLE(table), args->strength,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,0,0); table_y++; struct dynvHandlerMap* handler_map=dynv_system_get_handler_map(gs->getColorList()->params); ColorList* preview_color_list = color_list_new(handler_map); dynv_handler_map_release(handler_map); args->preview_color_list = preview_color_list; args->gs = gs; gtk_widget_show_all(hbox); update(0, args); args->main = hbox; args->source.widget = hbox; return (ColorSource*)args; } int variations_source_register(ColorSourceManager *csm) { ColorSource *color_source = new ColorSource; color_source_init(color_source, "variations", _("Variations")); color_source->implement = (ColorSource* (*)(ColorSource *source, GlobalState *gs, struct dynvSystem *dynv_namespace))source_implement; color_source->default_accelerator = GDK_KEY_v; color_source_manager_add_source(csm, color_source); return 0; } gpick-gpick-0.2.6rc1/source/Variations.h000066400000000000000000000032771315430016700201160ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_VARIATIONS_H_ #define GPICK_VARIATIONS_H_ struct ColorSourceManager; int variations_source_register(ColorSourceManager *csm); #endif /* GPICK_VARIATIONS_H_ */ gpick-gpick-0.2.6rc1/source/Vector2.h000066400000000000000000000050521315430016700173140ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_VECTOR2_H_ #define GPICK_VECTOR2_H_ #include namespace math{ /** \class Vec2 * \brief Two dimensional vector */ template class Vec2 { public: Vec2() { x = y = 0; }; Vec2(const T &x_, const T &y_) { x = x_; y = y_; }; Vec2(T &x_, T &y_) { x = x_; y = y_; }; Vec2 &operator=(const Vec2 &v) { x = v.x; y = v.y; return *this; }; Vec2 operator*(const Vec2 &v) { Vec2 r; r.x = x * v.x; r.y = y * v.y; return r; }; Vec2 operator*(const double &v) { Vec2 r; r.x = x * v; r.y = y * v; return r; }; Vec2 operator+(const Vec2 &v) { Vec2 r; r.x = x + v.x; r.y = y + v.y; return r; }; friend bool operator!=(const Vec2 &lhs, const Vec2 &rhs) { if (lhs.x != rhs.x) return false; if (lhs.y != rhs.y) return false; return true; }; static T distance(const Vec2&a, const Vec2 &b) { return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)); }; T x; T y; }; } #endif /* GPICK_VECTOR2_H_ */ gpick-gpick-0.2.6rc1/source/color_names/000077500000000000000000000000001315430016700201165ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/source/color_names/ColorNames.cpp000066400000000000000000000232031315430016700226640ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ColorNames.h" #include "../Color.h" #include "../Paths.h" #include #include #include #include #include #include using namespace std; struct ColorNameEntry { std::string name; }; struct ColorEntry { Color color; Color original_color; ColorNameEntry* name; }; const int SpaceDivisions = 8; struct ColorNames { std::list names; std::vector colors[SpaceDivisions][SpaceDivisions][SpaceDivisions]; void (*color_space_convert)(const Color* a, Color* b); float (*color_space_distance)(const Color* a, const Color* b); }; ColorNames* color_names_new() { ColorNames* color_names = new ColorNames; color_names->color_space_convert = color_rgb_to_lab_d50; color_names->color_space_distance = color_distance_lch; return color_names; } void color_names_clear(ColorNames *color_names) { for (auto i = color_names->names.begin(); i != color_names->names.end(); i++){ delete *i; } color_names->names.clear(); for (int x = 0; x < SpaceDivisions; x++){ for (int y = 0; y < SpaceDivisions; y++){ for (int z = 0; z < SpaceDivisions; z++){ for (auto i = color_names->colors[x][y][z].begin(); i != color_names->colors[x][y][z].end(); ++i){ delete *i; } color_names->colors[x][y][z].clear(); } } } } static void color_names_strip_spaces(string& string_x, const string& strip_chars) { if (string_x.empty()) return; if (strip_chars.empty()) return; size_t start_index = string_x.find_first_not_of(strip_chars); size_t end_index = string_x.find_last_not_of(strip_chars); if ((start_index == string::npos) || (end_index == string::npos)){ string_x.erase(); return; } string_x = string_x.substr(start_index, (end_index - start_index) + 1); } void color_names_normalize(const Color &color, Color &out) { out.xyz.x = color.xyz.x / 100.0; out.xyz.y = (color.xyz.y + 86.1825) / (86.1825 + 98.2346); out.xyz.z = (color.xyz.z + 107.86) / (107.86 + 94.478); } void color_names_get_color_xyz(ColorNames* color_names, Color* c, int* x1, int* y1, int* z1, int* x2, int* y2, int* z2) { *x1 = clamp_int(int(c->xyz.x / 100 * SpaceDivisions - 0.5), 0, SpaceDivisions - 1); *y1 = clamp_int(int((c->xyz.y + 100) / 200 * SpaceDivisions - 0.5), 0, SpaceDivisions - 1); *z1 = clamp_int(int((c->xyz.z + 100) / 200 * SpaceDivisions - 0.5), 0, SpaceDivisions - 1); *x2 = clamp_int(int(c->xyz.x / 100 * SpaceDivisions + 0.5), 0, SpaceDivisions - 1); *y2 = clamp_int(int((c->xyz.y + 100) / 200 * SpaceDivisions + 0.5), 0, SpaceDivisions - 1); *z2 = clamp_int(int((c->xyz.z + 100) / 200 * SpaceDivisions + 0.5), 0, SpaceDivisions - 1); } static vector* color_names_get_color_list(ColorNames* color_names, Color* c) { int x,y,z; x = clamp_int(int(c->xyz.x / 100 * SpaceDivisions), 0, SpaceDivisions - 1); y = clamp_int(int((c->xyz.y + 100) / 200 * SpaceDivisions), 0, SpaceDivisions - 1); z = clamp_int(int((c->xyz.z + 100) / 200 * SpaceDivisions), 0, SpaceDivisions - 1); return &color_names->colors[x][y][z]; } int color_names_load_from_file(ColorNames* color_names, const char* filename) { float a = 0, b = 0, c = 0; ifstream file(filename, ifstream::in); if (file.is_open()){ string line; stringstream rline (ios::in | ios::out); Color color; string name; while (!(file.eof())){ getline(file, line); if (line.empty()) continue; if (line.at(0) == '!') continue; rline.clear(); rline.str(line); rline >> color.rgb.red >> color.rgb.green >> color.rgb.blue; getline(rline, name); const string strip_chars = " \t,.\n\r"; color_names_strip_spaces(name, strip_chars); string::iterator i(name.begin()); if (i != name.end()){ name[0] = toupper((unsigned char)name[0]); while(++i != name.end()){ *i = tolower((unsigned char)*i); } color_multiply(&color, 1 / 255.0); ColorNameEntry* name_entry = new ColorNameEntry; name_entry->name = name; color_names->names.push_back(name_entry); ColorEntry* color_entry = new ColorEntry; color_entry->name = name_entry; color_names->color_space_convert(&color, &color_entry->color); color_copy(&color, &color_entry->original_color); color_names_get_color_list(color_names, &color_entry->color)->push_back(color_entry); } } file.close(); return 0; } return -1; } void color_names_destroy(ColorNames* color_names) { color_names_clear(color_names); delete color_names; } static void color_names_iterate(ColorNames* color_names, const Color* color, function on_color, function on_expansion) { Color c1; color_names->color_space_convert(color, &c1); int x1, y1, z1, x2, y2, z2; color_names_get_color_xyz(color_names, &c1, &x1, &y1, &z1, &x2, &y2, &z2); char skip_mask[SpaceDivisions][SpaceDivisions][SpaceDivisions]; memset(&skip_mask, 0, sizeof(skip_mask)); /* Search expansion should be from 0 to SpaceDivisions, but this would only increase search time and return * wrong color names when no closely matching color is found. Search expansion is only useful * when color name database is very small (16 colors) */ for (int expansion = 0; expansion < SpaceDivisions - 1; ++expansion){ int x_start = std::max(x1 - expansion, 0), x_end = std::min(x2 + expansion, SpaceDivisions - 1); int y_start = std::max(y1 - expansion, 0), y_end = std::min(y2 + expansion, SpaceDivisions - 1); int z_start = std::max(z1 - expansion, 0), z_end = std::min(z2 + expansion, SpaceDivisions - 1); for (int x_i = x_start; x_i <= x_end; ++x_i){ for (int y_i = y_start; y_i <= y_end; ++y_i){ for (int z_i = z_start; z_i <= z_end; ++z_i){ if (skip_mask[x_i][y_i][z_i]) continue; // skip checked items skip_mask[x_i][y_i][z_i] = 1; for (auto i = color_names->colors[x_i][y_i][z_i].begin(); i != color_names->colors[x_i][y_i][z_i].end(); ++i){ float delta = color_names->color_space_distance(&(*i)->color, &c1); if (!on_color(*i, delta)) return; } } } } if (on_expansion && !on_expansion()) return; } } string color_names_get(ColorNames* color_names, const Color* color, bool imprecision_postfix) { float result_delta = 1e5; ColorEntry* found_color_entry = nullptr; color_names_iterate(color_names, color, [&](ColorEntry *color_entry, float delta){ if (delta < result_delta){ result_delta = delta; found_color_entry = color_entry; } return true; }, [&](){ return found_color_entry == nullptr; // stop further expansion if we have found a match }); if (found_color_entry){ stringstream s; s << found_color_entry->name->name; if (imprecision_postfix) if (result_delta > 0.1) s << " ~"; return s.str(); } return string(""); } void color_names_load(ColorNames *color_names, dynvSystem *params) { uint32_t dictionary_count = 0; struct dynvSystem** dictionaries = dynv_get_dynv_array_wd(params, "color_dictionaries.items", nullptr, 0, &dictionary_count); if (dictionaries){ for (uint32_t i = 0; i < dictionary_count; i++){ bool enable = dynv_get_bool_wd(dictionaries[i], "enable", "false"); if (enable){ bool built_in = dynv_get_bool_wd(dictionaries[i], "built_in", "false"); string path = dynv_get_string_wd(dictionaries[i], "path", ""); if (built_in){ if (path == "built_in_0"){ gchar *tmp; color_names_load_from_file(color_names, tmp = build_filename("color_dictionary_0.txt")); g_free(tmp); } }else{ color_names_load_from_file(color_names, path.c_str()); } } dynv_system_release(dictionaries[i]); } if (dictionaries) delete [] dictionaries; } } void color_names_find_nearest(ColorNames *color_names, const Color &color, size_t count, std::vector> &colors) { multimap found_colors; color_names_iterate(color_names, &color, [&](ColorEntry *color_entry, float delta){ found_colors.insert(pair(delta, color_entry)); return true; }, [&](){ return found_colors.size() < count; }); if (found_colors.size() >= count) colors.resize(count); else colors.resize(found_colors.size()); size_t index = 0; for (auto &item: found_colors){ if (index >= count) break; colors[index++] = pair(item.second->name->name.c_str(), item.second->original_color); } } gpick-gpick-0.2.6rc1/source/color_names/ColorNames.h000066400000000000000000000044011315430016700223300ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_COLOR_NAMES_COLOR_NAMES_H_ #define GPICK_COLOR_NAMES_COLOR_NAMES_H_ #include "../Color.h" #include "../DynvHelpers.h" #include #include struct ColorNames; ColorNames *color_names_new(); void color_names_clear(ColorNames *color_names); void color_names_load(ColorNames *color_names, dynvSystem *params); int color_names_load_from_file(ColorNames *color_names, const char *filename); void color_names_destroy(ColorNames *color_names); std::string color_names_get(ColorNames *color_names, const Color *color, bool imprecision_postfix); void color_names_find_nearest(ColorNames *color_names, const Color &color, size_t count, std::vector> &colors); #endif /* GPICK_COLOR_NAMES_COLOR_NAMES_H_ */ gpick-gpick-0.2.6rc1/source/color_names/SConscript000066400000000000000000000005021315430016700221250ustar00rootroot00000000000000#!/usr/bin/env python import os import sys Import('*') local_env = env.Clone() if not local_env.GetOption('clean') and not env['TOOLCHAIN'] == 'msvc': local_env.ParseConfig('pkg-config --cflags --libs $GTK_PC') sources = local_env.Glob('*.cpp') objects = local_env.StaticObject(source = [sources]) Return('objects') gpick-gpick-0.2.6rc1/source/cssparser/000077500000000000000000000000001315430016700176225ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/source/cssparser/SConscript000066400000000000000000000012211315430016700216300ustar00rootroot00000000000000#!/usr/bin/env python import os import sys Import('*') local_env = env.Clone() local_env.PrependUnique(CPPPATH = ['.']) local_env.Append(CPPDEFINES = ['YY_NO_UNISTD_H']) if not env['PREBUILD_GRAMMAR']: parser = local_env.Lemon('css_grammar.y') lexer = local_env.Flex('css_lex.l') else: parser = [File('css_grammar.c'), File('css_grammar.h')] lexer = [File('css_lex.cpp'), File('css_lex.h')] generated_files = Flatten([parser, lexer]) sources = local_env.Glob('*.cpp') objects = local_env.StaticObject( source = [sources]) if not env['PREBUILD_GRAMMAR']: Depends(parser, lexer) Depends(objects, parser) Return('objects', 'generated_files') gpick-gpick-0.2.6rc1/source/cssparser/css_grammar.y000066400000000000000000000214171315430016700223170ustar00rootroot00000000000000 %include { #include #include "css_lex.h" #include using namespace css_parser; } %extra_argument { parse_parm_s *parm } %name css_parse %token_prefix CSS_TOKEN_ %token_type {css_yystype} %default_type {css_yystype} %left S. %right IDENT. %left CDO CDC. %left INCLUDES. %left DASHMATCH. %left STRING. %left INVALID. %left HEXCOLOR. %left SEMICOLON COMMA LBRACE RBRACE HASH GREATER PLUS CLPARENTH RBRACK SLASH. %nonassoc DOT COLON LBRACK ASTERISK. %left IMPORT_SYM. %left PAGE_SYM. %left MEDIA_SYM. %left CHARSET_SYM. %left IMPORTANT_SYM. %left FONTFACE_SYM. %left NAMESPACE_SYM. %left EMS EXS LENGTH ANGLE TIME FREQ DIMENSION PERCENTAGE NUMBER. %left FUNCTION. %left URI. %type property {css_property*} %type expr {css_base*} %type term {css_base*} %type hexcolor {css_hex*} %type function {css_function*} %type declaration {css_property*} %type selectors {css_selectors*} %type maybe_declarations {css_properties*} %type ruleset {css_ruleset*} %type declarations {css_properties*} %type declaration_list {css_properties*} %type selector {css_selector*} %type universal_selector {css_simple_selector*} %type type_selector {css_simple_selector*} %type class_selector {css_simple_selector*} %type id_selector {css_simple_selector*} %type simple_selectors {css_selector*} %type pseudo_selector {css_simple_selector*} %type attribute_selector {css_simple_selector*} %type simple_selector {css_selector*} %syntax_error { printf("Error: %s\n", yyTokenName[yymajor]); } %start_symbol stylesheet stylesheet ::= maybe_charset maybe_sgml maybe_rules. maybe_space ::= . maybe_space ::= maybe_space S. space ::= S. space ::= space S. maybe_sgml ::= . maybe_sgml ::= maybe_sgml CDO. maybe_sgml ::= maybe_sgml CDC. maybe_sgml ::= maybe_sgml S. maybe_charset ::= . maybe_charset ::= CHARSET_SYM maybe_space STRING maybe_space SEMICOLON. maybe_rules ::= . maybe_rules ::= maybe_rules rule maybe_sgml. rule ::= import. rule ::= ruleset. rule ::= media. rule ::= page. medium ::= IDENT maybe_space. maybe_medium ::= . maybe_medium ::= medium. maybe_medium ::= maybe_medium COMMA maybe_space medium. uri_or_string ::= URI. uri_or_string ::= STRING. import ::= IMPORT_SYM maybe_space uri_or_string maybe_space maybe_medium SEMICOLON. import ::= IMPORT_SYM error SEMICOLON. ruleset(R) ::= selectors(A) block_start maybe_declarations(B) block_end. { css_ruleset *ruleset = new(parm) css_ruleset(); ruleset->setSelectors(A->selectors_); if (B) ruleset->addProperties(B); R = ruleset; parm->page->addRuleset(ruleset); } ruleset(R) ::= selectors(A) block_start space maybe_declarations(B) block_end. { css_ruleset *ruleset = new(parm) css_ruleset(); ruleset->setSelectors(A->selectors_); if (B) ruleset->addProperties(B); R = ruleset; parm->page->addRuleset(ruleset); } media_list ::= media_list COMMA maybe_space medium. media_list ::= medium. media ::= MEDIA_SYM maybe_space media_list block_start maybe_space maybe_declarations block_end. media ::= MEDIA_SYM maybe_space block_start maybe_space maybe_declarations block_end. page ::= PAGE_SYM maybe_space maybe_pseudo_page block_start maybe_space maybe_declarations block_end. maybe_pseudo_page ::= . maybe_pseudo_page ::= COLON IDENT maybe_space. maybe_declarations(R) ::= . { R = 0; } maybe_declarations(R) ::= declarations(A). { R = A; } universal_selector(R) ::= ASTERISK(A). { R = new(parm) css_simple_selector(A.string); } type_selector(R) ::= IDENT(A). { R = new(parm) css_simple_selector(A.string); } class_selector(R) ::= DOT IDENT(A). { R = new(parm) css_simple_selector(A.string); } id_selector(R) ::= HASH IDENT(A). { R = new(parm) css_simple_selector(A.string); } attribute_selector(R) ::= LBRACK maybe_space IDENT(A) maybe_space RBRACK. { R = new(parm) css_simple_selector(A.string); } pseudo_selector(R) ::= COLON IDENT(A). { R = new(parm) css_simple_selector(A.string); } pseudo_selector ::= COLON FUNCTION maybe_space CLPARENTH. pseudo_selector ::= COLON FUNCTION maybe_space IDENT maybe_space CLPARENTH. pseudo_selector(R) ::= COLON COLON IDENT(A). { R = new(parm) css_simple_selector(A.string); } simple_selectors(R) ::= simple_selectors(A) id_selector(B). { A->addSimpleSelector(B); R = A; } simple_selectors(R) ::= simple_selectors(A) class_selector(B). { A->addSimpleSelector(B); R = A; } simple_selectors(R) ::= simple_selectors(A) attribute_selector(B). { A->addSimpleSelector(B); R = A; } simple_selectors(R) ::= simple_selectors(A) pseudo_selector(B). { A->addSimpleSelector(B); R = A; } simple_selectors(R) ::= id_selector(A). { css_selector* selector = new(parm) css_selector(); selector->addSimpleSelector(A); R = selector; } simple_selectors(R) ::= class_selector(A). { css_selector* selector = new(parm) css_selector(); selector->addSimpleSelector(A); R = selector; } simple_selectors(R) ::= attribute_selector(A). { css_selector* selector = new(parm) css_selector(); selector->addSimpleSelector(A); R = selector; } simple_selectors(R) ::= pseudo_selector(A). { css_selector* selector = new(parm) css_selector(); selector->addSimpleSelector(A); R = selector; } simple_selector(R) ::= type_selector(A). { css_selector* selector = new(parm) css_selector(); selector->addSimpleSelector(A); R = selector; } simple_selector(R) ::= type_selector(A) simple_selectors(B). { B->prependSimpleSelector(A); R = B; } simple_selector(R) ::= universal_selector(A). { css_selector* selector = new(parm) css_selector(); selector->addSimpleSelector(A); R = selector; } simple_selector(R) ::= universal_selector(A) simple_selectors(B). { B->prependSimpleSelector(A); R = B; } simple_selector(R) ::= simple_selectors(A). { R = A; } selector(R) ::= simple_selector(A). { R = A; } selector(R) ::= selector(A) combinator simple_selector(B). { A->addSelector(B); R = A; } selector(R) ::= selector(A) space simple_selector(B). { A->addSelector(B); R = A; } selector(R) ::= selector(A) space combinator simple_selector(B). { A->addSelector(B); R = A; } selectors(R) ::= selector(A). { css_selectors* selectors = new(parm) css_selectors(); selectors->addSelector(A); R = selectors; } selectors(R) ::= selector(A) space. { css_selectors* selectors = new(parm) css_selectors(); selectors->addSelector(A); R = selectors; } selectors(R) ::= selectors(A) COMMA maybe_space selector(B). { A->addSelector(B); R = A; } selectors(R) ::= selectors(A) COMMA maybe_space selector(B) space. { A->addSelector(B); R = A; } combinator ::= PLUS maybe_space. combinator ::= GREATER maybe_space. declaration_list(R) ::= declaration(A) SEMICOLON maybe_space. { css_properties* properties = new(parm) css_properties(); if (A) properties->addProperty(A); R = properties; } declaration_list(R) ::= declaration_list(A) declaration(B) SEMICOLON maybe_space. { if (B) A->addProperty(B); R = A; } declarations(R) ::= declaration(A). { css_properties* properties = new(parm) css_properties(); if (A) properties->addProperty(A); R = properties; } declarations(R) ::= declaration_list(A) declaration(B). { if (B) A->addProperty(B); R = A; } declarations(R) ::= declaration_list(A). { R = A; } declaration(R) ::= property(A) COLON maybe_space expr(B) maybe_prio. { if (strcmp(A->name_, "color") == 0 || strcmp(A->name_, "background-color") == 0){ A->addValue(B); R = A; }else{ R = 0; } } property(R) ::= IDENT(A) maybe_space. { R = new(parm) css_property(A.string);} maybe_prio ::= . maybe_prio ::= IMPORTANT_SYM maybe_space. expr(R) ::= term(A). { R = A; } expr(R) ::= expr(A) term(B). { R = A; R = B; } expr(R) ::= expr(A) operator term(C). { R = A; R = C; } unary_operator ::= MINUS. unary_operator ::= PLUS. maybe_unary_operator ::= . maybe_unary_operator ::= unary_operator. operator ::= SLASH maybe_space. operator ::= COMMA maybe_space. term(R) ::= maybe_unary_operator NUMBER(A) maybe_space. { R = new(parm) css_number(A.number); } term(R) ::= maybe_unary_operator PERCENTAGE maybe_space. { R = 0; } term(R) ::= maybe_unary_operator LENGTH maybe_space. { R = 0; } term(R) ::= maybe_unary_operator EMS maybe_space. { R = 0; } term(R) ::= maybe_unary_operator EXS maybe_space. { R = 0; } term(R) ::= maybe_unary_operator ANGLE maybe_space. { R = 0; } term(R) ::= maybe_unary_operator TIME maybe_space. { R = 0; } term(R) ::= maybe_unary_operator FREQ maybe_space. { R = 0; } term(R) ::= STRING(A) maybe_space. { R = new(parm) css_string(A.string); } term(R) ::= IDENT(A) maybe_space. { R = new(parm) css_string(A.string); } term(R) ::= URI maybe_space. { R = 0; } term(R) ::= HEXCOLOR(A) maybe_space. { R = new(parm) css_hex(A.string); } term(R) ::= function(A) maybe_space. { R = A; } function(R) ::= FUNCTION(A) maybe_space expr(B) CLPARENTH maybe_space. { css_function* function = new(parm) css_function(A.string); function->addArgument(B); R = function; } block_start ::= LBRACE. block_end ::= RBRACE. block_end ::= error RBRACE. gpick-gpick-0.2.6rc1/source/cssparser/css_grammar_wrap.cpp000066400000000000000000000031161315430016700236560ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #undef NDEBUG #define NEVER(a) false #include gpick-gpick-0.2.6rc1/source/cssparser/css_lex.l000066400000000000000000000136561315430016700214520ustar00rootroot00000000000000 %option reentrant bison-bridge %option noyywrap nounput batch %option never-interactive %option prefix="css_" %option case-insensitive %option stack %option 8bit %option nounistd %option noyyalloc noyyrealloc noyyfree %{ #include "css_grammar.h" #include #include "memory_manager.h" using namespace std; #define YY_USER_ACTION { yyextra->last_column += yyleng; yyextra->position += yyleng; } char* css_strdup(char* x, void * yyscanner); %} h [0-9a-f] nonascii [\200-\377] unicode \\{h}{1,6}(\r\n|[ \t\r\n\f])? escape {unicode}|\\[^\r\n\f0-9a-f] nmstart [_a-z]|{nonascii}|{escape} nmchar [_a-z0-9-]|{nonascii}|{escape} string1 \"([^\n\r\f\\"]|\\{nl}|{escape})*\" string2 \'([^\n\r\f\\']|\\{nl}|{escape})*\' invalid1 \"([^\n\r\f\\"]|\\{nl}|{escape})* invalid2 \'([^\n\r\f\\']|\\{nl}|{escape})* comment_begin "/*" comment_end "*/" ident -?{nmstart}{nmchar}* name {nmchar}+ num [0-9]+|[0-9]*"."[0-9]+ string {string1}|{string2} invalid {invalid1}|{invalid2} url ([!#$%&*-~]|{nonascii}|{escape})* s [ \t\r\n\f]+ w {s}? ws [ \t]+ nl \n|\r\n|\r|\f hexcolor {h}{3}|{h}{6} A a|\\0{0,4}(41|61)(\r\n|[ \t\r\n\f])? B b|\\0{0,4}(42|62)(\r\n|[ \t\r\n\f])? C c|\\0{0,4}(43|63)(\r\n|[ \t\r\n\f])? D d|\\0{0,4}(44|64)(\r\n|[ \t\r\n\f])? E e|\\0{0,4}(45|65)(\r\n|[ \t\r\n\f])? F f|\\0{0,4}(46|66)(\r\n|[ \t\r\n\f])? G g|\\0{0,4}(47|67)(\r\n|[ \t\r\n\f])?|\\g H h|\\0{0,4}(48|68)(\r\n|[ \t\r\n\f])?|\\h I i|\\0{0,4}(49|69)(\r\n|[ \t\r\n\f])?|\\i J j|\\0{0,4}(4a|6a)(\r\n|[ \t\r\n\f])?|\\j K k|\\0{0,4}(4b|6b)(\r\n|[ \t\r\n\f])?|\\k L l|\\0{0,4}(4c|6c)(\r\n|[ \t\r\n\f])?|\\l M m|\\0{0,4}(4d|6d)(\r\n|[ \t\r\n\f])?|\\m N n|\\0{0,4}(4e|6e)(\r\n|[ \t\r\n\f])?|\\n O o|\\0{0,4}(4f|6f)(\r\n|[ \t\r\n\f])?|\\o P p|\\0{0,4}(50|70)(\r\n|[ \t\r\n\f])?|\\p Q q|\\0{0,4}(51|71)(\r\n|[ \t\r\n\f])?|\\q R r|\\0{0,4}(52|72)(\r\n|[ \t\r\n\f])?|\\r S s|\\0{0,4}(53|73)(\r\n|[ \t\r\n\f])?|\\s T t|\\0{0,4}(54|74)(\r\n|[ \t\r\n\f])?|\\t U u|\\0{0,4}(55|75)(\r\n|[ \t\r\n\f])?|\\u V v|\\0{0,4}(56|76)(\r\n|[ \t\r\n\f])?|\\v W w|\\0{0,4}(57|77)(\r\n|[ \t\r\n\f])?|\\w X x|\\0{0,4}(58|78)(\r\n|[ \t\r\n\f])?|\\x Y y|\\0{0,4}(59|79)(\r\n|[ \t\r\n\f])?|\\y Z z|\\0{0,4}(5a|7a)(\r\n|[ \t\r\n\f])?|\\z %x comment %x sgml %% %{ CSS_LOCATION_STEP (*yyextra); %} {nl}+ {CSS_LOCATION_LINES (*yyextra, yyleng); CSS_LOCATION_STEP (*yyextra); return CSS_TOKEN_S;} {ws} {CSS_LOCATION_STEP (*yyextra); return CSS_TOKEN_S;} {comment_begin} { yy_push_state(comment, yyscanner); } {nl}+ {CSS_LOCATION_LINES (*yyextra, yyleng); CSS_LOCATION_STEP (*yyextra); } [^*\n\r\f]* /* eat up comments */ "*"+[^*/\n\r\f]* /* eat up '*'s not followed by '/'s */ {comment_end} { yy_pop_state(yyscanner); } "" { yy_pop_state(yyscanner); } "~=" {return CSS_TOKEN_INCLUDES;} "|=" {return CSS_TOKEN_DASHMATCH;} {string} {yylval->string = css_strdup(yytext, yyscanner); return CSS_TOKEN_STRING;} {invalid} {return CSS_TOKEN_INVALID; /* unclosed string */} {ident} {yylval->string = css_strdup(yytext, yyscanner); return CSS_TOKEN_IDENT; } "#"{hexcolor} {yylval->string = css_strdup(yytext, yyscanner); return CSS_TOKEN_HEXCOLOR;} "@import" {return CSS_TOKEN_IMPORT_SYM;} "@page" {return CSS_TOKEN_PAGE_SYM;} "@media" {return CSS_TOKEN_MEDIA_SYM;} "@font-face" {return CSS_TOKEN_FONTFACE_SYM;} "@charset " {return CSS_TOKEN_CHARSET_SYM;} "@namespace" {return CSS_TOKEN_NAMESPACE_SYM;} "!"({w}|{comment_begin})*{I}{M}{P}{O}{R}{T}{A}{N}{T} {return CSS_TOKEN_IMPORTANT_SYM;} {num}{E}{M} {return CSS_TOKEN_EMS;} {num}{E}{X} {return CSS_TOKEN_EXS;} {num}{P}{X} {return CSS_TOKEN_LENGTH;} {num}{C}{M} {return CSS_TOKEN_LENGTH;} {num}{M}{M} {return CSS_TOKEN_LENGTH;} {num}{I}{N} {return CSS_TOKEN_LENGTH;} {num}{P}{T} {return CSS_TOKEN_LENGTH;} {num}{P}{C} {return CSS_TOKEN_LENGTH;} {num}{D}{E}{G} {return CSS_TOKEN_ANGLE;} {num}{R}{A}{D} {return CSS_TOKEN_ANGLE;} {num}{G}{R}{A}{D} {return CSS_TOKEN_ANGLE;} {num}{M}{S} {return CSS_TOKEN_TIME;} {num}{S} {return CSS_TOKEN_TIME;} {num}{H}{Z} {return CSS_TOKEN_FREQ;} {num}{K}{H}{Z} {return CSS_TOKEN_FREQ;} {num}{ident} {return CSS_TOKEN_DIMENSION;} {num}% {yylval->number = strtod(yytext, 0); return CSS_TOKEN_PERCENTAGE;} {num} {yylval->number = strtod(yytext, 0); return CSS_TOKEN_NUMBER;} {U}{R}{L}"("{w}{string}{w}")" {return CSS_TOKEN_URI;} {U}{R}{L}"("{w}{url}{w}")" {return CSS_TOKEN_URI;} {ident}"(" {yylval->string = css_strdup(yytext, yyscanner); return CSS_TOKEN_FUNCTION;} "-" {return CSS_TOKEN_MINUS;} "+" {return CSS_TOKEN_PLUS;} "/" {return CSS_TOKEN_SLASH;} "*" {return CSS_TOKEN_ASTERISK;} "#" {return CSS_TOKEN_HASH;} "{" {return CSS_TOKEN_LBRACE;} "}" {return CSS_TOKEN_RBRACE;} "[" {return CSS_TOKEN_LBRACK;} "]" {return CSS_TOKEN_RBRACK;} "." {return CSS_TOKEN_DOT;} "," {return CSS_TOKEN_COMMA;} ":" {return CSS_TOKEN_COLON;} ";" {return CSS_TOKEN_SEMICOLON;} ")" {return CSS_TOKEN_CLPARENTH;} ">" {return CSS_TOKEN_GREATER;} . {printf("Unknown char\n"); return *yytext;} %% void * css_alloc (size_t bytes, void* yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return memory_alloc (yyextra->memory, bytes); } void * css_realloc (void * ptr, size_t bytes, void* yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return memory_realloc (yyextra->memory, ptr, bytes); } void css_free (void * ptr, void * yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; memory_free(yyextra->memory, ptr); } char* css_strdup(char* x, void * yyscanner){ uint32_t size=strlen(x)+1; char* r=(char*)css_alloc(size, yyscanner); memcpy(r, x, size); return r; } gpick-gpick-0.2.6rc1/source/cssparser/css_parser.cpp000066400000000000000000000144161315430016700225000ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include "css_parser.h" #include "css_lex.h" #include using namespace std; namespace css_parser{ css_base::css_base(){ } void css_base::polymorphic(){ } void* css_base::operator new(size_t num_bytes, parse_parm* parm){ return memory_alloc(parm->memory, num_bytes); } void css_base::operator delete(void* base, parse_parm* parm){ memory_free(parm->memory, base); } css_property::css_property(const char* name){ name_ = name; } void css_property::addValue(css_base* value){ values_.push_back(value); } css_simple_selector::css_simple_selector(const char* name){ name_ = name; } css_selector::css_selector(){ } void css_selector::addSimpleSelector(css_simple_selector* simple_selector){ simple_selectors_.push_back(simple_selector); } void css_selector::addSelector(css_selector* selector){ for (list::iterator i = selector->simple_selectors_.begin(); i != selector->simple_selectors_.end(); i++){ simple_selectors_.push_back(*i); } } void css_selector::prependSimpleSelector(css_simple_selector* simple_selector){ simple_selectors_.push_front(simple_selector); } css_selectors::css_selectors(){ } void css_selectors::addSelector(css_selector* selector){ selectors_.push_back(selector); } css_ruleset::css_ruleset(){ } void css_ruleset::addSelector(css_selector* selector){ selectors_.push_back(selector); } void css_ruleset::setSelectors(std::list &selectors){ selectors_ = selectors; } void css_ruleset::addProperty(css_property* property){ properties_.push_back(property); } void css_ruleset::addProperties(css_properties* properties){ for (list::iterator i = properties->properties_.begin(); i != properties->properties_.end(); i++){ properties_.push_back(*i); } } css_file::css_file(){ } void css_file::addRuleset(css_ruleset* ruleset){ rulesets_.push_back(ruleset); } css_function::css_function(const char* name){ name_ = name; } void css_function::addArgument(css_base* argument){ arguments_.push_back(argument); } css_hex::css_hex(uint32_t value){ value_ = value; } css_hex::css_hex(const char *value){ uint32_t x; std::stringstream ss; ss << (value + 1); ss << hex; ss >> x; value_ = x; if (strlen(value) == 4){ value_ = (value_ & 0xf00) << 12 | (value_ & 0xf00) << 8 | (value_ & 0x0f0) << 8 | (value_ & 0x0f0) << 4 | (value_ & 0x00f) << 4 | (value_ & 0x00f) << 0; } } css_number::css_number(double value){ value_ = value; } css_percentage::css_percentage(double value){ value_ = value; } css_string::css_string(const char* value){ value_ = value; } css_properties::css_properties(){ } void css_properties::addProperty(css_property* property){ properties_.push_back(property); } } using namespace css_parser; void *css_parseAlloc(void *(*mallocProc)(size_t)); void css_parseFree(void *p, void (*freeProc)(void*)); void css_parse(void *yyp, int yymajor, css_yystype yyminor, parse_parm*); void print_rec(css_base *node){ css_file *file; css_ruleset *ruleset; css_selector *selector; css_property *property; css_simple_selector *simple_selector; if ((file = dynamic_cast(node))){ printf("file\n"); for (list::iterator i = file->rulesets_.begin(); i != file->rulesets_.end(); i++){ print_rec(*i); } }else if ((ruleset = dynamic_cast(node))){ if (ruleset->properties_.begin() == ruleset->properties_.end()) return; printf("ruleset\n"); for (list::iterator i = ruleset->selectors_.begin(); i != ruleset->selectors_.end(); i++){ print_rec(*i); } for (list::iterator i = ruleset->properties_.begin(); i != ruleset->properties_.end(); i++){ print_rec(*i); } printf("\n"); }else if ((selector = dynamic_cast(node))){ for (list::iterator i = selector->simple_selectors_.begin(); i != selector->simple_selectors_.end(); i++){ print_rec(*i); } printf("-> "); }else if ((simple_selector = dynamic_cast(node))){ printf("%s ", simple_selector->name_); }else if ((property = dynamic_cast(node))){ printf("%s = %06x, ", property->name_, ((css_hex*)*property->values_.begin())->value_); } } int parse_file(const char *filename){ FILE* f = fopen(filename, "rt"); yyscan_t scanner; css_yystype stype; parse_parm pp; struct Memory* memory = memory_new(); pp.memory = memory; pp.page = new(&pp) css_file; css_lex_init_extra(&pp, &scanner); css_set_in(f, scanner); css_restart(f, scanner); void *parser = css_parseAlloc(malloc); int token_id; while( (token_id = css_lex(&stype, scanner)) != 0){ css_parse(parser, token_id, stype, &pp); } css_parseFree(parser, free); css_lex_destroy(scanner); print_rec(pp.page); memory_destroy(memory); fclose(f); printf("\n"); return 1; } gpick-gpick-0.2.6rc1/source/cssparser/css_parser.h000066400000000000000000000125771315430016700221530ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CSS_PARSER_H #define CSS_PARSER_H #ifndef _MSC_VER #include #endif #include #include #include #include "memory_manager.h" typedef struct parse_parm_s parse_parm; namespace css_parser { class css_file; class css_base; } typedef struct parse_parm_s { css_parser::css_file *page; struct Memory* memory; uint32_t first_line; uint32_t first_column; uint32_t last_line; uint32_t last_column; uint32_t position; }parse_parm; int parse(FILE* f, int *result); #define YY_EXTRA_TYPE parse_parm* #ifndef YYSTYPE typedef union css_yystype{ css_parser::css_base *base; char* string; uint32_t number; } css_yystype; # define YYSTYPE css_yystype # define YYSTYPE_IS_TRIVIAL 1 # define YYSTYPE_IS_DECLARED 1 #endif /* extern YYSTYPE yylval; */ //YYSTYPE yylval; /*#define YY_EXTRA_TYPE parse_parm* */ /* Initialize LOC. */ # define CSS_LOCATION_RESET(Loc) \ (Loc).first_column = (Loc).first_line = 1; \ (Loc).last_column = (Loc).last_line = 1; \ (Loc).position = 0; /* Advance of NUM lines. */ # define CSS_LOCATION_LINES(Loc, Num) \ (Loc).last_column = 1; \ (Loc).last_line += Num; /* Restart: move the first cursor to the last position. */ # define CSS_LOCATION_STEP(Loc) \ (Loc).first_column = (Loc).last_column; \ (Loc).first_line = (Loc).last_line; /* Output LOC on the stream OUT. */ # define CSS_LOCATION_PRINT(Out, Loc) \ if ((Loc).first_line != (Loc).last_line) \ fprintf(Out, "%d.%d-%d.%d", \ (Loc).first_line, (Loc).first_column, \ (Loc).last_line, (Loc).last_column - 1); \ else if ((Loc).first_column < (Loc).last_column - 1) \ fprintf(Out, "%d.%d-%d", (Loc).first_line, \ (Loc).first_column, (Loc).last_column - 1); \ else \ fprintf(Out, "%d.%d", (Loc).first_line, (Loc).first_column) namespace css_parser { class css_base{ public: css_base(); void* operator new(size_t num_bytes, parse_parm* parm); void operator delete(void* base, parse_parm* parm); virtual void polymorphic(); }; class css_property: public css_base{ public: const char* name_; std::list values_; css_property(const char* name); void addValue(css_base* value); }; class css_properties: public css_base{ public: std::list properties_; css_properties(); void addProperty(css_property* property); }; class css_simple_selector: public css_base{ public: const char* name_; css_simple_selector(const char* name); }; class css_selector: public css_base{ public: std::list simple_selectors_; css_selector(); void addSimpleSelector(css_simple_selector* simple_selector); void addSelector(css_selector* selector); void prependSimpleSelector(css_simple_selector* simple_selector); }; class css_selectors: public css_base{ public: std::list selectors_; css_selectors(); void addSelector(css_selector* selector); }; class css_ruleset: public css_base{ public: std::list selectors_; std::list properties_; css_ruleset(); void addSelector(css_selector* selector); void setSelectors(std::list &selectors); void addProperty(css_property* property); void addProperties(css_properties* properties); }; class css_file: public css_base{ public: std::list rulesets_; css_file(); void addRuleset(css_ruleset* ruleset); }; class css_function: public css_base{ public: const char* name_; std::list arguments_; css_function(const char* name); void addArgument(css_base* argument); }; class css_hex: public css_base{ public: uint32_t value_; css_hex(uint32_t value); css_hex(const char *value); }; class css_number: public css_base{ public: double value_; css_number(double value); }; class css_percentage: public css_base{ public: double value_; css_percentage(double value); }; class css_string: public css_base{ public: const char* value_; css_string(const char* value); }; } int parse_file(const char *filename); #endif gpick-gpick-0.2.6rc1/source/cssparser/memory_manager.cpp000066400000000000000000000130661315430016700233360ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "memory_manager.h" #include #include #include static struct MemoryPage* memory_page_new(uint32_t total_size, uint32_t atom_size){ uint32_t atoms = total_size / atom_size; struct MemoryPage* page=(struct MemoryPage*)malloc(sizeof(struct MemoryPage) + atoms + total_size); page->total_size = atoms; page->total_free = atoms; page->atom_size = atom_size; page->map = ((uint8_t*)page) + sizeof(struct MemoryPage); page->raw_memory = ((uint8_t*)page) + sizeof(struct MemoryPage) + atoms; memset(page->map, 1, atoms); page->next_page=0; return page; } static void memory_page_destroy(struct MemoryPage* page){ free(page); } static void* memory_page_alloc(struct MemoryPage* page, uint32_t alloc_size){ register uint32_t size = (alloc_size + sizeof(uint32_t) + (page->atom_size-1))/page->atom_size; if (size>page->total_free) return 0; register uint32_t space=0; for (register uint32_t i=0; itotal_size; ++i){ space=(space+1)*page->map[i]; if (space == size){ memset(page->map+(i+1-size), 0, size); page->total_free-=size; uint8_t *mem_ptr = page->raw_memory+(i+1-size)*page->atom_size; ((uint32_t*)mem_ptr)[0] = alloc_size; return mem_ptr+sizeof(uint32_t); } } return 0; } bool memory_page_free(struct MemoryPage* page, void* mem_ptr){ if ((mem_ptr >= page->raw_memory) && (mem_ptr < page->raw_memory + page->total_size * page->atom_size )){ uint32_t atom_i = (uintptr_t(mem_ptr) - uintptr_t(page->raw_memory) - sizeof(uint32_t)) / page->atom_size; uint32_t atom_count = ((((uint32_t*)mem_ptr)-1)[0] + sizeof(uint32_t) + (page->atom_size-1))/page->atom_size; memset(page->map+atom_i, 1, atom_count); page->total_free+=atom_count; return true; } return false; } static uint32_t high_bit(uint32_t x){ register uint32_t bit=32; register uint32_t mask=(1<<(bit-1)); while (!(x & mask)){ mask>>=1; --bit; if (!mask) break; } return bit; } void* memory_alloc(struct Memory* memory, uint32_t size){ struct MemoryPage* page=memory->pages; void* ptr; struct { int32_t atom_size; int32_t memory_size; }segments[]={ {1<<5, (1<<5)*4096}, // 0 {1<<5, (1<<5)*4096}, // 1 {1<<5, (1<<5)*4096}, // 2 {1<<5, (1<<5)*4096}, // 3 {1<<5, (1<<5)*4096}, // 4 {1<<5, (1<<5)*4096}, // 5 {1<<5, (1<<5)*4096}, // 6 {1<<5, (1<<5)*4096}, // 7 {1<<5, (1<<5)*4096}, // 8 {1<<7, (1<<7)*1024}, // 9 {1<<7, (1<<7)*1024}, // 10 {1<<7, (1<<7)*1024}, // 11 {1<<7, (1<<7)*1024}, // 12 {1<<8, (1<<8)*512}, // 13 {1<<8, (1<<8)*512}, // 14 {1<<8, (1<<8)*512}, // 15 {1<<12, (1<<12)*256}, // 16 {1<<12, (1<<12)*256}, // 17 {1<<12, (1<<12)*256}, // 18 {1<<12, (1<<12)*256}, // 19 // 1MB and more }; uint32_t highbit = high_bit(size); if (page){ do{ if (page->atom_size != segments[highbit].atom_size) continue; if ((ptr = memory_page_alloc(page, size))) return ptr; }while ((page = page->next_page)); } //printf("new page: %d %d %d %d\n", segments[highbit].memory_size, segments[highbit].atom_size, highbit, size); page = memory_page_new( segments[highbit].memory_size, segments[highbit].atom_size); page->next_page = memory->pages; memory->pages = page; if ((ptr = memory_page_alloc(page, size))) return ptr; exit(0); return 0; } void* memory_realloc(struct Memory* memory, void* mem_ptr, uint32_t size){ //printf("r: %d\n", size); void* newptr=memory_alloc(memory, size); memcpy(newptr, mem_ptr, (((uint32_t*)mem_ptr)-1)[0]); memory_free(memory, mem_ptr); return newptr; } void memory_free(struct Memory* memory, void* mem_ptr){ struct MemoryPage* page=memory->pages; if (page){ do{ if (memory_page_free(page, mem_ptr)) return; }while ((page = page->next_page)); } } struct Memory* memory_new(){ struct Memory* memory=(struct Memory*)malloc(sizeof(struct Memory)); memory->pages=0; return memory; } void memory_destroy(struct Memory* memory){ struct MemoryPage* page=memory->pages; struct MemoryPage* tmp; while (page){ tmp=page; page=page->next_page; memory_page_destroy(tmp); } free(memory); } gpick-gpick-0.2.6rc1/source/cssparser/memory_manager.h000066400000000000000000000042041315430016700227750ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef MEMORY_MANAGER_H #define MEMORY_MANAGER_H #ifndef _MSC_VER #include #endif #include struct MemoryPage; struct MemoryPage{ uint32_t total_size; uint32_t total_free; uint32_t atom_size; struct MemoryPage* next_page; uint8_t *map; uint8_t *raw_memory; }; struct Memory{ struct MemoryPage* pages; }; struct Memory* memory_new(); void memory_destroy(struct Memory* memory); void* memory_alloc(struct Memory* mem, uint32_t size); void memory_free(struct Memory* mem, void* mem_ptr); void* memory_realloc(struct Memory* memory, void* mem_ptr, uint32_t size); #endif /* MEMORY_MANAGER_H */ gpick-gpick-0.2.6rc1/source/dbus/000077500000000000000000000000001315430016700165525ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/source/dbus/Control.cpp000066400000000000000000000175121315430016700207040ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Control.h" #ifndef WIN32 #include "DbusInterface.h" #include using namespace std; namespace dbus { class Control::Impl { public: Control *m_decl; GDBusObjectManagerServer *m_manager; guint m_bus_id; Impl(Control *decl): m_decl(decl), m_manager(nullptr), m_bus_id(0) { } void ownName() { m_bus_id = g_bus_own_name(G_BUS_TYPE_SESSION, "org.gpick", GBusNameOwnerFlags(G_BUS_NAME_OWNER_FLAGS_REPLACE), (GBusAcquiredCallback)on_bus_acquired, (GBusNameAcquiredCallback)on_name_acquired, (GBusNameLostCallback)on_name_lost, this, nullptr); } void unownName() { g_bus_unown_name(m_bus_id); m_bus_id = 0; } GDBusObjectManager* getManager() { GDBusObjectManager *manager; GError *error = nullptr; manager = gpick_object_manager_client_new_for_bus_sync(G_BUS_TYPE_SESSION, G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_NONE, "org.gpick", "/org/gpick", nullptr, &error); if (manager == nullptr) { cerr << "Error getting object manager client: " << error->message << endl; g_error_free (error); return 0; } return manager; } bool activateFloatingPicker(const std::string &converter_name) { GDBusObjectManager *manager = getManager(); if (!manager) return false; GError *error = nullptr; GDBusInterface *interface = g_dbus_object_manager_get_interface(manager, "/org/gpick/Control", "org.gpick.Control"); bool result = false; if (interface){ if (!gpick_control_call_activate_floating_picker_sync(GPICK_CONTROL(interface), converter_name.c_str(), nullptr, &error)){ cerr << "Error calling \"Control.ActivateFloatingPicker\": " << error->message << endl; g_error_free (error); }else result = true; g_object_unref(interface); } g_object_unref(manager); return result; } bool checkIfRunning() { GDBusObjectManager *manager = getManager(); if (!manager) return false; GError *error = nullptr; GDBusInterface *interface = g_dbus_object_manager_get_interface(manager, "/org/gpick/Control", "org.gpick.Control"); bool result = false; if (interface){ if (!gpick_control_call_check_if_running_sync(GPICK_CONTROL(interface), nullptr, &error)){ cerr << "Error calling \"Control.CheckIfRunning\": " << error->message << endl; g_error_free (error); }else result = true; g_object_unref(interface); } g_object_unref(manager); return result; } bool singleInstanceActivate() { GDBusObjectManager *manager = getManager(); if (!manager) return false; GError *error = nullptr; GDBusInterface *interface = g_dbus_object_manager_get_interface(manager, "/org/gpick/SingleInstance", "org.gpick.SingleInstance"); bool result = false; if (interface){ if (!gpick_single_instance_call_activate_sync(GPICK_SINGLE_INSTANCE(interface), nullptr, &error)){ cerr << "Error calling \"SingleInstance.Activate\": " << error->message << endl; g_error_free (error); }else result = true; g_object_unref(interface); } g_object_unref(manager); return result; } static gboolean on_control_activate_floating_picker(GpickControl *control, GDBusMethodInvocation *invocation, const char *converter_name, Impl *impl) { bool result = impl->m_decl->onActivateFloatingPicker ? impl->m_decl->onActivateFloatingPicker(converter_name) : false; gpick_control_complete_activate_floating_picker(control, invocation); return result; } static gboolean on_control_check_if_running(GpickControl *control, GDBusMethodInvocation *invocation, Impl*) { gpick_control_complete_check_if_running(control, invocation); return true; } static gboolean on_single_instance_activate(GpickSingleInstance *single_instance, GDBusMethodInvocation *invocation, Impl *impl) { bool result = impl->m_decl->onSingleInstanceActivate(); gpick_single_instance_complete_activate(single_instance, invocation); return result; } static void on_bus_acquired(GDBusConnection *connection, const gchar *name, Impl *impl) { auto manager = g_dbus_object_manager_server_new("/org/gpick"); impl->m_manager = manager; GpickObjectSkeleton *object; object = gpick_object_skeleton_new("/org/gpick/Control"); GpickControl *control; control = gpick_control_skeleton_new(); gpick_object_skeleton_set_control(object, control); g_object_unref(control); g_signal_connect(control, "handle-activate-floating-picker", G_CALLBACK(on_control_activate_floating_picker), impl); g_signal_connect(control, "handle-check-if-running", G_CALLBACK(on_control_check_if_running), impl); g_dbus_object_manager_server_export(manager, G_DBUS_OBJECT_SKELETON(object)); g_object_unref(object); GpickSingleInstance *single_instance; object = gpick_object_skeleton_new("/org/gpick/SingleInstance"); single_instance = gpick_single_instance_skeleton_new(); gpick_object_skeleton_set_single_instance(object, single_instance); g_object_unref(single_instance); g_signal_connect(single_instance, "handle-activate", G_CALLBACK(on_single_instance_activate), impl); g_dbus_object_manager_server_export(manager, G_DBUS_OBJECT_SKELETON(object)); g_object_unref(object); g_dbus_object_manager_server_set_connection(manager, connection); } static void on_name_acquired(GDBusConnection *connection, const gchar *name, Impl*) { } static void on_name_lost(GDBusConnection *connection, const gchar *name, Impl*) { }; }; Control::Control() { m_impl = make_unique(this); } Control::~Control() { } void Control::ownName() { m_impl->ownName(); } void Control::unownName() { m_impl->unownName(); } bool Control::singleInstanceActivate() { return m_impl->singleInstanceActivate(); } bool Control::activateFloatingPicker(const std::string &converter_name) { return m_impl->activateFloatingPicker(converter_name); } bool Control::checkIfRunning() { return m_impl->checkIfRunning(); } } #else namespace dbus { class Control::Impl { }; Control::Control() { } Control::~Control() { } void Control::ownName() { } void Control::unownName() { } bool Control::singleInstanceActivate() { return false; } bool Control::activateFloatingPicker(const std::string &converter_name) { return false; } bool Control::checkIfRunning() { return false; } } #endif gpick-gpick-0.2.6rc1/source/dbus/Control.h000066400000000000000000000041171315430016700203460ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_DBUS_CONTROL_H_ #define GPICK_DBUS_CONTROL_H_ #include #include #include namespace dbus { class Control { public: Control(); ~Control(); void ownName(); void unownName(); bool singleInstanceActivate(); bool activateFloatingPicker(const std::string &converter_name); bool checkIfRunning(); std::function onActivateFloatingPicker; std::function onSingleInstanceActivate; private: class Impl; std::unique_ptr m_impl; }; } #endif /* GPICK_DBUS_CONTROL_H_ */ gpick-gpick-0.2.6rc1/source/dbus/DbusInterface.c000066400000000000000000002710721315430016700214450ustar00rootroot00000000000000/* * Generated by gdbus-codegen 2.48.0. DO NOT EDIT. * * The license of this code is the same as for the source it was derived from. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "DbusInterface.h" #include #ifdef G_OS_UNIX # include #endif typedef struct { GDBusArgInfo parent_struct; gboolean use_gvariant; } _ExtendedGDBusArgInfo; typedef struct { GDBusMethodInfo parent_struct; const gchar *signal_name; gboolean pass_fdlist; } _ExtendedGDBusMethodInfo; typedef struct { GDBusSignalInfo parent_struct; const gchar *signal_name; } _ExtendedGDBusSignalInfo; typedef struct { GDBusPropertyInfo parent_struct; const gchar *hyphen_name; gboolean use_gvariant; } _ExtendedGDBusPropertyInfo; typedef struct { GDBusInterfaceInfo parent_struct; const gchar *hyphen_name; } _ExtendedGDBusInterfaceInfo; typedef struct { const _ExtendedGDBusPropertyInfo *info; guint prop_id; GValue orig_value; /* the value before the change */ } ChangedProperty; static void _changed_property_free (ChangedProperty *data) { g_value_unset (&data->orig_value); g_free (data); } static gboolean _g_strv_equal0 (gchar **a, gchar **b) { gboolean ret = FALSE; guint n; if (a == NULL && b == NULL) { ret = TRUE; goto out; } if (a == NULL || b == NULL) goto out; if (g_strv_length (a) != g_strv_length (b)) goto out; for (n = 0; a[n] != NULL; n++) if (g_strcmp0 (a[n], b[n]) != 0) goto out; ret = TRUE; out: return ret; } static gboolean _g_variant_equal0 (GVariant *a, GVariant *b) { gboolean ret = FALSE; if (a == NULL && b == NULL) { ret = TRUE; goto out; } if (a == NULL || b == NULL) goto out; ret = g_variant_equal (a, b); out: return ret; } G_GNUC_UNUSED static gboolean _g_value_equal (const GValue *a, const GValue *b) { gboolean ret = FALSE; g_assert (G_VALUE_TYPE (a) == G_VALUE_TYPE (b)); switch (G_VALUE_TYPE (a)) { case G_TYPE_BOOLEAN: ret = (g_value_get_boolean (a) == g_value_get_boolean (b)); break; case G_TYPE_UCHAR: ret = (g_value_get_uchar (a) == g_value_get_uchar (b)); break; case G_TYPE_INT: ret = (g_value_get_int (a) == g_value_get_int (b)); break; case G_TYPE_UINT: ret = (g_value_get_uint (a) == g_value_get_uint (b)); break; case G_TYPE_INT64: ret = (g_value_get_int64 (a) == g_value_get_int64 (b)); break; case G_TYPE_UINT64: ret = (g_value_get_uint64 (a) == g_value_get_uint64 (b)); break; case G_TYPE_DOUBLE: { /* Avoid -Wfloat-equal warnings by doing a direct bit compare */ gdouble da = g_value_get_double (a); gdouble db = g_value_get_double (b); ret = memcmp (&da, &db, sizeof (gdouble)) == 0; } break; case G_TYPE_STRING: ret = (g_strcmp0 (g_value_get_string (a), g_value_get_string (b)) == 0); break; case G_TYPE_VARIANT: ret = _g_variant_equal0 (g_value_get_variant (a), g_value_get_variant (b)); break; default: if (G_VALUE_TYPE (a) == G_TYPE_STRV) ret = _g_strv_equal0 (g_value_get_boxed (a), g_value_get_boxed (b)); else g_critical ("_g_value_equal() does not handle type %s", g_type_name (G_VALUE_TYPE (a))); break; } return ret; } /* ------------------------------------------------------------------------ * Code for interface org.gpick.SingleInstance * ------------------------------------------------------------------------ */ /** * SECTION:GpickSingleInstance * @title: GpickSingleInstance * @short_description: Generated C code for the org.gpick.SingleInstance D-Bus interface * * This section contains code for working with the org.gpick.SingleInstance D-Bus interface in C. */ /* ---- Introspection data for org.gpick.SingleInstance ---- */ static const _ExtendedGDBusMethodInfo _gpick_single_instance_method_info_activate = { { -1, (gchar *) "Activate", NULL, NULL, NULL }, "handle-activate", FALSE }; static const _ExtendedGDBusMethodInfo * const _gpick_single_instance_method_info_pointers[] = { &_gpick_single_instance_method_info_activate, NULL }; static const _ExtendedGDBusInterfaceInfo _gpick_single_instance_interface_info = { { -1, (gchar *) "org.gpick.SingleInstance", (GDBusMethodInfo **) &_gpick_single_instance_method_info_pointers, NULL, NULL, NULL }, "single-instance", }; /** * gpick_single_instance_interface_info: * * Gets a machine-readable description of the org.gpick.SingleInstance D-Bus interface. * * Returns: (transfer none): A #GDBusInterfaceInfo. Do not free. */ GDBusInterfaceInfo * gpick_single_instance_interface_info (void) { return (GDBusInterfaceInfo *) &_gpick_single_instance_interface_info.parent_struct; } /** * gpick_single_instance_override_properties: * @klass: The class structure for a #GObject-derived class. * @property_id_begin: The property id to assign to the first overridden property. * * Overrides all #GObject properties in the #GpickSingleInstance interface for a concrete class. * The properties are overridden in the order they are defined. * * Returns: The last property id. */ guint gpick_single_instance_override_properties (GObjectClass *klass, guint property_id_begin) { return property_id_begin - 1; } /** * GpickSingleInstance: * * Abstract interface type for the D-Bus interface org.gpick.SingleInstance. */ /** * GpickSingleInstanceIface: * @parent_iface: The parent interface. * @handle_activate: Handler for the #GpickSingleInstance::handle-activate signal. * * Virtual table for the D-Bus interface org.gpick.SingleInstance. */ typedef GpickSingleInstanceIface GpickSingleInstanceInterface; G_DEFINE_INTERFACE (GpickSingleInstance, gpick_single_instance, G_TYPE_OBJECT); static void gpick_single_instance_default_init (GpickSingleInstanceIface *iface) { /* GObject signals for incoming D-Bus method calls: */ /** * GpickSingleInstance::handle-activate: * @object: A #GpickSingleInstance. * @invocation: A #GDBusMethodInvocation. * * Signal emitted when a remote caller is invoking the Activate() D-Bus method. * * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call gpick_single_instance_complete_activate() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. * * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. */ g_signal_new ("handle-activate", G_TYPE_FROM_INTERFACE (iface), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GpickSingleInstanceIface, handle_activate), g_signal_accumulator_true_handled, NULL, g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 1, G_TYPE_DBUS_METHOD_INVOCATION); } /** * gpick_single_instance_call_activate: * @proxy: A #GpickSingleInstanceProxy. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. * @user_data: User data to pass to @callback. * * Asynchronously invokes the Activate() D-Bus method on @proxy. * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. * You can then call gpick_single_instance_call_activate_finish() to get the result of the operation. * * See gpick_single_instance_call_activate_sync() for the synchronous, blocking version of this method. */ void gpick_single_instance_call_activate ( GpickSingleInstance *proxy, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_dbus_proxy_call (G_DBUS_PROXY (proxy), "Activate", g_variant_new ("()"), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, callback, user_data); } /** * gpick_single_instance_call_activate_finish: * @proxy: A #GpickSingleInstanceProxy. * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to gpick_single_instance_call_activate(). * @error: Return location for error or %NULL. * * Finishes an operation started with gpick_single_instance_call_activate(). * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean gpick_single_instance_call_activate_finish ( GpickSingleInstance *proxy, GAsyncResult *res, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * gpick_single_instance_call_activate_sync: * @proxy: A #GpickSingleInstanceProxy. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL. * * Synchronously invokes the Activate() D-Bus method on @proxy. The calling thread is blocked until a reply is received. * * See gpick_single_instance_call_activate() for the asynchronous version of this method. * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean gpick_single_instance_call_activate_sync ( GpickSingleInstance *proxy, GCancellable *cancellable, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), "Activate", g_variant_new ("()"), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * gpick_single_instance_complete_activate: * @object: A #GpickSingleInstance. * @invocation: (transfer full): A #GDBusMethodInvocation. * * Helper function used in service implementations to finish handling invocations of the Activate() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. * * This method will free @invocation, you cannot use it afterwards. */ void gpick_single_instance_complete_activate ( GpickSingleInstance *object, GDBusMethodInvocation *invocation) { g_dbus_method_invocation_return_value (invocation, g_variant_new ("()")); } /* ------------------------------------------------------------------------ */ /** * GpickSingleInstanceProxy: * * The #GpickSingleInstanceProxy structure contains only private data and should only be accessed using the provided API. */ /** * GpickSingleInstanceProxyClass: * @parent_class: The parent class. * * Class structure for #GpickSingleInstanceProxy. */ struct _GpickSingleInstanceProxyPrivate { GData *qdata; }; static void gpick_single_instance_proxy_iface_init (GpickSingleInstanceIface *iface); #if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 G_DEFINE_TYPE_WITH_CODE (GpickSingleInstanceProxy, gpick_single_instance_proxy, G_TYPE_DBUS_PROXY, G_ADD_PRIVATE (GpickSingleInstanceProxy) G_IMPLEMENT_INTERFACE (GPICK_TYPE_SINGLE_INSTANCE, gpick_single_instance_proxy_iface_init)); #else G_DEFINE_TYPE_WITH_CODE (GpickSingleInstanceProxy, gpick_single_instance_proxy, G_TYPE_DBUS_PROXY, G_IMPLEMENT_INTERFACE (GPICK_TYPE_SINGLE_INSTANCE, gpick_single_instance_proxy_iface_init)); #endif static void gpick_single_instance_proxy_finalize (GObject *object) { GpickSingleInstanceProxy *proxy = GPICK_SINGLE_INSTANCE_PROXY (object); g_datalist_clear (&proxy->priv->qdata); G_OBJECT_CLASS (gpick_single_instance_proxy_parent_class)->finalize (object); } static void gpick_single_instance_proxy_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec G_GNUC_UNUSED) { } static void gpick_single_instance_proxy_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec G_GNUC_UNUSED) { } static void gpick_single_instance_proxy_g_signal (GDBusProxy *proxy, const gchar *sender_name G_GNUC_UNUSED, const gchar *signal_name, GVariant *parameters) { _ExtendedGDBusSignalInfo *info; GVariantIter iter; GVariant *child; GValue *paramv; guint num_params; guint n; guint signal_id; info = (_ExtendedGDBusSignalInfo *) g_dbus_interface_info_lookup_signal ((GDBusInterfaceInfo *) &_gpick_single_instance_interface_info.parent_struct, signal_name); if (info == NULL) return; num_params = g_variant_n_children (parameters); paramv = g_new0 (GValue, num_params + 1); g_value_init (¶mv[0], GPICK_TYPE_SINGLE_INSTANCE); g_value_set_object (¶mv[0], proxy); g_variant_iter_init (&iter, parameters); n = 1; while ((child = g_variant_iter_next_value (&iter)) != NULL) { _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.args[n - 1]; if (arg_info->use_gvariant) { g_value_init (¶mv[n], G_TYPE_VARIANT); g_value_set_variant (¶mv[n], child); n++; } else g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); g_variant_unref (child); } signal_id = g_signal_lookup (info->signal_name, GPICK_TYPE_SINGLE_INSTANCE); g_signal_emitv (paramv, signal_id, 0, NULL); for (n = 0; n < num_params + 1; n++) g_value_unset (¶mv[n]); g_free (paramv); } static void gpick_single_instance_proxy_g_properties_changed (GDBusProxy *_proxy, GVariant *changed_properties, const gchar *const *invalidated_properties) { GpickSingleInstanceProxy *proxy = GPICK_SINGLE_INSTANCE_PROXY (_proxy); guint n; const gchar *key; GVariantIter *iter; _ExtendedGDBusPropertyInfo *info; g_variant_get (changed_properties, "a{sv}", &iter); while (g_variant_iter_next (iter, "{&sv}", &key, NULL)) { info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_gpick_single_instance_interface_info.parent_struct, key); g_datalist_remove_data (&proxy->priv->qdata, key); if (info != NULL) g_object_notify (G_OBJECT (proxy), info->hyphen_name); } g_variant_iter_free (iter); for (n = 0; invalidated_properties[n] != NULL; n++) { info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_gpick_single_instance_interface_info.parent_struct, invalidated_properties[n]); g_datalist_remove_data (&proxy->priv->qdata, invalidated_properties[n]); if (info != NULL) g_object_notify (G_OBJECT (proxy), info->hyphen_name); } } static void gpick_single_instance_proxy_init (GpickSingleInstanceProxy *proxy) { #if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 proxy->priv = gpick_single_instance_proxy_get_instance_private (proxy); #else proxy->priv = G_TYPE_INSTANCE_GET_PRIVATE (proxy, GPICK_TYPE_SINGLE_INSTANCE_PROXY, GpickSingleInstanceProxyPrivate); #endif g_dbus_proxy_set_interface_info (G_DBUS_PROXY (proxy), gpick_single_instance_interface_info ()); } static void gpick_single_instance_proxy_class_init (GpickSingleInstanceProxyClass *klass) { GObjectClass *gobject_class; GDBusProxyClass *proxy_class; gobject_class = G_OBJECT_CLASS (klass); gobject_class->finalize = gpick_single_instance_proxy_finalize; gobject_class->get_property = gpick_single_instance_proxy_get_property; gobject_class->set_property = gpick_single_instance_proxy_set_property; proxy_class = G_DBUS_PROXY_CLASS (klass); proxy_class->g_signal = gpick_single_instance_proxy_g_signal; proxy_class->g_properties_changed = gpick_single_instance_proxy_g_properties_changed; #if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 g_type_class_add_private (klass, sizeof (GpickSingleInstanceProxyPrivate)); #endif } static void gpick_single_instance_proxy_iface_init (GpickSingleInstanceIface *iface) { } /** * gpick_single_instance_proxy_new: * @connection: A #GDBusConnection. * @flags: Flags from the #GDBusProxyFlags enumeration. * @name: (allow-none): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied. * @user_data: User data to pass to @callback. * * Asynchronously creates a proxy for the D-Bus interface org.gpick.SingleInstance. See g_dbus_proxy_new() for more details. * * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. * You can then call gpick_single_instance_proxy_new_finish() to get the result of the operation. * * See gpick_single_instance_proxy_new_sync() for the synchronous, blocking version of this constructor. */ void gpick_single_instance_proxy_new ( GDBusConnection *connection, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_async_initable_new_async (GPICK_TYPE_SINGLE_INSTANCE_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "org.gpick.SingleInstance", NULL); } /** * gpick_single_instance_proxy_new_finish: * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to gpick_single_instance_proxy_new(). * @error: Return location for error or %NULL * * Finishes an operation started with gpick_single_instance_proxy_new(). * * Returns: (transfer full) (type GpickSingleInstanceProxy): The constructed proxy object or %NULL if @error is set. */ GpickSingleInstance * gpick_single_instance_proxy_new_finish ( GAsyncResult *res, GError **error) { GObject *ret; GObject *source_object; source_object = g_async_result_get_source_object (res); ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); g_object_unref (source_object); if (ret != NULL) return GPICK_SINGLE_INSTANCE (ret); else return NULL; } /** * gpick_single_instance_proxy_new_sync: * @connection: A #GDBusConnection. * @flags: Flags from the #GDBusProxyFlags enumeration. * @name: (allow-none): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL * * Synchronously creates a proxy for the D-Bus interface org.gpick.SingleInstance. See g_dbus_proxy_new_sync() for more details. * * The calling thread is blocked until a reply is received. * * See gpick_single_instance_proxy_new() for the asynchronous version of this constructor. * * Returns: (transfer full) (type GpickSingleInstanceProxy): The constructed proxy object or %NULL if @error is set. */ GpickSingleInstance * gpick_single_instance_proxy_new_sync ( GDBusConnection *connection, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GError **error) { GInitable *ret; ret = g_initable_new (GPICK_TYPE_SINGLE_INSTANCE_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "org.gpick.SingleInstance", NULL); if (ret != NULL) return GPICK_SINGLE_INSTANCE (ret); else return NULL; } /** * gpick_single_instance_proxy_new_for_bus: * @bus_type: A #GBusType. * @flags: Flags from the #GDBusProxyFlags enumeration. * @name: A bus name (well-known or unique). * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied. * @user_data: User data to pass to @callback. * * Like gpick_single_instance_proxy_new() but takes a #GBusType instead of a #GDBusConnection. * * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. * You can then call gpick_single_instance_proxy_new_for_bus_finish() to get the result of the operation. * * See gpick_single_instance_proxy_new_for_bus_sync() for the synchronous, blocking version of this constructor. */ void gpick_single_instance_proxy_new_for_bus ( GBusType bus_type, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_async_initable_new_async (GPICK_TYPE_SINGLE_INSTANCE_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "org.gpick.SingleInstance", NULL); } /** * gpick_single_instance_proxy_new_for_bus_finish: * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to gpick_single_instance_proxy_new_for_bus(). * @error: Return location for error or %NULL * * Finishes an operation started with gpick_single_instance_proxy_new_for_bus(). * * Returns: (transfer full) (type GpickSingleInstanceProxy): The constructed proxy object or %NULL if @error is set. */ GpickSingleInstance * gpick_single_instance_proxy_new_for_bus_finish ( GAsyncResult *res, GError **error) { GObject *ret; GObject *source_object; source_object = g_async_result_get_source_object (res); ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); g_object_unref (source_object); if (ret != NULL) return GPICK_SINGLE_INSTANCE (ret); else return NULL; } /** * gpick_single_instance_proxy_new_for_bus_sync: * @bus_type: A #GBusType. * @flags: Flags from the #GDBusProxyFlags enumeration. * @name: A bus name (well-known or unique). * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL * * Like gpick_single_instance_proxy_new_sync() but takes a #GBusType instead of a #GDBusConnection. * * The calling thread is blocked until a reply is received. * * See gpick_single_instance_proxy_new_for_bus() for the asynchronous version of this constructor. * * Returns: (transfer full) (type GpickSingleInstanceProxy): The constructed proxy object or %NULL if @error is set. */ GpickSingleInstance * gpick_single_instance_proxy_new_for_bus_sync ( GBusType bus_type, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GError **error) { GInitable *ret; ret = g_initable_new (GPICK_TYPE_SINGLE_INSTANCE_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "org.gpick.SingleInstance", NULL); if (ret != NULL) return GPICK_SINGLE_INSTANCE (ret); else return NULL; } /* ------------------------------------------------------------------------ */ /** * GpickSingleInstanceSkeleton: * * The #GpickSingleInstanceSkeleton structure contains only private data and should only be accessed using the provided API. */ /** * GpickSingleInstanceSkeletonClass: * @parent_class: The parent class. * * Class structure for #GpickSingleInstanceSkeleton. */ struct _GpickSingleInstanceSkeletonPrivate { GValue *properties; GList *changed_properties; GSource *changed_properties_idle_source; GMainContext *context; GMutex lock; }; static void _gpick_single_instance_skeleton_handle_method_call ( GDBusConnection *connection G_GNUC_UNUSED, const gchar *sender G_GNUC_UNUSED, const gchar *object_path G_GNUC_UNUSED, const gchar *interface_name, const gchar *method_name, GVariant *parameters, GDBusMethodInvocation *invocation, gpointer user_data) { GpickSingleInstanceSkeleton *skeleton = GPICK_SINGLE_INSTANCE_SKELETON (user_data); _ExtendedGDBusMethodInfo *info; GVariantIter iter; GVariant *child; GValue *paramv; guint num_params; guint num_extra; guint n; guint signal_id; GValue return_value = G_VALUE_INIT; info = (_ExtendedGDBusMethodInfo *) g_dbus_method_invocation_get_method_info (invocation); g_assert (info != NULL); num_params = g_variant_n_children (parameters); num_extra = info->pass_fdlist ? 3 : 2; paramv = g_new0 (GValue, num_params + num_extra); n = 0; g_value_init (¶mv[n], GPICK_TYPE_SINGLE_INSTANCE); g_value_set_object (¶mv[n++], skeleton); g_value_init (¶mv[n], G_TYPE_DBUS_METHOD_INVOCATION); g_value_set_object (¶mv[n++], invocation); if (info->pass_fdlist) { #ifdef G_OS_UNIX g_value_init (¶mv[n], G_TYPE_UNIX_FD_LIST); g_value_set_object (¶mv[n++], g_dbus_message_get_unix_fd_list (g_dbus_method_invocation_get_message (invocation))); #else g_assert_not_reached (); #endif } g_variant_iter_init (&iter, parameters); while ((child = g_variant_iter_next_value (&iter)) != NULL) { _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.in_args[n - num_extra]; if (arg_info->use_gvariant) { g_value_init (¶mv[n], G_TYPE_VARIANT); g_value_set_variant (¶mv[n], child); n++; } else g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); g_variant_unref (child); } signal_id = g_signal_lookup (info->signal_name, GPICK_TYPE_SINGLE_INSTANCE); g_value_init (&return_value, G_TYPE_BOOLEAN); g_signal_emitv (paramv, signal_id, 0, &return_value); if (!g_value_get_boolean (&return_value)) g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD, "Method %s is not implemented on interface %s", method_name, interface_name); g_value_unset (&return_value); for (n = 0; n < num_params + num_extra; n++) g_value_unset (¶mv[n]); g_free (paramv); } static GVariant * _gpick_single_instance_skeleton_handle_get_property ( GDBusConnection *connection G_GNUC_UNUSED, const gchar *sender G_GNUC_UNUSED, const gchar *object_path G_GNUC_UNUSED, const gchar *interface_name G_GNUC_UNUSED, const gchar *property_name, GError **error, gpointer user_data) { GpickSingleInstanceSkeleton *skeleton = GPICK_SINGLE_INSTANCE_SKELETON (user_data); GValue value = G_VALUE_INIT; GParamSpec *pspec; _ExtendedGDBusPropertyInfo *info; GVariant *ret; ret = NULL; info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_gpick_single_instance_interface_info.parent_struct, property_name); g_assert (info != NULL); pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); if (pspec == NULL) { g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); } else { g_value_init (&value, pspec->value_type); g_object_get_property (G_OBJECT (skeleton), info->hyphen_name, &value); ret = g_dbus_gvalue_to_gvariant (&value, G_VARIANT_TYPE (info->parent_struct.signature)); g_value_unset (&value); } return ret; } static gboolean _gpick_single_instance_skeleton_handle_set_property ( GDBusConnection *connection G_GNUC_UNUSED, const gchar *sender G_GNUC_UNUSED, const gchar *object_path G_GNUC_UNUSED, const gchar *interface_name G_GNUC_UNUSED, const gchar *property_name, GVariant *variant, GError **error, gpointer user_data) { GpickSingleInstanceSkeleton *skeleton = GPICK_SINGLE_INSTANCE_SKELETON (user_data); GValue value = G_VALUE_INIT; GParamSpec *pspec; _ExtendedGDBusPropertyInfo *info; gboolean ret; ret = FALSE; info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_gpick_single_instance_interface_info.parent_struct, property_name); g_assert (info != NULL); pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); if (pspec == NULL) { g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); } else { if (info->use_gvariant) g_value_set_variant (&value, variant); else g_dbus_gvariant_to_gvalue (variant, &value); g_object_set_property (G_OBJECT (skeleton), info->hyphen_name, &value); g_value_unset (&value); ret = TRUE; } return ret; } static const GDBusInterfaceVTable _gpick_single_instance_skeleton_vtable = { _gpick_single_instance_skeleton_handle_method_call, _gpick_single_instance_skeleton_handle_get_property, _gpick_single_instance_skeleton_handle_set_property, {NULL} }; static GDBusInterfaceInfo * gpick_single_instance_skeleton_dbus_interface_get_info (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) { return gpick_single_instance_interface_info (); } static GDBusInterfaceVTable * gpick_single_instance_skeleton_dbus_interface_get_vtable (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) { return (GDBusInterfaceVTable *) &_gpick_single_instance_skeleton_vtable; } static GVariant * gpick_single_instance_skeleton_dbus_interface_get_properties (GDBusInterfaceSkeleton *_skeleton) { GpickSingleInstanceSkeleton *skeleton = GPICK_SINGLE_INSTANCE_SKELETON (_skeleton); GVariantBuilder builder; guint n; g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}")); if (_gpick_single_instance_interface_info.parent_struct.properties == NULL) goto out; for (n = 0; _gpick_single_instance_interface_info.parent_struct.properties[n] != NULL; n++) { GDBusPropertyInfo *info = _gpick_single_instance_interface_info.parent_struct.properties[n]; if (info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE) { GVariant *value; value = _gpick_single_instance_skeleton_handle_get_property (g_dbus_interface_skeleton_get_connection (G_DBUS_INTERFACE_SKELETON (skeleton)), NULL, g_dbus_interface_skeleton_get_object_path (G_DBUS_INTERFACE_SKELETON (skeleton)), "org.gpick.SingleInstance", info->name, NULL, skeleton); if (value != NULL) { g_variant_take_ref (value); g_variant_builder_add (&builder, "{sv}", info->name, value); g_variant_unref (value); } } } out: return g_variant_builder_end (&builder); } static void gpick_single_instance_skeleton_dbus_interface_flush (GDBusInterfaceSkeleton *_skeleton) { } static void gpick_single_instance_skeleton_iface_init (GpickSingleInstanceIface *iface); #if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 G_DEFINE_TYPE_WITH_CODE (GpickSingleInstanceSkeleton, gpick_single_instance_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, G_ADD_PRIVATE (GpickSingleInstanceSkeleton) G_IMPLEMENT_INTERFACE (GPICK_TYPE_SINGLE_INSTANCE, gpick_single_instance_skeleton_iface_init)); #else G_DEFINE_TYPE_WITH_CODE (GpickSingleInstanceSkeleton, gpick_single_instance_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, G_IMPLEMENT_INTERFACE (GPICK_TYPE_SINGLE_INSTANCE, gpick_single_instance_skeleton_iface_init)); #endif static void gpick_single_instance_skeleton_finalize (GObject *object) { GpickSingleInstanceSkeleton *skeleton = GPICK_SINGLE_INSTANCE_SKELETON (object); g_list_free_full (skeleton->priv->changed_properties, (GDestroyNotify) _changed_property_free); if (skeleton->priv->changed_properties_idle_source != NULL) g_source_destroy (skeleton->priv->changed_properties_idle_source); g_main_context_unref (skeleton->priv->context); g_mutex_clear (&skeleton->priv->lock); G_OBJECT_CLASS (gpick_single_instance_skeleton_parent_class)->finalize (object); } static void gpick_single_instance_skeleton_init (GpickSingleInstanceSkeleton *skeleton) { #if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 skeleton->priv = gpick_single_instance_skeleton_get_instance_private (skeleton); #else skeleton->priv = G_TYPE_INSTANCE_GET_PRIVATE (skeleton, GPICK_TYPE_SINGLE_INSTANCE_SKELETON, GpickSingleInstanceSkeletonPrivate); #endif g_mutex_init (&skeleton->priv->lock); skeleton->priv->context = g_main_context_ref_thread_default (); } static void gpick_single_instance_skeleton_class_init (GpickSingleInstanceSkeletonClass *klass) { GObjectClass *gobject_class; GDBusInterfaceSkeletonClass *skeleton_class; gobject_class = G_OBJECT_CLASS (klass); gobject_class->finalize = gpick_single_instance_skeleton_finalize; skeleton_class = G_DBUS_INTERFACE_SKELETON_CLASS (klass); skeleton_class->get_info = gpick_single_instance_skeleton_dbus_interface_get_info; skeleton_class->get_properties = gpick_single_instance_skeleton_dbus_interface_get_properties; skeleton_class->flush = gpick_single_instance_skeleton_dbus_interface_flush; skeleton_class->get_vtable = gpick_single_instance_skeleton_dbus_interface_get_vtable; #if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 g_type_class_add_private (klass, sizeof (GpickSingleInstanceSkeletonPrivate)); #endif } static void gpick_single_instance_skeleton_iface_init (GpickSingleInstanceIface *iface) { } /** * gpick_single_instance_skeleton_new: * * Creates a skeleton object for the D-Bus interface org.gpick.SingleInstance. * * Returns: (transfer full) (type GpickSingleInstanceSkeleton): The skeleton object. */ GpickSingleInstance * gpick_single_instance_skeleton_new (void) { return GPICK_SINGLE_INSTANCE (g_object_new (GPICK_TYPE_SINGLE_INSTANCE_SKELETON, NULL)); } /* ------------------------------------------------------------------------ * Code for interface org.gpick.Control * ------------------------------------------------------------------------ */ /** * SECTION:GpickControl * @title: GpickControl * @short_description: Generated C code for the org.gpick.Control D-Bus interface * * This section contains code for working with the org.gpick.Control D-Bus interface in C. */ /* ---- Introspection data for org.gpick.Control ---- */ static const _ExtendedGDBusArgInfo _gpick_control_method_info_activate_floating_picker_IN_ARG_converter_name = { { -1, (gchar *) "converter_name", (gchar *) "s", NULL }, FALSE }; static const _ExtendedGDBusArgInfo * const _gpick_control_method_info_activate_floating_picker_IN_ARG_pointers[] = { &_gpick_control_method_info_activate_floating_picker_IN_ARG_converter_name, NULL }; static const _ExtendedGDBusMethodInfo _gpick_control_method_info_activate_floating_picker = { { -1, (gchar *) "ActivateFloatingPicker", (GDBusArgInfo **) &_gpick_control_method_info_activate_floating_picker_IN_ARG_pointers, NULL, NULL }, "handle-activate-floating-picker", FALSE }; static const _ExtendedGDBusMethodInfo _gpick_control_method_info_check_if_running = { { -1, (gchar *) "CheckIfRunning", NULL, NULL, NULL }, "handle-check-if-running", FALSE }; static const _ExtendedGDBusMethodInfo * const _gpick_control_method_info_pointers[] = { &_gpick_control_method_info_activate_floating_picker, &_gpick_control_method_info_check_if_running, NULL }; static const _ExtendedGDBusInterfaceInfo _gpick_control_interface_info = { { -1, (gchar *) "org.gpick.Control", (GDBusMethodInfo **) &_gpick_control_method_info_pointers, NULL, NULL, NULL }, "control", }; /** * gpick_control_interface_info: * * Gets a machine-readable description of the org.gpick.Control D-Bus interface. * * Returns: (transfer none): A #GDBusInterfaceInfo. Do not free. */ GDBusInterfaceInfo * gpick_control_interface_info (void) { return (GDBusInterfaceInfo *) &_gpick_control_interface_info.parent_struct; } /** * gpick_control_override_properties: * @klass: The class structure for a #GObject-derived class. * @property_id_begin: The property id to assign to the first overridden property. * * Overrides all #GObject properties in the #GpickControl interface for a concrete class. * The properties are overridden in the order they are defined. * * Returns: The last property id. */ guint gpick_control_override_properties (GObjectClass *klass, guint property_id_begin) { return property_id_begin - 1; } /** * GpickControl: * * Abstract interface type for the D-Bus interface org.gpick.Control. */ /** * GpickControlIface: * @parent_iface: The parent interface. * @handle_activate_floating_picker: Handler for the #GpickControl::handle-activate-floating-picker signal. * @handle_check_if_running: Handler for the #GpickControl::handle-check-if-running signal. * * Virtual table for the D-Bus interface org.gpick.Control. */ typedef GpickControlIface GpickControlInterface; G_DEFINE_INTERFACE (GpickControl, gpick_control, G_TYPE_OBJECT); static void gpick_control_default_init (GpickControlIface *iface) { /* GObject signals for incoming D-Bus method calls: */ /** * GpickControl::handle-activate-floating-picker: * @object: A #GpickControl. * @invocation: A #GDBusMethodInvocation. * @arg_converter_name: Argument passed by remote caller. * * Signal emitted when a remote caller is invoking the ActivateFloatingPicker() D-Bus method. * * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call gpick_control_complete_activate_floating_picker() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. * * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. */ g_signal_new ("handle-activate-floating-picker", G_TYPE_FROM_INTERFACE (iface), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GpickControlIface, handle_activate_floating_picker), g_signal_accumulator_true_handled, NULL, g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 2, G_TYPE_DBUS_METHOD_INVOCATION, G_TYPE_STRING); /** * GpickControl::handle-check-if-running: * @object: A #GpickControl. * @invocation: A #GDBusMethodInvocation. * * Signal emitted when a remote caller is invoking the CheckIfRunning() D-Bus method. * * If a signal handler returns %TRUE, it means the signal handler will handle the invocation (e.g. take a reference to @invocation and eventually call gpick_control_complete_check_if_running() or e.g. g_dbus_method_invocation_return_error() on it) and no order signal handlers will run. If no signal handler handles the invocation, the %G_DBUS_ERROR_UNKNOWN_METHOD error is returned. * * Returns: %TRUE if the invocation was handled, %FALSE to let other signal handlers run. */ g_signal_new ("handle-check-if-running", G_TYPE_FROM_INTERFACE (iface), G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GpickControlIface, handle_check_if_running), g_signal_accumulator_true_handled, NULL, g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 1, G_TYPE_DBUS_METHOD_INVOCATION); } /** * gpick_control_call_activate_floating_picker: * @proxy: A #GpickControlProxy. * @arg_converter_name: Argument to pass with the method invocation. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. * @user_data: User data to pass to @callback. * * Asynchronously invokes the ActivateFloatingPicker() D-Bus method on @proxy. * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. * You can then call gpick_control_call_activate_floating_picker_finish() to get the result of the operation. * * See gpick_control_call_activate_floating_picker_sync() for the synchronous, blocking version of this method. */ void gpick_control_call_activate_floating_picker ( GpickControl *proxy, const gchar *arg_converter_name, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_dbus_proxy_call (G_DBUS_PROXY (proxy), "ActivateFloatingPicker", g_variant_new ("(s)", arg_converter_name), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, callback, user_data); } /** * gpick_control_call_activate_floating_picker_finish: * @proxy: A #GpickControlProxy. * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to gpick_control_call_activate_floating_picker(). * @error: Return location for error or %NULL. * * Finishes an operation started with gpick_control_call_activate_floating_picker(). * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean gpick_control_call_activate_floating_picker_finish ( GpickControl *proxy, GAsyncResult *res, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * gpick_control_call_activate_floating_picker_sync: * @proxy: A #GpickControlProxy. * @arg_converter_name: Argument to pass with the method invocation. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL. * * Synchronously invokes the ActivateFloatingPicker() D-Bus method on @proxy. The calling thread is blocked until a reply is received. * * See gpick_control_call_activate_floating_picker() for the asynchronous version of this method. * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean gpick_control_call_activate_floating_picker_sync ( GpickControl *proxy, const gchar *arg_converter_name, GCancellable *cancellable, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), "ActivateFloatingPicker", g_variant_new ("(s)", arg_converter_name), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * gpick_control_call_check_if_running: * @proxy: A #GpickControlProxy. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL. * @user_data: User data to pass to @callback. * * Asynchronously invokes the CheckIfRunning() D-Bus method on @proxy. * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. * You can then call gpick_control_call_check_if_running_finish() to get the result of the operation. * * See gpick_control_call_check_if_running_sync() for the synchronous, blocking version of this method. */ void gpick_control_call_check_if_running ( GpickControl *proxy, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_dbus_proxy_call (G_DBUS_PROXY (proxy), "CheckIfRunning", g_variant_new ("()"), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, callback, user_data); } /** * gpick_control_call_check_if_running_finish: * @proxy: A #GpickControlProxy. * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to gpick_control_call_check_if_running(). * @error: Return location for error or %NULL. * * Finishes an operation started with gpick_control_call_check_if_running(). * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean gpick_control_call_check_if_running_finish ( GpickControl *proxy, GAsyncResult *res, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_finish (G_DBUS_PROXY (proxy), res, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * gpick_control_call_check_if_running_sync: * @proxy: A #GpickControlProxy. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL. * * Synchronously invokes the CheckIfRunning() D-Bus method on @proxy. The calling thread is blocked until a reply is received. * * See gpick_control_call_check_if_running() for the asynchronous version of this method. * * Returns: (skip): %TRUE if the call succeded, %FALSE if @error is set. */ gboolean gpick_control_call_check_if_running_sync ( GpickControl *proxy, GCancellable *cancellable, GError **error) { GVariant *_ret; _ret = g_dbus_proxy_call_sync (G_DBUS_PROXY (proxy), "CheckIfRunning", g_variant_new ("()"), G_DBUS_CALL_FLAGS_NONE, -1, cancellable, error); if (_ret == NULL) goto _out; g_variant_get (_ret, "()"); g_variant_unref (_ret); _out: return _ret != NULL; } /** * gpick_control_complete_activate_floating_picker: * @object: A #GpickControl. * @invocation: (transfer full): A #GDBusMethodInvocation. * * Helper function used in service implementations to finish handling invocations of the ActivateFloatingPicker() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. * * This method will free @invocation, you cannot use it afterwards. */ void gpick_control_complete_activate_floating_picker ( GpickControl *object, GDBusMethodInvocation *invocation) { g_dbus_method_invocation_return_value (invocation, g_variant_new ("()")); } /** * gpick_control_complete_check_if_running: * @object: A #GpickControl. * @invocation: (transfer full): A #GDBusMethodInvocation. * * Helper function used in service implementations to finish handling invocations of the CheckIfRunning() D-Bus method. If you instead want to finish handling an invocation by returning an error, use g_dbus_method_invocation_return_error() or similar. * * This method will free @invocation, you cannot use it afterwards. */ void gpick_control_complete_check_if_running ( GpickControl *object, GDBusMethodInvocation *invocation) { g_dbus_method_invocation_return_value (invocation, g_variant_new ("()")); } /* ------------------------------------------------------------------------ */ /** * GpickControlProxy: * * The #GpickControlProxy structure contains only private data and should only be accessed using the provided API. */ /** * GpickControlProxyClass: * @parent_class: The parent class. * * Class structure for #GpickControlProxy. */ struct _GpickControlProxyPrivate { GData *qdata; }; static void gpick_control_proxy_iface_init (GpickControlIface *iface); #if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 G_DEFINE_TYPE_WITH_CODE (GpickControlProxy, gpick_control_proxy, G_TYPE_DBUS_PROXY, G_ADD_PRIVATE (GpickControlProxy) G_IMPLEMENT_INTERFACE (GPICK_TYPE_CONTROL, gpick_control_proxy_iface_init)); #else G_DEFINE_TYPE_WITH_CODE (GpickControlProxy, gpick_control_proxy, G_TYPE_DBUS_PROXY, G_IMPLEMENT_INTERFACE (GPICK_TYPE_CONTROL, gpick_control_proxy_iface_init)); #endif static void gpick_control_proxy_finalize (GObject *object) { GpickControlProxy *proxy = GPICK_CONTROL_PROXY (object); g_datalist_clear (&proxy->priv->qdata); G_OBJECT_CLASS (gpick_control_proxy_parent_class)->finalize (object); } static void gpick_control_proxy_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec G_GNUC_UNUSED) { } static void gpick_control_proxy_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec G_GNUC_UNUSED) { } static void gpick_control_proxy_g_signal (GDBusProxy *proxy, const gchar *sender_name G_GNUC_UNUSED, const gchar *signal_name, GVariant *parameters) { _ExtendedGDBusSignalInfo *info; GVariantIter iter; GVariant *child; GValue *paramv; guint num_params; guint n; guint signal_id; info = (_ExtendedGDBusSignalInfo *) g_dbus_interface_info_lookup_signal ((GDBusInterfaceInfo *) &_gpick_control_interface_info.parent_struct, signal_name); if (info == NULL) return; num_params = g_variant_n_children (parameters); paramv = g_new0 (GValue, num_params + 1); g_value_init (¶mv[0], GPICK_TYPE_CONTROL); g_value_set_object (¶mv[0], proxy); g_variant_iter_init (&iter, parameters); n = 1; while ((child = g_variant_iter_next_value (&iter)) != NULL) { _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.args[n - 1]; if (arg_info->use_gvariant) { g_value_init (¶mv[n], G_TYPE_VARIANT); g_value_set_variant (¶mv[n], child); n++; } else g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); g_variant_unref (child); } signal_id = g_signal_lookup (info->signal_name, GPICK_TYPE_CONTROL); g_signal_emitv (paramv, signal_id, 0, NULL); for (n = 0; n < num_params + 1; n++) g_value_unset (¶mv[n]); g_free (paramv); } static void gpick_control_proxy_g_properties_changed (GDBusProxy *_proxy, GVariant *changed_properties, const gchar *const *invalidated_properties) { GpickControlProxy *proxy = GPICK_CONTROL_PROXY (_proxy); guint n; const gchar *key; GVariantIter *iter; _ExtendedGDBusPropertyInfo *info; g_variant_get (changed_properties, "a{sv}", &iter); while (g_variant_iter_next (iter, "{&sv}", &key, NULL)) { info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_gpick_control_interface_info.parent_struct, key); g_datalist_remove_data (&proxy->priv->qdata, key); if (info != NULL) g_object_notify (G_OBJECT (proxy), info->hyphen_name); } g_variant_iter_free (iter); for (n = 0; invalidated_properties[n] != NULL; n++) { info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_gpick_control_interface_info.parent_struct, invalidated_properties[n]); g_datalist_remove_data (&proxy->priv->qdata, invalidated_properties[n]); if (info != NULL) g_object_notify (G_OBJECT (proxy), info->hyphen_name); } } static void gpick_control_proxy_init (GpickControlProxy *proxy) { #if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 proxy->priv = gpick_control_proxy_get_instance_private (proxy); #else proxy->priv = G_TYPE_INSTANCE_GET_PRIVATE (proxy, GPICK_TYPE_CONTROL_PROXY, GpickControlProxyPrivate); #endif g_dbus_proxy_set_interface_info (G_DBUS_PROXY (proxy), gpick_control_interface_info ()); } static void gpick_control_proxy_class_init (GpickControlProxyClass *klass) { GObjectClass *gobject_class; GDBusProxyClass *proxy_class; gobject_class = G_OBJECT_CLASS (klass); gobject_class->finalize = gpick_control_proxy_finalize; gobject_class->get_property = gpick_control_proxy_get_property; gobject_class->set_property = gpick_control_proxy_set_property; proxy_class = G_DBUS_PROXY_CLASS (klass); proxy_class->g_signal = gpick_control_proxy_g_signal; proxy_class->g_properties_changed = gpick_control_proxy_g_properties_changed; #if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 g_type_class_add_private (klass, sizeof (GpickControlProxyPrivate)); #endif } static void gpick_control_proxy_iface_init (GpickControlIface *iface) { } /** * gpick_control_proxy_new: * @connection: A #GDBusConnection. * @flags: Flags from the #GDBusProxyFlags enumeration. * @name: (allow-none): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied. * @user_data: User data to pass to @callback. * * Asynchronously creates a proxy for the D-Bus interface org.gpick.Control. See g_dbus_proxy_new() for more details. * * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. * You can then call gpick_control_proxy_new_finish() to get the result of the operation. * * See gpick_control_proxy_new_sync() for the synchronous, blocking version of this constructor. */ void gpick_control_proxy_new ( GDBusConnection *connection, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_async_initable_new_async (GPICK_TYPE_CONTROL_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "org.gpick.Control", NULL); } /** * gpick_control_proxy_new_finish: * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to gpick_control_proxy_new(). * @error: Return location for error or %NULL * * Finishes an operation started with gpick_control_proxy_new(). * * Returns: (transfer full) (type GpickControlProxy): The constructed proxy object or %NULL if @error is set. */ GpickControl * gpick_control_proxy_new_finish ( GAsyncResult *res, GError **error) { GObject *ret; GObject *source_object; source_object = g_async_result_get_source_object (res); ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); g_object_unref (source_object); if (ret != NULL) return GPICK_CONTROL (ret); else return NULL; } /** * gpick_control_proxy_new_sync: * @connection: A #GDBusConnection. * @flags: Flags from the #GDBusProxyFlags enumeration. * @name: (allow-none): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL * * Synchronously creates a proxy for the D-Bus interface org.gpick.Control. See g_dbus_proxy_new_sync() for more details. * * The calling thread is blocked until a reply is received. * * See gpick_control_proxy_new() for the asynchronous version of this constructor. * * Returns: (transfer full) (type GpickControlProxy): The constructed proxy object or %NULL if @error is set. */ GpickControl * gpick_control_proxy_new_sync ( GDBusConnection *connection, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GError **error) { GInitable *ret; ret = g_initable_new (GPICK_TYPE_CONTROL_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-connection", connection, "g-object-path", object_path, "g-interface-name", "org.gpick.Control", NULL); if (ret != NULL) return GPICK_CONTROL (ret); else return NULL; } /** * gpick_control_proxy_new_for_bus: * @bus_type: A #GBusType. * @flags: Flags from the #GDBusProxyFlags enumeration. * @name: A bus name (well-known or unique). * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied. * @user_data: User data to pass to @callback. * * Like gpick_control_proxy_new() but takes a #GBusType instead of a #GDBusConnection. * * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. * You can then call gpick_control_proxy_new_for_bus_finish() to get the result of the operation. * * See gpick_control_proxy_new_for_bus_sync() for the synchronous, blocking version of this constructor. */ void gpick_control_proxy_new_for_bus ( GBusType bus_type, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_async_initable_new_async (GPICK_TYPE_CONTROL_PROXY, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "org.gpick.Control", NULL); } /** * gpick_control_proxy_new_for_bus_finish: * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to gpick_control_proxy_new_for_bus(). * @error: Return location for error or %NULL * * Finishes an operation started with gpick_control_proxy_new_for_bus(). * * Returns: (transfer full) (type GpickControlProxy): The constructed proxy object or %NULL if @error is set. */ GpickControl * gpick_control_proxy_new_for_bus_finish ( GAsyncResult *res, GError **error) { GObject *ret; GObject *source_object; source_object = g_async_result_get_source_object (res); ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); g_object_unref (source_object); if (ret != NULL) return GPICK_CONTROL (ret); else return NULL; } /** * gpick_control_proxy_new_for_bus_sync: * @bus_type: A #GBusType. * @flags: Flags from the #GDBusProxyFlags enumeration. * @name: A bus name (well-known or unique). * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL * * Like gpick_control_proxy_new_sync() but takes a #GBusType instead of a #GDBusConnection. * * The calling thread is blocked until a reply is received. * * See gpick_control_proxy_new_for_bus() for the asynchronous version of this constructor. * * Returns: (transfer full) (type GpickControlProxy): The constructed proxy object or %NULL if @error is set. */ GpickControl * gpick_control_proxy_new_for_bus_sync ( GBusType bus_type, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GError **error) { GInitable *ret; ret = g_initable_new (GPICK_TYPE_CONTROL_PROXY, cancellable, error, "g-flags", flags, "g-name", name, "g-bus-type", bus_type, "g-object-path", object_path, "g-interface-name", "org.gpick.Control", NULL); if (ret != NULL) return GPICK_CONTROL (ret); else return NULL; } /* ------------------------------------------------------------------------ */ /** * GpickControlSkeleton: * * The #GpickControlSkeleton structure contains only private data and should only be accessed using the provided API. */ /** * GpickControlSkeletonClass: * @parent_class: The parent class. * * Class structure for #GpickControlSkeleton. */ struct _GpickControlSkeletonPrivate { GValue *properties; GList *changed_properties; GSource *changed_properties_idle_source; GMainContext *context; GMutex lock; }; static void _gpick_control_skeleton_handle_method_call ( GDBusConnection *connection G_GNUC_UNUSED, const gchar *sender G_GNUC_UNUSED, const gchar *object_path G_GNUC_UNUSED, const gchar *interface_name, const gchar *method_name, GVariant *parameters, GDBusMethodInvocation *invocation, gpointer user_data) { GpickControlSkeleton *skeleton = GPICK_CONTROL_SKELETON (user_data); _ExtendedGDBusMethodInfo *info; GVariantIter iter; GVariant *child; GValue *paramv; guint num_params; guint num_extra; guint n; guint signal_id; GValue return_value = G_VALUE_INIT; info = (_ExtendedGDBusMethodInfo *) g_dbus_method_invocation_get_method_info (invocation); g_assert (info != NULL); num_params = g_variant_n_children (parameters); num_extra = info->pass_fdlist ? 3 : 2; paramv = g_new0 (GValue, num_params + num_extra); n = 0; g_value_init (¶mv[n], GPICK_TYPE_CONTROL); g_value_set_object (¶mv[n++], skeleton); g_value_init (¶mv[n], G_TYPE_DBUS_METHOD_INVOCATION); g_value_set_object (¶mv[n++], invocation); if (info->pass_fdlist) { #ifdef G_OS_UNIX g_value_init (¶mv[n], G_TYPE_UNIX_FD_LIST); g_value_set_object (¶mv[n++], g_dbus_message_get_unix_fd_list (g_dbus_method_invocation_get_message (invocation))); #else g_assert_not_reached (); #endif } g_variant_iter_init (&iter, parameters); while ((child = g_variant_iter_next_value (&iter)) != NULL) { _ExtendedGDBusArgInfo *arg_info = (_ExtendedGDBusArgInfo *) info->parent_struct.in_args[n - num_extra]; if (arg_info->use_gvariant) { g_value_init (¶mv[n], G_TYPE_VARIANT); g_value_set_variant (¶mv[n], child); n++; } else g_dbus_gvariant_to_gvalue (child, ¶mv[n++]); g_variant_unref (child); } signal_id = g_signal_lookup (info->signal_name, GPICK_TYPE_CONTROL); g_value_init (&return_value, G_TYPE_BOOLEAN); g_signal_emitv (paramv, signal_id, 0, &return_value); if (!g_value_get_boolean (&return_value)) g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD, "Method %s is not implemented on interface %s", method_name, interface_name); g_value_unset (&return_value); for (n = 0; n < num_params + num_extra; n++) g_value_unset (¶mv[n]); g_free (paramv); } static GVariant * _gpick_control_skeleton_handle_get_property ( GDBusConnection *connection G_GNUC_UNUSED, const gchar *sender G_GNUC_UNUSED, const gchar *object_path G_GNUC_UNUSED, const gchar *interface_name G_GNUC_UNUSED, const gchar *property_name, GError **error, gpointer user_data) { GpickControlSkeleton *skeleton = GPICK_CONTROL_SKELETON (user_data); GValue value = G_VALUE_INIT; GParamSpec *pspec; _ExtendedGDBusPropertyInfo *info; GVariant *ret; ret = NULL; info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_gpick_control_interface_info.parent_struct, property_name); g_assert (info != NULL); pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); if (pspec == NULL) { g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); } else { g_value_init (&value, pspec->value_type); g_object_get_property (G_OBJECT (skeleton), info->hyphen_name, &value); ret = g_dbus_gvalue_to_gvariant (&value, G_VARIANT_TYPE (info->parent_struct.signature)); g_value_unset (&value); } return ret; } static gboolean _gpick_control_skeleton_handle_set_property ( GDBusConnection *connection G_GNUC_UNUSED, const gchar *sender G_GNUC_UNUSED, const gchar *object_path G_GNUC_UNUSED, const gchar *interface_name G_GNUC_UNUSED, const gchar *property_name, GVariant *variant, GError **error, gpointer user_data) { GpickControlSkeleton *skeleton = GPICK_CONTROL_SKELETON (user_data); GValue value = G_VALUE_INIT; GParamSpec *pspec; _ExtendedGDBusPropertyInfo *info; gboolean ret; ret = FALSE; info = (_ExtendedGDBusPropertyInfo *) g_dbus_interface_info_lookup_property ((GDBusInterfaceInfo *) &_gpick_control_interface_info.parent_struct, property_name); g_assert (info != NULL); pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (skeleton), info->hyphen_name); if (pspec == NULL) { g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "No property with name %s", property_name); } else { if (info->use_gvariant) g_value_set_variant (&value, variant); else g_dbus_gvariant_to_gvalue (variant, &value); g_object_set_property (G_OBJECT (skeleton), info->hyphen_name, &value); g_value_unset (&value); ret = TRUE; } return ret; } static const GDBusInterfaceVTable _gpick_control_skeleton_vtable = { _gpick_control_skeleton_handle_method_call, _gpick_control_skeleton_handle_get_property, _gpick_control_skeleton_handle_set_property, {NULL} }; static GDBusInterfaceInfo * gpick_control_skeleton_dbus_interface_get_info (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) { return gpick_control_interface_info (); } static GDBusInterfaceVTable * gpick_control_skeleton_dbus_interface_get_vtable (GDBusInterfaceSkeleton *skeleton G_GNUC_UNUSED) { return (GDBusInterfaceVTable *) &_gpick_control_skeleton_vtable; } static GVariant * gpick_control_skeleton_dbus_interface_get_properties (GDBusInterfaceSkeleton *_skeleton) { GpickControlSkeleton *skeleton = GPICK_CONTROL_SKELETON (_skeleton); GVariantBuilder builder; guint n; g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}")); if (_gpick_control_interface_info.parent_struct.properties == NULL) goto out; for (n = 0; _gpick_control_interface_info.parent_struct.properties[n] != NULL; n++) { GDBusPropertyInfo *info = _gpick_control_interface_info.parent_struct.properties[n]; if (info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE) { GVariant *value; value = _gpick_control_skeleton_handle_get_property (g_dbus_interface_skeleton_get_connection (G_DBUS_INTERFACE_SKELETON (skeleton)), NULL, g_dbus_interface_skeleton_get_object_path (G_DBUS_INTERFACE_SKELETON (skeleton)), "org.gpick.Control", info->name, NULL, skeleton); if (value != NULL) { g_variant_take_ref (value); g_variant_builder_add (&builder, "{sv}", info->name, value); g_variant_unref (value); } } } out: return g_variant_builder_end (&builder); } static void gpick_control_skeleton_dbus_interface_flush (GDBusInterfaceSkeleton *_skeleton) { } static void gpick_control_skeleton_iface_init (GpickControlIface *iface); #if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 G_DEFINE_TYPE_WITH_CODE (GpickControlSkeleton, gpick_control_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, G_ADD_PRIVATE (GpickControlSkeleton) G_IMPLEMENT_INTERFACE (GPICK_TYPE_CONTROL, gpick_control_skeleton_iface_init)); #else G_DEFINE_TYPE_WITH_CODE (GpickControlSkeleton, gpick_control_skeleton, G_TYPE_DBUS_INTERFACE_SKELETON, G_IMPLEMENT_INTERFACE (GPICK_TYPE_CONTROL, gpick_control_skeleton_iface_init)); #endif static void gpick_control_skeleton_finalize (GObject *object) { GpickControlSkeleton *skeleton = GPICK_CONTROL_SKELETON (object); g_list_free_full (skeleton->priv->changed_properties, (GDestroyNotify) _changed_property_free); if (skeleton->priv->changed_properties_idle_source != NULL) g_source_destroy (skeleton->priv->changed_properties_idle_source); g_main_context_unref (skeleton->priv->context); g_mutex_clear (&skeleton->priv->lock); G_OBJECT_CLASS (gpick_control_skeleton_parent_class)->finalize (object); } static void gpick_control_skeleton_init (GpickControlSkeleton *skeleton) { #if GLIB_VERSION_MAX_ALLOWED >= GLIB_VERSION_2_38 skeleton->priv = gpick_control_skeleton_get_instance_private (skeleton); #else skeleton->priv = G_TYPE_INSTANCE_GET_PRIVATE (skeleton, GPICK_TYPE_CONTROL_SKELETON, GpickControlSkeletonPrivate); #endif g_mutex_init (&skeleton->priv->lock); skeleton->priv->context = g_main_context_ref_thread_default (); } static void gpick_control_skeleton_class_init (GpickControlSkeletonClass *klass) { GObjectClass *gobject_class; GDBusInterfaceSkeletonClass *skeleton_class; gobject_class = G_OBJECT_CLASS (klass); gobject_class->finalize = gpick_control_skeleton_finalize; skeleton_class = G_DBUS_INTERFACE_SKELETON_CLASS (klass); skeleton_class->get_info = gpick_control_skeleton_dbus_interface_get_info; skeleton_class->get_properties = gpick_control_skeleton_dbus_interface_get_properties; skeleton_class->flush = gpick_control_skeleton_dbus_interface_flush; skeleton_class->get_vtable = gpick_control_skeleton_dbus_interface_get_vtable; #if GLIB_VERSION_MAX_ALLOWED < GLIB_VERSION_2_38 g_type_class_add_private (klass, sizeof (GpickControlSkeletonPrivate)); #endif } static void gpick_control_skeleton_iface_init (GpickControlIface *iface) { } /** * gpick_control_skeleton_new: * * Creates a skeleton object for the D-Bus interface org.gpick.Control. * * Returns: (transfer full) (type GpickControlSkeleton): The skeleton object. */ GpickControl * gpick_control_skeleton_new (void) { return GPICK_CONTROL (g_object_new (GPICK_TYPE_CONTROL_SKELETON, NULL)); } /* ------------------------------------------------------------------------ * Code for Object, ObjectProxy and ObjectSkeleton * ------------------------------------------------------------------------ */ /** * SECTION:GpickObject * @title: GpickObject * @short_description: Specialized GDBusObject types * * This section contains the #GpickObject, #GpickObjectProxy, and #GpickObjectSkeleton types which make it easier to work with objects implementing generated types for D-Bus interfaces. */ /** * GpickObject: * * The #GpickObject type is a specialized container of interfaces. */ /** * GpickObjectIface: * @parent_iface: The parent interface. * * Virtual table for the #GpickObject interface. */ typedef GpickObjectIface GpickObjectInterface; G_DEFINE_INTERFACE_WITH_CODE (GpickObject, gpick_object, G_TYPE_OBJECT, g_type_interface_add_prerequisite (g_define_type_id, G_TYPE_DBUS_OBJECT)); static void gpick_object_default_init (GpickObjectIface *iface) { /** * GpickObject:single-instance: * * The #GpickSingleInstance instance corresponding to the D-Bus interface org.gpick.SingleInstance, if any. * * Connect to the #GObject::notify signal to get informed of property changes. */ g_object_interface_install_property (iface, g_param_spec_object ("single-instance", "single-instance", "single-instance", GPICK_TYPE_SINGLE_INSTANCE, G_PARAM_READWRITE|G_PARAM_STATIC_STRINGS)); /** * GpickObject:control: * * The #GpickControl instance corresponding to the D-Bus interface org.gpick.Control, if any. * * Connect to the #GObject::notify signal to get informed of property changes. */ g_object_interface_install_property (iface, g_param_spec_object ("control", "control", "control", GPICK_TYPE_CONTROL, G_PARAM_READWRITE|G_PARAM_STATIC_STRINGS)); } /** * gpick_object_get_single_instance: * @object: A #GpickObject. * * Gets the #GpickSingleInstance instance for the D-Bus interface org.gpick.SingleInstance on @object, if any. * * Returns: (transfer full): A #GpickSingleInstance that must be freed with g_object_unref() or %NULL if @object does not implement the interface. */ GpickSingleInstance *gpick_object_get_single_instance (GpickObject *object) { GDBusInterface *ret; ret = g_dbus_object_get_interface (G_DBUS_OBJECT (object), "org.gpick.SingleInstance"); if (ret == NULL) return NULL; return GPICK_SINGLE_INSTANCE (ret); } /** * gpick_object_get_control: * @object: A #GpickObject. * * Gets the #GpickControl instance for the D-Bus interface org.gpick.Control on @object, if any. * * Returns: (transfer full): A #GpickControl that must be freed with g_object_unref() or %NULL if @object does not implement the interface. */ GpickControl *gpick_object_get_control (GpickObject *object) { GDBusInterface *ret; ret = g_dbus_object_get_interface (G_DBUS_OBJECT (object), "org.gpick.Control"); if (ret == NULL) return NULL; return GPICK_CONTROL (ret); } /** * gpick_object_peek_single_instance: (skip) * @object: A #GpickObject. * * Like gpick_object_get_single_instance() but doesn't increase the reference count on the returned object. * * It is not safe to use the returned object if you are on another thread than the one where the #GDBusObjectManagerClient or #GDBusObjectManagerServer for @object is running. * * Returns: (transfer none): A #GpickSingleInstance or %NULL if @object does not implement the interface. Do not free the returned object, it is owned by @object. */ GpickSingleInstance *gpick_object_peek_single_instance (GpickObject *object) { GDBusInterface *ret; ret = g_dbus_object_get_interface (G_DBUS_OBJECT (object), "org.gpick.SingleInstance"); if (ret == NULL) return NULL; g_object_unref (ret); return GPICK_SINGLE_INSTANCE (ret); } /** * gpick_object_peek_control: (skip) * @object: A #GpickObject. * * Like gpick_object_get_control() but doesn't increase the reference count on the returned object. * * It is not safe to use the returned object if you are on another thread than the one where the #GDBusObjectManagerClient or #GDBusObjectManagerServer for @object is running. * * Returns: (transfer none): A #GpickControl or %NULL if @object does not implement the interface. Do not free the returned object, it is owned by @object. */ GpickControl *gpick_object_peek_control (GpickObject *object) { GDBusInterface *ret; ret = g_dbus_object_get_interface (G_DBUS_OBJECT (object), "org.gpick.Control"); if (ret == NULL) return NULL; g_object_unref (ret); return GPICK_CONTROL (ret); } static void gpick_object_notify (GDBusObject *object, GDBusInterface *interface) { _ExtendedGDBusInterfaceInfo *info = (_ExtendedGDBusInterfaceInfo *) g_dbus_interface_get_info (interface); /* info can be NULL if the other end is using a D-Bus interface we don't know * anything about, for example old generated code in this process talking to * newer generated code in the other process. */ if (info != NULL) g_object_notify (G_OBJECT (object), info->hyphen_name); } /** * GpickObjectProxy: * * The #GpickObjectProxy structure contains only private data and should only be accessed using the provided API. */ /** * GpickObjectProxyClass: * @parent_class: The parent class. * * Class structure for #GpickObjectProxy. */ static void gpick_object_proxy__gpick_object_iface_init (GpickObjectIface *iface G_GNUC_UNUSED) { } static void gpick_object_proxy__g_dbus_object_iface_init (GDBusObjectIface *iface) { iface->interface_added = gpick_object_notify; iface->interface_removed = gpick_object_notify; } G_DEFINE_TYPE_WITH_CODE (GpickObjectProxy, gpick_object_proxy, G_TYPE_DBUS_OBJECT_PROXY, G_IMPLEMENT_INTERFACE (GPICK_TYPE_OBJECT, gpick_object_proxy__gpick_object_iface_init) G_IMPLEMENT_INTERFACE (G_TYPE_DBUS_OBJECT, gpick_object_proxy__g_dbus_object_iface_init)); static void gpick_object_proxy_init (GpickObjectProxy *object G_GNUC_UNUSED) { } static void gpick_object_proxy_set_property (GObject *gobject, guint prop_id, const GValue *value G_GNUC_UNUSED, GParamSpec *pspec) { G_OBJECT_WARN_INVALID_PROPERTY_ID (gobject, prop_id, pspec); } static void gpick_object_proxy_get_property (GObject *gobject, guint prop_id, GValue *value, GParamSpec *pspec) { GpickObjectProxy *object = GPICK_OBJECT_PROXY (gobject); GDBusInterface *interface; switch (prop_id) { case 1: interface = g_dbus_object_get_interface (G_DBUS_OBJECT (object), "org.gpick.SingleInstance"); g_value_take_object (value, interface); break; case 2: interface = g_dbus_object_get_interface (G_DBUS_OBJECT (object), "org.gpick.Control"); g_value_take_object (value, interface); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (gobject, prop_id, pspec); break; } } static void gpick_object_proxy_class_init (GpickObjectProxyClass *klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); gobject_class->set_property = gpick_object_proxy_set_property; gobject_class->get_property = gpick_object_proxy_get_property; g_object_class_override_property (gobject_class, 1, "single-instance"); g_object_class_override_property (gobject_class, 2, "control"); } /** * gpick_object_proxy_new: * @connection: A #GDBusConnection. * @object_path: An object path. * * Creates a new proxy object. * * Returns: (transfer full): The proxy object. */ GpickObjectProxy * gpick_object_proxy_new (GDBusConnection *connection, const gchar *object_path) { g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL); g_return_val_if_fail (g_variant_is_object_path (object_path), NULL); return GPICK_OBJECT_PROXY (g_object_new (GPICK_TYPE_OBJECT_PROXY, "g-connection", connection, "g-object-path", object_path, NULL)); } /** * GpickObjectSkeleton: * * The #GpickObjectSkeleton structure contains only private data and should only be accessed using the provided API. */ /** * GpickObjectSkeletonClass: * @parent_class: The parent class. * * Class structure for #GpickObjectSkeleton. */ static void gpick_object_skeleton__gpick_object_iface_init (GpickObjectIface *iface G_GNUC_UNUSED) { } static void gpick_object_skeleton__g_dbus_object_iface_init (GDBusObjectIface *iface) { iface->interface_added = gpick_object_notify; iface->interface_removed = gpick_object_notify; } G_DEFINE_TYPE_WITH_CODE (GpickObjectSkeleton, gpick_object_skeleton, G_TYPE_DBUS_OBJECT_SKELETON, G_IMPLEMENT_INTERFACE (GPICK_TYPE_OBJECT, gpick_object_skeleton__gpick_object_iface_init) G_IMPLEMENT_INTERFACE (G_TYPE_DBUS_OBJECT, gpick_object_skeleton__g_dbus_object_iface_init)); static void gpick_object_skeleton_init (GpickObjectSkeleton *object G_GNUC_UNUSED) { } static void gpick_object_skeleton_set_property (GObject *gobject, guint prop_id, const GValue *value, GParamSpec *pspec) { GpickObjectSkeleton *object = GPICK_OBJECT_SKELETON (gobject); GDBusInterfaceSkeleton *interface; switch (prop_id) { case 1: interface = g_value_get_object (value); if (interface != NULL) { g_warn_if_fail (GPICK_IS_SINGLE_INSTANCE (interface)); g_dbus_object_skeleton_add_interface (G_DBUS_OBJECT_SKELETON (object), interface); } else { g_dbus_object_skeleton_remove_interface_by_name (G_DBUS_OBJECT_SKELETON (object), "org.gpick.SingleInstance"); } break; case 2: interface = g_value_get_object (value); if (interface != NULL) { g_warn_if_fail (GPICK_IS_CONTROL (interface)); g_dbus_object_skeleton_add_interface (G_DBUS_OBJECT_SKELETON (object), interface); } else { g_dbus_object_skeleton_remove_interface_by_name (G_DBUS_OBJECT_SKELETON (object), "org.gpick.Control"); } break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (gobject, prop_id, pspec); break; } } static void gpick_object_skeleton_get_property (GObject *gobject, guint prop_id, GValue *value, GParamSpec *pspec) { GpickObjectSkeleton *object = GPICK_OBJECT_SKELETON (gobject); GDBusInterface *interface; switch (prop_id) { case 1: interface = g_dbus_object_get_interface (G_DBUS_OBJECT (object), "org.gpick.SingleInstance"); g_value_take_object (value, interface); break; case 2: interface = g_dbus_object_get_interface (G_DBUS_OBJECT (object), "org.gpick.Control"); g_value_take_object (value, interface); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (gobject, prop_id, pspec); break; } } static void gpick_object_skeleton_class_init (GpickObjectSkeletonClass *klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); gobject_class->set_property = gpick_object_skeleton_set_property; gobject_class->get_property = gpick_object_skeleton_get_property; g_object_class_override_property (gobject_class, 1, "single-instance"); g_object_class_override_property (gobject_class, 2, "control"); } /** * gpick_object_skeleton_new: * @object_path: An object path. * * Creates a new skeleton object. * * Returns: (transfer full): The skeleton object. */ GpickObjectSkeleton * gpick_object_skeleton_new (const gchar *object_path) { g_return_val_if_fail (g_variant_is_object_path (object_path), NULL); return GPICK_OBJECT_SKELETON (g_object_new (GPICK_TYPE_OBJECT_SKELETON, "g-object-path", object_path, NULL)); } /** * gpick_object_skeleton_set_single_instance: * @object: A #GpickObjectSkeleton. * @interface_: (allow-none): A #GpickSingleInstance or %NULL to clear the interface. * * Sets the #GpickSingleInstance instance for the D-Bus interface org.gpick.SingleInstance on @object. */ void gpick_object_skeleton_set_single_instance (GpickObjectSkeleton *object, GpickSingleInstance *interface_) { g_object_set (G_OBJECT (object), "single-instance", interface_, NULL); } /** * gpick_object_skeleton_set_control: * @object: A #GpickObjectSkeleton. * @interface_: (allow-none): A #GpickControl or %NULL to clear the interface. * * Sets the #GpickControl instance for the D-Bus interface org.gpick.Control on @object. */ void gpick_object_skeleton_set_control (GpickObjectSkeleton *object, GpickControl *interface_) { g_object_set (G_OBJECT (object), "control", interface_, NULL); } /* ------------------------------------------------------------------------ * Code for ObjectManager client * ------------------------------------------------------------------------ */ /** * SECTION:GpickObjectManagerClient * @title: GpickObjectManagerClient * @short_description: Generated GDBusObjectManagerClient type * * This section contains a #GDBusObjectManagerClient that uses gpick_object_manager_client_get_proxy_type() as the #GDBusProxyTypeFunc. */ /** * GpickObjectManagerClient: * * The #GpickObjectManagerClient structure contains only private data and should only be accessed using the provided API. */ /** * GpickObjectManagerClientClass: * @parent_class: The parent class. * * Class structure for #GpickObjectManagerClient. */ G_DEFINE_TYPE (GpickObjectManagerClient, gpick_object_manager_client, G_TYPE_DBUS_OBJECT_MANAGER_CLIENT); static void gpick_object_manager_client_init (GpickObjectManagerClient *manager G_GNUC_UNUSED) { } static void gpick_object_manager_client_class_init (GpickObjectManagerClientClass *klass G_GNUC_UNUSED) { } /** * gpick_object_manager_client_get_proxy_type: * @manager: A #GDBusObjectManagerClient. * @object_path: The object path of the remote object (unused). * @interface_name: (allow-none): Interface name of the remote object or %NULL to get the object proxy #GType. * @user_data: User data (unused). * * A #GDBusProxyTypeFunc that maps @interface_name to the generated #GDBusObjectProxy- and #GDBusProxy-derived types. * * Returns: A #GDBusProxy-derived #GType if @interface_name is not %NULL, otherwise the #GType for #GpickObjectProxy. */ GType gpick_object_manager_client_get_proxy_type (GDBusObjectManagerClient *manager G_GNUC_UNUSED, const gchar *object_path G_GNUC_UNUSED, const gchar *interface_name, gpointer user_data G_GNUC_UNUSED) { static gsize once_init_value = 0; static GHashTable *lookup_hash; GType ret; if (interface_name == NULL) return GPICK_TYPE_OBJECT_PROXY; if (g_once_init_enter (&once_init_value)) { lookup_hash = g_hash_table_new (g_str_hash, g_str_equal); g_hash_table_insert (lookup_hash, (gpointer) "org.gpick.SingleInstance", GSIZE_TO_POINTER (GPICK_TYPE_SINGLE_INSTANCE_PROXY)); g_hash_table_insert (lookup_hash, (gpointer) "org.gpick.Control", GSIZE_TO_POINTER (GPICK_TYPE_CONTROL_PROXY)); g_once_init_leave (&once_init_value, 1); } ret = (GType) GPOINTER_TO_SIZE (g_hash_table_lookup (lookup_hash, interface_name)); if (ret == (GType) 0) ret = G_TYPE_DBUS_PROXY; return ret; } /** * gpick_object_manager_client_new: * @connection: A #GDBusConnection. * @flags: Flags from the #GDBusObjectManagerClientFlags enumeration. * @name: (allow-none): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied. * @user_data: User data to pass to @callback. * * Asynchronously creates #GDBusObjectManagerClient using gpick_object_manager_client_get_proxy_type() as the #GDBusProxyTypeFunc. See g_dbus_object_manager_client_new() for more details. * * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. * You can then call gpick_object_manager_client_new_finish() to get the result of the operation. * * See gpick_object_manager_client_new_sync() for the synchronous, blocking version of this constructor. */ void gpick_object_manager_client_new ( GDBusConnection *connection, GDBusObjectManagerClientFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_async_initable_new_async (GPICK_TYPE_OBJECT_MANAGER_CLIENT, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "flags", flags, "name", name, "connection", connection, "object-path", object_path, "get-proxy-type-func", gpick_object_manager_client_get_proxy_type, NULL); } /** * gpick_object_manager_client_new_finish: * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to gpick_object_manager_client_new(). * @error: Return location for error or %NULL * * Finishes an operation started with gpick_object_manager_client_new(). * * Returns: (transfer full) (type GpickObjectManagerClient): The constructed object manager client or %NULL if @error is set. */ GDBusObjectManager * gpick_object_manager_client_new_finish ( GAsyncResult *res, GError **error) { GObject *ret; GObject *source_object; source_object = g_async_result_get_source_object (res); ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); g_object_unref (source_object); if (ret != NULL) return G_DBUS_OBJECT_MANAGER (ret); else return NULL; } /** * gpick_object_manager_client_new_sync: * @connection: A #GDBusConnection. * @flags: Flags from the #GDBusObjectManagerClientFlags enumeration. * @name: (allow-none): A bus name (well-known or unique) or %NULL if @connection is not a message bus connection. * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL * * Synchronously creates #GDBusObjectManagerClient using gpick_object_manager_client_get_proxy_type() as the #GDBusProxyTypeFunc. See g_dbus_object_manager_client_new_sync() for more details. * * The calling thread is blocked until a reply is received. * * See gpick_object_manager_client_new() for the asynchronous version of this constructor. * * Returns: (transfer full) (type GpickObjectManagerClient): The constructed object manager client or %NULL if @error is set. */ GDBusObjectManager * gpick_object_manager_client_new_sync ( GDBusConnection *connection, GDBusObjectManagerClientFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GError **error) { GInitable *ret; ret = g_initable_new (GPICK_TYPE_OBJECT_MANAGER_CLIENT, cancellable, error, "flags", flags, "name", name, "connection", connection, "object-path", object_path, "get-proxy-type-func", gpick_object_manager_client_get_proxy_type, NULL); if (ret != NULL) return G_DBUS_OBJECT_MANAGER (ret); else return NULL; } /** * gpick_object_manager_client_new_for_bus: * @bus_type: A #GBusType. * @flags: Flags from the #GDBusObjectManagerClientFlags enumeration. * @name: A bus name (well-known or unique). * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @callback: A #GAsyncReadyCallback to call when the request is satisfied. * @user_data: User data to pass to @callback. * * Like gpick_object_manager_client_new() but takes a #GBusType instead of a #GDBusConnection. * * When the operation is finished, @callback will be invoked in the thread-default main loop of the thread you are calling this method from. * You can then call gpick_object_manager_client_new_for_bus_finish() to get the result of the operation. * * See gpick_object_manager_client_new_for_bus_sync() for the synchronous, blocking version of this constructor. */ void gpick_object_manager_client_new_for_bus ( GBusType bus_type, GDBusObjectManagerClientFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data) { g_async_initable_new_async (GPICK_TYPE_OBJECT_MANAGER_CLIENT, G_PRIORITY_DEFAULT, cancellable, callback, user_data, "flags", flags, "name", name, "bus-type", bus_type, "object-path", object_path, "get-proxy-type-func", gpick_object_manager_client_get_proxy_type, NULL); } /** * gpick_object_manager_client_new_for_bus_finish: * @res: The #GAsyncResult obtained from the #GAsyncReadyCallback passed to gpick_object_manager_client_new_for_bus(). * @error: Return location for error or %NULL * * Finishes an operation started with gpick_object_manager_client_new_for_bus(). * * Returns: (transfer full) (type GpickObjectManagerClient): The constructed object manager client or %NULL if @error is set. */ GDBusObjectManager * gpick_object_manager_client_new_for_bus_finish ( GAsyncResult *res, GError **error) { GObject *ret; GObject *source_object; source_object = g_async_result_get_source_object (res); ret = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object), res, error); g_object_unref (source_object); if (ret != NULL) return G_DBUS_OBJECT_MANAGER (ret); else return NULL; } /** * gpick_object_manager_client_new_for_bus_sync: * @bus_type: A #GBusType. * @flags: Flags from the #GDBusObjectManagerClientFlags enumeration. * @name: A bus name (well-known or unique). * @object_path: An object path. * @cancellable: (allow-none): A #GCancellable or %NULL. * @error: Return location for error or %NULL * * Like gpick_object_manager_client_new_sync() but takes a #GBusType instead of a #GDBusConnection. * * The calling thread is blocked until a reply is received. * * See gpick_object_manager_client_new_for_bus() for the asynchronous version of this constructor. * * Returns: (transfer full) (type GpickObjectManagerClient): The constructed object manager client or %NULL if @error is set. */ GDBusObjectManager * gpick_object_manager_client_new_for_bus_sync ( GBusType bus_type, GDBusObjectManagerClientFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GError **error) { GInitable *ret; ret = g_initable_new (GPICK_TYPE_OBJECT_MANAGER_CLIENT, cancellable, error, "flags", flags, "name", name, "bus-type", bus_type, "object-path", object_path, "get-proxy-type-func", gpick_object_manager_client_get_proxy_type, NULL); if (ret != NULL) return G_DBUS_OBJECT_MANAGER (ret); else return NULL; } gpick-gpick-0.2.6rc1/source/dbus/DbusInterface.h000066400000000000000000000451041315430016700214450ustar00rootroot00000000000000/* * Generated by gdbus-codegen 2.48.0. DO NOT EDIT. * * The license of this code is the same as for the source it was derived from. */ #ifndef __DBUSINTERFACE_H__ #define __DBUSINTERFACE_H__ #include G_BEGIN_DECLS /* ------------------------------------------------------------------------ */ /* Declarations for org.gpick.SingleInstance */ #define GPICK_TYPE_SINGLE_INSTANCE (gpick_single_instance_get_type ()) #define GPICK_SINGLE_INSTANCE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GPICK_TYPE_SINGLE_INSTANCE, GpickSingleInstance)) #define GPICK_IS_SINGLE_INSTANCE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GPICK_TYPE_SINGLE_INSTANCE)) #define GPICK_SINGLE_INSTANCE_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), GPICK_TYPE_SINGLE_INSTANCE, GpickSingleInstanceIface)) struct _GpickSingleInstance; typedef struct _GpickSingleInstance GpickSingleInstance; typedef struct _GpickSingleInstanceIface GpickSingleInstanceIface; struct _GpickSingleInstanceIface { GTypeInterface parent_iface; gboolean (*handle_activate) ( GpickSingleInstance *object, GDBusMethodInvocation *invocation); }; GType gpick_single_instance_get_type (void) G_GNUC_CONST; GDBusInterfaceInfo *gpick_single_instance_interface_info (void); guint gpick_single_instance_override_properties (GObjectClass *klass, guint property_id_begin); /* D-Bus method call completion functions: */ void gpick_single_instance_complete_activate ( GpickSingleInstance *object, GDBusMethodInvocation *invocation); /* D-Bus method calls: */ void gpick_single_instance_call_activate ( GpickSingleInstance *proxy, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); gboolean gpick_single_instance_call_activate_finish ( GpickSingleInstance *proxy, GAsyncResult *res, GError **error); gboolean gpick_single_instance_call_activate_sync ( GpickSingleInstance *proxy, GCancellable *cancellable, GError **error); /* ---- */ #define GPICK_TYPE_SINGLE_INSTANCE_PROXY (gpick_single_instance_proxy_get_type ()) #define GPICK_SINGLE_INSTANCE_PROXY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GPICK_TYPE_SINGLE_INSTANCE_PROXY, GpickSingleInstanceProxy)) #define GPICK_SINGLE_INSTANCE_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), GPICK_TYPE_SINGLE_INSTANCE_PROXY, GpickSingleInstanceProxyClass)) #define GPICK_SINGLE_INSTANCE_PROXY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GPICK_TYPE_SINGLE_INSTANCE_PROXY, GpickSingleInstanceProxyClass)) #define GPICK_IS_SINGLE_INSTANCE_PROXY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GPICK_TYPE_SINGLE_INSTANCE_PROXY)) #define GPICK_IS_SINGLE_INSTANCE_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GPICK_TYPE_SINGLE_INSTANCE_PROXY)) typedef struct _GpickSingleInstanceProxy GpickSingleInstanceProxy; typedef struct _GpickSingleInstanceProxyClass GpickSingleInstanceProxyClass; typedef struct _GpickSingleInstanceProxyPrivate GpickSingleInstanceProxyPrivate; struct _GpickSingleInstanceProxy { /*< private >*/ GDBusProxy parent_instance; GpickSingleInstanceProxyPrivate *priv; }; struct _GpickSingleInstanceProxyClass { GDBusProxyClass parent_class; }; GType gpick_single_instance_proxy_get_type (void) G_GNUC_CONST; #if GLIB_CHECK_VERSION(2, 44, 0) G_DEFINE_AUTOPTR_CLEANUP_FUNC (GpickSingleInstanceProxy, g_object_unref) #endif void gpick_single_instance_proxy_new ( GDBusConnection *connection, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); GpickSingleInstance *gpick_single_instance_proxy_new_finish ( GAsyncResult *res, GError **error); GpickSingleInstance *gpick_single_instance_proxy_new_sync ( GDBusConnection *connection, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GError **error); void gpick_single_instance_proxy_new_for_bus ( GBusType bus_type, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); GpickSingleInstance *gpick_single_instance_proxy_new_for_bus_finish ( GAsyncResult *res, GError **error); GpickSingleInstance *gpick_single_instance_proxy_new_for_bus_sync ( GBusType bus_type, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GError **error); /* ---- */ #define GPICK_TYPE_SINGLE_INSTANCE_SKELETON (gpick_single_instance_skeleton_get_type ()) #define GPICK_SINGLE_INSTANCE_SKELETON(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GPICK_TYPE_SINGLE_INSTANCE_SKELETON, GpickSingleInstanceSkeleton)) #define GPICK_SINGLE_INSTANCE_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), GPICK_TYPE_SINGLE_INSTANCE_SKELETON, GpickSingleInstanceSkeletonClass)) #define GPICK_SINGLE_INSTANCE_SKELETON_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GPICK_TYPE_SINGLE_INSTANCE_SKELETON, GpickSingleInstanceSkeletonClass)) #define GPICK_IS_SINGLE_INSTANCE_SKELETON(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GPICK_TYPE_SINGLE_INSTANCE_SKELETON)) #define GPICK_IS_SINGLE_INSTANCE_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GPICK_TYPE_SINGLE_INSTANCE_SKELETON)) typedef struct _GpickSingleInstanceSkeleton GpickSingleInstanceSkeleton; typedef struct _GpickSingleInstanceSkeletonClass GpickSingleInstanceSkeletonClass; typedef struct _GpickSingleInstanceSkeletonPrivate GpickSingleInstanceSkeletonPrivate; struct _GpickSingleInstanceSkeleton { /*< private >*/ GDBusInterfaceSkeleton parent_instance; GpickSingleInstanceSkeletonPrivate *priv; }; struct _GpickSingleInstanceSkeletonClass { GDBusInterfaceSkeletonClass parent_class; }; GType gpick_single_instance_skeleton_get_type (void) G_GNUC_CONST; #if GLIB_CHECK_VERSION(2, 44, 0) G_DEFINE_AUTOPTR_CLEANUP_FUNC (GpickSingleInstanceSkeleton, g_object_unref) #endif GpickSingleInstance *gpick_single_instance_skeleton_new (void); /* ------------------------------------------------------------------------ */ /* Declarations for org.gpick.Control */ #define GPICK_TYPE_CONTROL (gpick_control_get_type ()) #define GPICK_CONTROL(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GPICK_TYPE_CONTROL, GpickControl)) #define GPICK_IS_CONTROL(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GPICK_TYPE_CONTROL)) #define GPICK_CONTROL_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), GPICK_TYPE_CONTROL, GpickControlIface)) struct _GpickControl; typedef struct _GpickControl GpickControl; typedef struct _GpickControlIface GpickControlIface; struct _GpickControlIface { GTypeInterface parent_iface; gboolean (*handle_activate_floating_picker) ( GpickControl *object, GDBusMethodInvocation *invocation, const gchar *arg_converter_name); gboolean (*handle_check_if_running) ( GpickControl *object, GDBusMethodInvocation *invocation); }; GType gpick_control_get_type (void) G_GNUC_CONST; GDBusInterfaceInfo *gpick_control_interface_info (void); guint gpick_control_override_properties (GObjectClass *klass, guint property_id_begin); /* D-Bus method call completion functions: */ void gpick_control_complete_activate_floating_picker ( GpickControl *object, GDBusMethodInvocation *invocation); void gpick_control_complete_check_if_running ( GpickControl *object, GDBusMethodInvocation *invocation); /* D-Bus method calls: */ void gpick_control_call_activate_floating_picker ( GpickControl *proxy, const gchar *arg_converter_name, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); gboolean gpick_control_call_activate_floating_picker_finish ( GpickControl *proxy, GAsyncResult *res, GError **error); gboolean gpick_control_call_activate_floating_picker_sync ( GpickControl *proxy, const gchar *arg_converter_name, GCancellable *cancellable, GError **error); void gpick_control_call_check_if_running ( GpickControl *proxy, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); gboolean gpick_control_call_check_if_running_finish ( GpickControl *proxy, GAsyncResult *res, GError **error); gboolean gpick_control_call_check_if_running_sync ( GpickControl *proxy, GCancellable *cancellable, GError **error); /* ---- */ #define GPICK_TYPE_CONTROL_PROXY (gpick_control_proxy_get_type ()) #define GPICK_CONTROL_PROXY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GPICK_TYPE_CONTROL_PROXY, GpickControlProxy)) #define GPICK_CONTROL_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), GPICK_TYPE_CONTROL_PROXY, GpickControlProxyClass)) #define GPICK_CONTROL_PROXY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GPICK_TYPE_CONTROL_PROXY, GpickControlProxyClass)) #define GPICK_IS_CONTROL_PROXY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GPICK_TYPE_CONTROL_PROXY)) #define GPICK_IS_CONTROL_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GPICK_TYPE_CONTROL_PROXY)) typedef struct _GpickControlProxy GpickControlProxy; typedef struct _GpickControlProxyClass GpickControlProxyClass; typedef struct _GpickControlProxyPrivate GpickControlProxyPrivate; struct _GpickControlProxy { /*< private >*/ GDBusProxy parent_instance; GpickControlProxyPrivate *priv; }; struct _GpickControlProxyClass { GDBusProxyClass parent_class; }; GType gpick_control_proxy_get_type (void) G_GNUC_CONST; #if GLIB_CHECK_VERSION(2, 44, 0) G_DEFINE_AUTOPTR_CLEANUP_FUNC (GpickControlProxy, g_object_unref) #endif void gpick_control_proxy_new ( GDBusConnection *connection, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); GpickControl *gpick_control_proxy_new_finish ( GAsyncResult *res, GError **error); GpickControl *gpick_control_proxy_new_sync ( GDBusConnection *connection, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GError **error); void gpick_control_proxy_new_for_bus ( GBusType bus_type, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); GpickControl *gpick_control_proxy_new_for_bus_finish ( GAsyncResult *res, GError **error); GpickControl *gpick_control_proxy_new_for_bus_sync ( GBusType bus_type, GDBusProxyFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GError **error); /* ---- */ #define GPICK_TYPE_CONTROL_SKELETON (gpick_control_skeleton_get_type ()) #define GPICK_CONTROL_SKELETON(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GPICK_TYPE_CONTROL_SKELETON, GpickControlSkeleton)) #define GPICK_CONTROL_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), GPICK_TYPE_CONTROL_SKELETON, GpickControlSkeletonClass)) #define GPICK_CONTROL_SKELETON_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GPICK_TYPE_CONTROL_SKELETON, GpickControlSkeletonClass)) #define GPICK_IS_CONTROL_SKELETON(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GPICK_TYPE_CONTROL_SKELETON)) #define GPICK_IS_CONTROL_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GPICK_TYPE_CONTROL_SKELETON)) typedef struct _GpickControlSkeleton GpickControlSkeleton; typedef struct _GpickControlSkeletonClass GpickControlSkeletonClass; typedef struct _GpickControlSkeletonPrivate GpickControlSkeletonPrivate; struct _GpickControlSkeleton { /*< private >*/ GDBusInterfaceSkeleton parent_instance; GpickControlSkeletonPrivate *priv; }; struct _GpickControlSkeletonClass { GDBusInterfaceSkeletonClass parent_class; }; GType gpick_control_skeleton_get_type (void) G_GNUC_CONST; #if GLIB_CHECK_VERSION(2, 44, 0) G_DEFINE_AUTOPTR_CLEANUP_FUNC (GpickControlSkeleton, g_object_unref) #endif GpickControl *gpick_control_skeleton_new (void); /* ---- */ #define GPICK_TYPE_OBJECT (gpick_object_get_type ()) #define GPICK_OBJECT(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GPICK_TYPE_OBJECT, GpickObject)) #define GPICK_IS_OBJECT(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GPICK_TYPE_OBJECT)) #define GPICK_OBJECT_GET_IFACE(o) (G_TYPE_INSTANCE_GET_INTERFACE ((o), GPICK_TYPE_OBJECT, GpickObject)) struct _GpickObject; typedef struct _GpickObject GpickObject; typedef struct _GpickObjectIface GpickObjectIface; struct _GpickObjectIface { GTypeInterface parent_iface; }; GType gpick_object_get_type (void) G_GNUC_CONST; GpickSingleInstance *gpick_object_get_single_instance (GpickObject *object); GpickControl *gpick_object_get_control (GpickObject *object); GpickSingleInstance *gpick_object_peek_single_instance (GpickObject *object); GpickControl *gpick_object_peek_control (GpickObject *object); #define GPICK_TYPE_OBJECT_PROXY (gpick_object_proxy_get_type ()) #define GPICK_OBJECT_PROXY(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GPICK_TYPE_OBJECT_PROXY, GpickObjectProxy)) #define GPICK_OBJECT_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), GPICK_TYPE_OBJECT_PROXY, GpickObjectProxyClass)) #define GPICK_OBJECT_PROXY_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GPICK_TYPE_OBJECT_PROXY, GpickObjectProxyClass)) #define GPICK_IS_OBJECT_PROXY(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GPICK_TYPE_OBJECT_PROXY)) #define GPICK_IS_OBJECT_PROXY_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GPICK_TYPE_OBJECT_PROXY)) typedef struct _GpickObjectProxy GpickObjectProxy; typedef struct _GpickObjectProxyClass GpickObjectProxyClass; typedef struct _GpickObjectProxyPrivate GpickObjectProxyPrivate; struct _GpickObjectProxy { /*< private >*/ GDBusObjectProxy parent_instance; GpickObjectProxyPrivate *priv; }; struct _GpickObjectProxyClass { GDBusObjectProxyClass parent_class; }; GType gpick_object_proxy_get_type (void) G_GNUC_CONST; #if GLIB_CHECK_VERSION(2, 44, 0) G_DEFINE_AUTOPTR_CLEANUP_FUNC (GpickObjectProxy, g_object_unref) #endif GpickObjectProxy *gpick_object_proxy_new (GDBusConnection *connection, const gchar *object_path); #define GPICK_TYPE_OBJECT_SKELETON (gpick_object_skeleton_get_type ()) #define GPICK_OBJECT_SKELETON(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GPICK_TYPE_OBJECT_SKELETON, GpickObjectSkeleton)) #define GPICK_OBJECT_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), GPICK_TYPE_OBJECT_SKELETON, GpickObjectSkeletonClass)) #define GPICK_OBJECT_SKELETON_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GPICK_TYPE_OBJECT_SKELETON, GpickObjectSkeletonClass)) #define GPICK_IS_OBJECT_SKELETON(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GPICK_TYPE_OBJECT_SKELETON)) #define GPICK_IS_OBJECT_SKELETON_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GPICK_TYPE_OBJECT_SKELETON)) typedef struct _GpickObjectSkeleton GpickObjectSkeleton; typedef struct _GpickObjectSkeletonClass GpickObjectSkeletonClass; typedef struct _GpickObjectSkeletonPrivate GpickObjectSkeletonPrivate; struct _GpickObjectSkeleton { /*< private >*/ GDBusObjectSkeleton parent_instance; GpickObjectSkeletonPrivate *priv; }; struct _GpickObjectSkeletonClass { GDBusObjectSkeletonClass parent_class; }; GType gpick_object_skeleton_get_type (void) G_GNUC_CONST; #if GLIB_CHECK_VERSION(2, 44, 0) G_DEFINE_AUTOPTR_CLEANUP_FUNC (GpickObjectSkeleton, g_object_unref) #endif GpickObjectSkeleton *gpick_object_skeleton_new (const gchar *object_path); void gpick_object_skeleton_set_single_instance (GpickObjectSkeleton *object, GpickSingleInstance *interface_); void gpick_object_skeleton_set_control (GpickObjectSkeleton *object, GpickControl *interface_); /* ---- */ #define GPICK_TYPE_OBJECT_MANAGER_CLIENT (gpick_object_manager_client_get_type ()) #define GPICK_OBJECT_MANAGER_CLIENT(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), GPICK_TYPE_OBJECT_MANAGER_CLIENT, GpickObjectManagerClient)) #define GPICK_OBJECT_MANAGER_CLIENT_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), GPICK_TYPE_OBJECT_MANAGER_CLIENT, GpickObjectManagerClientClass)) #define GPICK_OBJECT_MANAGER_CLIENT_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), GPICK_TYPE_OBJECT_MANAGER_CLIENT, GpickObjectManagerClientClass)) #define GPICK_IS_OBJECT_MANAGER_CLIENT(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), GPICK_TYPE_OBJECT_MANAGER_CLIENT)) #define GPICK_IS_OBJECT_MANAGER_CLIENT_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GPICK_TYPE_OBJECT_MANAGER_CLIENT)) typedef struct _GpickObjectManagerClient GpickObjectManagerClient; typedef struct _GpickObjectManagerClientClass GpickObjectManagerClientClass; typedef struct _GpickObjectManagerClientPrivate GpickObjectManagerClientPrivate; struct _GpickObjectManagerClient { /*< private >*/ GDBusObjectManagerClient parent_instance; GpickObjectManagerClientPrivate *priv; }; struct _GpickObjectManagerClientClass { GDBusObjectManagerClientClass parent_class; }; #if GLIB_CHECK_VERSION(2, 44, 0) G_DEFINE_AUTOPTR_CLEANUP_FUNC (GpickObjectManagerClient, g_object_unref) #endif GType gpick_object_manager_client_get_type (void) G_GNUC_CONST; GType gpick_object_manager_client_get_proxy_type (GDBusObjectManagerClient *manager, const gchar *object_path, const gchar *interface_name, gpointer user_data); void gpick_object_manager_client_new ( GDBusConnection *connection, GDBusObjectManagerClientFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); GDBusObjectManager *gpick_object_manager_client_new_finish ( GAsyncResult *res, GError **error); GDBusObjectManager *gpick_object_manager_client_new_sync ( GDBusConnection *connection, GDBusObjectManagerClientFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GError **error); void gpick_object_manager_client_new_for_bus ( GBusType bus_type, GDBusObjectManagerClientFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); GDBusObjectManager *gpick_object_manager_client_new_for_bus_finish ( GAsyncResult *res, GError **error); GDBusObjectManager *gpick_object_manager_client_new_for_bus_sync ( GBusType bus_type, GDBusObjectManagerClientFlags flags, const gchar *name, const gchar *object_path, GCancellable *cancellable, GError **error); G_END_DECLS #endif /* __DBUSINTERFACE_H__ */ gpick-gpick-0.2.6rc1/source/dbus/SConscript000066400000000000000000000010031315430016700205560ustar00rootroot00000000000000#!/usr/bin/env python import os import sys Import('*') local_env = env.Clone() if not local_env.GetOption('clean') and not env['TOOLCHAIN'] == 'msvc': if not env['USE_GTK3']: local_env.ParseConfig('pkg-config --cflags $GIO_PC') else: local_env.ParseConfig('pkg-config --cflags $GTK_PC') if not env['BUILD_TARGET'] == 'win32': sources = local_env.Glob('*.c') + local_env.Glob('*.cpp') else: sources = local_env.Glob('*.cpp') objects = local_env.StaticObject(source = [sources]) Return('objects') gpick-gpick-0.2.6rc1/source/dbus/interface.xml000066400000000000000000000006021315430016700212320ustar00rootroot00000000000000 gpick-gpick-0.2.6rc1/source/dynv/000077500000000000000000000000001315430016700165755ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/source/dynv/DynvHandler.cpp000066400000000000000000000117501315430016700215230ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "DynvHandler.h" #include "DynvVariable.h" #include "DynvIO.h" #include "../Endian.h" #include #include #include #include #include using namespace std; bool dynvHandlerMap::dynvKeyCompare::operator() (const char* const& x, const char* const& y) const { return strcmp(x,y)<0; } struct dynvHandler* dynv_handler_create(const char* name){ struct dynvHandler* handler=new struct dynvHandler; handler->name=strdup(name); handler->create=nullptr; handler->destroy=nullptr; handler->set=nullptr; handler->serialize=nullptr; handler->deserialize=nullptr; handler->serialize_xml=nullptr; handler->deserialize_xml=nullptr; handler->get=nullptr; return handler; } void dynv_handler_destroy(struct dynvHandler* handler){ free(handler->name); delete handler; } struct dynvHandlerMap* dynv_handler_map_create(){ struct dynvHandlerMap* handler_map=new struct dynvHandlerMap; handler_map->refcnt=0; return handler_map; } int dynv_handler_map_release(struct dynvHandlerMap* handler_map){ if (handler_map->refcnt){ handler_map->refcnt--; return -1; }else{ dynvHandlerMap::HandlerMap::iterator i; for (i=handler_map->handlers.begin(); i != handler_map->handlers.end(); ++i){ dynv_handler_destroy((*i).second); } handler_map->handlers.clear(); delete handler_map; return 0; } } struct dynvHandlerMap* dynv_handler_map_ref(struct dynvHandlerMap* handler_map){ handler_map->refcnt++; return handler_map; } int dynv_handler_map_add_handler(struct dynvHandlerMap* handler_map, struct dynvHandler* handler){ dynvHandlerMap::HandlerMap::iterator i; i=handler_map->handlers.find(handler->name); if (i != handler_map->handlers.end()){ return -1; }else{ handler_map->handlers[handler->name]=handler; return 0; } } struct dynvHandler* dynv_handler_map_get_handler(struct dynvHandlerMap* handler_map, const char* handler_name){ dynvHandlerMap::HandlerMap::iterator i; i=handler_map->handlers.find(handler_name); if (i != handler_map->handlers.end()){ return (*i).second; }else{ return 0; } } int dynv_handler_map_serialize(struct dynvHandlerMap* handler_map, struct dynvIO* io){ dynvHandlerMap::HandlerMap::iterator i; uint32_t written, length; uint32_t id=0; uint32_t handler_count=handler_map->handlers.size(); handler_count=UINT32_TO_LE(handler_count); dynv_io_write(io, &handler_count, 4, &written); for (i=handler_map->handlers.begin(); i != handler_map->handlers.end(); ++i){ struct dynvHandler* handler=(*i).second; length=strlen(handler->name); uint32_t length_le=UINT32_TO_LE(length); dynv_io_write(io, &length_le, 4, &written); dynv_io_write(io, handler->name, length, &written); handler->id=id; id++; } return 0; } int dynv_handler_map_deserialize(struct dynvHandlerMap* handler_map, struct dynvIO* io, dynvHandlerMap::HandlerVec& handler_vec){ uint32_t read; uint32_t handler_count; uint32_t length; char* name; struct dynvHandler* handler; if (dynv_io_read(io, &handler_count, 4, &read) == 0){ if (read != 4) return -1; }else return -1; handler_count=UINT32_TO_LE(handler_count); handler_vec.resize(handler_count); for (uint32_t i=0; i != handler_count; ++i){ dynv_io_read(io, &length, 4, &read); length=UINT32_TO_LE(length); name=new char [length+1]; dynv_io_read(io, name, length, &read); name[length]=0; handler=dynv_handler_map_get_handler(handler_map, name); handler_vec[i]=handler; //cout<<"Handler: "<< name< #include #include #include #include #ifndef _MSC_VER #include #endif struct dynvIO; struct dynvHandler{ char* name; int (*set)(struct dynvVariable* variable, void* value, bool deref); int (*create)(struct dynvVariable* variable); int (*destroy)(struct dynvVariable* variable); int (*get)(struct dynvVariable* variable, void** value, bool *deref); int (*serialize)(struct dynvVariable* variable, struct dynvIO* io); int (*deserialize)(struct dynvVariable* variable, struct dynvIO* io); int (*serialize_xml)(struct dynvVariable* variable, std::ostream& out); int (*deserialize_xml)(struct dynvVariable* variable, const char* data); uint32_t id; uint32_t data_size; }; struct dynvHandler* dynv_handler_create(const char* name); void dynv_handler_destroy(struct dynvHandler* handler); struct dynvHandlerMap{ class dynvKeyCompare{ public: bool operator() (const char* const& x, const char* const& y) const; }; typedef std::map HandlerMap; typedef std::vector HandlerVec; uint32_t refcnt; HandlerMap handlers; }; struct dynvHandlerMap* dynv_handler_map_create(); int dynv_handler_map_release(struct dynvHandlerMap* handler_map); struct dynvHandlerMap* dynv_handler_map_ref(struct dynvHandlerMap* handler_map); int dynv_handler_map_add_handler(struct dynvHandlerMap* handler_map, struct dynvHandler* handler); struct dynvHandler* dynv_handler_map_get_handler(struct dynvHandlerMap* handler_map, const char* handler_name); int dynv_handler_map_serialize(struct dynvHandlerMap* handler_map, struct dynvIO* io); int dynv_handler_map_deserialize(struct dynvHandlerMap* handler_map, struct dynvIO* io, dynvHandlerMap::HandlerVec& handler_vec); #endif /* DYNVHANDLER_H_ */ gpick-gpick-0.2.6rc1/source/dynv/DynvIO.cpp000066400000000000000000000030441315430016700204520ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "DynvIO.h" gpick-gpick-0.2.6rc1/source/dynv/DynvIO.h000066400000000000000000000044151315430016700201220ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DYNVIO_H_ #define DYNVIO_H_ #include struct dynvIO{ int (*write)(struct dynvIO* io, void* data, uint32_t size, uint32_t* data_written); int (*read)(struct dynvIO* io, void* data, uint32_t size, uint32_t* data_read); int (*seek)(struct dynvIO* io, uint32_t offset, int type, uint32_t* position); int (*free)(struct dynvIO* io); int (*reset)(struct dynvIO* io); void* userdata; }; int dynv_io_write(struct dynvIO* io, void* data, uint32_t size, uint32_t* data_written); int dynv_io_read(struct dynvIO* io, void* data, uint32_t size, uint32_t* data_read); int dynv_io_seek(struct dynvIO* io, uint32_t offset, int type, uint32_t* position); int dynv_io_free(struct dynvIO* io); int dynv_io_reset(struct dynvIO* io); #endif /* DYNVIO_H_ */ gpick-gpick-0.2.6rc1/source/dynv/DynvMemoryIO.cpp000066400000000000000000000127241315430016700216500ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "DynvMemoryIO.h" #include #include struct dynvMemoryIO{ char* buffer; uint32_t size; uint32_t eof; uint32_t position; }; static int dynv_io_memory_write(struct dynvIO* io, void* data, uint32_t size, uint32_t* data_written) { struct dynvMemoryIO* mem_io = (struct dynvMemoryIO*) io->userdata; uint32_t data_left = mem_io->size - mem_io->position; if (data_left < size){ //buffer too small uint32_t new_buf = mem_io->size + size + 4096; //while (new_buf - mem_io->position < size) // new_buf *= 2; char *nb; if ((nb = new char[new_buf])){ if (mem_io->buffer){ memcpy(nb, mem_io->buffer, mem_io->position); delete[] mem_io->buffer; } mem_io->buffer = nb; mem_io->size = new_buf; }else{ *data_written = 0; return 0; } } memcpy(mem_io->buffer + mem_io->position, data, size); mem_io->position += size; if (mem_io->position > mem_io->eof) mem_io->eof = mem_io->position; *data_written = size; return 0; } static int dynv_io_memory_read(struct dynvIO* io, void* data, uint32_t size, uint32_t* data_read){ struct dynvMemoryIO* mem_io = (struct dynvMemoryIO*) io->userdata; uint32_t data_left = mem_io->eof - mem_io->position; if (size > data_left) size = data_left; memcpy(data, mem_io->buffer + mem_io->position, size); mem_io->position += size; *data_read=size; return 0; } static int dynv_io_memory_seek(struct dynvIO* io, uint32_t offset, int type, uint32_t* position){ struct dynvMemoryIO* mem_io = (struct dynvMemoryIO*) io->userdata; switch (type){ case SEEK_CUR: mem_io->position+=offset; if (mem_io->position>mem_io->eof) mem_io->position=mem_io->eof; if(position) *position=mem_io->position; return 0; break; case SEEK_SET: mem_io->position=offset; if (mem_io->position>mem_io->eof) mem_io->position=mem_io->eof; if(position) *position=mem_io->position; return 0; break; case SEEK_END: mem_io->position=mem_io->eof-offset; if (mem_io->position>mem_io->eof) mem_io->position=mem_io->eof; if(position) *position=mem_io->position; return 0; break; } return -1; } static int dynv_io_memory_free(struct dynvIO* io){ struct dynvMemoryIO* mem_io=(struct dynvMemoryIO*)io->userdata; if (mem_io->buffer) delete [] mem_io->buffer; delete mem_io; return 0; } static int dynv_io_memory_reset(struct dynvIO* io){ struct dynvMemoryIO* mem_io=(struct dynvMemoryIO*)io->userdata; mem_io->eof=0; mem_io->position=0; return 0; } struct dynvIO* dynv_io_memory_new(){ struct dynvIO* io=new struct dynvIO; struct dynvMemoryIO* mem_io=new struct dynvMemoryIO; mem_io->buffer=0; mem_io->eof=0; mem_io->position=0; mem_io->size=0; io->userdata=mem_io; io->write=dynv_io_memory_write; io->read=dynv_io_memory_read; io->seek=dynv_io_memory_seek; io->free=dynv_io_memory_free; io->reset=dynv_io_memory_reset; return io; } int dynv_io_memory_get_data(struct dynvIO* io, char** data, uint32_t* size){ struct dynvMemoryIO* mem_io=(struct dynvMemoryIO*)io->userdata; if (!mem_io) return -1; if (!mem_io->buffer) return -1; *data=mem_io->buffer; *size=mem_io->eof; return 0; } int dynv_io_memory_set_data(struct dynvIO* io, char* data, uint32_t size){ struct dynvMemoryIO* mem_io=(struct dynvMemoryIO*)io->userdata; if (!mem_io) return -1; dynv_io_memory_reset(io); uint32_t written; dynv_io_memory_write(io, data, size, &written); return 0; } int dynv_io_memory_prepare_size(struct dynvIO* io, uint32_t size){ struct dynvMemoryIO* mem_io=(struct dynvMemoryIO*)io->userdata; if (!mem_io) return -1; mem_io->eof=size; mem_io->position=0; if (mem_io->sizebuffer, mem_io->position); if (mem_io->buffer) delete[] mem_io->buffer; mem_io->buffer = nb; mem_io->size = size; return 0; }else{ return -1; } } return 0; } void* dynv_io_memory_get_buffer(struct dynvIO* io){ struct dynvMemoryIO* mem_io=(struct dynvMemoryIO*)io->userdata; if (!mem_io) return 0; return mem_io->buffer; } gpick-gpick-0.2.6rc1/source/dynv/DynvMemoryIO.h000066400000000000000000000036501315430016700213130ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DYNVMEMORYIO_H_ #define DYNVMEMORYIO_H_ #include "DynvIO.h" struct dynvIO* dynv_io_memory_new(); int dynv_io_memory_get_data(struct dynvIO* io, char** data, uint32_t* size); int dynv_io_memory_set_data(struct dynvIO* io, char* data, uint32_t size); int dynv_io_memory_prepare_size(struct dynvIO* io, uint32_t size); void* dynv_io_memory_get_buffer(struct dynvIO* io); #endif /* DYNVMEMORYIO_H_ */ gpick-gpick-0.2.6rc1/source/dynv/DynvSystem.cpp000066400000000000000000000446431315430016700214410ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "DynvSystem.h" #include "DynvVariable.h" #include "DynvIO.h" #include "../Endian.h" #include #include #include #include #include using namespace std; bool dynvSystem::dynvKeyCompare::operator() (const char* const& x, const char* const& y) const { return strcmp(x,y)<0; } struct dynvHandlerMap* dynv_system_get_handler_map(struct dynvSystem* dynv_system){ return dynv_handler_map_ref(dynv_system->handler_map); } void dynv_system_set_handler_map(struct dynvSystem* dynv_system, struct dynvHandlerMap* handler_map){ if (dynv_system->handler_map != nullptr){ dynv_handler_map_release(dynv_system->handler_map); dynv_system->handler_map=nullptr; } if (handler_map != nullptr){ dynv_system->handler_map=dynv_handler_map_ref(handler_map); } } struct dynvSystem* dynv_system_create(struct dynvHandlerMap* handler_map){ struct dynvSystem* dynv_system=new struct dynvSystem; dynv_system->handler_map=nullptr; dynv_system->refcnt=0; dynv_system_set_handler_map(dynv_system, handler_map); return dynv_system; } struct dynvSystem* dynv_system_create(struct dynvSystem* dynv_system){ struct dynvHandlerMap* handler_map = dynv_system_get_handler_map(dynv_system); struct dynvSystem* new_dynv = dynv_system_create(handler_map); dynv_handler_map_release(handler_map); return new_dynv; } int dynv_system_release(struct dynvSystem* dynv_system){ if (dynv_system->refcnt){ dynv_system->refcnt--; return -1; }else{ dynvSystem::VariableMap::iterator i; for (i=dynv_system->variables.begin(); i != dynv_system->variables.end(); ++i){ dynv_variable_destroy((*i).second); } dynv_system->variables.clear(); dynv_handler_map_release(dynv_system->handler_map); delete dynv_system; return 0; } } struct dynvSystem* dynv_system_ref(struct dynvSystem* dynv_system){ dynv_system->refcnt++; return dynv_system; } struct dynvVariable* dynv_system_add_empty(struct dynvSystem* dynv_system, struct dynvHandler* handler, const char* variable_name){ struct dynvVariable* variable=nullptr; dynvSystem::VariableMap::iterator i; i=dynv_system->variables.find(variable_name); if (i == dynv_system->variables.end()){ if (handler == nullptr) return 0; variable=dynv_variable_create(variable_name, handler); dynv_system->variables[variable->name]=variable; variable->handler->create(variable); return variable; }else{ variable=(*i).second; } if ((variable->flags & dynvVariable::Flag::read_only) == dynvVariable::Flag::read_only) return 0; if (variable->handler == handler){ return variable; }else{ if (handler->create != nullptr){ dynv_variable_destroy_data(variable); variable->handler=handler; variable->handler->create(variable); return variable; } } return 0; } int dynv_system_set(struct dynvSystem* dynv_system, const char* handler_name, const char* variable_name, void* value){ struct dynvVariable* variable=nullptr; struct dynvHandler* handler=nullptr; if (handler_name != nullptr){ dynvHandlerMap::HandlerMap::iterator j; j=dynv_system->handler_map->handlers.find(handler_name); if (j == dynv_system->handler_map->handlers.end()){ return -3; }else{ handler=(*j).second; } } dynvSystem::VariableMap::iterator i; i=dynv_system->variables.find(variable_name); if (i == dynv_system->variables.end()){ if (handler == nullptr) return -2; variable=dynv_variable_create(variable_name, handler); dynv_system->variables[variable->name]=variable; variable->handler->create(variable); return variable->handler->set(variable, value, false); }else{ variable=(*i).second; } if ((variable->flags & dynvVariable::Flag::read_only) == dynvVariable::Flag::read_only) return -4; if (variable->handler == handler){ return variable->handler->set(variable, value, false); }else{ if (handler->create != nullptr){ dynv_variable_destroy_data(variable); variable->handler=handler; variable->handler->create(variable); return variable->handler->set(variable, value, false); } } return -1; } void* dynv_system_get_r(struct dynvSystem* dynv_system, const char* handler_name, const char* variable_name, int* error){ struct dynvVariable* variable=nullptr; struct dynvHandler* handler=nullptr; int error_redir; if (error == nullptr) error = &error_redir; *error = 1; if (handler_name != nullptr){ dynvHandlerMap::HandlerMap::iterator j; j=dynv_system->handler_map->handlers.find(handler_name); if (j == dynv_system->handler_map->handlers.end()){ return 0; }else{ handler=(*j).second; } } dynvSystem::VariableMap::iterator i; i=dynv_system->variables.find(variable_name); if (i == dynv_system->variables.end()){ return 0; }else{ variable=(*i).second; } if (variable->handler == handler){ if (variable->handler->get != nullptr){ void* value = 0; bool deref = true; if (variable->handler->get(variable, &value, &deref) == 0){ *error = 0; return value; }else{ return 0; } } } return 0; } void* dynv_system_get(struct dynvSystem* dynv_system, const char* handler_name, const char* variable_name){ return dynv_system_get_r(dynv_system, handler_name, variable_name, 0); } void** dynv_system_get_array_r(struct dynvSystem* dynv_system, const char* handler_name, const char* variable_name, uint32_t *count, int* error){ struct dynvVariable* variable=nullptr; struct dynvHandler* handler=nullptr; int error_redir; if (error == nullptr) error = &error_redir; *error = 1; if (handler_name != nullptr){ dynvHandlerMap::HandlerMap::iterator j; j=dynv_system->handler_map->handlers.find(handler_name); if (j == dynv_system->handler_map->handlers.end()){ return 0; }else{ handler=(*j).second; } } dynvSystem::VariableMap::iterator i; i=dynv_system->variables.find(variable_name); if (i == dynv_system->variables.end()){ return 0; }else{ variable=(*i).second; } if (variable->handler == handler){ uint32_t n = 0; struct dynvVariable *i = variable; while (i){ n++; i = i->next; } if (count) *count = n; void** array = (void**)new char [n * handler->data_size]; void** o_array = array; i = variable; for (uint32_t j=0; j != n; j++){ void *var; bool deref = true; if (i->handler->get && i->handler->get(i, &var, &deref) == 0){ if (deref) memcpy(array, var, handler->data_size); else memcpy(array, &var, handler->data_size); }else{ memset(array, 0, handler->data_size); //array[j] = 0; } array = (void**)(((char*)array) + handler->data_size); i = i->next; } *error = 0; return o_array; } return 0; } static int build_linked_list(struct dynvVariable* start_variable, void** values, uint32_t count) { if (count < 1) return -1; dynvVariable *variable, *v; dynvHandler* handler = start_variable->handler; handler->set(start_variable, values, true); values = (void**)(((char*)values) + handler->data_size); v = start_variable; for (uint32_t i = 1; i < count; i++){ variable = dynv_variable_create(nullptr, handler); variable->handler->create(variable); variable->handler->set(variable, values, true); values = (void**)(((char*)values) + handler->data_size); v->next = variable; v = variable; } return 0; } int dynv_system_set_array(dynvSystem* dynv_system, const char* handler_name, const char* variable_name, void** values, uint32_t count) { dynvHandler* handler = nullptr; if (count < 1){ return dynv_system_remove(dynv_system, variable_name); } if (handler_name != nullptr){ auto j = dynv_system->handler_map->handlers.find(handler_name); if (j == dynv_system->handler_map->handlers.end()){ return -3; }else{ handler = (*j).second; } } dynvVariable* variable = nullptr; auto i = dynv_system->variables.find(variable_name); if (i == dynv_system->variables.end()){ if (handler == nullptr) return -2; variable = dynv_variable_create(variable_name, handler); dynv_system->variables[variable->name] = variable; variable->handler->create(variable); return build_linked_list(variable, values, count); }else{ variable = (*i).second; } if ((variable->flags & dynvVariable::Flag::read_only) == dynvVariable::Flag::read_only) return -4; dynv_variable_destroy_data(variable); variable->handler = handler; variable->handler->create(variable); return build_linked_list(variable, values, count); } int dynv_system_remove(struct dynvSystem* dynv_system, const char* variable_name){ dynvSystem::VariableMap::iterator i; i=dynv_system->variables.find(variable_name); if (i == dynv_system->variables.end()){ return -1; }else{ dynv_variable_destroy((*i).second); dynv_system->variables.erase(i); return 0; } } int dynv_system_remove_all(struct dynvSystem* dynv_system){ dynvSystem::VariableMap::iterator i; for (i=dynv_system->variables.begin(); i != dynv_system->variables.end(); ++i){ dynv_variable_destroy((*i).second); } dynv_system->variables.clear(); return 0; } struct dynvVariable* dynv_system_get_var(struct dynvSystem* dynv_system, const char* variable_name){ dynvSystem::VariableMap::iterator i; i=dynv_system->variables.find(variable_name); if (i == dynv_system->variables.end()){ return 0; }else{ return (*i).second; } } int dynv_system_serialize(struct dynvSystem* dynv_system, struct dynvIO* io){ dynvSystem::VariableMap::iterator i; uint32_t written, length, id; uint32_t variable_count=dynv_system->variables.size(); variable_count=UINT32_TO_LE(variable_count); dynv_io_write(io, &variable_count, 4, &written); uint32_t handler_count=dynv_system->handler_map->handlers.size(); int_fast32_t handler_bytes; if (handler_count<=0xFF) handler_bytes=1; else if (handler_count<=0xFFFF) handler_bytes=2; else if (handler_count<=0xFFFFFF) handler_bytes=3; else handler_bytes=4; for (i=dynv_system->variables.begin(); i != dynv_system->variables.end(); ++i){ struct dynvVariable* variable=(*i).second; id=UINT32_TO_LE(variable->handler->id); dynv_io_write(io, &id, handler_bytes, &written); length=strlen(variable->name); uint32_t length_le=UINT32_TO_LE(length); dynv_io_write(io, &length_le, 4, &written); dynv_io_write(io, variable->name, length, &written); variable->handler->serialize(variable, io); } return 0; } int dynv_system_deserialize(struct dynvSystem* dynv_system, dynvHandlerMap::HandlerVec& handler_vec, struct dynvIO* io){ uint32_t read; uint32_t variable_count, handler_id; uint32_t length=0; char* name; struct dynvVariable* variable; if (dynv_io_read(io, &variable_count, 4, &read) == 0){ if (read != 4) return -1; }else return -1; variable_count=UINT32_FROM_LE(variable_count); int_fast32_t handler_bytes; if (handler_vec.size()<=0xFF) handler_bytes=1; else if (handler_vec.size()<=0xFFFF) handler_bytes=2; else if (handler_vec.size()<=0xFFFFFF) handler_bytes=3; else handler_bytes=4; for (uint32_t i=0; i != variable_count; ++i){ handler_id=0; dynv_io_read(io, &handler_id, handler_bytes, &read); handler_id=UINT32_FROM_LE(handler_id); if ((handler_idname<deserialize(variable, io) != 0){ dynv_io_read(io, &length, 4, &read); length=UINT32_FROM_LE(length); dynv_io_seek(io, length, SEEK_CUR, 0); } }else{ //cout<<"Var: skipping val"<write(io, data, size, data_written); } int dynv_io_read(struct dynvIO* io, void* data, uint32_t size, uint32_t* data_read) { return io->read(io, data, size, data_read); } int dynv_io_seek(struct dynvIO* io, uint32_t offset, int type, uint32_t* position) { return io->seek(io, offset, type, position); } int dynv_io_free(struct dynvIO* io) { int r = io->free(io); delete io; return r; } int dynv_io_reset(struct dynvIO* io) { if (io->reset) return io->reset(io); return -1; } struct dynvSystem* dynv_system_copy(struct dynvSystem* dynv_system){ struct dynvHandlerMap* handler_map = dynv_system_get_handler_map(dynv_system); struct dynvSystem* new_dynv = dynv_system_create(handler_map); dynv_handler_map_release(handler_map); void* value; struct dynvVariable *variable, *new_variable; struct dynvHandler* handler; dynvSystem::VariableMap::iterator i; for (i=dynv_system->variables.begin(); i != dynv_system->variables.end(); ++i){ variable = (*i).second; handler = (*i).second->handler; bool deref = true; if (handler->get(variable, &value, &deref) == 0){ new_variable = dynv_variable_create(variable->name, handler); new_dynv->variables[new_variable->name] = new_variable; new_variable->handler->create(new_variable); new_variable->handler->set(new_variable, value, false); } } return new_dynv; } int dynv_set(struct dynvSystem* dynv_system, const char* handler_name, const char* variable_path, const void* value){ string path(variable_path); size_t found; struct dynvSystem* dlevel = dynv_system_ref(dynv_system); for (;;){ found = path.find('.'); if (found != string::npos){ struct dynvSystem* dlevel_new; dlevel_new = (struct dynvSystem*)dynv_system_get(dlevel, "dynv", path.substr(0, found).c_str()); if (dlevel_new){ dynv_system_release(dlevel); dlevel = dlevel_new; }else{ struct dynvHandlerMap* handler_map = dynv_system_get_handler_map(dynv_system); struct dynvSystem* dlevel_new = dynv_system_create(handler_map); dynv_handler_map_release(handler_map); dynv_system_set(dlevel, "dynv", path.substr(0, found).c_str(), dlevel_new); dynv_system_release(dlevel); dlevel = dlevel_new; } path = path.substr(found+1); }else break; } int r = dynv_system_set(dlevel, handler_name, path.c_str(), (void*)value); dynv_system_release(dlevel); return r; } int dynv_set_array(dynvSystem* dynv_system, const char* handler_name, const char* variable_path, const void** values, uint32_t count) { string path(variable_path); size_t found; dynvSystem* dlevel = dynv_system_ref(dynv_system); for (;;){ found = path.find('.'); if (found != string::npos){ dynvSystem* dlevel_new = (dynvSystem*)dynv_system_get(dlevel, "dynv", path.substr(0, found).c_str()); if (dlevel_new){ dynv_system_release(dlevel); dlevel = dlevel_new; }else{ dynvHandlerMap* handler_map = dynv_system_get_handler_map(dynv_system); dynvSystem* dlevel_new = dynv_system_create(handler_map); dynv_handler_map_release(handler_map); dynv_system_set(dlevel, "dynv", path.substr(0, found).c_str(), dlevel_new); dynv_system_release(dlevel); dlevel = dlevel_new; } path = path.substr(found+1); }else break; } int r = dynv_system_set_array(dlevel, handler_name, path.c_str(), (void**)values, count); dynv_system_release(dlevel); return r; } void* dynv_get(struct dynvSystem* dynv_system, const char* handler_name, const char* variable_path, int* error){ string path(variable_path); size_t found; int error_redir; if (error == nullptr) error = &error_redir; *error = 0; struct dynvSystem* dlevel = dynv_system_ref(dynv_system); for (;;){ found = path.find('.'); if (found != string::npos){ struct dynvSystem* dlevel_new; dlevel_new = (struct dynvSystem*)dynv_system_get(dlevel, "dynv", path.substr(0, found).c_str()); if (dlevel_new){ dynv_system_release(dlevel); dlevel = dlevel_new; }else{ dynv_system_release(dlevel); *error = 1; return 0; } path = path.substr(found+1); }else break; } void* r = dynv_system_get_r(dlevel, handler_name, path.c_str(), error); dynv_system_release(dlevel); return r; } void** dynv_get_array(struct dynvSystem* dynv_system, const char* handler_name, const char* variable_path, uint32_t *count, int* error){ string path(variable_path); size_t found; int error_redir; if (error == nullptr) error = &error_redir; if (count) *count = 0; *error = 0; struct dynvSystem* dlevel = dynv_system_ref(dynv_system); for (;;){ found = path.find('.'); if (found != string::npos){ struct dynvSystem* dlevel_new; dlevel_new = (struct dynvSystem*)dynv_system_get(dlevel, "dynv", path.substr(0, found).c_str()); if (dlevel_new){ dynv_system_release(dlevel); dlevel = dlevel_new; }else{ dynv_system_release(dlevel); *error = 1; return 0; } path = path.substr(found+1); }else break; } void** r = dynv_system_get_array_r(dlevel, handler_name, path.c_str(), count, error); dynv_system_release(dlevel); return r; } gpick-gpick-0.2.6rc1/source/dynv/DynvSystem.h000066400000000000000000000103471315430016700211000ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DYNVSYSTEM_H_ #define DYNVSYSTEM_H_ #include "DynvHandler.h" #include #include #include #include #include struct dynvSystem{ class dynvKeyCompare{ public: bool operator() (const char* const& x, const char* const& y) const; }; typedef std::map VariableMap; uint32_t refcnt; VariableMap variables; dynvHandlerMap* handler_map; }; struct dynvSystem* dynv_system_create(struct dynvHandlerMap* handler_map); struct dynvSystem* dynv_system_create(struct dynvSystem* dynv_system); int dynv_system_release(struct dynvSystem* dynv_system); struct dynvSystem* dynv_system_ref(struct dynvSystem* dynv_system); struct dynvHandlerMap* dynv_system_get_handler_map(struct dynvSystem* dynv_system); void dynv_system_set_handler_map(struct dynvSystem* dynv_system, struct dynvHandlerMap* handler_map); int dynv_system_set(struct dynvSystem* dynv_system, const char* handler_name, const char* variable_name, void* value); struct dynvVariable* dynv_system_add_empty(struct dynvSystem* dynv_system, struct dynvHandler* handler, const char* variable_name); void* dynv_system_get(struct dynvSystem* dynv_system, const char* handler_name, const char* variable_name); void* dynv_system_get_r(struct dynvSystem* dynv_system, const char* handler_name, const char* variable_name, int* error); int dynv_system_set_array(struct dynvSystem* dynv_system, const char* handler_name, const char* variable_name, void** values, uint32_t count, uint32_t data_size); void** dynv_system_get_array_r(struct dynvSystem* dynv_system, const char* handler_name, const char* variable_name, uint32_t *count, uint32_t data_size, int* error); struct dynvVariable* dynv_system_get_var(struct dynvSystem* dynv_system, const char* variable_name); int dynv_system_remove(struct dynvSystem* dynv_system, const char* variable_name); int dynv_system_remove_all(struct dynvSystem* dynv_system); struct dynvSystem* dynv_system_copy(struct dynvSystem* dynv_system); int dynv_system_serialize(struct dynvSystem* dynv_system, struct dynvIO* io); int dynv_system_deserialize(struct dynvSystem* dynv_system, dynvHandlerMap::HandlerVec& handler_vec, struct dynvIO* io); int dynv_set(struct dynvSystem* dynv_system, const char* handler_name, const char* variable_path, const void* value); void* dynv_get(struct dynvSystem* dynv_system, const char* handler_name, const char* variable_path, int* error); void** dynv_get_array(struct dynvSystem* dynv_system, const char* handler_name, const char* variable_path, uint32_t *count, int* error); int dynv_set_array(struct dynvSystem* dynv_system, const char* handler_name, const char* variable_path, const void** values, uint32_t count); #endif /* DYNVSYSTEM_H_ */ gpick-gpick-0.2.6rc1/source/dynv/DynvVarBool.cpp000066400000000000000000000055431315430016700215150ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "DynvVarBool.h" #include "DynvVariable.h" #include "DynvIO.h" #include "../Endian.h" #include #include #include using namespace std; static int create(struct dynvVariable* variable){ variable->bool_value = false; return 0; } static int destroy(struct dynvVariable* variable){ return 0; } static int set(struct dynvVariable* variable, void* value, bool deref){ variable->bool_value = *(bool*)value; return 0; } static int get(struct dynvVariable* variable, void** value, bool *deref){ *value = &variable->bool_value; return 0; } static int serialize_xml(struct dynvVariable* variable, ostream& out){ if (variable->bool_value){ out << "true"; }else{ out << "false"; } return 0; } static int deserialize_xml(struct dynvVariable* variable, const char *data){ if (strcmp(data, "true") == 0){ *(bool*)&variable->bool_value = true; }else{ *(bool*)&variable->bool_value = false; } return 0; } struct dynvHandler* dynv_var_bool_new(){ struct dynvHandler* handler=dynv_handler_create("bool"); handler->create=create; handler->destroy=destroy; handler->set=set; handler->get=get; //handler->serialize=serialize; //handler->deserialize=deserialize; handler->serialize_xml = serialize_xml; handler->deserialize_xml = deserialize_xml; handler->data_size = sizeof(bool); return handler; } gpick-gpick-0.2.6rc1/source/dynv/DynvVarBool.h000066400000000000000000000032371315430016700211600ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DYNVVARBOOL_H_ #define DYNVVARBOOL_H_ #include "DynvHandler.h" struct dynvHandler* dynv_var_bool_new(); #endif /* DYNVVARBOOL_H_ */ gpick-gpick-0.2.6rc1/source/dynv/DynvVarColor.cpp000066400000000000000000000110321315430016700216660ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "DynvVarColor.h" #include "DynvVariable.h" #include "DynvIO.h" #include "../Endian.h" #include #include using namespace std; static int dynv_var_color_create(struct dynvVariable* variable){ if ((variable->ptr_value = new float[4])){ return 0; } return -1; } static int dynv_var_color_destroy(struct dynvVariable* variable){ if (variable->ptr_value){ delete [] (float*)variable->ptr_value; return 0; } return -1; } static int dynv_var_color_set(struct dynvVariable* variable, void* value, bool deref){ if (!variable->ptr_value) return -1; memcpy(variable->ptr_value, *(void**)value, sizeof(float[4])); /*((float*)variable->ptr_value)[0] = ((float*)value)[0]; ((float*)variable->ptr_value)[1] = ((float*)value)[1]; ((float*)variable->ptr_value)[2] = ((float*)value)[2]; ((float*)variable->ptr_value)[3] = ((float*)value)[3];*/ return 0; } static int dynv_var_color_get(struct dynvVariable* variable, void** value, bool *deref){ if (variable->ptr_value){ *value = &variable->ptr_value; return 0; } return -1; } static int dynv_var_color_serialize(struct dynvVariable* variable, struct dynvIO* io){ if (!variable->ptr_value) return -1; uint32_t written; uint32_t length=16; length=UINT32_TO_LE(length); dynv_io_write(io, &length, 4, &written); uint32_t value[4]; memcpy(value, variable->ptr_value, 16); value[0]=UINT32_TO_LE(value[0]); value[1]=UINT32_TO_LE(value[1]); value[2]=UINT32_TO_LE(value[2]); value[3]=UINT32_TO_LE(value[3]); if (dynv_io_write(io, value, 16, &written) == 0){ if (written != 16) return -1; }else return -1; return 0; } static int dynv_var_color_deserialize(struct dynvVariable* variable, struct dynvIO* io){ if (!variable->ptr_value) return -1; uint32_t read; uint32_t length; uint32_t value[4]; dynv_io_read(io, &length, 4, &read); if (dynv_io_read(io, value, 16, &read) == 0){ if (read == 16){ value[0]=UINT32_FROM_LE(value[0]); value[1]=UINT32_FROM_LE(value[1]); value[2]=UINT32_FROM_LE(value[2]); value[3]=UINT32_FROM_LE(value[3]); memcpy(variable->ptr_value, value, 16); return 0; } } return -1; } static int serialize_xml(struct dynvVariable* variable, ostream& out){ if (variable->ptr_value){ float* color = (float*)variable->ptr_value; out << color[0] <<" "<< color[1] <<" "<< color[2] <<" "<< color[3]; } return 0; } static int deserialize_xml(struct dynvVariable* variable, const char *data){ stringstream ss(stringstream::in); ss.str(data); float *c = (float*)variable->ptr_value; ss >> c[0] >> c[1] >> c[2] >> c[3]; return 0; } struct dynvHandler* dynv_var_color_new(){ struct dynvHandler* handler=dynv_handler_create("color"); handler->create=dynv_var_color_create; handler->destroy=dynv_var_color_destroy; handler->set=dynv_var_color_set; handler->get=dynv_var_color_get; handler->serialize=dynv_var_color_serialize; handler->deserialize=dynv_var_color_deserialize; handler->serialize_xml=serialize_xml; handler->deserialize_xml=deserialize_xml; handler->data_size = sizeof(float*); return handler; } gpick-gpick-0.2.6rc1/source/dynv/DynvVarColor.h000066400000000000000000000032431315430016700213400ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DYNVVARCOLOR_H_ #define DYNVVARCOLOR_H_ #include "DynvHandler.h" struct dynvHandler* dynv_var_color_new(); #endif /* DYNVVARCOLOR_H_ */ gpick-gpick-0.2.6rc1/source/dynv/DynvVarDynv.cpp000066400000000000000000000061341315430016700215370ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "DynvSystem.h" #include "DynvVariable.h" #include "DynvIO.h" #include "DynvXml.h" #include "DynvVarDynv.h" #include "../Endian.h" #include using namespace std; static int dynv_var_dynv_create(struct dynvVariable* variable) { variable->ptr_value = 0; return 0; } static int dynv_var_dynv_destroy(struct dynvVariable* variable) { if (variable->ptr_value){ dynv_system_release((struct dynvSystem*)variable->ptr_value); return 0; } return -1; } static int dynv_var_dynv_set(struct dynvVariable* variable, void* value, bool deref) { if (variable->ptr_value) dynv_system_release((struct dynvSystem*)variable->ptr_value); if (deref) variable->ptr_value = dynv_system_ref(*((struct dynvSystem**)value)); else variable->ptr_value = dynv_system_ref((struct dynvSystem*)value); return 0; } static int dynv_var_dynv_get(struct dynvVariable* variable, void** value, bool *deref) { if (variable->ptr_value){ *value= dynv_system_ref((struct dynvSystem*)variable->ptr_value); *deref = false; return 0; } return -1; } static int serialize_xml(struct dynvVariable* variable, ostream& out) { if (variable->ptr_value){ out << endl; dynv_xml_serialize((struct dynvSystem*)variable->ptr_value, out); } return 0; } struct dynvHandler* dynv_var_dynv_new() { struct dynvHandler* handler = dynv_handler_create("dynv"); handler->create = dynv_var_dynv_create; handler->destroy = dynv_var_dynv_destroy; handler->set = dynv_var_dynv_set; handler->get = dynv_var_dynv_get; handler->serialize_xml = serialize_xml; handler->data_size = sizeof(struct dynvSystem*); return handler; } gpick-gpick-0.2.6rc1/source/dynv/DynvVarDynv.h000066400000000000000000000032361315430016700212040ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DYNVVARDYNV_H_ #define DYNVVARDYNV_H_ #include "DynvSystem.h" struct dynvHandler* dynv_var_dynv_new(); #endif /* DYNVVARDYNV_H_ */ gpick-gpick-0.2.6rc1/source/dynv/DynvVarFloat.cpp000066400000000000000000000072431315430016700216660ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "DynvVarFloat.h" #include "DynvVariable.h" #include "DynvIO.h" #include "../Endian.h" #include using namespace std; static int dynv_var_float_create(struct dynvVariable* variable){ variable->float_value = 0; return 0; } static int dynv_var_float_destroy(struct dynvVariable* variable){ return 0; } static int dynv_var_float_set(struct dynvVariable* variable, void* value, bool deref){ variable->float_value = *((float*)value); return 0; } static int dynv_var_float_get(struct dynvVariable* variable, void** value, bool *deref){ *value = &variable->float_value; return 0; } static int dynv_var_float_serialize(struct dynvVariable* variable, struct dynvIO* io){ uint32_t written; uint32_t length = 4; length = UINT32_TO_LE(length); dynv_io_write(io, &length, 4, &written); union{ uint32_t i32; float f32; }value; value.f32 = variable->float_value; value.i32 = UINT32_TO_LE(value.i32); if (dynv_io_write(io, &value, 4, &written) == 0){ if (written == 4) return 0; } return -1; } static int dynv_var_float_deserialize(struct dynvVariable* variable, struct dynvIO* io){ uint32_t read; uint32_t size; dynv_io_read(io, &size, 4, &read); union{ uint32_t i32; float f32; }value; if (dynv_io_read(io, &value, 4, &read) == 0){ if (read == 4){ value.i32 = UINT32_FROM_LE(value.i32); variable->float_value = value.f32; return 0; } } return -1; } static int serialize_xml(struct dynvVariable* variable, ostream& out){ out << variable->float_value; return 0; } static int deserialize_xml(struct dynvVariable* variable, const char *data){ stringstream ss(stringstream::in); ss.str(data); ss >> variable->float_value; return 0; } struct dynvHandler* dynv_var_float_new(){ struct dynvHandler* handler=dynv_handler_create("float"); handler->create=dynv_var_float_create; handler->destroy=dynv_var_float_destroy; handler->set=dynv_var_float_set; handler->get=dynv_var_float_get; handler->serialize=dynv_var_float_serialize; handler->deserialize=dynv_var_float_deserialize; handler->serialize_xml = serialize_xml; handler->deserialize_xml = deserialize_xml; handler->data_size = sizeof(float); return handler; } gpick-gpick-0.2.6rc1/source/dynv/DynvVarFloat.h000066400000000000000000000032421315430016700213260ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DYNVVARFLOAT_H_ #define DYNVVARFLOAT_H_ #include "DynvSystem.h" struct dynvHandler* dynv_var_float_new(); #endif /* DYNVVARFLOAT_H_ */ gpick-gpick-0.2.6rc1/source/dynv/DynvVarInt32.cpp000066400000000000000000000070111315430016700215110ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "DynvVarInt32.h" #include "DynvVariable.h" #include "DynvIO.h" #include "../Endian.h" #include using namespace std; static int dynv_var_int32_create(struct dynvVariable* variable){ variable->int_value = 0; return 0; } static int dynv_var_int32_destroy(struct dynvVariable* variable){ return 0; } static int dynv_var_int32_set(struct dynvVariable* variable, void* value, bool deref){ variable->int_value = *((int32_t*)value); return 0; } static int dynv_var_int32_get(struct dynvVariable* variable, void** value, bool *deref){ *value = &variable->int_value; return 0; } static int dynv_var_int32_serialize(struct dynvVariable* variable, struct dynvIO* io){ uint32_t written; uint32_t length=4; length = UINT32_TO_LE(length); dynv_io_write(io, &length, 4, &written); int32_t value = UINT32_TO_LE(variable->int_value); if (dynv_io_write(io, &value, 4, &written) == 0){ if (written == 4) return 0; } return -1; } static int dynv_var_int32_deserialize(struct dynvVariable* variable, struct dynvIO* io){ uint32_t read; int32_t value; dynv_io_read(io, &value, 4, &read); if (dynv_io_read(io, &value, 4, &read) == 0){ if (read == 4){ variable->int_value = UINT32_FROM_LE(value); return 0; } } return -1; } static int serialize_xml(struct dynvVariable* variable, ostream& out){ out << variable->int_value; return 0; } static int deserialize_xml(struct dynvVariable* variable, const char *data){ stringstream ss(stringstream::in); ss.str(data); ss >> variable->int_value; return 0; } struct dynvHandler* dynv_var_int32_new(){ struct dynvHandler* handler=dynv_handler_create("int32"); handler->create=dynv_var_int32_create; handler->destroy=dynv_var_int32_destroy; handler->set=dynv_var_int32_set; handler->get=dynv_var_int32_get; handler->serialize=dynv_var_int32_serialize; handler->deserialize=dynv_var_int32_deserialize; handler->serialize_xml = serialize_xml; handler->deserialize_xml = deserialize_xml; handler->data_size = sizeof(int32_t); return handler; } gpick-gpick-0.2.6rc1/source/dynv/DynvVarInt32.h000066400000000000000000000032421315430016700211600ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DYNVVARINT32_H_ #define DYNVVARINT32_H_ #include "DynvSystem.h" struct dynvHandler* dynv_var_int32_new(); #endif /* DYNVVARINT32_H_ */ gpick-gpick-0.2.6rc1/source/dynv/DynvVarPtr.cpp000066400000000000000000000046141315430016700213650ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "DynvVarPtr.h" #include "DynvVariable.h" #include "DynvIO.h" #include "../Endian.h" static int dynv_var_ptr_create(struct dynvVariable* variable){ variable->ptr_value = 0; return 0; } static int dynv_var_ptr_destroy(struct dynvVariable* variable){ return 0; } static int dynv_var_ptr_set(struct dynvVariable* variable, void* value, bool deref){ variable->ptr_value = *(void**)value; return 0; } static int dynv_var_ptr_get(struct dynvVariable* variable, void** value, bool *deref){ *value = &variable->ptr_value; return 0; } struct dynvHandler* dynv_var_ptr_new(){ struct dynvHandler* handler=dynv_handler_create("ptr"); handler->create=dynv_var_ptr_create; handler->destroy=dynv_var_ptr_destroy; handler->set=dynv_var_ptr_set; handler->get=dynv_var_ptr_get; handler->serialize=0; handler->deserialize=0; handler->data_size = sizeof(void*); return handler; } gpick-gpick-0.2.6rc1/source/dynv/DynvVarPtr.h000066400000000000000000000032321315430016700210250ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DYNVVARPTR_H_ #define DYNVVARPTR_H_ #include "DynvSystem.h" struct dynvHandler* dynv_var_ptr_new(); #endif /* DYNVVARPTR_H_ */ gpick-gpick-0.2.6rc1/source/dynv/DynvVarString.cpp000066400000000000000000000106571315430016700220720ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "DynvVarString.h" #include "DynvVariable.h" #include "DynvIO.h" #include "DynvXml.h" #include "../Endian.h" #include using namespace std; static int dynv_var_string_create(struct dynvVariable* variable){ variable->ptr_value = 0; return -1; } static int dynv_var_string_destroy(struct dynvVariable* variable){ if (variable->ptr_value){ delete [] (char*)variable->ptr_value; return 0; } return -1; } static int dynv_var_string_set(struct dynvVariable* variable, void* value, bool deref){ if (variable->ptr_value){ delete [] (char*)variable->ptr_value; } uint32_t len = strlen(*(char**)value)+1; variable->ptr_value = new char [len]; memcpy(variable->ptr_value, *(void**)value, len); return 0; } static int dynv_var_string_get(struct dynvVariable* variable, void** value, bool *deref){ if (variable->ptr_value){ *value = &variable->ptr_value; return 0; } return -1; } static int dynv_var_string_serialize(struct dynvVariable* variable, struct dynvIO* io){ if (!variable->ptr_value) return -1; uint32_t written; uint32_t length = strlen((char*)variable->ptr_value); uint32_t length_le = UINT32_TO_LE(length); if (dynv_io_write(io, &length_le, 4, &written) == 0){ if (written != 4) return -1; }else return -1; if (dynv_io_write(io, variable->ptr_value, length, &written) == 0){ if (written != length) return -1; }else return -1; return 0; } static int dynv_var_string_deserialize(struct dynvVariable* variable, struct dynvIO* io){ if (variable->ptr_value){ delete [] (char*)variable->ptr_value; variable->ptr_value = 0; } uint32_t read; uint32_t length; if (dynv_io_read(io, &length, 4, &read) == 0){ if (read != 4) return -1; }else return -1; length = UINT32_FROM_LE(length); variable->ptr_value = new char [length+1]; if (dynv_io_read(io, variable->ptr_value, length, &read) == 0){ if (read != length) return -1; }else return -1; ((char*)variable->ptr_value)[length] = 0; return 0; } static int serialize_xml(struct dynvVariable* variable, ostream& out){ if (variable->ptr_value){ //out << (char*)variable->value; dynv_xml_escape((char*)variable->ptr_value, out); } return 0; } static int deserialize_xml(struct dynvVariable* variable, const char *data){ if (variable->ptr_value){ delete [] (char*)variable->ptr_value; variable->ptr_value = 0; } uint32_t len = strlen(data)+1; variable->ptr_value = new char [len]; memcpy(variable->ptr_value, data, len); return 0; } struct dynvHandler* dynv_var_string_new(){ struct dynvHandler* handler=dynv_handler_create("string"); handler->create=dynv_var_string_create; handler->destroy=dynv_var_string_destroy; handler->set=dynv_var_string_set; handler->get=dynv_var_string_get; handler->serialize=dynv_var_string_serialize; handler->deserialize=dynv_var_string_deserialize; handler->serialize_xml=serialize_xml; handler->deserialize_xml=deserialize_xml; handler->data_size = sizeof(char*); return handler; } gpick-gpick-0.2.6rc1/source/dynv/DynvVarString.h000066400000000000000000000032461315430016700215330ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DYNVVARSTRING_H_ #define DYNVVARSTRING_H_ #include "DynvSystem.h" struct dynvHandler* dynv_var_string_new(); #endif /* DYNVVARSTRING_H_ */ gpick-gpick-0.2.6rc1/source/dynv/DynvVariable.cpp000066400000000000000000000056541315430016700217010ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "DynvVariable.h" #include "DynvHandler.h" #include #include dynvVariable* dynv_variable_create(const char* name, dynvHandler* handler) { struct dynvVariable* variable = new struct dynvVariable; if (name){ variable->name = strdup(name); }else{ variable->name = nullptr; } variable->handler = handler; variable->ptr_value = nullptr; variable->next = nullptr; variable->flags = dynvVariable::Flag::none; return variable; } void dynv_variable_destroy_data(dynvVariable* variable) { dynvVariable *next, *i; i = variable->next; while (i){ next = i->next; if (i->handler->destroy != nullptr) i->handler->destroy(i); if (i->name) free(i->name); delete i; i = next; } if (variable->handler->destroy != nullptr) variable->handler->destroy(variable); variable->next = nullptr; variable->ptr_value = nullptr; variable->handler = nullptr; } void dynv_variable_destroy(dynvVariable* variable) { dynvVariable *next, *i; i = variable; while (i){ next = i->next; if (i->handler->destroy != nullptr) i->handler->destroy(i); if (i->name) free(i->name); delete i; i = next; } } dynvVariable::Flag operator&(dynvVariable::Flag x, dynvVariable::Flag y) { return static_cast(static_cast(x) & static_cast(y)); } bool operator!=(dynvVariable::Flag x, dynvVariable::Flag y) { return static_cast(x) != static_cast(y); } gpick-gpick-0.2.6rc1/source/dynv/DynvVariable.h000066400000000000000000000044001315430016700213320ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DYNVVARIABLE_H_ #define DYNVVARIABLE_H_ #include #ifndef _MSC_VER #include #endif struct dynvHandler; struct dynvVariable { char* name; struct dynvHandler* handler; union{ void* ptr_value; bool bool_value; int32_t int_value; float float_value; }; enum class Flag: uintptr_t { none = 0, no_save = 1, read_only = 2, }flags; dynvVariable *next; }; dynvVariable* dynv_variable_create(const char* name, dynvHandler* handler); void dynv_variable_destroy(dynvVariable* variable); void dynv_variable_destroy_data(dynvVariable* variable); dynvVariable::Flag operator&(dynvVariable::Flag x, dynvVariable::Flag y); bool operator!=(dynvVariable::Flag x, dynvVariable::Flag y); #endif /* DYNVVARIABLE_H_ */ gpick-gpick-0.2.6rc1/source/dynv/DynvXml.cpp000066400000000000000000000205701315430016700207060ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "DynvXml.h" #include "DynvSystem.h" #include "DynvVariable.h" #include #include #include #include #include #include using namespace std; int dynv_xml_serialize(struct dynvSystem* dynv_system, ostream& out) { for (auto variable_item: dynv_system->variables){ dynvVariable *variable = variable_item.second; if ((variable->flags & dynvVariable::Flag::no_save) == dynvVariable::Flag::no_save) continue; if (variable->handler->serialize_xml){ if (variable->next){ out << "<" << variable->name << " type=\"" << variable->handler->name << "\" list=\"true\">"; dynvVariable *v = variable; while (v){ out << "
  • "; v->handler->serialize_xml(v, out); out << "
  • "; v = v->next; } out << "name << ">" << endl; }else{ out << "<" << variable->name << " type=\"" << variable->handler->name << "\">"; variable->handler->serialize_xml(variable, out); out << "name << ">" << endl; } } } return 0; } class XmlEntity { public: stringstream entity_data; dynvVariable *variable; dynvSystem* dynv; dynvHandler *list_handler; bool list_expected; bool first_item; XmlEntity(dynvVariable *_variable, dynvSystem* _dynv, bool _list_expected): entity_data(stringstream::out), variable(_variable), dynv(_dynv), list_expected(_list_expected) { list_handler = 0; first_item = true; }; }; class XmlCtx { public: bool root_found; stack entity; dynvHandlerMap *handler_map; XmlCtx(){ root_found = false; handler_map = 0; }; ~XmlCtx(){ if (handler_map) dynv_handler_map_release(handler_map); for (; !entity.empty(); entity.pop()){ if (entity.top()) delete entity.top(); } } }; static char* get_attribute(const XML_Char **atts, const char *attribute) { XML_Char **i = (XML_Char**)atts; while (*i){ if (strcmp(attribute, *i) == 0){ return *(i + 1); } i += 2; } return 0; } static void start_element_handler(XmlCtx *xml, const XML_Char *name, const XML_Char **atts) { if (xml->root_found){ XmlEntity *entity = xml->entity.top(); if (!entity) return; dynvVariable *variable; XmlEntity *n; if (entity->list_expected){ if (name && strcmp(name, "li") == 0){ if (entity->first_item){ xml->entity.push(n = new XmlEntity(entity->variable, entity->dynv, false)); entity->first_item = false; }else{ variable = dynv_variable_create(0, entity->list_handler); variable->handler->create(variable); if (strcmp(entity->list_handler->name, "dynv") == 0){ struct dynvHandlerMap* handler_map = dynv_system_get_handler_map(entity->dynv); struct dynvSystem* dlevel_new = dynv_system_create(handler_map); dynv_handler_map_release(handler_map); entity->list_handler->set(variable, dlevel_new, false); xml->entity.push(n = new XmlEntity(variable, dlevel_new, false)); dynv_system_release(dlevel_new); }else{ xml->entity.push(n = new XmlEntity(variable, entity->dynv, false)); } entity->variable->next = variable; entity->variable = variable; } }else{ xml->entity.push(0); } }else{ char* type = get_attribute(atts, "type"); char* list = get_attribute(atts, "list"); struct dynvHandler *handler = dynv_handler_map_get_handler(xml->handler_map, type); if (handler){ if (strcmp(type, "dynv") == 0){ struct dynvHandlerMap* handler_map = dynv_system_get_handler_map(entity->dynv); struct dynvSystem* dlevel_new = dynv_system_create(handler_map); dynv_handler_map_release(handler_map); if ((variable = dynv_system_add_empty(entity->dynv, handler, name))){ handler->set(variable, dlevel_new, false); } if (list && strcmp(list, "true") == 0){ xml->entity.push(n = new XmlEntity(variable, dlevel_new, true)); n->list_handler = handler; }else{ xml->entity.push(n = new XmlEntity(variable, dlevel_new, false)); } dynv_system_release(dlevel_new); }else if (handler->deserialize_xml){ if (list && strcmp(list, "true") == 0){ if ((variable = dynv_system_add_empty(entity->dynv, handler, name))){ xml->entity.push(n = new XmlEntity(variable, entity->dynv, true)); n->list_handler = handler; }else{ xml->entity.push(0); } }else{ if ((variable = dynv_system_add_empty(entity->dynv, handler, name))){ xml->entity.push(new XmlEntity(variable, entity->dynv, false)); }else{ xml->entity.push(0); } } }else{ /* not deserialize'able */ xml->entity.push(0); } }else{ /* unknown type */ xml->entity.push(0); } } }else{ if (strcmp(name, "root") == 0){ xml->root_found = true; } } } static void end_element_handler(XmlCtx *xml, const XML_Char *name) { if (xml->root_found){ XmlEntity *entity = xml->entity.top(); if (entity){ if (entity->list_expected){ if (entity->first_item){ //entry declared as list, but no list items defined dynv_system_remove(entity->dynv, entity->variable->name); } }else if (entity->variable){ if (entity->variable->handler->deserialize_xml){ string value = entity->entity_data.str(); entity->variable->handler->deserialize_xml(entity->variable, value.c_str()); } } delete entity; } xml->entity.pop(); } } static void character_data_handler(XmlCtx *xml, const XML_Char *s, int len) { XmlEntity *entity = xml->entity.top(); if (entity){ entity->entity_data.write(s, len); } } int dynv_xml_deserialize(struct dynvSystem* dynv_system, istream& in) { XML_Parser p = XML_ParserCreate("UTF-8"); XML_SetElementHandler(p, (XML_StartElementHandler)start_element_handler, (XML_EndElementHandler)end_element_handler); XML_SetCharacterDataHandler(p, (XML_CharacterDataHandler)character_data_handler); XmlCtx ctx; ctx.entity.push(new XmlEntity(0, dynv_system, false)); ctx.handler_map = dynv_system_get_handler_map(dynv_system); XML_SetUserData(p, &ctx); for (;;){ void *buffer = XML_GetBuffer(p, 4096); in.read((char*)buffer, 4096); size_t bytes_read = in.gcount(); if (!XML_ParseBuffer(p, bytes_read, bytes_read == 0)) { } if (bytes_read == 0) break; } XML_ParserFree(p); return 0; } int dynv_xml_escape(const char* data, std::ostream& out) { char* i = const_cast(data); char* last_esc = i; for (;;){ switch (*i){ case '&': if (last_esc != i) out.write(last_esc, uintptr_t(i) - uintptr_t(last_esc)); out << "&"; last_esc = i + 1; break; case '<': if (last_esc != i) out.write(last_esc, uintptr_t(i) - uintptr_t(last_esc)); out << "<"; last_esc = i + 1; break; case '>': if (last_esc != i) out.write(last_esc, uintptr_t(i) - uintptr_t(last_esc)); out << ">"; last_esc = i + 1; break; case 0: if (last_esc != i) out.write(last_esc, uintptr_t(i) - uintptr_t(last_esc)); return 0; break; } ++i; } return 0; } gpick-gpick-0.2.6rc1/source/dynv/DynvXml.h000066400000000000000000000034711315430016700203540ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef DYNVXML_H_ #define DYNVXML_H_ struct dynvSystem; #include int dynv_xml_serialize(dynvSystem* dynv_system, std::ostream& out); int dynv_xml_deserialize(dynvSystem* dynv_system, std::istream& in); int dynv_xml_escape(const char* data, std::ostream& out); #endif /* DYNVXML_H_ */ gpick-gpick-0.2.6rc1/source/gtk/000077500000000000000000000000001315430016700164025ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/source/gtk/ColorCell.cpp000066400000000000000000000201671315430016700207720ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ColorCell.h" #include "../ColorObject.h" #include static void init(CustomCellRendererColor *cellcolor); static void class_init(CustomCellRendererColorClass *klass); static void get_property(GObject *object, guint param_id, GValue *value, GParamSpec *pspec); static void set_property(GObject *object, guint param_id, const GValue *value, GParamSpec *pspec); static void finalize(GObject *gobject); #if GTK_MAJOR_VERSION >= 3 static void get_preferred_width(GtkCellRenderer *cell, GtkWidget *widget, gint *minimum_size, gint *natural_size); static void get_preferred_height(GtkCellRenderer *cell, GtkWidget *widget, gint *minimum_size, gint *natural_size); static void render(GtkCellRenderer *cell, cairo_t *cr, GtkWidget *widget, const GdkRectangle *background_area, const GdkRectangle *cell_area, GtkCellRendererState flags); #else static void get_size(GtkCellRenderer *cell, GtkWidget *widget, GdkRectangle *cell_area, gint *x_offset, gint *y_offset, gint *width, gint *height); static void render(GtkCellRenderer *cell, GdkDrawable *window, GtkWidget *widget, GdkRectangle *background_area, GdkRectangle *cell_area, GdkRectangle *expose_area, GtkCellRendererState flags); #endif enum { PROP_COLOR = 1, }; static gpointer parent_class; GType custom_cell_renderer_color_get_type() { static GType cell_color_type = 0; if (cell_color_type == 0){ static const GTypeInfo cell_color_info = { sizeof(CustomCellRendererColorClass), nullptr, /* base_init */ nullptr, /* base_finalize */ (GClassInitFunc) class_init, nullptr, /* class_finalize */ nullptr, /* class_data */ sizeof(CustomCellRendererColor), 0, /* n_preallocs */ (GInstanceInitFunc) init, }; cell_color_type = g_type_register_static(GTK_TYPE_CELL_RENDERER, "CustomCellRendererColor", &cell_color_info, (GTypeFlags) 0); } return cell_color_type; } static void init(CustomCellRendererColor *cellrenderercolor) { #if GTK_MAJOR_VERSION >= 3 #else GTK_CELL_RENDERER(cellrenderercolor)->mode = GTK_CELL_RENDERER_MODE_INERT; GTK_CELL_RENDERER(cellrenderercolor)->xpad = 2; GTK_CELL_RENDERER(cellrenderercolor)->ypad = 2; #endif cellrenderercolor->width = 32; cellrenderercolor->height = 16; cellrenderercolor->color = nullptr; } static void class_init(CustomCellRendererColorClass *klass) { GtkCellRendererClass *cell_class = GTK_CELL_RENDERER_CLASS(klass); GObjectClass *object_class = G_OBJECT_CLASS(klass); parent_class = g_type_class_peek_parent(klass); object_class->finalize = finalize; object_class->get_property = get_property; object_class->set_property = set_property; #if GTK_MAJOR_VERSION >= 3 cell_class->get_preferred_width = get_preferred_width; cell_class->get_preferred_height = get_preferred_height; #else cell_class->get_size = get_size; #endif cell_class->render = render; g_object_class_install_property(object_class, PROP_COLOR, g_param_spec_pointer("color", "Color", "ColorObject pointer", (GParamFlags) G_PARAM_READWRITE)); } static void finalize(GObject *object) { (*G_OBJECT_CLASS(parent_class)->finalize)(object); } static void get_property(GObject *object, guint param_id, GValue *value, GParamSpec *psec) { CustomCellRendererColor *cellcolor = CUSTOM_CELL_RENDERER_COLOR(object); switch (param_id){ case PROP_COLOR: g_value_set_pointer(value, cellcolor->color); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, param_id, psec); break; } } static void set_property(GObject *object, guint param_id, const GValue *value, GParamSpec *pspec) { CustomCellRendererColor *cellcolor = CUSTOM_CELL_RENDERER_COLOR(object); switch (param_id){ case PROP_COLOR: cellcolor->color = (ColorObject*)g_value_get_pointer(value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, param_id, pspec); break; } } GtkCellRenderer *custom_cell_renderer_color_new() { return (GtkCellRenderer*)g_object_new(CUSTOM_TYPE_CELL_RENDERER_COLOR, nullptr); } void custom_cell_renderer_color_set_size(GtkCellRenderer *cell, gint width, gint height) { CustomCellRendererColor *cellcolor = CUSTOM_CELL_RENDERER_COLOR(cell); cellcolor->width = width; cellcolor->height = height; } #if GTK_MAJOR_VERSION >= 3 static void get_preferred_width(GtkCellRenderer *cell, GtkWidget *widget, gint *minimum_size, gint *natural_size) { CustomCellRendererColor *cellcolor = CUSTOM_CELL_RENDERER_COLOR(cell); if (minimum_size) *minimum_size = 1; *natural_size = cellcolor->width; } static void get_preferred_height(GtkCellRenderer *cell, GtkWidget *widget, gint *minimum_size, gint *natural_size) { CustomCellRendererColor *cellcolor = CUSTOM_CELL_RENDERER_COLOR(cell); if (minimum_size) *minimum_size = 1; *natural_size = cellcolor->height; } static void render(GtkCellRenderer *cell, cairo_t *cr, GtkWidget *widget, const GdkRectangle *background_area, const GdkRectangle *cell_area, GtkCellRendererState flags) { CustomCellRendererColor *cellcolor = CUSTOM_CELL_RENDERER_COLOR(cell); cairo_rectangle(cr, cell_area->x, cell_area->y, cell_area->width, cell_area->height); Color color = cellcolor->color->getColor(); cairo_set_source_rgb(cr, round(color.rgb.red * 255.0) / 255.0, round(color.rgb.green * 255.0) / 255.0, round(color.rgb.blue * 255.0) / 255.0); cairo_fill(cr); } #else static void get_size(GtkCellRenderer *cell, GtkWidget *widget, GdkRectangle *cell_area, gint *x_offset, gint *y_offset, gint *width, gint *height) { CustomCellRendererColor *cellcolor = CUSTOM_CELL_RENDERER_COLOR(cell); gint calc_width; gint calc_height; calc_width = (gint) cell->xpad * 2 + cellcolor->width; calc_height = (gint) cell->ypad * 2 + cellcolor->height; if (width) *width = calc_width; if (height) *height = calc_height; if (cell_area){ if (x_offset){ *x_offset = gint(cell->xalign * (cell_area->width - calc_width)); *x_offset = MAX(*x_offset, 0); } if (y_offset){ *y_offset = gint(cell->yalign * (cell_area->height - calc_height)); *y_offset = MAX(*y_offset, 0); } } } static void render(GtkCellRenderer *cell, GdkDrawable *window, GtkWidget *widget, GdkRectangle *background_area, GdkRectangle *cell_area, GdkRectangle *expose_area, GtkCellRendererState flags) { using boost::math::round; CustomCellRendererColor *cellcolor = CUSTOM_CELL_RENDERER_COLOR(cell); cairo_t *cr; cr = gdk_cairo_create(window); cairo_rectangle(cr, expose_area->x, expose_area->y, expose_area->width, expose_area->height); cairo_clip(cr); cairo_rectangle(cr, expose_area->x, expose_area->y, expose_area->width, expose_area->height); Color color = cellcolor->color->getColor(); cairo_set_source_rgb(cr, round(color.rgb.red * 255.0) / 255.0, round(color.rgb.green * 255.0) / 255.0, round(color.rgb.blue * 255.0) / 255.0); cairo_fill(cr); cairo_destroy(cr); } #endif gpick-gpick-0.2.6rc1/source/gtk/ColorCell.h000066400000000000000000000053501315430016700204340ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_GTK_COLOR_CELL_H_ #define GPICK_GTK_COLOR_CELL_H_ class ColorObject; #include #define CUSTOM_TYPE_CELL_RENDERER_COLOR (custom_cell_renderer_color_get_type()) #define CUSTOM_CELL_RENDERER_COLOR(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), CUSTOM_TYPE_CELL_RENDERER_COLOR, CustomCellRendererColor)) #define CUSTOM_CELL_RENDERER_COLOR_CLASS(obj) (G_TYPE_CHECK_CLASS_CAST((obj), CUSTOM_TYPE_CELL_RENDERER_COLOR, CustomCellRendererColorClass)) #define CUSTOM_IS_CELL_COLOR_COLOR(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), CUSTOM_TYPE_CELL_RENDERER_COLOR)) #define CUSTOM_IS_CELL_COLOR_COLOR_CLASS(obj) (G_TYPE_CHECK_CLASS_TYPE((obj), CUSTOM_TYPE_CELL_RENDERER_COLOR)) #define CUSTOM_CELL_RENDERER_COLOR_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), CUSTOM_TYPE_CELL_RENDERER_COLOR, CustomCellRendererColorClass)) struct CustomCellRendererColor { GtkCellRenderer parent; ColorObject *color; int width; int height; }; struct CustomCellRendererColorClass { GtkCellRendererClass parent_class; }; GType custom_cell_renderer_color_get_type(); GtkCellRenderer *custom_cell_renderer_color_new(); void custom_cell_renderer_color_set_size(GtkCellRenderer *cell, gint width, gint height); #endif /* GPICK_GTK_COLOR_CELL_H_ */ gpick-gpick-0.2.6rc1/source/gtk/ColorComponent.cpp000066400000000000000000000744711315430016700220640ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ColorComponent.h" #include "../uiUtilities.h" #include "../Color.h" #include "../MathUtil.h" #include "../Paths.h" #include #include #include using namespace std; #define GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE((obj), GTK_TYPE_COLOR_COMPONENT, GtkColorComponentPrivate)) G_DEFINE_TYPE(GtkColorComponent, gtk_color_component, GTK_TYPE_DRAWING_AREA); struct GtkColorComponentPrivate; static gboolean button_release(GtkWidget *widget, GdkEventButton *event); static gboolean button_press(GtkWidget *node_system, GdkEventButton *event); static gboolean motion_notify(GtkWidget *node_system, GdkEventMotion *event); static void update_rgb_color(GtkColorComponentPrivate *ns, Color *c); static void finalize(GObject *color_obj); #if GTK_MAJOR_VERSION >= 3 static gboolean draw(GtkWidget *widget, cairo_t *cr); #else static gboolean expose(GtkWidget *widget, GdkEventExpose *event); static void size_request(GtkWidget *widget, GtkRequisition *requisition); #endif enum { COLOR_CHANGED, INPUT_CLICKED, LAST_SIGNAL }; static const int MaxNumberOfComponents = 4; static guint signals[LAST_SIGNAL] = {}; struct GtkColorComponentPrivate { Color orig_color; Color color; GtkColorComponentComp component; int n_components; int capture_on; gint last_event_position; bool changing_color; bool out_of_gamut_mask; ReferenceIlluminant lab_illuminant; ReferenceObserver lab_observer; cairo_surface_t *pattern_surface; cairo_pattern_t *pattern; const char *label[MaxNumberOfComponents][2]; gchar *text[MaxNumberOfComponents]; double range[MaxNumberOfComponents]; double offset[MaxNumberOfComponents]; #if GTK_MAJOR_VERSION >= 3 GdkDevice *pointer_grab; #endif }; static void gtk_color_component_class_init(GtkColorComponentClass *color_component_class) { GObjectClass *obj_class = G_OBJECT_CLASS (color_component_class); obj_class->finalize = finalize; g_type_class_add_private(obj_class, sizeof(GtkColorComponentPrivate)); GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (color_component_class); widget_class->button_release_event = button_release; widget_class->button_press_event = button_press; widget_class->motion_notify_event = motion_notify; #if GTK_MAJOR_VERSION >= 3 widget_class->draw = draw; #else widget_class->expose_event = expose; widget_class->size_request = size_request; #endif signals[COLOR_CHANGED] = g_signal_new( "color-changed", G_OBJECT_CLASS_TYPE(obj_class), G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET(GtkColorComponentClass, color_changed), nullptr, nullptr, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1, G_TYPE_POINTER); signals[INPUT_CLICKED] = g_signal_new( "input-clicked", G_OBJECT_CLASS_TYPE(obj_class), G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET(GtkColorComponentClass, input_clicked), nullptr, nullptr, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); } static void gtk_color_component_init(GtkColorComponent *color_component) { gtk_widget_add_events(GTK_WIDGET(color_component), GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_BUTTON_MOTION_MASK); } static void finalize(GObject *color_obj) { GtkColorComponentPrivate *ns = GET_PRIVATE(color_obj); for (int i = 0; i != sizeof(ns->text) / sizeof(gchar*); i++){ if (ns->text[i]){ g_free(ns->text[i]); ns->text[i] = 0; } } if (ns->pattern_surface) cairo_surface_destroy(ns->pattern_surface); if (ns->pattern) cairo_pattern_destroy(ns->pattern); gpointer parent_class = g_type_class_peek_parent(G_OBJECT_CLASS(GTK_COLOR_COMPONENT_GET_CLASS(color_obj))); G_OBJECT_CLASS(parent_class)->finalize(color_obj); } GtkWidget *gtk_color_component_new(GtkColorComponentComp component) { GtkWidget* widget = (GtkWidget*)g_object_new(GTK_TYPE_COLOR_COMPONENT, nullptr); GtkColorComponentPrivate *ns = GET_PRIVATE(widget); gchar* pattern_filename = build_filename("gpick-gray-pattern.png"); ns->pattern_surface = cairo_image_surface_create_from_png(pattern_filename); g_free(pattern_filename); ns->pattern = cairo_pattern_create_for_surface(ns->pattern_surface); cairo_pattern_set_extend(ns->pattern, CAIRO_EXTEND_REPEAT); ns->component = component; ns->last_event_position = -1; ns->changing_color = false; ns->lab_illuminant = REFERENCE_ILLUMINANT_D50; ns->lab_observer= REFERENCE_OBSERVER_2; ns->out_of_gamut_mask = false; #if GTK_MAJOR_VERSION >= 3 ns->pointer_grab = nullptr; #endif for (int i = 0; i != sizeof(ns->text) / sizeof(gchar*); i++){ ns->text[i] = 0; } for (int i = 0; i != sizeof(ns->label) / sizeof(const char*[2]); i++){ ns->label[i][0] = 0; ns->label[i][1] = 0; } switch (component){ case GtkColorComponentComp::lab: ns->n_components = 3; ns->range[0] = 100; ns->offset[0] = 0; ns->range[1] = ns->range[2] = 290; ns->offset[1] = ns->offset[2] = -145; break; case GtkColorComponentComp::lch: ns->n_components = 3; ns->range[0] = 100; ns->offset[0] = 0; ns->range[1] = 136; ns->range[2] = 360; ns->offset[1] = ns->offset[2] = 0; break; case GtkColorComponentComp::xyz: //TODO: implement break; case GtkColorComponentComp::cmyk: ns->n_components = 4; ns->range[0] = ns->range[1] = ns->range[2] = ns->range[3] = 1; ns->offset[0] = ns->offset[1] = ns->offset[2] = ns->offset[3] = 0; break; default: ns->n_components = 3; ns->range[0] = ns->range[1] = ns->range[2] = ns->range[3] = 1; ns->offset[0] = ns->offset[1] = ns->offset[2] = ns->offset[3] = 0; } gtk_widget_set_size_request(GTK_WIDGET(widget), 242, 16 * ns->n_components); return widget; } void gtk_color_component_get_color(GtkColorComponent* color_component, Color* color) { GtkColorComponentPrivate *ns = GET_PRIVATE(color_component); color_copy(&ns->orig_color, color); } void gtk_color_component_get_transformed_color(GtkColorComponent* color_component, Color* color) { GtkColorComponentPrivate *ns = GET_PRIVATE(color_component); color_copy(&ns->color, color); } void gtk_color_component_set_transformed_color(GtkColorComponent* color_component, Color* color) { GtkColorComponentPrivate *ns = GET_PRIVATE(color_component); color_copy(color, &ns->color); update_rgb_color(ns, &ns->orig_color); gtk_widget_queue_draw(GTK_WIDGET(color_component)); } int gtk_color_component_get_component_id_at(GtkColorComponent* color_component, gint x, gint y) { GtkColorComponentPrivate *ns = GET_PRIVATE(color_component); int component = y / 16; if (component < 0) component = 0; else if (component >= ns->n_components) component = ns->n_components - 1; return component; } const char* gtk_color_component_get_text(GtkColorComponent* color_component, gint component_id) { GtkColorComponentPrivate *ns = GET_PRIVATE(color_component); return ns->text[component_id]; } void gtk_color_component_set_text(GtkColorComponent* color_component, const char **text) { GtkColorComponentPrivate *ns = GET_PRIVATE(color_component); for (int i = 0; i != sizeof(ns->text) / sizeof(gchar*); i++){ if (!text[i]) break; if (ns->text[i]){ g_free(ns->text[i]); } ns->text[i] = g_strdup(text[i]); } gtk_widget_queue_draw(GTK_WIDGET(color_component)); } void gtk_color_component_set_label(GtkColorComponent* color_component, const char **label) { GtkColorComponentPrivate *ns = GET_PRIVATE(color_component); for (int i = 0; i != MaxNumberOfComponents * 2; i++){ if (!label[i]) break; ns->label[i >> 1][i & 1] = label[i]; } gtk_widget_queue_draw(GTK_WIDGET(color_component)); } void gtk_color_component_set_color(GtkColorComponent* color_component, Color* color) { GtkColorComponentPrivate *ns = GET_PRIVATE(color_component); color_copy(color, &ns->orig_color); switch (ns->component){ case GtkColorComponentComp::rgb: color_copy(&ns->orig_color, &ns->color); break; case GtkColorComponentComp::hsl: color_rgb_to_hsl(&ns->orig_color, &ns->color); break; case GtkColorComponentComp::hsv: color_rgb_to_hsv(&ns->orig_color, &ns->color); break; case GtkColorComponentComp::cmyk: color_rgb_to_cmyk(&ns->orig_color, &ns->color); break; case GtkColorComponentComp::lab: { matrix3x3 adaptation_matrix; color_get_chromatic_adaptation_matrix(color_get_reference(REFERENCE_ILLUMINANT_D65, REFERENCE_OBSERVER_2), color_get_reference(ns->lab_illuminant, ns->lab_observer), &adaptation_matrix); color_rgb_to_lab(&ns->orig_color, &ns->color, color_get_reference(ns->lab_illuminant, ns->lab_observer), color_get_sRGB_transformation_matrix(), &adaptation_matrix); } break; case GtkColorComponentComp::xyz: //TODO: implement break; case GtkColorComponentComp::lch: { matrix3x3 adaptation_matrix; color_get_chromatic_adaptation_matrix(color_get_reference(REFERENCE_ILLUMINANT_D65, REFERENCE_OBSERVER_2), color_get_reference(ns->lab_illuminant, ns->lab_observer), &adaptation_matrix); color_rgb_to_lch(&ns->orig_color, &ns->color, color_get_reference(ns->lab_illuminant, ns->lab_observer), color_get_sRGB_transformation_matrix(), &adaptation_matrix); } break; } gtk_widget_queue_draw(GTK_WIDGET(color_component)); } static void interpolate_colors(Color *color1, Color *color2, float position, Color *result) { result->rgb.red = color1->rgb.red * (1 - position) + color2->rgb.red * position; result->rgb.green= color1->rgb.green * (1 - position) + color2->rgb.green * position; result->rgb.blue = color1->rgb.blue * (1 - position) + color2->rgb.blue * position; } #if GTK_MAJOR_VERSION >= 3 #else static void size_request(GtkWidget *widget, GtkRequisition *requisition) { GtkColorComponentPrivate *ns = GET_PRIVATE(widget); gint width = 240 + widget->style->xthickness * 2; gint height = ns->n_components * 16 + widget->style->ythickness * 2; requisition->width = width; requisition->height = height; } #endif static int get_x_offset(GtkWidget *widget) { #if GTK_MAJOR_VERSION >= 3 return 0; #else return widget->allocation.width - widget->style->xthickness * 2 - 240; #endif } static gboolean draw(GtkWidget *widget, cairo_t *cr) { GtkColorComponentPrivate *ns = GET_PRIVATE(widget); Color c[MaxNumberOfComponents]; double pointer_pos[MaxNumberOfComponents]; float steps; int i, j; for (int i = 0; i < ns->n_components; ++i){ pointer_pos[i] = (ns->color.ma[i] - ns->offset[i]) / ns->range[i]; } cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 200, ns->n_components * 16); unsigned char *data = cairo_image_surface_get_data(surface); int stride = cairo_image_surface_get_stride(surface); int surface_width = cairo_image_surface_get_width(surface); unsigned char *col_ptr; Color *rgb_points = new Color[ns->n_components * 200]; double int_part; matrix3x3 adaptation_matrix; vector > out_of_gamut(MaxNumberOfComponents, vector(false, 1)); switch (ns->component) { case GtkColorComponentComp::rgb: steps = 1; for (i = 0; i < 3; ++i){ color_copy(&ns->color, &c[i]); } for (i = 0; i < surface_width; ++i){ c[0].rgb.red = c[1].rgb.green = c[2].rgb.blue = (float)i / (float)(surface_width - 1); col_ptr = data + i * 4; for (int y = 0; y < ns->n_components * 16; ++y){ if ((y & 0x0f) != 0x0f){ col_ptr[2] = (unsigned char)(c[y / 16].rgb.red * 255); col_ptr[1] = (unsigned char)(c[y / 16].rgb.green * 255); col_ptr[0] = (unsigned char)(c[y / 16].rgb.blue * 255); col_ptr[3] = 0xff; }else{ col_ptr[0] = 0x00; col_ptr[1] = 0x00; col_ptr[2] = 0x00; col_ptr[3] = 0x00; } col_ptr += stride; } } break; case GtkColorComponentComp::hsv: steps = 100; for (i = 0; i < 3; ++i){ color_copy(&ns->color, &c[i]); } for (i = 0; i <= steps; ++i){ c[0].hsv.hue = c[1].hsv.saturation = c[2].hsv.value = i / steps; for (j = 0; j < 3; ++j){ color_hsv_to_rgb(&c[j], &rgb_points[j * (int(steps) + 1) + i]); } } for (i = 0; i < surface_width; ++i){ float position = modf(i * steps / surface_width, &int_part); int index = i * int(steps) / surface_width; interpolate_colors(&rgb_points[0 * (int(steps) + 1) + index], &rgb_points[0 * (int(steps) + 1) + index + 1], position, &c[0]); interpolate_colors(&rgb_points[1 * (int(steps) + 1) + index], &rgb_points[1 * (int(steps) + 1) + index + 1], position, &c[1]); interpolate_colors(&rgb_points[2 * (int(steps) + 1) + index], &rgb_points[2 * (int(steps) + 1) + index + 1], position, &c[2]); col_ptr = data + i * 4; for (int y = 0; y < ns->n_components * 16; ++y){ if ((y & 0x0f) != 0x0f){ col_ptr[2] = (unsigned char)(c[y / 16].rgb.red * 255); col_ptr[1] = (unsigned char)(c[y / 16].rgb.green * 255); col_ptr[0] = (unsigned char)(c[y / 16].rgb.blue * 255); col_ptr[3] = 0xff; }else{ col_ptr[0] = 0x00; col_ptr[1] = 0x00; col_ptr[2] = 0x00; col_ptr[3] = 0x00; } col_ptr += stride; } } break; case GtkColorComponentComp::hsl: steps = 100; for (i = 0; i < 3; ++i){ color_copy(&ns->color, &c[i]); } for (i = 0; i <= steps; ++i){ c[0].hsl.hue = c[1].hsl.saturation = c[2].hsl.lightness = i / steps; for (j = 0; j < 3; ++j){ color_hsl_to_rgb(&c[j], &rgb_points[j * (int(steps) + 1) + i]); } } for (i = 0; i < surface_width; ++i){ float position = modf(i * steps / surface_width, &int_part); int index = i * int(steps) / surface_width; interpolate_colors(&rgb_points[0 * (int(steps) + 1) + index], &rgb_points[0 * (int(steps) + 1) + index + 1], position, &c[0]); interpolate_colors(&rgb_points[1 * (int(steps) + 1) + index], &rgb_points[1 * (int(steps) + 1) + index + 1], position, &c[1]); interpolate_colors(&rgb_points[2 * (int(steps) + 1) + index], &rgb_points[2 * (int(steps) + 1) + index + 1], position, &c[2]); col_ptr = data + i * 4; for (int y = 0; y < ns->n_components * 16; ++y){ if ((y & 0x0f) != 0x0f){ col_ptr[2] = (unsigned char)(c[y / 16].rgb.red * 255); col_ptr[1] = (unsigned char)(c[y / 16].rgb.green * 255); col_ptr[0] = (unsigned char)(c[y / 16].rgb.blue * 255); col_ptr[3] = 0xff; }else{ col_ptr[0] = 0x00; col_ptr[1] = 0x00; col_ptr[2] = 0x00; col_ptr[3] = 0x00; } col_ptr += stride; } } break; case GtkColorComponentComp::cmyk: steps = 100; for (i = 0; i < 4; ++i){ color_copy(&ns->color, &c[i]); } for (i = 0; i <= steps; ++i){ c[0].cmyk.c = c[1].cmyk.m = c[2].cmyk.y = c[3].cmyk.k = i / steps; for (j = 0; j < 4; ++j){ color_cmyk_to_rgb(&c[j], &rgb_points[j * (int(steps) + 1) + i]); } } for (i = 0; i < surface_width; ++i){ float position = modf(i * steps / surface_width, &int_part); int index = i * int(steps) / surface_width; interpolate_colors(&rgb_points[0 * (int(steps) + 1) + index], &rgb_points[0 * (int(steps) + 1) + index + 1], position, &c[0]); interpolate_colors(&rgb_points[1 * (int(steps) + 1) + index], &rgb_points[1 * (int(steps) + 1) + index + 1], position, &c[1]); interpolate_colors(&rgb_points[2 * (int(steps) + 1) + index], &rgb_points[2 * (int(steps) + 1) + index + 1], position, &c[2]); interpolate_colors(&rgb_points[3 * (int(steps) + 1) + index], &rgb_points[3 * (int(steps) + 1) + index + 1], position, &c[3]); col_ptr = data + i * 4; for (int y = 0; y < ns->n_components * 16; ++y){ if ((y & 0x0f) != 0x0f){ col_ptr[2] = (unsigned char)(c[y / 16].rgb.red * 255); col_ptr[1] = (unsigned char)(c[y / 16].rgb.green * 255); col_ptr[0] = (unsigned char)(c[y / 16].rgb.blue * 255); col_ptr[3] = 0xff; }else{ col_ptr[0] = 0x00; col_ptr[1] = 0x00; col_ptr[2] = 0x00; col_ptr[3] = 0x00; } col_ptr += stride; } } break; case GtkColorComponentComp::lab: steps = 100; color_get_chromatic_adaptation_matrix(color_get_reference(ns->lab_illuminant, ns->lab_observer), color_get_reference(REFERENCE_ILLUMINANT_D65, REFERENCE_OBSERVER_2), &adaptation_matrix); for (j = 0; j < 3; ++j){ color_copy(&ns->color, &c[j]); out_of_gamut[j] = vector(steps + 1, false); for (i = 0; i <= steps; ++i){ c[j].ma[j] = (i / steps) * ns->range[j] + ns->offset[j]; color_lab_to_rgb(&c[j], &rgb_points[j * (int(steps) + 1) + i], color_get_reference(ns->lab_illuminant, ns->lab_observer), color_get_inverted_sRGB_transformation_matrix(), &adaptation_matrix); if (color_is_rgb_out_of_gamut(&rgb_points[j * (int(steps) + 1) + i])){ out_of_gamut[j][i] = true; } color_rgb_normalize(&rgb_points[j * (int(steps) + 1) + i]); } } for (i = 0; i < surface_width; ++i){ float position = modf(i * steps / surface_width, &int_part); int index = i * int(steps) / surface_width; interpolate_colors(&rgb_points[0 * (int(steps) + 1) + index], &rgb_points[0 * (int(steps) + 1) + index + 1], position, &c[0]); interpolate_colors(&rgb_points[1 * (int(steps) + 1) + index], &rgb_points[1 * (int(steps) + 1) + index + 1], position, &c[1]); interpolate_colors(&rgb_points[2 * (int(steps) + 1) + index], &rgb_points[2 * (int(steps) + 1) + index + 1], position, &c[2]); col_ptr = data + i * 4; for (int y = 0; y < ns->n_components * 16; ++y){ if ((y & 0x0f) != 0x0f){ col_ptr[2] = (unsigned char)(c[y / 16].rgb.red * 255); col_ptr[1] = (unsigned char)(c[y / 16].rgb.green * 255); col_ptr[0] = (unsigned char)(c[y / 16].rgb.blue * 255); col_ptr[3] = 0xff; }else{ col_ptr[0] = 0x00; col_ptr[1] = 0x00; col_ptr[2] = 0x00; col_ptr[3] = 0x00; } col_ptr += stride; } } break; case GtkColorComponentComp::lch: steps = 100; color_get_chromatic_adaptation_matrix(color_get_reference(ns->lab_illuminant, ns->lab_observer), color_get_reference(REFERENCE_ILLUMINANT_D65, REFERENCE_OBSERVER_2), &adaptation_matrix); for (j = 0; j < 3; ++j){ color_copy(&ns->color, &c[j]); out_of_gamut[j] = vector(steps + 1, false); for (i = 0; i <= steps; ++i){ c[j].ma[j] = (i / steps) * ns->range[j] + ns->offset[j]; color_lch_to_rgb(&c[j], &rgb_points[j * (int(steps) + 1) + i], color_get_reference(ns->lab_illuminant, ns->lab_observer), color_get_inverted_sRGB_transformation_matrix(), &adaptation_matrix); if (color_is_rgb_out_of_gamut(&rgb_points[j * (int(steps) + 1) + i])){ out_of_gamut[j][i] = true; } color_rgb_normalize(&rgb_points[j * (int(steps) + 1) + i]); } } for (i = 0; i < surface_width; ++i){ float position = modf(i * steps / surface_width, &int_part); int index = i * int(steps) / surface_width; interpolate_colors(&rgb_points[0 * (int(steps) + 1) + index], &rgb_points[0 * (int(steps) + 1) + index + 1], position, &c[0]); interpolate_colors(&rgb_points[1 * (int(steps) + 1) + index], &rgb_points[1 * (int(steps) + 1) + index + 1], position, &c[1]); interpolate_colors(&rgb_points[2 * (int(steps) + 1) + index], &rgb_points[2 * (int(steps) + 1) + index + 1], position, &c[2]); col_ptr = data + i * 4; for (int y = 0; y < ns->n_components * 16; ++y){ if ((y & 0x0f) != 0x0f){ col_ptr[2] = (unsigned char)(c[y / 16].rgb.red * 255); col_ptr[1] = (unsigned char)(c[y / 16].rgb.green * 255); col_ptr[0] = (unsigned char)(c[y / 16].rgb.blue * 255); col_ptr[3] = 0xff; }else{ col_ptr[0] = 0x00; col_ptr[1] = 0x00; col_ptr[2] = 0x00; col_ptr[3] = 0x00; } col_ptr += stride; } } break; default: break; } delete [] rgb_points; cairo_surface_mark_dirty(surface); cairo_save(cr); int offset_x = get_x_offset(widget); cairo_set_source_surface(cr, surface, offset_x, 0); cairo_surface_destroy(surface); for (i = 0; i < ns->n_components; ++i){ cairo_rectangle(cr, offset_x, 16 * i, 200, 15); cairo_fill(cr); } cairo_restore(cr); for (i = 0; i < ns->n_components; ++i){ cairo_matrix_t matrix; cairo_matrix_init_translate(&matrix, -offset_x - 64, -64 + 5 * i); cairo_pattern_set_matrix(ns->pattern, &matrix); if (ns->out_of_gamut_mask){ int first_out_of_gamut = 0; bool out_of_gamut_found = false; cairo_set_source(cr, ns->pattern); for (size_t j = 0; j < out_of_gamut[i].size(); j++){ if (out_of_gamut[i][j]){ if (!out_of_gamut_found){ out_of_gamut_found = true; first_out_of_gamut = j; } }else{ if (out_of_gamut_found){ cairo_rectangle(cr, offset_x + (first_out_of_gamut * 200.0 / out_of_gamut[i].size()), 16 * i, (j - first_out_of_gamut) * 200.0 / out_of_gamut[i].size(), 15); cairo_fill(cr); out_of_gamut_found = false; } } } if (out_of_gamut_found){ cairo_rectangle(cr, offset_x + (first_out_of_gamut * 200.0 / out_of_gamut[i].size()), 16 * i, (out_of_gamut[i].size() - first_out_of_gamut) * 200.0 / out_of_gamut[i].size(), 15); cairo_fill(cr); } } cairo_move_to(cr, offset_x + 200 * pointer_pos[i], 16 * i + 9); cairo_line_to(cr, offset_x + 200 * pointer_pos[i] + 3, 16 * i + 16); cairo_line_to(cr, offset_x + 200 * pointer_pos[i] - 3, 16 * i + 16); cairo_set_source_rgb(cr, 1, 1, 1); cairo_fill_preserve(cr); cairo_set_source_rgb(cr, 0, 0, 0); cairo_set_line_width(cr, 1); cairo_stroke(cr); if (ns->text[i] || ns->label[i]){ PangoLayout *layout; PangoFontDescription *font_description; font_description = pango_font_description_new(); layout = pango_cairo_create_layout(cr); pango_font_description_set_family(font_description, "sans"); pango_font_description_set_weight(font_description, PANGO_WEIGHT_NORMAL); pango_font_description_set_absolute_size(font_description, 12 * PANGO_SCALE); pango_layout_set_font_description(layout, font_description); pango_layout_set_wrap(layout, PANGO_WRAP_WORD); pango_layout_set_single_paragraph_mode(layout, true); #if GTK_MAJOR_VERSION >= 3 //TODO: GTK3 font color #else gdk_cairo_set_source_color(cr, &widget->style->text[0]); #endif int width, height; if (ns->text[i]){ pango_layout_set_text(layout, ns->text[i], -1); pango_layout_set_width(layout, 40 * PANGO_SCALE); pango_layout_set_height(layout, 16 * PANGO_SCALE); pango_layout_set_alignment(layout, PANGO_ALIGN_RIGHT); pango_cairo_update_layout(cr, layout); pango_layout_get_pixel_size(layout, &width, &height); cairo_move_to(cr, 200 + offset_x, i * 16); pango_cairo_show_layout(cr, layout); } if (ns->label[i] && offset_x > 10){ if (offset_x > 50){ pango_layout_set_text(layout, ns->label[i][1], -1); }else{ pango_layout_set_text(layout, ns->label[i][0], -1); } pango_layout_set_width(layout, (offset_x - 10) * PANGO_SCALE); pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_END); pango_layout_set_height(layout, 16 * PANGO_SCALE); pango_layout_set_alignment(layout, PANGO_ALIGN_LEFT); pango_cairo_update_layout(cr, layout); pango_layout_get_pixel_size(layout, &width, &height); cairo_move_to(cr, 5, i * 16); pango_cairo_show_layout(cr, layout); } g_object_unref(layout); pango_font_description_free(font_description); } } return TRUE; } #if GTK_MAJOR_VERSION < 3 static gboolean expose(GtkWidget *widget, GdkEventExpose *event) { cairo_t *cr = gdk_cairo_create(gtk_widget_get_window(widget)); cairo_rectangle(cr, event->area.x, event->area.y, event->area.width, event->area.height); cairo_clip(cr); cairo_translate(cr, widget->style->xthickness, widget->style->ythickness); gboolean result = draw(widget, cr); cairo_destroy(cr); return result; } #endif GtkColorComponentComp gtk_color_component_get_component(GtkColorComponent* color_component) { return GET_PRIVATE(color_component)->component; } static void update_rgb_color(GtkColorComponentPrivate *ns, Color *c) { switch (ns->component){ case GtkColorComponentComp::rgb: color_copy(&ns->color, c); color_rgb_normalize(c); break; case GtkColorComponentComp::hsv: color_hsv_to_rgb(&ns->color, c); color_rgb_normalize(c); break; case GtkColorComponentComp::hsl: color_hsl_to_rgb(&ns->color, c); color_rgb_normalize(c); break; case GtkColorComponentComp::cmyk: color_cmyk_to_rgb(&ns->color, c); color_rgb_normalize(c); break; case GtkColorComponentComp::lab: { matrix3x3 adaptation_matrix; color_get_chromatic_adaptation_matrix(color_get_reference(ns->lab_illuminant, ns->lab_observer), color_get_reference(REFERENCE_ILLUMINANT_D65, REFERENCE_OBSERVER_2), &adaptation_matrix); color_lab_to_rgb(&ns->color, c, color_get_reference(ns->lab_illuminant, ns->lab_observer), color_get_inverted_sRGB_transformation_matrix(), &adaptation_matrix); color_rgb_normalize(c); } break; case GtkColorComponentComp::xyz: //TODO: implement break; case GtkColorComponentComp::lch: { matrix3x3 adaptation_matrix; color_get_chromatic_adaptation_matrix(color_get_reference(ns->lab_illuminant, ns->lab_observer), color_get_reference(REFERENCE_ILLUMINANT_D65, REFERENCE_OBSERVER_2), &adaptation_matrix); color_lch_to_rgb(&ns->color, c, color_get_reference(ns->lab_illuminant, ns->lab_observer), color_get_inverted_sRGB_transformation_matrix(), &adaptation_matrix); color_rgb_normalize(c); } break; } } void gtk_color_component_get_raw_color(GtkColorComponent* color_component, Color* color) { GtkColorComponentPrivate *ns = GET_PRIVATE(color_component); color_copy(&ns->color, color); } void gtk_color_component_set_raw_color(GtkColorComponent* color_component, Color* color) { GtkColorComponentPrivate *ns = GET_PRIVATE(color_component); color_copy(color, &ns->color); Color c; update_rgb_color(ns, &c); color_copy(&c, &ns->orig_color); gtk_widget_queue_draw(GTK_WIDGET(color_component)); g_signal_emit(GTK_WIDGET(color_component), signals[COLOR_CHANGED], 0, &c); } static void emit_color_change(GtkWidget *widget, int component, double value) { GtkColorComponentPrivate *ns = GET_PRIVATE(widget); Color c; ns->color.ma[component] = value * ns->range[component] + ns->offset[component]; update_rgb_color(ns, &c); g_signal_emit(widget, signals[COLOR_CHANGED], 0, &c); } static gboolean button_release(GtkWidget *widget, GdkEventButton *event) { GtkColorComponentPrivate *ns = GET_PRIVATE(widget); #if GTK_MAJOR_VERSION >= 3 if (ns->pointer_grab){ gdk_seat_ungrab(gdk_device_get_seat(ns->pointer_grab)); ns->pointer_grab = nullptr; } #else gdk_pointer_ungrab(GDK_CURRENT_TIME); #endif ns->changing_color = false; return false; } static gboolean button_press(GtkWidget *widget, GdkEventButton *event) { GtkColorComponentPrivate *ns = GET_PRIVATE(widget); if ((event->type == GDK_BUTTON_PRESS) && (event->button == 1)){ int component = event->y / 16; if (component < 0) component = 0; else if (component >= ns->n_components) component = ns->n_components - 1; int offset_x = get_x_offset(widget); if (event->x < offset_x || event->x > 200 + offset_x) { g_signal_emit(widget, signals[INPUT_CLICKED], 0, component); return FALSE; } ns->changing_color = true; ns->last_event_position = event->x; double value; value = (event->x - offset_x) / 200.0; if (value < 0) value = 0; else if (value > 1) value = 1; ns->capture_on = component; #if GTK_MAJOR_VERSION >= 3 ns->pointer_grab = event->device; gdk_seat_grab(gdk_device_get_seat(event->device), gtk_widget_get_window(widget), GDK_SEAT_CAPABILITY_ALL, false, nullptr, nullptr, nullptr, nullptr); #else gdk_pointer_grab(gtk_widget_get_window(widget), false, GdkEventMask(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK), nullptr, nullptr, GDK_CURRENT_TIME); #endif emit_color_change(widget, component, value); gtk_widget_queue_draw(widget); return TRUE; } return FALSE; } static gboolean motion_notify(GtkWidget *widget, GdkEventMotion *event) { GtkColorComponentPrivate *ns = GET_PRIVATE(widget); if (ns->changing_color && (event->state & GDK_BUTTON1_MASK)){ int offset_x = get_x_offset(widget); if ((event->x < offset_x && ns->last_event_position < offset_x) || ((event->x > 200 + offset_x) && (ns->last_event_position > 200 + offset_x))) return FALSE; ns->last_event_position = event->x; double value; value = (event->x - offset_x) / 200.0; if (value < 0) value = 0; else if (value > 1) value = 1; emit_color_change(widget, ns->capture_on, value); gtk_widget_queue_draw(widget); return TRUE; } return FALSE; } void gtk_color_component_set_lab_illuminant(GtkColorComponent* color_component, ReferenceIlluminant illuminant) { GtkColorComponentPrivate *ns = GET_PRIVATE(color_component); ns->lab_illuminant = illuminant; gtk_color_component_set_color(color_component, &ns->orig_color); gtk_widget_queue_draw(GTK_WIDGET(color_component)); } void gtk_color_component_set_lab_observer(GtkColorComponent* color_component, ReferenceObserver observer) { GtkColorComponentPrivate *ns = GET_PRIVATE(color_component); ns->lab_observer = observer; gtk_color_component_set_color(color_component, &ns->orig_color); gtk_widget_queue_draw(GTK_WIDGET(color_component)); } void gtk_color_component_set_out_of_gamut_mask(GtkColorComponent* color_component, bool mask_enabled) { GtkColorComponentPrivate *ns = GET_PRIVATE(color_component); ns->out_of_gamut_mask = mask_enabled; gtk_widget_queue_draw(GTK_WIDGET(color_component)); } bool gtk_color_component_get_out_of_gamut_mask(GtkColorComponent* color_component) { GtkColorComponentPrivate *ns = GET_PRIVATE(color_component); return ns->out_of_gamut_mask; } gpick-gpick-0.2.6rc1/source/gtk/ColorComponent.h000066400000000000000000000102101315430016700215060ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_GTK_COLOR_COMPONENT_H_ #define GPICK_GTK_COLOR_COMPONENT_H_ #include #include "../Color.h" #define GTK_TYPE_COLOR_COMPONENT (gtk_color_component_get_type()) #define GTK_COLOR_COMPONENT(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), GTK_TYPE_COLOR_COMPONENT, GtkColorComponent)) #define GTK_COLOR_COMPONENT_CLASS(obj) (G_TYPE_CHECK_CLASS_CAST((obj), GTK_COLOR_COMPONENT, GtkColorComponentClass)) #define GTK_IS_COLOR_COMPONENT(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), GTK_TYPE_COLOR_COMPONENT)) #define GTK_IS_COLOR_COMPONENT_CLASS(obj) (G_TYPE_CHECK_CLASS_TYPE((obj), GTK_TYPE_COLOR_COMPONENT)) #define GTK_COLOR_COMPONENT_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), GTK_TYPE_COLOR_COMPONENT, GtkColorComponentClass)) struct GtkColorComponent { GtkDrawingArea parent; }; struct GtkColorComponentClass { GtkDrawingAreaClass parent_class; void (*color_changed)(GtkWidget* widget, Color* c, gpointer userdata); void (*input_clicked)(GtkWidget* widget, int component_id, gpointer userdata); }; enum class GtkColorComponentComp: int { rgb, hsv, hsl, cmyk, xyz, lab, lch, }; GtkWidget* gtk_color_component_new(GtkColorComponentComp component); void gtk_color_component_set_color(GtkColorComponent* color_component, Color* color); void gtk_color_component_set_text(GtkColorComponent* color_component, const char **text); const char* gtk_color_component_get_text(GtkColorComponent* color_component, gint component_id); void gtk_color_component_set_label(GtkColorComponent* color_component, const char **label); void gtk_color_component_get_color(GtkColorComponent* color_component, Color* color); void gtk_color_component_get_raw_color(GtkColorComponent* color_component, Color* color); void gtk_color_component_set_raw_color(GtkColorComponent* color_component, Color* color); void gtk_color_component_get_transformed_color(GtkColorComponent* color_component, Color* color); void gtk_color_component_set_transformed_color(GtkColorComponent* color_component, Color* color); void gtk_color_component_set_out_of_gamut_mask(GtkColorComponent* color_component, bool mask_enabled); bool gtk_color_component_get_out_of_gamut_mask(GtkColorComponent* color_component); void gtk_color_component_set_lab_illuminant(GtkColorComponent* color_component, ReferenceIlluminant illuminant); void gtk_color_component_set_lab_observer(GtkColorComponent* color_component, ReferenceObserver observer); GtkColorComponentComp gtk_color_component_get_component(GtkColorComponent* color_component); int gtk_color_component_get_component_id_at(GtkColorComponent* color_component, gint x, gint y); GType gtk_color_component_get_type(); #endif /* GPICK_GTK_COLOR_COMPONENT_H_ */ gpick-gpick-0.2.6rc1/source/gtk/ColorWheel.cpp000066400000000000000000000422731315430016700211610ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ColorWheel.h" #include "../Color.h" #include "../ColorWheelType.h" #include "../MathUtil.h" #include #ifdef _MSC_VER #define M_PI 3.14159265359 #endif #include #include #include using namespace std; #define GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE((obj), GTK_TYPE_COLOR_WHEEL, GtkColorWheelPrivate)) G_DEFINE_TYPE (GtkColorWheel, gtk_color_wheel, GTK_TYPE_DRAWING_AREA); struct GtkColorWheelPrivate; struct ColorPoint; static GtkWindowClass *parent_class = nullptr; static gboolean button_release(GtkWidget *color_wheel, GdkEventButton *event); static gboolean button_press(GtkWidget *color_wheel, GdkEventButton *event); static gboolean motion_notify(GtkWidget *widget, GdkEventMotion *event); static uint32_t get_color_index(GtkColorWheelPrivate *ns, ColorPoint *cp); #if GTK_MAJOR_VERSION >= 3 static gboolean draw(GtkWidget *widget, cairo_t *cr); #else static gboolean expose(GtkWidget *color_wheel, GdkEventExpose *event); #endif enum { HUE_CHANGED, SATURATION_VALUE_CHANGED, LAST_SIGNAL }; static guint signals[LAST_SIGNAL] = {0}; struct ColorPoint { double hue; double lightness; double saturation; }; struct GtkColorWheelPrivate { ColorPoint cpoint[10]; uint32_t n_cpoint; ColorPoint *grab_active; bool grab_block; ColorPoint *selected; int active_color; double radius; double circle_width; double block_size; bool block_editable; const ColorWheelType *color_wheel_type; cairo_surface_t *cache_color_wheel; #if GTK_MAJOR_VERSION >= 3 GdkDevice *pointer_grab; #endif }; static void finalize(GObject *color_wheel_obj) { GtkColorWheelPrivate *ns = GET_PRIVATE(color_wheel_obj); if (ns->cache_color_wheel){ cairo_surface_destroy(ns->cache_color_wheel); ns->cache_color_wheel = 0; } G_OBJECT_CLASS(parent_class)->finalize(color_wheel_obj); } static void gtk_color_wheel_class_init(GtkColorWheelClass *color_wheel_class) { GObjectClass *obj_class = G_OBJECT_CLASS(color_wheel_class); obj_class->finalize = finalize; GtkWidgetClass *widget_class = GTK_WIDGET_CLASS(color_wheel_class); widget_class->button_release_event = button_release; widget_class->button_press_event = button_press; widget_class->motion_notify_event = motion_notify; #if GTK_MAJOR_VERSION >= 3 widget_class->draw = draw; #else widget_class->expose_event = expose; #endif parent_class = (GtkWindowClass*)g_type_class_peek_parent(G_OBJECT_CLASS(color_wheel_class)); g_type_class_add_private(obj_class, sizeof(GtkColorWheelPrivate)); signals[HUE_CHANGED] = g_signal_new("hue_changed", G_OBJECT_CLASS_TYPE(obj_class), G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET(GtkColorWheelClass, hue_changed), nullptr, nullptr, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); signals[SATURATION_VALUE_CHANGED] = g_signal_new("saturation_value_changed", G_OBJECT_CLASS_TYPE(obj_class), G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET(GtkColorWheelClass, saturation_value_changed), nullptr, nullptr, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); } static void gtk_color_wheel_init(GtkColorWheel *color_wheel) { gtk_widget_add_events(GTK_WIDGET(color_wheel), GDK_2BUTTON_PRESS | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_FOCUS_CHANGE_MASK | GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK); } GtkWidget* gtk_color_wheel_new() { GtkWidget* widget = (GtkWidget*) g_object_new(GTK_TYPE_COLOR_WHEEL, nullptr); GtkColorWheelPrivate *ns = GET_PRIVATE(widget); ns->active_color = 1; ns->radius = 80; ns->circle_width = 14; ns->block_size = 2 * (ns->radius - ns->circle_width) * sin(M_PI / 4) - 8; #if GTK_MAJOR_VERSION >= 3 gtk_widget_set_size_request(GTK_WIDGET(widget), ns->radius * 2, ns->radius * 2); #else gtk_widget_set_size_request(GTK_WIDGET(widget), ns->radius * 2 + widget->style->xthickness * 2, ns->radius * 2 + widget->style->ythickness * 2); #endif ns->n_cpoint = 0; ns->grab_active = 0; ns->grab_block = false; ns->selected = &ns->cpoint[0]; ns->block_editable = true; ns->color_wheel_type = &color_wheel_types_get()[0]; ns->cache_color_wheel = 0; #if GTK_MAJOR_VERSION >= 3 ns->pointer_grab = nullptr; #endif gtk_widget_set_can_focus(widget, true); return widget; } void gtk_color_wheel_set_color_wheel_type(GtkColorWheel *color_wheel, const ColorWheelType *color_wheel_type) { GtkColorWheelPrivate *ns = GET_PRIVATE(color_wheel); if (ns->color_wheel_type != color_wheel_type){ ns->color_wheel_type = color_wheel_type; if (ns->cache_color_wheel){ cairo_surface_destroy(ns->cache_color_wheel); ns->cache_color_wheel = 0; } gtk_widget_queue_draw(GTK_WIDGET(color_wheel)); } } void gtk_color_wheel_set_block_editable(GtkColorWheel* color_wheel, bool editable) { GtkColorWheelPrivate *ns = GET_PRIVATE(color_wheel); ns->block_editable = editable; } bool gtk_color_wheel_get_block_editable(GtkColorWheel* color_wheel) { GtkColorWheelPrivate *ns = GET_PRIVATE(color_wheel); return ns->block_editable; } void gtk_color_wheel_set_selected(GtkColorWheel* color_wheel, guint32 index) { GtkColorWheelPrivate *ns = GET_PRIVATE(color_wheel); if (index < 10){ ns->selected = &ns->cpoint[index]; gtk_widget_queue_draw(GTK_WIDGET(color_wheel)); } } void gtk_color_wheel_set_n_colors(GtkColorWheel* color_wheel, guint32 number_of_colors) { GtkColorWheelPrivate *ns = GET_PRIVATE(color_wheel); if (number_of_colors <= 10){ if (ns->n_cpoint != number_of_colors){ ns->n_cpoint = number_of_colors; if (ns->selected){ uint32_t index = get_color_index(ns, ns->selected); if (index >= number_of_colors){ ns->selected = &ns->cpoint[0]; } } gtk_widget_queue_draw(GTK_WIDGET(color_wheel)); } } } void gtk_color_wheel_set_hue(GtkColorWheel* color_wheel, guint32 index, double hue) { GtkColorWheelPrivate *ns = GET_PRIVATE(color_wheel); if (index < 10){ ns->cpoint[index].hue = hue; gtk_widget_queue_draw(GTK_WIDGET(color_wheel)); } } void gtk_color_wheel_set_saturation(GtkColorWheel* color_wheel, guint32 index, double saturation) { GtkColorWheelPrivate *ns = GET_PRIVATE(color_wheel); if (index < 10){ ns->cpoint[index].saturation = saturation; if (&ns->cpoint[index] == ns->selected) gtk_widget_queue_draw(GTK_WIDGET(color_wheel)); } } void gtk_color_wheel_set_value(GtkColorWheel* color_wheel, guint32 index, double value) { GtkColorWheelPrivate *ns = GET_PRIVATE(color_wheel); if (index < 10){ ns->cpoint[index].lightness = value; if (&ns->cpoint[index] == ns->selected) gtk_widget_queue_draw(GTK_WIDGET(color_wheel)); } } double gtk_color_wheel_get_hue(GtkColorWheel* color_wheel, guint32 index) { GtkColorWheelPrivate *ns = GET_PRIVATE(color_wheel); if (index < 10){ return ns->cpoint[index].hue; } return 0; } double gtk_color_wheel_get_saturation(GtkColorWheel* color_wheel, guint32 index) { GtkColorWheelPrivate *ns = GET_PRIVATE(color_wheel); if (index < 10){ return ns->cpoint[index].saturation; } return 0; } double gtk_color_wheel_get_value(GtkColorWheel* color_wheel, guint32 index) { GtkColorWheelPrivate *ns = GET_PRIVATE(color_wheel); if (index < 10){ return ns->cpoint[index].lightness; } return 0; } static void draw_dot(cairo_t *cr, double x, double y, double size) { cairo_arc(cr, x, y, size - 1, 0, 2 * M_PI); cairo_set_source_rgba(cr, 1, 1, 1, 0.5); cairo_set_line_width(cr, 2); cairo_stroke(cr); cairo_arc(cr, x, y, size, 0, 2 * M_PI); cairo_set_source_rgba(cr, 0, 0, 0, 1); cairo_set_line_width(cr, 1); cairo_stroke(cr); } static void draw_sat_val_block(cairo_t *cr, double pos_x, double pos_y, double size, double hue) { cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, ceil(size), ceil(size)); unsigned char *data = cairo_image_surface_get_data(surface); int stride = cairo_image_surface_get_stride(surface); int surface_width = cairo_image_surface_get_width(surface); int surface_height = cairo_image_surface_get_height(surface); Color c; unsigned char *line_data; for (int y = 0; y < surface_height; ++y){ line_data = data + stride * y; for (int x = 0; x < surface_width; ++x){ c.hsv.hue = hue; c.hsv.saturation = x / size; c.hsv.value = y / size; color_hsv_to_rgb(&c, &c); line_data[2] = c.rgb.red * 255; line_data[1] = c.rgb.green * 255; line_data[0] = c.rgb.blue * 255; line_data[3] = 0xFF; line_data += 4; } } cairo_surface_mark_dirty(surface); cairo_save(cr); cairo_set_source_surface(cr, surface, pos_x - size / 2, pos_y - size / 2); cairo_surface_destroy(surface); cairo_rectangle(cr, pos_x - size / 2, pos_y - size / 2, size, size); cairo_fill(cr); cairo_restore(cr); } static void draw_wheel(GtkColorWheelPrivate *ns, cairo_t *cr, double radius, double width, const ColorWheelType *wheel) { cairo_surface_t *surface; double inner_radius = radius - width; if (ns->cache_color_wheel){ surface = ns->cache_color_wheel; }else{ surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, ceil(radius * 2), ceil(radius * 2)); if (cairo_surface_status(surface) != CAIRO_STATUS_SUCCESS){ cerr << "ColorWheel image surface allocation failed" << endl; return; } unsigned char *data = cairo_image_surface_get_data(surface); int stride = cairo_image_surface_get_stride(surface); int surface_width = cairo_image_surface_get_width(surface); int surface_height = cairo_image_surface_get_height(surface); double radius_sq = radius * radius + 2 * radius + 1; double inner_radius_sq = inner_radius * inner_radius - 2 * inner_radius + 1; Color c; unsigned char *line_data; for (int y = 0; y < surface_height; ++y){ line_data = data + stride * y; for (int x = 0; x < surface_width; ++x){ int dx = -(x - surface_width / 2); int dy = y - surface_height / 2; int dist = dx * dx + dy * dy; if ((dist >= inner_radius_sq) && (dist <= radius_sq)){ double angle = atan2((double)dx, (double)dy) + M_PI; wheel->hue_to_hsl(angle / (M_PI * 2), &c); color_hsl_to_rgb(&c, &c); line_data[2] = c.rgb.red * 255; line_data[1] = c.rgb.green * 255; line_data[0] = c.rgb.blue * 255; line_data[3] = 0xFF; } line_data += 4; } } ns->cache_color_wheel = surface; } cairo_surface_mark_dirty(surface); cairo_save(cr); cairo_set_source_surface(cr, surface, 0, 0); cairo_set_line_width(cr, width); cairo_new_path(cr); cairo_arc(cr, radius, radius, (inner_radius + radius) / 2, 0, M_PI * 2); cairo_stroke(cr); cairo_restore(cr); } static bool is_inside_block(GtkColorWheelPrivate *ns, gint x, gint y) { double size = ns->block_size; if ((x >= ns->radius - size / 2) && (x <= ns->radius + size / 2)){ if ((y >= ns->radius - size / 2) && (y <= ns->radius + size / 2)){ return true; } } return false; } static ColorPoint* get_cpoint_at(GtkColorWheelPrivate *ns, gint x, gint y) { double dx, dy; for (uint32_t i = 0; i != ns->n_cpoint; i++){ dx = ns->radius + (ns->radius - ns->circle_width / 2) * sin(ns->cpoint[i].hue * M_PI * 2) - x; dy = ns->radius - (ns->radius - ns->circle_width / 2) * cos(ns->cpoint[i].hue * M_PI * 2) - y; if (sqrt(dx * dx + dy * dy) < 16){ return &ns->cpoint[i]; } } return 0; } static uint32_t get_color_index(GtkColorWheelPrivate *ns, ColorPoint *cp) { return (uint64_t(cp) - uint64_t(ns)) / sizeof(ColorPoint); } int gtk_color_wheel_get_at(GtkColorWheel *color_wheel, int x, int y) { GtkColorWheelPrivate *ns = GET_PRIVATE(color_wheel); ColorPoint *cp = get_cpoint_at(ns, x, y); if (cp){ return get_color_index(ns, cp); } if (is_inside_block(ns, x, y)) return -1; return -2; } static void offset_xy(GtkWidget *widget, gint &x, gint &y) { #if GTK_MAJOR_VERSION < 3 x = x - widget->style->xthickness; y = y - widget->style->ythickness; #endif } static gboolean motion_notify(GtkWidget *widget, GdkEventMotion *event) { GtkColorWheelPrivate *ns = GET_PRIVATE(widget); int x = event->x, y = event->y; offset_xy(widget, x, y); if (ns->grab_active){ double dx = -(x - ns->radius); double dy = y - ns->radius; double angle = atan2(dx, dy) + M_PI; ns->grab_active->hue = angle / (M_PI * 2); g_signal_emit(widget, signals[HUE_CHANGED], 0, get_color_index(ns, ns->grab_active)); gtk_widget_queue_draw(widget); return true; }else if (ns->grab_block){ double dx = event->x - ns->radius + ns->block_size / 2; double dy = event->y - ns->radius + ns->block_size / 2; ns->selected->saturation = clamp_float(dx / ns->block_size, 0, 1); ns->selected->lightness = clamp_float(dy / ns->block_size, 0, 1); g_signal_emit(widget, signals[SATURATION_VALUE_CHANGED], 0, get_color_index(ns, ns->selected)); gtk_widget_queue_draw(widget); return true; } return false; } static gboolean draw(GtkWidget *widget, cairo_t *cr) { GtkColorWheelPrivate *ns = GET_PRIVATE(widget); draw_wheel(ns, cr, ns->radius, ns->circle_width, ns->color_wheel_type); if (ns->selected){ double block_size = 2 * (ns->radius - ns->circle_width) * sin(M_PI / 4) - 6; Color hsl; ns->color_wheel_type->hue_to_hsl(ns->selected->hue, &hsl); draw_sat_val_block(cr, ns->radius, ns->radius, block_size, hsl.hsl.hue); draw_dot(cr, ns->radius - block_size / 2 + block_size * ns->selected->saturation, ns->radius - block_size / 2 + block_size * ns->selected->lightness, 4); } for (uint32_t i = 0; i != ns->n_cpoint; i++){ draw_dot(cr, ns->radius + (ns->radius - ns->circle_width / 2) * sin(ns->cpoint[i].hue * M_PI * 2), ns->radius - (ns->radius - ns->circle_width / 2) * cos(ns->cpoint[i].hue * M_PI * 2), (&ns->cpoint[i] == ns->selected) ? 7 : 4); } return FALSE; } #if GTK_MAJOR_VERSION < 3 static gboolean expose(GtkWidget *widget, GdkEventExpose *event) { cairo_t *cr; GtkColorWheelPrivate *ns = GET_PRIVATE(widget); cr = gdk_cairo_create(gtk_widget_get_window(widget)); cairo_rectangle(cr, event->area.x, event->area.y, event->area.width, event->area.height); cairo_clip(cr); cairo_translate(cr, widget->style->xthickness + 0.5, widget->style->ythickness + 0.5); gboolean result = draw(widget, cr); cairo_destroy(cr); return result; } #endif static gboolean button_press(GtkWidget *widget, GdkEventButton *event) { GtkColorWheelPrivate *ns = GET_PRIVATE(widget); int x = event->x, y = event->y; offset_xy(widget, x, y); gtk_widget_grab_focus(widget); ColorPoint *p; if (is_inside_block(ns, x, y)){ if ((event->type == GDK_BUTTON_PRESS) && (event->button == 1)){ if (ns->block_editable && ns->selected){ ns->grab_block = true; GdkCursor *cursor = gdk_cursor_new_for_display(gtk_widget_get_display(widget), GDK_CROSS); #if GTK_MAJOR_VERSION >= 3 ns->pointer_grab = event->device; gdk_seat_grab(gdk_device_get_seat(event->device), gtk_widget_get_window(widget), GDK_SEAT_CAPABILITY_ALL, false, cursor, nullptr, nullptr, nullptr); g_object_unref(cursor); #else gdk_pointer_grab(gtk_widget_get_window(widget), false, GdkEventMask(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK), nullptr, cursor, GDK_CURRENT_TIME); gdk_cursor_unref(cursor); #endif return true; } } }else if ((p = get_cpoint_at(ns, x, y))){ if ((event->type == GDK_BUTTON_PRESS) && (event->button == 1)){ ns->grab_active = p; ns->selected = p; GdkCursor *cursor = gdk_cursor_new_for_display(gtk_widget_get_display(widget), GDK_CROSS); #if GTK_MAJOR_VERSION >= 3 ns->pointer_grab = event->device; gdk_seat_grab(gdk_device_get_seat(event->device), gtk_widget_get_window(widget), GDK_SEAT_CAPABILITY_ALL, false, cursor, nullptr, nullptr, nullptr); g_object_unref(cursor); #else gdk_pointer_grab(gtk_widget_get_window(widget), false, GdkEventMask(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK), nullptr, cursor, GDK_CURRENT_TIME); gdk_cursor_unref(cursor); #endif return true; } } return false; } static gboolean button_release(GtkWidget *widget, GdkEventButton *event) { GtkColorWheelPrivate *ns = GET_PRIVATE(widget); #if GTK_MAJOR_VERSION >= 3 if (ns->pointer_grab){ gdk_seat_ungrab(gdk_device_get_seat(ns->pointer_grab)); ns->pointer_grab = nullptr; } #else gdk_pointer_ungrab(GDK_CURRENT_TIME); #endif ns->grab_active = 0; ns->grab_block = false; return false; } gpick-gpick-0.2.6rc1/source/gtk/ColorWheel.h000066400000000000000000000071051315430016700206210ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_GTK_COLOR_WHEEL_H_ #define GPICK_GTK_COLOR_WHEEL_H_ #include #include "../Color.h" #include "../ColorWheelType.h" #define GTK_TYPE_COLOR_WHEEL (gtk_color_wheel_get_type()) #define GTK_COLOR_WHEEL(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), GTK_TYPE_COLOR_WHEEL, GtkColorWheel)) #define GTK_COLOR_WHEEL_CLASS(obj) (G_TYPE_CHECK_CLASS_CAST((obj), GTK_COLOR_WHEEL, GtkColorWheelClass)) #define GTK_IS_COLOR_WHEEL(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), GTK_TYPE_COLOR_WHEEL)) #define GTK_IS_COLOR_WHEEL_CLASS(obj) (G_TYPE_CHECK_CLASS_TYPE((obj), GTK_TYPE_COLOR_WHEEL)) #define GTK_COLOR_WHEEL_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), GTK_TYPE_COLOR_WHEEL, GtkColorWheelClass)) struct GtkColorWheel { GtkDrawingArea parent; }; struct GtkColorWheelClass { GtkDrawingAreaClass parent_class; void (*hue_changed)(GtkWidget *widget, gint color_id, gpointer userdata); void (*saturation_value_changed)(GtkWidget *widget, gint color_id, gpointer userdata); }; GtkWidget* gtk_color_wheel_new(); void gtk_color_wheel_set_value(GtkColorWheel *color_wheel, guint32 index, double value); void gtk_color_wheel_set_hue(GtkColorWheel *color_wheel, guint32 index, double hue); void gtk_color_wheel_set_saturation(GtkColorWheel *color_wheel, guint32 index, double saturation); void gtk_color_wheel_set_selected(GtkColorWheel *color_wheel, guint32 index); double gtk_color_wheel_get_hue(GtkColorWheel *color_wheel, guint32 index); double gtk_color_wheel_get_saturation(GtkColorWheel *color_wheel, guint32 index); double gtk_color_wheel_get_value(GtkColorWheel *color_wheel, guint32 index); void gtk_color_wheel_set_block_editable(GtkColorWheel *color_wheel, bool editable); bool gtk_color_wheel_get_block_editable(GtkColorWheel *color_wheel); int gtk_color_wheel_get_at(GtkColorWheel *color_wheel, int x, int y); void gtk_color_wheel_set_n_colors(GtkColorWheel *color_wheel, guint32 number_of_colors); void gtk_color_wheel_set_color_wheel_type(GtkColorWheel *color_wheel, const ColorWheelType *color_wheel_type); GType gtk_color_wheel_get_type(); #endif /* GPICK_GTK_COLOR_WHEEL_H_ */ gpick-gpick-0.2.6rc1/source/gtk/ColorWidget.cpp000066400000000000000000000265341315430016700213420ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ColorWidget.h" #include "../Color.h" #include "../MathUtil.h" #include #include #include using namespace std; #define GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE((obj), GTK_TYPE_COLOR, GtkColorPrivate)) G_DEFINE_TYPE(GtkColor, gtk_color, GTK_TYPE_DRAWING_AREA); static gboolean button_release(GtkWidget *widget, GdkEventButton *event); static gboolean button_press(GtkWidget *widget, GdkEventButton *event); static void finalize(GObject *color_obj); #if GTK_MAJOR_VERSION >= 3 static gboolean draw(GtkWidget *widget, cairo_t *cr); #else static gboolean expose(GtkWidget *widget, GdkEventExpose *event); static void size_request(GtkWidget *widget, GtkRequisition *requisition); #endif enum { ACTIVATED, LAST_SIGNAL, }; static guint signals[LAST_SIGNAL] = {}; struct GtkColorPrivate { Color color; Color text_color; gchar* text; bool rounded_rectangle; bool h_center; bool secondary_color; double roundness; transformation::Chain *transformation_chain; }; static void gtk_color_class_init(GtkColorClass *color_class) { GObjectClass *obj_class = G_OBJECT_CLASS(color_class); obj_class->finalize = finalize; g_type_class_add_private(obj_class, sizeof(GtkColorPrivate)); GtkWidgetClass *widget_class = GTK_WIDGET_CLASS(color_class); widget_class->button_release_event = button_release; widget_class->button_press_event = button_press; #if GTK_MAJOR_VERSION >= 3 widget_class->draw = draw; #else widget_class->expose_event = expose; widget_class->size_request = size_request; #endif signals[ACTIVATED] = g_signal_new("activated", G_OBJECT_CLASS_TYPE(obj_class), G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET(GtkColorClass, activated), nullptr, nullptr, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); } static void gtk_color_init(GtkColor *color) { gtk_widget_add_events (GTK_WIDGET (color), GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_FOCUS_CHANGE_MASK | GDK_2BUTTON_PRESS | GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK); } GtkWidget* gtk_color_new() { GtkWidget* widget = (GtkWidget*)g_object_new(GTK_TYPE_COLOR, nullptr); GtkColorPrivate *ns = GET_PRIVATE(widget); color_set(&ns->color, 0); ns->text = 0; ns->rounded_rectangle = false; ns->h_center = false; ns->secondary_color = false; ns->roundness = 20; ns->transformation_chain = 0; gtk_widget_set_can_focus(widget, true); return widget; } #if GTK_MAJOR_VERSION < 3 static void size_request(GtkWidget *widget, GtkRequisition *requisition) { GtkColorPrivate *ns = GET_PRIVATE(widget); gint width = 32 + widget->style->xthickness * 2; gint height = 16 + widget->style->ythickness * 2; if (ns->rounded_rectangle){ width += ns->roundness; height += ns->roundness; } requisition->width = width; requisition->height = height; } #endif static void finalize(GObject *color_obj) { GtkColorPrivate *ns = GET_PRIVATE(color_obj); if (ns->text){ g_free(ns->text); ns->text = 0; } gpointer parent_class = g_type_class_peek_parent(G_OBJECT_CLASS(GTK_COLOR_GET_CLASS(color_obj))); G_OBJECT_CLASS(parent_class)->finalize(color_obj); } void gtk_color_get_color(GtkColor* widget, Color* color) { GtkColorPrivate *ns = GET_PRIVATE(widget); color_copy(&ns->color, color); } void gtk_color_set_text_color(GtkColor* widget, Color* color) { GtkColorPrivate *ns = GET_PRIVATE(widget); color_copy(color, &ns->text_color); gtk_widget_queue_draw(GTK_WIDGET(widget)); } void gtk_color_set_roundness(GtkColor* widget, double roundness) { GtkColorPrivate *ns = GET_PRIVATE(widget); ns->roundness = roundness; gint width = 32; gint height = 16; #if GTK_MAJOR_VERSION < 3 width += GTK_WIDGET(widget)->style->xthickness * 2; height += GTK_WIDGET(widget)->style->ythickness * 2; #endif if (ns->rounded_rectangle){ width += ns->roundness; height += ns->roundness; } gtk_widget_set_size_request(GTK_WIDGET(widget), width, height); gtk_widget_queue_draw(GTK_WIDGET(widget)); } void gtk_color_set_color(GtkColor* widget, Color* color, const char* text) { GtkColorPrivate *ns = GET_PRIVATE(widget); color_copy(color, &ns->color); if (ns->secondary_color){ }else{ if (ns->transformation_chain){ Color c; ns->transformation_chain->apply(&ns->color, &c); color_get_contrasting(&c, &ns->text_color); }else{ color_get_contrasting(&ns->color, &ns->text_color); } } if (ns->text) g_free(ns->text); ns->text = 0; if (text) ns->text = g_strdup(text); gtk_widget_queue_draw(GTK_WIDGET(widget)); } void gtk_color_set_rounded(GtkColor* widget, bool rounded_rectangle) { GtkColorPrivate *ns = GET_PRIVATE(widget); ns->rounded_rectangle = rounded_rectangle; gtk_widget_queue_draw(GTK_WIDGET(widget)); } void gtk_color_set_hcenter(GtkColor* widget, bool hcenter) { GtkColorPrivate *ns = GET_PRIVATE(widget); ns->h_center = hcenter; gtk_widget_queue_draw(GTK_WIDGET(widget)); } static void cairo_rounded_rectangle(cairo_t *cr, double x, double y, double width, double height, double roundness) { double strength = 0.3; cairo_move_to(cr, x+roundness, y); cairo_line_to(cr, x+width-roundness, y); cairo_curve_to(cr, x+width-roundness*strength, y, x+width, y+roundness*strength, x+width, y+roundness); cairo_line_to(cr, x+width, y+height-roundness); cairo_curve_to(cr, x+width, y+height-roundness*strength, x+width-roundness*strength, y+height, x+width-roundness, y+height); cairo_line_to(cr, x+roundness, y+height); cairo_curve_to(cr, x+roundness*strength, y+height, x, y+height-roundness*strength, x, y+height-roundness); cairo_line_to(cr, x, y+roundness); cairo_curve_to(cr, x, y+roundness*strength, x+roundness*strength, y, x+roundness, y); cairo_close_path (cr); } static gboolean draw(GtkWidget *widget, cairo_t *cr) { GtkColorPrivate *ns = GET_PRIVATE(widget); Color color; #if GTK_MAJOR_VERSION >= 3 int width = gtk_widget_get_allocated_width(widget), height = gtk_widget_get_allocated_height(widget); #else GtkAllocation rectangle; gtk_widget_get_allocation(widget, &rectangle); int width = rectangle.width - widget->style->xthickness * 2 - 1, height = rectangle.height - widget->style->ythickness * 2 - 1; #endif bool sensitive = gtk_widget_get_sensitive(widget); if (ns->rounded_rectangle){ cairo_rounded_rectangle(cr, 0, 0, width, height, ns->roundness); if (ns->transformation_chain){ ns->transformation_chain->apply(&ns->color, &color); }else{ color_copy(&ns->color, &color); } if (sensitive){ cairo_set_source_rgb(cr, boost::math::round(color.rgb.red * 255.0) / 255.0, boost::math::round(color.rgb.green * 255.0) / 255.0, boost::math::round(color.rgb.blue * 255.0) / 255.0); cairo_fill_preserve(cr); } if (gtk_widget_has_focus(widget)){ #if GTK_MAJOR_VERSION >= 3 //TODO: GTK3 get border color #else cairo_set_source_rgb(cr, widget->style->fg[GTK_STATE_NORMAL].red / 65536.0, widget->style->fg[GTK_STATE_NORMAL].green / 65536.0, widget->style->fg[GTK_STATE_NORMAL].blue / 65536.0); #endif cairo_set_line_width(cr, 3); }else{ cairo_set_source_rgb(cr, 0, 0, 0); cairo_set_line_width(cr, 1); } cairo_stroke(cr); }else{ if (ns->transformation_chain){ ns->transformation_chain->apply(&ns->color, &color); }else{ color_copy(&ns->color, &color); } if (sensitive){ cairo_set_source_rgb(cr, color.rgb.red, color.rgb.green, color.rgb.blue); cairo_paint(cr); } } if (sensitive && ns->text){ PangoLayout *layout; PangoFontDescription *font_description; font_description = pango_font_description_new(); layout = pango_cairo_create_layout(cr); pango_font_description_set_family(font_description, "monospace"); pango_font_description_set_weight(font_description, PANGO_WEIGHT_NORMAL); pango_font_description_set_absolute_size(font_description, 14 * PANGO_SCALE); pango_layout_set_font_description(layout, font_description); pango_layout_set_wrap(layout, PANGO_WRAP_WORD_CHAR); if (ns->transformation_chain){ if (ns->secondary_color){ ns->transformation_chain->apply(&ns->text_color, &color); }else{ color_copy(&ns->text_color, &color); } }else{ color_copy(&ns->text_color, &color); } cairo_set_source_rgb(cr, color.rgb.red, color.rgb.green, color.rgb.blue); pango_layout_set_markup(layout, ns->text, -1); pango_layout_set_width(layout, width * PANGO_SCALE); pango_layout_set_height(layout, height * PANGO_SCALE); int layout_width, layout_height; pango_layout_get_pixel_size(layout, &layout_width, &layout_height); cairo_move_to(cr, 0, (height - layout_height) / 2); if (ns->h_center) pango_layout_set_alignment(layout, PANGO_ALIGN_CENTER); else pango_layout_set_alignment(layout, PANGO_ALIGN_LEFT); pango_cairo_update_layout(cr, layout); pango_cairo_show_layout(cr, layout); g_object_unref(layout); pango_font_description_free(font_description); } return FALSE; } #if GTK_MAJOR_VERSION < 3 static gboolean expose(GtkWidget *widget, GdkEventExpose *event) { cairo_t *cr = gdk_cairo_create(gtk_widget_get_window(widget)); cairo_rectangle(cr, event->area.x, event->area.y, event->area.width, event->area.height); cairo_clip(cr); cairo_translate(cr, widget->style->xthickness + 0.5, widget->style->ythickness + 0.5); gboolean result = draw(widget, cr); cairo_destroy(cr); return result; } #endif static gboolean button_release(GtkWidget *widget, GdkEventButton *event) { gtk_widget_grab_focus(widget); return FALSE; } static gboolean button_press(GtkWidget *widget, GdkEventButton *event) { gtk_widget_grab_focus(widget); if ((event->type == GDK_2BUTTON_PRESS) && (event->button == 1)) { g_signal_emit(widget, signals[ACTIVATED], 0); } return FALSE; } void gtk_color_set_transformation_chain(GtkColor* widget, transformation::Chain *chain) { GtkColorPrivate *ns = GET_PRIVATE(widget); ns->transformation_chain = chain; if (!ns->secondary_color){ if (ns->transformation_chain){ Color c; ns->transformation_chain->apply(&ns->color, &c); color_get_contrasting(&c, &ns->text_color); }else{ color_get_contrasting(&ns->color, &ns->text_color); } } gtk_widget_queue_draw(GTK_WIDGET(widget)); } gpick-gpick-0.2.6rc1/source/gtk/ColorWidget.h000066400000000000000000000055521315430016700210040ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_GTK_COLOR_WIDGET_H_ #define GPICK_GTK_COLOR_WIDGET_H_ #include #include "../Color.h" #include "../transformation/Chain.h" #define GTK_TYPE_COLOR (gtk_color_get_type()) #define GTK_COLOR(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), GTK_TYPE_COLOR, GtkColor)) #define GTK_COLOR_CLASS(obj) (G_TYPE_CHECK_CLASS_CAST((obj), GTK_COLOR, GtkColorClass)) #define GTK_IS_COLOR(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), GTK_TYPE_COLOR)) #define GTK_IS_COLOR_CLASS(obj) (G_TYPE_CHECK_CLASS_TYPE((obj), GTK_TYPE_COLOR)) #define GTK_COLOR_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), GTK_TYPE_COLOR, GtkColorClass)) struct GtkColor { GtkDrawingArea parent; }; struct GtkColorClass { GtkDrawingAreaClass parent_class; void (*activated)(GtkWidget* widget, gpointer userdata); }; GtkWidget* gtk_color_new(); void gtk_color_set_color(GtkColor* widget, Color* color, const char* text); void gtk_color_set_text_color(GtkColor* widget, Color* color); void gtk_color_get_color(GtkColor* widget, Color* color); void gtk_color_set_rounded(GtkColor* widget, bool rounded_rectangle); void gtk_color_set_roundness(GtkColor* widget, double roundness); void gtk_color_set_hcenter(GtkColor* widget, bool hcenter); void gtk_color_set_transformation_chain(GtkColor* widget, transformation::Chain *chain); GType gtk_color_get_type(); #endif /* GPICK_GTK_COLOR_WIDGET_H_ */ gpick-gpick-0.2.6rc1/source/gtk/LayoutPreview.cpp000066400000000000000000000223741315430016700217350ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "LayoutPreview.h" #include "../layout/System.h" #include "../transformation/Chain.h" #include "../Rect2.h" #include #include using namespace std; using namespace math; using namespace layout; #define GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE((obj), GTK_TYPE_LAYOUT_PREVIEW, GtkLayoutPreviewPrivate)) G_DEFINE_TYPE(GtkLayoutPreview, gtk_layout_preview, GTK_TYPE_DRAWING_AREA); static gboolean button_release(GtkWidget *layout_preview, GdkEventButton *event); static gboolean button_press(GtkWidget *layout_preview, GdkEventButton *event); #if GTK_MAJOR_VERSION >= 3 static gboolean draw(GtkWidget *widget, cairo_t *cr); #else static gboolean expose(GtkWidget *layout_preview, GdkEventExpose *event); #endif enum { COLOR_CHANGED, EMPTY, LAST_SIGNAL }; static guint signals[LAST_SIGNAL] = {}; struct GtkLayoutPreviewPrivate { System *system; Rect2 area; Style* selected_style; Box* selected_box; transformation::Chain *transformation_chain; }; static void gtk_layout_preview_class_init(GtkLayoutPreviewClass *klass) { GObjectClass *obj_class = G_OBJECT_CLASS(klass); g_type_class_add_private(obj_class, sizeof(GtkLayoutPreviewPrivate)); GtkWidgetClass *widget_class = GTK_WIDGET_CLASS(klass); widget_class->button_release_event = button_release; widget_class->button_press_event = button_press; #if GTK_MAJOR_VERSION >= 3 widget_class->draw = draw; #else widget_class->expose_event = expose; #endif signals[COLOR_CHANGED] = g_signal_new("color_changed", G_OBJECT_CLASS_TYPE(obj_class), G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET(GtkLayoutPreviewClass, color_changed), nullptr, nullptr, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1, G_TYPE_POINTER); } static void gtk_layout_preview_init(GtkLayoutPreview *layout_preview) { gtk_widget_add_events(GTK_WIDGET(layout_preview), GDK_2BUTTON_PRESS | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_FOCUS_CHANGE_MASK | GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK); } static void destroy(GtkLayoutPreview *widget) { GtkLayoutPreviewPrivate *ns = GET_PRIVATE(widget); if (ns->system) System::unref(ns->system); } GtkWidget* gtk_layout_preview_new() { GtkWidget* widget = (GtkWidget*)g_object_new(GTK_TYPE_LAYOUT_PREVIEW, nullptr); GtkLayoutPreviewPrivate *ns = GET_PRIVATE(widget); ns->area = Rect2(0, 0, 1, 1); ns->selected_style = nullptr; ns->selected_box = nullptr; ns->system = nullptr; ns->transformation_chain = nullptr; g_signal_connect(G_OBJECT(widget), "destroy", G_CALLBACK(destroy), nullptr); gtk_widget_set_can_focus(widget, true); return widget; } static bool set_selected_box(GtkLayoutPreviewPrivate *ns, Box* box) { bool changed = false; if (box && box->style){ if (ns->selected_style) ns->selected_style->SetState(false, 0); ns->selected_style = box->style; ns->selected_style->SetState(true, box); if (ns->selected_box != box) changed=true; ns->selected_box = box; }else{ if (ns->selected_style){ ns->selected_style->SetState(false, 0); changed = true; } ns->selected_style = 0; ns->selected_box = 0; } return changed; } static gboolean draw(GtkWidget *widget, cairo_t *cr) { GtkLayoutPreviewPrivate *ns = GET_PRIVATE(widget); if (ns->system && ns->system->box){ ns->area = Rect2(0, 0, 1, 1); layout::Context context(cr, ns->transformation_chain); ns->system->box->Draw(&context, ns->area); } return true; } #if GTK_MAJOR_VERSION < 3 static gboolean expose(GtkWidget *widget, GdkEventExpose *event) { GtkLayoutPreviewPrivate *ns = GET_PRIVATE(widget); cairo_t *cr = gdk_cairo_create(gtk_widget_get_window(widget)); cairo_rectangle(cr, event->area.x, event->area.y, event->area.width, event->area.height); cairo_clip(cr); gboolean result = draw(widget, cr); cairo_destroy(cr); return result; } #endif static gboolean button_release(GtkWidget *layout_preview, GdkEventButton *event){ return true; } static gboolean button_press(GtkWidget *widget, GdkEventButton *event) { GtkLayoutPreviewPrivate *ns = GET_PRIVATE(widget); if (ns->system){ Vec2 point = Vec2((event->x-ns->area.getX()) / ns->area.getWidth(), (event->y-ns->area.getY()) / ns->area.getHeight()); if (set_selected_box(ns, ns->system->GetBoxAt(point))){ gtk_widget_queue_draw(GTK_WIDGET(widget)); } } return false; } int gtk_layout_preview_set_system(GtkLayoutPreview* widget, System* system) { GtkLayoutPreviewPrivate *ns = GET_PRIVATE(widget); if (ns->system){ System::unref(ns->system); } if (system){ ns->system = static_cast(system->ref()); if (ns->system->box) gtk_widget_set_size_request(GTK_WIDGET(widget), ns->system->box->rect.getWidth(), ns->system->box->rect.getHeight()); }else ns->system = 0; return 0; } int gtk_layout_preview_set_color_at(GtkLayoutPreview* widget, Color* color, gdouble x, gdouble y) { GtkLayoutPreviewPrivate *ns = GET_PRIVATE(widget); if (!ns->system) return -1; Vec2 point = Vec2((x-ns->area.getX()) / ns->area.getWidth(), (y-ns->area.getY()) / ns->area.getHeight()); Box* box = ns->system->GetBoxAt(point); if (box && box->style && !box->locked){ color_copy(color, &box->style->color); gtk_widget_queue_draw(GTK_WIDGET(widget)); return 0; } return -1; } int gtk_layout_preview_set_color_named(GtkLayoutPreview* widget, Color* color, const char *name) { GtkLayoutPreviewPrivate *ns = GET_PRIVATE(widget); if (!ns->system) return -1; Box* box = ns->system->GetNamedBox(name); if (box && box->style && !box->locked){ color_copy(color, &box->style->color); gtk_widget_queue_draw(GTK_WIDGET(widget)); return 0; } return -1; } int gtk_layout_preview_set_focus_named(GtkLayoutPreview* widget, const char *name) { GtkLayoutPreviewPrivate *ns = GET_PRIVATE(widget); if (!ns->system) return -1; Box* box; if (set_selected_box(ns, box = ns->system->GetNamedBox(name))){ gtk_widget_queue_draw(GTK_WIDGET(widget)); return (box)?(0):(-1); } return -1; } int gtk_layout_preview_set_focus_at(GtkLayoutPreview* widget, gdouble x, gdouble y) { GtkLayoutPreviewPrivate *ns = GET_PRIVATE(widget); if (!ns->system) return -1; Vec2 point = Vec2((x-ns->area.getX()) / ns->area.getWidth(), (y-ns->area.getY()) / ns->area.getHeight()); Box* box; if (set_selected_box(ns, box = ns->system->GetBoxAt(point))){ gtk_widget_queue_draw(GTK_WIDGET(widget)); return (box)?(0):(-1); } return -1; } int gtk_layout_preview_get_current_style(GtkLayoutPreview* widget, Style** style) { GtkLayoutPreviewPrivate *ns = GET_PRIVATE(widget); if (ns->system && ns->selected_style){ *style = ns->selected_style; return 0; } return -1; } int gtk_layout_preview_get_current_color(GtkLayoutPreview* widget, Color* color) { GtkLayoutPreviewPrivate *ns = GET_PRIVATE(widget); if (ns->system && ns->selected_style){ Box* box = ns->selected_box; color_copy(&box->style->color, color); return 0; } return -1; } int gtk_layout_preview_set_current_color(GtkLayoutPreview* widget, Color* color) { GtkLayoutPreviewPrivate *ns = GET_PRIVATE(widget); if (ns->system && ns->selected_style && !ns->selected_box->locked){ Box* box = ns->selected_box; color_copy(color, &box->style->color); gtk_widget_queue_draw(GTK_WIDGET(widget)); return 0; } return -1; } bool gtk_layout_preview_is_selected(GtkLayoutPreview* widget) { GtkLayoutPreviewPrivate *ns = GET_PRIVATE(widget); if (ns->system && ns->selected_style && ns->selected_box){ return true; } return false; } bool gtk_layout_preview_is_editable(GtkLayoutPreview* widget) { GtkLayoutPreviewPrivate *ns = GET_PRIVATE(widget); if (ns->system && ns->selected_style && ns->selected_box){ return !ns->selected_box->locked; } return false; } void gtk_layout_preview_set_transformation_chain(GtkLayoutPreview* widget, transformation::Chain *chain) { GtkLayoutPreviewPrivate *ns = GET_PRIVATE(widget); ns->transformation_chain = chain; gtk_widget_queue_draw(GTK_WIDGET(widget)); } gpick-gpick-0.2.6rc1/source/gtk/LayoutPreview.h000066400000000000000000000072431315430016700214000ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_GTK_LAYOUT_PREVIEW_H_ #define GPICK_GTK_LAYOUT_PREVIEW_H_ #include #include "../ColorObject.h" #include "../layout/System.h" #include "../transformation/Chain.h" #define GTK_TYPE_LAYOUT_PREVIEW (gtk_layout_preview_get_type()) #define GTK_LAYOUT_PREVIEW(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), GTK_TYPE_LAYOUT_PREVIEW, GtkLayoutPreview)) #define GTK_LAYOUT_PREVIEW_CLASS(obj) (G_TYPE_CHECK_CLASS_CAST((obj), GTK_LAYOUT_PREVIEW, GtkLayoutPreviewClass)) #define GTK_IS_LAYOUT_PREVIEW(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), GTK_TYPE_LAYOUT_PREVIEW)) #define GTK_IS_LAYOUT_PREVIEW_CLASS(obj) (G_TYPE_CHECK_CLASS_TYPE((obj), GTK_TYPE_LAYOUT_PREVIEW)) #define GTK_LAYOUT_PREVIEW_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), GTK_TYPE_LAYOUT_PREVIEW, GtkLayoutPreviewClass)) struct GtkLayoutPreview { GtkDrawingArea parent; }; struct GtkLayoutPreviewClass { GtkDrawingAreaClass parent_class; void (* active_color_changed)(GtkWidget* widget, gint32 active_color, gpointer userdata); void (* color_changed)(GtkWidget* widget, gpointer userdata); void (* color_activated)(GtkWidget* widget, gpointer userdata); }; GtkWidget* gtk_layout_preview_new(); GType gtk_layout_preview_get_type(); int gtk_layout_preview_set_system(GtkLayoutPreview* widget, layout::System* system); int gtk_layout_preview_set_color_at(GtkLayoutPreview* widget, Color* color, gdouble x, gdouble y); int gtk_layout_preview_set_focus_at(GtkLayoutPreview* widget, gdouble x, gdouble y); int gtk_layout_preview_set_focus_named(GtkLayoutPreview* widget, const char *name); int gtk_layout_preview_set_color_named(GtkLayoutPreview* widget, Color* color, const char *name); int gtk_layout_preview_get_current_color(GtkLayoutPreview* widget, Color* color); int gtk_layout_preview_set_current_color(GtkLayoutPreview* widget, Color* color); bool gtk_layout_preview_is_selected(GtkLayoutPreview* widget); bool gtk_layout_preview_is_editable(GtkLayoutPreview* widget); int gtk_layout_preview_get_current_style(GtkLayoutPreview* widget, layout::Style** style); void gtk_layout_preview_set_transformation_chain(GtkLayoutPreview* widget, transformation::Chain *chain); #endif /* GPICK_GTK_LAYOUT_PREVIEW_H_ */ gpick-gpick-0.2.6rc1/source/gtk/Range2D.cpp000066400000000000000000000267071315430016700203440ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Range2D.h" #include "../Color.h" #include "../MathUtil.h" #include #ifdef _MSC_VER #define M_PI 3.14159265359 #endif #include using namespace std; #define GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GTK_TYPE_RANGE_2D, GtkRange2DPrivate)) G_DEFINE_TYPE (GtkRange2D, gtk_range_2d, GTK_TYPE_DRAWING_AREA); static gboolean button_release(GtkWidget *range_2d, GdkEventButton *event); static gboolean button_press(GtkWidget *range_2d, GdkEventButton *event); static gboolean motion_notify(GtkWidget *widget, GdkEventMotion *event); #if GTK_MAJOR_VERSION >= 3 static gboolean draw(GtkWidget *widget, cairo_t *cr); #else static gboolean expose(GtkWidget *range_2d, GdkEventExpose *event); #endif enum { VALUES_CHANGED, LAST_SIGNAL }; static guint signals[LAST_SIGNAL] = {}; struct GtkRange2DPrivate { double x; double y; char *xname; char *yname; double block_size; bool grab_block; cairo_surface_t *cache_range_2d; #if GTK_MAJOR_VERSION >= 3 GdkDevice *pointer_grab; #endif }; static void finalize(GObject *range_2d_obj) { GtkRange2DPrivate *ns = GET_PRIVATE(range_2d_obj); if (ns->xname) g_free(ns->xname); if (ns->yname) g_free(ns->yname); if (ns->cache_range_2d){ cairo_surface_destroy(ns->cache_range_2d); ns->cache_range_2d = 0; } gpointer parent_class = g_type_class_peek_parent(G_OBJECT_CLASS(GTK_RANGE_2D_GET_CLASS(range_2d_obj))); G_OBJECT_CLASS(parent_class)->finalize(range_2d_obj); } static void gtk_range_2d_class_init(GtkRange2DClass *range_2d_class) { GObjectClass *obj_class = G_OBJECT_CLASS(range_2d_class); obj_class->finalize = finalize; g_type_class_add_private(obj_class, sizeof(GtkRange2DPrivate)); GtkWidgetClass *widget_class = GTK_WIDGET_CLASS(range_2d_class); widget_class->button_release_event = button_release; widget_class->button_press_event = button_press; widget_class->motion_notify_event = motion_notify; #if GTK_MAJOR_VERSION >= 3 widget_class->draw = draw; #else widget_class->expose_event = expose; #endif signals[VALUES_CHANGED] = g_signal_new("values_changed", G_OBJECT_CLASS_TYPE(obj_class), G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET(GtkRange2DClass, values_changed), nullptr, nullptr, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); } static void gtk_range_2d_init(GtkRange2D *range_2d) { gtk_widget_add_events(GTK_WIDGET(range_2d), GDK_2BUTTON_PRESS | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_FOCUS_CHANGE_MASK | GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK); } GtkWidget* gtk_range_2d_new() { GtkWidget* widget = (GtkWidget*) g_object_new(GTK_TYPE_RANGE_2D, nullptr); GtkRange2DPrivate *ns = GET_PRIVATE(widget); ns->block_size = 128; ns->grab_block = false; ns->xname = 0; ns->yname = 0; #if GTK_MAJOR_VERSION >= 3 gtk_widget_set_size_request(GTK_WIDGET(widget), ns->block_size, ns->block_size); #else gtk_widget_set_size_request(GTK_WIDGET(widget), ns->block_size + widget->style->xthickness * 2, ns->block_size + widget->style->ythickness * 2); #endif ns->cache_range_2d = 0; #if GTK_MAJOR_VERSION >= 3 ns->pointer_grab = nullptr; #endif gtk_widget_set_can_focus(widget, true); return widget; } void gtk_range_2d_set_values(GtkRange2D* range_2d, double x, double y) { GtkRange2DPrivate *ns = GET_PRIVATE(range_2d); ns->x = x; ns->y = 1 - y; gtk_widget_queue_draw(GTK_WIDGET(range_2d)); } double gtk_range_2d_get_x(GtkRange2D* range_2d) { GtkRange2DPrivate *ns = GET_PRIVATE(range_2d); return ns->x; } double gtk_range_2d_get_y(GtkRange2D* range_2d) { GtkRange2DPrivate *ns = GET_PRIVATE(range_2d); return 1 - ns->y; } static void draw_dot(cairo_t *cr, double x, double y, double size) { cairo_arc(cr, x, y, size - 1, 0, 2 * M_PI); cairo_set_source_rgba(cr, 1, 1, 1, 0.5); cairo_set_line_width(cr, 2); cairo_stroke(cr); cairo_arc(cr, x, y, size, 0, 2 * M_PI); cairo_set_source_rgba(cr, 0, 0, 0, 1); cairo_set_line_width(cr, 1); cairo_stroke(cr); } static void draw_sat_val_block(GtkRange2DPrivate *ns, cairo_t *cr, double pos_x, double pos_y, double size) { cairo_surface_t *surface; if (ns->cache_range_2d){ surface = ns->cache_range_2d; }else{ surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, ceil(size), ceil(size)); unsigned char *data = cairo_image_surface_get_data(surface); int stride = cairo_image_surface_get_stride(surface); int surface_width = cairo_image_surface_get_width(surface); int surface_height = cairo_image_surface_get_height(surface); float v; unsigned char *line_data; for (int y = 0; y < surface_height; ++y){ line_data = data + stride * y; for (int x = 0; x < surface_width; ++x){ if ((x % 16 < 8) ^ (y % 16 < 8) ){ v = mix_float(0.5, 1.0, pow(x / size, 2)); }else{ v = mix_float(0.5, 0.0, pow(1 - (y / size), 2)); } line_data[2] = v * 255; line_data[1] = v / 2 * 255; line_data[0] = v / 4 * 255; line_data[3] = 0xFF; line_data += 4; } } ns->cache_range_2d = surface; } cairo_surface_mark_dirty(surface); cairo_save(cr); cairo_set_source_surface(cr, surface, pos_x, pos_y); cairo_rectangle(cr, pos_x, pos_y, size, size); cairo_fill(cr); cairo_restore(cr); } static gboolean motion_notify(GtkWidget *widget, GdkEventMotion *event) { GtkRange2DPrivate *ns = GET_PRIVATE(widget); if (ns->grab_block){ #if GTK_MAJOR_VERSION >= 3 double dx = event->x; double dy = event->y; #else double dx = (event->x - widget->style->xthickness); double dy = (event->y - widget->style->ythickness); #endif ns->x = clamp_float(dx / ns->block_size, 0, 1); ns->y = clamp_float(dy / ns->block_size, 0, 1); g_signal_emit(widget, signals[VALUES_CHANGED], 0); gtk_widget_queue_draw(widget); return true; } return false; } static gboolean draw(GtkWidget *widget, cairo_t *cr) { GtkRange2DPrivate *ns = GET_PRIVATE(widget); draw_sat_val_block(ns, cr, 0, 0, ns->block_size); draw_dot(cr, ns->block_size * ns->x, ns->block_size * ns->y, 6); if (ns->xname){ PangoLayout *layout; PangoFontDescription *font_description; font_description = pango_font_description_new(); layout = pango_cairo_create_layout(cr); pango_font_description_set_family(font_description, "monospace"); pango_font_description_set_weight(font_description, PANGO_WEIGHT_NORMAL); pango_font_description_set_absolute_size(font_description, 12 * PANGO_SCALE); pango_layout_set_font_description(layout, font_description); pango_layout_set_wrap(layout, PANGO_WRAP_WORD_CHAR); cairo_set_source_rgb(cr, 1, 1, 1); pango_layout_set_text(layout, ns->xname, -1); #if GTK_MAJOR_VERSION >= 3 int width = gtk_widget_get_allocated_width(widget), height = gtk_widget_get_allocated_height(widget); int padding_x = 0, padding_y = 0; #else int width = widget->allocation.width, height = widget->allocation.height; int padding_x = widget->style->xthickness, padding_y = widget->style->ythickness; #endif pango_layout_set_width(layout, (width - padding_x * 2) * PANGO_SCALE); pango_layout_set_height(layout, (height - padding_y * 2) * PANGO_SCALE); pango_layout_set_alignment(layout, PANGO_ALIGN_CENTER); pango_cairo_update_layout(cr, layout); int layout_width, layout_height; pango_layout_get_pixel_size(layout, &layout_width, &layout_height); cairo_move_to(cr, 0, ns->block_size - layout_height - 1); pango_cairo_show_layout(cr, layout); PangoContext *context = pango_layout_get_context(layout); pango_context_set_gravity_hint(context, PANGO_GRAVITY_HINT_STRONG); pango_context_set_base_gravity(context, PANGO_GRAVITY_NORTH); pango_layout_context_changed(layout); pango_layout_set_text(layout, ns->yname, -1); pango_layout_get_pixel_size(layout, &layout_width, &layout_height); cairo_move_to(cr, layout_height + 1, 0); cairo_rotate(cr, 90 / (180.0 / M_PI)); pango_cairo_update_layout(cr, layout); pango_cairo_show_layout(cr, layout); g_object_unref(layout); pango_font_description_free(font_description); } return false; } #if GTK_MAJOR_VERSION < 3 static gboolean expose(GtkWidget *widget, GdkEventExpose *event) { cairo_t *cr = gdk_cairo_create(gtk_widget_get_window(widget)); cairo_rectangle(cr, event->area.x, event->area.y, event->area.width, event->area.height); cairo_clip(cr); cairo_translate(cr, widget->style->xthickness, widget->style->ythickness); gboolean result = draw(widget, cr); cairo_destroy(cr); return result; } #endif static gboolean button_press(GtkWidget *widget, GdkEventButton *event) { GtkRange2DPrivate *ns = GET_PRIVATE(widget); gtk_widget_grab_focus(widget); if ((event->type == GDK_BUTTON_PRESS) && (event->button == 1)){ ns->grab_block = true; GdkCursor *cursor = gdk_cursor_new_for_display(gtk_widget_get_display(widget), GDK_CROSS); #if GTK_MAJOR_VERSION >= 3 ns->pointer_grab = event->device; gdk_seat_grab(gdk_device_get_seat(event->device), gtk_widget_get_window(widget), GDK_SEAT_CAPABILITY_ALL, false, cursor, nullptr, nullptr, nullptr); #else gdk_pointer_grab(gtk_widget_get_window(widget), false, GdkEventMask(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK), nullptr, cursor, GDK_CURRENT_TIME); #endif #if GTK_MAJOR_VERSION >= 3 g_object_unref(cursor); double dx = event->x; double dy = event->y; #else gdk_cursor_unref(cursor); double dx = (event->x - widget->style->xthickness); double dy = (event->y - widget->style->ythickness); #endif ns->x = clamp_float(dx / ns->block_size, 0, 1); ns->y = clamp_float(dy / ns->block_size, 0, 1); g_signal_emit(widget, signals[VALUES_CHANGED], 0); gtk_widget_queue_draw(widget); return true; } return false; } static gboolean button_release(GtkWidget *widget, GdkEventButton *event) { GtkRange2DPrivate *ns = GET_PRIVATE(widget); #if GTK_MAJOR_VERSION >= 3 if (ns->pointer_grab){ gdk_seat_ungrab(gdk_device_get_seat(ns->pointer_grab)); ns->pointer_grab = nullptr; } #else gdk_pointer_ungrab(GDK_CURRENT_TIME); #endif ns->grab_block = false; return false; } void gtk_range_2d_set_axis(GtkRange2D *range_2d, const char *x, const char *y) { GtkRange2DPrivate *ns = GET_PRIVATE(range_2d); if (ns->xname) g_free(ns->xname); ns->xname = g_strdup(x); if (ns->yname) g_free(ns->yname); ns->yname = g_strdup(y); gtk_widget_queue_draw(GTK_WIDGET(range_2d)); } gpick-gpick-0.2.6rc1/source/gtk/Range2D.h000066400000000000000000000051711315430016700200010ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_GTK_RANGE_2D_H_ #define GPICK_GTK_RANGE_2D_H_ #include #define GTK_TYPE_RANGE_2D (gtk_range_2d_get_type ()) #define GTK_RANGE_2D(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), GTK_TYPE_RANGE_2D, GtkRange2D)) #define GTK_RANGE_2D_CLASS(obj) (G_TYPE_CHECK_CLASS_CAST ((obj), GTK_RANGE_2D, GtkRange2DClass)) #define GTK_IS_RANGE_2D(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GTK_TYPE_RANGE_2D)) #define GTK_IS_RANGE_2D_CLASS(obj) (G_TYPE_CHECK_CLASS_TYPE ((obj), GTK_TYPE_RANGE_2D)) #define GTK_RANGE_2D_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), GTK_TYPE_RANGE_2D, GtkRange2DClass)) struct GtkRange2D { GtkDrawingArea parent; }; struct GtkRange2DClass { GtkDrawingAreaClass parent_class; void (*values_changed)(GtkWidget *widget, gpointer userdata); }; GtkWidget* gtk_range_2d_new(); void gtk_range_2d_set_values(GtkRange2D *range_2d, double x, double y); void gtk_range_2d_set_axis(GtkRange2D *range_2d, const char *x, const char *y); double gtk_range_2d_get_x(GtkRange2D *range_2d); double gtk_range_2d_get_y(GtkRange2D *range_2d); GType gtk_range_2d_get_type(); #endif /* GPICK_GTK_RANGE_2D_H_ */ gpick-gpick-0.2.6rc1/source/gtk/SConscript000066400000000000000000000006041315430016700204140ustar00rootroot00000000000000#!/usr/bin/env python import os import sys Import('*') local_env = env.Clone() if not local_env.GetOption('clean') and not env['TOOLCHAIN'] == 'msvc': local_env.ParseConfig('pkg-config --cflags --libs $GTK_PC') local_env.ParseConfig('pkg-config --cflags --libs $LUA_PC') sources = local_env.Glob('*.cpp') objects = local_env.StaticObject( source = [sources]) Return('objects') gpick-gpick-0.2.6rc1/source/gtk/Swatch.cpp000066400000000000000000000343711315430016700203470ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Swatch.h" #include "../Color.h" #include "../MathUtil.h" #include #include #define GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE((obj), GTK_TYPE_SWATCH, GtkSwatchPrivate)) G_DEFINE_TYPE (GtkSwatch, gtk_swatch, GTK_TYPE_DRAWING_AREA); static gboolean button_release(GtkWidget *swatch, GdkEventButton *event); static gboolean button_press(GtkWidget *swatch, GdkEventButton *event); #if GTK_MAJOR_VERSION >= 3 static gboolean draw(GtkWidget *widget, cairo_t *cr); #else static gboolean expose(GtkWidget *widget, GdkEventExpose *event); #endif enum { ACTIVE_COLOR_CHANGED, COLOR_CHANGED, COLOR_ACTIVATED, CENTER_ACTIVATED, LAST_SIGNAL }; static guint signals[LAST_SIGNAL] = {}; struct GtkSwatchPrivate { Color color[7]; gint32 current_color; gboolean active; transformation::Chain *transformation_chain; #if GTK_MAJOR_VERSION >= 3 GtkStyleContext *context; #endif }; static void finalize(GObject *obj) { GtkSwatchPrivate *ns = GET_PRIVATE(obj); #if GTK_MAJOR_VERSION >= 3 g_object_unref(ns->context); #endif G_OBJECT_CLASS(g_type_class_peek_parent(G_OBJECT_CLASS(GTK_SWATCH_GET_CLASS(obj))))->finalize(obj); } static void gtk_swatch_class_init(GtkSwatchClass *swatch_class) { GObjectClass *obj_class = G_OBJECT_CLASS(swatch_class); obj_class->finalize = finalize; g_type_class_add_private(obj_class, sizeof(GtkSwatchPrivate)); GtkWidgetClass *widget_class = GTK_WIDGET_CLASS(swatch_class); widget_class->button_release_event = button_release; widget_class->button_press_event = button_press; #if GTK_MAJOR_VERSION >= 3 widget_class->draw = draw; #else widget_class->expose_event = expose; #endif signals[ACTIVE_COLOR_CHANGED] = g_signal_new("active_color_changed", G_OBJECT_CLASS_TYPE(obj_class), G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET(GtkSwatchClass, active_color_changed), nullptr, nullptr, g_cclosure_marshal_VOID__INT, G_TYPE_NONE, 1, G_TYPE_INT); signals[COLOR_CHANGED] = g_signal_new("color_changed", G_OBJECT_CLASS_TYPE(obj_class), G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET(GtkSwatchClass, color_changed), nullptr, nullptr, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); signals[COLOR_ACTIVATED] = g_signal_new("color_activated", G_OBJECT_CLASS_TYPE(obj_class), G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET(GtkSwatchClass, color_activated), nullptr, nullptr, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); signals[CENTER_ACTIVATED] = g_signal_new("center_activated", G_OBJECT_CLASS_TYPE(obj_class), G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET(GtkSwatchClass, center_activated), nullptr, nullptr, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); } #if GTK_MAJOR_VERSION >= 3 static GtkStyleContext* get_style_context(GType type) { GtkWidgetPath* path = gtk_widget_path_new(); gtk_widget_path_append_type(path, type); GtkStyleContext *context = gtk_style_context_new(); gtk_style_context_set_path(context, path); gtk_widget_path_free(path); return context; } #endif static void gtk_swatch_init(GtkSwatch *swatch) { gtk_widget_add_events(GTK_WIDGET(swatch), GDK_2BUTTON_PRESS | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_FOCUS_CHANGE_MASK | GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK); } GtkWidget* gtk_swatch_new() { GtkWidget* widget = (GtkWidget*)g_object_new(GTK_TYPE_SWATCH, nullptr); GtkSwatchPrivate *ns = GET_PRIVATE(widget); #if GTK_MAJOR_VERSION >= 3 gtk_widget_set_size_request(GTK_WIDGET(widget), 150, 136); #else gtk_widget_set_size_request(GTK_WIDGET(widget), 150 + widget->style->xthickness * 2, 136 + widget->style->ythickness * 2); #endif for (gint32 i = 0; i < 7; ++i) color_set(&ns->color[i], i / 7.0); ns->current_color = 1; ns->transformation_chain = 0; ns->active = false; #if GTK_MAJOR_VERSION >= 3 ns->context = get_style_context(GTK_TYPE_SWATCH); #endif gtk_widget_set_can_focus(widget, true); return widget; } void gtk_swatch_set_color_to_main(GtkSwatch* swatch) { GtkSwatchPrivate *ns = GET_PRIVATE(swatch); color_copy(&ns->color[0], &ns->color[ns->current_color]); gtk_widget_queue_draw(GTK_WIDGET(swatch)); } void gtk_swatch_move_active(GtkSwatch* swatch, gint32 direction) { GtkSwatchPrivate *ns = GET_PRIVATE(swatch); if (direction < 0){ if (ns->current_color == 1){ ns->current_color = 7 - 1; }else{ ns->current_color--; } }else{ ns->current_color++; if (ns->current_color >= 7) ns->current_color = 1; } } void gtk_swatch_get_color(GtkSwatch* swatch, guint32 index, Color* color) { GtkSwatchPrivate *ns = GET_PRIVATE(swatch); color_copy(&ns->color[index], color); } void gtk_swatch_get_main_color(GtkSwatch* swatch, Color* color) { GtkSwatchPrivate *ns = GET_PRIVATE(swatch); color_copy(&ns->color[0], color); } gint32 gtk_swatch_get_active_index(GtkSwatch* swatch) { GtkSwatchPrivate *ns = GET_PRIVATE(swatch); return ns->current_color; } void gtk_swatch_get_active_color(GtkSwatch* swatch, Color* color) { GtkSwatchPrivate *ns = GET_PRIVATE(swatch); color_copy(&ns->color[ns->current_color], color); } void gtk_swatch_set_color(GtkSwatch* swatch, guint32 index, Color* color) { GtkSwatchPrivate *ns = GET_PRIVATE(swatch); color_copy(color, &ns->color[index]); gtk_widget_queue_draw(GTK_WIDGET(swatch)); } void gtk_swatch_set_main_color(GtkSwatch* swatch, Color* color) { GtkSwatchPrivate *ns = GET_PRIVATE(swatch); color_copy(color, &ns->color[0]); gtk_widget_queue_draw(GTK_WIDGET(swatch)); } void gtk_swatch_set_active_index(GtkSwatch* swatch, guint32 index) { GtkSwatchPrivate *ns = GET_PRIVATE(swatch); ns->current_color = index; gtk_widget_queue_draw(GTK_WIDGET(swatch)); } void gtk_swatch_set_active_color(GtkSwatch* swatch, Color* color) { GtkSwatchPrivate *ns = GET_PRIVATE(swatch); color_copy(color, &ns->color[ns->current_color]); gtk_widget_queue_draw(GTK_WIDGET(swatch)); } void gtk_swatch_set_main_color(GtkSwatch* swatch, guint index, Color* color) { GtkSwatchPrivate *ns = GET_PRIVATE(swatch); color_copy(color, &ns->color[0]); gtk_widget_queue_draw(GTK_WIDGET(swatch)); } static int get_color_by_position(gint x, gint y) { vector2 a, b; vector2_set(&a, 1, 0); vector2_set(&b, x - 75, y - (75 - 7)); float distance = vector2_length(&b); if (distance < 20){ //center color return 0; }else if (distance > 70){ //outside return -1; }else{ vector2_normalize(&b, &b); float angle = acos(vector2_dot(&a, &b)); if (b.y < 0) angle = 2 * PI - angle; angle += (PI / 6) * 3; if (angle < 0) angle += PI * 2; if (angle > 2 * PI) angle -= PI * 2; return 1 + (int)floor(angle / ((PI * 2) / 6)); } } gint gtk_swatch_get_color_at(GtkSwatch* swatch, gint x, gint y) { #if GTK_MAJOR_VERSION >= 3 return get_color_by_position(x, y); #else return get_color_by_position(x - GTK_WIDGET(swatch)->style->xthickness, y - GTK_WIDGET(swatch)->style->ythickness); #endif } static void draw_hexagon(cairo_t *cr, float x, float y, float radius) { cairo_new_sub_path(cr); for (int i = 0; i < 6; ++i) { cairo_line_to(cr, x + sin(i * PI / 3) * radius, y + cos(i * PI / 3) * radius); } cairo_close_path(cr); } static gboolean draw(GtkWidget *widget, cairo_t *cr) { GtkSwatchPrivate *ns = GET_PRIVATE(widget); if (gtk_widget_has_focus(widget) || ns->active){ #if GTK_MAJOR_VERSION >= 3 gtk_render_focus(ns->context, cr, 0, 0, 150, 136); #else gtk_paint_focus(widget->style, widget->window, GTK_STATE_ACTIVE, nullptr, widget, 0, widget->style->xthickness, widget->style->ythickness, 150, 136); #endif cairo_set_source_rgba(cr, 0, 0, 0, 0.5); cairo_arc(cr, 150 - 11.5, 12.5, 6, 0, 2 * PI); cairo_fill(cr); cairo_set_source_rgb(cr, 1, 0, 0); cairo_arc(cr, 150 - 12, 12, 6, 0, 2 * PI); cairo_fill(cr); } cairo_select_font_face(cr, "monospace", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL); cairo_set_font_size(cr, 12); cairo_matrix_t matrix; cairo_get_matrix(cr, &matrix); #if GTK_MAJOR_VERSION >= 3 int padding_x = 0, padding_y = 0; #else int padding_x = widget->style->xthickness, padding_y = widget->style->ythickness; #endif cairo_translate(cr, 75 + padding_x, 75 + padding_y - 7); int edges = 6; cairo_set_source_rgb(cr, 0, 0, 0); float radius_multi = 50 * cos((180 / edges) / (180 / PI)); float rotation = -(PI/6 * 4); //Draw stroke cairo_set_source_rgb(cr, 0, 0, 0); cairo_set_line_width(cr, 3); for (int i = 1; i < 7; ++i) { if (i == ns->current_color) continue; draw_hexagon(cr, radius_multi * cos(rotation + i * (2 * PI) / edges), radius_multi * sin(rotation + i * (2 * PI) / edges), 27); } cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND); cairo_stroke(cr); cairo_set_source_rgb(cr, 1, 1, 1); draw_hexagon(cr, radius_multi * cos(rotation + (ns->current_color) * (2 * PI) / edges), radius_multi * sin(rotation + (ns->current_color) * (2 * PI) / edges), 27); cairo_stroke(cr); Color color; //Draw fill for (int i = 1; i < 7; ++i) { if (i == ns->current_color) continue; if (ns->transformation_chain){ ns->transformation_chain->apply(&ns->color[i], &color); }else{ color_copy(&ns->color[i], &color); } cairo_set_source_rgb(cr, boost::math::round(color.rgb.red * 255.0) / 255.0, boost::math::round(color.rgb.green * 255.0) / 255.0, boost::math::round(color.rgb.blue * 255.0) / 255.0); draw_hexagon(cr, radius_multi * cos(rotation + i * (2 * PI) / edges), radius_multi * sin(rotation + i * (2 * PI) / edges), 25.5); cairo_fill(cr); } if (ns->transformation_chain){ ns->transformation_chain->apply(&ns->color[ns->current_color], &color); }else{ color_copy(&ns->color[ns->current_color], &color); } cairo_set_source_rgb(cr, boost::math::round(color.rgb.red * 255.0) / 255.0, boost::math::round(color.rgb.green * 255.0) / 255.0, boost::math::round(color.rgb.blue * 255.0) / 255.0); draw_hexagon(cr, radius_multi * cos(rotation + (ns->current_color) * (2 * PI) / edges), radius_multi * sin(rotation + (ns->current_color) * (2 * PI) / edges), 25.5); cairo_fill(cr); //Draw center if (ns->transformation_chain){ ns->transformation_chain->apply(&ns->color[0], &color); }else{ color_copy(&ns->color[0], &color); } cairo_set_source_rgb(cr, boost::math::round(color.rgb.red * 255.0) / 255.0, boost::math::round(color.rgb.green * 255.0) / 255.0, boost::math::round(color.rgb.blue * 255.0) / 255.0); draw_hexagon(cr, 0, 0, 25.5); cairo_fill(cr); //Draw numbers char numb[2] = " "; for (int i = 1; i < 7; ++i) { Color c; if (ns->transformation_chain){ Color t; ns->transformation_chain->apply(&ns->color[i], &t); color_get_contrasting(&t, &c); }else{ color_get_contrasting(&ns->color[i], &c); } cairo_text_extents_t extends; numb[0] = '0' + i; cairo_text_extents(cr, numb, &extends); cairo_set_source_rgb(cr, boost::math::round(c.rgb.red * 255.0) / 255.0, boost::math::round(c.rgb.green * 255.0) / 255.0, boost::math::round(c.rgb.blue * 255.0) / 255.0); cairo_move_to(cr, radius_multi * cos(rotation + i * (2 * PI) / edges) - extends.width / 2, radius_multi * sin(rotation + i * (2 * PI) / edges) + extends.height / 2); cairo_show_text(cr, numb); } cairo_set_matrix(cr, &matrix); return true; } #if GTK_MAJOR_VERSION < 3 static gboolean expose(GtkWidget *widget, GdkEventExpose *event) { cairo_t *cr = gdk_cairo_create(gtk_widget_get_window(widget)); cairo_rectangle(cr, event->area.x, event->area.y, event->area.width, event->area.height); cairo_clip(cr); cairo_translate(cr, widget->style->xthickness + 0.5, widget->style->ythickness + 0.5); gboolean result = draw(widget, cr); cairo_destroy(cr); return result; } #endif static void offset_xy(GtkWidget *widget, gint &x, gint &y) { #if GTK_MAJOR_VERSION < 3 x = x - widget->style->xthickness; y = y - widget->style->ythickness; #endif } static gboolean button_press(GtkWidget *widget, GdkEventButton *event) { GtkSwatchPrivate *ns = GET_PRIVATE(widget); int x = event->x, y = event->y; offset_xy(widget, x, y); int new_color = get_color_by_position(x, y); gtk_widget_grab_focus(widget); if ((event->type == GDK_2BUTTON_PRESS) && (event->button == 1)) { if (new_color>0){ g_signal_emit(widget, signals[COLOR_ACTIVATED], 0); } }else if ((event->type == GDK_BUTTON_PRESS) && ((event->button == 1) || (event->button == 3))) { if (new_color == 0){ g_signal_emit(widget, signals[CENTER_ACTIVATED], 0); }else if (new_color<0){ g_signal_emit(widget, signals[ACTIVE_COLOR_CHANGED], 0, ns->current_color); }else{ if (new_color != ns->current_color){ ns->current_color = new_color; g_signal_emit(widget, signals[ACTIVE_COLOR_CHANGED], 0, ns->current_color); gtk_widget_queue_draw(GTK_WIDGET(widget)); } } } return FALSE; } static gboolean button_release(GtkWidget *widget, GdkEventButton *event) { return FALSE; } void gtk_swatch_set_transformation_chain(GtkSwatch* widget, transformation::Chain *chain){ GtkSwatchPrivate *ns = GET_PRIVATE(widget); ns->transformation_chain = chain; gtk_widget_queue_draw(GTK_WIDGET(widget)); } void gtk_swatch_set_active(GtkSwatch* widget, gboolean active) { GtkSwatchPrivate *ns = GET_PRIVATE(widget); ns->active = active; gtk_widget_queue_draw(GTK_WIDGET(widget)); } gpick-gpick-0.2.6rc1/source/gtk/Swatch.h000066400000000000000000000070261315430016700200110ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_GTK_SWATCH_H_ #define GPICK_GTK_SWATCH_H_ #include #include "../Color.h" #include "../transformation/Chain.h" #define GTK_TYPE_SWATCH (gtk_swatch_get_type()) #define GTK_SWATCH(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), GTK_TYPE_SWATCH, GtkSwatch)) #define GTK_SWATCH_CLASS(obj) (G_TYPE_CHECK_CLASS_CAST((obj), GTK_SWATCH, GtkSwatchClass)) #define GTK_IS_SWATCH(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), GTK_TYPE_SWATCH)) #define GTK_IS_SWATCH_CLASS(obj) (G_TYPE_CHECK_CLASS_TYPE((obj), GTK_TYPE_SWATCH)) #define GTK_SWATCH_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), GTK_TYPE_SWATCH, GtkSwatchClass)) struct GtkSwatch { GtkDrawingArea parent; }; struct GtkSwatchClass { GtkDrawingAreaClass parent_class; void (*active_color_changed)(GtkWidget* widget, gint32 active_color, gpointer userdata); void (*color_changed)(GtkWidget* widget, gpointer userdata); void (*color_activated)(GtkWidget* widget, gpointer userdata); void (*center_activated)(GtkWidget* widget, gpointer userdata); }; GtkWidget* gtk_swatch_new(); void gtk_swatch_set_color(GtkSwatch* swatch, guint32 index, Color* color); void gtk_swatch_set_main_color(GtkSwatch* swatch, Color* color); void gtk_swatch_set_active_index(GtkSwatch* swatch, guint32 index); void gtk_swatch_set_active_color(GtkSwatch* swatch, Color* color); void gtk_swatch_move_active(GtkSwatch* swatch, gint32 direction); void gtk_swatch_set_color_to_main(GtkSwatch* swatch); void gtk_swatch_get_color(GtkSwatch* swatch, guint32 index, Color* color); void gtk_swatch_get_main_color(GtkSwatch* swatch, Color* color); gint32 gtk_swatch_get_active_index(GtkSwatch* swatch); void gtk_swatch_get_active_color(GtkSwatch* swatch, Color* color); void gtk_swatch_set_color_count(GtkSwatch* swatch, gint32 colors); gint gtk_swatch_get_color_at(GtkSwatch* swatch, gint x, gint y); void gtk_swatch_set_transformation_chain(GtkSwatch* widget, transformation::Chain *chain); void gtk_swatch_set_active(GtkSwatch* swatch, gboolean active); GType gtk_swatch_get_type(); #endif /* GPICK_GTK_SWATCH_H_ */ gpick-gpick-0.2.6rc1/source/gtk/Zoomed.cpp000066400000000000000000000420101315430016700203400ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Zoomed.h" #include "../Color.h" #include "../MathUtil.h" #include #include #include #include #include using namespace std; #define GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE((obj), GTK_TYPE_ZOOMED, GtkZoomedPrivate)) G_DEFINE_TYPE(GtkZoomed, gtk_zoomed, GTK_TYPE_DRAWING_AREA); static void finalize(GObject *zoomed_obj); static gboolean button_press(GtkWidget *node_system, GdkEventButton *event); #if GTK_MAJOR_VERSION >= 3 static gboolean draw(GtkWidget *widget, cairo_t *cr); #else static gboolean expose(GtkWidget *widget, GdkEventExpose *event); #endif enum { COLOR_CHANGED, ACTIVATED, LAST_SIGNAL }; static guint signals[LAST_SIGNAL] = { 0 }; struct GtkZoomedPrivate { Color color; gfloat zoom; cairo_surface_t *surface; vector2 point; vector2 point_size; int32_t width_height; struct{ bool valid; math::Vec2 position; }marks[2]; math::Vec2 pointer; math::Rect2 screen_rect; bool fade; #if GTK_MAJOR_VERSION >= 3 GtkStyleContext *context; #endif }; static void gtk_zoomed_class_init(GtkZoomedClass *zoomed_class) { GObjectClass *obj_class = G_OBJECT_CLASS(zoomed_class); obj_class->finalize = finalize; g_type_class_add_private(obj_class, sizeof(GtkZoomedPrivate)); GtkWidgetClass *widget_class = GTK_WIDGET_CLASS(zoomed_class); widget_class->button_press_event = button_press; #if GTK_MAJOR_VERSION >= 3 widget_class->draw = draw; #else widget_class->expose_event = expose; #endif signals[ACTIVATED] = g_signal_new("activated", G_OBJECT_CLASS_TYPE(obj_class), G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET(GtkZoomedClass, activated), nullptr, nullptr, g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0); signals[COLOR_CHANGED] = g_signal_new("color-changed", G_OBJECT_CLASS_TYPE(obj_class), G_SIGNAL_RUN_FIRST, G_STRUCT_OFFSET(GtkZoomedClass, color_changed), nullptr, nullptr, g_cclosure_marshal_VOID__POINTER, G_TYPE_NONE, 1, G_TYPE_POINTER); } static void gtk_zoomed_init(GtkZoomed *zoomed) { gtk_widget_add_events(GTK_WIDGET(zoomed), GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_BUTTON_MOTION_MASK | GDK_2BUTTON_PRESS); } #if GTK_MAJOR_VERSION >= 3 static GtkStyleContext* get_style_context(GType type) { GtkWidgetPath* path = gtk_widget_path_new(); gtk_widget_path_append_type(path, type); GtkStyleContext *context = gtk_style_context_new(); gtk_style_context_set_path(context, path); gtk_widget_path_free(path); return context; } #endif GtkWidget* gtk_zoomed_new() { GtkWidget* widget = (GtkWidget*)g_object_new(GTK_TYPE_ZOOMED, nullptr); GtkZoomedPrivate *ns = GET_PRIVATE(widget); ns->fade = false; ns->zoom = 20; ns->point.x = 0; ns->point.y = 0; ns->width_height = 0; ns->surface = nullptr; #if GTK_MAJOR_VERSION >= 3 ns->context = get_style_context(GTK_TYPE_ZOOMED); #endif gtk_zoomed_set_size(GTK_ZOOMED(widget), 150); return widget; } int32_t gtk_zoomed_get_size(GtkZoomed *zoomed) { GtkZoomedPrivate *ns = GET_PRIVATE(zoomed); return ns->width_height; } void gtk_zoomed_set_size(GtkZoomed *zoomed, int32_t width_height) { GtkZoomedPrivate *ns = GET_PRIVATE(zoomed); if (ns->width_height != width_height){ if (ns->surface){ cairo_surface_destroy(ns->surface); ns->surface = nullptr; } ns->width_height = width_height; ns->surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, ns->width_height, ns->width_height); #if GTK_MAJOR_VERSION >= 3 gtk_widget_set_size_request(GTK_WIDGET(zoomed), ns->width_height, ns->width_height); #else gtk_widget_set_size_request(GTK_WIDGET(zoomed), ns->width_height + GTK_WIDGET(zoomed)->style->xthickness * 2, ns->width_height + GTK_WIDGET(zoomed)->style->ythickness * 2); #endif } } void gtk_zoomed_set_fade(GtkZoomed* zoomed, bool fade) { GtkZoomedPrivate *ns = GET_PRIVATE(zoomed); ns->fade = fade; gtk_widget_queue_draw(GTK_WIDGET(zoomed)); } static void finalize(GObject *zoomed_obj) { GtkZoomedPrivate *ns = GET_PRIVATE(zoomed_obj); if (ns->surface){ cairo_surface_destroy(ns->surface); ns->surface = nullptr; } #if GTK_MAJOR_VERSION >= 3 g_object_unref(ns->context); #endif G_OBJECT_CLASS(g_type_class_peek_parent(G_OBJECT_CLASS(GTK_ZOOMED_GET_CLASS(zoomed_obj))))->finalize(zoomed_obj); } static double zoom_transformation(double value) { return (1 - log(1 + value * 0.01 * 3) / log((double)(1 + 3))) / 2; } void gtk_zoomed_get_current_screen_rect(GtkZoomed* zoomed, math::Rect2 *rect) { GtkZoomedPrivate *ns = GET_PRIVATE(zoomed); gtk_zoomed_get_screen_rect(zoomed, ns->pointer, ns->screen_rect, rect); } void gtk_zoomed_get_screen_rect(GtkZoomed *zoomed, math::Vec2& pointer, math::Rect2& screen_rect, math::Rect2 *rect) { GtkZoomedPrivate *ns = GET_PRIVATE(zoomed); gint32 x = pointer.x, y = pointer.y; gint32 left, right, top, bottom; gint32 area_width = uint32_t(ns->width_height * zoom_transformation(ns->zoom)); if (!area_width) area_width = 1; left = x - area_width / 2; top = y - area_width / 2; right = x + (area_width - area_width / 2); bottom = y + (area_width - area_width / 2); if (left < screen_rect.getLeft()){ right += -(left - screen_rect.getLeft()); left = screen_rect.getLeft(); } if (right > screen_rect.getRight()){ left -= right - screen_rect.getRight(); right = screen_rect.getRight(); } if (top < screen_rect.getTop()){ bottom += -(top - screen_rect.getTop()); top = screen_rect.getTop(); } if (bottom > screen_rect.getBottom()){ top -= bottom - screen_rect.getBottom(); bottom = screen_rect.getBottom(); } *rect = math::Rect2(left, top, right, bottom); } math::Vec2 gtk_zoomed_get_screen_position(GtkZoomed *zoomed, const math::Vec2& position) { GtkZoomedPrivate *ns = GET_PRIVATE(zoomed); gint32 x = ns->pointer.x, y = ns->pointer.y; gint32 left, right, top, bottom; gint32 area_width = uint32_t(ns->width_height * zoom_transformation(ns->zoom)); if (!area_width) area_width = 1; left = x - area_width / 2; top = y - area_width / 2; right = x + (area_width - area_width / 2); bottom = y + (area_width - area_width / 2); if (left < ns->screen_rect.getLeft()){ right += -(left - ns->screen_rect.getLeft()); left = ns->screen_rect.getLeft(); } if (right > ns->screen_rect.getRight()){ left -= right - ns->screen_rect.getRight(); right = ns->screen_rect.getRight(); } if (top < ns->screen_rect.getTop()){ bottom += -(top - ns->screen_rect.getTop()); top = ns->screen_rect.getTop(); } if (bottom > ns->screen_rect.getBottom()){ top -= bottom - ns->screen_rect.getBottom(); bottom = ns->screen_rect.getBottom(); } gint32 xl = ((position.x - left) * ns->width_height) / area_width; gint32 xh = (((position.x + 1) - left) * ns->width_height) / area_width; gint32 yl = ((position.y - top) * ns->width_height) / area_width; gint32 yh = (((position.y + 1) - top) * ns->width_height) / area_width; math::Vec2 result((xl + xh) / 2.0, (yl + yh) / 2.0); return result; } void gtk_zoomed_update(GtkZoomed *zoomed, math::Vec2& pointer, math::Rect2& screen_rect, math::Vec2& offset, cairo_surface_t *surface) { GtkZoomedPrivate *ns = GET_PRIVATE(zoomed); ns->pointer = pointer; ns->screen_rect = screen_rect; gint32 x = pointer.x, y = pointer.y; gint32 left, right, top, bottom; gint32 area_width = uint32_t(ns->width_height * zoom_transformation(ns->zoom)); if (!area_width) area_width = 1; left = x - area_width / 2; top = y - area_width / 2; right = x + (area_width - area_width / 2); bottom = y + (area_width - area_width / 2); if (left < ns->screen_rect.getLeft()){ right += -(left - ns->screen_rect.getLeft()); left = ns->screen_rect.getLeft(); } if (right > ns->screen_rect.getRight()){ left -= right - ns->screen_rect.getRight(); right = ns->screen_rect.getRight(); } if (top < ns->screen_rect.getTop()){ bottom += -(top - ns->screen_rect.getTop()); top = ns->screen_rect.getTop(); } if (bottom > ns->screen_rect.getBottom()){ top -= bottom - ns->screen_rect.getBottom(); bottom = ns->screen_rect.getBottom(); } gint32 xl = ((x - left) * ns->width_height) / area_width; gint32 xh = (((x + 1) - left) * ns->width_height) / area_width; gint32 yl = ((y - top) * ns->width_height) / area_width; gint32 yh = (((y + 1) - top) * ns->width_height) / area_width; ns->point.x = (xl + xh) / 2.0; ns->point.y = (yl + yh) / 2.0; ns->point_size.x = xh - xl; ns->point_size.y = yh - yl; int width = right - left; int height = bottom - top; cairo_t *cr = cairo_create(ns->surface); cairo_scale(cr, ns->width_height / (double)width, ns->width_height / (double)height); cairo_set_source_surface(cr, surface, offset.x, offset.y); cairo_pattern_set_filter(cairo_get_source(cr), CAIRO_FILTER_NEAREST); cairo_rectangle(cr, 0, 0, ns->width_height, ns->width_height); cairo_fill(cr); cairo_destroy(cr); gtk_widget_queue_draw(GTK_WIDGET(zoomed)); } void gtk_zoomed_set_zoom(GtkZoomed *zoomed, gfloat zoom) { GtkZoomedPrivate *ns = GET_PRIVATE(zoomed); if (zoom < 0){ ns->zoom = 0; }else if (zoom > 100){ ns->zoom = 100; }else{ ns->zoom = zoom; } gtk_widget_queue_draw(GTK_WIDGET(zoomed)); } gfloat gtk_zoomed_get_zoom(GtkZoomed* zoomed) { GtkZoomedPrivate *ns = GET_PRIVATE(zoomed); return ns->zoom; } static gboolean draw(GtkWidget *widget, cairo_t *cr) { GtkZoomedPrivate *ns = GET_PRIVATE(widget); #if GTK_MAJOR_VERSION >= 3 int padding_x = 0, padding_y = 0; gint pixbuf_x = padding_x; gint pixbuf_y = padding_y; #else int padding_x = widget->style->xthickness, padding_y = widget->style->ythickness; gint pixbuf_x = -padding_x; gint pixbuf_y = -padding_y; #endif if (ns->surface){ gint pixbuf_width = min(ns->width_height - pixbuf_x, ns->width_height); gint pixbuf_height = min(ns->width_height - pixbuf_y, ns->width_height); if (pixbuf_width > 0 && pixbuf_height > 0){ cairo_set_source_surface(cr, ns->surface, pixbuf_x, pixbuf_y); cairo_pattern_set_filter(cairo_get_source(cr), CAIRO_FILTER_NEAREST); if (ns->fade){ cairo_paint_with_alpha(cr, 0.2); }else{ cairo_paint(cr); } } } if (!ns->fade){ float radius; float size = vector2_length(&ns->point_size); if (size < 5){ radius = 5; }else if (size < 25){ radius = 7; }else if (size < 50){ radius = 10; }else{ radius = 15; } cairo_set_source_rgba(cr, 0, 0, 0, 0.75); cairo_arc(cr, ns->point.x, ns->point.y, radius + 0.5, -PI, PI); cairo_stroke(cr); cairo_set_source_rgba(cr, 1, 1, 1, 0.75); cairo_arc(cr, ns->point.x, ns->point.y, radius, -PI, PI); cairo_stroke(cr); } PangoLayout *layout; PangoFontDescription *font_description; font_description = pango_font_description_new(); layout = pango_cairo_create_layout(cr); pango_font_description_set_family(font_description, "sans"); pango_font_description_set_absolute_size(font_description, 12 * PANGO_SCALE); pango_layout_set_font_description(layout, font_description); math::Rect2 area_rect; math::Rect2 widget_rect = math::Rect2(5, 5, ns->width_height - 5, ns->width_height - 5); gtk_zoomed_get_current_screen_rect(GTK_ZOOMED(widget), &area_rect); cairo_rectangle(cr, 0, 0, ns->width_height - padding_x * 2, ns->width_height - padding_y * 2); cairo_clip(cr); vector > relative_positions(2); bool draw_distance = true; for (int i = 0; i < 2; i++){ if (ns->marks[i].valid){ relative_positions[i] = gtk_zoomed_get_screen_position(GTK_ZOOMED(widget), ns->marks[i].position); }else{ draw_distance = false; } } for (int layer = 0; layer != 2; layer++){ if (draw_distance){ cairo_move_to(cr, relative_positions[0].x, relative_positions[0].y); for (int i = 1; i < 2; i++){ cairo_line_to(cr, relative_positions[i].x, relative_positions[i].y); } if (layer == 0){ cairo_set_source_rgba(cr, 0, 0, 0, 1); cairo_set_line_width(cr, 3); }else{ cairo_set_source_rgba(cr, 1, 1, 1, 1); cairo_set_line_width(cr, 1); } cairo_stroke(cr); } for (int i = 0; i < 2; i++){ if (ns->marks[i].valid){ cairo_arc(cr, relative_positions[i].x, relative_positions[i].y, 2, -PI, PI); if (layer == 0){ cairo_set_source_rgba(cr, 0, 0, 0, 1); cairo_set_line_width(cr, 2); cairo_stroke(cr); }else{ cairo_set_source_rgba(cr, 1, 1, 1, 1); cairo_fill(cr); } stringstream ss; ss << ns->marks[i].position.x << "x" << ns->marks[i].position.y; pango_layout_set_text(layout, ss.str().c_str(), -1); pango_cairo_update_layout(cr, layout); cairo_move_to(cr, relative_positions[i].x + 5, relative_positions[i].y); if (layer == 0){ cairo_set_source_rgba(cr, 0, 0, 0, 1); pango_cairo_layout_path(cr, layout); cairo_set_line_width(cr, 1.5); cairo_stroke(cr); }else{ cairo_set_source_rgba(cr, 1, 1, 1, 1); pango_cairo_show_layout(cr, layout); } } } } for (int layer = 0; layer != 2; layer++){ if (draw_distance){ double distance = math::Vec2::distance( math::Vec2(ns->marks[0].position.x, ns->marks[0].position.y), math::Vec2(ns->marks[1].position.x, ns->marks[1].position.y) ); math::Vec2 center = (ns->marks[0].position + ns->marks[1].position) * 0.5; stringstream ss; ss << fixed << setprecision(1) << distance << endl << 1 + abs(ns->marks[0].position.x - ns->marks[1].position.x) << "x" << 1 + abs(ns->marks[0].position.y - ns->marks[1].position.y); pango_layout_set_text(layout, ss.str().c_str(), -1); pango_cairo_update_layout(cr, layout); math::Vec2 relative_position = gtk_zoomed_get_screen_position(GTK_ZOOMED(widget), center); PangoRectangle rect; pango_layout_get_pixel_extents(layout, nullptr, &rect); int text_width = rect.width; int text_height = rect.height; math::Rect2 text_rect(relative_position.x + 10, relative_position.y, relative_position.x + 10 + text_width, relative_position.y + text_height); if (!text_rect.isInside(widget_rect)) text_rect = widget_rect.positionInside(text_rect); cairo_move_to(cr, text_rect.getX(), text_rect.getY()); if (layer == 0){ cairo_set_source_rgba(cr, 0, 0, 0, 1); pango_cairo_layout_path(cr, layout); cairo_set_line_width(cr, 1.5); cairo_stroke(cr); }else{ cairo_set_source_rgba(cr, 1, 1, 1, 1); pango_cairo_show_layout(cr, layout); } } } g_object_unref(layout); pango_font_description_free(font_description); #if GTK_MAJOR_VERSION >= 3 gtk_render_frame(ns->context, cr, 0, 0, ns->width_height, ns->width_height); #else gtk_paint_shadow(widget->style, widget->window, GTK_STATE_NORMAL, GTK_SHADOW_IN, nullptr, widget, 0, widget->style->xthickness, widget->style->ythickness, ns->width_height + widget->style->xthickness * 2, ns->width_height + widget->style->ythickness * 2); #endif return true; } #if GTK_MAJOR_VERSION < 3 static gboolean expose(GtkWidget *widget, GdkEventExpose *event) { cairo_t *cr = gdk_cairo_create(gtk_widget_get_window(widget)); cairo_rectangle(cr, event->area.x, event->area.y, event->area.width, event->area.height); cairo_clip(cr); cairo_translate(cr, widget->style->xthickness + 0.5, widget->style->ythickness + 0.5); gboolean result = draw(widget, cr); cairo_destroy(cr); return result; } #endif static gboolean button_press(GtkWidget *widget, GdkEventButton *event) { gtk_widget_grab_focus(widget); if ((event->type == GDK_2BUTTON_PRESS) && (event->button == 1)) { g_signal_emit(widget, signals[ACTIVATED], 0); } return FALSE; } void gtk_zoomed_set_mark(GtkZoomed *zoomed, int index, math::Vec2& position) { GtkZoomedPrivate *ns = GET_PRIVATE(zoomed); ns->marks[index].position = position; ns->marks[index].valid = true; gtk_widget_queue_draw(GTK_WIDGET(zoomed)); } void gtk_zoomed_clear_mark(GtkZoomed *zoomed, int index) { GtkZoomedPrivate *ns = GET_PRIVATE(zoomed); ns->marks[index].valid = false; gtk_widget_queue_draw(GTK_WIDGET(zoomed)); } gpick-gpick-0.2.6rc1/source/gtk/Zoomed.h000066400000000000000000000062531315430016700200160ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_GTK_ZOOMED_H_ #define GPICK_GTK_ZOOMED_H_ #include #include #include "../Color.h" #include "../Rect2.h" #include "../Vector2.h" #define GTK_TYPE_ZOOMED (gtk_zoomed_get_type()) #define GTK_ZOOMED(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), GTK_TYPE_ZOOMED, GtkZoomed)) #define GTK_ZOOMED_CLASS(obj) (G_TYPE_CHECK_CLASS_CAST((obj), GTK_ZOOMED, GtkZoomedClass)) #define GTK_IS_ZOOMED(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), GTK_TYPE_ZOOMED)) #define GTK_IS_ZOOMED_CLASS(obj) (G_TYPE_CHECK_CLASS_TYPE((obj), GTK_TYPE_ZOOMED)) #define GTK_ZOOMED_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), GTK_TYPE_ZOOMED, GtkZoomedClass)) struct GtkZoomed { GtkDrawingArea parent; }; struct GtkZoomedClass { GtkDrawingAreaClass parent_class; void (* color_changed)(GtkWidget* widget, Color* c, gpointer userdata); void (*activated)(GtkWidget* widget, gpointer userdata); }; GtkWidget* gtk_zoomed_new(); void gtk_zoomed_set_zoom(GtkZoomed* zoomed, gfloat zoom); gfloat gtk_zoomed_get_zoom(GtkZoomed* zoomed); void gtk_zoomed_set_fade(GtkZoomed* zoomed, bool fade); int32_t gtk_zoomed_get_size(GtkZoomed *zoomed); void gtk_zoomed_set_size(GtkZoomed *zoomed, int32_t width_height); void gtk_zoomed_set_mark(GtkZoomed *zoomed, int index, math::Vec2& position); void gtk_zoomed_clear_mark(GtkZoomed *zoomed, int index); void gtk_zoomed_update(GtkZoomed* zoomed, math::Vec2& pointer, math::Rect2& screen_rect, math::Vec2& offset, cairo_surface_t *surface); void gtk_zoomed_get_screen_rect(GtkZoomed* zoomed, math::Vec2& pointer, math::Rect2& screen_rect, math::Rect2 *rect); GType gtk_zoomed_get_type(); #endif /* GPICK_GTK_ZOOMED_H_ */ gpick-gpick-0.2.6rc1/source/internationalisation/000077500000000000000000000000001315430016700220535ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/source/internationalisation/Internationalisation.cpp000066400000000000000000000036471315430016700267670ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifdef ENABLE_NLS #include #endif #include #include #include #define TO_STRING(x) #x #define T_(x) TO_STRING(x) void initialize_internationalisation() { #ifdef ENABLE_NLS bindtextdomain("gpick", T_(LOCALEDIR)); char *td = textdomain("gpick"); if (!(td && (strcmp(td, "gpick") == 0))){ fprintf(stderr, "failed to load textdomain \"gpick\"\n"); } #endif } gpick-gpick-0.2.6rc1/source/internationalisation/SConscript000066400000000000000000000005261315430016700240700ustar00rootroot00000000000000#!/usr/bin/env python import os import sys Import('*') local_env = env.Clone() if not local_env.GetOption('clean'): if local_env['ENABLE_NLS']: local_env.Append( CPPDEFINES = ['ENABLE_NLS', 'LOCALEDIR=' + local_env['LOCALEDIR']], ) sources = local_env.Glob('*.cpp') objects = local_env.StaticObject([sources]) Return('objects') gpick-gpick-0.2.6rc1/source/layout/000077500000000000000000000000001315430016700171325ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/source/layout/Box.cpp000066400000000000000000000134051315430016700203710ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Box.h" #include #include #include #include using namespace std; using namespace math; namespace layout{ void Box::SetStyle(Style *_style){ if (style){ unref(style); style=0; } if (_style){ style = static_cast(_style->ref()); } } void Box::Draw(Context *context, const Rect2& parent_rect ){ DrawChildren(context, parent_rect); } void Box::DrawChildren(Context *context, const math::Rect2& parent_rect ){ Rect2 child_rect = rect.impose( parent_rect ); for (list::iterator i = child.begin(); i != child.end(); i++){ (*i)->Draw(context, child_rect); } } void Box::AddChild(Box* box){ child.push_back(box); } Box::Box(const char* _name, float x, float y, float width, float height){ style = 0; name = _name; rect = Rect2(x, y, x+width, y+height); helper_only = false; locked = false; } Box::~Box(){ SetStyle(0); for (list::iterator i = child.begin(); i != child.end(); i++){ unref(*i); } } Box* Box::GetNamedBox(const char *name_){ if (name.compare(name_) == 0){ return this; } Box* r; for (list::iterator i = child.begin(); i != child.end(); i++){ if ((r = (*i)->GetNamedBox(name_))){ if (!r->helper_only) return r; } } return 0; } Box* Box::GetBoxAt(const Vec2& point){ if (rect.isInside(point.x, point.y)){ Vec2 transformed_point = Vec2((point.x-rect.getX()) / rect.getWidth(), (point.y-rect.getY()) / rect.getHeight()); Box* r; for (list::iterator i = child.begin(); i != child.end(); i++){ if ((r = (*i)->GetBoxAt(transformed_point))){ if (!r->helper_only) return r; } } if (typeid(*this) == typeid(Box)) //do not match Box, because it is invisible return 0; else return this; }else{ return 0; } } void Text::Draw(Context *context, const Rect2& parent_rect ){ Rect2 draw_rect = rect.impose( parent_rect ); cairo_t *cr = context->getCairo(); if (text != ""){ if (helper_only){ cairo_select_font_face(cr, "sans-serif", CAIRO_FONT_SLANT_ITALIC, CAIRO_FONT_WEIGHT_NORMAL); }else{ cairo_select_font_face(cr, "sans-serif", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL); } if (style){ cairo_set_font_size(cr, style->font_size * draw_rect.getHeight()); Color color; if (context->getTransformationChain()){ context->getTransformationChain()->apply(&style->color, &color); }else{ color_copy(&style->color, &color); } cairo_set_source_rgb(cr, boost::math::round(color.rgb.red * 255.0) / 255.0, boost::math::round(color.rgb.green * 255.0) / 255.0, boost::math::round(color.rgb.blue * 255.0) / 255.0); }else{ cairo_set_font_size(cr, draw_rect.getHeight()); cairo_set_source_rgb(cr, 0, 0, 0); } cairo_text_extents_t extents; cairo_text_extents(cr, text.c_str(), &extents); cairo_move_to(cr, draw_rect.getX() + draw_rect.getWidth()/2 - (extents.width/2 + extents.x_bearing), draw_rect.getY() + draw_rect.getHeight()/2 - (extents.height/2 + extents.y_bearing)); cairo_show_text(cr, text.c_str()); if (style && style->GetBox() == this){ cairo_rectangle(cr, draw_rect.getX()+1, draw_rect.getY()+1, draw_rect.getWidth()-2, draw_rect.getHeight()-2); cairo_set_source_rgb(cr, 1, 1, 1); cairo_set_line_width(cr, 2); cairo_stroke(cr); } } DrawChildren(context, parent_rect); } void Fill::Draw(Context *context, const Rect2& parent_rect ){ Rect2 draw_rect = rect.impose( parent_rect ); cairo_t *cr = context->getCairo(); Color color; if (context->getTransformationChain()){ context->getTransformationChain()->apply(&style->color, &color); }else{ color_copy(&style->color, &color); } cairo_set_source_rgb(cr, boost::math::round(color.rgb.red * 255.0) / 255.0, boost::math::round(color.rgb.green * 255.0) / 255.0, boost::math::round(color.rgb.blue * 255.0) / 255.0); cairo_rectangle(cr, draw_rect.getX(), draw_rect.getY(), draw_rect.getWidth(), draw_rect.getHeight()); cairo_fill(cr); if (style->GetBox() == this){ cairo_rectangle(cr, draw_rect.getX()+1, draw_rect.getY()+1, draw_rect.getWidth()-2, draw_rect.getHeight()-2); cairo_set_source_rgb(cr, 1, 1, 1); cairo_set_line_width(cr, 2); cairo_stroke(cr); } DrawChildren(context, parent_rect); } } gpick-gpick-0.2.6rc1/source/layout/Box.h000066400000000000000000000054371315430016700200440ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef LAYOUT_BOX_H_ #define LAYOUT_BOX_H_ #include "../Color.h" #include "../Rect2.h" #include "../Vector2.h" #include "ReferenceCounter.h" #include "Style.h" #include "Context.h" #include #include #include namespace layout{ class Box: public ReferenceCounter{ public: std::string name; Style *style; bool helper_only; bool locked; math::Rect2 rect; std::list child; virtual void Draw(Context *context, const math::Rect2& parent_rect ); void DrawChildren(Context *context, const math::Rect2& parent_rect ); void AddChild(Box* box); void SetStyle(Style *style); Box* GetBoxAt(const math::Vec2& point); Box* GetNamedBox(const char *name); Box(const char* name, float x, float y, float width, float height); virtual ~Box(); }; class Text:public Box{ public: std::string text; virtual void Draw(Context *context, const math::Rect2& parent_rect ); Text(const char* name, float x, float y, float width, float height):Box(name,x,y,width,height){ }; }; class Fill:public Box{ public: virtual void Draw(Context *context, const math::Rect2& parent_rect ); Fill(const char* name, float x, float y, float width, float height):Box(name,x,y,width,height){ }; }; } #endif /* LAYOUT_BOX_H_ */ gpick-gpick-0.2.6rc1/source/layout/Context.cpp000066400000000000000000000034741315430016700212720ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Context.h" namespace layout{ Context::Context(cairo_t *cr_, transformation::Chain *chain_) { cr = cr_; chain = chain_; } Context::~Context() { } cairo_t* Context::getCairo() const { return cr; } transformation::Chain* Context::getTransformationChain() const { return chain; } } gpick-gpick-0.2.6rc1/source/layout/Context.h000066400000000000000000000040021315430016700207230ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef LAYOUT_CONTEXT_H_ #define LAYOUT_CONTEXT_H_ #include "../transformation/Chain.h" #include #ifndef _MSC_VER #include #endif #include #include #include namespace layout{ class Context{ protected: cairo_t *cr; transformation::Chain *chain; public: Context(cairo_t *cr, transformation::Chain *chain); ~Context(); cairo_t* getCairo() const; transformation::Chain* getTransformationChain() const; }; } #endif /* LAYOUT_SYSTEM_H_ */ gpick-gpick-0.2.6rc1/source/layout/Layout.cpp000066400000000000000000000120701315430016700211130ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Layout.h" #include "LuaBindings.h" #include "../LuaExt.h" #include "../DynvHelpers.h" #include #include #include #include #include #include #include #include #include extern "C"{ #include } using namespace std; namespace layout{ class LayoutKeyCompare{ public: bool operator() (const char* const& x, const char* const& y) const { return strcmp(x,y)<0; }; }; class Layouts{ public: typedef std::map LayoutMap; LayoutMap layouts; vector all_layouts; lua_State *L; ~Layouts(); }; Layouts::~Layouts(){ Layouts::LayoutMap::iterator i; for (i = layouts.begin(); i != layouts.end(); ++i){ g_free(((*i).second)->human_readable); g_free(((*i).second)->name); delete ((*i).second); } layouts.clear(); } Layouts* layouts_init(lua_State *lua, dynvSystem* settings) { if (lua == nullptr || settings == nullptr) return nullptr; lua_State* L = lua; Layouts *layouts = new Layouts; layouts->L = L; int status; int stack_top = lua_gettop(L); lua_getglobal(L, "gpick"); int gpick_namespace = lua_gettop(L); if (lua_type(L, -1) != LUA_TNIL){ lua_pushstring(L, "layouts"); lua_gettable(L, gpick_namespace); int layouts_table = lua_gettop(L); lua_pushstring(L, "layouts_get"); lua_gettable(L, gpick_namespace); if (lua_type(L, -1) != LUA_TNIL){ if ((status=lua_pcall(L, 0, 1, 0)) == 0){ if (lua_type(L, -1) == LUA_TTABLE){ int table_index = lua_gettop(L); for (int i=1;;i++){ lua_pushinteger(L, i); lua_gettable(L, table_index); if (lua_isnil(L, -1)) break; lua_pushstring(L, lua_tostring(L, -1)); //duplicate, because lua_gettable replaces stack top lua_gettable(L, layouts_table); lua_pushstring(L, "human_readable"); lua_gettable(L, -2); lua_pushstring(L, "mask"); lua_gettable(L, -3); Layout *layout = new Layout; layout->human_readable = g_strdup(lua_tostring(L, -2)); layout->name = g_strdup(lua_tostring(L, -4)); layout->mask = lua_tointeger(L, -1); layouts->layouts[layout->name] = layout; layouts->all_layouts.push_back(layout); lua_pop(L, 3); } } }else{ cerr<<"layouts_get: "<all_layouts.size(); return &layouts->all_layouts[0]; } System* layouts_get(Layouts *layouts, const char* name){ Layouts::LayoutMap::iterator i; i=layouts->layouts.find(name); if (i != layouts->layouts.end()){ //layout name matched, build layout lua_State* L = layouts->L; int status; int stack_top = lua_gettop(L); lua_getglobal(L, "gpick"); int gpick_namespace = lua_gettop(L); if (lua_type(L, -1) != LUA_TNIL){ lua_pushstring(L, "layouts"); lua_gettable(L, gpick_namespace); int layouts_table = lua_gettop(L); lua_pushstring(L, name); lua_gettable(L, layouts_table); lua_pushstring(L, "build"); lua_gettable(L, -2); if (!lua_isnil(L, -1)){ System *layout_system = new System; lua_pushlsystem(L, layout_system); if ((status=lua_pcall(L, 1, 1, 0)) == 0){ if (!lua_isnil(L, -1)){ lua_settop(L, stack_top); return layout_system; } }else{ cerr<<"layouts.build: "< #ifndef _MSC_VER #include #endif #include namespace layout{ class Layouts; class System; typedef struct Layout{ char* name; char* human_readable; uint32_t mask; }Layout; Layouts* layouts_init(lua_State *lua, dynvSystem* params); int layouts_term(Layouts *layouts); Layout** layouts_get_all(Layouts *layouts, size_t *size); System* layouts_get(Layouts *layouts, const char* name); } #endif /* GPICK_LAYOUT_LAYOUT_H_ */ gpick-gpick-0.2.6rc1/source/layout/LuaBindings.cpp000066400000000000000000000177251315430016700220510ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "LuaBindings.h" #include "Box.h" #include "System.h" extern "C"{ #include #include } #include #include using namespace std; namespace layout{ static int lua_lstyle_new (lua_State *L) { size_t st; const char* name = luaL_checklstring(L, 2, &st); Color* color = lua_checkcolor(L, 3); double font_size = luaL_optnumber(L, 4, 1.0); Style** c = static_cast(lua_newuserdata(L, sizeof(Style*))); luaL_getmetatable(L, "layout_style"); lua_setmetatable(L, -2); Style *e = new Style(name, color, font_size); *c = static_cast(e); return 1; } Style* lua_checklstyle (lua_State *L, int index) { Style** c = static_cast(luaL_checkudata(L, index, "layout_style")); luaL_argcheck(L, c != nullptr, index, "`layout_style' expected"); return *c; } int lua_pushlstyle (lua_State *L, Style* style) { Style** c = static_cast(lua_newuserdata(L, sizeof(Style*))); luaL_getmetatable(L, "layout_style"); lua_setmetatable(L, -2); *c = style; return 1; } int lua_lstyle_gc (lua_State *L) { Style* style = lua_checklstyle(L, 1); Style::unref(style); return 0; } int lua_lstyle_humanname (lua_State *L) { Style *style = lua_checklstyle(L, 1); if (lua_type(L, 2) == LUA_TSTRING){ size_t st; const char* name = luaL_checklstring(L, 2, &st); style->human_name = name; return 0; }else{ lua_pushstring(L, style->human_name.c_str()); return 1; } } static const struct luaL_Reg lua_lstylelib_f [] = { {"new", lua_lstyle_new}, {nullptr, nullptr} }; static const struct luaL_Reg lua_lstylelib_m [] = { {"humanname", lua_lstyle_humanname}, {"__gc", lua_lstyle_gc}, {nullptr, nullptr} }; static int lua_new_box (lua_State *L) { size_t st; const char* name = luaL_checklstring(L, 2, &st); double x = luaL_checknumber(L, 3); double y = luaL_checknumber(L, 4); double w = luaL_checknumber(L, 5); double h = luaL_checknumber(L, 6); Box** c = (Box**)lua_newuserdata(L, sizeof(Box*)); luaL_getmetatable(L, "layout"); lua_setmetatable(L, -2); Box *e = new Box(name, x, y, w, h); *c = static_cast(e); return 1; } static int lua_new_fill (lua_State *L) { size_t st; const char* name = luaL_checklstring(L, 2, &st); double x = luaL_checknumber(L, 3); double y = luaL_checknumber(L, 4); double w = luaL_checknumber(L, 5); double h = luaL_checknumber(L, 6); Style* style = lua_checklstyle(L, 7); Box** c = (Box**)lua_newuserdata(L, sizeof(Box*)); luaL_getmetatable(L, "layout"); lua_setmetatable(L, -2); Fill *e = new Fill(name, x, y, w, h); e->SetStyle(style); *c = static_cast(e); return 1; } static int lua_new_text (lua_State *L) { size_t st; const char* name = luaL_checklstring(L, 2, &st); double x = luaL_checknumber(L, 3); double y = luaL_checknumber(L, 4); double w = luaL_checknumber(L, 5); double h = luaL_checknumber(L, 6); Style* style = 0; if (lua_type(L, 7) != LUA_TNIL){ style = lua_checklstyle(L, 7); } const char* text = luaL_checklstring(L, 8, &st); Box** c = (Box**)lua_newuserdata(L, sizeof(Box*)); luaL_getmetatable(L, "layout"); lua_setmetatable(L, -2); Text *e = new Text(name, x, y, w, h); if (style) e->SetStyle(style); e->text = text; *c = static_cast(e); return 1; } Box* lua_checklbox (lua_State *L, int index) { Box** c = static_cast(luaL_checkudata(L, index, "layout")); luaL_argcheck(L, c != nullptr, index, "`layout' expected"); return *c; } int lua_pushlbox (lua_State *L, Box* box) { Box** c = static_cast(lua_newuserdata(L, sizeof(Box*))); luaL_getmetatable(L, "layout"); lua_setmetatable(L, -2); *c = static_cast(box->ref()); return 1; } int lua_add (lua_State *L) { Box* box = lua_checklbox(L, 1); Box* box2 = lua_checklbox(L, 2); box->AddChild(static_cast(box2->ref())); lua_pushlbox(L, box); return 1; } int lua_box_helper_only (lua_State *L) { Box* box = lua_checklbox(L, 1); if (lua_type(L, 2) == LUA_TBOOLEAN){ int v = lua_toboolean(L, 2); if (v){ box->helper_only = true; }else{ box->helper_only = false; } return 0; }else{ lua_pushboolean(L, box->helper_only); return 1; } } int lua_box_locked (lua_State *L) { Box* box = lua_checklbox(L, 1); if (lua_type(L, 2) == LUA_TBOOLEAN){ int v = lua_toboolean(L, 2); if (v){ box->locked = true; }else{ box->locked = false; } return 0; }else{ lua_pushboolean(L, box->locked); return 1; } } int lua_box_gc(lua_State *L) { Box* box = lua_checklbox(L, 1); Box::unref(box); return 0; } static const struct luaL_Reg lua_lboxlib_f [] = { {"new_box", lua_new_box}, {"new_text", lua_new_text}, {"new_fill", lua_new_fill}, {nullptr, nullptr} }; static const struct luaL_Reg lua_lboxlib_m [] = { {"add", lua_add}, {"helper_only", lua_box_helper_only}, {"locked", lua_box_locked}, {"__gc", lua_box_gc}, {nullptr, nullptr} }; System* lua_checklsystem (lua_State *L, int index) { System** c = static_cast(luaL_checkudata(L, index, "layout_system")); luaL_argcheck(L, c != nullptr, index, "`layout_system' expected"); return *c; } int lua_pushlsystem (lua_State *L, System* system) { System** c = static_cast(lua_newuserdata(L, sizeof(System*))); luaL_getmetatable(L, "layout_system"); lua_setmetatable(L, -2); *c = static_cast(system); return 1; } int lua_lsystem_addstyle (lua_State *L) { System* system = lua_checklsystem(L, 1); Style* style = lua_checklstyle(L, 2); system->AddStyle(style); return 0; } int lua_lsystem_setbox (lua_State *L) { System* system = lua_checklsystem(L, 1); Box* box = lua_checklbox(L, 2); system->SetBox(box); return 0; } static const struct luaL_Reg lua_systemlib_m [] = { {"addstyle", lua_lsystem_addstyle}, {"setbox", lua_lsystem_setbox}, {nullptr, nullptr} }; int luaopen_lbox (lua_State *L) { luaL_newmetatable(L, "layout"); lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); luaL_setfuncs(L, lua_lboxlib_m, 0); lua_pop(L, 1); luaL_newlibtable(L, lua_lboxlib_f); luaL_setfuncs(L, lua_lboxlib_f, 0); lua_setglobal(L, "layout"); luaL_newmetatable(L, "layout_style"); lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); luaL_setfuncs(L, lua_lstylelib_m, 0); lua_pop(L, 1); luaL_newlibtable(L, lua_lstylelib_f); luaL_setfuncs(L, lua_lstylelib_f, 0); lua_setglobal(L, "layout_style"); luaL_newmetatable(L, "layout_system"); lua_pushvalue(L, -1); lua_setfield(L, -2, "__index"); luaL_setfuncs(L, lua_systemlib_m, 0); lua_pop(L, 1); return 1; } int lua_ext_layout_openlib(lua_State *L){ luaopen_lbox(L); return 0; } } gpick-gpick-0.2.6rc1/source/layout/LuaBindings.h000066400000000000000000000036611315430016700215100ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef LAYOUT_LUABINDINGS_H_ #define LAYOUT_LUABINDINGS_H_ #include "../LuaExt.h" #include "Box.h" #include "System.h" namespace layout{ int lua_ext_layout_openlib(lua_State *L); Box* lua_checklbox (lua_State *L, int index); int lua_pushlbox (lua_State *L, Box* box); System* lua_checklsystem (lua_State *L, int index); int lua_pushlsystem (lua_State *L, System* system); } #endif /* LAYOUT_LUABINDINGS_H_ */ gpick-gpick-0.2.6rc1/source/layout/ReferenceCounter.cpp000066400000000000000000000036731315430016700231050ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ReferenceCounter.h" #include using namespace std; namespace layout{ ReferenceCounter::ReferenceCounter(){ refcnt = 0; } ReferenceCounter::~ReferenceCounter(){ } ReferenceCounter* ReferenceCounter::ref(){ refcnt++; return this; } bool ReferenceCounter::unref(ReferenceCounter* rc){ if (rc->refcnt){ rc->refcnt--; return false; }else{ //cout< #ifndef _MSC_VER #include #endif namespace layout{ class ReferenceCounter{ protected: uint32_t refcnt; public: ReferenceCounter(); virtual ~ReferenceCounter(); ReferenceCounter* ref(); static bool unref(ReferenceCounter* rc); }; } #endif /* LAYOUT_REFERENCECOUNTER_H_ */ gpick-gpick-0.2.6rc1/source/layout/SConscript000066400000000000000000000006031315430016700211430ustar00rootroot00000000000000#!/usr/bin/env python import os import sys Import('*') local_env = env.Clone() if not local_env.GetOption('clean') and not env['TOOLCHAIN'] == 'msvc': local_env.ParseConfig('pkg-config --cflags --libs $GTK_PC') local_env.ParseConfig('pkg-config --cflags --libs $LUA_PC') sources = local_env.Glob('*.cpp') objects = local_env.StaticObject( source = [sources]) Return('objects') gpick-gpick-0.2.6rc1/source/layout/Style.cpp000066400000000000000000000051431315430016700207410ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Box.h" #include #include using namespace std; using namespace math; namespace layout{ Style::Style(const char* _name, Color* _color, float _font_size){ string name = string(_name); size_t pos = name.find(":"); if (pos != string::npos){ ident_name = name.substr(0, pos); human_name = name.substr(pos+1); }else{ ident_name = name; human_name = name; } style_type = TYPE_UNKNOWN; if ((pos = ident_name.rfind("_")) != string::npos){ string flags = ident_name.substr(pos); if (flags.find("t") != string::npos){ style_type = TYPE_COLOR; }else if (flags.find("b") != string::npos){ style_type = TYPE_BACKGROUND; } } color_copy(_color, &color); font_size = _font_size; dirty = true; highlight = false; selected_box = 0; } Style::~Style(){ } bool Style::IsDirty(){ return dirty; } void Style::SetDirty(bool _dirty){ dirty = _dirty; } bool Style::GetHighlight(){ return highlight; } Box* Style::GetBox(){ return selected_box; } void Style::SetState(bool _highlight, Box *box){ selected_box = box; highlight = _highlight; } } gpick-gpick-0.2.6rc1/source/layout/Style.h000066400000000000000000000043101315430016700204010ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef LAYOUT_STYLE_H_ #define LAYOUT_STYLE_H_ #include "../Color.h" #include "ReferenceCounter.h" #include "Box.h" #include #include namespace layout{ class Box; class Style:public ReferenceCounter{ public: std::string ident_name; std::string human_name; Color color; float font_size; enum{ TYPE_UNKNOWN = 0, TYPE_COLOR, TYPE_BACKGROUND, TYPE_BORDER, }style_type; bool dirty; bool highlight; Box* selected_box; bool IsDirty(); void SetDirty(bool dirty); bool GetHighlight(); Box* GetBox(); void SetState(bool highlight, Box *box); Style(const char* name, Color* color, float font_size); virtual ~Style(); }; } #endif /* LAYOUT_STYLE_H_ */ gpick-gpick-0.2.6rc1/source/layout/System.cpp000066400000000000000000000045031315430016700211240ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "System.h" using namespace std; namespace layout{ System::System(){ box = 0; } System::~System(){ for (list::iterator i=styles.begin(); i != styles.end(); i++){ Style::unref(*i); } styles.clear(); Box::unref(box); } void System::Draw(Context *context, const math::Rect2& parent_rect ){ if (!box) return; box->Draw(context, parent_rect); } void System::AddStyle(Style *_style){ styles.push_back(static_cast(_style->ref())); } void System::SetBox(Box *_box){ if (box){ Box::unref(box); box = 0; } box = static_cast(_box->ref()); } Box* System::GetBoxAt(const math::Vec2& point){ if (box) return box->GetBoxAt(point); else return 0; } Box* System::GetNamedBox(const char *name){ if (box) return box->GetNamedBox(name); else return 0; } } gpick-gpick-0.2.6rc1/source/layout/System.h000066400000000000000000000043031315430016700205670ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef LAYOUT_SYSTEM_H_ #define LAYOUT_SYSTEM_H_ #include "../Rect2.h" #include "../Vector2.h" #include "Box.h" #include "Style.h" #include "Context.h" #include "ReferenceCounter.h" #include #ifndef _MSC_VER #include #endif #include #include #include namespace layout{ class System:public ReferenceCounter{ public: std::list styles; Box* box; System(); virtual ~System(); void Draw(Context *context, const math::Rect2& parent_rect ); Box* GetBoxAt(const math::Vec2& point); Box* GetNamedBox(const char *name); void AddStyle(Style *style); void SetBox(Box *box); }; } #endif /* LAYOUT_SYSTEM_H_ */ gpick-gpick-0.2.6rc1/source/main.cpp000066400000000000000000000122241315430016700172460ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "main.h" #include "Paths.h" #include "uiAbout.h" #include "uiApp.h" #include "Internationalisation.h" #include "version/Version.h" #include "DynvHelpers.h" #include #include #include using namespace std; static gchar **commandline_filename = nullptr; static gchar *commandline_geometry = nullptr; static gboolean pick_color = FALSE; static gboolean output_picked_color = FALSE; static gboolean output_without_newline = FALSE; static gboolean single_color_pick_mode = FALSE; static gboolean version_information = FALSE; static gboolean do_not_start = FALSE; static gchar *converter_name = nullptr; static GOptionEntry commandline_entries[] = { {"geometry", 'g', 0, G_OPTION_ARG_STRING, &commandline_geometry, "Window geometry", "GEOMETRY"}, {"pick", 'p', 0, G_OPTION_ARG_NONE, &pick_color, "Pick a color", nullptr}, {"single", 's', 0, G_OPTION_ARG_NONE, &single_color_pick_mode, "Pick one color and exit", nullptr}, {"output", 'o', 0, G_OPTION_ARG_NONE, &output_picked_color, "Output picked color", nullptr}, {"no-newline", 0, 0, G_OPTION_ARG_NONE, &output_without_newline, "Output picked color without newline", nullptr}, {"no-start", 0, 0, G_OPTION_ARG_NONE, &do_not_start, "Do not start Gpick if it is not already running", nullptr}, {"converter-name", 'c', 0, G_OPTION_ARG_STRING, &converter_name, "Converter name used for floating picker mode", nullptr}, {"version", 'v', 0, G_OPTION_ARG_NONE, &version_information, "Print version information", nullptr}, {G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &commandline_filename, nullptr, "[FILE...]"}, {nullptr} }; int main(int argc, char **argv) { setlocale(LC_ALL, ""); gtk_init(&argc, &argv); initialize_internationalisation(); g_set_application_name(program_name); GError *error = nullptr; GOptionContext *context = g_option_context_new("- advanced color picker"); g_option_context_add_main_entries(context, commandline_entries, 0); g_option_context_add_group(context, gtk_get_option_group(TRUE)); gchar **argv_copy; #ifdef WIN32 argv_copy = g_win32_get_command_line(); #else argv_copy = g_strdupv(argv); #endif if (!g_option_context_parse_strv(context, &argv_copy, &error)){ g_print("option parsing failed: %s\n", error->message); g_clear_error(&error); g_option_context_free(context); g_strfreev(argv_copy); return -1; } if (version_information){ string version = string(program_name) + " version " + string(gpick_build_version); string revision = "Revision " + string(gpick_build_revision); string build_date = "Date " + string(gpick_build_date); g_print("%s\n%s\n%s\n", version.c_str(), revision.c_str(), build_date.c_str()); g_option_context_free(context); g_strfreev(argv_copy); return 0; } AppOptions options; options.floating_picker_mode = pick_color; options.output_picked_color = output_picked_color; options.output_without_newline = output_without_newline; options.single_color_pick_mode = single_color_pick_mode; options.do_not_start = do_not_start; if (converter_name != nullptr) options.converter_name = converter_name; int return_value = 0; app_initialize(); AppArgs *args = app_create_main(options, return_value); if (args){ if (!single_color_pick_mode){ if (commandline_filename){ app_load_file(args, commandline_filename[0]); }else{ if (app_is_autoload_enabled(args)){ gchar* autosave_file = build_config_path("autosave.gpa"); app_load_file(args, autosave_file, true); g_free(autosave_file); } } } if (commandline_geometry) app_parse_geometry(args, commandline_geometry); return_value = app_run(args); } g_option_context_free(context); g_strfreev(argv_copy); return return_value; } gpick-gpick-0.2.6rc1/source/main.h000066400000000000000000000031301315430016700167070ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_MAIN_H_ #define GPICK_MAIN_H_ #endif /* GPICK_MAIN_H_ */ gpick-gpick-0.2.6rc1/source/parser/000077500000000000000000000000001315430016700171115ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/source/parser/TextFile.cpp000066400000000000000000000040261315430016700213430ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "TextFile.h" namespace text_file_parser { Configuration::Configuration() { single_line_c_comments = true; single_line_hash_comments = true; multi_line_c_comments = true; short_hex = true; full_hex = true; css_rgb = true; css_rgba = true; float_values = true; int_values = true; } bool scanner(TextFile &text_file, const Configuration &configuration); bool TextFile::parse(const Configuration &configuration) { return scanner(*this, configuration); } TextFile::~TextFile() { } } gpick-gpick-0.2.6rc1/source/parser/TextFile.h000066400000000000000000000044621315430016700210140ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_PARSER_TEXT_FILE_H_ #define GPICK_PARSER_TEXT_FILE_H_ class Color; #include namespace text_file_parser { class Configuration { public: Configuration(); bool single_line_c_comments; bool single_line_hash_comments; bool multi_line_c_comments; bool short_hex; bool full_hex; bool css_rgb; bool css_rgba; bool float_values; bool int_values; }; class TextFile { public: bool parse(const Configuration &configuration); virtual ~TextFile(); virtual void outOfMemory() = 0; virtual void syntaxError(size_t start_line, size_t start_column, size_t end_line, size_t end_colunn) = 0; virtual size_t read(char *buffer, size_t length) = 0; virtual void addColor(const Color &color) = 0; }; } #endif /* GPICK_PARSER_TEXT_FILE_H_ */ gpick-gpick-0.2.6rc1/source/parser/TextFileParser.rl000066400000000000000000000145531315430016700223610ustar00rootroot00000000000000#include "parser/TextFile.h" #include "Color.h" #include #include #include #include #include #include #include using namespace std; namespace text_file_parser { class FSM { public: int cs; char separator; int act; int top; char *ts; char *te; int stack[256]; char buffer[8 * 1024]; int line; int column; int line_start; int buffer_offset; int64_t number_i64; vector numbers_i64; char *number_double_start; vector numbers_double; function addColor; void handleNewline() { line++; column = 0; line_start = te - buffer; } int hexToInt(char hex) { if (hex >= '0' && hex <= '9') return hex - '0'; if (hex >= 'a' && hex <= 'f') return hex - 'a' + 10; if (hex >= 'A' && hex <= 'F') return hex - 'A' + 10; return 0; } int hexPairToInt(const char *hex_pair) { return hexToInt(hex_pair[0]) << 4 | hexToInt(hex_pair[1]); } void colorHexFull(bool with_hash_symbol) { Color color; int start_index = with_hash_symbol ? 1 : 0; color.rgb.red = hexPairToInt(ts + start_index) / 255.0; color.rgb.green = hexPairToInt(ts + start_index + 2) / 255.0; color.rgb.blue = hexPairToInt(ts + start_index + 4) / 255.0; addColor(color); } void colorHexShort(bool with_hash_symbol) { Color color; int start_index = with_hash_symbol ? 1 : 0; color.rgb.red = hexToInt(ts[start_index + 0]) / 15.0; color.rgb.green = hexToInt(ts[start_index + 1]) / 15.0; color.rgb.blue = hexToInt(ts[start_index + 2]) / 15.0; color.ma[3] = 0; addColor(color); } void colorRgb() { Color color; color.rgb.red = numbers_i64[0] / 255.0; color.rgb.green = numbers_i64[1] / 255.0; color.rgb.blue = numbers_i64[2] / 255.0; color.ma[3] = 0; numbers_i64.clear(); addColor(color); } void colorRgba() { Color color; color.rgb.red = numbers_i64[0] / 255.0; color.rgb.green = numbers_i64[1] / 255.0; color.rgb.blue = numbers_i64[2] / 255.0; color.ma[3] = numbers_double[0]; numbers_i64.clear(); numbers_double.clear(); addColor(color); } void colorValues() { Color color; color.rgb.red = numbers_double[0]; color.rgb.green = numbers_double[1]; color.rgb.blue = numbers_double[2]; color.ma[3] = 0; numbers_double.clear(); addColor(color); } void colorValueIntegers() { Color color; color.rgb.red = numbers_i64[0] / 255.0; color.rgb.green = numbers_i64[1] / 255.0; color.rgb.blue = numbers_i64[2] / 255.0; color.ma[3] = 0; numbers_i64.clear(); addColor(color); } double parseDouble(const char *start, const char *end) { string v(start, end); return stod(v.c_str()); } void clearNumberStacks() { numbers_i64.clear(); numbers_double.clear(); } }; %%{ machine text_file; access fsm->; number_i64 = digit+ >{ fsm->number_i64 = 0; } ${ fsm->number_i64 = fsm->number_i64 * 10 + (*p - '0'); }; sign = '-' | '+'; number_double = sign? (([0-9]+ '.' [0-9]+) | ('.' [0-9]+) | ([0-9]+)) ('e'i sign? digit+)?; number = number_i64 %{ fsm->numbers_i64.push_back(fsm->number_i64); }; real_number = number_double >{ fsm->number_double_start = p; } %{ fsm->numbers_double.push_back(fsm->parseDouble(fsm->number_double_start, p)); }; newline = ('\n' | '\r\n') @{ fsm->handleNewline(); }; anything = any | newline; multi_line_comment := anything* :>> '*/' @{ fgoto main; }; single_line_comment := (any - newline)* :>> ('\n' | '\r\n') @{ fgoto main; }; main := |* ( '#'[0-9a-fA-F]{6} ) { if (configuration.full_hex) fsm->colorHexFull(true); }; ( '#'[0-9a-fA-F]{3} ) { if (configuration.short_hex) fsm->colorHexShort(true); }; ( [0-9a-fA-F]{6} ) { if (configuration.full_hex) fsm->colorHexFull(false); }; ( [0-9a-fA-F]{3} ) { if (configuration.short_hex) fsm->colorHexShort(false); }; ( 'rgb'i '(' space* number space* ',' space* number space* ',' space* number space* ')' ) { if (configuration.css_rgb) fsm->colorRgb(); else fsm->clearNumberStacks(); }; ( 'rgba'i '(' space* number space* ',' space* number space* ',' space* number space* ',' space* real_number space* ')' ) { if (configuration.css_rgba) fsm->colorRgba(); else fsm->clearNumberStacks(); }; ( number space* ',' space* number space* ',' space* number ) { if (configuration.int_values) fsm->colorValueIntegers(); else fsm->clearNumberStacks(); }; ( number space+ number space+ number ) { if (configuration.int_values) fsm->colorValueIntegers(); else fsm->clearNumberStacks(); }; ( real_number space* ',' space* real_number space* ',' space* real_number ) { if (configuration.float_values) fsm->colorValues(); else fsm->clearNumberStacks(); }; ( '//' ) { if (configuration.single_line_c_comments) fgoto single_line_comment; }; ( '/*' ) { if (configuration.multi_line_c_comments) fgoto multi_line_comment; }; ( '#' ) { if (configuration.single_line_hash_comments) fgoto single_line_comment; }; ( space+ ) { }; ( punct+ ) { }; ( (any - (newline | space | punct | '//' | '/*'))+ ) { }; ( newline ) { }; *|; }%% %% write data; bool scanner(TextFile &text_file, const Configuration &configuration) { FSM fsm_struct; FSM *fsm = &fsm_struct; fsm->ts = 0; fsm->te = 0; fsm->line = 0; fsm->line_start = 0; fsm->column = 0; fsm->buffer_offset = 0; bool parse_error = false; fsm->addColor = [&text_file](const Color &color){ Color c = color; color_rgb_normalize(&c); text_file.addColor(c); }; %% write init; int have = 0; while (1){ char *p = fsm->buffer + have; int space = sizeof(fsm->buffer) - have; if (space == 0){ text_file.outOfMemory(); break; } char *eof = 0; auto read_size = text_file.read(fsm->buffer + have, space); char *pe = p + read_size; if (read_size > 0){ if (read_size < sizeof(fsm->buffer)) eof = pe; %% write exec; if (fsm->cs == text_file_error) { parse_error = true; text_file.syntaxError(fsm->line, fsm->ts - fsm->buffer - fsm->line_start, fsm->line, fsm->te - fsm->buffer - fsm->line_start); break; } if (fsm->ts == 0){ have = 0; fsm->line_start -= sizeof(fsm->buffer); }else{ have = pe - fsm->ts; memmove(fsm->buffer, fsm->ts, have); int buffer_movement = fsm->ts - fsm->buffer; fsm->te -= buffer_movement; fsm->line_start -= buffer_movement; fsm->ts = fsm->buffer; fsm->buffer_offset += fsm->ts - fsm->buffer; } }else{ break; } } return parse_error == false; } } gpick-gpick-0.2.6rc1/source/test/000077500000000000000000000000001315430016700165745ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/source/test/DynvTest.cpp000066400000000000000000000100251315430016700210560ustar00rootroot00000000000000#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE dynv #include #include #include #include "dynv/DynvSystem.h" #include "dynv/DynvXml.h" #include "dynv/DynvVarString.h" #include "dynv/DynvVarInt32.h" #include "dynv/DynvVarColor.h" #include "dynv/DynvVarFloat.h" #include "dynv/DynvVarDynv.h" #include "dynv/DynvVarBool.h" #include "dynv/DynvVarPtr.h" using namespace std; static dynvSystem* buildDynv() { auto handler_map = dynv_handler_map_create(); dynv_handler_map_add_handler(handler_map, dynv_var_string_new()); dynv_handler_map_add_handler(handler_map, dynv_var_int32_new()); dynv_handler_map_add_handler(handler_map, dynv_var_color_new()); dynv_handler_map_add_handler(handler_map, dynv_var_ptr_new()); dynv_handler_map_add_handler(handler_map, dynv_var_float_new()); dynv_handler_map_add_handler(handler_map, dynv_var_dynv_new()); dynv_handler_map_add_handler(handler_map, dynv_var_bool_new()); auto dynv = dynv_system_create(handler_map); dynv_handler_map_release(handler_map); return dynv; } BOOST_AUTO_TEST_CASE(xml_deserialization) { auto dynv = buildDynv(); ifstream file("test/config01.xml"); BOOST_CHECK(file.is_open()); if (file.is_open()){ BOOST_CHECK(dynv_xml_deserialize(dynv, file) == 0); file.close(); } const char *data[] = {"a", "b", "c"}; int error; uint32_t count; char** values = (char**)dynv_get_array(dynv, "string", "test", &count, &error); BOOST_CHECK(error == 0); BOOST_CHECK(values != nullptr); BOOST_CHECK(count == 3); for (int i = 0; i < 3; i++){ string value(data[i]); BOOST_CHECK(value == values[i]); } delete [] values; BOOST_CHECK(dynv_system_release(dynv) == 0); } BOOST_AUTO_TEST_CASE(string_array) { auto dynv = buildDynv(); const char *data[] = {"a", "b", "c"}; dynv_set_array(dynv, "string", "a", (const void**)data, 3); int error; uint32_t count; char** values = (char**)dynv_get_array(dynv, "string", "a", &count, &error); BOOST_CHECK(error == 0); BOOST_CHECK(values != nullptr); BOOST_CHECK(count == 3); for (int i = 0; i < 3; i++){ string value(data[i]); BOOST_CHECK(value == values[i]); } delete [] values; BOOST_CHECK(dynv_system_release(dynv) == 0); } BOOST_AUTO_TEST_CASE(string_array_overwrite) { auto dynv = buildDynv(); const char *data[] = {"a", "b", "c"}; dynv_set_array(dynv, "string", "a", (const void**)data, 3); dynv_set_array(dynv, "string", "a", (const void**)data, 3); int error; uint32_t count; char** values = (char**)dynv_get_array(dynv, "string", "a", &count, &error); BOOST_CHECK(error == 0); BOOST_CHECK(values != nullptr); BOOST_CHECK(count == 3); for (int i = 0; i < 3; i++){ string value(data[i]); BOOST_CHECK(value == values[i]); } delete [] values; BOOST_CHECK(dynv_system_release(dynv) == 0); } BOOST_AUTO_TEST_CASE(dynv_array) { auto dynv = buildDynv(); dynvSystem *data[] = {dynv_system_create(dynv), dynv_system_create(dynv), dynv_system_create(dynv)}; dynv_set_array(dynv, "dynv", "a", (const void**)data, 3); int error; uint32_t count; dynvSystem** values = (dynvSystem**)dynv_get_array(dynv, "dynv", "a", &count, &error); BOOST_CHECK(error == 0); BOOST_CHECK(values != nullptr); BOOST_CHECK(count == 3); for (int i = 0; i < 3; i++){ BOOST_CHECK(values[i] == data[i]); BOOST_CHECK(dynv_system_release(values[i]) == -1); } for (int i = 0; i < 3; i++){ BOOST_CHECK(dynv_system_release(data[i]) == -1); } delete [] values; BOOST_CHECK(dynv_system_release(dynv) == 0); } BOOST_AUTO_TEST_CASE(dynv_array_null) { auto dynv = buildDynv(); dynvSystem *data[] = {dynv_system_create(dynv), dynv_system_create(dynv), dynv_system_create(dynv)}; dynv_set_array(dynv, "dynv", "a", (const void**)data, 3); dynv_set_array(dynv, "dynv", "a", nullptr, 0); int error; uint32_t count; dynvSystem** values = (dynvSystem**)dynv_get_array(dynv, "dynv", "a", &count, &error); BOOST_CHECK(error != 0); BOOST_CHECK(values == nullptr); BOOST_CHECK(count == 0); for (int i = 0; i < 3; i++){ BOOST_CHECK(dynv_system_release(data[i]) == 0); } delete [] values; BOOST_CHECK(dynv_system_release(dynv) == 0); }gpick-gpick-0.2.6rc1/source/test/TextFileTest.cpp000066400000000000000000000076311315430016700216730ustar00rootroot00000000000000#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE text_file #include #include #include #include #include "parser/TextFile.h" #include "Color.h" using namespace std; class TextFile: public text_file_parser::TextFile { public: istream *m_stream; vector m_colors; bool m_failed; TextFile(istream *stream) { m_stream = stream; m_failed = false; } virtual ~TextFile() { } virtual void outOfMemory() { m_failed = true; } virtual void syntaxError(size_t start_line, size_t start_column, size_t end_line, size_t end_colunn) { m_failed = true; } virtual size_t read(char *buffer, size_t length) { m_stream->read(buffer, length); size_t bytes = m_stream->gcount(); if (bytes > 0) return bytes; if (m_stream->eof()) return 0; if (!m_stream->good()){ m_failed = true; } return 0; } virtual void addColor(const Color &color) { m_colors.push_back(color); } size_t count() { return m_colors.size(); } bool checkColor(size_t index, const Color &color) { return color_equal(&m_colors[index], &color); } void parse() { text_file_parser::Configuration configuration; text_file_parser::TextFile::parse(configuration); } }; BOOST_AUTO_TEST_CASE(full_hex) { ifstream file("test/textImport01.txt"); BOOST_CHECK(file.is_open()); TextFile parser(&file); parser.parse(); BOOST_CHECK(parser.count() == 1); Color color; color_set(&color, 0xaa, 0xbb, 0xcc); BOOST_CHECK(parser.checkColor(0, color)); file.close(); } BOOST_AUTO_TEST_CASE(short_hex) { ifstream file("test/textImport02.txt"); BOOST_CHECK(file.is_open()); TextFile parser(&file); parser.parse(); BOOST_CHECK(parser.count() == 1); Color color; color_set(&color, 0xaa, 0xbb, 0xcc); BOOST_CHECK(parser.checkColor(0, color)); file.close(); } BOOST_AUTO_TEST_CASE(css_rgb) { ifstream file("test/textImport03.txt"); BOOST_CHECK(file.is_open()); TextFile parser(&file); parser.parse(); BOOST_CHECK(parser.count() == 1); Color color; color_set(&color, 0xaa, 0xbb, 0xcc); BOOST_CHECK(parser.checkColor(0, color)); file.close(); } BOOST_AUTO_TEST_CASE(css_rgba) { ifstream file("test/textImport04.txt"); BOOST_CHECK(file.is_open()); TextFile parser(&file); parser.parse(); BOOST_CHECK(parser.count() == 1); Color color; color_set(&color, 0xaa, 0xbb, 0xcc); color.ma[3] = 0.5; BOOST_CHECK(parser.checkColor(0, color)); file.close(); } BOOST_AUTO_TEST_CASE(int_values) { ifstream file("test/textImport05.txt"); BOOST_CHECK(file.is_open()); TextFile parser(&file); parser.parse(); BOOST_CHECK(parser.count() == 1); Color color; color_set(&color, 0xaa, 0xbb, 0xcc); BOOST_CHECK(parser.checkColor(0, color)); file.close(); } BOOST_AUTO_TEST_CASE(float_values) { ifstream file("test/textImport06.txt"); BOOST_CHECK(file.is_open()); TextFile parser(&file); parser.parse(); BOOST_CHECK(parser.count() == 1); Color color; color_set(&color, 0xaa, 0xbb, 0xcc); BOOST_CHECK(parser.checkColor(0, color)); file.close(); } BOOST_AUTO_TEST_CASE(single_line_c_comments) { ifstream file("test/textImport07.txt"); BOOST_CHECK(file.is_open()); TextFile parser(&file); parser.parse(); BOOST_CHECK(parser.count() == 1); Color color; color_set(&color, 0xaa, 0xbb, 0xcc); BOOST_CHECK(parser.checkColor(0, color)); file.close(); } BOOST_AUTO_TEST_CASE(multi_line_c_comments) { ifstream file("test/textImport08.txt"); BOOST_CHECK(file.is_open()); TextFile parser(&file); parser.parse(); BOOST_CHECK(parser.count() == 1); Color color; color_set(&color, 0xaa, 0xbb, 0xcc); BOOST_CHECK(parser.checkColor(0, color)); file.close(); } BOOST_AUTO_TEST_CASE(single_line_hash_comments) { ifstream file("test/textImport09.txt"); BOOST_CHECK(file.is_open()); TextFile parser(&file); parser.parse(); BOOST_CHECK(parser.count() == 1); Color color; color_set(&color, 0xaa, 0xbb, 0xcc); BOOST_CHECK(parser.checkColor(0, color)); file.close(); } gpick-gpick-0.2.6rc1/source/tools/000077500000000000000000000000001315430016700167555ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/source/tools/ColorSpaceSampler.cpp000066400000000000000000000313421315430016700230420ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ColorSpaceSampler.h" #include "../ColorList.h" #include "../ColorObject.h" #include "../GlobalState.h" #include "../Internationalisation.h" #include "../DynvHelpers.h" #include "../uiListPalette.h" #include "../uiUtilities.h" #include "../ToolColorNaming.h" #include #include using namespace std; #define N_AXIS 3 typedef struct AxisOptions { GtkWidget *range_samples; GtkWidget *range_min_value; GtkWidget *range_max_value; GtkWidget *toggle_include_max_value; int samples; float min_value; float max_value; bool include_max_value; }AxisOptions; typedef struct ColorSpaceSamplerArgs { GtkWidget *combo_color_space; GtkWidget *toggle_linearization; int color_space; bool linearization; AxisOptions axis[N_AXIS]; GtkWidget *preview_expander; ColorList *color_list; ColorList *preview_color_list; struct dynvSystem *params; GlobalState* gs; }ColorSpaceSamplerArgs; class ColorSpaceSamplerNameAssigner: public ToolColorNameAssigner { protected: stringstream m_stream; public: ColorSpaceSamplerNameAssigner(GlobalState *gs): ToolColorNameAssigner(gs) { } void assign(ColorObject *color_object, const Color *color) { ToolColorNameAssigner::assign(color_object, color); } virtual std::string getToolSpecificName(ColorObject *color_object, const Color *color) { m_stream.str(""); m_stream << _("color space"); return m_stream.str(); } }; static void calc(ColorSpaceSamplerArgs *args, bool preview, size_t limit) { ColorSpaceSamplerNameAssigner name_assigner(args->gs); ColorList *color_list; if (preview) color_list = args->preview_color_list; else color_list = args->gs->getColorList(); vector values; size_t value_count = args->axis[0].samples * args->axis[1].samples * args->axis[2].samples; if (preview) value_count = std::min(limit, value_count); values.resize(value_count); size_t value_i = 0; for (int x = 0; x < args->axis[0].samples; x++){ float x_value = (args->axis[0].samples > 1) ? (args->axis[0].min_value + (args->axis[0].max_value - args->axis[0].min_value) * (x / (double)(args->axis[0].samples - 1))) : args->axis[0].min_value; for (int y = 0; y < args->axis[1].samples; y++){ float y_value = (args->axis[1].samples > 1) ? (args->axis[1].min_value + (args->axis[1].max_value - args->axis[1].min_value) * (y / (double)(args->axis[1].samples - 1))) : args->axis[1].min_value; for (int z = 0; z < args->axis[2].samples; z++){ float z_value = (args->axis[2].samples > 1) ? (args->axis[2].min_value + (args->axis[2].max_value - args->axis[2].min_value) * (z / (double)(args->axis[2].samples - 1))) : args->axis[2].min_value; values[value_i].ma[0] = x_value; values[value_i].ma[1] = y_value; values[value_i].ma[2] = z_value; value_i++; if (preview && value_i >= limit){ x = args->axis[0].samples; y = args->axis[1].samples; break; } } } } Color t; for (size_t i = 0; i < value_count; i++){ if (preview){ if (limit <= 0) return; limit--; } switch (args->color_space){ case 0: color_copy(&values[i], &t); break; case 1: color_hsv_to_rgb(&values[i], &t); break; case 2: color_hsl_to_rgb(&values[i], &t); break; case 3: color_copy(&values[i], &t); t.lab.L *= 100; t.lab.a = (t.lab.a - 0.5) * 290; t.lab.b = (t.lab.b - 0.5) * 290; color_lab_to_rgb_d50(&t, &t); break; case 4: color_copy(&values[i], &t); t.lch.L *= 100; t.lch.C *= 136; t.lch.h *= 360; color_lch_to_rgb_d50(&t, &t); break; } if (args->linearization) color_linear_get_rgb(&t, &t); color_rgb_normalize(&t); ColorObject *color_object = color_list_new_color_object(color_list, &t); name_assigner.assign(color_object, &t); color_list_add_color_object(color_list, color_object, 1); color_object->release(); } } static void destroy_cb(GtkWidget* widget, ColorSpaceSamplerArgs *args) { color_list_destroy(args->preview_color_list); dynv_system_release(args->params); delete args; } static void get_settings(ColorSpaceSamplerArgs *args) { args->color_space = gtk_combo_box_get_active(GTK_COMBO_BOX(args->combo_color_space)); args->linearization = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->toggle_linearization)); for (int i = 0; i < N_AXIS; i++){ args->axis[i].samples = gtk_spin_button_get_value(GTK_SPIN_BUTTON(args->axis[i].range_samples)); args->axis[i].min_value = gtk_spin_button_get_value(GTK_SPIN_BUTTON(args->axis[i].range_min_value)); args->axis[i].max_value = gtk_spin_button_get_value(GTK_SPIN_BUTTON(args->axis[i].range_max_value)); } } static dynvSystem* get_axis_config(int axis, ColorSpaceSamplerArgs *args) { stringstream config_name; config_name << "axis" << axis; string config_name_string = config_name.str(); return dynv_get_dynv(args->params, config_name_string.c_str()); } static void save_settings(ColorSpaceSamplerArgs *args) { dynv_set_int32(args->params, "color_space", args->color_space); dynv_set_bool(args->params, "linearization", args->linearization); for (int i = 0; i < N_AXIS; i++){ dynvSystem *axis_config = get_axis_config(i, args); dynv_set_int32(axis_config, "samples", args->axis[i].samples); dynv_set_float(axis_config, "min_value", args->axis[i].min_value); dynv_set_float(axis_config, "max_value", args->axis[i].max_value); dynv_system_release(axis_config); } } static void update(GtkWidget *widget, ColorSpaceSamplerArgs *args) { color_list_remove_all(args->preview_color_list); get_settings(args); calc(args, true, 100); } static void response_cb(GtkWidget* widget, gint response_id, ColorSpaceSamplerArgs *args) { get_settings(args); save_settings(args); gint width, height; gtk_window_get_size(GTK_WINDOW(widget), &width, &height); dynv_set_int32(args->params, "window.width", width); dynv_set_int32(args->params, "window.height", height); dynv_set_bool(args->params, "show_preview", gtk_expander_get_expanded(GTK_EXPANDER(args->preview_expander))); switch (response_id){ case GTK_RESPONSE_APPLY: calc(args, false, 0); break; case GTK_RESPONSE_DELETE_EVENT: break; case GTK_RESPONSE_CLOSE: gtk_widget_destroy(widget); break; } } void tools_color_space_sampler_show(GtkWindow* parent, GlobalState* gs) { ColorSpaceSamplerArgs *args = new ColorSpaceSamplerArgs; args->gs = gs; args->params = dynv_get_dynv(args->gs->getSettings(), "gpick.tools.color_space_sampler"); int table_m_y; GtkWidget *table, *table_m, *widget; GtkWidget *dialog = gtk_dialog_new_with_buttons(_("Color space sampler"), parent, GtkDialogFlags(GTK_DIALOG_DESTROY_WITH_PARENT), GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE, GTK_STOCK_ADD, GTK_RESPONSE_APPLY, nullptr); gtk_window_set_default_size(GTK_WINDOW(dialog), dynv_get_int32_wd(args->params, "window.width", -1), dynv_get_int32_wd(args->params, "window.height", -1)); gtk_dialog_set_alternative_button_order(GTK_DIALOG(dialog), GTK_RESPONSE_APPLY, GTK_RESPONSE_CLOSE, -1); table_m = gtk_table_new(3, 1, FALSE); table_m_y = 0; int table_y; table = gtk_table_new(7, 3, FALSE); gtk_table_attach(GTK_TABLE(table_m), table, 0, 1, table_m_y, table_m_y+1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL), 5, 5); table_m_y++; table_y = 0; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Color space:")), 0, 1, table_y, table_y + 1, GtkAttachOptions(GTK_FILL), GTK_FILL, 5, 5); args->combo_color_space = widget = gtk_combo_box_text_new(); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(widget), _("RGB")); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(widget), _("HSV")); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(widget), _("HSL")); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(widget), _("LAB")); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(widget), _("LCH")); gtk_combo_box_set_active(GTK_COMBO_BOX(widget), dynv_get_int32_wd(args->params, "color_space", 0)); gtk_table_attach(GTK_TABLE(table), widget, 1, 2, table_y, table_y + 1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GTK_FILL, 5, 0); g_signal_connect(G_OBJECT(widget), "changed", G_CALLBACK(update), args); table_y++; args->toggle_linearization = gtk_check_button_new_with_mnemonic(_("_Linearization")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(args->toggle_linearization), dynv_get_bool_wd(args->params, "linearization", false)); gtk_table_attach(GTK_TABLE(table), args->toggle_linearization,1,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); g_signal_connect(G_OBJECT(args->toggle_linearization), "toggled", G_CALLBACK(update), args); table_y++; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Sample count")), 1, 3, table_y, table_y + 1, GtkAttachOptions(GTK_FILL), GTK_FILL, 5, 5); gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Minimal value")), 3, 5, table_y, table_y + 1, GtkAttachOptions(GTK_FILL), GTK_FILL, 5, 5); gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Maximal value")), 5, 7, table_y, table_y + 1, GtkAttachOptions(GTK_FILL), GTK_FILL, 5, 5); table_y++; const char *axis_names[] = { _("X axis"), _("Y axis"), _("Z axis"), }; for (int i = 0; i < N_AXIS; i++){ string axis_name = string(axis_names[i]) + ":"; dynvSystem *axis_config = get_axis_config(i, args); gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(axis_name.c_str()), 0, 1, table_y, table_y + 1, GtkAttachOptions(GTK_FILL), GTK_FILL, 5, 5); args->axis[i].range_samples = widget = gtk_spin_button_new_with_range(1, 255, 1); gtk_spin_button_set_value(GTK_SPIN_BUTTON(widget), dynv_get_int32_wd(axis_config, "samples", 12)); gtk_table_attach(GTK_TABLE(table), widget, 1, 3, table_y, table_y + 1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL, 3, 3); g_signal_connect(G_OBJECT(widget), "value-changed", G_CALLBACK(update), args); args->axis[i].range_min_value = widget = gtk_spin_button_new_with_range(0, 1, 0.001); gtk_spin_button_set_value(GTK_SPIN_BUTTON(widget), dynv_get_float_wd(axis_config, "min_value", 0)); gtk_table_attach(GTK_TABLE(table), widget, 3, 5, table_y, table_y + 1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL, 3, 3); g_signal_connect(G_OBJECT(widget), "value-changed", G_CALLBACK(update), args); args->axis[i].range_max_value = widget = gtk_spin_button_new_with_range(0, 1, 0.001); gtk_spin_button_set_value(GTK_SPIN_BUTTON(widget), dynv_get_float_wd(axis_config, "max_value", 1)); gtk_table_attach(GTK_TABLE(table), widget, 5, 7, table_y, table_y + 1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL, 3, 3); g_signal_connect(G_OBJECT(widget), "value-changed", G_CALLBACK(update), args); table_y++; dynv_system_release(axis_config); } ColorList* preview_color_list = nullptr; gtk_table_attach(GTK_TABLE(table_m), args->preview_expander = palette_list_preview_new(gs, true, dynv_get_bool_wd(args->params, "show_preview", true), gs->getColorList(), &preview_color_list), 0, 1, table_m_y, table_m_y+1 , GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL | GTK_EXPAND), 5, 5); table_m_y++; args->preview_color_list = preview_color_list; get_settings(args); calc(args, true, 100); gtk_widget_show_all(table_m); gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), table_m); g_signal_connect(G_OBJECT(dialog), "destroy", G_CALLBACK(destroy_cb), args); g_signal_connect(G_OBJECT(dialog), "response", G_CALLBACK(response_cb), args); gtk_widget_show(dialog); } gpick-gpick-0.2.6rc1/source/tools/ColorSpaceSampler.h000066400000000000000000000034111315430016700225030ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_TOOLS_COLOR_SPACE_SAMPLER_H_ #define GPICK_TOOLS_COLOR_SPACE_SAMPLER_H_ class GlobalState; #include void tools_color_space_sampler_show(GtkWindow* parent, GlobalState* gs); #endif /* GPICK_TOOLS_COLOR_SPACE_SAMPLER_H_ */ gpick-gpick-0.2.6rc1/source/tools/PaletteFromCssFile.cpp000066400000000000000000000035701315430016700231610ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "PaletteFromCssFile.h" /*#include "../uiUtilities.h" #include "../uiListPalette.h" #include "../GlobalStateStruct.h" #include "../DynvHelpers.h" */ using namespace std; int parse_file(const char *filename); void tools_palette_from_css_file_show(GtkWindow* parent, GlobalState* gs) { #ifdef EXPERIMENTAL_CSS_PARSER parse_file("test.css"); #endif } gpick-gpick-0.2.6rc1/source/tools/PaletteFromCssFile.h000066400000000000000000000034211315430016700226210ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_TOOLS_PALETTE_FROM_CSS_FILE_H_ #define GPICK_TOOLS_PALETTE_FROM_CSS_FILE_H_ class GlobalState; #include void tools_palette_from_css_file_show(GtkWindow* parent, GlobalState* gs); #endif /* GPICK_TOOLS_PALETTE_FROM_CSS_FILE_H_ */ gpick-gpick-0.2.6rc1/source/tools/PaletteFromImage.cpp000066400000000000000000000441551315430016700226570ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "PaletteFromImage.h" #include "../ColorList.h" #include "../ColorObject.h" #include "../uiUtilities.h" #include "../uiListPalette.h" #include "../GlobalState.h" #include "../ToolColorNaming.h" #include "../DynvHelpers.h" #include "../Internationalisation.h" #include #include #include #include #include using namespace std; /** \file PaletteFromImage.cpp * \brief */ /** \struct Node * \brief Node is a cube in space with color information * * Each node can b */ typedef struct Node{ uint32_t n_pixels; /**< Number of colors in current Node and its children */ uint32_t n_pixels_in; /**< Number of colors in current Node */ float color[3]; /**< Sum of color values */ float distance; /**< Squared distances from Node center of colors in Node */ Node *child[8]; /**< Pointers to child Nodes */ Node *parent; /**< Pointer to parent Node */ }Node; /** \struct Cube * \brief Cube structure holds all information necessary to define cube size and position in space */ typedef struct Cube{ float x; /**< X position */ float w; /**< Width */ float y; /**< Y position */ float h; /**< Height */ float z; /**< Z position */ float d; /**< Depth */ }Cube; typedef struct PaletteFromImageArgs{ GtkWidget *file_browser; GtkWidget *range_colors; GtkWidget *merge_threshold; GtkWidget *preview_expander; string filename; uint32_t n_colors; string previous_filename; Node *previous_node; ColorList *color_list; ColorList *preview_color_list; struct dynvSystem *params; GlobalState* gs; }PaletteFromImageArgs; class PaletteColorNameAssigner: public ToolColorNameAssigner { protected: stringstream m_stream; const char *m_filename; int m_index; public: PaletteColorNameAssigner(GlobalState *gs): ToolColorNameAssigner(gs) { m_index = 0; } void assign(ColorObject *color_object, const Color *color, const char *filename, const int index) { m_filename = filename; m_index = index; ToolColorNameAssigner::assign(color_object, color); } virtual std::string getToolSpecificName(ColorObject *color_object, const Color *color) { m_stream.str(""); m_stream << m_filename << " #" << m_index; return m_stream.str(); } }; /** * Allocate and initialize a new node with specified parent * @param[in] parent Parent node * @return New node */ static Node* node_new(Node *parent){ Node *n = new Node; n->color[0] = n->color[1] = n->color[2] = 0; n->distance = 0; n->n_pixels = 0; n->n_pixels_in = 0; n->parent = parent; for (int i = 0; i < 8; i++){ n->child[i] = 0; } return n; } /** * Deallocate node and its children * @param[in] node Node to deallocate */ static void node_delete(Node *node){ for (int i = 0; i < 8; i++){ if (node->child[i]){ node_delete(node->child[i]); } } delete node; } /** * Copy node and assing new parent * @param[in] node Node to copy * @param[in] parent Parent of copied node * @return A copy of node */ static Node* node_copy(Node *node, Node *parent){ Node *n = node_new(0); memcpy(n, node, sizeof(Node)); n->parent = parent; for (int i = 0; i < 8; i++){ if (node->child[i]){ n->child[i] = node_copy(node->child[i], n); }else{ n->child[i] = 0; } } return n; } /** * Get the number of nodes with available color information in them * @param[in] node Start from this node * @return Number of nodes with available color information in them */ static uint32_t node_count_leafs(Node *node){ uint32_t r = 0; if (node->n_pixels_in) r++; for (int i = 0; i < 8; i++){ if (node->child[i]) r += node_count_leafs(node->child[i]); } return r; } /** * Call callback on all nodes with available color information in them * @param[in] node Start from this node * @param[in] leaf_cb Callback function * @param[in] userdata User supplied pointer which is passed when calling callback */ static void node_leaf_callback(Node *node, void (*leaf_cb)(Node* node, void* userdata), void* userdata){ if (node->n_pixels_in > 0) leaf_cb(node, userdata); for (int i = 0; i < 8; i++){ if (node->child[i]) node_leaf_callback(node->child[i], leaf_cb, userdata); } } /** * Merge node information into its parent node * @param[in] node Node to merge */ static void node_prune(Node *node){ for (int i = 0; i < 8; i++){ if (node->child[i]){ node_prune(node->child[i]); node->child[i] = 0; } } if (node->parent){ node->parent->n_pixels_in += node->n_pixels_in; node->parent->color[0] += node->color[0]; node->parent->color[1] += node->color[1]; node->parent->color[2] += node->color[2]; } node_delete(node); } typedef struct PruneData{ float threshold; float min_distance; uint32_t n_colors; uint32_t n_colors_target; Node *prune_node; uint32_t distant_nodes; }PruneData; static bool node_prune_threshold(Node *node, PruneData *prune_data){ if (node->distance <= prune_data->threshold){ uint32_t colors_removed = node_count_leafs(node); node_prune(node); prune_data->n_colors -= colors_removed; return true; } if (node->distance < prune_data->min_distance){ prune_data->min_distance = node->distance; } uint32_t n = node->n_pixels_in; for (int i = 0; i < 8; i++){ if (node->child[i]){ if (node_prune_threshold(node->child[i], prune_data)){ node->child[i] = 0; } } } if (node->n_pixels_in > 0 && n == 0) prune_data->n_colors++; return false; } static void node_reduce(Node *node, uint32_t colors){ PruneData prune_data; prune_data.n_colors = node_count_leafs(node); prune_data.n_colors_target = colors; prune_data.threshold = 0; while (prune_data.n_colors > colors){ prune_data.min_distance = node->distance; if (node_prune_threshold(node, &prune_data)) break; prune_data.threshold = prune_data.min_distance; } } static void node_update(Node *node, Color *color, Cube *cube, uint32_t max_depth){ Cube new_cube; new_cube.w = cube->w / 2; new_cube.h = cube->h / 2; new_cube.d = cube->d / 2; node->n_pixels++; node->distance += (color->xyz.x - (cube->x + new_cube.w)) * (color->xyz.x - (cube->x + new_cube.w)) + (color->xyz.y - (cube->y + new_cube.h)) * (color->xyz.y - (cube->y + new_cube.h)) + (color->xyz.z - (cube->z + new_cube.d)) * (color->xyz.z - (cube->z + new_cube.d)); if (!max_depth){ node->n_pixels_in++; node->color[0] += color->xyz.x; node->color[1] += color->xyz.y; node->color[2] += color->xyz.z; }else{ int x, y, z; if (color->xyz.x - cube->x < new_cube.w) x = 0; else x = 1; if (color->xyz.y - cube->y < new_cube.h) y = 0; else y = 1; if (color->xyz.z - cube->z < new_cube.d) z = 0; else z = 1; new_cube.x = cube->x + new_cube.w * x; new_cube.y = cube->y + new_cube.h * y; new_cube.z = cube->z + new_cube.d * z; int i = x | (y<<1) | (z<<2); if (!node->child[i]) node->child[i] = node_new(node); node->n_pixels++; node_update(node->child[x | (y<<1) | (z<<2)], color, &new_cube, max_depth - 1); } } static void leaf_cb(Node *node, void *userdata){ list *l = static_cast*>(userdata); Color c; c.xyz.x = node->color[0] / node->n_pixels_in; c.xyz.y = node->color[1] / node->n_pixels_in; c.xyz.z = node->color[2] / node->n_pixels_in; l->push_back(c); } static Node* process_image(PaletteFromImageArgs *args, const char *filename, Node* node){ if (args->previous_filename == filename){ if (args->previous_node) return node_copy(args->previous_node, 0); else return 0; } args->previous_filename = filename; if (args->previous_node){ node_delete(args->previous_node); args->previous_node = 0; } GError *error = nullptr; GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file(filename, &error); if (error){ cout << error->message << endl; g_error_free(error); return 0; } int channels = gdk_pixbuf_get_n_channels(pixbuf); int width = gdk_pixbuf_get_width(pixbuf); int height = gdk_pixbuf_get_height(pixbuf); int rowstride = gdk_pixbuf_get_rowstride(pixbuf); guchar *image_data = gdk_pixbuf_get_pixels(pixbuf); guchar *ptr = image_data; Cube cube; cube.x = 0; cube.y = 0; cube.z = 0; cube.w = 1; cube.h = 1; cube.d = 1; Color color; args->previous_node = node_new(0); for (int y = 0; y < height; y++){ ptr = image_data + rowstride * y; for (int x = 0; x < width; x++){ color.xyz.x = ptr[0] / 255.0; color.xyz.y = ptr[1] / 255.0; color.xyz.z = ptr[2] / 255.0; node_update(args->previous_node, &color, &cube, 5); ptr += channels; } } g_object_unref(pixbuf); node_reduce(args->previous_node, 200); return node_copy(args->previous_node, 0); } static void get_settings(PaletteFromImageArgs *args){ gchar *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(args->file_browser)); if (filename){ args->filename = filename; g_free(filename); }else{ args->filename.clear(); } args->n_colors = gtk_spin_button_get_value(GTK_SPIN_BUTTON(args->range_colors)); } static void save_settings(PaletteFromImageArgs *args){ dynv_set_int32(args->params, "colors", args->n_colors); gchar *current_folder = gtk_file_chooser_get_current_folder(GTK_FILE_CHOOSER(args->file_browser)); if (current_folder){ dynv_set_string(args->params, "current_folder", current_folder); g_free(current_folder); } GtkFileFilter *filter = gtk_file_chooser_get_filter(GTK_FILE_CHOOSER(args->file_browser)); if (filter){ const char *filter_name = static_cast(g_object_get_data(G_OBJECT(filter), "name")); dynv_set_string(args->params, "filter", filter_name); } } static void calc(PaletteFromImageArgs *args, bool preview, int limit){ Node *root_node = 0; int index = 0; gchar *name = g_path_get_basename(args->filename.c_str()); PaletteColorNameAssigner name_assigner(args->gs); if (!args->filename.empty()) root_node = process_image(args, args->filename.c_str(), root_node); ColorList *color_list; if (preview) color_list = args->preview_color_list; else color_list = args->gs->getColorList(); list tmp_list; if (root_node){ node_reduce(root_node, args->n_colors); node_leaf_callback(root_node, leaf_cb, &tmp_list); node_delete(root_node); } for (list::iterator i = tmp_list.begin(); i != tmp_list.end(); i++){ ColorObject *color_object = color_list_new_color_object(color_list, &(*i)); name_assigner.assign(color_object, &(*i), name, index); color_list_add_color_object(color_list, color_object, 1); color_object->release(); index++; } } static void update(GtkWidget *widget, PaletteFromImageArgs *args ){ color_list_remove_all(args->preview_color_list); get_settings(args); calc(args, true, 100); } static gchar* format_threshold_value_cb(GtkScale *scale, gdouble value){ return g_strdup_printf("%0.01f%%", value); } static void destroy_cb(GtkWidget* widget, PaletteFromImageArgs *args){ if (args->previous_node) node_delete(args->previous_node); color_list_destroy(args->preview_color_list); dynv_system_release(args->params); delete args; } static void response_cb(GtkWidget* widget, gint response_id, PaletteFromImageArgs *args){ get_settings(args); save_settings(args); gint width, height; gtk_window_get_size(GTK_WINDOW(widget), &width, &height); dynv_set_int32(args->params, "window.width", width); dynv_set_int32(args->params, "window.height", height); dynv_set_bool(args->params, "show_preview", gtk_expander_get_expanded(GTK_EXPANDER(args->preview_expander))); switch (response_id){ case GTK_RESPONSE_APPLY: calc(args, false, 0); break; case GTK_RESPONSE_DELETE_EVENT: break; case GTK_RESPONSE_CLOSE: gtk_widget_destroy(widget); break; } } void tools_palette_from_image_show(GtkWindow* parent, GlobalState* gs) { PaletteFromImageArgs *args = new PaletteFromImageArgs; args->previous_filename = ""; args->gs = gs; args->params = dynv_get_dynv(args->gs->getSettings(), "gpick.tools.palette_from_image"); args->previous_node = 0; GtkWidget *table, *table_m, *widget; GtkWidget *dialog = gtk_dialog_new_with_buttons(_("Palette from image"), parent, GtkDialogFlags(GTK_DIALOG_DESTROY_WITH_PARENT), GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE, GTK_STOCK_ADD, GTK_RESPONSE_APPLY, nullptr); gtk_window_set_default_size(GTK_WINDOW(dialog), dynv_get_int32_wd(args->params, "window.width", -1), dynv_get_int32_wd(args->params, "window.height", -1)); gtk_dialog_set_alternative_button_order(GTK_DIALOG(dialog), GTK_RESPONSE_APPLY, GTK_RESPONSE_CLOSE, -1); GtkWidget *frame; gint table_y, table_m_y; table_m = gtk_table_new(3, 1, FALSE); table_m_y = 0; frame = gtk_frame_new(_("Image")); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_NONE); gtk_table_attach(GTK_TABLE(table_m), frame, 0, 1, table_m_y, table_m_y+1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL), 5, 5); table_m_y++; table = gtk_table_new(5, 3, FALSE); table_y=0; gtk_container_add(GTK_CONTAINER(frame), table); args->file_browser = widget = gtk_file_chooser_button_new(_("Image file"), GTK_FILE_CHOOSER_ACTION_OPEN); gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(widget), dynv_get_string_wd(args->params, "current_folder", "")); gtk_table_attach(GTK_TABLE(table), widget, 0, 3, table_y, table_y+1, GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,3,3); g_signal_connect(G_OBJECT(args->file_browser), "file-set", G_CALLBACK(update), args); table_y++; const char* selected_filter = dynv_get_string_wd(args->params, "filter", "all_images"); GtkFileFilter *filter; GtkFileFilter *all_image_filter; filter = gtk_file_filter_new(); gtk_file_filter_set_name(filter, _("All files")); gtk_file_filter_add_pattern(filter, "*"); g_object_set_data_full(G_OBJECT(filter), "name", (void*)"all_files", GDestroyNotify(nullptr)); gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(widget), filter); if (g_strcmp0("all_files", selected_filter) == 0) gtk_file_chooser_set_filter(GTK_FILE_CHOOSER(widget), filter); all_image_filter = gtk_file_filter_new(); gtk_file_filter_set_name(all_image_filter, _("All images")); g_object_set_data_full(G_OBJECT(all_image_filter), "name", (void*)"all_images", GDestroyNotify(nullptr)); gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(widget), all_image_filter); if (g_strcmp0("all_images", selected_filter) == 0) gtk_file_chooser_set_filter(GTK_FILE_CHOOSER(widget), all_image_filter); stringstream ss; GSList *formats = gdk_pixbuf_get_formats(); GSList *i = formats; while (i){ GdkPixbufFormat *format = static_cast(g_slist_nth_data(i, 0)); filter = gtk_file_filter_new(); gtk_file_filter_set_name(filter, gdk_pixbuf_format_get_description(format)); gchar **extensions = gdk_pixbuf_format_get_extensions(format); if (extensions){ for (int j = 0; extensions[j]; j++){ ss.str(""); ss << "*." << extensions[j]; gtk_file_filter_add_pattern(filter, ss.str().c_str()); gtk_file_filter_add_pattern(all_image_filter, ss.str().c_str()); } g_strfreev(extensions); } g_object_set_data_full(G_OBJECT(filter), "name", gdk_pixbuf_format_get_name(format), GDestroyNotify(nullptr)); gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(widget), filter); if (g_strcmp0(gdk_pixbuf_format_get_name(format), selected_filter) == 0) gtk_file_chooser_set_filter(GTK_FILE_CHOOSER(widget), filter); i = g_slist_next(i); } if (formats) g_slist_free(formats); frame = gtk_frame_new(_("Options")); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_NONE); gtk_table_attach(GTK_TABLE(table_m), frame, 0, 1, table_m_y, table_m_y+1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL), 5, 5); table_m_y++; table = gtk_table_new(5, 3, FALSE); table_y=0; gtk_container_add(GTK_CONTAINER(frame), table); gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Colors:"),0,0,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); args->range_colors = widget = gtk_spin_button_new_with_range (1, 100, 1); gtk_spin_button_set_value(GTK_SPIN_BUTTON(args->range_colors), dynv_get_int32_wd(args->params, "colors", 3)); gtk_table_attach(GTK_TABLE(table), widget,1,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,3,3); g_signal_connect(G_OBJECT(args->range_colors), "value-changed", G_CALLBACK(update), args); table_y++; ColorList* preview_color_list = nullptr; gtk_table_attach(GTK_TABLE(table_m), args->preview_expander = palette_list_preview_new(gs, true, dynv_get_bool_wd(args->params, "show_preview", true), gs->getColorList(), &preview_color_list), 0, 1, table_m_y, table_m_y+1 , GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL | GTK_EXPAND), 5, 5); table_m_y++; args->preview_color_list = preview_color_list; gtk_widget_show_all(table_m); gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), table_m); g_signal_connect(G_OBJECT(dialog), "destroy", G_CALLBACK(destroy_cb), args); g_signal_connect(G_OBJECT(dialog), "response", G_CALLBACK(response_cb), args); gtk_widget_show(dialog); } gpick-gpick-0.2.6rc1/source/tools/PaletteFromImage.h000066400000000000000000000034051315430016700223150ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_TOOLS_PALETTE_FROM_IMAGE_H_ #define GPICK_TOOLS_PALETTE_FROM_IMAGE_H_ #include class GlobalState; void tools_palette_from_image_show(GtkWindow* parent, GlobalState* gs); #endif /* GPICK_TOOLS_PALETTE_FROM_IMAGE_H_ */ gpick-gpick-0.2.6rc1/source/tools/SConscript000066400000000000000000000010431315430016700207650ustar00rootroot00000000000000#!/usr/bin/env python Import('*') local_env = env.Clone() if not local_env.GetOption('clean') and not env['TOOLCHAIN'] == 'msvc': local_env.ParseConfig('pkg-config --cflags --libs $GTK_PC') local_env.ParseConfig('pkg-config --cflags --libs $LUA_PC') if local_env['ENABLE_NLS']: local_env.Append( CPPDEFINES = ['ENABLE_NLS'], ) if env['EXPERIMENTAL_CSS_PARSER']: local_env.Append( CPPDEFINES = ['EXPERIMENTAL_CSS_PARSER'], ) sources = local_env.Glob('*.cpp') objects = local_env.StaticObject( source = [sources]) Return('objects') gpick-gpick-0.2.6rc1/source/transformation/000077500000000000000000000000001315430016700206635ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/source/transformation/Chain.cpp000066400000000000000000000052261315430016700224160ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Chain.h" using namespace std; namespace transformation { Chain::Chain() { enabled = true; } void Chain::apply(const Color *input, Color *output) { if (!enabled) { color_copy(input, output); return; } Color tmp[2]; Color *tmp_p[3]; color_copy(input, &tmp[0]); tmp_p[0] = &tmp[0]; tmp_p[1] = &tmp[1]; for (TransformationList::iterator i = transformation_chain.begin(); i != transformation_chain.end(); i++){ (*i)->apply(tmp_p[0], tmp_p[1]); tmp_p[2] = tmp_p[0]; tmp_p[0] = tmp_p[1]; tmp_p[1] = tmp_p[2]; } color_copy(tmp_p[0], output); } void Chain::add(boost::shared_ptr transformation) { transformation_chain.push_back(transformation); } void Chain::remove(const Transformation *transformation) { for (TransformationList::iterator i = transformation_chain.begin(); i != transformation_chain.end(); i++){ if ((*i).get() == transformation){ transformation_chain.erase(i); return; } } } void Chain::clear() { transformation_chain.clear(); } Chain::TransformationList& Chain::getAll() { return transformation_chain; } void Chain::setEnabled(bool enabled_) { enabled = enabled_; } } gpick-gpick-0.2.6rc1/source/transformation/Chain.h000066400000000000000000000057571315430016700220740ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TRANSFORMATION_CHAIN_H_ #define TRANSFORMATION_CHAIN_H_ #include "Transformation.h" #include #include /** \file source/transformation/Chain.h * \brief Class for transformation object list handling. */ namespace transformation { /** \class Chain * \brief Transformation object chain management class. */ class Chain{ public: typedef std::list > TransformationList; protected: TransformationList transformation_chain; bool enabled; public: /** * Chain constructor. */ Chain(); /** * Apply transformation chain to color. * @param[in] input Source color in RGB color space. * @param[out] output Destination color in RGB color space. */ void apply(const Color *input, Color *output); /** * Add transformation object into the list. * @param[in] transformation Transformation object. */ void add(boost::shared_ptr transformation); /** * Remove transformation object from the list. * @param[in] transformation Transformation object. */ void remove(const Transformation *transformation); /** * Clear transformation object list. */ void clear(); /** * Enable/disable transformation chain. * @param[in] enabled Enabled. */ void setEnabled(bool enabled); /** * Get the list of transformation objects. * @return Transformation object list. */ TransformationList& getAll(); }; } #endif /* TRANSFORMATION_CHAIN_H_ */ gpick-gpick-0.2.6rc1/source/transformation/ColorVisionDeficiency.cpp000066400000000000000000000416271315430016700256320ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ColorVisionDeficiency.h" #include "../MathUtil.h" #include "../uiUtilities.h" #include "../Internationalisation.h" #include #include #include #include using namespace std; namespace transformation { static const char * transformation_name = "color_vision_deficiency"; const char *ColorVisionDeficiency::getName() { return transformation_name; } const char *ColorVisionDeficiency::getReadableName() { return _("Color vision deficiency"); } const char* ColorVisionDeficiency::deficiency_type_string[] = { "protanomaly", "deuteranomaly", "tritanomaly", "protanopia", "deuteranopia", "tritanopia", }; const double protanomaly[11][9] = { {1.000000,0.000000,-0.000000,0.000000,1.000000,0.000000,-0.000000,-0.000000,1.000000}, {0.856167,0.182038,-0.038205,0.029342,0.955115,0.015544,-0.002880,-0.001563,1.004443}, {0.734766,0.334872,-0.069637,0.051840,0.919198,0.028963,-0.004928,-0.004209,1.009137}, {0.630323,0.465641,-0.095964,0.069181,0.890046,0.040773,-0.006308,-0.007724,1.014032}, {0.539009,0.579343,-0.118352,0.082546,0.866121,0.051332,-0.007136,-0.011959,1.019095}, {0.458064,0.679578,-0.137642,0.092785,0.846313,0.060902,-0.007494,-0.016807,1.024301}, {0.385450,0.769005,-0.154455,0.100526,0.829802,0.069673,-0.007442,-0.022190,1.029632}, {0.319627,0.849633,-0.169261,0.106241,0.815969,0.077790,-0.007025,-0.028051,1.035076}, {0.259411,0.923008,-0.182420,0.110296,0.804340,0.085364,-0.006276,-0.034346,1.040622}, {0.203876,0.990338,-0.194214,0.112975,0.794542,0.092483,-0.005222,-0.041043,1.046265}, {0.152286,1.052583,-0.204868,0.114503,0.786281,0.099216,-0.003882,-0.048116,1.051998}, }; const double deuteranomaly[11][9] = { {1.000000,0.000000,-0.000000,0.000000,1.000000,0.000000,-0.000000,-0.000000,1.000000}, {0.866435,0.177704,-0.044139,0.049567,0.939063,0.011370,-0.003453,0.007233,0.996220}, {0.760729,0.319078,-0.079807,0.090568,0.889315,0.020117,-0.006027,0.013325,0.992702}, {0.675425,0.433850,-0.109275,0.125303,0.847755,0.026942,-0.007950,0.018572,0.989378}, {0.605511,0.528560,-0.134071,0.155318,0.812366,0.032316,-0.009376,0.023176,0.986200}, {0.547494,0.607765,-0.155259,0.181692,0.781742,0.036566,-0.010410,0.027275,0.983136}, {0.498864,0.674741,-0.173604,0.205199,0.754872,0.039929,-0.011131,0.030969,0.980162}, {0.457771,0.731899,-0.189670,0.226409,0.731012,0.042579,-0.011595,0.034333,0.977261}, {0.422823,0.781057,-0.203881,0.245752,0.709602,0.044646,-0.011843,0.037423,0.974421}, {0.392952,0.823610,-0.216562,0.263559,0.690210,0.046232,-0.011910,0.040281,0.971630}, {0.367322,0.860646,-0.227968,0.280085,0.672501,0.047413,-0.011820,0.042940,0.968881}, }; const double tritanomaly[11][9] = { {1.000000,0.000000,-0.000000,0.000000,1.000000,0.000000,-0.000000,-0.000000,1.000000}, {0.926670,0.092514,-0.019184,0.021191,0.964503,0.014306,0.008437,0.054813,0.936750}, {0.895720,0.133330,-0.029050,0.029997,0.945400,0.024603,0.013027,0.104707,0.882266}, {0.905871,0.127791,-0.033662,0.026856,0.941251,0.031893,0.013410,0.148296,0.838294}, {0.948035,0.089490,-0.037526,0.014364,0.946792,0.038844,0.010853,0.193991,0.795156}, {1.017277,0.027029,-0.044306,-0.006113,0.958479,0.047634,0.006379,0.248708,0.744913}, {1.104996,-0.046633,-0.058363,-0.032137,0.971635,0.060503,0.001336,0.317922,0.680742}, {1.193214,-0.109812,-0.083402,-0.058496,0.979410,0.079086,-0.002346,0.403492,0.598854}, {1.257728,-0.139648,-0.118081,-0.078003,0.975409,0.102594,-0.003316,0.501214,0.502102}, {1.278864,-0.125333,-0.153531,-0.084748,0.957674,0.127074,-0.000989,0.601151,0.399838}, {1.255528,-0.076749,-0.178779,-0.078411,0.930809,0.147602,0.004733,0.691367,0.303900}, }; const double rgb_to_lms[3][3] = { {0.05059983, 0.08585369, 0.00952420}, {0.01893033, 0.08925308, 0.01370054}, {0.00292202, 0.00975732, 0.07145979}, }; const double lms_to_rgb[3][3] = { {30.830854, -29.832659, 1.610474}, {-6.481468, 17.715578, -2.532642}, {-0.375690, -1.199062, 14.273846}, }; const double anchor[] = { 0.080080, 0.157900, 0.589700, 0.128400, 0.223700, 0.363600, 0.985600, 0.732500, 0.001079, 0.091400, 0.007009, 0.000000, }; const double rgb_anchor[] = { rgb_to_lms[0][0] + rgb_to_lms[0][1] + rgb_to_lms[0][2], rgb_to_lms[1][0] + rgb_to_lms[1][1] + rgb_to_lms[1][2], rgb_to_lms[2][0] + rgb_to_lms[2][1] + rgb_to_lms[2][2], }; const vector3 protanopia_abc[2] = { {{{ rgb_anchor[1] * anchor[8] - rgb_anchor[2] * anchor[7], rgb_anchor[2] * anchor[6] - rgb_anchor[0] * anchor[8], rgb_anchor[0] * anchor[7] - rgb_anchor[1] * anchor[6], }}}, {{{ rgb_anchor[1] * anchor[2] - rgb_anchor[2] * anchor[1], rgb_anchor[2] * anchor[0] - rgb_anchor[0] * anchor[2], rgb_anchor[0] * anchor[1] - rgb_anchor[1] * anchor[0], }}}, }; const vector3 deuteranopia_abc[2] = { {{{ rgb_anchor[1] * anchor[8] - rgb_anchor[2] * anchor[7], rgb_anchor[2] * anchor[6] - rgb_anchor[0] * anchor[8], rgb_anchor[0] * anchor[7] - rgb_anchor[1] * anchor[6], }}}, {{{ rgb_anchor[1] * anchor[2] - rgb_anchor[2] * anchor[1], rgb_anchor[2] * anchor[0] - rgb_anchor[0] * anchor[2], rgb_anchor[0] * anchor[1] - rgb_anchor[1] * anchor[0], }}}, }; const vector3 tritanopia_abc[2] = { {{{ rgb_anchor[1] * anchor[11] - rgb_anchor[2] * anchor[10], rgb_anchor[2] * anchor[9] - rgb_anchor[0] * anchor[11], rgb_anchor[0] * anchor[10] - rgb_anchor[1] * anchor[9], }}}, {{{ rgb_anchor[1] * anchor[5] - rgb_anchor[2] * anchor[4], rgb_anchor[2] * anchor[3] - rgb_anchor[0] * anchor[5], rgb_anchor[0] * anchor[4] - rgb_anchor[1] * anchor[3], }}}, }; static void load_matrix(const double matrix_data[9], matrix3x3 *matrix) { matrix->m[0][0] = matrix_data[0]; matrix->m[1][0] = matrix_data[1]; matrix->m[2][0] = matrix_data[2]; matrix->m[0][1] = matrix_data[3]; matrix->m[1][1] = matrix_data[4]; matrix->m[2][1] = matrix_data[5]; matrix->m[0][2] = matrix_data[6]; matrix->m[1][2] = matrix_data[7]; matrix->m[2][2] = matrix_data[8]; } static void load_matrix(const double matrix_data[3][3], matrix3x3 *matrix) { matrix->m[0][0] = matrix_data[0][0]; matrix->m[1][0] = matrix_data[1][0]; matrix->m[2][0] = matrix_data[2][0]; matrix->m[0][1] = matrix_data[0][1]; matrix->m[1][1] = matrix_data[1][1]; matrix->m[2][1] = matrix_data[2][1]; matrix->m[0][2] = matrix_data[0][2]; matrix->m[1][2] = matrix_data[1][2]; matrix->m[2][2] = matrix_data[2][2]; } static void load_vector(const Color *color, vector3 *vector) { vector->x = color->rgb.red; vector->y = color->rgb.green; vector->z = color->rgb.blue; } void ColorVisionDeficiency::apply(Color *input, Color *output) { Color linear_input, linear_output; color_rgb_get_linear(input, &linear_input); vector3 vi, vo1, vo2; load_vector(&linear_input, &vi); matrix3x3 matrix1, matrix2; int index = floor(strength * 10); int index_secondary = std::min(index + 1, 10); float interpolation_factor = 1 - ((strength * 10) - index); vector3 lms; if ((type == PROTANOPIA) || (type == DEUTERANOPIA) || (type == TRITANOPIA)){ load_matrix(rgb_to_lms, &matrix1); load_matrix(lms_to_rgb, &matrix2); vector3_multiply_matrix3x3(&vi, &matrix1, &lms); } switch (type){ case PROTANOMALY: load_matrix(protanomaly[index], &matrix1); load_matrix(protanomaly[index_secondary], &matrix2); vector3_multiply_matrix3x3(&vi, &matrix1, &vo1); vector3_multiply_matrix3x3(&vi, &matrix2, &vo2); break; case DEUTERANOMALY: load_matrix(deuteranomaly[index], &matrix1); load_matrix(deuteranomaly[index_secondary], &matrix2); vector3_multiply_matrix3x3(&vi, &matrix1, &vo1); vector3_multiply_matrix3x3(&vi, &matrix2, &vo2); break; case TRITANOMALY: load_matrix(tritanomaly[index], &matrix1); load_matrix(tritanomaly[index_secondary], &matrix2); vector3_multiply_matrix3x3(&vi, &matrix1, &vo1); vector3_multiply_matrix3x3(&vi, &matrix2, &vo2); break; case PROTANOPIA: if (lms.z / lms.y < rgb_anchor[2] / rgb_anchor[1]){ lms.x = -(protanopia_abc[0].y * lms.y + protanopia_abc[0].z * lms.z) / protanopia_abc[0].x; }else{ lms.x = -(protanopia_abc[1].y * lms.y + protanopia_abc[1].z * lms.z) / protanopia_abc[1].x; } vector3_multiply_matrix3x3(&lms, &matrix2, &vo1); load_vector(&linear_input, &vo2); interpolation_factor = strength; break; case DEUTERANOPIA: if (lms.z / lms.x < rgb_anchor[2] / rgb_anchor[0]){ lms.y = -(deuteranopia_abc[0].x * lms.x + deuteranopia_abc[0].z * lms.z) / deuteranopia_abc[0].y; }else{ lms.y = -(deuteranopia_abc[1].x * lms.x + deuteranopia_abc[1].z * lms.z) / deuteranopia_abc[1].y; } vector3_multiply_matrix3x3(&lms, &matrix2, &vo1); load_vector(&linear_input, &vo2); interpolation_factor = strength; break; case TRITANOPIA: if (lms.y / lms.x < rgb_anchor[1] / rgb_anchor[0]){ lms.z = -(tritanopia_abc[0].x * lms.x + tritanopia_abc[0].y * lms.y) / tritanopia_abc[0].z; }else{ lms.z = -(tritanopia_abc[1].x * lms.x + tritanopia_abc[1].y * lms.y) / tritanopia_abc[1].z; } vector3_multiply_matrix3x3(&lms, &matrix2, &vo1); load_vector(&linear_input, &vo2); interpolation_factor = strength; break; default: color_copy(input, output); return; } linear_output.rgb.red = vo1.x * interpolation_factor + vo2.x * (1 - interpolation_factor); linear_output.rgb.green = vo1.y * interpolation_factor + vo2.y * (1 - interpolation_factor); linear_output.rgb.blue = vo1.z * interpolation_factor + vo2.z * (1 - interpolation_factor); color_linear_get_rgb(&linear_output, output); color_rgb_normalize(output); } ColorVisionDeficiency::ColorVisionDeficiency():Transformation(transformation_name, getReadableName()) { type = PROTANOMALY; strength = 0.5; } ColorVisionDeficiency::ColorVisionDeficiency(DeficiencyType type_, float strength_):Transformation(transformation_name, getReadableName()) { type = type_; strength = strength_; } ColorVisionDeficiency::~ColorVisionDeficiency() { } void ColorVisionDeficiency::serialize(struct dynvSystem *dynv) { dynv_set_float(dynv, "strength", strength); dynv_set_string(dynv, "type", deficiency_type_string[type]); Transformation::serialize(dynv); } ColorVisionDeficiency::DeficiencyType ColorVisionDeficiency::typeFromString(const char *type_string) { for (int i = 0; i < DEFICIENCY_TYPE_COUNT; i++){ if (strcmp(type_string, deficiency_type_string[i]) == 0){ return (DeficiencyType)i; } } return PROTANOMALY; } void ColorVisionDeficiency::deserialize(struct dynvSystem *dynv) { strength = dynv_get_float_wd(dynv, "strength", 0.5); type = typeFromString(dynv_get_string_wd(dynv, "type", "protanomaly")); } static GtkWidget* create_type_list(void){ GtkListStore *store; GtkCellRenderer *renderer; GtkWidget *widget; store = gtk_list_store_new(2, G_TYPE_STRING, G_TYPE_INT); widget = gtk_combo_box_new_with_model(GTK_TREE_MODEL(store)); gtk_combo_box_set_add_tearoffs(GTK_COMBO_BOX(widget), 0); renderer = gtk_cell_renderer_text_new(); gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(widget), renderer, 0); gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(widget), renderer, "text", 0, nullptr); g_object_unref(GTK_TREE_MODEL(store)); GtkTreeIter iter1; struct { const char *name; int type; } types[] = { {_("Protanomaly"), ColorVisionDeficiency::PROTANOMALY}, {_("Deuteranomaly"), ColorVisionDeficiency::DEUTERANOMALY}, {_("Tritanomaly"), ColorVisionDeficiency::TRITANOMALY}, {_("Protanopia"), ColorVisionDeficiency::PROTANOPIA}, {_("Deuteranopia"), ColorVisionDeficiency::DEUTERANOPIA}, {_("Tritanopia"), ColorVisionDeficiency::TRITANOPIA}, }; for (int i = 0; i < ColorVisionDeficiency::DEFICIENCY_TYPE_COUNT; ++i){ gtk_list_store_append(store, &iter1); gtk_list_store_set(store, &iter1, 0, types[i].name, 1, types[i].type, -1); } return widget; } boost::shared_ptr ColorVisionDeficiency::getConfig(){ boost::shared_ptr config = boost::shared_ptr(new ColorVisionDeficiencyConfig(*this)); return config; } ColorVisionDeficiencyConfig::ColorVisionDeficiencyConfig(ColorVisionDeficiency &transformation){ GtkWidget *table = gtk_table_new(2, 2, false); GtkWidget *widget; int table_y = 0; table_y = 0; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Type:"), 0, 0.5, 0, 0), 0, 1, table_y, table_y + 1, GTK_FILL, GTK_FILL, 5, 5); type = widget = create_type_list(); g_signal_connect(G_OBJECT(type), "changed", G_CALLBACK(ColorVisionDeficiencyConfig::type_combobox_change_cb), this); gtk_table_attach(GTK_TABLE(table), widget, 1, 2, table_y, table_y + 1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GTK_FILL, 5, 0); table_y++; info_bar = widget = gtk_info_bar_new(); info_label = gtk_label_new(""); gtk_label_set_line_wrap(GTK_LABEL(info_label), true); gtk_label_set_justify(GTK_LABEL(info_label), GTK_JUSTIFY_LEFT); gtk_label_set_single_line_mode(GTK_LABEL(info_label), false); gtk_misc_set_alignment(GTK_MISC(info_label), 0, 0.5); gtk_widget_set_size_request(info_label, 1, -1); GtkWidget *content_area = gtk_info_bar_get_content_area(GTK_INFO_BAR(info_bar)); gtk_container_add(GTK_CONTAINER(content_area), info_label); gtk_widget_show_all(info_bar); g_signal_connect(G_OBJECT(info_label), "size-allocate", G_CALLBACK(info_label_size_allocate_cb), this); gtk_table_attach(GTK_TABLE(table), widget, 1, 2, table_y, table_y + 1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GTK_FILL, 5, 0); table_y++; gtk_combo_box_set_active(GTK_COMBO_BOX(type), transformation.type); gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Strength:"), 0, 0.5, 0, 0), 0, 1, table_y, table_y + 1, GTK_FILL, GTK_FILL, 5, 5); strength = widget = gtk_hscale_new_with_range(0, 100, 1); gtk_range_set_value(GTK_RANGE(widget), transformation.strength * 100); gtk_table_attach(GTK_TABLE(table), widget, 1, 2, table_y, table_y + 1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GTK_FILL, 5, 0); table_y++; main = table; gtk_widget_show_all(main); g_object_ref(main); } ColorVisionDeficiencyConfig::~ColorVisionDeficiencyConfig(){ g_object_unref(main); } GtkWidget* ColorVisionDeficiencyConfig::getWidget(){ return main; } void ColorVisionDeficiencyConfig::applyConfig(dynvSystem *dynv){ dynv_set_float(dynv, "strength", gtk_range_get_value(GTK_RANGE(strength)) / 100.0f); GtkTreeIter iter; if (gtk_combo_box_get_active_iter(GTK_COMBO_BOX(type), &iter)) { GtkTreeModel* model = gtk_combo_box_get_model(GTK_COMBO_BOX(type)); ColorVisionDeficiency::DeficiencyType type_id; gtk_tree_model_get(model, &iter, 1, &type_id, -1); dynv_set_string(dynv, "type", ColorVisionDeficiency::deficiency_type_string[type_id]); } } void ColorVisionDeficiencyConfig::type_combobox_change_cb(GtkWidget *widget, ColorVisionDeficiencyConfig *this_) { const char *descriptions[] = { _("Altered spectral sensitivity of red receptors"), _("Altered spectral sensitivity of green receptors"), _("Altered spectral sensitivity of blue receptors"), _("Absence of red receptors"), _("Absence of green receptors"), _("Absence of blue receptors"), }; GtkTreeIter iter; if (gtk_combo_box_get_active_iter(GTK_COMBO_BOX(this_->type), &iter)) { GtkTreeModel* model = gtk_combo_box_get_model(GTK_COMBO_BOX(this_->type)); ColorVisionDeficiency::DeficiencyType type_id; gtk_tree_model_get(model, &iter, 1, &type_id, -1); gtk_label_set_text(GTK_LABEL(this_->info_label), descriptions[type_id]); }else{ gtk_label_set_text(GTK_LABEL(this_->info_label), ""); } gtk_info_bar_set_message_type(GTK_INFO_BAR(this_->info_bar), GTK_MESSAGE_INFO); } void ColorVisionDeficiencyConfig::info_label_size_allocate_cb(GtkWidget *widget, GtkAllocation *allocation, ColorVisionDeficiencyConfig *this_) { gtk_widget_set_size_request(this_->info_label, allocation->width - 16, -1); } } gpick-gpick-0.2.6rc1/source/transformation/ColorVisionDeficiency.h000066400000000000000000000062521315430016700252720ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TRANSFORMATION_COLOR_VISION_DEFICIENCY_H_ #define TRANSFORMATION_COLOR_VISION_DEFICIENCY_H_ #include "Transformation.h" namespace transformation { class ColorVisionDeficiency; class ColorVisionDeficiencyConfig: public Configuration{ protected: GtkWidget *main; GtkWidget *info_bar; GtkWidget *info_label; GtkWidget *type; GtkWidget *strength; static void type_combobox_change_cb(GtkWidget *widget, ColorVisionDeficiencyConfig *this_); static void info_label_size_allocate_cb(GtkWidget *widget, GtkAllocation *allocation, ColorVisionDeficiencyConfig *this_); public: ColorVisionDeficiencyConfig(ColorVisionDeficiency &transformation); virtual ~ColorVisionDeficiencyConfig(); virtual GtkWidget* getWidget(); virtual void applyConfig(dynvSystem *dynv); }; class ColorVisionDeficiency: public Transformation{ public: enum DeficiencyType{ PROTANOMALY, DEUTERANOMALY, TRITANOMALY, PROTANOPIA, DEUTERANOPIA, TRITANOPIA, DEFICIENCY_TYPE_COUNT, }; static const char *deficiency_type_string[]; static const char *getName(); static const char *getReadableName(); protected: float strength; DeficiencyType type; virtual void apply(Color *input, Color *output); public: ColorVisionDeficiency(); ColorVisionDeficiency(DeficiencyType type, float strength); virtual ~ColorVisionDeficiency(); virtual void serialize(struct dynvSystem *dynv); virtual void deserialize(struct dynvSystem *dynv); virtual boost::shared_ptr getConfig(); DeficiencyType typeFromString(const char *type_string); friend class ColorVisionDeficiencyConfig; }; } #endif /* TRANSFORMATION_COLOR_VISION_DEFICIENCY_H_ */ gpick-gpick-0.2.6rc1/source/transformation/Configuration.cpp000066400000000000000000000034001315430016700241730ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Configuration.h" namespace transformation { Configuration::Configuration() { } Configuration::~Configuration() { } GtkWidget* Configuration::getWidget() { return 0; } void Configuration::applyConfig(dynvSystem *dynv) { } } gpick-gpick-0.2.6rc1/source/transformation/Configuration.h000066400000000000000000000041411315430016700236430ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TRANSFORMATION_CONFIGURATION_H_ #define TRANSFORMATION_CONFIGURATION_H_ #include "../DynvHelpers.h" #include /** \file source/transformation/Configuration.h * \brief Class for transformation object configuration handling. */ namespace transformation { /** \class Configuration * \brief Transformation object configuration management class. */ class Configuration{ protected: public: Configuration(); virtual ~Configuration(); virtual GtkWidget* getWidget(); virtual void applyConfig(dynvSystem *dynv); }; } #endif /* TRANSFORMATION_CONFIGURATION_H_ */ gpick-gpick-0.2.6rc1/source/transformation/Factory.cpp000066400000000000000000000052461315430016700230050ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Factory.h" #include "ColorVisionDeficiency.h" #include "GammaModification.h" #include "Quantization.h" #include namespace transformation { boost::shared_ptr Factory::create(const char *type) { if (strcmp(ColorVisionDeficiency::getName(), type) == 0){ return boost::shared_ptr(new ColorVisionDeficiency()); } if (strcmp(GammaModification::getName(), type) == 0){ return boost::shared_ptr(new GammaModification()); } if (strcmp(Quantization::getName(), type) == 0){ return boost::shared_ptr(new Quantization()); } return boost::shared_ptr(); } std::vector Factory::getAllTypes() { std::vector result; result.push_back(TypeInfo(ColorVisionDeficiency::getName(), ColorVisionDeficiency::getReadableName())); result.push_back(TypeInfo(GammaModification::getName(), GammaModification::getReadableName())); result.push_back(TypeInfo(Quantization::getName(), Quantization::getReadableName())); return result; } Factory::TypeInfo::TypeInfo(const char *name_, const char *human_name_): name(name_), human_name(human_name_) { } } gpick-gpick-0.2.6rc1/source/transformation/Factory.h000066400000000000000000000047231315430016700224510ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TRANSFORMATION_FACTORY_H_ #define TRANSFORMATION_FACTORY_H_ #include "Transformation.h" #include #include /** \file source/transformation/Factory.h * \brief Class for transformation object creation. */ namespace transformation { /** \class Factory * \brief Transformation object creation management class. */ class Factory{ public: typedef struct TypeInfo{ const char *name; const char *human_name; TypeInfo(const char *name, const char *human_name); }TypeInfo; /** * Create new transformation object. * @param[in] type Name of transformation object type. * @return New transformation object. */ static boost::shared_ptr create(const char *type); /** * Get all transformation object types. * @return Vector of transformation object type information structures. */ static std::vector getAllTypes(); }; } #endif /* TRANSFORMATION_FACTORY_H_ */ gpick-gpick-0.2.6rc1/source/transformation/GammaModification.cpp000066400000000000000000000100161315430016700247350ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "GammaModification.h" #include "../MathUtil.h" #include "../uiUtilities.h" #include "../Internationalisation.h" #include #include #include namespace transformation { static const char * transformation_name = "gamma_modification"; const char *GammaModification::getName() { return transformation_name; } const char *GammaModification::getReadableName() { return _("Gamma modification"); } void GammaModification::apply(Color *input, Color *output) { Color linear_input, linear_output; color_rgb_get_linear(input, &linear_input); linear_output.rgb.red = pow(linear_input.rgb.red, value); linear_output.rgb.green= pow(linear_input.rgb.green, value); linear_output.rgb.blue = pow(linear_input.rgb.blue, value); color_linear_get_rgb(&linear_output, output); color_rgb_normalize(output); } GammaModification::GammaModification():Transformation(transformation_name, getReadableName()) { value = 1; } GammaModification::GammaModification(float value_):Transformation(transformation_name, getReadableName()) { value = value_; } GammaModification::~GammaModification() { } void GammaModification::serialize(struct dynvSystem *dynv) { dynv_set_float(dynv, "value", value); Transformation::serialize(dynv); } void GammaModification::deserialize(struct dynvSystem *dynv) { value = dynv_get_float_wd(dynv, "value", 1); } boost::shared_ptr GammaModification::getConfig(){ boost::shared_ptr config = boost::shared_ptr(new GammaModificationConfig(*this)); return config; } GammaModificationConfig::GammaModificationConfig(GammaModification &transformation){ GtkWidget *table = gtk_table_new(2, 2, false); GtkWidget *widget; int table_y = 0; table_y=0; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Value:"),0, 0.5, 0, 0), 0, 1, table_y, table_y + 1, GTK_FILL, GTK_FILL, 5, 5); value = widget = gtk_spin_button_new_with_range(0, 100, 0.01); gtk_spin_button_set_value(GTK_SPIN_BUTTON(widget), transformation.value); gtk_table_attach(GTK_TABLE(table), widget, 1, 2, table_y, table_y + 1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GTK_FILL, 5, 0); table_y++; main = table; gtk_widget_show_all(main); g_object_ref(main); } GammaModificationConfig::~GammaModificationConfig(){ g_object_unref(main); } GtkWidget* GammaModificationConfig::getWidget(){ return main; } void GammaModificationConfig::applyConfig(dynvSystem *dynv){ dynv_set_float(dynv, "value", gtk_spin_button_get_value(GTK_SPIN_BUTTON(value))); } } gpick-gpick-0.2.6rc1/source/transformation/GammaModification.h000066400000000000000000000050341315430016700244060ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TRANSFORMATION_GAMMA_MODIFICATION_H_ #define TRANSFORMATION_GAMMA_MODIFICATION_H_ #include "Transformation.h" namespace transformation { class GammaModification; class GammaModificationConfig: public Configuration{ protected: GtkWidget *main; GtkWidget *value; public: GammaModificationConfig(GammaModification &transformation); virtual ~GammaModificationConfig(); virtual GtkWidget* getWidget(); virtual void applyConfig(dynvSystem *dynv); }; class GammaModification: public Transformation{ public: static const char *getName(); static const char *getReadableName(); protected: float value; virtual void apply(Color *input, Color *output); public: GammaModification(); GammaModification(float value); virtual ~GammaModification(); virtual void serialize(struct dynvSystem *dynv); virtual void deserialize(struct dynvSystem *dynv); virtual boost::shared_ptr getConfig(); friend class GammaModificationConfig; }; } #endif /* TRANSFORMATION_GAMMA_MODIFICATION_H_ */ gpick-gpick-0.2.6rc1/source/transformation/Invert.cpp000066400000000000000000000035041315430016700226400ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Invert.h" namespace transformation { void Invert::apply(Color *input, Color *output) { output->rgb.red = 1 - input->rgb.red; output->rgb.green= 1 - input->rgb.green; output->rgb.blue = 1 - input->rgb.blue; } Invert::Invert():Transformation("invert", "Invert") { } Invert::~Invert() { } } gpick-gpick-0.2.6rc1/source/transformation/Invert.h000066400000000000000000000035101315430016700223020ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TRANSFORMATION_INVERT_H_ #define TRANSFORMATION_INVERT_H_ #include "Transformation.h" namespace transformation { class Invert : public Transformation{ protected: virtual void apply(Color *input, Color *output); public: Invert(); virtual ~Invert(); }; } #endif /* TRANSFORMATION_INVERT_H_ */ gpick-gpick-0.2.6rc1/source/transformation/Quantization.cpp000066400000000000000000000114741315430016700240640ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * Copyright (c) 2012, David Gowers (Portions regarding adaptation of GammaModification.(cpp|h) to quantise colors instead.) * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Quantization.h" #include "../MathUtil.h" #include "../uiUtilities.h" #include "../Internationalisation.h" #include #include #include #include namespace transformation { static const char * transformation_name = "quantization"; const char *Quantization::getName() { return transformation_name; } const char *Quantization::getReadableName() { return _("Quantization"); } void Quantization::apply(Color *input, Color *output) { if (clip_top) { float max_intensity = (value - 1) / value; output->rgb.red = MIN(max_intensity, boost::math::round(input->rgb.red * value) / value); output->rgb.green = MIN(max_intensity, boost::math::round(input->rgb.green * value) / value); output->rgb.blue = MIN(max_intensity, boost::math::round(input->rgb.blue * value) / value); }else{ float actualmax = value - 1; output->rgb.red = boost::math::round(input->rgb.red * actualmax) / actualmax; output->rgb.green = boost::math::round(input->rgb.green * actualmax) / actualmax; output->rgb.blue = boost::math::round(input->rgb.blue * actualmax) / actualmax; } } Quantization::Quantization():Transformation(transformation_name, getReadableName()) { value = 16; } Quantization::Quantization(float value_):Transformation(transformation_name, getReadableName()) { value = value_; } Quantization::~Quantization() { } void Quantization::serialize(struct dynvSystem *dynv) { dynv_set_float(dynv, "value", value); dynv_set_bool(dynv, "clip-top", clip_top); Transformation::serialize(dynv); } void Quantization::deserialize(struct dynvSystem *dynv) { value = dynv_get_float_wd(dynv, "value", 16); clip_top = dynv_get_bool_wd(dynv, "clip-top", 0); } boost::shared_ptr Quantization::getConfig(){ boost::shared_ptr config = boost::shared_ptr(new QuantizationConfig(*this)); return config; } QuantizationConfig::QuantizationConfig(Quantization &transformation){ GtkWidget *table = gtk_table_new(2, 3, false); GtkWidget *widget; int table_y = 0; table_y=0; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Value:"),0, 0.5, 0, 0), 0, 1, table_y, table_y + 1, GTK_FILL, GTK_FILL, 5, 5); value = widget = gtk_spin_button_new_with_range(2, 256, 1); gtk_spin_button_set_value(GTK_SPIN_BUTTON(widget), transformation.value); gtk_table_attach(GTK_TABLE(table), widget, 1, 2, table_y, table_y + 1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GTK_FILL, 5, 0); table_y++; clip_top = widget = gtk_check_button_new_with_label(_("Clip top-end")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), transformation.clip_top); gtk_table_attach(GTK_TABLE(table), widget, 1, 2, table_y, table_y + 1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GTK_FILL, 5, 0); main = table; gtk_widget_show_all(main); g_object_ref(main); } QuantizationConfig::~QuantizationConfig(){ g_object_unref(main); } GtkWidget* QuantizationConfig::getWidget(){ return main; } void QuantizationConfig::applyConfig(dynvSystem *dynv){ dynv_set_float(dynv, "value", gtk_spin_button_get_value(GTK_SPIN_BUTTON(value))); dynv_set_bool(dynv, "clip-top", gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON(clip_top))); } } gpick-gpick-0.2.6rc1/source/transformation/Quantization.h000066400000000000000000000050061315430016700235230ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TRANSFORMATION_QUANTIZATION_H_ #define TRANSFORMATION_QUANTIZATION_H_ #include "Transformation.h" namespace transformation { class Quantization; class QuantizationConfig: public Configuration{ protected: GtkWidget *main; GtkWidget *value; GtkWidget *clip_top; public: QuantizationConfig(Quantization &transformation); virtual ~QuantizationConfig(); virtual GtkWidget* getWidget(); virtual void applyConfig(dynvSystem *dynv); }; class Quantization: public Transformation{ public: static const char *getName(); static const char *getReadableName(); protected: float value; bool clip_top; virtual void apply(Color *input, Color *output); public: Quantization(); Quantization(float value); virtual ~Quantization(); virtual void serialize(struct dynvSystem *dynv); virtual void deserialize(struct dynvSystem *dynv); virtual boost::shared_ptr getConfig(); friend class QuantizationConfig; }; } #endif /* TRANSFORMATION_GAMMA_MODIFICATION_H_ */ gpick-gpick-0.2.6rc1/source/transformation/Transformation.cpp000066400000000000000000000043671315430016700244070ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Transformation.h" namespace transformation { Transformation::Transformation(const char *name_, const char *readable_name_) { name = name_; readable_name = readable_name_; } Transformation::~Transformation() { } void Transformation::apply(Color *input, Color *output) { color_copy(input, output); } std::string Transformation::getName() const { return name; } std::string Transformation::getReadableName() const { return readable_name; } void Transformation::serialize(struct dynvSystem *dynv) { dynv_set_string(dynv, "name", name.c_str()); } void Transformation::deserialize(struct dynvSystem *dynv) { } boost::shared_ptr Transformation::getConfig() { return boost::shared_ptr(); } } gpick-gpick-0.2.6rc1/source/transformation/Transformation.h000066400000000000000000000066021315430016700240460ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TRANSFORMATION_H_ #define TRANSFORMATION_H_ #include "../Color.h" #include "Configuration.h" #include "../DynvHelpers.h" #include #include /** \file source/transformation/Transformation.h * \brief Color transformation class. */ namespace transformation { /** \class Transformation * \brief Transformation object class. */ class Transformation{ protected: std::string name; /**< System name */ std::string readable_name; /**< Human readable name */ /** * Apply transformation to color. * @param[in] input Source color in RGB color space. * @param[out] output Destination color in RGB color space. */ virtual void apply(Color *input, Color *output); public: /** * Transformation object constructor. * @param[in] name Transformation object system name. * @param[in] readable_name Transformation object human readable name. */ Transformation(const char *name, const char *readable_name); /** * Transformation object destructor. */ virtual ~Transformation(); /** * Serialize settings into configuration system. * @param[in,out] dynv Configuration system. */ virtual void serialize(struct dynvSystem *dynv); /** * Deserialize settings from configuration system. * @param[in] dynv Configuration system. */ virtual void deserialize(struct dynvSystem *dynv); /** * Get configuration for transformation object. * @return Configuration for transformation object. */ virtual boost::shared_ptr getConfig(); /** * Get transformation object system name. * @return Transformation object system name. */ std::string getName() const; /** * Get transformation object human readable name. * @return Transformation object human readable name. */ std::string getReadableName() const; friend class Chain; }; } #endif /* TRANSFORMATION_H_ */ gpick-gpick-0.2.6rc1/source/uiAbout.cpp000066400000000000000000000231241315430016700177330ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "uiAbout.h" #include "version/Version.h" #include "Internationalisation.h" const gchar* program_name = "Gpick"; static GtkWidget* new_page(const char *text) { GtkWidget *text_view = gtk_text_view_new(); gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(text_view), GTK_WRAP_WORD); GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text_view)); gtk_text_buffer_set_text(buffer, text, -1); gtk_text_view_set_editable(GTK_TEXT_VIEW(text_view), false); GtkWidget *scrolled = gtk_scrolled_window_new(0, 0); gtk_container_add(GTK_CONTAINER(scrolled), text_view); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); return scrolled; } void show_about_box(GtkWidget *widget) { const char *license = { "Copyright \xc2\xa9 2009-2016, Albertas Vyšniauskas\n" "\n" "All rights reserved.\n" "\n" "Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n" "\n" " * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n" " * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n" " * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n" "\n" "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" }; const char *expat_license = { "Copyright \xc2\xa9 1998, 1999, 2000 Thai Open Source Software Center Ltd and Clark Cooper\n" "Copyright \xc2\xa9 2001, 2002, 2003, 2004, 2005, 2006 Expat maintainers.\n" "\n" "Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n" "\n" "The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n" "\n" "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n" }; const char *lua_license = { "Copyright \xc2\xa9 1994-2008 Lua.org, PUC-Rio.\n" "\n" "Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n" "\n" "The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n" "\n" "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n" }; const char *program_authors = { "Albertas Vyšniauskas \n" /* Add yourself here if you helped Gpick project in any way (patch, translation, etc). * Everything is optional, if you do not want, you do not have to disclose your e-mail * address, real name or any other information. * Please keep this list sorted alphabetically. */ }; GtkWidget* dialog = gtk_dialog_new_with_buttons(_("About Gpick"), GTK_WINDOW(gtk_widget_get_toplevel(widget)), GtkDialogFlags(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), GTK_STOCK_CLOSE, GTK_RESPONSE_CANCEL, nullptr); gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_CANCEL); GtkWidget *vbox = gtk_vbox_new(false, 5); GtkWidget *align_box = gtk_hbox_new(false, 5); gtk_box_pack_start(GTK_BOX(vbox), align_box, false, false, 0); gtk_box_pack_start(GTK_BOX(align_box), gtk_vbox_new(false, 0), true, true, 0); gtk_box_pack_end(GTK_BOX(align_box), gtk_vbox_new(false, 0), true, true, 0); GtkWidget *hbox = gtk_hbox_new(false, 5); gtk_box_pack_start(GTK_BOX(align_box), hbox, false, false, 0); GtkWidget *image = gtk_image_new(); gtk_image_set_from_icon_name(GTK_IMAGE(image), "gpick", GTK_ICON_SIZE_DIALOG); gtk_box_pack_start(GTK_BOX(hbox), image, false, false, 0); GtkWidget *vbox2 = gtk_vbox_new(false, 0); gtk_box_pack_start(GTK_BOX(hbox), vbox2, false, false, 0); gchar *tmp_string = g_markup_printf_escaped("%s %s", program_name, gpick_build_version); GtkWidget *name = gtk_label_new(0); gtk_label_set_selectable(GTK_LABEL(name), true); gtk_label_set_justify(GTK_LABEL(name), GTK_JUSTIFY_CENTER); gtk_label_set_markup(GTK_LABEL(name), tmp_string); gtk_box_pack_start(GTK_BOX(vbox2), name, false, false, 0); g_free(tmp_string); GtkWidget *comments = gtk_label_new(_("Advanced color picker")); gtk_label_set_selectable(GTK_LABEL(comments), true); gtk_label_set_justify(GTK_LABEL(comments), GTK_JUSTIFY_CENTER); gtk_box_pack_start(GTK_BOX(vbox2), comments, false, false, 0); tmp_string = g_markup_printf_escaped ("%s", _("Copyright © 2009-2016, Albertas Vyšniauskas and Gpick development team")); GtkWidget *copyright = gtk_label_new(0); gtk_label_set_selectable(GTK_LABEL(copyright), true); gtk_label_set_justify(GTK_LABEL(copyright), GTK_JUSTIFY_CENTER); gtk_label_set_line_wrap(GTK_LABEL(copyright), true); gtk_label_set_markup(GTK_LABEL(copyright), tmp_string); gtk_box_pack_start(GTK_BOX(vbox2), copyright, false, false, 0); g_free(tmp_string); GtkWidget *website = gtk_link_button_new("http://www.gpick.org/"); gtk_box_pack_start(GTK_BOX(vbox2), website, false, false, 0); GtkWidget *notebook = gtk_notebook_new(); gtk_notebook_set_scrollable(GTK_NOTEBOOK(notebook), true); gtk_notebook_append_page(GTK_NOTEBOOK(notebook), new_page(license), gtk_label_new(_("License"))); gtk_notebook_append_page(GTK_NOTEBOOK(notebook), new_page(program_authors), gtk_label_new(_("Credits"))); gtk_notebook_append_page(GTK_NOTEBOOK(notebook), new_page(expat_license), gtk_label_new(_("Expat License"))); gtk_notebook_append_page(GTK_NOTEBOOK(notebook), new_page(lua_license), gtk_label_new(_("Lua License"))); gtk_box_pack_start(GTK_BOX(vbox), notebook, true, true, 0); gtk_widget_show_all(vbox); gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), vbox, true, true, 5); gtk_window_set_default_size(GTK_WINDOW(dialog), 400, 300); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); return; } gpick-gpick-0.2.6rc1/source/uiAbout.h000066400000000000000000000033311315430016700173760ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_UI_DIALOG_ABOUT_H_ #define GPICK_UI_DIALOG_ABOUT_H_ #include void show_about_box(GtkWidget *widget); extern const gchar* program_name; #endif /* GPICK_UI_DIALOG_ABOUT_H_ */ gpick-gpick-0.2.6rc1/source/uiApp.cpp000066400000000000000000002112331315430016700174010ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "uiApp.h" #include "ColorObject.h" #include "ColorList.h" #include "GlobalState.h" #include "ColorSourceManager.h" #include "ColorSource.h" #include "Paths.h" #include "Converter.h" #include "CopyPaste.h" #include "StandardMenu.h" #include "RegisterSources.h" #include "GenerateScheme.h" #include "ColorPicker.h" #include "LayoutPreview.h" #include "ImportExport.h" #include "uiAbout.h" #include "uiListPalette.h" #include "uiUtilities.h" #include "uiImportExport.h" #include "uiDialogMix.h" #include "uiDialogVariations.h" #include "uiDialogGenerate.h" #include "uiDialogAutonumber.h" #include "uiDialogSort.h" #include "uiColorDictionaries.h" #include "uiTransformations.h" #include "uiDialogOptions.h" #include "uiConverter.h" #include "uiStatusIcon.h" #include "tools/PaletteFromImage.h" #include "tools/PaletteFromCssFile.h" #include "tools/ColorSpaceSampler.h" #include "dbus/Control.h" #include "DynvHelpers.h" #include "FileFormat.h" #include "MathUtil.h" #include "Clipboard.h" #include "Internationalisation.h" #include "color_names/ColorNames.h" #include #include #include #include #include #include #include #include #include #include using namespace std; struct AppArgs { GtkWidget *window; map color_source; vector color_source_index; list recent_files; ColorSourceManager *csm; ColorSource *current_color_source; ColorSource *secondary_color_source; GtkWidget *secondary_source_widget; GtkWidget *secondary_source_scrolled_viewpoint; GtkWidget *secondary_source_container; GtkWidget *color_list; GtkWidget *notebook; GtkWidget *statusbar; GtkWidget *hpaned; GtkWidget *vpaned; uiStatusIcon* status_icon; FloatingPicker floating_picker; AppOptions options; struct dynvSystem *params; GlobalState *gs; string current_filename; bool current_filename_set; bool imported; GtkWidget *precision_loss_icon; gint x, y; gint width, height; bool initialization; dbus::Control dbus_control; }; static void app_release(AppArgs *args); static void update_recent_file_list(AppArgs *args, const char *filename, bool move_up) { list::iterator i = std::find(args->recent_files.begin(), args->recent_files.end(), string(filename)); if (i == args->recent_files.end()){ args->recent_files.push_front(string(filename)); while (args->recent_files.size() > 10){ args->recent_files.pop_back(); } }else{ if (move_up){ args->recent_files.erase(i); args->recent_files.push_front(string(filename)); } } } static gboolean delete_event(GtkWidget *widget, GdkEvent *event, AppArgs *args) { if (dynv_get_bool_wd(args->params, "close_to_tray", false)){ gtk_widget_hide(args->window); status_icon_set_visible(args->status_icon, true); return true; } return false; } static gboolean on_window_state_event(GtkWidget *widget, GdkEventWindowState *event, AppArgs *args) { if (event->new_window_state == GDK_WINDOW_STATE_ICONIFIED || event->new_window_state == GDK_WINDOW_STATE_WITHDRAWN){ if (args->secondary_color_source) color_source_deactivate(args->secondary_color_source); if (args->current_color_source) color_source_deactivate(args->current_color_source); }else{ if (args->secondary_color_source) color_source_activate(args->secondary_color_source); if (args->current_color_source) color_source_activate(args->current_color_source); } if (dynv_get_bool_wd(args->params, "minimize_to_tray", false)){ if (event->changed_mask & GDK_WINDOW_STATE_ICONIFIED){ if (event->new_window_state & GDK_WINDOW_STATE_ICONIFIED){ gtk_widget_hide(args->window); gtk_window_deiconify(GTK_WINDOW(args->window)); status_icon_set_visible(args->status_icon, true); return true; } } } return false; } static gboolean on_window_configure(GtkWidget *widget, GdkEventConfigure *event, AppArgs *args) { if (gtk_widget_get_visible(widget)){ if (gdk_window_get_state(gtk_widget_get_window(widget)) & (GDK_WINDOW_STATE_MAXIMIZED | GDK_WINDOW_STATE_FULLSCREEN | GDK_WINDOW_STATE_ICONIFIED)) { return false; } gint x, y; gtk_window_get_position(GTK_WINDOW(widget), &x, &y); args->x = x; args->y = y; args->width = event->width; args->height = event->height; dynv_set_int32(args->params, "window.x", args->x); dynv_set_int32(args->params, "window.y", args->y); dynv_set_int32(args->params, "window.width", args->width); dynv_set_int32(args->params, "window.height", args->height); } return false; } static void notebook_switch_cb(GtkNotebook *notebook, GtkWidget *page, guint page_num, AppArgs *args) { if (args->current_color_source) color_source_deactivate(args->current_color_source); args->current_color_source = nullptr; if (page_num >= 0 && page_num <= args->color_source_index.size() && args->color_source_index[page_num]){ if (!args->initialization) // do not initialize color sources while initializing program color_source_activate(args->color_source_index[page_num]); args->current_color_source = args->color_source_index[page_num]; args->gs->setCurrentColorSource(args->current_color_source); }else{ args->gs->setCurrentColorSource(nullptr); } } static void destroy_cb(GtkWidget *widget, AppArgs *args) { g_signal_handlers_disconnect_matched(G_OBJECT(args->notebook), G_SIGNAL_MATCH_FUNC, 0, 0, nullptr, (void*)notebook_switch_cb, 0); //disconnect notebook switch callback, because destroying child widgets triggers it dynv_set_string(args->params, "color_source", args->color_source_index[gtk_notebook_get_current_page(GTK_NOTEBOOK(args->notebook))]->identificator); dynv_set_int32(args->params, "paned_position", gtk_paned_get_position(GTK_PANED(args->hpaned))); dynv_set_int32(args->params, "vertical_paned_position", gtk_paned_get_position(GTK_PANED(args->vpaned))); if (args->secondary_color_source){ dynv_set_string(args->params, "secondary_color_source", args->secondary_color_source->identificator); }else{ dynv_set_string(args->params, "secondary_color_source", ""); } dynv_set_int32(args->params, "window.x", args->x); dynv_set_int32(args->params, "window.y", args->y); dynv_set_int32(args->params, "window.width", args->width); dynv_set_int32(args->params, "window.height", args->height); app_release(args); gtk_main_quit(); } static void app_update_program_name(AppArgs *args) { stringstream program_title; if (!args->current_filename_set){ program_title << _("New palette"); if (args->precision_loss_icon) gtk_widget_hide(args->precision_loss_icon); }else{ gchar* filename = g_path_get_basename(args->current_filename.c_str()); if (args->imported){ program_title << filename << " " << _("(Imported)"); if (args->precision_loss_icon) gtk_widget_show(args->precision_loss_icon); }else{ program_title << filename; if (args->precision_loss_icon) gtk_widget_hide(args->precision_loss_icon); } g_free(filename); } program_title << " - " << program_name; string title = program_title.str(); gtk_window_set_title(GTK_WINDOW(args->window), title.c_str()); } static void show_dialog_converter(GtkWidget *widget, AppArgs *args) { dialog_converter_show(GTK_WINDOW(args->window), args->gs); return; } static void show_dialog_transformations(GtkWidget *widget, AppArgs *args) { dialog_transformations_show(GTK_WINDOW(args->window), args->gs); return; } static void show_dialog_options(GtkWidget *widget, AppArgs *args) { dialog_options_show(GTK_WINDOW(args->window), args->gs); return; } static void show_dialog_color_dictionaries(GtkWidget *widget, AppArgs *args) { dialog_color_dictionaries_show(GTK_WINDOW(args->window), args->gs); return; } static void menu_file_new(GtkWidget *widget, AppArgs *args) { args->current_filename_set = false; color_list_remove_all(args->gs->getColorList()); app_update_program_name(args); } int app_save_file(AppArgs *args, const char *filename) { string current_filename; if (filename != nullptr){ current_filename = filename; }else{ if (!args->current_filename_set) return -1; current_filename = args->current_filename; } FileType filetype; ImportExport import_export(args->gs->getColorList(), current_filename.c_str(), args->gs); bool return_value = false; switch (filetype = ImportExport::getFileType(current_filename.c_str())){ case FileType::gpl: return_value = import_export.exportGPL(); break; case FileType::ase: return_value = import_export.exportASE(); break; case FileType::gpa: return_value = import_export.exportGPA(); break; default: return_value = import_export.exportGPA(); } if (return_value){ if (filetype == FileType::gpa || filetype == FileType::unknown){ args->imported = false; }else{ args->imported = true; } args->current_filename = current_filename; args->current_filename_set = true; app_update_program_name(args); update_recent_file_list(args, current_filename.c_str(), true); return 0; }else{ app_update_program_name(args); return -1; } return 0; } int app_load_file(AppArgs *args, const char *filename, ColorList *color_list, bool autoload) { string current_filename(filename); bool imported = false; bool return_value = false; ImportExport import_export(color_list, current_filename.c_str(), args->gs); switch (ImportExport::getFileType(current_filename.c_str())){ case FileType::gpl: return_value = import_export.importGPL(); imported = true; break; case FileType::ase: return_value = import_export.importASE(); imported = true; break; case FileType::gpa: return_value = import_export.importGPA(); break; default: return_value = import_export.importGPA(); } args->current_filename_set = false; if (return_value){ if (imported){ args->imported = true; }else{ args->imported = false; } if (!autoload){ args->current_filename = current_filename; args->current_filename_set = true; update_recent_file_list(args, current_filename.c_str(), false); } app_update_program_name(args); }else{ app_update_program_name(args); return -1; } return 0; } int app_load_file(AppArgs *args, const char *filename, bool autoload) { int r = 0; ColorList *color_list = color_list_new(args->gs->getColorList()); if ((r = app_load_file(args, filename, color_list, autoload)) == 0){ color_list_remove_all(args->gs->getColorList()); color_list_add(args->gs->getColorList(), color_list, true); } color_list_destroy(color_list); return r; } int app_parse_geometry(AppArgs *args, const char *geometry) { gtk_window_parse_geometry(GTK_WINDOW(args->window), geometry); return 0; } static void menu_file_revert(GtkWidget *widget, AppArgs *args) { if (!args->current_filename_set) return; if (app_load_file(args, args->current_filename.c_str()) == 0){ }else{ GtkWidget* message; message = gtk_message_dialog_new(GTK_WINDOW(args->window), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, _("File could not be opened")); gtk_window_set_title(GTK_WINDOW(message), _("Open")); gtk_dialog_run(GTK_DIALOG(message)); gtk_widget_destroy(message); } } static void menu_file_open_last(GtkWidget *widget, AppArgs *args) { const char *filename = args->recent_files.begin()->c_str(); if (app_load_file(args, filename) == 0){ }else{ GtkWidget* message; message = gtk_message_dialog_new(GTK_WINDOW(args->window), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, _("File could not be opened")); gtk_window_set_title(GTK_WINDOW(message), _("Open")); gtk_dialog_run(GTK_DIALOG(message)); gtk_widget_destroy(message); } } static void menu_file_open_nth(GtkWidget *widget, AppArgs *args) { list::iterator i = args->recent_files.begin(); uintptr_t index = (uintptr_t)g_object_get_data(G_OBJECT(widget), "index"); std::advance(i, index); const char *filename = (*i).c_str(); if (app_load_file(args, filename) == 0){ }else{ GtkWidget* message; message = gtk_message_dialog_new(GTK_WINDOW(args->window), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, _("File could not be opened")); gtk_window_set_title(GTK_WINDOW(message), _("Open")); gtk_dialog_run(GTK_DIALOG(message)); gtk_widget_destroy(message); } } static void add_file_filters(GtkWidget *dialog, FileType preselect) { const struct{ FileType type; const char *label; const char *filter; }filters[] = { {FileType::gpa, _("Gpick Palette (*.gpa)"), "*.gpa"}, {FileType::gpl, _("GIMP/Inkscape Palette (*.gpl)"), "*.gpl"}, {FileType::ase, _("Adobe Swatch Exchange (*.ase)"), "*.ase"}, {FileType::unknown, 0, 0}, }; GtkFileFilter *filter; filter = gtk_file_filter_new(); gtk_file_filter_set_name(filter, _("All files")); gtk_file_filter_add_pattern(filter, "*"); gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); filter = gtk_file_filter_new(); gtk_file_filter_set_name(filter, _("All supported formats")); for (gint i = 0; filters[i].type != FileType::unknown; ++i) { gtk_file_filter_add_pattern(filter, filters[i].filter); } gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); gtk_file_chooser_set_filter(GTK_FILE_CHOOSER(dialog), filter); for (gint i = 0; filters[i].type != FileType::unknown; ++i) { filter = gtk_file_filter_new(); gtk_file_filter_set_name(filter, filters[i].label); gtk_file_filter_add_pattern(filter, filters[i].filter); gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); if (preselect == filters[i].type){ gtk_file_chooser_set_filter(GTK_FILE_CHOOSER(dialog), filter); } } } static void menu_file_open(GtkWidget *widget, AppArgs *args) { GtkWidget *dialog; dialog = gtk_file_chooser_dialog_new(_("Open File"), GTK_WINDOW(gtk_widget_get_toplevel(widget)), GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_OK, nullptr); gtk_dialog_set_alternative_button_order(GTK_DIALOG(dialog), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1); const gchar* default_path = dynv_get_string_wd(args->params, "open.path", ""); gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), default_path); add_file_filters(dialog, FileType::unknown); gboolean finished = FALSE; while (!finished){ if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK) { gchar *filename; filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); gchar *path; path = gtk_file_chooser_get_current_folder(GTK_FILE_CHOOSER(dialog)); dynv_set_string(args->params, "open.path", path); g_free(path); if (app_load_file(args, filename) == 0){ finished = TRUE; }else{ GtkWidget* message; message = gtk_message_dialog_new(GTK_WINDOW(dialog), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, _("File could not be opened")); gtk_window_set_title(GTK_WINDOW(dialog), _("Open")); gtk_dialog_run(GTK_DIALOG(message)); gtk_widget_destroy(message); } g_free(filename); }else break; } gtk_widget_destroy (dialog); } static void menu_file_save_as(GtkWidget *widget, AppArgs *args) { GtkWidget *dialog; dialog = gtk_file_chooser_dialog_new(_("Save As"), GTK_WINDOW(gtk_widget_get_toplevel(widget)), GTK_FILE_CHOOSER_ACTION_SAVE, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_SAVE, GTK_RESPONSE_OK, nullptr); gtk_dialog_set_alternative_button_order(GTK_DIALOG(dialog), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1); gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog), TRUE); const gchar* default_path = dynv_get_string_wd(args->params, "save.path", ""); gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), default_path); add_file_filters(dialog, FileType::unknown); gboolean finished = FALSE; while (!finished){ if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK) { gchar *filename; filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); gchar *path; path = gtk_file_chooser_get_current_folder(GTK_FILE_CHOOSER(dialog)); dynv_set_string(args->params, "save.path", path); g_free(path); if (app_save_file(args, filename) == 0){ finished = TRUE; }else{ GtkWidget* message; message = gtk_message_dialog_new(GTK_WINDOW(dialog), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, _("File could not be saved")); gtk_window_set_title(GTK_WINDOW(message), _("Save As")); gtk_dialog_run(GTK_DIALOG(message)); gtk_widget_destroy(message); } g_free(filename); }else break; } gtk_widget_destroy (dialog); } static void menu_file_save(GtkWidget *widget, AppArgs *args) { if (!args->current_filename_set){ menu_file_save_as(widget, args); // if file has no name, "Save As" dialog is shown instead. }else{ if (app_save_file(args, nullptr) == 0){ }else{ GtkWidget* message; message = gtk_message_dialog_new(GTK_WINDOW(args->window), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, _("File could not be saved")); gtk_window_set_title(GTK_WINDOW(message), _("Save")); gtk_dialog_run(GTK_DIALOG(message)); gtk_widget_destroy(message); } } } static PaletteListCallbackReturn color_list_selected(ColorObject* color_object, void *userdata) { color_list_add_color_object((ColorList *)userdata, color_object, 1); return PALETTE_LIST_CALLBACK_NO_UPDATE; } static void menu_file_export_all(GtkWidget *widget, AppArgs *args) { ImportExportDialog import_export_dialog(GTK_WINDOW(args->window), args->gs->getColorList(), args->gs); import_export_dialog.showExport(); } static void menu_file_import(GtkWidget *widget, AppArgs *args) { ImportExportDialog import_export_dialog(GTK_WINDOW(args->window), args->gs->getColorList(), args->gs); import_export_dialog.showImport(); } static void menu_file_import_text_file(GtkWidget *widget, AppArgs *args) { ImportExportDialog import_export_dialog(GTK_WINDOW(args->window), args->gs->getColorList(), args->gs); import_export_dialog.showImportTextFile(); } static void menu_file_export(GtkWidget *widget, gpointer data) { AppArgs* args = (AppArgs*)data; struct dynvHandlerMap* handler_map = dynv_system_get_handler_map(args->gs->getSettings()); ColorList *color_list = color_list_new(handler_map); dynv_handler_map_release(handler_map); palette_list_foreach_selected(args->color_list, color_list_selected, color_list); ImportExportDialog import_export_dialog(GTK_WINDOW(args->window), color_list, args->gs); import_export_dialog.showExport(); color_list_destroy(color_list); } typedef struct FileMenuItems{ GtkWidget *export_all; GtkWidget *export_selected; GtkWidget *recent_files; }FileMenuItems; static void menu_file_activate(GtkWidget *widget, gpointer data) { AppArgs* args = (AppArgs*)data; gint32 selected_count = palette_list_get_selected_count(args->color_list); gint32 total_count = palette_list_get_count(args->color_list); FileMenuItems *items = (FileMenuItems*) g_object_get_data(G_OBJECT(widget), "items"); gtk_widget_set_sensitive(items->export_all, (total_count >= 1)); gtk_widget_set_sensitive(items->export_selected, (selected_count >= 1)); if (args->recent_files.size() > 0){ GtkMenu *menu2 = GTK_MENU(gtk_menu_new()); GtkWidget *item; item = gtk_menu_item_new_with_image (_("Open Last File"), gtk_image_new_from_stock(GTK_STOCK_OPEN, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu2), item); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK (menu_file_open_last), args); gtk_menu_shell_append (GTK_MENU_SHELL (menu2), gtk_separator_menu_item_new ()); uintptr_t j = 0; for (list::iterator i = args->recent_files.begin(); i != args->recent_files.end(); i++){ item = gtk_menu_item_new_with_label ((*i).c_str()); gtk_menu_shell_append (GTK_MENU_SHELL (menu2), item); g_object_set_data_full(G_OBJECT(item), "index", (void*)j, (GDestroyNotify)nullptr); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK (menu_file_open_nth), args); j++; } gtk_widget_show_all(GTK_WIDGET(menu2)); gtk_menu_item_set_submenu (GTK_MENU_ITEM (items->recent_files), GTK_WIDGET(menu2)); gtk_widget_set_sensitive(items->recent_files, true); }else{ gtk_widget_set_sensitive(items->recent_files, false); } } static void floating_picker_show_cb(GtkWidget *widget, AppArgs* args) { floating_picker_activate(args->floating_picker, false, false, nullptr); } static void show_about_box_cb(GtkWidget *widget, AppArgs* args) { show_about_box(args->window); } static void view_palette_cb(GtkWidget *widget, AppArgs* args) { if (gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(widget))){ g_object_ref(args->vpaned); GtkWidget *vbox = gtk_widget_get_parent(GTK_WIDGET(args->vpaned)); gtk_container_remove(GTK_CONTAINER(vbox), args->vpaned); gtk_paned_pack1(GTK_PANED(args->hpaned), args->vpaned, false, false); g_object_unref(args->vpaned); gtk_widget_show(GTK_WIDGET(args->hpaned)); dynv_set_bool(args->params, "view.palette", true); }else{ gtk_widget_hide(GTK_WIDGET(args->hpaned)); g_object_ref(args->vpaned); gtk_container_remove(GTK_CONTAINER(args->hpaned), args->vpaned); GtkWidget *vbox = gtk_widget_get_parent(GTK_WIDGET(args->hpaned)); gtk_box_pack_start(GTK_BOX(vbox), args->vpaned, TRUE, TRUE, 5); g_object_unref(args->vpaned); dynv_set_bool(args->params, "view.palette", false); } } static void palette_from_image_cb(GtkWidget *widget, AppArgs* args) { tools_palette_from_image_show(GTK_WINDOW(args->window), args->gs); } static void color_space_sampler_cb(GtkWidget *widget, AppArgs* args) { tools_color_space_sampler_show(GTK_WINDOW(args->window), args->gs); } static void destroy_file_menu_items(FileMenuItems *items) { delete items; } static void activate_secondary_source(AppArgs *args, ColorSource *source) { if (args->secondary_color_source){ color_source_deactivate(args->secondary_color_source); color_source_destroy(args->secondary_color_source); args->secondary_color_source = 0; args->secondary_source_widget = 0; if (args->secondary_source_scrolled_viewpoint) gtk_container_remove(GTK_CONTAINER(args->secondary_source_container), args->secondary_source_scrolled_viewpoint); args->secondary_source_scrolled_viewpoint= 0; if (!source) gtk_widget_hide(args->secondary_source_container); } if (source){ string namespace_str = "gpick.secondary_view."; namespace_str += source->identificator; struct dynvSystem *dynv_namespace = dynv_get_dynv(args->gs->getSettings(), namespace_str.c_str()); source = color_source_implement(source, args->gs, dynv_namespace); GtkWidget *new_widget = color_source_get_widget(source); dynv_system_release(dynv_namespace); args->secondary_color_source = source; args->secondary_source_widget = new_widget; if (source->needs_viewport){ GtkWidget *scrolled_window = gtk_scrolled_window_new(0,0); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled_window),GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scrolled_window), GTK_SHADOW_NONE); gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(scrolled_window), new_widget); args->secondary_source_scrolled_viewpoint = scrolled_window; gtk_box_pack_start(GTK_BOX(args->secondary_source_container), args->secondary_source_scrolled_viewpoint, true, true, 0); gtk_widget_show(args->secondary_source_scrolled_viewpoint); }else{ gtk_box_pack_start(GTK_BOX(args->secondary_source_container), new_widget, true, true, 0); gtk_widget_show(new_widget); } gtk_widget_show(args->secondary_source_container); color_source_activate(source); } } static void secondary_view_cb(GtkWidget *widget, AppArgs *args) { if (gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(widget))){ ColorSource *source = static_cast(g_object_get_data(G_OBJECT(widget), "source")); activate_secondary_source(args, source); } } static void create_menu(GtkMenuBar *menu_bar, AppArgs *args, GtkAccelGroup *accel_group) { GtkMenu *menu; GtkWidget *item; GtkWidget* file_item; GtkStockItem stock_item; menu = GTK_MENU(gtk_menu_new()); FileMenuItems *items = new FileMenuItems(); if (gtk_stock_lookup(GTK_STOCK_NEW, &stock_item)){ item = gtk_menu_item_new_with_image(stock_item.label, gtk_image_new_from_stock(stock_item.stock_id, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL (menu), item); if (stock_item.keyval) gtk_widget_add_accelerator(item, "activate", accel_group, stock_item.keyval, stock_item.modifier, GTK_ACCEL_VISIBLE); g_signal_connect(G_OBJECT (item), "activate", G_CALLBACK(menu_file_new), args); } if (gtk_stock_lookup(GTK_STOCK_OPEN, &stock_item)){ item = gtk_menu_item_new_with_image(stock_item.label, gtk_image_new_from_stock(stock_item.stock_id, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); if (stock_item.keyval) gtk_widget_add_accelerator(item, "activate", accel_group, stock_item.keyval, stock_item.modifier, GTK_ACCEL_VISIBLE); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(menu_file_open), args); } item = gtk_menu_item_new_with_mnemonic(_("Recent _Files")); items->recent_files = item; gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); if (gtk_stock_lookup(GTK_STOCK_REVERT_TO_SAVED, &stock_item)){ item = gtk_menu_item_new_with_image(stock_item.label, gtk_image_new_from_stock(stock_item.stock_id, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); gtk_widget_add_accelerator(item, "activate", accel_group, GDK_KEY_r, GdkModifierType(GDK_CONTROL_MASK), GTK_ACCEL_VISIBLE); gtk_widget_add_accelerator(item, "activate", accel_group, GDK_KEY_F5, GdkModifierType(0), GTK_ACCEL_VISIBLE); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(menu_file_revert), args); } gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new ()); if (gtk_stock_lookup(GTK_STOCK_SAVE, &stock_item)){ item = gtk_menu_item_new_with_image (stock_item.label, gtk_image_new_from_stock(stock_item.stock_id, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); if (stock_item.keyval) gtk_widget_add_accelerator (item, "activate", accel_group, stock_item.keyval, stock_item.modifier, GTK_ACCEL_VISIBLE); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK(menu_file_save), args); } if (gtk_stock_lookup(GTK_STOCK_SAVE_AS, &stock_item)){ item = gtk_menu_item_new_with_image (stock_item.label, gtk_image_new_from_stock(stock_item.stock_id, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); if (stock_item.keyval) gtk_widget_add_accelerator (item, "activate", accel_group, stock_item.keyval, stock_item.modifier, GTK_ACCEL_VISIBLE); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK(menu_file_save_as), args); } gtk_menu_shell_append (GTK_MENU_SHELL (menu), gtk_separator_menu_item_new ()); item = gtk_image_menu_item_new_with_mnemonic(_("Ex_port...")); gtk_widget_add_accelerator(item, "activate", accel_group, GDK_KEY_e, GdkModifierType(GDK_CONTROL_MASK), GTK_ACCEL_VISIBLE); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect(G_OBJECT (item), "activate", G_CALLBACK (menu_file_export_all), args); items->export_all = item; item = gtk_image_menu_item_new_with_mnemonic(_("Expo_rt Selected...")); gtk_widget_add_accelerator(item, "activate", accel_group, GDK_KEY_e, GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK), GTK_ACCEL_VISIBLE); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect(G_OBJECT (item), "activate", G_CALLBACK (menu_file_export), args); items->export_selected = item; item = gtk_image_menu_item_new_with_mnemonic(_("_Import...")); gtk_widget_add_accelerator(item, "activate", accel_group, GDK_KEY_i, GdkModifierType(GDK_CONTROL_MASK), GTK_ACCEL_VISIBLE); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect(G_OBJECT (item), "activate", G_CALLBACK (menu_file_import), args); item = gtk_image_menu_item_new_with_mnemonic(_("Import _Text File...")); gtk_widget_add_accelerator(item, "activate", accel_group, GDK_KEY_i, GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK), GTK_ACCEL_VISIBLE); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(menu_file_import_text_file), args); gtk_menu_shell_append (GTK_MENU_SHELL (menu), gtk_separator_menu_item_new ()); if (gtk_stock_lookup(GTK_STOCK_QUIT, &stock_item)){ item = gtk_menu_item_new_with_image (stock_item.label, gtk_image_new_from_stock(stock_item.stock_id, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); if (stock_item.keyval) gtk_widget_add_accelerator (item, "activate", accel_group, stock_item.keyval, stock_item.modifier, GTK_ACCEL_VISIBLE); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK(destroy_cb), args); } file_item = gtk_menu_item_new_with_mnemonic(_("_File")); g_signal_connect (G_OBJECT (file_item), "activate", G_CALLBACK (menu_file_activate), args); g_object_set_data_full(G_OBJECT(file_item), "items", items, (GDestroyNotify)destroy_file_menu_items); gtk_menu_item_set_submenu (GTK_MENU_ITEM (file_item),GTK_WIDGET( menu)); gtk_menu_shell_append (GTK_MENU_SHELL (menu_bar), file_item); menu = GTK_MENU(gtk_menu_new()); item = gtk_menu_item_new_with_image(_("Edit _Converters..."), gtk_image_new_from_stock(GTK_STOCK_PROPERTIES, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK (show_dialog_converter), args); item = gtk_menu_item_new_with_image(_("Display _Filters..."), gtk_image_new_from_stock(GTK_STOCK_PROPERTIES, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK (show_dialog_transformations), args); item = gtk_menu_item_new_with_image(_("Color _Dictionaries..."), gtk_image_new_from_stock(GTK_STOCK_PROPERTIES, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(show_dialog_color_dictionaries), args); if (gtk_stock_lookup(GTK_STOCK_PREFERENCES, &stock_item)){ item = gtk_menu_item_new_with_image (stock_item.label, gtk_image_new_from_stock(stock_item.stock_id, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); if (stock_item.keyval) gtk_widget_add_accelerator (item, "activate", accel_group, stock_item.keyval, stock_item.modifier, GTK_ACCEL_VISIBLE); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK(show_dialog_options), args); } file_item = gtk_menu_item_new_with_mnemonic(_("_Edit")); gtk_menu_item_set_submenu (GTK_MENU_ITEM (file_item),GTK_WIDGET( menu)); gtk_menu_shell_append (GTK_MENU_SHELL (menu_bar), file_item); menu = GTK_MENU(gtk_menu_new()); GtkMenu *menu2 = GTK_MENU(gtk_menu_new()); GSList *group = nullptr; ColorSource *source = color_source_manager_get(args->csm, dynv_get_string_wd(args->params, "secondary_color_source", "")); item = gtk_radio_menu_item_new_with_label(group, _("None")); group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(item)); if (source == nullptr) gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item), true); g_object_set_data_full(G_OBJECT(item), "source", 0, (GDestroyNotify)nullptr); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(secondary_view_cb), args); gtk_widget_add_accelerator(item, "activate", accel_group, GDK_KEY_N, GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK), GTK_ACCEL_VISIBLE); gtk_menu_shell_append(GTK_MENU_SHELL(menu2), item); vector sources = color_source_manager_get_all(args->csm); for (uint32_t i = 0; i < sources.size(); i++){ if (!(sources[i]->single_instance_only)){ item = gtk_radio_menu_item_new_with_label(group, sources[i]->hr_name); group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(item)); if (source == sources[i]) gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item), true); g_object_set_data_full(G_OBJECT(item), "source", sources[i], (GDestroyNotify)nullptr); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(secondary_view_cb), args); if (color_source_get_default_accelerator(sources[i])) gtk_widget_add_accelerator(item, "activate", accel_group, color_source_get_default_accelerator(sources[i]), GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK), GTK_ACCEL_VISIBLE); gtk_menu_shell_append(GTK_MENU_SHELL(menu2), item); } } item = gtk_menu_item_new_with_mnemonic(_("_Secondary View")); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); gtk_menu_item_set_submenu(GTK_MENU_ITEM(item), GTK_WIDGET(menu2)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); item = gtk_check_menu_item_new_with_mnemonic(_("Palette")); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item), dynv_get_bool_wd(args->params, "view.palette", true)); gtk_widget_add_accelerator(item, "activate", accel_group, GDK_KEY_p, GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK), GTK_ACCEL_VISIBLE); g_signal_connect(G_OBJECT(item), "toggled", G_CALLBACK(view_palette_cb), args); file_item = gtk_menu_item_new_with_mnemonic (_("_View")); gtk_menu_item_set_submenu (GTK_MENU_ITEM (file_item),GTK_WIDGET( menu)); gtk_menu_shell_append (GTK_MENU_SHELL (menu_bar), file_item); menu = GTK_MENU(gtk_menu_new()); item = gtk_menu_item_new_with_mnemonic(_("Palette From _Image...")); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(palette_from_image_cb), args); item = gtk_menu_item_new_with_mnemonic(_("Color Space _Sampler...")); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(color_space_sampler_cb), args); file_item = gtk_menu_item_new_with_mnemonic(_("_Tools")); gtk_menu_item_set_submenu(GTK_MENU_ITEM(file_item), GTK_WIDGET(menu)); gtk_menu_shell_append(GTK_MENU_SHELL(menu_bar), file_item); menu = GTK_MENU(gtk_menu_new()); if (gtk_stock_lookup(GTK_STOCK_ABOUT, &stock_item)){ item = gtk_menu_item_new_with_image (stock_item.label, gtk_image_new_from_stock(stock_item.stock_id, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); if (stock_item.keyval) gtk_widget_add_accelerator (item, "activate", accel_group, stock_item.keyval, stock_item.modifier, GTK_ACCEL_VISIBLE); g_signal_connect (G_OBJECT (item), "activate", G_CALLBACK(show_about_box_cb), args); } file_item = gtk_menu_item_new_with_mnemonic (_("_Help")); gtk_menu_item_set_submenu (GTK_MENU_ITEM (file_item),GTK_WIDGET( menu)); gtk_menu_shell_append (GTK_MENU_SHELL (menu_bar), file_item); } void converter_get_text(const gchar* function, ColorObject* color_object, GtkWidget* palette_widget, Converters *converters, gchar** out_text) { stringstream text(ios::out); ColorList *color_list = color_list_new(); if (palette_widget){ palette_list_foreach_selected(palette_widget, color_list_selected, color_list); }else{ color_list_add_color_object(color_list, color_object, 1); } ConverterSerializePosition position; position.first = true; position.last = false; position.index = 0; position.count = color_list->colors.size(); if (position.count > 0){ string text_line; for (ColorList::iter i = color_list->colors.begin(); i != color_list->colors.end(); ++i){ if (position.index + 1 == position.count) position.last = true; if (converters_color_serialize(converters, function, *i, position, text_line) == 0){ if (position.first){ text << text_line; position.first = false; }else{ text << endl << text_line; } position.index++; } } } color_list_destroy(color_list); if (text.str().length() > 0){ *out_text = g_strdup(text.str().c_str()); }else{ *out_text = 0; } } static PaletteListCallbackReturn color_list_mark_selected(ColorObject* color_object, void *userdata) { color_object->setSelected(true); return PALETTE_LIST_CALLBACK_NO_UPDATE; } static void palette_popup_menu_remove_all(GtkWidget *widget, AppArgs* args) { color_list_remove_all(args->gs->getColorList()); } static void palette_popup_menu_remove_selected(GtkWidget *widget, AppArgs* args) { palette_list_foreach_selected(args->color_list, color_list_mark_selected, 0); color_list_remove_selected(args->gs->getColorList()); } static PaletteListCallbackReturn color_list_clear_names(ColorObject* color_object, void *userdata) { color_object->setName(""); return PALETTE_LIST_CALLBACK_UPDATE_NAME; } static void palette_popup_menu_clear_names(GtkWidget *widget, AppArgs* args) { palette_list_foreach_selected(args->color_list, color_list_clear_names, nullptr); } typedef struct AutonameState{ ColorNames *color_names; bool imprecision_postfix; }AutonameState; static PaletteListCallbackReturn color_list_autoname(ColorObject* color_object, void *userdata) { AutonameState *state = (AutonameState *)(userdata); Color color = color_object->getColor(); color_object->setName(color_names_get(state->color_names, &color, state->imprecision_postfix)); return PALETTE_LIST_CALLBACK_UPDATE_NAME; } static void palette_popup_menu_autoname(GtkWidget *widget, AppArgs* args) { AutonameState state; state.color_names = args->gs->getColorNames(); state.imprecision_postfix = dynv_get_bool_wd(args->gs->getSettings(), "gpick.color_names.imprecision_postfix", true); palette_list_foreach_selected(args->color_list, color_list_autoname, &state); } typedef struct AutonumberState{ std::string name; uint32_t index; uint32_t nplaces; bool decreasing; bool append; }AutonumberState; static PaletteListCallbackReturn color_list_autonumber(ColorObject* color_object, void *userdata) { AutonumberState *state = (AutonumberState*)userdata; stringstream ss; if (state->append == true){ ss << color_object->getName() << " "; } ss << state->name << "-"; ss.width(state->nplaces); ss.fill('0'); if (state->decreasing){ ss << right << state->index; state->index--; } else{ ss << right << state->index++; } color_object->setName(ss.str()); return PALETTE_LIST_CALLBACK_UPDATE_NAME; } static PaletteListCallbackReturn color_list_set_color(ColorObject* color_object, void *userdata) { Color *source_color = (Color *)(userdata); color_object->setColor(*source_color); return PALETTE_LIST_CALLBACK_UPDATE_ROW; } static void palette_popup_menu_autonumber(GtkWidget *widget, AppArgs* args) { AutonumberState state; int response; uint32_t selected_count = palette_list_get_selected_count(args->color_list); response = dialog_autonumber_show(GTK_WINDOW(args->window), selected_count, args->gs); if (response == GTK_RESPONSE_OK){ struct dynvSystem *params; params = dynv_get_dynv(args->gs->getSettings(), "gpick.autonumber"); state.name = dynv_get_string_wd(params, "name", "autonum"); state.nplaces = dynv_get_int32_wd(params, "nplaces", 1); state.index = dynv_get_int32_wd(params, "startindex", 1); state.decreasing = dynv_get_bool_wd(params, "decreasing", true); state.append = dynv_get_bool_wd(params, "append", true); palette_list_foreach_selected(args->color_list, color_list_autonumber, &state); dynv_system_release(params); } } typedef struct ReplaceState{ std::list::reverse_iterator iter; } ReplaceState; static PaletteListCallbackReturn color_list_reverse_replace(ColorObject** color_object, void *userdata) { ReplaceState *state = reinterpret_cast(userdata); *color_object = (*(state->iter))->reference(); state->iter++; return PALETTE_LIST_CALLBACK_UPDATE_ROW; } static void palette_popup_menu_reverse(GtkWidget *widget, AppArgs* args) { ColorList *color_list = color_list_new(); ReplaceState state; palette_list_foreach_selected(args->color_list, color_list_selected, color_list); state.iter = color_list->colors.rbegin(); palette_list_foreach_selected(args->color_list, color_list_reverse_replace, &state); } gint32 palette_popup_menu_mix_list(Color* color, void *userdata) { *((GList**)userdata) = g_list_append(*((GList**)userdata), color); return 0; } static void palette_popup_menu_mix(GtkWidget *widget, AppArgs* args) { ColorList *color_list = color_list_new(); palette_list_foreach_selected(args->color_list, color_list_selected, color_list); dialog_mix_show(GTK_WINDOW(args->window), color_list, args->gs); color_list_destroy(color_list); } static void palette_popup_menu_variations(GtkWidget *widget, AppArgs* args) { struct dynvHandlerMap* handler_map = dynv_system_get_handler_map(args->gs->getSettings()); ColorList *color_list = color_list_new(handler_map); palette_list_foreach_selected(args->color_list, color_list_selected, color_list); dialog_variations_show(GTK_WINDOW(args->window), color_list, args->gs); color_list_destroy(color_list); dynv_handler_map_release(handler_map); } static void palette_popup_menu_generate(GtkWidget *widget, AppArgs* args) { ColorList *color_list = color_list_new(); palette_list_foreach_selected(args->color_list, color_list_selected, color_list); dialog_generate_show(GTK_WINDOW(args->window), color_list, args->gs); color_list_destroy(color_list); } typedef struct GroupAndSortState{ std::list::iterator iter; } GroupAndSortState; static PaletteListCallbackReturn color_list_group_and_sort_replace(ColorObject** color_object, void *userdata) { GroupAndSortState *state = reinterpret_cast(userdata); *color_object = (*(state->iter))->reference(); state->iter++; return PALETTE_LIST_CALLBACK_UPDATE_ROW; } static void palette_popup_menu_group_and_sort(GtkWidget *widget, AppArgs* args) { ColorList *color_list = color_list_new(); ColorList *sorted_color_list = color_list_new(); palette_list_foreach_selected(args->color_list, color_list_selected, color_list); if (dialog_sort_show(GTK_WINDOW(args->window), color_list, sorted_color_list, args->gs)){ GroupAndSortState state; state.iter = sorted_color_list->colors.begin(); palette_list_foreach_selected(args->color_list, color_list_group_and_sort_replace, &state); } color_list_destroy(color_list); color_list_destroy(sorted_color_list); } static gboolean palette_popup_menu_show(GtkWidget *widget, GdkEventButton* event, AppArgs *args) { GtkWidget *menu; GtkWidget* item ; gint32 button, event_time; menu = gtk_menu_new(); GtkAccelGroup *accel_group = gtk_accel_group_new(); gtk_menu_set_accel_group(GTK_MENU(menu), accel_group); gint32 selected_count = palette_list_get_selected_count(args->color_list); gint32 total_count = palette_list_get_count(args->color_list); if (total_count > 0 && selected_count >= 1){ ColorList *color_list = color_list_new(); palette_list_forfirst_selected(args->color_list, color_list_selected, color_list); if (color_list_get_count(color_list) != 0){ StandardMenu::appendMenu(menu, *color_list->colors.begin(), args->color_list, args->gs); }else{ StandardMenu::appendMenu(menu); } color_list_destroy(color_list); }else{ StandardMenu::appendMenu(menu); } gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); item = gtk_menu_item_new_with_image (_("_Mix Colors..."), gtk_image_new_from_stock(GTK_STOCK_CONVERT, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect(G_OBJECT (item), "activate", G_CALLBACK(palette_popup_menu_mix), args); gtk_widget_set_sensitive(item, (selected_count >= 2)); item = gtk_menu_item_new_with_image (_("_Variations..."), gtk_image_new_from_stock(GTK_STOCK_CONVERT, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect(G_OBJECT (item), "activate", G_CALLBACK(palette_popup_menu_variations), args); gtk_widget_set_sensitive(item, (selected_count >= 1)); item = gtk_menu_item_new_with_image (_("_Generate..."), gtk_image_new_from_stock(GTK_STOCK_CONVERT, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect(G_OBJECT (item), "activate", G_CALLBACK(palette_popup_menu_generate), args); gtk_widget_set_sensitive(item, (selected_count >= 1)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), gtk_separator_menu_item_new ()); item = gtk_menu_item_new_with_mnemonic (_("C_lear names")); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect(G_OBJECT (item), "activate", G_CALLBACK(palette_popup_menu_clear_names), args); gtk_widget_add_accelerator(item, "activate", accel_group, GDK_KEY_E, GdkModifierType(0), GTK_ACCEL_VISIBLE); gtk_widget_set_sensitive(item, (selected_count >= 1)); item = gtk_menu_item_new_with_mnemonic (_("Autona_me")); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect(G_OBJECT (item), "activate", G_CALLBACK(palette_popup_menu_autoname), args); gtk_widget_add_accelerator(item, "activate", accel_group, GDK_KEY_N, GdkModifierType(0), GTK_ACCEL_VISIBLE); gtk_widget_set_sensitive(item, (selected_count >= 1)); item = gtk_menu_item_new_with_mnemonic (_("Auto_number...")); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect(G_OBJECT (item), "activate", G_CALLBACK(palette_popup_menu_autonumber), args); gtk_widget_add_accelerator(item, "activate", accel_group, GDK_KEY_a, GdkModifierType(0), GTK_ACCEL_VISIBLE); gtk_widget_set_sensitive(item, (selected_count >= 1)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), gtk_separator_menu_item_new ()); item = gtk_menu_item_new_with_mnemonic(_("R_everse")); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect(G_OBJECT (item), "activate", G_CALLBACK(palette_popup_menu_reverse), args); gtk_widget_add_accelerator(item, "activate", accel_group, GDK_KEY_v, GdkModifierType(0), GTK_ACCEL_VISIBLE); gtk_widget_set_sensitive(item, (selected_count >= 2)); item = gtk_menu_item_new_with_mnemonic(_("Group and _sort...")); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(palette_popup_menu_group_and_sort), args); gtk_widget_add_accelerator(item, "activate", accel_group, GDK_KEY_g, GdkModifierType(0), GTK_ACCEL_VISIBLE); gtk_widget_set_sensitive(item, (selected_count >= 2)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), gtk_separator_menu_item_new ()); item = gtk_menu_item_new_with_image (_("_Remove"), gtk_image_new_from_stock(GTK_STOCK_REMOVE, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect(G_OBJECT (item), "activate", G_CALLBACK(palette_popup_menu_remove_selected), args); gtk_widget_add_accelerator(item, "activate", accel_group, GDK_KEY_Delete, GdkModifierType(0), GTK_ACCEL_VISIBLE); gtk_widget_set_sensitive(item, (selected_count >= 1)); item = gtk_menu_item_new_with_image (_("Remove _All"), gtk_image_new_from_stock(GTK_STOCK_REMOVE, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append (GTK_MENU_SHELL (menu), item); g_signal_connect(G_OBJECT (item), "activate", G_CALLBACK(palette_popup_menu_remove_all), args); gtk_widget_set_sensitive(item, (total_count >= 1)); gtk_widget_show_all (GTK_WIDGET(menu)); if (event){ button = event->button; event_time = event->time; }else{ button = 0; event_time = gtk_get_current_event_time (); } gtk_menu_popup(GTK_MENU(menu), nullptr, nullptr, nullptr, nullptr, button, event_time); g_object_ref_sink(G_OBJECT(accel_group)); g_object_unref(G_OBJECT(accel_group)); g_object_ref_sink(menu); g_object_unref(menu); return TRUE; } static void on_palette_popup_menu(GtkWidget *widget, AppArgs *args) { palette_popup_menu_show(widget, 0, args); } static gboolean on_palette_button_press(GtkWidget *widget, GdkEventButton *event, AppArgs *args) { if (event->button == 3 && event->type == GDK_BUTTON_PRESS) { return palette_popup_menu_show(widget, event, args); } return FALSE; } static gboolean on_palette_list_key_press(GtkWidget *widget, GdkEventKey *event, AppArgs *args) { guint modifiers = gtk_accelerator_get_default_mod_mask(); switch(event->keyval) { case GDK_KEY_1: case GDK_KEY_KP_1: case GDK_KEY_2: case GDK_KEY_KP_2: case GDK_KEY_3: case GDK_KEY_KP_3: case GDK_KEY_4: case GDK_KEY_KP_4: case GDK_KEY_5: case GDK_KEY_KP_5: case GDK_KEY_6: case GDK_KEY_KP_6: { ColorList *color_list = color_list_new(); palette_list_forfirst_selected(args->color_list, color_list_selected, color_list); if (color_list_get_count(color_list) > 0){ ColorSource *color_source = args->gs->getCurrentColorSource(); uint32_t color_index = 0; switch(event->keyval) { case GDK_KEY_KP_1: case GDK_KEY_1: color_index = 0; break; case GDK_KEY_KP_2: case GDK_KEY_2: color_index = 1; break; case GDK_KEY_KP_3: case GDK_KEY_3: color_index = 2; break; case GDK_KEY_KP_4: case GDK_KEY_4: color_index = 3; break; case GDK_KEY_KP_5: case GDK_KEY_5: color_index = 4; break; case GDK_KEY_KP_6: case GDK_KEY_6: color_index = 5; break; } if ((event->state&modifiers) == GDK_CONTROL_MASK){ ColorObject *source_color_object; Color source_color; color_source_get_nth_color(color_source, color_index, &source_color_object); source_color = source_color_object->getColor(); palette_list_forfirst_selected (args->color_list, color_list_set_color, &source_color); } else{ color_source_set_nth_color(color_source, color_index, *color_list->colors.begin()); } } color_list_destroy(color_list); return true; } return false; break; case GDK_KEY_c: if ((event->state & modifiers) == GDK_CONTROL_MASK){ Clipboard::set(args->color_list, args->gs); return true; } return false; break; case GDK_KEY_v: if ((event->state&modifiers) == GDK_CONTROL_MASK){ ColorObject* color_object; if (copypaste_get_color_object(&color_object, args->gs) == 0){ color_list_add_color_object(args->gs->getColorList(), color_object, 1); color_object->release(); } return true; }else{ palette_popup_menu_reverse(widget, args); return true; } return false; break; case GDK_KEY_g: palette_popup_menu_group_and_sort(widget, args); return true; break; case GDK_KEY_Delete: palette_popup_menu_remove_selected(widget, args); break; case GDK_KEY_a: if ((event->state & GDK_CONTROL_MASK) == 0){ palette_popup_menu_autonumber(widget, args); return true; } break; case GDK_KEY_e: if ((event->state & GDK_CONTROL_MASK) == 0){ palette_popup_menu_clear_names(widget, args); return true; } break; case GDK_KEY_n: if ((event->state & GDK_CONTROL_MASK) == 0){ palette_popup_menu_autoname(widget, args); return true; } break; default: return false; break; } return false; } static int color_list_on_insert(ColorList* color_list, ColorObject* color_object) { palette_list_add_entry(((AppArgs*)color_list->userdata)->color_list, color_object); return 0; } static int color_list_on_delete_selected(ColorList* color_list) { palette_list_remove_selected_entries(((AppArgs*)color_list->userdata)->color_list); return 0; } static int color_list_on_delete(ColorList* color_list, ColorObject* color_object) { palette_list_remove_entry(((AppArgs*)color_list->userdata)->color_list, color_object); return 0; } static int color_list_on_clear(ColorList* color_list) { palette_list_remove_all_entries(((AppArgs*)color_list->userdata)->color_list); return 0; } static PaletteListCallbackReturn callback_color_list_on_get_positions(ColorObject* color_object, size_t *position) { color_object->setPosition(*position); (*position)++; return PALETTE_LIST_CALLBACK_NO_UPDATE; } static int color_list_on_get_positions(ColorList* color_list) { size_t position = 0; palette_list_foreach(((AppArgs*)color_list->userdata)->color_list, (PaletteListCallback)callback_color_list_on_get_positions, &position); return 0; } int main_show_window(GtkWidget* window, struct dynvSystem *main_params) { if (gtk_widget_get_visible(window)){ gtk_window_deiconify(GTK_WINDOW(window)); return -1; //already visible } gint x, y; gint width, height; x = dynv_get_int32_wd(main_params, "window.x", -1); y = dynv_get_int32_wd(main_params, "window.y", -1); width = dynv_get_int32_wd(main_params, "window.width", -1); height = dynv_get_int32_wd(main_params, "window.height", -1); if (x < 0 || y < 0 || x > gdk_screen_width() || y > gdk_screen_height()){ gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); }else{ gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_NONE); gtk_window_move(GTK_WINDOW(window), x, y); } if (width > 0 && height > 0) gtk_window_resize(GTK_WINDOW(window), width, height); gtk_widget_show(window); return 0; } static gboolean on_window_focus_change(GtkWidget *widget, GdkEventFocus *event, AppArgs* args) { if (event->in){ if (args->secondary_color_source) color_source_activate(args->secondary_color_source); if (args->current_color_source) color_source_activate(args->current_color_source); }else{ if (args->secondary_color_source) color_source_deactivate(args->secondary_color_source); if (args->current_color_source) color_source_deactivate(args->current_color_source); } return FALSE; } static void set_main_window_icon() { GList *icons = 0; GtkIconTheme *icon_theme; GError *error = nullptr; icon_theme = gtk_icon_theme_get_default(); gint sizes[] = {16, 32, 48, 128}; for (guint32 i = 0; i < sizeof(sizes) / sizeof(gint); ++i) { GdkPixbuf* pixbuf = gtk_icon_theme_load_icon(icon_theme, "gpick", sizes[i], GtkIconLookupFlags(0), &error); if (pixbuf && (error == nullptr)){ icons = g_list_append(icons, pixbuf); } if (error){ cerr << error->message << endl; g_error_free(error); error = nullptr; } } if (icons){ gtk_window_set_default_icon_list(icons); g_list_foreach(icons, (GFunc)g_object_unref, nullptr); g_list_free(icons); } } bool app_is_autoload_enabled(AppArgs *args) { return dynv_get_bool_wd(args->params, "main.save_restore_palette", true); } static void app_initialize_variables(AppArgs *args) { args->current_filename_set = false; args->imported = false; args->precision_loss_icon = 0; args->current_color_source = 0; args->secondary_color_source = 0; args->secondary_source_widget = 0; args->secondary_source_scrolled_viewpoint = 0; args->gs->loadAll(); dialog_options_update(args->gs->getLua(), args->gs->getSettings()); args->params = dynv_get_dynv(args->gs->getSettings(), "gpick.main"); args->csm = color_source_manager_create(); register_sources(args->csm); } static void app_initialize_color_list(AppArgs *args) { args->gs->getColorList()->on_insert = color_list_on_insert; args->gs->getColorList()->on_clear = color_list_on_clear; args->gs->getColorList()->on_delete_selected = color_list_on_delete_selected; args->gs->getColorList()->on_get_positions = color_list_on_get_positions; args->gs->getColorList()->on_delete = color_list_on_delete; args->gs->getColorList()->userdata = args; } static void app_initialize_floating_picker(AppArgs *args) { args->floating_picker = floating_picker_new(args->gs); } static void app_initialize_picker(AppArgs *args, GtkWidget *notebook) { ColorSource *source; struct dynvSystem *dynv_namespace; dynv_namespace = dynv_get_dynv(args->gs->getSettings(), "gpick.picker"); source = color_source_implement(color_source_manager_get(args->csm, "color_picker"), args->gs, dynv_namespace); GtkWidget *widget = color_source_get_widget(source); dynv_system_release(dynv_namespace); args->color_source[source->identificator] = source; args->color_source_index.push_back(source); floating_picker_set_picker_source(args->floating_picker, source); color_picker_set_floating_picker(source, args->floating_picker); gtk_notebook_append_page(GTK_NOTEBOOK(notebook), widget, gtk_label_new_with_mnemonic(_("Color pic_ker"))); gtk_widget_show(widget); } void app_initialize() { GtkIconTheme *icon_theme = gtk_icon_theme_get_default(); gchar *tmp; gtk_icon_theme_append_search_path(icon_theme, tmp = build_filename(nullptr)); g_free(tmp); } AppArgs* app_create_main(const AppOptions &options, int &return_value) { AppArgs* args = new AppArgs; args->initialization = true; args->options = options; color_init(); args->gs = new GlobalState(); args->gs->loadSettings(); if (args->options.single_color_pick_mode){ app_initialize_variables(args); app_initialize_floating_picker(args); args->initialization = false; return args; // No main UI initialization needed }else{ args->dbus_control.onActivateFloatingPicker = [args](const char *converter_name){ if (converter_name != nullptr && string(converter_name).length() > 0){ floating_picker_activate(args->floating_picker, false, false, converter_name); }else{ floating_picker_activate(args->floating_picker, false, false, nullptr); } return true; }; args->dbus_control.onSingleInstanceActivate = [args]{ status_icon_set_visible(args->status_icon, false); main_show_window(args->window, args->params); return true; }; args->dbus_control.ownName(); bool cancel_startup = false; if (!cancel_startup && args->options.floating_picker_mode){ if (args->dbus_control.activateFloatingPicker(args->options.converter_name)){ cancel_startup = true; }else if (args->options.do_not_start){ return_value = 1; cancel_startup = true; } } if (args->options.do_not_start){ if (args->dbus_control.checkIfRunning()){ return_value = 1; cancel_startup = true; } } if (!cancel_startup && dynv_get_bool_wd(args->gs->getSettings(), "gpick.main.single_instance", false)){ if (args->dbus_control.singleInstanceActivate()){ cancel_startup = true; } } if (cancel_startup){ delete args; return 0; } app_initialize_variables(args); app_initialize_color_list(args); } args->window = gtk_window_new(GTK_WINDOW_TOPLEVEL); set_main_window_icon(); app_update_program_name(args); g_signal_connect(G_OBJECT(args->window), "delete_event", G_CALLBACK(delete_event), args); g_signal_connect(G_OBJECT(args->window), "destroy", G_CALLBACK(destroy_cb), args); g_signal_connect(G_OBJECT(args->window), "configure-event", G_CALLBACK(on_window_configure), args); g_signal_connect(G_OBJECT(args->window), "window-state-event", G_CALLBACK(on_window_state_event), args); g_signal_connect(G_OBJECT(args->window), "focus-in-event", G_CALLBACK(on_window_focus_change), args); g_signal_connect(G_OBJECT(args->window), "focus-out-event", G_CALLBACK(on_window_focus_change), args); GtkAccelGroup *accel_group = gtk_accel_group_new(); gtk_window_add_accel_group(GTK_WINDOW(args->window), accel_group); g_object_unref(G_OBJECT (accel_group)); GtkWidget *widget, *statusbar, *notebook, *vpaned, *hpaned; GtkWidget* vbox_main = gtk_vbox_new(false, 0); gtk_container_add (GTK_CONTAINER(args->window), vbox_main); GtkWidget* menu_bar; menu_bar = gtk_menu_bar_new (); gtk_box_pack_start (GTK_BOX(vbox_main), menu_bar, FALSE, FALSE, 0); hpaned = gtk_hpaned_new(); bool color_list_visible = dynv_get_bool_wd(args->params, "view.palette", true); vpaned = gtk_vpaned_new(); args->vpaned = vpaned; if (color_list_visible) gtk_paned_pack1(GTK_PANED(hpaned), vpaned, false, false); else gtk_box_pack_start(GTK_BOX(vbox_main), vpaned, TRUE, TRUE, 5); notebook = gtk_notebook_new(); g_signal_connect(G_OBJECT(notebook), "switch-page", G_CALLBACK(notebook_switch_cb), args); gtk_notebook_set_scrollable(GTK_NOTEBOOK(notebook), true); statusbar = gtk_statusbar_new(); args->gs->setStatusBar(statusbar); gtk_paned_pack1(GTK_PANED(vpaned), notebook, false, false); if (color_list_visible){ gtk_box_pack_start(GTK_BOX(vbox_main), hpaned, TRUE, TRUE, 5); gtk_widget_show_all(vbox_main); }else{ gtk_widget_show_all(vbox_main); gtk_box_pack_start(GTK_BOX(vbox_main), hpaned, TRUE, TRUE, 5); } ColorSource *source; struct dynvSystem *dynv_namespace; app_initialize_floating_picker(args); app_initialize_picker(args, notebook); dynv_namespace = dynv_get_dynv(args->gs->getSettings(), "gpick.generate_scheme"); source = color_source_implement(color_source_manager_get(args->csm, "generate_scheme"), args->gs, dynv_namespace); widget = color_source_get_widget(source); dynv_system_release(dynv_namespace); args->color_source[source->identificator] = source; args->color_source_index.push_back(source); gtk_notebook_append_page(GTK_NOTEBOOK(notebook), widget, gtk_label_new_with_mnemonic(_("Scheme _generation"))); gtk_widget_show(widget); { widget = gtk_vbox_new(false, 0); gtk_paned_pack2(GTK_PANED(vpaned), widget, false, false); args->secondary_source_container = widget; source = color_source_manager_get(args->csm, dynv_get_string_wd(args->params, "secondary_color_source", "")); if (source) activate_secondary_source(args, source); } dynv_namespace = dynv_get_dynv(args->gs->getSettings(), "gpick.layout_preview"); source = color_source_implement(color_source_manager_get(args->csm, "layout_preview"), args->gs, dynv_namespace); widget = color_source_get_widget(source); dynv_system_release(dynv_namespace); args->color_source[source->identificator] = source; args->color_source_index.push_back(source); gtk_notebook_append_page(GTK_NOTEBOOK(notebook), widget, gtk_label_new_with_mnemonic(_("Lay_out preview"))); gtk_widget_show(widget); GtkWidget *count_label = gtk_label_new(""); widget = palette_list_new(args->gs, count_label); args->color_list = widget; gtk_widget_show(widget); g_signal_connect(G_OBJECT(widget), "popup-menu", G_CALLBACK (on_palette_popup_menu), args); g_signal_connect(G_OBJECT(widget), "button-press-event",G_CALLBACK (on_palette_button_press), args); g_signal_connect(G_OBJECT(widget), "key_press_event", G_CALLBACK (on_palette_list_key_press), args); GtkWidget *scrolled_window; scrolled_window = gtk_scrolled_window_new (0,0); gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window),GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW(scrolled_window), GTK_SHADOW_IN); gtk_container_add(GTK_CONTAINER(scrolled_window), args->color_list ); gtk_paned_pack2(GTK_PANED(hpaned), scrolled_window, TRUE, FALSE); gtk_widget_show(scrolled_window); args->hpaned = hpaned; args->notebook = notebook; { const char *tab = dynv_get_string_wd(args->params, "color_source", ""); map::iterator i = args->color_source.find(tab); if (i != args->color_source.end()){ uint32_t tab_index = 0; for (vector::iterator j = args->color_source_index.begin(); j != args->color_source_index.end(); ++j){ if ((*j) == (*i).second){ gtk_notebook_set_current_page(GTK_NOTEBOOK(args->notebook), tab_index); break; } tab_index++; } } } gtk_box_pack_end (GTK_BOX(vbox_main), statusbar, 0, 0, 0); args->statusbar = statusbar; GtkWidget *button = gtk_button_new(); gtk_button_set_focus_on_click(GTK_BUTTON(button), false); g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(floating_picker_show_cb), args); gtk_widget_add_accelerator(button, "clicked", accel_group, GDK_KEY_p, GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE); gtk_widget_set_tooltip_text(button, _("Pick colors (Ctrl+P)")); gtk_container_add(GTK_CONTAINER(button), gtk_image_new_from_icon_name("gpick", GTK_ICON_SIZE_MENU)); gtk_box_pack_end(GTK_BOX(statusbar), button, false, false, 0); gtk_widget_show_all(button); gtk_box_pack_end(GTK_BOX(statusbar), count_label, false, false, 0); gtk_widget_show_all(count_label); widget = gtk_image_new_from_stock(GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_MENU); gtk_widget_set_tooltip_text(widget, _("File is currently in a non-native format, possible loss of precision and/or metadata.")); args->precision_loss_icon = widget; if (args->imported) gtk_widget_show(widget); gtk_box_pack_end(GTK_BOX(statusbar), widget, false, false, 0); gtk_widget_show(statusbar); { //Load recent file list char** recent_array; uint32_t recent_array_size; if ((recent_array = (char**)dynv_get_string_array_wd(args->gs->getSettings(), "gpick.recent.files", 0, 0, &recent_array_size))){ for (uint32_t i = 0; i < recent_array_size; i++){ args->recent_files.push_back(string(recent_array[i])); } delete [] recent_array; } } create_menu(GTK_MENU_BAR(menu_bar), args, accel_group); gtk_widget_show_all(menu_bar); args->status_icon = status_icon_new(args->window, args->gs, args->floating_picker); args->initialization = false; return args; } static void app_release(AppArgs *args) { if (args->current_color_source){ color_source_deactivate(args->current_color_source); args->current_color_source = 0; } if (args->secondary_color_source){ color_source_deactivate(args->secondary_color_source); color_source_destroy(args->secondary_color_source); args->secondary_color_source = 0; args->secondary_source_widget = 0; } for (map::iterator i = args->color_source.begin(); i != args->color_source.end(); ++i){ color_source_destroy((*i).second); } args->color_source.clear(); args->color_source_index.clear(); floating_picker_free(args->floating_picker); if (!args->options.single_color_pick_mode){ if (app_is_autoload_enabled(args)){ gchar* autosave_file = build_config_path("autosave.gpa"); palette_file_save(autosave_file, args->gs->getColorList()); g_free(autosave_file); } } color_list_remove_all(args->gs->getColorList()); } static void app_save_recent_file_list(AppArgs *args) { const char** recent_array; uint32_t recent_array_size; recent_array_size = args->recent_files.size(); recent_array = new const char* [recent_array_size]; uint32_t j = 0; for (list::iterator i = args->recent_files.begin(); i != args->recent_files.end(); i++){ recent_array[j] = (*i).c_str(); j++; } dynv_set_string_array(args->gs->getSettings(), "gpick.recent.files", recent_array, recent_array_size); delete [] recent_array; } class FloatingPickerAction { public: AppArgs *args; bool clipboard_touched; FloatingPickerAction(AppArgs *args) { this->args = args; clipboard_touched = false; } void colorPicked(FloatingPicker fp, const Color &color) { string text; if (args->options.converter_name.length() > 0){ auto converter = converters_get(args->gs->getConverters(), args->options.converter_name.c_str()); auto color_object = color_list_new_color_object(args->gs->getColorList(), &color); converter_get_text(color_object, converter, args->gs, text); color_object->release(); }else{ converter_get_text(color, ConverterArrayType::copy, args->gs, text); } if (text.length() > 0){ if (args->options.output_picked_color){ if (args->options.output_without_newline){ cout << text; }else{ cout << text << endl; } }else{ Clipboard::set(text); clipboard_touched = true; } } } static gboolean close_application(gpointer user_data) { gtk_main_quit(); return FALSE; } void done(FloatingPicker fp) { if (clipboard_touched) g_timeout_add(100, close_application, args); // quiting main gtk loop early will not give enough time for clipboard manager to retrieve the clipboard contents else gtk_main_quit(); } }; int app_run(AppArgs *args) { if (args->options.single_color_pick_mode){ FloatingPickerAction pick_action(args); floating_picker_set_custom_pick_action(args->floating_picker, [&pick_action](FloatingPicker fp, const Color &color){ pick_action.colorPicked(fp, color); }); floating_picker_set_custom_done_action(args->floating_picker, [&pick_action](FloatingPicker fp){ pick_action.done(fp); }); floating_picker_enable_custom_pick_action(args->floating_picker); floating_picker_activate(args->floating_picker, false, true, args->options.converter_name.c_str()); gtk_main(); app_release(args); }else{ gtk_widget_realize(args->window); if (args->options.floating_picker_mode || dynv_get_bool_wd(args->params, "start_in_tray", false)){ status_icon_set_visible(args->status_icon, true); }else{ main_show_window(args->window, args->params); } gtk_paned_set_position(GTK_PANED(args->hpaned), dynv_get_int32_wd(args->params, "paned_position", -1)); gtk_paned_set_position(GTK_PANED(args->vpaned), dynv_get_int32_wd(args->params, "vertical_paned_position", -1)); if (args->options.floating_picker_mode) floating_picker_activate(args->floating_picker, false, false, args->options.converter_name.c_str()); gtk_main(); app_save_recent_file_list(args); args->dbus_control.unownName(); status_icon_destroy(args->status_icon); } args->gs->writeSettings(); dynv_system_release(args->params); delete args->gs; color_source_manager_destroy(args->csm); delete args; return 0; } gpick-gpick-0.2.6rc1/source/uiApp.h000066400000000000000000000044511315430016700170500ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_UI_APP_H_ #define GPICK_UI_APP_H_ #include #include class GlobalState; class ColorObject; class Converters; struct Color; int main_show_window(GtkWidget* window, struct dynvSystem *main_params); typedef struct AppArgs AppArgs; struct AppOptions { bool floating_picker_mode; std::string converter_name; bool output_picked_color; bool output_without_newline; bool single_color_pick_mode; bool do_not_start; }; void app_initialize(); AppArgs* app_create_main(const AppOptions &options, int &return_value); int app_load_file(AppArgs *args, const char *filename, bool autoload = false); int app_run(AppArgs *args); int app_parse_geometry(AppArgs *args, const char *geometry); bool app_is_autoload_enabled(AppArgs *args); #endif /* GPICK_UI_APP_H_ */ gpick-gpick-0.2.6rc1/source/uiColorDictionaries.cpp000066400000000000000000000323261315430016700223010ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "uiColorDictionaries.h" #include "uiUtilities.h" #include "DynvHelpers.h" #include "GlobalState.h" #include "color_names/ColorNames.h" #include "Internationalisation.h" #include #include #include #include #include using namespace std; enum class ColorDictionaryList: int { path = 0, built_in, enable, pointer, n_columns }; struct ColorDictionary { ColorDictionary(): built_in(false), enable(false) { } ColorDictionary(const char *path, bool built_in, bool enable): path(path), built_in(built_in), enable(enable) { } string path; bool built_in, enable; size_t index; bool operator==(const ColorDictionary &color_dictionary) const { if (this == &color_dictionary) return true; if (path == color_dictionary.path && built_in == color_dictionary.built_in && enable == color_dictionary.enable) return true; return false; } }; struct ColorDictionarySort { bool operator()(const ColorDictionary &a, const ColorDictionary &b) { return a.index < b.index; } }; struct ColorDictionariesArgs { GtkWidget *dictionary_list, *file_browser; list color_dictionaries; struct dynvSystem *params; GlobalState *gs; }; static void color_dictionaries_update_row(GtkTreeModel *model, GtkTreeIter *iter1, ColorDictionary *color_dictionary, ColorDictionariesArgs *args) { gtk_list_store_set(GTK_LIST_STORE(model), iter1, ColorDictionaryList::path, color_dictionary->path.c_str(), ColorDictionaryList::enable, color_dictionary->enable, ColorDictionaryList::built_in, color_dictionary->built_in, ColorDictionaryList::pointer, color_dictionary, -1); } static void enable_toggled_cb(GtkCellRendererText *cell, gchar *path, ColorDictionariesArgs *args) { GtkListStore *store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(args->dictionary_list))); GtkTreeIter iter1; gtk_tree_model_get_iter_from_string(GTK_TREE_MODEL(store), &iter1, path); ColorDictionary *color_dictionary; gtk_tree_model_get(GTK_TREE_MODEL(store), &iter1, ColorDictionaryList::pointer, &color_dictionary, -1); color_dictionary->enable = !color_dictionary->enable; gtk_list_store_set(store, &iter1, ColorDictionaryList::enable, color_dictionary->enable, -1); } static GtkWidget* color_dictionaries_list_new(ColorDictionariesArgs *args) { GtkCellRenderer *renderer; GtkTreeViewColumn *col; GtkWidget *view = args->dictionary_list = gtk_tree_view_new(); gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), true); GtkListStore *store = gtk_list_store_new(static_cast(ColorDictionaryList::n_columns), G_TYPE_STRING, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN, G_TYPE_POINTER); col = gtk_tree_view_column_new(); gtk_tree_view_column_set_sizing(col, GTK_TREE_VIEW_COLUMN_AUTOSIZE); gtk_tree_view_column_set_resizable(col, true); gtk_tree_view_column_set_title(col, _("Path")); renderer = gtk_cell_renderer_text_new(); gtk_tree_view_column_pack_start(col, renderer, true); gtk_tree_view_append_column(GTK_TREE_VIEW(view), col); gtk_tree_view_column_add_attribute(col, renderer, "text", static_cast(ColorDictionaryList::path)); col = gtk_tree_view_column_new(); gtk_tree_view_column_set_sizing(col, GTK_TREE_VIEW_COLUMN_GROW_ONLY); gtk_tree_view_column_set_title(col, _("Enable")); renderer = gtk_cell_renderer_toggle_new(); gtk_tree_view_column_pack_start(col, renderer, false); gtk_tree_view_append_column(GTK_TREE_VIEW(view), col); g_signal_connect(renderer, "toggled", reinterpret_cast(enable_toggled_cb), args); gtk_tree_view_column_set_attributes(col, renderer, "active", ColorDictionaryList::enable, nullptr); gtk_tree_view_set_model(GTK_TREE_VIEW(view), GTK_TREE_MODEL(store)); g_object_unref(GTK_TREE_MODEL(store)); GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(view)); gtk_tree_selection_set_mode(selection, GTK_SELECTION_MULTIPLE); gtk_tree_view_set_reorderable(GTK_TREE_VIEW(view), true); return view; } static void add_file(GtkWidget *widget, ColorDictionariesArgs *args) { gchar *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(args->file_browser)); if (filename){ args->color_dictionaries.push_back(ColorDictionary(filename, false, true)); g_free(filename); GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(args->dictionary_list)); GtkTreeIter iter1; gtk_list_store_append(GTK_LIST_STORE(model), &iter1); color_dictionaries_update_row(model, &iter1, &args->color_dictionaries.back(), args); } gchar *current_folder = gtk_file_chooser_get_current_folder(GTK_FILE_CHOOSER(args->file_browser)); if (current_folder){ dynv_set_string(args->params, "current_folder", current_folder); g_free(current_folder); } } static void remove_selected(ColorDictionariesArgs *args) { GtkListStore *store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(args->dictionary_list))); GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(args->dictionary_list)); GtkTreeIter iter1; GList *selected_list = gtk_tree_selection_get_selected_rows(selection, nullptr); list remove_items; { GList *i = selected_list; while (i){ GtkTreeRowReference *row_reference; GtkTreePath *path; bool reference_inserted = false; if ((row_reference = gtk_tree_row_reference_new(GTK_TREE_MODEL(store), (GtkTreePath*) (i->data)))){ if ((path = gtk_tree_row_reference_get_path(row_reference))){ if (gtk_tree_model_get_iter(GTK_TREE_MODEL(store), &iter1, path)){ ColorDictionary *dictionary = nullptr; gtk_tree_model_get(GTK_TREE_MODEL(store), &iter1, static_cast(ColorDictionaryList::pointer), &dictionary, -1); if (!dictionary->built_in){ remove_items.push_back(row_reference); reference_inserted = true; args->color_dictionaries.remove(*dictionary); } } gtk_tree_path_free(path); } if (!reference_inserted) gtk_tree_row_reference_free(row_reference); } i = g_list_next(i); } } for (auto i = remove_items.begin(); i != remove_items.end(); i++){ GtkTreePath *path = gtk_tree_row_reference_get_path(*i); if (gtk_tree_model_get_iter(GTK_TREE_MODEL(store), &iter1, path)){ gtk_list_store_remove(GTK_LIST_STORE(store), &iter1); } gtk_tree_row_reference_free(*i); } g_list_foreach(selected_list, (GFunc)gtk_tree_path_free, nullptr); g_list_free(selected_list); } static gboolean key_press_event(GtkWidget *widget, GdkEventKey *event, ColorDictionariesArgs *args) { switch (event->keyval){ case GDK_KEY_Delete: remove_selected(args); break; default: return false; break; } return false; } static void reorder(ColorDictionariesArgs *args) { GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(args->dictionary_list)); GtkTreeIter iter1; bool valid = gtk_tree_model_get_iter_first(model, &iter1); size_t index = 0; while (valid){ ColorDictionary *color_dictionary; gtk_tree_model_get(GTK_TREE_MODEL(model), &iter1, ColorDictionaryList::pointer, &color_dictionary, -1); color_dictionary->index = index++; valid = gtk_tree_model_iter_next(model, &iter1); } args->color_dictionaries.sort(ColorDictionarySort()); } void dialog_color_dictionaries_show(GtkWindow* parent, GlobalState* gs) { ColorDictionariesArgs *args = new ColorDictionariesArgs; args->gs = gs; args->params = dynv_get_dynv(args->gs->getSettings(), "gpick"); GtkWidget *dialog = gtk_dialog_new_with_buttons(_("Color dictionaries"), parent, GtkDialogFlags(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OK, GTK_RESPONSE_OK, nullptr); gtk_window_set_default_size(GTK_WINDOW(dialog), dynv_get_int32_wd(args->params, "color_dictionaries.window.width", -1), dynv_get_int32_wd(args->params, "color_dictionaries.window.height", -1)); gtk_dialog_set_alternative_button_order(GTK_DIALOG(dialog), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1); GtkWidget* vbox = gtk_vbox_new(false, 5); GtkWidget *list = color_dictionaries_list_new(args); g_signal_connect(G_OBJECT(list), "key_press_event", G_CALLBACK(key_press_event), args); GtkWidget *scrolled = gtk_scrolled_window_new(0, 0); gtk_container_add(GTK_CONTAINER(scrolled), list); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_box_pack_start(GTK_BOX(vbox), scrolled, true, true, 0); gint table_y; GtkWidget* table = gtk_table_new(3, 1, false); gtk_box_pack_start(GTK_BOX(vbox), table, false, false, 0); table_y = 0; GtkWidget *frame = gtk_frame_new(_("Add color dictionary file")); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_NONE); gtk_table_attach(GTK_TABLE(table), frame, 0, 1, table_y, table_y + 1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL), 5, 5); GtkWidget *widget = args->file_browser = gtk_file_chooser_button_new(_("Color dictionary file"), GTK_FILE_CHOOSER_ACTION_OPEN); gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(widget), dynv_get_string_wd(args->params, "current_folder", "")); gtk_container_add(GTK_CONTAINER(frame), widget); g_signal_connect(G_OBJECT(args->file_browser), "file-set", G_CALLBACK(add_file), args); table_y++; bool built_in_found = false; uint32_t dictionary_count = 0; struct dynvSystem** dictionaries = dynv_get_dynv_array_wd(args->params, "color_dictionaries.items", nullptr, 0, &dictionary_count); if (dictionaries){ for (uint32_t i = 0; i < dictionary_count; i++){ ColorDictionary dictionary; dictionary.path = dynv_get_string_wd(dictionaries[i], "path", ""); dictionary.enable = dynv_get_bool_wd(dictionaries[i], "enable", "false"); dictionary.built_in = dynv_get_bool_wd(dictionaries[i], "built_in", "false"); if (dictionary.built_in){ if (dictionary.path == "built_in_0"){ built_in_found = true; dictionary.path = _("Built in"); }else{ dynv_system_release(dictionaries[i]); continue; } } args->color_dictionaries.push_back(dictionary); dynv_system_release(dictionaries[i]); } if (dictionaries) delete [] dictionaries; } if (!built_in_found){ args->color_dictionaries.push_back(ColorDictionary(_("Built in"), true, true)); } GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(list)); for (auto &dictionary: args->color_dictionaries){ GtkTreeIter iter1; gtk_list_store_append(GTK_LIST_STORE(model), &iter1); color_dictionaries_update_row(model, &iter1, &dictionary, args); } gtk_widget_show_all(vbox); gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), vbox, true, true, 5); if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK){ size_t item_count = args->color_dictionaries.size(); if (item_count){ reorder(args); vector serialized; serialized.resize(item_count); size_t i = 0; for (auto &dictionary: args->color_dictionaries){ serialized[i] = dynv_system_create(args->params); if (dictionary.built_in){ dynv_set_string(serialized[i], "path", "built_in_0"); }else{ dynv_set_string(serialized[i], "path", dictionary.path.c_str()); } dynv_set_bool(serialized[i], "enable", dictionary.enable); dynv_set_bool(serialized[i], "built_in", dictionary.built_in); i++; } dynv_set_dynv_array(args->params, "color_dictionaries.items", const_cast(serialized.data()), serialized.size()); for (auto i: serialized){ dynv_system_release(i); } }else{ dynv_set_dynv_array(args->params, "color_dictionaries.items", nullptr, 0); } color_names_clear(args->gs->getColorNames()); color_names_load(args->gs->getColorNames(), args->params); } gint width, height; gtk_window_get_size(GTK_WINDOW(dialog), &width, &height); dynv_set_int32(args->params, "color_dictionaries.window.width", width); dynv_set_int32(args->params, "color_dictionaries.window.height", height); gtk_widget_destroy(dialog); dynv_system_release(args->params); delete args; } gpick-gpick-0.2.6rc1/source/uiColorDictionaries.h000066400000000000000000000033751315430016700217500ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_UI_COLOR_DICTIONARIES_H_ #define GPICK_UI_COLOR_DICTIONARIES_H_ class GlobalState; #include void dialog_color_dictionaries_show(GtkWindow* parent, GlobalState* gs); #endif /* GPICK_UI_COLOR_DICTIONARIES_H_ */ gpick-gpick-0.2.6rc1/source/uiColorInput.cpp000066400000000000000000000153021315430016700207560ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "uiColorInput.h" #include "Converter.h" #include "DynvHelpers.h" #include "uiUtilities.h" #include "GlobalState.h" #include "gtk/ColorWheel.h" #include "Internationalisation.h" #include "gtk/ColorComponent.h" #include "gtk/ColorWidget.h" #include "ColorObject.h" #include "ColorSpaceType.h" #include #include using namespace std; int dialog_color_input_show(GtkWindow* parent, GlobalState* gs, ColorObject* color_object, ColorObject** new_color_object) { string text; converter_get_text(color_object, ConverterArrayType::display, gs, text); GtkWidget *dialog = gtk_dialog_new_with_buttons(_("Edit color"), parent, GtkDialogFlags(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OK, GTK_RESPONSE_OK, nullptr); gtk_dialog_set_alternative_button_order(GTK_DIALOG(dialog), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1); GtkWidget* vbox = gtk_vbox_new(false, 5); GtkWidget* hbox = gtk_hbox_new(false, 5); gtk_box_pack_start(GTK_BOX(vbox), hbox, true, true, 0); GtkWidget *widget; widget = gtk_color_new(); gtk_color_set_rounded(GTK_COLOR(widget), true); gtk_color_set_hcenter(GTK_COLOR(widget), true); gtk_color_set_roundness(GTK_COLOR(widget), 5); Color color = color_object->getColor(); gtk_color_set_color(GTK_COLOR(widget), &color, ""); gtk_box_pack_start(GTK_BOX(hbox), widget, false, true, 0); gtk_box_pack_start(GTK_BOX(hbox), gtk_label_aligned_new(_("Color:"),0,0.5,0,0), false, false, 0); GtkWidget* entry = gtk_entry_new(); gtk_entry_set_activates_default(GTK_ENTRY(entry), true); gtk_box_pack_start(GTK_BOX(hbox), entry, true, true, 0); gtk_entry_set_text(GTK_ENTRY(entry), text.c_str()); gtk_widget_show_all(vbox); gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), vbox); gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_OK); if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK) { ColorObject* color_object; if (converter_get_color_object((char*)gtk_entry_get_text(GTK_ENTRY(entry)), gs, &color_object)){ *new_color_object = color_object; gtk_widget_destroy(dialog); return 0; } } gtk_widget_destroy(dialog); return -1; } typedef struct ColorPickerComponentEditArgs{ GtkWidget* value[4]; GtkColorComponentComp component; int component_id; struct dynvSystem *params; }ColorPickerComponentEditArgs; void dialog_color_component_input_show(GtkWindow* parent, GtkColorComponent *color_component, int component_id, struct dynvSystem *params) { GtkColorComponentComp component = gtk_color_component_get_component(GTK_COLOR_COMPONENT(color_component)); ColorPickerComponentEditArgs *args = new ColorPickerComponentEditArgs; args->params = params; args->component = component; args->component_id = component_id; memset(args->value, 0, sizeof(args->value)); GtkWidget *table; GtkWidget *dialog = gtk_dialog_new_with_buttons(_("Edit"), parent, GtkDialogFlags(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OK, GTK_RESPONSE_OK, nullptr); gtk_window_set_default_size(GTK_WINDOW(dialog), dynv_get_int32_wd(args->params, "window.width", -1), dynv_get_int32_wd(args->params, "window.height", -1)); gtk_dialog_set_alternative_button_order(GTK_DIALOG(dialog), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1); table = gtk_table_new(2, 2, FALSE); Color raw_color; gtk_color_component_get_raw_color(color_component, &raw_color); const ColorSpaceType *color_space_type = 0; for (uint32_t i = 0; i < color_space_count_types(); i++){ if (color_space_get_types()[i].comp_type == component){ color_space_type = &color_space_get_types()[i]; break; } } if (color_space_type){ for (int i = 0; i < color_space_type->n_items; i++){ gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(color_space_type->items[i].name,0,0,0,0),0,1,i,i+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); args->value[i] = gtk_spin_button_new_with_range(color_space_type->items[i].min_value, color_space_type->items[i].max_value, color_space_type->items[i].step); gtk_entry_set_activates_default(GTK_ENTRY(args->value[i]), true); gtk_spin_button_set_value(GTK_SPIN_BUTTON(args->value[i]), raw_color.ma[i] * color_space_type->items[i].raw_scale); gtk_table_attach(GTK_TABLE(table), args->value[i],1,2,i,i+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); if (i == component_id) gtk_widget_grab_focus(args->value[i]); } } gtk_widget_show_all(table); gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), table); gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_OK); if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK){ if (color_space_type){ for (int i = 0; i < color_space_type->n_items; i++){ raw_color.ma[i] = gtk_spin_button_get_value(GTK_SPIN_BUTTON(args->value[i])) / color_space_type->items[i].raw_scale; } gtk_color_component_set_raw_color(color_component, &raw_color); } } gint width, height; gtk_window_get_size(GTK_WINDOW(dialog), &width, &height); dynv_set_int32(args->params, "window.width", width); dynv_set_int32(args->params, "window.height", height); gtk_widget_destroy(dialog); dynv_system_release(args->params); delete args; } gpick-gpick-0.2.6rc1/source/uiColorInput.h000066400000000000000000000037241315430016700204300ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_UI_COLOR_INPUT_H_ #define GPICK_UI_COLOR_INPUT_H_ class GlobalState; class ColorObject; struct GtkColorComponent; #include int dialog_color_input_show(GtkWindow* parent, GlobalState* gs, ColorObject* color_object, ColorObject** new_color_object); void dialog_color_component_input_show(GtkWindow* parent, GtkColorComponent *color_component, int component_id, struct dynvSystem *params); #endif /* GPICK_UI_COLOR_INPUT_H_ */ gpick-gpick-0.2.6rc1/source/uiConverter.cpp000066400000000000000000000340161315430016700206320ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "uiConverter.h" #include "Converter.h" #include "uiUtilities.h" #include "DynvHelpers.h" #include "GlobalState.h" #include "Internationalisation.h" #include "ColorObject.h" #include "ColorList.h" #include using namespace std; typedef enum{ CONVERTERLIST_HUMAN_NAME = 0, CONVERTERLIST_EXAMPLE, CONVERTERLIST_CONVERTER_PTR, CONVERTERLIST_COPY, CONVERTERLIST_COPY_ENABLED, CONVERTERLIST_PASTE, CONVERTERLIST_PASTE_ENABLED, CONVERTERLIST_N_COLUMNS }ConverterListColumns; typedef struct ConverterArgs{ GtkWidget* list; struct dynvSystem *params; GlobalState *gs; }ConverterArgs; static void converter_update_row(GtkTreeModel *model, GtkTreeIter *iter1, Converter *converter, ConverterArgs *args) { string text_line; ConverterSerializePosition position; position.first = true; position.last = true; position.index = 0; position.count = 1; Color c; c.rgb.red=0.75; c.rgb.green=0.50; c.rgb.blue=0.25; ColorObject *color_object = color_list_new_color_object(args->gs->getColorList(), &c); color_object->setName(_("Test color")); auto converters = args->gs->getConverters(); if (converters_color_serialize(converters, converter->function_name, color_object, position, text_line) == 0) { gtk_list_store_set(GTK_LIST_STORE(model), iter1, CONVERTERLIST_HUMAN_NAME, converter->human_readable, CONVERTERLIST_EXAMPLE, text_line.c_str(), CONVERTERLIST_CONVERTER_PTR, converter, CONVERTERLIST_COPY, converter->copy, CONVERTERLIST_COPY_ENABLED, converter->serialize_available, CONVERTERLIST_PASTE, converter->paste, CONVERTERLIST_PASTE_ENABLED, converter->deserialize_available, -1); }else{ gtk_list_store_set(GTK_LIST_STORE(model), iter1, CONVERTERLIST_HUMAN_NAME, converter->human_readable, CONVERTERLIST_EXAMPLE, _("error"), CONVERTERLIST_CONVERTER_PTR, converter, CONVERTERLIST_COPY, converter->copy, CONVERTERLIST_COPY_ENABLED, converter->serialize_available, CONVERTERLIST_PASTE, converter->paste, CONVERTERLIST_PASTE_ENABLED, converter->deserialize_available, -1); } color_object->release(); } static void copy_toggled_cb(GtkCellRendererText *cell, gchar *path, ConverterArgs *args) { GtkTreeIter iter1; GtkListStore *store=GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(args->list))); gtk_tree_model_get_iter_from_string(GTK_TREE_MODEL(store), &iter1, path ); gboolean value; gtk_tree_model_get(GTK_TREE_MODEL(store), &iter1, CONVERTERLIST_COPY, &value, -1); gtk_list_store_set(store, &iter1, CONVERTERLIST_COPY, !value, -1); } static void paste_toggled_cb(GtkCellRendererText *cell, gchar *path, ConverterArgs *args) { GtkTreeIter iter1; GtkListStore *store=GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(args->list))); gtk_tree_model_get_iter_from_string(GTK_TREE_MODEL(store), &iter1, path ); gboolean value; gtk_tree_model_get(GTK_TREE_MODEL(store), &iter1, CONVERTERLIST_PASTE, &value, -1); gtk_list_store_set(store, &iter1, CONVERTERLIST_PASTE, !value, -1); } static GtkWidget* converter_dropdown_new(ConverterArgs *args, GtkTreeModel *model){ GtkListStore *store = 0; GtkCellRenderer *renderer; GtkWidget *combo; if (model){ combo = gtk_combo_box_new_with_model(model); }else{ store = gtk_list_store_new (CONVERTERLIST_N_COLUMNS, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_POINTER, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN); combo = gtk_combo_box_new_with_model(GTK_TREE_MODEL(store)); } renderer = gtk_cell_renderer_text_new(); gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combo), renderer, true); gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (combo), renderer, "text", CONVERTERLIST_HUMAN_NAME, nullptr); if (store) g_object_unref (store); return combo; } static GtkWidget* converter_list_new(ConverterArgs *args){ GtkListStore *store; GtkCellRenderer *renderer; GtkTreeViewColumn *col; GtkWidget *view; view = gtk_tree_view_new (); args->list=view; gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view),1); store = gtk_list_store_new (CONVERTERLIST_N_COLUMNS, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_POINTER, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN); col = gtk_tree_view_column_new(); gtk_tree_view_column_set_sizing(col,GTK_TREE_VIEW_COLUMN_AUTOSIZE); gtk_tree_view_column_set_resizable(col,1); gtk_tree_view_column_set_title(col, _("Function name")); renderer = gtk_cell_renderer_text_new(); gtk_tree_view_column_pack_start(col, renderer, TRUE); gtk_tree_view_column_add_attribute(col, renderer, "text", CONVERTERLIST_HUMAN_NAME); gtk_tree_view_append_column(GTK_TREE_VIEW(view), col); col = gtk_tree_view_column_new(); gtk_tree_view_column_set_sizing(col,GTK_TREE_VIEW_COLUMN_AUTOSIZE); gtk_tree_view_column_set_resizable(col,1); gtk_tree_view_column_set_title(col, _("Example")); renderer = gtk_cell_renderer_text_new(); gtk_tree_view_column_pack_start(col, renderer, TRUE); gtk_tree_view_column_add_attribute(col, renderer, "text", CONVERTERLIST_EXAMPLE); gtk_tree_view_append_column(GTK_TREE_VIEW(view), col); col = gtk_tree_view_column_new(); gtk_tree_view_column_set_sizing(col,GTK_TREE_VIEW_COLUMN_GROW_ONLY); gtk_tree_view_column_set_title(col, _("Copy")); renderer = gtk_cell_renderer_toggle_new(); gtk_tree_view_column_pack_start(col, renderer, false); gtk_tree_view_append_column(GTK_TREE_VIEW(view), col); g_signal_connect(renderer, "toggled", (GCallback) copy_toggled_cb, args); gtk_tree_view_column_set_attributes(col, renderer, "active", CONVERTERLIST_COPY, "activatable", CONVERTERLIST_COPY_ENABLED, (void*)0); col = gtk_tree_view_column_new(); gtk_tree_view_column_set_sizing(col,GTK_TREE_VIEW_COLUMN_GROW_ONLY); gtk_tree_view_column_set_title(col, _("Paste")); renderer = gtk_cell_renderer_toggle_new(); gtk_tree_view_column_pack_start(col, renderer, false); gtk_tree_view_append_column(GTK_TREE_VIEW(view), col); g_signal_connect(renderer, "toggled", (GCallback) paste_toggled_cb, args); gtk_tree_view_column_set_attributes(col, renderer, "active", CONVERTERLIST_PASTE, "activatable", CONVERTERLIST_PASTE_ENABLED, (void*)0); gtk_tree_view_set_model (GTK_TREE_VIEW (view), GTK_TREE_MODEL(store)); g_object_unref (GTK_TREE_MODEL(store)); GtkTreeSelection *selection = gtk_tree_view_get_selection ( GTK_TREE_VIEW(view) ); gtk_tree_selection_set_mode(selection, GTK_SELECTION_MULTIPLE); gtk_tree_view_set_reorderable(GTK_TREE_VIEW (view), TRUE); return view; } void dialog_converter_show(GtkWindow* parent, GlobalState* gs) { ConverterArgs *args = new ConverterArgs; args->gs = gs; args->params = dynv_get_dynv(args->gs->getSettings(), "gpick"); GtkWidget *dialog = gtk_dialog_new_with_buttons(_("Converters"), parent, GtkDialogFlags(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OK, GTK_RESPONSE_OK, nullptr); gtk_window_set_default_size(GTK_WINDOW(dialog), dynv_get_int32_wd(args->params, "converters.window.width", -1), dynv_get_int32_wd(args->params, "converters.window.height", -1)); gtk_dialog_set_alternative_button_order(GTK_DIALOG(dialog), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1); GtkWidget* vbox = gtk_vbox_new(false, 5); GtkWidget *list; list = converter_list_new(args); GtkWidget *scrolled = gtk_scrolled_window_new(0, 0); gtk_container_add(GTK_CONTAINER(scrolled), list); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_box_pack_start (GTK_BOX(vbox), scrolled, true, true, 0); gint table_y; GtkWidget* table = gtk_table_new(5, 2, false); gtk_box_pack_start(GTK_BOX(vbox), table, false, false, 0); table_y=0; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Displays:"),0,0.5,0,0), 0, 1, table_y, table_y+1, GtkAttachOptions(GTK_FILL), GTK_FILL, 0, 0); GtkWidget *display = converter_dropdown_new(args, 0); GtkTreeModel *model2=gtk_combo_box_get_model(GTK_COMBO_BOX(display)); gtk_table_attach(GTK_TABLE(table), display, 1, 2, table_y, table_y+1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GTK_FILL, 0, 0); table_y++; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Color list:"),0,0.5,0,0), 0, 1, table_y, table_y+1, GtkAttachOptions(GTK_FILL), GTK_FILL, 0, 0); GtkWidget *color_list = converter_dropdown_new(args, model2); gtk_table_attach(GTK_TABLE(table), color_list, 1, 2, table_y, table_y+1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GTK_FILL, 0, 0); table_y++; auto converters = args->gs->getConverters(); Converter **converter_table; size_t total_converters, converter_i; converter_table = converters_get_all(converters, &total_converters); GtkTreeIter iter1; GtkTreeModel *model=gtk_tree_view_get_model(GTK_TREE_VIEW(list)); GtkTreeIter iter2; Converter *converter = converters_get_first(converters, ConverterArrayType::display); bool display_converter_found = false; Converter *list_converter = converters_get_first(converters, ConverterArrayType::color_list); bool color_list_converter_found = false; converter_i = 0; while (converter_iparams, "converters.display", converter->function_name); } if (gtk_combo_box_get_active_iter(GTK_COMBO_BOX(color_list), &iter2)){ gtk_tree_model_get(GTK_TREE_MODEL(model2), &iter2, CONVERTERLIST_CONVERTER_PTR, &converter, -1); converters_set(converters, converter, ConverterArrayType::color_list); dynv_set_string(args->params, "converters.color_list", converter->function_name); } store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(list))); valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter); unsigned int count = gtk_tree_model_iter_n_children(GTK_TREE_MODEL(store), nullptr); if (count > 0){ char** name_array = new char*[count]; bool* copy_array = new bool[count]; bool* paste_array = new bool[count]; unsigned int i = 0; while (valid){ Converter* converter; gboolean copy, paste; gtk_tree_model_get(GTK_TREE_MODEL(store), &iter, CONVERTERLIST_CONVERTER_PTR, &converter, CONVERTERLIST_COPY, ©, CONVERTERLIST_PASTE, &paste, -1); name_array[i] = converter->function_name; copy_array[i] = copy; paste_array[i] = paste; converter->copy = copy; converter->paste = paste; valid = gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter); ++i; } converters_reorder(converters, (const char**)name_array, count); dynv_set_string_array(args->params, "converters.names", (const char**)name_array, count); dynv_set_bool_array(args->params, "converters.copy", copy_array, count); dynv_set_bool_array(args->params, "converters.paste", paste_array, count); delete [] name_array; delete [] copy_array; delete [] paste_array; }else{ converters_reorder(converters, 0, 0); dynv_set_string_array(args->params, "converters.names", 0, 0); dynv_set_bool_array(args->params, "converters.copy", 0, 0); dynv_set_bool_array(args->params, "converters.paste", 0, 0); } converters_rebuild_arrays(converters, ConverterArrayType::copy); converters_rebuild_arrays(converters, ConverterArrayType::paste); } gint width, height; gtk_window_get_size(GTK_WINDOW(dialog), &width, &height); dynv_set_int32(args->params, "converters.window.width", width); dynv_set_int32(args->params, "converters.window.height", height); gtk_widget_destroy(dialog); dynv_system_release(args->params); delete args; } gpick-gpick-0.2.6rc1/source/uiConverter.h000066400000000000000000000033311315430016700202730ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_UI_CONVERTER_H_ #define GPICK_UI_CONVERTER_H_ class GlobalState; #include void dialog_converter_show(GtkWindow* parent, GlobalState* gs); #endif /* GPICK_UI_CONVERTER_H_ */ gpick-gpick-0.2.6rc1/source/uiDialogAutonumber.cpp000066400000000000000000000204711315430016700221240ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "uiDialogAutonumber.h" #include "uiListPalette.h" #include "uiUtilities.h" #include "MathUtil.h" #include "DynvHelpers.h" #include "GlobalState.h" #include "ColorRYB.h" #include "Noise.h" #include "GenerateScheme.h" #include "Internationalisation.h" #include #include #include using namespace std; typedef struct DialogAutonumberArgs{ GtkWidget *name; GtkWidget *nplaces; GtkWidget *startindex; GtkWidget *toggle_decreasing; GtkWidget *toggle_append; uint32_t selected_count; GtkWidget *sample; dynvSystem *params; GlobalState* gs; }DialogAutonumberArgs; static int default_nplaces(uint32_t selected_count) { uint32_t places = 1; uint32_t ncolors = selected_count; // technically this can be implemented as `places = 1 + (int) (trunc(log (ncolors,10)));` // however I don't know the exact function names, and this has minimal dependencies and acceptable speed. while (ncolors > 10) { ncolors = ncolors / 10; places += 1; } return places; } static void update(GtkWidget *widget, DialogAutonumberArgs *args) { uint32_t nplaces = gtk_spin_button_get_value (GTK_SPIN_BUTTON(args->nplaces)); int startindex = gtk_spin_button_get_value (GTK_SPIN_BUTTON(args->startindex)); const char *name = gtk_entry_get_text(GTK_ENTRY(args->name)); stringstream ss; ss << name << "-"; ss.fill('0'); ss.width(nplaces); ss << right << startindex; gtk_entry_set_text(GTK_ENTRY(args->sample), ss.str().c_str()); dynv_set_string (args->params, "name", name); dynv_set_bool (args->params, "append", gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->toggle_append))); dynv_set_bool (args->params, "decreasing", gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->toggle_decreasing))); dynv_set_int32 (args->params, "nplaces", nplaces); dynv_set_int32 (args->params, "startindex", startindex); } static void update_startindex(GtkWidget *widget, DialogAutonumberArgs *args) { int startindex = gtk_spin_button_get_value (GTK_SPIN_BUTTON(args->startindex)); int newindex; gdouble min, max; gtk_spin_button_get_range(GTK_SPIN_BUTTON(args->startindex), &min, &max); if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget))){ if (startindex == 0){ newindex = args->selected_count; }else{ newindex = args->selected_count + (startindex - 1); } min = args->selected_count; }else{ newindex = (startindex + 1) - args->selected_count; min = 1; } gtk_spin_button_set_range(GTK_SPIN_BUTTON(args->startindex), min, max); gtk_spin_button_set_value(GTK_SPIN_BUTTON(args->startindex), newindex); update(widget, args); } int dialog_autonumber_show(GtkWindow* parent, size_t selected_count, GlobalState* gs) { DialogAutonumberArgs *args = new DialogAutonumberArgs; int return_val; args->gs = gs; args->params = dynv_get_dynv(args->gs->getSettings(), "gpick.autonumber"); args->selected_count = selected_count; GtkWidget *dialog = gtk_dialog_new_with_buttons(_("Autonumber colors"), parent, GtkDialogFlags(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OK, GTK_RESPONSE_OK, nullptr); gtk_window_set_default_size(GTK_WINDOW(dialog), dynv_get_int32_wd(args->params, "window.width", -1), dynv_get_int32_wd(args->params, "window.height", -1)); gtk_dialog_set_alternative_button_order(GTK_DIALOG(dialog), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1); gint table_y; GtkWidget *table; table = gtk_table_new(4, 4, FALSE); table_y=0; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Name:"),0,0.5,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); args->name = gtk_entry_new(); // dynv_get_str_wd? gtk_entry_set_text (GTK_ENTRY(args->name), dynv_get_string_wd (args->params, "name", "autonum")); g_signal_connect (G_OBJECT (args->name), "changed", G_CALLBACK(update), args); gtk_table_attach(GTK_TABLE(table), args->name,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); table_y++; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Decimal places:"),0,0,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); args->nplaces = gtk_spin_button_new_with_range (1, 6, 1); gtk_spin_button_set_value(GTK_SPIN_BUTTON(args->nplaces), dynv_get_int32_wd(args->params, "nplaces", default_nplaces (selected_count))); gtk_table_attach(GTK_TABLE(table), args->nplaces,1,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); g_signal_connect(G_OBJECT (args->nplaces), "value-changed", G_CALLBACK (update), args); table_y++; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Starting number:"),0,0,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); args->startindex = gtk_spin_button_new_with_range (1, 0x7fffffff, 1); gtk_spin_button_set_value(GTK_SPIN_BUTTON(args->startindex), dynv_get_int32_wd(args->params, "startindex", 1)); gtk_table_attach(GTK_TABLE(table), args->startindex,1,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); g_signal_connect(G_OBJECT (args->startindex), "value-changed", G_CALLBACK (update), args); table_y++; args->toggle_decreasing = gtk_check_button_new_with_mnemonic (_("_Decreasing")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(args->toggle_decreasing), dynv_get_bool_wd(args->params, "decreasing", false)); gtk_table_attach(GTK_TABLE(table), args->toggle_decreasing,1,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); g_signal_connect (G_OBJECT(args->toggle_decreasing), "toggled", G_CALLBACK (update_startindex), args); table_y++; args->toggle_append = gtk_check_button_new_with_mnemonic (_("_Append")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(args->toggle_append), dynv_get_bool_wd(args->params, "append", false)); gtk_table_attach(GTK_TABLE(table), args->toggle_append,1,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); g_signal_connect (G_OBJECT(args->toggle_append), "toggled", G_CALLBACK (update), args); table_y++; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Sample:"),0,0.5,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GtkAttachOptions(GTK_FILL | GTK_EXPAND),5,5); args->sample = gtk_entry_new(); gtk_editable_set_editable(GTK_EDITABLE(args->sample), false); gtk_widget_set_sensitive(args->sample, false); gtk_table_attach(GTK_TABLE(table), args->sample,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); update(0, args); gtk_widget_show_all(table); gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), table); return_val = gtk_dialog_run(GTK_DIALOG(dialog)); gint width, height; gtk_window_get_size(GTK_WINDOW(dialog), &width, &height); dynv_set_int32(args->params, "window.width", width); dynv_set_int32(args->params, "window.height", height); gtk_widget_destroy(dialog); dynv_system_release(args->params); delete args; return return_val; } gpick-gpick-0.2.6rc1/source/uiDialogAutonumber.h000066400000000000000000000034101315430016700215630ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_UI_DIALOG_AUTONUMBER_H_ #define GPICK_UI_DIALOG_AUTONUMBER_H_ class GlobalState; #include int dialog_autonumber_show(GtkWindow* parent, size_t selected_count, GlobalState* gs); #endif /* GPICK_UI_DIALOG_AUTONUMBER_H_ */ gpick-gpick-0.2.6rc1/source/uiDialogGenerate.cpp000066400000000000000000000322721315430016700215370ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "uiDialogGenerate.h" #include "uiListPalette.h" #include "uiUtilities.h" #include "ColorList.h" #include "ColorObject.h" #include "MathUtil.h" #include "DynvHelpers.h" #include "GlobalState.h" #include "ToolColorNaming.h" #include "color_names/ColorNames.h" #include "ColorRYB.h" #include "Noise.h" #include "GenerateScheme.h" #include "Internationalisation.h" #include "Random.h" #include #include #include using namespace std; typedef struct DialogGenerateArgs { GtkWidget *gen_type; GtkWidget *wheel_type; GtkWidget *range_colors; GtkWidget *range_chaos; GtkWidget *range_additional_rotation; GtkWidget *range_chaos_seed; GtkWidget *toggle_reverse; ColorList *color_list; ColorList *selected_color_list; ColorList *preview_color_list; struct dynvSystem *params; GlobalState* gs; }DialogGenerateArgs; typedef struct ColorWheelType { const char *name; void (*hue_to_hsl)(double hue, Color* hsl); void (*rgbhue_to_hue)(double rgbhue, double *hue); }ColorWheelType; class GenerateColorNameAssigner: public ToolColorNameAssigner { protected: stringstream m_stream; string m_scheme_name; int32_t m_ident; public: GenerateColorNameAssigner(GlobalState *gs): ToolColorNameAssigner(gs) { } void assign(ColorObject *color_object, const Color *color, const int32_t ident, const char *scheme_name) { m_ident = ident; m_scheme_name = scheme_name; ToolColorNameAssigner::assign(color_object, color); } virtual std::string getToolSpecificName(ColorObject *color_object, const Color *color) { m_stream.str(""); m_stream << _("scheme") << " " << m_scheme_name << " #" << m_ident << "[" << color_names_get(m_gs->getColorNames(), color, false) << "]"; return m_stream.str(); } }; static void rgb_hue2hue(double hue, Color* hsl) { hsl->hsl.hue = hue; hsl->hsl.saturation = 1; hsl->hsl.lightness = 0.5; } static void rgb_rgbhue2hue(double rgbhue, double *hue) { *hue = rgbhue; } static void ryb1_hue2hue(double hue, Color* hsl) { Color c; color_rybhue_to_rgb(hue, &c); color_rgb_to_hsl(&c, hsl); } static void ryb1_rgbhue2hue(double rgbhue, double *hue) { color_rgbhue_to_rybhue(rgbhue, hue); } static void ryb2_hue2hue(double hue, Color* hsl) { hsl->hsl.hue = color_rybhue_to_rgbhue_f(hue); hsl->hsl.saturation = 1; hsl->hsl.lightness = 0.5; } static void ryb2_rgbhue2hue(double rgbhue, double *hue) { color_rgbhue_to_rybhue_f(rgbhue, hue); } const ColorWheelType color_wheel_types[] = { {"RGB", rgb_hue2hue, rgb_rgbhue2hue}, {"RYB v1", ryb1_hue2hue, ryb1_rgbhue2hue}, {"RYB v2", ryb2_hue2hue, ryb2_rgbhue2hue}, }; static void calc(DialogGenerateArgs *args, bool preview, int limit) { int32_t type = gtk_combo_box_get_active(GTK_COMBO_BOX(args->gen_type)); int32_t wheel_type = gtk_combo_box_get_active(GTK_COMBO_BOX(args->wheel_type)); int32_t color_count = static_cast(gtk_spin_button_get_value(GTK_SPIN_BUTTON(args->range_colors))); double chaos = gtk_spin_button_get_value(GTK_SPIN_BUTTON(args->range_chaos)); int32_t chaos_seed = static_cast(gtk_spin_button_get_value(GTK_SPIN_BUTTON(args->range_chaos_seed))); bool reverse = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->toggle_reverse)); double additional_rotation = gtk_spin_button_get_value(GTK_SPIN_BUTTON(args->range_additional_rotation)); if (!preview){ dynv_set_int32(args->params, "type", type); dynv_set_int32(args->params, "wheel_type", wheel_type); dynv_set_int32(args->params, "colors", color_count); dynv_set_float(args->params, "chaos", chaos); dynv_set_int32(args->params, "chaos_seed", chaos_seed); dynv_set_bool(args->params, "reverse", reverse); dynv_set_float(args->params, "additional_rotation", additional_rotation); } GenerateColorNameAssigner name_assigner(args->gs); Color r, hsl, hsl_results; double hue; double hue_step; ColorList *color_list; if (preview) color_list = args->preview_color_list; else color_list = args->gs->getColorList(); const ColorWheelType *wheel = &color_wheel_types[wheel_type]; struct Random* random = random_new("SHR3", chaos_seed); const SchemeType *scheme_type; SchemeType static_scheme_type = {_("Static"), 1, 1, {0}}; if (type >= generate_scheme_get_n_scheme_types()){ scheme_type = &static_scheme_type; }else{ scheme_type = generate_scheme_get_scheme_type(type); } for (ColorList::iter i = args->selected_color_list->colors.begin(); i != args->selected_color_list->colors.end(); ++i){ Color in = (*i)->getColor(); color_rgb_to_hsl(&in, &hsl); wheel->rgbhue_to_hue(hsl.hsl.hue, &hue); wheel->hue_to_hsl(hue, &hsl_results); double saturation = hsl.hsl.saturation * 1 / hsl_results.hsl.saturation; double lightness = hsl.hsl.lightness - hsl_results.hsl.lightness; for (int32_t i = 0; i < color_count; i++){ if (preview){ if (limit <= 0){ random_destroy(random); return; } limit--; } wheel->hue_to_hsl(hue, &hsl); hsl.hsl.lightness = clamp_float(hsl.hsl.lightness + lightness, 0, 1); hsl.hsl.saturation = clamp_float(hsl.hsl.saturation * saturation, 0, 1); color_hsl_to_rgb(&hsl, &r); ColorObject *color_object = color_list_new_color_object(color_list, &r); name_assigner.assign(color_object, &r, i, scheme_type->name); color_list_add_color_object(color_list, color_object, 1); color_object->release(); hue_step = (scheme_type->turn[i % scheme_type->turn_types]) / (360.0) + chaos * (random_get_double(random) - 0.5) + additional_rotation / 360.0; if (reverse){ hue = wrap_float(hue - hue_step); }else{ hue = wrap_float(hue + hue_step); } } } random_destroy(random); } static void update(GtkWidget *widget, DialogGenerateArgs *args ){ color_list_remove_all(args->preview_color_list); calc(args, true, 100); } void dialog_generate_show(GtkWindow* parent, ColorList *selected_color_list, GlobalState* gs) { DialogGenerateArgs *args = new DialogGenerateArgs; args->gs = gs; args->params = dynv_get_dynv(args->gs->getSettings(), "gpick.generate"); GtkWidget *table; GtkWidget *dialog = gtk_dialog_new_with_buttons(_("Generate colors"), parent, GtkDialogFlags(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OK, GTK_RESPONSE_OK, nullptr); gtk_window_set_default_size(GTK_WINDOW(dialog), dynv_get_int32_wd(args->params, "window.width", -1), dynv_get_int32_wd(args->params, "window.height", -1)); gtk_dialog_set_alternative_button_order(GTK_DIALOG(dialog), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1); gint table_y; table = gtk_table_new(4, 4, FALSE); table_y = 0; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Colors:"),0,0,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); args->range_colors = gtk_spin_button_new_with_range(1, 72, 1); gtk_spin_button_set_value(GTK_SPIN_BUTTON(args->range_colors), dynv_get_int32_wd(args->params, "colors", 1)); gtk_table_attach(GTK_TABLE(table), args->range_colors,1,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); g_signal_connect(G_OBJECT(args->range_colors), "value-changed", G_CALLBACK(update), args); table_y++; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Type:"),0,0.5,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); args->gen_type = gtk_combo_box_text_new(); for (uint32_t i = 0; i < generate_scheme_get_n_scheme_types(); i++){ gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(args->gen_type), _(generate_scheme_get_scheme_type(i)->name)); } gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(args->gen_type), _("Static")); gtk_combo_box_set_active(GTK_COMBO_BOX(args->gen_type), dynv_get_int32_wd(args->params, "type", 0)); g_signal_connect(G_OBJECT(args->gen_type), "changed", G_CALLBACK(update), args); gtk_table_attach(GTK_TABLE(table), args->gen_type,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Color wheel:"),0,0.5,0,0),2,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); args->wheel_type = gtk_combo_box_text_new(); for (uint32_t i = 0; i < sizeof(color_wheel_types) / sizeof(ColorWheelType); i++){ gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(args->wheel_type), color_wheel_types[i].name); } gtk_combo_box_set_active(GTK_COMBO_BOX(args->wheel_type), dynv_get_int32_wd(args->params, "wheel_type", 0)); g_signal_connect(G_OBJECT(args->wheel_type), "changed", G_CALLBACK(update), args); gtk_table_attach(GTK_TABLE(table), args->wheel_type,3,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,0); table_y++; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Chaos:"),0,0,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); args->range_chaos = gtk_spin_button_new_with_range(0,1,0.001); gtk_spin_button_set_value(GTK_SPIN_BUTTON(args->range_chaos), dynv_get_float_wd(args->params, "chaos", 0)); gtk_table_attach(GTK_TABLE(table), args->range_chaos,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); g_signal_connect(G_OBJECT(args->range_chaos), "value-changed", G_CALLBACK(update), args); gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Seed:"),0,0,0,0),2,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); args->range_chaos_seed = gtk_spin_button_new_with_range(0, 0xFFFF, 1); gtk_spin_button_set_value(GTK_SPIN_BUTTON(args->range_chaos_seed), dynv_get_int32_wd(args->params, "chaos_seed", 0)); gtk_table_attach(GTK_TABLE(table), args->range_chaos_seed,3,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); g_signal_connect(G_OBJECT(args->range_chaos_seed), "value-changed", G_CALLBACK(update), args); table_y++; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Rotation:"),0,0,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); args->range_additional_rotation = gtk_spin_button_new_with_range(-360, 360, 0.1); gtk_spin_button_set_value(GTK_SPIN_BUTTON(args->range_additional_rotation), dynv_get_float_wd(args->params, "range_additional_rotation", 0)); gtk_table_attach(GTK_TABLE(table), args->range_additional_rotation,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); g_signal_connect(G_OBJECT(args->range_additional_rotation), "value-changed", G_CALLBACK(update), args); table_y++; args->toggle_reverse = gtk_check_button_new_with_mnemonic(_("_Reverse")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(args->toggle_reverse), dynv_get_bool_wd(args->params, "reverse", false)); gtk_table_attach(GTK_TABLE(table), args->toggle_reverse,1,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); g_signal_connect(G_OBJECT(args->toggle_reverse), "toggled", G_CALLBACK(update), args); table_y++; GtkWidget* preview_expander; ColorList* preview_color_list = nullptr; gtk_table_attach(GTK_TABLE(table), preview_expander = palette_list_preview_new(gs, true, dynv_get_bool_wd(args->params, "show_preview", true), gs->getColorList(), &preview_color_list), 0, 4, table_y, table_y+1 , GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL | GTK_EXPAND), 5, 5); table_y++; args->selected_color_list = selected_color_list; args->preview_color_list = preview_color_list; update(0, args); gtk_widget_show_all(table); gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), table); if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK) calc(args, false, 0); gint width, height; gtk_window_get_size(GTK_WINDOW(dialog), &width, &height); dynv_set_int32(args->params, "window.width", width); dynv_set_int32(args->params, "window.height", height); dynv_set_bool(args->params, "show_preview", gtk_expander_get_expanded(GTK_EXPANDER(preview_expander))); gtk_widget_destroy(dialog); color_list_destroy(args->preview_color_list); dynv_system_release(args->params); delete args; } gpick-gpick-0.2.6rc1/source/uiDialogGenerate.h000066400000000000000000000034331315430016700212010ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_UI_DIALOG_GENERATE_H_ #define GPICK_UI_DIALOG_GENERATE_H_ class GlobalState; class ColorList; #include void dialog_generate_show(GtkWindow* parent, ColorList *selected_color_list, GlobalState* gs); #endif /* GPICK_UI_DIALOG_GENERATE_H_ */ gpick-gpick-0.2.6rc1/source/uiDialogMix.cpp000066400000000000000000000272241315430016700205430ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "uiDialogMix.h" #include "uiListPalette.h" #include "uiUtilities.h" #include "ColorList.h" #include "ColorObject.h" #include "ColorUtils.h" #include "MathUtil.h" #include "DynvHelpers.h" #include "GlobalState.h" #include "ToolColorNaming.h" #include "Internationalisation.h" #ifndef _MSC_VER #include #endif #include using namespace std; typedef struct DialogMixArgs{ GtkWidget *mix_type; GtkWidget *mix_steps; GtkWidget *toggle_endpoints; ColorList *selected_color_list; ColorList *preview_color_list; dynvSystem *params; GlobalState* gs; }DialogMixArgs; class MixColorNameAssigner: public ToolColorNameAssigner { protected: stringstream m_stream; const char *m_color_start; const char *m_color_end; int m_start_percent; int m_end_percent; int m_steps; int m_stage; int m_is_node; public: MixColorNameAssigner(GlobalState *gs): ToolColorNameAssigner(gs) { m_is_node = false; } void setStartName(const char *start_color_name) { m_color_start = start_color_name; } void setEndName(const char *end_color_name) { m_color_end = end_color_name; } void setStepsAndStage(int steps, int stage) { m_steps = steps; m_stage = stage; } void assign(ColorObject *color_object, const Color *color, int step) { m_start_percent = step * 100 / (m_steps - 1); m_end_percent = 100 - (step * 100 / (m_steps - 1)); m_is_node = (((step == 0 || step == m_steps - 1) && m_stage == 0) || (m_stage == 1 && step == m_steps - 1)); ToolColorNameAssigner::assign(color_object, color); } void assign(ColorObject *color_object, const Color *color, const char *item_name) { m_color_start = item_name; m_is_node = false; ToolColorNameAssigner::assign(color_object, color); } virtual std::string getToolSpecificName(ColorObject *color_object, const Color *color) { m_stream.str(""); if (m_is_node){ if (m_end_percent == 100){ m_stream << m_color_end << " " << _("mix node"); }else{ m_stream << m_color_start << " " << _("mix node"); } }else{ m_stream << m_color_start << " " << m_start_percent << " " << _("mix") << " " << m_end_percent << " " << m_color_end; } return m_stream.str(); } }; #define STORE_COLOR() ColorObject *color_object=color_list_new_color_object(color_list, &r); \ float mixfactor = step_i/(float)(steps-1); \ name_assigner.assign(color_object, &r, name_a, name_b, (int)((1.0 - mixfactor)*100), (int)(mixfactor*100), with_endpoints && (step_i == 0 || step_i == (max_step - 1))); \ color_list_add_color_object(color_list, color_object, 1); \ color_object->release() #define STORE_LINEARCOLOR() color_linear_get_rgb(&r, &r); \ STORE_COLOR() static void store(ColorList *color_list, const Color *color, int step, MixColorNameAssigner &name_assigner) { ColorObject *color_object = color_list_new_color_object(color_list, color); name_assigner.assign(color_object, color, step); color_list_add_color_object(color_list, color_object, 1); color_object->release(); } static void calc( DialogMixArgs *args, bool preview, int limit) { gint steps=gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(args->mix_steps)); gint type=gtk_combo_box_get_active(GTK_COMBO_BOX(args->mix_type)); bool with_endpoints=gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->toggle_endpoints)); gint start_step = 0; gint max_step = steps; MixColorNameAssigner name_assigner(args->gs); if (!preview){ dynv_set_int32(args->params, "type", type); dynv_set_int32(args->params, "steps", steps); dynv_set_bool(args->params, "includeendpoints", with_endpoints); } if (with_endpoints == false){ start_step = 1; max_step = steps - 1; } Color r; gint step_i; stringstream s; s.precision(0); s.setf(ios::fixed,ios::floatfield); Color a ,b; ColorList *color_list; if (preview) color_list = args->preview_color_list; else color_list = args->gs->getColorList(); ColorList::iter j; for (ColorList::iter i=args->selected_color_list->colors.begin(); i != args->selected_color_list->colors.end(); ++i){ a = (*i)->getColor(); if (type == 0) color_rgb_get_linear(&a, &a); name_assigner.setStartName((*i)->getName().c_str()); j = i; ++j; for (; j != args->selected_color_list->colors.end(); ++j){ if (preview){ if (limit <= 0) return; limit--; } b = (*j)->getColor(); if (type == 0) color_rgb_get_linear(&b, &b); name_assigner.setEndName((*j)->getName().c_str()); name_assigner.setStepsAndStage(steps, 0); switch (type){ case 0: for (step_i = start_step; step_i < max_step; ++step_i) { color_utils::mix(a, b, step_i / (float)(steps - 1), r); color_linear_get_rgb(&r, &r); store(color_list, &r, step_i, name_assigner); } break; case 1: { Color a_hsv, b_hsv, r_hsv; color_rgb_to_hsv(&a, &a_hsv); color_rgb_to_hsv(&b, &b_hsv); if (a_hsv.hsv.hue>b_hsv.hsv.hue){ if (a_hsv.hsv.hue-b_hsv.hsv.hue>0.5) a_hsv.hsv.hue-=1; }else{ if (b_hsv.hsv.hue-a_hsv.hsv.hue>0.5) b_hsv.hsv.hue-=1; } for (step_i = start_step; step_i < max_step; ++step_i) { color_utils::mix(a_hsv, b_hsv, step_i / (float)(steps - 1), r_hsv); if (r_hsv.hsv.hue < 0) r_hsv.hsv.hue += 1; color_hsv_to_rgb(&r_hsv, &r); store(color_list, &r, step_i, name_assigner); } } break; case 2: { Color a_lab, b_lab, r_lab; color_rgb_to_lab_d50(&a, &a_lab); color_rgb_to_lab_d50(&b, &b_lab); for (step_i = start_step; step_i < max_step; ++step_i) { color_utils::mix(a_lab, b_lab, step_i / (float)(steps - 1), r_lab); color_lab_to_rgb_d50(&r_lab, &r); color_rgb_normalize(&r); store(color_list, &r, step_i, name_assigner); } } break; case 3: { Color a_lch, b_lch, r_lch; color_rgb_to_lch_d50(&a, &a_lch); color_rgb_to_lch_d50(&b, &b_lch); if (a_lch.lch.h>b_lch.lch.h){ if (a_lch.lch.h-b_lch.lch.h>180) a_lch.lch.h-=360; }else{ if (b_lch.lch.h-a_lch.lch.h>180) b_lch.lch.h-=360; } for (step_i = start_step; step_i < max_step; ++step_i) { color_utils::mix(a_lch, b_lch, step_i / (float)(steps - 1), r_lch); if (r_lch.lch.h < 0) r_lch.lch.h += 360; color_lch_to_rgb_d50(&r_lch, &r); color_rgb_normalize(&r); store(color_list, &r, step_i, name_assigner); } } break; } } } } static void update(GtkWidget *widget, DialogMixArgs *args ){ color_list_remove_all(args->preview_color_list); calc(args, true, 100); } void dialog_mix_show(GtkWindow* parent, ColorList *selected_color_list, GlobalState* gs) { DialogMixArgs *args = new DialogMixArgs; args->gs = gs; args->params = dynv_get_dynv(args->gs->getSettings(), "gpick.mix"); GtkWidget *table; GtkWidget *mix_type, *mix_steps; GtkWidget *dialog = gtk_dialog_new_with_buttons(_("Mix colors"), parent, GtkDialogFlags(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OK, GTK_RESPONSE_OK, nullptr); gtk_window_set_default_size(GTK_WINDOW(dialog), dynv_get_int32_wd(args->params, "window.width", -1), dynv_get_int32_wd(args->params, "window.height", -1)); gtk_dialog_set_alternative_button_order(GTK_DIALOG(dialog), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1); gint table_y; table = gtk_table_new(3, 2, FALSE); table_y=0; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Type:"),0,0,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); mix_type = gtk_combo_box_text_new(); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(mix_type), _("RGB")); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(mix_type), _("HSV")); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(mix_type), _("LAB")); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(mix_type), _("LCH")); gtk_combo_box_set_active(GTK_COMBO_BOX(mix_type), dynv_get_int32_wd(args->params, "type", 0)); gtk_table_attach(GTK_TABLE(table), mix_type,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); table_y++; args->mix_type = mix_type; g_signal_connect(G_OBJECT(mix_type), "changed", G_CALLBACK (update), args); gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Steps:"),0,0,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); mix_steps = gtk_spin_button_new_with_range (3,255,1); gtk_spin_button_set_value(GTK_SPIN_BUTTON(mix_steps), dynv_get_int32_wd(args->params, "steps", 3)); gtk_table_attach(GTK_TABLE(table), mix_steps,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); table_y++; args->mix_steps = mix_steps; g_signal_connect (G_OBJECT (mix_steps), "value-changed", G_CALLBACK (update), args); args->toggle_endpoints = gtk_check_button_new_with_mnemonic (_("_Include Endpoints")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(args->toggle_endpoints), dynv_get_bool_wd(args->params, "includeendpoints", true)); gtk_table_attach(GTK_TABLE(table), args->toggle_endpoints,1,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); g_signal_connect (G_OBJECT(args->toggle_endpoints), "toggled", G_CALLBACK (update), args); table_y++; GtkWidget* preview_expander; ColorList* preview_color_list=nullptr; gtk_table_attach(GTK_TABLE(table), preview_expander = palette_list_preview_new(gs, true, dynv_get_bool_wd(args->params, "show_preview", true), gs->getColorList(), &preview_color_list), 0, 2, table_y, table_y+1 , GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL | GTK_EXPAND), 5, 5); table_y++; args->selected_color_list = selected_color_list; args->preview_color_list = preview_color_list; update(0, args); gtk_widget_show_all(table); gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), table); if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK) calc(args, false, 0); gint width, height; gtk_window_get_size(GTK_WINDOW(dialog), &width, &height); dynv_set_int32(args->params, "window.width", width); dynv_set_int32(args->params, "window.height", height); dynv_set_bool(args->params, "show_preview", gtk_expander_get_expanded(GTK_EXPANDER(preview_expander))); gtk_widget_destroy(dialog); color_list_destroy(args->preview_color_list); dynv_system_release(args->params); delete args; } gpick-gpick-0.2.6rc1/source/uiDialogMix.h000066400000000000000000000034071315430016700202050ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_UI_DIALOG_MIX_H_ #define GPICK_UI_DIALOG_MIX_H_ class GlobalState; class ColorList; #include void dialog_mix_show(GtkWindow* parent, ColorList *selected_color_list, GlobalState* gs); #endif /* GPICK_UI_DIALOG_MIX_H_ */ gpick-gpick-0.2.6rc1/source/uiDialogOptions.cpp000066400000000000000000000551461315430016700214450ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "uiDialogOptions.h" #include "uiUtilities.h" #include "ToolColorNaming.h" #include "GlobalState.h" #include "Internationalisation.h" #include "LuaExt.h" #include "DynvHelpers.h" #include #include using namespace std; extern "C"{ #include #include } static const struct{ const char *label; const char *setting; }available_color_spaces[] = { {"CMYK", "picker.color_space.cmyk"}, {"HSL", "picker.color_space.hsl"}, {"HSV", "picker.color_space.hsv"}, {"LAB", "picker.color_space.lab"}, {"LCH", "picker.color_space.lch"}, {"RGB", "picker.color_space.rgb"}, {0, 0}, }; typedef struct DialogOptionsArgs{ GtkWidget *minimize_to_tray; GtkWidget *close_to_tray; GtkWidget *start_in_tray; GtkWidget *refresh_rate; GtkWidget *single_instance; GtkWidget *default_drag_action[2]; GtkWidget *hex_case[2]; GtkWidget *save_restore_palette; GtkWidget *add_on_release; GtkWidget *add_to_palette; GtkWidget *copy_to_clipboard; GtkWidget *rotate_swatch; GtkWidget *copy_on_release; GtkWidget *zoom_size; GtkWidget *imprecision_postfix; GtkWidget *tool_color_naming[3]; GtkWidget *color_spaces[6]; GtkWidget *out_of_gamut_mask; GtkWidget *lab_illuminant; GtkWidget *lab_observer; struct dynvSystem *params; GlobalState* gs; }DialogOptionsArgs; int dialog_options_update(lua_State *lua, dynvSystem *settings) { if (lua == nullptr || settings == nullptr) return -1; lua_State* L = lua; int status; int stack_top = lua_gettop(L); lua_getglobal(L, "gpick"); int gpick_namespace = lua_gettop(L); if (lua_type(L, -1) != LUA_TNIL){ lua_pushstring(L, "options_update"); lua_gettable(L, gpick_namespace); if (lua_type(L, -1) != LUA_TNIL){ lua_pushdynvsystem(L, settings); status = lua_pcall(L, 1, 0, 0); dynv_system_release(settings); if (status == 0){ lua_settop(L, stack_top); return 0; }else{ cerr << "gpick.options_update: " << lua_tostring(L, -1) << endl; } }else{ cerr << "gpick.options_update: no such function \"options_update\"" << endl; } } lua_settop(L, stack_top); return -1; } static void calc( DialogOptionsArgs *args, bool preview, int limit) { if (preview) return; dynv_set_bool(args->params, "main.minimize_to_tray", gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->minimize_to_tray))); dynv_set_bool(args->params, "main.close_to_tray", gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->close_to_tray))); dynv_set_bool(args->params, "main.start_in_tray", gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->start_in_tray))); dynv_set_bool(args->params, "main.single_instance", gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->single_instance))); dynv_set_bool(args->params, "main.save_restore_palette", gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->save_restore_palette))); if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->default_drag_action[0]))) dynv_set_bool(args->params, "main.dragging_moves", true); else dynv_set_bool(args->params, "main.dragging_moves", false); if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->hex_case[0]))) dynv_set_string(args->params, "options.hex_case", "lower"); else dynv_set_string(args->params, "options.hex_case", "upper"); dynv_set_float(args->params, "picker.refresh_rate", gtk_spin_button_get_value(GTK_SPIN_BUTTON(args->refresh_rate))); dynv_set_int32(args->params, "picker.zoom_size", gtk_spin_button_get_value(GTK_SPIN_BUTTON(args->zoom_size))); dynv_set_bool(args->params, "picker.sampler.add_on_release", gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->add_on_release))); dynv_set_bool(args->params, "picker.sampler.copy_on_release", gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->copy_on_release))); dynv_set_bool(args->params, "picker.sampler.add_to_palette", gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->add_to_palette))); dynv_set_bool(args->params, "picker.sampler.copy_to_clipboard", gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->copy_to_clipboard))); dynv_set_bool(args->params, "picker.sampler.rotate_swatch_after_sample", gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->rotate_swatch))); dynv_set_bool(args->params, "picker.out_of_gamut_mask", gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->out_of_gamut_mask))); dynv_set_bool(args->params, "color_names.imprecision_postfix", gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->imprecision_postfix))); const ToolColorNamingOption *color_naming_options = tool_color_naming_get_options(); int i = 0; while (color_naming_options[i].name){ if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->tool_color_naming[i]))){ dynv_set_string(args->params, "color_names.tool_color_naming", color_naming_options[i].name); break; } i++; } for (int i = 0; available_color_spaces[i].label; i++){ dynv_set_bool(args->params, available_color_spaces[i].setting, gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->color_spaces[i]))); } dynv_set_string(args->params, "picker.lab.illuminant", gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(args->lab_illuminant))); dynv_set_string(args->params, "picker.lab.observer", gtk_combo_box_text_get_active_text(GTK_COMBO_BOX_TEXT(args->lab_observer))); } void dialog_options_show(GtkWindow* parent, GlobalState* gs) { DialogOptionsArgs *args = new DialogOptionsArgs; args->gs = gs; args->params = dynv_get_dynv(args->gs->getSettings(), "gpick"); GtkWidget *table, *table_m, *widget; GtkWidget *dialog = gtk_dialog_new_with_buttons(_("Options"), parent, GtkDialogFlags(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OK, GTK_RESPONSE_OK, nullptr); gtk_window_set_default_size(GTK_WINDOW(dialog), dynv_get_int32_wd(args->params, "options.window.width", -1), dynv_get_int32_wd(args->params, "options.window.height", -1)); gtk_dialog_set_alternative_button_order(GTK_DIALOG(dialog), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1); GtkWidget *frame; GtkWidget* notebook = gtk_notebook_new(); gint table_y, table_m_y; table_m = gtk_table_new(3, 1, FALSE); table_m_y = 0; frame = gtk_frame_new(_("System")); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_NONE); gtk_table_attach(GTK_TABLE(table_m), frame, 0, 1, table_m_y, table_m_y+1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL), 5, 5); table_m_y++; table = gtk_table_new(5, 3, FALSE); table_y=0; gtk_container_add(GTK_CONTAINER(frame), table); args->single_instance = widget = gtk_check_button_new_with_mnemonic (_("_Single instance")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), dynv_get_bool_wd(args->params, "main.single_instance", false)); gtk_table_attach(GTK_TABLE(table), widget,0,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,3,3); table_y++; args->save_restore_palette = widget = gtk_check_button_new_with_mnemonic (_("Save/_Restore palette")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), dynv_get_bool_wd(args->params, "main.save_restore_palette", true)); gtk_table_attach(GTK_TABLE(table), widget,0,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,3,3); table_y++; frame = gtk_frame_new(_("System tray")); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_NONE); gtk_table_attach(GTK_TABLE(table_m), frame, 0, 1, table_m_y, table_m_y+1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL), 5, 5); table_m_y++; table = gtk_table_new(5, 3, FALSE); table_y=0; gtk_container_add(GTK_CONTAINER(frame), table); args->minimize_to_tray = widget = gtk_check_button_new_with_mnemonic (_("_Minimize to system tray")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), dynv_get_bool_wd(args->params, "main.minimize_to_tray", false)); gtk_table_attach(GTK_TABLE(table), widget,0,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,3,3); table_y++; args->close_to_tray = widget = gtk_check_button_new_with_mnemonic (_("_Close to system tray")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), dynv_get_bool_wd(args->params, "main.close_to_tray", false)); gtk_table_attach(GTK_TABLE(table), widget,0,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,3,3); table_y++; args->start_in_tray = widget = gtk_check_button_new_with_mnemonic (_("_Start in system tray")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), dynv_get_bool_wd(args->params, "main.start_in_tray", false)); gtk_table_attach(GTK_TABLE(table), widget,0,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,3,3); table_y++; frame = gtk_frame_new(_("Default drag action")); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_NONE); gtk_table_attach(GTK_TABLE(table_m), frame, 0, 1, table_m_y, table_m_y+1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL), 5, 5); table_m_y++; table = gtk_table_new(5, 3, FALSE); table_y=0; gtk_container_add(GTK_CONTAINER(frame), table); GSList *group = nullptr; bool dragging_moves = dynv_get_bool_wd(args->params, "main.dragging_moves", true); args->default_drag_action[0] = widget = gtk_radio_button_new_with_mnemonic(group, _("M_ove")); group = gtk_radio_button_get_group(GTK_RADIO_BUTTON(widget)); if (dragging_moves) gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), true); gtk_table_attach(GTK_TABLE(table), widget,0,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,3,3); table_y++; args->default_drag_action[1] = widget = gtk_radio_button_new_with_mnemonic(group, _("Cop_y")); group = gtk_radio_button_get_group(GTK_RADIO_BUTTON(widget)); if (dragging_moves == false) gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), true); gtk_table_attach(GTK_TABLE(table), widget,0,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,3,3); table_y++; table_m_y = 0; frame = gtk_frame_new(_("Hex format")); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_NONE); gtk_table_attach(GTK_TABLE(table_m), frame, 1, 2, table_m_y, table_m_y+1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL), 5, 5); table_m_y++; table = gtk_table_new(1, 1, FALSE); table_y=0; gtk_container_add(GTK_CONTAINER(frame), table); group = nullptr; string hex_format = dynv_get_string_wd(args->params, "options.hex_case", "upper"); args->hex_case[0] = widget = gtk_radio_button_new_with_mnemonic(group, _("Lower case")); group = gtk_radio_button_get_group(GTK_RADIO_BUTTON(widget)); if (hex_format == "lower") gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), true); gtk_table_attach(GTK_TABLE(table), widget,0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,3,3); table_y++; args->hex_case[1] = widget = gtk_radio_button_new_with_mnemonic(group, _("Upper case")); group = gtk_radio_button_get_group(GTK_RADIO_BUTTON(widget)); if (hex_format == "upper") gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), true); gtk_table_attach(GTK_TABLE(table), widget,0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,3,3); table_y++; gtk_notebook_append_page(GTK_NOTEBOOK(notebook), table_m, gtk_label_new_with_mnemonic(_("_Main"))); table_m = gtk_table_new(3, 2, FALSE); table_m_y = 0; frame = gtk_frame_new(_("Display")); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_NONE); gtk_table_attach(GTK_TABLE(table_m), frame, 0, 1, table_m_y, table_m_y+1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL), 5, 5); table_m_y++; table = gtk_table_new(5, 3, FALSE); table_y=0; gtk_container_add(GTK_CONTAINER(frame), table); gtk_table_attach(GTK_TABLE(table), gtk_label_mnemonic_aligned_new(_("_Refresh rate:"),0,0.5,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,3,3); args->refresh_rate = widget = gtk_spin_button_new_with_range(1, 60, 1); gtk_spin_button_set_value(GTK_SPIN_BUTTON(args->refresh_rate), dynv_get_float_wd(args->params, "picker.refresh_rate", 30)); gtk_table_attach(GTK_TABLE(table), widget,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,5); gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new("Hz",0,0.5,0,0),2,3,table_y,table_y+1,GTK_FILL,GTK_FILL,5,5); table_y++; gtk_table_attach(GTK_TABLE(table), gtk_label_mnemonic_aligned_new(_("_Magnified area size:"),0,0.5,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,3,3); args->zoom_size = widget = gtk_spin_button_new_with_range(75, 300, 15); gtk_spin_button_set_value(GTK_SPIN_BUTTON(args->zoom_size), dynv_get_int32_wd(args->params, "picker.zoom_size", 150)); gtk_table_attach(GTK_TABLE(table), widget,1,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,5); table_y++; frame = gtk_frame_new(_("Floating picker click behaviour")); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_NONE); gtk_table_attach(GTK_TABLE(table_m), frame, 0, 1, table_m_y, table_m_y+1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL), 5, 5); table_m_y++; table = gtk_table_new(5, 3, FALSE); table_y=0; gtk_container_add(GTK_CONTAINER(frame), table); args->add_on_release = widget = gtk_check_button_new_with_mnemonic(_("_Add to palette")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), dynv_get_bool_wd(args->params, "picker.sampler.add_on_release", false)); gtk_table_attach(GTK_TABLE(table), widget,0,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,3,3); table_y++; args->copy_on_release = widget = gtk_check_button_new_with_mnemonic(_("_Copy to clipboard")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), dynv_get_bool_wd(args->params, "picker.sampler.copy_on_release", false)); gtk_table_attach(GTK_TABLE(table), widget,0,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,3,3); table_y++; frame = gtk_frame_new(_("'Spacebar' button behaviour")); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_NONE); gtk_table_attach(GTK_TABLE(table_m), frame, 0, 1, table_m_y, table_m_y+1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL), 5, 5); table_m_y++; table = gtk_table_new(5, 3, FALSE); table_y=0; gtk_container_add(GTK_CONTAINER(frame), table); args->add_to_palette = widget = gtk_check_button_new_with_mnemonic(_("_Add to palette")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), dynv_get_bool_wd(args->params, "picker.sampler.add_to_palette", false)); gtk_table_attach(GTK_TABLE(table), widget,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,3,3); table_y++; args->copy_to_clipboard = widget = gtk_check_button_new_with_mnemonic(_("_Copy to clipboard")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), dynv_get_bool_wd(args->params, "picker.sampler.copy_to_clipboard", false)); gtk_table_attach(GTK_TABLE(table), widget,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,3,3); table_y++; args->rotate_swatch = widget = gtk_check_button_new_with_mnemonic(_("_Rotate swatch")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), dynv_get_bool_wd(args->params, "picker.sampler.rotate_swatch_after_sample", false)); gtk_table_attach(GTK_TABLE(table), widget,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,3,3); table_y++; table_m_y = 0; frame = gtk_frame_new(_("Enabled color spaces")); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_NONE); gtk_table_attach(GTK_TABLE(table_m), frame, 1, 2, table_m_y, table_m_y+1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL), 5, 5); table_m_y++; table = gtk_table_new(5, 3, FALSE); table_y=0; gtk_container_add(GTK_CONTAINER(frame), table); for (int i = 0; available_color_spaces[i].label; i++){ args->color_spaces[i] = widget = gtk_check_button_new_with_label(available_color_spaces[i].label); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), dynv_get_bool_wd(args->params, available_color_spaces[i].setting, true)); gtk_table_attach(GTK_TABLE(table), widget, 1, 2, table_y, table_y+1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GTK_FILL, 3, 3); table_y++; } frame = gtk_frame_new(_("Lab settings")); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_NONE); gtk_table_attach(GTK_TABLE(table_m), frame, 1, 2, table_m_y, table_m_y+1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL), 5, 5); table_m_y++; table = gtk_table_new(5, 3, FALSE); table_y=0; gtk_container_add(GTK_CONTAINER(frame), table); { int selected; const char *option; gtk_table_attach(GTK_TABLE(table), gtk_label_mnemonic_aligned_new(_("_Illuminant:"),0,0.5,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,3,3); args->lab_illuminant = widget = gtk_combo_box_text_new(); const char *illuminants[] = { "A", "C", "D50", "D55", "D65", "D75", "F2", "F7", "F11", 0, }; selected = 0; option = dynv_get_string_wd(args->params, "picker.lab.illuminant", "D50"); for (int i = 0; illuminants[i]; i++){ if (string(illuminants[i]).compare(option) == 0) selected = i; gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(widget), illuminants[i]); } gtk_combo_box_set_active(GTK_COMBO_BOX(widget), selected); gtk_table_attach(GTK_TABLE(table), widget,1,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,5); table_y++; gtk_table_attach(GTK_TABLE(table), gtk_label_mnemonic_aligned_new(_("_Observer:"),0,0.5,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,3,3); args->lab_observer = widget = gtk_combo_box_text_new(); const char *observers[] = { "2", "10", 0, }; selected = 0; option = dynv_get_string_wd(args->params, "picker.lab.observer", "2"); for (int i = 0; observers[i]; i++){ if (string(observers[i]).compare(option) == 0) selected = i; gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(widget), observers[i]); } gtk_combo_box_set_active(GTK_COMBO_BOX(widget), selected); gtk_table_attach(GTK_TABLE(table), widget,1,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,5); table_y++; } frame = gtk_frame_new(_("Other settings")); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_NONE); gtk_table_attach(GTK_TABLE(table_m), frame, 1, 2, table_m_y, table_m_y+1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL), 5, 5); table_m_y++; table = gtk_table_new(5, 3, FALSE); table_y=0; gtk_container_add(GTK_CONTAINER(frame), table); args->out_of_gamut_mask = widget = gtk_check_button_new_with_mnemonic(_("_Mask out of gamut colors")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), dynv_get_bool_wd(args->params, "picker.out_of_gamut_mask", true)); gtk_table_attach(GTK_TABLE(table), widget, 1, 2, table_y, table_y+1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GTK_FILL, 3, 3); table_y++; gtk_notebook_append_page(GTK_NOTEBOOK(notebook), table_m, gtk_label_new_with_mnemonic(_("_Picker"))); table_m = gtk_table_new(3, 1, FALSE); table_m_y = 0; frame = gtk_frame_new(_("Color name generation")); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_NONE); gtk_table_attach(GTK_TABLE(table_m), frame, 0, 1, table_m_y, table_m_y+1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL), 5, 5); table_m_y++; table = gtk_table_new(5, 3, FALSE); table_y=0; gtk_container_add(GTK_CONTAINER(frame), table); args->imprecision_postfix = widget = gtk_check_button_new_with_mnemonic(_("_Imprecision postfix")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), dynv_get_bool_wd(args->params, "color_names.imprecision_postfix", true)); gtk_table_attach(GTK_TABLE(table), widget,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,3,3); table_y++; frame = gtk_frame_new(_("Tool color naming")); gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_NONE); gtk_table_attach(GTK_TABLE(table_m), frame, 0, 1, table_m_y, table_m_y+1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL), 5, 5); table_m_y++; table = gtk_table_new(5, 3, FALSE); table_y=0; gtk_container_add(GTK_CONTAINER(frame), table); group = nullptr; ToolColorNamingType color_naming_type = tool_color_naming_name_to_type(dynv_get_string_wd(args->params, "color_names.tool_color_naming", "tool_specific")); const ToolColorNamingOption *color_naming_options = tool_color_naming_get_options(); int i = 0; while (color_naming_options[i].name){ args->tool_color_naming[i] = widget = gtk_radio_button_new_with_mnemonic(group, _(color_naming_options[i].label)); group = gtk_radio_button_get_group(GTK_RADIO_BUTTON(widget)); if (color_naming_type == color_naming_options[i].type) gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), true); gtk_table_attach(GTK_TABLE(table), widget,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,3,3); table_y++; i++; } gtk_notebook_append_page(GTK_NOTEBOOK(notebook), table_m, gtk_label_new_with_mnemonic(_("_Color names"))); gtk_widget_show_all(notebook); gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), notebook); if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK) { calc(args, false, 0); dialog_options_update(args->gs->getLua(), args->gs->getSettings()); } gint width, height; gtk_window_get_size(GTK_WINDOW(dialog), &width, &height); dynv_set_int32(args->params, "options.window.width", width); dynv_set_int32(args->params, "options.window.height", height); dynv_system_release(args->params); gtk_widget_destroy(dialog); delete args; } gpick-gpick-0.2.6rc1/source/uiDialogOptions.h000066400000000000000000000035141315430016700211020ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_UI_DIALOG_OPTIONS_H_ #define GPICK_UI_DIALOG_OPTIONS_H_ class GlobalState; struct dynvSystem; struct lua_State; #include void dialog_options_show(GtkWindow* parent, GlobalState* gs); int dialog_options_update(lua_State *lua, dynvSystem *settings); #endif /* GPICK_UI_DIALOG_OPTIONS_H_ */ gpick-gpick-0.2.6rc1/source/uiDialogSort.cpp000066400000000000000000000477051315430016700207430ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "uiDialogSort.h" #include "uiListPalette.h" #include "uiUtilities.h" #include "ColorList.h" #include "ColorObject.h" #include "MathUtil.h" #include "DynvHelpers.h" #include "GlobalState.h" #include "ColorRYB.h" #include "Noise.h" #include "GenerateScheme.h" #include "Internationalisation.h" #include #include #include #include #include using namespace std; typedef struct DialogSortArgs{ GtkWidget *group_type; GtkWidget *group_sensitivity; GtkWidget *max_groups; GtkWidget *sort_type; GtkWidget *toggle_reverse; GtkWidget *toggle_reverse_groups; ColorList *sorted_color_list; ColorList *selected_color_list; ColorList *preview_color_list; struct dynvSystem *params; GlobalState* gs; }DialogSortArgs; typedef struct SortType{ const char *name; double (*get_value)(Color *color); }SortType; typedef struct GroupType{ const char *name; double (*get_group)(Color *color); }GroupType; static double sort_rgb_red(Color *color) { return color->rgb.red; } static double sort_rgb_green(Color *color) { return color->rgb.green; } static double sort_rgb_blue(Color *color) { return color->rgb.blue; } static double sort_rgb_grayscale(Color *color) { return (color->rgb.red + color->rgb.green + color->rgb.blue) / 3.0; } static double sort_hsl_hue(Color *color) { Color hsl; color_rgb_to_hsl(color, &hsl); return hsl.hsl.hue; } static double sort_hsl_saturation(Color *color) { Color hsl; color_rgb_to_hsl(color, &hsl); return hsl.hsl.saturation; } static double sort_hsl_lightness(Color *color) { Color hsl; color_rgb_to_hsl(color, &hsl); return hsl.hsl.lightness; } static double sort_lab_lightness(Color *color) { Color lab; color_rgb_to_lab_d50(color, &lab); return lab.lab.L; } static double sort_lab_a(Color *color) { Color lab; color_rgb_to_lab_d50(color, &lab); return lab.lab.a; } static double sort_lab_b(Color *color) { Color lab; color_rgb_to_lab_d50(color, &lab); return lab.lab.b; } static double sort_lch_lightness(Color *color) { Color lch; color_rgb_to_lch_d50(color, &lch); return lch.lch.L; } static double sort_lch_chroma(Color *color) { Color lch; color_rgb_to_lch_d50(color, &lch); return lch.lch.C; } static double sort_lch_hue(Color *color) { Color lch; color_rgb_to_lch_d50(color, &lch); return lch.lch.h; } const SortType sort_types[] = { {N_("RGB Red"), sort_rgb_red}, {N_("RGB Green"), sort_rgb_green}, {N_("RGB Blue"), sort_rgb_blue}, {N_("RGB Grayscale"), sort_rgb_grayscale}, {N_("HSL Hue"), sort_hsl_hue}, {N_("HSL Saturation"), sort_hsl_saturation}, {N_("HSL Lightness"), sort_hsl_lightness}, {N_("Lab Lightness"), sort_lab_lightness}, {N_("Lab A"), sort_lab_a}, {N_("Lab B"), sort_lab_b}, {N_("LCh Lightness"), sort_lch_lightness}, {N_("LCh Chroma"), sort_lch_chroma}, {N_("LCh Hue"), sort_lch_hue}, }; static double group_rgb_red(Color *color) { return color->rgb.red; } static double group_rgb_green(Color *color) { return color->rgb.green; } static double group_rgb_blue(Color *color) { return color->rgb.blue; } static double group_rgb_grayscale(Color *color) { return (color->rgb.red + color->rgb.green + color->rgb.blue) / 3.0; } static double group_hsl_hue(Color *color) { Color hsl; color_rgb_to_hsl(color, &hsl); return hsl.hsl.hue; } static double group_hsl_saturation(Color *color) { Color hsl; color_rgb_to_hsl(color, &hsl); return hsl.hsl.saturation; } static double group_hsl_lightness(Color *color) { Color hsl; color_rgb_to_hsl(color, &hsl); return hsl.hsl.lightness; } static double group_lab_lightness(Color *color) { Color lab; color_rgb_to_lab_d50(color, &lab); return lab.lab.L / 100.0; } static double group_lab_a(Color *color) { Color lab; color_rgb_to_lab_d50(color, &lab); return (lab.lab.a + 145) / 290.0; } static double group_lab_b(Color *color) { Color lab; color_rgb_to_lab_d50(color, &lab); return (lab.lab.b + 145) / 290.0; } static double group_lch_lightness(Color *color) { Color lch; color_rgb_to_lch_d50(color, &lch); return lch.lch.L / 100.0; } static double group_lch_chroma(Color *color) { Color lch; color_rgb_to_lch_d50(color, &lch); return lch.lch.C / 136.0; } static double group_lch_hue(Color *color) { Color lch; color_rgb_to_lch_d50(color, &lch); return lch.lch.h / 360.0; } const GroupType group_types[] = { {N_("None"), nullptr}, {N_("RGB Red"), group_rgb_red}, {N_("RGB Green"), group_rgb_green}, {N_("RGB Blue"), group_rgb_blue}, {N_("RGB Grayscale"), group_rgb_grayscale}, {N_("HSL Hue"), group_hsl_hue}, {N_("HSL Saturation"), group_hsl_saturation}, {N_("HSL Lightness"), group_hsl_lightness}, {N_("Lab Lightness"), group_lab_lightness}, {N_("Lab A"), group_lab_a}, {N_("Lab B"), group_lab_b}, {N_("LCh Lightness"), group_lch_lightness}, {N_("LCh Chroma"), group_lch_chroma}, {N_("LCh Hue"), group_lch_hue}, }; typedef struct Node{ uint32_t n_values; uint32_t n_values_in; double value_sum; double distance; Node *child[2]; Node *parent; }Node; typedef struct Range{ double x; double w; }Range; static Node* node_new(Node *parent){ Node *n = new Node; n->value_sum = 0; n->distance = 0; n->n_values = 0; n->n_values_in = 0; n->parent = parent; for (int i = 0; i < 2; i++){ n->child[i] = 0; } return n; } static void node_delete(Node *node){ for (int i = 0; i < 2; i++){ if (node->child[i]){ node_delete(node->child[i]); } } delete node; } static Node* node_copy(Node *node, Node *parent){ Node *n = node_new(0); memcpy(n, node, sizeof(Node)); n->parent = parent; for (int i = 0; i < 2; i++){ if (node->child[i]){ n->child[i] = node_copy(node->child[i], n); }else{ n->child[i] = 0; } } return n; } static uint32_t node_count_leafs(Node *node){ uint32_t r = 0; if (node->n_values_in) r++; for (int i = 0; i < 2; i++){ if (node->child[i]) r += node_count_leafs(node->child[i]); } return r; } static void node_leaf_callback(Node *node, void (*leaf_cb)(Node* node, void* userdata), void* userdata){ if (node->n_values_in > 0) leaf_cb(node, userdata); for (int i = 0; i < 2; i++){ if (node->child[i]) node_leaf_callback(node->child[i], leaf_cb, userdata); } } static void node_prune(Node *node){ for (int i = 0; i < 2; i++){ if (node->child[i]){ node_prune(node->child[i]); node->child[i] = 0; } } if (node->parent){ node->parent->n_values_in += node->n_values_in; node->parent->value_sum += node->value_sum; } node_delete(node); } typedef struct PruneData{ double threshold; double min_distance; uint32_t n_values; uint32_t n_values_target; Node *prune_node; uint32_t distant_nodes; }PruneData; static bool node_prune_threshold(Node *node, PruneData *prune_data, bool leave_node){ if (node->distance <= prune_data->threshold){ uint32_t values_removed; if (leave_node){ values_removed = 0; for (int i = 0; i < 2; i++){ if (node->child[i]){ values_removed += node_count_leafs(node->child[i]); node_prune(node->child[i]); node->child[i] = 0; } } }else{ values_removed = node_count_leafs(node); node_prune(node); } prune_data->n_values -= values_removed; return true; } if (node->distance < prune_data->min_distance){ prune_data->min_distance = node->distance; } uint32_t n = node->n_values_in; for (int i = 0; i < 2; i++){ if (node->child[i]){ if (node_prune_threshold(node->child[i], prune_data, false)){ node->child[i] = 0; } } } if (node->n_values_in > 0 && n == 0) prune_data->n_values++; return false; } static void node_reduce(Node *node, double threshold, uintptr_t max_values){ PruneData prune_data; prune_data.n_values = node_count_leafs(node); prune_data.n_values_target = max_values; prune_data.threshold = threshold; prune_data.min_distance = node->distance; node_prune_threshold(node, &prune_data, true); prune_data.threshold = prune_data.min_distance; while (prune_data.n_values > max_values){ prune_data.min_distance = node->distance; if (node_prune_threshold(node, &prune_data, true)) break; prune_data.threshold = prune_data.min_distance; } } static Node* node_find(Node *node, Range *range, double value) { Range new_range; new_range.w = range->w / 2; int x; if (value - range->x < new_range.w) x = 0; else x = 1; new_range.x = range->x + new_range.w * x; if (node->child[x]){ return node_find(node->child[x], &new_range, value); }else return node; } static void node_update(Node *node, Range *range, double value, uint32_t max_depth){ Range new_range; new_range.w = range->w / 2; node->n_values++; node->distance += (value - (range->x + new_range.w)) * (value - (range->x + new_range.w)); if (!max_depth){ node->n_values_in++; node->value_sum += value; }else{ int x; if (value - range->x < new_range.w) x = 0; else x = 1; new_range.x = range->x + new_range.w * x; if (!node->child[x]) node->child[x] = node_new(node); node->n_values++; node_update(node->child[x], &new_range, value, max_depth - 1); } } static void calc(DialogSortArgs *args, bool preview, int limit){ int32_t group_type = gtk_combo_box_get_active(GTK_COMBO_BOX(args->group_type)); double group_sensitivity = gtk_spin_button_get_value(GTK_SPIN_BUTTON(args->group_sensitivity)); int max_groups = gtk_spin_button_get_value(GTK_SPIN_BUTTON(args->max_groups)); int32_t sort_type = gtk_combo_box_get_active(GTK_COMBO_BOX(args->sort_type)); bool reverse = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->toggle_reverse)); bool reverse_groups = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->toggle_reverse_groups)); if (!preview){ dynv_set_int32(args->params, "group_type", group_type); dynv_set_float(args->params, "group_sensitivity", group_sensitivity); dynv_set_int32(args->params, "max_groups", max_groups); dynv_set_int32(args->params, "sort_type", sort_type); dynv_set_bool(args->params, "reverse", reverse); dynv_set_bool(args->params, "reverse_groups", reverse_groups); } ColorList *color_list; if (preview) color_list = args->preview_color_list; else color_list = args->sorted_color_list; typedef std::multimap SortedColors; typedef std::map GroupedSortedColors; GroupedSortedColors grouped_sorted_colors; typedef std::multimap SortedGroups; SortedGroups sorted_groups; const GroupType *group = &group_types[group_type]; const SortType *sort = &sort_types[sort_type]; Color in; Node *group_nodes = node_new(0); Range range; range.x = 0; range.w = 1; int tmp_limit = limit; if (group->get_group){ for (ColorList::iter i = args->selected_color_list->colors.begin(); i != args->selected_color_list->colors.end(); ++i){ in = (*i)->getColor(); node_update(group_nodes, &range, group->get_group(&in), 8); if (preview){ if (tmp_limit <= 0) break; tmp_limit--; } } } node_reduce(group_nodes, group_sensitivity / 100.0, max_groups); tmp_limit = limit; for (ColorList::iter i = args->selected_color_list->colors.begin(); i != args->selected_color_list->colors.end(); ++i){ in = (*i)->getColor(); uintptr_t node_ptr = 0; if (group->get_group){ node_ptr = reinterpret_cast(node_find(group_nodes, &range, group->get_group(&in))); } grouped_sorted_colors[node_ptr].insert(std::pair(sort->get_value(&in), *i)); if (preview){ if (tmp_limit <= 0) break; tmp_limit--; } } node_delete(group_nodes); for (GroupedSortedColors::iterator i = grouped_sorted_colors.begin(); i != grouped_sorted_colors.end(); ++i){ in = (*(*i).second.begin()).second->getColor(); sorted_groups.insert(std::pair(sort->get_value(&in), (*i).first)); } if (reverse_groups){ for (SortedGroups::reverse_iterator i = sorted_groups.rbegin(); i != sorted_groups.rend(); ++i){ GroupedSortedColors::iterator a, b; a = grouped_sorted_colors.lower_bound((*i).second); b = grouped_sorted_colors.upper_bound((*i).second); for (GroupedSortedColors::iterator j = a; j != b; ++j){ if (reverse){ for (SortedColors::reverse_iterator k = (*j).second.rbegin(); k != (*j).second.rend(); ++k){ color_list_add_color_object(color_list, (*k).second, true); } }else{ for (SortedColors::iterator k = (*j).second.begin(); k != (*j).second.end(); ++k){ color_list_add_color_object(color_list, (*k).second, true); } } } } }else{ for (SortedGroups::iterator i = sorted_groups.begin(); i != sorted_groups.end(); ++i){ GroupedSortedColors::iterator a, b; a = grouped_sorted_colors.lower_bound((*i).second); b = grouped_sorted_colors.upper_bound((*i).second); for (GroupedSortedColors::iterator j = a; j != b; ++j){ if (reverse){ for (SortedColors::reverse_iterator k = (*j).second.rbegin(); k != (*j).second.rend(); ++k){ color_list_add_color_object(color_list, (*k).second, true); } }else{ for (SortedColors::iterator k = (*j).second.begin(); k != (*j).second.end(); ++k){ color_list_add_color_object(color_list, (*k).second, true); } } } } } } static void update(GtkWidget *widget, DialogSortArgs *args ){ color_list_remove_all(args->preview_color_list); calc(args, true, 100); } bool dialog_sort_show(GtkWindow* parent, ColorList *selected_color_list, ColorList *sorted_color_list, GlobalState* gs) { DialogSortArgs *args = new DialogSortArgs; args->gs = gs; args->params = dynv_get_dynv(args->gs->getSettings(), "gpick.group_and_sort"); args->sorted_color_list = sorted_color_list; GtkWidget *table; GtkWidget *dialog = gtk_dialog_new_with_buttons(_("Group and sort"), parent, GtkDialogFlags(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OK, GTK_RESPONSE_OK, nullptr); gtk_window_set_default_size(GTK_WINDOW(dialog), dynv_get_int32_wd(args->params, "window.width", -1), dynv_get_int32_wd(args->params, "window.height", -1)); gtk_dialog_set_alternative_button_order(GTK_DIALOG(dialog), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1); gint table_y; table = gtk_table_new(4, 4, FALSE); table_y = 0; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Group type:"),0,0.5,0,0),2,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); args->group_type = gtk_combo_box_text_new(); for (uint32_t i = 0; i < sizeof(group_types) / sizeof(GroupType); i++){ gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(args->group_type), _(group_types[i].name)); } gtk_combo_box_set_active(GTK_COMBO_BOX(args->group_type), dynv_get_int32_wd(args->params, "group_type", 0)); g_signal_connect(G_OBJECT(args->group_type), "changed", G_CALLBACK(update), args); gtk_table_attach(GTK_TABLE(table), args->group_type,3,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); table_y++; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Grouping sensitivity:"),0,0,0,0),2,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); args->group_sensitivity = gtk_spin_button_new_with_range(0, 100, 0.01); gtk_spin_button_set_value(GTK_SPIN_BUTTON(args->group_sensitivity), dynv_get_float_wd(args->params, "group_sensitivity", 50)); gtk_table_attach(GTK_TABLE(table), args->group_sensitivity,3,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); g_signal_connect(G_OBJECT(args->group_sensitivity), "value-changed", G_CALLBACK(update), args); table_y++; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Maximum number of groups:"),0,0,0,0),2,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); args->max_groups = gtk_spin_button_new_with_range(1, 255, 1); gtk_spin_button_set_value(GTK_SPIN_BUTTON(args->max_groups), dynv_get_int32_wd(args->params, "max_groups", 10)); gtk_table_attach(GTK_TABLE(table), args->max_groups,3,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); g_signal_connect(G_OBJECT(args->max_groups), "value-changed", G_CALLBACK(update), args); table_y++; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Sort type:"),0,0.5,0,0),2,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); args->sort_type = gtk_combo_box_text_new(); for (uint32_t i = 0; i < sizeof(sort_types) / sizeof(SortType); i++){ gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(args->sort_type), _(sort_types[i].name)); } gtk_combo_box_set_active(GTK_COMBO_BOX(args->sort_type), dynv_get_int32_wd(args->params, "sort_type", 0)); g_signal_connect (G_OBJECT (args->sort_type), "changed", G_CALLBACK(update), args); gtk_table_attach(GTK_TABLE(table), args->sort_type,3,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); table_y++; args->toggle_reverse_groups = gtk_check_button_new_with_mnemonic(_("_Reverse group order")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(args->toggle_reverse_groups), dynv_get_bool_wd(args->params, "reverse_groups", false)); gtk_table_attach(GTK_TABLE(table), args->toggle_reverse_groups,1,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); g_signal_connect (G_OBJECT(args->toggle_reverse_groups), "toggled", G_CALLBACK(update), args); table_y++; args->toggle_reverse = gtk_check_button_new_with_mnemonic(_("_Reverse order inside groups")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(args->toggle_reverse), dynv_get_bool_wd(args->params, "reverse", false)); gtk_table_attach(GTK_TABLE(table), args->toggle_reverse,1,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); g_signal_connect (G_OBJECT(args->toggle_reverse), "toggled", G_CALLBACK(update), args); table_y++; GtkWidget* preview_expander; ColorList* preview_color_list = nullptr; gtk_table_attach(GTK_TABLE(table), preview_expander = palette_list_preview_new(gs, true, dynv_get_bool_wd(args->params, "show_preview", true), gs->getColorList(), &preview_color_list), 0, 4, table_y, table_y + 1 , GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL | GTK_EXPAND), 5, 5); table_y++; args->selected_color_list = selected_color_list; args->preview_color_list = preview_color_list; update(0, args); gtk_widget_show_all(table); gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), table); bool retval = false; if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK){ calc(args, false, 0); retval = true; } gint width, height; gtk_window_get_size(GTK_WINDOW(dialog), &width, &height); dynv_set_int32(args->params, "window.width", width); dynv_set_int32(args->params, "window.height", height); dynv_set_bool(args->params, "show_preview", gtk_expander_get_expanded(GTK_EXPANDER(preview_expander))); gtk_widget_destroy(dialog); color_list_destroy(args->preview_color_list); dynv_system_release(args->params); delete args; return retval; } gpick-gpick-0.2.6rc1/source/uiDialogSort.h000066400000000000000000000034511315430016700203760ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_UI_DIALOG_SORT_H_ #define GPICK_UI_DIALOG_SORT_H_ class GlobalState; class ColorList; #include bool dialog_sort_show(GtkWindow* parent, ColorList *selected_color_list, ColorList *sorted_color_list, GlobalState* gs); #endif /* GPICK_UI_DIALOG_SORT_H_ */ gpick-gpick-0.2.6rc1/source/uiDialogVariations.cpp000066400000000000000000000271651315430016700221310ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "uiDialogVariations.h" #include "uiListPalette.h" #include "uiUtilities.h" #include "ColorList.h" #include "ColorObject.h" #include "MathUtil.h" #include "DynvHelpers.h" #include "GlobalState.h" #include "ToolColorNaming.h" #include "Internationalisation.h" #include using namespace std; typedef struct DialogVariationsArgs { GtkWidget *toggle_multiplication, *toggle_linearization; GtkWidget *range_lightness_from, *range_lightness_to, *range_steps; GtkWidget *range_saturation_from, *range_saturation_to; ColorList *selected_color_list; ColorList *preview_color_list; struct dynvSystem *params; GlobalState* gs; }DialogVariationsArgs; class VariationsColorNameAssigner: public ToolColorNameAssigner { protected: stringstream m_stream; const char *m_name; uint32_t m_step_i; public: VariationsColorNameAssigner(GlobalState *gs): ToolColorNameAssigner(gs) { } void assign(ColorObject *color_object, const Color *color, const char *name, uint32_t step_i) { m_name = name; m_step_i = step_i; ToolColorNameAssigner::assign(color_object, color); } virtual std::string getToolSpecificName(ColorObject *color_object, const Color *color) { m_stream.str(""); m_stream << m_name << " " << _("variation") << " " << m_step_i; return m_stream.str(); } }; static void calc(DialogVariationsArgs *args, bool preview, int limit) { gint steps = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON(args->range_steps)); gfloat lightness_from = gtk_spin_button_get_value(GTK_SPIN_BUTTON(args->range_lightness_from)); gfloat lightness_to = gtk_spin_button_get_value(GTK_SPIN_BUTTON(args->range_lightness_to)); gfloat saturation_from = gtk_spin_button_get_value(GTK_SPIN_BUTTON(args->range_saturation_from)); gfloat saturation_to = gtk_spin_button_get_value(GTK_SPIN_BUTTON(args->range_saturation_to)); bool multiplication = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->toggle_multiplication)); bool linearization = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->toggle_linearization)); if (!preview){ dynv_set_int32(args->params, "steps", steps); dynv_set_float(args->params, "lightness_from", lightness_from); dynv_set_float(args->params, "lightness_to", lightness_to); dynv_set_float(args->params, "saturation_from", saturation_from); dynv_set_float(args->params, "saturation_to", saturation_to); dynv_set_bool(args->params, "multiplication", multiplication); dynv_set_bool(args->params, "linearization", linearization); } Color r, hsl; gint step_i; ColorList *color_list; if (preview) color_list = args->preview_color_list; else color_list = args->gs->getColorList(); VariationsColorNameAssigner name_assigner(args->gs); for (ColorList::iter i = args->selected_color_list->colors.begin(); i != args->selected_color_list->colors.end(); ++i){ Color in = (*i)->getColor(); const char* name = (*i)->getName().c_str(); if (linearization) color_rgb_get_linear(&in, &in); for (step_i = 0; step_i < steps; ++step_i) { if (preview){ if (limit <= 0) return; limit--; } color_rgb_to_hsl(&in, &hsl); if (steps == 1){ if (multiplication){ hsl.hsl.saturation *= mix_float(saturation_from, saturation_to, 0); hsl.hsl.lightness *= mix_float(lightness_from, lightness_to, 0); }else{ hsl.hsl.saturation += mix_float(saturation_from, saturation_to, 0); hsl.hsl.lightness += mix_float(lightness_from, lightness_to, 0); } }else{ if (multiplication){ hsl.hsl.saturation *= mix_float(saturation_from, saturation_to, (step_i / (float) (steps - 1))); hsl.hsl.lightness *= mix_float(lightness_from, lightness_to, (step_i / (float) (steps - 1))); }else{ hsl.hsl.saturation += mix_float(saturation_from, saturation_to, (step_i / (float) (steps - 1))); hsl.hsl.lightness += mix_float(lightness_from, lightness_to, (step_i / (float) (steps - 1))); } } hsl.hsl.saturation = clamp_float(hsl.hsl.saturation, 0, 1); hsl.hsl.lightness = clamp_float(hsl.hsl.lightness, 0, 1); color_hsl_to_rgb(&hsl, &r); if (linearization) color_linear_get_rgb(&r, &r); ColorObject *color_object = color_list_new_color_object(color_list, &r); name_assigner.assign(color_object, &r, name, step_i); color_list_add_color_object(color_list, color_object, 1); color_object->release(); } } } static void update(GtkWidget *widget, DialogVariationsArgs *args) { color_list_remove_all(args->preview_color_list); calc(args, true, 100); } void dialog_variations_show(GtkWindow* parent, ColorList *selected_color_list, GlobalState* gs) { DialogVariationsArgs *args = new DialogVariationsArgs; args->gs = gs; args->params = dynv_get_dynv(args->gs->getSettings(), "gpick.variations"); GtkWidget *table, *toggle_multiplication; GtkWidget *range_lightness_from, *range_lightness_to, *range_steps; GtkWidget *range_saturation_from, *range_saturation_to; GtkWidget *dialog = gtk_dialog_new_with_buttons(_("Variations"), parent, GtkDialogFlags(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OK, GTK_RESPONSE_OK, nullptr); gtk_window_set_default_size(GTK_WINDOW(dialog), dynv_get_int32_wd(args->params, "window.width", -1), dynv_get_int32_wd(args->params, "window.height", -1)); gtk_dialog_set_alternative_button_order(GTK_DIALOG(dialog), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1); gint table_y; table = gtk_table_new(5, 3, FALSE); table_y = 0; gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Lightness:"),0,0,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); range_lightness_from = gtk_spin_button_new_with_range(-100,100,0.001); gtk_spin_button_set_value(GTK_SPIN_BUTTON(range_lightness_from), dynv_get_float_wd(args->params, "lightness_from", 1)); gtk_table_attach(GTK_TABLE(table), range_lightness_from,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); args->range_lightness_from = range_lightness_from; g_signal_connect(G_OBJECT(range_lightness_from), "value-changed", G_CALLBACK(update), args); range_lightness_to = gtk_spin_button_new_with_range(-100,100,0.001); gtk_spin_button_set_value(GTK_SPIN_BUTTON(range_lightness_to), dynv_get_float_wd(args->params, "lightness_to", 1)); gtk_table_attach(GTK_TABLE(table), range_lightness_to,2,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); table_y++; args->range_lightness_to = range_lightness_to; g_signal_connect(G_OBJECT(range_lightness_to), "value-changed", G_CALLBACK(update), args); gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Saturation:"),0,0,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); range_saturation_from = gtk_spin_button_new_with_range(-100,100,0.001); gtk_spin_button_set_value(GTK_SPIN_BUTTON(range_saturation_from), dynv_get_float_wd(args->params, "saturation_from", 0)); gtk_table_attach(GTK_TABLE(table), range_saturation_from,1,2,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); args->range_saturation_from = range_saturation_from; g_signal_connect(G_OBJECT(range_saturation_from), "value-changed", G_CALLBACK(update), args); range_saturation_to = gtk_spin_button_new_with_range(-100,100,0.001); gtk_spin_button_set_value(GTK_SPIN_BUTTON(range_saturation_to), dynv_get_float_wd(args->params, "saturation_to", 1)); gtk_table_attach(GTK_TABLE(table), range_saturation_to,2,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); table_y++; args->range_saturation_to = range_saturation_to; g_signal_connect(G_OBJECT(range_saturation_to), "value-changed", G_CALLBACK(update), args); gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(_("Steps:"),0,0,0,0),0,1,table_y,table_y+1,GtkAttachOptions(GTK_FILL),GTK_FILL,5,5); range_steps = gtk_spin_button_new_with_range(1, 255, 1); gtk_spin_button_set_value(GTK_SPIN_BUTTON(range_steps), dynv_get_int32_wd(args->params, "steps", 3)); gtk_table_attach(GTK_TABLE(table), range_steps,1,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); table_y++; args->range_steps = range_steps; g_signal_connect(G_OBJECT(range_steps), "value-changed", G_CALLBACK(update), args); toggle_multiplication = gtk_check_button_new_with_mnemonic(_("_Use multiplication")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(toggle_multiplication), dynv_get_bool_wd(args->params, "multiplication", true)); gtk_table_attach(GTK_TABLE(table), toggle_multiplication,1,3,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); table_y++; args->toggle_multiplication = toggle_multiplication; g_signal_connect(G_OBJECT(toggle_multiplication), "toggled", G_CALLBACK(update), args); args->toggle_linearization = gtk_check_button_new_with_mnemonic(_("_Linearization")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(args->toggle_linearization), dynv_get_bool_wd(args->params, "linearization", false)); gtk_table_attach(GTK_TABLE(table), args->toggle_linearization,1,4,table_y,table_y+1,GtkAttachOptions(GTK_FILL | GTK_EXPAND),GTK_FILL,5,0); g_signal_connect(G_OBJECT(args->toggle_linearization), "toggled", G_CALLBACK(update), args); table_y++; GtkWidget* preview_expander; ColorList* preview_color_list = nullptr; gtk_table_attach(GTK_TABLE(table), preview_expander = palette_list_preview_new(gs, true, dynv_get_bool_wd(args->params, "show_preview", true), gs->getColorList(), &preview_color_list), 0, 3, table_y, table_y+1 , GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL | GTK_EXPAND), 5, 5); table_y++; args->selected_color_list = selected_color_list; args->preview_color_list = preview_color_list; update(0, args); gtk_widget_show_all(table); gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), table); if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK) calc(args, false, 0); gint width, height; gtk_window_get_size(GTK_WINDOW(dialog), &width, &height); dynv_set_int32(args->params, "window.width", width); dynv_set_int32(args->params, "window.height", height); dynv_set_bool(args->params, "show_preview", gtk_expander_get_expanded(GTK_EXPANDER(preview_expander))); gtk_widget_destroy(dialog); color_list_destroy(args->preview_color_list); dynv_system_release(args->params); delete args; } gpick-gpick-0.2.6rc1/source/uiDialogVariations.h000066400000000000000000000034431315430016700215670ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_UI_DIALOG_VARIATIONS_H_ #define GPICK_UI_DIALOG_VARIATIONS_H_ class GlobalState; class ColorList; #include void dialog_variations_show(GtkWindow* parent, ColorList *selected_color_list, GlobalState *gs); #endif /* GPICK_UI_DIALOG_VARIATIONS_H_ */ gpick-gpick-0.2.6rc1/source/uiImportExport.cpp000066400000000000000000000603131315430016700213360ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "uiImportExport.h" #include "uiUtilities.h" #include "uiListPalette.h" #include "DynvHelpers.h" #include "ImportExport.h" #include "StringUtils.h" #include "ColorList.h" #include "Converter.h" #include "GlobalState.h" #include "Internationalisation.h" #include "parser/TextFile.h" #include #include using namespace std; struct ImportExportFormat { const char* name; const char* pattern; FileType type; }; struct ListOption { const char* name; const char* label; }; class ImportExportDialogOptions { public: enum class Options { import, import_text_file, }; Options m_options; GtkWidget *m_dialog; GtkWidget *m_converters, *m_item_sizes, *m_backgrounds, *m_include_color_names; GtkWidget *m_single_line_c_comments, *m_multi_line_c_comments, *m_single_line_hash_comments, *m_css_rgb, *m_css_rgba, *m_short_hex, *m_full_hex, *m_float_values, *m_int_values; GlobalState *m_gs; ImportExportDialogOptions(GtkWidget *dialog, GlobalState *gs) { m_dialog = dialog; m_gs = gs; } void createImportOptions() { m_options = Options::import; m_converters = newConverterList(); g_signal_connect(G_OBJECT(m_dialog), "notify::filter", G_CALLBACK(filterChanged), this); auto converters = m_gs->getConverters(); Converter **converter_table; size_t total_converters; converter_table = converters_get_all(converters, &total_converters); GtkTreeIter iter; GtkTreeModel *model = gtk_combo_box_get_model(GTK_COMBO_BOX(m_converters)); bool converter_found = false; string converter_name = dynv_get_string_wd(m_gs->getSettings(), "gpick.import.converter", ""); for (size_t i = 0; i < total_converters; i++){ gtk_list_store_append(GTK_LIST_STORE(model), &iter); gtk_list_store_set(GTK_LIST_STORE(model), &iter, 0, converter_table[i]->human_readable, 1, converter_table[i], -1); if (converter_name == converter_table[i]->function_name){ gtk_combo_box_set_active_iter(GTK_COMBO_BOX(m_converters), &iter); converter_found = true; } } if (!converter_found){ gtk_combo_box_set_active(GTK_COMBO_BOX(m_converters), 0); } delete [] converter_table; const ListOption item_size_options[] = { {"small", _("Small")}, {"medium", _("Medium")}, {"big", _("Big")}, {"controllable", _("User controllable")}, }; m_item_sizes = newOptionList(item_size_options, sizeof(item_size_options) / sizeof(ListOption), dynv_get_string_wd(m_gs->getSettings(), "gpick.import.item_size", "medium")); const ListOption background_options[] = { {"none", _("None")}, {"white", _("White")}, {"gray", _("Gray")}, {"black", _("Black")}, {"first_color", _("First color")}, {"last_color", _("Last color")}, {"controllable", _("User controllable")}, }; m_backgrounds = newOptionList(background_options, sizeof(background_options) / sizeof(ListOption), dynv_get_string_wd(m_gs->getSettings(), "gpick.import.background", "none")); m_include_color_names = newCheckbox(_("Include color names"), dynv_get_bool_wd(m_gs->getSettings(), "gpick.import.include_color_names", true)); afterFilterChanged(); int y = 0; GtkWidget *table = gtk_table_new(2, 3, false); addOption(_("Converter:"), m_converters, 0, y, table); addOption(_("Item size:"), m_item_sizes, 0, y, table); addOption(_("Background:"), m_backgrounds, 0, y, table); addOption(m_include_color_names, 0, y, table); gtk_widget_show_all(table); gtk_file_chooser_set_extra_widget(GTK_FILE_CHOOSER(m_dialog), table); } void createImportTextFileOptions() { m_options = Options::import_text_file; int y = 0; GtkWidget *table = gtk_table_new(2, 3, false); addOption(m_single_line_c_comments = newCheckbox(string(_("C style single-line comments")) + " (//abc)", dynv_get_bool_wd(m_gs->getSettings(), "gpick.import_text_file.single_line_c_comments", true)), 0, y, table); addOption(m_multi_line_c_comments = newCheckbox(string(_("C style multi-line comments")) + " (/*abc*/)", dynv_get_bool_wd(m_gs->getSettings(), "gpick.import_text_file.multi_line_c_comments", true)), 0, y, table); addOption(m_single_line_hash_comments = newCheckbox(string(_("Hash single-line comments")) + " (#abc)", dynv_get_bool_wd(m_gs->getSettings(), "gpick.import_text_file.single_line_hash_comments", true)), 0, y, table); y = 0; addOption(m_css_rgb = newCheckbox("CSS rgb()", dynv_get_bool_wd(m_gs->getSettings(), "gpick.import_text_file.css_rgb", true)), 1, y, table); addOption(m_css_rgba = newCheckbox("CSS rgba()", dynv_get_bool_wd(m_gs->getSettings(), "gpick.import_text_file.css_rgba", true)), 1, y, table); addOption(m_full_hex = newCheckbox(_("Full hex"), dynv_get_bool_wd(m_gs->getSettings(), "gpick.import_text_file.full_hex", true)), 1, y, table); y = 0; addOption(m_short_hex = newCheckbox(_("Short hex"), dynv_get_bool_wd(m_gs->getSettings(), "gpick.import_text_file.short_hex", true)), 2, y, table); addOption(m_int_values = newCheckbox(_("Integer values"), dynv_get_bool_wd(m_gs->getSettings(), "gpick.import_text_file.int_values", true)), 2, y, table); addOption(m_float_values = newCheckbox(_("Real values"), dynv_get_bool_wd(m_gs->getSettings(), "gpick.import_text_file.float_values", true)), 2, y, table); gtk_widget_show_all(table); gtk_file_chooser_set_extra_widget(GTK_FILE_CHOOSER(m_dialog), table); } GtkWidget *addOption(const char *label, GtkWidget *widget, int x, int &y, GtkWidget *table) { gtk_table_attach(GTK_TABLE(table), gtk_label_aligned_new(label, 0, 0.5, 0, 0), x * 3, x * 3 + 1, y, y + 1, GTK_FILL, GTK_FILL, 3, 1); gtk_table_attach(GTK_TABLE(table), widget, 1, 2, y, y + 1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL), 3, 1); y++; return widget; } GtkWidget *addOption(GtkWidget *widget, int x, int &y, GtkWidget *table) { gtk_table_attach(GTK_TABLE(table), widget, x * 3 + 1, x * 3 + 2, y, y + 1, GtkAttachOptions(GTK_FILL | GTK_EXPAND), GtkAttachOptions(GTK_FILL), 3, 1); y++; return widget; } Converter *getSelectedConverter() { GtkTreeIter iter; if (gtk_combo_box_get_active_iter(GTK_COMBO_BOX(m_converters), &iter)){ GtkTreeModel *model = gtk_combo_box_get_model(GTK_COMBO_BOX(m_converters)); Converter *converter; gtk_tree_model_get(GTK_TREE_MODEL(model), &iter, 1, &converter, -1); return converter; } return nullptr; } string getOptionValue(GtkWidget *widget) { GtkTreeIter iter; if (gtk_combo_box_get_active_iter(GTK_COMBO_BOX(widget), &iter)){ GtkTreeModel *model = gtk_combo_box_get_model(GTK_COMBO_BOX(widget)); gchar *value; gtk_tree_model_get(GTK_TREE_MODEL(model), &iter, 1, &value, -1); string result(value); g_free(value); return result; } return string(); } string getSelectedItemSize() { return getOptionValue(m_item_sizes); } string getSelectedBackground() { return getOptionValue(m_backgrounds); } bool isIncludeColorNamesEnabled() { return gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(m_include_color_names)); } bool isSingleLineCCommentsEnabled() { return gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(m_single_line_c_comments)); } bool isMultiLineCCommentsEnabled() { return gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(m_multi_line_c_comments)); } bool isSingleLineHashCommentsEnabled() { return gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(m_single_line_hash_comments)); } bool isCssRgbEnabled() { return gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(m_css_rgb)); } bool isCssRgbaEnabled() { return gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(m_css_rgba)); } bool isFullHexEnabled() { return gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(m_full_hex)); } bool isShortHexEnabled() { return gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(m_short_hex)); } bool isIntValuesEnabled() { return gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(m_int_values)); } bool isFloatValuesEnabled() { return gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(m_float_values)); } void saveState() { auto settings = m_gs->getSettings(); if (m_options == Options::import){ Converter *converter = getSelectedConverter(); if (converter) dynv_set_string(settings, "gpick.import.converter", converter->function_name); string item_size = getSelectedItemSize(); dynv_set_string(settings, "gpick.import.item_size", item_size.c_str()); string background = getSelectedBackground(); dynv_set_string(settings, "gpick.import.background", background.c_str()); dynv_set_bool(settings, "gpick.import.include_color_names", isIncludeColorNamesEnabled()); }else if (m_options == Options::import_text_file){ dynv_set_bool(settings, "gpick.import_text_file.single_line_c_comments", isSingleLineCCommentsEnabled()); dynv_set_bool(settings, "gpick.import_text_file.multi_line_c_comments", isMultiLineCCommentsEnabled()); dynv_set_bool(settings, "gpick.import_text_file.single_line_hash_comments", isSingleLineHashCommentsEnabled()); dynv_set_bool(settings, "gpick.import_text_file.css_rgb", isCssRgbEnabled()); dynv_set_bool(settings, "gpick.import_text_file.css_rgba", isCssRgbaEnabled()); dynv_set_bool(settings, "gpick.import_text_file.full_hex", isFullHexEnabled()); dynv_set_bool(settings, "gpick.import_text_file.short_hex", isShortHexEnabled()); dynv_set_bool(settings, "gpick.import_text_file.int_values", isIntValuesEnabled()); dynv_set_bool(settings, "gpick.import_text_file.float_values", isFloatValuesEnabled()); } } GtkWidget* newConverterList() { GtkListStore *store = gtk_list_store_new(2, G_TYPE_STRING, G_TYPE_POINTER); GtkWidget *list = gtk_combo_box_new_with_model(GTK_TREE_MODEL(store)); GtkCellRenderer *renderer = gtk_cell_renderer_text_new(); gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(list), renderer, true); gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(list), renderer, "text", 0, nullptr); if (store) g_object_unref(store); return list; } GtkWidget* newOptionList(const ListOption *options, size_t n_options, const string &selected_value) { GtkListStore *store = gtk_list_store_new(2, G_TYPE_STRING, G_TYPE_STRING); GtkWidget *list = gtk_combo_box_new_with_model(GTK_TREE_MODEL(store)); GtkCellRenderer *renderer = gtk_cell_renderer_text_new(); gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(list), renderer, true); gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(list), renderer, "text", 0, nullptr); bool found = false; GtkTreeIter iter; for (size_t i = 0; i != n_options; i++){ gtk_list_store_append(store, &iter); gtk_list_store_set(store, &iter, 0, options[i].label, 1, options[i].name, -1); if (selected_value == options[i].name){ gtk_combo_box_set_active_iter(GTK_COMBO_BOX(list), &iter); found = true; } } if (!found){ gtk_combo_box_set_active(GTK_COMBO_BOX(list), 0); } g_object_unref(store); return list; } GtkWidget *newCheckbox(const char *label, bool value) { GtkWidget *widget = gtk_check_button_new_with_label(label); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), value); return widget; } GtkWidget *newCheckbox(const string &label, bool value) { GtkWidget *widget = gtk_check_button_new_with_label(label.c_str()); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), value); return widget; } void afterFilterChanged() { GtkFileFilter *filter = gtk_file_chooser_get_filter(GTK_FILE_CHOOSER(m_dialog)); ImportExportFormat *format = (ImportExportFormat*)g_object_get_data(G_OBJECT(filter), "format"); gtk_widget_set_sensitive(m_converters, format->type == FileType::txt); gtk_widget_set_sensitive(m_item_sizes, format->type == FileType::html); gtk_widget_set_sensitive(m_backgrounds, format->type == FileType::html); gtk_widget_set_sensitive(m_include_color_names, format->type == FileType::html); } static void filterChanged(GtkFileChooserDialog*, GParamSpec*, ImportExportDialogOptions *import_export_dialog) { import_export_dialog->afterFilterChanged(); } }; ImportExportDialog::ImportExportDialog(GtkWindow* parent, ColorList *color_list, GlobalState *gs): m_parent(parent), m_color_list(color_list), m_gs(gs) { } ImportExportDialog::~ImportExportDialog() { } bool ImportExportDialog::showImport() { GtkWidget *dialog = gtk_file_chooser_dialog_new(_("Import"), m_parent, GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_OK, nullptr); gtk_dialog_set_alternative_button_order(GTK_DIALOG(dialog), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1); const ImportExportFormat formats[] = { {_("Gpick Palette (*.gpa)"), "*.gpa", FileType::gpa}, {_("GIMP/Inkscape Palette (*.gpl)"), "*.gpl", FileType::gpl}, {_("Adobe Swatch Exchange (*.ase)"), "*.ase", FileType::ase}, {_("Text File (*.txt)"), "*.txt", FileType::txt}, {_("rgb.txt File (rgb.txt)"), "rgb.txt", FileType::rgbtxt}, }; const size_t n_formats = sizeof(formats) / sizeof(ImportExportFormat); const char* default_path = dynv_get_string_wd(m_gs->getSettings(), "gpick.import.path", ""); gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), default_path); const char* selected_filter = dynv_get_string_wd(m_gs->getSettings(), "gpick.import.filter", "all_supported"); GtkFileFilter *filter = gtk_file_filter_new(); gtk_file_filter_set_name(filter, _("All files")); g_object_set_data(G_OBJECT(filter), "identification", (gpointer)"all"); gtk_file_filter_add_pattern(filter, "*"); gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); if (g_strcmp0(selected_filter, "all") == 0){ gtk_file_chooser_set_filter(GTK_FILE_CHOOSER(dialog), filter); } filter = gtk_file_filter_new(); gtk_file_filter_set_name(filter, _("All supported formats")); g_object_set_data(G_OBJECT(filter), "identification", (gpointer)"all_supported"); for (size_t i = 0; i != n_formats; ++i){ gtk_file_filter_add_pattern(filter, formats[i].pattern); } gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); if (g_strcmp0(selected_filter, "all_supported") == 0){ gtk_file_chooser_set_filter(GTK_FILE_CHOOSER(dialog), filter); } for (size_t i = 0; i != n_formats; ++i){ filter = gtk_file_filter_new(); gtk_file_filter_set_name(filter, formats[i].name); g_object_set_data(G_OBJECT(filter), "identification", (gpointer)formats[i].pattern); gtk_file_filter_add_pattern(filter, formats[i].pattern); gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); if (g_strcmp0(formats[i].pattern, selected_filter) == 0){ gtk_file_chooser_set_filter(GTK_FILE_CHOOSER(dialog), filter); } } bool finished = false; while (!finished){ if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK){ gchar *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); gchar *path = gtk_file_chooser_get_current_folder(GTK_FILE_CHOOSER(dialog)); dynv_set_string(m_gs->getSettings(), "gpick.import.path", path); g_free(path); FileType type = ImportExport::getFileType(filename); if (type == FileType::unknown){ const gchar *format_name = gtk_file_filter_get_name(gtk_file_chooser_get_filter(GTK_FILE_CHOOSER(dialog))); for (size_t i = 0; i != n_formats; ++i){ if (g_strcmp0(formats[i].name, format_name) == 0){ type = formats[i].type; break; } } } GtkWidget* message; if (type == FileType::unknown){ message = gtk_message_dialog_new(GTK_WINDOW(dialog), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, _("File format is not supported")); gtk_window_set_title(GTK_WINDOW(message), _("Import")); gtk_dialog_run(GTK_DIALOG(message)); gtk_widget_destroy(message); }else{ auto converters = m_gs->getConverters(); for (size_t i = 0; i != n_formats; ++i){ if (formats[i].type == type){ ColorList *color_list = color_list_new(m_color_list); ImportExport import_export(color_list, filename, m_gs); import_export.setConverters(converters); if (import_export.importType(formats[i].type)){ finished = true; color_list_add(m_color_list, color_list, true); }else{ message = gtk_message_dialog_new(GTK_WINDOW(dialog), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, _("File could not be imported")); gtk_window_set_title(GTK_WINDOW(message), _("Import")); gtk_dialog_run(GTK_DIALOG(message)); gtk_widget_destroy(message); } const char *identification = (const char*)g_object_get_data(G_OBJECT(gtk_file_chooser_get_filter(GTK_FILE_CHOOSER(dialog))), "identification"); dynv_set_string(m_gs->getSettings(), "gpick.import.filter", identification); color_list_destroy(color_list); break; } } } g_free(filename); }else break; } gtk_widget_destroy(dialog); return finished; } bool ImportExportDialog::showImportTextFile() { GtkWidget *dialog = gtk_file_chooser_dialog_new(_("Import text file"), m_parent, GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_OK, nullptr); gtk_dialog_set_alternative_button_order(GTK_DIALOG(dialog), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1); const char* default_path = dynv_get_string_wd(m_gs->getSettings(), "gpick.import_text_file.path", ""); gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), default_path); ImportExportDialogOptions import_export_dialog_options(dialog, m_gs); import_export_dialog_options.createImportTextFileOptions(); bool finished = false; while (!finished){ if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK){ gchar *path = gtk_file_chooser_get_current_folder(GTK_FILE_CHOOSER(dialog)); dynv_set_string(m_gs->getSettings(), "gpick.import_text_file.path", path); g_free(path); import_export_dialog_options.saveState(); GtkWidget* message; gchar *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); ColorList *color_list = color_list_new(m_color_list); ImportExport import_export(color_list, filename, m_gs); auto converters = m_gs->getConverters(); import_export.setConverters(converters); text_file_parser::Configuration configuration; configuration.single_line_c_comments = import_export_dialog_options.isSingleLineCCommentsEnabled(); configuration.multi_line_c_comments = import_export_dialog_options.isMultiLineCCommentsEnabled(); configuration.single_line_hash_comments = import_export_dialog_options.isSingleLineHashCommentsEnabled(); configuration.css_rgb = import_export_dialog_options.isCssRgbEnabled(); configuration.css_rgba = import_export_dialog_options.isCssRgbaEnabled(); configuration.full_hex = import_export_dialog_options.isFullHexEnabled(); configuration.short_hex = import_export_dialog_options.isShortHexEnabled(); configuration.int_values = import_export_dialog_options.isIntValuesEnabled(); configuration.float_values = import_export_dialog_options.isFloatValuesEnabled(); if (import_export.importTextFile(configuration)){ finished = true; color_list_add(m_color_list, color_list, true); }else{ message = gtk_message_dialog_new(GTK_WINDOW(dialog), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, _("File could not be imported")); gtk_window_set_title(GTK_WINDOW(message), _("Import text file")); gtk_dialog_run(GTK_DIALOG(message)); gtk_widget_destroy(message); } g_free(filename); color_list_destroy(color_list); }else break; } gtk_widget_destroy(dialog); return finished; } bool ImportExportDialog::showExport() { GtkWidget *dialog = gtk_file_chooser_dialog_new(_("Export"), m_parent, GTK_FILE_CHOOSER_ACTION_SAVE, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_SAVE, GTK_RESPONSE_OK, nullptr); gtk_dialog_set_alternative_button_order(GTK_DIALOG(dialog), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1); gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog), true); const ImportExportFormat formats[] = { {_("Gpick Palette (*.gpa)"), "*.gpa", FileType::gpa}, {_("GIMP/Inkscape Palette (*.gpl)"), "*.gpl", FileType::gpl}, {_("Alias/WaveFront Material (*.mtl)"), "*.mtl", FileType::mtl}, {_("Adobe Swatch Exchange (*.ase)"), "*.ase", FileType::ase}, {_("Cascading Style Sheet (*.css)"), "*.css", FileType::css}, {_("Hyper Text Markup Language (*.html, *.htm)"), "*.html,*.htm", FileType::html}, {_("Text file (*.txt)"), "*.txt", FileType::txt}, }; const size_t n_formats = sizeof(formats) / sizeof(ImportExportFormat); const char* default_path = dynv_get_string_wd(m_gs->getSettings(), "gpick.export.path", ""); gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(dialog), default_path); string selected_filter = dynv_get_string_wd(m_gs->getSettings(), "gpick.export.filter", "*.gpl"); for (size_t i = 0; i != n_formats; ++i){ GtkFileFilter *filter = gtk_file_filter_new(); g_object_set_data(G_OBJECT(filter), "format", (gpointer)&formats[i]); gtk_file_filter_set_name(filter, formats[i].name); split(formats[i].pattern, ',', true, [filter](const string &value){ gtk_file_filter_add_pattern(filter, value.c_str()); }); gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); if (formats[i].pattern == selected_filter){ gtk_file_chooser_set_filter(GTK_FILE_CHOOSER(dialog), filter); } } ImportExportDialogOptions import_export_dialog_options(dialog, m_gs); import_export_dialog_options.createImportOptions(); bool finished = false; while (!finished){ if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK){ gchar *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); gchar *path = gtk_file_chooser_get_current_folder(GTK_FILE_CHOOSER(dialog)); dynv_set_string(m_gs->getSettings(), "gpick.import.path", path); g_free(path); import_export_dialog_options.saveState(); string format_name = gtk_file_filter_get_name(gtk_file_chooser_get_filter(GTK_FILE_CHOOSER(dialog))); for (size_t i = 0; i != n_formats; ++i){ if (formats[i].name == format_name){ ImportExport import_export(m_color_list, filename, m_gs); import_export.setConverter(import_export_dialog_options.getSelectedConverter()); string item_size = import_export_dialog_options.getSelectedItemSize(); import_export.setItemSize(item_size.c_str()); string background = import_export_dialog_options.getSelectedBackground(); import_export.setBackground(background.c_str()); import_export.setIncludeColorNames(import_export_dialog_options.isIncludeColorNamesEnabled()); if (import_export.exportType(formats[i].type)){ finished = true; }else{ GtkWidget* message = gtk_message_dialog_new(GTK_WINDOW(dialog), GTK_DIALOG_MODAL, GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, _("File could not be exported")); gtk_window_set_title(GTK_WINDOW(dialog), _("Export")); gtk_dialog_run(GTK_DIALOG(message)); gtk_widget_destroy(message); } dynv_set_string(m_gs->getSettings(), "gpick.export.filter", formats[i].pattern); } } g_free(filename); }else break; } gtk_widget_destroy(dialog); return finished; } gpick-gpick-0.2.6rc1/source/uiImportExport.h000066400000000000000000000037371315430016700210120ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_UI_IMPORT_EXPORT_H_ #define GPICK_UI_IMPORT_EXPORT_H_ #include class GlobalState; class ColorList; class ImportExportDialog { public: ImportExportDialog(GtkWindow* parent, ColorList *color_list, GlobalState *gs); ~ImportExportDialog(); bool showImport(); bool showImportTextFile(); bool showExport(); private: GtkWindow *m_parent; ColorList *m_color_list; GlobalState *m_gs; }; #endif /* GPICK_UI_IMPORT_EXPORT_H_ */ gpick-gpick-0.2.6rc1/source/uiListPalette.cpp000066400000000000000000001041001315430016700211050ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "uiListPalette.h" #include "uiUtilities.h" #include "gtk/ColorCell.h" #include "ColorObject.h" #include "ColorList.h" #include "ColorSource.h" #include "DragDrop.h" #include "GlobalState.h" #include "Converter.h" #include "GlobalState.h" #include "DynvHelpers.h" #include "Vector2.h" #include "Internationalisation.h" #include #include #include #include using namespace math; using namespace std; typedef struct ListPaletteArgs{ ColorSource source; GtkWidget *treeview; gint scroll_timeout; Vec2 last_click_position; bool disable_selection; GtkWidget* count_label; GlobalState* gs; }ListPaletteArgs; static void destroy_arguments(gpointer data); static ColorObject* get_color_object(struct DragDrop* dd); static ColorObject** get_color_object_list(struct DragDrop* dd, size_t *color_object_n); #define SCROLL_EDGE_SIZE 15 //SCROLL_EDGE_SIZE from gtktreeview.c static void add_scroll_timeout(ListPaletteArgs *args); static void remove_scroll_timeout(ListPaletteArgs *args); static gboolean scroll_row_timeout(ListPaletteArgs *args); static void palette_list_vertical_autoscroll(GtkTreeView *treeview); static void update_counts(ListPaletteArgs *args); static gboolean scroll_row_timeout(ListPaletteArgs *args){ palette_list_vertical_autoscroll(GTK_TREE_VIEW(args->treeview)); return true; } static void add_scroll_timeout(ListPaletteArgs *args){ if (!args->scroll_timeout){ args->scroll_timeout = gdk_threads_add_timeout(150, (GSourceFunc)scroll_row_timeout, args); } } static void remove_scroll_timeout(ListPaletteArgs *args){ if (args->scroll_timeout){ g_source_remove(args->scroll_timeout); args->scroll_timeout = 0; } } static bool drag_end(struct DragDrop* dd, GtkWidget *widget, GdkDragContext *context){ remove_scroll_timeout((ListPaletteArgs*)dd->userdata); update_counts((ListPaletteArgs*)dd->userdata); return true; } typedef struct SelectionBoundsArgs{ int min_index; int max_index; int last_index; bool discontinuous; } SelectionBoundsArgs; static void find_selection_bounds(GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter, gpointer data){ gint *indices = gtk_tree_path_get_indices(path); SelectionBoundsArgs *args = (SelectionBoundsArgs *) data; int index = indices[0]; // currently indices are all 1d. int diff = index - args->last_index; if ((args->last_index != 0x7fffffff) && (diff != 1) && (diff != -1)){ args->discontinuous = true; } if (index > args->max_index){ args->max_index = index; } if (index < args->min_index){ args->min_index = index; } args->last_index = index; } static boost::format format_ignore_arg_errors(const std::string &f_string) { boost::format fmter(f_string); fmter.exceptions(boost::io::all_error_bits ^ (boost::io::too_many_args_bit | boost::io::too_few_args_bit)); return fmter; } static void update_counts(ListPaletteArgs *args){ stringstream s; GtkTreeSelection *sel; GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(args->treeview)); SelectionBoundsArgs bounds; int selected_count; int total_colors; if (!args->count_label){ return; } sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(args->treeview)); selected_count = gtk_tree_selection_count_selected_rows(sel); total_colors = gtk_tree_model_iter_n_children(model, nullptr); bounds.discontinuous = false; bounds.min_index = 0x7fffffff; bounds.last_index = 0x7fffffff; bounds.max_index = 0; if (selected_count > 0){ s.str(""); s << "#"; gtk_tree_selection_selected_foreach(sel, &find_selection_bounds, &bounds); if (bounds.min_index < bounds.max_index){ s << bounds.min_index; if (bounds.discontinuous){ s << ".."; }else{ s << "-"; } s << bounds.max_index; }else{ s << bounds.min_index; } #ifdef ENABLE_NLS string selected_color_count; try{ selected_color_count = (format_ignore_arg_errors(ngettext("%d color", "%d colors", selected_count)) % selected_count).str(); }catch(const boost::io::format_error &e){ selected_color_count = ngettext("%d color", "%d colors", selected_count); } s << " (" << selected_color_count << ")"; #else s << " (" << ((selected_count == 1) ? "color" : "colors") << ")"; #endif s << " " << _("selected") << ". "; } #ifdef ENABLE_NLS string total_color_count; try{ total_color_count = (format_ignore_arg_errors(ngettext("Total %d color", "Total %d colors", total_colors)) % total_colors).str(); }catch(const boost::io::format_error &e){ total_color_count = ngettext("Total %d color", "Total %d colors", total_colors); } s << total_color_count; #else s << "Total " << total_colors << " colors."; #endif gtk_label_set_text(GTK_LABEL(args->count_label), s.str().c_str()); } static void palette_list_vertical_autoscroll(GtkTreeView *treeview) { GdkRectangle visible_rect; gint y; gint offset; gdk_window_get_pointer(gtk_tree_view_get_bin_window(treeview), nullptr, &y, nullptr); gint dy; gtk_tree_view_convert_bin_window_to_tree_coords(treeview, 0, 0, 0, &dy); y += dy; gtk_tree_view_get_visible_rect(treeview, &visible_rect); offset = y - (visible_rect.y + 2 * SCROLL_EDGE_SIZE); if (offset > 0) { offset = y - (visible_rect.y + visible_rect.height - 2 * SCROLL_EDGE_SIZE); if (offset < 0) return; } GtkAdjustment *adjustment = gtk_tree_view_get_vadjustment(treeview); gtk_adjustment_set_value(adjustment, min(max(gtk_adjustment_get_value(adjustment) + offset, 0.0), gtk_adjustment_get_upper(adjustment) - gtk_adjustment_get_page_size (adjustment))); } static void palette_list_entry_fill(GtkListStore* store, GtkTreeIter *iter, ColorObject* color_object, ListPaletteArgs* args) { string text; converter_get_text(color_object, ConverterArrayType::color_list, args->gs, text); gtk_list_store_set(store, iter, 0, color_object->reference(), 1, text.c_str(), 2, color_object->getName().c_str(), -1); } static void palette_list_entry_update_row(GtkListStore* store, GtkTreeIter *iter, ColorObject* color_object, ListPaletteArgs* args) { string text; converter_get_text(color_object, ConverterArrayType::color_list, args->gs, text); gtk_list_store_set(store, iter, 1, text.c_str(), 2, color_object->getName().c_str(), -1); } static void palette_list_entry_update_name(GtkListStore* store, GtkTreeIter *iter, ColorObject* color_object) { gtk_list_store_set(store, iter, 2, color_object->getName().c_str(), -1); } static void palette_list_cell_edited(GtkCellRendererText *cell, gchar *path, gchar *new_text, gpointer user_data) { GtkTreeIter iter; GtkTreeModel *model=GTK_TREE_MODEL(user_data); gtk_tree_model_get_iter_from_string(model, &iter, path ); gtk_list_store_set(GTK_LIST_STORE(model), &iter, 2, new_text, -1); ColorObject *color_object; gtk_tree_model_get(model, &iter, 0, &color_object, -1); color_object->setName(new_text); } static void palette_list_row_activated(GtkTreeView *tree_view, GtkTreePath *path, GtkTreeViewColumn *column, gpointer user_data) { ListPaletteArgs* args = (ListPaletteArgs*)user_data; GtkTreeModel* model = gtk_tree_view_get_model(tree_view);; GtkTreeIter iter; gtk_tree_model_get_iter(model, &iter, path); ColorObject *color_object; gtk_tree_model_get(model, &iter, 0, &color_object, -1); ColorSource *color_source = args->gs->getCurrentColorSource(); if (color_source != nullptr) color_source_set_color(color_source, color_object); update_counts(args); } static int palette_list_preview_on_insert(ColorList* color_list, ColorObject* color_object){ palette_list_add_entry(GTK_WIDGET(color_list->userdata), color_object); return 0; } static int palette_list_preview_on_clear(ColorList* color_list){ palette_list_remove_all_entries(GTK_WIDGET(color_list->userdata)); return 0; } static void destroy_cb(GtkWidget* widget, ListPaletteArgs *args){ remove_scroll_timeout(args); palette_list_remove_all_entries(widget); } GtkWidget* palette_list_get_widget(ColorList *color_list){ return (GtkWidget*)color_list->userdata; } GtkWidget* palette_list_preview_new(GlobalState* gs, bool expander, bool expanded, ColorList* color_list, ColorList** out_color_list){ ListPaletteArgs* args = new ListPaletteArgs; args->gs = gs; args->scroll_timeout = 0; args->count_label = nullptr; GtkListStore *store; GtkCellRenderer *renderer; GtkTreeViewColumn *col; GtkWidget *view; view = gtk_tree_view_new(); args->treeview = view; gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), 0); store = gtk_list_store_new (3, G_TYPE_POINTER, G_TYPE_STRING, G_TYPE_STRING); col = gtk_tree_view_column_new(); gtk_tree_view_column_set_sizing(col,GTK_TREE_VIEW_COLUMN_AUTOSIZE); gtk_tree_view_column_set_resizable(col, 0); renderer = custom_cell_renderer_color_new(); custom_cell_renderer_color_set_size(renderer, 16, 16); gtk_tree_view_column_pack_start(col, renderer, TRUE); gtk_tree_view_column_add_attribute(col, renderer, "color", 0); gtk_tree_view_append_column(GTK_TREE_VIEW(view), col); gtk_tree_view_set_enable_search(GTK_TREE_VIEW(view), false); gtk_tree_view_set_model(GTK_TREE_VIEW(view), GTK_TREE_MODEL(store)); g_object_unref(GTK_TREE_MODEL(store)); GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(view)); gtk_tree_selection_set_mode(selection, GTK_SELECTION_SINGLE); gtk_drag_source_set(view, GDK_BUTTON1_MASK, 0, 0, GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE | GDK_ACTION_ASK)); struct DragDrop dd; dragdrop_init(&dd, gs); dd.get_color_object = get_color_object; dd.get_color_object_list = get_color_object_list; dd.drag_end = drag_end; dd.handler_map = dynv_system_get_handler_map(gs->getColorList()->params); dd.userdata = args; dragdrop_widget_attach(view, DragDropFlags(DRAGDROP_SOURCE), &dd); if (out_color_list) { struct dynvHandlerMap* handler_map = dynv_system_get_handler_map(color_list->params); ColorList* cl=color_list_new(handler_map); dynv_handler_map_release(handler_map); cl->userdata=view; cl->on_insert=palette_list_preview_on_insert; cl->on_clear=palette_list_preview_on_clear; *out_color_list=cl; } GtkWidget *scrolled_window; scrolled_window=gtk_scrolled_window_new (0,0); gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window),GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW(scrolled_window), GTK_SHADOW_IN); gtk_container_add(GTK_CONTAINER(scrolled_window), view); GtkWidget *main_widget = scrolled_window; if (expander){ GtkWidget *expander=gtk_expander_new(_("Preview")); gtk_container_add(GTK_CONTAINER(expander), scrolled_window); gtk_expander_set_expanded(GTK_EXPANDER(expander), expanded); main_widget = expander; } g_object_set_data_full(G_OBJECT(view), "arguments", args, destroy_arguments); g_signal_connect(G_OBJECT(view), "destroy", G_CALLBACK(destroy_cb), args); return main_widget; } static ColorObject** get_color_object_list(struct DragDrop* dd, size_t *color_object_n){ GtkTreeIter iter; GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(dd->widget)); GtkTreeModel* model; gint selected = gtk_tree_selection_count_selected_rows(selection); if (selected <= 1){ if (color_object_n) *color_object_n = selected; return 0; } GList *list = gtk_tree_selection_get_selected_rows(selection, &model); ColorObject** color_objects = new ColorObject*[selected]; if (color_object_n) *color_object_n = selected; if (list){ GList *i = list; ColorObject* color_object; uint32_t j = 0; while (i) { gtk_tree_model_get_iter(model, &iter, (GtkTreePath*) (i->data)); gtk_tree_model_get(model, &iter, 0, &color_object, -1); color_objects[j] = color_object->reference(); i = g_list_next(i); j++; } g_list_foreach (list, (GFunc)gtk_tree_path_free, nullptr); g_list_free (list); } return color_objects; } static ColorObject* get_color_object(struct DragDrop* dd){ GtkTreeIter iter; GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(dd->widget)); GtkTreeModel* model; GList *list = gtk_tree_selection_get_selected_rows ( selection, &model ); if (list){ GList *i = list; ColorObject* color_object; while (i) { gtk_tree_model_get_iter(model, &iter, (GtkTreePath*) (i->data)); gtk_tree_model_get(model, &iter, 0, &color_object, -1); g_list_foreach (list, (GFunc)gtk_tree_path_free, nullptr); g_list_free (list); return color_object->reference(); i = g_list_next(i); } g_list_foreach (list, (GFunc)gtk_tree_path_free, nullptr); g_list_free (list); } return 0; } static int set_color_object_list_at(DragDrop* dd, ColorObject** color_objects, size_t color_object_n, int x, int y, bool move){ ListPaletteArgs* args = (ListPaletteArgs*)dd->userdata; remove_scroll_timeout(args); GtkTreePath* path; GtkTreeViewDropPosition pos; GtkTreeIter iter, iter2; GtkTreeModel* model = gtk_tree_view_get_model(GTK_TREE_VIEW(dd->widget)); bool copy = false; bool path_is_valid = false; if (gtk_tree_view_get_dest_row_at_pos(GTK_TREE_VIEW(dd->widget), x, y, &path, &pos)){ gtk_tree_model_get_iter(model, &iter, path); if (pos == GTK_TREE_VIEW_DROP_BEFORE || pos == GTK_TREE_VIEW_DROP_INTO_OR_BEFORE){ path_is_valid = true; }else if (pos == GTK_TREE_VIEW_DROP_AFTER || pos == GTK_TREE_VIEW_DROP_INTO_OR_AFTER){ path_is_valid = true; }else{ return -1; } } for (uint32_t i = 0; i != color_object_n; i++){ ColorObject *color_object = nullptr; if (pos == GTK_TREE_VIEW_DROP_BEFORE || pos == GTK_TREE_VIEW_DROP_INTO_OR_BEFORE){ color_object = color_objects[i]; }else if (pos == GTK_TREE_VIEW_DROP_AFTER || pos == GTK_TREE_VIEW_DROP_INTO_OR_AFTER){ color_object = color_objects[color_object_n - i - 1]; }else{ color_object = color_objects[i]; } if (move){ ColorObject *reference_color_object; gtk_tree_model_get(GTK_TREE_MODEL(model), &iter, 0, &reference_color_object, -1); if (reference_color_object == color_object){ // Reference item is going to be removed, so any further inserts // will fail if the same iterator is used. Iterator is moved forward // to avoid that. if (pos == GTK_TREE_VIEW_DROP_BEFORE || pos == GTK_TREE_VIEW_DROP_INTO_OR_BEFORE){ if (!gtk_tree_model_iter_next(GTK_TREE_MODEL(model), &iter)){ path_is_valid = false; } }else if (pos == GTK_TREE_VIEW_DROP_AFTER || pos == GTK_TREE_VIEW_DROP_INTO_OR_AFTER){ GtkTreePath *path = gtk_tree_model_get_path(GTK_TREE_MODEL(model), &iter); if (gtk_tree_path_prev(path)) { if (!gtk_tree_model_get_iter(GTK_TREE_MODEL(model), &iter, path)){ path_is_valid = false; } }else{ path_is_valid = false; } gtk_tree_path_free(path); } } if (color_object->getReferenceCount() != 1){ //only one reference, can't be in palette color_list_remove_color_object(args->gs->getColorList(), color_object); } }else{ color_object = color_object->copy(); copy = true; } if (path_is_valid){ if (pos == GTK_TREE_VIEW_DROP_BEFORE || pos == GTK_TREE_VIEW_DROP_INTO_OR_BEFORE){ gtk_list_store_insert_before(GTK_LIST_STORE(model), &iter2, &iter); palette_list_entry_fill(GTK_LIST_STORE(model), &iter2, color_object, args); color_list_add_color_object(args->gs->getColorList(), color_object, false); }else if (pos == GTK_TREE_VIEW_DROP_AFTER || pos == GTK_TREE_VIEW_DROP_INTO_OR_AFTER){ gtk_list_store_insert_after(GTK_LIST_STORE(model), &iter2, &iter); palette_list_entry_fill(GTK_LIST_STORE(model), &iter2, color_object, args); color_list_add_color_object(args->gs->getColorList(), color_object, false); }else{ if (copy) color_object->release(); return -1; } }else{ color_list_add_color_object(args->gs->getColorList(), color_object, true); if (copy) color_object->release(); } } update_counts(args); return 0; } static int set_color_object_at(struct DragDrop* dd, ColorObject* color_object, int x, int y, bool move) { ListPaletteArgs* args = (ListPaletteArgs*)dd->userdata; remove_scroll_timeout((ListPaletteArgs*)dd->userdata); GtkTreePath* path; GtkTreeViewDropPosition pos; GtkTreeIter iter, iter2; GtkTreeModel* model = gtk_tree_view_get_model(GTK_TREE_VIEW(dd->widget)); bool copy = false; if (move){ if (color_object->getReferenceCount() != 1){ //only one reference, can't be in palette color_list_remove_color_object(args->gs->getColorList(), color_object); } }else{ color_object = color_object->copy(); copy = true; } if (gtk_tree_view_get_dest_row_at_pos(GTK_TREE_VIEW(dd->widget), x, y, &path, &pos)){ gtk_tree_model_get_iter(model, &iter, path); GdkModifierType mask; gdk_window_get_pointer(gtk_tree_view_get_bin_window(GTK_TREE_VIEW(dd->widget)), nullptr, nullptr, &mask); if ((mask & GDK_CONTROL_MASK) && (pos == GTK_TREE_VIEW_DROP_INTO_OR_AFTER || pos == GTK_TREE_VIEW_DROP_INTO_OR_BEFORE)){ Color color = color_object->getColor(); ColorObject* original_color_object; gtk_tree_model_get(GTK_TREE_MODEL(model), &iter, 0, &original_color_object, -1); original_color_object->setColor(color); palette_list_entry_update_row(GTK_LIST_STORE(model), &iter, original_color_object, args); }else if (pos == GTK_TREE_VIEW_DROP_BEFORE || pos == GTK_TREE_VIEW_DROP_INTO_OR_BEFORE){ gtk_list_store_insert_before(GTK_LIST_STORE(model), &iter2, &iter); palette_list_entry_fill(GTK_LIST_STORE(model), &iter2, color_object, args); color_list_add_color_object(args->gs->getColorList(), color_object, false); }else if (pos == GTK_TREE_VIEW_DROP_AFTER || pos == GTK_TREE_VIEW_DROP_INTO_OR_AFTER){ gtk_list_store_insert_after(GTK_LIST_STORE(model), &iter2, &iter); palette_list_entry_fill(GTK_LIST_STORE(model), &iter2, color_object, args); color_list_add_color_object(args->gs->getColorList(), color_object, false); }else{ if (copy) color_object->release(); update_counts(args); return -1; } if (copy) color_object->release(); }else{ color_list_add_color_object(args->gs->getColorList(), color_object, true); update_counts(args); if (copy) color_object->release(); } update_counts(args); return 0; } static bool test_at(struct DragDrop* dd, int x, int y) { GtkTreePath* path; GtkTreeViewDropPosition pos; if (gtk_tree_view_get_dest_row_at_pos(GTK_TREE_VIEW(dd->widget), x, y, &path, &pos)){ GdkModifierType mask; gdk_window_get_pointer(gtk_tree_view_get_bin_window(GTK_TREE_VIEW(dd->widget)), nullptr, nullptr, &mask); if ((mask & GDK_CONTROL_MASK) && (pos == GTK_TREE_VIEW_DROP_INTO_OR_AFTER || pos == GTK_TREE_VIEW_DROP_INTO_OR_BEFORE)){ pos = GTK_TREE_VIEW_DROP_INTO_OR_BEFORE; }else if (pos == GTK_TREE_VIEW_DROP_BEFORE || pos == GTK_TREE_VIEW_DROP_INTO_OR_BEFORE){ pos = GTK_TREE_VIEW_DROP_BEFORE; }else if (pos == GTK_TREE_VIEW_DROP_AFTER || pos == GTK_TREE_VIEW_DROP_INTO_OR_AFTER){ pos = GTK_TREE_VIEW_DROP_AFTER; } gtk_tree_view_set_drag_dest_row(GTK_TREE_VIEW(dd->widget), path, pos); add_scroll_timeout((ListPaletteArgs*)dd->userdata); }else{ gtk_tree_view_unset_rows_drag_dest(GTK_TREE_VIEW(dd->widget)); } return true; } static void destroy_arguments(gpointer data){ ListPaletteArgs* args = (ListPaletteArgs*)data; delete args; } static gboolean disable_palette_selection_function(GtkTreeSelection *selection, GtkTreeModel *model, GtkTreePath *path, gboolean path_currently_selected, ListPaletteArgs *args) { return args->disable_selection; } static void disable_palette_selection(GtkWidget *widget, gboolean disable, int x, int y, ListPaletteArgs *args) { GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(widget)); args->disable_selection = disable; gtk_tree_selection_set_select_function(selection, (GtkTreeSelectionFunc)disable_palette_selection_function, args, nullptr); args->last_click_position.x = x; args->last_click_position.y = y; } static gboolean on_palette_button_press(GtkWidget *widget, GdkEventButton *event, ListPaletteArgs *args) { disable_palette_selection(widget, true, -1, -1, args); if (event->button != 1) return false; if (event->state & (GDK_SHIFT_MASK|GDK_CONTROL_MASK)) return false; GtkTreePath *path = nullptr; if (!gtk_tree_view_get_path_at_pos(GTK_TREE_VIEW(widget), event->x, event->y, &path, nullptr, nullptr, nullptr)) return false; GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(widget)); if (gtk_tree_selection_path_is_selected(selection, path)) { disable_palette_selection(widget, false, event->x, event->y, args); } if (path) gtk_tree_path_free(path); update_counts((ListPaletteArgs*)args); return false; } static gboolean on_palette_button_release(GtkWidget *widget, GdkEventButton *event, ListPaletteArgs *args) { if (args->last_click_position != Vec2(-1, -1)) { Vec2 click_pos = args->last_click_position; disable_palette_selection(widget, true, -1, -1, args); if (click_pos.x == event->x && click_pos.y == event->y) { GtkTreePath *path = nullptr; GtkTreeViewColumn *column; if (gtk_tree_view_get_path_at_pos(GTK_TREE_VIEW(widget), event->x, event->y, &path, &column, nullptr, nullptr)) { gtk_tree_view_set_cursor(GTK_TREE_VIEW(widget), path, column, FALSE); } if (path) gtk_tree_path_free(path); } } update_counts((ListPaletteArgs*)args); return false; } static void on_palette_cursor_changed(GtkTreeView *treeview, ListPaletteArgs *args){ update_counts(args); } static gboolean on_palette_select_all(GtkTreeView *treeview, ListPaletteArgs *args){ update_counts(args); return FALSE; } static gboolean on_palette_unselect_all(GtkTreeView *treeview, ListPaletteArgs *args){ update_counts(args); return FALSE; } GtkWidget* palette_list_new(GlobalState* gs, GtkWidget* count_label){ ListPaletteArgs* args = new ListPaletteArgs; args->gs = gs; args->count_label = count_label; args->scroll_timeout = 0; GtkListStore *store; GtkCellRenderer *renderer; GtkTreeViewColumn *col; GtkWidget *view; view = gtk_tree_view_new (); args->treeview = view; gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), 1); store = gtk_list_store_new (3, G_TYPE_POINTER, G_TYPE_STRING, G_TYPE_STRING); col = gtk_tree_view_column_new(); gtk_tree_view_column_set_sizing(col,GTK_TREE_VIEW_COLUMN_AUTOSIZE); gtk_tree_view_column_set_resizable(col,1); gtk_tree_view_column_set_title(col, _("Color")); renderer = custom_cell_renderer_color_new(); gtk_tree_view_column_pack_start(col, renderer, TRUE); gtk_tree_view_column_add_attribute(col, renderer, "color", 0); gtk_tree_view_append_column(GTK_TREE_VIEW(view), col); col = gtk_tree_view_column_new(); gtk_tree_view_column_set_sizing(col,GTK_TREE_VIEW_COLUMN_AUTOSIZE); gtk_tree_view_column_set_resizable(col,1); gtk_tree_view_column_set_title(col, _("Color")); renderer = gtk_cell_renderer_text_new(); gtk_tree_view_column_pack_start(col, renderer, TRUE); gtk_tree_view_column_add_attribute(col, renderer, "text", 1); gtk_tree_view_append_column(GTK_TREE_VIEW(view), col); col = gtk_tree_view_column_new(); gtk_tree_view_column_set_sizing(col,GTK_TREE_VIEW_COLUMN_AUTOSIZE); gtk_tree_view_column_set_resizable(col,1); gtk_tree_view_column_set_title(col, _("Name")); renderer = gtk_cell_renderer_text_new(); gtk_tree_view_column_pack_start(col, renderer, TRUE); gtk_tree_view_column_add_attribute(col, renderer, "text", 2); gtk_tree_view_append_column(GTK_TREE_VIEW(view), col); g_object_set(renderer, "editable", TRUE, nullptr); g_signal_connect(renderer, "edited", (GCallback) palette_list_cell_edited, store); gtk_tree_view_set_enable_search(GTK_TREE_VIEW(view), false); gtk_tree_view_set_model(GTK_TREE_VIEW(view), GTK_TREE_MODEL(store)); g_object_unref(GTK_TREE_MODEL(store)); GtkTreeSelection *selection = gtk_tree_view_get_selection ( GTK_TREE_VIEW(view) ); gtk_tree_selection_set_mode(selection, GTK_SELECTION_MULTIPLE); g_signal_connect(G_OBJECT(view), "row-activated", G_CALLBACK(palette_list_row_activated), args); g_signal_connect(G_OBJECT(view), "button-press-event", G_CALLBACK(on_palette_button_press), args); g_signal_connect(G_OBJECT(view), "button-release-event", G_CALLBACK(on_palette_button_release), args); g_signal_connect(G_OBJECT(view), "cursor-changed", G_CALLBACK(on_palette_cursor_changed), args); g_signal_connect_after(G_OBJECT(view), "select-all", G_CALLBACK(on_palette_select_all), args); g_signal_connect_after(G_OBJECT(view), "unselect-all", G_CALLBACK(on_palette_unselect_all), args); ///gtk_tree_view_set_reorderable(GTK_TREE_VIEW (view), TRUE); gtk_drag_dest_set( view, GtkDestDefaults(GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_HIGHLIGHT), 0, 0, GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE | GDK_ACTION_ASK)); gtk_drag_source_set( view, GDK_BUTTON1_MASK, 0, 0, GdkDragAction(GDK_ACTION_COPY | GDK_ACTION_MOVE | GDK_ACTION_ASK)); struct DragDrop dd; dragdrop_init(&dd, gs); dd.get_color_object = get_color_object; dd.get_color_object_list = get_color_object_list; dd.set_color_object_at = set_color_object_at; dd.set_color_object_list_at = set_color_object_list_at; dd.handler_map = dynv_system_get_handler_map(gs->getColorList()->params); dd.test_at = test_at; dd.drag_end = drag_end; dd.userdata = args; dragdrop_widget_attach(view, DragDropFlags(DRAGDROP_SOURCE | DRAGDROP_DESTINATION), &dd); g_object_set_data_full(G_OBJECT(view), "arguments", args, destroy_arguments); g_signal_connect(G_OBJECT(view), "destroy", G_CALLBACK(destroy_cb), args); if (count_label){ update_counts(args); } return view; } void palette_list_remove_all_entries(GtkWidget* widget) { ListPaletteArgs* args = (ListPaletteArgs*)g_object_get_data(G_OBJECT(widget), "arguments"); GtkTreeIter iter; GtkListStore *store; gboolean valid; store=GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(widget))); valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter); while (valid){ ColorObject* c; gtk_tree_model_get(GTK_TREE_MODEL(store), &iter, 0, &c, -1); c->release(); valid = gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter); } gtk_list_store_clear(GTK_LIST_STORE(store)); update_counts(args); } gint32 palette_list_get_selected_count(GtkWidget* widget) { return gtk_tree_selection_count_selected_rows(gtk_tree_view_get_selection(GTK_TREE_VIEW(widget))); } gint32 palette_list_get_count(GtkWidget* widget){ GtkTreeModel *store; store=gtk_tree_view_get_model(GTK_TREE_VIEW(widget)); return gtk_tree_model_iter_n_children(store, nullptr); } gint32 palette_list_get_selected_color(GtkWidget* widget, Color* color) { GtkTreeSelection *selection = gtk_tree_view_get_selection ( GTK_TREE_VIEW(widget) ); GtkListStore *store; GtkTreeIter iter; if (gtk_tree_selection_count_selected_rows(selection) != 1){ return -1; } store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(widget))); GList *list = gtk_tree_selection_get_selected_rows ( selection, 0 ); GList *i = list; if (i){ ColorObject* color_object; gtk_tree_model_get_iter(GTK_TREE_MODEL(store), &iter, (GtkTreePath*)i->data); gtk_tree_model_get(GTK_TREE_MODEL(store), &iter, 0, &color_object, -1); *color = color_object->getColor(); } g_list_foreach(list, (GFunc)gtk_tree_path_free, nullptr); g_list_free(list); return 0; } void palette_list_remove_selected_entries(GtkWidget* widget) { ListPaletteArgs* args = (ListPaletteArgs*)g_object_get_data(G_OBJECT(widget), "arguments"); GtkTreeIter iter; GtkListStore *store; gboolean valid; store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(widget))); valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter); ColorObject* color_object; while (valid){ gtk_tree_model_get(GTK_TREE_MODEL(store), &iter, 0, &color_object, -1); if (color_object->isSelected()){ valid = gtk_list_store_remove(GTK_LIST_STORE(store), &iter); color_object->release(); }else{ valid = gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter); } } update_counts(args); } void palette_list_add_entry(GtkWidget* widget, ColorObject* color_object) { ListPaletteArgs* args = (ListPaletteArgs*)g_object_get_data(G_OBJECT(widget), "arguments"); GtkTreeIter iter1; GtkListStore *store; store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(widget))); gtk_list_store_append(store, &iter1); palette_list_entry_fill(store, &iter1, color_object, args); update_counts(args); } int palette_list_remove_entry(GtkWidget* widget, ColorObject* r_color_object) { ListPaletteArgs* args = (ListPaletteArgs*)g_object_get_data(G_OBJECT(widget), "arguments"); GtkTreeIter iter; GtkListStore *store; gboolean valid; store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(widget))); valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter); ColorObject* color_object; while (valid){ gtk_tree_model_get(GTK_TREE_MODEL(store), &iter, 0, &color_object, -1); if (color_object == r_color_object){ valid = gtk_list_store_remove(GTK_LIST_STORE(store), &iter); color_object->release(); return 0; } valid = gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter); } update_counts(args); return -1; } static void execute_callback(GtkListStore *store, GtkTreeIter *iter, ListPaletteArgs* args, PaletteListCallback callback, void *userdata) { ColorObject* color_object; gtk_tree_model_get(GTK_TREE_MODEL(store), iter, 0, &color_object, -1); PaletteListCallbackReturn r = callback(color_object, userdata); switch (r){ case PALETTE_LIST_CALLBACK_UPDATE_NAME: palette_list_entry_update_name(store, iter, color_object); break; case PALETTE_LIST_CALLBACK_UPDATE_ROW: palette_list_entry_update_row(store, iter, color_object, args); break; case PALETTE_LIST_CALLBACK_NO_UPDATE: break; } } static void execute_replace_callback(GtkListStore *store, GtkTreeIter *iter, ListPaletteArgs* args, PaletteListReplaceCallback callback, void *userdata) { ColorObject *color_object, *orig_color_object; gtk_tree_model_get(GTK_TREE_MODEL(store), iter, 0, &color_object, -1); orig_color_object = color_object; color_object->reference(); PaletteListCallbackReturn r = callback(&color_object, userdata); if (color_object != orig_color_object){ gtk_list_store_set(store, iter, 0, color_object, -1); } switch (r){ case PALETTE_LIST_CALLBACK_UPDATE_NAME: palette_list_entry_update_name(store, iter, color_object); break; case PALETTE_LIST_CALLBACK_UPDATE_ROW: palette_list_entry_update_row(store, iter, color_object, args); break; case PALETTE_LIST_CALLBACK_NO_UPDATE: break; } color_object->release(); } gint32 palette_list_foreach(GtkWidget* widget, PaletteListCallback callback, void *userdata) { ListPaletteArgs* args = (ListPaletteArgs*)g_object_get_data(G_OBJECT(widget), "arguments"); GtkTreeIter iter; GtkListStore *store; gboolean valid; store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(widget))); valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter); while (valid){ execute_callback(store, &iter, args, callback, userdata); valid = gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter); } return 0; } gint32 palette_list_foreach_selected(GtkWidget* widget, PaletteListCallback callback, void *userdata) { ListPaletteArgs* args = (ListPaletteArgs*)g_object_get_data(G_OBJECT(widget), "arguments"); GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(widget)); GtkListStore *store; GtkTreeIter iter; store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(widget))); GList *list = gtk_tree_selection_get_selected_rows(selection, 0); GList *i = list; while (i) { gtk_tree_model_get_iter(GTK_TREE_MODEL(store), &iter, (GtkTreePath*) (i->data)); execute_callback(store, &iter, args, callback, userdata); i = g_list_next(i); } g_list_foreach(list, (GFunc)gtk_tree_path_free, nullptr); g_list_free(list); return 0; } gint32 palette_list_foreach_selected(GtkWidget* widget, PaletteListReplaceCallback callback, void *userdata){ ListPaletteArgs* args = (ListPaletteArgs*)g_object_get_data(G_OBJECT(widget), "arguments"); GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(widget)); GtkListStore *store; GtkTreeIter iter; store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(widget))); GList *list = gtk_tree_selection_get_selected_rows(selection, 0); GList *i = list; while (i) { gtk_tree_model_get_iter(GTK_TREE_MODEL(store), &iter, (GtkTreePath*) (i->data)); execute_replace_callback(store, &iter, args, callback, userdata); i = g_list_next(i); } g_list_foreach(list, (GFunc)gtk_tree_path_free, nullptr); g_list_free(list); return 0; } gint32 palette_list_forfirst_selected(GtkWidget* widget, PaletteListCallback callback, void *userdata) { ListPaletteArgs* args = (ListPaletteArgs*)g_object_get_data(G_OBJECT(widget), "arguments"); GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(widget)); GtkListStore *store; GtkTreeIter iter; store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(widget))); GList *list = gtk_tree_selection_get_selected_rows(selection, 0); GList *i = list; if (i) { gtk_tree_model_get_iter(GTK_TREE_MODEL(store), &iter, (GtkTreePath*) (i->data)); execute_callback(store, &iter, args, callback, userdata); } g_list_foreach(list, (GFunc)gtk_tree_path_free, nullptr); g_list_free(list); return 0; } gpick-gpick-0.2.6rc1/source/uiListPalette.h000066400000000000000000000061201315430016700205550ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_UI_LIST_PALETTE_H_ #define GPICK_UI_LIST_PALETTE_H_ class GlobalState; class ColorObject; class ColorList; #include GtkWidget* palette_list_new(GlobalState* gs, GtkWidget* count_label); void palette_list_add_entry(GtkWidget* widget, ColorObject *color_object); GtkWidget* palette_list_preview_new(GlobalState* gs, bool expander, bool expanded, ColorList* color_list, ColorList** out_color_list); GtkWidget* palette_list_get_widget(ColorList *color_list); void palette_list_remove_all_entries(GtkWidget* widget); void palette_list_remove_selected_entries(GtkWidget* widget); int palette_list_remove_entry(GtkWidget* widget, ColorObject *color_object); enum PaletteListCallbackReturn{ PALETTE_LIST_CALLBACK_NO_UPDATE = 0, PALETTE_LIST_CALLBACK_UPDATE_ROW = 1, PALETTE_LIST_CALLBACK_UPDATE_NAME = 2, }; typedef PaletteListCallbackReturn (*PaletteListCallback)(ColorObject* color_object, void *userdata); typedef PaletteListCallbackReturn (*PaletteListReplaceCallback)(ColorObject** color_object, void *userdata); gint32 palette_list_foreach_selected(GtkWidget* widget, PaletteListCallback callback, void *userdata); gint32 palette_list_foreach_selected(GtkWidget* widget, PaletteListReplaceCallback callback, void *userdata); gint32 palette_list_forfirst_selected(GtkWidget* widget, PaletteListCallback callback, void *userdata); gint32 palette_list_foreach(GtkWidget* widget, PaletteListCallback callback, void *userdata); gint32 palette_list_get_selected_count(GtkWidget* widget); gint32 palette_list_get_count(GtkWidget* widget); #endif /* GPICK_UI_LIST_PALETTE_H_ */ gpick-gpick-0.2.6rc1/source/uiStatusIcon.cpp000066400000000000000000000107461315430016700207630ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "uiStatusIcon.h" #include "gtk/Zoomed.h" #include "gtk/ColorWidget.h" #include "uiUtilities.h" #include "uiApp.h" #include "GlobalState.h" #include "ColorPicker.h" #include "FloatingPicker.h" #include "Converter.h" #include "DynvHelpers.h" #include "Internationalisation.h" #include using namespace math; struct uiStatusIcon { GtkWidget *parent; GtkStatusIcon *status_icon; FloatingPicker floating_picker; GlobalState *gs; }; static void status_icon_destroy_parent(GtkWidget *, uiStatusIcon* si) { gtk_widget_destroy(GTK_WIDGET(si->parent)); } static void status_icon_show_parent(GtkWidget *, uiStatusIcon* si) { floating_picker_deactivate(si->floating_picker); status_icon_set_visible(si, false); struct dynvSystem *params = dynv_get_dynv(si->gs->getSettings(), "gpick.main"); main_show_window(si->parent, params); dynv_system_release(params); } static void status_icon_popup(GtkStatusIcon *status_icon, guint button, guint activate_time, gpointer user_data) { struct uiStatusIcon* si = (struct uiStatusIcon*)user_data; GtkMenu *menu = GTK_MENU(gtk_menu_new()); GtkWidget* item = gtk_menu_item_new_with_image(_("_Show Main Window"), gtk_image_new_from_icon_name("gpick", GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(status_icon_show_parent), si); gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new()); item = gtk_menu_item_new_with_image(_("_Quit"), gtk_image_new_from_stock(GTK_STOCK_QUIT, GTK_ICON_SIZE_MENU)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), item); g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(status_icon_destroy_parent), si); gtk_widget_show_all(GTK_WIDGET(menu)); gtk_menu_popup(GTK_MENU(menu), nullptr, nullptr, 0, 0, button, activate_time); g_object_ref_sink(menu); g_object_unref(menu); } static void status_icon_activate(GtkWidget *widget, gpointer user_data) { struct uiStatusIcon* si = (struct uiStatusIcon*)user_data; floating_picker_activate(si->floating_picker, false, false, nullptr); } void status_icon_set_visible(struct uiStatusIcon* si, bool visible) { if (visible == false){ floating_picker_deactivate(si->floating_picker); } gtk_status_icon_set_visible(si->status_icon, visible); } struct uiStatusIcon* status_icon_new(GtkWidget* parent, GlobalState* gs, FloatingPicker floating_picker) { struct uiStatusIcon *si = new struct uiStatusIcon; si->gs = gs; si->parent = gtk_widget_get_toplevel(parent); GtkStatusIcon *status_icon = gtk_status_icon_new(); gtk_status_icon_set_visible(status_icon, FALSE); gtk_status_icon_set_from_icon_name(status_icon, "gpick"); g_signal_connect(G_OBJECT(status_icon), "popup-menu", G_CALLBACK(status_icon_popup), si); #ifndef WIN32 g_signal_connect(G_OBJECT(status_icon), "activate", G_CALLBACK(status_icon_activate), si); #endif si->floating_picker = floating_picker; si->status_icon = status_icon; return si; } void status_icon_destroy(struct uiStatusIcon* si) { delete si; } gpick-gpick-0.2.6rc1/source/uiStatusIcon.h000066400000000000000000000036351315430016700204270ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_UI_STATUS_ICON_H_ #define GPICK_UI_STATUS_ICON_H_ class GlobalState; #include "FloatingPicker.h" #include struct uiStatusIcon; uiStatusIcon* status_icon_new(GtkWidget* parent, GlobalState* gs, FloatingPicker floating_picker); void status_icon_set_visible(uiStatusIcon* si, bool visible); void status_icon_destroy(uiStatusIcon* si); #endif /* GPICK_UI_STATUS_ICON_H_ */ gpick-gpick-0.2.6rc1/source/uiTransformations.cpp000066400000000000000000000423331315430016700220550ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "uiTransformations.h" #include "Converter.h" #include "uiUtilities.h" #include "DynvHelpers.h" #include "GlobalState.h" #include "Internationalisation.h" #include "transformation/Chain.h" #include "transformation/Factory.h" #include "transformation/ColorVisionDeficiency.h" #include using namespace std; typedef enum{ TRANSFORMATIONS_HUMAN_NAME = 0, TRANSFORMATIONS_TRANSFORMATION_PTR, TRANSFORMATIONS_N_COLUMNS }TransformationsColumns; typedef enum{ AVAILABLE_TRANSFORMATIONS_HUMAN_NAME = 0, AVAILABLE_TRANSFORMATIONS_NAME, AVAILABLE_TRANSFORMATIONS_N_COLUMNS }AvailableTransformationsColumns; typedef struct TransformationsArgs{ GtkWidget *available_transformations; GtkWidget *transformation_list; GtkWidget *config_vbox; GtkWidget *vpaned; GtkWidget *configuration_label; GtkWidget *enabled; transformation::Transformation *transformation; boost::shared_ptr configuration; struct dynvSystem *params; struct dynvSystem *transformations_params; GlobalState *gs; }TransformationsArgs; static void configure_transformation(TransformationsArgs *args, transformation::Transformation *transformation); static void tranformations_update_row(GtkTreeModel *model, GtkTreeIter *iter1, transformation::Transformation *transformation, TransformationsArgs *args) { gtk_list_store_set(GTK_LIST_STORE(model), iter1, TRANSFORMATIONS_HUMAN_NAME, transformation->getReadableName().c_str(), TRANSFORMATIONS_TRANSFORMATION_PTR, transformation, -1); } static void available_tranformations_update_row(GtkTreeModel *model, GtkTreeIter *iter1, transformation::Factory::TypeInfo *type_info, TransformationsArgs *args) { gtk_list_store_set(GTK_LIST_STORE(model), iter1, AVAILABLE_TRANSFORMATIONS_HUMAN_NAME, type_info->human_name, AVAILABLE_TRANSFORMATIONS_NAME, type_info->name, -1); } static void available_transformation_row_activated(GtkTreeView *tree_view, GtkTreePath *path, GtkTreeViewColumn *column, TransformationsArgs *args) { GtkTreeModel* model; GtkTreeIter iter; model = gtk_tree_view_get_model(tree_view); gtk_tree_model_get_iter(model, &iter, path); gchar *name = 0; gtk_tree_model_get(model, &iter, AVAILABLE_TRANSFORMATIONS_NAME, &name, -1); boost::shared_ptr tran = transformation::Factory::create(name); if (tran){ auto chain = args->gs->getTransformationChain(); chain->add(tran); configure_transformation(args, tran.get()); model = gtk_tree_view_get_model(GTK_TREE_VIEW(args->transformation_list)); gtk_list_store_append(GTK_LIST_STORE(model), &iter); tranformations_update_row(model, &iter, tran.get(), args); } } static void add_transformation_cb(GtkWidget *widget, TransformationsArgs *args) { GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(args->available_transformations)); GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(args->available_transformations)); GtkTreeIter iter; if (gtk_tree_selection_count_selected_rows(selection) == 0){ return; } GList *list = gtk_tree_selection_get_selected_rows(selection, 0); GList *i = list; while (i) { gtk_tree_model_get_iter(model, &iter, (GtkTreePath*)i->data); gchar *name = 0; gtk_tree_model_get(model, &iter, AVAILABLE_TRANSFORMATIONS_NAME, &name, -1); boost::shared_ptr tran = transformation::Factory::create(name); if (tran){ auto chain = args->gs->getTransformationChain(); chain->add(tran); configure_transformation(args, tran.get()); model = gtk_tree_view_get_model(GTK_TREE_VIEW(args->transformation_list)); gtk_list_store_append(GTK_LIST_STORE(model), &iter); tranformations_update_row(model, &iter, tran.get(), args); } i = g_list_next(i); } g_list_foreach(list, (GFunc)gtk_tree_path_free, nullptr); g_list_free(list); } static void remove_transformation_cb(GtkWidget *widget, TransformationsArgs *args) { GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(args->transformation_list)); GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(args->transformation_list)); GtkTreeIter iter; if (gtk_tree_selection_count_selected_rows(selection) == 0){ return; } configure_transformation(args, nullptr); GList *list = gtk_tree_selection_get_selected_rows(selection, 0); GList *ref_list = nullptr; GList *i = list; while (i) { ref_list = g_list_prepend(ref_list, gtk_tree_row_reference_new(model, (GtkTreePath*) (i->data))); i = g_list_next(i); } auto chain = args->gs->getTransformationChain(); i = ref_list; GtkTreePath *path; while (i) { path = gtk_tree_row_reference_get_path((GtkTreeRowReference*)i->data); if (path) { gtk_tree_model_get_iter(model, &iter, path); gtk_tree_path_free(path); transformation::Transformation *transformation; gtk_tree_model_get(model, &iter, TRANSFORMATIONS_TRANSFORMATION_PTR, &transformation, -1); chain->remove(transformation); gtk_list_store_remove(GTK_LIST_STORE(model), &iter); } i = g_list_next(i); } g_list_foreach(ref_list, (GFunc)gtk_tree_row_reference_free, nullptr); g_list_free(ref_list); g_list_foreach(list, (GFunc)gtk_tree_path_free, nullptr); g_list_free(list); } static GtkWidget* transformations_list_new(bool selection_list) { GtkListStore *store; GtkCellRenderer *renderer; GtkTreeViewColumn *col; GtkWidget *view; view = gtk_tree_view_new(); gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), 1); if (selection_list){ store = gtk_list_store_new(AVAILABLE_TRANSFORMATIONS_N_COLUMNS, G_TYPE_STRING, G_TYPE_STRING); }else{ store = gtk_list_store_new(TRANSFORMATIONS_N_COLUMNS, G_TYPE_STRING, G_TYPE_POINTER); } col = gtk_tree_view_column_new(); gtk_tree_view_column_set_sizing(col,GTK_TREE_VIEW_COLUMN_AUTOSIZE); gtk_tree_view_column_set_resizable(col, 1); renderer = gtk_cell_renderer_text_new(); gtk_tree_view_column_pack_start(col, renderer, true); gtk_tree_view_append_column(GTK_TREE_VIEW(view), col); if (selection_list){ gtk_tree_view_column_set_title(col, _("Available filters")); gtk_tree_view_column_add_attribute(col, renderer, "text", AVAILABLE_TRANSFORMATIONS_HUMAN_NAME); }else{ gtk_tree_view_column_set_title(col, _("Active filters")); gtk_tree_view_column_add_attribute(col, renderer, "text", TRANSFORMATIONS_HUMAN_NAME); } gtk_tree_view_set_model(GTK_TREE_VIEW(view), GTK_TREE_MODEL(store)); g_object_unref(GTK_TREE_MODEL(store)); if (!selection_list){ GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(view)); gtk_tree_selection_set_mode(selection, GTK_SELECTION_MULTIPLE); gtk_tree_view_set_reorderable(GTK_TREE_VIEW(view), true); } return view; } static void apply_configuration(TransformationsArgs *args){ if (args->configuration && args->transformation){ auto handler_map = dynv_system_get_handler_map(args->gs->getSettings()); auto dv = dynv_system_create(handler_map); args->configuration->applyConfig(dv); args->transformation->deserialize(dv); dynv_handler_map_release(handler_map); dynv_system_release(dv); } } static void configure_transformation(TransformationsArgs *args, transformation::Transformation *transformation) { if (args->configuration){ gtk_container_remove(GTK_CONTAINER(args->config_vbox), args->configuration->getWidget()); apply_configuration(args); args->configuration = boost::shared_ptr(); } if (transformation){ gtk_label_set_text(GTK_LABEL(args->configuration_label), transformation->getReadableName().c_str()); args->configuration = transformation->getConfig(); args->transformation = transformation; gtk_box_pack_start(GTK_BOX(args->config_vbox), args->configuration->getWidget(), true, true, 0); }else{ gtk_label_set_text(GTK_LABEL(args->configuration_label), _("No filter selected")); } } static void transformation_chain_cursor_changed(GtkWidget *widget, TransformationsArgs *args) { GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(args->transformation_list)); GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(args->transformation_list)); GtkTreeIter iter; if (gtk_tree_selection_count_selected_rows(selection) == 0){ return; } configure_transformation(args, nullptr); GList *list = gtk_tree_selection_get_selected_rows(selection, 0); GList *i = list; if (i) { gtk_tree_model_get_iter(model, &iter, (GtkTreePath*)i->data); transformation::Transformation *transformation; gtk_tree_model_get(model, &iter, TRANSFORMATIONS_TRANSFORMATION_PTR, &transformation, -1); configure_transformation(args, transformation); } g_list_foreach(list, (GFunc)gtk_tree_path_free, nullptr); g_list_free(list); } static void transformation_chain_row_activated(GtkTreeView *tree_view, GtkTreePath *path, GtkTreeViewColumn *column, TransformationsArgs *args) { GtkTreeModel* model; GtkTreeIter iter; model = gtk_tree_view_get_model(tree_view); gtk_tree_model_get_iter(model, &iter, path); transformation::Transformation *transformation; gtk_tree_model_get(model, &iter, TRANSFORMATIONS_TRANSFORMATION_PTR, &transformation, -1); configure_transformation(args, transformation); } void dialog_transformations_show(GtkWindow* parent, GlobalState* gs) { TransformationsArgs *args = new TransformationsArgs; args->gs = gs; args->params = dynv_get_dynv(args->gs->getSettings(), "gpick"); args->transformations_params = dynv_get_dynv(args->gs->getSettings(), "gpick.transformations"); args->transformation = 0; GtkWidget *dialog = gtk_dialog_new_with_buttons(_("Display filters"), parent, GtkDialogFlags(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OK, GTK_RESPONSE_OK, nullptr); gtk_window_set_default_size(GTK_WINDOW(dialog), dynv_get_int32_wd(args->params, "transformations.window.width", -1), dynv_get_int32_wd(args->params, "transformations.window.height", -1)); gtk_dialog_set_alternative_button_order(GTK_DIALOG(dialog), GTK_RESPONSE_OK, GTK_RESPONSE_CANCEL, -1); GtkWidget* vbox = gtk_vbox_new(false, 5); GtkWidget *widget = args->enabled = gtk_check_button_new_with_mnemonic(_("_Enable display filters")); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget), dynv_get_bool_wd(args->transformations_params, "enabled", false)); gtk_box_pack_start(GTK_BOX(vbox), args->enabled, false, false, 0); args->vpaned = gtk_vpaned_new(); gtk_box_pack_start(GTK_BOX(vbox), args->vpaned, true, true, 0); GtkWidget *hbox = gtk_hbox_new(false, 5); GtkWidget *list = args->available_transformations = transformations_list_new(true); g_signal_connect(G_OBJECT(list), "row-activated", G_CALLBACK(available_transformation_row_activated), args); GtkWidget *scrolled = gtk_scrolled_window_new(0, 0); gtk_container_add(GTK_CONTAINER(scrolled), list); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_box_pack_start(GTK_BOX(hbox), scrolled, true, true, 0); GtkTreeModel *model = gtk_tree_view_get_model(GTK_TREE_VIEW(list)); vector types = transformation::Factory::getAllTypes(); for (size_t i = 0; i != types.size(); i++){ GtkTreeIter iter; gtk_list_store_append(GTK_LIST_STORE(model), &iter); available_tranformations_update_row(model, &iter, &types[i], args); } GtkWidget *vbox3 = gtk_vbox_new(5, true); GtkWidget *button = gtk_button_new_from_stock(GTK_STOCK_ADD); gtk_box_pack_start(GTK_BOX(vbox3), button, false, false, 0); g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(add_transformation_cb), args); button = gtk_button_new_from_stock(GTK_STOCK_REMOVE); gtk_box_pack_start(GTK_BOX(vbox3), button, false, false, 0); g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(remove_transformation_cb), args); gtk_box_pack_start(GTK_BOX(hbox), vbox3, false, false, 0); args->transformation_list = list = transformations_list_new(false); g_signal_connect(G_OBJECT(list), "row-activated", G_CALLBACK(transformation_chain_row_activated), args); g_signal_connect(G_OBJECT(list), "cursor-changed", G_CALLBACK(transformation_chain_cursor_changed), args); scrolled = gtk_scrolled_window_new(0, 0); gtk_container_add(GTK_CONTAINER(scrolled), list); gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_box_pack_start(GTK_BOX(hbox), scrolled, true, true, 0); gtk_paned_pack1(GTK_PANED(args->vpaned), hbox, false, false); GtkWidget *config_wrap_vbox = gtk_vbox_new(false, 5); args->configuration_label = gtk_label_new(_("No filter selected")); gtk_box_pack_start(GTK_BOX(config_wrap_vbox), gtk_widget_aligned_new(args->configuration_label, 0, 0.5, 0, 0), false, false, 5); args->config_vbox = gtk_vbox_new(false, 5); gtk_box_pack_start(GTK_BOX(config_wrap_vbox), args->config_vbox, true, true, 0); gtk_paned_pack2(GTK_PANED(args->vpaned), config_wrap_vbox, false, false); auto chain = args->gs->getTransformationChain(); model = gtk_tree_view_get_model(GTK_TREE_VIEW(list)); for (auto transformation: chain->getAll()){ GtkTreeIter iter; gtk_list_store_append(GTK_LIST_STORE(model), &iter); tranformations_update_row(model, &iter, transformation.get(), args); } gtk_paned_set_position(GTK_PANED(args->vpaned), dynv_get_int32_wd(args->params, "paned_position", -1)); gtk_widget_show_all(vbox); gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), vbox, true, true, 5); if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK){ apply_configuration(args); GtkListStore *store = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(list))); GtkTreeIter iter; bool valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter); bool enabled = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(args->enabled)); dynv_set_bool(args->transformations_params, "enabled", enabled); chain->setEnabled(enabled); unsigned int count = gtk_tree_model_iter_n_children(GTK_TREE_MODEL(store), nullptr); if (count > 0){ struct dynvSystem** config_array = new struct dynvSystem*[count]; unsigned int i = 0; auto handler_map = dynv_system_get_handler_map(args->gs->getSettings()); while (valid){ transformation::Transformation* transformation; gtk_tree_model_get(GTK_TREE_MODEL(store), &iter, TRANSFORMATIONS_TRANSFORMATION_PTR, &transformation, -1); auto dv = dynv_system_create(handler_map); transformation->serialize(dv); config_array[i] = dv; valid = gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter); ++i; } dynv_handler_map_release(handler_map); dynv_set_dynv_array(args->transformations_params, "items", (const dynvSystem**)config_array, count); for (i = 0; i != count; i++){ dynv_system_release(config_array[i]); } delete [] config_array; }else{ dynv_set_dynv_array(args->transformations_params, "items", 0, 0); } } chain->clear(); chain->setEnabled(dynv_get_bool_wd(gs->getSettings(), "gpick.transformations.enabled", false)); struct dynvSystem** config_array; uint32_t config_size; if ((config_array = (struct dynvSystem**)dynv_get_dynv_array_wd(gs->getSettings(), "gpick.transformations.items", 0, 0, &config_size))){ for (uint32_t i = 0; i != config_size; i++){ const char *name = dynv_get_string_wd(config_array[i], "name", 0); if (name){ boost::shared_ptr tran = transformation::Factory::create(name); if (tran){ tran->deserialize(config_array[i]); chain->add(tran); } } dynv_system_release(config_array[i]); } delete [] config_array; } gint width, height; gtk_window_get_size(GTK_WINDOW(dialog), &width, &height); dynv_set_int32(args->params, "transformations.window.width", width); dynv_set_int32(args->params, "transformations.window.height", height); dynv_set_int32(args->params, "paned_position", gtk_paned_get_position(GTK_PANED(args->vpaned))); gtk_widget_destroy(dialog); dynv_system_release(args->transformations_params); dynv_system_release(args->params); delete args; } gpick-gpick-0.2.6rc1/source/uiTransformations.h000066400000000000000000000033611315430016700215200ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef GPICK_UI_TRANSFORMATIONS_H_ #define GPICK_UI_TRANSFORMATIONS_H_ class GlobalState; #include void dialog_transformations_show(GtkWindow* parent, GlobalState* gs); #endif /* GPICK_UI_TRANSFORMATIONS_H_ */ gpick-gpick-0.2.6rc1/source/uiUtilities.cpp000066400000000000000000000052451315430016700206400ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "uiUtilities.h" GtkWidget* gtk_menu_item_new_with_image(const gchar* label, GtkWidget *image) { GtkWidget* menu_item = gtk_image_menu_item_new_with_mnemonic(label); gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_item), image); return menu_item; } GtkWidget* gtk_label_aligned_new(const gchar* text, gfloat xalign, gfloat yalign, gfloat xscale, gfloat yscale) { GtkWidget* align = gtk_alignment_new(xalign, yalign, xscale, yscale); GtkWidget* label = gtk_label_new(text); gtk_container_add(GTK_CONTAINER(align), label); return align; } GtkWidget* gtk_label_mnemonic_aligned_new(const gchar* text, gfloat xalign, gfloat yalign, gfloat xscale, gfloat yscale) { GtkWidget* align = gtk_alignment_new(xalign, yalign, xscale, yscale); GtkWidget* label = gtk_label_new(""); gtk_label_set_text_with_mnemonic(GTK_LABEL(label), text); gtk_container_add(GTK_CONTAINER(align), label); return align; } GtkWidget* gtk_widget_aligned_new(GtkWidget* widget, gfloat xalign, gfloat yalign, gfloat xscale, gfloat yscale){ GtkWidget* align = gtk_alignment_new(xalign, yalign, xscale, yscale); gtk_container_add(GTK_CONTAINER(align), widget); return align; } gpick-gpick-0.2.6rc1/source/uiUtilities.h000066400000000000000000000040571315430016700203050ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef UIUTILITIES_H_ #define UIUTILITIES_H_ #include GtkWidget* gtk_menu_item_new_with_image(const gchar* label, GtkWidget *image); GtkWidget* gtk_label_aligned_new(const gchar* text, gfloat xalign = 0, gfloat yalign = 0, gfloat xscale = 0, gfloat yscale = 0); GtkWidget* gtk_label_mnemonic_aligned_new(const gchar* text, gfloat xalign, gfloat yalign, gfloat xscale, gfloat yscale); GtkWidget* gtk_widget_aligned_new(GtkWidget* widget, gfloat xalign, gfloat yalign, gfloat xscale, gfloat yscale); #endif /* UIUTILITIES_H_ */ gpick-gpick-0.2.6rc1/source/version/000077500000000000000000000000001315430016700173025ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/source/version/SConscript000066400000000000000000000005751315430016700213230ustar00rootroot00000000000000#!/usr/bin/env python import os import sys Import('*') local_env = env.Clone() local_env.Append(CPPDEFINES = {'BUILD_DATE': env['GPICK_BUILD_DATE'], 'BUILD_REVISION': env['GPICK_BUILD_REVISION'], 'BUILD_PLATFORM': sys.platform, 'BUILD_VERSION': env['GPICK_BUILD_VERSION'], }) sources = local_env.Glob('*.cpp') objects = local_env.StaticObject([sources]) Return('objects') gpick-gpick-0.2.6rc1/source/version/Version.cpp000066400000000000000000000034541315430016700214410ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Version.h" #define TO_STRING(x) #x #define T_(x) TO_STRING(x) const char* gpick_build_version = T_(BUILD_VERSION); const char* gpick_build_revision = T_(BUILD_REVISION); const char* gpick_build_date = T_(BUILD_DATE); const char* gpick_build_platform = T_(BUILD_PLATFORM); gpick-gpick-0.2.6rc1/source/version/Version.h000066400000000000000000000033241315430016700211020ustar00rootroot00000000000000/* * Copyright (c) 2009-2016, Albertas Vyšniauskas * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the software author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ extern const char* gpick_build_version; extern const char* gpick_build_revision; extern const char* gpick_build_date; extern const char* gpick_build_time; extern const char* gpick_build_platform; gpick-gpick-0.2.6rc1/source/winres/000077500000000000000000000000001315430016700171245ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/source/winres/SConscript000066400000000000000000000014751315430016700211450ustar00rootroot00000000000000#!/usr/bin/env python import os import sys import re Import('*') local_env = env.Clone() local_env.Append(RESOURCE_TEMPLATE_VARS = { 'VERSION': env['GPICK_BUILD_VERSION'], 'VERSION_COMMA': env['GPICK_BUILD_VERSION'].replace('.', ','), 'REVISION': env['GPICK_BUILD_REVISION'], 'BUILD_DATE': env['GPICK_BUILD_DATE'], }) sources = local_env.Glob('*.rct') resources = local_env.AlwaysBuild(local_env.ResourceTemplate(sources)) objects = local_env.RES(resources) Command("gpick-icon.ico", File("gpick-icon.ico").srcnode(), Copy("$TARGET", "${SOURCE}")) if not (env['TOOLCHAIN'] == 'msvc'): Command("gpick.exe.manifest", File("gpick.exe.manifest").srcnode(), Copy("$TARGET", "${SOURCE}")) Depends(resources, 'gpick-icon.ico') if not (env['TOOLCHAIN'] == 'msvc'): Depends(resources, 'gpick.exe.manifest') Return('objects') gpick-gpick-0.2.6rc1/source/winres/gpick-icon.ico000066400000000000000000003330561315430016700216550ustar00rootroot00000000000000 (f@@ (B00 %J  ^p h 0n( 6[wL!o :" 2 tXڗeJ5fڮ{r{4:]}um.Qwop- 60u9yqEKBc{sQ{!n}u?U.wd,0ٿy/zx>lQ)%4is87Ѷ wrd:Qv % |k8Dl/} nJ,n6܊S hB r^4ieܲlJQBmFÚoQ2(q+/$ va CxC<2i7 OF{ni^~=67 t';zm{n{nzmrf]SCŁ>7p609ggg4 #4DTdu{{{{: #4DTdutŏB #4DTdumxxx|ʟJ #4DTdug(slllvήS #4DTdu`&]]]pѼ^ #4DTduZ$ ~QQQli #4DTduT" jBBBiu #4DTduN  lZ444gق #4DTdvHRK(((e۾ #4DTdvC =fָ... #4DTdvR 1gѲJJJ #4DTdw!!!###""" C' jˬddd$ #4DTr###&&&%%%###"""  oĤ* #4S&&&***(((&&&%%%###""" v񼓓0 3(((---+++***(((&&&%%%###"""4}§9 +++000///---+++***((('''%%%### ~ ...333222000///---+++***((('''$$$רa"///777555333222000///---+++***(((%|NNNH,.222:::888777555333222000///---+++***tttnA@...999;;;:::888777555333222000///---,,,4rS+++666888999;;;:::888777555444222000///...$$$` a(((333444666777999;;;:::888777555444222111...,,,***""" $$$///111333444666777999;;;:::888777555444222000...,,,***(((&&&$$$""",,,...///111333444666777999::::::999888666444222000...,,,***(((&&&$$$"""M )))+++,,,...///111222444666777999:::::::::888666444222000...,,,***(((&&&$$$""" &&&((()))+++,,,...///111222444555777666888::::::888666444222000...,,,***(((%%%###"""###$$$&&&''')))+++,,,...///111222444333444666888::::::888666444222000...+++***(((%%%###!!! !!!###$$$&&&''')))+++,,,...///111222000222444666888::::::888666444222000...+++)))'''%%%###!!!%!!!###$$$&&&''')))***,,,......---...000222444666888::::::888666444222///...+++)))'''%%%###!!!!!!"""$$$&&&''')))***,,,+++***,,,...000222444666888::::::888666444222///---+++)))'''%%%###!!!!!!"""$$$&&&&&&&&&(((EEE,,,...000222444666888::::::888555333111///---+++)))'''%%%###!!!p   &&&444,,,...000222444666888;;;999888555333111///---+++)))'''%%%###!!!Fr  ]G***,,,...000222555666888;;;999777555333111///---+++)))'''%%%###!!!  u o*mmm***,,,///111222555777999;;;999777555333111///---+++)))'''%%%###!!!w<IgggEEE+++---///111333555777999;;;999777555333111///---+++)))'''%%%###!!!$ ###...+++---///111333555777999;;;999777555333111///---+++)))'''%%%###!!!)))+++---///111333555777999;;;999777555333111///---+++)))'''%%%"""  /UUUvvv)))+++---///111333555777999;;;999777555333111///---+++((('''%%%"""cqqq)))+++---///111333555777999;;;999777555333111///---+++(((&&&$$$""" &222lll)))+++---///111333555777999;;;999777555333111///,,,***(((&&&$$$iii)))+++---///111333555777999;;;999777555222111///,,,***(((&&&eee)))+++---///111333555777999;;;999777555222000...,,,***((("7$$$ddd)))+++---///111333555777999;;;888666555222000...,,,***y...444+++---///111333555888999;;;888666444222000...,,,888[[[+++---///222444555888::::::888666444222000...@@@555...///222444666888::::::888666444222---m###[[[...000222444666888::::::888666444 rrrbbb222222444666888::::::888&&&TBBBBTTT666666888:::)))SSS888s777yyy~~~FFFW& gewW ???????C!?p A ???(@ !E0 3&hF^|DI#" zrX$ )$t:1.4;xD($ f|2aj"4.;X-%!ʫ$OC7AN J$ ׯ:&B7f `'  b z% Z2e1,QIK$ (F-zm{nrfPGe0,2 "bWzm{nrfbXRJq60 Er81pdzm{nrfbXRJr71 3f[pdzm{nrfbXRJt82 "ؾ\Rvlpdzm{nrfbXRJv:4  F?ڀwpdzm{nrfbXRJx;4 !׷܇~pdzm{nrfbXRJz;5 *մލpdzm{nrfbXRJ|<6 $ (Үᖎpdzm{nrfbXRJ~=7 ( 'Χ㞗pdzm{nrfbXRJ>7 - %ʟ槠pdzm{nrfbXRJ>8 (!%ŗ诪qezm{nrfbXRJ>7 #! ٭ɾe^jwlZznXcYdE?zi2-? ǏJJJ4T ǁfff#4TW sss|||)4TS aaa04TM .QQQĤ84TT  DDDʷ@4T $$$"""666Kh ***(((%%%"""1+++Ѣ7= 000///+++(((%%%ZZZ>M666555222///+++j 666;;;888555222///$$$i ///444777;;;888555333...((( u2 )))...111444777:::999666222...***&&&!!!. """'''+++...111444555888:::666222...***%%%!!!3+!!!$$$'''***...///000444888:::666222...)))%%%!!! B(!!!$$$'''%%%)))111000444888:::555222---)))%%%!!! uuu,,,000555888999555111---)))%%%!!!L Ɋkkk,,,111555999999555111---)))%%%!!!yE\\\EEE---111555999999555111---)))%%%!!!<<<---111555999999555111---((($$$ ybbb:::---111555999999555111,,,((({ ͘888---111555999888555000,,,!!! 䤤]]]---222555:::888444000P"888222666:::888444 "dddbbb999:::mooovvv' ????~A?(0` &=:'O0D$,$ Gi f>=6Bz}q-95Qj-'$\ǮF[P*a!M5/ QJ+o]4ɇ'i1*ޮV< C5* r*% w:4JBM%"1"y"N&"zm{ng\G@G!#_/h\zm{ng\RJO&"!e 9C=mazm{ng\RJP'"! lP'#אpdzm{ng\RJR'# s.ŝ辺sgzm{ng\RJT(% z1̪vkzm{ng\RJU)% 1Ȣzozm{ng\RJW*% 1Ú~tzm{ng\RJX*&"1yzm{ng\RJW*&'άJ)TjѹT)Tci%uuu_)T] o %fffk)TW i^|WWWx)T""" lGGG@@@y***&&&!!! \<<<Ɉ:\333///***IM---|;;;777333/// |222666;;;777444...### qO***...222666999999333...(((### M!!!%%%)))...111333888888333...(((### ( !!!!!!111222333888888333---((("""  D珏...333888888222---((("""c0 www...333999888222---'''""" ]]]]]]...444999888222---''' III///444999777222,,,"""{ѯ]]]///444:::777222 J!!!ᓓAAA444:::777 DDD```I^&&&... !??|??????( @  j|_a'.+Me?/,FL<@|[S){C;_-g laB3'i%ZA:F?e0,A!p60zmrfNG@M$!j_zmrfNGB .7{zmrfNGD!E##`⚓zmrfNGH#N$$\壜zmrfNGK$ V(%Y㵰zmnbB;)6ڗ[C0zzzߠ [*lll[  %^^^殿 %%%((( !PPP///555///}###444:::666... Fp'''...333888666...%%%x===000888555---%%% A\ {LLL{{{111999555---%%%ibbb111999555---)(((ż```111999444'''?777ǡZZZ;;; FMMMQQQ+++"????q!?(  ++pt?a;;'.jǩeyjR^7 AWN܍D=a,(:TNxKCb/+<R)|JAb/+Ah..pI#* ._ zzz"""---,,,:::+++NNN888---___nnn:::'''WWWzzz,,,PNG  IHDR\rf IDATxwx?N[mL1TSM6 @^ސ1Pބ6 1%`cܛdY]wҝn?vt|E>3fwF~wΈ1EQWo@Qġ(I$1jĨ(J(I$1jĨ(J(I$1jĨ(J(I$1ENH ``  uRscLMn5*.$;"2 8މ#ƘbHp6p=0)9\.18:iG/K?Oc{DZA @I*D0 v \.D$1x^^/:|>_7⒱.$ "r)p7PGVVyyydff!CaРAihhSVVw}ڵk2*++[>.1ƬsV;=?ӝ8ENNyyy{sGp!KU֭[x뭷(--eΝرF [(q7v呗nj38c)** ]ڌ |駼k^uQYYzݭo@ @镈 `'.==" 1cz*YYY-.q@ 6rJV\ɚ5kGD(--eLc7Jm^6X| 9s&gq~ס׳b VZիz: CC}}=˖->8^ҫ[dffRXXȸq1bD%K[om۶oQ˗ƘbN D$ pG>} 9sfpH/o#mܸ7x? Y|9 %.15E) L?STTĸqOʐ!C"@ '|oի;%pwB]]˗/w ˁ1;bW2hDd$0 %%>}0m4nF233C f-[ƣ>کj~G[uVr0ƜjJEDbFqq1\p{n3q'q.]j_o!rJ@qƘ7cXLmHDX`tML:~@}}=?/83fОP[[˷~ʓƘscUN+=^zz:Çg- {>c{1ʂ"'~7-"~c ddd8Hfd/ȑ#뮻5jTs#<;Vy )tFNw 8 x6"cT93ᄏ߾};rKw,iD8]1[KXG}`=9DҥKi==S6N1 SPz"r 0Ç`?pB^|N;d @B! da5cRxmt{DdO>z 6y~[SS XjU4Ù#bh2Ά[-@ @Q#".q@nn.^{-'Ony^ߖsmy.3g<vM)jJwf(&s9r)N'~_QRR5vAZ@h| (9>Caܹ-i͛7smQ^^;t9AD2E|ĿvZ~_SSSS>AG bbRtWFdee1g2WXw[FZ@^s?9SCokrw㊗#5:B^$hP tGn^믿٘|Ko&4~ZǼD#t+ZG`M934h]+++۩NÙA{̀?(Jc͌̚5 /~c6Й?@TP "2 wawͺu뺅 tCCMMpSZ`Y6jJwvarg?C=_mV-04b\PP"R ֌ӧڴ>_|%Kt;3,=ӂm5ptNN~xD5kְhѢn)4|>_hcxn$YAqq1p@hllgq1-EDƋHZ8=NnyٱcGUz[ 466R[[di=R<ʷ-VrY,"7~Gn9 HCmy?[|GABVMCk1gѩJ3Dd.{cpvX\e˞e_~5{_Dشi>("WJM w cmcp "2&񓚚:\8*l334kv}`ʔ)꿈=\߉ v }l)lY5!\ӃO/GCCCuqvR,Cxts999;ֹ}ш+83h-P[[:}@D!G?XBhhh`vP-"a4Ƭ s41dggo)X/߽ ' &*h*pKMMv磾>Bo?" `(X[y'ر?OC9ݻ***BMrA8#L$jIk} õdddx^< f.{گ墨!;;F/廻^/uuuNGs\dee Xxtcx18,ĊƓsRSSc.ṕhEc̿cg j Ƙzw٬&ѧzXFmT`Z1fo{h' ǚwXs?%W,k`Uc%p5iԄVTuARPZ!"X&?X&0`Vmuܨ#xw2te_1,&(a"`@zz:aWk@: U =n+Nc#V(kw}z_РAaWm;m5)3Lgp1)b&"x 33A9cΊ?& w9x]ap1 b."k8L`С^s{wG@>M7{+0.ƘQ͛[=k#4_3wzzl߾=T07t  C ;DPAB ]e/zM*jJX&0u ֪c>ˆ:U^?7kTB @4"2ܰe\sB;U͝h *jkkiƘQ@ @"r""yyy1";Iggu%QYYi];1ձ,Dt9xgȑ1hU&ty຅>eVcMޒ(BDN5 `PPPPȑ##6Z~ŅOx|->&t9x{AO ܉m5**OBu۷o& gz7Ǣtx#/aZO>LN'* 8q۶m<[1fkǢx(k.aX&P\\ѣc&Uu9WeNcbU6= &a๙3g?&e@%Ν;lKs15ۨ(a<dGz_={v߇z6mZ&7@@II ֭kSшkOY2VivTXro~3/###[D̹;&;K,lرcG& c  0+ӫPP!"vT-p;٭:g?Uiii"bDL4i>N[vmLo!%%%10~oAi5%4-vU X`nA㏀۷~Nۋs>9YqĴz j "2k~;_~E)))P㧵}>֒`6nt\=';;;pnJ "#6cc=vYf\.i)~eRSS3,X0oMd%ضm6mm "ܙ_DqxeG~xgr)z[_DLuuҧ~z#`yx2-[^Vk9k:l PxLrTKᇊ)Sܵa/m߾V xH8p  Z` `Æ cƢz ZHRD`ܙR{hO%%%/5N?cp}>۶mcQBcD䠨\/C X:JY.++=a„m͋~i1El۶NBoAmd%?bB|p{YOcǎ}v‰?Ě'k,(--J_@FFFpBl>0$"c/4M}۠Aȑ#$~W_ݳ~=9/ n;Cj#T5$AD?ocǎMyw/#ӧϠHoll|g~2cƌ;;߭~yiÕ{N\H- kJ5^df덾OO:餼 /$~_?ٳg ."^=Rh р0BD$xk XOYf<7'' 6u]?'.ZR k;RǠv/$\zbpU+{WeffDn;BşxP;1Ƙ{y5JJJM:pnmD"Dd& ~7gH⯭]vb^9Xi'-0=$kcKfffj@;w:Im9f7סKqXbGjΙ3ԔH⯬\zꫯj}a:cu\""p6 C1:_½mDd2>M_u=;wmΝN<8? kG‰nlSZZ԰`zz 8sۻ@GDcїkG} =ÓO?½֭/?뉏ۂU_ہ|&HOO3kp}AF #"?Ětk+k… p '#u=9~b-;ہ%՝ρ_nM5Ic6vmPD|4mM9L$~[p'D2ഹ+?B9{!??T'&@BDnI#yyy9mS /2?&'DCƘCee3ԧZ!ﰦȂC_aÆ}WDL |1o޼UOaI ,TDkx&7`9;\Җ~}8(N1bތ1Z'Hm%QB ֛r`>`پ~....:Ϳ/n#~LkN3Ƽݒi<˗ĩ;@7EDRXgFX}g,Z¾x;w/y2'À|Ƙע\40F{)*}IǚsU =csyKrss #>%KT?V9Ƙg\4m""jy>ɨt3i!J:6vi<%ٹ_^^[rZ'zc̢( Ѝ\vaѷ墋.ww^I%%%N2/d2*@7AD ׀R,o꫇z}_D̦M^0a O)%1z(1C  "$;jV[nyG|_D̚5k4i"Ew,Ŀ_g:1GdX`Dd Mn;se]vVJJ+K=_~#v؋WhGr1薌 ޡiquXC}>YfE|_D|W{a.t1(=H"2iyۇ+\99C' b 5ϕ/5FwZntsr@kn)s{꽕*wCCeզ|unn{~56֧5ݵ5[>Ę#ۍ1?c)QF ~ ⽘xuٜt8N8n4 HȿzâgKٴ5&%% ˍ+Mo0i:硱ъ,˟$s1'q*2%Fh Έ;ۏ ^۝3a#.Oc*BwGD@ ;  ~伳'0_Qߟ*r?Icc1ũȔ'D0p0x L f?& (2?:W\_S:IS@c4OMzz&_|{+(-xxR+ͬZ4U9xkk*{InN_ (=5!"`SF9{JaA̙€95\S[ªeOkv\ eǧԔxD e\c:cNoq̙BqhioSW޺2V-[HC}[LcLC)5(#"?Z <AS'Z"r3Wk _<԰} Ƙ8 n""7}&]AAġ>")a__oxl֓_şd"r-?r >Cyg +ں=Rw{vƘ8ҍP""2kD\=R‘pƌHXWTyK= /*F ]= ʉǍ/㱧SS+ N'IYDPl =1GE<x]/k&ϱ_bJR DBXfܾ1d:s"2,_as%) Bâgv}C_e Ԗ8I~%.(!:±l1 y??Jůt5p<((lW4ؓ[(H?D' s*@zz>j)>p U$D Ap\/mu1E@ I? <+-(~]QcPS' _W+B 5?p>].7xyR\}%-  'I)J;fsof"wܼ~EDnw\W+7 ZZ^3񧤤%V˚%Wvf,@N#~o/4hu1Ej!H> 'wHg/ ɯWv5qr&\v][ۿ 4gs?<6\]חXx$%j4gsPP8:aⷶ~"tOuO%ڨ4@4 JkjB| 5N'v]J,Pk}Ƒ%{˜AxTmdղE}uNoa[b(?1⯪XϷw~8SP5&t3%|)Ze'JAAMe%߰vA?64'J2ālxMK?\i -JRH0+|]/v|L90F JQ8 H4e$.2<*YΈkken$ 8Y|(Iz'?c,~-Tmv+u5۩DU)_`s3(HzN2ufQQҒ(+YFyJ*IvwcjE jpÊdlۿ`gWڹ6X |<{BR0t eÿY|Tmj/;`eЗxJRo."fzbRR3X#[2 ~/BNHzbPP4N݀=ƘmqME)=oLcKxeMQB2Cc>IM)JIg7c̮ݕğ4B p1vW^I5D$ ?؎1ޒ$dFp읨QDT5qIc̹3EI V5 ܻ`N"gnJQEL10s\3kܙ$1w8R`)0z"2&ҏ7 "'G00>^O`- ߄ܠ$^ ("XS{!8Xg`2=1xˊ7p0g^ZO' 0+X HnI=*JB5zO j(p>y%c1aE%w|R pY:q%I5) /}y9}੭5} ;No܅?~Yy'vƃ5?*J " >ӯ \=VTӼ3G;\fOV^K4~k= ZZqgE;DX`*SO M]L]Hσ:) E'Dd p,OC _ tnf}?7 *JWmk~L[k04d9N} $(o"28 ?hwi!'X0? '+c#E=GWxʇzC ?{^vsCQz=-.àp3s hzX]t / ű̓ēmHN> RAў+]jӡ`ssD$3R i_L;38I)(J`?`h4lf. T6Tzl=fb=͙jM yaQNrG+)J'@SF JI-t¾ٰ_Ob+E#=Ddpc"=1'`0.1TϋU%^HkU?9fUj;!%p+"Cb9E=&L=*(i0y緅 D`G&;=Rxӳ F-βM%DO hgLQI3&0@@<`w B~x3(q0gqL&dh($=RDzb* 3 OPܐtǪNn_t('@E}oXmL:XzEjߊV D2m4 yS < 27.Q˙ęhkGhu?#N^4S Q5ƒCL &jޏcq`)*M0_(k.٘$L\6`gL3(1"6LW9*Z?]70} lz5Ƙpg)J@z_ X_juA01(Y|Ccȱul[cqȲĄY0Ƭ֋5Ut ߑ7_Hp\h|Y%8>7eIQJl8A;@6Gww6|o\e˝cމC%ht"{MѶ l/~{.%P1,O%x~/kpFO!%PU %V(_a?6lu~%^ pqmN5{+^e" v~@:au*n oi*J{\B,ї%Ƙޞ$1EQZӓ((J(I$1jĨ(J(I$1jĨ(J(I$1jĨ(J(I$1jĨ(J(I$1j?<>DNIENDB`gpick-gpick-0.2.6rc1/source/winres/gpick.exe.manifest000066400000000000000000000011501315430016700225260ustar00rootroot00000000000000 gpick-gpick-0.2.6rc1/source/winres/resources.rct000066400000000000000000000012571315430016700216550ustar00rootroot000000000000001 ICON "gpick-icon.ico" 1 VERSIONINFO FILEVERSION %VERSION_COMMA% PRODUCTVERSION %VERSION_COMMA% BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904E4" BEGIN VALUE "CompanyName", "Gpick developers" VALUE "FileDescription", "Gpick - Advanced color picker" VALUE "FileVersion", "%VERSION%" VALUE "InternalName", "gpick" VALUE "LegalCopyright", "New BSD License" VALUE "OriginalFilename", "gpick.exe" VALUE "ProductName", "Gpick" VALUE "ProductVersion", "%VERSION%" VALUE "Comments", "Revision %REVISION%, built at %BUILD_DATE%" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1252 END END gpick-gpick-0.2.6rc1/test/000077500000000000000000000000001315430016700152745ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/test/config01.xml000066400000000000000000000002101315430016700174150ustar00rootroot00000000000000
  • a
  • b
  • c
  • gpick-gpick-0.2.6rc1/test/textImport01.txt000066400000000000000000000000171315430016700203530ustar00rootroot00000000000000color: #aabbcc gpick-gpick-0.2.6rc1/test/textImport02.txt000066400000000000000000000000141315430016700203510ustar00rootroot00000000000000color: #abc gpick-gpick-0.2.6rc1/test/textImport03.txt000066400000000000000000000000321315430016700203520ustar00rootroot00000000000000color: rgb(170, 187, 204) gpick-gpick-0.2.6rc1/test/textImport04.txt000066400000000000000000000000401315430016700203520ustar00rootroot00000000000000color: rgba(170, 187, 204, 0.5) gpick-gpick-0.2.6rc1/test/textImport05.txt000066400000000000000000000000251315430016700203560ustar00rootroot00000000000000color: 170, 187, 204 gpick-gpick-0.2.6rc1/test/textImport06.txt000066400000000000000000000000371315430016700203620ustar00rootroot00000000000000color: 0.666667, 0.733333, 0.8 gpick-gpick-0.2.6rc1/test/textImport07.txt000066400000000000000000000000401315430016700203550ustar00rootroot00000000000000//color: #ccbbaa color: #aabbcc gpick-gpick-0.2.6rc1/test/textImport08.txt000066400000000000000000000000431315430016700203610ustar00rootroot00000000000000/*color: #ccbbaa */ color: #aabbcc gpick-gpick-0.2.6rc1/test/textImport09.txt000066400000000000000000000000371315430016700203650ustar00rootroot00000000000000#color: #ccbbaa color: #aabbcc gpick-gpick-0.2.6rc1/tools/000077500000000000000000000000001315430016700154555ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/tools/__init__.py000066400000000000000000000000001315430016700175540ustar00rootroot00000000000000gpick-gpick-0.2.6rc1/tools/crossmingw.py000066400000000000000000000113111315430016700202170ustar00rootroot00000000000000 import os import os.path import string import SCons.Action import SCons.Builder import SCons.Defaults import SCons.Tool import SCons.Util # This is what we search for to find mingw: prefixes = SCons.Util.Split(""" mingw32- i386-mingw32msvc- i486-mingw32msvc- i586-mingw32msvc- i686-mingw32msvc- i686-w64-mingw32- """) def find(env): for prefix in prefixes: # First search in the SCons path and then the OS path: if env.WhereIs(prefix + 'gcc') or SCons.Util.WhereIs(prefix + 'gcc'): return prefix return '' def shlib_generator(target, source, env, for_signature): cmd = SCons.Util.CLVar(['$SHLINK', '$SHLINKFLAGS']) dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX') if dll: cmd.extend(['-o', dll]) cmd.extend(['$SOURCES', '$_LIBDIRFLAGS', '$_LIBFLAGS']) implib = env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX') if implib: cmd.append('-Wl,--out-implib,'+implib.get_string(for_signature)) def_target = env.FindIxes(target, 'WIN32DEFPREFIX', 'WIN32DEFSUFFIX') if def_target: cmd.append('-Wl,--output-def,'+def_target.get_string(for_signature)) return [cmd] def shlib_emitter(target, source, env): dll = env.FindIxes(target, 'SHLIBPREFIX', 'SHLIBSUFFIX') no_import_lib = env.get('no_import_lib', 0) if not dll: raise SCons.Errors.UserError, "A shared library should have exactly one target with the suffix: %s" % env.subst("$SHLIBSUFFIX") if not no_import_lib and \ not env.FindIxes(target, 'LIBPREFIX', 'LIBSUFFIX'): # Append an import library to the list of targets. target.append(env.ReplaceIxes(dll, 'SHLIBPREFIX', 'SHLIBSUFFIX', 'LIBPREFIX', 'LIBSUFFIX')) # Append a def file target if there isn't already a def file target # or a def file source. There is no option to disable def file # target emitting, because I can't figure out why someone would ever # want to turn it off. def_source = env.FindIxes(source, 'WIN32DEFPREFIX', 'WIN32DEFSUFFIX') def_target = env.FindIxes(target, 'WIN32DEFPREFIX', 'WIN32DEFSUFFIX') if not def_source and not def_target: target.append(env.ReplaceIxes(dll, 'SHLIBPREFIX', 'SHLIBSUFFIX', 'WIN32DEFPREFIX', 'WIN32DEFSUFFIX')) return (target, source) shlib_action = SCons.Action.Action(shlib_generator, generator=1) res_action = SCons.Action.Action('$RCCOM', '$RCCOMSTR') res_builder = SCons.Builder.Builder(action=res_action, suffix='.o', source_scanner=SCons.Tool.SourceFileScanner) SCons.Tool.SourceFileScanner.add_scanner('.rc', SCons.Defaults.CScan) def generate(env): mingw_prefix = find(env) if mingw_prefix: dir = os.path.dirname(env.WhereIs(mingw_prefix + 'gcc') or SCons.Util.WhereIs(mingw_prefix + 'gcc')) # The mingw bin directory must be added to the path: path = env['ENV'].get('PATH', []) if not path: path = [] if SCons.Util.is_String(path): path = path.split(os.pathsep) env['ENV']['PATH'] = os.pathsep.join([dir] + path) # Most of mingw is the same as gcc and friends... gnu_tools = ['gcc', 'g++', 'gnulink', 'ar', 'gas'] for tool in gnu_tools: SCons.Tool.Tool(tool)(env) #... but a few things differ: env['CC'] = mingw_prefix + 'gcc' env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS') env['CXX'] = mingw_prefix + 'g++' env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS') env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared') env['SHLINKCOM'] = shlib_action env.Append(SHLIBEMITTER = [shlib_emitter]) # This line isn't required and breaks C++ linking #env['LINK'] = mingw_prefix + 'g++' env['AS'] = mingw_prefix + 'as' env['AR'] = mingw_prefix + 'ar' env['RANLIB'] = mingw_prefix + 'ranlib' env['WIN32DEFPREFIX'] = '' env['WIN32DEFSUFFIX'] = '.def' env['SHOBJSUFFIX'] = '.o' env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1 env['RC'] = mingw_prefix + 'windres' env['RCFLAGS'] = SCons.Util.CLVar('') env['RCINCFLAGS'] = '$( ${_concat(RCINCPREFIX, CPPPATH, RCINCSUFFIX, __env__, RDirs, TARGET)} $)' env['RCINCPREFIX'] = '--include-dir ' env['RCINCSUFFIX'] = '' env['RCCOM'] = '$RC $RCINCFLAGS $RCINCPREFIX $SOURCE.dir $RCFLAGS -i $SOURCE -o $TARGET' env['BUILDERS']['RES'] = res_builder # Some setting from the platform also have to be overridden: env['OBJPREFIX'] = '' env['OBJSUFFIX'] = '.o' env['LIBPREFIX'] = 'lib' env['LIBSUFFIX'] = '.a' env['SHOBJPREFIX'] = '$OBJPREFIX' env['SHOBJSUFFIX'] = '$OBJSUFFIX' env['PROGPREFIX'] = '' env['PROGSUFFIX'] = '.exe' env['LIBPREFIX'] = '' env['LIBSUFFIX'] = '.lib' env['SHLIBPREFIX'] = '' env['SHLIBSUFFIX'] = '.dll' env['LIBPREFIXES'] = [ '$LIBPREFIX' ] env['LIBSUFFIXES'] = [ '$LIBSUFFIX' ] def exists(env): return find(env) gpick-gpick-0.2.6rc1/tools/flex.py000066400000000000000000000010261315430016700167640ustar00rootroot00000000000000from SCons.Script import * def addFlexBuilder(env): FlexAction = SCons.Action.Action("$FLEXCOM", "$FLEXCOMSTR") env["FLEX"] = env.Detect("flex") env["FLEXCOM"] = "flex --header-file=${TARGET.base}.h -o $TARGET $SOURCE" def headerEmitter(target, source, env): bs = SCons.Util.splitext(str(source[0].name))[0] target.append(bs + '.h') return (target, source) builder = Builder(action = FlexAction, suffix = '.cpp', src_suffix = '.l', emitter = headerEmitter) env.Append(BUILDERS = {'Flex': builder}) gpick-gpick-0.2.6rc1/tools/gettext.py000066400000000000000000000027771315430016700175300ustar00rootroot00000000000000from SCons.Script import * def addGettextBuilder(env): GettextAction = SCons.Action.Action("$GETTEXTCOM", "$GETTEXTCOMSTR") env["GETTEXT"] = env.Detect("msgfmt") env["GETTEXTCOM"] = "$GETTEXT --check-format --check-domain -f -o $TARGET $SOURCE" builder = Builder( action = GettextAction, suffix = '.mo', src_suffix = '.po', single_source = True) env.Append(BUILDERS = {'Gettext': builder}) XgettextAction = SCons.Action.Action("$XGETTEXTCOM", "$XGETTEXTCOMSTR") env["XGETTEXT"] = env.Detect("xgettext") env["XGETTEXTCOM"] = "$XGETTEXT --keyword=_ --from-code utf-8 --package-name=gpick $XGETTEXT_FLAGS --output=$TARGET $SOURCES" builder = Builder( action = XgettextAction, suffix = '.pot', src_suffix = '.cpp', single_source = False) env.Append(BUILDERS = {'Xgettext': builder}) MsgmergeAction = SCons.Action.Action("$MSGMERGECOM", "$MSGMERGECOMSTR") env["MSGMERGE"] = env.Detect("msgmerge") env["MSGMERGECOM"] = "$MSGMERGE $MSGMERGE_FLAGS --output-file=$TARGET $SOURCES" builder = Builder( action = MsgmergeAction, suffix = '.pot', src_suffix = '.pot', single_source = False) env.Append(BUILDERS = {'Msgmerge': builder}) MsgcatAction = SCons.Action.Action("$MSGCATCOM", "$MSGCATCOMSTR") env["MSGCAT"] = env.Detect("msgcat") env["MSGCATCOM"] = "$MSGCAT $MSGCAT_FLAGS --output-file=$TARGET $SOURCES" builder = Builder( action = MsgcatAction, suffix = '.pot', src_suffix = '.pot', single_source = False) env.Append(BUILDERS = {'Msgcat': builder}) gpick-gpick-0.2.6rc1/tools/gpick.py000066400000000000000000000140651315430016700171320ustar00rootroot00000000000000#!/usr/bin/env python import os import time import SCons import re import string import glob import subprocess from lemon import * from flex import * from gettext import * from resource_template import * from ragel import * from template import * from SCons.Script import * from SCons.Util import * from SCons.Script.SConscript import SConsEnvironment import SCons.Script.SConscript import SCons.SConf import SCons.Conftest def MatchFiles (files, path, repath, dir_exclude_pattern, file_exclude_pattern): for filename in os.listdir(path): fullname = os.path.join (path, filename) repath_file = os.path.join (repath, filename); if os.path.isdir (fullname): if not dir_exclude_pattern.search(repath_file): MatchFiles (files, fullname, repath_file, dir_exclude_pattern, file_exclude_pattern) else: if not file_exclude_pattern.search(filename): files.append (fullname) def CheckPKG(context, name): context.Message('Checking for library %s... ' % name) ret = context.TryAction('pkg-config --exists "%s"' % name)[0] context.Result(ret) return ret def CheckProgram(context, env, name, member_name): context.Message('Checking for program %s... ' % name) if env[member_name]: context.Result(True) return True else: context.Result(False) return False def CompareVersions(a, b): for i in range(0, min(len(a), len(b))): if a[i] < b[i]: return 1 if a[i] > b[i]: return -1 return 0 def CheckBoost(context, version): context.Message('Checking for library boost >= %s... ' % (version)) result, boost_version = context.TryRun(""" #include #include int main(){ std::cout << BOOST_LIB_VERSION << std::endl; return 0; } """, '.cpp') if result: found_version = boost_version.strip('\r\n\t ').split('_') required_version = version.strip('\r\n\t ').split('.') result = CompareVersions(required_version, found_version) >= 0 context.Result(result) return result class GpickLibrary(NodeList): include_dirs = [] class GpickEnvironment(SConsEnvironment): extern_libs = {} def AddCustomBuilders(self): addLemonBuilder(self) addFlexBuilder(self) addGettextBuilder(self) addResourceTemplateBuilder(self) addTemplateBuilder(self) addRagelBuilder(self) def DefineLibrary(self, library_name, library): self.extern_libs[library_name] = library def UseLibrary(self, library_name): lib = self.extern_libs[library_name] for i in lib: lib_include_path = os.path.split(i.path)[0] self.PrependUnique(LIBS = [library_name], LIBPATH = ['#' + lib_include_path]) self.PrependUnique(CPPPATH = lib.include_dirs) return lib def ConfirmPrograms(self, conf, programs): conf.AddTests({'CheckProgram': CheckProgram}) for evar, args in programs.iteritems(): found = False for name, member_name in args['checks'].iteritems(): if conf.CheckProgram(self, name, member_name): found = True; break if not found: if 'required' in args: if not args['required']==False: self.Exit(1) else: self.Exit(1) def ConfirmLibs(self, conf, libs): conf.AddTests({'CheckPKG': CheckPKG}) for evar, args in libs.iteritems(): found = False for name, version in args['checks'].iteritems(): if conf.CheckPKG(name + ' ' + version): self[evar]=name found = True; break if not found: if 'required' in args: if not args['required']==False: self.Exit(1) else: self.Exit(1) def ConfirmBoost(self, conf, version): conf.AddTests({'CheckBoost': CheckBoost}) if conf.CheckBoost(version): return else: self.Exit(1) def InstallPerm(self, dir, source, perm): obj = self.Install(dir, source) for i in obj: self.AddPostAction(i, Chmod(i, perm)) return dir def InstallPermAutoDir(self, dir, relative_dir, source, perm): for f in Flatten(source): path = dir if str(f.get_dir()).startswith(relative_dir): path = os.path.join(path, str(f.get_dir())[len(relative_dir):]) else: path = os.path.join(path, str(f.get_dir())) obj = self.Install(path, f) for i in obj: self.AddPostAction(i, Chmod(i, perm)) return dir InstallProgram = lambda self, dir, source: GpickEnvironment.InstallPerm(self, dir, source, 0755) InstallData = lambda self, dir, source: GpickEnvironment.InstallPerm(self, dir, source, 0644) InstallDataAutoDir = lambda self, dir, relative_dir, source: GpickEnvironment.InstallPermAutoDir(self, dir, relative_dir, source, 0644) def GetSourceFiles(self, dir_exclude_pattern, file_exclude_pattern): dir_exclude_prog = re.compile(dir_exclude_pattern) file_exclude_prog = re.compile(file_exclude_pattern) files = [] MatchFiles(files, self.GetLaunchDir(), os.sep, dir_exclude_prog, file_exclude_prog) return files def GetVersionInfo(self): try: revision = subprocess.Popen(['git', 'show', '--no-patch', '--format="%H %ct"'], shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] match = re.search('([\d\w]+) (\d+)', str(revision)) rev_hash = match.group(1) commit_date = time.gmtime(int(match.group(2))) rev_date = time.strftime("%Y-%m-%d", commit_date) rev_time = time.strftime("%H:%M:%S", commit_date) except: try: with open("../version.txt", "r") as version_file: lines = version_file.read().splitlines() rev_hash = lines[0] rev_date = lines[1] rev_time = lines[2] except: rev_hash = 'unknown' commit_date = time.gmtime(int(os.environ.get('SOURCE_DATE_EPOCH', time.time()))) rev_date = time.strftime("%Y-%m-%d", commit_date) rev_time = time.strftime("%H:%M:%S", commit_date) self.Replace( GPICK_BUILD_REVISION = rev_hash, GPICK_BUILD_DATE = rev_date, GPICK_BUILD_TIME = rev_time, ); def RegexEscape(str): return str.replace('\\', '\\\\') def WriteNsisVersion(target, source, env): for t in target: for s in source: file = open(str(t),"w") file.writelines('!define VERSION "' + str(env['GPICK_BUILD_VERSION']) + '"') file.close() return 0 def Glob(path): files = [] for f in glob.glob(os.path.join(path, '*')): if os.path.isdir(str(f)): files.extend(Glob(str(f))); else: files.append(str(f)); return files gpick-gpick-0.2.6rc1/tools/lemon.py000066400000000000000000000016631315430016700171470ustar00rootroot00000000000000from SCons.Script import * from SCons.Tool.install import copyFunc def addLemonBuilder(env): LemonAction = SCons.Action.Action("$LEMONCOM", "$LEMONCOMSTR") env["LEMON"] = env.Detect("lemon") env["LEMONCOM"] = "cd build/; $LEMON $SOURCE" def headerEmitter(target, source, env): bs = SCons.Util.splitext(str(source[0].name))[0] target.append(bs + '.h') bs = SCons.Util.splitext(str(target[0]))[0] + ".y" source.append(bs) return (target, source) def buildAction(target, source, env): source_dest = SCons.Util.splitext(str(target[0]))[0] + ".y" Execute(Copy('build/lempar.c', 'extern/lempar.c')) Execute(Copy(source_dest, File(source[0]).srcnode())) LemonAction.execute([target], ['../' + source_dest], env); Execute(Delete(source_dest)) return 0 builder = Builder( action = buildAction, suffix = '.c', src_suffix = '.y', emitter = headerEmitter) env.Append(BUILDERS = {'Lemon': builder}) gpick-gpick-0.2.6rc1/tools/ragel.py000066400000000000000000000007651315430016700171310ustar00rootroot00000000000000#!/usr/bin/env python from SCons.Script import * from SCons.Script.SConscript import SConsEnvironment import SCons.Script.SConscript def addRagelBuilder(env): RagelAction = SCons.Action.Action("$RAGELCOM", "$RAGELCOMSTR") env["RAGEL"] = env.Detect("ragel") env["RAGELCOM"] = "$RAGEL $RAGELFLAGS -o $TARGET $SOURCE" env["RAGELFLAGS"] = "-F1 -C" builder = Builder( action = RagelAction, suffix = '.cpp', src_suffix = '.rl', single_source = True) env.Append(BUILDERS = {'Ragel': builder}) gpick-gpick-0.2.6rc1/tools/resource_template.py000066400000000000000000000013421315430016700215510ustar00rootroot00000000000000from SCons.Script import * import re def addResourceTemplateBuilder(env): def buildResourceFile(target, source, env): source_dest = SCons.Util.splitext(str(target[0]))[0] + ".rc" wfile = open(source_dest,"w") data = open(str(File(source[0]).srcnode())).read() for key, var in env['RESOURCE_TEMPLATE_VARS'].iteritems(): data = re.sub("%" + key + "%", var, data) wfile.write(data) wfile.close() return 0 def buildResourceFileString(target, source, env): return "Preparing resource file %s" % os.path.basename(str(target[0])) builder = Builder( action = SCons.Action.Action(buildResourceFile, buildResourceFileString), suffix = '.rc', src_suffix = '.rct', ) env.Append(BUILDERS = {'ResourceTemplate': builder}) gpick-gpick-0.2.6rc1/tools/template.py000066400000000000000000000016501315430016700176440ustar00rootroot00000000000000from SCons.Script import * import re def addTemplateBuilder(env): def buildEmitter(target, source, env): data = open(str(File(source[0]).srcnode())).read() dict = env.Dictionary() keys = dict.keys() for key in keys: if isinstance(dict[key], str): env.Depends(target, env.Value(dict[key])) return target, source def buildFile(target, source, env): source_dest = str(target[0]) wfile = open(source_dest, "w") data = open(str(File(source[0]).srcnode())).read() dict = env.Dictionary() keys = dict.keys() for key in keys: if isinstance(dict[key], str): data = re.sub("%" + key + "%", dict[key], data) wfile.write(data) wfile.close() return 0 def buildString(target, source, env): return "Preparing file %s" % os.path.basename(str(target[0])) builder = Builder( action = SCons.Action.Action(buildFile, buildString), emitter = buildEmitter, ) env.Append(BUILDERS = {'Template': builder}) gpick-gpick-0.2.6rc1/version.py000066400000000000000000000000371315430016700163540ustar00rootroot00000000000000GPICK_BUILD_VERSION='0.2.6rc1' gpick-gpick-0.2.6rc1/version.template000066400000000000000000000000751315430016700175410ustar00rootroot00000000000000%GPICK_BUILD_REVISION% %GPICK_BUILD_DATE% %GPICK_BUILD_TIME%