summaryrefslogtreecommitdiffstats
path: root/quanta/src/quantadoc.cpp
blob: eb5c538f986b107b40e04bfd2266b676e0c90dd5 (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
/***************************************************************************
                          quantadoc.cpp  -  description
                             -------------------
    begin                : ���� 9 13:29:57 EEST 2000
    copyright            : (C) 2000 by Dmitry Poplavsky & Alexander Yakovlev & Eric Laffoon <pdima@users.sourceforge.net,yshurik@linuxfan.com,sequitur@easystreet.com>
                           (C) 2001-2003 Andras Mantia <amantia@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.                                   *
 *                                                                         *
 ***************************************************************************/

// include files for Qt
#include <tqdir.h>
#include <tqfileinfo.h>
#include <tqwidget.h>
#include <tqtabwidget.h>
#include <tqtabbar.h>
#include <tqlayout.h>
#include <tqdragobject.h>
#include <tqobject.h>


// include files for KDE
#include <klocale.h>
#include <kaction.h>
#include <kconfig.h>
#include <kpopupmenu.h>
#include <kmessagebox.h>
#include <kdirwatch.h>
#include <kdeversion.h>
#include <kdebug.h>
#include <kiconloader.h>

#include <ktexteditor/view.h>
#include <ktexteditor/configinterface.h>
#include <ktexteditor/highlightinginterface.h>
#include <ktexteditor/popupmenuinterface.h>
#include <ktexteditor/markinterface.h>
#include <ktexteditor/undointerface.h>
#include <ktexteditor/viewcursorinterface.h>
#include <ktexteditor/clipboardinterface.h>
#include <ktexteditor/selectioninterface.h>
#include <ktexteditor/encodinginterface.h>
#include <ktexteditor/dynwordwrapinterface.h>
#include <ktexteditor/editorchooser.h>
#include <ktexteditor/editinterface.h>

#include <kparts/componentfactory.h>

#include <klibloader.h>
#include <ktrader.h>


// application specific includes
#include "document.h"
#include "quanta.h"
#include "quantadoc.h"
#include "quantaview.h"
#include "viewmanager.h"

#include "quantacommon.h"
#include "qextfileinfo.h"
#include "resource.h"
#include "debuggermanager.h"

#include "project.h"
//#include "dtds.h"

#include "undoredo.h"
#include "tagactionmanager.h"
#include "tagactionset.h"

QuantaDoc::QuantaDoc(TQWidget *parent, const char *name) : TQObject(parent, name)
{
  fileWatcher = new KDirWatch(this);

  attribMenu = new KPopupMenu();
  attribMenu->insertTitle(i18n("Tag"));
  connect( attribMenu, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotInsertAttrib(int)));
}

QuantaDoc::~QuantaDoc()
{
  //kdDebug(24000) << "QuantaDoc::~QuantaDoc: " << endl;
}


bool QuantaDoc::newDocument( const KURL& url, bool switchToExisting )
{
  bool newfile = false;
  if ( url.url().isEmpty() ) newfile = true;
  Document *w = 0L;
  QuantaView *view = ViewManager::ref()->isOpened(url);
  if (!view || newfile)
  {
    w = ViewManager::ref()->activeDocument();
    if (w && !newfile && !w->isModified() && w->isUntitled() && !w->busy)
         ViewManager::ref()->removeActiveView(false);

/*    
    // no modi and new -> we can remove                           !!!!
    w = ViewManager::ref()->activeDocument();
    if (w && !w->isModified() &&
         w->isUntitled() && !w->busy)
    {
      //workaround for some strange Katepart behavior. If there is a highlighting mode
      //selected and new content is loaded, the highlighting is reset to None. To avoid this
      //remove the untitled document and create a new one, where we don't set the
      //highlighting
      ViewManager::ref()->removeActiveView(false);
      w = ViewManager::ref()->activeDocument();
   
      if (w && !w->isModified() && w->isUntitled() && !w->busy)
          return true;
    }
*/
    // now we can create new kwrite
    ViewManager::ref()->createNewDocument();
    view = ViewManager::ref()->activeView();

    if (Project::ref()->hasProject())
        view->document()->processDTD(Project::ref()->defaultDTD());
    else
        view->document()->processDTD(qConfig.defaultDocType);
  }
  else // select opened
  if (switchToExisting)
  {
    view->document()->checkDirtyStatus();
    if (view != ViewManager::ref()->activeView())
    {
      view->activate();
      view->activated();
    }
    return false; // don't need loadURL
  }

  return true;
}

