summaryrefslogtreecommitdiffstats
path: root/parts/appwizard/importdlg.cpp
blob: b900181d80c794f9376e12ebe40bf9b8da5ed096 (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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
/***************************************************************************
 *   Copyright (C) 2001-2002 by Bernd Gehrmann                             *
 *   [email protected]                                                    *
 *                                                                         *
 *   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 "importdlg.h"
#include <stdlib.h>
#include <qcombobox.h>
#include <qdir.h>
#include <qfile.h>
#include <qlabel.h>
#include <qlayout.h>
#include <klineedit.h>
#include <qpushbutton.h>
#include <qregexp.h>
#include <qtextstream.h>
#include <qtooltip.h>
#include <qcheckbox.h>
#include <kbuttonbox.h>
#include <kdebug.h>
#include <kdialog.h>
#include <kfiledialog.h>
#include <kinstance.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kcursor.h>
#include <kfile.h>
#include <kurlrequester.h>
#include <ktrader.h>
#include <kparts/componentfactory.h>
#include <kprocess.h>

#include "kdevcore.h"
#include "kdevversioncontrol.h"
#include "kdevplugincontroller.h"

#include "domutil.h"
#include "settings.h"
#include "profile.h"
#include "profileengine.h"

#include "appwizardfactory.h"
#include "appwizardpart.h"
#include "misc.h"


ImportDialog::ImportDialog(AppWizardPart *part, QWidget *parent, const char *name)
    : ImportDialogBase(parent, name, true), m_part(part)
{
    QString author, email;
    AppWizardUtil::guessAuthorAndEmail(&author, &email);
    author_edit->setText(author);
    email_edit->setText(email);
    QToolTip::add( urlinput_edit->button(), i18n("Choose directory to import") );
    urlinput_edit->setMode(KFile::Directory|KFile::ExistingOnly|KFile::LocalOnly);

    KStandardDirs *dirs = AppWizardFactory::instance()->dirs();
    importNames = dirs->findAllResources("appimports", QString::null, false, true);
    importNames.sort();

    QStringList::ConstIterator it;
    for (it = importNames.begin(); it != importNames.end(); ++it) {
        KConfig config(KGlobal::dirs()->findResource("appimports", *it));
        config.setGroup("General");
        QString type = config.readEntry("Comment");
        project_combo->insertItem(type);

        if (config.hasGroup("Infrastructure"))
        {
            config.setGroup("Infrastructure");
            m_infrastructure[type].isOn = true;
            m_infrastructure[type].comment = config.readEntry("Comment");
            m_infrastructure[type].command = config.readEntry("Command");
            m_infrastructure[type].existingPattern = config.readEntry("ExistingProjectPattern");
        }
        else
            m_infrastructure[type].isOn = false;
    }

    infrastructureBox->setEnabled(false);
    setProjectType("c");
    connect( name_edit, SIGNAL( textChanged ( const QString & ) ), this, SLOT( slotProjectNameChanged( const QString & ) ) );
//    scanAvailableVCS();
    connect( fetchModuleButton, SIGNAL(clicked()),
        this, SLOT(slotFetchModulesFromRepository()) );
    connect(urlinput_edit, SIGNAL(urlSelected(const QString& )), this, SLOT(dirChanged()));
    connect(urlinput_edit, SIGNAL(returnPressed(const QString& )), this, SLOT(dirChanged()));
    slotProjectNameChanged( name_edit->text() );
}


ImportDialog::~ImportDialog()
{}

void ImportDialog::slotProjectNameChanged( const QString &_text )
{
    ok_button->setEnabled( !_text.isEmpty() && !urlinput_edit->url().contains( QRegExp("\\s") ) );
}

void ImportDialog::accept()
{
    QDir dir(urlinput_edit->url());
    if (urlinput_edit->url().isEmpty() || !dir.exists()) {
        KMessageBox::sorry(this, i18n("You have to choose a directory."));
        return;
    }

    QString projectName = name_edit->text();
    if (projectName.isEmpty()) {
        KMessageBox::sorry(this, i18n("You have to choose a project name."));
        return;
    }

    for (uint i=0; i < projectName.length(); ++i)
        if (!projectName[i].isLetterOrNumber() && projectName[i] != '_') {
            KMessageBox::sorry(this, i18n("Your application name should only contain letters and numbers."));
            return;
        }

    if (infrastructureBox->isVisible() && infrastructureBox->isChecked())
        createProjectInfrastructure();

//    QString author = author_edit->text();
//    QString email = email_edit->text();

    QFileInfo finfo(importNames[project_combo->currentItem()]);
    QDir importdir(finfo.dir());
    importdir.cdUp();
    QFile src(importdir.filePath("importfiles/" + finfo.fileName() + ".kdevelop"));
    kdDebug(9010) << "Import template " << src.name() << endl;
    if (!src.open(IO_ReadOnly)) {
        KMessageBox::sorry(this, i18n("Cannot open project template."));
        return;
    }

    // Read the DOM of the newly created project
    QDomDocument projectDOM;

    int errorLine, errorCol;
    QString errorMsg;
    bool success = projectDOM.setContent( &src, &errorMsg, &errorLine, &errorCol);
    src.close();
    if ( !success )
    {
        KMessageBox::sorry( 0, i18n("This is not a valid project file.\n"
                "XML error in line %1, column %2:\n%3")
                .arg(errorLine).arg(errorCol).arg(errorMsg));
        return;
    }

    DomUtil::writeEntry( projectDOM, "/general/author", author_edit->text() );
    DomUtil::writeEntry( projectDOM, "/general/email" , email_edit->text() );
    DomUtil::writeEntry( projectDOM, "/general/projectname", name_edit->text() );
    if ( !projectVersion.isNull()){
        DomUtil::writeEntry( projectDOM, "/general/version", projectVersion );
    } else {
        DomUtil::writeEntry( projectDOM, "/general/version", "1" );
    }

    // figure out what plugins we should disable by default
    QString profileName = DomUtil::readEntry( projectDOM, "general/profile" );
    if ( profileName.isEmpty() )
    {
        QString language = DomUtil::readEntry( projectDOM, "general/primarylanguage" );
        QStringList keywords = DomUtil::readListEntry( projectDOM, "general/keywords", "keyword" );

        profileName = Settings::profileByAttributes( language, keywords );
    }

    ProfileEngine & engine = m_part->pluginController()->engine();
    Profile * profile = engine.findProfile( profileName );

    QStringList disableList;
    Profile::EntryList disableEntryList = profile->list( Profile::ExplicitDisable );
    for ( Profile::EntryList::const_iterator it = disableEntryList.constBegin(); it != disableEntryList.constEnd(); ++it )
    {
        disableList << (*it).name;
    }

    DomUtil::writeListEntry( projectDOM, "/general/ignoreparts", "part", disableList );


    // write the dom back
    QFile dest(dir.filePath(projectName + ".kdevelop"));
    if (!dest.open(IO_WriteOnly)) {
        KMessageBox::sorry(this, i18n("Cannot write the project file."));
        return;
    }
    QTextStream ts( &dest );
    ts.setEncoding(QTextStream::UnicodeUTF8);
    ts << projectDOM.toString(2);
    dest.close();


//     QTextStream srcstream(&src);
//     QTextStream deststream(&dest);
//
//     while (!srcstream.atEnd()) {
//         QString line = srcstream.readLine();
//         line.replace(QRegExp("\\$APPNAMELC\\$"), projectName);
//         line.replace(QRegExp("\\$AUTHOR\\$"), author);
//         line.replace(QRegExp("\\$EMAIL\\$"), email);
//         deststream << line << endl;
//     }
//
//     dest.close();
//     src.close();

    m_part->core()->openProject(dir.filePath(projectName + ".kdevelop"));

    kdDebug(9010) << "OPENING PROJECT: " << dir.filePath(projectName + ".kdevelop") << endl;

    QDialog::accept();
}


// Checks if the directory dir and all of its subdirectories
// (one level recursion) have files that follow patterns
// patterns is comma-separated
static bool dirHasFiles(QDir &dir, const QString &patterns)
{
    QStringList::ConstIterator pit, sit;

    QStringList patternList = QStringList::split(",", patterns);
    for (pit = patternList.begin(); pit != patternList.end(); ++pit) {
        if (!dir.entryList(*pit, QDir::Files).isEmpty()) {
            kdDebug(9010) << "Has files " << (*pit) << endl;
            return true;
        }
    }

    QStringList subdirList = dir.entryList("*", QDir::Dirs);
    for (sit = subdirList.begin(); sit != subdirList.end(); ++sit) {
        QDir subdir(dir);
        subdir.cd(*sit);
        for (pit = patternList.begin(); pit != patternList.end(); ++pit) {
            if (!subdir.entryList(*pit, QDir::Files).isEmpty()) {
                kdDebug(9010) << "Has files " << (*pit) << " in " << (*sit) << endl;
                return true;
            }
        }
    }

    return false;
}


void ImportDialog::dirChanged()
{
    kdDebug(9010) << "ImportDialog::dirChanged" << endl;
    QString dirName = urlinput_edit->url();
    QDir dir(dirName);
    if (!dir.exists())
        return;

    if ( dirName.contains( QRegExp("\\s") ) )
    {
        ok_button->setEnabled( false );
        return;
    }else
    {
        ok_button->setEnabled( true );
    }

    // KDevelop legacy project?
    QStringList files = dir.entryList("*.kdevprj");
    if (!files.isEmpty()) {
        scanLegacyKDevelopProject(dir.absFilePath(files.first()));
        return;
    }

    // Studio legacy project?
    files = dir.entryList("*.studio");
    if (!files.isEmpty()) {
        scanLegacyStudioProject(dir.absFilePath(files.first()));
        return;
    }

    // Automake based?
    if ( dir.exists("configure.in.in")|| dir.exists("configure.ac")|| dir.exists("configure.in")) {
        scanAutomakeProject(dirName);
        return;
    }

    // Remove any characters from the dirName that would be invalid in a project name
    QString projectName(dir.dirName().replace(QRegExp("[^a-zA-Z0-9_]"), "_"));

    // Set the project name
    name_edit->setText(projectName);

    // QMake based?
    files = dir.entryList("*.pro");
    if (!files.isEmpty()) {
        setProjectType("qtqmake");
        return;
    }

    // C++?
    if (dirHasFiles(dir, "*.cpp,*.c++,*.cxx,*.C,*.cc,*.ocl")) {
        setProjectType("cpp");
        return;
    }

    // Fortran?
    if (dirHasFiles(dir, "*.f77,*.f,*.for,*.ftn")) {
        setProjectType("fortran");
        return;
    }

    // Python?
    if (dirHasFiles(dir, "*.py")) {
        setProjectType("python");
        return;
    }

    // Perl?
    if (dirHasFiles(dir, "*.pl,*.pm")) {
        setProjectType("perl");
        return;
    }
}


void ImportDialog::scanLegacyKDevelopProject(const QString &fileName)
{
    kdDebug(9010) << "Scanning legacy KDevelop project file " << fileName << endl;

    KSimpleConfig config(fileName, true);
    config.setGroup("General");
    author_edit->setText(config.readEntry("author"));
    email_edit->setText(config.readEntry("email"));
    name_edit->setText(config.readEntry("project_name"));

    QString legacyType = config.readEntry("project_type");
    if (QStringList::split(",", "normal_kde,normal_kde2,kde2_normal,mdi_kde2").contains(legacyType))
        setProjectType("kde");
    else if (legacyType == "normal_gnome")
        setProjectType("gnome");
    else if (legacyType == "normal_empty")
        setProjectType("cpp-auto");
    else
        setProjectType("cpp");
}


void ImportDialog::scanLegacyStudioProject(const QString &fileName)
{
    kdDebug(9010) << "Scanning legacy studio project file " << fileName << endl;

    // Not much to do here...
    KSimpleConfig config(fileName, true);
    config.setGroup("kdestudio");
    name_edit->setText(config.readEntry("Name"));
}


void ImportDialog::scanAutomakeProject(const QString &dirName)
{
    kdDebug(9010) << "Scanning automake project directory " << dirName << endl;

    bool stop = false;
    if (QFile::exists(dirName + "/admin/am_edit")) {
        setProjectType("kde");
        stop = true;
    } else if (QFile::exists(dirName + "/macros/gnome.m4")) {
        setProjectType("gnome");
        stop = true;
    } else {
        setProjectType("c-auto");
    }

    // if we get an authors file, use it.
    QFile af(dirName + "/AUTHORS");
    if (af.open(IO_ReadOnly)){
        QTextStream astream(&af);

        QRegExp authorre("(.*)<(.*)>");
        while (!astream.atEnd()) {
            QString s = astream.readLine();
            if (authorre.search(s) != -1) {
                author_edit->setText(authorre.cap(1).stripWhiteSpace());
                email_edit->setText(authorre.cap(2).stripWhiteSpace());
                break;
            }
        }
        af.close();
    }

    // we ignore old AC_INIT that had no version..
    // only match the if there is a comma and at least two args..
    // AC_INIT (package, version, [bug-report], [tarname])
    QRegExp ac_init("^AC_INIT\\s*\\(\\s*([^,]+),([^,\\)]+)(.*)");

    // AM_INIT_AUTOMAKE([OPTIONS])
    // example: AM_INIT_AUTOMAKE([gnits 1.5 no-define dist-bzip2])
    QRegExp am_autoSpace("^AM_INIT_AUTOMAKE\\s{0,}\\(\\s{0,}([\\[\\s]{0,}[^\\s]+)\\s+([^\\s\\)\\]]+)(.*)");

    // AM_INIT_AUTOMAKE(PACKAGE, VERSION, [NO-DEFINE])
    QRegExp am_autoComma("^AM_INIT_AUTOMAKE\\s*\\(\\s*([^,]+),([^,\\)]+)(.*)");

    // look for version in a define.
    // AC_DEFINE(VERSION, "5.6")
    QRegExp ac_define("^AC_DEFINE\\s*\\(\\s*[^,]+,([^\\)]+)");
    QRegExp version("(\\bversion\\b)");
    version.setCaseSensitive(FALSE);

    QTextStream cstream;
    // try for configure.in.in, configure.in, then configure.ac
    QFile configInIn(dirName + "/configure.in.in");
    QFile configIn(dirName+"/configure.in");
    QFile configAc(dirName+"/configure.ac");
    if (configInIn.open(IO_ReadOnly)){
        cstream.setDevice(&configInIn);
        while (!cstream.atEnd()) {
            QString line = cstream.readLine();
            if ( ac_init.search(line) >= 0){
                projectVersion=ac_init.cap(2).stripWhiteSpace();
            }
            else if ( am_autoComma.search(line) >= 0 ){
                projectVersion=am_autoComma.cap(2).stripWhiteSpace();
            }
            else if ( am_autoSpace.search(line) >= 0 ){
                projectVersion=am_autoSpace.cap(2).stripWhiteSpace();
            }
            else if ( ac_define.search(line) >=0 && version.search(line) >=0) {
                projectVersion=ac_define.cap(2).stripWhiteSpace();
            }
        }
        configInIn.close();
    }

    if (configIn.open(IO_ReadOnly)){
        cstream.setDevice(&configIn);
    }
    else{
        if (configAc.open(IO_ReadOnly)){
            cstream.setDevice(&configAc);
        }
        else{
            return;
        }
    }

    QRegExp namere("\\s*AM_INIT_AUTOMAKE\\((.*),.*\\).*");
    QRegExp cppre("\\s*AC_PROG_CXX");
    QRegExp f77re("\\s*AC_PROG_F77");
    while (!cstream.atEnd()) {
        QString line = cstream.readLine();
        if ( ac_init.search(line) >= 0){
            projectVersion=ac_init.cap(2).stripWhiteSpace();
        }
        else if ( am_autoComma.search(line) >= 0 ){
            projectVersion=am_autoComma.cap(2).stripWhiteSpace();
        }
        else if ( am_autoSpace.search(line) >= 0 ){
            projectVersion=am_autoSpace.cap(2).stripWhiteSpace();
        }
        else if ( ac_define.search(line) >=0 && version.search(line) >=0) {
            projectVersion=ac_define.cap(2).stripWhiteSpace();
        }

        if (namere.search(line) == 0)
            name_edit->setText(namere.cap(1).stripWhiteSpace());
        if (!stop)
            continue;
        else if (cppre.search(line) == 0)
            setProjectType("cpp-auto");
        else if (f77re.search(line) == 0)
            setProjectType("fortran-auto");
    }

    if ( configIn.isOpen()) configIn.close();
    if ( configAc.isOpen()) configAc.close();
}


void ImportDialog::setProjectType(const QString &type)
{
    kdDebug(9010) << "Setting project type " << type << endl;
    QString suffix = "/" + type;
    int suffixLength = suffix.length();

    int i=0;
    QStringList::ConstIterator it;
    for (it = importNames.begin(); it != importNames.end(); ++it) {
        if ((*it).right(suffixLength) == suffix) {
            project_combo->setCurrentItem(i);
            break;
        }
        ++i;
    }
}
/*
void ImportDialog::scanAvailableVCS()
{
//    vcsCombo->insertStringList( m_part->registeredVersionControls() );
    int i = 0;
    KTrader::OfferList offers = KTrader::self()->query("KDevelop/VersionControl");
    KTrader::OfferList::const_iterator it = offers.begin();
    while( it != offers.end() )
    {
        vcsCombo->insertItem( (*it)->genericName(), i++ );
        ++it;
    }
}
*/
/*
void ImportDialog::slotFinishedCheckout( QString destinationDir )
{
    urlinput_edit->setURL( destinationDir );

    setCursor( KCursor::arrowCursor() );
//    setEnabled( true );
}
*/
/*
void ImportDialog::slotFetchModulesFromRepository()
{

    KDevVersionControl *vcs = m_part->versionControlByName( vcsCombo->currentText() );
    if (!vcs)
        return;

    setCursor( KCursor::waitCursor() );
//    setEnabled( false );

    connect( vcs, SIGNAL(finishedFetching(QString)),
        this, SLOT(slotFinishedCheckout(QString)) );

    //restore cursor if we can't fetch repository
    if ( !vcs->fetchFromRepository() )
        setCursor( KCursor::arrowCursor() );

}
*/
void ImportDialog::projectTypeChanged( const QString &type )
{
    if (m_infrastructure[type].isOn)
    {
        infrastructureBox->setEnabled(true);
        infrastructureBox->setText(m_infrastructure[type].comment);
    }
    else
    {
        infrastructureBox->setEnabled(false);
        infrastructureBox->setText(i18n("Generate build system infrastrucure"));
    }
}

void ImportDialog::createProjectInfrastructure( )
{
    kdDebug(9010) << "ImportDialog::createProjectInfrastructure" << endl;
    InfrastructureCmd cmd = m_infrastructure[project_combo->currentText()];
    if (!cmd.isOn)
        return;

    QDir dir (urlinput_edit->url());
    QStringList files = dir.entryList(cmd.existingPattern);
    if (!files.isEmpty()) {
        if (KMessageBox::questionYesNo(this, i18n("Project infrastrucure already exists in target directory.\nGenerate new project infrastructure and overwrite old?"), QString::null, i18n("Generate"), i18n("Do Not Generate")) == KMessageBox::No)
            return;
    }

    QString command = "cd " + urlinput_edit->url() + " && " + cmd.command;
    kdDebug(9010) << "executing " << command.ascii() << endl;
    system(command.ascii());
}

void ImportDialog::projectTypeChanged( int type )
{
    projectTypeChanged(project_combo->text(type));
}


#include "importdlg.moc"