summaryrefslogtreecommitdiffstats
path: root/kplato/kptpart.cc
blob: 7b0dbd554df7be843e856f16ee684b407cdf8eeb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
/* This file is part of the KDE project
   Copyright (C) 1998, 1999, 2000 Torben Weis <weis@kde.org>
   Copyright (C) 2004, 2005 Dag Andersen <danders@get2net.dk>
   Copyright (C) 2006 Raphael Langerhorst <raphael.langerhorst@kdemail.net>
   Copyright (C) 2006 Dag Andersen <danders@get2net.dk>

   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 "kptpart.h"
#include "kptview.h"
#include "kptfactory.h"
#include "kptproject.h"
#include "kptprojectdialog.h"
#include "kptresource.h"
#include "kptcontext.h"
#include "kptganttview.h"
#include "KDGanttViewTaskLink.h"

#include <tqpainter.h>
#include <tqfileinfo.h>

#include <kdebug.h>
#include <tdeconfig.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kcommand.h>
#include <KoTemplateChooseDia.h>
#include <KoCommandHistory.h>
#include <KoGlobal.h>

#define CURRENT_SYNTAX_VERSION "0.5"

namespace KPlato
{

Part::Part(TQWidget *parentWidget, const char *widgetName,
		 TQObject *parent, const char *name, bool singleViewMode)
    : KoDocument(parentWidget, widgetName, parent, name, singleViewMode),
      m_project(0), m_projectDialog(0), m_parentWidget(parentWidget), m_view(0),
      m_embeddedGanttView(new GanttView(parentWidget)),
      m_embeddedContext(new Context()), m_embeddedContextInitialized(false),
      m_context(0), m_xmlLoader()
{
    m_update = m_calculate = false;
    m_commandHistory = new KoCommandHistory(actionCollection());

    setInstance(Factory::global());
    setTemplateType("kplato_template");
    m_config.setReadWrite(isReadWrite()|| !isEmbedded());
    m_config.load();

    delete m_project;
    m_project = new Project(); // after config is loaded

    connect(m_commandHistory, TQT_SIGNAL(commandExecuted()), TQT_SLOT(slotCommandExecuted()));
    connect(m_commandHistory, TQT_SIGNAL(documentRestored()), TQT_SLOT(slotDocumentRestored()));

    //FIXME the following is really dirty, we should make KPlato::Context a real class
    //      with getter and setter and signals when content changes, thus we can keep track
    TQTimer* timer = new TQTimer(this,"context update timer");
    connect(timer,TQT_SIGNAL(timeout()),this,TQT_SLOT(slotCopyContextFromView()));
    timer->start(500);
}


Part::~Part() {
    m_config.save();
    delete m_commandHistory; // before project, in case of dependencies...
    delete m_project;
    delete m_projectDialog;
    if (m_embeddedGanttView)
      delete m_embeddedGanttView;
    if (m_embeddedContext)
      delete m_embeddedContext;
}


bool Part::initDoc(InitDocFlags flags, TQWidget* parentWidget) {
    bool result = true;

    if (flags==KoDocument::InitDocEmpty)
    {
        delete m_project;
        m_project = new Project();
        setAutoSave(0); // disable
        setModified(false);
        return true;
    }

    TQString templateDoc;
    KoTemplateChooseDia::ReturnType ret;
    KoTemplateChooseDia::DialogType dlgtype;
    if (flags != KoDocument::InitDocFileNew )
        dlgtype = KoTemplateChooseDia::Everything;
    else
        dlgtype = KoTemplateChooseDia::OnlyTemplates;

    ret = KoTemplateChooseDia::choose(Factory::global(), templateDoc,
                                      dlgtype,
                                      "kplato_template",
                                      parentWidget);
    if (ret == KoTemplateChooseDia::Template) {
        resetURL();
        result = loadNativeFormat(templateDoc);
        if ( !result )
            showLoadingErrorDialog();
    } else if (ret == KoTemplateChooseDia::File) {
        KURL url(templateDoc);
        kdDebug() << "Part::initDoc opening URL " << url.prettyURL() <<endl;
        result = openURL(url);
    } else if (ret == KoTemplateChooseDia::Empty) {
        // Make a fresh project and let the user enter some info
        delete m_project;
        m_project = new Project();
       // an emty project should be empty
        // m_projectDialog = new ProjectDialog(*m_project, m_view);
        // m_projectDialog->exec();

        result = true;
    } else {
        result = false;
    }
    setAutoSave(0); // disable
    setModified(false);
    return result;
}


KoView *Part::createViewInstance(TQWidget *parent, const char *name) {
    m_view = new View(this, parent, name);
    connect(m_view,TQT_SIGNAL(destroyed()),this,TQT_SLOT(slotViewDestroyed()));

    // If there is a project dialog this should be deleted so it will
    // use the m_view as parent. If the dialog will be needed again,
    // it will be made at that point
    if (m_projectDialog != 0) {
	kdDebug() << "Deleting m_projectDialog because of new ViewInstance\n";
	delete m_projectDialog;
	m_projectDialog = 0;
    }
    if (m_context)
        m_view->setContext( *m_context );
    else if (m_embeddedContext && m_embeddedContextInitialized)
        m_view->setContext( *m_embeddedContext );
    else {
        // Activate menu actions. Assumes ganttview, we don't get any 
        // 'aboutToShow' signal. Need to redo action control.
        m_view->setTaskActionsEnabled(true);
    }
    //m_view->setBaselineMode(getProject().isBaselined()); FIXME: Removed for this release  
    return m_view;
}


void Part::editProject() {

    TQWidget* parent = m_parentWidget;
    if (m_view)
      parent = m_view;
      
    if (m_projectDialog == 0)
	// Make the dialog
	m_projectDialog = new ProjectDialog(*m_project, parent);

    m_projectDialog->exec();
}


bool Part::loadXML(TQIODevice *, const TQDomDocument &document) {
    TQTime dt;
    dt.start();
    emit sigProgress( 0 );

    TQString value;
    TQDomElement plan = document.documentElement();

    // Check if this is the right app
    value = plan.attribute("mime", TQString());
    if (value.isEmpty()) {
        kdError() << "No mime type specified!" << endl;
        setErrorMessage(i18n("Invalid document. No mimetype specified."));
        return false;
    }
    else if (value != "application/x-vnd.kde.kplato") {
        kdError() << "Unknown mime type " << value << endl;
        setErrorMessage(i18n("Invalid document. Expected mimetype application/x-vnd.kde.kplato, got %1").arg(value));
        return false;
    }
    TQString m_syntaxVersion = plan.attribute("version", CURRENT_SYNTAX_VERSION);
    if (m_syntaxVersion > CURRENT_SYNTAX_VERSION) {
        int ret = KMessageBox::warningContinueCancel(
            0, i18n("This document was created with a newer version of KPlato (syntax version: %1)\n"
                    "Opening it in this version of KPlato will lose some information.").arg(m_syntaxVersion),
            i18n("File-Format Mismatch"), i18n("Continue") );
        if (ret == KMessageBox::Cancel)
        {
            setErrorMessage("USER_CANCELED");
            return false;
        }
    }
    emit sigProgress(5);

    TQDomNodeList list = plan.childNodes();
    if (list.count() > 2) {
        // TODO: Make a proper bitching about this
        kdDebug() << "*** Error ***\n";
        kdDebug() << "  Children count should be 1 but is " << list.count()
                << "\n";
        return false;
    }
    m_xmlLoader.startLoad();
    for (unsigned int i = 0; i < list.count(); ++i) {
        if (list.item(i).isElement()) {
            TQDomElement e = list.item(i).toElement();

            if (e.tagName() == "context") {
                delete m_context;
                m_context = new Context();
                m_context->load(e);
            } else if (e.tagName() == "project") {
                Project *newProject = new Project();
                if (newProject->load(e)) {
                    // The load went fine. Throw out the old project
                    delete m_project;
                    m_project = newProject;
                    delete m_projectDialog;
                    m_projectDialog = 0;
                }
                else {
                    delete newProject;
                    m_xmlLoader.addMsg(XMLLoaderObject::Errors, "Loading of project failed");
                    //TODO add some ui here
                }
            }
        }
    }
    m_xmlLoader.stopLoad();
    emit sigProgress(100); // the rest is only processing, not loading

    kdDebug() << "Loading took " << (float)(dt.elapsed()) / 1000 << " seconds" << endl;

    // do some sanity checking on document.
    emit sigProgress(-1);

    m_commandHistory->clear();
    m_commandHistory->documentSaved();
    setModified( false );
    if (m_view)
        m_view->slotUpdate(false);
    return true;
}

TQDomDocument Part::saveXML() {
    TQDomDocument document("kplato");

    document.appendChild(document.createProcessingInstruction(
			"xml",
			"version=\"1.0\" encoding=\"UTF-8\""));

    TQDomElement doc = document.createElement("kplato");
    doc.setAttribute("editor", "KPlato");
    doc.setAttribute("mime", "application/x-vnd.kde.kplato");
    doc.setAttribute("version", CURRENT_SYNTAX_VERSION);
    document.appendChild(doc);

    delete m_context;
    m_context = 0;
    if (m_view) {
        m_context = new Context();
        m_view->getContext(*m_context);
    }
    if (m_context) {
        m_context->save(doc);
    }
    // Save the project
    m_project->save(doc);

    m_commandHistory->documentSaved();
    return document;
}


void Part::slotDocumentRestored() {
    //kdDebug()<<k_funcinfo<<endl;
    setModified(false);
}


void Part::paintContent(TQPainter &painter, const TQRect &rect,
			   bool /*transparent*/,
			   double zoomX, double /*zoomY*/)
{
    kdDebug() << "----------- KPlato: Part::paintContent ------------" << endl;
    if (isEmbedded() && m_embeddedGanttView && m_project)
    {
        if (m_embeddedContext)
        {
            int ganttsize = m_embeddedContext->ganttview.ganttviewsize;
            int tasksize = m_embeddedContext->ganttview.taskviewsize;
            bool showtaskname = m_embeddedContext->ganttview.showTaskName;
            
//            m_embeddedContext->ganttview.ganttviewsize += m_embeddedContext->ganttview.taskviewsize;
//            m_embeddedContext->ganttview.taskviewsize = 0;  //TODO this doesn't have any effect?! (bug?)
            m_embeddedContext->ganttview.showTaskName = true;  //since task view is not shown(?), show name in the gantt itself
            
            m_embeddedGanttView->setContext( m_embeddedContext->ganttview, *m_project );
            
            m_embeddedContext->ganttview.ganttviewsize = ganttsize;
            m_embeddedContext->ganttview.taskviewsize = tasksize;
            m_embeddedContext->ganttview.showTaskName = showtaskname;
        }
        else
        {
            kdWarning() << "Don't have any context to set!" << endl;
        }
        painter.setClipRect(rect, TQPainter::CoordPainter);
        // We don't support zoom yet, so use the painters scaling
        double d_zoom = 1.0;
        setZoomAndResolution(100, KoGlobal::dpiX(), KoGlobal::dpiY());
        if ( m_zoomedResolutionX != zoomX ) {
            d_zoom *= ( zoomX / m_zoomedResolutionX );
            painter.scale(d_zoom, d_zoom);
        }
        
        m_embeddedGanttView->clear();
        m_embeddedGanttView->draw(*m_project);
        m_embeddedGanttView->drawOnPainter(&painter,rect);
    }
    // ####### handle transparency

    // Need to draw only the document rectangle described in the parameter rect.
//     int left = rect.left() / 20;
//     int right = rect.right() / 20 + 1;
//     int top = rect.top() / 20;
//     int bottom = rect.bottom() / 20 + 1;

//     for( int x = left; x < right; ++x )
//         painter.drawLine( x * 40, top * 20, 40 * 20, bottom * 20 );
//     for( int y = left; y < right; ++y )
//         painter.drawLine( left * 20, y * 20, right * 20, y * 20 );
}