void QuantaDoc::openDocument(const KURL& urlToOpen, const TQString &a_encoding,
                             bool switchToExisting, bool readOnly)
{
  bool idleTimerStatus = quantaApp->slotEnableIdleTimer(false);
  KURL url = urlToOpen;
  if (url.isLocalFile())
  {
    TQString path = TQDir(url.path()).canonicalPath();
    if (!path.isEmpty())
        url.setPath(path);
  }
  TQString encoding = a_encoding;
  if (!newDocument(url, switchToExisting))
  {
     quantaApp->slotEnableIdleTimer(idleTimerStatus);
     return;
  }
  Document *w = ViewManager::ref()->activeDocument();
  if (readOnly)
  {
    //might work only with Kate part
    KAction *writeLockAction =  w->view()->actionCollection()->action("tools_toggle_write_lock");
    if (writeLockAction)
      writeLockAction->activate();
  }
  if (!url.isEmpty())
  {
    if (QExtFileInfo::exists(url, true, quantaApp))
    {
       if (encoding.isEmpty())
          encoding = quantaApp->defaultEncoding();
       w->disconnect(TQT_SIGNAL(openingFailed(const KURL&)));
       connect(w, TQT_SIGNAL(openingFailed(const KURL&)), this, TQT_SLOT(slotOpeningFailed(const KURL&)));
       w->disconnect(TQT_SIGNAL(openingCompleted(const KURL&)));
       connect(w, TQT_SIGNAL(openingCompleted(const KURL&)), this, TQT_SLOT(slotOpeningCompleted(const KURL&)));
       w->open(url, encoding);
       quantaApp->setTitle(url.prettyURL(0, KURL::StripFileProtocol));
    }
    else
    {
      slotOpeningFailed(url);
    }
  } else
  {
    quantaApp->reparse(true);
    KTextEditor::HighlightingInterface* highlightIf = dynamic_cast<KTextEditor::HighlightingInterface*>(w->doc());
    if (highlightIf)
    {
      TQString hlName;
      int htmlIdx = -1, xmlIdx = -1;
      for (uint i = 0; i < highlightIf->hlModeCount(); i++)
      {
          hlName = highlightIf->hlModeName(i);
          if (hlName == "HTML")
            htmlIdx = i;
          if (hlName == "XML")
            xmlIdx = i;
      }
      const DTDStruct *dtd = w->defaultDTD();
      if (dtd->family == 1)
      {
          if (dtd->singleTagStyle == "xml")
            highlightIf->setHlMode(xmlIdx);
          else
            highlightIf->setHlMode(htmlIdx);
      }
    }
    emit newStatus();
  }
  quantaApp->slotEnableIdleTimer(idleTimerStatus);
}

void QuantaDoc::slotOpeningFailed(const KURL &url)
{
    Q_UNUSED(url);
    bool signalStatus = signalsBlocked();
    blockSignals(false);
    emit hideSplash();
    //Seems to be not needed anymore since KDE 3.2, but keep until it's completely verified
/*
    KMessageBox::error(quantaApp, i18n("<qt>Cannot open document <b>%1</b>.</qt>").arg(url.prettyURL(0, KURL::StripFileProtocol)));
*/
    ViewManager::ref()->removeActiveView();
    blockSignals(signalStatus);
}

void QuantaDoc::slotOpeningCompleted(const KURL &url)
{
  Document *w = ViewManager::ref()->activeDocument();
  Project::ref()->loadBookmarks(w->url(), dynamic_cast<KTextEditor::MarkInterface*>(w->doc()));
    
  quantaApp->fileRecent->addURL(url);
  quantaApp->slotRepaintPreview();
  quantaApp->reparse(true);
  if (url.isLocalFile())
    quantaApp->debugger()->fileOpened(url.prettyURL(0, KURL::StripFileProtocol));
  quantaApp->slotNewStatus();
  quantaApp->setTitle(url.prettyURL(0, KURL::StripFileProtocol));
  Project::ref()->loadCursorPosition(w->url(), dynamic_cast<KTextEditor::ViewCursorInterface*>(w->view()));
  emit eventHappened("after_open", url.url(), TQString::null);
  
  bool flag = TagActionManager::canIndentDTD(w->defaultDTD()->name);
  quantaApp->actionCollection()->action("apply_source_indentation")->setEnabled(flag);
}

