vsnippetlist.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. #include "vsnippetlist.h"
  2. #include <QtWidgets>
  3. #include "vconfigmanager.h"
  4. #include "dialog/veditsnippetdialog.h"
  5. #include "utils/vutils.h"
  6. #include "utils/vimnavigationforwidget.h"
  7. #include "dialog/vsortdialog.h"
  8. #include "dialog/vconfirmdeletiondialog.h"
  9. #include "vmainwindow.h"
  10. #include "utils/viconutils.h"
  11. extern VConfigManager *g_config;
  12. extern VMainWindow *g_mainWin;
  13. const QString VSnippetList::c_infoShortcutSequence = "F2";
  14. VSnippetList::VSnippetList(QWidget *p_parent)
  15. : QWidget(p_parent)
  16. {
  17. setupUI();
  18. initShortcuts();
  19. initActions();
  20. if (!readSnippetsFromConfig()) {
  21. VUtils::showMessage(QMessageBox::Warning,
  22. tr("Warning"),
  23. tr("Fail to read snippets from <span style=\"%1\">%2</span>.")
  24. .arg(g_config->c_dataTextStyle)
  25. .arg(g_config->getSnippetConfigFolder()),
  26. "",
  27. QMessageBox::Ok,
  28. QMessageBox::Ok,
  29. this);
  30. }
  31. updateContent();
  32. }
  33. void VSnippetList::setupUI()
  34. {
  35. m_addBtn = new QPushButton(VIconUtils::buttonIcon(":/resources/icons/add_snippet.svg"), "");
  36. m_addBtn->setToolTip(tr("New Snippet"));
  37. m_addBtn->setProperty("FlatBtn", true);
  38. connect(m_addBtn, &QPushButton::clicked,
  39. this, &VSnippetList::newSnippet);
  40. m_locateBtn = new QPushButton(VIconUtils::buttonIcon(":/resources/icons/locate_snippet.svg"), "");
  41. m_locateBtn->setToolTip(tr("Open Folder"));
  42. m_locateBtn->setProperty("FlatBtn", true);
  43. connect(m_locateBtn, &QPushButton::clicked,
  44. this, [this]() {
  45. makeSureFolderExist();
  46. QUrl url = QUrl::fromLocalFile(g_config->getSnippetConfigFolder());
  47. QDesktopServices::openUrl(url);
  48. });
  49. m_numLabel = new QLabel();
  50. QHBoxLayout *btnLayout = new QHBoxLayout;
  51. btnLayout->addWidget(m_addBtn);
  52. btnLayout->addWidget(m_locateBtn);
  53. btnLayout->addStretch();
  54. btnLayout->addWidget(m_numLabel);
  55. btnLayout->setContentsMargins(0, 0, 3, 0);
  56. m_snippetList = new QListWidget();
  57. m_snippetList->setAttribute(Qt::WA_MacShowFocusRect, false);
  58. m_snippetList->setContextMenuPolicy(Qt::CustomContextMenu);
  59. m_snippetList->setSelectionMode(QAbstractItemView::ExtendedSelection);
  60. connect(m_snippetList, &QListWidget::customContextMenuRequested,
  61. this, &VSnippetList::handleContextMenuRequested);
  62. connect(m_snippetList, &QListWidget::itemActivated,
  63. this, &VSnippetList::handleItemActivated);
  64. QVBoxLayout *mainLayout = new QVBoxLayout();
  65. mainLayout->addLayout(btnLayout);
  66. mainLayout->addWidget(m_snippetList);
  67. mainLayout->setContentsMargins(0, 0, 0, 0);
  68. setLayout(mainLayout);
  69. }
  70. void VSnippetList::initActions()
  71. {
  72. m_applyAct = new QAction(VIconUtils::menuIcon(":/resources/icons/apply_snippet.svg"),
  73. tr("&Apply"),
  74. this);
  75. m_applyAct->setToolTip(tr("Insert this snippet in editor"));
  76. connect(m_applyAct, &QAction::triggered,
  77. this, [this]() {
  78. QListWidgetItem *item = m_snippetList->currentItem();
  79. handleItemActivated(item);
  80. });
  81. m_infoAct = new QAction(VIconUtils::menuIcon(":/resources/icons/snippet_info.svg"),
  82. tr("&Info\t%1").arg(VUtils::getShortcutText(c_infoShortcutSequence)),
  83. this);
  84. m_infoAct->setToolTip(tr("View and edit snippet's information"));
  85. connect(m_infoAct, &QAction::triggered,
  86. this, &VSnippetList::snippetInfo);
  87. m_deleteAct = new QAction(VIconUtils::menuDangerIcon(":/resources/icons/delete_snippet.svg"),
  88. tr("&Delete"),
  89. this);
  90. m_deleteAct->setToolTip(tr("Delete selected snippets"));
  91. connect(m_deleteAct, &QAction::triggered,
  92. this, &VSnippetList::deleteSelectedItems);
  93. m_sortAct = new QAction(VIconUtils::menuIcon(":/resources/icons/sort.svg"),
  94. tr("&Sort"),
  95. this);
  96. m_sortAct->setToolTip(tr("Sort snippets manually"));
  97. connect(m_sortAct, &QAction::triggered,
  98. this, &VSnippetList::sortItems);
  99. }
  100. void VSnippetList::initShortcuts()
  101. {
  102. QShortcut *infoShortcut = new QShortcut(QKeySequence(c_infoShortcutSequence), this);
  103. infoShortcut->setContext(Qt::WidgetWithChildrenShortcut);
  104. connect(infoShortcut, &QShortcut::activated,
  105. this, &VSnippetList::snippetInfo);
  106. }
  107. void VSnippetList::newSnippet()
  108. {
  109. QString defaultName = VUtils::getFileNameWithSequence(g_config->getSnippetConfigFolder(),
  110. "snippet");
  111. VSnippet tmpSnippet(defaultName);
  112. QString info = tr("Magic words are supported in the content of the snippet.");
  113. VEditSnippetDialog dialog(tr("Create Snippet"),
  114. info,
  115. m_snippets,
  116. tmpSnippet,
  117. this);
  118. if (dialog.exec() == QDialog::Accepted) {
  119. makeSureFolderExist();
  120. VSnippet snippet(dialog.getNameInput(),
  121. dialog.getTypeInput(),
  122. dialog.getContentInput(),
  123. dialog.getCursorMarkInput(),
  124. dialog.getSelectionMarkInput(),
  125. dialog.getShortcutInput(),
  126. dialog.getAutoIndentInput());
  127. QString errMsg;
  128. if (!addSnippet(snippet, &errMsg)) {
  129. VUtils::showMessage(QMessageBox::Warning,
  130. tr("Warning"),
  131. tr("Fail to create snippet <span style=\"%1\">%2</span>.")
  132. .arg(g_config->c_dataTextStyle)
  133. .arg(snippet.getName()),
  134. errMsg,
  135. QMessageBox::Ok,
  136. QMessageBox::Ok,
  137. this);
  138. updateContent();
  139. }
  140. }
  141. }
  142. void VSnippetList::handleContextMenuRequested(QPoint p_pos)
  143. {
  144. QListWidgetItem *item = m_snippetList->itemAt(p_pos);
  145. QMenu menu(this);
  146. menu.setToolTipsVisible(true);
  147. if (item) {
  148. int itemCount = m_snippetList->selectedItems().size();
  149. if (itemCount == 1) {
  150. menu.addAction(m_applyAct);
  151. menu.addAction(m_infoAct);
  152. }
  153. menu.addAction(m_deleteAct);
  154. }
  155. m_snippetList->update();
  156. if (m_snippets.size() > 1) {
  157. if (!menu.actions().isEmpty()) {
  158. menu.addSeparator();
  159. }
  160. menu.addAction(m_sortAct);
  161. }
  162. if (!menu.actions().isEmpty()) {
  163. menu.exec(m_snippetList->mapToGlobal(p_pos));
  164. }
  165. }
  166. void VSnippetList::handleItemActivated(QListWidgetItem *p_item)
  167. {
  168. const VSnippet *snip = getSnippet(p_item);
  169. if (snip) {
  170. VEditTab *tab = g_mainWin->getCurrentTab();
  171. if (tab) {
  172. tab->applySnippet(snip);
  173. }
  174. }
  175. }
  176. void VSnippetList::deleteSelectedItems()
  177. {
  178. QVector<ConfirmItemInfo> items;
  179. const QList<QListWidgetItem *> selectedItems = m_snippetList->selectedItems();
  180. if (selectedItems.isEmpty()) {
  181. return;
  182. }
  183. for (auto const & item : selectedItems) {
  184. QString name = item->data(Qt::UserRole).toString();
  185. items.push_back(ConfirmItemInfo(name,
  186. name,
  187. "",
  188. NULL));
  189. }
  190. QString text = tr("Are you sure to delete these snippets?");
  191. QString info = tr("Click \"Cancel\" to leave them untouched.");
  192. VConfirmDeletionDialog dialog(tr("Confirm Deleting Snippets"),
  193. text,
  194. info,
  195. items,
  196. false,
  197. false,
  198. false,
  199. this);
  200. if (dialog.exec()) {
  201. items = dialog.getConfirmedItems();
  202. QList<QString> names;
  203. for (auto const & item : items) {
  204. names.append(item.m_name);
  205. }
  206. QString errMsg;
  207. if (!deleteSnippets(names, &errMsg)) {
  208. VUtils::showMessage(QMessageBox::Warning,
  209. tr("Warning"),
  210. tr("Fail to delete snippets."),
  211. errMsg,
  212. QMessageBox::Ok,
  213. QMessageBox::Ok,
  214. this);
  215. }
  216. updateContent();
  217. }
  218. }
  219. void VSnippetList::sortItems()
  220. {
  221. if (m_snippets.size() < 2) {
  222. return;
  223. }
  224. VSortDialog dialog(tr("Sort Snippets"),
  225. tr("Sort snippets in the configuration file."),
  226. this);
  227. QTreeWidget *tree = dialog.getTreeWidget();
  228. tree->clear();
  229. tree->setColumnCount(1);
  230. QStringList headers;
  231. headers << tr("Name");
  232. tree->setHeaderLabels(headers);
  233. for (int i = 0; i < m_snippets.size(); ++i) {
  234. QTreeWidgetItem *item = new QTreeWidgetItem(tree, QStringList(m_snippets[i].getName()));
  235. item->setData(0, Qt::UserRole, i);
  236. }
  237. dialog.treeUpdated();
  238. if (dialog.exec()) {
  239. QVector<QVariant> data = dialog.getSortedData();
  240. Q_ASSERT(data.size() == m_snippets.size());
  241. QVector<int> sortedIdx(data.size(), -1);
  242. for (int i = 0; i < data.size(); ++i) {
  243. sortedIdx[i] = data[i].toInt();
  244. }
  245. QString errMsg;
  246. if (!sortSnippets(sortedIdx, &errMsg)) {
  247. VUtils::showMessage(QMessageBox::Warning,
  248. tr("Warning"),
  249. tr("Fail to sort snippets."),
  250. errMsg,
  251. QMessageBox::Ok,
  252. QMessageBox::Ok,
  253. this);
  254. }
  255. updateContent();
  256. }
  257. }
  258. void VSnippetList::snippetInfo()
  259. {
  260. if (m_snippetList->selectedItems().size() != 1) {
  261. return;
  262. }
  263. QListWidgetItem *item = m_snippetList->currentItem();
  264. VSnippet *snip = getSnippet(item);
  265. if (!snip) {
  266. return;
  267. }
  268. QString info = tr("Magic words are supported in the content of the snippet.");
  269. VEditSnippetDialog dialog(tr("Snippet Information"),
  270. info,
  271. m_snippets,
  272. *snip,
  273. this);
  274. if (dialog.exec() == QDialog::Accepted) {
  275. QString errMsg;
  276. bool ret = true;
  277. if (snip->getName() != dialog.getNameInput()) {
  278. // Delete the original snippet file.
  279. if (!deleteSnippetFile(*snip, &errMsg)) {
  280. ret = false;
  281. }
  282. }
  283. if (snip->update(dialog.getNameInput(),
  284. dialog.getTypeInput(),
  285. dialog.getContentInput(),
  286. dialog.getCursorMarkInput(),
  287. dialog.getSelectionMarkInput(),
  288. dialog.getShortcutInput(),
  289. dialog.getAutoIndentInput())) {
  290. if (!writeSnippetFile(*snip, &errMsg)) {
  291. ret = false;
  292. }
  293. if (!writeSnippetsToConfig()) {
  294. VUtils::addErrMsg(&errMsg,
  295. tr("Fail to write snippets configuration file."));
  296. ret = false;
  297. }
  298. updateContent();
  299. }
  300. if (!ret) {
  301. VUtils::showMessage(QMessageBox::Warning,
  302. tr("Warning"),
  303. tr("Fail to update information of snippet <span style=\"%1\">%2</span>.")
  304. .arg(g_config->c_dataTextStyle)
  305. .arg(snip->getName()),
  306. errMsg,
  307. QMessageBox::Ok,
  308. QMessageBox::Ok,
  309. this);
  310. }
  311. }
  312. }
  313. void VSnippetList::makeSureFolderExist() const
  314. {
  315. QString path = g_config->getSnippetConfigFolder();
  316. if (!QFileInfo::exists(path)) {
  317. QDir dir;
  318. dir.mkpath(path);
  319. }
  320. }
  321. void VSnippetList::updateContent()
  322. {
  323. m_snippetList->clear();
  324. for (int i = 0; i < m_snippets.size(); ++i) {
  325. const VSnippet &snip = m_snippets[i];
  326. QString text = QString("%1%2").arg(snip.getName())
  327. .arg(snip.getShortcut().isNull()
  328. ? "" : QString(" [%1]").arg(snip.getShortcut()));
  329. QListWidgetItem *item = new QListWidgetItem(text);
  330. item->setToolTip(snip.getName());
  331. item->setData(Qt::UserRole, snip.getName());
  332. m_snippetList->addItem(item);
  333. }
  334. int cnt = m_snippetList->count();
  335. if (cnt > 0) {
  336. m_numLabel->setText(tr("%1 %2").arg(cnt)
  337. .arg(cnt > 1 ? tr("Snippets") : tr("Snippet")));
  338. m_snippetList->setFocus();
  339. } else {
  340. m_numLabel->setText("");
  341. m_addBtn->setFocus();
  342. }
  343. }
  344. bool VSnippetList::addSnippet(const VSnippet &p_snippet, QString *p_errMsg)
  345. {
  346. if (!writeSnippetFile(p_snippet, p_errMsg)) {
  347. return false;
  348. }
  349. m_snippets.push_back(p_snippet);
  350. bool ret = true;
  351. if (!writeSnippetsToConfig()) {
  352. VUtils::addErrMsg(p_errMsg,
  353. tr("Fail to write snippets configuration file."));
  354. m_snippets.pop_back();
  355. ret = false;
  356. }
  357. updateContent();
  358. return ret;
  359. }
  360. bool VSnippetList::writeSnippetsToConfig() const
  361. {
  362. makeSureFolderExist();
  363. QJsonObject snippetJson;
  364. snippetJson[SnippetConfig::c_version] = "1";
  365. QJsonArray snippetArray;
  366. for (int i = 0; i < m_snippets.size(); ++i) {
  367. snippetArray.append(m_snippets[i].toJson());
  368. }
  369. snippetJson[SnippetConfig::c_snippets] = snippetArray;
  370. return VUtils::writeJsonToDisk(g_config->getSnippetConfigFilePath(),
  371. snippetJson);
  372. }
  373. bool VSnippetList::readSnippetsFromConfig()
  374. {
  375. m_snippets.clear();
  376. if (!QFileInfo::exists(g_config->getSnippetConfigFilePath())) {
  377. return true;
  378. }
  379. QJsonObject snippets = VUtils::readJsonFromDisk(g_config->getSnippetConfigFilePath());
  380. if (snippets.isEmpty()) {
  381. qWarning() << "invalid snippets configuration file" << g_config->getSnippetConfigFilePath();
  382. return false;
  383. }
  384. // [snippets] section.
  385. bool ret = true;
  386. QJsonArray snippetArray = snippets[SnippetConfig::c_snippets].toArray();
  387. for (int i = 0; i < snippetArray.size(); ++i) {
  388. VSnippet snip = VSnippet::fromJson(snippetArray[i].toObject());
  389. // Read the content.
  390. QString filePath(QDir(g_config->getSnippetConfigFolder()).filePath(snip.getName()));
  391. QString content = VUtils::readFileFromDisk(filePath);
  392. if (content.isNull()) {
  393. qWarning() << "fail to read snippet" << snip.getName();
  394. ret = false;
  395. continue;
  396. }
  397. snip.setContent(content);
  398. m_snippets.push_back(snip);
  399. }
  400. return ret;
  401. }
  402. void VSnippetList::keyPressEvent(QKeyEvent *p_event)
  403. {
  404. if (VimNavigationForWidget::injectKeyPressEventForVim(m_snippetList,
  405. p_event)) {
  406. return;
  407. }
  408. QWidget::keyPressEvent(p_event);
  409. }
  410. void VSnippetList::showNavigation()
  411. {
  412. VNavigationMode::showNavigation(m_snippetList);
  413. }
  414. bool VSnippetList::handleKeyNavigation(int p_key, bool &p_succeed)
  415. {
  416. static bool secondKey = false;
  417. return VNavigationMode::handleKeyNavigation(m_snippetList,
  418. secondKey,
  419. p_key,
  420. p_succeed);
  421. }
  422. int VSnippetList::getSnippetIndex(QListWidgetItem *p_item) const
  423. {
  424. if (!p_item) {
  425. return -1;
  426. }
  427. QString name = p_item->data(Qt::UserRole).toString();
  428. for (int i = 0; i < m_snippets.size(); ++i) {
  429. if (m_snippets[i].getName() == name) {
  430. return i;
  431. }
  432. }
  433. Q_ASSERT(false);
  434. return -1;
  435. }
  436. VSnippet *VSnippetList::getSnippet(QListWidgetItem *p_item)
  437. {
  438. int idx = getSnippetIndex(p_item);
  439. if (idx == -1) {
  440. return NULL;
  441. } else {
  442. return &m_snippets[idx];
  443. }
  444. }
  445. bool VSnippetList::writeSnippetFile(const VSnippet &p_snippet, QString *p_errMsg)
  446. {
  447. // Create and write to the snippet file.
  448. QString filePath = getSnippetFilePath(p_snippet);
  449. if (!VUtils::writeFileToDisk(filePath, p_snippet.getContent())) {
  450. VUtils::addErrMsg(p_errMsg,
  451. tr("Fail to add write the snippet file %1.")
  452. .arg(filePath));
  453. return false;
  454. }
  455. return true;
  456. }
  457. QString VSnippetList::getSnippetFilePath(const VSnippet &p_snippet) const
  458. {
  459. return QDir(g_config->getSnippetConfigFolder()).filePath(p_snippet.getName());
  460. }
  461. bool VSnippetList::sortSnippets(const QVector<int> &p_sortedIdx, QString *p_errMsg)
  462. {
  463. V_ASSERT(p_sortedIdx.size() == m_snippets.size());
  464. auto ori = m_snippets;
  465. for (int i = 0; i < p_sortedIdx.size(); ++i) {
  466. m_snippets[i] = ori[p_sortedIdx[i]];
  467. }
  468. bool ret = true;
  469. if (!writeSnippetsToConfig()) {
  470. VUtils::addErrMsg(p_errMsg,
  471. tr("Fail to write snippets configuration file."));
  472. m_snippets = ori;
  473. ret = false;
  474. }
  475. return ret;
  476. }
  477. bool VSnippetList::deleteSnippets(const QList<QString> &p_snippets,
  478. QString *p_errMsg)
  479. {
  480. if (p_snippets.isEmpty()) {
  481. return true;
  482. }
  483. bool ret = true;
  484. QSet<QString> targets = QSet<QString>::fromList(p_snippets);
  485. for (auto it = m_snippets.begin(); it != m_snippets.end();) {
  486. if (targets.contains(it->getName())) {
  487. // Remove it.
  488. if (!deleteSnippetFile(*it, p_errMsg)) {
  489. ret = false;
  490. }
  491. it = m_snippets.erase(it);
  492. } else {
  493. ++it;
  494. }
  495. }
  496. if (!writeSnippetsToConfig()) {
  497. VUtils::addErrMsg(p_errMsg,
  498. tr("Fail to write snippets configuration file."));
  499. ret = false;
  500. }
  501. return ret;
  502. }
  503. bool VSnippetList::deleteSnippetFile(const VSnippet &p_snippet, QString *p_errMsg)
  504. {
  505. QString filePath = getSnippetFilePath(p_snippet);
  506. if (!VUtils::deleteFile(filePath)) {
  507. VUtils::addErrMsg(p_errMsg,
  508. tr("Fail to remove snippet file %1.")
  509. .arg(filePath));
  510. return false;
  511. }
  512. return true;
  513. }
  514. void VSnippetList::focusInEvent(QFocusEvent *p_event)
  515. {
  516. QWidget::focusInEvent(p_event);
  517. if (m_snippets.isEmpty()) {
  518. m_addBtn->setFocus();
  519. } else {
  520. m_snippetList->setFocus();
  521. }
  522. }