File: calculator.cpp

package info (click to toggle)
portabase 2.0%2Bgit20110117-1
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 6,692 kB
  • sloc: cpp: 32,047; sh: 2,675; ansic: 2,320; makefile: 343; xml: 20; python: 16; asm: 10
file content (418 lines) | stat: -rw-r--r-- 11,279 bytes parent folder | download | duplicates (2)
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/*
 * calculator.cpp (based on kmymoneycalculator.cpp, by Thomas Baumgart)
 *
 * (c) 2002-2004,2008-2010 by Jeremy Bowman <jmbowman@alum.mit.edu>
 * (c) 2000-2002 by Michael Edwardes <mte@users.sourceforge.net>
 *
 * 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.
 */

/** @file calculator.cpp
 * Source file for Calculator
 */

#include <QAbstractButton>
#include <QDialogButtonBox>
#include <QKeyEvent>
#include <QLabel>
#include <QLayout>
#include <QLocale>
#include <QSignalMapper>
#include <QRegExp>

#include "calculator.h"
#include "factory.h"
#include "formatting.h"

/**
 * Constructor.
 * @param parent The dialog's parent widget, if any.
 */
Calculator::Calculator(QWidget* parent)
  : PBDialog("", parent, true)
{
    setSizeGripEnabled(false);
    m_result = "";

    QGridLayout* grid = new QGridLayout();
    vbox->addLayout(grid);
    grid->setMargin(1);
    grid->setSpacing(2);
    grid->setSizeConstraint(QLayout::SetFixedSize);

    display = new QLabel(this);
#if !defined(Q_WS_MAEMO_5)
    display->setAutoFillBackground(true);
    QPalette displayPalette(display->palette());
    displayPalette.setColor(QPalette::Window, Qt::white);
    display->setPalette(displayPalette);
#endif

    display->setFrameStyle(QFrame::Panel | QFrame::Sunken);
    display->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
    grid->addWidget(display, 0, 0, 1, 5);

    int i;
    for (i = 0; i < MAX_BUTTONS; i++) {
        buttons[i] = Factory::button(this);
        buttons[i]->setSizePolicy(QSizePolicy::MinimumExpanding,
                                  QSizePolicy::Fixed);
    }
    buttons[0]->setText("0");
    buttons[1]->setText("1");
    buttons[2]->setText("2");
    buttons[3]->setText("3");
    buttons[4]->setText("4");
    buttons[5]->setText("5");
    buttons[6]->setText("6");
    buttons[7]->setText("7");
    buttons[8]->setText("8");
    buttons[9]->setText("9");
    buttons[PLUS]->setText("+");
    buttons[MINUS]->setText("-");
    buttons[STAR]->setText("X");
    buttons[DECIMAL]->setText(QLocale::system().decimalPoint());
    buttons[EQUAL]->setText("=");
    buttons[SLASH]->setText("/");
    buttons[CLEAR]->setText("C");
    buttons[CLEARALL]->setText("AC");
    buttons[PLUSMINUS]->setText("+-");
    buttons[PERCENT]->setText("%");

    grid->addWidget(buttons[7], 1, 0);
    grid->addWidget(buttons[8], 1, 1);
    grid->addWidget(buttons[9], 1, 2);
    grid->addWidget(buttons[4], 2, 0);
    grid->addWidget(buttons[5], 2, 1);
    grid->addWidget(buttons[6], 2, 2);
    grid->addWidget(buttons[1], 3, 0);
    grid->addWidget(buttons[2], 3, 1);
    grid->addWidget(buttons[3], 3, 2);
    grid->addWidget(buttons[0], 4, 1);

    grid->addWidget(buttons[DECIMAL], 4, 0);
    grid->addWidget(buttons[PLUS], 3, 3);
    grid->addWidget(buttons[MINUS], 4, 3);
    grid->addWidget(buttons[STAR], 3, 4);
    grid->addWidget(buttons[SLASH], 4, 4);
    grid->addWidget(buttons[EQUAL], 4, 2);
    grid->addWidget(buttons[PLUSMINUS], 2, 3);
    grid->addWidget(buttons[PERCENT], 2, 4);
    grid->addWidget(buttons[CLEAR], 1, 3);
    grid->addWidget(buttons[CLEARALL], 1, 4);

    int colWidth = buttons[CLEARALL]->sizeHint().width();
    for (i = 0; i < 5; i++) {
        grid->setColumnMinimumWidth(i, colWidth);
    }

    buttons[EQUAL]->setFocus();

    op1 = 0.0;
    op = 0;
    operand = "";
    changeDisplay("0");

    // connect the digit signals through a signal mapper
    QSignalMapper* mapper = new QSignalMapper(this);
    for (i = 0; i < 10; i++) {
        mapper->setMapping(buttons[i], i);
        connect(buttons[i], SIGNAL(clicked()), mapper, SLOT(map()));
    }
    connect(mapper, SIGNAL(mapped(int)), this, SLOT(digitClicked(int)));

    // connect the calculation operations through another mapper
    mapper = new QSignalMapper(this);
    for (i = PLUS; i <= EQUAL; i++) {
        mapper->setMapping(buttons[i], i);
        connect(buttons[i], SIGNAL(clicked()), mapper, SLOT(map()));
    }
    connect(mapper, SIGNAL(mapped(int)), this, SLOT(calculationClicked(int)));

    // connect all remaining signals
    connect(buttons[DECIMAL], SIGNAL(clicked()), SLOT(decimalClicked()));
    connect(buttons[PLUSMINUS], SIGNAL(clicked()), SLOT(plusminusClicked()));
    connect(buttons[PERCENT], SIGNAL(clicked()), SLOT(percentClicked()));
    connect(buttons[CLEAR], SIGNAL(clicked()), SLOT(clearClicked()));
    connect(buttons[CLEARALL], SIGNAL(clicked()), SLOT(clearAllClicked()));

    finishLayout();
}

