summaryrefslogtreecommitdiffstats
path: root/katapult/plugins/catalogs/calculatorcatalog/calculatorcatalog.cpp
blob: 12891d03d392ba9344840032a10c72823d84a99c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/***************************************************************************
 *   Copyright (C) 2005  Tobi Vollebregt                                   *
 *   tobivollebregt@gmail.com                                              *
 *                                                                         *
 *   Copyright (C) 2005 by Joe Ferris                                      *
 *   jferris@optimistictech.com                                            *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.             *
 ***************************************************************************/

#include <kservicegroup.h>
#include <ksycocaentry.h>
#include <ksycocatype.h>
#include <kapplication.h>
#include <knuminput.h>
#include <kcombobox.h>

#include <tqcheckbox.h>
#include <tqbuttongroup.h>
#include <tqradiobutton.h>
#include <tqregexp.h>

#include <math.h>

#include "settings.h"
#include "calculatorcatalog.h"
#include "expression.h"
#include "actionregistry.h"
#include "actionevalexpr.h"
#include "status.h"


#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

#ifndef M_E
#define M_E  2.7182818284590452354
#endif


static double frac(double x)
{
	double nowhere;
	return modf(x, &nowhere);
}


static double deg_sin(double x)   { return sin(x * (M_PI / 180.0)); }
static double deg_cos(double x)   { return cos(x * (M_PI / 180.0)); }
static double deg_tan(double x)   { return tan(x * (M_PI / 180.0)); }
static double deg_asin(double x)  { return asin(x) * (180.0 / M_PI); }
static double deg_acos(double x)  { return acos(x) * (180.0 / M_PI); }
static double deg_atan(double x)  { return atan(x) * (180.0 / M_PI); }
static double deg_sinh(double x)  { return sinh(x * (M_PI / 180.0)); }
static double deg_cosh(double x)  { return cosh(x * (M_PI / 180.0)); }
static double deg_tanh(double x)  { return tanh(x * (M_PI / 180.0)); }
static double deg_asinh(double x) { return asinh(x) * (180.0 / M_PI); }
static double deg_acosh(double x) { return acosh(x) * (180.0 / M_PI); }
static double deg_atanh(double x) { return atanh(x) * (180.0 / M_PI); }


const CalculatorCatalog::Function CalculatorCatalog::radiansFunctionTable[] =
{
	{ "sin",   3, sin   },
	{ "cos",   3, cos   },
	{ "tan",   3, tan   },
	{ "asin",  4, asin  },
	{ "acos",  4, acos  },
	{ "atan",  4, atan  },
	{ "sinh",  4, sinh  },
	{ "cosh",  4, cosh  },
	{ "tanh",  4, tanh  },
	{ "asinh", 5, asinh },
	{ "acosh", 5, acosh },
	{ "atanh", 5, atanh },
	{ "sqrt",  4, sqrt  },
	{ "log",   3, log10 },
	{ "ln",    2, log   },
	{ "exp",   3, exp   },
	{ "abs",   3, fabs  },
	{ "frac",  4, frac  },
	{ "round", 5, round },
	{ "int",   3, trunc },
	{ 0, 0, 0 }
};

const CalculatorCatalog::Function CalculatorCatalog::degreesFunctionTable[] =
{
	{ "sin",   3, deg_sin   },
	{ "cos",   3, deg_cos   },
	{ "tan",   3, deg_tan   },
	{ "asin",  4, deg_asin  },
	{ "acos",  4, deg_acos  },
	{ "atan",  4, deg_atan  },
	{ "sinh",  4, deg_sinh  },
	{ "cosh",  4, deg_cosh  },
	{ "tanh",  4, deg_tanh  },
	{ "asinh", 5, deg_asinh },
	{ "acosh", 5, deg_acosh },
	{ "atanh", 5, deg_atanh },
	{ "sqrt",  4, sqrt  },
	{ "log",   3, log10 },
	{ "ln",    2, log   },
	{ "exp",   3, exp   },
	{ "abs",   3, fabs  },
	{ "frac",  4, frac  },
	{ "round", 5, round },
	{ "int",   3, trunc },
	{ 0, 0, 0 }
};


