├── .gitignore
├── CMakeLists.txt
├── LICENSE
├── README.md
├── cmake
└── utils.cmake
├── res
├── calce.hlf.in
├── calce.lng
├── calcr.hlf.in
├── calcr.lng
├── calcset.csr
├── csr.dtd
├── file_id.diz.in
├── readme.txt
├── units
│ ├── angle.csr
│ ├── area.csr
│ ├── date.csr
│ ├── force.csr
│ ├── info.csr
│ ├── length.csr
│ ├── mass.csr
│ ├── pressure.csr
│ ├── speed.csr
│ ├── temperature.csr
│ ├── time.csr
│ └── volume.csr
└── user-examples.csr
├── src
├── CMakeLists.txt
├── plugcalc
│ ├── api-far3.cpp
│ ├── api.cpp
│ ├── api.h
│ ├── calc.cpp
│ ├── calc.h
│ ├── calc.rc
│ ├── config.cpp
│ ├── config.h
│ ├── messages.h
│ ├── newparse.cpp
│ ├── newparse.h
│ ├── plugcalc.def
│ ├── sarg.cpp
│ ├── sarg.h
│ ├── syntax.cpp
│ ├── syntax.h
│ └── version.h
└── shared
│ ├── farplugin
│ ├── 3.0
│ │ ├── farcolor.hpp
│ │ └── plugin.hpp
│ ├── vc_crt_fix.asm
│ └── vc_crt_fix_impl.cpp
│ ├── mathexpression
│ ├── MathExpression.h
│ ├── MathExpressionBase.h
│ ├── README
│ └── StdComplexMathExpression.h
│ ├── sgml
│ ├── sgml.cpp
│ ├── sgml.h
│ ├── sgmledit.cpp
│ ├── sgmledit.h
│ └── tools.cpp
│ ├── trex
│ ├── TRexpp.h
│ ├── history.txt
│ ├── readme.txt
│ ├── test.c
│ ├── trex.c
│ └── trex.h
│ └── ttmath
│ ├── ttmath.h
│ ├── ttmathbig.h
│ ├── ttmathdec.h
│ ├── ttmathint.h
│ ├── ttmathmisc.h
│ ├── ttmathobjects.h
│ ├── ttmathparser.h
│ ├── ttmaththreads.h
│ ├── ttmathtypes.h
│ ├── ttmathuint.h
│ ├── ttmathuint_noasm.h
│ ├── ttmathuint_x86.h
│ ├── ttmathuint_x86_64.h
│ └── ttmathuint_x86_64_msvc.asm
├── vc.build.release.cmd
├── whatsnew_en.txt
└── whatsnew_ru.txt
/.gitignore:
--------------------------------------------------------------------------------
1 | # Clion project files
2 | /.idea
3 | /cmake-build*
4 | /build*
5 | /bin
--------------------------------------------------------------------------------
/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 3.15)
2 | project(Calculator)
3 |
4 | #====================================================
5 | # Enable policy
6 | #====================================================
7 | # enable CMAKE_MSVC_RUNTIME_LIBRARY
8 | cmake_policy(SET CMP0091 NEW)
9 |
10 | #====================================================
11 | # Set default build to release
12 | #====================================================
13 | if (NOT CMAKE_BUILD_TYPE)
14 | set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type, one of: Release, Debug" FORCE)
15 | endif ()
16 | message("Build type for ${PROJECT_NAME}: ${CMAKE_BUILD_TYPE}")
17 |
18 | #====================================================
19 | # Set configuration types
20 | #====================================================
21 | if(NOT MSVC_IDE)
22 | set(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING "" FORCE)
23 | else()
24 | #target_compile_options cannot set parameters for all configurations in MSVC
25 | set(CMAKE_CONFIGURATION_TYPES "${CMAKE_BUILD_TYPE}" CACHE STRING "" FORCE)
26 | endif()
27 | message("Configurations for IDE: ${CMAKE_CONFIGURATION_TYPES}")
28 |
29 | set(CALC_BUILD_ARCH x64 CACHE STRING "Build architecture: x86, x64, arm64")
30 |
31 | # check platform for build
32 | set(IS_x64_PLATFORM FALSE CACHE BOOL "" FORCE)
33 | if ("$ENV{PLATFORM}" MATCHES "x64")
34 | set(IS_x64_PLATFORM TRUE CACHE BOOL "" FORCE)
35 | endif ()
36 |
37 | include(cmake/utils.cmake)
38 | plugin_extract_version(${CMAKE_CURRENT_LIST_DIR}/src/plugcalc/version.h)
39 | set(PACKAGE_FILE_NAME "${PROJECT_NAME}.${PLUGIN_VERSION}.${CALC_BUILD_ARCH}")
40 |
41 | #====================================================
42 | # build plugin
43 | #====================================================
44 | add_subdirectory(src)
45 |
46 | #====================================================
47 | # build resource files
48 | #====================================================
49 | # used @@ESCAPE and ESCAPE@@ for escape @ in files
50 | configure_file(res/file_id.diz.in res/file_id.diz)
51 | configure_file(res/calce.hlf.in res/calce.hlf)
52 | configure_file(res/calcr.hlf.in res/calcr.hlf)
53 |
54 | #====================================================
55 | # install
56 | #====================================================
57 | install(TARGETS Calculator RUNTIME DESTINATION .)
58 | install(DIRECTORY res/
59 | DESTINATION .
60 | PATTERN "*.in" EXCLUDE)
61 | install(FILES
62 | ${CMAKE_CURRENT_BINARY_DIR}/src/calc.map
63 | ${CMAKE_CURRENT_BINARY_DIR}/res/file_id.diz
64 | ${CMAKE_CURRENT_BINARY_DIR}/res/calce.hlf
65 | ${CMAKE_CURRENT_BINARY_DIR}/res/calcr.hlf
66 | whatsnew_en.txt
67 | whatsnew_ru.txt
68 | DESTINATION .)
69 |
70 | #====================================================
71 | # cpack
72 | #====================================================
73 | set(CPACK_GENERATOR "ZIP" CACHE STRING "Generators to support. semi-colon delimited list")
74 | set(CPACK_INCLUDE_TOPLEVEL_DIRECTORY 0)
75 | set(CPACK_PACKAGE_FILE_NAME "${PACKAGE_FILE_NAME}")
76 |
77 | include(CPack)
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | BSD 3-Clause License
2 |
3 | Copyright (c) 1998-2001, Igor Russkih
4 | Copyright (c) 2009-2012, uncle-vunkis
5 | Copyright (c) 2020, FarPlugins Team
6 | All rights reserved.
7 |
8 | Redistribution and use in source and binary forms, with or without
9 | modification, are permitted provided that the following conditions are met:
10 |
11 | * Redistributions of source code must retain the above copyright notice, this
12 | list of conditions and the following disclaimer.
13 |
14 | * Redistributions in binary form must reproduce the above copyright notice,
15 | this list of conditions and the following disclaimer in the documentation
16 | and/or other materials provided with the distribution.
17 |
18 | * Neither the name of the copyright holder nor the names of its
19 | contributors may be used to endorse or promote products derived from
20 | this software without specific prior written permission.
21 |
22 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
23 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
26 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
28 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
29 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Calculator
2 | Advanced configurable calculator, plugin for Far Manager 3.
3 |
4 | ## How to build from source
5 | To build plugin from source, you will need:
6 |
7 | * Visual Studio 2019
8 | * cmake 3.15 (included in Visual Studio 2019)
9 |
10 | #### Release
11 | From root of source call `vc.build.release.cmd`. The build result will be in ./bin folder.
12 |
13 | #### Debug or develop
14 | For example:
15 | ```
16 | call "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" x64
17 | mkdir cmake-build-debug
18 | cd cmake-build-debug
19 | cmake .. -DCMAKE_BUILD_TYPE=Debug -G "Visual Studio 16 2019"
20 | Calculator.sln
21 | ```
22 |
23 | # Common info
24 | * Extracted from: https://github.com/FarPlugins/farplug-alvls
25 | * PlugRing page: https://plugring.farmanager.com/plugin.php?pid=15
26 | * Discuss: https://forum.farmanager.com/viewtopic.php?t=4196&start=300
27 |
--------------------------------------------------------------------------------
/cmake/utils.cmake:
--------------------------------------------------------------------------------
1 | function(plugin_extract_version path_to_version_file)
2 | file(READ "${path_to_version_file}" file_contents)
3 | string(REGEX MATCH "PLUGIN_VER_MAJOR ([0-9]+)" _ "${file_contents}")
4 | if (NOT CMAKE_MATCH_COUNT EQUAL 1)
5 | message(FATAL_ERROR "Could not extract major version number from ${path_to_version_file}")
6 | endif ()
7 | set(ver_major ${CMAKE_MATCH_1})
8 |
9 | string(REGEX MATCH "PLUGIN_VER_MINOR ([0-9]+)" _ "${file_contents}")
10 | if (NOT CMAKE_MATCH_COUNT EQUAL 1)
11 | message(FATAL_ERROR "Could not extract minor version number from ${path_to_version_file}")
12 | endif ()
13 |
14 | set(ver_minor ${CMAKE_MATCH_1})
15 | string(REGEX MATCH "PLUGIN_VER_PATCH ([0-9]+)" _ "${file_contents}")
16 | if (NOT CMAKE_MATCH_COUNT EQUAL 1)
17 | message(FATAL_ERROR "Could not extract patch version number from ${path_to_version_file}")
18 | endif ()
19 | set(ver_patch ${CMAKE_MATCH_1})
20 |
21 | set(PLUGIN_VERSION "${ver_major}.${ver_minor}.${ver_patch}" PARENT_SCOPE)
22 | endfunction()
23 |
--------------------------------------------------------------------------------
/res/calce.hlf.in:
--------------------------------------------------------------------------------
1 | .Language=English,English
2 | .PluginContents=Calculator
3 |
4 | @Contents
5 | $^#Calculator for FAR Manager. Version ${PLUGIN_VERSION}#
6 | $^#Copyright (c) 1998-2001 Igor Russkih#.
7 | $^#Copyright (c) 2009-2012 uncle-vunkis#.
8 | $^#Copyright (c) 2020 FarPlugins Team#.
9 |
10 | PlugIn #Calculator# for #Far# Manager.
11 |
12 |
13 | ~how you can use it?~@@ESCAPE@howuse@ESCAPE@@
14 |
15 | ~technical information.~@@ESCAPE@techinfo@ESCAPE@@
16 |
17 | ~advanced features~@@ESCAPE@addon@ESCAPE@@
18 |
19 | ~about this program.~@@ESCAPE@prog@ESCAPE@@
20 |
21 | ~about author.~@@ESCAPE@author@ESCAPE@@
22 |
23 | @howuse
24 | $^#How you can use it?#
25 |
26 | So, if you didn't understand yet, I'll describe it for you:
27 |
28 | In the #Input Line# you can enter any combination of digits,
29 | words and points, using rules, you know from school(#I hope#).
30 | Calculator will analyze this expression, and show you the result.
31 | If you know little more, you can use extended features.
32 | They are listed in ~Technical Info~@@ESCAPE@TechInfo@ESCAPE@@. Pressing #Ctrl-Down# you
33 | will see history, where are saved recently used expressions.
34 |
35 | The Left from the results you can choose shown number system
36 | with #RadioButtons#. You can press F2 in calculator or select item
37 | in calculator's main menu - you'll see contertation dialogs.
38 | There you can convert different values.
39 |
40 |
41 | @unders
42 | $#Wherefrom it Appears?#
43 |
44 | A-a, I don't know really. So, if we can make a little decision
45 | that my Brains architecture is more complexes, than the Windows 95
46 | architecture, the ideas of those programs was created in parallel
47 | threads of my own brains.
48 |
49 | @techinfo
50 | $^#Technical Information#
51 |
52 | The Calculator lets you compute in all popular systems:
53 | #Decimal#, #Hexadecimal#, #Binary#, #Octal#.
54 |
55 | The number showing is like all standard (#C#, #Pascal#, #Assembler#):
56 |
57 | #0x#12EF = #$#12EF = 12EF#h# - #Hexadecimal.#
58 | 1289 = 1289#D# - #Decimal.#
59 | 123#.#001 = 1#.#23001#e2# = 1#.#23001#e+2# - #Decimal, Exponential.#
60 | #0#1267 = 1267#O# - #Octal.#
61 | 0111#b# - #Binary.#
62 | 'b', 'bb', 'bbbb' - #Symbolic#.
63 |
64 | And now about operators, functions and constants. They are fully configurable
65 | in file #CalcSet.Csr#. How you can do it? Easy. It has the next syntax:
66 |
67 | ##
68 | ##
69 |
70 | ##
71 | ##
72 | ##
73 | ##
74 | ##
75 | ##
76 |
77 | ##
83 |
84 | ##
85 | ##
86 |
87 | This is an exemplary scheme - you can add blocks #Set# and #Use# as much,
88 | as you want. 'Set' Block defines constants, functions, and operators.
89 | Parameter Syntax sets symbolic name, and Mean parameter - calculating expression.
90 | Expression can use variables #op0#, #op1#, #op2#... Operators use only first two -
91 | left and right operators. Functions can have up to ten parameters.
92 |
93 | #Mean# Expression can use buildin and previously user-defined elements.
94 |
95 | #Format# is a radix value (2,8,10,16) or
96 | "exp" = exponential format (for addons only)
97 | "rep" = repeating decimal format
98 | "con" = continued fraction format
99 | Default format is "10".
100 | Also additional flags are available (comma separated):
101 | - for output:
102 | "delim" = use current digit delimiter (depends on settings)
103 |
104 |
105 | Build-in operators (in order of precedence):
106 | #_lor# Logical OR
107 | #_land# Logical AND
108 | #_or# Binary OR
109 | #_xor# Binary XOR
110 | #_and# Binary AND
111 | #_neq, _eq# Not Equal, Equal
112 | #_gt ,_lt# More, Less
113 | #_shr _shl _ror _rol# Shift right, left, rotate shift
114 | #_minus, _plus# Plus, minus
115 | #_mod _div _mul# Mod, Divide, Multiply
116 | #_pow# Power
117 | #_not# Bitwise Not
118 | #_lnot# Logical Not
119 |
120 |
121 | Base functions - #Func(Par)#:
122 |
123 | Functions with no arguments
124 | #_rnd# Random number
125 | #_finf# Float +Infinity number
126 | #_fnan# Float NaN number
127 |
128 | Functions with one argument
129 | #_frac# Fraction
130 | #_floor# Floor of number
131 | #_ceil# Ceil of number
132 | #_sin# Sine
133 | #_cos# Cosine
134 | #_tan# Tanget
135 | #_arctan# ArcTangent
136 | #_ln# Natural Logarithm
137 | #_factor# Factorial
138 | #_f2b# Float to binary (IEEE-754)
139 | #_d2b# Double to binary (IEEE-754)
140 | #_b2f# Binary to float (IEEE-754)
141 | #_b2d# Binary to double (IEEE-754)
142 | #_numer# Numerator of a common fraction
143 | #_denom# Denominator of a common fraction
144 |
145 | Functions with multiple arguments:
146 | #_if# _if(val,a,b). Return a, if val, else return b.
147 | #_gcd# _gcd(num,denom). Greatest common divisor
148 |
149 | Functional operators
150 | #_int64# #_uint64#
151 | #_int# #_uint#
152 | #_short# #_ushort#
153 | #_char# #_byte#
154 | #_double# #_float#
155 |
156 | All #Spaces# in entered expression mean nothing,
157 | so you can use it anywhere. #Symbols register# mean nothing too.
158 |
159 |
160 | @addon
161 | $^#Advanced Features.#
162 | In #Far v1.6# and higher the Calc can work in FAR Editor.
163 | You can call it with #F11-Calculator#.
164 |
165 | Also, there is an #advanced feature# of background working.
166 | With this mode Calc try to calculate any expression in plain text,
167 | with #Alt=#, #AltH#, #AltO#, #AltB# macroses.
168 |
169 |
170 | @prog
171 | $^#About this program and so...#
172 | The Idea of this PlugIn was born from DN's Calculator. So, there
173 | r some visual aspects.... Also you can find Windows version of this
174 | #calc# with the same functionality. I don't know, ~which~@@ESCAPE@Unders@ESCAPE@@ of
175 | the ideas came first in my head.
176 |
177 | So, doing nothing, I desided to incarnate this Idea. With BG Music
178 | under the Star Adelaide it was created.
179 |
180 | Thanks for using Calc,
181 | I hope it needs somebody.
182 | #Igor Russkih#
183 | ...and a tiny bit by #uncle-vunkis#
184 |
185 | @DN
186 |
187 | #Hmmmm...#
188 |
189 | @author
190 | $^#Calculator for FAR Manager. Version ${PLUGIN_VERSION}
191 | #Igor Russkih#. Copyright (c) 1998-2001. All rights reserved.
192 | #uncle-vunkis#. Copyright (c) 2009-2012. #.
193 | #FarPlugins Team#. Copyright (c) 2020. #.
194 | This program is a #FreeWare#. It Means, that you can do anything with
195 | it copies, if this actions are not breaks #Author Rights#.
196 |
197 | Spinning tales about silence
198 | About radio silence
199 | About some kind of asylum
200 | In the middle of an empty field full of danger
201 |
--------------------------------------------------------------------------------
/res/calce.lng:
--------------------------------------------------------------------------------
1 | .Language=English,English
2 |
3 | "calculator"
4 | "&calculator"
5 | "Calculator's Setup"
6 | "en"
7 |
8 | "Dialogs"
9 | "OK"
10 | "Cancel"
11 |
12 | "Show results during the input"
13 | "Case-sensitive input"
14 | "Show periodic fractions"
15 | "Max.period"
16 | "Pad zeroes for fixed-size numbers"
17 | "Right-aligned"
18 | "History"
19 | "Hide"
20 | "Show above"
21 | "Show below"
22 | "lines"
23 | "Autocomplete"
24 | "Delimiters"
25 | "Decimal symbol"
26 | "Use regional settings"
27 | "Arguments"
28 | "Digit group delimiter"
29 |
30 | "ok"
31 | "error"
32 | "expression error"
33 | "type error"
34 | "parameters error"
35 | "brackets error"
36 | "division by zero"
37 | "overflow error"
38 | "too long expression"
39 |
--------------------------------------------------------------------------------
/res/calcr.hlf.in:
--------------------------------------------------------------------------------
1 | .Language=Russian,Russian (Русский)
2 | .PluginContents=Калькулятор
3 |
4 | Отвыкайте копаться в чужих исходниках.
5 |
6 | @Contents
7 | $^#Калькулятор для FAR. Версия ${PLUGIN_VERSION}#
8 | $^#Copyright (c) 1998-2001 Игорь Русских#.
9 | $^#Copyright (c) 2009-2012 uncle-vunkis#.
10 | $^#Copyright (c) 2020 FarPlugins Team#.
11 |
12 | Plugin #Калькулятор# для #FAR#.
13 |
14 |
15 | ~как пользоваться калькулятором?~@@ESCAPE@howuse@ESCAPE@@
16 |
17 | ~техническая информация~@@ESCAPE@techinfo@ESCAPE@@
18 |
19 | ~дополнительные возможности~@@ESCAPE@Addon@ESCAPE@@
20 |
21 | ~о программе~@@ESCAPE@prog@ESCAPE@@
22 |
23 | ~об авторе.~@@ESCAPE@author@ESCAPE@@
24 |
25 | @howuse
26 | $^#Как пользоваться калькулятором?#
27 | Ну если вы еще не поняли, то объясняю:
28 |
29 | В строке выражения вы можете набирать любую комбинацию буковок, циферок,
30 | точечек, крестиков, в соответствии с правилами, которые вы знаете с начальной
31 | школы (надеюсь). Калькулятор автоматически анализирует выражение и в случае
32 | сделанного вами правильного ввода (тоже надеюсь) показывает результат.
33 |
34 | Если вы знаете немного больше, вы можете использовать расширенные
35 | возможности калькулятора. Они перечислены в разделе ~Технической информации~@@ESCAPE@techinfo@ESCAPE@@.
36 |
37 | С помощью мышки или через #Ctrl+F5# вы можете перемещать окошко
38 | калькулятора по бескрайним просторам монитора.
39 | При нажатии в поле ввода выражения #Ctrl-Down# появляется меню истории
40 | ввода. Естественно, там вы можете выбрать старые выражения.
41 | Слева от выводимого результата с помощью #RadioButton# вы можете выбрать,
42 | в какой системе будет отображаться результат в #окне выражения# после нажатия
43 | клавиши #Enter#. Как можно догадаться из сказанного, вышеупомянутая клавиша
44 | используется для преобразования выражения в конечный результат.
45 |
46 | Находясь в самом калькуляторе по клавише #F2#, или же непосредственно выбрав
47 | из меню, вы попадете в один из диалогов по преобразованию величин. Там все
48 | хорошо и понято. Закрывается диалог по #ESC#, но так же вы можете нажать
49 | #Ctrl+Enter# - тогда диалог закроется и в выражение в строке калькулятора
50 | добавится число под курсором из этого диалога.
51 | Аналогично, нажав #Ctrl+Enter# в самом калькуляторе, в зависимости от
52 | того, находитесь ли вы в редакторе или в панелях, текущее значение в строке
53 | калькулятора вставится в редактируемый текст или в командную строку.
54 |
55 |
56 | @unders
57 | $#Откуда она взялась?#
58 |
59 | А черт ее знает. Ну, если сделать смелое предположение о том, что
60 | архитектура моего мозга немногим сложнее архитектуры Windows 95, то
61 | проще будет сказать, что идеи обеих программ возникли в параллельных
62 | потоках(читай извилинах) моих мозгов.
63 |
64 | @techinfo
65 | $^#Техническая Информация#
66 |
67 | Калькулятор позволяет производить расчеты во всех популярных системах счисления:
68 | #Десятичной#, #Шестнадцатеричной#, #Двоичной#, #Восьмеричной#.
69 |
70 | Представление чисел в соответствующих системах соответствует всем стандартам. (#C#, #Pascal#, #Assembler#):
71 |
72 | ###12EF = #0x#12EF = #$#12EF = 12EF#h# - #Шестнадцатеричный.#
73 | 1289 = 1289#D# - #Десятичный.#
74 | 123#.#001 = 1#.#23001#e2# = 1#.#23001#e+2# - #Десятичный, экспонента.#
75 | #0#1267 = 1267#O# - #Восьмеричный.#
76 | 0111#b# - #Двоичный.#
77 | 'b', 'bb', 'bbbb' - #Символьный#.
78 |
79 | Теперь на счет операторов, функций и констант. Они полностью настраиваемы
80 | в файле #calcset.csr#. Как их настраивать? Просто. Это xml-формат.
81 | Если вы имели дело с моим колорером, то сейчас у вас проблем не должно
82 | быть. Синтаксис его следующий:
83 |
84 | ##
85 | ##
86 |
87 | ##
88 | ##
89 | ##
90 | ##
91 | ##
92 | ##
93 |
94 | ##
100 |
101 | ##
102 | ##
103 |
104 | Это примерная схемка - блоков #set# и соответственно тэгов #use# может
105 | быть сколько угодно. В блоке set определяются константы, функции и операторы.
106 | У соотвествующих тэгов параметр Syntax задает символическое имя лексемы, а
107 | параметр mean - выражение для вычисления. В выражении могут использоваться
108 | переменные - #op0#, #op1#, #op2#... Для операторов значение имеют только первые
109 | две - это правый и левый параметры. Для функций их может быть до
110 | десяти(то есть можно определить функцию со множественными аргументами).
111 |
112 | В выражении параметра mean могут использоваться как встроенные лексемы,
113 | так и уже определенные.
114 |
115 | #format# это числовое значение системы счисления (2,8,10,16) или
116 | "exp" = экспоненциальный формат (только для аддонов)
117 | "rep" = смешанные периодические десятичные дроби
118 | "con" = непрерывные дроби в линейной нотации
119 | Формат по умолчанию = "10".
120 | Также доступны дополнительные флаги (через запятую):
121 | - для output:
122 | "delim" = использовать разделитель групп разрядов (зависит от настроек)
123 |
124 |
125 | Встроенные лексемы в порядке увеличения приоритета:
126 | #_lor# Логическое или
127 | #_land# Логическое и
128 | #_or# Побитовое Или (Or)
129 | #_xor# Побитовое Исключающее или (XOr)
130 | #_and# Побитовое И (And)
131 | #_neq, _eq# Не равно, равно
132 | #_gt ,_lt# Больше, меньше
133 | #_shr _shl _ror _rol# Сдвиг вправо, сдвиг влево, циклические
134 | #_minus, _plus# Плюс, минус
135 | #_mod _div _mul# Остаток, Делить, Умножить
136 | #_pow# Степень
137 | #_not# Побитовое не
138 | #_lnot# Логическое Не
139 |
140 |
141 | В определениях функций и операторов лучше избегать смешанного
142 | использования встроенных и уже определенных лексем. Лучше либо одно,
143 | либо другое. Это необходимо, так как приоритет любого встроенного
144 | оператора ниже приоритета любого определенного. Выбирайте: Первое
145 | быстрее, второе удобнее.
146 |
147 | Базовые и определенные функции используются в обычном виде: #func(par)#.
148 |
149 | Ниже перечислены все встроенные функции:
150 |
151 | Функции без параметров
152 | #_rnd# Случайное число
153 | #_finf# Число Float +Infinity
154 | #_fnan# Число Float NaN
155 |
156 | Функции с одним параметром
157 | #_frac# Дробная часть
158 | #_floor# Округление вверх
159 | #_ceil# Округление вниз
160 | #_sin# Синус
161 | #_cos# Косинус
162 | #_tan# Тангенс
163 | #_arctan# АркТангенс
164 | #_ln# Натуральный логарифм
165 | #_factor# Факториал
166 | #_f2b# Из float в бинарный вид (IEEE-754)
167 | #_d2b# Из double в бинарный вид (IEEE-754)
168 | #_b2f# Из бинарного вида в float (IEEE-754)
169 | #_b2d# Из бинарного вида в double (IEEE-754)
170 | #_numer# Числитель простой дроби
171 | #_denom# Знаменатель простой дроби
172 |
173 | Функции с несколькими аргументами
174 | #_if# Условие _if(val,a,b). Возвращает значение a, если val,
175 | и значение b, в противном случае.
176 | #_gcd# _gcd(num,denom). Наибольший общий делитель
177 |
178 | Функциональные операторы преобразования типов.
179 | Вызываются в виде #_int64(expr)#
180 | #_int64# #_uint64#
181 | #_int# #_uint#
182 | #_short# #_ushort#
183 | #_char# #_byte#
184 | #_double# #_float#
185 |
186 | Все остальные функции и операторы могут быть выведены из базовых - что
187 | и сделано в файле calcset.csr. Там же вы можете найти дополнительную
188 | информацию о всех определенных функциях, константах, операторах - описывать
189 | их здесь нет смысла.
190 |
191 | Все символы #пробелов# в набранном выражении игнорируются, так что
192 | вы можете использовать их по своему усмотрению для удобства.
193 | #регистр символов# в набранных выражениях так же не имеет значения.
194 |
195 |
196 | @addon
197 | $^#Дополнительные возможности.#
198 | Да - это значит новые фичи.
199 | Ну, об описании синтаксиса я говорить не буду - сами разберетесь(в
200 | файлике #calcset.csr#), есть у калка еще фичи по вычислению прямо в редакторе. То бишь:
201 | Открываете любой файл на редактирование, вписываете любую формулу или
202 | просто 2+2, нажимаете #Alt=# - и результат готов. Вы можете предварительно
203 | выделить ту часть текста, которая вами считается за формулу.
204 | Помимо #Alt=# можете юзать еще три макроса: #AltO# #AltH# #AltB#.
205 | Соответственно для восьмеричного, шестнадцатеричного и двоичного результата.
206 | Все эти макросы определены в файле shotcuts.reg - так что вам надо сначала
207 | запустить его. Естественно, вы можете переопределить их на свой вкус.
208 |
209 |
210 | @Prog
211 | $^#О программе и так, по мелочам.#
212 | Нуу.. ээх.. давно я тут не писал...
213 | Аж пальцы дрожат...
214 | Многие из тех, ээ.. ну да - чья прошлая жизнь была неразрывно связана
215 | с ~Dos Navigator~@@ESCAPE@DN@ESCAPE@@'ом(им самым), несомненно помнят его встроенный
216 | калькулятор. Переход на Far и для меня, и для многих из вас, думаю,
217 | сопровождался приятными чувствами. Да вот только руки все чаще интуитивно
218 | тянулись к тем самым ~Ctrl-F6~@@ESCAPE@Keys@ESCAPE@@ (по правде сказать не так уж сильно
219 | они и тянулись - больше они тянулись к его редактору с подсветкой синтаксиса).
220 |
221 | Идея этого Plugin'а брала, и берет свое начало из DN'овского калькулятора,
222 | и да простят мне разработчики последнего некоторое сходство. У данного
223 | PlugIn'а имеется аналог в виде Windows-программы абсолютно с теми-же
224 | возможностями. Ее вы можете взять по адресу
225 | ~http://www.uic.nnov.ru/~~ruiv/files/calc.rar~@@ESCAPE@http://www.uic.nnov.ru/~~ruiv/files/calc.rar@ESCAPE@@
226 |
227 | Хотя, который из вариантов воплощения идеи калькулятора пришел ко мне в
228 | голову первым - ~не понятно~@@ESCAPE@Unders@ESCAPE@@ даже ~Мне~@@ESCAPE@Author@ESCAPE@@.
229 |
230 | Итак, сидя, и маясь от безделья, я решил воплотить идею в жизнь.
231 | Постясь и молясь через раз идолу нашему главному, я набивал Это.
232 | Результат вы созерцаете теперь у себя на мониторе.
233 |
234 | Спасибо за использование этого
235 | калькулятора, надеюсь у него
236 | никогда не сядут батарейки.
237 | #Игорь Русских#
238 | ...and a tiny bit by #uncle-vunkis#
239 |
240 | @DN
241 |
242 | #Кхе...#
243 |
244 |
245 | @Keys
246 | $^#Вам нравятся Ctrl-F6?
247 | Как переопределить эту комбинацию для использования с моим калькулятором?
248 | В каталоге с Plugin'ом вы найдете файл: #shortcuts.reg#. Этот файл содержит
249 | макросы переопределения. Запустите - и все в порядке.
250 |
251 |
252 | @Author
253 | $^#Калькулятор-plugin для FAR Manager. Версия ${PLUGIN_VERSION}
254 | #Игорь Русских#. Copyright (c) 1998-2001.
255 | #uncle-vunkis#. Copyright (c) 2009-2012.
256 | #FarPlugins Team#. Copyright (c) 2020. #.
257 |
258 | Эту программу я писал для себя и для вас, поэтому я не собираюсь ставить
259 | перед вами каких-либо серьезных требований. Единственно чего прошу - так
260 | это выслать мне заполненную формочку.
261 |
262 | У этой песни нет конца и начала,
263 | Но есть эпиграф - несколько фраз...
264 | Мы выросли в поле такого напряга,
265 | где любое устройство сгорает на раз...
--------------------------------------------------------------------------------
/res/calcr.lng:
--------------------------------------------------------------------------------
1 | .Language=Russian,Russian (Русский)
2 |
3 | "калькулятор"
4 | "калькулятор"
5 | "Калькулятор: Настройки"
6 | "ru"
7 |
8 | "Разделы"
9 | "OK"
10 | "Отмена"
11 |
12 | "Показывать результаты при вводе"
13 | "Ввод чувствителен к регистру"
14 | "Показывать периодические дроби;"
15 | "Макс.период"
16 | "Дополнять нулями числа фиксированной длины"
17 | "Выравнивать по правому краю"
18 | "История"
19 | "Прятать"
20 | "Показать над"
21 | "Показать под"
22 | "cтрок"
23 | "Автодополнение ввода"
24 | "Разделители"
25 | "Десятичная точка"
26 | "Из региональных настроек"
27 | "Аргументы"
28 | "Разделитель разрядов"
29 |
30 | "ok"
31 | "ошибка"
32 | "ошибка выражения"
33 | "ошибка типа"
34 | "ошибка в параметрах"
35 | "ошибка в скобках"
36 | "ошибка деления на ноль"
37 | "ошибка переполения"
38 | "слишком длинное выражение"
39 |
--------------------------------------------------------------------------------
/res/calcset.csr:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FarPlugins/Calculator/90254b77b3c4ccc39218c747d3525de8d0369b93/res/calcset.csr
--------------------------------------------------------------------------------
/res/csr.dtd:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
6 |
7 |
8 |
10 |
11 |
12 |
14 |
15 |
16 |
18 |
19 |
20 |
22 |
23 |
24 |
27 |
28 |
29 |
33 |
34 |
35 |
39 |
40 |
41 |
45 |
46 |
47 |
50 |
51 |
52 |
54 |
55 |
56 |
58 |
59 |
60 |
65 |
66 |
--------------------------------------------------------------------------------
/res/file_id.diz.in:
--------------------------------------------------------------------------------
1 |
2 | FAR Manager Calculator ${PLUGIN_VERSION}
3 | Igor Russkih (c) 1998-2001
4 | uncle-vunkis (c) 2009-2012
5 | FarPlugins Team (c) 2020
6 |
7 | Free syntax, powerfull settings
8 | FAR 3.0 support, convertation dialogs
9 |
10 |
--------------------------------------------------------------------------------
/res/readme.txt:
--------------------------------------------------------------------------------
1 |
2 | Plugin Calculator for FAR Manager (c) Igor Russkih 1998-2001
3 | (c) uncle-vunkis 2009-2012
4 | (c) FarPlugins Team 2020
5 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
6 | https://github.com/FarPlugins/Calculator
7 |
8 | How you can install this plugin?
9 |
10 | 1. Create subdirectory \Far\PlugIns\Calculator
11 | and copy there all calculator files.
12 | 2. Restart FAR Manager and Calculator is ready for work:
13 | F11 (plugins Menu) - Calculator.
14 |
15 | License - BSD 3-Clause License
16 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
17 |
18 | Плагин заменит ваш ручной калькулятор, если у того подсядут
19 | батарейки. Ну, может еще и поболе того.
20 |
21 | Как заставить этого хрена работать?
22 |
23 | 1. Создайте каталог Far\Plugins\calculator
24 | 2. Киньте туда все файлы калькулятора с сохранением путей.
25 | 2. Перезапустите FAR, и Калькулятор готов к работе:
26 | F11(Меню плагиновов) - Калькулятор(Calculator)
27 |
28 | Лицензия - BSD 3-Clause License
29 |
--------------------------------------------------------------------------------
/res/units/angle.csr:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FarPlugins/Calculator/90254b77b3c4ccc39218c747d3525de8d0369b93/res/units/angle.csr
--------------------------------------------------------------------------------
/res/units/area.csr:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FarPlugins/Calculator/90254b77b3c4ccc39218c747d3525de8d0369b93/res/units/area.csr
--------------------------------------------------------------------------------
/res/units/date.csr:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FarPlugins/Calculator/90254b77b3c4ccc39218c747d3525de8d0369b93/res/units/date.csr
--------------------------------------------------------------------------------
/res/units/force.csr:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FarPlugins/Calculator/90254b77b3c4ccc39218c747d3525de8d0369b93/res/units/force.csr
--------------------------------------------------------------------------------
/res/units/info.csr:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FarPlugins/Calculator/90254b77b3c4ccc39218c747d3525de8d0369b93/res/units/info.csr
--------------------------------------------------------------------------------
/res/units/length.csr:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FarPlugins/Calculator/90254b77b3c4ccc39218c747d3525de8d0369b93/res/units/length.csr
--------------------------------------------------------------------------------
/res/units/mass.csr:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FarPlugins/Calculator/90254b77b3c4ccc39218c747d3525de8d0369b93/res/units/mass.csr
--------------------------------------------------------------------------------
/res/units/pressure.csr:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FarPlugins/Calculator/90254b77b3c4ccc39218c747d3525de8d0369b93/res/units/pressure.csr
--------------------------------------------------------------------------------
/res/units/speed.csr:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FarPlugins/Calculator/90254b77b3c4ccc39218c747d3525de8d0369b93/res/units/speed.csr
--------------------------------------------------------------------------------
/res/units/temperature.csr:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FarPlugins/Calculator/90254b77b3c4ccc39218c747d3525de8d0369b93/res/units/temperature.csr
--------------------------------------------------------------------------------
/res/units/time.csr:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FarPlugins/Calculator/90254b77b3c4ccc39218c747d3525de8d0369b93/res/units/time.csr
--------------------------------------------------------------------------------
/res/units/volume.csr:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FarPlugins/Calculator/90254b77b3c4ccc39218c747d3525de8d0369b93/res/units/volume.csr
--------------------------------------------------------------------------------
/res/user-examples.csr:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/FarPlugins/Calculator/90254b77b3c4ccc39218c747d3525de8d0369b93/res/user-examples.csr
--------------------------------------------------------------------------------
/src/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | project(Calculator VERSION ${PLUGIN_VERSION} LANGUAGES CXX C)
2 |
3 | set(SRC_CPP
4 | plugcalc/api.cpp
5 | plugcalc/api.h
6 | plugcalc/api-far3.cpp
7 | plugcalc/calc.cpp
8 | plugcalc/calc.h
9 | plugcalc/calc.rc
10 | plugcalc/config.cpp
11 | plugcalc/config.h
12 | plugcalc/messages.h
13 | plugcalc/newparse.cpp
14 | plugcalc/newparse.h
15 | plugcalc/sarg.cpp
16 | plugcalc/sarg.h
17 | plugcalc/syntax.cpp
18 | plugcalc/syntax.h
19 | plugcalc/version.h
20 | shared/mathexpression/MathExpressionBase.h
21 | shared/sgml/sgml.cpp
22 | shared/trex/trex.c
23 | shared/trex/trex.h
24 | shared/ttmath/ttmath.h
25 | shared/ttmath/ttmathbig.h
26 | shared/ttmath/ttmathint.h
27 | shared/ttmath/ttmathobjects.h
28 | shared/ttmath/ttmathparser.h
29 | shared/ttmath/ttmathtypes.h
30 | shared/ttmath/ttmathuint.h
31 | shared/ttmath/ttmathuint_noasm.h
32 | shared/ttmath/ttmathuint_x86.h
33 | shared/ttmath/ttmathuint_x86_64.h
34 | )
35 |
36 | set(SRC_DEF plugcalc/plugcalc.def)
37 |
38 | #====================================================
39 | # common flags
40 | #====================================================
41 | if (CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
42 | # default for msvc project
43 | # CMAKE_CXX_FLAGS= /DWIN32 /D_WINDOWS /GR /EHsc
44 | # CMAKE_CXX_FLAGS_DEBUG= /MDd /Zi /Ob0 /Od /RTC1
45 | # CMAKE_CXX_FLAGS_RELEASE= /MD /O2 /Ob2 /DNDEBUG
46 |
47 | # for replace /Ob2 https://gitlab.kitware.com/cmake/cmake/-/issues/19084
48 | string(REGEX REPLACE "/Ob2" "" CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE}")
49 |
50 | if (CMAKE_BUILD_TYPE MATCHES Debug)
51 | set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreadedDebug")
52 | else ()
53 | set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded")
54 | endif ()
55 |
56 | set(FLAGS_CXX_DEFAULT /Zi /EHsc)
57 | set(FLAGS_CXX_RELEASE /W3 /Oi /Ot /GL /GS- /Ob1 /GF /GR)
58 | set(FLAGS_CXX_DEBUG /W3 /GS)
59 |
60 | set(LINK_FLAGS "/MAP /MANIFEST:NO")
61 |
62 | # build with debug info in pdb
63 | if (CMAKE_BUILD_TYPE MATCHES "Release")
64 | set(LINK_FLAGS "${LINK_FLAGS} /incremental:no /OPT:REF /OPT:ICF /debug /ltcg")
65 | endif ()
66 |
67 | add_definitions(-DUNICODE -D_UNICODE -D_CRT_SECURE_NO_WARNINGS -DTTMATH_RELEASE)
68 |
69 | if (IS_x64_PLATFORM)
70 | set(CMAKE_RC_FLAGS -D_WIN64)
71 | add_definitions(-DTTMATH_NOASM -DTTMATH_PLATFORM64)
72 | elseif ("${CALC_BUILD_ARCH}" STREQUAL "x86")
73 | add_definitions(-DWINDOWS_IGNORE_PACKING_MISMATCH)
74 | # support old CPU AMD on WinXP
75 | set(FLAGS_CXX_DEFAULT ${FLAGS_CXX_DEFAULT} /arch:IA32)
76 | set(FLAGS_C_DEFAULT ${FLAGS_C_DEFAULT} /arch:IA32)
77 | endif ()
78 |
79 | if (NOT("${CALC_BUILD_ARCH}" STREQUAL "arm64"))
80 | # for vc_crt_fix_impl.cpp
81 | set(FLAGS_CXX_DEFAULT ${FLAGS_CXX_DEFAULT} /Zc:threadSafeInit-)
82 | set(FLAGS_C_DEFAULT ${FLAGS_C_DEFAULT} /Zc:threadSafeInit-)
83 | endif()
84 | endif ()
85 |
86 | # set options for target
87 | set(MAIN_FLAGS_CXX_DEBUG ${FLAGS_CXX_DEBUG} ${FLAGS_CXX_DEFAULT})
88 | set(MAIN_FLAGS_CXX_RELEASE ${FLAGS_CXX_RELEASE} ${FLAGS_CXX_DEFAULT})
89 | set(MAIN_FLAGS_C_DEBUG ${FLAGS_C_DEBUG} ${FLAGS_C_DEFAULT})
90 | set(MAIN_FLAGS_C_RELEASE ${FLAGS_C_RELEASE} ${FLAGS_C_DEFAULT})
91 |
92 | #====================================================
93 | # support win2k, winxp
94 | #====================================================
95 | if (MSVC AND NOT("${CALC_BUILD_ARCH}" STREQUAL "arm64"))
96 | set(ASM_SOURCE ${PROJECT_SOURCE_DIR}/shared/farplugin/vc_crt_fix.asm)
97 | set(ASM_OBJECT ${CMAKE_CURRENT_BINARY_DIR}/vc_crt_fix.obj)
98 | set(ASM_OBJECTS ${ASM_OBJECTS} ${ASM_OBJECT})
99 | set(MASM_DEFINES "")
100 | if (${CMAKE_CL_64} STREQUAL "0")
101 | find_program(MASM_EXECUTABLE ml)
102 | else ()
103 | find_program(MASM_EXECUTABLE ml64)
104 | set(MASM_DEFINES "/DX64")
105 | endif ()
106 |
107 | add_custom_command(
108 | OUTPUT ${ASM_OBJECT}
109 | COMMAND ${MASM_EXECUTABLE}
110 | ARGS /c ${MASM_DEFINES} /Fo ${ASM_OBJECT} ${ASM_SOURCE}
111 | DEPENDS ${ASM_SOURCE}
112 | )
113 |
114 | set(SRC_CPP ${SRC_CPP}
115 | ${PROJECT_SOURCE_DIR}/shared/farplugin/vc_crt_fix_impl.cpp
116 | ${ASM_OBJECTS}
117 | )
118 | endif ()
119 | #====================================================
120 | # build
121 | #====================================================
122 |
123 | set(SRC_FILES ${SRC_CPP} ${SRC_DEF})
124 | add_library(${PROJECT_NAME} SHARED ${SRC_FILES})
125 | target_include_directories(${PROJECT_NAME}
126 | PRIVATE ./shared
127 | )
128 |
129 | set_target_properties(${PROJECT_NAME} PROPERTIES
130 | CXX_STANDARD 11
131 | CXX_STANDARD_REQUIRED YES
132 | CXX_EXTENSIONS NO
133 | )
134 |
135 | if (${CMAKE_BUILD_TYPE} MATCHES Debug)
136 | target_compile_options(${PROJECT_NAME}
137 | PUBLIC $<$:${MAIN_FLAGS_C_DEBUG}>
138 | PUBLIC $<$:${MAIN_FLAGS_CXX_DEBUG}>
139 | )
140 | else ()
141 | target_compile_options(${PROJECT_NAME}
142 | PUBLIC $<$:${MAIN_FLAGS_C_RELEASE}>
143 | PUBLIC $<$:${MAIN_FLAGS_CXX_RELEASE}>
144 | )
145 | endif ()
146 |
147 | set_target_properties(${PROJECT_NAME}
148 | PROPERTIES
149 | LINK_FLAGS "${LINK_FLAGS}"
150 | OUTPUT_NAME "calc"
151 | )
152 |
153 | # create archive with pdb file
154 | add_custom_target(
155 | ${PROJECT_NAME}_PDB ALL
156 | COMMAND ${CMAKE_COMMAND} -E tar "cfv" "../${PACKAGE_FILE_NAME}.pdb.zip" --format=zip $
157 | DEPENDS $
158 | )
--------------------------------------------------------------------------------
/src/plugcalc/api.cpp:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) uncle-vunkis 2009-2011
3 | // You can use, modify, distribute this code or any other part
4 | // of this program in sources or in binaries only according
5 | // to License (see /doc/license.txt for more information).
6 | //
7 |
8 | #include
9 | #include
10 | #include
11 |
12 | #include "api.h"
13 | #include "calc.h"
14 | #include "messages.h"
15 |
16 |
17 | CalcApi *api = nullptr;
18 | CalcDialogFuncs *dlg_funcs = nullptr;
19 |
20 | // exports
21 |
22 | extern "C"
23 | {
24 | void WINAPI SetStartupInfoW(void *info);
25 | void WINAPI GetPluginInfoW(void *pinfo);
26 | void WINAPI GetGlobalInfoW(void *ginfo);
27 | HANDLE WINAPI OpenW(void *oinfo);
28 | int WINAPI ConfigureW(void *);
29 | void WINAPI ExitFARW(void* einfo);
30 | }
31 |
32 |
33 | //////////////////////////////////////////////////////////////
34 | // FAR exports
35 | void WINAPI SetStartupInfoW(void *info)
36 | {
37 | //TODO start on first call in OpenW, not in init
38 | api = CreateApiFar3(info);
39 | if (api)
40 | {
41 | dlg_funcs = api->GetDlgFuncs();
42 | CalcStartup();
43 | }
44 | }
45 |
46 | void WINAPI GetPluginInfoW(void *pinfo)
47 | {
48 | api->GetPluginInfo(pinfo, api->GetMsg(mName));
49 | }
50 |
51 | HANDLE WINAPI OpenW(void *oinfo)
52 | {
53 | CalcOpen(api->IsOpenedFromEditor(oinfo, 0));
54 | return nullptr;
55 | }
56 |
57 | int WINAPI ConfigureW(void *c)
58 | {
59 | return CalcConfig();
60 | }
61 |
62 | void WINAPI GetGlobalInfoW(void *ginfo)
63 | {
64 | GetGlobalInfoFar3(ginfo, L"calculator");
65 | }
66 |
67 | void WINAPI ExitFARW(void* einfo)
68 | {
69 | delete api;
70 | delete dlg_funcs;
71 | }
72 | ////////////////////////////////////////////////////////////////////
73 |
74 | static std::unordered_map dlg_hash;
75 |
76 | static CALC_INT_PTR __stdcall dlgProc(DLGHANDLE hdlg, int msg, int param1, void *param2)
77 | {
78 | auto op = dlg_hash.find(hdlg);
79 | CALC_INT_PTR ret = -1;
80 | if (op != dlg_hash.end())
81 | {
82 | CalcDialog *dlg = op->second;
83 |
84 | if (dlg->msg_tbl[msg])
85 | {
86 | dlg_funcs->PreProcessMessage(hdlg, msg, param1, param2);
87 |
88 | ret = (dlg->*(dlg->msg_tbl[msg]))(param1, param2);
89 |
90 | dlg_funcs->PostProcessMessage(hdlg, msg, ret, param1, param2);
91 | }
92 | }
93 |
94 | if (ret == -1)
95 | return dlg_funcs->DefDlgProc(hdlg, msg, param1, param2);
96 | return ret;
97 | }
98 |
99 | /////////////////////////////////////////////////////////////////////////
100 |
101 | CalcDialog::CalcDialog()
102 | {
103 | msg_tbl = dlg_funcs->GetMessageTable();
104 | hdlg = nullptr;
105 | }
106 |
107 | CalcDialog::~CalcDialog()
108 | {
109 | if (hdlg)
110 | {
111 | auto op = dlg_hash.find(hdlg);
112 | if (op != dlg_hash.end())
113 | dlg_hash.erase(op);
114 | dlg_funcs->DialogFree(hdlg);
115 | }
116 | }
117 |
118 | bool CalcDialog::Init(int id, int X1, int Y1, int X2, int Y2, const wchar_t *HelpTopic,
119 | struct CalcDialogItem *Item, unsigned int ItemsNumber)
120 | {
121 | hdlg = dlg_funcs->DialogInit(id, X1, Y1, X2, Y2, HelpTopic, Item, ItemsNumber, dlgProc);
122 | if (hdlg == INVALID_HANDLE_VALUE)
123 | return false;
124 | dlg_hash.insert(std::make_pair(hdlg, this));
125 | return true;
126 | }
127 |
128 | intptr_t CalcDialog::Run()
129 | {
130 | return dlg_funcs->DialogRun(hdlg);
131 | }
132 |
133 | void CalcDialog::EnableRedraw(bool en)
134 | {
135 | dlg_funcs->EnableRedraw(hdlg, en);
136 | }
137 | void CalcDialog::ResizeDialog(const CalcCoord & dims)
138 | {
139 | dlg_funcs->ResizeDialog(hdlg, dims);
140 | }
141 | void CalcDialog::RedrawDialog()
142 | {
143 | dlg_funcs->RedrawDialog(hdlg);
144 | }
145 | void CalcDialog::GetDlgRect(CalcRect *rect)
146 | {
147 | dlg_funcs->GetDlgRect(hdlg, rect);
148 | }
149 | void CalcDialog::Close(int exitcode)
150 | {
151 | dlg_funcs->Close(hdlg, exitcode);
152 | }
153 |
154 | void CalcDialog::GetDlgItemShort(int id, CalcDialogItem *item)
155 | {
156 | dlg_funcs->GetDlgItemShort(hdlg, id, item);
157 | }
158 | void CalcDialog::SetDlgItemShort(int id, const CalcDialogItem & item)
159 | {
160 | dlg_funcs->SetDlgItemShort(hdlg, id, item);
161 | }
162 | void CalcDialog::SetItemPosition(int id, const CalcRect & rect)
163 | {
164 | dlg_funcs->SetItemPosition(hdlg, id, rect);
165 | }
166 | int CalcDialog::GetFocus()
167 | {
168 | return dlg_funcs->GetFocus(hdlg);
169 | }
170 | void CalcDialog::SetFocus(int id)
171 | {
172 | dlg_funcs->SetFocus(hdlg, id);
173 | }
174 | void CalcDialog::EditChange(int id, const CalcDialogItem & item)
175 | {
176 | dlg_funcs->EditChange(hdlg, id, item);
177 | }
178 | void CalcDialog::SetSelection(int id, const CalcEditorSelect & sel)
179 | {
180 | dlg_funcs->SetSelection(hdlg, id, sel);
181 | }
182 | void CalcDialog::SetCursorPos(int id, const CalcCoord & pos)
183 | {
184 | dlg_funcs->SetCursorPos(hdlg, id, pos);
185 | }
186 | void CalcDialog::GetText(int id, std::wstring &str)
187 | {
188 | dlg_funcs->GetText(hdlg, id, str);
189 | }
190 | void CalcDialog::SetText(int id, const std::wstring & str)
191 | {
192 | dlg_funcs->SetText(hdlg, id, str);
193 | }
194 | void CalcDialog::AddHistory(int id, const std::wstring & str)
195 | {
196 | dlg_funcs->AddHistory(hdlg, id, str);
197 | }
198 | bool CalcDialog::IsChecked(int id)
199 | {
200 | return dlg_funcs->IsChecked(hdlg, id);
201 | }
--------------------------------------------------------------------------------
/src/plugcalc/api.h:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) uncle-vunkis 2009-2012
3 | // You can use, modify, distribute this code or any other part
4 | // of this program in sources or in binaries only according
5 | // to License (see /doc/license.txt for more information).
6 | //
7 |
8 | #ifndef _CALC_API_H_
9 | #define _CALC_API_H_
10 |
11 | #include
12 | #include
13 |
14 | enum CalcDialogItemTypes
15 | {
16 | CALC_DI_TEXT,
17 | CALC_DI_VTEXT,
18 | CALC_DI_SINGLEBOX,
19 | CALC_DI_DOUBLEBOX,
20 | CALC_DI_EDIT,
21 | CALC_DI_PSWEDIT,
22 | CALC_DI_FIXEDIT,
23 | CALC_DI_BUTTON,
24 | CALC_DI_CHECKBOX,
25 | CALC_DI_RADIOBUTTON,
26 | CALC_DI_COMBOBOX,
27 | CALC_DI_LISTBOX,
28 |
29 | CALC_DI_USERCONTROL=255,
30 | };
31 |
32 | typedef unsigned __int64 CalcDialogItemFlags;
33 | static const CalcDialogItemFlags
34 | CALC_DIF_NONE = 0,
35 | CALC_DIF_BOXCOLOR = 0x0000000000000200ULL,
36 | CALC_DIF_GROUP = 0x0000000000000400ULL,
37 | CALC_DIF_LEFTTEXT = 0x0000000000000800ULL,
38 | CALC_DIF_MOVESELECT = 0x0000000000001000ULL,
39 | CALC_DIF_SHOWAMPERSAND = 0x0000000000002000ULL,
40 | CALC_DIF_CENTERGROUP = 0x0000000000004000ULL,
41 | CALC_DIF_NOBRACKETS = 0x0000000000008000ULL,
42 | CALC_DIF_MANUALADDHISTORY = 0x0000000000008000ULL,
43 | CALC_DIF_SEPARATOR = 0x0000000000010000ULL,
44 | CALC_DIF_SEPARATOR2 = 0x0000000000020000ULL,
45 | CALC_DIF_EDITOR = 0x0000000000020000ULL,
46 | CALC_DIF_LISTNOAMPERSAND = 0x0000000000020000ULL,
47 | CALC_DIF_LISTNOBOX = 0x0000000000040000ULL,
48 | CALC_DIF_HISTORY = 0x0000000000040000ULL,
49 | CALC_DIF_BTNNOCLOSE = 0x0000000000040000ULL,
50 | CALC_DIF_CENTERTEXT = 0x0000000000040000ULL,
51 | CALC_DIF_SETSHIELD = 0x0000000000080000ULL,
52 | CALC_DIF_EDITEXPAND = 0x0000000000080000ULL,
53 | CALC_DIF_DROPDOWNLIST = 0x0000000000100000ULL,
54 | CALC_DIF_USELASTHISTORY = 0x0000000000200000ULL,
55 | CALC_DIF_MASKEDIT = 0x0000000000400000ULL,
56 | CALC_DIF_SELECTONENTRY = 0x0000000000800000ULL,
57 | CALC_DIF_3STATE = 0x0000000000800000ULL,
58 | CALC_DIF_EDITPATH = 0x0000000001000000ULL,
59 | CALC_DIF_LISTWRAPMODE = 0x0000000001000000ULL,
60 | CALC_DIF_NOAUTOCOMPLETE = 0x0000000002000000ULL,
61 | CALC_DIF_LISTAUTOHIGHLIGHT = 0x0000000002000000ULL,
62 | CALC_DIF_LISTNOCLOSE = 0x0000000004000000ULL,
63 | CALC_DIF_HIDDEN = 0x0000000010000000ULL,
64 | CALC_DIF_READONLY = 0x0000000020000000ULL,
65 | CALC_DIF_NOFOCUS = 0x0000000040000000ULL,
66 | CALC_DIF_DISABLE = 0x0000000080000000ULL,
67 | CALC_DIF_DEFAULTBUTTON = 0x0000000100000000ULL,
68 | CALC_DIF_FOCUS = 0x0000000200000000ULL;
69 |
70 |
71 | enum CalcMenuFlags
72 | {
73 | CALC_FMENU_SHOWAMPERSAND = 0x00000001ULL,
74 | CALC_FMENU_WRAPMODE = 0x00000002ULL,
75 | CALC_FMENU_AUTOHIGHLIGHT = 0x00000004ULL,
76 | CALC_FMENU_REVERSEAUTOHIGHLIGHT = 0x00000008ULL,
77 | };
78 |
79 | enum CalcEditorBlockTypes
80 | {
81 | CALC_BTYPE_NONE,
82 | CALC_BTYPE_STREAM,
83 | CALC_BTYPE_COLUMN
84 | };
85 |
86 | typedef unsigned __int64 CALCCOLORFLAGS;
87 | static const CALCCOLORFLAGS
88 | CALC_FCF_FG_4BIT = 0x0000000000000001ULL,
89 | CALC_FCF_BG_4BIT = 0x0000000000000002ULL;
90 |
91 |
92 | struct CalcDialogItem
93 | {
94 | CalcDialogItemTypes Type;
95 |
96 | int X1, Y1, X2, Y2;
97 | union
98 | {
99 | intptr_t Reserved;
100 | intptr_t Selected;
101 | };
102 | unsigned long long Flags;
103 | const wchar_t *PtrData;
104 | };
105 |
106 | class CalcMenuItem
107 | {
108 | public:
109 | CalcMenuItem() { Text = nullptr; Selected = 0; Checked = 0; Separator = 0; }
110 | public:
111 | const wchar_t *Text;
112 | int Selected;
113 | int Checked;
114 | int Separator;
115 | };
116 |
117 | struct CalcEditorInfo
118 | {
119 | size_t StructSize;
120 | intptr_t EditorID;
121 | intptr_t WindowSizeX;
122 | intptr_t WindowSizeY;
123 | intptr_t TotalLines;
124 | intptr_t CurLine;
125 | intptr_t CurPos;
126 | intptr_t CurTabPos;
127 | intptr_t TopScreenLine;
128 | intptr_t LeftPos;
129 | intptr_t Overtype;
130 | intptr_t BlockType;
131 | intptr_t BlockStartLine;
132 | uintptr_t Options;
133 | intptr_t TabSize;
134 | size_t BookmarkCount;
135 | size_t SessionBookmarkCount;
136 | uintptr_t CurState;
137 | uintptr_t CodePage;
138 | };
139 |
140 | struct CalcEditorSelect
141 | {
142 | size_t StructSize;
143 | intptr_t BlockType;
144 | intptr_t BlockStartLine;
145 | intptr_t BlockStartPos;
146 | intptr_t BlockWidth;
147 | intptr_t BlockHeight;
148 | };
149 |
150 | struct CalcEditorGetString
151 | {
152 | size_t StructSize;
153 | intptr_t StringNumber;
154 | intptr_t StringLength;
155 | const wchar_t *StringText;
156 | const wchar_t *StringEOL;
157 | intptr_t SelStart;
158 | intptr_t SelEnd;
159 | };
160 |
161 | struct CalcCoord
162 | {
163 | short X;
164 | short Y;
165 | };
166 |
167 | struct CalcRect
168 | {
169 | short Left;
170 | short Top;
171 | short Right;
172 | short Bottom;
173 | };
174 |
175 | struct CalcColor
176 | {
177 | unsigned __int64 Flags;
178 | unsigned int ForegroundColor;
179 | unsigned int BackgroundColor;
180 | void* Reserved;
181 | };
182 |
183 | struct CalcDialogItemColors
184 | {
185 | size_t StructSize;
186 | unsigned __int64 Flags;
187 | size_t ColorsCount;
188 | struct CalcColor* Colors;
189 | };
190 |
191 |
192 | ///////////////////////////////////////////////////////////////////////////////////
193 |
194 | typedef void *DLGHANDLE;
195 | #if defined(_WIN64)
196 | typedef __int64 CALC_INT_PTR;
197 | #else
198 | typedef __int32 CALC_INT_PTR;
199 | #endif
200 | typedef CALC_INT_PTR (__stdcall *CALCDLGPROC)(DLGHANDLE hdlg, int msg, int param1, void *param2);
201 |
202 |
203 | class CalcDialog
204 | {
205 | public:
206 | CalcDialog();
207 | virtual ~CalcDialog();
208 |
209 | bool Init(int id, int X1, int Y1, int X2, int Y2, const wchar_t *HelpTopic,
210 | struct CalcDialogItem *Item, unsigned int ItemsNumber);
211 | intptr_t Run();
212 |
213 | void EnableRedraw(bool);
214 | void ResizeDialog(const CalcCoord & dims);
215 | void RedrawDialog();
216 | void GetDlgRect(CalcRect *rect);
217 | void Close(int exitcode);
218 |
219 | void GetDlgItemShort(int id, CalcDialogItem *item);
220 | void SetDlgItemShort(int id, const CalcDialogItem & item);
221 | void SetItemPosition(int id, const CalcRect & rect);
222 | int GetFocus();
223 | void SetFocus(int id);
224 | void EditChange(int id, const CalcDialogItem & item);
225 | void SetSelection(int id, const CalcEditorSelect & sel);
226 | void SetCursorPos(int id, const CalcCoord & pos);
227 | void GetText(int id, std::wstring &str);
228 | void SetText(int id, const std::wstring & str);
229 | bool IsChecked(int id);
230 | void AddHistory(int id, const std::wstring & str);
231 |
232 | public:
233 | virtual CALC_INT_PTR OnInitDialog(int param1, void *param2) { return -1; }
234 | virtual CALC_INT_PTR OnClose(int param1, void *param2) { return -1; }
235 | virtual CALC_INT_PTR OnResizeConsole(int param1, void *param2) { return -1; }
236 | virtual CALC_INT_PTR OnDrawDialog(int param1, void *param2) { return -1; }
237 | virtual CALC_INT_PTR OnButtonClick(int param1, void *param2) { return -1; }
238 | virtual CALC_INT_PTR OnGotFocus(int param1, void *param2) { return -1; }
239 | virtual CALC_INT_PTR OnEditChange(int param1, void *param2) { return -1; }
240 | virtual CALC_INT_PTR OnInput(int param1, void *param2) { return -1; }
241 | virtual CALC_INT_PTR OnCtrlColorDlgItem(int param1, void *param2) { return -1; }
242 |
243 | public:
244 | typedef CALC_INT_PTR (CalcDialog::*CalcDialogCallback)(int param1, void *param2);
245 | CalcDialogCallback *msg_tbl;
246 | protected:
247 | DLGHANDLE hdlg;
248 | };
249 |
250 | ///////////////////////////////////////////////////////////////////////////////////
251 |
252 | class CalcDialogFuncs
253 | {
254 | public:
255 | virtual void EnableRedraw(DLGHANDLE, bool) = 0;
256 | virtual void ResizeDialog(DLGHANDLE, const CalcCoord & dims) = 0;
257 | virtual void RedrawDialog(DLGHANDLE) = 0;
258 | virtual void Close(DLGHANDLE, int exitcode) = 0;
259 | virtual void GetDlgRect(DLGHANDLE, CalcRect *rect) = 0;
260 |
261 | virtual void GetDlgItemShort(DLGHANDLE, int id, CalcDialogItem *item) = 0;
262 | virtual void SetDlgItemShort(DLGHANDLE, int id, const CalcDialogItem & item) = 0;
263 | virtual void SetItemPosition(DLGHANDLE, int id, const CalcRect & rect) = 0;
264 | virtual int GetFocus(DLGHANDLE) = 0;
265 | virtual void SetFocus(DLGHANDLE, int id) = 0;
266 | virtual void EditChange(DLGHANDLE, int id, const CalcDialogItem & item) = 0;
267 | virtual void SetSelection(DLGHANDLE, int id, const CalcEditorSelect & sel) = 0;
268 | virtual void SetCursorPos(DLGHANDLE, int id, const CalcCoord & pos) = 0;
269 | virtual void GetText(DLGHANDLE, int id, std::wstring &str) = 0;
270 | virtual void SetText(DLGHANDLE, int id, const std::wstring & str) = 0;
271 | virtual void AddHistory(DLGHANDLE, int id, const std::wstring & str) = 0;
272 | virtual bool IsChecked(DLGHANDLE, int id) = 0;
273 |
274 | public:
275 | virtual DLGHANDLE DialogInit(int id, int X1, int Y1, int X2, int Y2, const wchar_t *HelpTopic,
276 | struct CalcDialogItem *Item, unsigned int ItemsNumber,
277 | CALCDLGPROC dlgProc) = 0;
278 | virtual intptr_t DialogRun(DLGHANDLE) = 0;
279 | virtual void DialogFree(DLGHANDLE) = 0;
280 | virtual CALC_INT_PTR DefDlgProc(DLGHANDLE hdlg, int msg, int param1, void *param2) = 0;
281 | virtual void ConvertToDlgItem(void *, CalcDialogItem *) = 0;
282 | virtual void ConvertFromDlgItem(const CalcDialogItem *, void *) = 0;
283 |
284 | virtual CALC_INT_PTR PreProcessMessage(DLGHANDLE hdlg, int msg, int ¶m1, void * ¶m2) = 0;
285 | virtual CALC_INT_PTR PostProcessMessage(DLGHANDLE hdlg, int msg, CALC_INT_PTR &ret, int ¶m1, void * ¶m2) = 0;
286 |
287 | virtual CalcDialog::CalcDialogCallback *GetMessageTable() = 0;
288 | };
289 |
290 | ///////////////////////////////////////////////////////////////////////////////////
291 |
292 | class CalcApi
293 | {
294 | public:
295 | virtual void GetPluginInfo(void *pinfo, const wchar_t *name) = 0;
296 | virtual bool IsOpenedFromEditor(void *oinfo, int OpenFrom) = 0;
297 | virtual const wchar_t *GetMsg(int MsgId) = 0;
298 | virtual CalcDialogFuncs *GetDlgFuncs() = 0;
299 |
300 | virtual intptr_t Message(unsigned long Flags, const wchar_t *HelpTopic, const wchar_t * const *Items,
301 | int ItemsNumber, int ButtonsNumber) = 0;
302 |
303 | virtual intptr_t Menu(int X, int Y, int MaxHeight, unsigned long long Flags,
304 | const wchar_t *Title, const wchar_t *HelpTopic,
305 | const std::vector & Items) = 0;
306 |
307 | virtual void EditorGet(CalcEditorGetString *string, CalcEditorInfo *info) = 0;
308 | virtual void EditorSelect(const CalcEditorSelect & sel) = 0;
309 | virtual void EditorInsert(const wchar_t *text) = 0;
310 | virtual void EditorRedraw() = 0;
311 |
312 | virtual void GetDlgColors(CalcColor *edit_color, CalcColor *sel_color, CalcColor *highlight_color) = 0;
313 |
314 | virtual int GetCmdLine(std::wstring &cmd) = 0;
315 | virtual void SetCmdLine(const std::wstring & cmd) = 0;
316 |
317 | virtual bool SettingsBegin() = 0;
318 | virtual bool SettingsEnd() = 0;
319 | virtual bool SettingsGet(const wchar_t *name, std::wstring *sval, unsigned long *ival) = 0;
320 | virtual bool SettingsSet(const wchar_t *name, const std::wstring *sval, const unsigned long *ival) = 0;
321 |
322 | virtual const wchar_t *GetModuleName() = 0;
323 |
324 | };
325 |
326 | extern CalcApi *CreateApiFar3(void *info);
327 | extern void GetGlobalInfoFar3(void *ginfo, const wchar_t *name);
328 |
329 | extern CalcApi *api;
330 |
331 | #endif
332 |
--------------------------------------------------------------------------------
/src/plugcalc/calc.h:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Cail Lomecb (Igor Ruskih) 1999-2001
3 | // Copyright (c) uncle-vunkis 2009-2012
4 | // You can use, modify, distribute this code or any other part
5 | // of this program in sources or in binaries only according
6 | // to License (see /doc/license.txt for more information).
7 | //
8 |
9 | #ifndef _CALC_H_
10 | #define _CALC_H_
11 |
12 | enum
13 | {
14 | CALC_DIALOG_MAIN,
15 | CALC_DIALOG_UNITS,
16 | CALC_DIALOG_CONFIG,
17 | };
18 |
19 | void CalcStartup();
20 | void CalcExit();
21 | bool CalcOpen(bool editor);
22 | bool CalcConfig();
23 |
24 | void InitDynamicData();
25 | void DeInitDynamicData();
26 |
27 | void EditorDialog();
28 | void ShellDialog();
29 | bool ConfigDialog();
30 | int CalcMenu(int c);
31 | void ShowDialog(int no);
32 | void CalcShowDialog();
33 |
34 | void SetActive(int Act);
35 |
36 | #endif
37 |
--------------------------------------------------------------------------------
/src/plugcalc/calc.rc:
--------------------------------------------------------------------------------
1 | #pragma code_page(65001)
2 | #include
3 | #include "version.h"
4 |
5 | LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
6 | VS_VERSION_INFO VERSIONINFO
7 | FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
8 | FILEFLAGS 0
9 |
10 | #ifdef _DEBUG
11 | | VS_FF_PRERELEASE | VS_FF_DEBUG
12 | #endif
13 |
14 | FILEOS VOS_NT_WINDOWS32
15 | FILETYPE VFT_APP
16 |
17 | FILEVERSION PLUGIN_VER_MAJOR,PLUGIN_VER_MINOR,PLUGIN_VER_PATCH,0
18 | PRODUCTVERSION PLUGIN_VER_MAJOR,PLUGIN_VER_MINOR,PLUGIN_VER_PATCH,0
19 |
20 | BEGIN
21 | BLOCK "StringFileInfo"
22 | BEGIN
23 | BLOCK "040904B0"
24 | BEGIN
25 | VALUE "FileDescription", PLUGIN_DESC
26 | VALUE "FileVersion", PLUGIN_VERSION
27 | VALUE "LegalCopyright", PLUGIN_COPYRIGHT
28 | VALUE "OriginalFilename", PLUGIN_FILENAME
29 | VALUE "ProductName", PLUGIN_NAME
30 | VALUE "ProductVersion", PLUGIN_VERSION
31 | END
32 | END
33 | BLOCK "VarFileInfo"
34 | BEGIN
35 | VALUE "Translation", 0x0409, 1200
36 | END
37 | END
38 |
--------------------------------------------------------------------------------
/src/plugcalc/config.cpp:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Cail Lomecb (Igor Ruskih) 1999-2001
3 | // Copyright (c) uncle-vunkis 2009-2011
4 | // You can use, modify, distribute this code or any other part
5 | // of this program in sources or in binaries only according
6 | // to License (see /doc/license.txt for more information).
7 | //
8 |
9 | #include
10 | #include
11 | #include
12 | #include "api.h"
13 | #include "newparse.h"
14 | #include "calc.h"
15 | #include "config.h"
16 | #include "messages.h"
17 |
18 | CalcProperties props;
19 |
20 | enum CALC_PARAM_CHECK_TYPE
21 | {
22 | CALC_PARAM_CHECK_BOOL,
23 | CALC_PARAM_CHECK_RADIO,
24 | CALC_PARAM_CHECK_LINES,
25 | CALC_PARAM_CHECK_PERIOD,
26 | CALC_PARAM_CHECK_DECIMAL,
27 | CALC_PARAM_CHECK_ARGS,
28 | CALC_PARAM_CHECK_DELIM,
29 | CALC_PARAM_CHECK_LENGTH,
30 | CALC_PARAM_CHECK_FRAC,
31 | };
32 |
33 | static const struct
34 | {
35 | int *ival;
36 | wchar_t *sval; // if sval != nullptr then (int)ival = max strlen
37 |
38 | const wchar_t *reg_name;
39 | const wchar_t *def_value;
40 |
41 | CALC_PARAM_CHECK_TYPE check_type;
42 | } param_table[] =
43 | {
44 | { &props.auto_update, nullptr, L"autoUpdate", L"1", CALC_PARAM_CHECK_BOOL },
45 | { &props.case_sensitive, nullptr, L"caseSensitive", L"0", CALC_PARAM_CHECK_BOOL },
46 | { &props.pad_zeroes, nullptr, L"padZeroes", L"1", CALC_PARAM_CHECK_BOOL },
47 | /*{ &props.right_align, nullptr, L"rightAlign", L"0", CALC_PARAM_CHECK_BOOL },*/
48 |
49 | { &props.history_hide, nullptr, L"historyHide", L"1", CALC_PARAM_CHECK_RADIO },
50 | { &props.history_above, nullptr, L"historyAbove", L"0", CALC_PARAM_CHECK_RADIO },
51 | { &props.history_below, nullptr, L"historyBelow", L"0", CALC_PARAM_CHECK_RADIO },
52 | { &props.history_lines, nullptr, L"historyLines", L"8", CALC_PARAM_CHECK_LINES },
53 | { &props.autocomplete, nullptr, L"autoComplete", L"0", CALC_PARAM_CHECK_BOOL },
54 |
55 | { &props.use_regional, nullptr, L"useRegional", L"0", CALC_PARAM_CHECK_BOOL },
56 | { (int *)sizeof(props.decimal_point), props.decimal_point, L"decimalPoint", L".", CALC_PARAM_CHECK_DECIMAL },
57 | { (int *)sizeof(props.args), props.args, L"Args", L",", CALC_PARAM_CHECK_ARGS },
58 | { &props.use_delim, nullptr, L"useDelim", L"0", CALC_PARAM_CHECK_BOOL },
59 | { (int *)sizeof(props.digit_delim), props.digit_delim, L"digitDelim", L"'", CALC_PARAM_CHECK_DELIM },
60 |
61 | // registry-only
62 | { &props.max_period, nullptr, L"maxPeriod", L"10", CALC_PARAM_CHECK_PERIOD },
63 | { &props.result_length, nullptr, L"resultLength", L"128", CALC_PARAM_CHECK_LENGTH },
64 | { &props.rep_fraction_max_start, nullptr, L"repFractionMaxStart", L"32", CALC_PARAM_CHECK_FRAC },
65 | { &props.rep_fraction_max_period, nullptr, L"repFractionMaxPeriod", L"128", CALC_PARAM_CHECK_FRAC },
66 | { &props.cont_fraction_max, nullptr, L"contFractionMax", L"64", CALC_PARAM_CHECK_FRAC },
67 |
68 | { nullptr, nullptr, L"", nullptr, CALC_PARAM_CHECK_BOOL },
69 | };
70 |
71 | static const struct
72 | {
73 | CalcDialogItemTypes Type;
74 | int X1, Y1, X2, Y2; // if Y1 == 0, then Y1=last_Y1; if Y1 == -1, then Y1=last_Y1+1
75 | unsigned long long Flags;
76 | int name_ID;
77 | int *prop_ivalue;
78 | wchar_t *prop_svalue;
79 | } dlgItems[] =
80 | {
81 | { CALC_DI_DOUBLEBOX, 3, 1, 54, 14, 0, mConfigName, nullptr, nullptr },
82 | { CALC_DI_CHECKBOX, 5, -1, 0, 0, CALC_DIF_FOCUS, mConfigShowResults, &props.auto_update, nullptr },
83 | { CALC_DI_CHECKBOX, 5, -1, 0, 0, 0, mConfigCaseSensitive, &props.case_sensitive, nullptr },
84 |
85 | { CALC_DI_CHECKBOX, 5, -1, 0, 0, 0, mConfigPadZeroes, &props.pad_zeroes, nullptr },
86 | #if 0
87 | { CALC_DI_CHECKBOX, 5, -1, 0, 0, 0, mConfigRightAligned, &props.right_align, nullptr },
88 |
89 | { CALC_DI_TEXT, 41, 0, 0, 0, CALC_DIF_DISABLE, mConfigMaxPeriod, nullptr, nullptr },
90 | { CALC_DI_FIXEDIT, 53, 0, 55, 0, CALC_DIF_DISABLE, 0, &props.max_period, nullptr },
91 | #endif
92 |
93 | { CALC_DI_TEXT, 5, -1, 0, 0, CALC_DIF_BOXCOLOR|CALC_DIF_SEPARATOR, mConfigHistory, nullptr, nullptr },
94 |
95 | { CALC_DI_RADIOBUTTON, 5, -1, 0, 0, CALC_DIF_GROUP, mConfigHide, &props.history_hide, nullptr },
96 | { CALC_DI_RADIOBUTTON, 19, 0, 0, 0, CALC_DIF_DISABLE, mConfigShowAbove, &props.history_above, nullptr },
97 | { CALC_DI_RADIOBUTTON, 37, 0, 0, 0, CALC_DIF_DISABLE, mConfigShowBelow, &props.history_below, nullptr },
98 |
99 | { CALC_DI_FIXEDIT, 5, -1, 7, 0, CALC_DIF_DISABLE, 0, &props.history_lines, nullptr },
100 | { CALC_DI_TEXT, 9, 0, 0, 0, CALC_DIF_DISABLE, mConfigLines, nullptr, nullptr },
101 | { CALC_DI_CHECKBOX, 19, 0, 0, 0, 0, mConfigAutocomplete, &props.autocomplete, nullptr },
102 |
103 | { CALC_DI_TEXT, 5, -1, 0, 0, CALC_DIF_BOXCOLOR|CALC_DIF_SEPARATOR, mConfigDelimiters, nullptr, nullptr },
104 |
105 | { CALC_DI_TEXT, 5, -1, 0, 0, 0, mConfigDecimalSymbol, nullptr, nullptr },
106 | { CALC_DI_FIXEDIT, 22, 0, 22, 0 , 0, 0, (int *)sizeof(props.decimal_point), props.decimal_point },
107 | { CALC_DI_CHECKBOX, 25, 0, 0, 0, 0, mConfigDigitDelimiter, &props.use_delim, nullptr },
108 | { CALC_DI_FIXEDIT, 51, 0, 51, 0, 0, 0, (int *)sizeof(props.digit_delim), props.digit_delim },
109 |
110 | { CALC_DI_TEXT, 5, -1, 0, 0, 0, mConfigArguments, nullptr, nullptr },
111 | { CALC_DI_FIXEDIT, 22, 0, 22, 0, 0, 0, (int *)sizeof(props.args), props.args },
112 | { CALC_DI_CHECKBOX, 25, 0, 0, 0, 0, mConfigUseRegional, &props.use_regional, nullptr },
113 |
114 | { CALC_DI_TEXT, 5, -1, 0, 0, CALC_DIF_BOXCOLOR|CALC_DIF_SEPARATOR, 0, nullptr, nullptr },
115 |
116 | { CALC_DI_BUTTON, 0, -1, 0, 0, CALC_DIF_CENTERGROUP | CALC_DIF_DEFAULTBUTTON, mOk, nullptr, nullptr },
117 | { CALC_DI_BUTTON, 0, 0, 0, 0, CALC_DIF_CENTERGROUP, mCancel, nullptr, nullptr },
118 | };
119 |
120 |
121 | BOOL InitConfig()
122 | {
123 | return TRUE;
124 | }
125 |
126 | BOOL LoadConfig()
127 | {
128 | api->SettingsBegin();
129 | for (int i = 0; param_table[i].ival; i++)
130 | {
131 | if (param_table[i].sval)
132 | {
133 | std::wstring str;
134 | if (api->SettingsGet(param_table[i].reg_name, &str, nullptr))
135 | wcsncpy(param_table[i].sval, str.c_str(), (int)param_table[i].ival / sizeof(wchar_t));
136 | else
137 | wcsncpy(param_table[i].sval, param_table[i].def_value, (int)param_table[i].ival / sizeof(wchar_t));
138 | } else
139 | {
140 | if (!api->SettingsGet(param_table[i].reg_name, nullptr, (DWORD *)param_table[i].ival))
141 | *param_table[i].ival = _wtoi(param_table[i].def_value);
142 | }
143 | }
144 | api->SettingsEnd();
145 | return TRUE;
146 | }
147 |
148 | BOOL SaveConfig()
149 | {
150 | api->SettingsBegin();
151 | for (int i = 0; param_table[i].ival; i++)
152 | {
153 | if (param_table[i].sval)
154 | {
155 | std::wstring str = param_table[i].sval;
156 | api->SettingsSet(param_table[i].reg_name, &str, nullptr);
157 | }
158 | else
159 | {
160 | api->SettingsSet(param_table[i].reg_name, nullptr, (DWORD *)param_table[i].ival);
161 | }
162 | }
163 | api->SettingsEnd();
164 | return TRUE;
165 | }
166 |
167 | BOOL CheckConfig()
168 | {
169 | wchar_t decimal = 0, args = 0;
170 | for (int i = 0; param_table[i].ival; i++)
171 | {
172 | int *v = param_table[i].ival;
173 | wchar_t *s = param_table[i].sval;
174 | switch (param_table[i].check_type)
175 | {
176 | case CALC_PARAM_CHECK_BOOL:
177 | *v = (*v != 0) ? 1 : 0;
178 | break;
179 | case CALC_PARAM_CHECK_RADIO:
180 | *v = std::min(std::max(*v, 0), 2);
181 | break;
182 | case CALC_PARAM_CHECK_LINES:
183 | *v = std::min(std::max(*v, 0), 10);
184 | break;
185 | case CALC_PARAM_CHECK_PERIOD:
186 | *v = std::min(std::max(*v, 0), 100);
187 | break;
188 | case CALC_PARAM_CHECK_LENGTH:
189 | case CALC_PARAM_CHECK_FRAC:
190 | *v = std::min(std::max(*v, 16), 512);
191 | break;
192 | case CALC_PARAM_CHECK_DECIMAL:
193 | if (props.use_regional)
194 | {
195 | GetLocaleInfo(GetSystemDefaultLCID(), LOCALE_SDECIMAL, s, 2);
196 | }
197 | if (wcschr(L".,", s[0]) == nullptr)
198 | s[0] = '.';
199 | decimal = s[0];
200 | s[1] = '\0';
201 | break;
202 | case CALC_PARAM_CHECK_ARGS:
203 | if (s[0] == '\0' || wcschr(L",;.:", s[0]) == nullptr)
204 | s[0] = ',';
205 | if (s[0] == decimal)
206 | s[0] = (decimal == L',') ? ';' : ',';
207 | args = s[0];
208 | s[1] = '\0';
209 | break;
210 | case CALC_PARAM_CHECK_DELIM:
211 | if (props.use_regional)
212 | {
213 | GetLocaleInfo(GetSystemDefaultLCID(), LOCALE_SMONTHOUSANDSEP , s, 2);
214 | }
215 | if (wcschr(L" ,'`\xa0", s[0]) == nullptr)
216 | s[0] = ' ';
217 | if (s[0] == decimal || s[0] == args)
218 | s[0] = ' ';
219 |
220 | s[1] = '\0';
221 | break;
222 | }
223 | }
224 | return TRUE;
225 | }
226 |
227 | class DlgConfig : public CalcDialog
228 | {
229 |
230 | };
231 |
232 | bool ConfigDialog()
233 | {
234 | const int num = sizeof(dlgItems)/sizeof(dlgItems[0]);
235 | wchar_t tmpnum[num][32];
236 |
237 | int ExitCode, ok_id = -2;
238 |
239 | auto *dlg = new CalcDialogItem[num];
240 |
241 | int Y1 = 0;
242 | for (int i = 0; i < num; i++)
243 | {
244 | dlg[i].Type = dlgItems[i].Type; dlg[i].Flags = dlgItems[i].Flags;
245 | dlg[i].X1 = dlgItems[i].X1; dlg[i].X2 = dlgItems[i].X2;
246 |
247 | dlg[i].Y1 = (dlgItems[i].Y1 == -1) ? (Y1+1) : ((dlgItems[i].Y1 == 0) ? Y1 : dlgItems[i].Y1);
248 | dlg[i].Y2 = (dlgItems[i].Type == CALC_DI_FIXEDIT) ? dlg[i].Y1 : dlgItems[i].Y2;
249 |
250 | Y1 = dlg[i].Y1;
251 |
252 | if (dlgItems[i].name_ID == mOk)
253 | ok_id = i;
254 |
255 | if (dlgItems[i].Type == CALC_DI_FIXEDIT)
256 | {
257 | if (dlgItems[i].prop_svalue)
258 | dlg[i].PtrData = dlgItems[i].prop_svalue;
259 | else if (dlgItems[i].prop_ivalue)
260 | {
261 | _itow(*dlgItems[i].prop_ivalue, tmpnum[i], 10);
262 | dlg[i].PtrData = tmpnum[i];
263 | }
264 | }
265 | else
266 | {
267 | dlg[i].PtrData = dlgItems[i].name_ID ? api->GetMsg(dlgItems[i].name_ID) : L"";
268 | if (dlgItems[i].prop_ivalue && !dlgItems[i].prop_svalue)
269 | dlg[i].Selected = *dlgItems[i].prop_ivalue;
270 | }
271 | }
272 |
273 | dlg[0].Y2 = Y1 + 1;
274 |
275 | DlgConfig cfg;
276 | if (!cfg.Init(CALC_DIALOG_CONFIG, -1, -1, 58, 15, L"Config", dlg, num))
277 | return false;
278 |
279 | ExitCode = (int)cfg.Run();
280 |
281 | if (ExitCode == ok_id)
282 | {
283 | for (int i = 0; i < num; i++)
284 | {
285 | std::wstring str;
286 | if (dlgItems[i].prop_svalue)
287 | {
288 | cfg.GetText(i, str);
289 | wcsncpy(dlgItems[i].prop_svalue, str.c_str(), (int)dlgItems[i].prop_ivalue / sizeof(wchar_t));
290 | }
291 | else if (dlgItems[i].prop_ivalue)
292 | {
293 | if (dlgItems[i].Type == CALC_DI_FIXEDIT)
294 | {
295 | cfg.GetText(i, str);
296 | *dlgItems[i].prop_ivalue = _wtoi(str.c_str());
297 | }
298 | else
299 | {
300 | *dlgItems[i].prop_ivalue = cfg.IsChecked(i) ? 1 : 0;
301 | }
302 | }
303 | }
304 | }
305 |
306 | delete [] dlg;
307 |
308 | return true;
309 | }
310 |
311 |
--------------------------------------------------------------------------------
/src/plugcalc/config.h:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Cail Lomecb (Igor Ruskih) 1999-2001
3 | // Copyright (c) uncle-vunkis 2009-2011
4 | // You can use, modify, distribute this code or any other part
5 | // of this program in sources or in binaries only according
6 | // to License (see /doc/license.txt for more information).
7 | //
8 |
9 | #ifndef _CALC_CONFIG_H_
10 | #define _CALC_CONFIG_H_
11 |
12 | // configuration
13 |
14 | BOOL InitConfig();
15 | BOOL LoadConfig();
16 | BOOL CheckConfig();
17 | BOOL SaveConfig();
18 |
19 | struct CalcProperties
20 | {
21 | int auto_update;
22 | int case_sensitive;
23 | int max_period;
24 | int pad_zeroes;
25 | int right_align;
26 |
27 | int history_hide;
28 | int history_above;
29 | int history_below;
30 | int history_lines;
31 | int autocomplete;
32 |
33 | int use_regional, use_delim;
34 | wchar_t decimal_point[2];
35 | wchar_t args[2];
36 | wchar_t digit_delim[2];
37 |
38 | int result_length;
39 | int rep_fraction_max_start;
40 | int rep_fraction_max_period;
41 | int cont_fraction_max;
42 | };
43 |
44 | extern CalcProperties props;
45 |
46 | #endif // of _CALC_CONFIG_H_
47 |
--------------------------------------------------------------------------------
/src/plugcalc/messages.h:
--------------------------------------------------------------------------------
1 | #ifndef _CALC_MESSAGES_H_
2 | #define _CALC_MESSAGES_H_
3 |
4 | enum
5 | {
6 | mName, mMenuName, mConfigName, mLang,
7 |
8 | mDialogs,
9 | mOk, mCancel,
10 |
11 | mConfigShowResults,
12 | mConfigCaseSensitive,
13 | mConfigShowPeriodic,
14 | mConfigMaxPeriod,
15 | mConfigPadZeroes,
16 | mConfigRightAligned,
17 | mConfigHistory,
18 | mConfigHide,
19 | mConfigShowAbove,
20 | mConfigShowBelow,
21 | mConfigLines,
22 | mConfigAutocomplete,
23 | mConfigDelimiters,
24 | mConfigDecimalSymbol,
25 | mConfigUseRegional,
26 | mConfigArguments,
27 | mConfigDigitDelimiter,
28 |
29 | mNoError,
30 | mError1, mError2, mError3, mError4, mError5, mError6, mError7, mError8,
31 | };
32 |
33 |
34 | #endif
35 |
--------------------------------------------------------------------------------
/src/plugcalc/newparse.h:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) uncle-vunkis 2009-2012
3 | // You can use, modify, distribute this code or any other part
4 | // of this program in sources or in binaries only according
5 | // to License (see /doc/license.txt for more information).
6 | //
7 |
8 | #ifndef CALC_NEWPARSE_H
9 | #define CALC_NEWPARSE_H
10 |
11 | #include
12 | #include
13 | #undef min
14 | #undef max
15 | #include
16 |
17 | #include "sarg.h"
18 | #include "syntax.h"
19 |
20 |
21 | enum CALC_ERROR
22 | {
23 | ERR_OK = 0,
24 | ERR_ALL, ERR_EXPR, ERR_TYPE,
25 | ERR_PARAM, ERR_BRACK, ERR_ZERO, ERR_FLOW, ERR_TOOLONG
26 | };
27 |
28 | enum CALC_CONV_TYPE
29 | {
30 | CALC_CONV_DECPT = -1,
31 | CALC_CONV_DECEXP = -2,
32 | CALC_CONV_ENTER = -3,
33 | CALC_CONV_UNITS = -4,
34 | };
35 |
36 | class CalcAddonPart
37 | {
38 | public:
39 | CalcAddonPart()
40 | {
41 | parser = nullptr;
42 | }
43 | CalcAddonPart(const CalcAddonPart & p);
44 |
45 | ~CalcAddonPart();
46 |
47 | void Parse(bool no_args = false);
48 |
49 | public:
50 | friend class CalcParser;
51 | std::wstring expr;
52 | CalcParser *parser; /// pre-parsed pattern expression
53 | int str_pos; /// abs. string position for replacement
54 | };
55 |
56 | class CalcAddon
57 | {
58 | public:
59 | CalcAddon()
60 | {
61 | radix = 10;
62 | flags = CALC_ADDON_FLAG_NONE;
63 | }
64 |
65 | public:
66 | std::wstring name;
67 | std::wstring expr;
68 |
69 | int radix, flags;
70 |
71 | std::vector parts;
72 | };
73 |
74 | struct SDialogElem
75 | {
76 | wchar_t Name[64];
77 | int Type;
78 | Big scale;
79 | int addon_idx;
80 | int column_idx;
81 |
82 | CalcAddonPart *input, *scale_expr;
83 |
84 | // PEditObject Edit;
85 | SDialogElem *Next;
86 | SDialogElem();
87 | ~SDialogElem();
88 | };
89 |
90 | typedef SDialogElem *PDialogElem;
91 |
92 | struct SDialogData
93 | {
94 | wchar_t Name[64];
95 | int num;
96 | SDialogElem *Elem;
97 | SDialogData *Next;
98 | SDialogData();
99 | ~SDialogData();
100 | };
101 |
102 | typedef SDialogData *PDialogData;
103 |
104 | class CalcParser : public MathExpressionBase
105 | {
106 | typedef MathExpressionBase mybase;
107 |
108 | friend wchar_t *convertToString(SArg val, int type_idx, int num_lim, bool append_suffix, bool pad_zeroes, bool group_delim);
109 | friend void print_repeating_decimal(std::wstring & s, SArg val, int num_lim, bool group_delim);
110 | friend void print_continued_decimal(std::wstring & s, SArg val, int num_lim, bool group_delim);
111 | friend int CalcMenu(int c);
112 | friend void SetUnitsDialogDims();
113 | friend void ShowUnitsDialog(int no);
114 | friend struct SArg;
115 | friend class CalcAddonPart;
116 |
117 | public:
118 | typedef SArg value_type;
119 |
120 | CalcParser();
121 | CalcParser(const CalcParser & p);
122 |
123 | ~CalcParser();
124 |
125 | static bool InitTables(int rep_fraction_max_start, int rep_fraction_max_period, int cont_fraction_max);
126 | static bool ProcessData(PSgmlEl BaseRc, bool case_sensitive);
127 | static void FillDialogData(PSgmlEl Base, bool case_sensitive, const wchar_t *lang_name);
128 | static bool SetDelims(wchar_t decimal, wchar_t args, wchar_t digit);
129 | static bool ProcessAddons();
130 | static bool ProcessDialogData();
131 | static int GetNumDialogs();
132 |
133 | /// Add all functs, ops, consts
134 | static bool AddAll(bool add_user_ops_and_funcs = true);
135 |
136 | static void GetFraction(Big b, BigInt *numer, BigInt *denom);
137 | static void RoundUp(Big &b);
138 |
139 | SArg Parse(const wchar_t* str, bool case_sensitive);
140 |
141 | CALC_ERROR GetError();
142 |
143 | public:
144 | /// parsed addons
145 | static std::vector addons;
146 | static unsigned main_addons_num;
147 | static wchar_t delim_decimal, delim_args, delim_digit;
148 |
149 | static ttmath::Conv from_convs[17], to_convs[17];
150 |
151 | protected:
152 |
153 | bool parse_number(SArg *value, const wchar_t *curpos, wchar_t **endptr);
154 |
155 | static bool FillSet(PSgmlEl set, bool case_sensitive);
156 | static bool AddLexem(PSyntax &syntax, PSgmlEl Ch, PSgmlEl set, bool case_sensitive);
157 | static int DelSpaces(wchar_t *str);
158 |
159 | static std::wstring ReplaceDelims(const wchar_t *str);
160 |
161 | bool SetVar(wchar_t *name, SArg value);
162 |
163 | static PSyntax Consts;
164 | static PSyntax Ops;
165 | static PSyntax Functs;
166 | static PSyntax Addons;
167 | static PSyntax Numerals;
168 | static PVars Vars;
169 |
170 | protected:
171 |
172 | static SArg builtin_binary_op(const SArg & op0, const SArg & op1);
173 | static SArg builtin_unary_not(const SArg & op);
174 |
175 | static SArg binary_op(const SArg & op0, const SArg & op1);
176 | static SArg unary_op(const SArg & op0);
177 |
178 | class UserFunctionList : public std::vector
179 | {
180 | public:
181 | UserFunctionList() = default;
182 | ~UserFunctionList();
183 | };
184 |
185 | protected:
186 | CALC_ERROR math_error;
187 | string func_name;
188 |
189 | static std::unordered_map user_bin_ops, user_un_ops;
190 |
191 | protected:
192 | static UserFunctionList *user_funcs;
193 |
194 | static FunctionList allFunctions;
195 | static NamedConstantList allNamedConstants;
196 | static UnaryOperationTable allUnaryOpTable;
197 | static BinaryOperationTable allBinaryOpTable;
198 |
199 | static std::vector rep_fraction_coefs;
200 | static std::vector rep_mul1, rep_mul2;
201 | static Big rep_fraction_thr, rep_fraction_thr2;
202 | static int rep_fraction_max_start, rep_fraction_max_period;
203 | static int cont_fraction_max;
204 |
205 | static PDialogData DialogData;
206 | static int DialogsNum;
207 |
208 | };
209 |
210 | /// if type_idx >= 0 then it's index to addons, or type enum if < 0
211 | wchar_t *convertToString(const SArg & val, int type_idx, int num_lim = 0, bool append_suffix = false, bool pad_zeroes = true, bool group_delim = true, CALC_ERROR *error_code = nullptr);
212 |
213 | #endif // of CALC_NEWPARSE_H
214 |
--------------------------------------------------------------------------------
/src/plugcalc/plugcalc.def:
--------------------------------------------------------------------------------
1 | LIBRARY
2 | EXPORTS
3 | OpenW
4 | SetStartupInfoW
5 | GetGlobalInfoW
6 | GetPluginInfoW
7 | ConfigureW
8 | ExitFARW
--------------------------------------------------------------------------------
/src/plugcalc/sarg.h:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Cail Lomecb (Igor Ruskih) 1999-2001
3 | // Copyright (c) uncle-vunkis 2009-2011
4 | // You can use, modify, distribute this code or any other part
5 | // of this program in sources or in binaries only according
6 | // to License (see /doc/license.txt for more information).
7 | //
8 |
9 |
10 | #include
11 |
12 | #ifndef SARG_H
13 | #define SARG_H
14 |
15 | typedef ttmath::Big<1,26> Big;
16 | typedef ttmath::Int<24> BigInt;
17 | typedef ttmath::UInt<24> BigUInt;
18 |
19 | enum EArgType
20 | {
21 | SA_BIG,
22 | SA_INT64, SA_UINT64, SA_INT, SA_SHORT, SA_CHAR,
23 | SA_UINT, SA_USHORT, SA_BYTE, SA_DOUBLE, SA_FLOAT,
24 | };
25 |
26 | struct SArg
27 | {
28 | private:
29 | EArgType type;
30 | bool empty;
31 | int size;
32 | union
33 | {
34 | __int64 v_int64;
35 | int v_int;
36 | short v_short;
37 | char v_char;
38 | unsigned __int64 v_uint64;
39 | unsigned int v_uint;
40 | unsigned short v_ushort;
41 | unsigned char v_byte;
42 | double v_dbl;
43 | float v_flt;
44 |
45 | } arg;
46 |
47 | // XXX:
48 | Big v_big;
49 |
50 | public:
51 | SArg();
52 | ~SArg();
53 | SArg(const SArg &a);
54 |
55 | SArg(__int64 var);
56 | SArg(bool var);
57 | SArg(short var);
58 | SArg(char var);
59 | SArg(int var);
60 | SArg(unsigned __int64 var);
61 | SArg(unsigned int var);
62 | SArg(unsigned short var);
63 | SArg(unsigned char var);
64 | SArg(double var);
65 | SArg(float var);
66 |
67 | SArg(const Big & var);
68 |
69 |
70 |
71 | bool isempty() const;
72 | int varsize() const;
73 | EArgType gettype();
74 |
75 | bool IsFixedLength() const;
76 |
77 | SArg &operator=(const SArg & op);
78 | // XXX:
79 | //SArg &operator=(double op);
80 |
81 | friend SArg operator+ (const SArg & op1, const SArg & op2);
82 | friend SArg operator- (const SArg & op1, const SArg & op2);
83 | friend SArg operator* (const SArg & op1, const SArg & op2);
84 | friend SArg operator/ (const SArg & op1, const SArg & op2);
85 | friend SArg operator| (const SArg & op1, const SArg & op2);
86 | friend SArg operator& (const SArg & op1, const SArg & op2);
87 | friend SArg operator^ (const SArg & op1, const SArg & op2);
88 | friend SArg operator>> (const SArg & op1, int n);
89 | friend SArg operator<< (const SArg & op1, int n);
90 |
91 | friend bool operator== (const SArg & op1, const SArg & op2);
92 | friend bool operator!= (const SArg & op1, const SArg & op2);
93 | friend bool operator> (const SArg & op1, const SArg & op2);
94 | friend bool operator< (const SArg & op1, const SArg & op2);
95 |
96 | SArg Ror(const SArg & op) const;
97 | SArg Rol(const SArg & op) const;
98 |
99 | SArg Pow(const SArg & op) const;
100 |
101 | SArg operator- ();
102 | SArg operator% (const SArg & op) const;
103 |
104 |
105 | SArg operator~ () const;
106 |
107 |
108 | SArg operator+= (const SArg & op);
109 | SArg operator-= (const SArg & op);
110 |
111 | operator __int64() const;
112 | operator int() const;
113 | operator short() const;
114 | operator char() const;
115 | operator unsigned __int64() const;
116 | operator unsigned int() const;
117 | operator unsigned short() const;
118 | operator unsigned char() const;
119 | operator float() const;
120 | operator double() const;
121 | operator bool() const;
122 |
123 | Big GetBig() const;
124 | Big GetInt() const;
125 |
126 | // Print fixed length numbers
127 | bool Print(std::wstring &str, int radix, int num_delim, wchar_t delim_digit);
128 |
129 | static Big GreatestCommonDiv(Big numer, Big denom);
130 |
131 | public:
132 |
133 | static SArg _factor(const SArg & op1);
134 | static SArg _frac(const SArg & op1);
135 | static SArg _floor(const SArg & op1);
136 | static SArg _ceil(const SArg & op1);
137 | static SArg _sin(const SArg & op1);
138 | static SArg _cos(const SArg & op1);
139 | static SArg _tan(const SArg & op1);
140 | static SArg _arctan(const SArg & op1);
141 | static SArg _ln(const SArg & op1);
142 | static SArg _rnd();
143 | //static SArg _sum", 1 },
144 | //static SArg _avr", 1 },
145 | static SArg _if(const SArg & op1, const SArg & op2, const SArg & op3);
146 |
147 | static SArg _f2b(const SArg & op1);
148 | static SArg _d2b(const SArg & op1);
149 | static SArg _b2f(const SArg & op1);
150 | static SArg _b2d(const SArg & op1);
151 | static SArg _finf();
152 | static SArg _fnan();
153 |
154 | static SArg _numer(const SArg & op1);
155 | static SArg _denom(const SArg & op1);
156 | static SArg _gcd(const SArg & op1, const SArg & op2);
157 |
158 | static SArg to_int64(const SArg & op1);
159 | static SArg to_uint64(const SArg & op1);
160 | static SArg to_int(const SArg & op1);
161 | static SArg to_uint(const SArg & op1);
162 | static SArg to_short(const SArg & op1);
163 | static SArg to_ushort(const SArg & op1);
164 | static SArg to_char(const SArg & op1);
165 | static SArg to_byte(const SArg & op1);
166 | static SArg to_double(const SArg & op1);
167 | static SArg to_float(const SArg & op1);
168 | };
169 |
170 | typedef struct SArg *PArg;
171 |
172 | #endif // of SARG_H
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 |
189 |
190 |
191 |
192 |
193 |
194 |
--------------------------------------------------------------------------------
/src/plugcalc/syntax.cpp:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Cail Lomecb (Igor Ruskih) 1999-2001
3 | // Copyright (c) uncle-vunkis 2009-2011
4 | // You can use, modify, distribute this code or any other part
5 | // of this program in sources or in binaries only according
6 | // to License (see /doc/license.txt for more information).
7 | //
8 |
9 | #include "syntax.h"
10 | #include "sarg.h"
11 |
12 | SSyntax::SSyntax()
13 | {
14 | next = nullptr;
15 | name_set = nullptr;
16 | name = mean = nullptr;
17 | priority = 0;
18 | flags = 0;
19 |
20 | re = nullptr;
21 | }
22 |
23 | // XXX:
24 | SSyntax::~SSyntax()
25 | {
26 | delete next;
27 | delete [] name;
28 | delete [] name_set;
29 | delete [] mean;
30 | if (re) trex_free(re);
31 | }
32 |
33 | SVars::SVars()= default;
34 |
35 | SVars::~SVars()= default;
36 |
37 |
--------------------------------------------------------------------------------
/src/plugcalc/syntax.h:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Cail Lomecb (Igor Ruskih) 1999-2001
3 | // Copyright (c) uncle-vunkis 2009-2011
4 | // You can use, modify, distribute this code or any other part
5 | // of this program in sources or in binaries only according
6 | // to License (see /doc/license.txt for more information).
7 | //
8 |
9 | #ifndef SYNTAX_H
10 | #define SYNTAX_H
11 |
12 | #include "sarg.h"
13 | #include
14 |
15 | enum CALC_ADDON_FLAGS
16 | {
17 | CALC_ADDON_FLAG_NONE = 0,
18 | CALC_ADDON_FLAG_DELIM = 1,
19 | CALC_ADDON_FLAG_DIALOG = 2,
20 | };
21 |
22 | enum CALC_RADIX
23 | {
24 | CALC_RADIX_EXPONENTIAL = -10,
25 | CALC_RADIX_REPEATING = -110,
26 | CALC_RADIX_CONTINUED = -210,
27 | };
28 |
29 | struct SSyntax
30 | {
31 | wchar_t *name;
32 | wchar_t *name_set; // XXX:
33 | wchar_t *mean;
34 |
35 | TRex *re;
36 |
37 | union
38 | {
39 | int priority;
40 | int radix;
41 | };
42 |
43 | int flags;
44 |
45 | SSyntax *next;
46 |
47 | SSyntax();
48 | ~SSyntax();
49 | };
50 |
51 | typedef struct SSyntax *PSyntax;
52 |
53 | struct SVars:SSyntax
54 | {
55 | SArg value;
56 | SVars();
57 | ~SVars();
58 | };
59 |
60 | typedef struct SVars *PVars;
61 |
62 | #endif // of SYNTAX_H
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
--------------------------------------------------------------------------------
/src/plugcalc/version.h:
--------------------------------------------------------------------------------
1 | #ifdef _WIN64
2 | #define PLATFORM " x64"
3 | #elif defined _M_ARM64
4 | #define PLATFORM " ARM64"
5 | #elif defined _WIN32
6 | #define PLATFORM " x86"
7 | #else
8 | #define PLATFORM ""
9 | #endif
10 |
11 | #define PLUGIN_VER_MAJOR 3
12 | #define PLUGIN_VER_MINOR 26
13 | #define PLUGIN_VER_PATCH 1
14 | #define PLUGIN_DESC L"Calculator plugin for FAR manager 3.0" PLATFORM
15 | #define PLUGIN_NAME L"Calculator"
16 | #define PLUGIN_FILENAME L"calc.dll"
17 | #define PLUGIN_COPYRIGHT L"© Igor Russkih, 1999-2001. © 2009-2012, uncle-vunkis. © FarPlugins Team, 2020 -"
18 |
19 | #define STRINGIZE2(s) #s
20 | #define STRINGIZE(s) STRINGIZE2(s)
21 |
22 | #define PLUGIN_VERSION STRINGIZE(PLUGIN_VER_MAJOR) "." STRINGIZE(PLUGIN_VER_MINOR) "." STRINGIZE(PLUGIN_VER_PATCH)
23 |
--------------------------------------------------------------------------------
/src/shared/farplugin/3.0/farcolor.hpp:
--------------------------------------------------------------------------------
1 | #ifndef FARCOLOR_HPP_57151931_4591_44A5_92CF_8E51D1FBC57E
2 | #define FARCOLOR_HPP_57151931_4591_44A5_92CF_8E51D1FBC57E
3 | #pragma once
4 |
5 | /*
6 | farcolor.hpp
7 |
8 | Colors Index for FAR Manager 3.0 build 5655
9 | */
10 | /*
11 | Copyright © 1996 Eugene Roshal
12 | Copyright © 2000 Far Group
13 | All rights reserved.
14 |
15 | Redistribution and use in source and binary forms, with or without
16 | modification, are permitted provided that the following conditions
17 | are met:
18 | 1. Redistributions of source code must retain the above copyright
19 | notice, this list of conditions and the following disclaimer.
20 | 2. Redistributions in binary form must reproduce the above copyright
21 | notice, this list of conditions and the following disclaimer in the
22 | documentation and/or other materials provided with the distribution.
23 | 3. The name of the authors may not be used to endorse or promote products
24 | derived from this software without specific prior written permission.
25 |
26 | THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS' AND ANY EXPRESS OR
27 | IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28 | OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29 | IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31 | NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35 | THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 |
37 | EXCEPTION:
38 | Far Manager plugins that use this header file can be distributed under any
39 | other possible license with no implications from the above license on them.
40 | */
41 |
42 |
43 |
44 | enum PaletteColors
45 | {
46 | COL_MENUTEXT,
47 | COL_MENUSELECTEDTEXT,
48 | COL_MENUHIGHLIGHT,
49 | COL_MENUSELECTEDHIGHLIGHT,
50 | COL_MENUBOX,
51 | COL_MENUTITLE,
52 |
53 | COL_HMENUTEXT,
54 | COL_HMENUSELECTEDTEXT,
55 | COL_HMENUHIGHLIGHT,
56 | COL_HMENUSELECTEDHIGHLIGHT,
57 |
58 | COL_PANELTEXT,
59 | COL_PANELSELECTEDTEXT,
60 | COL_PANELHIGHLIGHTTEXT,
61 | COL_PANELINFOTEXT,
62 | COL_PANELCURSOR,
63 | COL_PANELSELECTEDCURSOR,
64 | COL_PANELTITLE,
65 | COL_PANELSELECTEDTITLE,
66 | COL_PANELCOLUMNTITLE,
67 | COL_PANELTOTALINFO,
68 | COL_PANELSELECTEDINFO,
69 |
70 | COL_DIALOGTEXT,
71 | COL_DIALOGHIGHLIGHTTEXT,
72 | COL_DIALOGBOX,
73 | COL_DIALOGBOXTITLE,
74 | COL_DIALOGHIGHLIGHTBOXTITLE,
75 | COL_DIALOGEDIT,
76 | COL_DIALOGBUTTON,
77 | COL_DIALOGSELECTEDBUTTON,
78 | COL_DIALOGHIGHLIGHTBUTTON,
79 | COL_DIALOGHIGHLIGHTSELECTEDBUTTON,
80 |
81 | COL_DIALOGLISTTEXT,
82 | COL_DIALOGLISTSELECTEDTEXT,
83 | COL_DIALOGLISTHIGHLIGHT,
84 | COL_DIALOGLISTSELECTEDHIGHLIGHT,
85 |
86 | COL_WARNDIALOGTEXT,
87 | COL_WARNDIALOGHIGHLIGHTTEXT,
88 | COL_WARNDIALOGBOX,
89 | COL_WARNDIALOGBOXTITLE,
90 | COL_WARNDIALOGHIGHLIGHTBOXTITLE,
91 | COL_WARNDIALOGEDIT,
92 | COL_WARNDIALOGBUTTON,
93 | COL_WARNDIALOGSELECTEDBUTTON,
94 | COL_WARNDIALOGHIGHLIGHTBUTTON,
95 | COL_WARNDIALOGHIGHLIGHTSELECTEDBUTTON,
96 |
97 | COL_KEYBARNUM,
98 | COL_KEYBARTEXT,
99 | COL_KEYBARBACKGROUND,
100 |
101 | COL_COMMANDLINE,
102 |
103 | COL_CLOCK,
104 |
105 | COL_VIEWERTEXT,
106 | COL_VIEWERSELECTEDTEXT,
107 | COL_VIEWERSTATUS,
108 |
109 | COL_EDITORTEXT,
110 | COL_EDITORSELECTEDTEXT,
111 | COL_EDITORSTATUS,
112 |
113 | COL_HELPTEXT,
114 | COL_HELPHIGHLIGHTTEXT,
115 | COL_HELPTOPIC,
116 | COL_HELPSELECTEDTOPIC,
117 | COL_HELPBOX,
118 | COL_HELPBOXTITLE,
119 |
120 | COL_PANELDRAGTEXT,
121 | COL_DIALOGEDITUNCHANGED,
122 | COL_PANELSCROLLBAR,
123 | COL_HELPSCROLLBAR,
124 | COL_PANELBOX,
125 | COL_PANELSCREENSNUMBER,
126 | COL_DIALOGEDITSELECTED,
127 | COL_COMMANDLINESELECTED,
128 | COL_VIEWERARROWS,
129 |
130 | COL_DIALOGLISTSCROLLBAR,
131 | COL_MENUSCROLLBAR,
132 | COL_VIEWERSCROLLBAR,
133 | COL_COMMANDLINEPREFIX,
134 | COL_DIALOGDISABLED,
135 | COL_DIALOGEDITDISABLED,
136 | COL_DIALOGLISTDISABLED,
137 | COL_WARNDIALOGDISABLED,
138 | COL_WARNDIALOGEDITDISABLED,
139 | COL_WARNDIALOGLISTDISABLED,
140 |
141 | COL_MENUDISABLEDTEXT,
142 |
143 | COL_EDITORCLOCK,
144 | COL_VIEWERCLOCK,
145 |
146 | COL_DIALOGLISTTITLE,
147 | COL_DIALOGLISTBOX,
148 |
149 | COL_WARNDIALOGEDITSELECTED,
150 | COL_WARNDIALOGEDITUNCHANGED,
151 |
152 | COL_DIALOGCOMBOTEXT,
153 | COL_DIALOGCOMBOSELECTEDTEXT,
154 | COL_DIALOGCOMBOHIGHLIGHT,
155 | COL_DIALOGCOMBOSELECTEDHIGHLIGHT,
156 | COL_DIALOGCOMBOBOX,
157 | COL_DIALOGCOMBOTITLE,
158 | COL_DIALOGCOMBODISABLED,
159 | COL_DIALOGCOMBOSCROLLBAR,
160 |
161 | COL_WARNDIALOGLISTTEXT,
162 | COL_WARNDIALOGLISTSELECTEDTEXT,
163 | COL_WARNDIALOGLISTHIGHLIGHT,
164 | COL_WARNDIALOGLISTSELECTEDHIGHLIGHT,
165 | COL_WARNDIALOGLISTBOX,
166 | COL_WARNDIALOGLISTTITLE,
167 | COL_WARNDIALOGLISTSCROLLBAR,
168 |
169 | COL_WARNDIALOGCOMBOTEXT,
170 | COL_WARNDIALOGCOMBOSELECTEDTEXT,
171 | COL_WARNDIALOGCOMBOHIGHLIGHT,
172 | COL_WARNDIALOGCOMBOSELECTEDHIGHLIGHT,
173 | COL_WARNDIALOGCOMBOBOX,
174 | COL_WARNDIALOGCOMBOTITLE,
175 | COL_WARNDIALOGCOMBODISABLED,
176 | COL_WARNDIALOGCOMBOSCROLLBAR,
177 |
178 | COL_DIALOGLISTARROWS,
179 | COL_DIALOGLISTARROWSDISABLED,
180 | COL_DIALOGLISTARROWSSELECTED,
181 | COL_DIALOGCOMBOARROWS,
182 | COL_DIALOGCOMBOARROWSDISABLED,
183 | COL_DIALOGCOMBOARROWSSELECTED,
184 | COL_WARNDIALOGLISTARROWS,
185 | COL_WARNDIALOGLISTARROWSDISABLED,
186 | COL_WARNDIALOGLISTARROWSSELECTED,
187 | COL_WARNDIALOGCOMBOARROWS,
188 | COL_WARNDIALOGCOMBOARROWSDISABLED,
189 | COL_WARNDIALOGCOMBOARROWSSELECTED,
190 | COL_MENUARROWS,
191 | COL_MENUARROWSDISABLED,
192 | COL_MENUARROWSSELECTED,
193 | COL_COMMANDLINEUSERSCREEN,
194 | COL_EDITORSCROLLBAR,
195 |
196 | COL_MENUGRAYTEXT,
197 | COL_MENUSELECTEDGRAYTEXT,
198 | COL_DIALOGCOMBOGRAY,
199 | COL_DIALOGCOMBOSELECTEDGRAYTEXT,
200 | COL_DIALOGLISTGRAY,
201 | COL_DIALOGLISTSELECTEDGRAYTEXT,
202 | COL_WARNDIALOGCOMBOGRAY,
203 | COL_WARNDIALOGCOMBOSELECTEDGRAYTEXT,
204 | COL_WARNDIALOGLISTGRAY,
205 | COL_WARNDIALOGLISTSELECTEDGRAYTEXT,
206 |
207 | COL_DIALOGDEFAULTBUTTON,
208 | COL_DIALOGSELECTEDDEFAULTBUTTON,
209 | COL_DIALOGHIGHLIGHTDEFAULTBUTTON,
210 | COL_DIALOGHIGHLIGHTSELECTEDDEFAULTBUTTON,
211 | COL_WARNDIALOGDEFAULTBUTTON,
212 | COL_WARNDIALOGSELECTEDDEFAULTBUTTON,
213 | COL_WARNDIALOGHIGHLIGHTDEFAULTBUTTON,
214 | COL_WARNDIALOGHIGHLIGHTSELECTEDDEFAULTBUTTON,
215 |
216 | COL_LASTPALETTECOLOR
217 | };
218 |
219 | #endif // FARCOLOR_HPP_57151931_4591_44A5_92CF_8E51D1FBC57E
220 |
--------------------------------------------------------------------------------
/src/shared/farplugin/vc_crt_fix.asm:
--------------------------------------------------------------------------------
1 | ;vc_crt_fix.asm
2 |
3 | ;Workaround for Visual C++ CRT incompatibility with old Windows versions
4 |
5 | ;Copyright © 2010 Far Group
6 | ;All rights reserved.
7 | ;
8 | ;Redistribution and use in source and binary forms, with or without
9 | ;modification, are permitted provided that the following conditions
10 | ;are met:
11 | ;1. Redistributions of source code must retain the above copyright
12 | ; notice, this list of conditions and the following disclaimer.
13 | ;2. Redistributions in binary form must reproduce the above copyright
14 | ; notice, this list of conditions and the following disclaimer in the
15 | ; documentation and/or other materials provided with the distribution.
16 | ;3. The name of the authors may not be used to endorse or promote products
17 | ; derived from this software without specific prior written permission.
18 | ;
19 | ;THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 | ;IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 | ;OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 | ;IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 | ;INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 | ;NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 | ;DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 | ;THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 | ;(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 | ;THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 |
30 | ifndef X64
31 | .model flat
32 | endif
33 |
34 | .const
35 |
36 | HOOK MACRO name, size, args:VARARG
37 | ifndef X64
38 | @CatStr(name, Wrapper) proto stdcall args
39 | @CatStr(__imp__, name, @, size) dd @CatStr(name, Wrapper)
40 | public @CatStr(__imp__, name, @, size)
41 | else
42 | @CatStr(name, Wrapper) proto stdcall
43 | @CatStr(__imp_, name) dq @CatStr(name, Wrapper)
44 | public @CatStr(__imp_, name)
45 | endif
46 | ENDM
47 |
48 | ifndef X64
49 | HOOK EncodePointer , 4, :dword
50 | HOOK DecodePointer , 4, :dword
51 | HOOK GetModuleHandleExW , 12, :dword, :dword, :dword
52 | HOOK InitializeSListHead , 4, :dword
53 | HOOK InterlockedFlushSList , 4, :dword
54 | HOOK InterlockedPopEntrySList , 4, :dword
55 | HOOK InterlockedPushEntrySList , 8, :dword, :dword
56 | HOOK InterlockedPushListSListEx , 16, :dword, :dword, :dword, :dword
57 | HOOK RtlFirstEntrySList , 4, :dword
58 | HOOK QueryDepthSList , 4, :dword
59 | HOOK GetNumaHighestNodeNumber , 4, :dword
60 | HOOK GetLogicalProcessorInformation , 8, :dword, :dword
61 | HOOK SetThreadStackGuarantee , 4, :dword
62 | endif
63 |
64 | end
65 |
--------------------------------------------------------------------------------
/src/shared/farplugin/vc_crt_fix_impl.cpp:
--------------------------------------------------------------------------------
1 | // validator: no-self-include
2 | /*
3 | vc_crt_fix_impl.cpp
4 |
5 | Workaround for Visual C++ CRT incompatibility with old Windows versions
6 | */
7 | /*
8 | Copyright © 2011 Far Group
9 | All rights reserved.
10 |
11 | Redistribution and use in source and binary forms, with or without
12 | modification, are permitted provided that the following conditions
13 | are met:
14 | 1. Redistributions of source code must retain the above copyright
15 | notice, this list of conditions and the following disclaimer.
16 | 2. Redistributions in binary form must reproduce the above copyright
17 | notice, this list of conditions and the following disclaimer in the
18 | documentation and/or other materials provided with the distribution.
19 | 3. The name of the authors may not be used to endorse or promote products
20 | derived from this software without specific prior written permission.
21 |
22 | THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS' AND ANY EXPRESS OR
23 | IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
24 | OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
25 | IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
26 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
27 | NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
31 | THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 | */
33 |
34 | #include
35 |
36 | #include
37 |
38 | #ifdef __clang__
39 | #pragma clang diagnostic ignored "-Wmissing-prototypes"
40 | #endif
41 |
42 |
43 | template
44 | static T GetFunctionPointer(const wchar_t* ModuleName, const char* FunctionName, T Replacement)
45 | {
46 | const auto Module = GetModuleHandleW(ModuleName);
47 | const auto Address = Module? GetProcAddress(Module, FunctionName) : nullptr;
48 | return Address? reinterpret_cast(reinterpret_cast(Address)) : Replacement;
49 | }
50 |
51 | #define CREATE_FUNCTION_POINTER(ModuleName, FunctionName)\
52 | static const auto Function = GetFunctionPointer(ModuleName, #FunctionName, &implementation::FunctionName)
53 |
54 | namespace modules
55 | {
56 | static const wchar_t kernel32[] = L"kernel32";
57 | static const wchar_t ntdll[] = L"ntdll";
58 | }
59 |
60 | static void* XorPointer(void* Ptr)
61 | {
62 | static const auto Cookie = []
63 | {
64 | static void* Ptr;
65 | auto Result = reinterpret_cast(&Ptr);
66 |
67 | FILETIME CreationTime, NotUsed;
68 | if (GetThreadTimes(GetCurrentThread(), &CreationTime, &NotUsed, &NotUsed, &NotUsed))
69 | {
70 | Result ^= CreationTime.dwLowDateTime;
71 | Result ^= CreationTime.dwHighDateTime;
72 | }
73 | return Result;
74 | }();
75 | return reinterpret_cast(reinterpret_cast(Ptr) ^ Cookie);
76 | }
77 |
78 | // EncodePointer (VC2010)
79 | extern "C" PVOID WINAPI EncodePointerWrapper(PVOID Ptr)
80 | {
81 | struct implementation
82 | {
83 | static PVOID WINAPI EncodePointer(PVOID Ptr)
84 | {
85 | return XorPointer(Ptr);
86 | }
87 | };
88 |
89 | CREATE_FUNCTION_POINTER(modules::kernel32, EncodePointer);
90 | return Function(Ptr);
91 | }
92 |
93 | // DecodePointer(VC2010)
94 | extern "C" PVOID WINAPI DecodePointerWrapper(PVOID Ptr)
95 | {
96 | struct implementation
97 | {
98 | static PVOID WINAPI DecodePointer(PVOID Ptr)
99 | {
100 | return XorPointer(Ptr);
101 | }
102 | };
103 |
104 | CREATE_FUNCTION_POINTER(modules::kernel32, DecodePointer);
105 | return Function(Ptr);
106 | }
107 |
108 | // GetModuleHandleExW (VC2012)
109 | extern "C" BOOL WINAPI GetModuleHandleExWWrapper(DWORD Flags, LPCWSTR ModuleName, HMODULE *Module)
110 | {
111 | struct implementation
112 | {
113 | static BOOL WINAPI GetModuleHandleExW(DWORD Flags, LPCWSTR ModuleName, HMODULE *Module)
114 | {
115 | if (Flags & GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS)
116 | {
117 | MEMORY_BASIC_INFORMATION mbi;
118 | if (!VirtualQuery(ModuleName, &mbi, sizeof(mbi)))
119 | return FALSE;
120 |
121 | const auto ModuleValue = static_cast(mbi.AllocationBase);
122 |
123 | if (!(Flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT))
124 | {
125 | wchar_t Buffer[MAX_PATH];
126 | if (!GetModuleFileNameW(ModuleValue, Buffer, ARRAYSIZE(Buffer)))
127 | return FALSE;
128 | // It's the same so not really necessary, but analysers report handle leak otherwise.
129 | *Module = LoadLibraryW(Buffer);
130 | }
131 | else
132 | {
133 | *Module = ModuleValue;
134 | }
135 | return TRUE;
136 | }
137 |
138 | // GET_MODULE_HANDLE_EX_FLAG_PIN not implemented
139 |
140 | if (const auto ModuleValue = (Flags & GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT? GetModuleHandleW : LoadLibraryW)(ModuleName))
141 | {
142 | *Module = ModuleValue;
143 | return TRUE;
144 | }
145 | return FALSE;
146 | }
147 | };
148 |
149 | CREATE_FUNCTION_POINTER(modules::kernel32, GetModuleHandleExW);
150 | return Function(Flags, ModuleName, Module);
151 | }
152 |
153 | namespace slist
154 | {
155 | namespace implementation
156 | {
157 | #ifdef _WIN64
158 | // These stubs are here only to unify compilation, they shall never be needed on x64.
159 | static void WINAPI InitializeSListHead(PSLIST_HEADER ListHead) {}
160 | static PSLIST_ENTRY WINAPI InterlockedFlushSList(PSLIST_HEADER ListHead) { return nullptr; }
161 | static PSLIST_ENTRY WINAPI InterlockedPopEntrySList(PSLIST_HEADER ListHead) { return nullptr; }
162 | static PSLIST_ENTRY WINAPI InterlockedPushEntrySList(PSLIST_HEADER ListHead, PSLIST_ENTRY ListEntry) { return nullptr; }
163 | static PSLIST_ENTRY WINAPI InterlockedPushListSListEx(PSLIST_HEADER ListHead, PSLIST_ENTRY List, PSLIST_ENTRY ListEnd, ULONG Count) { return nullptr; }
164 | static PSLIST_ENTRY WINAPI RtlFirstEntrySList(PSLIST_HEADER ListHead) { return nullptr; }
165 | static USHORT WINAPI QueryDepthSList(PSLIST_HEADER ListHead) { return 0; }
166 | #else
167 | class critical_section
168 | {
169 | public:
170 | critical_section() { InitializeCriticalSection(&m_Lock); }
171 | ~critical_section() { DeleteCriticalSection(&m_Lock); }
172 |
173 | critical_section(const critical_section&) = delete;
174 | critical_section(critical_section&&) = default;
175 |
176 | critical_section& operator=(const critical_section&) = delete;
177 | critical_section& operator=(critical_section&&) = default;
178 |
179 | void lock() { EnterCriticalSection(&m_Lock); }
180 | void unlock() { LeaveCriticalSection(&m_Lock); }
181 |
182 | private:
183 | CRITICAL_SECTION m_Lock;
184 | };
185 |
186 | struct service_entry: SLIST_ENTRY, critical_section
187 | {
188 | // InitializeSListHead might be called during runtime initialisation
189 | // when operator new might not be ready yet (especially in presence of leak detectors)
190 |
191 | void* operator new(size_t Size)
192 | {
193 | return malloc(Size);
194 | }
195 |
196 | void operator delete(void* Ptr)
197 | {
198 | free(Ptr);
199 | }
200 |
201 | service_entry* ServiceNext{};
202 | };
203 |
204 | class slist_lock
205 | {
206 | public:
207 | explicit slist_lock(PSLIST_HEADER ListHead):
208 | m_Entry(static_cast(*ListHead->Next.Next))
209 | {
210 | m_Entry.lock();
211 | }
212 |
213 | ~slist_lock()
214 | {
215 | m_Entry.unlock();
216 | }
217 |
218 | slist_lock(const slist_lock&) = delete;
219 | slist_lock& operator=(const slist_lock&) = delete;
220 |
221 | private:
222 | service_entry& m_Entry;
223 | };
224 |
225 | class service_deleter
226 | {
227 | public:
228 | ~service_deleter()
229 | {
230 | while (m_Data.ServiceNext)
231 | {
232 | delete std::exchange(m_Data.ServiceNext, m_Data.ServiceNext->ServiceNext);
233 | }
234 | }
235 |
236 | void add(service_entry* Entry)
237 | {
238 | m_Data.lock();
239 | Entry->ServiceNext = m_Data.ServiceNext;
240 | m_Data.ServiceNext = Entry;
241 | m_Data.unlock();
242 | }
243 |
244 | private:
245 | service_entry m_Data{};
246 | };
247 |
248 | static SLIST_ENTRY*& top(PSLIST_HEADER ListHead)
249 | {
250 | return ListHead->Next.Next->Next;
251 | }
252 |
253 | static void WINAPI InitializeSListHead(PSLIST_HEADER ListHead)
254 | {
255 | *ListHead = {};
256 |
257 | const auto Entry = new service_entry();
258 | ListHead->Next.Next = Entry;
259 |
260 | static service_deleter Deleter;
261 | Deleter.add(Entry);
262 | }
263 |
264 | static PSLIST_ENTRY WINAPI InterlockedFlushSList(PSLIST_HEADER ListHead)
265 | {
266 | slist_lock Lock(ListHead);
267 |
268 | ListHead->Depth = 0;
269 | return std::exchange(top(ListHead), nullptr);
270 | }
271 |
272 | static PSLIST_ENTRY WINAPI InterlockedPopEntrySList(PSLIST_HEADER ListHead)
273 | {
274 | slist_lock Lock(ListHead);
275 |
276 | auto& Top = top(ListHead);
277 | if (!Top)
278 | return nullptr;
279 |
280 | --ListHead->Depth;
281 | return std::exchange(Top, Top->Next);
282 | }
283 |
284 | static PSLIST_ENTRY WINAPI InterlockedPushEntrySList(PSLIST_HEADER ListHead, PSLIST_ENTRY ListEntry)
285 | {
286 | slist_lock Lock(ListHead);
287 |
288 | auto& Top = top(ListHead);
289 |
290 | ++ListHead->Depth;
291 | ListEntry->Next = Top;
292 | return std::exchange(Top, ListEntry);
293 | }
294 |
295 | static PSLIST_ENTRY WINAPI InterlockedPushListSListEx(PSLIST_HEADER ListHead, PSLIST_ENTRY List, PSLIST_ENTRY ListEnd, ULONG Count)
296 | {
297 | slist_lock Lock(ListHead);
298 |
299 | auto& Top = top(ListHead);
300 |
301 | ListHead->Depth += static_cast(Count);
302 | ListEnd->Next = Top;
303 | return std::exchange(Top, List);
304 | }
305 |
306 | static PSLIST_ENTRY WINAPI RtlFirstEntrySList(PSLIST_HEADER ListHead)
307 | {
308 | slist_lock Lock(ListHead);
309 |
310 | return top(ListHead);
311 | }
312 |
313 | static USHORT WINAPI QueryDepthSList(PSLIST_HEADER ListHead)
314 | {
315 | slist_lock Lock(ListHead);
316 |
317 | return ListHead->Depth;
318 | }
319 | #endif
320 | }
321 | }
322 |
323 | // InitializeSListHead (VC2015)
324 | extern "C" void WINAPI InitializeSListHeadWrapper(PSLIST_HEADER ListHead)
325 | {
326 | using namespace slist;
327 | CREATE_FUNCTION_POINTER(modules::kernel32, InitializeSListHead);
328 | return Function(ListHead);
329 | }
330 |
331 | // InterlockedFlushSList (VC2015)
332 | extern "C" PSLIST_ENTRY WINAPI InterlockedFlushSListWrapper(PSLIST_HEADER ListHead)
333 | {
334 | using namespace slist;
335 | CREATE_FUNCTION_POINTER(modules::kernel32, InterlockedFlushSList);
336 | return Function(ListHead);
337 | }
338 |
339 | // InterlockedPopEntrySList (VC2015)
340 | extern "C" PSLIST_ENTRY WINAPI InterlockedPopEntrySListWrapper(PSLIST_HEADER ListHead)
341 | {
342 | using namespace slist;
343 | CREATE_FUNCTION_POINTER(modules::kernel32, InterlockedPopEntrySList);
344 | return Function(ListHead);
345 | }
346 |
347 | // InterlockedPushEntrySList (VC2015)
348 | extern "C" PSLIST_ENTRY WINAPI InterlockedPushEntrySListWrapper(PSLIST_HEADER ListHead, PSLIST_ENTRY ListEntry)
349 | {
350 | using namespace slist;
351 | CREATE_FUNCTION_POINTER(modules::kernel32, InterlockedPushEntrySList);
352 | return Function(ListHead, ListEntry);
353 | }
354 |
355 | // InterlockedPushListSListEx (VC2015)
356 | extern "C" PSLIST_ENTRY WINAPI InterlockedPushListSListExWrapper(PSLIST_HEADER ListHead, PSLIST_ENTRY List, PSLIST_ENTRY ListEnd, ULONG Count)
357 | {
358 | using namespace slist;
359 | CREATE_FUNCTION_POINTER(modules::kernel32, InterlockedPushListSListEx);
360 | return Function(ListHead, List, ListEnd, Count);
361 | }
362 |
363 | // RtlFirstEntrySList (VC2015)
364 | extern "C" PSLIST_ENTRY WINAPI RtlFirstEntrySListWrapper(PSLIST_HEADER ListHead)
365 | {
366 | using namespace slist;
367 | CREATE_FUNCTION_POINTER(modules::ntdll, RtlFirstEntrySList);
368 | return Function(ListHead);
369 | }
370 |
371 | // QueryDepthSList (VC2015)
372 | extern "C" USHORT WINAPI QueryDepthSListWrapper(PSLIST_HEADER ListHead)
373 | {
374 | using namespace slist;
375 | CREATE_FUNCTION_POINTER(modules::kernel32, QueryDepthSList);
376 | return Function(ListHead);
377 | }
378 |
379 | // GetNumaHighestNodeNumber (VC2017)
380 | extern "C" BOOL WINAPI GetNumaHighestNodeNumberWrapper(PULONG HighestNodeNumber)
381 | {
382 | struct implementation
383 | {
384 | static BOOL WINAPI GetNumaHighestNodeNumber(PULONG HighestNodeNumber)
385 | {
386 | *HighestNodeNumber = 0;
387 | return TRUE;
388 | }
389 | };
390 |
391 | CREATE_FUNCTION_POINTER(modules::kernel32, GetNumaHighestNodeNumber);
392 | return Function(HighestNodeNumber);
393 | }
394 |
395 | // GetLogicalProcessorInformation (VC2017)
396 | extern "C" BOOL WINAPI GetLogicalProcessorInformationWrapper(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION Buffer, PDWORD ReturnLength)
397 | {
398 | struct implementation
399 | {
400 | static BOOL WINAPI GetLogicalProcessorInformation(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION Buffer, PDWORD ReturnLength)
401 | {
402 | SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
403 | return FALSE;
404 | }
405 | };
406 |
407 | CREATE_FUNCTION_POINTER(modules::kernel32, GetLogicalProcessorInformation);
408 | return Function(Buffer, ReturnLength);
409 | }
410 |
411 | // SetThreadStackGuarantee (VC2019)
412 | extern "C" BOOL WINAPI SetThreadStackGuaranteeWrapper(PULONG StackSizeInBytes)
413 | {
414 | struct implementation
415 | {
416 | static BOOL WINAPI SetThreadStackGuarantee(PULONG StackSizeInBytes)
417 | {
418 | SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
419 | return FALSE;
420 | }
421 | };
422 |
423 | CREATE_FUNCTION_POINTER(modules::kernel32, SetThreadStackGuarantee);
424 | return Function(StackSizeInBytes);
425 | }
426 |
427 |
428 | // disable VS2015 telemetry
429 | extern "C"
430 | {
431 | void __vcrt_initialize_telemetry_provider() {}
432 | void __telemetry_main_invoke_trigger() {}
433 | void __telemetry_main_return_trigger() {}
434 | void __vcrt_uninitialize_telemetry_provider() {}
435 | }
436 |
--------------------------------------------------------------------------------
/src/shared/mathexpression/README:
--------------------------------------------------------------------------------
1 |
2 | MathExpression-0.6.6 Alpha
3 |
4 | Authors : Andrey Myznikov
5 | Sergey Prokopenko
6 | Elizaveta Evstifeeva
7 |
8 | Last Update : June 23 2009
9 |
10 |
11 | MathExpression is the flexible, extensible, fast and easy to use C++ class template
12 | for creating your own customized math expression parsers for both built-in and
13 | user-defined numerical data types. User-defined functions, functional objects
14 | (functors), operators, named constants, parameter binding, as well as arguments
15 | are supported. The parser can be safely used in multi-threaded OpenMP applications.
16 |
17 | Be aware that this source still under alpha-development stage,
18 | and therefore it can be redesigned frequently. Lookup for
19 | updates at http://sourceforge.net/projects/mathexpression
20 |
21 |
22 |
23 | INSTALL
24 |
25 | To install just copy headers ./include/{*.h} into your favorite include
26 | directory where your compiler will able to find them.
27 |
28 | The examples were tested at these platforms:
29 |
30 | - SUSE Linux Enterprise Server 10 (ia64) on Itanium2
31 | ICC 10.0, GCC 4.1.2
32 |
33 | - SUSE Linux Enterprise Server 10 (x86_64) on Intel(R) Xeon(R) CPU X5355
34 | ICC 10.0, GCC 4.1.2
35 |
36 | - Red Hat Enterprise Linux Server release 5 (Tikanga) on Intel(R) Xeon(R) CPU 5160
37 | ICC 10.0, GCC 4.1.1
38 |
39 | - Ubuntu 9.04 (jaunty) desktop on both ia32 and x86_64
40 | ICC 11.0, GCC 4.3.3
41 |
42 | To build examples as is, the GNU make and GCC or ICC compiler are required.
43 | Type 'make help' for the hints on configurable parameters.
44 | The structure of examples is very simple, therefore I suggest that you can
45 | easily modify make.inc and makefiles in the ./example/ subdirs as you prefer.
46 |
47 | Notes for windows: Elizaveta Evstifeeva made some modifications to allow compile
48 | these sources using Visual Studio, but we still don't support this system. It may be
49 | that this will compilable and even will work, but this still not supported.
50 |
51 | Other note is that the math library implementation can vary between platforms,
52 | therefore if you encounter that some functions referenced in MathExpression.h
53 | are not defined, then just comment them out them or provide correct equivalents
54 | for your platform. Note here that the MathExpression.h is just example file,
55 | used for examples, and is not mandatory part of the library itself.
56 |
57 | For GSL (http://www.gnu.org/software/gsl) examples you need to have GSL
58 | library properly installed. On the Ubuntu you can install it typing
59 | 'sudo aptitude install libgsl0-dev'.
60 |
61 | For the CLN (http://www.ginac.de/CLN) example you need the CLN library installed.
62 | On Ubuntu install 'libcln-dev' package and dependencies.
63 |
64 | The GNU levmar example includes the sources of levmar-2.4 obtained from
65 | official web site http://www.ics.forth.gr/~lourakis/levmar. Most likely
66 | you will need to configure the makefiles in the ./examples/gnu_levmar/levmar-2.4
67 | directory to provide correct path to your favorite lapack implementation.
68 | See the gnu levmar documentation for more info.
69 |
70 |
71 | USE
72 |
73 | In essence the MathExpression is not a program and is not a library.
74 | This is just a set of C++ template classes allowing you create your own
75 | programs and libraries. These class templates are declared in MathExpressionBase.h.
76 | The MathExpression.h is not mandatory header, it just contains a few examples of
77 | user-defined parsers, although you can use it as is too.
78 |
79 | The basing steps to create your own customized math parser are roughly follows:
80 |
81 | 1) Select the numerical data type of math expression. This type can be thought
82 | as the 'result type' of math expression, and it will main type used during computation.
83 | The examples here will suppose that you selected built-in 'double', although it can
84 | seems trivial, the potential applications range is wide enough.
85 |
86 |
87 | 2) Derive your own class for MathExpression :
88 |
89 | #include "MathExpressionBase.h"
90 |
91 | class MathFunction
92 | : public MathExpressionBase
93 | {
94 | typedef MathExpressionBase mybase;
95 | public:
96 | typedef double value_type;
97 | MathFunction();
98 |
99 | protected:
100 | bool parse_number( double * value, const char * curpos, char ** endptr );
101 | };
102 |
103 |
104 |
105 | 3) Implement pure virtual routine parse_number() to convert string to the number.
106 | Obviously this can't be done at base class level, therefore you need made this.
107 |
108 | bool MathFunction :: parse_number( double * value, const char * curpos, char ** endptr )
109 | { * value = strtod(curpos,endptr);
110 | return *endptr>curpos;
111 | }
112 |
113 |
114 | 4) Customize your parser providing your own:
115 | - binary and unary operators
116 | - functions
117 | - bound parameters
118 | - named constants
119 | - named arguments
120 |
121 | You may made this at any time and at any point of code, below is an example of
122 | doing this in the constructor body.
123 |
124 | Note, that for most of functions there are 2 ways to add it to the MathExpression function list:
125 |
126 | 1) using function overloading notation, like this:
127 | add_function("sin",&sin,"the sine function");
128 |
129 | 2) using template overloading notation:
130 | add_function("sin","the sine function");
131 |
132 | Second way is preferable due to performance issues, it will bind the function staticaly,
133 | providing better performance on most machines, but this way not so flexible as first, and
134 | currently not all functions can be bound in this way.
135 |
136 | If you are user of MSVC++, then most likely you will have large problems;
137 | Try solve them providing strict function type as follows:
138 | add_function("sin","the sine function");
139 | In general, most likely we will not support the compilers which does not support for C++.
140 |
141 |
142 | MathFunction :: MathFunction()
143 | {
144 | // form the binary operations table
145 | BinaryOpTable.set_num_levels(3);
146 | BinaryOpTable[0]->add("+",std::plus());
147 | BinaryOpTable[0]->add("-",std::minus());
148 | BinaryOpTable[1]->add("*",std::multiplies());
149 | BinaryOpTable[1]->add("/",std::divides());
150 | BinaryOpTable[2]->add("**",&pow);
151 |
152 | // add unary + and -
153 | UnaryOpTable.add("-",&mybase::operator_unary_minus);
154 | UnaryOpTable.add("+",&mybase::operator_unary_plus);
155 |
156 | // add math functions
157 |
158 | // 1. using function-pointer notation
159 | add_function("abs",&fabs);
160 | add_function("sin",&sin);
161 |
162 | // 2. using template overloading notation
163 | add_function("cos");
164 | add_function("tan");
165 |
166 | // add named constants
167 | add_named_constant("pi",M_PI);
168 | add_named_constant("e",M_E);
169 | add_named_constant("eps",DBL_EPSILON);
170 |
171 | // add bound parameters
172 | bind("myvar",&some_global_variable);
173 |
174 | // add arguments passed over the stack,
175 | // providing the name and zero-based positional index of each
176 | add_argument("x",0);
177 | add_argument("y",1);
178 | }
179 |
180 | Again, this customization can be done at run-time at any place of code.
181 |
182 | 5) Having the MathFunction class defined, one can create as many instances as he want:
183 |
184 | MathFunction f;
185 | if( !f.parse("sin(x)*cos(y)" ) )
186 | { printf("parse error: %s : %s\n",f.get_error_msg(),f.get_error_pos());
187 | }
188 | else
189 | {
190 | for( double x=xmin; x<=xmax; x+=dx )
191 | for( double y=ymin; y<=ymax; y+=dy )
192 | { double args[] = {x,y};
193 | double z = f.eval(args);
194 | printf("%g\t%g\t%g\n",x,y,z);
195 | }
196 | }
197 |
198 | 6) For many cases it can be suitable to add operator () to the MathFunction class.
199 | This will allow to pass such functor object to anywhere a function is required,
200 | in particular to call one math expression from another:
201 |
202 | double MathFunction :: operator () (double x, double y)
203 | { double args[] = {x,y};
204 | return mybase::eval(args);
205 | }
206 | ...
207 | MathFunction f1;
208 | f1.parse("if(x==0,1,sin(x)/x)");
209 |
210 | MathFunction f2;
211 | f2.add_functor<2>("sinc",&f1);
212 | f2.parse("sinc(x)*sinc(y)");
213 |
214 | for( double x=xmin; x<=xmax; x+=dx )
215 | for( double y=ymin; y<=ymax; y+=dy )
216 | {
217 | z = f2(x,y);
218 | ...
219 | }
220 |
221 | See the ./examples/performance for example of using functors.
222 |
223 | USER-DEFINED NUMERICAL TYPES
224 |
225 | The MathExpressionBase<> can be parametrized by any data type, you just will need provide
226 | the functions for the math operators to process them. In particular you can create some kind
227 | of 'variant' data type to support run-time checks and conversions.
228 | The performance was one from my main goals when I created the project, therefore I avoid
229 | all run-time checks. If the performance is not your case, then you can use any suitable
230 | data type and any run-time checks and conversions.
231 |
232 |
233 | FURTHER DETAILS
234 | I have not prepared an valuable documentation now, therefore look please over the examples
235 | provided, as well as the MathExpressionBase.h and MathExpression.h sources itself for more
236 | details. I hope that it should be clear enough how it is organized.
237 |
238 |
239 | KNOW PROBLEMS
240 | There are know issues, which can lead to some difficulties using the class:
241 |
242 | 1) Troubles with mixing different numerical types in the MathExpression<>. Ideally, I would
243 | like to have possibility to safely mix the functions of real, complex, integer, boolean
244 | and user-defined numerical arguments, but it is not possible with existing implementation.
245 | Currently all nodes should return the value of the same data type.
246 | Of course, this does not mean that user-defined functions should accept and return the same type,
247 | but the conversions could be non-trivial.
248 |
249 | Suppose for example that I would like to create an ComplexMathExpression class, and provide function
250 | 'polar' returning complex number:
251 | complex polar( double r, double fi );
252 | This will not compile because there is no straight conversion from 'complex' to 'double'.
253 | As an example of my temporary (unsatisfactory) solution see the std_complex example.
254 |
255 | As an better (but probably slower from performance side) solution it can be use of some
256 | 'variant' data type for such conversions and checks. The performance was one from main goals
257 | when I created the project, therefore I have avoid all run-time checks.
258 |
259 |
260 | 2) Some troubles could be encountered implementing the variable-argument-list user-defined functions.
261 | Currently, such functions accepts the 'const NodeList & ' as argument list, but NodeList is protected
262 | in MathExpresionBase<>. Therefore, you will need implement such functions in the derived class or create
263 | a friend. See as an example the 'sum','product', 'min' and 'max' functions in the MathExpresionBase.h.
264 |
265 |
266 | 3) C++ function overloading
267 | You may encounter problems using overloaded functions in C++.
268 |
269 | Assume for an example that you have defined 2 functions with the same name:
270 | const cln_N conjugate ( const cl_N& x );
271 | const cln_R conjugate ( const cl_R& x );
272 |
273 | Then, the try to add the pointer to function will cause compile-time error,
274 | because of compiler can't select the correct version byself:
275 | add_function("conj",&conjugate); // ERROR HERE
276 |
277 | To workaround the problem you need point compiler to which exactly function you mean:
278 | add_function("conj", (const cln_N (*) ( const cl_N& )) &conjugate);
279 | or:
280 | add_function("conj", (const cln_R (*) ( const cl_R& )) &conjugate);
281 |
282 | As alternative, declare pointer to the function you have in mind, and add it then:
283 | const cln_N (*conj_func)( const cl_N& ) = conjugate; // That's fine
284 | add_function("conj", conj_func);
285 |
286 | To reduce the number of such type castings, the MathExpressionBase::add_function() has a lots of overloads,
287 | but if you encounter some case which is not handled by these overloads, then direct compiler manually.
288 |
--------------------------------------------------------------------------------
/src/shared/mathexpression/StdComplexMathExpression.h:
--------------------------------------------------------------------------------
1 | /*
2 | * StdComplexMathExpression.h
3 | *
4 | * Created on: May 27, 2009
5 | * Author: amyznikov
6 | */
7 |
8 | #ifndef __STD_COMPLEX_MATHEXPRESSION_H__
9 | #define __STD_COMPLEX_MATHEXPRESSION_H__
10 |
11 | #include
12 | #include
13 | #include
14 | #include
15 | #include "MathExpressionBase.h"
16 |
17 | template
18 | class StdComplexMathExpression
19 | : public MathExpressionBase >
20 | {
21 | typedef StdComplexMathExpression this_class;
22 | typedef MathExpressionBase > base_class;
23 | using base_class :: BinaryOpTable;
24 |
25 | public:
26 |
27 | typedef T value_type;
28 | typedef std::complex complex_type;
29 | StdComplexMathExpression()
30 | {
31 | BinaryOpTable.set_num_levels(4);
32 | BinaryOpTable[0]->template add > ("==");
33 | BinaryOpTable[0]->template add >("!=");
34 | BinaryOpTable[1]->template add("+");
35 | BinaryOpTable[1]->template add("-");
36 | BinaryOpTable[2]->template add("*");
37 | BinaryOpTable[2]->template add("/");
38 | BinaryOpTable[3]->template add >("**");
39 |
40 | base_class::template add_function >("conj","complex conjugate");
41 | base_class::template add_function > ("exp","complex exponential function");
42 | base_class::template add_function >("cos","complex cosine function");
43 | base_class::template add_function >("cosh","complex hyperbolic cosine");
44 | base_class::template add_function >("log","natural logarithm of a complex number");
45 | base_class::template add_function >("log10","base-10 logarithm of a complex number");
46 | base_class::template add_function >("pow","complex power function");
47 | base_class::template add_function >("sin","complex sine function");
48 | base_class::template add_function >("sinh","complex hyperbolic sine");
49 | base_class::template add_function >("sqrt","complex square root");
50 | base_class::template add_function >("tan","complex tangent function");
51 | base_class::template add_function >("tanh","complex hyperbolic tangent");
52 |
53 | base_class::template add_function<&this_class::real> ("real","get real part of a complex number");
54 | base_class::template add_function<&this_class::imag> ("imag","get imaginary part of a complex number");
55 | base_class::template add_function<&this_class::polar>("polar","Return complex with magnitude @a rho and angle @a theta");
56 | base_class::template add_function<&this_class::arg >("arg","get argument of a complex number");
57 | base_class::template add_function<&this_class::abs>("abs","absolute value of a complex number");
58 | base_class::template add_function<&this_class::norm>("norm","Return @a z magnitude squared");
59 | base_class::template add_function<&this_class::rand> ("rand","get real random number");
60 | base_class::template add_function<&this_class::crand> ("crand","get complex random number");
61 |
62 | base_class::template add_function("sum",base_class :: sum,"calculates the sum of arguments");
63 | base_class::template add_function("product",base_class :: product,"calculates the product of arguments");
64 |
65 | }
66 | protected:
67 | static complex_type rand()
68 | { return complex_type((value_type)::rand()/RAND_MAX);
69 | }
70 | static complex_type crand()
71 | { return complex_type((value_type)::rand()/RAND_MAX,(value_type)::rand()/RAND_MAX);
72 | }
73 | static complex_type real( const complex_type & x )
74 | { return x.real();
75 | }
76 | static complex_type imag( const complex_type & x )
77 | { return x.imag();
78 | }
79 | static complex_type arg( const complex_type & x )
80 | { return std::arg(x);
81 | }
82 | static complex_type abs( const complex_type & x )
83 | { return std::abs(x);
84 | }
85 | static complex_type norm( const complex_type & x )
86 | { return std::norm(x);
87 | }
88 | static complex_type polar(const complex_type & a, const complex_type & b )
89 | {
90 | if( a.imag() != 0 )
91 | { throw std::invalid_argument("polar() : first argument is not real");
92 | }
93 | if( b.imag() != 0 )
94 | { throw std::invalid_argument("polar() : second argument is not real");
95 | }
96 | return std::polar(a.real(),b.real());
97 | }
98 |
99 | protected:
100 | bool parse_number( complex_type * value, const char * curpos, char ** endptr )
101 | {
102 | if( (*curpos == 'i' || *curpos == 'I') && !base_class :: can_be_part_of_identifier(*(curpos+1)) )
103 | { value->real() = 0, value->imag() = 1;
104 | *endptr = (char*)( curpos+1 );
105 | return true;
106 | }
107 |
108 | value_type v = (value_type)strtod(curpos,endptr);
109 | if( *endptr > curpos )
110 | {
111 | if( **endptr=='i' || **endptr == 'I' )
112 | { value->real() = 0, value->imag() = v;
113 | ++*endptr;
114 | }
115 | else
116 | { value->real() = v, value->imag() = 0;
117 | }
118 | return true;
119 | }
120 | return false;
121 | }
122 | };
123 |
124 |
125 |
126 | #endif /* __STD_COMPLEX_MATHEXPRESSION_H__ */
127 |
--------------------------------------------------------------------------------
/src/shared/sgml/sgml.cpp:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Cail Lomecb (Igor Ruskih) 1999-2001
3 | // You can use, modify, distribute this code or any other part
4 | // of this program in sources or in binaries only according
5 | // to License (see /doc/license.txt for more information).
6 | //
7 |
8 | // creates object tree structure on html/xml files
9 |
10 | #include
11 | #include
12 | #include
13 | #include
14 |
15 | #include
16 | #include
17 |
18 | CSgmlEl::CSgmlEl()
19 | {
20 | eparent= nullptr;
21 | enext = nullptr;
22 | eprev = nullptr;
23 | echild = nullptr;
24 | chnum = 0;
25 | type = EBASEEL;
26 |
27 | name[0] = 0;
28 | content= nullptr;
29 | contentsz = 0;
30 | parnum = 0;
31 | }
32 |
33 | CSgmlEl::~CSgmlEl()
34 | {
35 | if (type == EBASEEL && enext)
36 | enext->destroylevel();
37 | if (echild)
38 | echild->destroylevel();
39 | // if (name) delete[] name;
40 | delete[] content;
41 | for (int i = 0; i < parnum; i++)
42 | {
43 | if (params[i][0])
44 | delete params[i][0];
45 | if (params[i][1])
46 | delete params[i][1];
47 | }
48 | }
49 |
50 | PSgmlEl CSgmlEl::createnew(ElType type, PSgmlEl parent, PSgmlEl after)
51 | {
52 | PSgmlEl El = new CSgmlEl;
53 | El->type = type;
54 | if (parent)
55 | {
56 | El->enext = parent->echild;
57 | El->eparent = parent;
58 | if (parent->echild)
59 | parent->echild->eprev = El;
60 | parent->echild = El;
61 | parent->chnum++;
62 | parent->type = EBLOCKEDEL;
63 | }
64 | else if (after)
65 | after->insert(El);
66 | return El;
67 | }
68 |
69 | bool CSgmlEl::init()
70 | {
71 | return true;
72 | }
73 |
74 | wchar_t *CSgmlEl::readfile(const wchar_t *basename, const wchar_t *fname, const wchar_t *buf, int pos, int *bufsize)
75 | {
76 | wchar_t tmpfname[4097];
77 | wcscpy(tmpfname, basename);
78 | int i;
79 | for (i = (int)wcslen(tmpfname); i; i--)
80 | {
81 | if (tmpfname[i] == '/' || tmpfname[i] == '\\')
82 | break;
83 | }
84 | wcscpy(tmpfname+i+1, fname);
85 | #if 0
86 | for (i = 0; tmpfname[i]; i++)
87 | {
88 | if (tmpfname[i] == '\\')
89 | tmpfname[i] = '/';
90 | }
91 | #endif
92 | FILE *fp = _wfopen(tmpfname, L"rb");
93 | if (fp == nullptr)
94 | return nullptr;
95 | unsigned len, num_read = 0;
96 |
97 | unsigned char bom[2];
98 | bool ansi = false;
99 | fread(bom, 2, 1, fp);
100 |
101 | fseek(fp, 0, SEEK_END);
102 | len = ftell(fp);
103 | rewind(fp);
104 |
105 | if (len < 2)
106 | {
107 | fclose(fp);
108 | return nullptr;
109 | }
110 |
111 | if (bom[0] != 0xff && bom[1] != 0xfe)
112 | {
113 | ansi = true;
114 | len *= 2;
115 | }
116 |
117 | unsigned wl = (len + 1) / 2;
118 | wchar_t *src;
119 |
120 | if (buf == nullptr)
121 | {
122 | src = (wchar_t *)malloc(len + 4);
123 | if (bufsize)
124 | *bufsize = wl;
125 | pos = 0;
126 | }
127 | else
128 | {
129 | if (!bufsize || !pos)
130 | return nullptr;
131 | src = (wchar_t *)realloc((void *)buf, *bufsize * 2 + len + 4);
132 | memmove(src + pos + wl, src + pos, (*bufsize - pos) * 2);
133 | *bufsize += wl;
134 | }
135 | if (ansi)
136 | {
137 | num_read = (unsigned)fread(src + pos, 1, wl, fp);
138 | char *asrc = (char *)(src + pos) + wl - 1;
139 | wchar_t *dst = src + pos + wl - 1;
140 | for (int i = len / 2; i > 0; i--, dst--, asrc--)
141 | {
142 | mbtowc(dst, asrc, 1);
143 | }
144 | num_read *= 2;
145 | } else
146 | {
147 | num_read = (unsigned)fread(src + pos, 1, len, fp);
148 | }
149 | fclose(fp);
150 |
151 | if (num_read != len)
152 | {
153 | free(src);
154 | return nullptr;
155 | }
156 |
157 | return src;
158 | }
159 |
160 | bool CSgmlEl::parse(const wchar_t *basename, const wchar_t *fname)
161 | {
162 | PSgmlEl Child, Parent, Next = nullptr;
163 | int i, j, lins, line;
164 | int ls, le, rs, re, empty;
165 |
166 | int sz = 0;
167 | wchar_t *src = readfile(basename, fname, nullptr, 0, &sz);
168 | if (src == nullptr)
169 | return false;
170 |
171 | // start object - base
172 | type = EBASEEL;
173 | Next = this;
174 |
175 | lins = line = 0;
176 | for (i = 0; i < sz; i++)
177 | {
178 | if (i >= sz)
179 | continue;
180 |
181 | // comments
182 | if (src[i] == '<' && src[i+1] == '!' && src[i+2] == '-' && src[i+3] == '-' && i+4 < sz)
183 | {
184 | i += 4;
185 | while((src[i] != '-' || src[i+1] != '-' || src[i+2] != '>') && i+3 < sz)
186 | i++;
187 | i+=3;
188 | }
189 |
190 | line = i;
191 |
192 | if (src[i] == '<' || i >= sz-1)
193 | {
194 | while (line > lins)
195 | {
196 | // linear
197 | j = lins;
198 | while (iswspace(src[j]) && j < i)
199 | j++;
200 | if (j == i)
201 | break; // empty text
202 | Child = createnew(EPLAINEL,nullptr,Next);
203 | Child->init();
204 | Child->setcontent(src + lins, i - lins);
205 | Next = Child;
206 | break;
207 | }
208 | if (i == sz-1)
209 | continue;
210 | // start or single tag
211 | if (src[i+1] != '/')
212 | {
213 | Child = createnew(ESINGLEEL,nullptr,Next);
214 | Child->init();
215 | Next = Child;
216 | j = i+1;
217 | while (src[i] != '>' && !iswspace(src[i]) && i < sz)
218 | i++;
219 | // Child->name = new wchar_t[i-j+1];
220 | if (i-j > MAXTAG)
221 | i = j + MAXTAG - 1;
222 | wcsncpy(Child->name, src+j, i-j);
223 | Child->name[i-j] = 0;
224 | // parameters
225 | Child->parnum = 0;
226 | while (src[i] != '>' && Child->parnum < MAXPARAMS && i < sz)
227 | {
228 | ls = i;
229 | while (iswspace(src[ls]) && ls < sz)
230 | ls++;
231 | le = ls;
232 | while (!iswspace(src[le]) && src[le]!='>' && src[le]!='=' && le < sz)
233 | le++;
234 | rs = le;
235 | while (iswspace(src[rs]) && rs < sz)
236 | rs++;
237 | empty = 1;
238 | if (src[rs] == '=')
239 | {
240 | empty = 0;
241 | rs++;
242 | while (iswspace(src[rs]) && rs < sz)
243 | rs++;
244 | re = rs;
245 | if (src[re] == '"')
246 | {
247 | while (src[++re] != '"' && re < sz)
248 | ;
249 | rs++;
250 | i = re+1;
251 | }
252 | else if (src[re] == '\'')
253 | {
254 | while (src[++re] != '\'' && re < sz)
255 | ;
256 | rs++;
257 | i = re+1;
258 | } else
259 | {
260 | while (!iswspace(src[re]) && src[re] != '>' && re < sz)
261 | re++;
262 | i = re;
263 | }
264 | } else
265 | i = re = rs;
266 |
267 | if (ls == le)
268 | continue;
269 | if (rs == re && empty)
270 | {
271 | rs = ls;
272 | re = le;
273 | }
274 |
275 | int pn = Child->parnum;
276 | Child->params[pn][0] = new wchar_t[le-ls+1];
277 | wcsncpy(Child->params[pn][0], src+ls, le-ls);
278 | Child->params[pn][0][le-ls] = 0;
279 |
280 | Child->params[pn][1] = new wchar_t[re-rs+1];
281 | wcsncpy(Child->params[pn][1], src+rs, re-rs);
282 | Child->params[pn][1][re-rs] = 0;
283 |
284 | Child->parnum++;
285 |
286 | substquote(Child->params[pn], L"<", '<');
287 | substquote(Child->params[pn], L">", '>');
288 | substquote(Child->params[pn], L"&", '&');
289 | substquote(Child->params[pn], L""", '"');
290 | }
291 | lins = i+1;
292 |
293 | // include
294 | if (_wcsicmp(Child->name, L"xi:include") == 0)
295 | {
296 | wchar_t *fn = Child->GetChrParam(L"href");
297 | if (fn)
298 | {
299 | wchar_t *new_src = readfile(basename, fn, src, i + 1, &sz);
300 | if (new_src)
301 | src = new_src;
302 | }
303 | }
304 | } else
305 | { // end tag
306 | j = i+2;
307 | i += 2;
308 | while (src[i] != '>' && !iswspace(src[i]) && i < sz)
309 | i++;
310 | int cn = 0;
311 | for (Parent = Next; Parent->eprev; Parent = Parent->eprev, cn++)
312 | {
313 | if (!*Parent->name)
314 | continue;
315 | int len = (int)wcslen(Parent->name);
316 | if (len != i-j)
317 | continue;
318 | if (Parent->type != ESINGLEEL || _wcsnicmp((wchar_t*)src+j, Parent->name, len))
319 | continue;
320 | break;
321 | }
322 |
323 | if (Parent && Parent->eprev)
324 | {
325 | Parent->echild = Parent->enext;
326 | Parent->chnum = cn;
327 | Parent->type = EBLOCKEDEL;
328 | Child = Parent->echild;
329 | if (Child)
330 | Child->eprev = nullptr;
331 | while(Child)
332 | {
333 | Child->eparent = Parent;
334 | Child = Child->enext;
335 | }
336 | Parent->enext = nullptr;
337 | Next = Parent;
338 | }
339 | while (src[i] != '>' && i < sz)
340 | i++;
341 | lins = i+1;
342 | }
343 | }
344 | }
345 |
346 | free(src);
347 | return true;
348 | }
349 |
350 | void CSgmlEl::substquote(SParams par, wchar_t *sstr, wchar_t c)
351 | {
352 | int len = (int)wcslen(sstr);
353 | int plen = (int)wcslen(par[1]);
354 |
355 | for (int i = 0; i <= plen-len; i++)
356 | {
357 | if (!wcsncmp(par[1]+i, sstr, len))
358 | {
359 | par[1][i] = c;
360 | for(int j = i+1; j <= plen-len+1; j++)
361 | par[1][j] = par[1][j+len-1];
362 | plen -= len-1;
363 | }
364 | }
365 | }
366 |
367 | bool CSgmlEl::setcontent(const wchar_t *src, int sz)
368 | {
369 | content = new wchar_t[sz+1];
370 | memmove(content, src, sz);
371 | content[sz] = 0;
372 | contentsz = sz;
373 | return true;
374 | }
375 |
376 | void CSgmlEl::insert(PSgmlEl El)
377 | {
378 | El->eprev = this;
379 | El->enext = this->enext;
380 | El->eparent = this->eparent;
381 | if (this->enext)
382 | this->enext->eprev = El;
383 | this->enext = El;
384 | }
385 |
386 | // recursive deletion
387 | void CSgmlEl::destroylevel()
388 | {
389 | if (enext)
390 | enext->destroylevel();
391 | delete this;
392 | }
393 |
394 | PSgmlEl CSgmlEl::parent()
395 | {
396 | return eparent;
397 | }
398 |
399 | PSgmlEl CSgmlEl::next()
400 | {
401 | return enext;
402 | }
403 |
404 | PSgmlEl CSgmlEl::prev()
405 | {
406 | return eprev;
407 | }
408 |
409 | PSgmlEl CSgmlEl::child()
410 | {
411 | return echild;
412 | }
413 |
414 | ElType CSgmlEl::gettype()
415 | {
416 | return type;
417 | }
418 |
419 | wchar_t *CSgmlEl::getname()
420 | {
421 | if (!*name)
422 | return nullptr;
423 | return name;
424 | }
425 |
426 | wchar_t *CSgmlEl::getcontent()
427 | {
428 | return content;
429 | }
430 |
431 | int CSgmlEl::getcontentsize()
432 | {
433 | return contentsz;
434 | }
435 |
436 | wchar_t* CSgmlEl::GetParam(int no)
437 | {
438 | if (no >= parnum)
439 | return nullptr;
440 | return params[no][0];
441 | }
442 |
443 | wchar_t* CSgmlEl::GetChrParam(const wchar_t *par)
444 | {
445 | for (int i = 0; i < parnum; i++)
446 | {
447 | if (!_wcsicmp(par,params[i][0]))
448 | return params[i][1];
449 | }
450 | return nullptr;
451 | }
452 |
453 | bool CSgmlEl::GetIntParam(const wchar_t *par, int *result)
454 | {
455 | double res = 0;
456 | for (int i=0; i < parnum; i++)
457 | {
458 | if (!_wcsicmp(par,params[i][0]))
459 | {
460 | bool b = get_number(params[i][1],&res);
461 | *result = b ? (int)res : 0;
462 | return b;
463 | }
464 | }
465 | return false;
466 | }
467 |
468 | bool CSgmlEl::GetFloatParam(const wchar_t *par, double *result)
469 | {
470 | double res;
471 | for (int i = 0; i < parnum; i++)
472 | {
473 | if (!_wcsicmp(par,params[i][0]))
474 | {
475 | bool b = get_number(params[i][1],&res);
476 | *result = b ? (double)res : 0;
477 | return b;
478 | }
479 | }
480 | return false;
481 | }
482 |
483 | PSgmlEl CSgmlEl::search(const wchar_t *TagName)
484 | {
485 | PSgmlEl Next = this->enext;
486 | while(Next)
487 | {
488 | if (!_wcsicmp(TagName,Next->name))
489 | return Next;
490 | Next = Next->enext;
491 | }
492 | return Next;
493 | }
494 |
495 | PSgmlEl CSgmlEl::enumchilds(int no)
496 | {
497 | PSgmlEl El = this->echild;
498 | while(no && El)
499 | {
500 | El = El->enext;
501 | no--;
502 | }
503 | return El;
504 | }
505 |
506 | PSgmlEl CSgmlEl::fprev()
507 | {
508 | PSgmlEl El = this;
509 | if (!El->eprev)
510 | return El->eparent;
511 | if (El->eprev->echild)
512 | return El->eprev->echild->flast();
513 | return El->eprev;
514 | }
515 |
516 | PSgmlEl CSgmlEl::fnext()
517 | {
518 | PSgmlEl El = this;
519 | if (El->echild)
520 | return El->echild;
521 | while(!El->enext)
522 | {
523 | El = El->eparent;
524 | if (!El)
525 | return nullptr;
526 | }
527 | return El->enext;
528 | }
529 |
530 | PSgmlEl CSgmlEl::ffirst()
531 | {
532 | PSgmlEl Prev = this;
533 | while(Prev)
534 | {
535 | if (!Prev->eprev)
536 | return Prev;
537 | Prev = Prev->eprev;
538 | }
539 | return Prev;
540 | }
541 |
542 | PSgmlEl CSgmlEl::flast()
543 | {
544 | PSgmlEl Nxt = this;
545 | while(Nxt->enext || Nxt->echild)
546 | {
547 | if (Nxt->enext)
548 | {
549 | Nxt = Nxt->enext;
550 | continue;
551 | }
552 | if (Nxt->echild)
553 | {
554 | Nxt = Nxt->echild;
555 | continue;
556 | }
557 | }
558 | return Nxt;
559 | }
560 |
--------------------------------------------------------------------------------
/src/shared/sgml/sgml.h:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Cail Lomecb (Igor Ruskih) 1999-2001
3 | // You can use, modify, distribute this code or any other part
4 | // of this program in sources or in binaries only according
5 | // to License (see /doc/license.txt for more information).
6 | //
7 | #ifndef _CSGML_
8 | #define _CSGML_
9 |
10 | // sometimes need it...
11 | bool get_number(wchar_t *str, double *res);
12 | #ifdef _UNIX_
13 | extern "C" int stricmp(wchar_t *s1, wchar_t *s2);
14 | extern "C" int strnicmp(wchar_t *s1, wchar_t *s2, int n);
15 | #endif
16 |
17 | typedef class CSgmlEl *PSgmlEl;
18 | typedef class CSgmlEdit *PSgmlEdit;
19 | typedef wchar_t *SParams[2];
20 |
21 | #define MAXPARAMS 0x20
22 | #define MAXTAG 0x10
23 | #define SP 1
24 |
25 | enum ElType{
26 | EPLAINEL, ESINGLEEL, EBLOCKEDEL, EBASEEL
27 | };
28 |
29 | class CSgmlEl
30 | {
31 | //for derived classes
32 | virtual PSgmlEl createnew(ElType type, PSgmlEl parent, PSgmlEl after);
33 | virtual bool init();
34 |
35 | void destroylevel();
36 | void insert(PSgmlEl El);
37 | bool setcontent(const wchar_t *src,int sz);
38 | void substquote(SParams par, wchar_t *sstr, wchar_t c);
39 |
40 | wchar_t *content;
41 | int contentsz;
42 | wchar_t name[MAXTAG];
43 |
44 | PSgmlEl eparent;
45 | PSgmlEl enext;
46 | PSgmlEl eprev;
47 | PSgmlEl echild;
48 | int chnum;
49 | ElType type;
50 |
51 | SParams params[MAXPARAMS];
52 | int parnum;
53 |
54 | public:
55 | CSgmlEl();
56 | ~CSgmlEl();
57 |
58 | bool parse(const wchar_t *modname, const wchar_t *fname);
59 |
60 | virtual PSgmlEl parent();
61 | virtual PSgmlEl next();
62 | virtual PSgmlEl prev();
63 | virtual PSgmlEl child();
64 |
65 | ElType gettype();
66 | wchar_t *getname();
67 | wchar_t *getcontent();
68 | int getcontentsize();
69 |
70 | wchar_t *GetParam(int no);
71 | wchar_t *GetChrParam(const wchar_t *par);
72 | bool GetIntParam(const wchar_t *par, int *result);
73 | bool GetFloatParam(const wchar_t *par, double *result);
74 |
75 | PSgmlEl search(const wchar_t *TagName);
76 | PSgmlEl enumchilds(int no);
77 | // in full hierarchy
78 | virtual PSgmlEl fprev();
79 | virtual PSgmlEl fnext();
80 | virtual PSgmlEl ffirst();
81 | virtual PSgmlEl flast();
82 |
83 | wchar_t *readfile(const wchar_t *modname, const wchar_t *fname, const wchar_t *buf, int pos, int *bufsize);
84 | };
85 |
86 | #endif
87 |
--------------------------------------------------------------------------------
/src/shared/sgml/sgmledit.cpp:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Cail Lomecb (Igor Ruskih) 1999-2001
3 | // You can use, modify, distribute this code or any other part
4 | // of this program in sources or in binaries only according
5 | // to License (see /doc/license.txt for more information).
6 | //
7 |
8 | // lets you modify objects...
9 |
10 | #include
11 | #include
12 |
13 | CSgmlEdit::CSgmlEdit(){ };
14 | CSgmlEdit::~CSgmlEdit()
15 | {
16 | if (eparent){
17 | eparent->chnum--;
18 | if (eparent->echild == this) eparent->echild = enext;
19 | };
20 | if (enext) enext->eprev = eprev;
21 | if (eprev) eprev->enext = enext;
22 | };
23 |
24 | void CSgmlEdit::setname(wchar_t *newname)
25 | {
26 | /* if (name){
27 | delete name;
28 | name = 0;
29 | };*/
30 | if (newname){
31 | // name = new wchar_t[wcslen(newname)+1];
32 | // !!! length
33 | wcscpy(name,newname);
34 | };
35 | };
36 | bool CSgmlEdit::addparam(wchar_t *name, wchar_t *val)
37 | {
38 | int i;
39 | if (parnum == MAXPARAMS) return false;
40 | i = parnum;
41 | parnum++;
42 | for (i = 0; i < parnum - 1; i++)
43 | if (!wcsicmp(params[i][0],name)){
44 | delete params[i][0];
45 | delete params[i][1];
46 | parnum--;
47 | break;
48 | };
49 | params[i][0] = new wchar_t[wcslen(name)+1];
50 | params[i][1] = new wchar_t[wcslen(val)+1];
51 | wcsrcpy(params[i][0], name);
52 | wcscpy(params[i][1], val);
53 | return true;
54 | };
55 | bool CSgmlEdit::addparam(wchar_t *name, int val)
56 | {
57 | wchar_t IntVal[20];
58 | swprintf(IntVal,L"%d",val);
59 | return addparam(name,IntVal);
60 | };
61 | bool CSgmlEdit::addparam(wchar_t *name, double val)
62 | {
63 | wchar_t FltVal[20];
64 | swprintf(FltVal,L"%.2f",val);
65 | return addparam(name,FltVal);
66 | };
67 | bool CSgmlEdit::delparam(wchar_t *name)
68 | {
69 | for (int i = 0; i < parnum; i++)
70 | if (!wcsicmp(params[i][0],name)){
71 | delete params[i][0];
72 | delete params[i][1];
73 | params[i][0] = params[parnum-1][0];
74 | params[i][1] = params[parnum-1][1];
75 | parnum--;
76 | return true;
77 | };
78 | return false;
79 | };
80 | bool CSgmlEdit::changecontent(wchar_t *data, int len)
81 | {
82 | if (type != EPLAINEL) return false;
83 | if (content) delete[] content;
84 | content = new wchar_t[len];
85 | memmove(content, data, len);
86 | contentsz = len;
87 | return true;
88 | };
89 |
90 | bool CSgmlEdit::isloop(PSgmlEdit El, PSgmlEdit Parent)
91 | {
92 | while(Parent){
93 | if (El == Parent) return true;
94 | Parent = (PSgmlEdit)Parent->eparent;
95 | };
96 | return false;
97 | };
98 | bool CSgmlEdit::move(PSgmlEdit parent, PSgmlEdit after)
99 | {
100 | if (isloop(this,parent)) return false;
101 | if (after && isloop(this,(PSgmlEdit)after->eparent)) return false;
102 | if (after){
103 | if (enext) enext->eprev = eprev;
104 | if (eprev) eprev->enext = enext;
105 | if (this->eparent->echild == this)
106 | this->eparent->echild = this->enext;
107 | this->eparent->chnum--;
108 |
109 | after->insert(this);
110 | this->eparent = after->eparent;
111 | if (this->eparent) this->eparent->chnum++;
112 | return true;
113 | }else
114 | if (parent){
115 | if (enext) enext->eprev = eprev;
116 | if (eprev) eprev->enext = enext;
117 | if (this->eparent->echild == this)
118 | this->eparent->echild = this->enext;
119 | this->eparent->chnum--;
120 | this->eparent = parent;
121 | enext = parent->echild;
122 | eprev = 0;
123 | this->eparent->echild = this;
124 | this->eparent->chnum++;
125 | if (enext) enext->eprev = this;
126 | return true;
127 | };
128 | return false;
129 | };
130 |
131 | int CSgmlEdit::getlevelsize(int Lev)
132 | {
133 | int Pos = 0;
134 | PSgmlEdit tmp = this;
135 | do{
136 | if (tmp->gettype() != EPLAINEL)
137 | Pos +=Lev*SP;
138 | if (tmp->name[0])
139 | Pos += wcslen(tmp->name)+1;
140 | for (int i = 0;i < tmp->parnum;i++){
141 | Pos +=wcslen(tmp->params[i][0])+2;
142 | Pos +=wcslen(tmp->params[i][1])+2;
143 | };
144 | if (tmp->name[0]) Pos +=3;
145 | if (tmp->gettype() == EPLAINEL && tmp->content)
146 | Pos += wcslen(tmp->content)+2;
147 | if (tmp->echild)
148 | Pos += PSgmlEdit(tmp->echild)->getlevelsize(Lev+1);
149 | if (tmp->gettype() == EBLOCKEDEL && tmp->name){
150 | Pos += Lev*SP+5;
151 | Pos += wcslen(tmp->name);
152 | };
153 | tmp = (PSgmlEdit)tmp->enext;
154 | }while(tmp);
155 | return Pos;
156 | };
157 |
158 | int CSgmlEdit::savelevel(wchar_t *Dest,int Lev)
159 | {
160 | int i,Pos = 0;
161 | PSgmlEdit tmp = this;
162 | do{
163 | if (tmp->gettype() != EPLAINEL)
164 | for(i = 0; i < Lev*SP; i++)
165 | Pos += swprintf(Dest+Pos,L" ");
166 | if (tmp->name[0])
167 | Pos += swprintf(Dest+Pos,L"<%s",tmp->name);
168 | for (i = 0; i < tmp->parnum; i++){
169 | Pos += swprintf(Dest+Pos,L" %s=",tmp->params[i][0]);
170 | Pos += swprintf(Dest+Pos,L"\"%s\"",tmp->params[i][1]);
171 | }
172 | if (tmp->name[0])
173 | Pos += swprintf(Dest+Pos,L">\r\n");
174 | if (tmp->gettype() == EPLAINEL)
175 | Pos += swprintf(Dest+Pos,L"%s\r\n", tmp->content);
176 | if (tmp->echild)
177 | Pos += PSgmlEdit(tmp->echild)->savelevel(Dest+Pos,Lev+1);
178 | if (tmp->gettype() == EBLOCKEDEL){
179 | for(i = 0; i < Lev*SP; i++)
180 | Pos += swprintf(Dest+Pos,L" ");
181 | Pos += swprintf(Dest+Pos,L"");
182 | if (tmp->name) Pos += swprintf(Dest+Pos,L"%s",tmp->name);
183 | Pos += swprintf(Dest+Pos,L">\r\n");
184 | };
185 | tmp = (PSgmlEdit)tmp->enext;
186 | }while(tmp);
187 | return Pos;
188 | };
189 |
--------------------------------------------------------------------------------
/src/shared/sgml/sgmledit.h:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Cail Lomecb (Igor Ruskih) 1999-2001
3 | // You can use, modify, distribute this code or any other part
4 | // of this program in sources or in binaries only according
5 | // to License (see /doc/license.txt for more information).
6 | //
7 | #ifndef _CSGMLEDIT_
8 | #define _CSGMLEDIT_
9 |
10 | #include
11 |
12 | class CSgmlEdit:public CSgmlEl
13 | {
14 | protected:
15 | bool isloop(PSgmlEdit El, PSgmlEdit Parent);
16 | public:
17 | CSgmlEdit();
18 | ~CSgmlEdit();
19 |
20 | void setname(wchar_t *newname);
21 |
22 | // parameters add and change
23 | bool addparam(wchar_t *name, wchar_t *val);
24 | bool addparam(wchar_t *name, int val);
25 | bool addparam(wchar_t *name, double val);
26 | bool changecontent(wchar_t *data, int len);
27 | bool delparam(wchar_t *name);
28 |
29 | bool move(PSgmlEdit parent, PSgmlEdit after);
30 | PSgmlEdit copytree(PSgmlEdit el);
31 |
32 | // saving tree into text
33 | int getlevelsize(int lev);
34 | int savelevel(wchar_t *dest,int lev);
35 | };
36 |
37 | #endif
38 |
--------------------------------------------------------------------------------
/src/shared/sgml/tools.cpp:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) Cail Lomecb (Igor Ruskih) 1999-2001
3 | // You can use, modify, distribute this code or any other part
4 | // of this program in sources or in binaries only according
5 | // to License (see /doc/license.txt for more information).
6 | //
7 | #include
8 | #include
9 |
10 | bool inline isspace(wchar_t c)
11 | {
12 | if (c==0x20 || c=='\t' || c=='\r' || c=='\n') return true;
13 | return false;
14 | };
15 | // modifed GetNumber - sign extension!
16 | bool get_number(wchar_t *str, double *res)
17 | {
18 | double Numr, r, flt;
19 | int pos, Type, Num;
20 | int s, e, i, j, pt, k, ExpS, ExpE;
21 | bool Exp = false, ExpSign = true, sign = false;
22 |
23 | pos = (int)wcslen(str);
24 | if (!pos) return false;
25 |
26 | s = 0;
27 | e = pos;
28 | Type = 3;
29 | while(1){
30 | if(str[0] == '0' && (str[1] == 'x' || str[1] == 'X')){
31 | s = 2;
32 | Type = 0;
33 | break;
34 | };
35 | if (str[0] == '$' || str[0] == '#'){
36 | s = 1;
37 | Type = 0;
38 | break;
39 | };
40 | if (str[0] == '-'){
41 | Type = 3;
42 | s = 1;
43 | sign = true;
44 | break;
45 | };
46 | break;
47 | };
48 |
49 | switch(Type){
50 | case 0:
51 | Num = 0;
52 | i = e-1;
53 | while(i >= s){
54 | j = str[i];
55 | if(((j < 0x30) || (j > 0x39)) &&
56 | (((j | 0x20) < 'a') || ((j | 0x20) > 'f')))
57 | return false;
58 | if(j > 0x40) j -=7;
59 | j &=15;
60 | if(i > e-9) Num |= (j << ((e-i-1)*4) );
61 | i--;
62 | };
63 | *res = (int)Num;
64 | break;
65 | case 3:
66 | for(i = s;i < e;i++)
67 | if (str[i] == 'e' || str[i] =='E'){
68 | Exp = true;
69 | ExpS = i+1;
70 | if (str[i+1] == '+' || str[i+1] == '-'){
71 | ExpS++;
72 | if (str[i+1] == '-') ExpSign = false;
73 | };
74 | ExpE = e;
75 | e = i;
76 | };
77 | pt = e;
78 | for(i = s;i < e;i++)
79 | if (str[i] == '.'){
80 | pt = i;
81 | break;
82 | };
83 | Numr = 0;
84 | i = pt-1;
85 | while(i >= s){
86 | j = str[i];
87 | if((j < 0x30)||(j > 0x39))
88 | return false;
89 | j &=15;
90 | k = pt-i-1;
91 | r = (long double)j;
92 | while(k){
93 | k--;
94 | r *=10;
95 | };
96 | Numr += r;
97 | i--;
98 | };
99 | i = e-1;
100 | while(i > pt){
101 | j = str[i];
102 | if((j < 0x30)||(j > 0x39))
103 | return false;
104 | j &=15;
105 | k = i-pt;
106 | r = 0;
107 | r = j;
108 | while(k){
109 | k--;
110 | r /=10;
111 | };
112 | Numr += r;
113 | i--;
114 | };
115 | if (Exp){
116 | flt = 0;
117 | i = ExpE-1;
118 | while(i >= ExpS){
119 | j = str[i];
120 | if((j < 0x30)||(j > 0x39))
121 | return false;
122 | j &=15;
123 | k = ExpE-i-1;
124 | r = (long double)j;
125 | while(k){
126 | k--;
127 | r *=10;
128 | };
129 | flt += r;
130 | i--;
131 | };
132 | if (ExpSign) Numr = Numr*pow(10,flt);
133 | if (!ExpSign) Numr = Numr/pow(10,flt);
134 | };
135 | *res = Numr;
136 | break;
137 | };
138 | if (sign) *res = -(*res);
139 | return true;
140 | };
141 |
--------------------------------------------------------------------------------
/src/shared/trex/TRexpp.h:
--------------------------------------------------------------------------------
1 | #ifndef _TREXPP_H_
2 | #define _TREXPP_H_
3 | /***************************************************************
4 | T-Rex a tiny regular expression library
5 |
6 | Copyright (C) 2003-2004 Alberto Demichelis
7 |
8 | This software is provided 'as-is', without any express
9 | or implied warranty. In no event will the authors be held
10 | liable for any damages arising from the use of this software.
11 |
12 | Permission is granted to anyone to use this software for
13 | any purpose, including commercial applications, and to alter
14 | it and redistribute it freely, subject to the following restrictions:
15 |
16 | 1. The origin of this software must not be misrepresented;
17 | you must not claim that you wrote the original software.
18 | If you use this software in a product, an acknowledgment
19 | in the product documentation would be appreciated but
20 | is not required.
21 |
22 | 2. Altered source versions must be plainly marked as such,
23 | and must not be misrepresented as being the original software.
24 |
25 | 3. This notice may not be removed or altered from any
26 | source distribution.
27 |
28 | ****************************************************************/
29 |
30 | extern "C" {
31 | #include "trex.h"
32 | }
33 |
34 | struct TRexParseException{TRexParseException(const TRexChar *c):desc(c){}const TRexChar *desc;};
35 |
36 | class TRexpp {
37 | public:
38 | TRexpp() { _exp = (TRex *)0; }
39 | ~TRexpp() { CleanUp(); }
40 | // compiles a regular expression
41 | void Compile(const TRexChar *pattern) {
42 | const TRexChar *error;
43 | CleanUp();
44 | if(!(_exp = trex_compile(pattern,&error)))
45 | throw TRexParseException(error);
46 | }
47 | // return true if the given text match the expression
48 | bool Match(const TRexChar* text) {
49 | return _exp?(trex_match(_exp,text) != 0):false;
50 | }
51 | // Searches for the first match of the expression in a zero terminated string
52 | bool Search(const TRexChar* text, const TRexChar** out_begin, const TRexChar** out_end) {
53 | return _exp?(trex_search(_exp,text,out_begin,out_end) != 0):false;
54 | }
55 | // Searches for the first match of the expression in a string sarting at text_begin and ending at text_end
56 | bool SearchRange(const TRexChar* text_begin,const TRexChar* text_end,const TRexChar** out_begin, const TRexChar** out_end) {
57 | return _exp?(trex_searchrange(_exp,text_begin,text_end,out_begin,out_end) != 0):false;
58 | }
59 | bool GetSubExp(int n, const TRexChar** out_begin, int *out_len)
60 | {
61 | TRexMatch match;
62 | TRexBool res = _exp?(trex_getsubexp(_exp,n,&match)):TRex_False;
63 | if(res) {
64 | *out_begin = match.begin;
65 | *out_len = match.len;
66 | return true;
67 | }
68 | return false;
69 | }
70 | int GetSubExpCount() { return _exp?trex_getsubexpcount(_exp):0; }
71 | private:
72 | void CleanUp() { if(_exp) trex_free(_exp); _exp = (TRex *)0; }
73 | TRex *_exp;
74 | };
75 | #endif //_TREXPP_H_
--------------------------------------------------------------------------------
/src/shared/trex/history.txt:
--------------------------------------------------------------------------------
1 | ===version 1.3
2 | -fixed a bug for GCC users(thx Brendan)
3 |
4 | ===version 1.2
5 | -added word boundary match \b and \B
6 | -added vertical tab escape \v
7 | -\w now also matches '_' (underscore)
8 | -fixed greediness for * and +
9 |
10 | ===version 1.1 , April 1, 2004
11 | -fixed some minor bug
12 | -added predefined character classes(\w,\W,\s,\S etc...)
13 |
14 | ===version 1.0 , February 23, 2004
15 | -first public realase
--------------------------------------------------------------------------------
/src/shared/trex/readme.txt:
--------------------------------------------------------------------------------
1 | T-REX 1.3 http://tiny-rex.sourceforge.net
2 | ----------------------------------------------------------------------
3 | T-Rex a tiny regular expression library
4 |
5 | Copyright (C) 2003-2006 Alberto Demichelis
6 |
7 | This software is provided 'as-is', without any express
8 | or implied warranty. In no event will the authors be held
9 | liable for any damages arising from the use of this software.
10 |
11 | Permission is granted to anyone to use this software for
12 | any purpose, including commercial applications, and to alter
13 | it and redistribute it freely, subject to the following restrictions:
14 |
15 | 1. The origin of this software must not be misrepresented;
16 | you must not claim that you wrote the original software.
17 | If you use this software in a product, an acknowledgment
18 | in the product documentation would be appreciated but
19 | is not required.
20 |
21 | 2. Altered source versions must be plainly marked as such,
22 | and must not be misrepresented as being the original software.
23 |
24 | 3. This notice may not be removed or altered from any
25 | source distribution.
26 |
27 | ----------------------------------------------------------------------
28 | TRex implements the following expressions
29 |
30 | \ Quote the next metacharacter
31 | ^ Match the beginning of the string
32 | . Match any character
33 | $ Match the end of the string
34 | | Alternation
35 | () Grouping (creates a capture)
36 | [] Character class
37 |
38 | ==GREEDY CLOSURES==
39 | * Match 0 or more times
40 | + Match 1 or more times
41 | ? Match 1 or 0 times
42 | {n} Match exactly n times
43 | {n,} Match at least n times
44 | {n,m} Match at least n but not more than m times
45 |
46 | ==ESCAPE CHARACTERS==
47 | \t tab (HT, TAB)
48 | \n newline (LF, NL)
49 | \r return (CR)
50 | \f form feed (FF)
51 |
52 | ==PREDEFINED CLASSES==
53 | \l lowercase next char
54 | \u uppercase next char
55 | \a letters
56 | \A non letters
57 | \w alphanimeric [0-9a-zA-Z]
58 | \W non alphanimeric
59 | \s space
60 | \S non space
61 | \d digits
62 | \D non nondigits
63 | \x exadecimal digits
64 | \X non exadecimal digits
65 | \c control charactrs
66 | \C non control charactrs
67 | \p punctation
68 | \P non punctation
69 | \b word boundary
70 | \B non word boundary
71 |
72 | ----------------------------------------------------------------------
73 | API DOC
74 | ----------------------------------------------------------------------
75 | TRex *trex_compile(const TRexChar *pattern,const TRexChar **error);
76 |
77 | compiles an expression and returns a pointer to the compiled version.
78 | in case of failure returns NULL.The returned object has to be deleted
79 | through the function trex_free().
80 |
81 | pattern
82 | a pointer to a zero terminated string containing the pattern that
83 | has to be compiled.
84 | error
85 | apointer to a string pointer that will be set with an error string
86 | in case of failure.
87 |
88 | ----------------------------------------------------------------------
89 | void trex_free(TRex *exp)
90 |
91 | deletes a expression structure created with trex_compile()
92 |
93 | exp
94 | the expression structure that has to be deleted
95 |
96 | ----------------------------------------------------------------------
97 | TRexBool trex_match(TRex* exp,const TRexChar* text)
98 |
99 | returns TRex_True if the string specified in the parameter text is an
100 | exact match of the expression, otherwise returns TRex_False.
101 |
102 | exp
103 | the compiled expression
104 | text
105 | the string that has to be tested
106 |
107 | ----------------------------------------------------------------------
108 | TRexBool trex_search(TRex* exp,const TRexChar* text, const TRexChar** out_begin, const TRexChar** out_end)
109 |
110 | searches the first match of the expressin in the string specified in the parameter text.
111 | if the match is found returns TRex_True and the sets out_begin to the beginning of the
112 | match and out_end at the end of the match; otherwise returns TRex_False.
113 |
114 | exp
115 | the compiled expression
116 | text
117 | the string that has to be tested
118 | out_begin
119 | a pointer to a string pointer that will be set with the beginning of the match
120 | out_end
121 | a pointer to a string pointer that will be set with the end of the match
122 |
123 | ----------------------------------------------------------------------
124 | TREX_API TRexBool trex_searchrange(TRex* exp,const TRexChar* text_begin,const TRexChar* text_end,const TRexChar** out_begin, const TRexChar** out_end)
125 |
126 | searches the first match of the expressin in the string delimited
127 | by the parameter text_begin and text_end.
128 | if the match is found returns TRex_True and the sets out_begin to the beginning of the
129 | match and out_end at the end of the match; otherwise returns TRex_False.
130 |
131 | exp
132 | the compiled expression
133 | text_begin
134 | a pointer to the beginnning of the string that has to be tested
135 | text_end
136 | a pointer to the end of the string that has to be tested
137 | out_begin
138 | a pointer to a string pointer that will be set with the beginning of the match
139 | out_end
140 | a pointer to a string pointer that will be set with the end of the match
141 |
142 | ----------------------------------------------------------------------
143 | int trex_getsubexpcount(TRex* exp)
144 |
145 | returns the number of sub expressions matched by the expression
146 |
147 | exp
148 | the compiled expression
149 |
150 | ---------------------------------------------------------------------
151 | TRexBool trex_getsubexp(TRex* exp, int n, TRexMatch *submatch)
152 |
153 | retrieve the begin and and pointer to the length of the sub expression indexed
154 | by n. The result is passed trhough the struct TRexMatch:
155 |
156 | typedef struct {
157 | const TRexChar *begin;
158 | int len;
159 | } TRexMatch;
160 |
161 | the function returns TRex_True if n is valid index otherwise TRex_False.
162 |
163 | exp
164 | the compiled expression
165 | n
166 | the index of the submatch
167 | submatch
168 | a pointer to structure that will store the result
169 |
170 | this function works also after a match operation has been performend.
171 |
172 |
--------------------------------------------------------------------------------
/src/shared/trex/test.c:
--------------------------------------------------------------------------------
1 | #include "trex.h"
2 | #include
3 | #include
4 |
5 | #ifdef _UNICODE
6 | #define trex_sprintf swprintf
7 | #else
8 | #define trex_sprintf sprintf
9 | #endif
10 |
11 | int main(int argc, char* argv[])
12 | {
13 | const TRexChar *begin,*end;
14 | TRexChar sTemp[200];
15 | const TRexChar *error = NULL;
16 | TRex *x = trex_compile(_TREXC("(x{1,5})xx"),&error);
17 | if(x) {
18 | trex_sprintf(sTemp,_TREXC("xxxxxxx"));
19 | if(trex_search(x,sTemp,&begin,&end))
20 | {
21 | int i,n = trex_getsubexpcount(x);
22 | TRexMatch match;
23 | for(i = 0; i < n; i++)
24 | {
25 | TRexChar t[200];
26 | trex_getsubexp(x,i,&match);
27 | trex_sprintf(t,_TREXC("[%%d]%%.%ds\n"),match.len);
28 | trex_printf(t,i,match.begin);
29 | }
30 | trex_printf(_TREXC("match! %d sub matches\n"),trex_getsubexpcount(x));
31 | }
32 | else {
33 | trex_printf(_TREXC("no match!\n"));
34 | }
35 | trex_free(x);
36 | }
37 | else {
38 | trex_printf(_TREXC("compilation error [%s]!\n"),error?error:_TREXC("undefined"));
39 | }
40 | return 0;
41 | }
42 |
--------------------------------------------------------------------------------
/src/shared/trex/trex.h:
--------------------------------------------------------------------------------
1 | #ifndef _TREX_H_
2 | #define _TREX_H_
3 | /***************************************************************
4 | T-Rex a tiny regular expression library
5 |
6 | Copyright (C) 2003-2006 Alberto Demichelis
7 |
8 | This software is provided 'as-is', without any express
9 | or implied warranty. In no event will the authors be held
10 | liable for any damages arising from the use of this software.
11 |
12 | Permission is granted to anyone to use this software for
13 | any purpose, including commercial applications, and to alter
14 | it and redistribute it freely, subject to the following restrictions:
15 |
16 | 1. The origin of this software must not be misrepresented;
17 | you must not claim that you wrote the original software.
18 | If you use this software in a product, an acknowledgment
19 | in the product documentation would be appreciated but
20 | is not required.
21 |
22 | 2. Altered source versions must be plainly marked as such,
23 | and must not be misrepresented as being the original software.
24 |
25 | 3. This notice may not be removed or altered from any
26 | source distribution.
27 |
28 | ****************************************************************/
29 |
30 | #ifdef _UNICODE
31 | #define TRexChar wchar_t
32 | #define MAX_CHAR 0xFFFF
33 | #define _TREXC(c) L##c
34 | #define trex_strlen wcslen
35 | #define trex_printf wprintf
36 | #else
37 | #define TRexChar char
38 | #define MAX_CHAR 0xFF
39 | #define _TREXC(c) (c)
40 | #define trex_strlen strlen
41 | #define trex_printf printf
42 | #endif
43 |
44 | #ifndef TREX_API
45 | #define TREX_API extern
46 | #endif
47 |
48 | #define TRex_True 1
49 | #define TRex_False 0
50 |
51 | typedef unsigned int TRexBool;
52 | typedef struct TRex TRex;
53 |
54 | typedef struct {
55 | const TRexChar *begin;
56 | int len;
57 | } TRexMatch;
58 |
59 | #ifdef __cplusplus
60 | extern "C"
61 | {
62 | #endif
63 |
64 | TREX_API TRex *trex_compile(const TRexChar *pattern,const TRexChar **error);
65 | TREX_API void trex_free(TRex *exp);
66 | TREX_API TRexBool trex_match(TRex* exp,const TRexChar* text);
67 | TREX_API TRexBool trex_search(TRex* exp,const TRexChar* text, const TRexChar** out_begin, const TRexChar** out_end);
68 | TREX_API TRexBool trex_searchrange(TRex* exp,const TRexChar* text_begin,const TRexChar* text_end,const TRexChar** out_begin, const TRexChar** out_end);
69 | TREX_API int trex_getsubexpcount(TRex* exp);
70 | TREX_API TRexBool trex_getsubexp(TRex* exp, int n, TRexMatch *subexp);
71 |
72 | #ifdef __cplusplus
73 | }
74 | #endif
75 |
76 | #endif
77 |
--------------------------------------------------------------------------------
/src/shared/ttmath/ttmathdec.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is a part of TTMath Bignum Library
3 | * and is distributed under the 3-Clause BSD Licence.
4 | * Author: Tomasz Sowa
5 | */
6 |
7 | /*
8 | * Copyright (c) 2012, Tomasz Sowa
9 | * All rights reserved.
10 | *
11 | * Redistribution and use in source and binary forms, with or without
12 | * modification, are permitted provided that the following conditions are met:
13 | *
14 | * * Redistributions of source code must retain the above copyright notice,
15 | * this list of conditions and the following disclaimer.
16 | *
17 | * * Redistributions in binary form must reproduce the above copyright
18 | * notice, this list of conditions and the following disclaimer in the
19 | * documentation and/or other materials provided with the distribution.
20 | *
21 | * * Neither the name Tomasz Sowa nor the names of contributors to this
22 | * project may be used to endorse or promote products derived
23 | * from this software without specific prior written permission.
24 | *
25 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
26 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
29 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
35 | * THE POSSIBILITY OF SUCH DAMAGE.
36 | */
37 |
38 | #ifndef headerfilettmathdec
39 | #define headerfilettmathdec
40 |
41 | #include "ttmathtypes.h"
42 | #include "ttmaththreads.h"
43 | #include "ttmathuint.h"
44 |
45 |
46 |
47 | namespace ttmath
48 | {
49 |
50 | template
51 | class Dec
52 | {
53 | public:
54 |
55 | UInt value;
56 | unsigned char info;
57 |
58 |
59 | /*!
60 | Sign
61 | the mask of a bit from 'info' which means that there is a sign
62 | (when the bit is set)
63 | */
64 | #define TTMATH_DEC_SIGN 128
65 |
66 |
67 | /*!
68 | Not a number
69 | if this bit is set that there is not a valid number
70 | */
71 | #define TTMATH_DEC_NAN 64
72 |
73 |
74 |
75 |
76 | Dec()
77 | {
78 | info = TTMATH_DEC_NAN;
79 | }
80 |
81 |
82 | Dec(const char * s)
83 | {
84 | info = TTMATH_DEC_NAN;
85 | FromString(s);
86 | }
87 |
88 |
89 | Dec & operator=(const char * s)
90 | {
91 | FromString(s);
92 |
93 | return *this;
94 | }
95 |
96 |
97 | uint FromString(const char * s, const char ** after_source = 0, bool * value_read = 0)
98 | {
99 | return FromStringBase(s, after_source, value_read);
100 | }
101 |
102 |
103 | void ToString(std::string & result) const
104 | {
105 | ToStringBase(result);
106 | }
107 |
108 |
109 | /*!
110 | this method clears a specific bit in the 'info' variable
111 |
112 | bit is one of:
113 | */
114 | void ClearInfoBit(unsigned char bit)
115 | {
116 | info = info & (~bit);
117 | }
118 |
119 |
120 | /*!
121 | this method sets a specific bit in the 'info' variable
122 |
123 | bit is one of:
124 |
125 | */
126 | void SetInfoBit(unsigned char bit)
127 | {
128 | info = info | bit;
129 | }
130 |
131 |
132 | /*!
133 | this method returns true if a specific bit in the 'info' variable is set
134 |
135 | bit is one of:
136 | */
137 | bool IsInfoBit(unsigned char bit) const
138 | {
139 | return (info & bit) != 0;
140 | }
141 |
142 |
143 | bool IsNan() const
144 | {
145 | return IsInfoBit(TTMATH_DEC_NAN);
146 | }
147 |
148 |
149 | bool IsSign() const
150 | {
151 | return IsInfoBit(TTMATH_DEC_SIGN);
152 | }
153 |
154 |
155 | /*!
156 | this method sets the sign
157 |
158 | e.g.
159 | -1 -> -1
160 | 2 -> -2
161 |
162 | we do not check whether there is a zero or not, if you're using this method
163 | you must be sure that the value is (or will be afterwards) different from zero
164 | */
165 | void SetSign()
166 | {
167 | SetInfoBit(TTMATH_DEC_SIGN);
168 | }
169 |
170 |
171 | void SetNaN()
172 | {
173 | SetInfoBit(TTMATH_DEC_NAN);
174 | }
175 |
176 |
177 | void Abs()
178 | {
179 | ClearInfoBit(TTMATH_DEC_SIGN);
180 | }
181 |
182 |
183 |
184 | uint Add(const Dec & arg)
185 | {
186 | uint c = 0;
187 |
188 | if( IsSign() == arg.IsSign() )
189 | {
190 | c += value.Add(arg.value);
191 | }
192 | else
193 | {
194 | bool is_sign;
195 |
196 | if( value > arg.value )
197 | {
198 | is_sign = IsSign();
199 | value.Sub(arg.value);
200 | }
201 | else
202 | {
203 | is_sign = arg.IsSign();
204 | UInt temp(this->value);
205 | value = arg.value;
206 | value.Sub(temp);
207 | }
208 |
209 | is_sign ? SetSign() : Abs();
210 | }
211 |
212 | if( c )
213 | SetNaN();
214 |
215 | return (c==0)? 0 : 1;
216 | }
217 |
218 | /*
219 | uint Sub(const Dec & arg)
220 | {
221 | }
222 | */
223 |
224 | private:
225 |
226 |
227 |
228 |
229 |
230 |
231 | #ifndef TTMATH_MULTITHREADS
232 |
233 | /*!
234 | */
235 | void SetMultipler(UInt & result)
236 | {
237 | // this guardian is initialized before the program runs (static POD type)
238 | static int guardian = 0;
239 | static UInt multipler;
240 |
241 | if( guardian == 0 )
242 | {
243 | multipler = 10;
244 | multipler.Pow(dec_digits);
245 | guardian = 1;
246 | }
247 |
248 | result = multipler;
249 | }
250 |
251 | #else
252 |
253 | /*!
254 | */
255 | void SetMultipler(UInt & result)
256 | {
257 | // this guardian is initialized before the program runs (static POD type)
258 | volatile static sig_atomic_t guardian = 0;
259 | static UInt * pmultipler;
260 |
261 | // double-checked locking
262 | if( guardian == 0 )
263 | {
264 | ThreadLock thread_lock;
265 |
266 | // locking
267 | if( thread_lock.Lock() )
268 | {
269 | static UInt multipler;
270 |
271 | if( guardian == 0 )
272 | {
273 | pmultipler = &multipler;
274 | multipler = 10;
275 | multipler.Pow(dec_digits);
276 | guardian = 1;
277 | }
278 | }
279 | else
280 | {
281 | // there was a problem with locking, we store the result directly in 'result' object
282 | result = 10;
283 | result.Pow(dec_digits);
284 |
285 | return;
286 | }
287 |
288 | // automatically unlocking
289 | }
290 |
291 | result = *pmultipler;
292 | }
293 |
294 | #endif
295 |
296 |
297 |
298 | /*!
299 | an auxiliary method for converting from a string
300 | */
301 | template
302 | uint FromStringBase(const char_type * s, const char_type ** after_source = 0, bool * value_read = 0)
303 | {
304 | UInt multipler;
305 | const char_type * after;
306 | uint c = 0;
307 | info = 0;
308 |
309 | Misc::SkipWhiteCharacters(s);
310 |
311 | if( *s == '-' )
312 | {
313 | s += 1;
314 | SetSign();
315 | }
316 | else
317 | if( *s == '+' )
318 | {
319 | s += 1;
320 | }
321 |
322 | c += value.FromString(s, 10, &after, value_read);
323 |
324 | if( after_source )
325 | *after_source = after;
326 |
327 | SetMultipler(multipler);
328 | c += value.Mul(multipler);
329 |
330 | if( *after == '.' )
331 | c += FromStringBaseAfterComma(after+1, after_source);
332 |
333 | if( c )
334 | SetInfoBit(TTMATH_DEC_NAN);
335 |
336 | return (c==0)? 0 : 1;
337 | }
338 |
339 |
340 | template
341 | uint FromStringBaseAfterComma(const char_type * s, const char_type ** after_source = 0, bool * value_read = 0)
342 | {
343 | UInt temp;
344 | UInt multipler;
345 | sint z;
346 | uint c = 0;
347 | size_t i = dec_digits;
348 |
349 | SetMultipler(multipler);
350 |
351 | for( ; i>0 && (z=Misc::CharToDigit(*s, 10)) != -1 ; --i, ++s )
352 | {
353 | multipler.DivInt(10);
354 | temp.SetZero();
355 |
356 | if( value_read )
357 | *value_read = true;
358 |
359 | if( c == 0 )
360 | {
361 | temp.table[0] = z;
362 | c += temp.Mul(multipler);
363 | c += value.Add(temp);
364 | }
365 | }
366 |
367 | if( i == 0 && (z=Misc::CharToDigit(*s, 10)) != -1 && z >= 5 )
368 | c += value.AddOne();
369 |
370 | if( after_source )
371 | {
372 | while( (z=Misc::CharToDigit(*s, 10)) != -1 )
373 | s += 1;
374 |
375 | *after_source = s;
376 | }
377 |
378 | return c;
379 | }
380 |
381 |
382 |
383 | template
384 | void ToStringBase(string_type & result) const
385 | {
386 | if( IsNan() )
387 | {
388 | result = "NaN";
389 | return;
390 | }
391 |
392 | value.ToStringBase(result, 10, IsSign());
393 |
394 | if( dec_digits > 0 )
395 | {
396 | size_t size = result.size();
397 |
398 | if( IsSign() && size > 0 )
399 | size -= 1;
400 |
401 | if( dec_digits >= size )
402 | {
403 | size_t zeroes = dec_digits - size + 1;
404 | size_t start = IsSign() ? 1 : 0;
405 | result.insert(start, zeroes, '0');
406 | }
407 |
408 | result.insert(result.end() - dec_digits, '.');
409 | }
410 | }
411 |
412 |
413 |
414 | };
415 |
416 |
417 | } // namespace
418 |
419 | #endif
420 |
--------------------------------------------------------------------------------
/src/shared/ttmath/ttmathmisc.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is a part of TTMath Bignum Library
3 | * and is distributed under the 3-Clause BSD Licence.
4 | * Author: Tomasz Sowa
5 | */
6 |
7 | /*
8 | * Copyright (c) 2006-2010, Tomasz Sowa
9 | * All rights reserved.
10 | *
11 | * Redistribution and use in source and binary forms, with or without
12 | * modification, are permitted provided that the following conditions are met:
13 | *
14 | * * Redistributions of source code must retain the above copyright notice,
15 | * this list of conditions and the following disclaimer.
16 | *
17 | * * Redistributions in binary form must reproduce the above copyright
18 | * notice, this list of conditions and the following disclaimer in the
19 | * documentation and/or other materials provided with the distribution.
20 | *
21 | * * Neither the name Tomasz Sowa nor the names of contributors to this
22 | * project may be used to endorse or promote products derived
23 | * from this software without specific prior written permission.
24 | *
25 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
26 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
29 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
35 | * THE POSSIBILITY OF SUCH DAMAGE.
36 | */
37 |
38 | #ifndef headerfilettmathmisc
39 | #define headerfilettmathmisc
40 |
41 |
42 | /*!
43 | \file ttmathmisc.h
44 | \brief some helpful functions
45 | */
46 |
47 |
48 | #include
49 |
50 |
51 | namespace ttmath
52 | {
53 |
54 | /*!
55 | some helpful functions
56 | */
57 | class Misc
58 | {
59 | public:
60 |
61 |
62 | /*
63 | *
64 | * AssignString(result, str)
65 | * result = str
66 | *
67 | */
68 |
69 | /*!
70 | result = str
71 | */
72 | static void AssignString(std::string & result, const char * str)
73 | {
74 | result = str;
75 | }
76 |
77 |
78 | #ifndef TTMATH_DONT_USE_WCHAR
79 |
80 | /*!
81 | result = str
82 | */
83 | static void AssignString(std::wstring & result, const char * str)
84 | {
85 | result.clear();
86 |
87 | for( ; *str ; ++str )
88 | result += *str;
89 | }
90 |
91 |
92 | /*!
93 | result = str
94 | */
95 | static void AssignString(std::wstring & result, const std::string & str)
96 | {
97 | return AssignString(result, str.c_str());
98 | }
99 |
100 |
101 | /*!
102 | result = str
103 | */
104 | static void AssignString(std::string & result, const wchar_t * str)
105 | {
106 | result.clear();
107 |
108 | for( ; *str ; ++str )
109 | result += static_cast(*str);
110 | }
111 |
112 |
113 | /*!
114 | result = str
115 | */
116 | static void AssignString(std::string & result, const std::wstring & str)
117 | {
118 | return AssignString(result, str.c_str());
119 | }
120 |
121 | #endif
122 |
123 |
124 | /*
125 | *
126 | * AddString(result, str)
127 | * result += str
128 | *
129 | */
130 |
131 |
132 | /*!
133 | result += str
134 | */
135 | static void AddString(std::string & result, const char * str)
136 | {
137 | result += str;
138 | }
139 |
140 |
141 | #ifndef TTMATH_DONT_USE_WCHAR
142 |
143 | /*!
144 | result += str
145 | */
146 | static void AddString(std::wstring & result, const char * str)
147 | {
148 | for( ; *str ; ++str )
149 | result += *str;
150 | }
151 |
152 | #endif
153 |
154 |
155 | /*
156 | this method omits any white characters from the string
157 | char_type is char or wchar_t
158 | */
159 | template
160 | static void SkipWhiteCharacters(const char_type * & c)
161 | {
162 | // 13 is at the end in a DOS text file (\r\n)
163 | while( (*c==' ' ) || (*c=='\t') || (*c==13 ) || (*c=='\n') )
164 | ++c;
165 | }
166 |
167 |
168 |
169 |
170 | /*!
171 | this static method converts one character into its value
172 |
173 | for example:
174 | - 1 -> 1
175 | - 8 -> 8
176 | - A -> 10
177 | - f -> 15
178 |
179 | this method don't check whether c is correct or not
180 | */
181 | static uint CharToDigit(uint c)
182 | {
183 | if(c>='0' && c<='9')
184 | return c-'0';
185 |
186 | if(c>='a' && c<='z')
187 | return c-'a'+10;
188 |
189 | return c-'A'+10;
190 | }
191 |
192 |
193 | /*!
194 | this method changes a character 'c' into its value
195 | (if there can't be a correct value it returns -1)
196 |
197 | for example:
198 | - c=2, base=10 -> function returns 2
199 | - c=A, base=10 -> function returns -1
200 | - c=A, base=16 -> function returns 10
201 | */
202 | static sint CharToDigit(uint c, uint base)
203 | {
204 | if( c>='0' && c<='9' )
205 | c=c-'0';
206 | else
207 | if( c>='a' && c<='z' )
208 | c=c-'a'+10;
209 | else
210 | if( c>='A' && c<='Z' )
211 | c=c-'A'+10;
212 | else
213 | return -1;
214 |
215 |
216 | if( c >= base )
217 | return -1;
218 |
219 |
220 | return sint(c);
221 | }
222 |
223 |
224 |
225 | /*!
226 | this method converts a digit into a char
227 | digit should be from <0,F>
228 | (we don't have to get a base)
229 |
230 | for example:
231 | - 1 -> 1
232 | - 8 -> 8
233 | - 10 -> A
234 | - 15 -> F
235 | */
236 | static uint DigitToChar(uint digit)
237 | {
238 | if( digit < 10 )
239 | return digit + '0';
240 |
241 | return digit - 10 + 'A';
242 | }
243 |
244 |
245 | }; // struct Misc
246 |
247 | }
248 |
249 |
250 | #endif
251 |
--------------------------------------------------------------------------------
/src/shared/ttmath/ttmaththreads.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This file is a part of TTMath Bignum Library
3 | * and is distributed under the 3-Clause BSD Licence.
4 | * Author: Tomasz Sowa
5 | */
6 |
7 | /*
8 | * Copyright (c) 2006-2009, Tomasz Sowa
9 | * All rights reserved.
10 | *
11 | * Redistribution and use in source and binary forms, with or without
12 | * modification, are permitted provided that the following conditions are met:
13 | *
14 | * * Redistributions of source code must retain the above copyright notice,
15 | * this list of conditions and the following disclaimer.
16 | *
17 | * * Redistributions in binary form must reproduce the above copyright
18 | * notice, this list of conditions and the following disclaimer in the
19 | * documentation and/or other materials provided with the distribution.
20 | *
21 | * * Neither the name Tomasz Sowa nor the names of contributors to this
22 | * project may be used to endorse or promote products derived
23 | * from this software without specific prior written permission.
24 | *
25 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
26 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
29 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
35 | * THE POSSIBILITY OF SUCH DAMAGE.
36 | */
37 |
38 |
39 |
40 | #ifndef headerfilettmaththreads
41 | #define headerfilettmaththreads
42 |
43 | #include "ttmathtypes.h"
44 |
45 | #ifdef TTMATH_WIN32_THREADS
46 | #include
47 | #include
48 | #endif
49 |
50 | #ifdef TTMATH_POSIX_THREADS
51 | #include
52 | #endif
53 |
54 |
55 |
56 | /*!
57 | \file ttmaththreads.h
58 | \brief Some objects used in multithreads environment
59 | */
60 |
61 |
62 | namespace ttmath
63 | {
64 |
65 |
66 | #ifdef TTMATH_WIN32_THREADS
67 |
68 | /*
69 | we use win32 threads
70 | */
71 |
72 |
73 | /*!
74 | in multithreads environment you should use TTMATH_MULTITHREADS_HELPER macro
75 | somewhere in *.cpp file
76 |
77 | (at the moment in win32 this macro does nothing)
78 | */
79 | #define TTMATH_MULTITHREADS_HELPER
80 |
81 |
82 | /*!
83 | objects of this class are used to synchronize
84 | */
85 | class ThreadLock
86 | {
87 | HANDLE mutex_handle;
88 |
89 |
90 | void CreateName(char * buffer) const
91 | {
92 | #ifdef _MSC_VER
93 | #pragma warning (disable : 4996)
94 | // warning C4996: 'sprintf': This function or variable may be unsafe. Consider using sprintf_s instead.
95 | #endif
96 |
97 | sprintf(buffer, "TTMATH_LOCK_%ul", (unsigned long)GetCurrentProcessId());
98 |
99 | #ifdef _MSC_VER
100 | #pragma warning (default : 4996)
101 | #endif
102 | }
103 |
104 |
105 | public:
106 |
107 | bool Lock()
108 | {
109 | char buffer[50];
110 |
111 | CreateName(buffer);
112 | mutex_handle = CreateMutexA(0, false, buffer);
113 |
114 | if( mutex_handle == 0 )
115 | return false;
116 |
117 | WaitForSingleObject(mutex_handle, INFINITE);
118 |
119 | return true;
120 | }
121 |
122 |
123 | ThreadLock()
124 | {
125 | mutex_handle = 0;
126 | }
127 |
128 |
129 | ~ThreadLock()
130 | {
131 | if( mutex_handle != 0 )
132 | {
133 | ReleaseMutex(mutex_handle);
134 | CloseHandle(mutex_handle);
135 | }
136 | }
137 | };
138 |
139 | #endif // #ifdef TTMATH_WIN32_THREADS
140 |
141 |
142 |
143 |
144 |
145 | #ifdef TTMATH_POSIX_THREADS
146 |
147 | /*
148 | we use posix threads
149 | */
150 |
151 |
152 | /*!
153 | in multithreads environment you should use TTMATH_MULTITHREADS_HELPER macro
154 | somewhere in *.cpp file
155 | (this macro defines a pthread_mutex_t object used by TTMath library)
156 | */
157 | #define TTMATH_MULTITHREADS_HELPER \
158 | namespace ttmath \
159 | { \
160 | pthread_mutex_t ttmath_mutex = PTHREAD_MUTEX_INITIALIZER; \
161 | }
162 |
163 |
164 | /*!
165 | ttmath_mutex will be defined by TTMATH_MULTITHREADS_HELPER macro
166 | */
167 | extern pthread_mutex_t ttmath_mutex;
168 |
169 |
170 | /*!
171 | \brief objects of this class are used to synchronize
172 |
173 | this is a simple skeleton of a program in multithreads environment:
174 |
175 | #define TTMATH_MULTITHREADS
176 | #include
177 |
178 | TTMATH_MULTITHREADS_HELPER
179 |
180 | int main()
181 | {
182 | [...]
183 | }
184 |
185 | make sure that macro TTMATH_MULTITHREADS is defined and (somewhere in *.cpp file)
186 | use TTMATH_MULTITHREADS_HELPER macro (outside of any classes/functions/namespaces scope)
187 | */
188 | class ThreadLock
189 | {
190 | public:
191 |
192 | /*!
193 | lock the current thread
194 |
195 | it uses a global mutex created by TTMATH_MULTITHREADS_HELPER macro
196 | */
197 | bool Lock()
198 | {
199 | if( pthread_mutex_lock(&ttmath_mutex) != 0 )
200 | return false;
201 |
202 | return true;
203 | }
204 |
205 |
206 | ~ThreadLock()
207 | {
208 | pthread_mutex_unlock(&ttmath_mutex);
209 | }
210 | };
211 |
212 | #endif // #ifdef TTMATH_POSIX_THREADS
213 |
214 |
215 |
216 |
217 | #if !defined(TTMATH_POSIX_THREADS) && !defined(TTMATH_WIN32_THREADS)
218 |
219 | /*!
220 | we don't use win32 and pthreads
221 | */
222 |
223 | /*!
224 | */
225 | #define TTMATH_MULTITHREADS_HELPER
226 |
227 |
228 | /*!
229 | objects of this class are used to synchronize
230 | actually we don't synchronize, the method Lock() returns always 'false'
231 | */
232 | class ThreadLock
233 | {
234 | public:
235 |
236 | bool Lock()
237 | {
238 | return false;
239 | }
240 | };
241 |
242 |
243 | #endif // #if !defined(TTMATH_POSIX_THREADS) && !defined(TTMATH_WIN32_THREADS)
244 |
245 |
246 |
247 |
248 |
249 | } // namespace
250 |
251 | #endif
252 |
253 |
--------------------------------------------------------------------------------
/src/shared/ttmath/ttmathuint_x86_64_msvc.asm:
--------------------------------------------------------------------------------
1 | ;
2 | ; This file is a part of TTMath Bignum Library
3 | ; and is distributed under the 3-Clause BSD Licence.
4 | ; Author: Christian Kaiser , Tomasz Sowa
5 | ;
6 |
7 | ;
8 | ; Copyright (c) 2009-2017, Christian Kaiser, Tomasz Sowa
9 | ; All rights reserved.
10 | ;
11 | ; Redistribution and use in source and binary forms, with or without
12 | ; modification, are permitted provided that the following conditions are met:
13 | ;
14 | ; * Redistributions of source code must retain the above copyright notice,
15 | ; this list of conditions and the following disclaimer.
16 | ;
17 | ; * Redistributions in binary form must reproduce the above copyright
18 | ; notice, this list of conditions and the following disclaimer in the
19 | ; documentation and/or other materials provided with the distribution.
20 | ;
21 | ; * Neither the name Christian Kaiser nor the names of contributors to this
22 | ; project may be used to endorse or promote products derived
23 | ; from this software without specific prior written permission.
24 | ;
25 | ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
26 | ; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 | ; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 | ; ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
29 | ; LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30 | ; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31 | ; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 | ; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33 | ; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34 | ; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
35 | ; THE POSSIBILITY OF SUCH DAMAGE.
36 | ;
37 |
38 | ;
39 | ; compile with debug info: ml64.exe /c /Zd /Zi ttmathuint_x86_64_msvc.asm
40 | ; compile without debug info: ml64.exe /c ttmathuint_x86_64_msvc.asm
41 | ; this creates ttmathuint_x86_64_msvc.obj file which can be linked with your program
42 | ;
43 |
44 | ; doxygen info is put to ttmathuint_x86_64.h file
45 |
46 |
47 | PUBLIC ttmath_adc_x64
48 | PUBLIC ttmath_addindexed_x64
49 | PUBLIC ttmath_addindexed2_x64
50 | PUBLIC ttmath_addvector_x64
51 |
52 | PUBLIC ttmath_sbb_x64
53 | PUBLIC ttmath_subindexed_x64
54 | PUBLIC ttmath_subvector_x64
55 |
56 | PUBLIC ttmath_rcl_x64
57 | PUBLIC ttmath_rcr_x64
58 |
59 | PUBLIC ttmath_rcl2_x64
60 | PUBLIC ttmath_rcr2_x64
61 |
62 | PUBLIC ttmath_div_x64
63 |
64 | ;
65 | ; Microsoft x86_64 convention: http://msdn.microsoft.com/en-us/library/9b372w95.aspx
66 | ;
67 | ; "rax, rcx, rdx, r8-r11 are volatile."
68 | ; "rbx, rbp, rdi, rsi, r12-r15 are nonvolatile."
69 | ;
70 |
71 |
72 | .CODE
73 |
74 |
75 | ALIGN 8
76 |
77 | ;----------------------------------------
78 |
79 | ttmath_adc_x64 PROC
80 | ; rcx = p1
81 | ; rdx = p2
82 | ; r8 = nSize
83 | ; r9 = nCarry
84 |
85 | xor rax, rax
86 | xor r11, r11
87 | sub rax, r9 ; sets CARRY if r9 != 0
88 |
89 | ALIGN 16
90 | loop1:
91 | mov rax,qword ptr [rdx + r11 * 8]
92 | adc qword ptr [rcx + r11 * 8], rax
93 | lea r11, [r11+1]
94 | dec r8
95 | jnz loop1
96 |
97 | setc al
98 | movzx rax, al
99 |
100 | ret
101 |
102 | ttmath_adc_x64 ENDP
103 |
104 | ;----------------------------------------
105 |
106 | ALIGN 8
107 |
108 | ;----------------------------------------
109 |
110 | ttmath_addindexed_x64 PROC
111 |
112 | ; rcx = p1
113 | ; rdx = nSize
114 | ; r8 = nPos
115 | ; r9 = nValue
116 |
117 | xor rax, rax ; rax = result
118 | sub rdx, r8 ; rdx = remaining count of uints
119 |
120 | add qword ptr [rcx + r8 * 8], r9
121 | jc next1
122 |
123 | ret
124 |
125 | next1:
126 | mov r9, 1
127 |
128 | ALIGN 16
129 | loop1:
130 | dec rdx
131 | jz done_with_cy
132 | lea r8, [r8+1]
133 | add qword ptr [rcx + r8 * 8], r9
134 | jc loop1
135 |
136 | ret
137 |
138 | done_with_cy:
139 | lea rax, [rax+1] ; rax = 1
140 |
141 | ret
142 |
143 | ttmath_addindexed_x64 ENDP
144 |
145 | ;----------------------------------------
146 |
147 | ALIGN 8
148 |
149 | ;----------------------------------------
150 |
151 | ttmath_addindexed2_x64 PROC
152 |
153 | ; rcx = p1 (pointer)
154 | ; rdx = b (value size)
155 | ; r8 = nPos
156 | ; r9 = nValue1
157 | ; [rsp+0x28] = nValue2
158 |
159 | xor rax, rax ; return value
160 | mov r11, rcx ; table
161 | sub rdx, r8 ; rdx = remaining count of uints
162 | mov r10, [rsp+028h] ; r10 = nValue2
163 |
164 | add qword ptr [r11 + r8 * 8], r9
165 | lea r8, [r8+1]
166 | lea rdx, [rdx-1]
167 | adc qword ptr [r11 + r8 * 8], r10
168 | jc next
169 | ret
170 |
171 | ALIGN 16
172 | loop1:
173 | lea r8, [r8+1]
174 | add qword ptr [r11 + r8 * 8], 1
175 | jc next
176 | ret
177 |
178 | next:
179 | dec rdx ; does not modify CY too...
180 | jnz loop1
181 | lea rax, [rax+1]
182 | ret
183 |
184 | ttmath_addindexed2_x64 ENDP
185 |
186 |
187 |
188 | ;----------------------------------------
189 |
190 | ALIGN 8
191 |
192 | ;----------------------------------------
193 |
194 |
195 | ttmath_addvector_x64 PROC
196 | ; rcx = ss1
197 | ; rdx = ss2
198 | ; r8 = ss1_size
199 | ; r9 = ss2_size
200 | ; [rsp+0x28] = result
201 |
202 | mov r10, [rsp+028h]
203 | sub r8, r9
204 | xor r11, r11 ; r11=0, cf=0
205 |
206 | ALIGN 16
207 | loop1:
208 | mov rax, qword ptr [rcx + r11 * 8]
209 | adc rax, qword ptr [rdx + r11 * 8]
210 | mov qword ptr [r10 + r11 * 8], rax
211 | inc r11
212 | dec r9
213 | jnz loop1
214 |
215 | adc r9, r9 ; r9 has the cf state
216 |
217 | or r8, r8
218 | jz done
219 |
220 | neg r9 ; setting cf from r9
221 | mov r9, 0 ; don't use xor here (cf is used)
222 | loop2:
223 | mov rax, qword ptr [rcx + r11 * 8]
224 | adc rax, r9
225 | mov qword ptr [r10 + r11 * 8], rax
226 | inc r11
227 | dec r8
228 | jnz loop2
229 |
230 | adc r8, r8
231 | mov rax, r8
232 |
233 | ret
234 |
235 | done:
236 | mov rax, r9
237 | ret
238 |
239 | ttmath_addvector_x64 ENDP
240 |
241 |
242 | ;----------------------------------------
243 |
244 | ALIGN 8
245 |
246 | ;----------------------------------------
247 |
248 | ttmath_sbb_x64 PROC
249 |
250 | ; rcx = p1
251 | ; rdx = p2
252 | ; r8 = nCount
253 | ; r9 = nCarry
254 |
255 | xor rax, rax
256 | xor r11, r11
257 | sub rax, r9 ; sets CARRY if r9 != 0
258 |
259 | ALIGN 16
260 | loop1:
261 | mov rax,qword ptr [rdx + r11 * 8]
262 | sbb qword ptr [rcx + r11 * 8], rax
263 | lea r11, [r11+1]
264 | dec r8
265 | jnz loop1
266 |
267 | setc al
268 | movzx rax, al
269 |
270 | ret
271 |
272 | ttmath_sbb_x64 ENDP
273 |
274 | ;----------------------------------------
275 |
276 | ALIGN 8
277 |
278 | ;----------------------------------------
279 |
280 | ttmath_subindexed_x64 PROC
281 | ; rcx = p1
282 | ; rdx = nSize
283 | ; r8 = nPos
284 | ; r9 = nValue
285 |
286 | sub rdx, r8 ; rdx = remaining count of uints
287 |
288 | ALIGN 16
289 | loop1:
290 | sub qword ptr [rcx + r8 * 8], r9
291 | jnc done
292 |
293 | lea r8, [r8+1]
294 | mov r9, 1
295 | dec rdx
296 | jnz loop1
297 |
298 | mov rax, 1
299 | ret
300 |
301 | done:
302 | xor rax, rax
303 | ret
304 |
305 | ttmath_subindexed_x64 ENDP
306 |
307 |
308 |
309 | ;----------------------------------------
310 |
311 | ALIGN 8
312 |
313 | ;----------------------------------------
314 |
315 | ; the same asm code as in addvector_x64 only two instructions 'adc' changed to 'sbb'
316 |
317 | ttmath_subvector_x64 PROC
318 | ; rcx = ss1
319 | ; rdx = ss2
320 | ; r8 = ss1_size
321 | ; r9 = ss2_size
322 | ; [rsp+0x28] = result
323 |
324 | mov r10, [rsp+028h]
325 | sub r8, r9
326 | xor r11, r11 ; r11=0, cf=0
327 |
328 | ALIGN 16
329 | loop1:
330 | mov rax, qword ptr [rcx + r11 * 8]
331 | sbb rax, qword ptr [rdx + r11 * 8]
332 | mov qword ptr [r10 + r11 * 8], rax
333 | inc r11
334 | dec r9
335 | jnz loop1
336 |
337 | adc r9, r9 ; r9 has the cf state
338 |
339 | or r8, r8
340 | jz done
341 |
342 | neg r9 ; setting cf from r9
343 | mov r9, 0 ; don't use xor here (cf is used)
344 | loop2:
345 | mov rax, qword ptr [rcx + r11 * 8]
346 | sbb rax, r9
347 | mov qword ptr [r10 + r11 * 8], rax
348 | inc r11
349 | dec r8
350 | jnz loop2
351 |
352 | adc r8, r8
353 | mov rax, r8
354 |
355 | ret
356 |
357 | done:
358 | mov rax, r9
359 | ret
360 |
361 | ttmath_subvector_x64 ENDP
362 |
363 |
364 |
365 |
366 | ;----------------------------------------
367 |
368 | ALIGN 8
369 |
370 | ;----------------------------------------
371 |
372 | ttmath_rcl_x64 PROC
373 | ; rcx = p1
374 | ; rdx = b
375 | ; r8 = nLowestBit
376 |
377 | mov r11, rcx ; table
378 | xor r10, r10
379 | neg r8 ; CY set if r8 <> 0
380 |
381 | ALIGN 16
382 | loop1:
383 | rcl qword ptr [r11 + r10 * 8], 1
384 | lea r10, [r10+1]
385 | dec rdx
386 | jnz loop1
387 |
388 | setc al
389 | movzx rax, al
390 |
391 | ret
392 |
393 | ttmath_rcl_x64 ENDP
394 |
395 | ;----------------------------------------
396 |
397 | ALIGN 8
398 |
399 | ;----------------------------------------
400 |
401 | ttmath_rcr_x64 PROC
402 | ; rcx = p1
403 | ; rdx = nSize
404 | ; r8 = nLowestBit
405 |
406 | xor r10, r10
407 | neg r8 ; CY set if r8 <> 0
408 |
409 | ALIGN 16
410 | loop1:
411 | rcr qword ptr -8[rcx + rdx * 8], 1
412 | dec rdx
413 | jnz loop1
414 |
415 | setc al
416 | movzx rax, al
417 |
418 | ret
419 |
420 | ttmath_rcr_x64 ENDP
421 |
422 | ;----------------------------------------
423 |
424 | ALIGN 8
425 |
426 | ;----------------------------------------
427 |
428 | ttmath_div_x64 PROC
429 |
430 | ; rcx = &Hi
431 | ; rdx = &Lo
432 | ; r8 = nDiv
433 |
434 | mov r11, rcx
435 | mov r10, rdx
436 |
437 | mov rdx, qword ptr [r11]
438 | mov rax, qword ptr [r10]
439 | div r8
440 | mov qword ptr [r10], rdx ; remainder
441 | mov qword ptr [r11], rax ; value
442 |
443 | ret
444 |
445 | ttmath_div_x64 ENDP
446 |
447 | ;----------------------------------------
448 |
449 | ALIGN 8
450 |
451 | ;----------------------------------------
452 |
453 | ttmath_rcl2_x64 PROC
454 | ; rcx = p1
455 | ; rdx = nSize
456 | ; r8 = bits
457 | ; r9 = c
458 |
459 | push rbx
460 |
461 | mov r10, rcx ; r10 = p1
462 | xor rax, rax
463 |
464 | mov rcx, 64
465 | sub rcx, r8
466 |
467 | mov r11, -1
468 | shr r11, cl ; r11 = mask
469 |
470 | mov rcx, r8 ; rcx = count of bits
471 |
472 | mov rbx, rax ; rbx = old value = 0
473 | or r9, r9
474 | cmovnz rbx, r11 ; if (c) then old value = mask
475 |
476 | mov r9, rax ; r9 = index (0..nSize-1)
477 |
478 | ALIGN 16
479 | loop1:
480 | rol qword ptr [r10+r9*8], cl
481 | mov rax, qword ptr [r10+r9*8]
482 | and rax, r11
483 | xor qword ptr [r10+r9*8], rax
484 | or qword ptr [r10+r9*8], rbx
485 | mov rbx, rax
486 |
487 | lea r9, [r9+1]
488 | dec rdx
489 |
490 | jnz loop1
491 |
492 | and rax, 1
493 | pop rbx
494 | ret
495 |
496 | ttmath_rcl2_x64 ENDP
497 |
498 | ;----------------------------------------
499 |
500 | ALIGN 8
501 |
502 | ;----------------------------------------
503 |
504 | ttmath_rcr2_x64 PROC
505 | ; rcx = p1
506 | ; rdx = nSize
507 | ; r8 = bits
508 | ; r9 = c
509 |
510 | push rbx
511 | mov r10, rcx ; r10 = p1
512 | xor rax, rax
513 |
514 | mov rcx, 64
515 | sub rcx, r8
516 |
517 | mov r11, -1
518 | shl r11, cl ; r11 = mask
519 |
520 | mov rcx, r8 ; rcx = count of bits
521 |
522 | mov rbx, rax ; rbx = old value = 0
523 | or r9, r9
524 | cmovnz rbx, r11 ; if (c) then old value = mask
525 |
526 | mov r9, rdx ; r9 = index (0..nSize-1)
527 | lea r9, [r9-1]
528 |
529 | ALIGN 16
530 | loop1:
531 | ror qword ptr [r10+r9*8], cl
532 | mov rax, qword ptr [r10+r9*8]
533 | and rax, r11
534 | xor qword ptr [r10+r9*8], rax
535 | or qword ptr [r10+r9*8], rbx
536 | mov rbx, rax
537 |
538 | lea r9, [r9-1]
539 | dec rdx
540 |
541 | jnz loop1
542 |
543 | rol rax, 1
544 | and rax, 1
545 | pop rbx
546 |
547 | ret
548 |
549 | ttmath_rcr2_x64 ENDP
550 |
551 | END
552 |
--------------------------------------------------------------------------------
/vc.build.release.cmd:
--------------------------------------------------------------------------------
1 | @echo off
2 |
3 | mkdir bin
4 |
5 | if exist "%VS170COMNTOOLS%..\..\VC\Auxiliary\Build\vcvarsall.bat" (
6 | call "%VS170COMNTOOLS%..\..\VC\Auxiliary\Build\vcvarsall.bat" x86
7 | ) else (
8 | call "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvarsall.bat" x86
9 | )
10 |
11 | mkdir build86
12 | cd build86
13 | cmake .. -DCMAKE_INSTALL_PREFIX=../bin/x86 -DCMAKE_BUILD_TYPE=Release -DCALC_BUILD_ARCH=x86 -G "NMake Makefiles"
14 | cmake --build .
15 | cpack
16 | copy *.zip ..\bin
17 |
18 | if errorlevel 1 goto end
19 |
20 | cd ..
21 | if exist "%VS170COMNTOOLS%..\..\VC\Auxiliary\Build\vcvarsall.bat" (
22 | call "%VS170COMNTOOLS%..\..\VC\Auxiliary\Build\vcvarsall.bat" x64
23 | ) else (
24 | call "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvarsall.bat" x64
25 | )
26 | mkdir build64
27 | cd build64
28 | cmake .. -DCMAKE_INSTALL_PREFIX=../bin/x64 -DCMAKE_BUILD_TYPE=Release -DCALC_BUILD_ARCH=x64 -G "NMake Makefiles"
29 | cmake --build .
30 | cpack
31 | copy *.zip ..\bin
32 |
33 |
34 | cd ..
35 | if exist "%VS170COMNTOOLS%..\..\VC\Auxiliary\Build\vcvarsall.bat" (
36 | call "%VS170COMNTOOLS%..\..\VC\Auxiliary\Build\vcvarsall.bat" amd64_arm64
37 | ) else (
38 | call "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvarsall.bat" amd64_arm64
39 | )
40 | mkdir build_arm64
41 | cd build_arm64
42 | cmake .. -DCMAKE_INSTALL_PREFIX=../bin/arm64 -DCMAKE_BUILD_TYPE=Release -DCALC_BUILD_ARCH=arm64 -G "NMake Makefiles"
43 | cmake --build .
44 | cpack
45 | copy *.zip ..\bin
46 |
47 | :end
48 | echo See result in directory "bin"
49 |
--------------------------------------------------------------------------------
/whatsnew_en.txt:
--------------------------------------------------------------------------------
1 | PlugIn Calculator
2 | -----===============-----
3 | *** This is not a new version of Calculator, just some modifications made
4 | *** by another author. All copyrights of the code, except the new modifications
5 | *** belong to the original author (Cail Lomecb).
6 |
7 | --== Ver 3.26 ==--
8 | * Fixed: incorrect drawing disabled edittext in FAR versions 5788 and newer
9 | * Improvement: call plugin from dialogs
10 | * Changed: function round = _floor(op0+0.5)
11 | * Changed: value of inch = 2.54
12 |
13 |
14 | --== Ver 3.25 ==--
15 | * Support Windows 2000 and WindowsXP added
16 |
17 |
18 | --== Ver 3.24 ==--
19 | * Remove Far2 support
20 | * Fixed: slow redraw in dialogs
21 | * Fixed: settings didn`t save
22 | * Now plugin on https://github.com/FarPlugins/Calculator
23 |
24 |
25 | --== Ver 3.23 ==--
26 | * Fixed: version
27 |
28 |
29 | --== Ver 3.22 ==--
30 | - General:
31 | * Update to current Far3 version (stable build 2927+)
32 | * Update of ttmath library with some fixes
33 | * Fixed: cursor moved in file panel after the Calculator was closed by pressing ESC
34 |
35 |
36 | --== Ver 3.21 ==--
37 | - General:
38 | * Update to current Far3 version (dev.build 2728+)
39 | * Fixed work with large console buffer (far /W)
40 | * Fixed: cursor dissapeared after pressing Enter
41 | * Fixed: error text "expression error" is now cleared correctly after pressing Enter
42 | * Fixed: plugin crashed on _numer(NaN) or _denom(NaN)
43 | * Fixed: arith. precision problems in some cases ("30000-6649.23-23350.77")
44 | * Fixed command line and editor expression insertion for Far3
45 | * Fixed: minor fixes for English names and translations
46 | + If all conversion units removed, the starting menu doesn't appear any more
47 |
48 |
49 | --== Ver 3.20 ==--
50 | !ATTENTION!
51 | File calcset.csr is heavily modified in this version!
52 | Please save all your changes from this file before updating plugin version!
53 | Now all user changes are recommended to place in user.csr file (one should be created)
54 | - General:
55 | * Fixed: minimal required Far version is corrected; some users of early versions had problems.
56 | * Fixed: empty or erroneous functions () are no longer cause faults and are simply not used.
57 | * Fixed: for Russian language, menu title "Dialogs" is translated.
58 | * Fixed: units conversion dialog wasn't shown correctly for certain console window size.
59 | * Fixed: the last digit of exponent part wasn't visible in some cases.
60 | * Fixed: unary operators didn't work sometimes.
61 | * Fixed: call of a binary operator from the same unary one ().
62 | * Fixed: symbol _char(38) wasn't displayed.
63 | * Fixed: integer calculation overflow ("factor(1e145)").
64 | * Fixed: non-argument functions behavior ("rnd()").
65 | * Fixed: plugin crashed when an addon was added in between the plugin calls.
66 | * All results are cleared now when the edit box is empty.
67 | * Symbol "=" at the end of expression for calculation in editor is now processed correctly.
68 | * Calculator language is now taken from FAR settings (but it can be overridden by in user.csr);
69 | also other languages are supported by creating language files (.lng) with 2-letter language codes inside.
70 | * User modifiers Kb,Mb,Gb,Tb are now case-insensitive.
71 | * Functions kelv() and sec() corrected, user functions lb(), gtg(), gctg(), gsec(), gcosec() added.
72 | * Functions arcsin() and arccos() corrected, built-in function _cos() added.
73 | * Function _rnd() corrected, now it returns the real pseudo-random number.
74 | + Function curt() added for cubic root (with sign).
75 | + Added date/time functions (jd, jdf, jdg, jdgf, utc, ansid, ratadie).
76 | + Added built-in functions for float/double conversion to binary IEEE-754 format and vice-versa,
77 | and also for 'Inf' and 'NaN' numbers: _f2b(), _d2b(), _b2f(), _b2d(), _finf(), _fnan().
78 | + Basic arithmetic operations for float and double types is now supported and Inf/NaN is displayed.
79 | * Overflow errors are displayed when converting too large(small) numbers to float/double.
80 | * For numerals, 'format' parameter is now used instead of 'radix', with unified syntax for numerals and addons.
81 | + "Lazy" arguments can be used in regular expressions for numerals ("/([0-9])([0-9])?/").
82 | * Big numbers library (ttmath) version updated with some bugfixes, assembler optimization enabled (for x86)
83 | * Code refactoring caused by Far API (compatible with both FAR 2.0 and FAR 3.0).
84 | + Added file user-examples.csr with examples of some additional addons, operators, numerals etc.
85 | - Settings dialog:
86 | + Calculator settings dialog added.
87 | + Option "Show results during the input" which can be turned off.
88 | + Case-sensitive input option.
89 | + Pad zeroes for fixed-size numbers option (_char,_short,_int, etc.).
90 | + Autocomplete input option (turned off by default).
91 | + Delimiter symbols definition:
92 | + decimal point (dot/comma);
93 | + function arguments delimiter (comma, semicolon);
94 | + digit group delimiter (for main calculator mode only);
95 | + regional settings usage option for point/comma/digit groups (turned off by default).
96 | - Addons:
97 | + Built-in addons (dec/hex/oct/bin/exp) moved to calcset.csr, and can be managed (disable, change order).
98 | + New parameter 'format' is added to addons, to set conversion base (radix) and addon format
99 | (see examples in calcset.csr and user-examples.csr).
100 | + Addon math errors are now displayed in their output fields.
101 | - Units converter and CSR files structure:
102 | + Other CSR-files inclusion support added to calcset.csr (format: ).
103 | + All unit conversion dialogs removed from calcset.csr and moved to separate files in 'bin/units/' folder.
104 | + All conversion units revised and supplemented according to suggestions from users.
105 | + New conversion dialogs added for temperature, dates and information measure
106 | (units/temperature.csr, units/date.csr and units/info.csr).
107 | + Conversion dialogs/sets redefinition is now possible (for standard sets correction from the user files).
108 | + Constant math expression can be now specified as a multiplier ('scale').
109 | + Complex math expressions can be used instead of multipliers (using output="" and input=""),
110 | see examples in the files units/temper.csr and units/date.csr.
111 | + Addon formatting rules are used for expressions in the output="" (curly brackets).
112 | + Column width selection method improved for conversion dialogs.
113 | - Fractions support: (EXPERIMENTAL! rational numbers approximations used; see examples in user-examples.csr)
114 | + Repeating decimals with ellipsis (new format="rep" for addon and numeral).
115 | + Finite continued fractions in canonical form of [a,b,c,d] (new format="con" for addon and numeral).
116 | + New built-in functions _numer(op0),_denom(op0) added for vulgar mixed fractions.
117 | + Built-in function _gcd(op0,op1) added for the greatest common divisor.
118 | + User functions added: 'gcd' (greatest common divisor) and 'lcm' (least common multiple).
119 |
120 |
121 | --== Ver 3.10 ==--
122 | - Numbers and expressions:
123 | + New expression parser implemented - no more bugs like "0x1e+0x2e",
124 | but the calc is more slow on extra-large expressions.
125 | + New numbers parser with regular expressions (regexps) and numeral systems implemented - numbers format is now set
126 | with tag in the file calcset.csr (see examples there). Considering that, postfix operators
127 | aren't supported no more.
128 | + 'Priority' parameter added for operators.
129 | + New unified operator list in the file calcset.csr
130 | + Basic bit operations shifted to BigNumbers (to do like this: 1<<100)
131 | * Rotation bit shift operator (_ror, _rol) are now used only with fixed-length types (_byte,_ushort,_uint,...)
132 | * Fixed-length numbers (_byte,_ushort,_uint,...) in bin/oct/hex format are displayed padded with zeroes by default
133 | (can be disabled in the calculator properties in the registry: padZeroes).
134 | * Fixed large _int64 numbers
135 | - Addons:
136 | + A spesial tag is now used for addons in the file calcset.csr
137 | + Addon output formatting added - all calculations are done only for braces {} contents,
138 | the rest is shown in dialog's field. Examples are in calcset.csr (including format 'hh:mm:ss').
139 | * Fixed: if erroneous message entered, the addon field names were erased.
140 | - Units converter dialog:
141 | + Units conversion precision increased (not not less then Converber utility has).
142 | + When switching input fields, the corresponding numbers are selected (highlighted) for easy input of new numbers.
143 | * Light of speed multiplier value corrected; precision of some multipliers and constants increased.
144 | - Miscellaneous:
145 | + Window size changes on-the-fly when console size changes (the larger the window, the more digits shown).
146 | + When Enter is pressed on an error, the resulting string is now selected for easy input of new expression.
147 | + When Enter is pressed on the large expressions, the result is shown from the first digit, if possible.
148 | + Expression limit is now set explicitly - 1024 characters (was 512 chars implicitly).
149 | + "Gray Enter" on numerical keypad now works the same as an ordinary Enter.
150 | + Default type name "double" replaced by "big number", and '_double' can be used again for type conversion.
151 | + For '_char' type the corresponding character symbol is now displayed
152 | + Factorial has become a _factor() function, not operator.
153 | + Hyperbolic sine and cosine functions renamed to 'sinh' and 'cosh' (instead of 'sh' and 'ch')
154 | in order to avoid collisions with hex number 'ch'
155 | * Fixed: current selected radio-button was not shown when dialog was called in sequence.
156 | + Added VERSION_INFO.
157 |
158 |
159 | --== Ver 3.01b ==--
160 | *** This is not a new version of Calculator, just some modifications made
161 | *** by another author. All copyrights of the code, except the new modifications
162 | *** belong to the original author (Cail Lomecb).
163 | Compatibility with FAR 2.0 and higher only (UNICODE version).
164 | Big numbers support added (192 bits for mantissa and 32 bits for exponent)
165 | for all math operations and numeral conversions.
166 | Addons supported - user-defined expressions are now added to the list -
167 | See 'Addons' section in calcset.csr (now in UNICODE format).
168 |
169 |
170 |
171 |
172 | --== Ver 3.0 ==--
173 |
174 | Compatibility with FAR 1.70b3 and higher only.
175 | In b1 and b2 works with bugs.
176 | All dialogs support codes are removed - now far
177 | draw all dialogs himself.
178 | Convertation dialogs now support multilanguage settings.
179 | Pressing Ctrl-Enter in convertation dialog moves current value
180 | from editline into calculator's editline. Pressing it in
181 | calculator moves result into command line in far shell.
182 | Calcset.csr fixed with XML standard, has DTD now.
183 | Some constants names changed:
184 | exp - exponent
185 | light - light speed
186 | grav - gravitation
187 | New combinatorial function CNK.
188 |
189 |
190 | --== Ver 2.9 ==--
191 |
192 | Now you can use dialogs for convertations of values (in
193 | russian language). You can call them from main menu or
194 | directry from calculator with F2 key.
195 | New parser. now you can use different number types,
196 | formats and etc.
197 | Functions Integral and Derived were removed.
198 | Some bugs in codes and defines are fixed.
199 |
200 |
201 | --== Ver 2.8 ==--
202 |
203 | Changed Parser Structure. Now you can define, redefine syntax
204 | and meaning of any operator, constant or function in
205 | CalcSet.Csr file.
206 | Moving Calc's window.
207 | Added mouse support.
208 | Increased calculations precision.
209 |
210 |
211 | --== Ver 2.65 ==--
212 |
213 | With yours requests was changed work in Far's Editor.
214 | Now it works alittle diffent: You must use
215 | macroses Alt=, AltH, AltO, AltB - of course, you can
216 | reassign them.
217 | Also shortcut keys was added.
218 |
219 |
220 | --== Ver 2.6 ==--
221 |
222 | Added work with user Functions/Constants.
223 | Changed Expression Parser.
224 |
225 |
226 | --== Ver 2.05 ==--
227 |
228 | History is avaiable now - Ctrl-Down.
229 | Sign function.
230 | Suffix output while pressing Enter.
231 | Syffixes Kb Mb Gb Tb - Translation to Kilo, Mega,
232 | Giga and Tera bytes.
233 | Added Far 1.6 support. You can use Calc in Editor window.
234 | Cels and Fahr functions.
235 |
236 |
237 | --== Ver 2.01 ==--
238 |
239 | Functions with multiple arguments.
240 | Some new functions.
241 | Now 19 operators "||","&&","|","^","&","!=","==",">>","<<",
242 | ">","<","+","-","*","/","%","pow","~","!"
243 | 18 functions "Sin","Cos","Tg","Ctg","ArcTg","ArcSin",
244 | "ArcCos","Sqrt","Sqr","Ln","Lg","Log","Rad",
245 | "Grad","Sum","Avr","Integral","Derived"
246 |
247 | Parser Changes.
248 | Nice-looking Error messages.
249 |
250 |
251 | --== Ver 1.0b ==--
252 |
253 | Now Calc uses Far's colors.
254 | Added Calc Config.
255 | Normal Screen Saving.
256 | Tested in Far 1.51 и 1.52.
257 |
--------------------------------------------------------------------------------