completion.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. /*
  2. ktigcc - TIGCC IDE for KDE
  3. Copyright (C) 2006-2007 Kevin Kofler
  4. Copyright (C) 2007 Konrad Meyer
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program; if not, write to the Free Software Foundation,
  15. Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  16. */
  17. #include <QString>
  18. #include <QLinkedList>
  19. #include <QPair>
  20. #include <QPoint>
  21. #include <QRegExp>
  22. #include <QFileInfo>
  23. #include <QDir>
  24. #include <QApplication>
  25. #include <QWidget>
  26. #include <QEvent>
  27. #include <Q3PopupMenu>
  28. #include <kmessagebox.h>
  29. #include <ktexteditor/view.h>
  30. #include <ktexteditor/document.h>
  31. #include <kconfig.h>
  32. #include <cstring>
  33. #include "completion.h"
  34. #include "parsing.h"
  35. #include "preferences.h"
  36. #include "mainform.h"
  37. #include "tpr.h"
  38. // Maps file name to a CompletionInfo.
  39. QMap<QString,CompletionInfo> systemHeaderCompletion, projectCompletion;
  40. static void resetSearchedFlags(void)
  41. {
  42. for (QMap<QString,CompletionInfo>::Iterator it=projectCompletion.begin();
  43. it!=projectCompletion.end(); ++it)
  44. (*it).searched=false;
  45. for (QMap<QString,CompletionInfo>::Iterator it=systemHeaderCompletion.begin();
  46. it!=systemHeaderCompletion.end(); ++it)
  47. (*it).searched=false;
  48. }
  49. static void findSymbolInSystemHeaders(const QString &symbol,
  50. const QStringList &systemHeaders,
  51. QString &symbolFile,
  52. unsigned &symbolLine,
  53. bool &systemHeader)
  54. {
  55. foreach (QString headerName, systemHeaders) {
  56. // Avoid infinite recursion.
  57. if (systemHeaderCompletion.contains(headerName)
  58. && !systemHeaderCompletion[headerName].searched) {
  59. CompletionInfo &completionInfo=systemHeaderCompletion[headerName];
  60. completionInfo.searched=true;
  61. if (completionInfo.lineNumbers.contains(symbol)) {
  62. symbolFile=headerName;
  63. symbolLine=completionInfo.lineNumbers[symbol];
  64. systemHeader=true;
  65. return;
  66. } else {
  67. findSymbolInSystemHeaders(symbol,completionInfo.includedSystem,
  68. symbolFile,symbolLine,systemHeader);
  69. if (!symbolFile.isNull()) return;
  70. }
  71. }
  72. }
  73. }
  74. static bool findSymbolInFileRecursive(const QString &symbol,
  75. const QString &fileText,
  76. const QString &fileName,
  77. MainForm *mainForm,
  78. QString &symbolFile,
  79. unsigned &symbolLine,
  80. bool &systemHeader)
  81. {
  82. symbolFile=QString::null;
  83. systemHeader=false;
  84. if (!projectCompletion.contains(fileName) || projectCompletion[fileName].dirty) {
  85. QFileInfo fileInfo(fileName);
  86. QString pathInProject=fileInfo.isRelative()?fileInfo.path():".";
  87. CompletionInfo completionInfo=parseFileCompletion(fileText,pathInProject);
  88. if (completionInfo.dirty) return false;
  89. projectCompletion.insert(fileName,completionInfo);
  90. }
  91. CompletionInfo &completionInfo=projectCompletion[fileName];
  92. // Avoid infinite recursion.
  93. if (completionInfo.searched) return true;
  94. completionInfo.searched=true;
  95. if (completionInfo.lineNumbers.contains(symbol)) {
  96. symbolFile=fileName;
  97. symbolLine=completionInfo.lineNumbers[symbol];
  98. return true;
  99. }
  100. foreach (QString headerName, completionInfo.included) {
  101. QString headerText=mainForm->textForHeader(headerName);
  102. if (!headerText.isNull()) {
  103. if (!findSymbolInFile(symbol,headerText,headerName,mainForm,symbolFile,
  104. symbolLine,systemHeader))
  105. return false;
  106. if (!symbolFile.isNull()) return true;
  107. }
  108. }
  109. findSymbolInSystemHeaders(symbol,completionInfo.includedSystem,symbolFile,
  110. symbolLine,systemHeader);
  111. return true;
  112. }
  113. bool findSymbolInFile(const QString &symbol,
  114. const QString &fileText,
  115. const QString &fileName,
  116. MainForm *mainForm,
  117. QString &symbolFile,
  118. unsigned &symbolLine,
  119. bool &systemHeader)
  120. {
  121. resetSearchedFlags();
  122. return findSymbolInFileRecursive(symbol,fileText,fileName,mainForm,symbolFile,
  123. symbolLine,systemHeader);
  124. }
  125. static void mergeCompletionEntries(QLinkedList<CompletionEntry> &dest,
  126. const QLinkedList<CompletionEntry> &src)
  127. {
  128. foreach (CompletionEntry entry, src) dest.append(entry);
  129. }
  130. static void completionEntriesForSystemHeaders(const QStringList &systemHeaders,
  131. QLinkedList<CompletionEntry> &result)
  132. {
  133. foreach (QString headerName, systemHeaders) {
  134. // Avoid infinite recursion.
  135. if (systemHeaderCompletion.contains(headerName)
  136. && !systemHeaderCompletion[headerName].searched) {
  137. CompletionInfo &completionInfo=systemHeaderCompletion[headerName];
  138. completionInfo.searched=true;
  139. mergeCompletionEntries(result,completionInfo.entries);
  140. completionEntriesForSystemHeaders(completionInfo.includedSystem,result);
  141. }
  142. }
  143. }
  144. static bool completionEntriesForFileRecursive(const QString &fileText,
  145. const QString &fileName,
  146. MainForm *mainForm,
  147. QLinkedList<CompletionEntry> &result)
  148. {
  149. if (!projectCompletion.contains(fileName) || projectCompletion[fileName].dirty) {
  150. QFileInfo fileInfo(fileName);
  151. QString pathInProject=fileInfo.isRelative()?fileInfo.path():".";
  152. CompletionInfo completionInfo=parseFileCompletion(fileText,pathInProject);
  153. if (completionInfo.dirty) return false;
  154. projectCompletion.insert(fileName,completionInfo);
  155. }
  156. CompletionInfo &completionInfo=projectCompletion[fileName];
  157. // Avoid infinite recursion.
  158. if (completionInfo.searched) return true;
  159. completionInfo.searched=true;
  160. mergeCompletionEntries(result,completionInfo.entries);
  161. completionEntriesForSystemHeaders(completionInfo.includedSystem,result);
  162. foreach (QString headerName, completionInfo.included) {
  163. QString headerText=mainForm->textForHeader(headerName);
  164. if (!headerText.isNull())
  165. if (!completionEntriesForFile(headerText,headerName,mainForm,result))
  166. return false;
  167. }
  168. return true;
  169. }
  170. bool completionEntriesForFile(const QString &fileText,
  171. const QString &fileName,
  172. MainForm *mainForm,
  173. QLinkedList<CompletionEntry> &result)
  174. {
  175. resetSearchedFlags();
  176. return completionEntriesForFileRecursive(fileText,fileName,mainForm,result);
  177. }
  178. static QLinkedList<CompletionEntry> sortCompletionEntries(
  179. const QLinkedList<CompletionEntry> &entries)
  180. {
  181. QMap<QString,QLinkedList<CompletionEntry> > map;
  182. foreach (CompletionEntry entry, entries) {
  183. QLinkedList<CompletionEntry> &list=map[entry.text];
  184. if (!list.contains(entry)) list.append(entry);
  185. }
  186. QLinkedList<CompletionEntry> result;
  187. for (QMap<QString,QLinkedList<CompletionEntry> >::ConstIterator
  188. it=map.begin(); it!=map.end(); ++it)
  189. mergeCompletionEntries(result,*it);
  190. return result;
  191. }
  192. static QStringList prototypesForIdentifier(const QString &identifier,
  193. const QLinkedList<CompletionEntry> &entries)
  194. {
  195. QStringList result;
  196. QStringList reservedIdentifiers=QString("__alignof__\n"
  197. "__asm__\n"
  198. "__attribute__\n"
  199. "__complex__\n"
  200. "__const__\n"
  201. "__extension__\n"
  202. "__imag__\n"
  203. "__inline__\n"
  204. "__label__\n"
  205. "__real__\n"
  206. "__typeof__\n"
  207. "asm\n"
  208. "auto\n"
  209. "break\n"
  210. "case\n"
  211. "char\n"
  212. "const\n"
  213. "continue\n"
  214. "default\n"
  215. "do\n"
  216. "double\n"
  217. "else\n"
  218. "enum\n"
  219. "extern\n"
  220. "float\n"
  221. "for\n"
  222. "goto\n"
  223. "if\n"
  224. "inline\n"
  225. "int\n"
  226. "long\n"
  227. "register\n"
  228. "return\n"
  229. "short\n"
  230. "signed\n"
  231. "sizeof\n"
  232. "static\n"
  233. "struct\n"
  234. "switch\n"
  235. "typedef\n"
  236. "typeof\n"
  237. "union\n"
  238. "unsigned\n"
  239. "void\n"
  240. "volatile\n"
  241. "while\n").split('\n',QString::SkipEmptyParts);
  242. if (!reservedIdentifiers.contains(identifier)) {
  243. foreach (CompletionEntry entry, entries) {
  244. if (entry.text==identifier) {
  245. QString prototype=entry.prefix+' '+entry.text+entry.postfix;
  246. if (result.find(prototype)==result.end()) result.append(prototype);
  247. }
  248. }
  249. if (result.isEmpty()) {
  250. // Try approximate matching.
  251. unsigned identifierLength=identifier.length();
  252. if (identifierLength>=4) {
  253. QString identifierUpper=identifier.toUpper();
  254. QLinkedList<unsigned> distances;
  255. foreach (CompletionEntry entry, entries) {
  256. QString entryText=entry.text;
  257. unsigned entryTextLength=entryText.length();
  258. unsigned minLength=qMin(identifierLength,entryTextLength);
  259. unsigned i=0;
  260. for (; i<minLength && identifierUpper[i]==entryText[i].toUpper(); i++);
  261. unsigned distance=minLength-i;
  262. if (distance<=(minLength>>1)) {
  263. QString prototype=entryText+"? "+entry.prefix+' '+entry.postfix;
  264. if (result.find(prototype)==result.end()) {
  265. // Sort by similarity. Smaller distances first.
  266. QStringList::Iterator it1=result.begin();
  267. QLinkedList<unsigned>::Iterator it2=distances.begin();
  268. for (; it2!=distances.end() && *it2<=distance; ++it1,++it2);
  269. result.insert(it1,prototype);
  270. distances.insert(it2,distance);
  271. }
  272. }
  273. }
  274. }
  275. }
  276. }
  277. return result;
  278. }
  279. bool parseHelpSources(QWidget *parent, const QString &directory,
  280. QMap<QString,CompletionInfo> &sysHdrCompletion)
  281. {
  282. QDir qdir(directory);
  283. QStringList headers=qdir.entryList("*.h",QDir::Dirs);
  284. foreach (QString header, headers) {
  285. CompletionInfo &completionInfo=sysHdrCompletion[header];
  286. QLinkedList<CompletionEntry> &entries=completionInfo.entries;
  287. QDir hdrQdir(QFileInfo(qdir,header).filePath());
  288. QStringList hsfs=hdrQdir.entryList("*.hsf *.ref",QDir::Files);
  289. foreach (QString hsf, hsfs) {
  290. QString fileText=loadFileText(QFileInfo(hdrQdir,hsf).filePath());
  291. if (fileText.isNull()) {
  292. KMessageBox::error(parent,QString("Can't open \'%1/%2\'.").arg(header)
  293. .arg(hsf));
  294. return false;
  295. }
  296. if (hsf.endsWith(".ref")) {
  297. QString realHeader=fileText.trimmed();
  298. QDir realHdrQdir(QFileInfo(qdir,realHeader).filePath());
  299. QString realHsf=hsf;
  300. realHsf.replace(realHsf.length()-3,3,"hsf");
  301. fileText=loadFileText(QFileInfo(realHdrQdir,realHsf).filePath());
  302. if (fileText.isNull()) {
  303. KMessageBox::error(parent,QString("Can't open \'%1/%2\'.").arg(realHeader)
  304. .arg(realHsf));
  305. return false;
  306. }
  307. }
  308. CompletionEntry entry;
  309. QStringList lines=fileText.split('\n');
  310. foreach (QString line, lines) {
  311. if (line.startsWith("Name=")) {
  312. entry.text=line.mid(5);
  313. break;
  314. }
  315. }
  316. bool isType=false;
  317. foreach (QString line, lines) {
  318. if (line.startsWith("Type=")) {
  319. QString hsfType=line.mid(5);
  320. if (hsfType=="Type") isType=true;
  321. entry.prefix=isType?"type"
  322. :(hsfType=="Function")?"func"
  323. :(hsfType=="Constant")?"const"
  324. :(hsfType=="Variable")?"var":hsfType;
  325. break;
  326. }
  327. }
  328. QRegExp comments("/\\*.*\\*/");
  329. comments.setMinimal(true);
  330. QString definition;
  331. foreach (QString line, lines) {
  332. if (line.startsWith("Definition=")) {
  333. definition=line.mid(11);
  334. definition.remove(comments);
  335. int pos=definition.find(entry.text);
  336. QString left=(pos>=0)?definition.left(pos).trimmed()
  337. :QString::null;
  338. QString right;
  339. if (left.startsWith("typedef")) {
  340. entry.postfix=left.mid(8).simplified();
  341. left=QString::null;
  342. } else if (left=="unknown_retval") left="?";
  343. else if (left=="#define") left=QString::null;
  344. if (!left.isEmpty()) {
  345. left.prepend(' ');
  346. entry.prefix+=left;
  347. }
  348. entry.postfix+=definition.mid(pos+entry.text.length()).simplified();
  349. break;
  350. }
  351. }
  352. QStringList::ConstIterator desc=lines.find("[Description]");
  353. QString description;
  354. if (desc!=lines.end() && ++desc!=lines.end()) description=*desc;
  355. description.remove(QRegExp("<A [^>]*>",FALSE)).remove("</A>",FALSE);
  356. if (description.isEmpty()) description=QString::null;
  357. entry.comment=description;
  358. if (isType) {
  359. for (QStringList::ConstIterator it=lines.begin(); it!=lines.end(); ++it) {
  360. const QString &line=*it;
  361. if (line.startsWith("Subtype=")
  362. || (!line.isEmpty() && line[0]=='[' && line!="[Main]")) {
  363. if (line=="Subtype=Enumeration") {
  364. int pos1=definition.find('{');
  365. if (pos1>=0) {
  366. QString left=definition.left(pos1).trimmed();
  367. int pos2=definition.find('}',++pos1);
  368. if (pos2>=0) {
  369. QString itemList=definition.mid(pos1,pos2-pos1);
  370. if (itemList=="...") {
  371. for (QStringList::ConstIterator it=lines.begin(); it!=lines.end(); ++it) {
  372. const QString &line=*it;
  373. if (line.startsWith("Real Definition=")) {
  374. QString realDefinition=line.mid(16);
  375. realDefinition.remove(comments);
  376. pos1=realDefinition.find('{');
  377. if (pos1>=0) {
  378. left=realDefinition.left(pos1).trimmed();
  379. pos2=realDefinition.find('}',++pos1);
  380. if (pos2>=0) {
  381. itemList=realDefinition.mid(pos1,pos2-pos1);
  382. goto foundDefinition;
  383. }
  384. }
  385. break;
  386. }
  387. }
  388. } else {
  389. foundDefinition:
  390. QStringList enumItems=itemList.split(',',QString::SkipEmptyParts);
  391. for (QStringList::ConstIterator it=enumItems.begin();
  392. it!=enumItems.end(); ++it) {
  393. const QString &enumItem=*it;
  394. CompletionEntry enumEntry;
  395. int pos=enumItem.find('=');
  396. if (pos>=0) {
  397. enumEntry.text=enumItem.left(pos).trimmed();
  398. enumEntry.postfix=enumItem.mid(pos+1).trimmed();
  399. } else enumEntry.text=enumItem.trimmed();
  400. enumEntry.prefix=left;
  401. enumEntry.comment=description;
  402. entries.append(enumEntry);
  403. }
  404. }
  405. }
  406. }
  407. }
  408. break;
  409. }
  410. }
  411. }
  412. if (entry.text.trimmed().isEmpty()) {
  413. // No function name, so use HSF name. Can happen for _ROM_CALL_*.
  414. if (!hsf.startsWith("_ROM_CALL_"))
  415. KMessageBox::sorry(parent,QString("No name found in %1/%2").arg(header)
  416. .arg(hsf),
  417. "Warning");
  418. entry.text=hsf.left(hsf.length()-4);
  419. }
  420. entries.append(entry);
  421. }
  422. }
  423. return true;
  424. }
  425. bool parseSystemHeaders(QWidget *parent, const QString &directory,
  426. QMap<QString,CompletionInfo> &sysHdrCompletion)
  427. {
  428. QDir qdir(directory);
  429. QStringList headers=qdir.entryList("*.h",QDir::Files);
  430. foreach (QString header, headers) {
  431. QString fileText=loadFileText(QFileInfo(qdir,header).filePath());
  432. if (fileText.isNull()) {
  433. KMessageBox::error(parent,QString("Can't open \'%1\'.").arg(header));
  434. return false;
  435. }
  436. sysHdrCompletion[header]=parseFileCompletion(fileText,QString::null,
  437. sysHdrCompletion[header]);
  438. if (sysHdrCompletion[header].dirty) return false;
  439. }
  440. return true;
  441. }
  442. void loadSystemHeaderCompletion(void)
  443. {
  444. #ifdef HAVE_KSHAREDCONFIG_H
  445. KConfig config("data","ktigcc/completion",KConfig::NoGlobals);
  446. #else
  447. KConfig config("ktigcc/completion",true,false,"data");
  448. #endif
  449. QStringList groupList=config.groupList();
  450. if (groupList.isEmpty()) {
  451. KMessageBox::queuedMessageBox(0,KMessageBox::Sorry,
  452. "<p>No completion data found for TIGCCLIB headers. KTIGCC will not be "
  453. "able to show completion entries for system headers. You have 2 options "
  454. "to fix this:</p>"
  455. "<p>1. Download ktigcc-completion-data from "
  456. "<a href=\"http://sourceforge.net/project/showfiles.php?group_id=31034"
  457. "&amp;package_id=200501\">http://sourceforge.net/project/showfiles.php?"
  458. "group_id=31034&amp;package_id=200501</a> (recommended).</p>"
  459. "<p>2. Regenerate the data yourself through File/Preferences/Coding "
  460. "(TIGCC source code required).</p>","No Completion Data",
  461. KMessageBox::Notify|KMessageBox::AllowLink);
  462. }
  463. systemHeaderCompletion.clear();
  464. foreach (QString key, groupList) {
  465. if (key.endsWith(" Lines")) continue;
  466. CompletionInfo completionInfo;
  467. config.setGroup(key);
  468. completionInfo.includedSystem=config.readListEntry("Included");
  469. unsigned numEntries=config.readUnsignedNumEntry("Num Entries");
  470. for (unsigned i=0; i<numEntries; i++) {
  471. CompletionEntry entry;
  472. entry.type=config.readEntry(QString("Entry %1 Type").arg(i));
  473. entry.text=config.readEntry(QString("Entry %1 Text").arg(i));
  474. entry.prefix=config.readEntry(QString("Entry %1 Prefix").arg(i));
  475. entry.postfix=config.readEntry(QString("Entry %1 Postfix").arg(i));
  476. entry.comment=config.readEntry(QString("Entry %1 Comment").arg(i));
  477. entry.userdata=config.readEntry(QString("Entry %1 User Data").arg(i));
  478. completionInfo.entries.append(entry);
  479. }
  480. QMap<QString,QString> entryMap=config.entryMap(key+" Lines");
  481. for (QMap<QString,QString>::ConstIterator it=entryMap.begin();
  482. it!=entryMap.end(); ++it)
  483. completionInfo.lineNumbers.insert(it.key(),(*it).toUInt());
  484. systemHeaderCompletion.insert(key,completionInfo);
  485. }
  486. }
  487. void saveSystemHeaderCompletion(void)
  488. {
  489. #ifdef HAVE_KSHAREDCONFIG_H
  490. KConfig config("data","ktigcc/completion",KConfig::NoGlobals);
  491. #else
  492. KConfig config("ktigcc/completion",false,false,"data");
  493. #endif
  494. for (QMap<QString,CompletionInfo>::ConstIterator it=systemHeaderCompletion.begin();
  495. it!=systemHeaderCompletion.end(); ++it) {
  496. const QString &key=it.key();
  497. const CompletionInfo &completionInfo=*it;
  498. config.setGroup(key);
  499. config.writeEntry("Included",completionInfo.includedSystem);
  500. unsigned i=0;
  501. foreach (CompletionEntry entry, completionInfo.entries) {
  502. config.writeEntry(QString("Entry %1 Type").arg(i),entry.type);
  503. config.writeEntry(QString("Entry %1 Text").arg(i),entry.text);
  504. config.writeEntry(QString("Entry %1 Prefix").arg(i),entry.prefix);
  505. config.writeEntry(QString("Entry %1 Postfix").arg(i),entry.postfix);
  506. config.writeEntry(QString("Entry %1 Comment").arg(i),entry.comment);
  507. config.writeEntry(QString("Entry %1 User Data").arg(i),entry.userdata);
  508. }
  509. config.writeEntry("Num Entries",i);
  510. config.setGroup(key+" Lines");
  511. for (QMap<QString,unsigned>::ConstIterator it=completionInfo.lineNumbers.begin();
  512. it!=completionInfo.lineNumbers.end(); ++it)
  513. config.writeEntry(it.key(),*it);
  514. }
  515. config.sync();
  516. }
  517. TemplatePopup::TemplatePopup(KTextEditor::View *parent)
  518. : Q3PopupMenu(parent), view(parent)
  519. {
  520. connect(this,SIGNAL(activated(int)),this,SLOT(QPopupMenu_activated(int)));
  521. unsigned i=0;
  522. for (QLinkedList<QPair<QString,QString> >::ConstIterator it=preferences.templates.begin();
  523. it!=preferences.templates.end(); ++it, i++)
  524. insertItem((*it).first,i);
  525. typedef const QPair<QString,QString> &StringPairConstRef;
  526. foreach (StringPairConstRef pair, preferences.templates)
  527. insertItem(pair.first, i++);
  528. QPoint pos=parent->cursorPositionCoordinates();
  529. if (pos.x()<0 || pos.y()<0) {
  530. // Cursor outside of the view, so center on view instead.
  531. QSize parentSize=parent->size();
  532. QSize popupSize=sizeHint();
  533. pos.setX((parentSize.width()-popupSize.width())>>1);
  534. pos.setY((parentSize.height()-popupSize.height())>>1);
  535. }
  536. exec(parent->mapToGlobal(pos));
  537. deleteLater();
  538. }
  539. void TemplatePopup::QPopupMenu_activated(int id)
  540. {
  541. KTextEditor::Document *doc=view->document();
  542. QString code=preferences.templates[id].second;
  543. QString indent=doc->line(view->cursorPosition().line());
  544. // Remove everything starting from the first non-whitespace character.
  545. indent=indent.remove(QRegExp("(?!\\s).*$"));
  546. indent.prepend('\n');
  547. code.replace('\n',indent);
  548. int cursorPos=code.find('|');
  549. if (cursorPos>=0) {
  550. QString left=code.left(cursorPos);
  551. QString right=code.mid(cursorPos+1);
  552. int row, col;
  553. doc->startEditing();
  554. view->insertText(left);
  555. view->cursorPosition().position(row,col);
  556. view->insertText(right);
  557. doc->endEditing();
  558. view->setCursorPosition(KTextEditor::Cursor(row,col));
  559. } else view->insertText(code);
  560. }
  561. CompletionPopup::CompletionPopup(KTextEditor::View *parent, const QString &fileName,
  562. MainForm *mainForm, QObject *receiver)
  563. : QObject(parent), done(false), completionPopup(0)
  564. {
  565. connect(this,SIGNAL(closed()),receiver,SLOT(completionPopup_closed()));
  566. QLinkedList<CompletionEntry> entries;
  567. if (!completionEntriesForFile(parent->document()->text(),fileName,mainForm,
  568. entries)) {
  569. emit closed();
  570. deleteLater();
  571. return;
  572. }
  573. entries=sortCompletionEntries(entries);
  574. KTextEditor::Cursor cursor=parent->cursorPosition();
  575. int column=cursor.column();
  576. int offset=0;
  577. if (column) {
  578. QString textLine=parent->document()->line(cursor.line());
  579. if (column<=textLine.length()) {
  580. while (column && (textLine[--column].isLetterOrNumber()
  581. || textLine[column]=='_' || textLine[column]=='$'))
  582. offset++;
  583. }
  584. }
  585. #if 0 // FIXME: Port completion.
  586. connect(parent,SIGNAL(completionAborted()),this,SLOT(slotDone()));
  587. connect(parent,SIGNAL(completionDone()),this,SLOT(slotDone()));
  588. parent->showCompletionBox(entries,offset);
  589. // Unfortunately, Kate doesn't always send the completionAborted or
  590. // completionDone event when it closes its popup. Work around that.
  591. QWidgetList *list=QApplication::topLevelWidgets();
  592. QWidgetListIt it(*list);
  593. while (QWidget *w=it.current()) {
  594. ++it;
  595. if (w->isVisible() && w->testWFlags(Qt::WType_Popup)
  596. && !std::strcmp(w->className(),"QVBox")) {
  597. completionPopup=w;
  598. break;
  599. }
  600. }
  601. delete list;
  602. if (completionPopup)
  603. completionPopup->installEventFilter(this);
  604. #else
  605. slotDone();
  606. #endif
  607. }
  608. void CompletionPopup::slotDone()
  609. {
  610. if (!done) {
  611. done=true;
  612. emit closed();
  613. deleteLater();
  614. }
  615. }
  616. bool CompletionPopup::eventFilter(QObject *o, QEvent *e)
  617. {
  618. if (!done && o==completionPopup && e->type()==QEvent::Hide) {
  619. done=true;
  620. emit closed();
  621. deleteLater();
  622. }
  623. return false;
  624. }
  625. ArgHintPopup::ArgHintPopup(KTextEditor::View *parent, const QString &fileName,
  626. MainForm *mainForm)
  627. : QObject(parent), done(false), argHintPopup(0)
  628. {
  629. QLinkedList<CompletionEntry> entries;
  630. if (!completionEntriesForFile(parent->document()->text(),fileName,mainForm,
  631. entries)) {
  632. nothingFound:
  633. deleteLater();
  634. return;
  635. }
  636. KTextEditor::Cursor cursor=parent->cursorPosition();
  637. int column=cursor.column();
  638. if (!column || !--column) goto nothingFound;
  639. QString textLine=parent->document()->line(cursor.line());
  640. if (column>textLine.length() || textLine[column]!='(') goto nothingFound;
  641. while (column && textLine[column-1].isSpace()) column--;
  642. if (!column) goto nothingFound;
  643. unsigned startColumn=column, endColumn=column;
  644. while (column && (textLine[--column].isLetterOrNumber()
  645. || textLine[column]=='_' || textLine[column]=='$'))
  646. startColumn--;
  647. if (startColumn==endColumn) goto nothingFound;
  648. QString identifier=textLine.mid(startColumn,endColumn-startColumn);
  649. QStringList prototypes=prototypesForIdentifier(identifier,entries);
  650. if (prototypes.isEmpty()) goto nothingFound;
  651. #if 0 // FIXME: Port completion.
  652. connect(parent,SIGNAL(argHintHidden()),this,SLOT(slotDone()));
  653. parent->showArgHint(prototypes,"()",",");
  654. // Unfortunately, Kate doesn't always send the argHintHidden event when it
  655. // closes its popup. Work around that.
  656. QWidgetList *list=QApplication::topLevelWidgets();
  657. QWidgetListIt it(*list);
  658. while (QWidget *w=it.current()) {
  659. ++it;
  660. if (w->isVisible() && w->testWFlags(Qt::WType_Popup)
  661. && !std::strcmp(w->className(),"KateArgHint")) {
  662. argHintPopup=w;
  663. break;
  664. }
  665. }
  666. delete list;
  667. if (argHintPopup)
  668. argHintPopup->installEventFilter(this);
  669. #else
  670. slotDone();
  671. #endif
  672. }
  673. void ArgHintPopup::slotDone()
  674. {
  675. if (!done) {
  676. done=true;
  677. deleteLater();
  678. }
  679. }
  680. bool ArgHintPopup::eventFilter(QObject *o, QEvent *e)
  681. {
  682. if (!done && o==argHintPopup && e->type()==QEvent::Hide) {
  683. done=true;
  684. deleteLater();
  685. }
  686. return false;
  687. }