/**
 * Append the digit represented by the parameter to the current operand
 *
 * @param button Integer value of the digit to be added in the range [0..9]
 */
void Calculator::digitClicked(int button)
{
    if (operand.length() >= 20) {
        return;
    }
    QChar newDigit(button + 0x30);
    QLocale locale = QLocale::system();
    QChar decimalPoint = locale.decimalPoint();
    if (operand.length() > 0 && !operand.contains(decimalPoint)) {
        // may need to change separator placement
        qlonglong value = locale.toLongLong(operand);
        operand = QString::number(value) + newDigit;
        value = operand.toLongLong();
        operand = locale.toString(value);
    }
    else {
        operand += newDigit;
    }
    changeDisplay(operand);
}

/**
 * Appends a period (comma) to initialize the fractional
 * part of an operand. The period is only appended once.
 */
void Calculator::decimalClicked()
{
    if (operand.length() == 0) {
        operand = "0";
    }
    QChar decimalPoint = QLocale::system().decimalPoint();
    if (operand.contains(decimalPoint) == 0) {
        operand += decimalPoint;
    }
    if (operand.length() > 16) {
        operand = operand.left(16);
    }
    changeDisplay(operand);
}

/**
 * Reverse the sign of the current operand.
 */
void Calculator::plusminusClicked()
{
    if (operand.length() == 0 && m_result.length() > 0) {
        operand = m_result;
    }
    if (operand.length() > 0) {
        QChar negativeSign = QLocale::system().negativeSign();
        if (operand[0] == negativeSign) {
            operand = operand.mid(1);
        }
        else {
            operand = QString(negativeSign) + operand;
        }
        changeDisplay(operand);
    }
}

/**
 * Start the operation contained in the parameter.
 *
 * @param button The Qt::Keycode for the button pressed or clicked
 */
