summaryrefslogtreecommitdiffstats
path: root/languages/python/pythonsupportpart.cpp
blob: afdf16cad60bacf7b01b01299ab0d7bbea2e803f (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
/***************************************************************************
 *   Copyright (C) 2001-2002 by Bernd Gehrmann                             *
 *   bernd@tdevelop.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.                                   *
 *                                                                         *
 ***************************************************************************/

#include "pythonsupportpart.h"
#include "pythonconfigwidget.h"

#include <kdevcore.h>
#include <kdevproject.h>
#include <kdevappfrontend.h>
#include <kdevpartcontroller.h>
#include <codemodel.h>
#include <domutil.h>

#include <tqfileinfo.h>
#include <tqpopupmenu.h>
#include <tqstringlist.h>
#include <tqtextstream.h>
#include <tqtimer.h>
#include <tqvbox.h>
#include <tdeaction.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kdialogbase.h>
#include <kdevgenericfactory.h>
#include <kdevplugininfo.h>
#include <kinputdialog.h>
#include <klocale.h>
#include <tqregexp.h>

#include "qtdesignerpythonintegration.h"
#include "pythonimplementationwidget.h"

typedef KDevGenericFactory<PythonSupportPart> PythonSupportFactory;
static const KDevPluginInfo data("kdevpythonsupport");
K_EXPORT_COMPONENT_FACTORY( libkdevpythonsupport, PythonSupportFactory( data ) )

PythonSupportPart::PythonSupportPart(TQObject *parent, const char *name, const TQStringList &)
    : KDevLanguageSupport(&data, parent, name ? name : "PythonSupportPart")
{
    setInstance(PythonSupportFactory::instance());

    setXMLFile("kdevpythonsupport.rc");

    connect( core(), TQT_SIGNAL(projectOpened()), this, TQT_SLOT(projectOpened()) );
    connect( core(), TQT_SIGNAL(projectClosed()), this, TQT_SLOT(projectClosed()) );
    connect( partController(), TQT_SIGNAL(savedFile(const KURL&)),
             this, TQT_SLOT(savedFile(const KURL&)) );
    connect( core(), TQT_SIGNAL(projectConfigWidget(KDialogBase*)),
             this, TQT_SLOT(projectConfigWidget(KDialogBase*)) );
  connect( core(), TQT_SIGNAL(contextMenu(TQPopupMenu *, const Context *)),
        this, TQT_SLOT(contextMenu(TQPopupMenu *, const Context *)) );

    TDEAction *action;

    action = new TDEAction( i18n("Execute Program"), "exec", 0,
                          this, TQT_SLOT(slotExecute()),
                          actionCollection(), "build_exec" );
    action->setToolTip( i18n("Execute program") );
    action->setWhatsThis(i18n("<b>Execute program</b><p>Runs the Python program."));

    action = new TDEAction( i18n("Execute String..."), "exec", 0,
                          this, TQT_SLOT(slotExecuteString()),
                          actionCollection(), "build_execstring" );
    action->setToolTip( i18n("Execute string") );
    action->setWhatsThis(i18n("<b>Execute String</b><p>Executes a string as Python code."));

    action = new TDEAction( i18n("Start Python Interpreter"), "exec", 0,
                          this, TQT_SLOT(slotStartInterpreter()),
                          actionCollection(), "build_runinterpreter" );
    action->setToolTip( i18n("Start Python interpreter") );
    action->setWhatsThis(i18n("<b>Start python interpreter</b><p>Starts the Python interpreter without a program"));

    action = new TDEAction( i18n("Python Documentation..."), 0,
                          this, TQT_SLOT(slotPydoc()),
                          actionCollection(), "help_pydoc" );
    action->setToolTip( i18n("Python documentation") );
    action->setWhatsThis(i18n("<b>Python documentation</b><p>Shows a Python documentation page."));
}


PythonSupportPart::~PythonSupportPart()
{}


void PythonSupportPart::contextMenu(TQPopupMenu *popup, const Context *context)
{
    if (context->hasType(Context::FileContext)){
        const FileContext *fc = static_cast<const FileContext*>(context);
        //this is a .ui file and only selection contains only one such file
        KURL url = fc->urls().first();
        if (url.fileName().endsWith(".ui"))
        {
            m_contextFileName = url.fileName();
            int id = popup->insertItem(i18n("Create or Select Implementation..."), this, TQT_SLOT(slotCreateSubclass()));
            popup->setWhatsThis(id, i18n("<b>Create or select implementation</b><p>Creates or selects a subclass of selected form for use with integrated KDevDesigner."));
        }
    }
}


void PythonSupportPart::projectConfigWidget(KDialogBase *dlg)
{
    TQVBox *vbox = dlg->addVBoxPage(i18n("Python"));
    PythonConfigWidget *w = new PythonConfigWidget(*projectDom(), vbox, "python config widget");
    connect( dlg, TQT_SIGNAL(okClicked()), w, TQT_SLOT(accept()) );
}


void PythonSupportPart::projectOpened()
{
    kdDebug(9014) << "projectOpened()" << endl;

    connect( project(), TQT_SIGNAL(addedFilesToProject(const TQStringList &)),
             this, TQT_SLOT(addedFilesToProject(const TQStringList &)) );
    connect( project(), TQT_SIGNAL(removedFilesFromProject(const TQStringList &)),
             this, TQT_SLOT(removedFilesFromProject(const TQStringList &)) );

    // We want to parse only after all components have been
    // properly initialized
    TQTimer::singleShot(0, this, TQT_SLOT(initialParse()));
}


void PythonSupportPart::projectClosed()
{
}


void PythonSupportPart::maybeParse(const TQString fileName)
{
    TQFileInfo fi(fileName);
    if (fi.extension() == "py") {

	if( codeModel()->hasFile(fileName) ){
	    emit aboutToRemoveSourceInfo( fileName );
	    codeModel()->removeFile( codeModel()->fileByName(fileName) );
	}

        parse( fileName );
    }
}


void PythonSupportPart::initialParse()
{
    kdDebug(9014) << "initialParse()" << endl;

    if (project()) {
        kapp->setOverrideCursor(waitCursor);
        TQStringList files = project()->allFiles();
        for (TQStringList::Iterator it = files.begin(); it != files.end() ;++it) {
            kdDebug(9014) << "maybe parse " << project()->projectDirectory() + "/" + (*it) << endl;
            maybeParse(project()->projectDirectory() + "/" + *it);
        }

        emit updatedSourceInfo();
        kapp->restoreOverrideCursor();
    } else {
        kdDebug(9014) << "No project" << endl;
    }
}


void PythonSupportPart::addedFilesToProject(const TQStringList &fileList)
{
    kdDebug(9014) << "addedFilesToProject()" << endl;

	TQStringList::ConstIterator it;

	for ( it = fileList.begin(); it != fileList.end(); ++it )
	{
		TQString fileName = project()->projectDirectory() + "/" + ( *it );
		maybeParse( fileName );
		emit addedSourceInfo( fileName );
	}

    //emit updatedSourceInfo();
}


void PythonSupportPart::removedFilesFromProject(const TQStringList &fileList)
{
	kdDebug(9014) << "removedFilesFromProject()" << endl;

	TQStringList::ConstIterator it;

	for ( it = fileList.begin(); it != fileList.end(); ++it )
	{
		TQString fileName = project()->projectDirectory() + "/" + ( *it );

		if( codeModel()->hasFile(fileName) ){
		    emit aboutToRemoveSourceInfo( fileName );
		    codeModel()->removeFile( codeModel()->fileByName(fileName) );
		}
	}

	//emit updatedSourceInfo();
}


void PythonSupportPart::savedFile(const KURL &fileName)
{
    kdDebug(9014) << "savedFile()" << endl;

    if (project()->allFiles().contains(fileName.path().mid ( project()->projectDirectory().length() + 1 ))) {
        maybeParse(fileName.path());
	emit addedSourceInfo( fileName.path() );
    }
}


KDevLanguageSupport::Features PythonSupportPart::features()
{
    return Features(Classes | Functions);
}


KMimeType::List PythonSupportPart::mimeTypes( )
{
    KMimeType::List list;
    KMimeType::Ptr mime = KMimeType::mimeType( "text/x-python" );
    if( mime )
	list << mime;

    mime = KMimeType::mimeType( "application/x-python" );
    if( mime )
        list << mime;

    return list;
}

void PythonSupportPart::parse(const TQString &fileName)
{
    TQFile f(TQFile::encodeName(fileName));
    if (!f.open(IO_ReadOnly))
        return;
    TQTextStream stream(&f);

    TQRegExp classre("^[ \t]*class[ \t]+([A-Za-z0-9_]+)[ \t]*(\\(([A-Za-z0-9_, \t]+)\\))?.*$");
    TQRegExp methodre("^[ \t]*def[ \t]+([A-Za-z0-9_]+).*$");

    FileDom m_file = codeModel()->create<FileModel>();
    m_file->setName( fileName );

    ClassDom lastClass;
    TQString rawline;
    TQCString line;
    int lineNo = 0;
    while (!stream.atEnd()) {
        rawline = stream.readLine();
        line = rawline.stripWhiteSpace().local8Bit();
        if (classre.search(line) != -1) {

            lastClass = codeModel()->create<ClassModel>();
            lastClass->setName(classre.cap(1));
	    lastClass->setFileName( fileName );
	    lastClass->setStartPosition( lineNo, 0 );

            TQStringList parentList = TQStringList::split(",", classre.cap(3));
            TQStringList::ConstIterator it;
            for (it = parentList.begin(); it != parentList.end(); ++it) {
                TQString baseName = (*it).stripWhiteSpace();
                kdDebug(9014) << "Add parent" << baseName << endl;
                lastClass->addBaseClass( baseName );
            }

           if (m_file->hasClass(lastClass->name())) {
                ClassDom old = m_file->classByName( lastClass->name() )[ 0 ];
		old->setFileName( lastClass->fileName() );

		int line, col;
		lastClass->getStartPosition( &line, &col );
		old->setStartPosition( line, col );

                lastClass = old;
            } else {
                kdDebug(9014) << "Add class " << lastClass->name() << endl;
                m_file->addClass( lastClass );
            }

        } else if (methodre.search(line) != -1 ) {

            FunctionDom method = codeModel()->create<FunctionModel>();
            method->setName(methodre.cap(1));
	    method->setFileName( fileName );
            method->setStartPosition( lineNo, 0 );

            if (lastClass && rawline.left(3) != "def") {
	        if( !lastClass->hasFunction(method->name()) )
                    lastClass->addFunction( method );
                TQStringList scope;
                scope << lastClass->name();
                method->setScope( scope );

            } else if( !m_file->hasFunction(method->name()) ){
                m_file->addFunction( method );
                lastClass = 0;
            }
        }
        ++lineNo;
    }

    f.close();

    codeModel()->addFile( m_file );
}


TQString PythonSupportPart::interpreter()
{
    TQString prog = DomUtil::readEntry(*projectDom(), "/kdevpythonsupport/run/interpreter");
    if (prog.isEmpty())
        prog = "python";

    return prog;
}


void PythonSupportPart::startApplication(const TQString &program)
{
    bool inTerminal = DomUtil::readBoolEntry(*projectDom(), "/kdevpythonsupport/run/terminal");
    if (KDevAppFrontend *appFrontend = extension<KDevAppFrontend>("TDevelop/AppFrontend"))
        appFrontend->startAppCommand(TQString(), program, inTerminal);
}


void PythonSupportPart::slotExecute()
{
    TQString program = project()->mainProgram();
    TQString cmd = interpreter() + " " + program;
    startApplication(cmd);
}


void PythonSupportPart::slotStartInterpreter()
{
    startApplication(interpreter());
}


void PythonSupportPart::slotExecuteString()
{
    bool ok;
    TQString cmd = KInputDialog::getText(i18n("String to Execute"), i18n("String to execute:"), TQString(), &ok, 0);
    if (ok) {
        cmd.prepend("'");
        cmd.append("'");
        startApplication(cmd);
    }
}


void PythonSupportPart::slotPydoc()
{
    bool ok;
    TQString key = KInputDialog::getText(i18n("Show Python Documentation"), i18n("Show Python documentation on keyword:"), "", &ok, 0);
    if (ok && !key.isEmpty()) {
        TQString url = "pydoc:";
        url += key;
        partController()->showDocument(KURL(url));
    }
}

KDevDesignerIntegration *PythonSupportPart::designer(KInterfaceDesigner::DesignerType type)
{
    KDevDesignerIntegration *des = 0;
    switch (type)
    {
        case KInterfaceDesigner::TQtDesigner:
            des = m_designers[type];
            if (des == 0)
            {
                PythonImplementationWidget *impl = new PythonImplementationWidget(this);
                des = new QtDesignerPythonIntegration(this, impl);
                des->loadSettings(*project()->projectDom(),
                    "kdevpythonsupport/designerintegration");
                m_designers[type] = des;
            }
            break;
        case KInterfaceDesigner::Glade:
		    break;
    }
    return des;

}

void PythonSupportPart::slotCreateSubclass()
{
    TQFileInfo fi(m_contextFileName);
    kdDebug(9014) << k_funcinfo << " file: " << m_contextFileName << " ext: " << fi.extension(false) << endl;
    if (fi.extension(false) != "ui")
        return;
    QtDesignerPythonIntegration *des = dynamic_cast<QtDesignerPythonIntegration*>(designer(KInterfaceDesigner::TQtDesigner));
    if (des)
    {
        kdDebug(9014) << "ok: " << des << endl;
        kdDebug(9014) << "have impl: " << des->selectImplementation(m_contextFileName);
    }
    kdDebug(9014) << "end: " << des << endl;
}

#include "pythonsupportpart.moc"