summaryrefslogtreecommitdiffstats
path: root/kspread/plugins
diff options
context:
space:
mode:
authortpearson <tpearson@283d02a7-25f6-0310-bc7c-ecb5cbfe19da>2010-01-20 01:29:50 +0000
committertpearson <tpearson@283d02a7-25f6-0310-bc7c-ecb5cbfe19da>2010-01-20 01:29:50 +0000
commit8362bf63dea22bbf6736609b0f49c152f975eb63 (patch)
tree0eea3928e39e50fae91d4e68b21b1e6cbae25604 /kspread/plugins
downloadkoffice-8362bf63dea22bbf6736609b0f49c152f975eb63.tar.gz
koffice-8362bf63dea22bbf6736609b0f49c152f975eb63.zip
Added old abandoned KDE3 version of koffice
git-svn-id: svn://anonsvn.kde.org/home/kde/branches/trinity/applications/koffice@1077364 283d02a7-25f6-0310-bc7c-ecb5cbfe19da
Diffstat (limited to 'kspread/plugins')
-rw-r--r--kspread/plugins/Makefile.am5
-rw-r--r--kspread/plugins/calculator/Makefile.am29
-rw-r--r--kspread/plugins/calculator/configdlg.cpp199
-rw-r--r--kspread/plugins/calculator/configdlg.h111
-rw-r--r--kspread/plugins/calculator/configure.in.in45
-rw-r--r--kspread/plugins/calculator/dlabel.cpp65
-rw-r--r--kspread/plugins/calculator/dlabel.h65
-rw-r--r--kspread/plugins/calculator/kcalc.cpp1787
-rw-r--r--kspread/plugins/calculator/kcalc.h447
-rw-r--r--kspread/plugins/calculator/kcalc_core.cpp2192
-rw-r--r--kspread/plugins/calculator/kcalctype.h104
-rw-r--r--kspread/plugins/calculator/kspreadcalc.rc8
-rw-r--r--kspread/plugins/calculator/main.cpp199
-rw-r--r--kspread/plugins/calculator/main.h76
-rw-r--r--kspread/plugins/calculator/pics/Makefile.am4
-rw-r--r--kspread/plugins/calculator/pics/lo16-app-kspreadcalc.pngbin0 -> 280 bytes
-rw-r--r--kspread/plugins/calculator/pics/lo22-app-kspreadcalc.pngbin0 -> 588 bytes
-rw-r--r--kspread/plugins/calculator/pics/lo32-app-kspreadcalc.pngbin0 -> 987 bytes
-rw-r--r--kspread/plugins/calculator/stats.cpp334
-rw-r--r--kspread/plugins/calculator/stats.h80
-rw-r--r--kspread/plugins/calculator/uninstall.desktop3
-rw-r--r--kspread/plugins/calculator/version.h1
-rw-r--r--kspread/plugins/insertcalendar/Makefile.am26
-rw-r--r--kspread/plugins/insertcalendar/insertcalendar.rc8
-rw-r--r--kspread/plugins/insertcalendar/kspread_insertcalendardialog.cc150
-rw-r--r--kspread/plugins/insertcalendar/kspread_insertcalendardialog.h165
-rw-r--r--kspread/plugins/insertcalendar/kspread_insertcalendardialogbase.ui207
-rw-r--r--kspread/plugins/insertcalendar/kspread_plugininsertcalendar.cc281
-rw-r--r--kspread/plugins/insertcalendar/kspread_plugininsertcalendar.h113
-rw-r--r--kspread/plugins/scripting/Makefile.am23
-rw-r--r--kspread/plugins/scripting/kspreadcore/CMakeLists.txt56
-rw-r--r--kspread/plugins/scripting/kspreadcore/Makefile.am23
-rw-r--r--kspread/plugins/scripting/kspreadcore/krs_cell.cpp211
-rw-r--r--kspread/plugins/scripting/kspreadcore/krs_cell.h170
-rw-r--r--kspread/plugins/scripting/kspreadcore/krs_doc.cpp135
-rw-r--r--kspread/plugins/scripting/kspreadcore/krs_doc.h122
-rw-r--r--kspread/plugins/scripting/kspreadcore/krs_sheet.cpp103
-rw-r--r--kspread/plugins/scripting/kspreadcore/krs_sheet.h140
-rw-r--r--kspread/plugins/scripting/kspreadcore/kspreadcoremodule.cpp82
-rw-r--r--kspread/plugins/scripting/kspreadcore/kspreadcoremodule.h82
-rw-r--r--kspread/plugins/scripting/kspreadscripting.desktop80
-rw-r--r--kspread/plugins/scripting/scripting.cc84
-rw-r--r--kspread/plugins/scripting/scripting.h49
-rw-r--r--kspread/plugins/scripting/scripting.rc13
-rw-r--r--kspread/plugins/scripting/scripts/Makefile.am1
-rwxr-xr-xkspread/plugins/scripting/scripts/exporthtml/ExportHtml.py179
-rwxr-xr-xkspread/plugins/scripting/scripts/exporthtml/ExportHtml.rc9
-rw-r--r--kspread/plugins/scripting/scripts/exporthtml/Makefile.am2
-rw-r--r--kspread/plugins/scripting/scripts/scripteditor/Makefile.am2
-rwxr-xr-xkspread/plugins/scripting/scripts/scripteditor/ScriptEditor.py1089
-rwxr-xr-xkspread/plugins/scripting/scripts/scripteditor/ScriptEditor.rc9
51 files changed, 9368 insertions, 0 deletions
diff --git a/kspread/plugins/Makefile.am b/kspread/plugins/Makefile.am
new file mode 100644
index 000000000..d1969dba5
--- /dev/null
+++ b/kspread/plugins/Makefile.am
@@ -0,0 +1,5 @@
+if compile_kross
+ SCRIPTINGDIR=scripting
+endif
+
+SUBDIRS = insertcalendar $(SCRIPTINGDIR)
diff --git a/kspread/plugins/calculator/Makefile.am b/kspread/plugins/calculator/Makefile.am
new file mode 100644
index 000000000..28afe7af7
--- /dev/null
+++ b/kspread/plugins/calculator/Makefile.am
@@ -0,0 +1,29 @@
+INCLUDES = -I$(srcdir)/../../../kspread $(KOFFICE_INCLUDES) $(KOTEXT_INCLUDES) -I$(top_srcdir)/lib/koscript -I$(top_builddir)/lib/koscript $(all_includes)
+
+kde_module_LTLIBRARIES = libkspreadcalc.la
+
+libkspreadcalc_la_SOURCES = configdlg.cpp \
+ dlabel.cpp \
+ kcalc.cpp \
+ kcalc_core.cpp \
+ main.cpp \
+ stats.cpp
+libkspreadcalc_la_LDFLAGS = $(all_libraries) -avoid-version -module -no-undefined
+libkspreadcalc_la_LIBADD = ../../libkspreadcommon.la
+
+METASOURCES = AUTO
+
+# Delete old unused file
+install-data-local: uninstall.desktop
+ $(mkinstalldirs) $(DESTDIR)$(kde_servicesdir)
+ $(INSTALL_DATA) $(srcdir)/uninstall.desktop $(DESTDIR)$(kde_servicesdir)/kspreadcalc.desktop
+
+rc_DATA = kspreadcalc.rc
+rcdir = $(kde_datadir)/kspread/kpartplugins
+
+SUBDIRS = pics
+
+messages: rc.cpp
+ $(XGETTEXT) *.cpp -o $(podir)/kspreadcalc_calc.pot
+
+
diff --git a/kspread/plugins/calculator/configdlg.cpp b/kspread/plugins/calculator/configdlg.cpp
new file mode 100644
index 000000000..9273b91a5
--- /dev/null
+++ b/kspread/plugins/calculator/configdlg.cpp
@@ -0,0 +1,199 @@
+/*
+
+ $Id: configdlg.cpp 466447 2005-10-02 17:54:10Z zander $
+
+ KCalc
+
+ Copyright (C) Bernd Johannes Wuebben
+ wuebben@math.cornell.edu
+ wuebben@kde.org
+
+ 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 "configdlg.h"
+
+#include <klocale.h>
+#include <kdialog.h>
+#include <qlayout.h>
+
+// Undefine HAVE_LONG_DOUBLE for Beta 4 since RedHat 5.0 comes with a borken
+// glibc
+
+#ifdef HAVE_LONG_DOUBLE
+#undef HAVE_LONG_DOUBLE
+#endif
+
+ConfigDlg::ConfigDlg(QWidget *parent, const char *name, DefStruct *defstruct)
+ : QDialog(parent, name)
+{
+ defst = defstruct;
+
+ QVBoxLayout *lay1 = new QVBoxLayout( this );
+ lay1->setMargin( KDialog::marginHint() );
+ lay1->setSpacing( KDialog::spacingHint() );
+
+ box = new QGroupBox(0, Qt::Vertical, i18n("Defaults"), this, "box");
+ box->layout()->setSpacing(KDialog::spacingHint());
+ box->layout()->setMargin(KDialog::marginHint());
+
+ QGridLayout *grid1 = new QGridLayout(box->layout(),8,2);
+ label1 = new QLabel(box);
+ label1->setText(i18n("Foreground color:"));
+ grid1->addWidget(label1,0,0);
+
+ button1 = new KColorButton( box, "button1" );
+ grid1->addWidget(button1,0,1);
+ button1->setColor( defst->forecolor );
+
+ connect(button1 , SIGNAL( changed( const QColor & ) ),
+ this, SLOT( set_fore_color( const QColor & ) ) );
+
+ label2 = new QLabel(box);
+ grid1->addWidget(label2,1,0);
+ label2->setText(i18n("Background color:"));
+
+ button2 = new KColorButton( box, "button2" );
+ grid1->addWidget(button2,1,1);
+ button2->setColor( defst->backcolor );
+
+ connect(button2 , SIGNAL( changed( const QColor & ) ),
+ this, SLOT( set_background_color( const QColor & ) ) );
+
+
+ // connect(button2,SIGNAL(clicked()),this,SLOT(set_background_color()));
+
+
+ label5 = new QLabel(box);
+ grid1->addWidget(label5,2,0);
+ label5->setText(i18n("Precision:"));
+
+ int maxprec;
+#ifdef HAVE_LONG_DOUBLE
+ maxprec = 16 ;
+#else
+ maxprec = 12 ;
+#endif
+
+ precspin = new QSpinBox( box );
+ precspin->setRange( 0, maxprec );
+ grid1->addWidget(precspin,2,1);
+
+ if( defst->precision <= maxprec)
+ precspin->setValue(defst->precision);
+ else
+ precspin->setValue(maxprec);
+
+
+ cb = new QCheckBox(box);
+ grid1->addWidget(cb,3,0);
+ cb->setText(i18n("Set fixed precision at:"));
+ if(defst->fixed)
+ cb->setChecked(true);
+
+ int fixprec;
+#ifdef HAVE_LONG_DOUBLE
+ fixprec = 14 ;
+#else
+ fixprec = 10 ;
+#endif
+
+ precspin2 = new QSpinBox( box );
+ precspin2->setRange(0,fixprec);
+ grid1->addWidget(precspin2,3,1);
+
+ if( defst->fixedprecision <= fixprec)
+ precspin2->setValue(defst->fixedprecision);
+ else
+ precspin2->setValue(fixprec);
+
+
+
+ cb2 = new QCheckBox(box);
+ grid1->addWidget(cb2,4,0);
+ cb2->setText(i18n("Beep on error"));
+ if(defst->beep)
+ cb2->setChecked(true);
+
+
+ stylegroup = new QButtonGroup(box,"stylegroup");
+ grid1->addMultiCellWidget(stylegroup,5,7,0,1);
+ stylegroup->setFrameStyle(QFrame::NoFrame);
+
+ QGridLayout *grid2 = new QGridLayout(stylegroup,2,2,KDialog::marginHint(), KDialog::spacingHint());
+
+ trigstyle = new QRadioButton(i18n("Trigonometry mode"),stylegroup,"trigstyle");
+ grid2->addWidget(trigstyle,0,0);
+ trigstyle->adjustSize();
+ trigstyle->setChecked(defst->style == 0 );
+
+ statstyle = new QRadioButton(i18n("Statistical mode"),stylegroup,"Stats");
+ grid2->addWidget(statstyle,1,0);
+ statstyle->adjustSize();
+ statstyle->setChecked(defst->style == 1 );
+
+ sheetstyle = new QRadioButton(i18n("Sheet mode"),stylegroup,"Sheet");
+ grid2->addWidget(sheetstyle,2,0);
+ sheetstyle->adjustSize();
+
+ sheetstyle->setChecked(defst->style == 2 );
+ button3 = new QPushButton(stylegroup);
+ grid2->addWidget(button3,0,1);
+ button3->setText(i18n("Help"));
+
+ connect(button3,SIGNAL(clicked()),this,SLOT(help()));
+
+ lay1->addWidget(box);
+ connect(parent,SIGNAL(applyButtonPressed()),SLOT(okButton()));
+}
+
+void ConfigDlg::help()
+{
+}
+
+void ConfigDlg::okButton()
+{
+ defst->precision = precspin->value();
+ defst->fixedprecision = precspin2->value();
+ defst->fixed = cb->isChecked();
+ defst->beep = cb2->isChecked();
+
+
+ if( trigstyle->isChecked())
+ defst->style = 0;
+ else if ( statstyle->isChecked() )
+ defst->style = 1;
+ else
+ defst->style = 2;
+}
+
+void ConfigDlg::cancelbutton()
+{
+ reject();
+}
+
+void ConfigDlg::set_fore_color(const QColor &_color)
+{
+ defst->forecolor=_color;
+}
+
+void ConfigDlg::set_background_color( const QColor &_color )
+{
+ defst->backcolor=_color;
+}
+
+#include "configdlg.moc"
diff --git a/kspread/plugins/calculator/configdlg.h b/kspread/plugins/calculator/configdlg.h
new file mode 100644
index 000000000..0de8262ea
--- /dev/null
+++ b/kspread/plugins/calculator/configdlg.h
@@ -0,0 +1,111 @@
+
+/*
+
+ $Id: configdlg.h 466447 2005-10-02 17:54:10Z zander $
+
+
+ KCalc
+
+ Copyright (C) Bernd Johannes Wuebben
+ wuebben@math.cornell.edu
+ wuebben@kde.org
+
+ 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.
+
+ */
+
+
+#ifndef _CONFIG_DLG_H_
+#define _CONFIG_DLG_H_
+
+#include <qgroupbox.h>
+#include <qcheckbox.h>
+#include <qdialog.h>
+#include <qlineedit.h>
+#include <qpushbutton.h>
+#include <qpainter.h>
+#include <qlabel.h>
+#include <qframe.h>
+#include <qspinbox.h>
+#include <kcolorbutton.h>
+
+#include "kcalc.h"
+
+
+
+class ConfigDlg : public QDialog {
+
+Q_OBJECT
+
+public:
+
+ ConfigDlg(QWidget *parent=0, const char *name=0, DefStruct *defstruct=NULL);
+
+ ~ConfigDlg() {}
+
+ DefStruct *defst ;
+ QLineEdit *mail;
+ QLineEdit *print;
+
+
+private slots:
+
+ void okButton();
+ void cancelbutton();
+ void set_fore_color(const QColor &);
+ void set_background_color(const QColor &);
+ void help();
+
+signals:
+ void color_change();
+
+public:
+ bool colors_changed;
+
+private:
+
+
+ QGroupBox *box;
+
+ QPushButton *ok;
+ QPushButton *cancel;
+
+ QLabel *label1;
+ KColorButton *button1;
+
+ QLabel *label2;
+ KColorButton *button2;
+
+ QLabel *label3;
+ QPushButton *button3;
+ QLabel *label5;
+
+ QGroupBox *gbox;
+ QCheckBox *cb;
+ QCheckBox *cb2;
+ QSpinBox* precspin;
+ QSpinBox* precspin2;
+ QCheckBox *mybox;
+ QCheckBox *frame3d;
+
+ QButtonGroup *stylegroup;
+ QLabel *stylelabel;
+ QRadioButton *trigstyle;
+ QRadioButton *statstyle;
+ QRadioButton *sheetstyle;
+};
+#endif
+
diff --git a/kspread/plugins/calculator/configure.in.in b/kspread/plugins/calculator/configure.in.in
new file mode 100644
index 000000000..d8d82e940
--- /dev/null
+++ b/kspread/plugins/calculator/configure.in.in
@@ -0,0 +1,45 @@
+AC_CHECK_HEADERS(ieeefp.h)
+
+AC_CHECK_FUNCS(fabsl)
+
+AC_DEFUN([KDE_C_LONG_DOUBLE],
+[
+ AC_CACHE_CHECK(for long double, ac_cv_c_long_double,
+ [
+ AC_TRY_RUN(
+ [
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+
+int main() {
+/* The Stardent Vistra knows sizeof(long double), but does not support it. */
+long double foo = 1.0;
+char buffer[10];
+/* On Ultrix 4.3 cc, long double is 4 and double is 8. */
+int result = (sizeof(long double) < sizeof(double));
+/* the following is needed for a broken printf in glibc2 */
+if (!result) {
+ foo = foo * 3;
+ sprintf(buffer,"%0.0Lf",foo);
+ result = strcmp(buffer, "3");
+/* and now something mean ;-) */
+ foo = powl(fabsl(foo), 1);
+}
+exit(result); }
+ ],
+ ac_cv_c_long_double=yes, ac_cv_c_long_double=no,
+ ac_cv_c_long_double=no
+ )
+ ])
+ if test $ac_cv_c_long_double = yes; then
+ AC_DEFINE(HAVE_LONG_DOUBLE, 1, [Define if you have support for long double in printf])
+ fi
+])
+KDE_C_LONG_DOUBLE
+
+AC_LANG_C
+KDE_CHECK_LIB(m, isinf, [
+ AC_DEFINE_UNQUOTED(HAVE_FUNC_ISINF, 1, [Define if you have isinf])
+])
diff --git a/kspread/plugins/calculator/dlabel.cpp b/kspread/plugins/calculator/dlabel.cpp
new file mode 100644
index 000000000..b35f26664
--- /dev/null
+++ b/kspread/plugins/calculator/dlabel.cpp
@@ -0,0 +1,65 @@
+/*
+ $Id: dlabel.cpp 466447 2005-10-02 17:54:10Z zander $
+
+ KCalc, a scientific calculator for the X window system using the
+ Qt widget libraries, available at no cost at http://www.troll.no
+
+ Copyright (C) 1996 Bernd Johannes Wuebben
+ wuebben@math.cornell.edu
+
+ 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 "dlabel.h"
+
+DLabel::DLabel(QWidget *parent, const char *name)
+ :QLabel(parent,name){
+
+ button = 0;
+ lit = false;
+}
+
+void DLabel::mousePressEvent(QMouseEvent *e){
+
+ if(e->button() == LeftButton){
+ lit = !lit;
+ button = LeftButton;
+ }
+ else{
+ button = MidButton;
+ }
+
+
+ emit clicked();
+}
+
+
+int DLabel::Button(){
+ return button;
+}
+
+bool DLabel::isLit(){
+
+ return lit;
+
+}
+
+void DLabel::setLit(bool _lit){
+ lit = _lit;
+}
+
+#include "dlabel.moc"
diff --git a/kspread/plugins/calculator/dlabel.h b/kspread/plugins/calculator/dlabel.h
new file mode 100644
index 000000000..9222e990d
--- /dev/null
+++ b/kspread/plugins/calculator/dlabel.h
@@ -0,0 +1,65 @@
+/*
+
+ $Id: dlabel.h 466447 2005-10-02 17:54:10Z zander $
+
+ KCalc
+
+ Copyright (C) Bernd Johannes Wuebben
+ wuebben@math.cornell.edu
+ wuebben@kde.org
+
+ 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.
+
+ */
+
+
+#ifndef _D_LABEL_H_
+#define _D_LABEL_H_
+
+#include <qlabel.h>
+
+
+class DLabel : public QLabel {
+
+Q_OBJECT
+
+public:
+
+DLabel(QWidget *parent=0, const char *name=0);
+
+ ~DLabel() {}
+
+protected:
+
+ void mousePressEvent ( QMouseEvent *);
+
+public:
+ bool isLit();
+ void setLit(bool _lit);
+ int Button();
+
+private:
+ int button;
+ bool lit;
+
+signals:
+ void clicked();
+
+};
+
+
+
+#endif
diff --git a/kspread/plugins/calculator/kcalc.cpp b/kspread/plugins/calculator/kcalc.cpp
new file mode 100644
index 000000000..1726653b3
--- /dev/null
+++ b/kspread/plugins/calculator/kcalc.cpp
@@ -0,0 +1,1787 @@
+/*
+ $Id: kcalc.cpp 466447 2005-10-02 17:54:10Z zander $
+
+ kCalculator, a simple scientific calculator for KDE
+
+ Copyright (C) 1996 Bernd Johannes Wuebben wuebben@math.cornell.edu
+
+ 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 "configdlg.h"
+#include "version.h"
+#include <klocale.h>
+#include <knotifyclient.h>
+#include <qlayout.h>
+#include <qobjectlist.h>
+#include <qpushbutton.h>
+#include <kapplication.h>
+#include <kglobalsettings.h>
+#include <qstyle.h>
+#include <kdialog.h>
+#include <kconfig.h>
+#include <kglobal.h>
+#include "kcalc.h"
+
+extern last_input_type last_input;
+extern item_contents display_data;
+extern num_base current_base;
+
+QPtrList<CALCAMNT> temp_stack;
+
+QtCalculator :: QtCalculator( Calculator *_corba, QWidget *parent, const char *name )
+ : QDialog( parent, name )
+{
+
+ corba = _corba;
+ mInternalSpacing=4;
+ key_pressed = false;
+ selection_timer = new QTimer;
+ status_timer = new QTimer;
+
+ connect(status_timer,SIGNAL(timeout()),this,SLOT(clear_status_label()));
+ connect(selection_timer,SIGNAL(timeout()),this,SLOT(selection_timed_out()));
+
+ readSettings();
+
+ QFont buttonfont( KGlobalSettings::generalFont() );
+ buttonfont.setStyleStrategy( QFont::PreferAntialias );
+
+ // Set the window caption/title
+
+ // connect(kapp,SIGNAL(kdisplayPaletteChanged()),this,SLOT(set_colors()));
+ // setCaption( kapp->caption() );
+
+ // create help button
+
+ QPushButton *pb;
+
+ pb = new QPushButton( this, "helpbutton" );
+ pb->setText( "kCalc" );
+ pb->setFont( QFont("times",12,QFont::Bold,FALSE) );
+ QToolTip::add( pb, i18n("KCalc Setup/Help") );
+
+ connect( pb, SIGNAL(clicked()), SLOT(configclicked()) );
+
+ // Create the display
+ calc_display = new DLabel( this, "display" );
+ calc_display->setFrameStyle( QFrame::WinPanel | QFrame::Sunken );
+ calc_display->setAlignment( AlignRight|AlignVCenter );
+ calc_display->setFocus();
+ calc_display->setFocusPolicy( QWidget::StrongFocus );
+
+ connect(calc_display,SIGNAL(clicked()),this,SLOT(display_selected()));
+
+ statusINVLabel = new QLabel( this, "INV" );
+ Q_CHECK_PTR( statusINVLabel );
+ statusINVLabel->setFrameStyle( QFrame::Panel | QFrame::Sunken );
+ statusINVLabel->setAlignment( AlignCenter );
+ statusINVLabel->setText("NORM");
+
+ statusHYPLabel = new QLabel( this, "HYP" );
+ Q_CHECK_PTR( statusHYPLabel );
+ statusHYPLabel->setFrameStyle( QFrame::Panel | QFrame::Sunken );
+ statusHYPLabel->setAlignment( AlignCenter );
+
+ statusERRORLabel = new QLabel( this, "ERROR" );
+ Q_CHECK_PTR( statusERRORLabel );
+ statusERRORLabel->setFrameStyle( QFrame::Panel | QFrame::Sunken );
+ statusERRORLabel->setAlignment( AlignLeft|AlignVCenter );
+
+ // create angle button group
+
+ QAccel *accel = new QAccel( this );
+
+ QButtonGroup *angle_group = new QButtonGroup( 3, Horizontal,this, "AngleButtons" );
+ angle_group->setTitle(i18n( "Angle") );
+
+ anglebutton[0] = new QRadioButton( angle_group );
+ anglebutton[0]->setText( "&Deg" ) ;
+ anglebutton[0]->setChecked( TRUE);
+ accel->connectItem( accel->insertItem(Key_D + ALT), this ,
+ SLOT(Deg_Selected()) );
+
+ anglebutton[1] = new QRadioButton( angle_group );
+ anglebutton[1]->setText( "&Rad" );
+ accel->connectItem( accel->insertItem(Key_R + ALT), this ,
+ SLOT(Rad_Selected()) );
+
+ anglebutton[2] = new QRadioButton( angle_group );
+ anglebutton[2]->setText( "&Gra" );
+ accel->connectItem( accel->insertItem(Key_G + ALT), this ,
+ SLOT(Gra_Selected()) );
+
+ connect( angle_group, SIGNAL(clicked(int)), SLOT(angle_selected(int)) );
+
+
+//////////////////////////////////////////////////////////////////////
+//
+// Create Number Base Button Group
+//
+
+
+
+ QButtonGroup *base_group = new QButtonGroup( 4, Horizontal,this, "BaseButtons" );
+ base_group->setTitle( i18n("Base") );
+
+ basebutton[0] = new QRadioButton( base_group );
+ basebutton[0]->setText( "&Hex" );
+ accel->connectItem( accel->insertItem(Key_H + ALT), this ,
+ SLOT(Hex_Selected()) );
+
+ basebutton[1] = new QRadioButton( base_group );
+ basebutton[1]->setText( "D&ec" );
+ basebutton[1]->setChecked(TRUE);
+ accel->connectItem( accel->insertItem(Key_E + ALT), this ,
+ SLOT(Dec_Selected()) );
+
+ basebutton[2] = new QRadioButton( base_group );
+ basebutton[2]->setText( "&Oct" );
+ accel->connectItem( accel->insertItem(Key_O + ALT), this ,
+ SLOT(Oct_Selected()) );
+
+ basebutton[3] = new QRadioButton( base_group);
+ basebutton[3]->setText( "&Bin" );
+ accel->connectItem( accel->insertItem(Key_B + ALT), this ,
+ SLOT(Bin_Selected()) );
+
+ connect( base_group, SIGNAL(clicked(int)), SLOT(base_selected(int)) );
+
+////////////////////////////////////////////////////////////////////////
+//
+// Create Calculator Buttons
+//
+
+
+ // First the widgets that are the parents of the buttons
+ mSmallPage = new QWidget(this);
+ mLargePage = new QWidget(this);
+
+ pbhyp = new QPushButton("Hyp", mSmallPage, "hypbutton" );
+ connect( pbhyp, SIGNAL(toggled(bool)), SLOT(pbhyptoggled(bool)));
+ pbhyp->setToggleButton(TRUE);
+
+ pbinv = new QPushButton( "Inv", mSmallPage, "InverseButton" );
+ connect( pbinv, SIGNAL(toggled(bool)), SLOT(pbinvtoggled(bool)));
+ pbinv->setToggleButton(TRUE);
+
+ pbA = new QPushButton("A",mSmallPage, "Abutton" );
+ connect( pbA, SIGNAL(toggled(bool)), SLOT(pbAtoggled(bool)));
+ pbA->setToggleButton(TRUE);
+
+ pbSin = new QPushButton("Sin",mSmallPage, "Sinbutton" );
+ connect( pbSin, SIGNAL(toggled(bool)), SLOT(pbSintoggled(bool)));
+ pbSin->setToggleButton(TRUE);
+
+ pbplusminus = new QPushButton( "+/-", mSmallPage, "plusminusbutton" );
+ connect( pbplusminus, SIGNAL(toggled(bool)), SLOT(pbplusminustoggled(bool)));
+ pbplusminus->setToggleButton(TRUE);
+ pbplusminus->setFont(buttonfont);
+
+ pbB = new QPushButton("B", mSmallPage, "Bbutton" );
+ connect( pbB, SIGNAL(toggled(bool)), SLOT(pbBtoggled(bool)));
+ pbB->setToggleButton(TRUE);
+
+ pbCos = new QPushButton("Cos",mSmallPage, "Cosbutton" );
+ pbCos->setText( "Cos" );
+ connect( pbCos, SIGNAL(toggled(bool)), SLOT(pbCostoggled(bool)));
+ pbCos->setToggleButton(TRUE);
+
+
+ pbreci = new QPushButton("1/x",mSmallPage, "recibutton" );
+ connect( pbreci, SIGNAL(toggled(bool)), SLOT(pbrecitoggled(bool)));
+ pbreci->setToggleButton(TRUE);
+
+ pbC = new QPushButton( "C", mSmallPage, "Cbutton" );
+ connect( pbC, SIGNAL(toggled(bool)), SLOT(pbCtoggled(bool)));
+ pbC->setToggleButton(TRUE);
+
+ pbTan = new QPushButton("Tan" ,mSmallPage, "Tanbutton" );
+ connect( pbTan, SIGNAL(toggled(bool)), SLOT(pbTantoggled(bool)));
+ pbTan->setToggleButton(TRUE);
+
+ pbfactorial = new QPushButton("x!",mSmallPage, "factorialbutton" );
+ connect( pbfactorial, SIGNAL(toggled(bool)), SLOT(pbfactorialtoggled(bool)));
+ pbfactorial->setToggleButton(TRUE);
+
+ pbD = new QPushButton("D",mSmallPage, "Dbutton" );
+ connect( pbD, SIGNAL(toggled(bool)), SLOT(pbDtoggled(bool)));
+ pbD->setToggleButton(TRUE);
+
+ pblog = new QPushButton("Log",mSmallPage, "logbutton" );
+ connect( pblog, SIGNAL(toggled(bool)), SLOT(pblogtoggled(bool)));
+ pblog->setToggleButton(TRUE);
+
+ pbsquare = new QPushButton( "x^2", mSmallPage, "squarebutton" );
+ connect( pbsquare, SIGNAL(toggled(bool)), SLOT(pbsquaretoggled(bool)));
+ pbsquare->setToggleButton(TRUE);
+
+ pbE = new QPushButton("E",mSmallPage, "Ebutton" );
+ connect( pbE, SIGNAL(toggled(bool)), SLOT(pbEtoggled(bool)));
+ pbE->setToggleButton(TRUE);
+
+
+ pbln = new QPushButton( "Ln", mSmallPage, "lnbutton" );
+ connect( pbln, SIGNAL(toggled(bool)), SLOT(pblntoggled(bool)));
+ pbln->setToggleButton(TRUE);
+
+ pbpower = new QPushButton("x^y",mSmallPage, "powerbutton" );
+ connect( pbpower, SIGNAL(toggled(bool)), SLOT(pbpowertoggled(bool)));
+ pbpower->setToggleButton(TRUE);
+
+ pbF = new QPushButton("F",mSmallPage, "Fbutton" );
+ connect( pbF, SIGNAL(toggled(bool)), SLOT(pbFtoggled(bool)));
+ pbF->setToggleButton(TRUE);
+
+ pbEE = new QPushButton("EE",mLargePage, "EEbutton" );
+ pbEE->setToggleButton(TRUE);
+ connect( pbEE, SIGNAL(toggled(bool)), SLOT(EEtoggled(bool)));
+
+ pbMR = new QPushButton("MR",mLargePage, "MRbutton" );
+ connect( pbMR, SIGNAL(toggled(bool)), SLOT(pbMRtoggled(bool)));
+ pbMR->setToggleButton(TRUE);
+ pbMR->setFont(buttonfont);
+
+ pbMplusminus = new QPushButton("M+-",mLargePage, "Mplusminusbutton" );
+ connect( pbMplusminus, SIGNAL(toggled(bool)), SLOT(pbMplusminustoggled(bool)));
+ pbMplusminus->setToggleButton(TRUE);
+
+ pbMC = new QPushButton("MC",mLargePage, "MCbutton" );
+ connect( pbMC, SIGNAL(toggled(bool)), SLOT(pbMCtoggled(bool)));
+ pbMC->setToggleButton(TRUE);
+
+ pbClear = new QPushButton("C",mLargePage, "Clearbutton" );
+ connect( pbClear, SIGNAL(toggled(bool)), SLOT(pbCleartoggled(bool)));
+ pbClear->setToggleButton(TRUE);
+
+ pbAC = new QPushButton("AC", mLargePage, "ACbutton" );
+ connect( pbAC, SIGNAL(toggled(bool)), SLOT(pbACtoggled(bool)));
+ pbAC->setToggleButton(TRUE);
+
+ pb7 = new QPushButton("7",mLargePage, "7button" );
+ connect( pb7, SIGNAL(toggled(bool)), SLOT(pb7toggled(bool)));
+ pb7->setToggleButton(TRUE);
+
+ pb8 = new QPushButton("8",mLargePage, "8button" );
+ connect( pb8, SIGNAL(toggled(bool)), SLOT(pb8toggled(bool)));
+ pb8->setToggleButton(TRUE);
+
+ pb9 = new QPushButton("9",mLargePage,"9button" );
+ connect( pb9, SIGNAL(toggled(bool)), SLOT(pb9toggled(bool)));
+ pb9->setToggleButton(TRUE);
+
+ pbparenopen = new QPushButton("(",mLargePage, "parenopenbutton" );
+ connect( pbparenopen, SIGNAL(toggled(bool)), SLOT(pbparenopentoggled(bool)));
+ pbparenopen->setToggleButton(TRUE);
+
+ pbparenclose = new QPushButton(")",mLargePage, "parenclosebutton" );
+ connect( pbparenclose, SIGNAL(toggled(bool)), SLOT(pbparenclosetoggled(bool)));
+ pbparenclose->setToggleButton(TRUE);
+
+ pband = new QPushButton("And",mLargePage, "andbutton" );
+ connect( pband, SIGNAL(toggled(bool)), SLOT(pbandtoggled(bool)));
+ pband->setToggleButton(TRUE);
+ pband->setFont(buttonfont);
+
+ pb4 = new QPushButton("4",mLargePage, "4button" );
+ connect( pb4, SIGNAL(toggled(bool)), SLOT(pb4toggled(bool)));
+ pb4->setToggleButton(TRUE);
+
+ pb5 = new QPushButton("5",mLargePage, "5button" );
+ connect( pb5, SIGNAL(toggled(bool)), SLOT(pb5toggled(bool)));
+ pb5->setToggleButton(TRUE);
+
+ pb6 = new QPushButton("6",mLargePage, "6button" );
+ connect( pb6, SIGNAL(toggled(bool)), SLOT(pb6toggled(bool)));
+ pb6->setToggleButton(TRUE);
+
+ pbX = new QPushButton("X",mLargePage, "Multiplybutton" );
+ connect( pbX, SIGNAL(toggled(bool)), SLOT(pbXtoggled(bool)));
+ pbX->setToggleButton(TRUE);
+
+ pbdivision = new QPushButton("/",mLargePage, "divisionbutton" );
+ connect( pbdivision, SIGNAL(toggled(bool)), SLOT(pbdivisiontoggled(bool)));
+ pbdivision->setToggleButton(TRUE);
+
+ pbor = new QPushButton("Or",mLargePage, "orbutton" );
+ connect( pbor, SIGNAL(toggled(bool)), SLOT(pbortoggled(bool)));
+ pbor->setToggleButton(TRUE);
+
+ pb1 = new QPushButton("1",mLargePage, "1button" );
+ connect( pb1, SIGNAL(toggled(bool)), SLOT(pb1toggled(bool)));
+ pb1->setToggleButton(TRUE);
+
+ pb2 = new QPushButton("2",mLargePage, "2button" );
+
+ connect( pb2, SIGNAL(toggled(bool)), SLOT(pb2toggled(bool)));
+ pb2->setToggleButton(TRUE);
+
+ pb3 = new QPushButton("3",mLargePage, "3button" );
+ connect( pb3, SIGNAL(toggled(bool)), SLOT(pb3toggled(bool)));
+ pb3->setToggleButton(TRUE);
+
+ pbplus = new QPushButton("+",mLargePage, "plusbutton" );
+ connect( pbplus, SIGNAL(toggled(bool)), SLOT(pbplustoggled(bool)));
+ pbplus->setToggleButton(TRUE);
+
+
+ pbminus = new QPushButton("-",mLargePage, "minusbutton" );
+ connect( pbminus, SIGNAL(toggled(bool)), SLOT(pbminustoggled(bool)));
+ pbminus->setToggleButton(TRUE);
+
+ pbshift = new QPushButton("Lsh",mLargePage, "shiftbutton" );
+ connect( pbshift, SIGNAL(toggled(bool)), SLOT(pbshifttoggled(bool)));
+ pbshift->setToggleButton(TRUE);
+
+ pbperiod = new QPushButton(".",mLargePage, "periodbutton" );
+ connect( pbperiod, SIGNAL(toggled(bool)), SLOT(pbperiodtoggled(bool)));
+ pbperiod->setToggleButton(TRUE);
+
+ pb0 = new QPushButton("0",mLargePage, "0button" );
+ connect( pb0, SIGNAL(toggled(bool)), SLOT(pb0toggled(bool)));
+ pb0->setToggleButton(TRUE);
+
+ pbequal = new QPushButton("=",mLargePage, "equalbutton" );
+ connect( pbequal, SIGNAL(toggled(bool)), SLOT(pbequaltoggled(bool)));
+ pbequal->setToggleButton(TRUE);
+
+ pbpercent = new QPushButton("%",mLargePage, "percentbutton" );
+ connect( pbpercent, SIGNAL(toggled(bool)), SLOT(pbpercenttoggled(bool)));
+ pbpercent->setToggleButton(TRUE);
+
+ pbnegate = new QPushButton("Cmp",mLargePage, "OneComplementbutton" );
+ connect( pbnegate, SIGNAL(toggled(bool)), SLOT(pbnegatetoggled(bool)));
+ pbnegate->setToggleButton(TRUE);
+
+ pbmod = new QPushButton("Mod",mLargePage, "modbutton" );
+ connect( pbmod, SIGNAL(toggled(bool)), SLOT(pbmodtoggled(bool)));
+ pbmod->setToggleButton(TRUE);
+
+ QGridLayout *smallBtnLayout = new QGridLayout(mSmallPage, 6, 3, 0,
+ mInternalSpacing);
+ QGridLayout *largeBtnLayout = new QGridLayout(mLargePage, 5, 6, 0,
+ mInternalSpacing);
+
+ QHBoxLayout *topLayout = new QHBoxLayout();
+ QHBoxLayout *radioLayout = new QHBoxLayout();
+ QHBoxLayout *btnLayout = new QHBoxLayout();
+ QHBoxLayout *statusLayout = new QHBoxLayout();
+
+ // bring them all together
+ QVBoxLayout *mainLayout = new QVBoxLayout(this, mInternalSpacing,
+ mInternalSpacing );
+
+ mainLayout->addLayout(topLayout );
+ mainLayout->addLayout(radioLayout, 1);
+ mainLayout->addLayout(btnLayout);
+ mainLayout->addLayout(statusLayout);
+
+ // button layout
+ btnLayout->addWidget(mSmallPage,0,AlignTop);
+ btnLayout->addSpacing(mInternalSpacing);
+ btnLayout->addWidget(mLargePage,0,AlignTop);
+
+ // small button layout
+ smallBtnLayout->addWidget(pbhyp, 0, 0);
+ smallBtnLayout->addWidget(pbinv, 0, 1);
+ smallBtnLayout->addWidget(pbA, 0, 2);
+
+ smallBtnLayout->addWidget(pbSin, 1, 0);
+ smallBtnLayout->addWidget(pbplusminus, 1, 1);
+ smallBtnLayout->addWidget(pbB, 1, 2);
+
+ smallBtnLayout->addWidget(pbCos, 2, 0);
+ smallBtnLayout->addWidget(pbreci, 2, 1);
+ smallBtnLayout->addWidget(pbC, 2, 2);
+
+ smallBtnLayout->addWidget(pbTan, 3, 0);
+ smallBtnLayout->addWidget(pbfactorial, 3, 1);
+ smallBtnLayout->addWidget(pbD, 3, 2);
+
+ smallBtnLayout->addWidget(pblog, 4, 0);
+ smallBtnLayout->addWidget(pbsquare, 4, 1);
+ smallBtnLayout->addWidget(pbE, 4, 2);
+
+ smallBtnLayout->addWidget(pbln, 5, 0);
+ smallBtnLayout->addWidget(pbpower, 5, 1);
+ smallBtnLayout->addWidget(pbF, 5, 2);
+
+ smallBtnLayout->setRowStretch(0, 0);
+ smallBtnLayout->setRowStretch(1, 0);
+ smallBtnLayout->setRowStretch(2, 0);
+ smallBtnLayout->setRowStretch(3, 0);
+ smallBtnLayout->setRowStretch(4, 0);
+ smallBtnLayout->setRowStretch(5, 0);
+
+ // large button layout
+ largeBtnLayout->addWidget(pbEE, 0, 0);
+ largeBtnLayout->addWidget(pbMR, 0, 1);
+ largeBtnLayout->addWidget(pbMplusminus, 0, 2);
+ largeBtnLayout->addWidget(pbMC, 0, 3);
+ largeBtnLayout->addWidget(pbClear, 0, 4);
+ largeBtnLayout->addWidget(pbAC, 0, 5);
+
+ largeBtnLayout->addWidget(pb7, 1, 0);
+ largeBtnLayout->addWidget(pb8, 1, 1);
+ largeBtnLayout->addWidget(pb9, 1, 2);
+ largeBtnLayout->addWidget(pbparenopen, 1, 3);
+ largeBtnLayout->addWidget(pbparenclose, 1, 4);
+ largeBtnLayout->addWidget(pband, 1, 5);
+
+ largeBtnLayout->addWidget(pb4, 2, 0);
+ largeBtnLayout->addWidget(pb5, 2, 1);
+ largeBtnLayout->addWidget(pb6, 2, 2);
+ largeBtnLayout->addWidget(pbX, 2, 3);
+ largeBtnLayout->addWidget(pbdivision, 2, 4);
+ largeBtnLayout->addWidget(pbor, 2, 5);
+
+ largeBtnLayout->addWidget(pb1, 3, 0);
+ largeBtnLayout->addWidget(pb2, 3, 1);
+ largeBtnLayout->addWidget(pb3, 3, 2);
+ largeBtnLayout->addWidget(pbplus, 3, 3);
+ largeBtnLayout->addWidget(pbminus, 3, 4);
+ largeBtnLayout->addWidget(pbshift, 3, 5);
+
+ largeBtnLayout->addWidget(pbperiod, 4, 0);
+ largeBtnLayout->addWidget(pb0, 4, 1);
+ largeBtnLayout->addWidget(pbequal, 4, 2);
+ largeBtnLayout->addWidget(pbpercent, 4, 3);
+ largeBtnLayout->addWidget(pbnegate, 4, 4);
+ largeBtnLayout->addWidget(pbmod, 4, 5);
+
+ largeBtnLayout->addColSpacing(0,10);
+ largeBtnLayout->addColSpacing(1,10);
+ largeBtnLayout->addColSpacing(2,10);
+ largeBtnLayout->addColSpacing(3,10);
+ largeBtnLayout->addColSpacing(4,10);
+ topLayout->addWidget(pb);
+ topLayout->addWidget(calc_display, 10);
+
+
+ // radiobutton layout
+ radioLayout->addWidget(base_group);
+ radioLayout->addWidget(angle_group);
+
+ // status layout
+ statusLayout->addWidget(statusINVLabel);
+ statusLayout->addWidget(statusHYPLabel);
+ statusLayout->addWidget(statusERRORLabel, 10);
+
+ mNumButtonList.append(pb0);
+ mNumButtonList.append(pb1);
+ mNumButtonList.append(pb2);
+ mNumButtonList.append(pb3);
+ mNumButtonList.append(pb4);
+ mNumButtonList.append(pb5);
+ mNumButtonList.append(pb6);
+ mNumButtonList.append(pb7);
+ mNumButtonList.append(pb8);
+ mNumButtonList.append(pb9);
+
+ mFunctionButtonList.append(pbhyp);
+ mFunctionButtonList.append(pbinv);
+ mFunctionButtonList.append(pbSin);
+ mFunctionButtonList.append(pbplusminus);
+ mFunctionButtonList.append(pbCos);
+ mFunctionButtonList.append(pbreci);
+ mFunctionButtonList.append(pbTan);
+ mFunctionButtonList.append(pbfactorial);
+ mFunctionButtonList.append(pblog);
+ mFunctionButtonList.append(pbsquare);
+ mFunctionButtonList.append(pbln);
+ mFunctionButtonList.append(pbpower);
+
+ mHexButtonList.append(pbA);
+ mHexButtonList.append(pbB);
+ mHexButtonList.append(pbC);
+ mHexButtonList.append(pbD);
+ mHexButtonList.append(pbE);
+ mHexButtonList.append(pbF);
+
+ mMemButtonList.append(pbEE);
+ mMemButtonList.append(pbMR);
+ mMemButtonList.append(pbMplusminus);
+ mMemButtonList.append(pbMC);
+ mMemButtonList.append(pbClear);
+ mMemButtonList.append(pbAC);
+
+ mOperationButtonList.append(pbX);
+ mOperationButtonList.append(pbparenopen);
+ mOperationButtonList.append(pbparenclose);
+ mOperationButtonList.append(pband);
+ mOperationButtonList.append(pbdivision);
+ mOperationButtonList.append(pbor);
+ mOperationButtonList.append(pbplus);
+ mOperationButtonList.append(pbminus);
+ mOperationButtonList.append(pbshift);
+ mOperationButtonList.append(pbperiod);
+ mOperationButtonList.append(pbequal);
+ mOperationButtonList.append(pbpercent);
+ mOperationButtonList.append(pbnegate);
+ mOperationButtonList.append(pbmod);
+
+ set_colors();
+ set_precision();
+ set_style();
+ updateGeometry();
+ setFixedHeight(minimumHeight());
+ InitializeCalculator();
+}
+
+QtCalculator::~QtCalculator()
+{
+ delete selection_timer;
+ delete status_timer;
+
+}
+
+void QtCalculator::set_display_font()
+{
+ calc_display->setFont(kcalcdefaults.font);
+}
+
+void QtCalculator::updateGeometry()
+{
+ QObjectList *l;
+ QSize s;
+ int margin;
+
+ //
+ // Uppermost bar
+ //
+ calc_display->setMinimumWidth(calc_display->fontMetrics().maxWidth() * 15);
+
+ //
+ // Button groups (base and angle)
+ //
+ //QButtonGroup *g;
+ //g = (QButtonGroup*)(anglebutton[0]->parentWidget());
+ //g = (QButtonGroup*)(basebutton[0]->parentWidget());
+
+ //
+ // Calculator buttons
+ //
+ s.setWidth(mSmallPage->fontMetrics().width("MMM"));
+ s.setHeight(mSmallPage->fontMetrics().lineSpacing());
+
+ l = (QObjectList*)mSmallPage->children(); // silence please
+
+ for(uint i=0; i < l->count(); i++)
+ {
+ QObject *o = l->at(i);
+ if( o->isWidgetType() )
+ {
+ margin = QApplication::style().
+ pixelMetric(QStyle::PM_ButtonMargin, ((QWidget *)o))*2;
+ ((QWidget*)o)->setMinimumSize(s.width()+margin, s.height()+margin);
+ ((QWidget*)o)->installEventFilter( this );
+ ((QWidget*)o)->setAcceptDrops(true);
+ }
+ }
+
+ l = (QObjectList*)mLargePage->children(); // silence please
+
+ int h1 = pbF->minimumSize().height();
+ int h2 = (int)((((float)h1 + 4.0) / 5.0));
+ s.setWidth(mLargePage->fontMetrics().width("MMM") +
+ QApplication::style().
+ pixelMetric(QStyle::PM_ButtonMargin, pbF)*2);
+ s.setHeight(h1 + h2);
+
+ for(uint i = 0; i < l->count(); i++)
+ {
+ QObject *o = l->at(i);
+ if(o->isWidgetType())
+ {
+ ((QWidget*)o)->setFixedSize(s);
+ ((QWidget*)o)->installEventFilter(this);
+ ((QWidget*)o)->setAcceptDrops(true);
+ }
+ }
+
+ //
+ // The status bar
+ //
+ s.setWidth( statusINVLabel->fontMetrics().width("NORM") +
+ statusINVLabel->frameWidth() * 2 + 10);
+ statusINVLabel->setMinimumWidth(s.width());
+ statusHYPLabel->setMinimumWidth(s.width());
+
+ //setFixedSize(minimumSize());
+}
+
+void QtCalculator::exit()
+{
+ // QApplication::exit();
+}
+
+void QtCalculator::Hex_Selected()
+{
+ basebutton[0]->setChecked(TRUE);
+ basebutton[1]->setChecked(FALSE);
+ basebutton[2]->setChecked(FALSE);
+ basebutton[3]->setChecked(FALSE);
+ SetHex();
+}
+
+
+void QtCalculator::Dec_Selected()
+{
+ basebutton[0]->setChecked(FALSE);
+ basebutton[1]->setChecked(TRUE);
+ basebutton[2]->setChecked(FALSE);
+ basebutton[3]->setChecked(FALSE);
+ SetDec();
+}
+
+
+void QtCalculator::Oct_Selected()
+{
+ basebutton[0]->setChecked(FALSE);
+ basebutton[1]->setChecked(FALSE);
+ basebutton[2]->setChecked(TRUE);
+ basebutton[3]->setChecked(FALSE);
+ SetOct();
+}
+
+
+
+void QtCalculator::Bin_Selected()
+{
+ basebutton[0]->setChecked(FALSE);
+ basebutton[1]->setChecked(FALSE);
+ basebutton[2]->setChecked(FALSE);
+ basebutton[3]->setChecked(TRUE);
+ SetBin();
+}
+
+void QtCalculator::Deg_Selected()
+{
+ anglebutton[0]->setChecked(TRUE);
+ anglebutton[1]->setChecked(FALSE);
+ anglebutton[2]->setChecked(FALSE);
+ SetDeg();
+}
+
+
+void QtCalculator::Rad_Selected()
+{
+ anglebutton[0]->setChecked(FALSE);
+ anglebutton[1]->setChecked(TRUE);
+ anglebutton[2]->setChecked(FALSE);
+ SetRad();
+
+}
+
+
+void QtCalculator::Gra_Selected()
+{
+ anglebutton[0]->setChecked(FALSE);
+ anglebutton[1]->setChecked(FALSE);
+ anglebutton[2]->setChecked(TRUE);
+ SetGra();
+}
+
+
+void QtCalculator::helpclicked(){
+}
+
+void QtCalculator::keyPressEvent( QKeyEvent *e ){
+
+ switch (e->key() ){
+
+ case Key_F1:
+ helpclicked();
+ break;
+ case Key_F2:
+ configclicked();
+ break;
+ case Key_F3:
+ if(kcalcdefaults.style == 0)
+ kcalcdefaults.style = 1;
+ else if(kcalcdefaults.style == 1)
+ kcalcdefaults.style = 2;
+ else
+ kcalcdefaults.style = 0;
+ set_style();
+ break;
+ case Key_Up:
+ temp_stack_prev();
+ break;
+ case Key_Down:
+ temp_stack_next();
+ break;
+
+ case Key_Next:
+ key_pressed = TRUE;
+ pbAC->setOn(TRUE);
+ break;
+ case Key_Prior:
+ key_pressed = TRUE;
+ pbClear->setOn(TRUE);
+ break;
+
+ case Key_H:
+ key_pressed = TRUE;
+ pbhyp->setOn(TRUE);
+ break;
+ case Key_I:
+ key_pressed = TRUE;
+ pbinv->setOn(TRUE);
+ break;
+ case Key_A:
+ key_pressed = TRUE;
+ pbA->setOn(TRUE);
+
+ break;
+ case Key_E:
+ key_pressed = TRUE;
+ if (current_base == NB_HEX)
+ pbE->setOn(TRUE);
+ else
+ pbEE->setOn(TRUE);
+ break;
+ case Key_Escape:
+ key_pressed = TRUE;
+ pbClear->setOn(TRUE);
+ break;
+ case Key_Delete:
+ key_pressed = TRUE;
+ pbAC->setOn(TRUE);
+ break;
+ case Key_S:
+ key_pressed = TRUE;
+ pbSin->setOn(TRUE);
+ break;
+ case Key_Backslash:
+ key_pressed = TRUE;
+ pbplusminus->setOn(TRUE);
+ break;
+ case Key_B:
+ key_pressed = TRUE;
+ pbB->setOn(TRUE);
+ break;
+ case Key_7:
+ key_pressed = TRUE;
+ pb7->setOn(TRUE);
+ break;
+ case Key_8:
+ key_pressed = TRUE;
+ pb8->setOn(TRUE);
+ break;
+ case Key_9:
+ key_pressed = TRUE;
+ pb9->setOn(TRUE);
+ break;
+ case Key_ParenLeft:
+ key_pressed = TRUE;
+ pbparenopen->setOn(TRUE);
+ break;
+ case Key_ParenRight:
+ key_pressed = TRUE;
+ pbparenclose->setOn(TRUE);
+ break;
+ case Key_Ampersand:
+ key_pressed = TRUE;
+ pband->setOn(TRUE);
+ break;
+ case Key_C:
+ key_pressed = TRUE;
+ if (current_base == NB_HEX)
+ pbC->setOn(TRUE);
+ else
+ pbCos->setOn(TRUE);
+ break;
+ case Key_4:
+ key_pressed = TRUE;
+ pb4->setOn(TRUE);
+ break;
+ case Key_5:
+ key_pressed = TRUE;
+ pb5->setOn(TRUE);
+ break;
+ case Key_6:
+ key_pressed = TRUE;
+ pb6->setOn(TRUE);
+ break;
+ case Key_Asterisk:
+ key_pressed = TRUE;
+ pbX->setOn(TRUE);
+ break;
+ case Key_Slash:
+ key_pressed = TRUE;
+ pbdivision->setOn(TRUE);
+ break;
+ case Key_O:
+ key_pressed = TRUE;
+ pbor->setOn(TRUE);
+ break;
+ case Key_T:
+ key_pressed = TRUE;
+ pbTan->setOn(TRUE);
+ break;
+ case Key_Exclam:
+ key_pressed = TRUE;
+ pbfactorial->setOn(TRUE);
+ break;
+ case Key_D:
+ key_pressed = TRUE;
+ if(kcalcdefaults.style == 0)
+ pbD->setOn(TRUE); // trig mode
+ else
+ pblog->setOn(TRUE); // stat mode
+ break;
+ case Key_1:
+ key_pressed = TRUE;
+ pb1->setOn(TRUE);
+ break;
+ case Key_2:
+ key_pressed = TRUE;
+ pb2->setOn(TRUE);
+ break;
+ case Key_3:
+ key_pressed = TRUE;
+ pb3->setOn(TRUE);
+ break;
+ case Key_Plus:
+ key_pressed = TRUE;
+ pbplus->setOn(TRUE);
+ break;
+ case Key_Minus:
+ key_pressed = TRUE;
+ pbminus->setOn(TRUE);
+ break;
+ case Key_Less:
+ key_pressed = TRUE;
+ pbshift->setOn(TRUE);
+ break;
+ case Key_N:
+ key_pressed = TRUE;
+ pbln->setOn(TRUE);
+ break;
+ case Key_L:
+ key_pressed = TRUE;
+ pblog->setOn(TRUE);
+ break;
+ case Key_AsciiCircum:
+ key_pressed = TRUE;
+ pbpower->setOn(TRUE);
+ break;
+ case Key_F:
+ key_pressed = TRUE;
+ pbF->setOn(TRUE);
+ break;
+ case Key_Period:
+ key_pressed = TRUE;
+ pbperiod->setOn(TRUE);
+ break;
+ case Key_Comma:
+ key_pressed = TRUE;
+ pbperiod->setOn(TRUE);
+ break;
+ case Key_0:
+ key_pressed = TRUE;
+ pb0->setOn(TRUE);
+ break;
+ case Key_Equal:
+ key_pressed = TRUE;
+ pbequal->setOn(TRUE);
+ break;
+ case Key_Return:
+ key_pressed = TRUE;
+ pbequal->setOn(TRUE);
+ break;
+ case Key_Enter:
+ key_pressed = TRUE;
+ pbequal->setOn(TRUE);
+ break;
+ case Key_Percent:
+ key_pressed = TRUE;
+ pbpercent->setOn(TRUE);
+ break;
+ case Key_AsciiTilde:
+ key_pressed = TRUE;
+ pbnegate->setOn(TRUE);
+ break;
+ case Key_Colon:
+ key_pressed = TRUE;
+ pbmod->setOn(TRUE);
+ break;
+ case Key_BracketLeft:
+ key_pressed = TRUE;
+ pbsquare->setOn(TRUE);
+ break;
+ case Key_Backspace:
+ key_pressed = TRUE;
+ pbAC->setOn(TRUE);
+ break;
+ case Key_R:
+ key_pressed = TRUE;
+ pbreci->setOn(TRUE);
+ break;
+ }
+}
+
+void QtCalculator::keyReleaseEvent( QKeyEvent *e ){
+ switch (e->key() ){
+
+ case Key_Next:
+ key_pressed = FALSE;
+ pbAC->setOn(FALSE);
+ break;
+ case Key_Prior:
+ key_pressed = FALSE;
+ pbClear->setOn(FALSE);
+ break;
+
+ case Key_H:
+ key_pressed = FALSE;
+ pbhyp->setOn(FALSE);
+ break;
+ case Key_I:
+ key_pressed = FALSE;
+ pbinv->setOn(FALSE);
+ break;
+ case Key_A:
+ key_pressed = FALSE;
+ pbA->setOn(FALSE);
+ break;
+ case Key_E:
+ key_pressed = FALSE;
+ if (current_base == NB_HEX)
+ pbE->setOn(FALSE);
+ else
+ pbEE->setOn(FALSE);
+ break;
+ case Key_Escape:
+ key_pressed = FALSE;
+ pbClear->setOn(FALSE);
+ break;
+ case Key_Delete:
+ key_pressed = FALSE;
+ pbAC->setOn(FALSE);
+ break;
+ case Key_S:
+ key_pressed = FALSE;
+ pbSin->setOn(FALSE);
+ break;
+ case Key_Backslash:
+ key_pressed = FALSE;
+ pbplusminus->setOn(FALSE);
+ break;
+ case Key_B:
+ key_pressed = FALSE;
+ pbB->setOn(FALSE);
+ break;
+ case Key_7:
+ key_pressed = FALSE;
+ pb7->setOn(FALSE);
+ break;
+ case Key_8:
+ key_pressed = FALSE;
+ pb8->setOn(FALSE);
+ break;
+ case Key_9:
+ key_pressed = FALSE;
+ pb9->setOn(FALSE);
+ break;
+ case Key_ParenLeft:
+ key_pressed = FALSE;
+ pbparenopen->setOn(FALSE);
+ break;
+ case Key_ParenRight:
+ key_pressed = FALSE;
+ pbparenclose->setOn(FALSE);
+ break;
+ case Key_Ampersand:
+ key_pressed = FALSE;
+ pband->setOn(FALSE);
+ break;
+ case Key_C:
+ key_pressed = FALSE;
+ if (current_base == NB_HEX)
+ pbC->setOn(FALSE);
+ else
+ pbCos->setOn(FALSE);
+ break;
+ case Key_4:
+ key_pressed = FALSE;
+ pb4->setOn(FALSE);
+ break;
+ case Key_5:
+ key_pressed = FALSE;
+ pb5->setOn(FALSE);
+ break;
+ case Key_6:
+ key_pressed = FALSE;
+ pb6->setOn(FALSE);
+ break;
+ case Key_Asterisk:
+ key_pressed = FALSE;
+ pbX->setOn(FALSE);
+ break;
+ case Key_Slash:
+ key_pressed = FALSE;
+ pbdivision->setOn(FALSE);
+ break;
+ case Key_O:
+ key_pressed = FALSE;
+ pbor->setOn(FALSE);
+ break;
+ case Key_T:
+ key_pressed = FALSE;
+ pbTan->setOn(FALSE);
+ break;
+ case Key_Exclam:
+ key_pressed = FALSE;
+ pbfactorial->setOn(FALSE);
+ break;
+ case Key_D:
+ key_pressed = FALSE;
+ if(kcalcdefaults.style == 0)
+ pbD->setOn(FALSE); // trig mode
+ else
+ pblog->setOn(FALSE);// stat mode
+ break;
+ case Key_1:
+ key_pressed = FALSE;
+ pb1->setOn(FALSE);
+ break;
+ case Key_2:
+ key_pressed = FALSE;
+ pb2->setOn(FALSE);
+ break;
+ case Key_3:
+ key_pressed = FALSE;
+ pb3->setOn(FALSE);
+ break;
+ case Key_Plus:
+ key_pressed = FALSE;
+ pbplus->setOn(FALSE);
+ break;
+ case Key_Minus:
+ key_pressed = FALSE;
+ pbminus->setOn(FALSE);
+ break;
+ case Key_Less:
+ key_pressed = FALSE;
+ pbshift->setOn(FALSE);
+ break;
+ case Key_N:
+ key_pressed = FALSE;
+ pbln->setOn(FALSE);
+ break;
+ case Key_L:
+ key_pressed = FALSE;
+ pblog->setOn(FALSE);
+ break;
+ case Key_AsciiCircum:
+ key_pressed = FALSE;
+ pbpower->setOn(FALSE);
+ break;
+ case Key_F:
+ key_pressed = FALSE;
+ pbF->setOn(FALSE);
+ break;
+ case Key_Period:
+ key_pressed = FALSE;
+ pbperiod->setOn(FALSE);
+ break;
+ case Key_Comma:
+ key_pressed = FALSE;
+ pbperiod->setOn(FALSE);
+ break;
+ case Key_0:
+ key_pressed = FALSE;
+ pb0->setOn(FALSE);
+ break;
+ case Key_Equal:
+ key_pressed = FALSE;
+ pbequal->setOn(FALSE);
+ break;
+ case Key_Return:
+ key_pressed = FALSE;
+ pbequal->setOn(FALSE);
+ break;
+ case Key_Enter:
+ key_pressed = FALSE;
+ pbequal->setOn(FALSE);
+ break;
+ case Key_Percent:
+ key_pressed = FALSE;
+ pbpercent->setOn(FALSE);
+ break;
+ case Key_AsciiTilde:
+ key_pressed = FALSE;
+ pbnegate->setOn(FALSE);
+ break;
+ case Key_Colon:
+ key_pressed = FALSE;
+ pbmod->setOn(FALSE);
+ break;
+ case Key_BracketLeft:
+ key_pressed = FALSE;
+ pbsquare->setOn(FALSE);
+ break;
+ case Key_Backspace:
+ key_pressed = FALSE;
+ pbAC->setOn(FALSE);
+ break;
+ case Key_R:
+ key_pressed = FALSE;
+ pbreci->setOn(FALSE);
+ break;
+ }
+
+ clear_buttons();
+}
+
+void QtCalculator::clear_buttons(){
+
+}
+
+void QtCalculator::EEtoggled(bool myboolean){
+
+ if(myboolean)
+ EE();
+ if(pbEE->isOn() && (!key_pressed))
+ pbEE->setOn(FALSE);
+}
+
+void QtCalculator::pbinvtoggled(bool myboolean){
+ if(myboolean)
+ SetInverse();
+ if(pbinv->isOn() && (!key_pressed))
+ pbinv->setOn(FALSE);
+}
+
+void QtCalculator::pbhyptoggled(bool myboolean){
+ if(myboolean)
+ EnterHyp();
+ if(pbhyp->isOn() && (!key_pressed))
+ pbhyp->setOn(FALSE);
+}
+void QtCalculator::pbMRtoggled(bool myboolean){
+ if(myboolean)
+ MR();
+ if(pbMR->isOn() && (!key_pressed))
+ pbMR->setOn(FALSE);
+}
+
+void QtCalculator::pbAtoggled(bool myboolean){
+ if(myboolean)
+ buttonA();
+ if(pbA->isOn() && (!key_pressed))
+ pbA->setOn(FALSE);
+}
+
+void QtCalculator::pbSintoggled(bool myboolean){
+ if(myboolean)
+ ExecSin();
+ if(pbSin->isOn() && (!key_pressed))
+ pbSin->setOn(FALSE);
+}
+void QtCalculator::pbplusminustoggled(bool myboolean){
+ if(myboolean)
+ EnterNegate();
+ if(pbplusminus->isOn() && (!key_pressed))
+ pbplusminus->setOn(FALSE);
+}
+void QtCalculator::pbMplusminustoggled(bool myboolean){
+ if(myboolean)
+ Mplusminus();
+ if(pbMplusminus->isOn() && (!key_pressed))
+ pbMplusminus->setOn(FALSE);
+}
+void QtCalculator::pbBtoggled(bool myboolean){
+ if(myboolean)
+ buttonB();
+ if(pbB->isOn() && (!key_pressed))
+ pbB->setOn(FALSE);
+}
+void QtCalculator::pbCostoggled(bool myboolean){
+ if(myboolean)
+ ExecCos();
+ if(pbCos->isOn() && (!key_pressed))
+ pbCos->setOn(FALSE);
+}
+void QtCalculator::pbrecitoggled(bool myboolean){
+ if(myboolean)
+ EnterRecip();
+ if(pbreci->isOn() && (!key_pressed))
+ pbreci->setOn(FALSE);
+}
+void QtCalculator::pbCtoggled(bool myboolean){
+ if(myboolean)
+ buttonC();
+ if(pbC->isOn() && (!key_pressed))
+ pbC->setOn(FALSE);
+}
+void QtCalculator::pbTantoggled(bool myboolean){
+ if(myboolean)
+ ExecTan();
+ if(pbTan->isOn() && (!key_pressed))
+ pbTan->setOn(FALSE);
+}
+void QtCalculator::pbfactorialtoggled(bool myboolean){
+ if(myboolean)
+ EnterFactorial();
+ if(pbfactorial->isOn() && (!key_pressed))
+ pbfactorial->setOn(FALSE);
+}
+void QtCalculator::pbDtoggled(bool myboolean){
+ if(myboolean)
+ buttonD();
+ if(pbD->isOn() && (!key_pressed))
+ pbD->setOn(FALSE);
+}
+void QtCalculator::pblogtoggled(bool myboolean){
+ if(myboolean)
+ EnterLogr();
+ if(pblog->isOn() && (!key_pressed))
+ pblog->setOn(FALSE);
+}
+void QtCalculator::pbsquaretoggled(bool myboolean){
+ if(myboolean)
+ EnterSquare();
+ if(pbsquare->isOn() && (!key_pressed))
+ pbsquare->setOn(FALSE);
+}
+void QtCalculator::pbEtoggled(bool myboolean){
+ if(myboolean)
+ buttonE();
+ if(pbE->isOn() && (!key_pressed))
+ pbE->setOn(FALSE);
+}
+void QtCalculator::pblntoggled(bool myboolean){
+ if(myboolean)
+ EnterLogn();
+ if(pbln->isOn() && (!key_pressed))
+ pbln->setOn(FALSE);
+}
+void QtCalculator::pbpowertoggled(bool myboolean){
+ if(myboolean)
+ Power();
+ if(pbpower->isOn() && (!key_pressed))
+ pbpower->setOn(FALSE);
+}
+void QtCalculator::pbFtoggled(bool myboolean){
+ if(myboolean)
+ buttonF();
+ if(pbF->isOn() && (!key_pressed))
+ pbF->setOn(FALSE);
+}
+void QtCalculator::pbMCtoggled(bool myboolean){
+ if(myboolean)
+ MC();
+ if(pbMC->isOn() && (!key_pressed))
+ pbMC->setOn(FALSE);
+}
+void QtCalculator::pbCleartoggled(bool myboolean){
+ if(myboolean)
+ Clear();
+ if(pbClear->isOn() && (!key_pressed))
+ pbClear->setOn(FALSE);
+}
+void QtCalculator::pbACtoggled(bool myboolean){
+ if(myboolean)
+ ClearAll();
+ if(pbAC->isOn() && (!key_pressed))
+ pbAC->setOn(FALSE);
+}
+void QtCalculator::pb7toggled(bool myboolean){
+ if(myboolean)
+ button7();
+ if(pb7->isOn() && (!key_pressed))
+ pb7->setOn(FALSE);
+}
+void QtCalculator::pb8toggled(bool myboolean){
+ if(myboolean)
+ button8();
+ if(pb8->isOn() && (!key_pressed))
+ pb8->setOn(FALSE);
+}
+void QtCalculator::pb9toggled(bool myboolean){
+ if(myboolean)
+ button9();
+ if(pb9->isOn() && (!key_pressed))
+ pb9->setOn(FALSE);
+}
+void QtCalculator::pbparenopentoggled(bool myboolean){
+ if(myboolean)
+ EnterOpenParen();
+ if(pbparenopen->isOn() && (!key_pressed))
+ pbparenopen->setOn(FALSE);
+}
+void QtCalculator::pbparenclosetoggled(bool myboolean){
+ if(myboolean)
+ EnterCloseParen();
+ if(pbparenclose->isOn() && (!key_pressed))
+ pbparenclose->setOn(FALSE);
+}
+void QtCalculator::pbandtoggled(bool myboolean){
+ if(myboolean)
+ And();
+ if(pband->isOn() && (!key_pressed))
+ pband->setOn(FALSE);
+}
+void QtCalculator::pb4toggled(bool myboolean){
+ if(myboolean)
+ button4();
+ if(pb4->isOn() && (!key_pressed))
+ pb4->setOn(FALSE);
+}
+void QtCalculator::pb5toggled(bool myboolean){
+ if(myboolean)
+ button5();
+ if(pb5->isOn() && (!key_pressed))
+ pb5->setOn(FALSE);
+}
+void QtCalculator::pb6toggled(bool myboolean){
+ if(myboolean)
+ button6();
+ if(pb6->isOn() && (!key_pressed))
+ pb6->setOn(FALSE);
+}
+void QtCalculator::pbXtoggled(bool myboolean){
+ if(myboolean)
+ Multiply();
+ if(pbX->isOn() && (!key_pressed))
+ pbX->setOn(FALSE);
+}
+void QtCalculator::pbdivisiontoggled(bool myboolean){
+ if(myboolean)
+ Divide();
+ if(pbdivision->isOn() && (!key_pressed))
+ pbdivision->setOn(FALSE);
+}
+void QtCalculator::pbortoggled(bool myboolean){
+ if(myboolean)
+ Or();
+ if(pbor->isOn() && (!key_pressed))
+ pbor->setOn(FALSE);
+}
+void QtCalculator::pb1toggled(bool myboolean){
+ if(myboolean)
+ button1();
+ if(pb1->isOn() && (!key_pressed))
+ pb1->setOn(FALSE);
+}
+void QtCalculator::pb2toggled(bool myboolean){
+ if(myboolean)
+ button2();
+ if(pb2->isOn() && (!key_pressed))
+ pb2->setOn(FALSE);
+}
+void QtCalculator::pb3toggled(bool myboolean){
+ if(myboolean)
+ button3();
+ if(pb3->isOn() && (!key_pressed))
+ pb3->setOn(FALSE);
+}
+void QtCalculator::pbplustoggled(bool myboolean){
+ if(myboolean)
+ Plus();
+ if(pbplus->isOn() && (!key_pressed))
+ pbplus->setOn(FALSE);
+}
+void QtCalculator::pbminustoggled(bool myboolean){
+ if(myboolean)
+ Minus();
+ if(pbminus->isOn() && (!key_pressed))
+ pbminus->setOn(FALSE);
+}
+void QtCalculator::pbshifttoggled(bool myboolean){
+ if(myboolean)
+ Shift();
+ if(pbshift->isOn() && (!key_pressed))
+ pbshift->setOn(FALSE);
+}
+void QtCalculator::pbperiodtoggled(bool myboolean){
+ if(myboolean)
+ EnterDecimal();
+ if(pbperiod->isOn() && (!key_pressed))
+ pbperiod->setOn(FALSE);
+}
+void QtCalculator::pb0toggled(bool myboolean){
+ if(myboolean)
+ button0();
+ if(pb0->isOn() && (!key_pressed))
+ pb0->setOn(FALSE);
+}
+void QtCalculator::pbequaltoggled(bool myboolean){
+ if(myboolean)
+ EnterEqual();
+ if(pbequal->isOn() && (!key_pressed))
+ pbequal->setOn(FALSE);
+}
+void QtCalculator::pbpercenttoggled(bool myboolean){
+ if(myboolean)
+ EnterPercent();
+ if(pbpercent->isOn() && (!key_pressed))
+ pbpercent->setOn(FALSE);
+}
+void QtCalculator::pbnegatetoggled(bool myboolean){
+ if(myboolean)
+ EnterNotCmp();
+ if(pbnegate->isOn() && (!key_pressed))
+ pbnegate->setOn(FALSE);
+}
+void QtCalculator::pbmodtoggled(bool myboolean) {
+ if(myboolean)
+ Mod();
+ if(pbmod->isOn() && (!key_pressed))
+ pbmod->setOn(FALSE);
+}
+
+void QtCalculator::configclicked(){
+
+
+ QTabDialog * tabdialog;
+ tabdialog = new QTabDialog(0,"tabdialog",TRUE);
+
+ tabdialog->setCaption( i18n("KCalc Configuration") );
+ tabdialog->resize( 360, 390 );
+ tabdialog->setCancelButton( i18n("&Cancel") );
+ tabdialog->setOKButton(i18n("&OK"));
+
+ QWidget *about = new QWidget(tabdialog,"about");
+ QVBoxLayout *lay1 = new QVBoxLayout( about );
+ lay1->setMargin( KDialog::marginHint() );
+ lay1->setSpacing( KDialog::spacingHint() );
+
+ QGroupBox *box = new QGroupBox(0,Qt::Vertical,about,"box");
+ box->layout()->setSpacing(KDialog::spacingHint());
+ box->layout()->setMargin(KDialog::marginHint());
+ QGridLayout *grid1 = new QGridLayout(box->layout(),2,2);
+ QLabel *label = new QLabel(box,"label");
+ QLabel *label2 = new QLabel(box,"label2");
+
+ box->setTitle(i18n("About"));
+ grid1->addWidget(label,0,1);
+ grid1->addMultiCellWidget(label2,2,2,0,1);
+
+ QString labelstring = "KCalc "KCALCVERSION"\n"\
+ "Bernd Johannes Wuebben\n"\
+ "wuebben@math.cornell.edu\n"\
+ "wuebben@kde.org\n"\
+ "Copyright (C) 1996-98\n"\
+ "\n\n";
+
+ QString labelstring2 =
+#ifdef HAVE_LONG_DOUBLE
+ i18n( "Base type: long double\n");
+#else
+ i18n( "Due to broken glibc's everywhere, "\
+ "I had to reduce KCalc's precision from 'long double' "\
+ "to 'double'. "\
+ "Owners of systems with a working libc "\
+ "should recompile KCalc with 'long double' precision "\
+ "enabled. See the README for details.");
+#endif
+
+ label->setAlignment(AlignLeft|WordBreak|ExpandTabs);
+ label->setText(labelstring);
+
+ label2->setAlignment(AlignLeft|WordBreak|ExpandTabs);
+ label2->setText(labelstring2);
+
+ // HACK
+ // QPixmap pm( BarIcon( "kcalclogo" ) );
+ QPixmap pm;
+ QLabel *logo = new QLabel(box);
+ logo->setPixmap(pm);
+ grid1->addWidget(logo,0,0);
+ lay1->addWidget(box);
+
+
+ DefStruct newdefstruct;
+ newdefstruct.forecolor = kcalcdefaults.forecolor;
+ newdefstruct.backcolor = kcalcdefaults.backcolor;
+ newdefstruct.precision = kcalcdefaults.precision;
+ newdefstruct.fixedprecision = kcalcdefaults.fixedprecision;
+ newdefstruct.fixed = kcalcdefaults.fixed;
+ newdefstruct.style = kcalcdefaults.style;
+ newdefstruct.beep = kcalcdefaults.beep;
+
+ ConfigDlg *configdlg;
+ configdlg = new ConfigDlg(tabdialog,"configdlg",&newdefstruct);
+
+ tabdialog->addTab(configdlg,i18n("Defaults"));
+ tabdialog->addTab(about,i18n("About"));
+
+
+ if(tabdialog->exec() == QDialog::Accepted){
+
+
+ kcalcdefaults.forecolor = newdefstruct.forecolor;
+ kcalcdefaults.backcolor = newdefstruct.backcolor;
+ kcalcdefaults.precision = newdefstruct.precision;
+ kcalcdefaults.fixedprecision = newdefstruct.fixedprecision;
+ kcalcdefaults.fixed = newdefstruct.fixed;
+ kcalcdefaults.style = newdefstruct.style;
+ kcalcdefaults.beep = newdefstruct.beep;
+
+ set_colors();
+ set_precision();
+ set_style();
+ updateGeometry();
+ resize(minimumSize());
+ }
+ delete configdlg;
+}
+
+
+void QtCalculator::set_style(){
+
+ switch(kcalcdefaults.style){
+ case 0:{
+ pbhyp->setText( "Hyp" );
+ pbSin->setText( "Sin" );
+ pbCos->setText( "Cos" );
+ pbTan->setText( "Tan" );
+ pblog->setText( "Log" );
+ pbln ->setText( "Ln" );
+ break;
+ }
+ case 1:{
+ pbhyp->setText( "N" );
+ pbSin->setText( "Mea" );
+ pbCos->setText( "Std" );
+ pbTan->setText( "Med" );
+ pblog->setText( "Dat" );
+ pbln ->setText( "CSt" );
+ break;
+ }
+ case 2:{
+ pbhyp->setText( "N" );
+ pbSin->setText( "Min" );
+ pbCos->setText( "Max" );
+ pbTan->setText( "Med" );
+ pblog->setText( "Sum" );
+ pbln ->setText( "Mul" );
+ break;
+ }
+
+ default:
+ break;
+ }
+}
+
+void QtCalculator::readSettings()
+{
+ QColor tmpC(189, 255, 180);
+ QColor blackC(0,0,0);
+
+ KConfig *config = KGlobal::config();
+ config->setGroup("CalcPlugin");
+ kcalcdefaults.forecolor = config->readColorEntry("ForeColor", &blackC);
+ kcalcdefaults.backcolor = config->readColorEntry("BackColor", &tmpC);
+
+#ifdef HAVE_LONG_DOUBLE
+ kcalcdefaults.precision = config->readNumEntry("precision", (int)14);
+#else
+ kcalcdefaults.precision = config->readNumEntry("precision", (int)10);
+#endif
+ kcalcdefaults.fixedprecision = config->readNumEntry("fixedprecision", (int)2);
+ kcalcdefaults.fixed = config->readBoolEntry("fixed", false);
+
+ kcalcdefaults.style = config->readNumEntry("style", (int)0);
+ kcalcdefaults.beep = config->readBoolEntry("beep", true);
+}
+
+void QtCalculator::writeSettings()
+{
+ KConfig *config = KGlobal::config();
+
+ config->setGroup("CalcPlugin");
+ config->writeEntry("ForeColor",kcalcdefaults.forecolor);
+ config->writeEntry("BackColor",kcalcdefaults.backcolor);
+
+ config->writeEntry("precision", kcalcdefaults.precision);
+ config->writeEntry("fixedprecision", kcalcdefaults.fixedprecision);
+ config->writeEntry("fixed", kcalcdefaults.fixed);
+
+ config->writeEntry("style",(int)kcalcdefaults.style);
+ config->writeEntry("beep", kcalcdefaults.beep);
+
+ config->sync();
+}
+
+void QtCalculator::display_selected(){
+
+ if(calc_display->Button() == LeftButton){
+
+ if(calc_display->isLit()){
+
+ QClipboard *cb = QApplication::clipboard();
+ cb->setText(calc_display->text());
+ selection_timer->start(100);
+
+ }
+ else{
+
+ selection_timer->stop();
+
+ }
+
+ invertColors();
+ }
+ else{
+
+ QClipboard *cb = QApplication::clipboard();
+
+ CALCAMNT result;
+ result = (CALCAMNT) cb->text().toDouble();
+ // printf("%Lg\n",result);
+ last_input = PASTE;
+ DISPLAY_AMOUNT = result;
+ UpdateDisplay();
+ }
+
+}
+
+void QtCalculator::selection_timed_out(){
+
+ // printf("selection timed out\n");
+ selection_timer->stop();
+ calc_display->setLit(FALSE);
+ invertColors();
+
+
+}
+
+
+void QtCalculator::clear_status_label(){
+
+ statusERRORLabel->setText("");
+ status_timer->stop();
+}
+
+void QtCalculator::setStatusLabel(const QString& string){
+
+ statusERRORLabel->setText(string);
+ status_timer->start(3000,TRUE);
+
+}
+
+
+void QtCalculator::invertColors(){
+
+ QColor tmpcolor;
+
+ if(calc_display->isLit()){
+ tmpcolor = kcalcdefaults.backcolor;
+ kcalcdefaults.backcolor = kcalcdefaults.forecolor;
+ kcalcdefaults.forecolor = tmpcolor;
+ set_colors();
+ tmpcolor = kcalcdefaults.backcolor;
+ kcalcdefaults.backcolor = kcalcdefaults.forecolor;
+ kcalcdefaults.forecolor = tmpcolor;
+ }
+ else{
+ set_colors();
+ //printf("normal Colors\n");
+ }
+}
+
+void QtCalculator::closeEvent( QCloseEvent*e )
+{
+ writeSettings();
+ e->accept();
+}
+
+void QtCalculator::set_colors(){
+
+
+ QPalette mypalette = (calc_display->palette()).copy();
+
+ QColorGroup cgrp = mypalette.active();
+ QColorGroup ncgrp(kcalcdefaults.forecolor,
+ cgrp.background(),
+ cgrp.light(),
+ cgrp.dark(),
+ cgrp.mid(),
+ kcalcdefaults.forecolor,
+ kcalcdefaults.backcolor);
+
+ mypalette.setActive(ncgrp);
+ mypalette.setDisabled(ncgrp);
+ mypalette.setActive(ncgrp);
+
+ calc_display->setPalette(mypalette);
+ calc_display->setBackgroundColor(kcalcdefaults.backcolor);
+
+}
+
+void QtCalculator::set_precision(){
+
+ UpdateDisplay();
+}
+
+void QtCalculator::temp_stack_next(){
+
+ CALCAMNT *number;
+
+ if( temp_stack.current() == temp_stack.getLast()){
+ KNotifyClient::beep();
+ return;
+ }
+
+ number = temp_stack.next();
+
+ if(number == NULL){
+ KNotifyClient::beep();
+ return;
+ }
+ else{
+ // printf("Number: %Lg\n",*number);
+ last_input = RECALL;
+ DISPLAY_AMOUNT = *number;
+ UpdateDisplay();
+
+ }
+
+
+}
+
+void QtCalculator::temp_stack_prev(){
+
+ CALCAMNT *number;
+
+ if( temp_stack.current() == temp_stack.getFirst()){
+ KNotifyClient::beep();
+ return;
+ }
+
+ number = temp_stack.prev();
+
+ if(number == NULL){
+ KNotifyClient::beep();
+ return;
+ }
+ else{
+ // printf("Number: %Lg\n",*number);
+ last_input = RECALL;
+ DISPLAY_AMOUNT = *number;
+ UpdateDisplay();
+
+ }
+
+}
+
+#include "kcalc.moc"
diff --git a/kspread/plugins/calculator/kcalc.h b/kspread/plugins/calculator/kcalc.h
new file mode 100644
index 000000000..752ae96e5
--- /dev/null
+++ b/kspread/plugins/calculator/kcalc.h
@@ -0,0 +1,447 @@
+/*
+ $Id: kcalc.h 466447 2005-10-02 17:54:10Z zander $
+
+ KCalc, a scientific calculator for the X window system using the
+ Qt widget libraries, available at no cost at http://www.troll.no
+
+ Copyright (C) 1996 Bernd Johannes Wuebben
+ wuebben@math.cornell.edu
+
+ 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.
+
+*/
+
+#ifndef QTCALC_H
+#define QTCALC_H
+
+#include <queue>
+using std::queue;
+
+#include <unistd.h>
+#include <stdlib.h>
+#include <ctype.h>
+
+#include <qlistbox.h>
+#include <qclipboard.h>
+#include <qptrlist.h>
+#include <qaccel.h>
+#include <qtabdialog.h>
+#include <qwidget.h>
+#include <qtimer.h>
+#include <qdialog.h>
+#include <qpixmap.h>
+#include <qapplication.h>
+#include <qfont.h>
+#include <qlabel.h>
+#include <qbuttongroup.h>
+#include <qcheckbox.h>
+#include <qframe.h>
+#include <qgroupbox.h>
+#include <qlineedit.h>
+#include <qpushbutton.h>
+#include <qradiobutton.h>
+#include <qtooltip.h>
+#include <qstring.h>
+#include <qrect.h>
+
+
+#include "dlabel.h"
+#include "stats.h"
+
+// IMPORTANT this has to come after ../config.h
+#include "kcalctype.h"
+
+#define STACK_SIZE 100
+#define TEMP_STACK_SIZE 1000 // the number of numbers kept in the temp stack
+ // which are accessible with the up and down arrow
+ // key
+
+#define PRECEDENCE_INCR 20
+
+#define FUNC_NULL 0
+#define FUNC_OR 1
+#define FUNC_XOR 2
+#define FUNC_AND 3
+#define FUNC_LSH 4
+#define FUNC_RSH 5
+#define FUNC_ADD 6
+#define FUNC_SUBTRACT 7
+#define FUNC_MULTIPLY 8
+#define FUNC_DIVIDE 9
+#define FUNC_MOD 10
+#define FUNC_POWER 11
+#define FUNC_PWR_ROOT 12
+#define FUNC_INTDIV 13
+
+#define DEC_SIZE 19
+#define BOH_SIZE 16
+#define DSP_SIZE 50 //25
+
+#define DEG2RAD(x) (((2L*pi)/360L)*x)
+#define GRA2RAD(x) ((pi/200L)*x)
+#define RAD2DEG(x) ((360L/(2L*pi))*x)
+#define RAD2GRA(x) ((200L/pi)*x)
+#define POS_ZERO 1e-19L /* What we consider zero is */
+#define NEG_ZERO -1e-19L /* anything between these two */
+
+
+typedef CALCAMNT (*Arith)(CALCAMNT, CALCAMNT);
+typedef CALCAMNT (*Prcnt)(CALCAMNT, CALCAMNT, CALCAMNT);
+typedef CALCAMNT (*Trig)(CALCAMNT);
+
+typedef enum _last_input_type {
+ DIGIT = 1, OPERATION = 2, RECALL = 3, PASTE = 4
+} last_input_type;
+
+typedef enum _num_base {
+ NB_BINARY = 2, NB_OCTAL = 8, NB_DECIMAL = 10, NB_HEX = 16
+} num_base;
+
+typedef enum _angle_type {
+ ANG_DEGREE = 0, ANG_RADIAN = 1, ANG_GRADIENT = 2
+} angle_type;
+
+typedef enum _item_type {
+ ITEM_FUNCTION, ITEM_AMOUNT
+} item_type;
+
+typedef struct _func_data {
+ int item_function;
+ int item_precedence;
+} func_data;
+
+typedef union _item_data { /* The item data */
+ CALCAMNT item_amount; /* an amount */
+ func_data item_func_data; /* or a function */
+} item_data; /* called item_data */
+
+typedef struct _item_contents { /* The item contents */
+ item_type s_item_type; /* a type flag */
+ item_data s_item_data; /* and data */
+} item_contents;
+
+typedef struct stack_item *stack_ptr;
+
+typedef struct stack_item {
+
+ /* Contents of an item on the input stack */
+
+ stack_ptr prior_item; /* Pointer to prior item */
+ stack_ptr prior_type; /* Pointer to prior type */
+ item_contents item_value; /* The value of the item */
+
+} stack_item; /* all called stack_item */
+
+
+CALCAMNT ExecOr(CALCAMNT left_op, CALCAMNT right_op);
+CALCAMNT ExecXor(CALCAMNT left_op, CALCAMNT right_op);
+CALCAMNT ExecAnd(CALCAMNT left_op, CALCAMNT right_op);
+CALCAMNT ExecLsh(CALCAMNT left_op, CALCAMNT right_op);
+CALCAMNT ExecRsh(CALCAMNT left_op, CALCAMNT right_op);
+CALCAMNT ExecAdd(CALCAMNT left_op, CALCAMNT right_op);
+CALCAMNT ExecSubtract(CALCAMNT left_op, CALCAMNT right_op);
+CALCAMNT ExecMultiply(CALCAMNT left_op, CALCAMNT right_op);
+CALCAMNT ExecDivide(CALCAMNT left_op, CALCAMNT right_op);
+CALCAMNT ExecMod(CALCAMNT left_op, CALCAMNT right_op);
+CALCAMNT ExecPower(CALCAMNT left_op, CALCAMNT right_op);
+CALCAMNT ExecPwrRoot(CALCAMNT left_op, CALCAMNT right_op);
+CALCAMNT ExecIntDiv(CALCAMNT left_op, CALCAMNT right_op);
+
+CALCAMNT ExecAddSubP(CALCAMNT left_op, CALCAMNT right_op, CALCAMNT result);
+CALCAMNT ExecMultiplyP(CALCAMNT left_op, CALCAMNT right_op, CALCAMNT result);
+CALCAMNT ExecDivideP(CALCAMNT left_op, CALCAMNT right_op, CALCAMNT result);
+CALCAMNT ExecPowerP(CALCAMNT left_op, CALCAMNT right_op, CALCAMNT result);
+CALCAMNT ExecPwrRootP(CALCAMNT left_op, CALCAMNT right_op, CALCAMNT result);
+
+
+int UpdateStack(int run_precedence);
+CALCAMNT ExecFunction(CALCAMNT left_op, int function, CALCAMNT right_op);
+int cvb(char *out_str, long amount, int max_out);
+
+void PrintStack(void);
+void InitStack(void);
+void PushStack(item_contents *add_item);
+item_contents *PopStack(void);
+item_contents *TopOfStack(void);
+item_contents *TopTypeStack(item_type rqstd_type);
+
+
+#define DISPLAY_AMOUNT display_data.s_item_data.item_amount
+
+
+
+typedef struct _DefStruct{
+ QColor forecolor;
+ QColor backcolor;
+ int precision;
+ int fixedprecision;
+ int style;
+ bool fixed;
+ bool beep;
+ QFont font;
+}DefStruct;
+
+class Calculator;
+
+class QtCalculator : public QDialog
+{
+ Q_OBJECT
+
+public:
+
+ QtCalculator( Calculator* _corba, QWidget *parent=0, const char *name=0 );
+ ~QtCalculator();
+
+ void keyPressEvent( QKeyEvent *e );
+ void keyReleaseEvent( QKeyEvent *e );
+ void closeEvent( QCloseEvent *e );
+ void readSettings();
+ void writeSettings();
+ void set_precision();
+ void set_style();
+ void set_display_font();
+ void temp_stack_next();
+ void temp_stack_prev();
+ void ComputeMean();
+ void ComputeSin();
+ void ComputeStd();
+ void ComputeCos();
+ void ComputeMedean();
+ void ComputeTan();
+ void ComputeSum();
+ void ComputeMul();
+ void ComputeMin();
+ void ComputeMax();
+
+ void setLabel( const char *_text );
+ void setValue( double _value );
+ void setData( const QRect& _range, const char *_sheet );
+ void useData();
+
+public slots:
+
+ void helpclicked();
+ void set_colors();
+ void display_selected();
+ void invertColors();
+ void selection_timed_out();
+ void clear_buttons();
+ void clear_status_label();
+ void setStatusLabel(const QString&);
+ void EnterDigit(int data);
+ void EnterDecimal();
+ void EnterStackFunction(int data);
+ void EnterNegate();
+ void EnterOpenParen();
+ void EnterCloseParen();
+ void EnterRecip();
+ void EnterInt();
+ void EnterFactorial();
+ void EnterSquare();
+ void EnterNotCmp();
+ void EnterHyp();
+ void EnterPercent();
+ void EnterLogr();
+ void EnterLogn();
+ void SetDeg();
+ void SetGra();
+ void SetRad();
+ void SetHex();
+ void SetOct();
+ void SetBin();
+ void SetDec();
+ void Deg_Selected();
+ void Rad_Selected();
+ void Gra_Selected();
+ void Hex_Selected();
+ void Dec_Selected();
+ void Oct_Selected();
+ void Bin_Selected();
+ void SetInverse();
+ void EnterEqual();
+ void Clear();
+ void ClearAll();
+ void RefreshCalculator(void);
+ void InitializeCalculator(void);
+ void UpdateDisplay();
+ void ExecSin();
+ void ExecCos();
+ void ExecTan();
+ void button0();
+ void button1();
+ void button2();
+ void button3();
+ void button4();
+ void button5();
+ void button6();
+ void button7();
+ void button8();
+ void button9();
+ void buttonA();
+ void buttonB();
+ void buttonC();
+ void buttonD();
+ void buttonE();
+ void buttonF();
+ void base_selected(int number);
+ void angle_selected(int number);
+ void Or();
+ void And();
+ void Shift();
+ void Plus();
+ void Minus();
+ void Multiply();
+ void Divide();
+ void Mod();
+ void Power();
+ void EE();
+ void MR();
+ void Mplusminus();
+ void MC();
+ void exit();
+ void EEtoggled(bool myboolean);
+ void pbinvtoggled(bool myboolean);
+ void pbMRtoggled(bool myboolean);
+ void pbAtoggled(bool myboolean);
+ void pbSintoggled(bool myboolean);
+ void pbplusminustoggled(bool myboolean);
+ void pbMplusminustoggled(bool myboolean);
+ void pbBtoggled(bool myboolean);
+ void pbCostoggled(bool myboolean);
+ void pbrecitoggled(bool myboolean);
+ void pbCtoggled(bool myboolean);
+ void pbTantoggled(bool myboolean);
+ void pbfactorialtoggled(bool myboolean);
+ void pbDtoggled(bool myboolean);
+ void pblogtoggled(bool myboolean);
+ void pbsquaretoggled(bool myboolean);
+ void pbEtoggled(bool myboolean);
+ void pblntoggled(bool myboolean);
+ void pbpowertoggled(bool myboolean);
+ void pbFtoggled(bool myboolean);
+ void pbMCtoggled(bool myboolean);
+ void pbCleartoggled(bool myboolean);
+ void pbACtoggled(bool myboolean);
+ void pb7toggled(bool myboolean);
+ void pb8toggled(bool myboolean);
+ void pb9toggled(bool myboolean);
+ void pbparenopentoggled(bool myboolean);
+ void pbparenclosetoggled(bool myboolean);
+ void pbandtoggled(bool myboolean);
+ void pb4toggled(bool myboolean);
+ void pb5toggled(bool myboolean);
+ void pb6toggled(bool myboolean);
+ void pbXtoggled(bool myboolean);
+ void pbdivisiontoggled(bool myboolean);
+ void pbortoggled(bool myboolean);
+ void pb1toggled(bool myboolean);
+ void pb2toggled(bool myboolean);
+ void pb3toggled(bool myboolean);
+ void pbplustoggled(bool myboolean);
+ void pbminustoggled(bool myboolean);
+ void pbshifttoggled(bool myboolean);
+ void pbperiodtoggled(bool myboolean);
+ void pb0toggled(bool myboolean);
+ void pbequaltoggled(bool myboolean);
+ void pbpercenttoggled(bool myboolean);
+ void pbnegatetoggled(bool myboolean);
+ void pbmodtoggled(bool myboolean);
+ void pbhyptoggled(bool myboolean);
+ void configclicked();
+
+public:
+
+ DefStruct kcalcdefaults;
+
+private:
+ void updateGeometry();
+
+ QTimer* selection_timer;
+ QLabel* statusINVLabel;
+ QLabel* statusHYPLabel;
+ QLabel* statusERRORLabel;
+ DLabel* calc_display;
+ QRadioButton* anglebutton[3];
+ QRadioButton* basebutton[4];
+ QPushButton* pbhyp;
+ QPushButton* pbEE;
+ QPushButton* pbinv;
+ QPushButton* pbMR;
+ QPushButton* pbA;
+ QPushButton* pbSin;
+ QPushButton* pbplusminus;
+ QPushButton* pbMplusminus;
+ QPushButton* pbB;
+ QPushButton* pbCos;
+ QPushButton* pbreci;
+ QPushButton* pbC;
+ QPushButton* pbTan;
+ QPushButton* pbfactorial;
+ QPushButton* pbD;
+ QPushButton* pblog;
+ QPushButton* pbsquare;
+ QPushButton* pbE;
+ QPushButton* pbln;
+ QPushButton* pbpower;
+ QPushButton* pbF;
+ QPushButton* pbMC;
+ QPushButton* pbClear;
+ QPushButton* pbAC;
+ QPushButton* pb7;
+ QPushButton* pb8;
+ QPushButton* pb9;
+ QPushButton* pbparenopen;
+ QPushButton* pbparenclose;
+ QPushButton* pband;
+ QPushButton* pb4;
+ QPushButton* pb5;
+ QPushButton* pb6;
+ QPushButton* pbX;
+ QPushButton* pbdivision;
+ QPushButton* pbor;
+ QPushButton* pb1;
+ QPushButton* pb2;
+ QPushButton* pb3;
+ QPushButton* pbplus;
+ QPushButton* pbminus;
+ QPushButton* pbshift;
+ QPushButton* pbperiod;
+ QPushButton* pb0;
+ QPushButton* pbequal;
+ QPushButton* pbpercent;
+ QPushButton* pbnegate;
+ QPushButton* pbmod;
+
+ QPtrList<QPushButton> mNumButtonList;
+ QPtrList<QPushButton> mFunctionButtonList;
+ QPtrList<QPushButton> mHexButtonList;
+ QPtrList<QPushButton> mMemButtonList;
+ QPtrList<QPushButton> mOperationButtonList;
+
+ bool key_pressed;
+ KStats stats;
+ QListBox *paper;
+ QTimer *status_timer;
+
+ QRect sheet_range;
+ QString sheet_name;
+ Calculator* corba;
+ QWidget *mSmallPage;
+ QWidget *mLargePage;
+ int mInternalSpacing;
+};
+
+#endif //QTCLAC_H
diff --git a/kspread/plugins/calculator/kcalc_core.cpp b/kspread/plugins/calculator/kcalc_core.cpp
new file mode 100644
index 000000000..43221b210
--- /dev/null
+++ b/kspread/plugins/calculator/kcalc_core.cpp
@@ -0,0 +1,2192 @@
+/*
+ $Id: kcalc_core.cpp 541875 2006-05-17 14:42:51Z zander $
+
+ kCalculator, a scientific calculator for the X window system using the
+ Qt widget libraries, available at no cost at http://www.troll.no
+
+ The stack engine conatined in this file was take from
+ Martin Bartlett's xfrmcalc
+
+ portions: Copyright (C) 1996 Bernd Johannes Wuebben
+ wuebben@math.cornell.edu
+
+ portions: Copyright (C) 1995 Martin Bartlett
+
+ 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 <config.h>
+#include <assert.h>
+#include <stdio.h>
+#include <errno.h>
+#include <limits.h>
+#include <math.h>
+#include <signal.h>
+#include <klocale.h>
+#include <kmessagebox.h>
+#include <knotifyclient.h>
+
+#include "kcalc.h"
+
+//What's that?!? (Werner)
+//#define i18n( x ) x
+
+// Undefine HAVE_LONG_DOUBLE for Beta 4 since RedHat 5.0 comes with a borken
+// glibc
+
+#ifdef HAVE_LONG_DOUBLE
+#undef HAVE_LONG_DOUBLE
+#endif
+
+#ifndef HAVE_FUNC_ISINF
+#ifdef HAVE_IEEEFP_H
+#include <ieeefp.h>
+#else
+#include <math.h>
+#endif
+
+int isinf(double x) { return !finite(x) && x==x; }
+#endif
+
+extern QPtrList<CALCAMNT> temp_stack;
+last_input_type last_input;
+char display_str[DSP_SIZE+1];
+
+stack_ptr top_of_stack = NULL;
+stack_ptr top_type_stack[2] = { NULL, NULL };
+int stack_next, stack_last;
+stack_item process_stack[STACK_SIZE];
+
+int inverse = FALSE;
+int precedence_base = 0;
+num_base current_base = NB_DECIMAL;
+int input_limit = 0;
+int input_count = 0;
+
+//item_contents display_data = { ITEM_AMOUNT, 0 };
+item_contents display_data;
+
+int display_size = DEC_SIZE;
+
+int hyp_mode = 0;
+int angle_mode = ANG_DEGREE;
+int refresh_display; // if 1 we start a new number
+int display_error = 0;
+int decimal_point = 0;
+int percent_mode = 0;
+bool eestate = false; // if true then we are in ee input mode
+
+CALCAMNT pi;
+CALCAMNT memory_num = 0.0;
+
+int precedence[14] = { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 7, 7, 6 };
+
+ int adjust_op[14][3] = {
+ {FUNC_NULL, FUNC_NULL, FUNC_NULL},
+ {FUNC_OR, FUNC_OR, FUNC_XOR },
+ {FUNC_XOR, FUNC_XOR, FUNC_XOR },
+ {FUNC_AND, FUNC_AND, FUNC_AND },
+ {FUNC_LSH, FUNC_LSH, FUNC_RSH },
+ {FUNC_RSH, FUNC_RSH, FUNC_RSH },
+ {FUNC_ADD, FUNC_ADD, FUNC_ADD },
+ {FUNC_SUBTRACT, FUNC_SUBTRACT, FUNC_SUBTRACT},
+ {FUNC_MULTIPLY, FUNC_MULTIPLY, FUNC_MULTIPLY},
+ {FUNC_DIVIDE, FUNC_DIVIDE, FUNC_DIVIDE},
+ {FUNC_MOD, FUNC_MOD, FUNC_INTDIV },
+ {FUNC_POWER, FUNC_POWER, FUNC_PWR_ROOT},
+ {FUNC_PWR_ROOT, FUNC_PWR_ROOT, FUNC_PWR_ROOT},
+ {FUNC_INTDIV, FUNC_INTDIV, FUNC_INTDIV},
+ };
+/*
+ char *function_desc[] = {
+
+ "Null",
+ "Or",
+ "Exclusive Or",
+ "And",
+ "Left Shift",
+ "Right Shift",
+ "Add",
+ "Subtract",
+ "Multiply",
+ "Divide",
+ "Modulus"
+ "Power"
+ "Reciprocal Power"
+ "Integer Division"
+ };
+ */
+ Arith Arith_ops[14] = { NULL,
+ ExecOr,
+ ExecXor,
+ ExecAnd,
+ ExecLsh,
+ ExecRsh,
+ ExecAdd, ExecSubtract,
+ ExecMultiply,
+ ExecDivide, ExecMod,
+ ExecPower, ExecPwrRoot,
+ ExecIntDiv
+ };
+
+ Prcnt Prcnt_ops[14] = { NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ ExecAddSubP, ExecAddSubP,
+ ExecMultiplyP,
+ ExecDivideP, ExecDivideP,
+ ExecPowerP, ExecPwrRootP,
+ ExecDivideP
+ };
+
+
+void QtCalculator::InitializeCalculator(void) {
+
+ //
+ // Basic initialization involves initializing the calcultion
+ // stack, forcing the display to refresh to zero, and setting
+ // up the floating point excetion signal handler to trap the
+ // errors that the code can/has not been written to trap.
+ //
+ // We also calculate pi as double the arc sine of 1.
+ //
+
+ display_data.s_item_type = ITEM_AMOUNT;
+ display_data.s_item_data.item_amount = 0.0;
+ display_data.s_item_data.item_func_data.item_function = 0;
+ display_data.s_item_data.item_func_data.item_precedence = 0;
+
+ void fpe_handler(int fpe_parm);
+ struct sigaction fpe_trap;
+
+ fpe_trap.sa_handler = &fpe_handler;
+#ifdef SA_RESTART
+ fpe_trap.sa_flags = SA_RESTART;
+#endif
+
+ sigaction(SIGFPE, &fpe_trap, NULL);
+
+ RefreshCalculator();
+ pi = ASIN(1.0) * 2L;
+}
+
+void fpe_handler(int fpe_parm)
+{
+ (void) fpe_parm;
+
+ display_error = 1;
+ DISPLAY_AMOUNT = 0L;
+
+}
+
+void QtCalculator::setData( const QRect& _range, const char *_sheet )
+{
+ sheet_range = _range;
+ sheet_name = _sheet;
+}
+
+void QtCalculator::setValue( double _value )
+{
+ last_input = DIGIT;
+ DISPLAY_AMOUNT = _value;
+ decimal_point = 0;
+ refresh_display = 1;
+ input_count = 0;
+
+ UpdateDisplay();
+}
+
+void QtCalculator::setLabel( const char *_text )
+{
+ last_input = DIGIT;
+ DISPLAY_AMOUNT = 0L;
+ decimal_point = 0;
+ refresh_display = 0;
+ input_count = 0;
+
+ calc_display->setText( _text );
+}
+
+void QtCalculator::RefreshCalculator(void)
+{
+ InitStack();
+ display_error = 0;
+ DISPLAY_AMOUNT = 0L;
+ inverse = FALSE;
+ UpdateDisplay();
+ last_input = DIGIT; // must set last to DIGIT after Update Display in order
+ // not to get a display holding e.g. 0.000
+ input_count = 0;
+ decimal_point = 0;
+}
+
+void QtCalculator::EnterDigit(int data)
+{
+
+ if(eestate){
+
+ QString string;
+ string.setNum(data);
+ strcat(display_str, string.latin1());
+ DISPLAY_AMOUNT = (CALCAMNT) strtod(display_str,0);
+ UpdateDisplay();
+ return;
+
+ }
+
+ last_input = DIGIT;
+ if (refresh_display) {
+ DISPLAY_AMOUNT = 0L;
+ decimal_point = 0;
+ refresh_display = 0;
+ input_count = 0;
+ }
+
+ if (!(input_limit && input_count >= input_limit))
+ if (DISPLAY_AMOUNT < 0)
+ DISPLAY_AMOUNT = decimal_point ?
+ DISPLAY_AMOUNT - ((CALCAMNT)data /
+ POW((float)current_base, decimal_point++)) :
+ (current_base * DISPLAY_AMOUNT) - data;
+ else
+ DISPLAY_AMOUNT = decimal_point ?
+ DISPLAY_AMOUNT + ((CALCAMNT)data /
+ POW((float)current_base, decimal_point++)) :
+ (current_base * DISPLAY_AMOUNT) + data;
+
+ if (decimal_point){
+ input_count ++;
+
+#ifdef MYDEBUG
+ printf("EnterDigit() inc dec.point:%d\n",input_count);
+#endif
+
+ }
+ UpdateDisplay();
+}
+
+void QtCalculator::button0()
+{
+ EnterDigit(0);
+}
+
+void QtCalculator::button1()
+{
+ EnterDigit(1);
+ }
+
+void QtCalculator::button2()
+{
+ if (current_base == NB_BINARY)
+ return;
+ EnterDigit(2);
+}
+
+void QtCalculator::button3()
+{
+ if (current_base == NB_BINARY)
+ return;
+ EnterDigit(3);
+}
+
+void QtCalculator::button4()
+{
+ if (current_base == NB_BINARY)
+ return;
+ EnterDigit(4);
+}
+
+void QtCalculator::button5()
+{
+ if (current_base == NB_BINARY)
+ return;
+ EnterDigit(5);
+}
+
+void QtCalculator::button6()
+{
+ if (current_base == NB_BINARY)
+ return;
+ EnterDigit(6);
+}
+
+void QtCalculator::button7()
+{
+ if (current_base == NB_BINARY)
+ return;
+ EnterDigit(7);
+}
+
+void QtCalculator::button8()
+{
+ if ((current_base == NB_BINARY) || (current_base == NB_OCTAL))
+ return;
+ EnterDigit(8);
+}
+
+void QtCalculator::button9()
+{
+ if ((current_base == NB_BINARY) || (current_base == NB_OCTAL))
+ return;
+ EnterDigit(9);
+}
+
+
+void QtCalculator::buttonA()
+{
+ if ((current_base == NB_BINARY) || (current_base == NB_OCTAL)
+ || (current_base == NB_DECIMAL))
+ return;
+ EnterDigit(10);
+}
+
+
+void QtCalculator::buttonB()
+{
+ if ((current_base == NB_BINARY) || (current_base == NB_OCTAL)
+ || (current_base == NB_DECIMAL))
+ return;
+ EnterDigit(11);
+}
+
+
+void QtCalculator::buttonC()
+{
+ if ((current_base == NB_BINARY) || (current_base == NB_OCTAL)
+ || (current_base == NB_DECIMAL))
+ return;
+ EnterDigit(12);
+}
+
+
+void QtCalculator::buttonD()
+{
+ if ((current_base == NB_BINARY) || (current_base == NB_OCTAL)
+ || (current_base == NB_DECIMAL))
+ return;
+ EnterDigit(13);
+}
+
+
+void QtCalculator::buttonE()
+{
+ if ((current_base == NB_BINARY) || (current_base == NB_OCTAL)
+ || (current_base == NB_DECIMAL))
+ return;
+ EnterDigit(14);
+}
+
+void QtCalculator::buttonF()
+{
+ if ((current_base == NB_BINARY) || (current_base == NB_OCTAL)
+ || (current_base == NB_DECIMAL))
+ return;
+ EnterDigit(15);
+}
+
+
+
+void QtCalculator::EnterDecimal()
+{
+
+ if(eestate){
+ KNotifyClient::beep();
+ return;
+ }
+
+ decimal_point = 1;
+ if (refresh_display) {
+ DISPLAY_AMOUNT = 0L;
+ refresh_display = 0;
+ input_count = 0;
+ }
+
+ if (last_input == DIGIT && !strpbrk( display_str,".")){
+
+ // if the last input was a DIGIT and we don't have already a period in our
+ // display string then display a period
+
+ calc_display->setText(strcat(display_str, "."));
+ }
+ else {
+
+ // the last input wasn't a DIGIT so we are about to
+ // input a new number in particular we neet do display a "0.".
+
+ DISPLAY_AMOUNT = 0L;
+ refresh_display = 0;
+ // decimal_point = 1;
+ // input_count = 1;
+ strcpy(display_str, "0.");
+ calc_display->setText(display_str);
+ }
+}
+
+
+void QtCalculator::Or()
+{
+ eestate = false;
+ if (inverse){
+ EnterStackFunction(2); // XOR
+ inverse = FALSE;
+ }
+ else {
+ EnterStackFunction(1); // OR
+ }
+ last_input = OPERATION;
+}
+
+void QtCalculator::And()
+{
+ eestate = false;
+ last_input = OPERATION;
+ EnterStackFunction(3);
+}
+
+
+void QtCalculator::Shift()
+{
+ eestate = false;
+ last_input = OPERATION;
+ if (inverse){
+ EnterStackFunction(5); // Rsh
+ inverse = FALSE;
+ }
+ else {
+ EnterStackFunction(4); // Lsh
+ }
+
+}
+
+void QtCalculator::Plus()
+{
+ eestate = false;
+ last_input = OPERATION;
+ EnterStackFunction(6);
+}
+
+void QtCalculator::Minus()
+{
+ eestate = false;
+ last_input = OPERATION;
+ EnterStackFunction(7);
+
+}
+
+void QtCalculator::Multiply()
+{
+ eestate = false;
+ last_input = OPERATION;
+ EnterStackFunction(8);
+}
+
+void QtCalculator::Divide()
+{
+ eestate = false;
+ last_input = OPERATION;
+ EnterStackFunction(9);
+}
+
+void QtCalculator::Mod()
+{
+ eestate = false;
+ last_input = OPERATION;
+ if (inverse){
+ EnterStackFunction(13); // InvMod
+ inverse = FALSE;
+ }
+ else {
+ EnterStackFunction(10); // Mod
+ }
+}
+
+void QtCalculator::Power()
+{
+ eestate = false;
+ last_input = OPERATION;
+ if (inverse){
+ EnterStackFunction(12); // InvPower
+ inverse = FALSE;
+ }
+ else {
+ EnterStackFunction(11); // Power
+ }
+
+}
+
+
+
+void QtCalculator::EnterStackFunction(int data)
+{
+ item_contents new_item;
+ int new_precedence;
+ int dummy;
+
+ dummy = 0;
+
+ /*
+ if (inverse ) {
+ dummy = 3;
+ inverse = FALSE;
+ }
+ else {
+ dummy = 1;
+ }
+ */
+
+ // printf("data %d dummy %d\n",data,dummy);
+ data = adjust_op[data][dummy];
+ // printf("data %d \n",data );
+
+ PushStack(&display_data);
+
+ new_item.s_item_type = ITEM_FUNCTION;
+ new_item.s_item_data.item_func_data.item_function = data;
+ new_item.s_item_data.item_func_data.item_precedence =
+ new_precedence = precedence[data] + precedence_base;
+
+ refresh_display = 1;
+ if (UpdateStack(new_precedence))
+ UpdateDisplay();
+ PushStack(&new_item);
+}
+
+void QtCalculator::EnterNegate()
+{
+
+ if(eestate){
+ QString string;
+ string = display_str;
+ int pos;
+ pos = string.findRev('e',-1,false);
+ if(pos == -1)
+ return;
+
+ if(display_str[pos+1] == '+')
+ display_str[pos+1] = '-';
+ else{
+ if(display_str[pos+1] == '-')
+ display_str[pos+1] = '+';
+ else{
+ string.insert(pos +1,'-');
+ strncpy(display_str,string.latin1(),DSP_SIZE);
+ }
+ }
+ DISPLAY_AMOUNT = (CALCAMNT)strtod(display_str,0);
+ UpdateDisplay();
+ }
+ else{
+ // last_input = OPERATION;
+ if (DISPLAY_AMOUNT != 0) {
+ DISPLAY_AMOUNT *= -1;
+ UpdateDisplay();
+ }
+ }
+ last_input = DIGIT;
+}
+
+void QtCalculator::EnterOpenParen()
+{
+ eestate = false;
+ last_input = OPERATION;
+ precedence_base += PRECEDENCE_INCR;
+ refresh_display = 1;
+
+}
+
+void QtCalculator::EnterCloseParen()
+{
+ eestate = false;
+ last_input = OPERATION;
+ PushStack(&display_data);
+ refresh_display = 1;
+ if (UpdateStack(precedence_base))
+ UpdateDisplay();
+ if ((precedence_base -= PRECEDENCE_INCR) < 0)
+ precedence_base = 0;
+
+}
+
+void QtCalculator::EnterRecip()
+{
+ eestate = false;
+ last_input = OPERATION;
+ DISPLAY_AMOUNT = 1 / DISPLAY_AMOUNT;
+ refresh_display = 1;
+ UpdateDisplay();
+}
+
+void QtCalculator::EnterInt()
+{
+ eestate = false;
+ CALCAMNT work_amount1 = 0.0, work_amount2 = 0.0;
+
+ last_input = OPERATION;
+ if (!inverse){
+ work_amount2 = MODF(DISPLAY_AMOUNT, &work_amount1);
+ DISPLAY_AMOUNT = work_amount2 ;
+ }
+ else {
+ DISPLAY_AMOUNT = work_amount1;
+ inverse = FALSE;
+ }
+
+ refresh_display = 1;
+ UpdateDisplay();
+
+}
+
+void QtCalculator::EnterFactorial()
+{
+ eestate = false;
+ CALCAMNT work_amount1, work_amount2;
+ int incr;
+
+ MODF(DISPLAY_AMOUNT, &work_amount1);
+
+ incr = work_amount1 < 0 ? -1 : 1;
+ work_amount2 = work_amount1 - incr;
+ while (work_amount1 != 0 && work_amount2 != 0 && !display_error) {
+ work_amount1 *= work_amount2;
+ work_amount2 -= incr;
+ if(isinf(work_amount1)) {
+ display_error=1;
+ break;
+ }
+ }
+
+ if( work_amount1 == 0.0)
+ work_amount1 = 1.0;
+
+ DISPLAY_AMOUNT = work_amount1;
+ refresh_display = 1;
+ last_input = OPERATION;
+ UpdateDisplay();
+
+}
+
+void QtCalculator::EnterSquare()
+{
+ eestate = false;
+ if (!inverse){
+ DISPLAY_AMOUNT *= DISPLAY_AMOUNT;
+ }
+ else if (DISPLAY_AMOUNT < 0)
+ display_error = 1;
+ else
+ DISPLAY_AMOUNT = SQRT(DISPLAY_AMOUNT);
+ refresh_display = 1;
+ inverse = FALSE;
+ last_input = OPERATION;
+ UpdateDisplay();
+
+}
+
+void QtCalculator::EnterNotCmp()
+{
+ eestate = false;
+ CALCAMNT boh_work_d;
+ long boh_work;
+
+ MODF(DISPLAY_AMOUNT, &boh_work_d);
+ if (FABS(boh_work_d) > LONG_MAX)
+ display_error = 1;
+ else {
+ boh_work = (long int) boh_work_d;
+ DISPLAY_AMOUNT = ~boh_work;
+ }
+ refresh_display = 1;
+ last_input = OPERATION;
+ UpdateDisplay();
+
+}
+
+void QtCalculator::EnterHyp()
+{
+
+ switch(kcalcdefaults.style){
+ case 2:
+ case 1:{
+ if ( !sheet_name.isEmpty() )
+ useData();
+
+ if(!inverse){
+ eestate = false; // terminate ee input mode
+ DISPLAY_AMOUNT = stats.count();
+ last_input = OPERATION;
+ refresh_display = 1;
+ UpdateDisplay();
+ }
+ else{
+ inverse = false;
+ eestate = false; // terminate ee input mode
+ DISPLAY_AMOUNT = stats.sum();
+ last_input = OPERATION;
+ refresh_display = 1;
+ UpdateDisplay();
+ }
+
+ break;
+ }
+
+ case 0: {
+ // toggle between hyperbolic and standart trig functions
+ hyp_mode = !hyp_mode;
+
+ if (hyp_mode){
+ statusHYPLabel->setText("HYP");
+ }
+ else{
+ statusHYPLabel->setText("");
+ }
+ break;
+ }
+ }
+}
+
+
+void QtCalculator::ExecSin(){
+
+ switch(kcalcdefaults.style){
+
+ case 0:{ // trig mode
+
+ ComputeSin();
+ break;
+ }
+
+ case 1:{ // stats mode
+ if ( !sheet_name.isEmpty() )
+ useData();
+
+ ComputeMean();
+ break;
+ }
+
+ case 2:{ // sheet mode
+ if ( !sheet_name.isEmpty() )
+ useData();
+
+ ComputeMin();
+ break;
+ }
+
+ }
+
+}
+
+void QtCalculator::ComputeSum()
+{
+ inverse = false;
+ eestate = false;
+ DISPLAY_AMOUNT = stats.sum();
+ if (stats.error())
+ display_error = 1;
+
+ refresh_display = 1;
+ last_input = OPERATION;
+ UpdateDisplay();
+}
+
+void QtCalculator::ComputeMul()
+{
+ inverse = false;
+ eestate = false;
+ DISPLAY_AMOUNT = stats.mul();
+ if (stats.error())
+ display_error = 1;
+
+ refresh_display = 1;
+ last_input = OPERATION;
+ UpdateDisplay();
+}
+
+void QtCalculator::ComputeMin()
+{
+ inverse = false;
+ eestate = false;
+ DISPLAY_AMOUNT = stats.min();
+ if (stats.error())
+ display_error = 1;
+
+ refresh_display = 1;
+ last_input = OPERATION;
+ UpdateDisplay();
+}
+
+void QtCalculator::ComputeMax()
+{
+ inverse = false;
+ eestate = false;
+ DISPLAY_AMOUNT = stats.max();
+ if (stats.error())
+ display_error = 1;
+
+ refresh_display = 1;
+ last_input = OPERATION;
+ UpdateDisplay();
+}
+
+void QtCalculator::ComputeMean(){
+
+ if(!inverse){
+ eestate = false;
+ DISPLAY_AMOUNT = stats.mean();
+ if (stats.error())
+ display_error = 1;
+
+ refresh_display = 1;
+ last_input = OPERATION;
+ UpdateDisplay();
+ }
+ else{
+ inverse = false;
+ eestate = false;
+ DISPLAY_AMOUNT = stats.sum_of_squares();
+ if (stats.error())
+ display_error = 1;
+ refresh_display = 1;
+ last_input = OPERATION;
+ UpdateDisplay();
+
+ }
+
+}
+
+void QtCalculator::ComputeSin()
+{
+ CALCAMNT work_amount;
+ eestate = false;
+ work_amount = DISPLAY_AMOUNT;
+
+ if (hyp_mode){
+ // sinh or arcsinh
+ if (!inverse){
+ DISPLAY_AMOUNT = SINH( work_amount);
+ }
+ else {
+ DISPLAY_AMOUNT = ASINH( work_amount);
+ if (errno == EDOM || errno == ERANGE)
+ display_error = 1;
+ inverse = FALSE; // reset the inverse flag
+ }
+ }
+ else {
+ // sine or arcsine
+ if (!inverse){
+ // sine
+ switch (angle_mode) {
+ case ANG_DEGREE:
+ work_amount = DEG2RAD(DISPLAY_AMOUNT);
+ break;
+ case ANG_GRADIENT:
+ work_amount = GRA2RAD(DISPLAY_AMOUNT);
+ break;
+ case ANG_RADIAN:
+ work_amount = DISPLAY_AMOUNT;
+ break;
+ }
+ DISPLAY_AMOUNT = SIN( work_amount);
+ }
+ else {
+ // arcsine
+ DISPLAY_AMOUNT = ASIN(work_amount);
+ switch (angle_mode) {
+ case ANG_DEGREE:
+ work_amount = RAD2DEG(DISPLAY_AMOUNT);
+ break;
+ case ANG_GRADIENT:
+ work_amount = RAD2GRA(DISPLAY_AMOUNT);
+ break;
+ case ANG_RADIAN:
+ work_amount = DISPLAY_AMOUNT;
+ break;
+ }
+ DISPLAY_AMOUNT = work_amount;
+ if (errno == EDOM || errno == ERANGE)
+ display_error = 1;
+ inverse = FALSE; // reset the inverse flag
+ }
+ }
+
+// Now a cheat to help the weird case of COS 90 degrees not being 0!!!
+
+ if (DISPLAY_AMOUNT < POS_ZERO && DISPLAY_AMOUNT > NEG_ZERO)
+ DISPLAY_AMOUNT=0;
+ refresh_display = 1;
+ last_input = OPERATION;
+ UpdateDisplay();
+
+}
+
+void QtCalculator::ExecCos(){
+
+ switch(kcalcdefaults.style){
+
+ case 0:{ // trig mode
+
+ ComputeCos();
+ break;
+ }
+
+ case 1:{ // stats mode
+ if ( !sheet_name.isEmpty() )
+ useData();
+
+ ComputeStd();
+ break;
+ }
+
+ case 2:{ // sheet mode
+ if ( !sheet_name.isEmpty() )
+ useData();
+
+ ComputeMax();
+ break;
+ }
+
+ }
+
+}
+
+void QtCalculator::ComputeStd(){
+
+ if(!inverse){ // std (n-1)
+ inverse = false;
+ eestate = false;
+ DISPLAY_AMOUNT = stats.std();
+
+ if (stats.error()){
+ display_error = 1;
+ }
+
+ refresh_display = 1;
+ last_input = OPERATION;
+ UpdateDisplay();
+ }
+ else{ // std (n)
+
+ inverse = false;
+ eestate = false;
+ DISPLAY_AMOUNT = stats.sample_std();
+
+ if (stats.error())
+ display_error = 1;
+
+ refresh_display = 1;
+ last_input = OPERATION;
+ UpdateDisplay();
+
+
+
+ }
+
+}
+
+void QtCalculator::ComputeCos()
+{
+ CALCAMNT work_amount;
+ eestate = false;
+ work_amount = DISPLAY_AMOUNT;
+
+ if (hyp_mode){
+ // cosh or arccosh
+ if (!inverse){
+ DISPLAY_AMOUNT = COSH( work_amount);
+ }
+ else {
+ DISPLAY_AMOUNT = ACOSH( work_amount);
+ if (errno == EDOM || errno == ERANGE)
+ display_error = 1;
+ inverse = FALSE; // reset the inverse flag
+ }
+ }
+ else {
+ // cosine or arccosine
+ if (!inverse){
+ // sine
+ switch (angle_mode) {
+ case ANG_DEGREE:
+ work_amount = DEG2RAD(DISPLAY_AMOUNT);
+ break;
+ case ANG_GRADIENT:
+ work_amount = GRA2RAD(DISPLAY_AMOUNT);
+ break;
+ case ANG_RADIAN:
+ work_amount = DISPLAY_AMOUNT;
+ break;
+ }
+ DISPLAY_AMOUNT = COS( work_amount);
+ }
+ else {
+ // arccosine
+ DISPLAY_AMOUNT = ACOS(work_amount);
+ switch (angle_mode) {
+ case ANG_DEGREE:
+ work_amount = RAD2DEG(DISPLAY_AMOUNT);
+ break;
+ case ANG_GRADIENT:
+ work_amount = RAD2GRA(DISPLAY_AMOUNT);
+ break;
+ case ANG_RADIAN:
+ work_amount = DISPLAY_AMOUNT;
+ break;
+ }
+
+ DISPLAY_AMOUNT = work_amount;
+
+ if (errno == EDOM || errno == ERANGE)
+ display_error = 1;
+ inverse = FALSE; // reset the inverse flag
+ }
+ }
+
+// Now a cheat to help the weird case of COS 90 degrees not being 0!!!
+
+
+ if (DISPLAY_AMOUNT < POS_ZERO && DISPLAY_AMOUNT > NEG_ZERO)
+ DISPLAY_AMOUNT=0;
+ refresh_display = 1;
+ last_input = OPERATION;
+ UpdateDisplay();
+
+}
+
+void QtCalculator::ExecTan(){
+
+ switch(kcalcdefaults.style){
+
+ case 0:{ // trig mode
+
+ ComputeTan();
+ break;
+ }
+
+ case 2:
+ case 1:{ // stats mode
+
+ if ( !sheet_name.isEmpty() )
+ useData();
+
+ ComputeMedean();
+ break;
+ }
+
+ }
+
+}
+
+void QtCalculator::ComputeMedean(){
+
+ if(!inverse){ // std (n-1)
+ inverse = false;
+ eestate = false;
+ DISPLAY_AMOUNT = stats.median();
+
+ if (stats.error()){
+ display_error = 1;
+ }
+
+ refresh_display = 1;
+ last_input = OPERATION;
+ UpdateDisplay();
+ }
+ else{ // std (n)
+
+ inverse = false;
+ eestate = false;
+ DISPLAY_AMOUNT = stats.median();
+
+ if (stats.error())
+ display_error = 1;
+
+ refresh_display = 1;
+ last_input = OPERATION;
+ UpdateDisplay();
+
+ }
+}
+
+
+void QtCalculator::ComputeTan()
+{
+ CALCAMNT work_amount;
+ eestate = false;
+ work_amount = DISPLAY_AMOUNT;
+
+ if (hyp_mode){
+ // tanh or arctanh
+ if (!inverse){
+ DISPLAY_AMOUNT = TANH( work_amount);
+ }
+ else {
+ DISPLAY_AMOUNT = ATANH( work_amount);
+ if (errno == EDOM || errno == ERANGE)
+ display_error = 1;
+ inverse = FALSE; // reset the inverse flag
+ }
+ }
+ else {
+ // tan or arctan
+ if (!inverse){
+ // tan
+ switch (angle_mode) {
+ case ANG_DEGREE:
+ work_amount = DEG2RAD(DISPLAY_AMOUNT);
+ break;
+ case ANG_GRADIENT:
+ work_amount = GRA2RAD(DISPLAY_AMOUNT);
+ break;
+ case ANG_RADIAN:
+ work_amount = DISPLAY_AMOUNT;
+ break;
+ }
+ DISPLAY_AMOUNT = TAN( work_amount);
+ if (errno == EDOM || errno == ERANGE)
+ display_error = 1;
+ }
+ else {
+ // arctan
+ DISPLAY_AMOUNT = ATAN(work_amount);
+ switch (angle_mode) {
+ case ANG_DEGREE:
+ work_amount = RAD2DEG(DISPLAY_AMOUNT);
+ break;
+ case ANG_GRADIENT:
+ work_amount = RAD2GRA(DISPLAY_AMOUNT);
+ break;
+ case ANG_RADIAN:
+ work_amount = DISPLAY_AMOUNT;
+ break;
+ }
+
+ DISPLAY_AMOUNT = work_amount;
+
+ if (errno == EDOM || errno == ERANGE)
+ display_error = 1;
+ inverse = FALSE; // reset the inverse flag
+ }
+ }
+
+// Now a cheat to help the weird case of COS 90 degrees not being 0!!!
+
+ if (DISPLAY_AMOUNT < POS_ZERO && DISPLAY_AMOUNT > NEG_ZERO)
+ DISPLAY_AMOUNT=0;
+ refresh_display = 1;
+ last_input = OPERATION;
+ UpdateDisplay();
+
+}
+
+
+void QtCalculator::EnterPercent()
+{
+ eestate = false;
+ last_input = OPERATION;
+ percent_mode = 1;
+ EnterEqual();
+ percent_mode = 0;
+
+}
+
+void QtCalculator::EnterLogr()
+{
+
+ switch(kcalcdefaults.style){
+ case 2:
+ {
+ if ( !sheet_name.isEmpty() )
+ useData();
+
+ ComputeSum();
+ break;
+ }
+ case 1:{
+
+ if ( !sheet_name.isEmpty() )
+ useData();
+
+ if(!inverse){
+ eestate = false; // terminate ee input mode
+ stats.enterData(DISPLAY_AMOUNT);
+ last_input = OPERATION;
+ refresh_display = 1;
+ DISPLAY_AMOUNT = stats.count();
+ UpdateDisplay();
+ }
+ else{
+ inverse = false;
+ last_input = OPERATION;
+ refresh_display = 1;
+ stats.clearLast();
+ setStatusLabel("Last stat item erased");
+ DISPLAY_AMOUNT = stats.count();
+ UpdateDisplay();
+
+ }
+
+ break;
+ }
+ case 0:{
+
+ eestate = false;
+ last_input = OPERATION;
+
+ if (!inverse) {
+ if (DISPLAY_AMOUNT <= 0)
+ display_error = 1;
+ else
+ DISPLAY_AMOUNT = LOG_TEN(DISPLAY_AMOUNT);
+ refresh_display = 1;
+ UpdateDisplay();
+ } else if (inverse) {
+ DISPLAY_AMOUNT = POW(10, DISPLAY_AMOUNT);
+ refresh_display = 1;
+ inverse = FALSE;
+ UpdateDisplay();
+ }
+ break;
+ }
+ }
+}
+
+void QtCalculator::EnterLogn()
+{
+
+ switch(kcalcdefaults.style){
+ case 2:{
+
+ if ( !sheet_name.isEmpty() )
+ useData();
+
+ ComputeMul();
+
+ break;
+ }
+ case 1:{
+
+ if ( !sheet_name.isEmpty() )
+ useData();
+
+ if(!inverse){
+
+ stats.clearAll();
+ setStatusLabel(i18n("Stat mem cleared"));
+
+ }
+ else{
+ inverse = false;
+ UpdateDisplay();
+ }
+
+ break;
+ }
+ case 0:{
+ eestate = false;
+ last_input = OPERATION;
+ if (!inverse) {
+ if (DISPLAY_AMOUNT <= 0)
+ display_error = 1;
+ else
+ DISPLAY_AMOUNT = LOG(DISPLAY_AMOUNT);
+ refresh_display = 1;
+ UpdateDisplay();
+ } else if (inverse) {
+ DISPLAY_AMOUNT = EXP(DISPLAY_AMOUNT);
+ refresh_display = 1;
+ inverse =FALSE;
+ UpdateDisplay();
+ }
+ break;
+ }
+ }
+
+}
+
+
+void QtCalculator::base_selected(int number){
+
+ switch(number){
+ case 0:
+ SetHex();
+ break;
+ case 1:
+ SetDec();
+ break;
+ case 2:
+ SetOct();
+ break;
+ case 3:
+ SetBin();
+ break;
+ default: // we shouldn't ever end up here
+ SetDec();
+ }
+}
+
+
+void QtCalculator::angle_selected(int number){
+
+ switch(number){
+ case 0:
+ SetDeg();
+ break;
+ case 1:
+ SetRad();
+ break;
+ case 2:
+ SetGra();
+ break;
+ default: // we shouldn't ever end up here
+ SetRad();
+ }
+}
+
+void QtCalculator::SetInverse(){
+
+ inverse = ! inverse;
+ if (inverse){
+ statusINVLabel->setText("INV");
+ }
+ else{
+ statusINVLabel->setText("NORM");
+ }
+}
+
+
+void QtCalculator::SetDeg() {
+ angle_mode = ANG_DEGREE;
+}
+
+void QtCalculator::SetGra() {
+ angle_mode = ANG_GRADIENT;
+}
+
+void QtCalculator::SetRad() {
+ angle_mode = ANG_RADIAN;
+
+}
+
+void QtCalculator::SetHex() {
+ /*
+ * Set Hex Mode
+ */
+
+ current_base = NB_HEX;
+ display_size = BOH_SIZE;
+ decimal_point = 0;
+ input_limit = 8;
+
+ UpdateDisplay();
+}
+
+void QtCalculator::SetOct() {
+ /*
+ * Set Oct Mode
+ */
+
+ current_base = NB_OCTAL;
+ display_size = BOH_SIZE;
+ decimal_point = 0;
+ input_limit = 11;
+
+ UpdateDisplay();
+}
+
+void QtCalculator::SetBin() {
+ /*
+ * Set Bin Mode
+ */
+
+ current_base = NB_BINARY;
+ display_size = BOH_SIZE;
+ decimal_point = 0;
+ input_limit = 16;
+
+ UpdateDisplay();
+}
+
+void QtCalculator::SetDec()
+{
+ /*
+ * Set Dec Mode
+ */
+
+ current_base = NB_DECIMAL;
+ display_size = DEC_SIZE;
+ input_limit = 0;
+
+
+ UpdateDisplay();
+}
+
+
+void QtCalculator::EE()
+{
+ if(inverse){
+ DISPLAY_AMOUNT = pi;
+ inverse = FALSE;
+ UpdateDisplay();
+ }
+ else{
+ if(eestate == true)
+ eestate = false;
+ else{
+ eestate = true;
+ strcat(display_str,"e");
+ }
+
+ UpdateDisplay();
+ }
+
+}
+
+void QtCalculator::MR()
+{
+ eestate = false;
+ last_input = OPERATION;
+ DISPLAY_AMOUNT = memory_num;
+ refresh_display = 1;
+ UpdateDisplay();
+
+}
+
+void QtCalculator::Mplusminus()
+{
+
+ eestate = false;
+ EnterEqual();
+ if (!inverse)
+ memory_num += DISPLAY_AMOUNT;
+ else {
+ memory_num -= DISPLAY_AMOUNT;
+ inverse = FALSE;
+ }
+}
+
+void QtCalculator::MC()
+{
+
+ memory_num = 0;
+ refresh_display = 1;
+}
+
+void QtCalculator::EnterEqual()
+{
+ eestate = false;
+ last_input = OPERATION;
+ PushStack(&display_data);
+ refresh_display = 1;
+
+ /* if (UpdateStack(0))*/
+ UpdateStack(0);
+
+ UpdateDisplay();
+ precedence_base = 0;
+
+ CALCAMNT* number ;
+
+ if(temp_stack.count() > TEMP_STACK_SIZE){
+
+ number = temp_stack.getFirst();
+ temp_stack.removeFirst();
+
+ if(number)
+ free(number);
+ }
+
+ number = (CALCAMNT*) malloc(sizeof(CALCAMNT));
+ *number = DISPLAY_AMOUNT;
+
+ //printf("appending %Lg\n",*number);
+
+ temp_stack.append(number);
+
+
+}
+
+void QtCalculator::Clear(){
+
+ eestate = false;
+
+ input_count = 0;
+ decimal_point = 0;
+
+ if(last_input == OPERATION){
+ // printf("LAST_INPUT = OPERATION\n");
+ last_input = DIGIT;
+ PopStack();
+ }
+ else{
+ // printf("LAST_INPUT = DIGIT\n");
+ last_input = DIGIT;
+ }
+
+
+ if( display_error){
+ display_error = 0;
+ refresh_display = 0;
+ }
+
+ if (!refresh_display) {
+ DISPLAY_AMOUNT = 0L;
+ UpdateDisplay();
+ }
+
+}
+
+void QtCalculator::ClearAll()
+{
+
+ eestate = false;
+ // last_input = OPERATION;
+ last_input = DIGIT;
+ RefreshCalculator();
+ refresh_display = 1;
+
+}
+
+
+
+void QtCalculator::UpdateDisplay()
+{
+
+ // this needs to be rewritten based on whether we are currently
+ // inputting a number so that the period and the 0 after a period
+ // are correctly displayed.
+
+ CALCAMNT boh_work_d;
+ long boh_work = 0;
+ int str_size = 0;
+
+ if(eestate && (current_base == NB_DECIMAL)){
+
+ calc_display->setText(display_str);
+ return;
+ }
+
+ if (current_base != NB_DECIMAL) {
+ MODF(DISPLAY_AMOUNT, &boh_work_d);
+ if (boh_work_d < LONG_MIN || boh_work_d > ULONG_MAX)
+ display_error = 1;
+
+ /*
+ * We may be in that never-never land where boh numbers
+ * turn from positive to negative - if so then we do
+ * just that, allowing boh negative numbers to be entered
+ * as read (from dumps and the like!)
+ */
+ else if (boh_work_d > LONG_MAX) {
+ DISPLAY_AMOUNT =
+ LONG_MIN+(boh_work_d-LONG_MAX-1);
+ boh_work = (long)DISPLAY_AMOUNT;
+ }
+ else {
+ DISPLAY_AMOUNT = boh_work_d;
+ boh_work = (long) boh_work_d;
+ }
+ }
+
+ if (!display_error) {
+
+ if (current_base == NB_BINARY)
+ str_size = cvb(display_str,
+ boh_work,
+ BOH_SIZE);
+ else if (current_base == NB_OCTAL)
+ str_size = sprintf(display_str,
+ "%lo",
+ boh_work);
+ else if (current_base == NB_DECIMAL) {
+
+ if(!kcalcdefaults.fixed || last_input == DIGIT
+ || (DISPLAY_AMOUNT > 1.0e+16)){
+
+ // if I don't guard against the DISPLAY_AMOUNT being too large
+ // kcalc will segfault on larger amount. Such as from typing
+ // from 5*5*******
+
+ str_size = sprintf(display_str,
+
+#ifdef HAVE_LONG_DOUBLE
+ "%.*Lg", // was *Lg
+
+ kcalcdefaults.precision +1,
+#else
+ "%.*g",
+
+ kcalcdefaults.precision +1,
+#endif
+ DISPLAY_AMOUNT);
+ }
+ else{//fixed
+
+ str_size = sprintf(display_str,
+
+#ifdef HAVE_LONG_DOUBLE
+ "%.*Lf", // was *Lg
+
+ kcalcdefaults.fixedprecision ,
+#else
+ "%.*f",
+
+ kcalcdefaults.fixedprecision ,
+#endif
+ DISPLAY_AMOUNT);
+
+ }// fixed
+
+ if ( input_count > 0 && !strpbrk(display_str,"e") &&
+ last_input == DIGIT ) {
+
+#ifdef HAVE_LONG_DOUBLE
+ str_size = sprintf(display_str,
+ "%.*Lf",
+ (kcalcdefaults.precision +1 > input_count)?
+ input_count : kcalcdefaults.precision ,
+ DISPLAY_AMOUNT);
+#else
+ str_size = sprintf(display_str,
+ "%.*f",
+ (kcalcdefaults.precision +1 > input_count)?
+ input_count : kcalcdefaults.precision ,
+ DISPLAY_AMOUNT);
+#endif
+ }
+
+ }
+ else
+ if (current_base == NB_HEX)
+ str_size = sprintf(display_str,
+ "%lX",
+ boh_work);
+ else
+ display_error = 1;
+ }
+
+ if (display_error || str_size < 0) {
+ display_error = 1;
+ strcpy(display_str,"Error");
+ if(kcalcdefaults.beep)
+ KNotifyClient::beep();
+ }
+ calc_display->setText(display_str);
+
+
+ if (inverse){
+ statusINVLabel->setText("INV");
+ }
+ else{
+ statusINVLabel->setText("NORM");
+ }
+
+ if (hyp_mode){
+ statusHYPLabel->setText("HYP");
+ }
+ else{
+ statusHYPLabel->setText("");
+ }
+
+
+}
+
+int cvb(char *out_str, long amount, int max_digits)
+{
+ /*
+ * A routine that converts a long int to
+ * binary display format
+ */
+
+ char work_str[(sizeof(amount) * CHAR_BIT) + 1];
+ int work_char = 0,
+ lead_zero = 1,
+ lead_one = 1,
+ lead_one_count = 0,
+ work_size = sizeof(amount) * CHAR_BIT;
+ unsigned long bit_mask = (1 << ((sizeof(amount) * CHAR_BIT) - 1));
+
+ while (bit_mask) {
+
+ if (amount & bit_mask) {
+ if (lead_one)
+ lead_one_count++;
+ lead_zero = 0;
+ work_str[work_char++] = '1';
+ } else {
+ lead_one = 0;
+ if (!lead_zero)
+ work_str[work_char++] = '0';
+ }
+ bit_mask >>= 1;
+ }
+ if (!work_char)
+ work_str[work_char++] = '0';
+ work_str[work_char] = '\0';
+
+ if (work_char-lead_one_count < max_digits)
+ return strlen(strcpy(out_str,
+ &work_str[lead_one_count ?
+ work_size - max_digits :
+ 0]));
+ else
+ return -1;
+}
+
+int UpdateStack(int run_precedence)
+{
+ item_contents new_item, *top_item , *top_function;
+ CALCAMNT left_op =0.0 , right_op =0.0;
+ int op_function= 0, return_value = 0;
+
+ new_item.s_item_type = ITEM_AMOUNT;
+ while ((top_function = TopTypeStack(ITEM_FUNCTION)) &&
+ top_function->s_item_data.item_func_data.item_precedence >=
+ run_precedence) {
+
+ return_value = 1;
+
+ if ((top_item = PopStack())->s_item_type != ITEM_AMOUNT){
+ KMessageBox::error( 0, "Stack processing error - right_op");
+
+ }
+ right_op = top_item->s_item_data.item_amount;
+
+ if (!((top_item = PopStack()) &&
+ top_item->s_item_type == ITEM_FUNCTION)) {
+ KMessageBox::error( 0, "Stack processing error - function");
+
+ }
+ op_function =
+ top_item->s_item_data.item_func_data.item_function;
+
+ if (!((top_item = PopStack()) &&
+ top_item->s_item_type == ITEM_AMOUNT)) {
+ KMessageBox::error( 0, "Stack processing error - left_op");
+ }
+ left_op = top_item->s_item_data.item_amount;
+
+ new_item.s_item_data.item_amount =
+ (Arith_ops[op_function])(left_op, right_op);
+ PushStack(&new_item);
+
+ }
+ if (return_value &&
+ percent_mode &&
+ !display_error &&
+ Prcnt_ops[op_function] != NULL){
+ new_item.s_item_data.item_amount =
+ (Prcnt_ops[op_function])(left_op,
+ right_op,
+ new_item.s_item_data.item_amount);
+ PushStack(&new_item);
+ }
+ if (return_value)
+ DISPLAY_AMOUNT = new_item.s_item_data.item_amount;
+
+ return return_value;
+}
+
+int isoddint(CALCAMNT input)
+{
+ CALCAMNT dummy;
+ /*
+ * Routine to check if CALCAMNT is an Odd integer
+ */
+ return (MODF(input, &dummy) == 0.0 &&
+ MODF(input/2, &dummy) == 0.5);
+}
+
+CALCAMNT ExecOr(CALCAMNT left_op, CALCAMNT right_op)
+{
+ // printf("ExecOr\n");
+ CALCAMNT boh_work_d;
+ long boh_work_l, boh_work_r;
+
+ MODF(left_op, &boh_work_d);
+ if (FABS(boh_work_d) > LONG_MAX) {
+ display_error = 1;
+ return 0;
+ }
+ boh_work_l = (long int)boh_work_d;
+ MODF(right_op, &boh_work_d);
+ if (FABS(boh_work_d) > LONG_MAX) {
+ display_error = 1;
+ return 0;
+ }
+ boh_work_r = (long int) boh_work_d;
+ return (boh_work_l | boh_work_r);
+}
+
+CALCAMNT ExecXor(CALCAMNT left_op, CALCAMNT right_op)
+{
+ // printf("ExecXOr\n");
+ CALCAMNT boh_work_d;
+ long boh_work_l, boh_work_r;
+
+ MODF(left_op, &boh_work_d);
+ if (FABS(boh_work_d) > LONG_MAX) {
+ display_error = 1;
+ return 0;
+ }
+ boh_work_l = (long int) boh_work_d;
+ MODF(right_op, &boh_work_d);
+ if (FABS(boh_work_d) > LONG_MAX) {
+ display_error = 1;
+ return 0;
+ }
+ boh_work_r = (long int) boh_work_d;
+ return (boh_work_l ^ boh_work_r);
+}
+
+CALCAMNT ExecAnd(CALCAMNT left_op, CALCAMNT right_op)
+{
+ // printf("ExecAnd\n");
+ CALCAMNT boh_work_d;
+ long boh_work_l, boh_work_r;
+
+ MODF(left_op, &boh_work_d);
+ if (FABS(boh_work_d) > LONG_MAX) {
+ display_error = 1;
+ return 0;
+ }
+ boh_work_l = (long int ) boh_work_d;
+ MODF(right_op, &boh_work_d);
+ if (FABS(boh_work_d) > LONG_MAX) {
+ display_error = 1;
+ return 0;
+ }
+ boh_work_r = (long int ) boh_work_d;
+ return (boh_work_l & boh_work_r);
+}
+
+CALCAMNT ExecLsh(CALCAMNT left_op, CALCAMNT right_op)
+{
+ // printf("ExecLsh\n");
+ CALCAMNT boh_work_d;
+ long boh_work_l, boh_work_r;
+
+ MODF(left_op, &boh_work_d);
+ if (FABS(boh_work_d) > LONG_MAX) {
+ display_error = 1;
+ return 0;
+ }
+ boh_work_l = (long int) boh_work_d;
+ MODF(right_op, &boh_work_d);
+ if (FABS(boh_work_d) > LONG_MAX) {
+ display_error = 1;
+ return 0;
+ }
+ boh_work_r = (long int ) boh_work_d;
+ return (boh_work_l << boh_work_r);
+}
+
+CALCAMNT ExecRsh(CALCAMNT left_op, CALCAMNT right_op)
+{
+ // printf("ExecRsh\n");
+ CALCAMNT boh_work_d;
+ long boh_work_l, boh_work_r;
+
+ MODF(left_op, &boh_work_d);
+ if (FABS(boh_work_d) > LONG_MAX) {
+ display_error = 1;
+ return 0;
+ }
+ boh_work_l = (long int ) boh_work_d;
+ MODF(right_op, &boh_work_d);
+ if (FABS(boh_work_d) > LONG_MAX) {
+ display_error = 1;
+ return 0;
+ }
+ boh_work_r = ( long int ) boh_work_d;
+ return (boh_work_l >> boh_work_r);
+}
+
+CALCAMNT ExecAdd(CALCAMNT left_op, CALCAMNT right_op)
+{
+ // printf("ExecAdd\n");
+ return left_op + right_op;
+}
+
+CALCAMNT ExecSubtract(CALCAMNT left_op, CALCAMNT right_op)
+{
+ // printf("ExecSubtract\n");
+ return left_op - right_op;
+}
+
+CALCAMNT ExecMultiply(CALCAMNT left_op, CALCAMNT right_op)
+{
+ // printf("ExecMulti\n");
+ return left_op * right_op;
+}
+
+CALCAMNT ExecDivide(CALCAMNT left_op, CALCAMNT right_op)
+{
+ // printf("ExecDivide\n");
+ if (right_op == 0) {
+ display_error = 1;
+ return 0L;
+ } else
+ return left_op / right_op;
+}
+
+CALCAMNT ExecMod(CALCAMNT left_op, CALCAMNT right_op)
+{
+ // printf("ExecMod\n");
+ CALCAMNT temp =0.0;
+
+ if (right_op == 0) {
+ display_error = 1;
+ return 0L;
+ } else {
+
+ // x mod y should be the same as x mod -y, thus:
+ right_op = FABS(right_op);
+
+ temp = FMOD(left_op, right_op);
+
+ // let's make sure that -7 mod 3 = 2 and NOT -1.
+ // In other words we wand x mod 3 to be a _positive_ number
+ // that is 0,1 or 2.
+
+ if( temp < 0 ) temp = right_op + temp;
+ temp = FABS(temp);
+
+ return temp;
+ }
+}
+
+CALCAMNT ExecIntDiv(CALCAMNT left_op, CALCAMNT right_op)
+{
+ // printf("IndDiv\n");
+ if (right_op == 0) {
+ display_error = 1;
+ return 0L;
+ } else {
+ MODF(left_op / right_op, &left_op);
+ return left_op;
+ }
+}
+
+CALCAMNT ExecPower(CALCAMNT left_op, CALCAMNT right_op)
+{
+
+ // printf("ExecPowser %g left_op, %g right_op\n",left_op, right_op);
+ if (right_op == 0)
+ return 1L;
+ if (left_op < 0 && isoddint(1/right_op))
+ left_op = -1L * POW((-1L * left_op), right_op);
+ else
+ left_op = POW(left_op, right_op);
+ if (errno == EDOM || errno == ERANGE) {
+ display_error = 1;
+ return 0;
+ } else
+ return left_op;
+}
+
+CALCAMNT ExecPwrRoot(CALCAMNT left_op, CALCAMNT right_op)
+{
+
+ // printf("ExecPwrRoot %g left_op, %g right_op\n", left_op, right_op);
+ if (right_op == 0) {
+ display_error = 1;
+ return 0L;
+ }
+ if (left_op < 0 && isoddint(right_op))
+ left_op = -1L * POW((-1L * left_op), (1L)/right_op);
+ else
+ left_op = POW(left_op, (1L)/right_op);
+ if (errno == EDOM || errno == ERANGE) {
+ display_error = 1;
+ return 0;
+ }
+ else
+ return left_op;
+}
+
+
+CALCAMNT ExecAddSubP(CALCAMNT left_op, CALCAMNT right_op, CALCAMNT result)
+{
+ // printf("ExecAddsubP\n");
+ (void) left_op;
+
+ if (result == 0) {
+ display_error = 1;
+ return 0;
+ } else
+ return (result * 100L) / right_op;
+}
+
+CALCAMNT ExecMultiplyP(CALCAMNT left_op, CALCAMNT right_op, CALCAMNT result)
+{
+ // printf("ExecMultiplyP\n");
+ (void) left_op;
+ (void) right_op;
+
+ return (result / 100L);
+}
+
+CALCAMNT ExecDivideP(CALCAMNT left_op, CALCAMNT right_op, CALCAMNT result)
+{
+ // printf("ExecDivideP\n");
+ (void) left_op;
+ (void) right_op;
+
+ return (result * 100L);
+}
+
+CALCAMNT ExecPowerP(CALCAMNT left_op, CALCAMNT right_op, CALCAMNT result)
+{
+ // printf("ExecPowerP\n");
+ (void) result;
+ return ExecPower(left_op, (right_op / 100L));
+}
+
+CALCAMNT ExecPwrRootP(CALCAMNT left_op, CALCAMNT right_op, CALCAMNT result)
+{
+ // printf("ExePwrRootP\n");
+ (void) result;
+
+ if (right_op == 0) {
+ display_error = 1;
+ return 0;
+ } else
+ return ExecPower(left_op, (100L / right_op));
+}
+
+
+
+stack_ptr AllocStackItem (void) {
+
+ if (stack_next <= stack_last) {
+
+ process_stack[stack_next].prior_item = NULL;
+ process_stack[stack_next].prior_type = NULL;
+ return &process_stack[stack_next++];
+ }
+
+ KMessageBox::error( 0, "Stack Error !");
+ return &process_stack[stack_next];
+}
+
+void UnAllocStackItem (stack_ptr return_item) {
+
+ if (return_item != &process_stack[--stack_next]) {
+
+ KMessageBox::error( 0, "Stack Error !");
+ }
+
+}
+void PushStack(item_contents *add_item)
+{
+ /*
+ * Add an item to the stack
+ */
+
+ stack_ptr new_item = top_of_stack;
+
+ if (!(new_item &&
+ new_item->item_value.s_item_type == add_item->s_item_type)) {
+
+ new_item = AllocStackItem(); /* Get a new item */
+
+ /*
+ * Chain new item to existing stacks
+ */
+
+ new_item->prior_item = top_of_stack;
+ top_of_stack = new_item;
+ new_item->prior_type = top_type_stack[add_item->s_item_type];
+ top_type_stack[add_item->s_item_type] = new_item;
+ }
+
+ new_item->item_value = *add_item; /* assign contents*/
+
+}
+
+item_contents *PopStack(void)
+{
+ /*
+ * Remove and return the top item in the stack
+ */
+
+ static item_contents return_item;
+ item_contents *return_item_ptr = NULL;
+ stack_ptr return_stack_ptr;
+
+ if ((return_stack_ptr = top_of_stack)) {
+ return_item = top_of_stack->item_value;
+
+ top_type_stack[return_item.s_item_type]
+ = top_of_stack->prior_type;
+ top_of_stack = top_of_stack->prior_item;
+
+ UnAllocStackItem(return_stack_ptr);
+ return_item_ptr = &return_item;
+ }
+
+ return return_item_ptr;
+}
+
+item_contents *TopOfStack(void)
+{
+ /*
+ * Return the top item in the stack without removing
+ */
+
+ item_contents *return_item_ptr = NULL;
+
+ if (top_of_stack) {
+ return_item_ptr = &top_of_stack->item_value;
+ }
+
+ return return_item_ptr;
+}
+
+item_contents *TopTypeStack(item_type rqstd_type)
+{
+ /*
+ * Return the top item in the stack without removing
+ */
+
+ item_contents *return_item_ptr = NULL;
+
+ if (top_type_stack[rqstd_type]) {
+ return_item_ptr = &top_type_stack[rqstd_type]->item_value;
+ }
+
+ return return_item_ptr;
+}
+
+
+/*
+ * Stack storage management Data and Functions
+ */
+
+
+
+void InitStack (void) {
+
+ stack_next = 0;
+ stack_last = STACK_SIZE - 1;
+ top_of_stack = top_type_stack[0] = top_type_stack[1] = NULL;
+}
+
+
diff --git a/kspread/plugins/calculator/kcalctype.h b/kspread/plugins/calculator/kcalctype.h
new file mode 100644
index 000000000..b051f1079
--- /dev/null
+++ b/kspread/plugins/calculator/kcalctype.h
@@ -0,0 +1,104 @@
+/*
+ $Id: kcalctype.h 466447 2005-10-02 17:54:10Z zander $
+
+ KCalc, a scientific calculator for the X window system using the
+ Qt widget libraries, available at no cost at http://www.troll.no
+
+ Copyright (C) 1996 Bernd Johannes Wuebben
+ wuebben@math.cornell.edu
+
+ 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.
+
+*/
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#ifndef KCALC_TYPE_H
+#define KCALC_TYPE_H
+
+// The following for all the poor devels out there who don't have long double math.
+// I guess it's time to switch to LINUX guys .....
+
+// Undefine HAVE_LONG_DOUBLE for Beta 4 since RedHat 5.0 comes with a borken
+// glibc
+
+#ifdef HAVE_LONG_DOUBLE
+#undef HAVE_LONG_DOUBLE
+#endif
+
+#ifdef HAVE_LONG_DOUBLE
+
+/* should be detected by autoconf and defined in config.h
+ Be carefull when modifying these lines. HAVE_LONG_DOUBLE
+ is used all over kcalc's sources to determine whether
+ long double of double is the fundamental data type for kcalc*/
+
+
+
+#define CALCAMNT long double
+#else
+#define CALCAMNT double
+#endif
+
+
+#ifdef HAVE_LONG_DOUBLE
+#define FABS(X) fabsl(X)
+#define MODF(X,Y) modfl(X,Y)
+#define FMOD(X,Y) fmodl(X,Y)
+#define SIN(X) sinl(X)
+#define ASIN(X) asinl(X)
+#define SINH(X) sinhl(X)
+#define ASINH(X) asinhl(X)
+#define COS(X) cosl(X)
+#define COSH(X) coshl(X)
+#define ACOS(X) acosl(X)
+#define ACOSH(X) acoshl(X)
+#define TAN(X) tanl(X)
+#define TANH(X) tanhl(X)
+#define ATAN(X) atanl(X)
+#define ATANH(X) atanhl(X)
+#define EXP(X) expl(X)
+#define POW(X,Y) powl(X,Y)
+#define LOG(X) logl(X)
+#define LOG_TEN(X) log10l(X)
+#define SQRT(X) sqrtl(X)
+#else
+#define FABS(X) fabs(X)
+#define MODF(X,Y) modf(X,Y)
+#define FMOD(X,Y) fmod(X,Y)
+#define SIN(X) sin(X)
+#define ASIN(X) asin(X)
+#define SINH(X) sinh(X)
+#define ASINH(X) asinh(X)
+#define COS(X) cos(X)
+#define COSH(X) cosh(X)
+#define ACOS(X) acos(X)
+#define ACOSH(X) acosh(X)
+#define TAN(X) tan(X)
+#define TANH(X) tanh(X)
+#define ATAN(X) atan(X)
+#define ATANH(X) atanh(X)
+#define EXP(X) exp(X)
+#define POW(X,Y) pow(X,Y)
+#define LOG(X) log(X)
+#define LOG_TEN(X) log10(X)
+#define SQRT(X) sqrt(X)
+#endif
+
+
+#endif
diff --git a/kspread/plugins/calculator/kspreadcalc.rc b/kspread/plugins/calculator/kspreadcalc.rc
new file mode 100644
index 000000000..853429dc5
--- /dev/null
+++ b/kspread/plugins/calculator/kspreadcalc.rc
@@ -0,0 +1,8 @@
+<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
+<kpartgui name="KSpreadPluginCalculator" library="libkspreadcalc" version="2">
+<MenuBar>
+ <Menu name="tools"><text>&amp;Tools</text>
+ <Action name="kspreadcalc" />
+ </Menu>
+</MenuBar>
+</kpartgui>
diff --git a/kspread/plugins/calculator/main.cpp b/kspread/plugins/calculator/main.cpp
new file mode 100644
index 000000000..358875472
--- /dev/null
+++ b/kspread/plugins/calculator/main.cpp
@@ -0,0 +1,199 @@
+/* This file is part of the KDE project
+ Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+#include "main.h"
+#include "kcalc.h"
+#include "kspread_view.h"
+#include "kspread_events.h"
+#include "kspread_doc.h"
+#include "kspread_locale.h"
+#include "kspread_util.h"
+#include "kspread_map.h"
+#include "region.h"
+
+#include <kdebug.h>
+
+#include <stdio.h>
+
+using namespace KSpread;
+
+/***************************************************
+ *
+ * Factory
+ *
+ ***************************************************/
+
+K_EXPORT_COMPONENT_FACTORY( libkspreadcalc, CalcFactory )
+
+KInstance* CalcFactory::s_global = 0;
+
+CalcFactory::CalcFactory( QObject* parent, const char* name )
+ : KLibFactory( parent, name )
+{
+ s_global = new KInstance( "kspreadcalc" );
+}
+
+CalcFactory::~CalcFactory()
+{
+ delete s_global;
+}
+
+QObject* CalcFactory::createObject( QObject* parent, const char* name, const char* /*classname*/, const QStringList & )
+{
+ if ( !parent->inherits("KSpread::View") )
+ {
+ kdError() << "CalcFactory: KSpread::View expected. Parent is " << parent->className() << endl;
+ return 0;
+ }
+
+ QObject *obj = new Calculator( (View*)parent, name );
+ return obj;
+}
+
+KInstance* CalcFactory::global()
+{
+ return s_global;
+}
+
+/***************************************************
+ *
+ * Calculator
+ *
+ ***************************************************/
+
+Calculator::Calculator( View* parent, const char* name )
+ : KParts::Plugin( parent, name )
+{
+ m_calc = 0;
+ m_view = parent;
+
+ KGlobal::locale()->insertCatalogue("kspreadcalc_calc");
+ parent->installEventFilter( this );
+
+ (void)new KAction( i18n("Calculator"), SmallIcon("kcalc", CalcFactory::global()),
+ 0, this, SLOT( showCalculator() ), actionCollection(), "kspreadcalc");
+}
+
+void Calculator::showCalculator()
+{
+ if ( m_calc )
+ {
+ m_calc->show();
+ m_calc->raise();
+ return;
+ }
+
+ m_calc = new QtCalculator( this, (View*)parent() );
+ m_calc->setFixedSize( 9 + 100 + 9 + 233 + 9, 239);
+ m_calc->show();
+ m_calc->raise();
+}
+
+Calculator::~Calculator()
+{
+}
+
+bool Calculator::eventFilter( QObject*, QEvent* ev )
+{
+ if ( !m_calc )
+ return FALSE;
+
+ if ( SelectionChanged::test( ev ) )
+ {
+ SelectionChanged* event = (SelectionChanged*)ev;
+
+ // Selection cleared ?
+ if (!event->region().isValid())
+ return FALSE;
+
+ Sheet* sheet = m_view->doc()->map()->findSheet( event->sheet() );
+ if ( !sheet )
+ return FALSE;
+
+ // A single cell selected ?
+ if (event->region().isSingular())
+ {
+ Cell* cell = sheet->cellAt( event->rect().left(), event->rect().top(), false );
+ if ( !cell )
+ return FALSE;
+
+ double d;
+ if ( cell->isEmpty() )
+ d = 0;
+ else
+ d = cell->value().asFloat();
+ m_calc->setValue( d );
+
+ return FALSE;
+ }
+
+ // Multiple cells selected ?
+ m_calc->setData( event->rect(), event->sheet().latin1() );
+ QString str = util_rangeName( sheet, event->rect() );
+ m_calc->setLabel( str.latin1() );
+
+ return FALSE;
+ }
+
+ return FALSE;
+}
+
+/***************************************************
+ *
+ * QtCalculator
+ *
+ ***************************************************/
+
+/**
+ * This is a hook that makes the calculator to
+ * ask KSpread for the values of the selected cells.
+ */
+void QtCalculator::useData()
+{
+ stats.clearAll();
+
+ // How many cells ?
+ int len = ( sheet_range.right() - sheet_range.left() + 1 ) *
+ ( sheet_range.bottom() - sheet_range.top() + 1 );
+
+ double *v = new double[ len ];
+ int n = 0;
+ for( int x = sheet_range.left(); x <= sheet_range.right(); x++ )
+ for( int y = sheet_range.top(); y <= sheet_range.bottom(); y++ )
+ {
+ View* view = corba->view();
+ Sheet* sheet = view->doc()->map()->findSheet( sheet_name );
+ if ( !sheet )
+ return;
+ Cell* cell = sheet->cellAt( x, y, false );
+ if ( !cell )
+ return;
+
+ v[n++] = cell->value().asFloat();
+ }
+
+ for( int i = 0; i < n; i++ )
+ stats.enterData( v[i] );
+
+ delete []v;
+
+ sheet_name = QString::null;
+}
+
+#include "main.moc"
diff --git a/kspread/plugins/calculator/main.h b/kspread/plugins/calculator/main.h
new file mode 100644
index 000000000..08e9b5c9b
--- /dev/null
+++ b/kspread/plugins/calculator/main.h
@@ -0,0 +1,76 @@
+/* This file is part of the KDE project
+ Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library 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
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+*/
+
+#ifndef __my_app_h__
+#define __my_app_h__
+
+#include <qptrlist.h>
+#include <qstring.h>
+#include <qobject.h>
+
+#include <klibloader.h>
+#include <kparts/plugin.h>
+
+#include <koffice_export.h>
+
+class QtCalculator;
+class KInstance;
+
+namespace KSpread
+{
+class View;
+}
+
+class CalcFactory : public KLibFactory
+{
+ Q_OBJECT
+public:
+ CalcFactory( QObject* parent = 0, const char* name = 0 );
+ ~CalcFactory();
+
+ virtual QObject* createObject( QObject* parent = 0, const char* name = 0,
+ const char* classname = "QObject", const QStringList &args = QStringList() );
+
+ static KInstance* global();
+
+private:
+ static KInstance* s_global;
+};
+
+class KSPREAD_EXPORT Calculator : public KParts::Plugin
+{
+ Q_OBJECT
+public:
+ Calculator( View* parent, const char* name = 0 );
+ ~Calculator();
+
+ View* view() { return m_view; }
+
+protected slots:
+ void showCalculator();
+
+protected:
+ bool eventFilter( QObject*, QEvent* );
+
+private:
+ QtCalculator* m_calc;
+ View* m_view;
+};
+
+#endif
diff --git a/kspread/plugins/calculator/pics/Makefile.am b/kspread/plugins/calculator/pics/Makefile.am
new file mode 100644
index 000000000..44ac8aa51
--- /dev/null
+++ b/kspread/plugins/calculator/pics/Makefile.am
@@ -0,0 +1,4 @@
+
+KDE_ICON = kspreadcalc
+
+
diff --git a/kspread/plugins/calculator/pics/lo16-app-kspreadcalc.png b/kspread/plugins/calculator/pics/lo16-app-kspreadcalc.png
new file mode 100644
index 000000000..d9e79c08f
--- /dev/null
+++ b/kspread/plugins/calculator/pics/lo16-app-kspreadcalc.png
Binary files differ
diff --git a/kspread/plugins/calculator/pics/lo22-app-kspreadcalc.png b/kspread/plugins/calculator/pics/lo22-app-kspreadcalc.png
new file mode 100644
index 000000000..4e04dd845
--- /dev/null
+++ b/kspread/plugins/calculator/pics/lo22-app-kspreadcalc.png
Binary files differ
diff --git a/kspread/plugins/calculator/pics/lo32-app-kspreadcalc.png b/kspread/plugins/calculator/pics/lo32-app-kspreadcalc.png
new file mode 100644
index 000000000..f11b8261a
--- /dev/null
+++ b/kspread/plugins/calculator/pics/lo32-app-kspreadcalc.png
Binary files differ
diff --git a/kspread/plugins/calculator/stats.cpp b/kspread/plugins/calculator/stats.cpp
new file mode 100644
index 000000000..14ce24b96
--- /dev/null
+++ b/kspread/plugins/calculator/stats.cpp
@@ -0,0 +1,334 @@
+/*
+ $Id: stats.cpp 466447 2005-10-02 17:54:10Z zander $
+
+ KCalc, a scientific calculator for the X window system using the
+ Qt widget libraries, available at no cost at http://www.troll.no
+
+ Copyright (C) 1996 Bernd Johannes Wuebben
+ wuebben@math.cornell.edu
+
+ 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 "stats.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+KStats::KStats(){
+
+ error_flag = FALSE;
+ data.setAutoDelete(TRUE);
+
+}
+
+KStats::~KStats(){
+
+ data.clear();
+
+}
+
+void KStats::clearAll(){
+
+ data.clear();
+
+}
+
+void KStats::enterData(CALCAMNT _data){
+
+ CALCAMNT *newdata;
+ newdata = new CALCAMNT;
+ *newdata = _data;
+ data.append(newdata);
+
+#ifdef DEBUG_STATS
+ printf("Added %Lg\n",*newdata);
+ printf("count %d\n",data.count());
+#endif
+
+}
+
+
+void KStats::clearLast(){
+
+
+ data.removeLast();
+#ifdef DEBUG_STATS
+printf("count %d\n",data.count());
+#endif
+
+
+}
+
+CALCAMNT KStats::sum(){
+
+ CALCAMNT result = 0.0;
+ CALCAMNT *dp;
+ for ( dp=data.first(); dp != 0; dp=data.next() ){
+
+ result += *dp;
+
+ }
+
+#ifdef DEBUG_STATS
+ printf("Sum %Lg\n",result);
+#endif
+
+ return result;
+}
+
+CALCAMNT KStats::min()
+{
+ printf("MIIINNNN\n");
+
+ if ( data.count() == 0 )
+ return 0.0;
+
+ printf("1\n");
+
+ CALCAMNT result = *(data.first());
+ printf("result=%f\n",result);
+
+ CALCAMNT *dp = data.next();
+ for ( ; dp != 0; dp=data.next() )
+ if ( *dp < result )
+ result = *dp;
+
+ printf("Return\n");
+
+ return result;
+}
+
+CALCAMNT KStats::max()
+{
+ if ( data.count() == 0 )
+ return 0.0;
+
+ CALCAMNT result = *(data.first());
+ CALCAMNT *dp = data.next();
+ for ( ; dp != 0; dp=data.next() )
+ if ( *dp > result )
+ result = *dp;
+
+ return result;
+}
+
+CALCAMNT KStats::mul(){
+
+ CALCAMNT result = 1.0;
+ CALCAMNT *dp;
+ for ( dp=data.first(); dp != 0; dp=data.next() ){
+
+ result *= *dp;
+
+ }
+
+ return result;
+}
+
+CALCAMNT KStats::median(){
+
+ int index;
+ CALCAMNT result;
+ CALCAMNT *dp;
+ int bound = 0;
+
+ MyList list;
+
+ for ( dp=data.first(); dp != 0; dp=data.next() ){
+ list.inSort(dp);
+ }
+
+#ifdef DEBUG_STATS
+ for(int l = 0; l < (int)list.count();l++){
+
+ printf("Sorted %Lg\n",*list.at(l));
+
+ }
+#endif
+
+ bound = list.count();
+
+ if (bound == 0){
+ error_flag = TRUE;
+ return 0.0;
+ }
+
+ if ( bound == 1)
+ return *list.at(0);
+
+ if( bound % 2){ // odd
+
+ index = (bound - 1 ) / 2 + 1;
+ result = *list.at(index - 1 );
+ }
+ else { // even
+
+ index = bound / 2;
+ result = ((*list.at(index - 1)) + (*list.at(index)))/2;
+ }
+
+ return result;
+
+}
+
+
+
+CALCAMNT KStats::std_kernel(){
+
+ CALCAMNT result = 0.0;
+ CALCAMNT _mean;
+
+ _mean = mean();
+
+ CALCAMNT *dp;
+ for ( dp=data.first(); dp != 0; dp=data.next() ){
+
+ result += (*dp - _mean) * (*dp - _mean);
+
+ }
+
+#ifdef DEBUG_STATS
+ printf("std_kernel %Lg\n",result);
+#endif
+
+ return result;
+
+}
+
+
+CALCAMNT KStats::sum_of_squares(){
+
+ CALCAMNT result = 0.0;
+ CALCAMNT *dp;
+ for ( dp=data.first(); dp != 0; dp=data.next() ){
+
+ result += (*dp) * (*dp);
+
+ }
+
+#ifdef DEBUG_STATS
+ printf("Sum of Squares %Lg\n",result);
+#endif
+
+ return result;
+
+}
+
+CALCAMNT KStats::mean(){
+
+ CALCAMNT result = 0.0;
+
+ if(data.count() == 0){
+ error_flag = TRUE;
+ return 0.0;
+ }
+
+ result = sum()/data.count();
+
+#ifdef DEBUG_STATS
+ printf("mean: %Lg\n",result);
+#endif
+
+ return result;
+
+}
+
+CALCAMNT KStats::std(){
+
+ CALCAMNT result = 0.0;
+
+ if(data.count() == 0){
+ error_flag = TRUE;
+
+#ifdef DEBUG_STATS
+ printf("set stats error\n");
+#endif
+
+ return 0.0;
+ }
+
+ result = SQRT(std_kernel());
+
+#ifdef DEBUG_STATS
+ printf ("data.count %d\n",data.count());
+#endif
+
+ result = result/data.count();
+
+#ifdef DEBUG_STATS
+ printf("std: %Lg\n",result);
+#endif
+
+ return result;
+
+}
+
+CALCAMNT KStats::sample_std(){
+
+ CALCAMNT result = 0.0;
+
+ if(data.count() < 2 ){
+ error_flag = TRUE;
+ return 0.0;
+ }
+
+ result = SQRT(std_kernel());
+ result = result/(data.count() - 1);
+#ifdef DEBUG_STATS
+ printf("sample std: %Lg\n",result);
+#endif
+ return result;
+
+}
+
+int KStats::count(){
+
+ return data.count();
+
+}
+
+bool KStats::error(){
+
+ bool value;
+ value = error_flag;
+ error_flag = FALSE;
+
+ return value;
+
+}
+
+int MyList::compareItems(Item item_1, Item item_2){
+
+ CALCAMNT *item1;
+ CALCAMNT *item2;
+
+ item1 = (CALCAMNT*) item_1;
+ item2 = (CALCAMNT*) item_2;
+
+ if(*item1 > *item2)
+ return 1;
+
+ if(*item2 > *item1)
+ return -1;
+
+ return 0;
+
+}
+
+
+
diff --git a/kspread/plugins/calculator/stats.h b/kspread/plugins/calculator/stats.h
new file mode 100644
index 000000000..1f325a207
--- /dev/null
+++ b/kspread/plugins/calculator/stats.h
@@ -0,0 +1,80 @@
+/*
+ $Id: stats.h 466447 2005-10-02 17:54:10Z zander $
+
+ KCalc, a scientific calculator for the X window system using the
+ Qt widget libraries, available at no cost at http://www.troll.no
+
+ Copyright (C) 1996 Bernd Johannes Wuebben
+ wuebben@math.cornell.edu
+
+ 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.
+
+*/
+
+#ifndef KSTATS_H
+#define KSTATS_H
+
+#include <qptrlist.h>
+#include <math.h>
+#include "kcalctype.h"
+
+class KStats
+{
+
+public:
+
+ KStats();
+ ~KStats();
+
+public:
+
+ void clearAll();
+ void enterData(CALCAMNT data);
+ void clearLast();
+ CALCAMNT min();
+ CALCAMNT max();
+ CALCAMNT sum();
+ CALCAMNT mul();
+ CALCAMNT sum_of_squares();
+ CALCAMNT mean();
+ CALCAMNT median();
+ CALCAMNT std_kernel();
+ CALCAMNT std();
+ CALCAMNT sample_std();
+ int count();
+ bool error();
+
+private:
+
+ QPtrList<CALCAMNT> data;
+ bool error_flag;
+
+};
+
+class MyList : public QPtrList<CALCAMNT>
+{
+
+public:
+
+ MyList() : QPtrList<CALCAMNT>() {};
+
+protected:
+ int compareItems(Item item1,Item item2);
+};
+
+
+#endif /*KSTATS_H*/
+
diff --git a/kspread/plugins/calculator/uninstall.desktop b/kspread/plugins/calculator/uninstall.desktop
new file mode 100644
index 000000000..e30d053aa
--- /dev/null
+++ b/kspread/plugins/calculator/uninstall.desktop
@@ -0,0 +1,3 @@
+[Desktop Entry]
+Type=Service
+Hidden=true
diff --git a/kspread/plugins/calculator/version.h b/kspread/plugins/calculator/version.h
new file mode 100644
index 000000000..55742e65b
--- /dev/null
+++ b/kspread/plugins/calculator/version.h
@@ -0,0 +1 @@
+#define KCALCVERSION "1.2.6"
diff --git a/kspread/plugins/insertcalendar/Makefile.am b/kspread/plugins/insertcalendar/Makefile.am
new file mode 100644
index 000000000..f8b72e81b
--- /dev/null
+++ b/kspread/plugins/insertcalendar/Makefile.am
@@ -0,0 +1,26 @@
+INCLUDES = -I$(srcdir)/../../../kspread $(KOFFICE_INCLUDES) $(KOTEXT_INCLUDES) -I$(top_srcdir)/lib/koscript -I$(top_builddir)/lib/koscript $(all_includes)
+
+kde_module_LTLIBRARIES = libkspreadinsertcalendar.la
+
+libkspreadinsertcalendar_la_SOURCES = kspread_plugininsertcalendar.cc \
+ kspread_insertcalendardialogbase.ui \
+ kspread_insertcalendardialog.cc
+libkspreadinsertcalendar_la_LDFLAGS = $(all_libraries) -avoid-version -module -no-undefined
+libkspreadinsertcalendar_la_LIBADD = ../../libkspreadcommon.la
+
+METASOURCES = AUTO
+
+# Delete old unused file
+#install-data-local: uninstall.desktop
+# $(mkinstalldirs) $(DESTDIR)$(kde_servicesdir)
+# $(INSTALL_DATA) $(srcdir)/uninstall.desktop $(DESTDIR)$(kde_servicesdir)/kspreadinsertcalendar.desktop
+
+rc_DATA = insertcalendar.rc
+rcdir = $(kde_datadir)/kspread/kpartplugins
+
+
+
+SUBDIRS =
+
+messages: rc.cpp
+ $(XGETTEXT) rc.cpp *.cc -o $(podir)/kspreadinsertcalendar.pot
diff --git a/kspread/plugins/insertcalendar/insertcalendar.rc b/kspread/plugins/insertcalendar/insertcalendar.rc
new file mode 100644
index 000000000..c4968254c
--- /dev/null
+++ b/kspread/plugins/insertcalendar/insertcalendar.rc
@@ -0,0 +1,8 @@
+<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
+<kpartgui name="KSpreadPluginInsertCalendar" library="libkspreadinsertcalendar" version="1">
+<MenuBar>
+ <Menu name="tools"><text>&amp;Tools</text>
+ <Action name="kspreadinsertcalendar" />
+ </Menu>
+</MenuBar>
+</kpartgui>
diff --git a/kspread/plugins/insertcalendar/kspread_insertcalendardialog.cc b/kspread/plugins/insertcalendar/kspread_insertcalendardialog.cc
new file mode 100644
index 000000000..541783b8a
--- /dev/null
+++ b/kspread/plugins/insertcalendar/kspread_insertcalendardialog.cc
@@ -0,0 +1,150 @@
+ /***************************************************************************
+ * Copyright (C) 2005 by Raphael Langerhorst *
+ * raphael-langerhorst@gmx.at *
+ * *
+ * Permission is hereby granted, free of charge, to any person obtaining *
+ * a copy of this software and associated documentation files (the *
+ * "Software"), to deal in the Software without restriction, including *
+ * without limitation the rights to use, copy, modify, merge, publish, *
+ * distribute, sublicense, and/or sell copies of the Software, and to *
+ * permit persons to whom the Software is furnished to do so, subject to *
+ * the following conditions: *
+ * *
+ * The above copyright notice and this permission notice shall be *
+ * included in all copies or substantial portions of the Software. *
+ * *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, *
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*
+ * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR *
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, *
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *
+ * OTHER DEALINGS IN THE SOFTWARE. *
+ ***************************************************************************/
+
+#include <kspread_insertcalendardialog.h>
+
+#include <kdatepicker.h>
+#include <kdatewidget.h>
+#include <kdebug.h>
+
+#include <qpushbutton.h>
+
+namespace KSpread
+{
+
+InsertCalendarDialog::InsertCalendarDialog(QWidget* parent, const char* name)
+: InsertCalendarDialogBase(parent,name)
+{
+ this->m_datePicker = NULL;
+
+ //we start with a default calendar for the current month;
+
+ QDate first_day_in_month = QDate::currentDate();
+ first_day_in_month.setYMD(first_day_in_month.year(),first_day_in_month.month(),1);
+
+ QDate last_day_in_month(first_day_in_month.year(),first_day_in_month.month(),first_day_in_month.daysInMonth());
+
+ this->m_startDateWidget->setDate(first_day_in_month);
+ this->m_endDateWidget->setDate(last_day_in_month);
+
+ connect(this->m_selectStartDateButton,SIGNAL(clicked()),this,SLOT(showStartDatePicker()));
+ connect(this->m_selectEndDateButton,SIGNAL(clicked()),this,SLOT(showEndDatePicker()));
+
+ connect(this->m_insertButton,SIGNAL(clicked()),this,SLOT(accept()));
+ connect(this->m_cancelButton,SIGNAL(clicked()),this,SLOT(reject()));
+}
+
+InsertCalendarDialog::~InsertCalendarDialog()
+{
+}
+
+bool InsertCalendarDialog::buildDatePickerFrame()
+{
+ if (m_datePicker)
+ {
+ delete m_datePicker; //destroyed signal is connected to datePickerDeleted()
+ }
+
+ m_datePicker = new KDatePicker(NULL,"date picker");
+
+ Q_ASSERT(m_datePicker);
+
+ if (!m_datePicker)
+ return false;
+
+ connect(m_datePicker,SIGNAL(destroyed()),this,SLOT(datePickerDeleted()));
+
+ m_datePicker->setCloseButton(true);
+ m_datePicker->move(this->x()+this->width(),this->y());
+ m_datePicker->show();
+
+ return true;
+}
+
+void InsertCalendarDialog::datePickerDeleted()
+{
+ kdDebug() << "date picker deleted" << endl;
+ m_datePicker = NULL;
+}
+
+void InsertCalendarDialog::accept()
+{
+ if (m_datePicker)
+ m_datePicker->deleteLater();
+ kdDebug() << "insert calendar dialog accepted (insert button clicked)" << endl;
+ done(QDialog::Accepted);
+ emit insertCalendar(startDate(),endDate());
+}
+
+void InsertCalendarDialog::reject()
+{
+ if (m_datePicker)
+ m_datePicker->deleteLater();
+ kdDebug() << "insert calendar dialog rejected (cancel button clicked)" << endl;
+ done(QDialog::Rejected);
+}
+
+void InsertCalendarDialog::showStartDatePicker()
+{
+ if (buildDatePickerFrame())
+ {
+ connect(m_datePicker,SIGNAL(dateSelected(QDate)),this,SLOT(setStartDate(QDate)));
+ connect(m_datePicker,SIGNAL(dateEntered(QDate)),this,SLOT(setStartDate(QDate)));
+ m_datePicker->setDate(startDate());
+ }
+}
+
+void InsertCalendarDialog::showEndDatePicker()
+{
+ if (buildDatePickerFrame())
+ {
+ connect(m_datePicker,SIGNAL(dateSelected(QDate)),this,SLOT(setEndDate(QDate)));
+ connect(m_datePicker,SIGNAL(dateEntered(QDate)),this,SLOT(setEndDate(QDate)));
+ m_datePicker->setDate(endDate());
+ }
+}
+
+void InsertCalendarDialog::setStartDate(QDate date)
+{
+ this->m_startDateWidget->setDate(date);
+}
+
+void InsertCalendarDialog::setEndDate(QDate date)
+{
+ this->m_endDateWidget->setDate(date);
+}
+
+QDate InsertCalendarDialog::startDate() const
+{
+ return this->m_startDateWidget->date();
+}
+
+QDate InsertCalendarDialog::endDate() const
+{
+ return this->m_endDateWidget->date();
+}
+
+}
+
+#include "kspread_insertcalendardialog.moc"
diff --git a/kspread/plugins/insertcalendar/kspread_insertcalendardialog.h b/kspread/plugins/insertcalendar/kspread_insertcalendardialog.h
new file mode 100644
index 000000000..f52c2e93f
--- /dev/null
+++ b/kspread/plugins/insertcalendar/kspread_insertcalendardialog.h
@@ -0,0 +1,165 @@
+ /***************************************************************************
+ * Copyright (C) 2005 by Raphael Langerhorst *
+ * raphael-langerhorst@gmx.at *
+ * *
+ * Permission is hereby granted, free of charge, to any person obtaining *
+ * a copy of this software and associated documentation files (the *
+ * "Software"), to deal in the Software without restriction, including *
+ * without limitation the rights to use, copy, modify, merge, publish, *
+ * distribute, sublicense, and/or sell copies of the Software, and to *
+ * permit persons to whom the Software is furnished to do so, subject to *
+ * the following conditions: *
+ * *
+ * The above copyright notice and this permission notice shall be *
+ * included in all copies or substantial portions of the Software. *
+ * *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, *
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*
+ * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR *
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, *
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *
+ * OTHER DEALINGS IN THE SOFTWARE. *
+ ***************************************************************************/
+
+#ifndef KSPREAD_INSERTCALENDARDIALOG_H
+#define KSPREAD_INSERTCALENDARDIALOG_H
+
+#include <kspread_insertcalendardialogbase.h>
+#include <koffice_export.h>
+
+#include <qdatetime.h>
+
+class KDatePicker;
+
+namespace KSpread
+{
+
+class KSPREAD_EXPORT InsertCalendarDialog : public InsertCalendarDialogBase
+{
+ Q_OBJECT
+
+ private:
+
+ /**
+ * Stores a pointer to the currently active date picker frame.
+ * This is useful if we want to delete it manually.
+ * @see datePickerDeleted
+ */
+ KDatePicker* m_datePicker;
+
+ public:
+
+ /**
+ * Constructor, initializes functionality.
+ * The dates in the dialog initialize to a complete calendar for the
+ * current month.
+ */
+ InsertCalendarDialog(QWidget* parent = 0, const char* name = 0);
+
+ /**
+ * Virtual destructor.
+ */
+ virtual ~InsertCalendarDialog();
+
+ protected:
+
+ /**
+ * Creates a KDatePicker frame that is not connected
+ * to any date widget. Normally showStartDatePicker
+ * of showEndDatePicker use this method to build
+ * a generally usable date picker widget and connect
+ * it to the appropriate KDateWidget of the dialog.
+ *
+ * DatePickerDeleted is already connected!
+ */
+ bool buildDatePickerFrame();
+
+ protected slots:
+
+ /**
+ * Sets the currently active KDatePicker frame to NULL.
+ * It's expected that the date picker frame is deleted.
+ * @see m_datePicker
+ */
+ void datePickerDeleted();
+
+ /**
+ * This slot is reimplemented from QDialog and
+ * is connected to the insert button.
+ * It also emits a insertCalendar signal.
+ *
+ * The dialog is closed (not deleted) when
+ * this slot is called.
+ *
+ * @see insertCalendar, reject, QDialog::done
+ */
+ virtual void accept();
+
+ /**
+ * This slot is reimplemented from QDialog and
+ * is connected to the cancel button.
+ *
+ * The dialog is closed (not deleted) when
+ * this slot is called.
+ *
+ * @see accept, QDialog::done
+ */
+ virtual void reject();
+
+ public slots:
+
+ /**
+ * Shows a KDatePicker widget to select the start date.
+ * This slot is activated by the select date button.
+ */
+ void showStartDatePicker();
+
+ /**
+ * Shows a KDatePicker widget to select the end date.
+ * This slot is activated by the select date button.
+ */
+ void showEndDatePicker();
+
+ /**
+ * Slot for setting the start date in the KDateWidget.
+ * Normally this slot is activated by a KDatePicker widget.
+ */
+ void setStartDate(QDate);
+
+ /**
+ * Slot for setting the end date in the KDateWidget.
+ * Normally this slot is activated by a KDatePicker widget.
+ */
+ void setEndDate(QDate);
+
+ public:
+
+ // METHODS for getting data //
+
+ /**
+ * @returns the selected start date.
+ */
+ QDate startDate() const;
+
+ /**
+ * @returns the selected end date.
+ */
+ QDate endDate() const;
+
+ signals:
+
+ /**
+ * This signal is emitted when the dialog is
+ * accepted - that is, when the Insert button
+ * is clicked.
+ * This signal is meant to tell the
+ * insert calendar plugin to actually insert
+ * the calendar with the selected dates.
+ */
+ void insertCalendar(const QDate &from, const QDate &to);
+};
+
+}
+
+#endif
diff --git a/kspread/plugins/insertcalendar/kspread_insertcalendardialogbase.ui b/kspread/plugins/insertcalendar/kspread_insertcalendardialogbase.ui
new file mode 100644
index 000000000..9315c38cc
--- /dev/null
+++ b/kspread/plugins/insertcalendar/kspread_insertcalendardialogbase.ui
@@ -0,0 +1,207 @@
+<!DOCTYPE UI><UI version="3.2" stdsetdef="1">
+<class>KSpread::InsertCalendarDialogBase</class>
+<widget class="QDialog">
+ <property name="name">
+ <cstring>KSpread::InsertCalendarDialogBase</cstring>
+ </property>
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>429</width>
+ <height>237</height>
+ </rect>
+ </property>
+ <property name="caption">
+ <string>Insert Calendar</string>
+ </property>
+ <property name="toolTip" stdset="0">
+ <string></string>
+ </property>
+ <property name="whatsThis" stdset="0">
+ <string>The Insert Calendar dialog lets you set the dates of the calendar you want to insert. When you have choosen the desired dates, simply press the Insert button to insert the calendar into the spreadsheet, starting at the cell you have currently selected.</string>
+ <comment>This what's this help applies for the entire dialog.</comment>
+ </property>
+ <grid>
+ <property name="name">
+ <cstring>unnamed</cstring>
+ </property>
+ <widget class="QGroupBox" row="0" column="0" rowspan="1" colspan="2">
+ <property name="name">
+ <cstring>m_startDateGroupBox</cstring>
+ </property>
+ <property name="title">
+ <string>Start Date</string>
+ </property>
+ <property name="toolTip" stdset="0">
+ <string>Set the start date of the calendar you want to insert.</string>
+ </property>
+ <property name="whatsThis" stdset="0">
+ <string>Here you can choose on which date your calendar should start. The selected date will be the first day of the inserted calendar. You can also choose a date from a calendar dialog by pressing Select Date.</string>
+ </property>
+ <grid>
+ <property name="name">
+ <cstring>unnamed</cstring>
+ </property>
+ <widget class="KDateWidget" row="0" column="0">
+ <property name="name">
+ <cstring>m_startDateWidget</cstring>
+ </property>
+ <property name="sizePolicy">
+ <sizepolicy>
+ <hsizetype>5</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>1</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ </widget>
+ <widget class="QPushButton" row="0" column="1">
+ <property name="name">
+ <cstring>m_selectStartDateButton</cstring>
+ </property>
+ <property name="sizePolicy">
+ <sizepolicy>
+ <hsizetype>3</hsizetype>
+ <vsizetype>0</vsizetype>
+ <horstretch>1</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text">
+ <string>Date Picker</string>
+ </property>
+ <property name="toolTip" stdset="0">
+ <string>Use a graphical date picker to select a date.</string>
+ </property>
+ </widget>
+ </grid>
+ </widget>
+ <widget class="QGroupBox" row="1" column="0" rowspan="1" colspan="2">
+ <property name="name">
+ <cstring>m_endDateGroupBox</cstring>
+ </property>
+ <property name="frameShape">
+ <enum>GroupBoxPanel</enum>
+ </property>
+ <property name="frameShadow">
+ <enum>Sunken</enum>
+ </property>
+ <property name="title">
+ <string>End Date</string>
+ </property>
+ <property name="toolTip" stdset="0">
+ <string>Set the end date of the calendar you want to insert.</string>
+ </property>
+ <property name="whatsThis" stdset="0">
+ <string>Here you can choose on which date your calendar should end. The selected date will be the last day of the inserted calendar. You can also choose a date from a calendar dialog by pressing Select Date.</string>
+ </property>
+ <grid>
+ <property name="name">
+ <cstring>unnamed</cstring>
+ </property>
+ <widget class="KDateWidget" row="0" column="0">
+ <property name="name">
+ <cstring>m_endDateWidget</cstring>
+ </property>
+ <property name="sizePolicy">
+ <sizepolicy>
+ <hsizetype>5</hsizetype>
+ <vsizetype>5</vsizetype>
+ <horstretch>1</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ </widget>
+ <widget class="QPushButton" row="0" column="1">
+ <property name="name">
+ <cstring>m_selectEndDateButton</cstring>
+ </property>
+ <property name="sizePolicy">
+ <sizepolicy>
+ <hsizetype>3</hsizetype>
+ <vsizetype>0</vsizetype>
+ <horstretch>1</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text">
+ <string>Date Picker</string>
+ </property>
+ <property name="toolTip" stdset="0">
+ <string>Use a graphical date picker to select a date.</string>
+ </property>
+ </widget>
+ </grid>
+ </widget>
+ <spacer row="2" column="0" rowspan="1" colspan="2">
+ <property name="name">
+ <cstring>spacer1</cstring>
+ </property>
+ <property name="orientation">
+ <enum>Vertical</enum>
+ </property>
+ <property name="sizeType">
+ <enum>Expanding</enum>
+ </property>
+ <property name="sizeHint">
+ <size>
+ <width>400</width>
+ <height>19</height>
+ </size>
+ </property>
+ </spacer>
+ <widget class="QPushButton" row="3" column="0">
+ <property name="name">
+ <cstring>m_insertButton</cstring>
+ </property>
+ <property name="sizePolicy">
+ <sizepolicy>
+ <hsizetype>7</hsizetype>
+ <vsizetype>0</vsizetype>
+ <horstretch>1</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text">
+ <string>&amp;Insert</string>
+ </property>
+ <property name="toolTip" stdset="0">
+ <string>Insert the calendar at the currently selected cell.</string>
+ <comment>Tooltip for the insert button of the insert calendar plugin</comment>
+ </property>
+ <property name="whatsThis" stdset="0">
+ <string>A new calendar will be inserted starting at the currently selected cell.</string>
+ <comment>What's this for the insert button of the insert calendar plugin</comment>
+ </property>
+ </widget>
+ <widget class="QPushButton" row="3" column="1">
+ <property name="name">
+ <cstring>m_cancelButton</cstring>
+ </property>
+ <property name="sizePolicy">
+ <sizepolicy>
+ <hsizetype>7</hsizetype>
+ <vsizetype>0</vsizetype>
+ <horstretch>1</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="text">
+ <string>&amp;Cancel</string>
+ </property>
+ <property name="toolTip" stdset="0">
+ <string>Don't insert a calendar.</string>
+ </property>
+ <property name="whatsThis" stdset="0">
+ <string>Quits the dialog and does not insert a calendar. Use this to cancel this operation.</string>
+ </property>
+ </widget>
+ </grid>
+</widget>
+<layoutdefaults spacing="6" margin="11"/>
+<includehints>
+ <includehint>kdatewidget.h</includehint>
+ <includehint>kdatewidget.h</includehint>
+</includehints>
+</UI>
diff --git a/kspread/plugins/insertcalendar/kspread_plugininsertcalendar.cc b/kspread/plugins/insertcalendar/kspread_plugininsertcalendar.cc
new file mode 100644
index 000000000..56388af8f
--- /dev/null
+++ b/kspread/plugins/insertcalendar/kspread_plugininsertcalendar.cc
@@ -0,0 +1,281 @@
+/***************************************************************************
+ * Copyright (C) 2005 by Raphael Langerhorst *
+ * raphael-langerhorst@gmx.at *
+ * *
+ * Permission is hereby granted, free of charge, to any person obtaining *
+ * a copy of this software and associated documentation files (the *
+ * "Software"), to deal in the Software without restriction, including *
+ * without limitation the rights to use, copy, modify, merge, publish, *
+ * distribute, sublicense, and/or sell copies of the Software, and to *
+ * permit persons to whom the Software is furnished to do so, subject to *
+ * the following conditions: *
+ * *
+ * The above copyright notice and this permission notice shall be *
+ * included in all copies or substantial portions of the Software. *
+ * *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, *
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*
+ * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR *
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, *
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *
+ * OTHER DEALINGS IN THE SOFTWARE. *
+ ***************************************************************************/
+
+#include "kspread_plugininsertcalendar.h"
+
+#include "kspread_insertcalendardialog.h"
+
+#include "../../kspread_view.h"
+#include "../../kspread_doc.h"
+#include "../../selection.h"
+#include "../../kspread_sheet.h"
+
+#include <kcalendarsystem.h>
+#include <kcalendarsystemfactory.h>
+#include <kaboutdata.h>
+#include <kgenericfactory.h>
+#include <klocale.h>
+#include <kofficeversion.h>
+#include <kmessagebox.h>
+
+#include <qpoint.h>
+#include <qrect.h>
+
+namespace KSpread
+{
+
+// make the plugin available
+typedef KGenericFactory<PluginInsertCalendar> InsertCalendarFactory;
+K_EXPORT_COMPONENT_FACTORY( libkspreadinsertcalendar, InsertCalendarFactory("kspreadinsertcalendar"))
+
+
+PluginInsertCalendar::PluginInsertCalendar( QObject *parent, const char *name, const QStringList& /*args*/ )
+: Plugin(parent,name)
+{
+ this->m_kspreadView = NULL;
+ if (parent)
+ {
+ if (parent->inherits("KSpread::View"))
+ {
+ this->m_kspreadView = (View*)parent;
+ }
+ else
+ {
+ kdWarning() << "Parent does not inherit View!!!" << endl;
+ }
+ }
+ else
+ {
+ kdWarning() << "Plugin created without a parent!!!" << endl;
+ }
+
+
+ this->m_dialog = NULL;
+
+ (void)new KAction( i18n("Insert Calendar..."), KShortcut::null(),
+ this, SLOT( slotShowDialog() ), actionCollection(), "kspreadinsertcalendar");
+}
+
+PluginInsertCalendar::~PluginInsertCalendar()
+{
+}
+
+KAboutData* PluginInsertCalendar::createAboutData()
+{
+ KAboutData * aboutData = new KAboutData(
+ "kspreadinsertcalendar", //app name
+ I18N_NOOP("Insert Calendar"), //program name
+ KOFFICE_VERSION_STRING, //version
+ I18N_NOOP("KSpread Insert Calendar Plugin"), //short description
+ KAboutData::License_BSD, //license type
+ I18N_NOOP("(c) 2005, The KSpread Team"), //copyright
+ 0,//I18N_NOOP("The Insert Calendar plugin can be used in spreadsheets"), //text
+ "http://www.koffice.org/kspread/");
+ aboutData->addAuthor("Raphael Langerhorst", 0, "Raphael.Langerhorst@kdemail.net");
+
+ return aboutData;
+}
+
+void PluginInsertCalendar::slotShowDialog()
+{
+ kdDebug() << "slotShowDialog..." << endl;
+
+ if (this->m_dialog == NULL)
+ {
+ this->m_dialog = new InsertCalendarDialog();
+
+ Q_ASSERT(m_dialog);
+
+ connect(m_dialog,SIGNAL(insertCalendar(const QDate&, const QDate&)),
+ this,SLOT(slotInsertCalendar(const QDate&, const QDate&)));
+ }
+
+ //@todo if anyone knows a better way to get a background window to foreground, please change this...
+ m_dialog->hide();
+ m_dialog->show();
+
+}
+
+void PluginInsertCalendar::slotInsertCalendar(const QDate &start, const QDate &end)
+{
+ //@todo implement
+ kdDebug() << "slotInsert... still to be implemented" << endl;
+
+ Doc* document = m_kspreadView->doc();
+
+ if (!document)
+ {
+ KMessageBox::error(NULL,i18n("Can't insert calendar because no document is set!"),i18n("Error"));
+ return;
+ }
+
+ if (end < start)
+ {
+ KMessageBox::error(NULL,i18n("End date is before start date! Please make sure that end date comes after start date."),i18n("Error"));
+ return;
+ }
+
+ if (start.daysTo(end) > 3652)
+ {
+ KMessageBox::error(NULL,i18n("Calendars shouldn't be longer than 10 years. If you really need such long periods you need to split them up."),i18n("Error"));
+ return;
+ }
+
+ if (start == end)
+ {
+ if (KMessageBox::No == KMessageBox::warningYesNo(NULL,i18n("Start and end dates are equal! Only one day will be inserted, do you want to continue?"),i18n("Warning")))
+ return;
+ }
+
+ if (start.daysTo(end)> 366)
+ {
+ if (KMessageBox::No == KMessageBox::warningYesNo(NULL,i18n("Creating a calendar for a longer period than a year can take up a lot of space, do you want to continue?"),i18n("Warning")))
+ return;
+ }
+
+ Selection* selection_info = m_kspreadView->selectionInfo();
+
+ Q_ASSERT(selection_info);
+
+ QPoint selection = selection_info->selection().topLeft();
+
+ Sheet* sheet = m_kspreadView->activeSheet();
+
+ Q_ASSERT(sheet);
+
+ if (!sheet)
+ return;
+
+ //now let's check if the area is really empty...
+ //we use two columns per day and one column for the week number
+ int sizeX = 15;
+ //we use two rows per week, some additional space between months...
+ //so that should be ok, but can be improved of course
+ //@todo improve calendar size prediction!
+ int sizeY = 4 + (int)(0.5*(float)(start.daysTo(end)));
+
+ if (!sheet->areaIsEmpty(QRect(selection,QSize(sizeX,sizeY))))
+ {
+ if (KMessageBox::No == KMessageBox::warningYesNo(NULL,i18n("The area where the calendar is inserted is NOT empty, are you sure you want to continue, overwriting existing data? If you choose No the area that would be required for the desired calendar will be selected so you can see what data would be overwritten."),i18n("Warning")))
+ {
+ //select the area so the user knows what's in the way
+ selection_info->initialize(QRect(selection.x(),selection.y(),sizeX,sizeY));//,sheet);
+ return;
+ }
+ }
+
+ KCalendarSystem* cs = KCalendarSystemFactory::create();
+
+ Q_ASSERT(cs);
+
+ document->emitBeginOperation();
+
+ int row = selection.y();
+ int col = selection.x();
+ int colstart = col; //this is where we get back after each week
+ sheet->setText(row,colstart,i18n("Calendar from %1 to %2").arg(start.toString()).arg(end.toString()));
+
+ QDate current(start);
+// QDate previous(current);
+ bool yearheader = true;
+ bool monthheader = true;
+ bool weekheader = true;
+
+ //this loop creates the actual calendar
+ //@todo formatting of cells - each day occupies QRect(row,col,row,col+1)
+ while (current <= end)
+ {
+
+ //let's see if any header is required
+ if (cs->dayOfWeek(current)==1)
+ {
+ col=colstart;
+ row++;
+ weekheader=true;
+ }
+ if (cs->day(current)==1)
+ {
+ row+=2;
+ col=colstart + (cs->dayOfWeek(current)-1)*2;
+ monthheader=true;
+ weekheader=true;
+ if (cs->month(current)==1)
+ {
+ row++;
+ yearheader=true;
+ }
+ }
+
+ if (yearheader)
+ {
+ kdDebug() << "inserting year " + QString::number(current.year()) << endl;
+ sheet->setText(row,colstart+6,cs->yearString(current,false));
+
+ row+=2;
+ yearheader=false;
+ }
+ if (monthheader)
+ {
+ kdDebug() << "inserting month " + QString::number(current.month()) << endl;
+ sheet->setText(row,colstart+6,cs->monthName(current,false));
+ row+=2;
+ //we always have the week number in the first column
+ sheet->setText(row,colstart,i18n("week"));
+ for (int i=1; i<8; i++)
+ {
+ sheet->setText(row,colstart+(i-1)*2+1,cs->weekDayName(i));
+ }
+ row++;
+ monthheader=false;
+ }
+ if (weekheader)
+ {
+ sheet->setText(row,colstart,QString::number(cs->weekNumber(current)));
+ col++;
+ weekheader=false;
+
+ //if we are at the beginning of the month we might need an offset
+ if (cs->day(current)==1)
+ {
+ col=colstart + (cs->dayOfWeek(current)-1)*2 + 1;
+ }
+ }
+
+ sheet->setText(row,col,QString::number(cs->day(current)));
+ //go to the next date
+ //@todo isn't there a better way, like current++ or something??
+ QDate next = current.addDays(1);
+ current.setYMD(next.year(),next.month(),next.day());
+ col+=2;
+
+ }
+
+ document->emitEndOperation();
+
+ kdDebug() << "inserting calendar completed" << endl;
+}
+
+}
+
+#include "kspread_plugininsertcalendar.moc"
diff --git a/kspread/plugins/insertcalendar/kspread_plugininsertcalendar.h b/kspread/plugins/insertcalendar/kspread_plugininsertcalendar.h
new file mode 100644
index 000000000..9eb6060df
--- /dev/null
+++ b/kspread/plugins/insertcalendar/kspread_plugininsertcalendar.h
@@ -0,0 +1,113 @@
+/***************************************************************************
+ * Copyright (C) 2005 by Raphael Langerhorst *
+ * raphael-langerhorst@gmx.at *
+ * *
+ * Permission is hereby granted, free of charge, to any person obtaining *
+ * a copy of this software and associated documentation files (the *
+ * "Software"), to deal in the Software without restriction, including *
+ * without limitation the rights to use, copy, modify, merge, publish, *
+ * distribute, sublicense, and/or sell copies of the Software, and to *
+ * permit persons to whom the Software is furnished to do so, subject to *
+ * the following conditions: *
+ * *
+ * The above copyright notice and this permission notice shall be *
+ * included in all copies or substantial portions of the Software. *
+ * *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, *
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*
+ * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR *
+ * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, *
+ * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *
+ * OTHER DEALINGS IN THE SOFTWARE. *
+ ***************************************************************************/
+
+#ifndef KSPREAD_PLUGININSERTCALENDAR_H
+#define KSPREAD_PLUGININSERTCALENDAR_H
+
+#include <kparts/plugin.h>
+
+#include <koffice_export.h>
+
+#include <qdatetime.h>
+
+class KAboutData;
+
+namespace KSpread
+{
+class View;
+
+class InsertCalendarDialog;
+
+/**
+ * \class PluginInsertCalender kspread_plugininsertcalendar.h
+ * \brief Plugin for inserting a calendar into a spreadsheet.
+ * @author Raphael Langerhorst
+ *
+ * The plugin class for the Insert Calendar plugin.
+ * This plugin is designed to work in KSpread and
+ * makes it possible to insert calendars into
+ * the spreadsheet.
+ */
+class KSPREAD_EXPORT PluginInsertCalendar : public KParts::Plugin
+{
+ Q_OBJECT
+
+ protected:
+
+ /**
+ * This is the parent part of the plugin. It is used
+ * to access the spreadsheet and actually insert the
+ * calendar.
+ *
+ * It is set in the constructor.
+ */
+ View* m_kspreadView;
+
+ /**
+ * This is the dialog used to select the start/end dates
+ * of the calendar. It is the user interface of this
+ * plugin.
+ * @see InsertCalendarDialog, slotShowDialog, slotInsertCalendar
+ */
+ InsertCalendarDialog* m_dialog;
+
+ public:
+
+ /**
+ * Constructor. This constructor is usable with KGenericFactory.
+ */
+ PluginInsertCalendar( QObject *parent, const char *name, const QStringList& args );
+
+ /**
+ * Virtual destructor.
+ */
+ virtual ~PluginInsertCalendar();
+
+ public:
+
+ /**
+ * Creates about data for the Insert Calendar plugin.
+ */
+ static KAboutData* createAboutData();
+
+ public slots:
+
+ /**
+ * This is called from the plugin action, it shows a dialog that
+ * allows start and end date selection and various other
+ * options. The calendar can then be inserted into a spreadsheet.
+ */
+ void slotShowDialog();
+
+ /**
+ * This actually inserts the calendar. It reads the configuration
+ * from the insert calendar dialog and builds an calendar in the
+ * spreadsheet accordingly.
+ */
+ void slotInsertCalendar(const QDate &start, const QDate &end);
+};
+
+}
+
+#endif
diff --git a/kspread/plugins/scripting/Makefile.am b/kspread/plugins/scripting/Makefile.am
new file mode 100644
index 000000000..61f9561ab
--- /dev/null
+++ b/kspread/plugins/scripting/Makefile.am
@@ -0,0 +1,23 @@
+#SUBDIRS = kspreadcore samples
+SUBDIRS = kspreadcore scripts
+
+INCLUDES = -I$(top_builddir)/lib/kross/main \
+ -I$(top_srcdir)/kspread \
+ $(KROSS_INCLUDES) \
+ $(KOFFICE_INCLUDES) \
+ $(all_includes)
+
+kspreadscripting_la_SOURCES = scripting.cc
+
+kde_module_LTLIBRARIES = kspreadscripting.la
+noinst_HEADERS = scripting.h
+
+kspreadscripting_la_METASOURCES = AUTO
+
+kspreadscripting_la_LDFLAGS = $(all_libraries) -module $(KDE_PLUGIN)
+kspreadscripting_la_LIBADD = $(top_builddir)/kspread/libkspreadcommon.la $(top_builddir)/lib/kross/main/libkrossmain.la
+
+kde_services_DATA = kspreadscripting.desktop
+
+kspreadrcdir = $(kde_datadir)/kspread/kpartplugins
+kspreadrc_DATA = scripting.rc
diff --git a/kspread/plugins/scripting/kspreadcore/CMakeLists.txt b/kspread/plugins/scripting/kspreadcore/CMakeLists.txt
new file mode 100644
index 000000000..50cd0a738
--- /dev/null
+++ b/kspread/plugins/scripting/kspreadcore/CMakeLists.txt
@@ -0,0 +1,56 @@
+
+
+include_directories( ${CMAKE_SOURCE_DIR}/core ${CMAKE_SOURCE_DIR}/kspread ${KDE4_INCLUDES} )
+
+
+########### next target ###############
+
+set(krosskspreadcore_PART_SRCS
+ kspreadcoremodule.cpp
+ krs_doc.cpp
+ krs_sheet.cpp
+ krs_cell.cpp )
+
+kde4_automoc(${krosskspreadcore_PART_SRCS})
+
+kde4_add_plugin(krosskspreadcore ${krosskspreadcore_PART_SRCS})
+
+kde4_install_libtool_file( ${PLUGIN_INSTALL_DIR} krosskspreadcore )
+
+target_link_libraries(krosskspreadcore ${KDE4_KDECORE_LIBS} krossapi krossmain kspreadcommon )
+
+install(TARGETS krosskspreadcore DESTINATION ${PLUGIN_INSTALL_DIR})
+
+
+########### install files ###############
+
+
+
+
+
+
+#original Makefile.am contents follow:
+
+#INCLUDES = -I$(top_srcdir)/core \
+# -I$(top_srcdir)/kspread $(KOFFICECORE_INCLUDES) $(KSTORE_INCLUDES) \
+# $(KOFFICEUI_INCLUDES) $(KROSS_INCLUDES) \
+# $(all_includes)
+#
+#kde_module_LTLIBRARIES = krosskspreadcore.la
+#
+#krosskspreadcore_la_SOURCES = kspreadcoremodule.cpp krs_doc.cpp krs_sheet.cpp krs_cell.cpp krs_color.cpp
+#
+#krosskspreadcore_la_LDFLAGS = $(all_libraries) $(KDE_PLUGIN) -module
+#krosskspreadcore_la_LIBADD = \
+# $(LIB_QT) \
+# $(LIB_KDECORE) \
+# $(top_builddir)/lib/kross/api/libkrossapi.la \
+# $(top_builddir)/lib/kross/main/libkrossmain.la \
+# $(top_builddir)/kspread/libkspreadcommon.la
+#
+#METASOURCES = AUTO
+#SUBDIRS = .
+#
+#KDE_CXXFLAGS = $(USE_EXCEPTIONS)
+#
+#noinst_HEADERS = krs_doc.h krs_sheet.h krs_cell.h krs_color.h
diff --git a/kspread/plugins/scripting/kspreadcore/Makefile.am b/kspread/plugins/scripting/kspreadcore/Makefile.am
new file mode 100644
index 000000000..1538610dc
--- /dev/null
+++ b/kspread/plugins/scripting/kspreadcore/Makefile.am
@@ -0,0 +1,23 @@
+INCLUDES = -I$(top_srcdir)/core \
+ -I$(top_srcdir)/kspread $(KOFFICECORE_INCLUDES) $(KSTORE_INCLUDES) \
+ $(KOFFICEUI_INCLUDES) $(KROSS_INCLUDES) \
+ $(all_includes)
+
+kde_module_LTLIBRARIES = krosskspreadcore.la
+
+krosskspreadcore_la_SOURCES = kspreadcoremodule.cpp krs_doc.cpp krs_sheet.cpp krs_cell.cpp
+
+krosskspreadcore_la_LDFLAGS = $(all_libraries) $(KDE_PLUGIN) -module
+krosskspreadcore_la_LIBADD = \
+ $(LIB_QT) \
+ $(LIB_KDECORE) \
+ $(top_builddir)/lib/kross/api/libkrossapi.la \
+ $(top_builddir)/lib/kross/main/libkrossmain.la \
+ $(top_builddir)/kspread/libkspreadcommon.la
+
+METASOURCES = AUTO
+SUBDIRS = .
+
+KDE_CXXFLAGS = $(USE_EXCEPTIONS)
+
+noinst_HEADERS = krs_doc.h krs_sheet.h krs_cell.h
diff --git a/kspread/plugins/scripting/kspreadcore/krs_cell.cpp b/kspread/plugins/scripting/kspreadcore/krs_cell.cpp
new file mode 100644
index 000000000..cabf0c50f
--- /dev/null
+++ b/kspread/plugins/scripting/kspreadcore/krs_cell.cpp
@@ -0,0 +1,211 @@
+/*
+ * Copyright (c) 2005 Cyrille Berger <cberger@cberger.net>
+ * Copyright (c) 2006 Isaac Clerencia <isaac@warp.es>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Library 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 Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library 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 "krs_cell.h"
+
+#include "manipulator.h"
+#include "manipulator_data.h"
+
+namespace Kross { namespace KSpreadCore {
+
+Cell::Cell(KSpread::Cell* cell, KSpread::Sheet* sheet, uint col, uint row)
+ : Kross::Api::Class<Cell>("KSpreadCell"), m_cell(cell), m_sheet(sheet), m_col(col), m_row(row)
+{
+ this->addFunction0< Kross::Api::Variant >("value", this, &Cell::value);
+ this->addFunction1< Kross::Api::Variant, Kross::Api::Variant >("setValue", this, &Cell::setValue);
+
+ this->addFunction0< Kross::Api::Variant >("column", this, &Cell::column);
+ this->addFunction0< Kross::Api::Variant >("row", this, &Cell::row);
+
+ this->addFunction0< Cell >("previousCell", this, &Cell::previousCell);
+ this->addFunction0< Cell >("nextCell", this, &Cell::nextCell);
+ this->addFunction1< void, Cell >("setPreviousCell", this, &Cell::setPreviousCell);
+ this->addFunction1< void, Cell >("setNextCell", this, &Cell::setNextCell);
+
+ this->addFunction0< Kross::Api::Variant >("name", this, &Cell::name);
+ this->addFunction0< Kross::Api::Variant >("fullName", this, &Cell::fullName);
+
+ this->addFunction0< Kross::Api::Variant >("comment", this, &Cell::comment);
+ this->addFunction1< void, Kross::Api::Variant >("setComment", this, &Cell::setComment);
+
+ this->addFunction0< Kross::Api::Variant >("getFormatString", this, &Cell::getFormatString);
+ this->addFunction1< void, Kross::Api::Variant >("setFormatString", this, &Cell::setFormatString);
+
+ this->addFunction0< Kross::Api::Variant >("text", this, &Cell::text);
+ this->addFunction1< void, Kross::Api::Variant >("setText", this, &Cell::setText);
+
+ this->addFunction0< Kross::Api::Variant >("textColor", this, &Cell::textColor);
+ this->addFunction1< void, Kross::Api::Variant >("setTextColor", this, &Cell::setTextColor);
+ this->addFunction0< Kross::Api::Variant >("backgroundColor", this, &Cell::backgroundColor);
+ this->addFunction1< void, Kross::Api::Variant >("setBackgroundColor", this, &Cell::setBackgroundColor);
+}
+
+Cell::~Cell() {
+}
+
+const QString Cell::getClassName() const {
+ return "Kross::KSpreadCore::KSpreadCell";
+}
+
+QVariant Cell::toVariant(const KSpread::Value& value) const
+{
+ //Should we use following value-format enums here?
+ //fmt_None, fmt_Boolean, fmt_Number, fmt_Percent, fmt_Money, fmt_DateTime, fmt_Date, fmt_Time, fmt_String
+
+ switch(value.type()) {
+ case KSpread::Value::Empty:
+ return QVariant();
+ case KSpread::Value::Boolean:
+ return QVariant( value.asBoolean() );
+ case KSpread::Value::Integer:
+ return static_cast<Q_LLONG>(value.asInteger());
+ case KSpread::Value::Float:
+ return (float)value.asFloat();
+ case KSpread::Value::String:
+ return value.asString();
+ case KSpread::Value::Array: {
+ QValueList<QVariant> colarray;
+ for(uint j = 0; j < value.rows(); j++) {
+ QValueList<QVariant> rowarray;
+ for( uint i = 0; i < value.columns(); i++) {
+ KSpread::Value v = value.element(i,j);
+ rowarray.append( toVariant(v) );
+ }
+ colarray.append(rowarray);
+ }
+ return colarray;
+ } break;
+ case KSpread::Value::CellRange:
+ //FIXME: not yet used
+ return QVariant();
+ case KSpread::Value::Error:
+ return QVariant();
+ }
+ return QVariant();
+}
+
+QVariant Cell::value() const {
+ return toVariant( m_cell->value() );
+}
+
+bool Cell::setValue(const QVariant& value) {
+ KSpread::Value v = m_cell->value();
+ switch(value.type()) {
+ case QVariant::Bool: v.setValue( value.toBool() ); break;
+ case QVariant::ULongLong: v.setValue( (long)value.toLongLong() ); break;
+ case QVariant::Int: v.setValue( value.toInt() ); break;
+ case QVariant::Double: v.setValue( value.toDouble() ); break;
+ case QVariant::String: v.setValue( value.toString() ); break;
+ case QVariant::Date: v.setValue( value.toDate() ); break;
+ case QVariant::Time: v.setValue( value.toTime() ); break;
+ case QVariant::DateTime: v.setValue( value.toDateTime() ); break;
+ default: return false;
+ }
+ return true;
+}
+
+int Cell::column() const {
+ return m_cell->column();
+}
+
+int Cell::row() const {
+ return m_cell->row();
+}
+
+Cell* Cell::previousCell() const {
+ KSpread::Cell* c = m_cell->previousCell();
+ return c ? new Cell(c,c->sheet(),c->column(),c->row()) : 0;
+}
+
+Cell* Cell::nextCell() const {
+ KSpread::Cell* c = m_cell->nextCell();
+ return c ? new Cell(c,c->sheet(),c->column(),c->row()) : 0;
+}
+
+void Cell::setPreviousCell(Cell* c) {
+ return m_cell->setPreviousCell(c->m_cell);
+}
+
+void Cell::setNextCell(Cell* c) {
+ return m_cell->setNextCell(c->m_cell);
+}
+
+const QString Cell::name() const {
+ return m_cell->name();
+}
+
+const QString Cell::fullName() const {
+ return m_cell->fullName();
+}
+
+const QString Cell::comment() const {
+ return m_cell->format()->comment(m_col, m_row);
+}
+
+void Cell::setComment(const QString& c) {
+ return m_cell->format()->setComment(c);
+}
+
+const QString Cell::getFormatString() const {
+ return m_cell->format()->getFormatString(m_col, m_row);
+}
+
+void Cell::setFormatString(const QString& format) {
+ m_cell->format()->setFormatString(format);
+}
+
+const QString Cell::text() const {
+ return m_cell->text();
+}
+
+bool Cell::setText(const QString& text) {
+ KSpread::ProtectedCheck prot;
+ prot.setSheet (m_sheet);
+ prot.add (QPoint (m_col, m_row));
+ if (prot.check())
+ return false;
+
+ KSpread::DataManipulator *dm = new KSpread::DataManipulator ();
+ dm->setSheet (m_sheet);
+ dm->setValue (text);
+ dm->setParsing (true);
+ dm->add (QPoint (m_col, m_row));
+ dm->execute ();
+
+ return true;
+}
+
+const QString Cell::textColor() {
+ return m_cell->format()->textColor(m_col, m_row).name();
+}
+
+void Cell::setTextColor(const QString& textcolor) {
+ m_cell->format()->setTextColor( QColor(textcolor) );
+}
+
+const QString Cell::backgroundColor() {
+ return m_cell->format()->bgColor(m_col, m_row).name();
+}
+
+void Cell::setBackgroundColor(const QString& backgroundcolor) {
+ m_cell->format()->setBgColor( QColor(backgroundcolor) );
+}
+
+}
+}
diff --git a/kspread/plugins/scripting/kspreadcore/krs_cell.h b/kspread/plugins/scripting/kspreadcore/krs_cell.h
new file mode 100644
index 000000000..5f3f221db
--- /dev/null
+++ b/kspread/plugins/scripting/kspreadcore/krs_cell.h
@@ -0,0 +1,170 @@
+/*
+ * Copyright (c) 2005 Cyrille Berger <cberger@cberger.net>
+ * Copyright (c) 2006 Isaac Clerencia <isaac@warp.es>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Library 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 Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library 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.
+ */
+
+#ifndef KROSS_KSPREADCOREKRSCELL_H
+#define KROSS_KSPREADCOREKRSCELL_H
+
+#include <kspread_sheet.h>
+#include <kspread_cell.h>
+#include <kspread_value.h>
+
+#include <api/class.h>
+
+#include <qstring.h>
+#include <qcolor.h>
+
+namespace Kross { namespace KSpreadCore {
+
+/**
+ * For every cell in the spread sheet there is a Cell object.
+ *
+ * Cell contains format information and algorithm and it
+ * contains the calculation algorithm.
+ *
+ * Example (in Ruby) :
+ * @code
+ * doc = krosskspreadcore::get("KSpreadDocument")
+ * sheet = doc.currentSheet()
+ * cellA1 = sheet.cell(0, 0)
+ * cellA2 = sheet.cell(0, 1)
+ * cellA2.setValue( cellA1.value() )
+ * cellA2.setTextColor( "#ff0000" )
+ * @endcode
+ */
+class Cell : public Kross::Api::Class<Cell>
+{
+ public:
+ Cell(KSpread::Cell* cell, KSpread::Sheet* sheet, uint col, uint row);
+ virtual ~Cell();
+ virtual const QString getClassName() const;
+ private:
+
+ /**
+ * Return the value of the cell.
+ */
+ QVariant value() const;
+ /**
+ * Set the value the cell has.
+ */
+ bool setValue(const QVariant& value);
+
+ /**
+ * Return the column number.
+ */
+ int column() const;
+ /**
+ * Return the row number.
+ */
+ int row() const;
+
+ /**
+ * Return the previous cell if there is any.
+ */
+ Cell* previousCell() const;
+ /**
+ * Return the next cell if there is any.
+ */
+ Cell* nextCell() const;
+ /**
+ * Set the previous cell.
+ */
+ void setPreviousCell(Cell* c);
+ /**
+ * Set the next cell.
+ */
+ void setNextCell(Cell* c);
+
+ /**
+ * Returns the name of the cell. For example, the cell in first column
+ * and first row is "A1".
+ */
+ const QString name() const;
+ /**
+ * Returns the full name of the cell, i.e. including the worksheet name.
+ * Example: "Sheet1!A1"
+ */
+ const QString fullName() const;
+
+ /**
+ * Returns the comment for the cell.
+ */
+ const QString comment() const;
+ /**
+ * Set the comment for the cell.
+ */
+ void setComment(const QString& c);
+
+#if 0
+ bool isFormula() const;
+ Formula *formula () const;
+#endif
+
+ /**
+ * Returns the format of the cell, e.g. #.##0.00, dd/mmm/yyyy,...
+ */
+ const QString getFormatString() const;
+ /**
+ * Sets the format of the cell, e.g. #.##0.00, dd/mmm/yyyy,...
+ */
+ void setFormatString(const QString& format);
+
+ /**
+ * Return the text of the cell (the formula if there is one,
+ * the value otherwise). This could be a value (e.g. "14.03")
+ * or a formula (e.g. "=SUM(A1:A10)")
+ */
+ const QString text() const;
+ /**
+ * Set the text of the cell. the text
+ * will be handled as string
+ */
+ bool setText(const QString& text);
+
+ /**
+ * Return the textcolor as RGB-value in the format "#RRGGBB".
+ */
+ const QString textColor();
+ /**
+ * Set the textcolor to the RGB-value in the format "#RRGGBB"
+ * where each of R, G, and B is a single hex digit.
+ */
+ void setTextColor(const QString& textcolor);
+
+ /**
+ * Return the backgroundcolor as RGB-value in the format "#RRGGBB".
+ */
+ const QString backgroundColor();
+ /**
+ * Set the backgroundcolor to the RGB-value in the format "#RRGGBB"
+ * where each of R, G, and B is a single hex digit.
+ */
+ void setBackgroundColor(const QString& backgroundcolor);
+
+ private:
+ KSpread::Cell* m_cell;
+ KSpread::Sheet* m_sheet;
+ uint m_col, m_row;
+
+ QVariant toVariant(const KSpread::Value& value) const;
+};
+}
+}
+
+
+#endif
diff --git a/kspread/plugins/scripting/kspreadcore/krs_doc.cpp b/kspread/plugins/scripting/kspreadcore/krs_doc.cpp
new file mode 100644
index 000000000..37c87efdb
--- /dev/null
+++ b/kspread/plugins/scripting/kspreadcore/krs_doc.cpp
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) 2005 Cyrille Berger <cberger@cberger.net>
+ * Copyright (c) 2006 Isaac Clerencia <isaac@warp.es>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Library 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 Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library 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 "krs_doc.h"
+#include "krs_sheet.h"
+
+#include <kspread_map.h>
+#include <kspread_sheet.h>
+
+namespace Kross { namespace KSpreadCore {
+
+Doc::Doc(KSpread::Doc* doc)
+ : Kross::Api::Class<Doc>("KSpreadDocument"), m_doc(doc)
+{
+ this->addFunction0< Sheet >("currentSheet", this, &Doc::currentSheet);
+ this->addFunction1< Sheet, Kross::Api::Variant >("sheetByName", this, &Doc::sheetByName);
+ this->addFunction0< Kross::Api::Variant >("sheetNames", this, &Doc::sheetNames);
+
+ this->addFunction1< Kross::Api::Variant, Kross::Api::Variant >("addSheet", this, &Doc::addSheet);
+ this->addFunction1< Kross::Api::Variant, Kross::Api::Variant >("removeSheet", this, &Doc::removeSheet);
+
+ this->addFunction1< Kross::Api::Variant, Kross::Api::Variant >("loadNativeXML", this, &Doc::loadNativeXML);
+ this->addFunction0< Kross::Api::Variant >("saveNativeXML", this, &Doc::saveNativeXML);
+
+ this->addFunction1< Kross::Api::Variant, Kross::Api::Variant >("openUrl", this, &Doc::openUrl);
+ this->addFunction1< Kross::Api::Variant, Kross::Api::Variant >("saveUrl", this, &Doc::saveUrl);
+ this->addFunction1< Kross::Api::Variant, Kross::Api::Variant >("import", this, &Doc::import);
+ this->addFunction1< Kross::Api::Variant, Kross::Api::Variant >("exp0rt", this, &Doc::exp0rt);
+
+}
+
+Doc::~Doc() {
+
+}
+
+const QString Doc::getClassName() const {
+ return "Kross::KSpreadCore::Doc";
+}
+
+Sheet* Doc::currentSheet()
+{
+ return new Sheet(m_doc->displaySheet(), m_doc);
+}
+
+Sheet* Doc::sheetByName(const QString& name)
+{
+ QPtrListIterator<KSpread::Sheet> it (m_doc->map()->sheetList());
+ for( ; it.current(); ++it )
+ if(it.current()->sheetName() == name)
+ return new Sheet(it.current(), m_doc);
+ return 0;
+}
+
+QStringList Doc::sheetNames()
+{
+ QStringList names;
+ QPtrListIterator<KSpread::Sheet> it (m_doc->map()->sheetList());
+ for( ; it.current(); ++it )
+ names.append( it.current()->sheetName() );
+ return names;
+}
+
+bool Doc::addSheet(const QString& sheetname)
+{
+ KSpread::Sheet* sheet = m_doc->map()->createSheet();
+ if(sheet) {
+ if(! sheet->setSheetName(sheetname)) {
+ delete sheet;
+ return false;
+ }
+ m_doc->map()->addSheet(sheet);
+ return true;
+ }
+ return false;
+}
+
+bool Doc::removeSheet(const QString& sheetname)
+{
+ KSpread::Sheet* sheet = m_doc->map()->findSheet(sheetname);
+ if(sheet) {
+ m_doc->map()->takeSheet(sheet);
+ return true;
+ }
+ return false;
+}
+
+bool Doc::loadNativeXML(const QString& xml) {
+ QDomDocument doc;
+ if(! doc.setContent(xml, true))
+ return false;
+ return m_doc->loadXML(0, doc);
+}
+
+QString Doc::saveNativeXML() {
+ return m_doc->saveXML().toString(2);
+}
+
+bool Doc::openUrl(const QString& url)
+{
+ return m_doc->openURL(url);
+}
+
+bool Doc::saveUrl(const QString& url)
+{
+ return m_doc->saveAs(url);
+}
+
+bool Doc::import(const QString& url)
+{
+ return m_doc->import(url);
+}
+
+bool Doc::exp0rt(const QString& url)
+{
+ return m_doc->exp0rt(url);
+}
+
+}}
+
diff --git a/kspread/plugins/scripting/kspreadcore/krs_doc.h b/kspread/plugins/scripting/kspreadcore/krs_doc.h
new file mode 100644
index 000000000..28c69845f
--- /dev/null
+++ b/kspread/plugins/scripting/kspreadcore/krs_doc.h
@@ -0,0 +1,122 @@
+/*
+ * Copyright (c) 2005 Cyrille Berger <cberger@cberger.net>
+ * Copyright (c) 2006 Isaac Clerencia <isaac@warp.es>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Library 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 Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library 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.
+ */
+
+#ifndef KSPREAD_KROSS_KRS_DOC_H_
+#define KSPREAD_KROSS_KRS_DOC_H_
+
+#include <kspread_doc.h>
+
+#include <api/class.h>
+
+#include <qstring.h>
+#include <qstringlist.h>
+#include <qdom.h>
+
+namespace Kross { namespace KSpreadCore {
+
+class Sheet;
+
+/**
+ * The KSpread document.
+ *
+ * Example (in Ruby) :
+ * @code
+ * doc = krosskspreadcore::get("KSpreadDocument")
+ * @endcode
+ */
+class Doc : public Kross::Api::Class<Doc>
+{
+ public:
+ explicit Doc(KSpread::Doc* doc);
+ virtual ~Doc();
+ virtual const QString getClassName() const;
+ private:
+
+ /**
+ * This function returns the Sheet currently active in this
+ * document.
+ *
+ * Example (in Ruby) :
+ * @code
+ * doc = krosskspreadcore::get("KSpreadDocument")
+ * sheet = doc.currentSheet()
+ * @endcode
+ */
+ Sheet* currentSheet();
+
+ /**
+ * This function returns a Sheet by name.
+ *
+ * Example (in Ruby) :
+ * @code
+ * doc = krosskspreadcore::get("KSpreadDocument")
+ * sheet = doc.sheetByName("foosheet")
+ * @endcode
+ */
+ Sheet* sheetByName(const QString& name);
+
+ /**
+ * This function returns an array with the sheet names
+ *
+ * Example (in Ruby) :
+ * @code
+ * doc = krosskspreadcore::get("KSpreadDocument")
+ * sheetnames = doc.sheetNames()
+ * sheet = doc.sheetByName( sheetnames[0] )
+ * @endcode
+ */
+ QStringList sheetNames();
+
+ /**
+ * Add a new sheet named @p sheetname to the document.
+ */
+ bool addSheet(const QString& sheetname);
+
+ /**
+ * Remove the sheet named @p sheetname from the document.
+ */
+ bool removeSheet(const QString& sheetname);
+
+ /**
+ * Loads the native XML document.
+ */
+ bool loadNativeXML(const QString& xml);
+ /**
+ * Save and return the to a native document saved XML.
+ */
+ QString saveNativeXML();
+
+#if 0
+ bool loadOpenDocXML(const QString& xml);
+ QString saveOpenDocXML();
+#endif
+
+ bool openUrl(const QString& url);
+ bool saveUrl(const QString& url);
+ bool import(const QString& url);
+ bool exp0rt(const QString& url);
+
+ private:
+ KSpread::Doc* m_doc;
+};
+}
+}
+
+
+#endif
diff --git a/kspread/plugins/scripting/kspreadcore/krs_sheet.cpp b/kspread/plugins/scripting/kspreadcore/krs_sheet.cpp
new file mode 100644
index 000000000..694037ede
--- /dev/null
+++ b/kspread/plugins/scripting/kspreadcore/krs_sheet.cpp
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2005 Cyrille Berger <cberger@cberger.net>
+ * Copyright (c) 2006 Isaac Clerencia <isaac@warp.es>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Library 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 Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library 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 "krs_cell.h"
+#include "krs_sheet.h"
+#include "krs_doc.h"
+
+#include <kspread_doc.h>
+#include <kspread_sheet.h>
+#include <kspread_cell.h>
+#include <kspread_value.h>
+
+namespace Kross { namespace KSpreadCore {
+
+Sheet::Sheet(KSpread::Sheet* sheet, KSpread::Doc *doc) : Kross::Api::Class<Sheet>("KSpreadSheet"), m_sheet(sheet), m_doc(doc) {
+
+ this->addFunction0< Kross::Api::Variant >("name", this, &Sheet::name);
+ this->addFunction1< void, Kross::Api::Variant >("setName", this, &Sheet::setName);
+
+ this->addFunction0< Kross::Api::Variant >("maxColumn", this, &Sheet::maxColumn);
+ this->addFunction0< Kross::Api::Variant >("maxRow", this, &Sheet::maxRow);
+
+ this->addFunction0< Cell >("firstCell", this, &Sheet::firstCell);
+
+ this->addFunction2< Cell, Kross::Api::Variant, Kross::Api::Variant >("cell", this, &Sheet::cell);
+
+ this->addFunction1< Kross::Api::Variant, Kross::Api::Variant >("insertRow", this, &Sheet::insertRow);
+ this->addFunction1< Kross::Api::Variant, Kross::Api::Variant >("insertColumn", this, &Sheet::insertColumn);
+
+ this->addFunction1< void, Kross::Api::Variant >("removeRow", this, &Sheet::removeRow);
+ this->addFunction1< void, Kross::Api::Variant >("removeColumn", this, &Sheet::removeColumn);
+}
+
+Sheet::~Sheet() {
+}
+
+const QString Sheet::getClassName() const {
+ return "Kross::KSpreadCore::Sheet";
+}
+
+const QString Sheet::name() const
+{
+ return m_sheet->sheetName();
+}
+
+void Sheet::setName(const QString& name)
+{
+ m_sheet->setSheetName(name);
+}
+
+int Sheet::maxColumn() const {
+ return m_sheet->maxColumn();
+}
+
+int Sheet::maxRow() const {
+ return m_sheet->maxRow();
+}
+
+Cell* Sheet::firstCell() const {
+ KSpread::Cell* c = m_sheet->firstCell();
+ return c ? new Cell(c,c->sheet(),c->column(),c->row()) : 0;
+}
+
+Cell* Sheet::cell(uint col, uint row) {
+ uint c = QMAX(uint(1), col);
+ uint r = QMAX(uint(1), row);
+ return new Cell(m_sheet->cellAt(c,r),m_sheet,c,r);
+}
+
+bool Sheet::insertRow(uint row) {
+ return m_sheet->insertRow(row);
+}
+
+bool Sheet::insertColumn(uint col) {
+ return m_sheet->insertColumn(col);
+}
+
+void Sheet::removeRow(uint row) {
+ m_sheet->removeRow( QMAX(uint(1), row) );
+}
+
+void Sheet::removeColumn(uint col) {
+ m_sheet->removeColumn( QMAX(uint(1), col) );
+}
+
+}
+}
diff --git a/kspread/plugins/scripting/kspreadcore/krs_sheet.h b/kspread/plugins/scripting/kspreadcore/krs_sheet.h
new file mode 100644
index 000000000..a96e758ed
--- /dev/null
+++ b/kspread/plugins/scripting/kspreadcore/krs_sheet.h
@@ -0,0 +1,140 @@
+/*
+ * Copyright (c) 2005 Cyrille Berger <cberger@cberger.net>
+ * Copyright (c) 2006 Isaac Clerencia <isaac@warp.es>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Library 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 Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library 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.
+ */
+
+#ifndef KROSS_KSPREADCOREKRSSHEET_H
+#define KROSS_KSPREADCOREKRSSHEET_H
+
+#include <kspread_sheet.h>
+#include <kspread_value.h>
+
+#include <api/class.h>
+
+namespace Kross { namespace KSpreadCore {
+
+class Cell;
+
+/**
+ * A sheet in a document.
+ *
+ * Example (in Ruby) :
+ * @code
+ * doc = krosskspreadcore::get("KSpreadDocument")
+ * sheet1 = doc.sheetByName("Sheet1")
+ * sheet2 = doc.sheetByName("Sheet2")
+ * cell1 = sheet1.firstCell()
+ * while cell1
+ * colnr = cell1.column()
+ * rownr = cell1.row()
+ * cell2 = sheet2.cell(colnr, rownr)
+ * cell2.setValue( cell1.value() )
+ * cell1 = cell1.nextCell()
+ * end
+ * @endcode
+ */
+class Sheet : public Kross::Api::Class<Sheet>
+{
+ public:
+ Sheet(KSpread::Sheet* sheet, KSpread::Doc* doc = 0);
+ virtual ~Sheet();
+ virtual const QString getClassName() const;
+ private:
+
+ /**
+ * Return the name of the sheet.
+ */
+ const QString name() const;
+ /**
+ * Set the name of the sheet.
+ */
+ void setName(const QString& name);
+
+ /**
+ * Return the currently maximum defined number of columns.
+ */
+ int maxColumn() const;
+ /**
+ * Return the currently maximum defined number of rows.
+ */
+ int maxRow() const;
+
+ /**
+ * Return the first cell. Use the firstCell() and nextCell()
+ * methods as outlined in the example to iterate only through
+ * filled cells (aka cells with content).
+ *
+ * Example (in Python) :
+ * @code
+ * import krosskspreadcore
+ * doc = krosskspreadcore.get("KSpreadDocument")
+ * sheet = doc.currentSheet()
+ * cell = sheet.firstCell()
+ * while cell:
+ * print "Cell col=%s row=%s value=%s" % (cell.column(),cell.row(),cell.value())
+ * cell = cell.nextCell()
+ * @endcode
+ */
+ Cell* firstCell() const;
+
+ /**
+ * Return the given cell. The first parameter is the column-number
+ * while the second defines the rownumber. The first cell starts
+ * with 0,0. If you like to iterate over all cells that have content,
+ * use the firstCell() and nextCell() methods which is much faster
+ * cause empty cells are ignored.
+ *
+ * Example (in Python) :
+ * @code
+ * import krosskspreadcore
+ * doc = krosskspreadcore.get("KSpreadDocument")
+ * sheet = doc.currentSheet()
+ * for colnr in range( sheet.maxColumn() ):
+ * for rownr in range( sheet.maxRow() ):
+ * cell = sheet.cell(colnr, rownr)
+ * if cell.value() != None:
+ * print "Cell col=%s row=%s value=%s" % (colnr,rownr,cell.value())
+ * @endcode
+ */
+ Cell* cell(uint col, uint row);
+
+ /**
+ * Add a new row.
+ */
+ bool insertRow(uint row);
+ /**
+ * Add a new column.
+ */
+ bool insertColumn(uint col);
+
+ /**
+ * Remove a row.
+ */
+ void removeRow(uint row);
+ /**
+ * Remove a column.
+ */
+ void removeColumn(uint col);
+
+ private:
+ KSpread::Sheet* m_sheet;
+ KSpread::Doc* m_doc;
+};
+}
+}
+
+#endif
diff --git a/kspread/plugins/scripting/kspreadcore/kspreadcoremodule.cpp b/kspread/plugins/scripting/kspreadcore/kspreadcoremodule.cpp
new file mode 100644
index 000000000..acfd0b2bd
--- /dev/null
+++ b/kspread/plugins/scripting/kspreadcore/kspreadcoremodule.cpp
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2005 Cyrille Berger <cberger@cberger.net>
+ * Copyright (c) 2006 Isaac Clerencia <isaac@warp.es>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Library 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 Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library 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 "kspreadcoremodule.h"
+
+#include <kdebug.h>
+
+//#include <api/variant.h>
+#include <api/qtobject.h>
+#include <main/manager.h>
+
+#include "krs_doc.h"
+
+extern "C"
+{
+ /**
+ * Exported an loadable function as entry point to use
+ * the \a KexiAppModule.
+ */
+ Kross::Api::Object* init_module(Kross::Api::Manager* manager)
+ {
+ return new Kross::KSpreadCore::KSpreadCoreModule(manager);
+ }
+}
+
+
+using namespace Kross::KSpreadCore;
+
+KSpreadCoreModule::KSpreadCoreModule(Kross::Api::Manager* manager)
+ : Kross::Api::Module("kspreadcore") , m_manager(manager)
+{
+ QMap<QString, Object::Ptr> children = manager->getChildren();
+ kdDebug() << " there are " << children.size() << endl;
+ for(QMap<QString, Object::Ptr>::const_iterator it = children.begin(); it != children.end(); it++)
+ {
+ kdDebug() << it.key() << " " << it.data() << endl;
+ }
+
+ // Wrap doc
+ Kross::Api::Object::Ptr kspreaddocument = manager->getChild("KSpreadDocument");
+ if(! kspreaddocument) {
+ KSpread::Doc* doc = new KSpread::Doc();
+ addChild( new Kross::KSpreadCore::Doc(doc) );
+ }
+ else {
+ Kross::Api::QtObject* kspreaddocumentqt = dynamic_cast< Kross::Api::QtObject* >( kspreaddocument.data() );
+ if(kspreaddocumentqt) {
+ KSpread::Doc* document = dynamic_cast< ::KSpread::Doc* >( kspreaddocumentqt->getObject() );
+ if(document) {
+ addChild( new Doc(document) );
+ } else {
+ throw Kross::Api::Exception::Ptr( new Kross::Api::Exception("There was no 'KSpreadDocument' published.") );
+ }
+ }
+ }
+}
+
+KSpreadCoreModule::~KSpreadCoreModule()
+{
+}
+
+
+const QString KSpreadCoreModule::getClassName() const
+{
+ return "Kross::KSpreadCore::KSpreadCoreModule";
+}
diff --git a/kspread/plugins/scripting/kspreadcore/kspreadcoremodule.h b/kspread/plugins/scripting/kspreadcore/kspreadcoremodule.h
new file mode 100644
index 000000000..ffc998cc1
--- /dev/null
+++ b/kspread/plugins/scripting/kspreadcore/kspreadcoremodule.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2005 Cyrille Berger <cberger@cberger.net>
+ * Copyright (c) 2006 Isaac Clerencia <isaac@warp.es>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Library 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 Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library 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.
+ */
+
+#ifndef KSPREAD_KROSS_KSPREADCOREMODULE_H
+#define KSPREAD_KROSS_KSPREADCOREMODULE_H
+
+#include <qstring.h>
+#include <qvariant.h>
+
+#define KROSS_MAIN_EXPORT KDE_EXPORT
+
+#include <api/module.h>
+#include <api/event.h>
+
+namespace Kross { namespace Api {
+ class Manager;
+}}
+
+namespace Kross { namespace KSpreadCore {
+
+ /**
+ * The KSpreadCoreModule class implements a Kross::Api::Module to
+ * provide access to the KSpread functionality.
+ *
+ * Example (in Ruby) :
+ * @code
+ * doc = krosskspreadcore::get("KSpreadDocument")
+ * sheet = doc.currentSheet()
+ * cell = sheet.cell(0, 0)
+ * cell.setValue("Hello World")
+ * @endcode
+ */
+ class KSpreadCoreModule : public Kross::Api::Module
+ {
+ public:
+ KSpreadCoreModule(Kross::Api::Manager* manager);
+ virtual ~KSpreadCoreModule();
+ virtual const QString getClassName() const;
+ //virtual Kross::Api::Object::Ptr call(const QString& name, Kross::Api::List::Ptr arguments);
+ private:
+
+#if 0
+ /**
+ * This function return a new Color with the given RGB triplet
+ * It takes three arguments :
+ * - red color (0 to 255)
+ * - blue color (0 to 255)
+ * - green color (0 to 255)
+ *
+ * For example (in ruby) :
+ * @code
+ * Krosskritacore::newRGBColor(255,0,0) # create a red color
+ * Krosskritacore::newRGBColor(255,255,255) # create a white color
+ * @endcode
+ */
+ Kross::Api::Object::Ptr newRGBColor(Kross::Api::List::Ptr);
+#endif
+
+ private:
+ Kross::Api::Manager* m_manager;
+ };
+
+}}
+
+#endif
+
diff --git a/kspread/plugins/scripting/kspreadscripting.desktop b/kspread/plugins/scripting/kspreadscripting.desktop
new file mode 100644
index 000000000..2a22f10b1
--- /dev/null
+++ b/kspread/plugins/scripting/kspreadscripting.desktop
@@ -0,0 +1,80 @@
+[Desktop Entry]
+Name=Scripting plugin
+Name[bg]=Приставка за скриптове
+Name[ca]=Connector de seqüenciació
+Name[da]=Scriptplugin
+Name[de]=Skripting-Modul
+Name[el]=Πρόσθετο γραφής σεναρίων
+Name[eo]=Skriptad-kromaĵo
+Name[es]=Complemento para guiones
+Name[et]=Skriptiplugin
+Name[fa]=وصلۀ دست‌نوشته
+Name[fr]=Module de scriptage
+Name[fy]=Skriptplugin
+Name[ga]=Breiseán scriptithe
+Name[gl]=Plugin de programación
+Name[he]=תוסף לתסריטים
+Name[hu]=Szkript modul
+Name[is]=Skriftu íforrit
+Name[it]=Plugin di scripting
+Name[ja]=スクリプトプラグイン
+Name[km]=កម្មវិធី​ជំនួយ​សម្រាប់​ស្គ្រីប
+Name[nb]=Programtillegg for skripting
+Name[nds]=Skriptmoduul
+Name[ne]=प्लगइन स्क्रिप्ट गर्दै
+Name[nl]=Scriptplugin
+Name[pl]=Wtyczka obsługi języków skryptowych
+Name[pt]='Plugin' de programação
+Name[pt_BR]=Plugin de programação
+Name[ru]=Модуль поддержки сценариев
+Name[sk]=Modul pre skripty
+Name[sl]=Vstavek za skripte
+Name[sr]=Прикључак за скриптовање
+Name[sr@Latn]=Priključak za skriptovanje
+Name[sv]=Skriptinsticksprogram
+Name[uk]=Втулок для скриптів
+Name[uz]=Skriptlash plagini
+Name[uz@cyrillic]=Скриптлаш плагини
+Name[zh_CN]=脚本插件
+Name[zh_TW]=命令稿外掛程式
+Comment=Allow execution of scripts
+Comment[bg]=Изпълнение на скриптове
+Comment[ca]=Permet l'execució de seqüències
+Comment[da]=Tillad kørsel af script
+Comment[de]=Ermöglicht das Ausführen von Skripten
+Comment[el]=Επιτρέπει την εκτέλεση σεναρίων
+Comment[eo]=Permesi ruligon de skriptoj
+Comment[es]=Permite la ejecución de guiones
+Comment[et]=Võimaldab skriptide käivitamist
+Comment[fa]=اجازۀ اجرای دست‌نوشته‌ها
+Comment[fr]=Permet d'exécuter des scripts
+Comment[fy]=Hjirmei kinne skripts útfierd wurde
+Comment[gl]=Permite executar guións
+Comment[he]=אפשרות להרצת תסריטים
+Comment[hu]=Lehetővé teszi szkriptek végrehajtását
+Comment[is]=Leyfa að skriftur séu keyrðar
+Comment[it]=Permette di eseguire script
+Comment[ja]=スクリプトの実行を可能にします
+Comment[km]=អនុញ្ញាត​ឲ្យ​ប្រតិបត្តិ​ស្គ្រីប
+Comment[lv]=Atļaut skriptu izpildi
+Comment[nb]=Tillater skriptkjøring
+Comment[nds]=Skripten utföhren
+Comment[ne]=स्क्रिप्टको कार्यान्वयनलाई अनुमति दिनुहोस्
+Comment[nl]=Hiermee kunnen scripts uitgevoerd worden
+Comment[pl]=Zezwala na wykonywanie skryptów
+Comment[pt]=Permitir executar programas ou 'scripts'
+Comment[pt_BR]=Permitir executar programas ou 'scripts'
+Comment[ru]=Возможность выполнения сценариев
+Comment[sk]=Povoliť vykonávanie skriptov
+Comment[sl]=Dovoli izvedbo skriptov
+Comment[sr]=Омогући извршавање скрипти
+Comment[sr@Latn]=Omogući izvršavanje skripti
+Comment[sv]=Tillåt körning av skript
+Comment[uk]=Дає змогу виконувати скрипти
+Comment[uz]=Skriptlarni ishga tushirishga ruxsat berish
+Comment[uz@cyrillic]=Скриптларни ишга туширишга рухсат бериш
+Comment[zh_CN]=允许执行脚本
+Comment[zh_TW]=允許執行命令稿
+Type=Service
+X-KDE-Library=kspreadscripting
+X-KDE-Version=1
diff --git a/kspread/plugins/scripting/scripting.cc b/kspread/plugins/scripting/scripting.cc
new file mode 100644
index 000000000..96cd1bafe
--- /dev/null
+++ b/kspread/plugins/scripting/scripting.cc
@@ -0,0 +1,84 @@
+/*
+ * This file is part of the KSpread project
+ *
+ * Copyright (c) 2005 Cyrille Berger <cberger@cberger.net>
+ * Copyright (c) 2006 Isaac Clerencia <isaac@warp.es>
+ *
+ * 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 "scripting.h"
+
+#include <qapplication.h>
+
+#include <kdebug.h>
+#include <kgenericfactory.h>
+#include <kstandarddirs.h>
+
+#define KROSS_MAIN_EXPORT KDE_EXPORT
+#include <main/manager.h>
+#include <main/scriptguiclient.h>
+#include <main/wdgscriptsmanager.h>
+
+#include <kspread_doc.h>
+#include <kspread_view.h>
+
+typedef KGenericFactory<Scripting> KSpreadScriptingFactory;
+K_EXPORT_COMPONENT_FACTORY( kspreadscripting, KSpreadScriptingFactory( "kspreadscripting" ) )
+
+Scripting::Scripting(QObject *parent, const char *name, const QStringList &)
+ : KParts::Plugin(parent, name)
+{
+ setInstance(KSpreadScriptingFactory::instance());
+
+ kdDebug() << "Scripting plugin. Class: "
+ << metaObject()->className()
+ << ", Parent: "
+ << parent->metaObject()->className()
+ << "\n";
+
+ if ( parent->inherits("KSpread::View") )
+ {
+ setInstance(Scripting::instance());
+ m_view = (KSpread::View*) parent;
+ m_scriptguiclient = new Kross::Api::ScriptGUIClient( m_view, m_view );
+// m_scriptguiclient ->setXMLFile(locate("data","kspreadplugins/scripting.rc"), true);
+ kdDebug() << "Setup actions for scripting !" << endl;
+
+ setXMLFile(locate("data","kspread/kpartplugins/scripting.rc"), true);
+
+ new KAction(i18n("Execute Script File..."), 0, 0, m_scriptguiclient, SLOT(executeScriptFile()), actionCollection(), "executescriptfile");
+ new KAction(i18n("Script Manager..."), 0, 0, m_scriptguiclient, SLOT(showScriptManager()), actionCollection(), "configurescripts");
+
+ KAction* scriptmenuaction = m_scriptguiclient->action("installedscripts");
+ actionCollection()->insert(scriptmenuaction);
+
+ connect(m_scriptguiclient, SIGNAL(executionFinished( const Kross::Api::ScriptAction* )), this, SLOT(executionFinished(const Kross::Api::ScriptAction*)));
+
+ Kross::Api::Manager::scriptManager()->addQObject(m_view->doc(), "KSpreadDocument");
+ Kross::Api::Manager::scriptManager()->addQObject(m_view, "KSpreadView");
+ }
+
+}
+
+Scripting::~Scripting()
+{
+}
+
+void Scripting::executionFinished(const Kross::Api::ScriptAction*)
+{
+ QApplication::restoreOverrideCursor();
+}
+
+#include "scripting.moc"
diff --git a/kspread/plugins/scripting/scripting.h b/kspread/plugins/scripting/scripting.h
new file mode 100644
index 000000000..1d08bd9fe
--- /dev/null
+++ b/kspread/plugins/scripting/scripting.h
@@ -0,0 +1,49 @@
+/*
+ * This file is part of KSpread
+ *
+ * Copyright (c) 2005 Cyrille Berger <cberger@cberger.net>
+ * Copyright (c) 2006 ISaac Clerencia <isaac@warp.es>
+ *
+ * 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.
+ */
+
+#ifndef SCRIPTING_H
+#define SCRIPTING_H
+
+#include <kparts/plugin.h>
+#include <kspread_view.h>
+
+namespace Kross {
+ namespace Api {
+ class ScriptGUIClient;
+ class ScriptAction;
+ }
+}
+
+class Scripting : public KParts::Plugin
+{
+ Q_OBJECT
+ public:
+ Scripting(QObject *parent, const char *name, const QStringList &);
+ virtual ~Scripting();
+ private slots:
+ void executionFinished(const Kross::Api::ScriptAction*);
+ private:
+ KSpread::View * m_view;
+ Kross::Api::ScriptGUIClient* m_scriptguiclient;
+};
+
+
+#endif
diff --git a/kspread/plugins/scripting/scripting.rc b/kspread/plugins/scripting/scripting.rc
new file mode 100644
index 000000000..7388099ab
--- /dev/null
+++ b/kspread/plugins/scripting/scripting.rc
@@ -0,0 +1,13 @@
+<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
+<kpartgui name="KSpreadPluginScripting" library="kspreadscripting" version="3">
+ <MenuBar>
+ <Menu name="tools"><text>&amp;Tools</text>
+ <Separator/>
+ <!--
+ <Action name="executescriptfile"/>
+ //-->
+ <Action name="configurescripts"/>
+ <Action name="installedscripts"/>
+ </Menu>
+ </MenuBar>
+</kpartgui>
diff --git a/kspread/plugins/scripting/scripts/Makefile.am b/kspread/plugins/scripting/scripts/Makefile.am
new file mode 100644
index 000000000..3dc0ae8e7
--- /dev/null
+++ b/kspread/plugins/scripting/scripts/Makefile.am
@@ -0,0 +1 @@
+SUBDIRS = exporthtml scripteditor
diff --git a/kspread/plugins/scripting/scripts/exporthtml/ExportHtml.py b/kspread/plugins/scripting/scripts/exporthtml/ExportHtml.py
new file mode 100755
index 000000000..2e2dfc317
--- /dev/null
+++ b/kspread/plugins/scripting/scripts/exporthtml/ExportHtml.py
@@ -0,0 +1,179 @@
+"""
+KSpread Kross Python Script.
+
+Export to HTML File.
+
+Description:
+This script exports data from KSpread to a HTML file.
+
+Author:
+Sebastian Sauer <mail@dipe.org>
+
+Copyright:
+Dual-licensed under LGPL v2+higher and the BSD license.
+"""
+
+import os, sys
+
+try:
+ import qt
+except (ImportError):
+ raise "Failed to import the required PyQt python module."
+
+class Dialog(qt.QDialog):
+ def __init__(self, scriptpath, parent):
+ self.scriptpath = scriptpath
+
+ import krosskspreadcore
+ self.doc = krosskspreadcore.get("KSpreadDocument")
+
+ import qt
+ qt.QDialog.__init__(self, parent, "Dialog", 1, qt.Qt.WDestructiveClose)
+ self.setCaption("Export to HTML File")
+ layout = qt.QVBoxLayout(self)
+ box = qt.QVBox(self)
+ box.setMargin(10)
+ box.setSpacing(10)
+ layout.addWidget(box)
+
+ sheetbox = qt.QHBox(box)
+ sheetbox.setSpacing(6)
+ sheetlabel = qt.QLabel("Sheet:",sheetbox)
+ self.sheetcombo = qt.QComboBox(sheetbox)
+ currentsheetname = self.doc.currentSheet().name()
+ for sheetname in self.doc.sheetNames():
+ self.sheetcombo.insertItem(sheetname)
+ if sheetname == currentsheetname:
+ self.sheetcombo.setCurrentItem(self.sheetcombo.count() - 1)
+ sheetlabel.setBuddy(self.sheetcombo)
+ sheetbox.setStretchFactor(self.sheetcombo,1)
+
+ self.styles = {
+ "Paper" :
+ "html { background-color:#efefef; }"
+ "body { background-color:#fafafa; color:#303030; margin:1em; padding:1em; border:#606060 1px solid; }"
+ ,
+ "Plain" :
+ "html { background-color:#ffffff; color:#000; }"
+ "body { margin:1em; }"
+ ,
+ "Seawater" :
+ "html { background-color:#0000aa; }"
+ "body { background-color:#000066; color:#efefff; margin:1em; padding:1em; border:#00f 1px solid; }"
+ "h1 { color:#0000ff; }"
+ "th { color:#6666ff; }"
+ ,
+ }
+
+ stylebox = qt.QHBox(box)
+ stylebox.setSpacing(6)
+ stylelabel = qt.QLabel("Style:",stylebox)
+ self.stylecombo = qt.QComboBox(stylebox)
+ stylenames = self.styles.keys()
+ stylenames.sort()
+ for stylename in stylenames:
+ self.stylecombo.insertItem(stylename)
+ stylelabel.setBuddy(self.stylecombo)
+ stylebox.setStretchFactor(self.stylecombo,1)
+
+ filebox = qt.QHBox(box)
+ filebox.setSpacing(6)
+ filelabel = qt.QLabel("File:",filebox)
+ self.fileedit = qt.QLineEdit(self.getDefaultFile(),filebox)
+ btn = qt.QPushButton("...",filebox)
+ qt.QObject.connect(btn, qt.SIGNAL("clicked()"),self.browseClicked)
+ filelabel.setBuddy(self.fileedit)
+ filebox.setStretchFactor(self.fileedit,1)
+
+ btnbox = qt.QHBox(box)
+ btnbox.setSpacing(6)
+ okbtn = qt.QPushButton(btnbox)
+ okbtn.setText("Export")
+ okbtn.setDefault(True)
+ qt.QObject.connect(okbtn,qt.SIGNAL("clicked()"),self.startExport)
+ cancelbtn = qt.QPushButton(btnbox)
+ cancelbtn.setText("Cancel")
+ qt.QObject.connect(cancelbtn,qt.SIGNAL("clicked()"),self.close)
+
+ box.setMinimumWidth(480)
+
+ def browseClicked(self):
+ import qt
+ filename = str( qt.QFileDialog.getSaveFileName(str(self.fileedit.text()),"*.htm *.html *.xhtml;;*", self) )
+ if filename != "": self.fileedit.setText(filename)
+
+ def getDefaultFile(self):
+ import os
+ try:
+ homepath = os.getenv("HOME")
+ if not homepath:
+ import pwd
+ user = os.getenv("USER") or os.getenv("LOGNAME")
+ if not user:
+ pwent = pwd.getpwuid(os.getuid())
+ else:
+ pwent = pwd.getpwnam(user)
+ homepath = pwent[6]
+ except (KeyError, ImportError):
+ homepath = os.curdir
+ return os.path.join(homepath, "kspreadexport.html")
+
+ def startExport(self):
+ import qt
+
+ sheetname = str( self.sheetcombo.currentText() )
+ sheet = self.doc.sheetByName( sheetname )
+ print "sheetname=%s sheet=%s" % (sheetname,sheet)
+
+ filename = str( self.fileedit.text() )
+ try:
+ file = open(filename, "w")
+ except IOError, (errno, strerror):
+ qt.QMessageBox.critical(self,"Error","<qt>Failed to create HTML file \"%s\"<br><br>%s</qt>" % (filename,strerror))
+ return
+
+ file.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n")
+ file.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n")
+ file.write("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">\n")
+ file.write("<head><title>%s</title>\n" % sheetname)
+
+ file.write("<style type=\"text/css\">\n<!--\n")
+ file.write( self.styles[ str(self.stylecombo.currentText()) ] )
+ file.write("\n//-->\n</style>\n")
+
+ file.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n")
+ file.write("</head><body><h1>%s</h1>\n" % sheetname)
+
+ file.write("<table border=\"1\">\n")
+ cell = sheet.firstCell()
+ prevrow = -1
+ while cell:
+ #print "Cell col=%s row=%s value=%s" % (cell.column(),cell.row(),cell.value())
+
+ row = cell.row()
+ if row != prevrow:
+ prevrow = row
+ file.write("<tr>")
+ file.write("<th>%s</th>" % row)
+
+ file.write("<td>%s</td>" % cell.value())
+
+ cell = cell.nextCell()
+ if cell == None or cell.row() != prevrow:
+ file.write("</tr>\n")
+
+ file.write("</table>\n")
+ file.write("</body></html>\n")
+
+ file.close()
+ self.close()
+
+if __name__ == "__main__":
+ scriptpath = os.getcwd()
+ qtapp = qt.QApplication(sys.argv)
+else:
+ scriptpath = os.path.dirname(__name__)
+ qtapp = qt.qApp
+
+dialog = Dialog(scriptpath, qtapp.mainWidget())
+dialog.exec_loop()
diff --git a/kspread/plugins/scripting/scripts/exporthtml/ExportHtml.rc b/kspread/plugins/scripting/scripts/exporthtml/ExportHtml.rc
new file mode 100755
index 000000000..8ec7b290c
--- /dev/null
+++ b/kspread/plugins/scripting/scripts/exporthtml/ExportHtml.rc
@@ -0,0 +1,9 @@
+<KrossScripting>
+ <ScriptAction
+ name="exporthtml"
+ version="1"
+ text="Export to HTML File..."
+ icon="fileexport"
+ interpreter="python"
+ file="ExportHtml.py" />
+</KrossScripting>
diff --git a/kspread/plugins/scripting/scripts/exporthtml/Makefile.am b/kspread/plugins/scripting/scripts/exporthtml/Makefile.am
new file mode 100644
index 000000000..aa65c3e5d
--- /dev/null
+++ b/kspread/plugins/scripting/scripts/exporthtml/Makefile.am
@@ -0,0 +1,2 @@
+scriptsdir = $(kde_datadir)/kspread/scripts/exporthtml
+scripts_SCRIPTS = ExportHtml.py ExportHtml.rc
diff --git a/kspread/plugins/scripting/scripts/scripteditor/Makefile.am b/kspread/plugins/scripting/scripts/scripteditor/Makefile.am
new file mode 100644
index 000000000..a18854762
--- /dev/null
+++ b/kspread/plugins/scripting/scripts/scripteditor/Makefile.am
@@ -0,0 +1,2 @@
+scriptsdir = $(kde_datadir)/kspread/scripts/scripteditor
+scripts_SCRIPTS = ScriptEditor.py ScriptEditor.rc
diff --git a/kspread/plugins/scripting/scripts/scripteditor/ScriptEditor.py b/kspread/plugins/scripting/scripts/scripteditor/ScriptEditor.py
new file mode 100755
index 000000000..f015a5f19
--- /dev/null
+++ b/kspread/plugins/scripting/scripts/scripteditor/ScriptEditor.py
@@ -0,0 +1,1089 @@
+"""
+Kross Script Editor
+
+Description:
+This script provides a in python written script editor.
+
+Author:
+Sebastian Sauer <mail@dipe.org>
+
+Copyright:
+Dual-licensed under LGPL v2+higher and the BSD license.
+"""
+
+import os, sys
+
+try:
+ import qt
+except (ImportError):
+ raise "Failed to import the required PyQt python module."
+
+####################################################################################
+# Samples.
+
+class Widget(qt.QHBox):
+ def __init__(self, parentwidget, label = None):
+ self.parentwidget = parentwidget
+ import qt
+ qt.QHBox.__init__(self, parentwidget)
+ self.setMargin(4)
+ self.setSpacing(4)
+ if label != None: qt.QLabel(label, self)
+ def value(self):
+ return None
+
+class ListWidget(Widget):
+ def __init__(self, parentwidget, label):
+ import qt
+ global Widget
+ Widget.__init__(self, parentwidget, label)
+ self.combo = qt.QComboBox(self)
+ self.combo.setEditable(True)
+ self.setStretchFactor(self.combo,1)
+ def value(self):
+ return self.combo.currentText()
+
+class EditWidget(Widget):
+ def __init__(self, parentwidget, label):
+ import qt
+ global Widget
+ Widget.__init__(self, parentwidget, label)
+ self.edit = qt.QLineEdit(self)
+ self.setStretchFactor(self.edit,1)
+ def value(self):
+ return self.edit.text()
+
+class FileWidget(Widget):
+ def __init__(self, parentwidget, label, filtermask, openfiledialog = True):
+ self.filtermask = filtermask
+ self.openfiledialog = openfiledialog
+ import qt
+ global Widget
+ Widget.__init__(self, parentwidget, label)
+ self.edit = qt.QLineEdit(self)
+ self.setStretchFactor(self.edit,1)
+ btn = qt.QPushButton("...",self)
+ qt.QObject.connect(btn, qt.SIGNAL("clicked()"), self.btnClicked)
+ def btnClicked(self):
+ import qt
+ text = str( self.edit.text() )
+ if self.openfiledialog:
+ filename = str( qt.QFileDialog.getOpenFileName(text, self.filtermask, self.parentwidget) )
+ else:
+ filename = qt.QFileDialog.getSaveFileName(text, self.filtermask, self.parentwidget)
+ if filename != "": self.edit.setText( filename )
+ def value(self):
+ return self.edit.text()
+
+class Samples:
+
+ ####################################################################################
+ # KexiDB
+
+ class KexiDB:
+ def __init__(self, parentwidget):
+ self.parentwidget = parentwidget
+
+ class _ProjectWidget(FileWidget):
+ def __init__(self, parentwidget):
+ global FileWidget
+ FileWidget.__init__(self, parentwidget, "Project File:", "*.kexi *.kexis *.kexic;;*")
+
+ class _DriverWidget(ListWidget):
+ def __init__(self, parentwidget):
+ global ListWidget
+ ListWidget.__init__(self, parentwidget, "Driver:")
+ import krosskexidb
+ for driver in krosskexidb.DriverManager().driverNames():
+ self.combo.insertItem(driver)
+
+ class _TableWidget(ListWidget):
+ def __init__(self, parentwidget):
+ global ListWidget
+ ListWidget.__init__(self, parentwidget, "Table:")
+
+ class PrintDriverDetails:
+ """ Print a the list of available KexiDB drivers and print details about one of them. """
+ name = "Details about a driver"
+ def __init__(self, parent):
+ self.widgets = {
+ "DriverName" : Samples.KexiDB._DriverWidget( parent.parentwidget ),
+ }
+ def getCode(self):
+ return (
+ 'import krosskexidb',
+ 'drivermanager = krosskexidb.DriverManager()',
+ 'print "drivernames: %s" % drivermanager.driverNames()',
+ '',
+ 'driver = drivermanager.driver( \"{DriverName}\" )',
+ 'print "driver: {DriverName}"',
+ 'print "version=%s.%s" % (driver.versionMajor(),driver.versionMinor())',
+ 'print "mimetype=%s" % driver.fileDBDriverMimeType()',
+ 'print "filedriver=%s" % driver.isFileDriver()',
+ )
+
+ class ConnectWithFile:
+ """ Connect with a KexiDB database by using a Kexi Connection Project File. """
+ name = "Connect with file"
+ def __init__(self, parent):
+ self.widgets = {
+ "ProjectFile" : Samples.KexiDB._ProjectWidget( parent.parentwidget ),
+ }
+ def getCode(self):
+ return (
+ '# Import the KexiDB module.',
+ 'import krosskexidb',
+ 'drivermanager = krosskexidb.DriverManager()',
+ '',
+ '# Get the connectiondata from the project file.',
+ 'connectiondata = drivermanager.createConnectionDataByFile( "{ProjectFile}" )',
+ 'print "Connectiondata: %s" % connectiondata.serverInfoString()',
+ '',
+ '# Create the driver for the database backend.',
+ 'driver = drivermanager.driver( connectiondata.driverName() )',
+ '',
+ '# Create and establish the connection to the database.',
+ 'connection = driver.createConnection(connectiondata)',
+ 'if not connection.isConnected():',
+ ' if not connection.connect():',
+ ' raise "Failed to connect"',
+ '',
+ '# Open the database for usage.',
+ 'print "Databases: %s" % connection.databaseNames()',
+ 'if not connection.isDatabaseUsed():',
+ ' if not connection.useDatabase( connectiondata.databaseName() ):',
+ ' if not connection.useDatabase( connectiondata.fileName() ):',
+ ' raise "Failed to use database"',
+ '',
+ '# Print some infos.',
+ 'print "All tables: %s" % connection.allTableNames()',
+ 'print "Tables: %s" % connection.tableNames()',
+ 'print "Queries: %s" % connection.queryNames()',
+ )
+
+ class IterateThroughTable:
+ """ Iterate through a table within a connected KexiDB database. """
+ name = "Iterate through table"
+ def __init__(self, parent):
+ self.widgets = {
+ "ProjectFile" : Samples.KexiDB._ProjectWidget( parent.parentwidget ),
+ "TableName" : Samples.KexiDB._TableWidget( parent.parentwidget ),
+ }
+ def getCode(self):
+ return (
+ '# Import the KexiDB module.',
+ 'import krosskexidb',
+ 'drivermanager = krosskexidb.DriverManager()',
+ '',
+ '# Get the connectiondata from the project file.',
+ 'connectiondata = drivermanager.createConnectionDataByFile( "{ProjectFile}" )',
+ 'print "Connectiondata: %s" % connectiondata.serverInfoString()',
+ '',
+ '# Create the driver for the database backend.',
+ 'driver = drivermanager.driver( connectiondata.driverName() )',
+ '',
+ '# Create and establish the connection to the database.',
+ 'connection = driver.createConnection(connectiondata)',
+ 'if not connection.isConnected():',
+ ' if not connection.connect():',
+ ' raise "Failed to connect"',
+ '',
+ '# Open the database for usage.',
+ 'if not connection.isDatabaseUsed():',
+ ' if not connection.useDatabase( connectiondata.databaseName() ):',
+ ' if not connection.useDatabase( connectiondata.fileName() ):',
+ ' raise "Failed to use database"',
+ '',
+ '# Get the table and create a query for it.',
+ 'table = connection.tableSchema( \"{TableName}\" )',
+ 'query = table.query()',
+ '',
+ '# Create a cursor to walk through the records.',
+ 'cursor = connection.executeQuerySchema( query )',
+ 'if not cursor:',
+ ' raise "Failed to create cursor."',
+ '',
+ '# Iterate through the records.',
+ 'if not cursor.moveFirst():',
+ ' raise "The cursor has no records to read from."',
+ 'while not cursor.eof():',
+ ' for i in range( cursor.fieldCount() ):',
+ ' print "%s" % cursor.value(i)',
+ ' cursor.moveNext()',
+ )
+
+ ####################################################################################
+ # KSpread
+
+ class KSpread:
+ def __init__(self, parentwidget):
+ self.parentwidget = parentwidget
+
+ class _SheetWidget(ListWidget):
+ def __init__(self, parentwidget, label = "Sheet:"):
+ global ListWidget
+ ListWidget.__init__(self, parentwidget, label)
+
+ try:
+ import krosskspreadcore
+ document = krosskspreadcore.get("KSpreadDocument")
+ for sheetname in document.sheetNames():
+ self.combo.insertItem(sheetname)
+ except:
+ import traceback
+ trace = "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) )
+ print trace
+
+ class _CellsWidget(ListWidget):
+ def __init__(self, parentwidget):
+ global ListWidget
+ ListWidget.__init__(self, parentwidget, "Cells (col1:row1 - col2:row2):")
+ self.combo.insertItem( "1:1 - %s:%s" % (5,10) )
+ self.combo.insertItem( "1:1 - %s:%s" % (256,256) )
+ self.combo.insertItem( "1:1 - %s:%s" % (32767,32767) )
+ def value(self):
+ return [ [ int(i) for i in item.split(':') ] for item in str( ListWidget.value(self) ).split('-') ]
+
+ class _ValueWidget(EditWidget):
+ def __init__(self, parentwidget):
+ global EditWidget
+ EditWidget.__init__(self, parentwidget, "Value:")
+ self.edit.setText("Some text")
+
+ class _ColorWidget(EditWidget):
+ def __init__(self, parentwidget,label,color):
+ global EditWidget
+ EditWidget.__init__(self, parentwidget, "%s (RGB):" % label)
+ self.edit.setText(color)
+ def value(self):
+ return "#%s" % EditWidget.value(self)
+
+ class SetTextOfCells:
+ """ Set the text of the defined cells. """
+ name = "Set text of cells"
+ def __init__(self, parent):
+ pass
+ self.widgets = {
+ "SheetName" : Samples.KSpread._SheetWidget( parent.parentwidget ),
+ "Cells" : Samples.KSpread._CellsWidget( parent.parentwidget ),
+ "Value" : Samples.KSpread._ValueWidget( parent.parentwidget ),
+ }
+ def getCode(self):
+ return (
+ '# Import the KSpread module.',
+ 'import krosskspreadcore',
+ '',
+ '# Get the current document.',
+ 'document = krosskspreadcore.get("KSpreadDocument")',
+ '',
+ '# Get the sheet defined by the sheetname.',
+ 'sheet = document.sheetByName( \"{SheetName}\" )',
+ 'if not sheet:',
+ ' raise "No such sheet {SheetName} %s" % document.sheetNames()',
+ '',
+ '( (col1,row1),(col2,row2) ) = {Cells}',
+ 'for c in range(col1,col2):',
+ ' for r in range(row1,row2):',
+ ' cell = sheet.cell(c,r)',
+ ' print "cell c=%s r=%s v=%s" % (c,r,cell.value())',
+ ' cell.setText( \"{Value}\" )',
+ )
+
+ class SetColorsOfCells:
+ """ Set the colors of the defined cells. """
+ name = "Set colors of cells"
+ def __init__(self, parent):
+ pass
+ self.widgets = {
+ "SheetName" : Samples.KSpread._SheetWidget( parent.parentwidget),
+ "Cells" : Samples.KSpread._CellsWidget( parent.parentwidget ),
+ "TextColor" : Samples.KSpread._ColorWidget( parent.parentwidget, "Textcolor", "ff0000" ),
+ "BackgroundColor" : Samples.KSpread._ColorWidget( parent.parentwidget, "Backgroundcolor", "c0c0c0" ),
+ }
+ def getCode(self):
+ return (
+ '# Import the KSpread module.',
+ 'import krosskspreadcore',
+ '',
+ '# Get the current document.',
+ 'document = krosskspreadcore.get("KSpreadDocument")',
+ '',
+ '# Get the sheet defined by the sheetname.',
+ 'sheet = document.sheetByName( \"{SheetName}\" )',
+ 'if not sheet:',
+ ' raise "No such sheet {SheetName} %s" % document.sheetNames()',
+ '',
+ '( (col1,row1),(col2,row2) ) = {Cells}',
+ 'for c in range(col1,col2):',
+ ' for r in range(col1,col2):',
+ ' cell = sheet.cell(c,r)',
+ ' cell.setTextColor( \"{TextColor}\" )',
+ ' cell.setBackgroundColor( \"{BackgroundColor}\" )',
+ )
+
+ class IterateThroughCellsWithContent:
+ """ Iterate over all cells in a sheet that have content (aka that are not empty). """
+ name = "Iterate through cells"
+ def __init__(self, parent):
+ pass
+ self.widgets = {
+ "SheetName" : Samples.KSpread._SheetWidget( parent.parentwidget ),
+ }
+ def getCode(self):
+ return (
+ '# Import the KSpread module.',
+ 'import krosskspreadcore',
+ '',
+ '# Get the current document.',
+ 'document = krosskspreadcore.get("KSpreadDocument")',
+ '',
+ '# Get the sheet defined by the sheetname.',
+ 'sheet = document.sheetByName( \"{SheetName}\" )',
+ 'if not sheet:',
+ ' raise "No such sheet {SheetName} %s" % document.sheetNames()',
+ '',
+ '# Iterate through the cells that have content (aka that are not empty).',
+ 'cell = sheet.firstCell()',
+ 'while cell:',
+ ' print "col=%s row=%s value=%s" % (cell.column(),cell.row(),cell.value())',
+ ' cell = cell.nextCell()',
+ )
+
+ class PrintSheetDetails:
+ """ Print details about the current sheet. """
+ name = "Details about a sheet"
+ def __init__(self, parent):
+ self.widgets = {
+ "SheetName" : Samples.KSpread._SheetWidget( parent.parentwidget ),
+ }
+ def getCode(self):
+ return (
+ '# Import the KSpread module.',
+ 'import krosskspreadcore',
+ '',
+ '# Get the current document.',
+ 'document = krosskspreadcore.get("KSpreadDocument")',
+ '',
+ '# Get the sheet defined by the sheetname.',
+ 'sheet = document.sheetByName( \"{SheetName}\" )',
+ 'if not sheet:',
+ ' raise "No such sheet {SheetName} %s" % document.sheetNames()',
+ '',
+ 'print "name=%s" % sheet.name()',
+ 'print "maxcolumns=%s maxrows=%s" % (sheet.maxColumn(),sheet.maxRow())',
+ )
+
+ class LoadDocFromNativeXML:
+ """ Load the document from a native XML file. """
+ name = "Load document from native XML File"
+ def __init__(self, parent):
+ global FileWidget
+ self.widgets = {
+ "FileName" : FileWidget( parent.parentwidget, "XML File:", "*.xml;;*" ),
+ }
+ def getCode(self):
+ return (
+ '# Import the PyQt module.',
+ 'import qt',
+ '',
+ 'def loadFile(filename):',
+ ' # Import the krosskspreadcore module.',
+ ' import krosskspreadcore',
+ ' # Try to read the file.',
+ ' try:',
+ ' file = open(filename, "r")',
+ ' xml = file.read()',
+ ' file.close()',
+ ' except IOError, (errno, strerror):',
+ ' qt.QMessageBox.critical(self,"Error","<qt>Failed to read file %s<br><br>%s</qt>" % (filename,strerror))',
+ ' return',
+ '',
+ ' # Get the current document.',
+ ' document = krosskspreadcore.get("KSpreadDocument")',
+ ' # Load the document from the native XML string.',
+ ' ok = document.loadNativeXML( xml )',
+ '',
+ '# Show the openfile dialog',
+ 'filename = "{FileName}"',
+ 'openfilename = qt.QFileDialog.getOpenFileName(filename,"*.xml;;*", self)',
+ 'if str(openfilename) != "":',
+ ' loadFile( openfilename )',
+ )
+
+ class SaveDocToNativeXML:
+ """ Save the document to a native XML file. """
+ name = "Save document to native XML File"
+ def __init__(self, parent):
+ global FileWidget
+ self.widgets = {
+ "FileName" : FileWidget( parent.parentwidget, "XML File:", "*.xml;;*", False ),
+ }
+ def getCode(self):
+ return (
+ '# Import the PyQt module.',
+ 'import qt',
+ '',
+ 'def saveFile(filename):',
+ ' # Import the krosskspreadcore module.',
+ ' import krosskspreadcore',
+ ' # Try to open the file for writting.',
+ ' try:',
+ ' file = open(filename, "w")',
+ ' except IOError, (errno, strerror):',
+ ' qt.QMessageBox.critical(self,"Error","<qt>Failed to create file %s<br><br>%s</qt>" % (filename,strerror))',
+ ' return',
+ ' # Get the current document.',
+ ' document = krosskspreadcore.get("KSpreadDocument")',
+ ' # Get the native XML string.',
+ ' xml = document.saveNativeXML()',
+ ' # Write the XML string to the file.',
+ ' file.write( xml )',
+ ' # Close the file.',
+ ' file.close()',
+ '',
+ '# Show the savefile dialog',
+ 'filename = "{FileName}"',
+ 'savefilename = qt.QFileDialog.getSaveFileName(filename,"*.xml;;*", self)',
+ 'if str(savefilename) != "":',
+ ' saveFile( savefilename )',
+ )
+
+ class CopySheets:
+ """ Copy the text-content from one sheet to another. """
+ name = "Copy sheets"
+ def __init__(self, parent):
+ self.widgets = {
+ "SourceSheet" : Samples.KSpread._SheetWidget( parent.parentwidget, "Source sheet:" ),
+ "TargetSheet" : Samples.KSpread._SheetWidget( parent.parentwidget, "Target sheet:" ),
+ }
+ def getCode(self):
+ return (
+ '# Import the KSpread module.',
+ 'import krosskspreadcore',
+ '# Get the current document.',
+ 'document = krosskspreadcore.get("KSpreadDocument")',
+ '# Get the source sheet.',
+ 'fromsheet = document.sheetByName( "{SourceSheet}" )',
+ 'if not fromsheet: raise "No such sheet {SourceSheet} %s" % document.sheetNames()',
+ '# Get the target sheet.',
+ 'tosheet = document.sheetByName( "{TargetSheet}" )',
+ 'if not fromsheet: raise "No such sheet {TargetSheet} %s" % document.sheetNames()',
+ '# Copy the cells.',
+ 'fromcell = fromsheet.firstCell()',
+ 'while fromcell:',
+ ' tocell = tosheet.cell( fromcell.column(), fromcell.row() )',
+ ' tocell.setText( fromcell.text() )',
+ ' #tocell.setValue( fromcell.value() )',
+ ' fromcell = fromcell.nextCell()',
+ )
+
+ class LoadSheetFromCSV:
+ """ Load the content of a CSV file into a KSpread sheet. """
+ name = "Load data from CSV file into sheet"
+ def __init__(self, parent):
+ self.widgets = {
+ "Sheet" : Samples.KSpread._SheetWidget( parent.parentwidget ),
+ "FileName" : FileWidget( parent.parentwidget, "CSV File:", "*.csv;;*", True ),
+ }
+ def getCode(self):
+ return (
+ '# Import the KSpread module.',
+ 'import krosskspreadcore',
+ '# Get the current document and the sheet.',
+ 'document = krosskspreadcore.get("KSpreadDocument")',
+ 'sheet = document.sheetByName( "{Sheet}" )',
+ 'if not sheet: raise "No such sheet {Sheet} %s" % document.sheetNames()',
+ '',
+ 'filename = "{FileName}"',
+ 'try:',
+ ' file = open(filename, "r")',
+ 'except IOError:',
+ ' raise "Failed to open CSV File: %s" % filename',
+ '',
+ 'import csv',
+ 'csvparser = csv.reader(file)',
+ 'row = 1',
+ 'while True:',
+ ' try:',
+ ' record = csvparser.next()',
+ ' except StopIteration:',
+ ' break',
+ ' col = 1',
+ ' for item in record:',
+ ' sheet.cell(col,row).setText( item )',
+ ' col += 1',
+ ' row += 1',
+ 'file.close()',
+ )
+
+ class SaveSheetToCSV:
+ """ Save the content of a KSpread sheet into a CSV file. """
+ name = "Save data from a sheet into a CSV file"
+ def __init__(self, parent):
+ self.widgets = {
+ "Sheet" : Samples.KSpread._SheetWidget( parent.parentwidget ),
+ "FileName" : FileWidget( parent.parentwidget, "CSV File:", "*.csv;;*", False ),
+ }
+ def getCode(self):
+ return (
+ 'filename = "{FileName}"',
+ 'try:',
+ ' file = open(filename, "w")',
+ 'except IOError:',
+ ' raise "Failed to write CSV File: %s" % filename',
+ '# Prepare CSV-writer',
+ 'import csv',
+ 'csvwriter = csv.writer(file)',
+ '# Import the KSpread module.',
+ 'import krosskspreadcore',
+ '# Get the current document and the sheet.',
+ 'document = krosskspreadcore.get("KSpreadDocument")',
+ 'sheet = document.sheetByName( "{Sheet}" )',
+ 'if not sheet: raise "No such sheet {Sheet} %s" % document.sheetNames()',
+ '# Iterate over the cells.',
+ 'cell = sheet.firstCell()',
+ 'record = []',
+ 'while cell:',
+ ' record.append( cell.text() )',
+ ' if cell.column() == 1 or not cell.nextCell():',
+ ' csvwriter.writerow( record )',
+ ' record = []',
+ ' cell = cell.nextCell()',
+ 'file.close()',
+ )
+
+
+ ####################################################################################
+ # PyQt
+
+ class PyQt:
+ def __init__(self, parentwidget):
+ self.parentwidget = parentwidget
+
+ class OpenFileDialog:
+ """ Show the usage of the openfile dialog with QFileDialog. """
+ name = "Open File Dialog"
+ def __init__(self, parent):
+ pass
+ self.widgets = {
+ "FileName" : FileWidget( parent.parentwidget, "Open File:", "*.txt *.html;;*" ),
+ }
+ def getCode(self):
+ return (
+ 'import qt',
+ 'openfilename = qt.QFileDialog.getOpenFileName("{FileName}","*.txt *.html;;*", self)',
+ 'print "openfile=%s" % openfilename',
+ )
+
+ class SaveFileDialog:
+ """ Show the usage of the savefile dialog with QFileDialog. """
+ name = "Save File Dialog"
+ def __init__(self, parent):
+ pass
+ self.widgets = {
+ "FileName" : FileWidget( parent.parentwidget, "Save File:", "*.txt *.html;;*", False ),
+ }
+ def getCode(self):
+ return (
+ 'import qt',
+ 'savefilename = qt.QFileDialog.getSaveFileName("{FileName}","*.txt *.html;;*", self)',
+ 'print "savefile=%s" % savefilename',
+ )
+
+ class CustomDialog:
+ """ Show a custom dialog that inherits a QDialog. """
+ name = "Custom Dialog"
+ def __init__(self, parent):
+ pass
+ self.widgets = {
+ }
+ def getCode(self):
+ return (
+ 'import qt',
+ '',
+ 'class MyDialog(qt.QDialog):',
+ ' def __init__(self, parent):',
+ ' import qt',
+ ' qt.QDialog.__init__(self, parent, "MyDialog", 1, qt.Qt.WDestructiveClose)',
+ ' self.setCaption("My Dialog")',
+ ' btn = qt.QPushButton("Click me",self)',
+ ' qt.QObject.connect(btn, qt.SIGNAL("clicked()"), self.buttonClicked)',
+ ' def buttonClicked(self):',
+ ' import qt',
+ ' qt.QMessageBox.information(self, "The Caption", "This is the message string.")',
+ '',
+ 'dialog = MyDialog(self)',
+ 'dialog.exec_loop()',
+ )
+
+ class InputDialog:
+ """ Show how to use a QInputDialog. """
+ name = "Input Dialog"
+ def __init__(self, parent):
+ global EditWidget
+ self.widgets = {
+ "Caption" : EditWidget( parent.parentwidget, "Caption" ),
+ "Message" : EditWidget( parent.parentwidget, "Message" ),
+ }
+ def getCode(self):
+ return (
+ 'import qt',
+ '',
+ 'text, ok = qt.QInputDialog.getText("{Caption}", "{Message}", qt.QLineEdit.Normal, "")',
+ 'if ok:',
+ ' print "Text defined: %s" % text',
+ 'else:',
+ ' print "Dialog aborted."',
+ )
+
+ ####################################################################################
+ # DCOP
+
+ class DCOP:
+ def __init__(self, parentwidget):
+ self.parentwidget = parentwidget
+
+ class PrintClipboard:
+ """ Print the content from the clipper via DCOP. """
+ name = "Clipboard content"
+ def __init__(self, parent):
+ self.widgets = {
+ }
+ def getCode(self):
+ return (
+ 'import qt, kdecore, dcop, dcopext',
+ 'dcopclient = kdecore.KApplication.dcopClient()',
+ 'apps = [ app for app in dcopclient.registeredApplications() if str(app).startswith("klipper") ]',
+ 'd = dcopext.DCOPApp(apps[0], dcopclient)',
+ 'result,typename,data = d.appclient.call(apps[0],"klipper","getClipboardContents()","")',
+ 'ds = qt.QDataStream(data, qt.IO_ReadOnly)',
+ 'print "Clipboard content:\\n%s" % kdecore.dcop_next(ds, "QString")',
+ )
+
+ class AmarokCollectionInfos:
+ """ Fetch some collection informations from the amarok collection via DCOP. """
+ name = "amarok collection infos"
+ def __init__(self, parent):
+ self.widgets = {
+ }
+ def getCode(self):
+ return (
+ 'import qt, kdecore, dcop, dcopext',
+ '',
+ 'dcopclient = kdecore.KApplication.dcopClient()',
+ 'apps = [ app for app in dcopclient.registeredApplications() if str(app).startswith("amarok") ]',
+ 'app = apps[0]',
+ 'd = dcopext.DCOPApp(app, dcopclient)',
+ '',
+ 'def dataToList(data, types = []):',
+ ' import qt, kdecore',
+ ' ds = qt.QDataStream(data, qt.IO_ReadOnly)',
+ ' return [ kdecore.dcop_next(ds, t) for t in types ]',
+ '',
+ 'for funcname in ["totalAlbums","totalArtists","totalCompilations","totalGenres","totalTracks"]:',
+ ' result,replytype,replydata = d.appclient.call("amarok", "collection", "%s()" % funcname,"")',
+ ' print "%s: %s" % ( funcname, dataToList(replydata,["int"])[0] )',
+ )
+
+ class KopeteContacts:
+ """ Print the names of all contacts Kopete knows via DCOP. """
+ name = "Kopete contacts"
+ def __init__(self, parent):
+ self.widgets = {
+ }
+ def getCode(self):
+ return (
+ 'import qt, kdecore, dcop, dcopext',
+ '',
+ 'dcopclient = kdecore.KApplication.dcopClient()',
+ 'apps = [ app for app in dcopclient.registeredApplications() if str(app).startswith("kopete") ]',
+ 'app = apps[0]',
+ 'd = dcopext.DCOPApp(app, dcopclient)',
+ '',
+ '(state,rtype,rdata) = d.appclient.call("kopete", "KopeteIface", "contacts()","")',
+ 'if not state: raise "Failed to call the kopete contacts-function"',
+ '',
+ 'ds = qt.QDataStream(rdata.data(), qt.IO_ReadOnly)',
+ 'sl = kdecore.dcop_next (ds, "QStringList")',
+ 'print "contacts=%s" % [ str(s) for s in sl ]',
+ )
+
+ class KWordSelectedText:
+ """ Get the selected text from a KWord instance via DCOP. """
+ name = "KWord selected text"
+ def __init__(self, parent):
+ self.widgets = {
+ }
+ def getCode(self):
+ return (
+ 'import qt, kdecore, dcop, dcopext',
+ '',
+ 'def dataToList(data, types = []):',
+ ' import qt, kdecore',
+ ' ds = qt.QDataStream(data, qt.IO_ReadOnly)',
+ ' return [ kdecore.dcop_next(ds, t) for t in types ]',
+ 'def listToData(listdict):',
+ ' import qt, kdecore',
+ ' ba= qt.QByteArray()',
+ ' ds = qt.QDataStream(ba, qt.IO_WriteOnly)',
+ ' for (typename,value) in listdict:',
+ ' kdecore.dcop_add (ds, value, typename)',
+ ' return ba',
+ '',
+ '# Get the KWord DCOP client.',
+ 'dcopclient = kdecore.KApplication.dcopClient()',
+ 'apps = [ app for app in dcopclient.registeredApplications() if str(app).startswith("kword") ]',
+ 'if len(apps) < 1: raise "No KWord instance is running. Please start KWord before!"',
+ 'appname = apps[0]',
+ 'd = dcopext.DCOPApp(appname, dcopclient)',
+ '',
+ '# Call the getDocuments() function.',
+ '(state,rtype,rdata) = d.appclient.call(appname, "KoApplicationIface", "getDocuments()","")',
+ 'if not state: raise "%s: Failed to call getDocuments-function" % appname',
+ 'documents = dataToList(rdata,["QValueList<DCOPRef>"])[0]',
+ 'print "documents=%s" % [ str( doc.obj() ) for doc in documents ]',
+ 'document = documents[0] # Let\'s just take the first document.',
+ '',
+ '# Get the frameset.',
+ 'ba = listToData( [ ("int",0) ] )',
+ '(state,rtype,rdata) = d.appclient.call(appname, document.obj(), "textFrameSet(int)", ba)',
+ 'if not state: raise "%s: Failed to call frameSet-function" % appname',
+ 'frameset = dataToList( rdata,["DCOPRef"] )[0] # Let\'s just take the first textframe.',
+ '',
+ '# Get the selected text.',
+ '(state,rtype,rdata) = d.appclient.call(appname, frameset.obj(), "selectedText()", "")',
+ 'print "Selected Text: %s" % dataToList( rdata,["QString"] )[0]',
+ )
+
+####################################################################################
+# Dialog implementations.
+
+class SampleDialog(qt.QDialog):
+ def __init__(self, parent, sampleclazz, samplechildclazz):
+ import qt
+ qt.QDialog.__init__(self, parent, "SampleDialog", 1)
+
+ layout = qt.QVBoxLayout(self)
+ box = qt.QVBox(self)
+ box.setMargin(4)
+ box.setSpacing(10)
+ layout.addWidget(box)
+
+ self.scrollview = qt.QScrollView(box)
+ self.scrollview.setResizePolicy(qt.QScrollView.AutoOne)
+ #self.scrollview.setFrameStyle(qt.QFrame.NoFrame);
+ self.scrollview.setResizePolicy(qt.QScrollView.AutoOneFit);
+ self.scrollview.viewport().setPaletteBackgroundColor(self.paletteBackgroundColor())
+ mainbox = qt.QVBox( self.scrollview.viewport() )
+ mainbox.setMargin(6)
+ mainbox.setSpacing(6)
+ desclabel = qt.QLabel(mainbox)
+ qt.QFrame(mainbox).setFrameStyle( qt.QFrame.HLine | qt.QFrame.Sunken )
+
+ self.sample = sampleclazz( mainbox )
+ self.samplechild = samplechildclazz( self.sample )
+
+ desclabel.setText( "<qt>%s</qt>" % self.samplechild.__doc__ )
+ mainbox.setStretchFactor(qt.QWidget(mainbox), 1)
+ mainbox.show()
+ self.scrollview.addChild(mainbox)
+
+ btnbox = qt.QHBox(box)
+ btnbox.setMargin(6)
+ btnbox.setSpacing(6)
+ okbtn = qt.QPushButton(btnbox)
+ okbtn.setText("Ok")
+ qt.QObject.connect(okbtn, qt.SIGNAL("clicked()"), self.okClicked)
+ cancelbtn = qt.QPushButton(btnbox)
+ cancelbtn.setText("Cancel")
+ qt.QObject.connect(cancelbtn, qt.SIGNAL("clicked()"), self.close)
+
+ self.setCaption(self.samplechild.name)
+ box.setMinimumSize(qt.QSize(500,340))
+
+ def okClicked(self):
+ self.code = self.samplechild.getCode()
+ self.close()
+
+ def getCode(self):
+ if not hasattr(self,"code"): return None
+ code = "\n".join( self.code )
+ for widgetname in self.samplechild.widgets.keys():
+ print ".............. %s" % widgetname
+ widget = self.samplechild.widgets[widgetname]
+ value = widget.value()
+ if value != None:
+ code = code.replace("{%s}" % widgetname, str(value))
+ return code
+
+class MainDialog(qt.QDialog):
+ def __init__(self, scriptpath, parent):
+ self.scriptpath = scriptpath
+ if not hasattr(__main__,"scripteditorfilename"):
+ __main__.scripteditorfilename = self.getFileName("myscript.py")
+
+ import krosskspreadcore
+ self.doc = krosskspreadcore.get("KSpreadDocument")
+
+ import os, qt
+ qt.QDialog.__init__(self, parent, "MainDialog", 1, qt.Qt.WDestructiveClose)
+ self.setCaption("Script Editor")
+
+ layout = qt.QVBoxLayout(self)
+ box = qt.QVBox(self)
+ box.setMargin(4)
+ box.setSpacing(10)
+ layout.addWidget(box)
+
+ menu = qt.QMenuBar(box)
+
+ splitter = qt.QSplitter(box)
+ splitter.setOrientation(qt.Qt.Vertical)
+
+ self.scripttext = qt.QMultiLineEdit(splitter)
+ self.scripttext.setWordWrap( qt.QTextEdit.NoWrap )
+ self.scripttext.setTextFormat( qt.Qt.PlainText )
+ qt.QObject.connect(self.scripttext, qt.SIGNAL("cursorPositionChanged(int,int)"),self.cursorPositionChanged)
+
+ self.console = qt.QTextBrowser(splitter)
+ splitter.setResizeMode(self.console, qt.QSplitter.KeepSize)
+
+ statusbar = qt.QStatusBar(box)
+ self.messagestatus = qt.QLabel(statusbar)
+ statusbar.addWidget(self.messagestatus,1)
+ self.cursorstatus = qt.QLabel(statusbar)
+ statusbar.addWidget(self.cursorstatus)
+ self.cursorPositionChanged()
+
+ box.setMinimumSize( qt.QSize(680,540) )
+
+ filemenu = qt.QPopupMenu(menu)
+ menu.insertItem("&File", filemenu)
+
+ newaction = qt.QAction("New", qt.QKeySequence("CTRL+N"), self)
+ qt.QObject.connect(newaction, qt.SIGNAL("activated()"), self.newFile)
+ newaction.addTo(filemenu)
+
+ openaction = qt.QAction("Open...", qt.QKeySequence("CTRL+O"), self)
+ qt.QObject.connect(openaction, qt.SIGNAL("activated()"), self.openFileAs)
+ openaction.addTo(filemenu)
+
+ saveaction = qt.QAction("Save", qt.QKeySequence("CTRL+S"), self)
+ qt.QObject.connect(saveaction, qt.SIGNAL("activated()"), self.saveFile)
+ saveaction.addTo(filemenu)
+
+ saveasaction = qt.QAction("Save as...", qt.QKeySequence("CTRL+A"), self)
+ qt.QObject.connect(saveasaction, qt.SIGNAL("activated()"), self.saveFileAs)
+ saveasaction.addTo(filemenu)
+
+ filemenu.insertSeparator()
+
+ quitaction = qt.QAction("Quit", qt.QKeySequence("CTRL+Q"), self)
+ qt.QObject.connect(quitaction, qt.SIGNAL("activated()"), self.close)
+ quitaction.addTo(filemenu)
+
+ editmenu = qt.QPopupMenu(menu)
+ menu.insertItem("&Edit", editmenu)
+
+ undoaction = qt.QAction("Undo", qt.QKeySequence("CTRL+Z"), self)
+ qt.QObject.connect(undoaction, qt.SIGNAL("activated()"), self.scripttext.undo)
+ undoaction.addTo(editmenu)
+
+ redoaction = qt.QAction("Redo", qt.QKeySequence("CTRL+Shift+Z"), self)
+ qt.QObject.connect(redoaction, qt.SIGNAL("activated()"), self.scripttext.redo)
+ redoaction.addTo(editmenu)
+
+ editmenu.insertSeparator()
+
+ cutaction = qt.QAction("Cut", qt.QKeySequence("CTRL+X"), self)
+ qt.QObject.connect(cutaction, qt.SIGNAL("activated()"), self.scripttext.cut)
+ cutaction.addTo(editmenu)
+
+ copyaction = qt.QAction("Copy", qt.QKeySequence("CTRL+C"), self)
+ qt.QObject.connect(copyaction, qt.SIGNAL("activated()"), self.scripttext.copy)
+ copyaction.addTo(editmenu)
+
+ pasteaction = qt.QAction("Paste", qt.QKeySequence("CTRL+V"), self)
+ qt.QObject.connect(pasteaction, qt.SIGNAL("activated()"), self.scripttext.paste)
+ pasteaction.addTo(editmenu)
+
+ clearaction = qt.QAction("Clear", qt.QKeySequence("CTRL+Shift+X"), self)
+ qt.QObject.connect(clearaction, qt.SIGNAL("activated()"), self.scripttext.clear)
+ clearaction.addTo(editmenu)
+
+ editmenu.insertSeparator()
+
+ selallaction = qt.QAction("Select All", 0, self)
+ qt.QObject.connect(selallaction, qt.SIGNAL("activated()"), self.scripttext.selectAll)
+ selallaction.addTo(editmenu)
+
+ scriptmenu = qt.QPopupMenu(menu)
+ menu.insertItem("&Script", scriptmenu)
+
+ compileaction = qt.QAction("Compile", qt.QKeySequence("F9"), self)
+ qt.QObject.connect(compileaction, qt.SIGNAL("activated()"), self.compileScript)
+ compileaction.addTo(scriptmenu)
+
+ executeaction = qt.QAction("Execute", qt.QKeySequence("F10"), self)
+ qt.QObject.connect(executeaction, qt.SIGNAL("activated()"), self.executeScript)
+ executeaction.addTo(scriptmenu)
+
+ self.samplemenu = qt.QPopupMenu(menu)
+ menu.insertItem("&Samples", self.samplemenu)
+ itemid = 500
+ global Samples
+ for samplename in dir(Samples):
+ if samplename.startswith("_"): continue
+ itemid += 1
+ menu = qt.QPopupMenu(self.samplemenu)
+ qt.QObject.connect(menu, qt.SIGNAL("activated(int)"), self.sampleActivated)
+ self.samplemenu.insertItem(samplename, menu, -1, self.samplemenu.count() - 1)
+ attr = getattr(Samples,samplename)
+ for a in dir(attr):
+ if a.startswith("_"): continue
+ itemid += 1
+ child = getattr(attr,a)
+ itemid = menu.insertItem(child.name, itemid)
+ menu.setWhatsThis(itemid,"%s/%s" % (samplename,a))
+
+ if os.path.exists(__main__.scripteditorfilename):
+ self.openFile(__main__.scripteditorfilename)
+
+ def getFileName(self, filename):
+ import os
+ try:
+ homepath = os.getenv("HOME")
+ if not homepath:
+ import pwd
+ user = os.getenv("USER") or os.getenv("LOGNAME")
+ if not user:
+ pwent = pwd.getpwuid(os.getuid())
+ else:
+ pwent = pwd.getpwnam(user)
+ homepath = pwent[6]
+ except (KeyError, ImportError):
+ homepath = os.curdir
+ return os.path.join(homepath, filename)
+
+ def cursorPositionChanged(self,para = 0,pos = 0):
+ self.cursorstatus.setText( "Line: %s Col: %s" % (para+1,pos+1) )
+
+ def sampleActivated(self, index):
+ global Samples
+ sampleid = str( self.sender().whatsThis(index) )
+ sampleidlist = sampleid.split('/')
+ sampleclazz = getattr( Samples,sampleidlist[0] )
+ samplechildclazz = getattr( sampleclazz, sampleidlist[1] )
+
+ global SampleDialog
+ dialog = SampleDialog(self, sampleclazz, samplechildclazz)
+ dialog.exec_loop()
+ code = dialog.getCode()
+ if code != None:
+ self.scripttext.append( code )
+
+ def execCode(self,function):
+ import sys, StringIO
+ codeOut = StringIO.StringIO()
+ codeErr = StringIO.StringIO()
+ sys.stdout = codeOut
+ sys.stderr = codeErr
+
+ try:
+ function(self)
+ except:
+ import traceback
+ trace = "".join( traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]) )
+ sys.stderr.write(trace)
+ try:
+ # this is a bit tricky. we need to go to steps back to know where the exception really happened.
+ tb = sys.exc_info()[2]
+ while hasattr(tb,"tb_next") and tb.tb_next:
+ tb = tb.tb_next
+ lineno = tb.tb_lineno
+ print "EXCEPTION: lineno=%s" % lineno
+ self.scripttext.setCursorPosition( lineno - 1, 0 )
+ except:
+ pass
+
+ sys.stdout = sys.__stdout__
+ sys.stderr = sys.__stderr__
+
+ s = codeErr.getvalue()
+ if s:
+ print "ERROR:\n%s\n" % s
+ self.console.append(s)
+
+ s = codeOut.getvalue()
+ if s:
+ print s
+ self.console.append(s)
+
+ codeOut.close()
+ codeErr.close()
+
+ def compileScript(self):
+ self.console.clear()
+ code = str( self.scripttext.text() )
+ def docompile(self):
+ compile(code, __main__.scripteditorfilename, 'exec')
+ self.execCode(docompile)
+ self.console.append("<b>Compiled!</b>")
+
+ def executeScript(self):
+ self.console.clear()
+ def doexecute(self):
+ code = str( self.scripttext.text() )
+ exec code in globals(), locals()
+ self.execCode(doexecute)
+ self.console.append("<b>Execution done!</b>")
+
+ def newFile(self):
+ self.console.clear()
+ #if qt.QMessageBox.warning(self,"Remove?","Remove the selected item?",qt.QMessageBox.Yes,qt.QMessageBox.Cancel) != qt.QMessageBox.Yes:
+ self.scripttext.clear()
+
+ def openFile(self, filename):
+ __main__.scripteditorfilename = None
+ try:
+ file = open(filename, "r")
+ self.scripttext.setText( str( file.read() ) )
+ file.close()
+ __main__.scripteditorfilename = filename
+ except IOError, (errno, strerror):
+ qt.QMessageBox.critical(self,"Error","<qt>Failed to open script file \"%s\"<br><br>%s</qt>" % (filename,strerror))
+
+ def openFileAs(self):
+ import qt
+ self.console.clear()
+ filename = str( qt.QFileDialog.getOpenFileName(__main__.scripteditorfilename,"*.py;;*", self) )
+ if filename == "": return
+ self.openFile(filename)
+
+ def saveFile(self):
+ try:
+ file = open(__main__.scripteditorfilename, "w")
+ file.write( str( self.scripttext.text() ) )
+ file.close()
+ except IOError, (errno, strerror):
+ qt.QMessageBox.critical(self,"Error","<qt>Failed to open script file \"%s\"<br><br>%s</qt>" % (__main__.scripteditorfilename,strerror))
+
+ def saveFileAs(self):
+ import qt
+ filename = str( qt.QFileDialog.getSaveFileName(__main__.scripteditorfilename,"*.py;;*", self) )
+ if filename == "": return
+ __main__.scripteditorfilename = filename
+ self.saveFile()
+
+####################################################################################
+# Show the main dialog.
+
+if __name__ == "__main__":
+ scriptpath = os.getcwd()
+ qtapp = qt.QApplication(sys.argv)
+else:
+ scriptpath = os.path.dirname(__name__)
+ qtapp = qt.qApp
+
+dialog = MainDialog(scriptpath, qtapp.mainWidget())
+dialog.exec_loop()
diff --git a/kspread/plugins/scripting/scripts/scripteditor/ScriptEditor.rc b/kspread/plugins/scripting/scripts/scripteditor/ScriptEditor.rc
new file mode 100755
index 000000000..8be0fe8de
--- /dev/null
+++ b/kspread/plugins/scripting/scripts/scripteditor/ScriptEditor.rc
@@ -0,0 +1,9 @@
+<KrossScripting>
+ <ScriptAction
+ name="scripteditor"
+ version="3"
+ text="Script Editor"
+ icon="edit"
+ interpreter="python"
+ file="ScriptEditor.py" />
+</KrossScripting>