summaryrefslogtreecommitdiffstats
path: root/parts/filecreate/filecreate_part.cpp
blob: 11fcfa6cb18934dc4f9d68775d251bdee1c74c16 (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
/***************************************************************************
 *   Copyright (C) 2003 by Julian Rockey                                   *
 *   linux@jrockey.com                                                     *
 *                                                                         *
 *   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 "filecreate_part.h"

#include <tqwhatsthis.h>
#include <tqdom.h>
#include <tqdir.h>
#include <tqfileinfo.h>
#include <tqvbox.h>
#include <tqtimer.h>

#include <tdeversion.h>
#include <kiconloader.h>
#include <tdelocale.h>
#include <tdevgenericfactory.h>
#include <tdefiledialog.h>
#include <kdebug.h>
#include <kstandarddirs.h>
#include <kstdaction.h>
#include <tdeaction.h>
#include <tdeapplication.h>
#include <tdeactionclasses.h>
#include <tdepopupmenu.h>
#include <tdemessagebox.h>

#include "tdevcore.h"
#include "tdevmainwindow.h"
#include "tdevproject.h"
#include "tdevpartcontroller.h"
#include "configwidgetproxy.h"

#include "filetemplate.h"
#include "domutil.h"
#include "urlutil.h"

#include "filecreate_widget2.h"
#include "filecreate_widget3.h"
#include "filecreate_filetype.h"
#include "filecreate_filedialog.h"
#include "filecreate_newfile.h"
#include "fcconfigwidget.h"

#define PROJECTSETTINGSPAGE 1
#define GLOBALSETTINGSPAGE 2

#include "tdevplugininfo.h"

#include "config.h"

static const TDevPluginInfo data("tdevfilecreate");

typedef TDevGenericFactory<FileCreatePart> FileCreateFactory;
K_EXPORT_COMPONENT_FACTORY( libtdevfilecreate, FileCreateFactory( data ) )

using namespace FileCreate;

FileCreatePart::FileCreatePart(TQObject *parent, const char *name, const TQStringList & )
//    : TDevCreateFile(&data, parent, name ? name : "FileCreatePart"), m_selectedWidget(-1), m_useSideTab(true), m_subPopups(0)
    : TDevCreateFile(&data, parent, name ? name : "FileCreatePart"), m_subPopups(0)
{
  setInstance(FileCreateFactory::instance());
  setXMLFile("tdevpart_filecreate.rc");

  connect( core(), TQT_SIGNAL(projectOpened()), this, TQT_SLOT(slotProjectOpened()) );
  connect( core(), TQT_SIGNAL(projectClosed()), this, TQT_SLOT(slotProjectClosed()) );

	_configProxy = new ConfigWidgetProxy( core() );
	_configProxy->createProjectConfigPage( i18n("File Templates"), PROJECTSETTINGSPAGE, info()->icon() );
	_configProxy->createGlobalConfigPage( i18n("File Templates"), GLOBALSETTINGSPAGE, info()->icon() );
	connect( _configProxy, TQT_SIGNAL(insertConfigWidget(const KDialogBase*, TQWidget*, unsigned int )),
		this, TQT_SLOT(insertConfigWidget(const KDialogBase*, TQWidget*, unsigned int )) );


  TDEToolBarPopupAction * newAction = new TDEToolBarPopupAction( i18n("&New"), "filenew", CTRL+TQt::Key_N, this, TQT_SLOT(slotNewFile()), actionCollection(), "file_new");
  newAction->setWhatsThis( i18n("<b>New file</b><p>Creates a new file. Also adds it the project if the <b>Add to project</b> checkbox is turned on.") );
  newAction->setToolTip( i18n("Create a new file") );
  m_newPopupMenu = newAction->popupMenu();
  connect(m_newPopupMenu, TQT_SIGNAL(aboutToShow()), this, TQT_SLOT(slotAboutToShowNewPopupMenu()));

  TQTimer::singleShot( 0, this, TQT_SLOT(slotGlobalInitialize()) );
}


FileCreatePart::~FileCreatePart()
{
  delete _configProxy;

  m_newPopupMenu->clear();
  delete m_subPopups;
}

void FileCreatePart::insertConfigWidget( const KDialogBase * dlg, TQWidget * page, unsigned int pagenumber )
{
	kdDebug() << k_funcinfo << endl;

	switch( pagenumber )
	{
		case PROJECTSETTINGSPAGE:
		{
			FCConfigWidget* w = new FCConfigWidget( this, false, page, "filecreate config widget" );
			connect( dlg, TQT_SIGNAL( okClicked( ) ), w, TQT_SLOT( accept( ) ) );
		}
		break;

		case GLOBALSETTINGSPAGE:
		{
			FCConfigWidget *w = new FCConfigWidget( this, true, page, "filecreate config widget" );
			connect(dlg, TQT_SIGNAL(okClicked()), w, TQT_SLOT(accept()));
		}
		break;
	}
}

void FileCreatePart::slotAboutToShowNewPopupMenu()
{
	TDEIconLoader * m_iconLoader = TDEGlobal::iconLoader();
	m_newPopupMenu->clear();
	delete m_subPopups;
	m_subPopups = NULL;
	int id = 0;
	FileType * filetype = m_filetypes.first();
	for(; filetype; filetype=m_filetypes.next())
	{
		if (filetype->enabled())
		{
			if (filetype->subtypes().count()==0)
			{
				TQPixmap iconPix = m_iconLoader->loadIcon(
					filetype->icon(), TDEIcon::Desktop, TDEIcon::SizeSmall,
					TDEIcon::DefaultState, NULL, true);
				m_newPopupMenu->insertItem(iconPix, filetype->name(), this,
					TQT_SLOT(slotNewFilePopup(int)), 0, ++id );
				m_newPopupMenu->setItemParameter( id, (long)filetype );
			} else
			{
				TDEPopupMenu* subMenu = NULL;
				TQPtrList<FileType> subtypes = filetype->subtypes();
				for(FileType * subtype = subtypes.first(); subtype; subtype=subtypes.next())
				{
					if (subtype->enabled()){
						if( !subMenu )
							subMenu = new TDEPopupMenu(0,0);
						TQPixmap iconPix = m_iconLoader->loadIcon(
							subtype->icon(), TDEIcon::Desktop, TDEIcon::SizeSmall,
							TDEIcon::DefaultState, NULL, true);
						subMenu->insertItem(iconPix, subtype->name(), this,
							TQT_SLOT(slotNewFilePopup(int)), 0, ++id );
						subMenu->setItemParameter( id, (long)subtype );
					}
				}
				if( subMenu )
				{
					if( !m_subPopups )
					{
						m_subPopups = new TQPtrList<TDEPopupMenu>;
						m_subPopups->setAutoDelete(true);
					}
					m_subPopups->append( subMenu );
					m_newPopupMenu->insertItem( filetype->name(), subMenu );
				}
			}

		}

	}
}

void FileCreatePart::slotNewFilePopup( int pFileType )
{
	const FileType* filetype = (const FileType*) pFileType;
	slotFiletypeSelected( filetype );
}

void FileCreatePart::slotNewFile() {
  TDevCreateFile::CreatedFile createdFile = createNewFile();
  if (createdFile.status == TDevCreateFile::CreatedFile::STATUS_NOTCREATED)
    KMessageBox::error(0, i18n("Cannot create file. Check whether the directory and filename are valid."));
  else if (createdFile.status != TDevCreateFile::CreatedFile::STATUS_CANCELED)
    openCreatedFile(createdFile);
}

void FileCreatePart::slotProjectOpened() {
    TQTimer::singleShot( 0, this, TQT_SLOT(slotInitialize()) );
}

void FileCreatePart::addFileType(const TQString & filename) {
  FileType * filetype = getType(filename);
  if (!filetype) {
    filetype = new FileType;
    filetype->setName( filename + " files" );
    filetype->setExt( filename );
    filetype->setCreateMethod("template");
    m_filetypes.append(filetype);
  }
  filetype->setEnabled(true);
}

void FileCreatePart::slotProjectClosed() {
  m_filetypes.clear();
  TQTimer::singleShot( 0, this, TQT_SLOT(slotGlobalInitialize()) );
}

void FileCreatePart::slotFiletypeSelected(const FileType * filetype) {

  TDevCreateFile::CreatedFile createdFile = createNewFile(filetype->ext(),
                                                          TQString(),
                                                          TQString(),
                                                          filetype->subtypeRef());

  openCreatedFile(createdFile);
}

void FileCreatePart::openCreatedFile(const TDevCreateFile::CreatedFile & createdFile)
{
  if ( createdFile.status == TDevCreateFile::CreatedFile::STATUS_OK )
  {
    KURL uu( createdFile.dir + "/" + createdFile.filename );
    partController()->editDocument ( uu );
  }
}

int FileCreatePart::readTypes(const TQDomDocument & dom, TQPtrList<FileType> &m_filetypes, bool enable) {
  int numRead = 0;
  TQDomElement fileTypes = DomUtil::elementByPath(dom,"/tdevfilecreate/filetypes");
  if (!fileTypes.isNull()) {
    for(TQDomNode node = fileTypes.firstChild();!node.isNull();node=node.nextSibling()) {

      if (node.isElement() && node.nodeName()=="type") {
        TQDomElement element = node.toElement();
        FileType * filetype = new FileType;
        filetype->setName( element.attribute("name") );
        filetype->setExt( element.attribute("ext") );
        filetype->setCreateMethod( element.attribute("create") );

        filetype->setIcon( element.attribute("icon") );
        filetype->setDescr( (DomUtil::namedChildElement(element, "descr")).text() );
        filetype->setEnabled(enable || (filetype->ext()==""));
        m_filetypes.append(filetype);
        numRead++;

        kdDebug(9034) << "node: " << filetype->name().latin1() << endl;

        if (node.hasChildNodes()) {
          for(TQDomNode subnode = node.firstChild();!subnode.isNull();subnode=subnode.nextSibling()) {
            kdDebug(9034) << "subnode: " << subnode.nodeName().latin1() << endl;
            if (subnode.isElement() && subnode.nodeName()=="subtype") {
              TQDomElement subelement = subnode.toElement();
              FileType * subtype = new FileType;
              subtype->setExt( filetype->ext() );
              subtype->setCreateMethod( filetype->createMethod() );
              subtype->setSubtypeRef( subelement.attribute("ref") );
              subtype->setIcon( subelement.attribute("icon") );
              subtype->setName( subelement.attribute("name") );
              subtype->setDescr( (DomUtil::namedChildElement(subelement, "descr")).text() );
              subtype->setEnabled(enable);
              filetype->addSubtype(subtype);
            }
          }
        }
      }
    }
  }
  return numRead;
}

FileType * FileCreatePart::getType(const TQString & ex, const TQString subtRef) {

  TQString subtypeRef = subtRef;
  TQString ext = ex;
  int dashPos = ext.find('-');
  if (dashPos>-1 && subtRef.isNull()) {
    ext = ex.left(dashPos);
    subtypeRef = ex.mid(dashPos+1);
  }

  TQPtrList<FileType> filetypes = getFileTypes();
  for(FileType * filetype = filetypes.first();
      filetype;
      filetype=filetypes.next()) {
    if (filetype->ext()==ext) {
      if (subtypeRef.isNull()) return filetype;
      TQPtrList<FileType> subtypes = filetype->subtypes();
      for(FileType * subtype = subtypes.first();
          subtype;
          subtype=subtypes.next()) {
        if (subtypeRef==subtype->subtypeRef()) return subtype;
      }
    }
  }
  return NULL;
}

FileType * FileCreatePart::getEnabledType(const TQString & ex, const TQString subtRef) {

  TQString subtypeRef = subtRef;
  TQString ext = ex;
  int dashPos = ext.find('-');
  if (dashPos>-1 && subtRef.isNull()) {
    ext = ex.left(dashPos);
    subtypeRef = ex.mid(dashPos+1);
  }

  TQPtrList<FileType> filetypes = getFileTypes();
  for(FileType * filetype = filetypes.first();
      filetype;
      filetype=filetypes.next()) {
    if (filetype->ext()==ext) {
      if ( (subtypeRef.isNull()) && (filetype->enabled()) ) return filetype;
      TQPtrList<FileType> subtypes = filetype->subtypes();
      for(FileType * subtype = subtypes.first();
          subtype;
          subtype=subtypes.next()) {
        if ( (subtypeRef==subtype->subtypeRef()) && (filetype->enabled()) ) return subtype;
      }
    }
  }
  return NULL;
}

// TDevFileCreate interface

TDevCreateFile::CreatedFile FileCreatePart::createNewFile(TQString ext, TQString dir, TQString name, TQString subtype)
{
  TDevCreateFile::CreatedFile result;

  KURL projectURL;
  if ( !project() )
  {
    //result.status = TDevCreateFile::CreatedFile::STATUS_NOTCREATED;
    //return result;
  }
  else
  {
    projectURL = project()->projectDirectory();
  }

  KURL selectedURL;

  NewFileChooser dialog;
  dialog.setFileTypes(m_filetypes);
  const FileType *filetype = getEnabledType(ext,subtype);
  kdDebug(9034) << "Looking for filetype pointer for " << ext << "/" << subtype << endl;
  if (filetype) {
    kdDebug(9034) << "found filetype" << endl;
  } else {
    kdDebug(9034) << "could not find filetype" << endl;
  }
  if (!project())
    dialog.setInProjectMode(false);

  if (!dir.isNull())
    dialog.setDirectory(dir);
  else if (!project())
    dialog.setDirectory(TQDir::currentDirPath());
  else
  {
    TQString activeDir = project()->activeDirectory();
    dialog.setDirectory( project()->projectDirectory() +
        ( activeDir[0] == '/' ? "" : "/" )
        + activeDir );
  }
  if (!name.isNull()) dialog.setName(name);
  if (filetype) dialog.setCurrent(filetype);

  dialog.setInitialSize(TQSize(500, 200));
  int dialogResult = dialog.exec();

  if (dialogResult == KDialogBase::Rejected) {
    result.status = TDevCreateFile::CreatedFile::STATUS_CANCELED;
    return result;
  }

  // OK was pressed

  result.addToProject = dialog.addToProject();
  selectedURL = dialog.url();
  const FileType *selectedFileType = dialog.selectedType();

  if (dialog.addToProject() && !projectURL.isParentOf(selectedURL) && !(project()->options() & TDevProject::UsesTQMakeBuildSystem) ) {
    result.status = TDevCreateFile::CreatedFile::STATUS_NOTWITHINPROJECT;
    return result;
  }

  if (selectedFileType) {
    ext = selectedFileType->ext();
    subtype = selectedFileType->subtypeRef();
  }

  TQString fullPath = selectedURL.path();
  // add appropriate extension, if not already there
  if ( !ext.isEmpty() && !fullPath.endsWith("." + ext)) fullPath+="." + ext;

  TQString filename = URLUtil::filename(fullPath);
  kdDebug(9034) << "full path = " << fullPath << endl;

  // add in subtype, if specified
  if (!subtype.isEmpty())
      ext += "-" + subtype;

  // create file from template
  bool created = false;
  if (FileTemplate::exists(this, ext))
      created = FileTemplate::copy(this, ext, fullPath);
  else {
      // no template, create a blank file instead
      TQFile f(fullPath);
      created = f.open( IO_WriteOnly );
      f.close();
  }
  if (!created)
  {
      result.status = TDevCreateFile::CreatedFile::STATUS_NOTCREATED;
      return result;
  }

  if (dialog.addToProject())
  {
    // work out the path relative to the project directory
//    TQString relToProj = URLUtil::relativePath(projectURL, selectedURL, URLUtil::SLASH_PREFIX );
	  TQString relToProj;
	  if( project()->options() & TDevProject::UsesTQMakeBuildSystem )
	  {
		relToProj = URLUtil::relativePathToFile( project()->projectDirectory(), fullPath );
		  project()->addFile(relToProj);
	  }else
	  {
        relToProj = URLUtil::relativePath(projectURL.path(), fullPath, URLUtil::SLASH_PREFIX );
        project()->addFile(relToProj.mid(1));
	  }
  }

  KURL url;
  url.setPath(fullPath);
  partController()->editDocument(url);

  TQString fileName = URLUtil::filename(fullPath);
  kdDebug(9034) << "file name = " << filename << endl;

  result.filename = fileName;
  result.dir = URLUtil::directory(fullPath);
  result.status = TDevCreateFile::CreatedFile::STATUS_OK;

  return result;
}

void FileCreatePart::slotNoteFiletype(const FileType * filetype) {
  kdDebug(9034) << "Noting file type: " << (filetype ? filetype->ext() : TQString::fromLatin1("Null") ) << endl;
  m_filedialogFiletype = filetype;
}

void FileCreatePart::slotInitialize( )
{
  m_filetypes.clear();

  //read global configuration
  slotGlobalInitialize();

  // read in which global templates are to be used for this project
  TQDomElement useGlobalTypes =
    DomUtil::elementByPath(*projectDom(),"/tdevfilecreate/useglobaltypes");
  for(TQDomNode node = useGlobalTypes.firstChild();
      !node.isNull();node=node.nextSibling()) {

    if (node.isElement() && node.nodeName()=="type") {
      TQDomElement element = node.toElement();
      TQString ext = element.attribute("ext");
      TQString subtyperef = element.attribute("subtyperef");
      // if an extension has been specified as enabled, ensure it
      // and all its subtypes are enabled
      if (subtyperef.isNull()) {
        FileType * filetype = getType(ext);
        if (filetype) {
          filetype->setEnabled(true);
          if (filetype->subtypes().count())
            filetype->setSubtypesEnabled(true);
        }
      } else {
        // if an extension + subtype have been specified, enable
        // the subtype and the extension (the 'parent')
        FileType * filetype = getType(ext);
        FileType * subtype = getType(ext,subtyperef);
        if (filetype && subtype) {
          filetype->setEnabled(true);
          subtype->setEnabled(true);
        }
      }
    }
  }

  // read in the list of file types for this project
  if ( project() && readTypes( *projectDom(), m_filetypes, true )==0  ) {
    // default by scanning the templates directory if no template info
    // found in project file
    TQDir templDir( project()->projectDirectory() + "/templates/" );
    if (templDir.exists()) {
      templDir.setFilter( TQDir::Files );
      const TQFileInfoList * list = templDir.entryInfoList();
      if( list ){
        TQFileInfoListIterator it( *list );
        TQFileInfo *fi;
        while ( (fi = it.current()) != 0 ) {
          addFileType(fi->fileName());
          ++it;
        }
      }
    }
/*    else { // it was probably an imported project
      // KLUDGE: we need a better way to determine file types
      // the current method looks a bit too restrictive
      addFileType( "cpp" );
      addFileType( "h" );
    }*/
  }
}