void Calculator::calculationClicked(int button)
{
    if (operand.length() == 0 && op != 0 && button == EQUAL) {
        op = 0;
        m_result = QLocale::system().toString(op1);
        changeDisplay(m_result);
    }
    else if (operand.length() > 0 && op != 0) {
        // perform operation
        double op2 = QLocale::system().toDouble(operand);
        bool error = false;
        switch(op) {
            case PLUS:
                op2 = op1 + op2;
                break;
            case MINUS:
                op2 = op1 - op2;
                break;
            case STAR:
                op2 = op1 * op2;
                break;
            case SLASH:
                if (op2 == 0.0) {
                    error = true;
                }
                else {
                    op2 = op1 / op2;
                }
                break;
        }
        if (error) {
            op = 0;
            changeDisplay("Error");
            operand = "";
        }
        else {
            op1 = op2;
            m_result = QLocale::system().toString(op1);
            changeDisplay(m_result);
        }
    }
    else if(operand.length() > 0 && op == 0) {
        op1 = QLocale::system().toDouble(operand);
    }

    if (button != EQUAL) {
        op = button;
    }
    else {
        op = 0;
    }
    operand = "";
}

/**
 * Clear the current operand.
 */
void Calculator::clearClicked()
{
    if (operand.length() > 0) {
        QLocale locale = QLocale::system();
        QChar decimalPoint = locale.decimalPoint();
        if (!operand.contains(decimalPoint)) {
            // may need to change separator placement
            qlonglong value = locale.toLongLong(operand);
            operand = QString::number(value);
            operand = operand.left(operand.length() - 1);
            value = operand.toLongLong();
            operand = locale.toString(value);
        }
        else {
            operand = operand.left(operand.length() - 1);
        }
    }
    if (operand.length() == 0) {
        changeDisplay("0");
    }
    else {
        changeDisplay(operand);
    }
}

/**
 * Clear all registers.
 */
void Calculator::clearAllClicked()
{
    operand = "";
    op = 0;
    changeDisplay("0");
}

/**
 * Execute the percent operation.
 */
void Calculator::percentClicked()
{
    if (op != 0) {
        double op2 = QLocale::system().toDouble(operand) / 100;
        if (op == PLUS || op == MINUS) {
            op2 = op1 * op2;
        }
        operand = QLocale::system().toString(op2);
        calculationClicked(EQUAL);
    }
}

/**
 * Extract the result of the last calculation.
 *
 * @return The C-locale string representation of the result of the last
 *         operation
 */
const QString Calculator::result() const
{
    QString txt = operand;
    if (operand.isEmpty()) {
        txt = m_result;
    }
    return Formatting::fromLocalDouble(txt);
}

/**
 * Update the display of the calculator.
 *
 * @param str The new display contents
 */
void Calculator::changeDisplay(const QString& str)
{
    display->setText("<b>" + str + "</b>");
}

void Calculator::keyPressEvent(QKeyEvent* ev)
{
    int button = -1;

    switch(ev->key()) {
        case Qt::Key_0:
        case Qt::Key_1:
        case Qt::Key_2:
        case Qt::Key_3:
        case Qt::Key_4:
        case Qt::Key_5:
        case Qt::Key_6:
        case Qt::Key_7:
        case Qt::Key_8:
        case Qt::Key_9:
            button = ev->key() - Qt::Key_0;
            break;
        case Qt::Key_Plus:
            button = PLUS;
            break;
        case Qt::Key_Comma:
            button = DECIMAL;
            break;
        case Qt::Key_Minus:
            button = MINUS;
            break;
        case Qt::Key_Period:
            button = DECIMAL;
            break;
        case Qt::Key_Slash:
            button = SLASH;
            break;
        case Qt::Key_Backspace:
            button = CLEAR;
            break;
        case Qt::Key_Asterisk:
            button = STAR;
            break;
        case Qt::Key_Return:
        case Qt::Key_Enter:
        case Qt::Key_Equal:
            button = EQUAL;
            break;
        case Qt::Key_Escape:
            button = CLEARALL;
            break;
        case Qt::Key_Percent:
            button = PERCENT;
            break;
        default:
            ev->ignore();
            break;
    }
    if (button != -1) {
        buttons[button]->animateClick();
    }
}

/**
 * Preset the first operand.
 *
 * @param value The operand's value
 */
void Calculator::setInitialValue(const QString& value)
{
    // setup operand
    operand = value;
    op1 = Formatting::parseDouble(value);
    m_result = QLocale::system().toString(op1);
    changeDisplay(m_result);
    operand = "";
}