K_EXPORT_COMPONENT_FACTORY( katapult_calculatorcatalog,
                            KGenericFactory<CalculatorCatalog>( "katapult_calculatorcatalog" ) )

CalculatorCatalog::CalculatorCatalog(TQObject*, const char*, const TQStringList&): _result(this, TQString())
{
	ActionRegistry::self()->registerAction(new ActionEvaluateExpression());

	setVar(getVarID("pi"), M_PI);
	setVar(getVarID("e"), M_E);
}

CalculatorCatalog::~CalculatorCatalog()
{
}

void CalculatorCatalog::queryChanged()
{
	int newtqStatus = 0;
	TQString cmd = query();

	if (cmd.isEmpty()) {
		reset();
		setBestMatch(Match());
	} else {
		if (accepts(cmd)) {
			int i, origLength = cmd.length(), length = origLength;
			//autocomplete functions
			cmd = cmd.lower();
			for (i = length - 1; i >= 0 && cmd[i].isLetter(); --i) { }
			if (i != length - 1) {
				TQString start = cmd.mid(i + 1);
				int lengthOfShortest = 9999, shortest = -1;
				for (int j = 0; radiansFunctionTable[j].name; ++j) {
					if (TQString(radiansFunctionTable[j].name).startsWith(start)) {
						if (radiansFunctionTable[j].length < lengthOfShortest) {
							lengthOfShortest = radiansFunctionTable[j].length;
							shortest = j;
						}
					}
				}
				if (shortest != -1) {
					cmd = cmd.left(i + 1).append(radiansFunctionTable[shortest].name).append("(");
					length = cmd.length();
				}
			}
			//fix parse errors at end of expression,
			//ie. close open parentheses, convert operators into NOPs
			for (i = length - 1; i >= 0 && (cmd[i] == '(' || cmd[i] == ' '); --i) { }
			if (i < 0 || cmd[i] == '+' || cmd[i] == '-') {
				cmd.append("0");
				++length;
			} else if (cmd[i] == '*' || cmd[i] == '/' || cmd[i] == '^') {
				cmd.append("1");
				++length;
			} else if (cmd[i].isLetter() && (i < length - 1 && cmd[i + 1] == '(')) {
				//just add a 0 if it's a function: we don't bother to backpropagate
				//through the parse tree (if it existed at all) to figure out a NOP value
				//for this particular (chain of) function(s).
				cmd.append("0");
				++length;
			}
			int openParen = 0;
			//use cmd.length() here, it may be > than length.
			for (i = 0; i < length; ++i) {
				if (cmd[i] == '(') ++openParen;
				if (cmd[i] == ')') --openParen;
			}
			if (openParen > 0) {
				char* closeParen = new char[openParen + 1];
				memset(closeParen, ')', openParen);
				closeParen[openParen] = 0;
				cmd.append(closeParen);
				delete[] closeParen;
			}
			_result.setText(cmd);
			setBestMatch(Match(&_result, _result.parseError() ? 10 : 100, origLength));
			//set status.
			//add S_Multiple to make sure katapult doesn't auto-exec and close the window
			//add S_Active to make sure katapult doesn't start the hideTimer or clearTimer
			newtqStatus = S_HasResults | S_Multiple | S_Active;
		} else {
			newtqStatus = 0;
		}
	}
	settqStatus(newtqStatus);
}

void CalculatorCatalog::reset()
{
	_result.setText(TQString());
}

bool CalculatorCatalog::accepts(const TQString& str) const
{
	//Heuristic to determine whether the string is an expression or not.
	//Accept anything containing [()+\\-/*^=.,0-9].
	return TQRegExp("[()+\\-/*^=.,0-9]").search(str) >= 0;
}