/** show popup menu with list of attributes for current tag */
void QuantaDoc::slotAttribPopup()
{
  Document *w = ViewManager::ref()->activeDocument();
  if (!w)  return;

  attribMenu->clear();
  uint line, col;
  w->viewCursorIf->cursorPositionReal(&line, &col);

  Node *node = parser->nodeAt(line, col, false);
  if (node && node->tag)
  {
    Tag *tag = node->tag;
    TQString tagName = tag->name;
    TQStrIList attrList = TQStrIList();
    TQString name;

    for (int i=0; i < tag->attrCount(); i++ )
        attrList.append( tag->attribute(i) );

    if ( QuantaCommon::isKnownTag(w->getDTDIdentifier(),tagName) )
    {
      TQString caption = i18n("Attributes of <%1>").arg(tagName);
      attribMenu->insertTitle( caption );

      AttributeList *list = QuantaCommon::tagAttributes(w->getDTDIdentifier(),tagName );
      uint menuId = 0;
      for ( uint i = 0; i < list->count(); i++ )
      {
        name = list->at(i)->name;
        attribMenu->insertItem( name , i);//list->findIndex(*item) );
        if (attrList.contains(name))
        {
          attribMenu->setItemEnabled( i , false );
        }
        menuId++;
      }

      QTag* qtag = QuantaCommon::tagFromDTD(w->getDTDIdentifier(), tagName);
      for (TQStringList::Iterator it = qtag->commonGroups.begin(); it != qtag->commonGroups.end(); ++it)
      {
       TQPopupMenu* popUpMenu = new TQPopupMenu(attribMenu, (*it).latin1());
       AttributeList *attrs = qtag->parentDTD->commonAttrs->find(*it);
       for (uint j = 0; j < attrs->count(); j++)
       {
        name = attrs->at(j)->name;
        popUpMenu->insertItem(name, ++menuId);
        if (attrList.contains(name))
        {
          popUpMenu->setItemEnabled( menuId , false );
        }
       }
       connect( popUpMenu, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotInsertAttrib(int)));
       attribMenu->insertItem(*it, popUpMenu);
      }

      if (menuId > 0)    // don't show empty menu, may be core dumped
      {
        attribMenu->setActiveItem( 0);

        TQPoint globalPos = w->view()->mapToGlobal(w->viewCursorIf->cursorCoordinates());
        TQFont font = w->view()->font();
        globalPos.setY(globalPos.y() + TQFontMetrics(font).height());
        attribMenu->exec(globalPos);
      }
    }
    else {
      TQString message = i18n("Unknown tag: %1").arg(tagName);
      quantaApp->slotStatusMsg( message );
    }
  }
}

void QuantaDoc::slotInsertAttrib( int id )
{
  Document *w = ViewManager::ref()->activeDocument();
  if (!w)  return;
  uint line, col;
  w->viewCursorIf->cursorPositionReal(&line, &col);
  Node *node = parser->nodeAt(line, col);
  if (node && node->tag)
  {
    Tag *tag = node->tag;
    TQString tagName = tag->name;
    if ( QuantaCommon::isKnownTag(w->getDTDIdentifier(), tagName) )
    {
      int menuId;
      AttributeList *list = QuantaCommon::tagAttributes(w->getDTDIdentifier(), tagName);
      menuId = list->count();
      TQString attrStr;
      if (id <= menuId)
      {
        attrStr = list->at(id)->name;
      } else
      {
        QTag* qtag = QuantaCommon::tagFromDTD(w->getDTDIdentifier(), tagName);
        for (TQStringList::Iterator it = qtag->commonGroups.begin(); it != qtag->commonGroups.end(); ++it)
        {
          AttributeList *attrs = qtag->parentDTD->commonAttrs->find(*it);
          menuId += attrs->count();
          if (id <= menuId)
          {
            attrStr = attrs->at(id - (menuId - attrs->count()) -1)->name;
            break;
          }
        }
      }
      //now insert the new attribute into the tag
      int el, ec;
      tag->endPos(el, ec);
      w->viewCursorIf->setCursorPositionReal( el, ec );
      w->insertTag( " " + QuantaCommon::attrCase(attrStr) + "="+qConfig.attrValueQuotation, qConfig.attrValueQuotation );
    }

    delete attribMenu;
    attribMenu = new KPopupMenu();
    attribMenu->insertTitle(i18n("Tag"));
    connect( attribMenu, TQT_SIGNAL(activated(int)), this, TQT_SLOT(slotInsertAttrib(int)));
  }
}


#include "quantadoc.moc"