1
0

fb2code.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. #include "fb2code.hpp"
  2. #ifdef FB2_USE_SCINTILLA
  3. /////////////////////////////////////////////////////////////////////////////
  4. //
  5. // http://qtcoder.blogspot.com/2010/10/qscintills.html
  6. // http://www.riverbankcomputing.co.uk/static/Docs/QScintilla2/classQsciScintilla.html
  7. //
  8. /////////////////////////////////////////////////////////////////////////////
  9. #include <Qsci/qscilexerxml.h>
  10. #include <QtDebug>
  11. Fb2CodeEdit::Fb2CodeEdit(QWidget *parent) :
  12. QsciScintilla(parent)
  13. {
  14. zoomTo(1);
  15. setUtf8(true);
  16. setCaretLineVisible(true);
  17. setCaretLineBackgroundColor(QColor("gainsboro"));
  18. setWrapMode(QsciScintilla::WrapWord);
  19. /*
  20. //setup autocompletion
  21. setAutoCompletionSource(QsciScintilla::AcsAll);
  22. setAutoCompletionCaseSensitivity(true);
  23. setAutoCompletionReplaceWord(true);
  24. setAutoCompletionShowSingle(true);
  25. setAutoCompletionThreshold(2);
  26. */
  27. //setup margins
  28. setMarginsBackgroundColor(QColor("gainsboro"));
  29. setMarginLineNumbers(0, true);
  30. setFolding(QsciScintilla::BoxedFoldStyle, 1);
  31. //setup brace matching
  32. setBraceMatching(QsciScintilla::SloppyBraceMatch);
  33. setMatchedBraceBackgroundColor(Qt::yellow);
  34. setUnmatchedBraceForegroundColor(Qt::blue);
  35. //setup end-of-line mode
  36. #if defined Q_WS_X11
  37. setEolMode(QsciScintilla::EolUnix);
  38. #elif defined Q_WS_WIN
  39. setEolMode(QsciScintilla::EolWindows);
  40. #elif defined Q_WS_MAC
  41. setEolMode(QsciScintilla::EolMac);
  42. #endif
  43. //setup auto-indentation
  44. setAutoIndent(true);
  45. setIndentationGuides(true);
  46. setIndentationsUseTabs(false);
  47. setIndentationWidth(2);
  48. QsciLexerXML * lexer = new QsciLexerXML;
  49. lexer->setFoldPreprocessor(true);
  50. #ifdef Q_WS_WIN
  51. lexer->setFont(QFont("Courier New", 8));
  52. #else
  53. lexer->setFont(QFont("Monospace", 8));
  54. #endif
  55. setLexer(lexer);
  56. connect(this, SIGNAL(linesChanged()), SLOT(linesChanged()));
  57. }
  58. void Fb2CodeEdit::linesChanged()
  59. {
  60. QString width = QString().setNum(lines() * 10);
  61. setMarginWidth(0, width);
  62. }
  63. void Fb2CodeEdit::load(const QByteArray &array, const QList<int> &folds)
  64. {
  65. SendScintilla(SCI_SETTEXT, array.constData());
  66. SendScintilla(SCI_EMPTYUNDOBUFFER);
  67. foldAll(false);
  68. foldLine(1);
  69. for (QList<int>::const_iterator it = folds.constBegin(); it != folds.constEnd(); it++) {
  70. foldLine(*it);
  71. }
  72. }
  73. void Fb2CodeEdit::zoomReset()
  74. {
  75. if (codeEdit) codeEdit->zoomTo(1);
  76. }
  77. #endif // FB2_USE_SCINTILLA
  78. #ifdef FB2_USE_PLAINTEXT
  79. #include <QtGui>
  80. static const QColor DEFAULT_SYNTAX_CHAR = Qt::blue;
  81. static const QColor DEFAULT_ELEMENT_NAME = Qt::darkRed;
  82. static const QColor DEFAULT_COMMENT = Qt::darkGreen;
  83. static const QColor DEFAULT_ATTRIBUTE_NAME = Qt::red;
  84. static const QColor DEFAULT_ATTRIBUTE_VALUE = Qt::darkGreen;
  85. static const QColor DEFAULT_ERROR = Qt::darkMagenta;
  86. static const QColor DEFAULT_OTHER = Qt::black;
  87. // Regular expressions for parsing XML borrowed from:
  88. // http://www.cs.sfu.ca/~cameron/REX.html
  89. static const QString EXPR_COMMENT = "<!--[^-]*-([^-][^-]*-)*->";
  90. static const QString EXPR_COMMENT_BEGIN = "<!--";
  91. static const QString EXPR_COMMENT_END = "[^-]*-([^-][^-]*-)*->";
  92. static const QString EXPR_ATTRIBUTE_VALUE = "\"[^<\"]*\"|'[^<']*'";
  93. static const QString EXPR_NAME = "([A-Za-z_:]|[^\\x00-\\x7F])([A-Za-z0-9_:.-]|[^\\x00-\\x7F])*";
  94. Fb2Highlighter::Fb2Highlighter(QObject* parent)
  95. : QSyntaxHighlighter(parent)
  96. {
  97. init();
  98. }
  99. Fb2Highlighter::Fb2Highlighter(QTextDocument* parent)
  100. : QSyntaxHighlighter(parent)
  101. {
  102. init();
  103. }
  104. Fb2Highlighter::Fb2Highlighter(QTextEdit* parent)
  105. : QSyntaxHighlighter(parent)
  106. {
  107. init();
  108. }
  109. Fb2Highlighter::~Fb2Highlighter()
  110. {
  111. }
  112. void Fb2Highlighter::init()
  113. {
  114. fmtSyntaxChar.setForeground(DEFAULT_SYNTAX_CHAR);
  115. fmtElementName.setForeground(DEFAULT_ELEMENT_NAME);
  116. fmtComment.setForeground(DEFAULT_COMMENT);
  117. fmtAttributeName.setForeground(DEFAULT_ATTRIBUTE_NAME);
  118. fmtAttributeValue.setForeground(DEFAULT_ATTRIBUTE_VALUE);
  119. fmtError.setForeground(DEFAULT_ERROR);
  120. fmtOther.setForeground(DEFAULT_OTHER);
  121. }
  122. void Fb2Highlighter::setHighlightColor(HighlightType type, QColor color, bool foreground)
  123. {
  124. QTextCharFormat format;
  125. if (foreground)
  126. format.setForeground(color);
  127. else
  128. format.setBackground(color);
  129. setHighlightFormat(type, format);
  130. }
  131. void Fb2Highlighter::setHighlightFormat(HighlightType type, QTextCharFormat format)
  132. {
  133. switch (type)
  134. {
  135. case SyntaxChar:
  136. fmtSyntaxChar = format;
  137. break;
  138. case ElementName:
  139. fmtElementName = format;
  140. break;
  141. case Comment:
  142. fmtComment = format;
  143. break;
  144. case AttributeName:
  145. fmtAttributeName = format;
  146. break;
  147. case AttributeValue:
  148. fmtAttributeValue = format;
  149. break;
  150. case Error:
  151. fmtError = format;
  152. break;
  153. case Other:
  154. fmtOther = format;
  155. break;
  156. }
  157. rehighlight();
  158. }
  159. void Fb2Highlighter::highlightBlock(const QString& text)
  160. {
  161. int i = 0;
  162. int pos = 0;
  163. int brackets = 0;
  164. state = (previousBlockState() == InElement ? ExpectAttributeOrEndOfElement : NoState);
  165. if (previousBlockState() == InComment)
  166. {
  167. // search for the end of the comment
  168. QRegExp expression(EXPR_COMMENT_END);
  169. pos = expression.indexIn(text, i);
  170. if (pos >= 0)
  171. {
  172. // end comment found
  173. const int iLength = expression.matchedLength();
  174. setFormat(0, iLength - 3, fmtComment);
  175. setFormat(iLength - 3, 3, fmtSyntaxChar);
  176. i += iLength; // skip comment
  177. }
  178. else
  179. {
  180. // in comment
  181. setFormat(0, text.length(), fmtComment);
  182. setCurrentBlockState(InComment);
  183. return;
  184. }
  185. }
  186. for (; i < text.length(); i++)
  187. {
  188. switch (text.at(i).toAscii())
  189. {
  190. case '<':
  191. brackets++;
  192. if (brackets == 1)
  193. {
  194. setFormat(i, 1, fmtSyntaxChar);
  195. state = ExpectElementNameOrSlash;
  196. }
  197. else
  198. {
  199. // wrong bracket nesting
  200. setFormat(i, 1, fmtError);
  201. }
  202. break;
  203. case '>':
  204. brackets--;
  205. if (brackets == 0)
  206. {
  207. setFormat(i, 1, fmtSyntaxChar);
  208. }
  209. else
  210. {
  211. // wrong bracket nesting
  212. setFormat( i, 1, fmtError);
  213. }
  214. state = NoState;
  215. break;
  216. case '/':
  217. if (state == ExpectElementNameOrSlash)
  218. {
  219. state = ExpectElementName;
  220. setFormat(i, 1, fmtSyntaxChar);
  221. }
  222. else
  223. {
  224. if (state == ExpectAttributeOrEndOfElement)
  225. {
  226. setFormat(i, 1, fmtSyntaxChar);
  227. }
  228. else
  229. {
  230. processDefaultText(i, text);
  231. }
  232. }
  233. break;
  234. case '=':
  235. if (state == ExpectEqual)
  236. {
  237. state = ExpectAttributeValue;
  238. setFormat(i, 1, fmtOther);
  239. }
  240. else
  241. {
  242. processDefaultText(i, text);
  243. }
  244. break;
  245. case '\'':
  246. case '\"':
  247. if (state == ExpectAttributeValue)
  248. {
  249. // search attribute value
  250. QRegExp expression(EXPR_ATTRIBUTE_VALUE);
  251. pos = expression.indexIn(text, i);
  252. if (pos == i) // attribute value found ?
  253. {
  254. const int iLength = expression.matchedLength();
  255. setFormat(i, 1, fmtOther);
  256. setFormat(i + 1, iLength - 2, fmtAttributeValue);
  257. setFormat(i + iLength - 1, 1, fmtOther);
  258. i += iLength - 1; // skip attribute value
  259. state = ExpectAttributeOrEndOfElement;
  260. }
  261. else
  262. {
  263. processDefaultText(i, text);
  264. }
  265. }
  266. else
  267. {
  268. processDefaultText(i, text);
  269. }
  270. break;
  271. case '!':
  272. if (state == ExpectElementNameOrSlash)
  273. {
  274. // search comment
  275. QRegExp expression(EXPR_COMMENT);
  276. pos = expression.indexIn(text, i - 1);
  277. if (pos == i - 1) // comment found ?
  278. {
  279. const int iLength = expression.matchedLength();
  280. setFormat(pos, 4, fmtSyntaxChar);
  281. setFormat(pos + 4, iLength - 7, fmtComment);
  282. setFormat(iLength - 3, 3, fmtSyntaxChar);
  283. i += iLength - 2; // skip comment
  284. state = NoState;
  285. brackets--;
  286. }
  287. else
  288. {
  289. // Try find multiline comment
  290. QRegExp expression(EXPR_COMMENT_BEGIN); // search comment start
  291. pos = expression.indexIn(text, i - 1);
  292. //if (pos == i - 1) // comment found ?
  293. if (pos >= i - 1)
  294. {
  295. setFormat(i, 3, fmtSyntaxChar);
  296. setFormat(i + 3, text.length() - i - 3, fmtComment);
  297. setCurrentBlockState(InComment);
  298. return;
  299. }
  300. else
  301. {
  302. processDefaultText(i, text);
  303. }
  304. }
  305. }
  306. else
  307. {
  308. processDefaultText(i, text);
  309. }
  310. break;
  311. default:
  312. const int iLength = processDefaultText(i, text);
  313. if (iLength > 0)
  314. i += iLength - 1;
  315. break;
  316. }
  317. }
  318. if (state == ExpectAttributeOrEndOfElement)
  319. {
  320. setCurrentBlockState(InElement);
  321. }
  322. }
  323. int Fb2Highlighter::processDefaultText(int i, const QString& text)
  324. {
  325. // length of matched text
  326. int iLength = 0;
  327. switch(state)
  328. {
  329. case ExpectElementNameOrSlash:
  330. case ExpectElementName:
  331. {
  332. // search element name
  333. QRegExp expression(EXPR_NAME);
  334. const int pos = expression.indexIn(text, i);
  335. if (pos == i) // found ?
  336. {
  337. iLength = expression.matchedLength();
  338. setFormat(pos, iLength, fmtElementName);
  339. state = ExpectAttributeOrEndOfElement;
  340. }
  341. else
  342. {
  343. setFormat(i, 1, fmtOther);
  344. }
  345. }
  346. break;
  347. case ExpectAttributeOrEndOfElement:
  348. {
  349. // search attribute name
  350. QRegExp expression(EXPR_NAME);
  351. const int pos = expression.indexIn(text, i);
  352. if (pos == i) // found ?
  353. {
  354. iLength = expression.matchedLength();
  355. setFormat(pos, iLength, fmtAttributeName);
  356. state = ExpectEqual;
  357. }
  358. else
  359. {
  360. setFormat(i, 1, fmtOther);
  361. }
  362. }
  363. break;
  364. default:
  365. setFormat(i, 1, fmtOther);
  366. break;
  367. }
  368. return iLength;
  369. }
  370. qreal Fb2CodeEdit::baseFontSize = 10;
  371. qreal Fb2CodeEdit::zoomRatioMin = 0.2;
  372. qreal Fb2CodeEdit::zoomRatioMax = 5.0;
  373. Fb2CodeEdit::Fb2CodeEdit(QWidget *parent) : QPlainTextEdit(parent)
  374. {
  375. lineNumberArea = new LineNumberArea(this);
  376. highlighter = new Fb2Highlighter(this);
  377. highlighter->setDocument( document() );
  378. connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateLineNumberAreaWidth(int)));
  379. connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateLineNumberArea(QRect,int)));
  380. connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine()));
  381. zoomRatio = 1;
  382. #ifdef Q_WS_WIN
  383. setFont(QFont("Courier New", baseFontSize));
  384. #else
  385. setFont(QFont("Monospace", baseFontSize));
  386. #endif
  387. updateLineNumberAreaWidth(0);
  388. highlightCurrentLine();
  389. }
  390. int Fb2CodeEdit::lineNumberAreaWidth()
  391. {
  392. int digits = 1;
  393. int max = qMax(1, blockCount());
  394. while (max >= 10) {
  395. max /= 10;
  396. ++digits;
  397. }
  398. int space = 3 + fontMetrics().width(QLatin1Char('9')) * digits;
  399. return space;
  400. }
  401. void Fb2CodeEdit::updateLineNumberAreaWidth(int /* newBlockCount */)
  402. {
  403. setViewportMargins(lineNumberAreaWidth(), 0, 0, 0);
  404. }
  405. void Fb2CodeEdit::updateLineNumberArea(const QRect &rect, int dy)
  406. {
  407. if (dy)
  408. lineNumberArea->scroll(0, dy);
  409. else
  410. lineNumberArea->update(0, rect.y(), lineNumberArea->width(), rect.height());
  411. if (rect.contains(viewport()->rect()))
  412. updateLineNumberAreaWidth(0);
  413. }
  414. void Fb2CodeEdit::resizeEvent(QResizeEvent *e)
  415. {
  416. QPlainTextEdit::resizeEvent(e);
  417. QRect cr = contentsRect();
  418. lineNumberArea->setGeometry(QRect(cr.left(), cr.top(), lineNumberAreaWidth(), cr.height()));
  419. }
  420. void Fb2CodeEdit::highlightCurrentLine()
  421. {
  422. QList<QTextEdit::ExtraSelection> extraSelections;
  423. if (!isReadOnly()) {
  424. QTextEdit::ExtraSelection selection;
  425. QColor lineColor = QColor(Qt::yellow).lighter(160);
  426. selection.format.setBackground(lineColor);
  427. selection.format.setProperty(QTextFormat::FullWidthSelection, true);
  428. selection.cursor = textCursor();
  429. selection.cursor.clearSelection();
  430. extraSelections.append(selection);
  431. }
  432. setExtraSelections(extraSelections);
  433. }
  434. void Fb2CodeEdit::lineNumberAreaPaintEvent(QPaintEvent *event)
  435. {
  436. QPainter painter(lineNumberArea);
  437. painter.fillRect(event->rect(), Qt::lightGray);
  438. QTextBlock block = firstVisibleBlock();
  439. int blockNumber = block.blockNumber();
  440. int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
  441. int bottom = top + (int) blockBoundingRect(block).height();
  442. while (block.isValid() && top <= event->rect().bottom()) {
  443. if (block.isVisible() && bottom >= event->rect().top()) {
  444. QString number = QString::number(blockNumber + 1);
  445. painter.setPen(Qt::black);
  446. painter.drawText(0, top, lineNumberArea->width(), fontMetrics().height(),
  447. Qt::AlignRight, number);
  448. }
  449. block = block.next();
  450. top = bottom;
  451. bottom = top + (int) blockBoundingRect(block).height();
  452. ++blockNumber;
  453. }
  454. }
  455. void Fb2CodeEdit::zoomIn()
  456. {
  457. qreal ratio = zoomRatio * 1.1;
  458. ratio = qMin(ratio, zoomRatioMax);
  459. setZoomRatio(ratio);
  460. }
  461. void Fb2CodeEdit::zoomOut()
  462. {
  463. qreal ratio = zoomRatio / 1.1;
  464. ratio = qMax(ratio, zoomRatioMin);
  465. setZoomRatio(ratio);
  466. }
  467. void Fb2CodeEdit::zoomReset()
  468. {
  469. setZoomRatio(1.0);
  470. }
  471. void Fb2CodeEdit::setZoomRatio(qreal ratio)
  472. {
  473. if (!qFuzzyCompare(1 + zoomRatio, 1 + ratio)) {
  474. zoomRatio = ratio;
  475. QFont f = font();
  476. f.setPointSizeF(baseFontSize * zoomRatio);
  477. setFont(f);
  478. }
  479. }
  480. #endif // FB2_USE_PLAINTEXT