int CalculatorCatalog::getVarID(const char* name)
{
	VarNameToIdMap::iterator it = varNameToId.tqfind(TQString(name));
	if (it == varNameToId.end()) {
		_pendingVarName = TQString(name);
		return -1;
	}
	return *it;
}

double CalculatorCatalog::getVar(int id) const
{
	return varIdToValue[id];
}

double CalculatorCatalog::setVar(int id, double value)
{
	if (id == -1) {
		id = varIdToValue.count();
		varNameToId.insert(_pendingVarName, id);
		varIdToValue.push_back(value);
	} else {
		varIdToValue[id] = value;
	}
	return value;
}

/*
void CalculatorCatalog::initialize()
{
}
*/

void CalculatorCatalog::readSettings(KConfigBase* config)
{
	_fracDigits = config->readUnsignedNumEntry("FracDigits", 2);
	_bScientific = config->readBoolEntry("Scientific", false);
	_bDegrees = config->readBoolEntry("Degrees", false);
	_bClipboard = config->readBoolEntry("Clipboard", true);
	_formatString = config->readEntry("FormatString", "%1 = %2");
}

void CalculatorCatalog::writeSettings(KConfigBase* config)
{
	config->writeEntry("FracDigits", fracDigits());
	config->writeEntry("Scientific", scientific());
	config->writeEntry("Degrees", degrees());
	config->writeEntry("Clipboard", clipboard());
	config->writeEntry("FormatString", formatString());
}

TQWidget * CalculatorCatalog::configure()
{
	CalculatorCatalogSettings* settings = new CalculatorCatalogSettings();

	settings->fracDigits->setValue(_fracDigits);
	connect(settings->fracDigits, TQT_SIGNAL(valueChanged(int)), this, TQT_SLOT(fracDigitsChanged(int)));

	settings->normal->setChecked(!scientific());
	settings->scientific->setChecked(scientific());
	connect(settings->scientific, TQT_SIGNAL(toggled(bool)), this, TQT_SLOT(scientificChanged(bool)));

	settings->radians->setChecked(!degrees());
	settings->degrees->setChecked(degrees());
	connect(settings->degrees, TQT_SIGNAL(toggled(bool)), this, TQT_SLOT(degreesChanged(bool)));

	settings->clipboard->setChecked(clipboard());
	connect(settings->clipboard, TQT_SIGNAL(toggled(bool)), this, TQT_SLOT(clipboardChanged(bool)));

	settings->formatString->setText(formatString());
	connect(settings->formatString, TQT_SIGNAL(textChanged(const TQString&)), this, TQT_SLOT(formatStringChanged(const TQString&)));

	return settings;
}

void CalculatorCatalog::fracDigitsChanged(int n)
{
	_fracDigits = n;
}

int CalculatorCatalog::fracDigits() const
{
	return _fracDigits;
}

void CalculatorCatalog::scientificChanged(bool en)
{
	_bScientific = en;
}

bool CalculatorCatalog::scientific() const
{
	return _bScientific;
}

void CalculatorCatalog::degreesChanged(bool en)
{
	_bDegrees = en;
}

bool CalculatorCatalog::degrees() const
{
	return _bDegrees;
}

void CalculatorCatalog::formatStringChanged(const TQString& fmt)
{
	_formatString = fmt;
}

TQString CalculatorCatalog::formatString() const
{
	return _formatString;
}

void CalculatorCatalog::clipboardChanged(bool en)
{
	_bClipboard = en;
}

bool CalculatorCatalog::clipboard() const
{
	return _bClipboard;
}

const CalculatorCatalog::Function* CalculatorCatalog::functionTable() const
{
	if (degrees()) {
		return degreesFunctionTable;
	} else {
		return radiansFunctionTable;
	}
}

#include "calculatorcatalog.moc"