void Part::addCommand(KCommand * cmd, bool execute)
{
    m_commandHistory->addCommand(cmd, execute);
}

void Part::slotCommandExecuted() {
    //kdDebug()<<k_funcinfo<<endl;
    setModified(true);
    kdDebug() << "------- KPlato, is embedded: " << isEmbedded() << endl;
    if (m_view == NULL)
      return;
      
    if (m_calculate)
        m_view->slotUpdate(false/*config().behavior().calculationMode == Behavior::OnChange*/);
    else if (m_update)
        m_view->slotUpdate(false);

    if (m_baseline)
        m_view->setBaselineMode(getProject().isBaselined());

    m_update = m_calculate = m_baseline = false;
}

void Part::slotCopyContextFromView()
{
    if (m_view)
    {
//         kdDebug() << "Updating embedded context from view context." << endl;
        this->m_view->getContext( *m_embeddedContext );
        this->m_embeddedContextInitialized = true;
    }
//     else
//     {
//         kdDebug() << "Not updating the context." << endl;
//         if (m_context)
//           kdDebug() << "Current View: " << m_context->currentView << endl;
//     }
}

void Part::slotViewDestroyed()
{
    m_view = NULL;
}

void Part::setCommandType(int type) {
    //kdDebug()<<k_funcinfo<<"type="<<type<<endl;
    if (type == 0)
        m_update = true;
    else if (type == 1)
        m_calculate = true;
    else if (type == 2)
        m_baseline = true;
}

void Part::generateWBS() {
    m_project->generateWBS(1, m_wbsDefinition);
}

}  //KPlato namespace

#include "kptpart.moc"