TQString FileCreatePart::findGlobalXMLFile() const
{
  int version = 0;
  TQString filename;
  TQStringList filenames = TDEGlobal::instance()->dirs()->findAllResources("data", "tdevfilecreate/template-info.xml");
  for( TQStringList::const_iterator it = filenames.begin(); it != filenames.end(); ++it )
  {
    TQDomDocument globalDom;
    DomUtil::openDOMFile(globalDom,*it);
    TQDomElement e = globalDom.documentElement();
    if( !e.hasAttribute( "version" ) && e.attribute( "version" ).toInt() < version )
    {
      continue;
    }else
    {
      version = e.attribute( "version" ).toInt();
      filename = *it;
    }
  }
  return filename;
}

void FileCreatePart::slotGlobalInitialize( )
{
  // read in global template information
  TQString globalXMLFile = findGlobalXMLFile();
  kdDebug(9034) << "Found global template info info " << globalXMLFile << endl;
  TQDomDocument globalDom;
  if (!globalXMLFile.isNull() && DomUtil::openDOMFile(globalDom,globalXMLFile))
  {
    kdDebug(9034) << "Reading global template info..." << endl;

    readTypes(globalDom, m_filetypes, false);

  }
}

#include "filecreate_part.moc"

// kate: indent-width 2; replace-tabs on; tab-width 4; space-indent on;