id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
21,375
finddocwidget.cpp
visualfc_liteide/liteidex/src/plugins/golangdoc/finddocwidget.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: finddocwidget.cpp // Creator: visualfc <visualfc@gmail.com> #include "finddocwidget.h" #include "liteenvapi/liteenvapi.h" #include "golangdoc_global.h" #include <QVBoxLayout> #include <QHBoxLayout> #include <QLabel> #include <QToolButton> #include <QActionGroup> #include <QAction> #include <QCoreApplication> #include <QPlainTextEdit> #include <QTextBrowser> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end static char help[] = "<b>Search Format</b>" "<pre>" "fmt.\n" " Extracts all fmt pkg symbol document\n" "fmt.Println or fmt Println\n" " Extracts fmt.Println document\n" "fmt.Print or fmt Print\n" " Extracts fmt.Print fmt.Printf fmt.Println etc\n" "Println\n" " Extracts fmt.Println log.Println log.Logger.Println etc" "</pre>" "<b>Search Option</b>" "<pre>" "Match Word.\n" " Match whole world only\n" "Match Case\n" " Match case sensitive\n" "Use Regexp\n" " Use regexp for search\n" " example fmt p.*\n" "</pre>" ; class SearchEdit : public Utils::FancyLineEdit { Q_DECLARE_TR_FUNCTIONS(SearchEdit) public: SearchEdit(QWidget *parent = 0) : Utils::FancyLineEdit(parent) { QIcon icon = QIcon::fromTheme(layoutDirection() == Qt::LeftToRight ? QLatin1String("edit-clear-locationbar-rtl") : QLatin1String("edit-clear-locationbar-ltr"), QIcon::fromTheme(QLatin1String("edit-clear"), QIcon(QLatin1String("icon:images/editclear.png")))); setButtonPixmap(Right, icon.pixmap(16)); setPlaceholderText(tr("Search")); setButtonToolTip(Right, tr("Stop Search")); } void showStopButton(bool b) { this->setButtonVisible(Right,b); } }; FindDocWidget::FindDocWidget(LiteApi::IApplication *app, QWidget *parent) : QWidget(parent), m_liteApp(app) { m_findEdit = new SearchEdit; m_findEdit->setPlaceholderText(tr("Search")); m_chaseWidget = new ChaseWidget; m_chaseWidget->setMinimumSize(QSize(16,16)); m_chaseWidget->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred); QToolButton *findBtn = new QToolButton; findBtn->setPopupMode(QToolButton::InstantPopup); findBtn->setText(tr("Find")); QHBoxLayout *findLayout = new QHBoxLayout; findLayout->setMargin(2); findLayout->addWidget(m_findEdit); findLayout->addWidget(findBtn); findLayout->addWidget(m_chaseWidget); m_browser = m_liteApp->htmlWidgetManager()->createByName(this,"QTextBrowser"); QStringList paths; paths << m_liteApp->resourcePath()+"/packages/go/godoc"; m_browser->setSearchPaths(paths); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->setMargin(1); mainLayout->setSpacing(1); mainLayout->addLayout(findLayout); mainLayout->addWidget(m_browser->widget()); QAction *findAll = new QAction(tr("Find All"),this); QAction *findConst = new QAction(tr("Find const"),this); findConst->setData("const"); QAction *findFunc = new QAction(tr("Find func"),this); findFunc->setData("func"); QAction *findInterface = new QAction(tr("Find interface"),this); findInterface->setData("interface"); QAction *findPkg = new QAction(tr("Find pkg"),this); findPkg->setData("pkg"); QAction *findStruct = new QAction(tr("Find struct"),this); findStruct->setData("struct"); QAction *findType = new QAction(tr("Find type"),this); findType->setData("type"); QAction *findVar = new QAction(tr("Find var"),this); findVar->setData("var"); m_useRegexpCheckAct = new QAction(tr("Use Regexp"),this); m_useRegexpCheckAct->setCheckable(true); m_matchCaseCheckAct = new QAction(tr("Match Case"),this); m_matchCaseCheckAct->setCheckable(true); m_matchWordCheckAct = new QAction(tr("Match Word"),this); m_matchWordCheckAct->setCheckable(true); m_useRegexpCheckAct->setChecked(m_liteApp->settings()->value(GODOCFIND_USEREGEXP,false).toBool()); m_matchCaseCheckAct->setChecked(m_liteApp->settings()->value(GODOCFIND_MATCHCASE,true).toBool()); m_matchWordCheckAct->setChecked(m_liteApp->settings()->value(GODOCFIND_MATCHWORD,false).toBool()); QMenu *menu = new QMenu(findBtn); menu->addActions(QList<QAction*>() << findAll //<< findPkg ); menu->addSeparator(); menu->addActions(QList<QAction*>() << findInterface << findStruct << findType << findFunc << findConst << findVar ); menu->addSeparator(); menu->addAction(m_matchWordCheckAct); menu->addAction(m_matchCaseCheckAct); menu->addAction(m_useRegexpCheckAct); findBtn->setMenu(menu); QAction *helpAct = new QAction(tr("Help"),this); menu->addSeparator(); menu->addAction(helpAct); connect(helpAct,SIGNAL(triggered()),this,SLOT(showHelp())); this->setLayout(mainLayout); connect(findAll,SIGNAL(triggered()),this,SLOT(findDoc())); connect(findConst,SIGNAL(triggered()),this,SLOT(findDoc())); connect(findFunc,SIGNAL(triggered()),this,SLOT(findDoc())); connect(findInterface,SIGNAL(triggered()),this,SLOT(findDoc())); connect(findPkg,SIGNAL(triggered()),this,SLOT(findDoc())); connect(findStruct,SIGNAL(triggered()),this,SLOT(findDoc())); connect(findType,SIGNAL(triggered()),this,SLOT(findDoc())); connect(findVar,SIGNAL(triggered()),this,SLOT(findDoc())); m_process = new ProcessEx(this); connect(m_process,SIGNAL(stateChanged(QProcess::ProcessState)),this,SLOT(stateChanged(QProcess::ProcessState))); connect(m_process,SIGNAL(extOutput(QByteArray,bool)),this,SLOT(extOutput(QByteArray,bool))); connect(m_process,SIGNAL(extFinish(bool,int,QString)),this,SLOT(extFinish(bool,int,QString))); connect(m_findEdit,SIGNAL(returnPressed()),findAll,SIGNAL(triggered())); connect(m_findEdit,SIGNAL(rightButtonClicked()),this,SLOT(abortFind())); connect(m_browser,SIGNAL(linkClicked(QUrl)),this,SLOT(openUrl(QUrl))); QString path = m_liteApp->resourcePath()+"/packages/go/godoc/finddoc.html"; QFile file(path); if (file.open(QIODevice::ReadOnly)) { m_templateData = file.readAll(); file.close(); } //QFont font = m_browser->widget()->font(); //font.setPointSize(12); //m_browser->widget()->setFont(font); showHelp(); } FindDocWidget::~FindDocWidget() { m_liteApp->settings()->setValue(GODOCFIND_MATCHCASE,m_matchCaseCheckAct->isChecked()); m_liteApp->settings()->setValue(GODOCFIND_MATCHWORD,m_matchWordCheckAct->isChecked()); m_liteApp->settings()->setValue(GODOCFIND_USEREGEXP,m_useRegexpCheckAct->isChecked()); abortFind(); delete m_process; } void FindDocWidget::findDoc() { QAction *act = (QAction*)sender(); QString text = m_findEdit->text().trimmed(); if (text.isEmpty()) { return; } QString findFlag = act->data().toString(); abortFind(); QStringList args; args << "finddoc" << "-urltag" << "<liteide_doc>"; if (m_matchWordCheckAct->isChecked()) { args << "-word"; } if (m_matchCaseCheckAct->isChecked()) { args << "-case"; } if (m_useRegexpCheckAct->isChecked()) { args << "-r"; } if (!findFlag.isEmpty()) { args << "-"+findFlag; } args << text.split(" "); m_browser->clear(); m_findFlag = findFlag; m_htmlData.clear(); QString cmd = LiteApi::getGotools(m_liteApp); m_process->setEnvironment(LiteApi::getGoEnvironment(m_liteApp).toStringList()); m_process->start(cmd,args); } struct doc_comment { QString url; QString file; QStringList comment; }; void FindDocWidget::extOutput(QByteArray data, bool error) { if (error) { m_liteApp->appendLog("FindDoc",QString::fromUtf8(data),false); return; } /* http://golang.org/pkg\fmt\#Println c:\go\src\pkg\log\log.go:169: // Println calls l.Output to print to the logger. // Arguments are handled in the manner of fmt.Println. func (l *Logger) Println(v ...interface{}) http://godoc.org\code.google.com\p\go.tools\cmd\vet\#Println F:\vfc\liteide-git\liteidex\src\code.google.com\p\go.tools\cmd\vet\main.go:375: // Println is fmt.Println guarded by -v. func Println(args ...interface{}) */ QList<doc_comment> dc_array; doc_comment dc; int flag = 0; foreach (QString line, QString::fromUtf8(data).split("\n")) { if (line.startsWith("<liteide_doc>")) { flag = 1; if (!dc.url.isEmpty()) { dc_array.push_back(dc); } dc.url = line.mid(13); dc.file.clear(); dc.comment.clear(); continue; } if (flag == 1) { dc.file = line; flag = 2; continue; } if (flag == 2) { dc.comment.push_back(line); } } if (!dc.url.isEmpty()) { dc_array.push_back(dc); } QStringList array; foreach (doc_comment dc, dc_array) { array.append(docToHtml(dc.url,dc.file,dc.comment)); } // qDebug() << array.join("\n"); // if (m_findFlag == "pkg") { // array = parserPkgDoc(QString::fromUtf8(data)); // } else { // array = parserDoc(QString::fromUtf8(data)); // } m_htmlData.append(array.join("\n")); QString html = m_templateData; html.replace("{content}",m_htmlData); int pos = m_browser->scrollBarValue(Qt::Vertical); m_browser->setHtml(html,QUrl()); m_browser->setScrollBarValue(Qt::Vertical,pos); } void FindDocWidget::extFinish(bool, int, QString) { if (m_htmlData.isEmpty()) { QString html = m_templateData; html.replace("{content}","<b>Not found!</b>"); m_browser->setHtml(html,QUrl()); } m_htmlData.clear(); } void FindDocWidget::abortFind() { m_process->stop(100); } void FindDocWidget::stateChanged(QProcess::ProcessState state) { m_chaseWidget->setAnimated(state == QProcess::Running); m_findEdit->showStopButton(state == QProcess::Running); } void FindDocWidget::openUrl(QUrl url) { if (!url.isLocalFile()) { return; } QString text = url.toLocalFile(); QRegExp rep("(\\w?\\:?[\\w\\d\\_\\-\\\\/\\.]+):(\\d+):"); int index = rep.indexIn(text); if (index < 0) return; QStringList capList = rep.capturedTexts(); if (capList.count() < 3) return; QString fileName = capList[1]; QString fileLine = capList[2]; bool ok = false; int line = fileLine.toInt(&ok); if (!ok) return; LiteApi::IEditor *editor = m_liteApp->fileManager()->openEditor(fileName,true); if (editor) { LiteApi::ITextEditor *textEditor = LiteApi::getTextEditor(editor); if (textEditor) { textEditor->gotoLine(line-1,0,true); } } } void FindDocWidget::showHelp() { QString data = m_templateData; data.replace("{content}",help); m_browser->setHtml(data,QUrl()); } static QString escape(const QString &text) { #if QT_VERSION >= 0x050000 return QString(text).toHtmlEscaped(); #else return Qt::escape(text); #endif } QStringList FindDocWidget::docToHtml(const QString &url, const QString &file, const QStringList &comment) { QString sz; QString pkgName; QString findName; if (url.startsWith("http://golang.org/pkg")) { sz = url.mid(21); } else if (url.startsWith("http://golang.org/cmd")) { sz = url.mid(21); } else if (url.startsWith("http://godoc.org")) { sz = url.mid(16); } //\code.google.com\p\go.tools\cmd\vet\#Println int pos = sz.indexOf("#"); if (pos != -1) { pkgName = QDir::fromNativeSeparators(sz.left(pos)); if (pkgName.startsWith("/")) { pkgName = pkgName.mid(1); } if (pkgName.endsWith("/")) { pkgName = pkgName.left(pkgName.length()-1); } findName = sz.mid(pos+1); } QStringList array; array.push_back(QString("<h4><b>%2</b>&nbsp;&nbsp;<a href=\"file:%1\">%3</a></h4>") .arg(QDir::fromNativeSeparators(escape(file))).arg(pkgName).arg(findName)); if (!comment.isEmpty() && ( comment.first().startsWith("const (") || comment.first().startsWith("var (")) ) { array.push_back("<pre>"); QString head = "const "; if (comment.first().startsWith("var (")) { head = "var "; } QStringList incmd; foreach (QString sz, comment) { if (sz.trimmed().startsWith("//")) { incmd.push_back(escape(sz.trimmed())); } else if (sz.indexOf(findName) >= 0) { array.append(incmd); array.push_back(escape(head+sz.replace("\t"," ").trimmed())); } else { incmd.clear(); } } array.push_back("</pre>"); return array; } int flag = 0; QString lastTag; foreach (QString sz, comment) { if (sz.startsWith("//")) { if (flag != 1) { if (!lastTag.isEmpty()) array.push_back(lastTag); array.push_back("<p>"); lastTag = "</p>"; } flag = 1; if (sz.mid(2).trimmed().isEmpty()) { array.push_back("</p><p>"); } else { array.push_back(escape(sz.mid(2))); } } else { if (sz.trimmed().isEmpty()) { continue; } if (flag != 3) { if (!lastTag.isEmpty()) array.push_back(lastTag); array.push_back("<pre>"); lastTag = "</pre>"; } flag = 3; array.push_back(escape(sz.replace("\t"," "))); } } if (!lastTag.isEmpty()) array.push_back(lastTag); array.push_back("<p></p>"); return array; } QStringList FindDocWidget::parserDoc(QString findText) { QStringList array; int lastFlag = 0; QString findName; QString findPos; QString findComment; foreach (QString sz, findText.split('\n')) { int flag = 0; if (sz.startsWith("http://golang.org/pkg")) { flag = 1; sz = sz.mid(21); } else if (sz.startsWith("http://golang.org/cmd")) { flag = 1; sz = sz.mid(21); } else if (sz.startsWith("http://godoc.org")) { flag = 1; sz = sz.mid(16); } else if (sz.startsWith("//")) { flag = 2; sz = sz.mid(2); } else if (sz.isEmpty()) { flag = 4; } else { flag = 3; } if (flag == 1) { //\code.google.com\p\go.tools\cmd\vet\#Println int pos = sz.indexOf("#"); if (pos != -1) { QString pkg = sz.left(pos); pkg = QDir::fromNativeSeparators(pkg); if (pkg.startsWith("/")) { pkg = pkg.mid(1); } if (pkg.endsWith("/")) { pkg = pkg.left(pkg.length()-1); } sz = pkg+sz.mid(pos); findName = sz; } else { QString pkg = sz; pkg = QDir::fromNativeSeparators(pkg); if (pkg.startsWith("/")) { pkg = pkg.mid(1); } if (pkg.endsWith("/")) { pkg = pkg.left(pkg.length()-1); } findName = pkg; } } else if (flag == 3) { if (lastFlag == 1) { findPos = "file:"+sz; array.push_back(QString("<h3><a href=\"%1\">%2</a></h3>").arg(findPos).arg(findName)); } else { array.push_back(QString("<b>%1</b>").arg(sz)); if (!findComment.isEmpty()) { array.push_back(QString("<p>%1</p>").arg(findComment)); } findComment.clear(); } } else if (flag == 2) { findComment += sz.trimmed(); } else if (flag == 4) { } lastFlag = flag; } return array; } QStringList FindDocWidget::parserPkgDoc(QString findText) { QStringList array; int lastFlag = 0; QString findName; QString findPos; QString findComment; bool bHead = false; foreach (QString sz, findText.split('\n')) { int flag = 0; if (sz.startsWith("http://golang.org/pkg")) { flag = 1; sz = sz.mid(21); } else if (sz.startsWith("http://golang.org/cmd")) { flag = 1; sz = sz.mid(21); } else if (sz.startsWith("http://godoc.org")) { flag = 1; sz = sz.mid(16); } else { flag = 3; } if (flag == 1) { bHead = false; } if (bHead) { // findComment.append(sz+"\n"); if (sz.startsWith("\t\t")) { flag = 5; } else if (sz.trimmed().isEmpty()){ flag = 6; } else { flag = 7; } sz.replace("\t"," "); if (lastFlag != flag && !findComment.isEmpty()) { if (lastFlag == 5) { array.push_back(QString("<pre>%1</pre>").arg(findComment)); } else { array.push_back(QString("<p>%1</p>").arg(findComment)); } findComment.clear(); } if (flag == 5) { findComment += sz.trimmed()+"\n"; } else { findComment += sz.trimmed(); } lastFlag = flag; continue; } if (flag == 1) { //\code.google.com\p\go.tools\cmd\vet\#Println int pos = sz.indexOf("#"); if (pos != -1) { QString pkg = sz.left(pos); pkg = QDir::fromNativeSeparators(pkg); if (pkg.startsWith("/")) { pkg = pkg.mid(1); } if (pkg.endsWith("/")) { pkg = pkg.left(pkg.length()-1); } sz = pkg+sz.mid(pos); findName = sz; } else { QString pkg = sz; pkg = QDir::fromNativeSeparators(pkg); if (pkg.startsWith("/")) { pkg = pkg.mid(1); } if (pkg.endsWith("/")) { pkg = pkg.left(pkg.length()-1); } findName = pkg; } } else if (flag == 3) { if (lastFlag == 1) { findPos = "file:"+sz; array.push_back(QString("<h3><a href=\"%1\">%2</a></h3>").arg(findPos).arg(findName)); bHead = true; } } else if (flag == 2) { findComment += sz.trimmed(); } lastFlag = flag; } if (!findComment.isEmpty()) { if (lastFlag == 5) { array.push_back(QString("<pre>%1</pre>").arg(findComment)); } else { array.push_back(QString("<p>%1</p>").arg(findComment)); } } return array; }
21,337
C++
.cpp
594
26.915825
124
0.550569
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,376
golangdocoptionfactory.cpp
visualfc_liteide/liteidex/src/plugins/golangdoc/golangdocoptionfactory.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangdocoptionfactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangdocoption.h" #include "golangdocoptionfactory.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangDocOptionFactory::GolangDocOptionFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IOptionFactory(parent), m_liteApp(app) { } QStringList GolangDocOptionFactory::mimeTypes() const { return QStringList() << "option/golangdoc"; } LiteApi::IOption *GolangDocOptionFactory::create(const QString &mimeType) { if (mimeType == "option/golangdoc") { return new GolangDocOption(m_liteApp,this); } return 0; }
1,899
C++
.cpp
49
36.469388
91
0.687432
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,377
golangdocoption.cpp
visualfc_liteide/liteidex/src/plugins/golangdoc/golangdocoption.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangdocoption.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangdocoption.h" #include "ui_golangdocoption.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangDocOption::GolangDocOption(LiteApi::IApplication *app,QObject *parent) : LiteApi::IOption(parent), m_liteApp(app), m_widget(new QWidget), ui(new Ui::GolangDocOption) { ui->setupUi(m_widget); } GolangDocOption::~GolangDocOption() { delete m_widget; delete ui; } QWidget *GolangDocOption::widget() { return m_widget; } QString GolangDocOption::name() const { return "GolangDoc"; } QString GolangDocOption::mimeType() const { return "option/golangdoc"; } void GolangDocOption::load() { bool defctx = m_liteApp->settings()->value("golangapi/defctx",true).toBool(); bool std = m_liteApp->settings()->value("golangapi/std",false).toBool(); ui->defContextCheckBox->setChecked(defctx); ui->onlyStdCheckBox->setChecked(std); } void GolangDocOption::save() { bool defctx = ui->defContextCheckBox->isChecked(); bool std = ui->onlyStdCheckBox->isChecked(); m_liteApp->settings()->setValue("golangapi/defctx",defctx); m_liteApp->settings()->setValue("golangapi/std",std); }
2,477
C++
.cpp
72
31.944444
82
0.688778
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,378
golangdocplugin.cpp
visualfc_liteide/liteidex/src/plugins/golangdoc/golangdocplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangdocplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangdocplugin.h" #include "golangdoc.h" #include "golangdocoptionfactory.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangDocPlugin::GolangDocPlugin() : m_golangDoc(0) { } GolangDocPlugin::~GolangDocPlugin() { if (m_golangDoc) { delete m_golangDoc; } } bool GolangDocPlugin::load(LiteApi::IApplication *app) { m_golangDoc = new GolangDoc(app,this); //app->optionManager()->addFactory(new GolangDocOptionFactory(app,this)); return true; } void GolangDocPlugin::currentEditorChanged(LiteApi::IEditor*) { } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
1,963
C++
.cpp
56
32.910714
82
0.69
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,379
golangcode.cpp
visualfc_liteide/liteidex/src/plugins/golangcode/golangcode.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangcode.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangcode.h" #include "golangcode_global.h" #include "fileutil/fileutil.h" #include "processex/processex.h" #include "../liteeditor/faketooltip.h" #include <QProcess> #include <QTextDocument> #include <QAbstractItemView> #include <QApplication> #include <QDesktopWidget> #include <QLabel> #include <QHBoxLayout> #include <QPlainTextEdit> #include <QTimer> #include <QScrollBar> #include <QDebug> //#define GOCODE_CHECKGOPATH //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end int GolangCode::g_gocodeInstCount = 0; GolangCode::GolangCode(LiteApi::IApplication *app, QObject *parent) : QObject(parent), m_liteApp(app), m_editor(0), m_completer(0), m_closeOnExit(true), m_allImportHint(true) { g_gocodeInstCount++; m_gocodeProcess = new Process(this); m_gocodeSetProcess = new Process(this); m_gocodeImportProcess = new Process(this); // m_importProcess = new Process(this); m_gocodeProcess->setWorkingDirectory(m_liteApp->applicationPath()); m_gocodeSetProcess->setWorkingDirectory(m_liteApp->applicationPath()); m_gocodeImportProcess->setWorkingDirectory(m_liteApp->applicationPath()); connect(m_gocodeProcess,SIGNAL(started()),this,SLOT(started())); connect(m_gocodeProcess,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(finished(int,QProcess::ExitStatus))); connect(m_gocodeImportProcess,SIGNAL(started()),this,SLOT(gocodeImportStarted())); connect(m_gocodeImportProcess,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(gocodeImportFinished(int,QProcess::ExitStatus))); // connect(m_importProcess,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(importFinished(int,QProcess::ExitStatus))); m_envManager = LiteApi::getEnvManager(m_liteApp); if (m_envManager) { connect(m_envManager,SIGNAL(currentEnvChanged(LiteApi::IEnv*)),this,SLOT(currentEnvChanged(LiteApi::IEnv*))); } m_golangAst = LiteApi::findExtensionObject<LiteApi::IGolangAst*>(m_liteApp,"LiteApi.IGolangAst"); m_pkgImportTip = new ImportPkgTip(m_liteApp,this); connect(m_pkgImportTip,SIGNAL(import(QString,int)),this,SLOT(import(QString,int))); connect(m_liteApp->editorManager(),SIGNAL(currentEditorChanged(LiteApi::IEditor*)),this,SLOT(currentEditorChanged(LiteApi::IEditor*))); connect(m_liteApp->optionManager(),SIGNAL(applyOption(QString)),this,SLOT(applyOption(QString))); connect(m_liteApp,SIGNAL(loaded()),this,SLOT(appLoaded())); //applyOption("option/golangcode"); } void GolangCode::applyOption(QString /*id*/) { // if (id != "option/golangcode") return; // m_closeOnExit = m_liteApp->settings()->value(GOLANGCODE_EXITCLOSE,true).toBool(); // m_allImportHint = m_liteApp->settings()->value(GOLANGCODE_IMPORTHINT_GOPATH,true).toBool(); } void GolangCode::appLoaded() { loadPkgList(); #ifdef GOCODE_CHECKGOPATH LiteApi::IGoEnvManger *goEnv = LiteApi::getGoEnvManager(m_liteApp); if (goEnv) { connect(goEnv,SIGNAL(customGOPATHChanged(QString)),this,SLOT(customGOPATHChanged(QString))); connect(goEnv,SIGNAL(globalGOPATHChanged()),this,SLOT(globalGOPATHChanged())); } #endif } void GolangCode::import(const QString &import, int startPos) { QPlainTextEdit *ed = LiteApi::getPlainTextEdit(m_editor); if (!ed) { return; } QTextBlock block = ed->document()->firstBlock(); int pos1 = -1; int pos2 = -1; int pos3 = -1; int pos4 = -1; int offset = 0; while (block.isValid()) { QString text = block.text(); if (text.startsWith("/*")) { block = block.next(); while(block.isValid()) { if (block.text().endsWith("*/")) { break; } block = block.next(); } if (!block.isValid()) { break; } } else if (text.startsWith("var")) { break; } else if (text.startsWith("func")) { break; } else if (text.startsWith("package ")) { pos1 = block.position()+block.length(); } else if (pos1 != -1 && text.startsWith("import (")) { pos2 = block.position()+block.length(); break; } else if (pos1 != -1 && text.startsWith("import ")) { QString path = text.right(text.length()-7).trimmed(); if (!path.startsWith("\"C\"")) { pos3 = block.position()+ 7; pos4 = block.position()+block.length(); break; } } block = block.next(); } if (pos1 < 0) { return; } QString text = "\t\""+import+"\"\n"; QTextCursor cur = ed->textCursor(); int orgPos = cur.position(); cur.beginEditBlock(); if (pos2 < 0) { if (pos3 < 0) { pos2 = pos1; text = "\nimport (\n\t\""+import+"\"\n)\n"; } else { cur.setPosition(pos3); cur.insertText("(\n\t"); pos2 = pos4+3; offset += 3; text = "\t\""+import+"\"\n)\n"; } } cur.setPosition(pos2); cur.insertText(text); cur.setPosition(orgPos+text.length()+offset); cur.endEditBlock(); ed->setTextCursor(cur); if (orgPos == startPos) { prefixChanged(cur,m_lastPrefix,true); } } bool check_import(const QString &path, const QString &id) { int start = path.indexOf("\""); if (start >= 0) { int end = path.indexOf("\"",start+1); if (end > 0) { QString name = path.left(start).trimmed(); if (!name.isEmpty()) { if (name == id) { return true; } } else { QString tmp = path.mid(start+1,end-start-1); if (tmp == id) { return true; } if (tmp.endsWith("/"+id)) { return true; } } } } return false; } bool GolangCode::findImport(const QString &id) { QPlainTextEdit *ed = LiteApi::getPlainTextEdit(m_editor); if (!ed) { return false; } QTextBlock block = ed->document()->firstBlock(); int pos1 = -1; while (block.isValid()) { QString text = block.text().trimmed(); if (text.startsWith("/*")) { block = block.next(); while(block.isValid()) { if (block.text().endsWith("*/")) { break; } block = block.next(); } if (!block.isValid()) { break; } } else if (text.startsWith("var")) { break; } else if (text.startsWith("func")) { break; } else if (text.startsWith("package ")) { pos1 = block.position()+block.length(); } else if (pos1 != -1 && text.startsWith("import (")) { block = block.next(); while(block.isValid()) { QString text = block.text().trimmed(); if (text.startsWith(")")) { break; } //skip if (text.startsWith("/*")) { block = block.next(); while(block.isValid()) { if (block.text().endsWith("*/")) { break; } block = block.next(); } if (!block.isValid()) { break; } } if (text.startsWith("//")) { block = block.next(); continue; } if (check_import(text,id)) { return true; } block = block.next(); } } else if (pos1 != -1 && text.startsWith("import ")) { QString path = text.right(text.length()-7); if (check_import(path,id)) { return true; } } block = block.next(); } return false; } void GolangCode::updateEditorGOPATH() { if (m_gocodeCmd.isEmpty()) { return; } #ifdef GOCODE_CHECKGOPATH QProcessEnvironment env = LiteApi::getCustomGoEnvironment(m_liteApp,m_liteApp->editorManager()->currentEditor()); QString gopathenv = env.value("GOPATH"); if (gopathenv != m_lastGopathEnv) { m_lastGopathEnv = gopathenv; gocodeUpdataLibpath(env); loadImportsList(env); m_liteApp->appendLog("GolangCode",QString("gocode set lib-path \"%1\"").arg(gopathenv),false); } #else QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); #endif if (!m_gocodeImportProcess->isStop()) { m_gocodeImportProcess->stop(10); } QStringList args; args << "-f" << "csv" << "autocomplete" << "main.go" << "21"; m_gocodeImportProcess->setProcessEnvironment(env); m_gocodeImportProcess->setWorkingDirectory(m_fileInfo.absolutePath()); m_gocodeImportProcess->startEx(m_gocodeCmd,args); } void GolangCode::customGOPATHChanged(const QString &/*buildPath*/) { updateEditorGOPATH(); } void GolangCode::globalGOPATHChanged() { updateEditorGOPATH(); } void GolangCode::broadcast(QString /*module*/,QString /*id*/,QString) { // if (module == "golangpackage" && id == "reloadgopath") { // resetGocode(); // } } GolangCode::~GolangCode() { delete m_gocodeProcess; delete m_gocodeSetProcess; // delete m_importProcess; delete m_gocodeImportProcess; g_gocodeInstCount--; if (g_gocodeInstCount == 0 && m_closeOnExit && !m_gocodeCmd.isEmpty()) { ProcessEx::startDetachedExAndHide(m_gocodeCmd,QStringList() << "close"); } } void GolangCode::gocodeUpdataLibpath(const QProcessEnvironment &env) { if (m_gocodeCmd.isEmpty()) { return; } m_gocodeProcess->setProcessEnvironment(env); m_gocodeSetProcess->setProcessEnvironment(env); if (!m_gocodeSetProcess->isStop()) { m_gocodeSetProcess->stopAndWait(100,1000); } m_gocodeSetProcess->startEx(m_gocodeCmd,QStringList() << "set" << "lib-path" << env.value("GOPATH")); } void GolangCode::gocodeReset(const QProcessEnvironment &env) { if (m_gocodeCmd.isEmpty()) { return; } m_gocodeProcess->setProcessEnvironment(env); m_gocodeSetProcess->setProcessEnvironment(env); if (g_gocodeInstCount > 1) { if (!m_gocodeSetProcess->isStop()) { m_gocodeSetProcess->stopAndWait(100,1000); } m_gocodeSetProcess->startEx(m_gocodeCmd,QStringList() << "close"); } } void GolangCode::cgoComplete() { QStandardItem *root= m_completer->findRoot(m_preWord); QStringList types; types << "int" << "uint" << "short" << "ushort" << "char" << "schar" << "uchar" << "long" << "ulong" << "longlong" << "ulonglong" << "float" << "double" << "complexfloat" << "complexdouble"; QIcon icon = m_golangAst->iconFromTagEnum(LiteApi::TagType,true); foreach(QString item, types) { m_completer->appendChildItem(root,item,"type","",icon,true); } icon = m_golangAst->iconFromTagEnum(LiteApi::TagFunc,true); m_completer->appendChildItem(root,"CString","func","func(string) *C.char",icon,true); m_completer->appendChildItem(root,"GoString","func","func(*C.char) string",icon,true); m_completer->appendChildItem(root,"GoStringN","func","func(*C.char, C.int) string",icon,true); m_completer->appendChildItem(root,"GoBytes","func","func(unsafe.Pointer, C.int) []byte",icon,true); m_completer->appendChildItem(root,"CBytes","func","func([]byte) unsafe.Pointer",icon,true); QStringList all = parserCgoInEditor(1024); icon = QIcon("icon:liteeditor/images/findword.png"); foreach (QString s, all) { m_completer->appendChildItem(root,s,"","",icon,false); } m_completer->updateCompleterModel(); m_completer->showPopup(); } QStringList GolangCode::parserCgoInEditor(int nmax) { QTextCursor tc = m_editor->textCursor(); QTextDocument *doc = m_editor->document(); int maxNumber = tc.blockNumber(); int blockNumber = tc.blockNumber(); QTextBlock block = doc->firstBlock(); int first = maxNumber-nmax; if (first > 0) { block = doc->findBlockByNumber(first); } maxNumber += nmax; QStringList all; QRegExp rx("C\\.([\\w\\-\\_]+)"); while (block.isValid()) { if (block.blockNumber() >= maxNumber) { break; } if (block.blockNumber() == blockNumber) { block = block.next(); continue; } QString line = block.text().trimmed(); if (!line.isEmpty()) { int pos = 0; while ((pos = rx.indexIn(line, pos)) != -1) { QString cap = rx.cap(1); all.push_back(cap); pos += rx.matchedLength(); } } block = block.next(); } all.removeDuplicates(); return all; } void GolangCode::loadPkgList() { QString path = m_liteApp->resourcePath()+("/packages/go/pkglist"); QFile file(path); if (file.open(QFile::ReadOnly)) { QByteArray data = file.readAll(); QString ar = QString::fromUtf8(data); ar.replace("\r\n","\n"); foreach(QString line, ar.split("\n")) { line = line.trimmed(); if (line.isEmpty()) { continue; } QStringList pathList = line.split("/"); m_pkgListMap.insert(pathList.last(),line); m_importList.append(line); } } m_importList.removeDuplicates(); m_importList << "github.com/" << "golang.org/x/"; m_allImportList = m_importList; } //void GolangCode::loadImportsList(const QProcessEnvironment &env) //{ // if (!m_importProcess->isStop()) { // m_importProcess->stopAndWait(100,1000); // } // QString cmd = LiteApi::getGotools(m_liteApp); // if (cmd.isEmpty()) { // return; // } // QStringList args; // args << "pkgs" << "-list" << "-pkg" << "-skip_goroot"; // m_importProcess->setProcessEnvironment(env); // m_importProcess->startEx(cmd,args); //} void GolangCode::currentEnvChanged(LiteApi::IEnv*) { QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); // if (!LiteApi::hasGoEnv(env)) { // return; // } m_liteApp->appendLog("GolangCode","go environment changed"); m_gobinCmd = FileUtil::lookupGoBin("go",m_liteApp,env,false); m_gocodeCmd = FileUtil::lookupGoBin("gocode",m_liteApp,env,true); if (m_gocodeCmd.isEmpty()) { m_liteApp->appendLog("GolangCode","gocode was not found on system PATH (hint: is gocode installed? \"go install github.com/visualfc/gocode@latest\")",true); } else { m_liteApp->appendLog("GolangCode",QString("Found gocode at %1").arg(m_gocodeCmd)); } m_gocodeProcess->setProcessEnvironment(env); // m_importProcess->setProcessEnvironment(env); m_gocodeSetProcess->setProcessEnvironment(env); gocodeReset(env); currentEditorChanged(m_liteApp->editorManager()->currentEditor()); } void GolangCode::currentEditorChanged(LiteApi::IEditor *editor) { if (!editor) { this->setCompleter(0); return; } if (editor->mimeType() == "text/x-gosrc") { LiteApi::ICompleter *completer = LiteApi::findExtensionObject<LiteApi::ICompleter*>(editor,"LiteApi.ICompleter"); this->setCompleter(completer); } else if (editor->mimeType() == "browser/goplay") { LiteApi::IEditor* pedit = LiteApi::findExtensionObject<LiteApi::IEditor*>(m_liteApp->extension(),"LiteApi.Goplay.IEditor"); if (pedit && pedit->mimeType() == "text/x-gosrc") { editor = pedit; LiteApi::ICompleter *completer = LiteApi::findExtensionObject<LiteApi::ICompleter*>(editor,"LiteApi.ICompleter"); this->setCompleter(completer); } } else { this->setCompleter(0); return; } m_editor = LiteApi::getTextEditor(editor); if (!m_editor) { return; } m_pkgImportTip->setWidget(editor->widget()); QString filePath = m_editor->filePath(); if (filePath.isEmpty()) { return; } m_fileInfo.setFile(filePath); m_gocodeProcess->setWorkingDirectory(m_fileInfo.absolutePath()); updateEditorGOPATH(); } void GolangCode::setCompleter(LiteApi::ICompleter *completer) { if (m_completer) { disconnect(m_completer,0,this,0); } m_completer = completer; if (m_completer) { m_completer->setImportList(m_allImportList); if (!m_gocodeCmd.isEmpty()) { m_completer->setSearchSeparator(false); m_completer->setExternalMode(true); connect(m_completer,SIGNAL(prefixChanged(QTextCursor,QString,bool)),this,SLOT(prefixChanged(QTextCursor,QString,bool))); connect(m_completer,SIGNAL(wordCompleted(QString,QString,QString)),this,SLOT(wordCompleted(QString,QString,QString))); } else { m_completer->setSearchSeparator(true); m_completer->setExternalMode(false); } } } void GolangCode::prefixChanged(QTextCursor cur,QString pre,bool force) { if (m_completer->completionContext() != LiteApi::CompleterCodeContext) { return; } if (m_gocodeCmd.isEmpty()) { return; } // if (m_completer->completer()->completionPrefix().startsWith(pre)) { // // qDebug() << pre << m_completer->completer()->completionPrefix(); // // return; // } if (!m_gocodeProcess->isStop()) { m_gocodeProcess->stopAndWait(30,100); } int offset = -1; if (pre.endsWith('.')) { m_preWord = pre; offset = 0; } else if (pre.length() == m_completer->prefixMin()) { m_preWord.clear(); } else { if (!force) { return; } m_preWord.clear(); int index = pre.lastIndexOf("."); if (index != -1) { m_preWord = pre.left(index); } } m_prefix = pre; m_lastPrefix = m_prefix; if (!m_preWord.isEmpty()) { m_completer->clearItemChilds(m_preWord); } if (m_preWord == "C.") { cgoComplete(); return; } if (m_preWord.endsWith(".")) { bool testDigit = true; for (int i = 0; i < m_preWord.size()-1; i++) { if (!m_preWord.at(i).isDigit()) { testDigit = false; break; } } if (testDigit) { return; } } if (m_prefix.lastIndexOf("..") > 0) { m_pkgImportTip->hide(); return; } QString src = cur.document()->toPlainText(); src = src.replace("\r\n","\n"); m_writeData = src.left(cur.position()).toUtf8(); QStringList args; args << "-f" << "csv" << "autocomplete" << m_fileInfo.fileName() << QString::number(m_writeData.length()+offset); m_writeData = src.toUtf8(); m_gocodeProcess->setWorkingDirectory(m_fileInfo.absolutePath()); m_gocodeProcess->startEx(m_gocodeCmd,args); } void GolangCode::wordCompleted(QString,QString,QString) { m_prefix.clear(); } void GolangCode::started() { if (m_writeData.isEmpty()) { m_gocodeProcess->closeWriteChannel(); return; } m_gocodeProcess->write(m_writeData); m_gocodeProcess->closeWriteChannel(); m_writeData.clear(); } void GolangCode::finished(int code,QProcess::ExitStatus) { if (code != 0) { return; } if (m_prefix.isEmpty()) { return; } if (m_prefix != m_lastPrefix) { m_prefix.clear(); return; } QByteArray read = m_gocodeProcess->readAllStandardOutput(); QList<QByteArray> all = read.split('\n'); //func,,Fprint,,func(w io.Writer, a ...interface{}) (n int, error os.Error) //type,,Formatter,,interface //const,,ModeExclusive,, //var,,Args,,[]string int n = 0; QIcon icon; QStandardItem *root= m_completer->findRoot(m_preWord); foreach (QByteArray bs, all) { QStringList word = QString::fromUtf8(bs,bs.size()).split(",,"); //nsf/gocode count=3 //mdempsky/gocode count = 4 // ("var", "s4", "string", "") // ("func", "Errorf", "func(format string, a ...interface{}) error", "fmt") if (word.count() < 3) { continue; } if (word.at(0) == "PANIC") { continue; } LiteApi::ASTTAG_ENUM tag = LiteApi::TagNone; QString kind = word.at(0); QString info = word.at(2); if (kind == "package") { tag = LiteApi::TagPackage; } else if (kind == "func") { tag = LiteApi::TagFunc; } else if (kind == "var") { tag = LiteApi::TagValue; } else if (kind == "const") { tag = LiteApi::TagConst; } else if (kind == "type") { if (info == "interface") { tag = LiteApi::TagInterface; } else if (info == "struct") { tag = LiteApi::TagStruct; } else { tag = LiteApi::TagType; } } if (m_golangAst) { icon = m_golangAst->iconFromTagEnum(tag,true); } //m_completer->appendItemEx(m_preWord+word.at(1),kind,info,icon,true); m_completer->appendChildItem(root,word.at(1),kind,info,icon,true); n++; } m_lastPrefix = m_prefix; m_prefix.clear(); if (n >= 1) { m_completer->updateCompleterModel(); m_completer->showPopup(); } if (n == 0 && m_lastPrefix.endsWith(".")) { QString id = m_lastPrefix.left(m_lastPrefix.length()-1); if (id.length() < 2) { return; } QStringList pkgs = m_pkgListMap.values(id); pkgs.sort(); if (m_allImportHint) { QStringList extras = m_extraPkgListMap.values(id); extras.sort(); pkgs << extras; } if (!pkgs.isEmpty() && !findImport(id)) { QPlainTextEdit *ed = LiteApi::getPlainTextEdit(m_editor); if (ed) { int pos = ed->textCursor().position(); m_pkgImportTip->showPkgHint(pos,pkgs,ed); } } } } void GolangCode::gocodeImportStarted() { m_gocodeImportProcess->write("package main\nimport \"\""); m_gocodeImportProcess->closeWriteChannel(); } void GolangCode::gocodeImportFinished(int code, QProcess::ExitStatus) { if (code != 0) { return; } QByteArray data = m_gocodeImportProcess->readAllStandardOutput(); QList<QString> lines = QString::fromUtf8(data).split('\n'); QStringList importList; m_extraPkgListMap.clear(); foreach (QString line, lines) { QStringList ar = line.split(",,"); if (ar.count() < 3) { continue; } if (ar.at(0) == "PANIC") { continue; } if (ar[0] != "import") { continue; } if (m_importList.contains(ar[1])) { continue; } QString pkg = ar[1]; importList.append(pkg); QStringList pathList = pkg.split("/"); m_extraPkgListMap.insert(pathList.last(),pkg); } if (m_completer) { m_completer->setImportList(QStringList() << m_importList << importList); } } //void GolangCode::importFinished(int code,QProcess::ExitStatus) //{ // if (code != 0) { // return; // } // return; // QByteArray read = m_importProcess->readAllStandardOutput(); // QString data = QString::fromUtf8(read); // QStringList importList = data.split('\n'); // importList.removeDuplicates(); // importList.sort(); // m_extraPkgListMap.clear(); // foreach (QString line, importList) { // QStringList pathList = line.split("/"); // m_extraPkgListMap.insert(pathList.last(),line); // } // m_allImportList = m_importList; // m_allImportList.append(importList); // m_allImportList.removeDuplicates(); // if (m_completer) { // m_completer->setImportList(m_allImportList); // } //} ImportPkgTip::ImportPkgTip(LiteApi::IApplication *app, QObject *parent) : QObject(parent), m_liteApp(app) { m_editWidget = 0; m_startPos = 0; m_pkgIndex = 0; m_escapePressed = false; m_enterPressed = false; m_popup = new FakeToolTip(); //m_popup->setFocusPolicy(Qt::NoFocus); m_infoLabel = new QLabel; m_pkgLabel = new QLabel; QHBoxLayout *layout = new QHBoxLayout; layout->setMargin(0); layout->addWidget(m_infoLabel); layout->addWidget(m_pkgLabel); m_popup->setLayout(layout); qApp->installEventFilter(this); } ImportPkgTip::~ImportPkgTip() { delete m_popup; } void ImportPkgTip::showPkgHint(int startpos, const QStringList &pkg, QPlainTextEdit *ed) { const QDesktopWidget *desktop = QApplication::desktop(); #ifdef Q_WS_MAC const QRect screen = desktop->availableGeometry(desktop->screenNumber(ed)); #else const QRect screen = desktop->screenGeometry(desktop->screenNumber(ed)); #endif m_pkg = pkg; m_startPos = startpos; m_enterPressed = false; m_escapePressed = false; m_pkgIndex = 0; const QSize sz = m_popup->minimumSizeHint(); QTextCursor cur = ed->textCursor(); cur.setPosition(startpos); QPoint pos = ed->cursorRect(cur).topLeft(); pos.setY(pos.y() - sz.height() - 1); pos = ed->mapToGlobal(pos); if (pos.x() + sz.width() > screen.right()) pos.setX(screen.right() - sz.width()); m_infoLabel->setText(tr("warning, pkg not find, please enter to import :")); if (m_pkg.size() == 1) { m_pkgLabel->setText(m_pkg[0]); } else { m_pkgLabel->setText(QString("[%1/%2] \"%3\"").arg(m_pkgIndex+1).arg(m_pkg.size()).arg(m_pkg[m_pkgIndex])); } m_popup->move(pos); if (!m_popup->isVisible()) { m_popup->show(); } } void ImportPkgTip::hide() { m_popup->hide(); } void ImportPkgTip::setWidget(QWidget *widget) { hide(); m_editWidget = widget; } bool ImportPkgTip::eventFilter(QObject *obj, QEvent *e) { if (!m_popup->isVisible()) { return QObject::eventFilter(obj,e); } switch (e->type()) { case QEvent::ShortcutOverride: if (m_popup->isVisible() && static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape) { m_escapePressed = true; e->accept(); } else if (static_cast<QKeyEvent*>(e)->modifiers() & Qt::ControlModifier) { m_popup->hide(); } break; case QEvent::KeyPress: { QKeyEvent *ke = static_cast<QKeyEvent*>(e); if (ke->key() == Qt::Key_Escape) { m_escapePressed = true; } else if (ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter) { m_enterPressed = true; e->accept(); return true; } else if (ke->key() == Qt::Key_Up) { if (m_pkg.size() > 1) { e->accept(); m_pkgIndex--; if (m_pkgIndex < 0) { m_pkgIndex = m_pkg.size()-1; } m_pkgLabel->setText(QString("[%1/%2] \"%3\"").arg(m_pkgIndex+1).arg(m_pkg.size()).arg(m_pkg[m_pkgIndex])); } return true; } else if (ke->key() == Qt::Key_Down) { if (m_pkg.size() > 1) { e->accept(); m_pkgIndex++; if (m_pkgIndex >= m_pkg.size()) { m_pkgIndex = 0; } m_pkgLabel->setText(QString("[%1/%2] \"%3\"").arg(m_pkgIndex+1).arg(m_pkg.size()).arg(m_pkg[m_pkgIndex])); } return true; } } break; case QEvent::KeyRelease: { QKeyEvent *ke = static_cast<QKeyEvent*>(e); if (ke->key() == Qt::Key_Escape && m_escapePressed) { hide(); } else if ( (ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter) && m_enterPressed) { e->accept(); m_enterPressed = false; hide(); emit import(m_pkg[m_pkgIndex],m_startPos); } else if (ke->key() == Qt::Key_Up) { return true; } else if (ke->key() == Qt::Key_Down) { return true; } else if (ke->text() != "."){ hide(); } } break; case QEvent::FocusOut: case QEvent::WindowDeactivate: case QEvent::Resize: if (obj != m_editWidget) break; hide(); break; case QEvent::Move: if (obj != m_liteApp->mainWindow()) break; hide(); break; case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseButtonDblClick: case QEvent::Wheel: { hide(); } break; default: break; } return false; }
30,608
C++
.cpp
890
26.975281
165
0.579475
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,380
golangcodeoptionfactory.cpp
visualfc_liteide/liteidex/src/plugins/golangcode/golangcodeoptionfactory.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangcodeoptionfactory.cpp // Creator: Nik-U <niku@vaxxine.com> #include "golangcodeoption.h" #include "golangcodeoptionfactory.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangCodeOptionFactory::GolangCodeOptionFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IOptionFactory(parent), m_liteApp(app) { } QStringList GolangCodeOptionFactory::mimeTypes() const { return QStringList() << "option/golangcode"; } LiteApi::IOption *GolangCodeOptionFactory::create(const QString &mimeType) { if (mimeType == "option/golangcode") { return new GolangCodeOption(m_liteApp,this); } return 0; }
1,904
C++
.cpp
49
36.571429
93
0.687736
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,381
golangcodeplugin.cpp
visualfc_liteide/liteidex/src/plugins/golangcode/golangcodeplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangcodeplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangcodeplugin.h" #include "liteeditorapi/liteeditorapi.h" #include "qtc_editutil/uncommentselection.h" #include "golangcode.h" #include "golangcodeoptionfactory.h" #include <QMenu> #include <QAction> #include <QPlainTextEdit> #include <QFileInfo> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangCodePlugin::GolangCodePlugin() { } bool GolangCodePlugin::load(LiteApi::IApplication *app) { m_liteApp = app; m_code = new GolangCode(app,this); //app->optionManager()->addFactory(new GolangCodeOptionFactory(app,this)); connect(app->editorManager(),SIGNAL(editorCreated(LiteApi::IEditor*)),this,SLOT(editorCreated(LiteApi::IEditor*))); //connect(app->editorManager(),SIGNAL(currentEditorChanged(LiteApi::IEditor*)),this,SLOT(currentEditorChanged(LiteApi::IEditor*))); connect(app,SIGNAL(loaded()),this,SLOT(appLoaded())); return true; } QStringList GolangCodePlugin::dependPluginList() const { return QStringList() << "plugin/liteenv" << "plugin/golangast"; } void GolangCodePlugin::appLoaded() { } void GolangCodePlugin::editorCreated(LiteApi::IEditor *editor) { if (!editor) { return; } if (editor->mimeType() != "text/x-gosrc") { return; } LiteApi::ILiteEditor *liteEdit = LiteApi::getLiteEditor(editor); if (liteEdit) { liteEdit->setSpellCheckZoneDontComplete(true); } } void GolangCodePlugin::currentEditorChanged(LiteApi::IEditor *editor) { if (editor) { if (editor->mimeType() == "text/x-gosrc") { LiteApi::ICompleter *completer = LiteApi::findExtensionObject<LiteApi::ICompleter*>(editor,"LiteApi.ICompleter"); m_code->setCompleter(completer); return; } else if (editor->mimeType() == "browser/goplay") { LiteApi::IEditor* editor = LiteApi::findExtensionObject<LiteApi::IEditor*>(m_liteApp->extension(),"LiteApi.Goplay.IEditor"); if (editor && editor->mimeType() == "text/x-gosrc") { LiteApi::ICompleter *completer = LiteApi::findExtensionObject<LiteApi::ICompleter*>(editor,"LiteApi.ICompleter"); m_code->setCompleter(completer); return; } } } m_code->setCompleter(0); } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
3,662
C++
.cpp
95
34.663158
136
0.68353
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,382
golangcodeoption.cpp
visualfc_liteide/liteidex/src/plugins/golangcode/golangcodeoption.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangcodeoption.cpp // Creator: Nik-U <niku@vaxxine.com> #include "golangcodeoption.h" #include "golangcode_global.h" #include "ui_golangcodeoption.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangCodeOption::GolangCodeOption(LiteApi::IApplication *app,QObject *parent) : LiteApi::IOption(parent), m_liteApp(app), m_widget(new QWidget), ui(new Ui::GolangCodeOption) { ui->setupUi(m_widget); } GolangCodeOption::~GolangCodeOption() { delete m_widget; delete ui; } QWidget *GolangCodeOption::widget() { return m_widget; } QString GolangCodeOption::name() const { return "GolangCode"; } QString GolangCodeOption::mimeType() const { return "option/golangcode"; } void GolangCodeOption::load() { bool close = m_liteApp->settings()->value(GOLANGCODE_EXITCLOSE,true).toBool(); bool allpkg = m_liteApp->settings()->value(GOLANGCODE_IMPORTHINT_GOPATH,true).toBool(); ui->exitCloseCheckBox->setChecked(close); ui->pkgHintGopathRadioButton->setChecked(allpkg); ui->pkgHintStdRadioButton->setChecked(!allpkg); } void GolangCodeOption::save() { bool close = ui->exitCloseCheckBox->isChecked(); bool allpkg = ui->pkgHintGopathRadioButton->isChecked(); m_liteApp->settings()->setValue(GOLANGCODE_EXITCLOSE,close); m_liteApp->settings()->setValue(GOLANGCODE_IMPORTHINT_GOPATH,allpkg); }
2,623
C++
.cpp
74
32.972973
91
0.701299
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,383
qsqleditor.cpp
visualfc_liteide/liteidex/src/plugins/qsqleditor/qsqleditor.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: qsqleditor.cpp // Creator: visualfc <visualfc@gmail.com> #include "qsqleditor.h" #include "ui_qsqleditor.h" #include <QStandardItemModel> #include <QStandardItem> #include <QMenu> #include <QAction> #include <tableviewwidget.h> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end QSqlEditor::QSqlEditor(LiteApi::IApplication *app) : m_liteApp(app), m_file(0), m_widget(new QWidget), ui(new Ui::QSqlEditor), m_bReadOnly(false) { ui->setupUi(m_widget); m_dbModel = new QStandardItemModel(this); ui->dbTreeView->setEditTriggers(0); ui->dbTreeView->setModel(m_dbModel); ui->dbTreeView->setHeaderHidden(true); ui->dbTreeView->setContextMenuPolicy(Qt::CustomContextMenu); ui->tabWidget->setTabsClosable(true); m_infoAct = new QAction(tr("Infomation"),this); m_editorAct = new QAction(tr("Edit Table"),this); m_tableMenu = new QMenu; m_tableMenu->addAction(m_infoAct); m_tableMenu->addAction(m_editorAct); connect(ui->dbTreeView,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(dbTreeContextMenuRequested(QPoint))); connect(m_editorAct,SIGNAL(triggered()),this,SLOT(editorTable())); //connect(ui->tabWidget,SIGNAL(tabCloseRequested(int)),this,SLOT()) } QSqlEditor::~QSqlEditor() { ui->tabWidget->clear(); if (m_file) { delete m_file; } delete m_tableMenu; delete ui; delete m_widget; } QWidget *QSqlEditor::widget() { return m_widget; } QString QSqlEditor::name() const { if (m_file) { return m_file->fileName(); } return QString(""); } bool QSqlEditor::open(const QString &/*fileName*/,const QString &/*mimeType*/) { return false; } bool QSqlEditor::reload() { return false; } bool QSqlEditor::save() { return false; } bool QSqlEditor::saveAs(const QString &/*fileName*/) { return false; } void QSqlEditor::setReadOnly(bool b) { m_bReadOnly = b; } bool QSqlEditor::isReadOnly() const { return m_bReadOnly; } bool QSqlEditor::isModified() const { return false; } QString QSqlEditor::fileName() const { if (!m_file) { return QString(); } return m_file->fileName(); } QString QSqlEditor::mimeType() const { if (!m_file) { return QString(); } return m_file->mimeType(); } LiteApi::IFile *QSqlEditor::file() { return m_file; } void QSqlEditor::setFile(QSqlDbFile *file) { m_file = file; if (m_file && m_file->db().isOpen()) { loadDatabase(); } } QString QSqlEditor::tableTypeNames(int type) const{ if (type == QSql::Tables) { return tr("Tables"); } else if (type == QSql::Views) { return tr("Views"); } else if (type == QSql::SystemTables) { return tr("SystemTables"); } else if (type == QSql::AllTables) { return tr("AllTables"); } return tr("Unknow"); } QString QSqlEditor::tableTypeName(int type) const{ if (type == QSql::Tables) { return tr("Table"); } else if (type == QSql::Views) { return tr("View"); } else if (type == QSql::SystemTables) { return tr("SystemTable"); } else if (type == QSql::AllTables) { return tr("AllTable"); } return tr("Unknow"); } void QSqlEditor::loadDatabase() { m_dbModel->clear(); appendTableItems(QSql::Tables); appendTableItems(QSql::Views); appendTableItems(QSql::SystemTables); ui->dbTreeView->expandAll(); } void QSqlEditor::appendTableItems(QSql::TableType type) { QString typeName = tableTypeNames(type); QStringList tables = m_file->db().tables(type); QStandardItem *root = new QStandardItem(typeName); foreach (QString table, tables) { QStandardItem *item = new QStandardItem(table); item->setData(type); root->appendRow(item); } m_dbModel->appendRow(root); } void QSqlEditor::dbTreeContextMenuRequested(const QPoint &pt) { QModelIndex index = ui->dbTreeView->indexAt(pt); m_contextIndex = index; if (!index.isValid()) { return; } bool bok; int type = index.data(Qt::UserRole+1).toInt(&bok); QMenu *contextMenu = 0; if (type == QSql::Tables || type == QSql::Views || type == QSql::SystemTables) { contextMenu = m_tableMenu; } if (contextMenu) { contextMenu->popup(ui->dbTreeView->mapToGlobal(pt)); } } void QSqlEditor::editorTable() { int type = m_contextIndex.data(Qt::UserRole+1).toInt(); if (type == QSql::Tables || type == QSql::Views || type == QSql::SystemTables) { QString typeName = tableTypeName(type); QString table = m_contextIndex.data().toString(); TableViewWidget *w = new TableViewWidget(m_file->db()); w->setTable(table); ui->tabWidget->addTab(w,QString(tr("%1:%2")).arg(typeName).arg(table)); ui->tabWidget->setCurrentWidget(w); } }
6,152
C++
.cpp
212
25.018868
117
0.654659
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,384
qsqleditorplugin.cpp
visualfc_liteide/liteidex/src/plugins/qsqleditor/qsqleditorplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: qsqleditorplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "qsqleditorplugin.h" #include "qsqlfilefactory.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end QSqlEditorPlugin::QSqlEditorPlugin() { m_info->setId("plugin/QSqlEditor"); m_info->setName("QSqlEditor"); m_info->setAuthor("visualfc"); m_info->setInfo("QtSql Editor Plugin"); } bool QSqlEditorPlugin::initWithApp(LiteApi::IApplication *app) { if (!LiteApi::IPlugin::initWithApp(app)) { return false; } QSqlFileFactory *factory = new QSqlFileFactory(app,this); if (factory) { m_liteApp->editorManager()->addFactory(factory); } return true; } Q_EXPORT_PLUGIN(QSqlEditorPlugin)
1,967
C++
.cpp
52
35.153846
82
0.675223
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,385
sqlitemdelegate.cpp
visualfc_liteide/liteidex/src/plugins/qsqleditor/sqlitemdelegate.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: sqlitemdelegate.cpp // Creator: visualfc <visualfc@gmail.com> #include "sqlitemdelegate.h" #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end SqlItemDelegate::SqlItemDelegate(QObject *parent) : QItemDelegate(parent) { } QWidget *SqlItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { QVariant var = index.data(Qt::EditRole); if (var.type() == QVariant::ByteArray) { return 0; } return QItemDelegate::createEditor(parent,option,index); }
1,848
C++
.cpp
47
36.191489
82
0.665184
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,386
sqliterfile.cpp
visualfc_liteide/liteidex/src/plugins/qsqleditor/sqliterfile.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: sqliterfile.cpp // Creator: visualfc <visualfc@gmail.com> #include "sqlitefile.h" #include <QDebug> #include <QSqlError> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end SQLiteFile::SQLiteFile(LiteApi::IApplication *app, QObject *parent) : QSqlDbFile(app,parent) { } bool SQLiteFile::open(const QString &fileName, const QString &/*mimeType*/) { m_db = QSqlDatabase::addDatabase("QSQLITE",fileName); m_db.setDatabaseName(fileName); return m_db.open(); } QString SQLiteFile::mimeType() const { return "database/sqlite"; }
1,802
C++
.cpp
48
35.520833
82
0.678857
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,387
qsqlfilefactory.cpp
visualfc_liteide/liteidex/src/plugins/qsqleditor/qsqlfilefactory.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: qsqlfilefactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "qsqlfilefactory.h" #include "sqlitefile.h" #include "qsqleditor.h" #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end QSqlFileFactory::QSqlFileFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IEditorFactory(parent), m_liteApp(app) { } QStringList QSqlFileFactory::mimeTypes() const { return QStringList() << "database/sqlite"; } LiteApi::IEditor *QSqlFileFactory::open(const QString &fileName, const QString &mimeType) { QSqlDbFile *file = 0; if (mimeType == "database/sqlite") { file = new SQLiteFile(m_liteApp); if (!file->open(fileName,mimeType)) { delete file; return 0; } } if (!file) { return 0; } QSqlEditor *editor = new QSqlEditor(m_liteApp); editor->setFile(file); return editor; } bool QSqlFileFactory::targetInfo(const QString &/*fileName*/, const QString &/*mimetype*/, QString &/*target*/, QString &/*targetPath*/, QString &/*workPath*/) const { return false; }
2,347
C++
.cpp
65
33.030769
165
0.66696
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,388
qsqldbfile.cpp
visualfc_liteide/liteidex/src/plugins/qsqleditor/qsqldbfile.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: qsqldbfile.cpp // Creator: visualfc <visualfc@gmail.com> #include "qsqldbfile.h" #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end QSqlDbFile::QSqlDbFile(LiteApi::IApplication *app, QObject *parent) : LiteApi::IFile(parent), m_liteApp(app) { } QSqlDbFile::~QSqlDbFile() { if (m_db.isOpen()) { m_db.close(); } } bool QSqlDbFile::open(const QString &/*fileName*/, const QString &/*mimeType*/) { return false; } bool QSqlDbFile::reload() { return false; } bool QSqlDbFile::save(const QString &/*fileName*/) { return false; } bool QSqlDbFile::isReadOnly() const { return false; } QString QSqlDbFile::fileName() const { return m_db.databaseName(); } QString QSqlDbFile::mimeType() const { return "database/sql"; } QSqlDatabase &QSqlDbFile::db() { return m_db; }
2,094
C++
.cpp
72
26.875
82
0.671968
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,389
tableviewwidget.cpp
visualfc_liteide/liteidex/src/plugins/qsqleditor/tableviewwidget.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: tableviewwidget.cpp // Creator: visualfc <visualfc@gmail.com> #include "tableviewwidget.h" #include "ui_tableviewwidget.h" #include "sqltablemodel.h" #include "sqlitemdelegate.h" #include <QTableWidgetItem> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end TableViewWidget::TableViewWidget(QSqlDatabase &db, QWidget *parent) : QWidget(parent), ui(new Ui::TableViewWidget) { ui->setupUi(this); m_model = new SqlTableModel(this,db); m_delegate = new SqlItemDelegate(this); ui->tableView->setModel(m_model); ui->tableView->resizeColumnsToContents(); ui->tableView->setItemDelegate(m_delegate); } TableViewWidget::~TableViewWidget() { delete ui; } void TableViewWidget::setTable(const QString &table) { m_model->setTable(table); m_model->select(); if (m_model->columnCount() <= 0) return; ui->tableView->resizeColumnsToContents(); ui->tableView->resizeRowsToContents(); int total = 0; for (int i = 0; i < m_model->columnCount(); ++i) total += ui->tableView->columnWidth(i); if (total < ui->tableView->viewport()->width()) { int extra = (ui->tableView->viewport()->width() - total) / m_model->columnCount(); for (int i = 0; i < m_model->columnCount(); ++i) ui->tableView->setColumnWidth(i, ui->tableView->columnWidth(i) + extra); } }
2,636
C++
.cpp
70
34.157143
84
0.661189
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,390
sqltablemodel.cpp
visualfc_liteide/liteidex/src/plugins/qsqleditor/sqltablemodel.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: sqltablemodel.cpp // Creator: visualfc <visualfc@gmail.com> #include "sqltablemodel.h" #include <QColor> #include <QDebug> #include <QSqlRecord> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end SqlTableModel::SqlTableModel(QObject *parent, QSqlDatabase db) : QSqlTableModel(parent,db) { m_blobColor = QColor(Qt::darkYellow); } QVariant SqlTableModel::data(const QModelIndex &idx, int role) const { QVariant var = QSqlTableModel::data(idx,Qt::DisplayRole); if (var.isNull()) { if (role == Qt::BackgroundColorRole) return QVariant(m_blobColor); if (role == Qt::ToolTipRole) return QVariant(tr("NULL value")); if (role == Qt::DisplayRole) return QVariant(tr("{null}")); if (role == Qt::EditRole) return QSqlTableModel::data(idx, Qt::DisplayRole); if (role == Qt::UserRole+1) return QVariant("{blob}"); } else if (var.type() == QVariant::ByteArray) { if (role == Qt::BackgroundColorRole) return QVariant(m_blobColor); if (role == Qt::ToolTipRole) return QVariant(tr("BLOB value")); if (role == Qt::DisplayRole) return QVariant(tr("{blob}")); if (role == Qt::EditRole) return QSqlTableModel::data(idx, Qt::DisplayRole); if (role == Qt::UserRole+1) return QVariant("{blob}"); } return QSqlTableModel::data(idx,role); }
2,705
C++
.cpp
68
34.970588
82
0.63512
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,391
filebrowserplugin.cpp
visualfc_liteide/liteidex/src/plugins/filebrowser/filebrowserplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: filebrowserplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "filebrowserplugin.h" #include "filebrowser.h" #include "filebrowseroptionfactory.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end FileBrowserPlugin::FileBrowserPlugin() : m_browser(0) { } bool FileBrowserPlugin::load(LiteApi::IApplication *app) { m_browser = new FileBrowser(app,this); //app->optionManager()->addFactory(new FileBrowserOptionFactory(app,this)); return true; } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
1,807
C++
.cpp
46
37.391304
82
0.69095
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,392
filebrowseroptionfactory.cpp
visualfc_liteide/liteidex/src/plugins/filebrowser/filebrowseroptionfactory.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: filebrowseroptionfactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "filebrowseroption.h" #include "filebrowseroptionfactory.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end FileBrowserOptionFactory::FileBrowserOptionFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IOptionFactory(parent), m_liteApp(app) { } QStringList FileBrowserOptionFactory::mimeTypes() const { return QStringList() << "option/filebrowser"; } LiteApi::IOption *FileBrowserOptionFactory::create(const QString &mimeType) { if (mimeType == "option/filebrowser") { return new FileBrowserOption(m_liteApp,this); } return 0; }
1,919
C++
.cpp
49
36.877551
95
0.690782
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,393
filebrowseroption.cpp
visualfc_liteide/liteidex/src/plugins/filebrowser/filebrowseroption.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: filebrowseroption.cpp // Creator: visualfc <visualfc@gmail.com> #include "filebrowseroption.h" #include "ui_filebrowseroption.h" #include "filebrowser.h" #include <QDir> #include <QFileInfo> #include <QLocale> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end FileBrowserOption::FileBrowserOption(LiteApi::IApplication *app,QObject *parent) : LiteApi::IOption(parent), m_liteApp(app), m_widget(new QWidget), ui(new Ui::FileBrowserOption) { ui->setupUi(m_widget); } FileBrowserOption::~FileBrowserOption() { delete m_widget; delete ui; } QWidget *FileBrowserOption::widget() { return m_widget; } QString FileBrowserOption::name() const { return "FileBrowser"; } QString FileBrowserOption::mimeType() const { return "option/filebrowser"; } void FileBrowserOption::load() { } void FileBrowserOption::save() { QString cmd = ui->cmdLineEdit->text().trimmed(); QString args = ui->argsLineEdit->text().trimmed(); m_liteApp->settings()->setValue("filebrowser/shell_cmd",cmd); m_liteApp->settings()->setValue("filebrowser/shell_args",args.split(" ",qtSkipEmptyParts)); }
2,384
C++
.cpp
72
30.861111
95
0.693443
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,394
filebrowser.cpp
visualfc_liteide/liteidex/src/plugins/filebrowser/filebrowser.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: filebrowser.cpp // Creator: visualfc <visualfc@gmail.com> #include "filebrowser.h" #include "golangdocapi/golangdocapi.h" #include "liteenvapi/liteenvapi.h" #include "litebuildapi/litebuildapi.h" #include "litedebugapi/litedebugapi.h" #include "fileutil/fileutil.h" #include "filebrowser_global.h" #include <QVBoxLayout> #include <QHBoxLayout> #include <QComboBox> #include <QTreeView> #include <QHeaderView> #include <QToolBar> #include <QAction> #include <QFileInfo> #include <QInputDialog> #include <QMessageBox> #include <QMenu> #include <QProcess> #include <QDesktopServices> #include <QUrl> #include <QDialogButtonBox> #include <QLineEdit> #include <QLabel> #include <QDebug> #ifdef Q_OS_WIN #include <windows.h> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end #endif FileBrowser::FileBrowser(LiteApi::IApplication *app, QObject *parent) : QObject(parent), m_liteApp(app) { m_widget = new QWidget; QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->setMargin(0); mainLayout->setSpacing(0); QDir::Filters filters = QDir::AllDirs | QDir::Files | QDir::Drives | QDir::Readable| QDir::Writable | QDir::Executable /*| QDir::Hidden*/ | QDir::NoDotAndDotDot; bool bShowHiddenFiles = m_liteApp->settings()->value(FILEBROWSER_SHOWHIDDENFILES,false).toBool(); if (bShowHiddenFiles) { filters |= QDir::Hidden; } bool bShowDetails = m_liteApp->settings()->value(FILEBROWSER_SHOWDETAILS,false).toBool(); #ifdef Q_OS_WIN // Symlinked directories can cause file watcher warnings on Win32. filters |= QDir::NoSymLinks; #endif //create filter toolbar //m_filterToolBar = new QToolBar(m_widget); //m_filterToolBar->setIconSize(QSize(16,16)); #ifdef Q_OS_MAC m_folderView = new FolderView(true,m_liteApp); #else m_folderView = new FolderView(false,m_liteApp); #endif m_folderView->setRootIsDecorated(true); m_folderView->setFilter(filters); m_syncAct = new QAction(QIcon("icon:images/sync.png"),tr("Synchronize with editor"),this); m_syncAct->setCheckable(true); m_reloadAct = new QAction(QIcon("icon:filebrowser/images/reload.png"),tr("Reload Folder"),this); m_showHideFilesAct = new QAction(tr("Show Hidden Files"),this); m_showHideFilesAct->setCheckable(true); if (bShowHiddenFiles) { m_showHideFilesAct->setChecked(true); } connect(m_showHideFilesAct,SIGNAL(triggered(bool)),this,SLOT(showHideFiles(bool))); m_showDetailsAct = new QAction(tr("Show Details"),this); m_showDetailsAct->setCheckable(true); if (bShowDetails) { m_showDetailsAct->setChecked(true); } connect(m_showDetailsAct,SIGNAL(triggered(bool)),m_folderView,SLOT(setShowDetails(bool))); m_folderView->setShowDetails(bShowDetails); m_executeFileAct = new QAction(tr("Execute File"),this); connect(m_executeFileAct,SIGNAL(triggered()),this,SLOT(executeFile())); m_debugFileAct = new QAction(tr("Debug File"),this); connect(m_debugFileAct,SIGNAL(triggered()),this,SLOT(debugFile())); // m_filterCombo = new QComboBox; // m_filterCombo->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); // m_filterCombo->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLength); // m_filterCombo->setEditable(true); // m_filterCombo->addItem("*"); // m_filterCombo->addItem("Makefile;*.go;*.cgo;*.s;*.goc;*.y;*.e64;*.pro"); // m_filterCombo->addItem("*.sh;Makefile;*.go;*.cgo;*.s;*.goc;*.y;*.*.c;*.cpp;*.h;*.hpp;*.e64;*.pro"); //m_filterToolBar->addAction(m_syncAct); //m_filterToolBar->addSeparator(); //m_filterToolBar->addWidget(m_filterCombo); //create root toolbar m_rootToolBar = new QToolBar(m_widget); m_rootToolBar->setIconSize(QSize(16,16)); m_cdupAct = new QAction(QIcon("icon:filebrowser/images/cdup.png"),tr("Open Parent"),this); m_rootCombo = new QComboBox; m_rootCombo->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); m_rootCombo->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLength); m_rootCombo->setEditable(false); m_rootToolBar->addAction(m_cdupAct); m_rootToolBar->addAction(m_reloadAct); m_rootToolBar->addSeparator(); m_rootToolBar->addWidget(m_rootCombo); //mainLayout->addWidget(m_filterToolBar); mainLayout->addWidget(m_rootToolBar); mainLayout->addWidget(m_folderView); m_widget->setLayout(mainLayout); m_setRootAct = new QAction(tr("Set As Root Folder"),this); m_openFolderInNewWindowAct = new QAction(tr("Open Folder in New Window"),this); m_addToFoldersAct = new QAction(tr("Add to Folders"),this); connect(m_setRootAct,SIGNAL(triggered()),this,SLOT(setFolderToRoot())); connect(m_cdupAct,SIGNAL(triggered()),this,SLOT(cdUp())); connect(m_openFolderInNewWindowAct,SIGNAL(triggered()),this,SLOT(openFolderInNewWindow())); connect(m_addToFoldersAct,SIGNAL(triggered()),this,SLOT(addToFolders())); QList<QAction*> actions; m_filterMenu = new QMenu(tr("Filter")); m_filterMenu->setIcon(QIcon("icon:images/filter.png")); m_filterMenu->addAction(m_showHideFilesAct); m_filterMenu->addAction(m_showDetailsAct); actions << m_filterMenu->menuAction() << m_syncAct; m_toolWindowAct = m_liteApp->toolWindowManager()->addToolWindow(Qt::LeftDockWidgetArea,m_widget,"FileSystem",tr("File System"),true,actions); connect(m_toolWindowAct,SIGNAL(toggled(bool)),this,SLOT(visibilityChanged(bool))); //connect(m_filterCombo,SIGNAL(activated(QString)),this,SLOT(activatedFilter(QString))); connect(m_rootCombo,SIGNAL(activated(QString)),this,SLOT(activatedRoot(QString))); connect(m_syncAct,SIGNAL(triggered(bool)),this,SLOT(syncFileModel(bool))); connect(m_reloadAct,SIGNAL(triggered()),this,SLOT(reloadFileModel())); connect(m_liteApp->editorManager(),SIGNAL(currentEditorChanged(LiteApi::IEditor*)),this,SLOT(currentEditorChanged(LiteApi::IEditor*))); connect(m_folderView,SIGNAL(aboutToShowContextMenu(QMenu*,LiteApi::FILESYSTEM_CONTEXT_FLAG,QFileInfo)),this,SLOT(aboutToShowContextMenu(QMenu*,LiteApi::FILESYSTEM_CONTEXT_FLAG,QFileInfo))); //connect(m_folderView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(openEditor(QModelIndex))); connect(m_folderView,SIGNAL(enterKeyPressed(QModelIndex)),this,SLOT(enterKeyPressedFolderView(QModelIndex))); connect(m_folderView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(doubleClickedFolderView(QModelIndex))); QString root = m_liteApp->settings()->value("FileBrowser/root","").toString(); if (!root.isEmpty()) { addFolderToRoot(root); } bool b = m_liteApp->settings()->value("FileBrowser/synceditor",true).toBool(); if (b) { m_syncAct->setChecked(true); } } FileBrowser::~FileBrowser() { QString root = m_rootCombo->currentText(); m_liteApp->settings()->setValue("FileBrowser/root",root); m_liteApp->settings()->setValue("FileBrowser/synceditor",m_syncAct->isChecked()); m_liteApp->settings()->setValue(FILEBROWSER_SHOWHIDDENFILES,m_showHideFilesAct->isChecked()); m_liteApp->settings()->setValue(FILEBROWSER_SHOWDETAILS,m_showDetailsAct->isChecked()); delete m_filterMenu; delete m_widget; } void FileBrowser::visibilityChanged(bool) { } void FileBrowser::currentEditorChanged(LiteApi::IEditor *editor) { if (!m_syncAct->isChecked()) { return; } if (!editor) { return; } QString fileName = editor->filePath(); if (fileName.isEmpty()) { return; } QFileInfo info(fileName); addFolderToRoot(info.path()); QModelIndex index = m_folderView->indexForPath(fileName); if (!index.isValid()) { return; } m_folderView->scrollTo(index,QAbstractItemView::EnsureVisible); m_folderView->clearSelection(); m_folderView->setCurrentIndex(index); } void FileBrowser::syncFileModel(bool b) { if (b == false) { return; } else { currentEditorChanged(m_liteApp->editorManager()->currentEditor()); } } void FileBrowser::reloadFileModel() { m_folderView->reload(); } void FileBrowser::aboutToShowContextMenu(QMenu *menu, LiteApi::FILESYSTEM_CONTEXT_FLAG flag, const QFileInfo &info) { m_liteApp->fileManager()->emitAboutToShowFolderContextMenu(menu,flag,info,"filebrowser"); if (flag == LiteApi::FILESYSTEM_FILES) { QString cmd = FileUtil::lookPathInDir(info.fileName(),info.path()); if (!cmd.isEmpty()) { QAction *act = 0; if (!menu->actions().isEmpty()) { act = menu->actions().at(0); } menu->insertAction(act,m_executeFileAct); bool hasGo = false; foreach(QFileInfo info, QDir(info.path()).entryInfoList(QDir::Files)) { if (info.suffix() == "go") { hasGo = true; break; } } if (hasGo) { menu->insertAction(act,m_debugFileAct); } menu->insertSeparator(act); } } else if (flag == LiteApi::FILESYSTEM_FOLDER || flag == LiteApi::FILESYSTEM_ROOTFOLDER) { menu->addSeparator(); if (flag == LiteApi::FILESYSTEM_ROOTFOLDER) { menu->addAction(m_cdupAct); } else { menu->addAction(m_setRootAct); } menu->addAction(m_addToFoldersAct); menu->addAction(m_openFolderInNewWindowAct); } } void FileBrowser::showHideFiles(bool b) { if (isShowHideFiles() == b) { return; } QDir::Filters filters = m_folderView->filter(); if (b) { filters |= QDir::Hidden; } else { filters ^= QDir::Hidden; } m_folderView->setFilter(filters); } bool FileBrowser::isShowHideFiles() const { return m_folderView->filter() & QDir::Hidden; } void FileBrowser::openFolderInNewWindow() { QDir dir = m_folderView->contextDir(); m_liteApp->fileManager()->openFolderInNewWindow(dir.path()); } void FileBrowser::addToFolders() { QDir dir = m_folderView->contextDir(); m_liteApp->fileManager()->addFolderList(dir.path()); } void FileBrowser::executeFile() { LiteApi::ILiteBuild *build = LiteApi::getLiteBuild(m_liteApp); if (build) { QFileInfo info = m_folderView->contextFileInfo(); QString cmd = FileUtil::lookPathInDir(info.fileName(),info.path()); if (!cmd.isEmpty()) { build->execCommand(cmd,QString(),info.path(),true,true,false); } } } void FileBrowser::debugFile() { LiteApi::ILiteDebug *debug = LiteApi::getLiteDebug(m_liteApp); if (debug) { QFileInfo info = m_folderView->contextFileInfo(); debug->startDebug(info.fileName(),"",info.path()); } } void FileBrowser::enterKeyPressedFolderView(const QModelIndex &index) { QFileInfo info = m_folderView->fileInfo(index); if (info.isFile()) { m_liteApp->fileManager()->openEditor(info.filePath()); } else if (info.isDir()) { m_folderView->setExpanded(index,!m_folderView->isExpanded(index)); } } void FileBrowser::doubleClickedFolderView(const QModelIndex &index) { QFileInfo info = m_folderView->fileInfo(index); if (info.isFile()) { m_liteApp->fileManager()->openEditor(info.filePath()); } } void FileBrowser::addFolderToRoot(const QString &path) { int index = -1; for (int i = 0; i < m_rootCombo->count(); i++) { QString text = m_rootCombo->itemText(i); if (text == path) { index = i; break; } } if (index == -1) { m_rootCombo->addItem(path); index = m_rootCombo->count()-1; } m_rootCombo->setCurrentIndex(index); activatedRoot(path); } void FileBrowser::setFolderToRoot() { QDir dir = m_folderView->contextDir(); addFolderToRoot(dir.path()); } void FileBrowser::activatedRoot(QString path) { m_folderView->setRootPath(path); } void FileBrowser::cdUp() { QString path = m_folderView->rootPath(); if (path.isEmpty()) { return; } QDir dir(path); if (!dir.path().isEmpty() && dir.cdUp()) { addFolderToRoot(dir.path()); } }
13,479
C++
.cpp
348
33.764368
193
0.682794
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,395
golangeditplugin.cpp
visualfc_liteide/liteidex/src/plugins/golangedit/golangeditplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangeditplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangeditplugin.h" #include "golangedit.h" #include "golanghighlighterfactory.h" #include "golangeditoptionfactory.h" #include "liteeditorapi/liteeditorapi.h" #include <QtPlugin> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangEditPlugin::GolangEditPlugin() { } bool GolangEditPlugin::load(LiteApi::IApplication *app) { LiteApi::IHighlighterManager *manager = LiteApi::getHighlighterManager(app); if (manager) { manager->addFactory(new GolangHighlighterFactory(this)); } app->optionManager()->addFactory(new GolangEditOptionFactory(app,this)); new GolangEdit(app,this); return true; } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
2,039
C++
.cpp
53
36.320755
82
0.701312
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,396
golanghighlighterfactory.cpp
visualfc_liteide/liteidex/src/plugins/golangedit/golanghighlighterfactory.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golanghighlighterfactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "golanghighlighterfactory.h" #include "golanghighlighter.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangHighlighterFactory::GolangHighlighterFactory(QObject *parent) : LiteApi::IHighlighterFactory(parent) { } QStringList GolangHighlighterFactory::mimeTypes() const { return QStringList() << "text/x-gosrc"; } TextEditor::SyntaxHighlighter *GolangHighlighterFactory::create(LiteApi::ITextEditor *editor, QTextDocument *doc, const QString &/*mimeType*/) { return new GolangHighlighter(editor,doc); }
1,864
C++
.cpp
45
39.488889
142
0.70011
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,397
golangeditoption.cpp
visualfc_liteide/liteidex/src/plugins/golangedit/golangeditoption.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangeditoption.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangeditoption.h" #include "ui_golangeditoption.h" #include "golangedit_global.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangEditOption::GolangEditOption(LiteApi::IApplication *app,QObject *parent) : LiteApi::IOption(parent), m_liteApp(app), m_widget(new QWidget), ui(new Ui::GolangEditOption) { ui->setupUi(m_widget); } GolangEditOption::~GolangEditOption() { delete m_widget; delete ui; } QWidget *GolangEditOption::widget() { return m_widget; } QString GolangEditOption::name() const { return "GolangEdit"; } QString GolangEditOption::mimeType() const { return OPTION_GOLANGEDIT; } void GolangEditOption::load() { bool info = m_liteApp->settings()->value(GOLANGEDIT_MOUSEINFO,true).toBool(); bool nav = m_liteApp->settings()->value(GOLANGEDIT_MOUSENAVIGATIOIN,true).toBool(); bool gorootReadOnly = m_liteApp->settings()->value(GOLANGEDIT_GOROOTSOURCEREADONLY,false).toBool(); ui->enableMouseInfoCheckBox->setChecked(info); ui->enableMouseNavigationCheckBox->setChecked(nav); ui->gorootSourceReadOnlyCheckBox->setChecked(gorootReadOnly); } void GolangEditOption::save() { bool info = ui->enableMouseInfoCheckBox->isChecked(); bool nav = ui->enableMouseNavigationCheckBox->isChecked(); bool gorootReadOnly = ui->gorootSourceReadOnlyCheckBox->isChecked(); m_liteApp->settings()->setValue(GOLANGEDIT_MOUSEINFO,info); m_liteApp->settings()->setValue(GOLANGEDIT_MOUSENAVIGATIOIN,nav); m_liteApp->settings()->setValue(GOLANGEDIT_GOROOTSOURCEREADONLY,gorootReadOnly); }
2,906
C++
.cpp
77
35.168831
103
0.713931
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,398
goremovetagsdialog.cpp
visualfc_liteide/liteidex/src/plugins/golangedit/goremovetagsdialog.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2017 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: goremovetagsdialog.cpp // Creator: visualfc <visualfc@gmail.com> #include "goremovetagsdialog.h" #include "ui_goremovetagsdialog.h" #include "liteapi/liteqt.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GoRemoveTagsDialog::GoRemoveTagsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::GoRemoveTagsDialog) { ui->setupUi(this); connect(ui->clearAllTagsRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->clearAllOptionsRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->removeJsonTagRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->removeXmlOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->removeCustomTagRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->removeJsonOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->removeXmlOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->removeCustomOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments())); connect(ui->customTaglineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments())); connect(ui->jsonOptionLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments())); connect(ui->xmlOptionLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments())); connect(ui->customOptionLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments())); } GoRemoveTagsDialog::~GoRemoveTagsDialog() { delete ui; } void GoRemoveTagsDialog::setInfo(const QString &info) { ui->infoLabel->setText(info); } QString GoRemoveTagsDialog::arguments() const { return ui->argumentsEdit->toPlainText().trimmed(); } static QString removeHead(const QString &text, const QString &head) { if (text.startsWith(head)) { return text.mid(head.length()); } return text; } void GoRemoveTagsDialog::updateArguments() { QString args; if (ui->clearAllTagsRadioButton->isChecked()) { args = "-clear-tags"; } else if (ui->clearAllOptionsRadioButton->isChecked()) { args = "-clear-options"; } else if (ui->removeJsonTagRadioButton->isChecked()) { args = "-remove-tags json"; } else if (ui->removeXmlTagRadioButton->isChecked()) { args = "-remove-tags xml"; } else if (ui->removeCustomTagRadioButton->isChecked()) { QString tag = ui->customTaglineEdit->text().trimmed(); if (!tag.isEmpty()) { args = "-remove-tags "+tag; } } else if (ui->removeJsonOptionRadioButton->isChecked()) { QStringList optList = ui->jsonOptionLineEdit->text().trimmed().split(",",qtSkipEmptyParts); QStringList options; foreach (QString opt, optList) { options << "json="+opt; } if (!options.isEmpty()) { args = "-remove-options "+options.join(","); } } else if (ui->removeXmlOptionRadioButton->isChecked()) { QStringList optList = ui->xmlOptionLineEdit->text().trimmed().split(",",qtSkipEmptyParts); QStringList options; foreach (QString opt, optList) { options << "xml="+opt; } if (!options.isEmpty()) { args = "-remove-options "+options.join(","); } } else if(ui->removeCustomOptionRadioButton->isChecked()) { QString opt = ui->customOptionLineEdit->text().trimmed(); if (opt == ui->customOptionLineEdit->placeholderText()) { if (ui->customOptionLineEdit->cursorPosition() == 0) { opt.clear(); } } if (opt.contains("=")) { args = "-remove-options "+opt; } } ui->argumentsEdit->setPlainText(args); }
5,166
C++
.cpp
118
37.652542
100
0.657382
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,399
golanghighlighter.cpp
visualfc_liteide/liteidex/src/plugins/golangedit/golanghighlighter.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golanghighlighter.cpp // Creator: visualfc <visualfc@gmail.com> #include "golanghighlighter.h" #include "qtc_texteditor/basetextdocumentlayout.h" #include "cplusplus/SimpleLexer.h" #include "cplusplus/Lexer.h" #include <QTextDocument> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end using namespace TextEditor; using namespace CPlusPlus; namespace { /** Enums used to record the state of recognizing function declaration. */ enum FuncState { FUNC_STATE_NORMAL = 0, // For function declaration. FUNC_STATE_FUNC, FUNC_STATE_LPAREN, FUNC_STATE_RPAREN, FUNC_STATE_FUNC_DECL, }; /** Checks the "function()" formats. */ bool maybeIsFunctionCall(const QList<Token> &tks, int idx) { const Token& tk = tks[idx]; if (!tk.isGoBuiltin() && !tk.is(T_IDENTIFIER)) { return false; } int tkCnt = tks.size(); for (int i = idx + 1; i < tkCnt; ++i) { if (tks[i].isComment()) { continue; } return tks[i].is(T_LPAREN); // || tks[i].is(T_LBRACE); } return false; } FuncState updateFuncState(const Token &tk, FuncState funcState) { if (tk.isComment()) { return funcState; } switch(funcState) { case FUNC_STATE_NORMAL: // fall through. case FUNC_STATE_FUNC_DECL: if (tk.is(T_GO_FUNC)) { return FUNC_STATE_FUNC; } else { return FUNC_STATE_NORMAL; } case FUNC_STATE_FUNC: if (tk.is(T_IDENTIFIER) || tk.isGoBuiltin()) { return FUNC_STATE_FUNC_DECL; } else if (tk.is(T_LPAREN)) { return FUNC_STATE_LPAREN; } else { return FUNC_STATE_NORMAL; } case FUNC_STATE_LPAREN: if (tk.is(T_RPAREN)) { return FUNC_STATE_RPAREN; } else { return FUNC_STATE_LPAREN; } case FUNC_STATE_RPAREN: if (tk.is(T_IDENTIFIER) || tk.isGoBuiltin()) { return FUNC_STATE_FUNC_DECL; } else { return FUNC_STATE_NORMAL; } } return funcState; } } //namespace GolangHighlighter::GolangHighlighter(LiteApi::ITextEditor *editor, QTextDocument *document) : TextEditor::SyntaxHighlighter(document) { m_todoList = QString("TODO,BUG,FIXME,NOTE,SECBUG").split(","); m_todoRegexp.setPattern(QString("^(%1)([\\s\\:\\(\\,]|$)").arg(m_todoList.join("|"))); m_gotagList = QString("+build").split(","); TextEditor::SyntaxComment comment; comment.singleLineComment = "//"; comment.multiLineCommentStart = "/*"; comment.multiLineCommentEnd = "*/"; comment.isCommentAfterWhiteSpaces = true; comment.isCommentAfterWhiteSpacesAddSpace = true; setupComment(comment); } GolangHighlighter::~GolangHighlighter() { } void GolangHighlighter::highlightBlock(const QString &text) { int blockNumber = this->currentBlock().blockNumber(); m_currentTodo.clear(); highlightBlockHelper(text); QString old = m_todoInfoMap.value(blockNumber); if (m_currentTodo != old) { if (m_currentTodo.isEmpty()) { m_todoInfoMap.remove(blockNumber); } else { m_todoInfoMap.insert(blockNumber,m_currentTodo); } } } void GolangHighlighter::highlightBlockHelper(const QString &text) { const int previousBlockState_ = previousBlockState(); int lexerState = 0, initialBraceDepth = 0; if (previousBlockState_ != -1) { lexerState = previousBlockState_ & 0xff; initialBraceDepth = previousBlockState_ >> 8; } //fix brace not matcher if (initialBraceDepth < 0) { initialBraceDepth = 0; } int braceDepth = initialBraceDepth; LanguageFeatures features; features.golangEnable = true; SimpleLexer tokenize; tokenize.setLanguageFeatures(features); //hack token convert no ansi code QString tk_text = text; for (int i = 0; i < tk_text.length(); i++) { if (tk_text[i].unicode() > 0x7f) { tk_text[i] = '_'; } } int initialLexerState = lexerState; QList<Token> tokens = tokenize(tk_text, initialLexerState); lexerState = tokenize.state(); // refresh lexer state initialLexerState &= ~0x80; // discard newline expected bit int foldingIndent = initialBraceDepth; if (TextBlockUserData *userData = BaseTextDocumentLayout::testUserData(currentBlock())) { //userData->setFoldingIndent(0); userData->setFoldingStartIncluded(false); userData->setFoldingEndIncluded(false); } if (tokens.isEmpty()) { setCurrentBlockState((braceDepth << 8) | lexerState); BaseTextDocumentLayout::clearParentheses(currentBlock()); if (text.length()) {// the empty line can still contain whitespace if (initialLexerState == T_COMMENT) { highlightLine(text, 0, text.length(), m_creatorFormats[SyntaxHighlighter::Comment]); } else if (initialLexerState == T_DOXY_COMMENT) { highlightLine(text, 0, text.length(), m_creatorFormats[SyntaxHighlighter::Comment]); } else if (initialLexerState == T_RAW_STRING_LITERAL) { highlightLine(text, 0, text.length(), m_creatorFormats[SyntaxHighlighter::String]); } else setFormat(0, text.length(), m_creatorFormats[SyntaxHighlighter::VisualWhitespace]); } //BaseTextDocumentLayout::setFoldingIndent(currentBlock(), foldingIndent); setFoldingIndent(currentBlock(), foldingIndent); return; } const unsigned firstNonSpace = tokens.first().begin(); Parentheses parentheses; parentheses.reserve(20); // assume wizard level ;-) //bool expectPreprocessorKeyword = false; //bool onlyHighlightComments = false; FuncState funcState = FUNC_STATE_NORMAL; for (int i = 0; i < tokens.size(); ++i) { Token &tk = tokens[i]; unsigned previousTokenEnd = 0; if (i != 0) { // mark the whitespaces previousTokenEnd = tokens.at(i - 1).begin() + tokens.at(i - 1).length(); } if (previousTokenEnd != tk.begin()) setFormat(previousTokenEnd, tk.begin() - previousTokenEnd, m_creatorFormats[SyntaxHighlighter::VisualWhitespace]); if (tk.is(T_LPAREN) || tk.is(T_LBRACE) || tk.is(T_LBRACKET)) { const QChar c = text.at(tk.begin()); parentheses.append(Parenthesis(Parenthesis::Opened, c, tk.begin())); if (tk.is(T_LBRACE) || tk.is(T_LPAREN)) { ++braceDepth; // if a folding block opens at the beginning of a line, treat the entire line // as if it were inside the folding block if (tk.begin() == firstNonSpace) { ++foldingIndent; BaseTextDocumentLayout::userData(currentBlock())->setFoldingStartIncluded(true); } } } else if (tk.is(T_RPAREN) || tk.is(T_RBRACE) || tk.is(T_RBRACKET)) { const QChar c = text.at(tk.begin()); parentheses.append(Parenthesis(Parenthesis::Closed, c, tk.begin())); if (tk.is(T_RBRACE) || tk.is(T_RPAREN)) { --braceDepth; if (braceDepth < foldingIndent) { // unless we are at the end of the block, we reduce the folding indent BaseTextDocumentLayout::userData(currentBlock())->setFoldingEndIncluded(true); //if (i == tokens.size()-1 || tokens.at(i+1).is(T_SEMICOLON)) //else // foldingIndent = qMin(braceDepth, foldingIndent); } } } else if (tk.is(T_GO_ELSE)) { --foldingIndent; } /* bool highlightCurrentWordAsPreprocessor = expectPreprocessorKeyword; if (expectPreprocessorKeyword) expectPreprocessorKeyword = false; if (onlyHighlightComments && !tk.isComment()) continue; if (i == 0 && tk.is(T_POUND)) { highlightLine(text, tk.begin(), tk.length(), m_creatorFormats[SyntaxHighlighter::PreprocessorFormat]); expectPreprocessorKeyword = true; } else if (highlightCurrentWordAsPreprocessor && (tk.isKeyword() || tk.is(T_IDENTIFIER)) && isPPKeyword(text.midRef(tk.begin(), tk.length()))) { setFormat(tk.begin(), tk.length(), m_creatorFormats[SyntaxHighlighter::PreprocessorFormat]); const QStringRef ppKeyword = text.midRef(tk.begin(), tk.length()); if (ppKeyword == QLatin1String("error") || ppKeyword == QLatin1String("warning") || ppKeyword == QLatin1String("pragma")) { onlyHighlightComments = true; } } else */ if (tk.is(T_NUMERIC_LITERAL)) { setFormat(tk.begin(), tk.length(), m_creatorFormats[SyntaxHighlighter::Decimal]); } else if (tk.isOperator()) { setFormat(tk.begin(), tk.length(), m_creatorFormats[SyntaxHighlighter::RegionMarker]); } else if (tk.is(T_RAW_STRING_LITERAL)) { const int startPosition = initialLexerState ? previousTokenEnd : tk.begin(); highlightLine(text, startPosition, tk.end() - startPosition, m_creatorFormats[SyntaxHighlighter::String]); // we need to insert a close comment parenthesis, if // - the line starts in a C Comment (initalState != 0) // - the first token of the line is a T_COMMENT (i == 0 && tk.is(T_COMMENT)) // - is not a continuation line (tokens.size() > 1 || !state) if (initialLexerState && i == 0 && (tokens.size() > 1 || !lexerState)) { --braceDepth; // unless we are at the end of the block, we reduce the folding indent if (i == tokens.size()-1) BaseTextDocumentLayout::userData(currentBlock())->setFoldingEndIncluded(true); else foldingIndent = qMin(braceDepth, foldingIndent); const int tokenEnd = tk.begin() + tk.length() - 1; parentheses.append(Parenthesis(Parenthesis::Closed, QLatin1Char('-'), tokenEnd)); // clear the initial state. initialLexerState = 0; } } else if (tk.isStringLiteral() || tk.isCharLiteral()) { highlightLine(text, tk.begin(), tk.length(), m_creatorFormats[SyntaxHighlighter::String]); } else if (tk.isComment()) { const int startPosition = initialLexerState ? previousTokenEnd : tk.begin(); if (tk.is(T_CPP_COMMENT)) { highlightCommentLine(text, startPosition, tk.end() - startPosition); } else { highlightLine(text, startPosition, tk.end() - startPosition, m_creatorFormats[SyntaxHighlighter::Comment]); } // we need to insert a close comment parenthesis, if // - the line starts in a C Comment (initalState != 0) // - the first token of the line is a T_COMMENT (i == 0 && tk.is(T_COMMENT)) // - is not a continuation line (tokens.size() > 1 || !state) if (initialLexerState && i == 0 && (tokens.size() > 1 || !lexerState)) { --braceDepth; // unless we are at the end of the block, we reduce the folding indent if (i == tokens.size()-1) BaseTextDocumentLayout::userData(currentBlock())->setFoldingEndIncluded(true); else foldingIndent = qMin(braceDepth, foldingIndent); const int tokenEnd = tk.begin() + tk.length() - 1; parentheses.append(Parenthesis(Parenthesis::Closed, QLatin1Char('-'), tokenEnd)); // clear the initial state. initialLexerState = 0; } } else if (tk.isGoKeyword()) { setFormat(tk.begin(), tk.length(), m_creatorFormats[SyntaxHighlighter::Keyword]); if (tk.is(T_GO_PACKAGE)) { int n = i+1; if (n < tokens.size() && tokens[n].is(T_IDENTIFIER)) { setContextData("go.package",text.mid(tokens[n].begin(),tokens[n].length())); } } else if (tk.is(T_GO_TYPE)) { int size = tokens.size()-1; int n = i+1; if (n < size && tokens[n].is(T_IDENTIFIER)) { setFormat(tokens[n].begin(), tokens[n].length(), m_creatorFormats[SyntaxHighlighter::DataType]); } } else if (tk.is(T_GO_VAR)) { } } else if (tk.isGoTyped()) { if ((i+1 == tokens.size()) || !tokens[i+1].is(T_DOT)) { setFormat(tk.begin(), tk.length(), m_creatorFormats[SyntaxHighlighter::DataType]); } } else if (tk.isGoBuiltin()) { setFormat(tk.begin(), tk.length(), m_creatorFormats[SyntaxHighlighter::BuiltinFunc]); } else if (tk.isGoPredecl()) { setFormat(tk.begin(), tk.length(), m_creatorFormats[SyntaxHighlighter::Predeclared]); } else if (i == 0 && tokens.size() > 1 && tokens.at(0).begin() == 0 && tk.is(T_IDENTIFIER) && tokens.at(1).is(T_COLON)) { setFormat(tk.begin(), tk.length(), m_creatorFormats[SyntaxHighlighter::DataType]); } else if (maybeIsFunctionCall(tokens, i)) { setFormat(tk.begin(), tk.length(), m_creatorFormats[SyntaxHighlighter::Function]); } else if (tk.is(T_IDENTIFIER)) { // highlightWord(text.midRef(tk.begin(), tk.length()), tk.begin(), tk.length()); } funcState = updateFuncState(tk, funcState); if (FUNC_STATE_FUNC_DECL == funcState) { setFormat(tk.begin(), tk.length(), m_creatorFormats[SyntaxHighlighter::FuncDecl]); } } // mark the trailing white spaces const int lastTokenEnd = tokens.last().end(); if (text.length() > lastTokenEnd) highlightLine(text, lastTokenEnd, text.length() - lastTokenEnd, m_creatorFormats[SyntaxHighlighter::VisualWhitespace]); if (!initialLexerState && lexerState && !tokens.isEmpty()) { const Token &lastToken = tokens.last(); if (lastToken.is(T_COMMENT) || lastToken.is(T_DOXY_COMMENT) || lastToken.is(T_RAW_STRING_LITERAL)) { parentheses.append(Parenthesis(Parenthesis::Opened, QLatin1Char('+'), lastToken.begin())); ++braceDepth; } } BaseTextDocumentLayout::setParentheses(currentBlock(), parentheses); // if the block is ifdefed out, we only store the parentheses, but // do not adjust the brace depth. if (BaseTextDocumentLayout::ifdefedOut(currentBlock())) { braceDepth = initialBraceDepth; foldingIndent = initialBraceDepth; } // qDebug() << text << foldingIndent; //BaseTextDocumentLayout::setFoldingIndent(currentBlock(), foldingIndent); setFoldingIndent(currentBlock(), foldingIndent); // optimization: if only the brace depth changes, we adjust subsequent blocks // to have QSyntaxHighlighter stop the rehighlighting // int currentState = currentBlockState(); // if (currentState != -1) { // int oldState = currentState & 0xff; // int oldBraceDepth = currentState >> 8; // if (oldState == tokenize.state() && oldBraceDepth != braceDepth) { // BaseTextDocumentLayout::FoldValidator foldValidor; // foldValidor.setup(qobject_cast<BaseTextDocumentLayout *>(document()->documentLayout())); // int delta = braceDepth - oldBraceDepth; // QTextBlock block = currentBlock().next(); // while (block.isValid() && block.userState() != -1) { // BaseTextDocumentLayout::changeBraceDepth(block, delta); // BaseTextDocumentLayout::changeFoldingIndent(block, delta); // foldValidor.process(block); // block = block.next(); // } // foldValidor.finalize(); // } // } setCurrentBlockState((braceDepth << 8) | tokenize.state()); } void GolangHighlighter::setFoldingIndent(const QTextBlock &block, int indent) { TextBlockUserData *userData = BaseTextDocumentLayout::userData(block); if (userData->foldingIndent() != indent) { emit foldIndentChanged(block); userData->setFoldingIndent(qMax(0,indent)); } } bool GolangHighlighter::isPPKeyword(const QStringRef &text) const { switch (text.length()) { case 2: if (text.at(0) == QLatin1Char('i') && text.at(1) == QLatin1Char('f')) return true; break; case 4: if (text.at(0) == QLatin1Char('e') && (text == QLatin1String("elif") || text == QLatin1String("else"))) return true; break; case 5: switch (text.at(0).toLatin1()) { case 'i': if (text == QLatin1String("ifdef")) return true; break; case 'u': if (text == QLatin1String("undef")) return true; break; case 'e': if (text == QLatin1String("endif") || text == QLatin1String("error")) return true; break; } break; case 6: switch (text.at(0).toLatin1()) { case 'i': if (text == QLatin1String("ifndef") || text == QLatin1String("import")) return true; break; case 'd': if (text == QLatin1String("define")) return true; break; case 'p': if (text == QLatin1String("pragma")) return true; break; } break; case 7: switch (text.at(0).toLatin1()) { case 'i': if (text == QLatin1String("include")) return true; break; case 'w': if (text == QLatin1String("warning")) return true; break; } break; case 12: if (text.at(0) == QLatin1Char('i') && text == QLatin1String("include_next")) return true; break; default: break; } return false; } void GolangHighlighter::highlightLine(const QString &text, int position, int length, const QTextCharFormat &format) { QTextCharFormat visualSpaceFormat = m_creatorFormats[SyntaxHighlighter::VisualWhitespace]; visualSpaceFormat.setBackground(format.background()); const int end = position + length; int index = position; while (index != end) { const bool isSpace = text.at(index).isSpace(); const int start = index; do { ++index; } while (index != end && text.at(index).isSpace() == isSpace); const int tokenLength = index - start; if (isSpace) setFormat(start, tokenLength, visualSpaceFormat); else if (format.isValid()) setFormat(start, tokenLength, format); } } void GolangHighlighter::highlightCommentLine(const QString &text, int position, int length) { QTextCharFormat format = m_creatorFormats[SyntaxHighlighter::Comment]; QTextCharFormat todoFormat = m_creatorFormats[SyntaxHighlighter::ToDo]; QTextCharFormat visualSpaceFormat = m_creatorFormats[SyntaxHighlighter::VisualWhitespace]; visualSpaceFormat.setBackground(format.background()); const int end = position + length; int index = position; if (text.mid(position).startsWith("//")) { setFormat(position, 2, format); index += 2; } int first = true; while (index != end) { const bool isSpace = text.at(index).isSpace(); const int start = index; do { ++index; } while (index != end && text.at(index).isSpace() == isSpace); const int tokenLength = index - start; if (isSpace) { setFormat(start, tokenLength, visualSpaceFormat); } else if (format.isValid()) { if (first) { first = false; int index = m_todoRegexp.indexIn(text.mid(start,tokenLength)); if (index == 0) { int todoLen = m_todoRegexp.cap(1).length(); setFormat(start,todoLen,todoFormat); if (todoLen < length) { setFormat(start+todoLen,length-todoLen, format); } m_currentTodo = text.mid(start); break; } if (m_gotagList.contains(text.mid(start,tokenLength))) { setFormat(position,length,todoFormat); break; } if (text.mid(start).startsWith("import") && text.startsWith("package")) { setFormat(position,length,todoFormat); break; } if (text.mid(start).startsWith("go:")) { setFormat(position,length,todoFormat); break; } } setFormat(start, tokenLength, format); } } } void GolangHighlighter::highlightWord(QStringRef word, int position, int length) { // try to highlight Qt 'identifiers' like QObject and Q_PROPERTY if (word.length() > 2 && word.at(0) == QLatin1Char('Q')) { if (word.at(1) == QLatin1Char('_') // Q_ || (word.at(1) == QLatin1Char('T') && word.at(2) == QLatin1Char('_'))) { // QT_ for (int i = 1; i < word.length(); ++i) { const QChar &ch = word.at(i); if (!(ch.isUpper() || ch == QLatin1Char('_'))) return; } setFormat(position, length, m_creatorFormats[SyntaxHighlighter::DataType]); } } }
23,223
C++
.cpp
537
33.934823
129
0.589611
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,400
golangtextlexer.cpp
visualfc_liteide/liteidex/src/plugins/golangedit/golangtextlexer.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangtextlexer.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangtextlexer.h" #include "cplusplus/BackwardsScanner.h" #include "cplusplus/SimpleLexer.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end using namespace CPlusPlus; GolangTextLexer::GolangTextLexer(QObject *parent) : LiteApi::ITextLexer(parent) { } bool GolangTextLexer::isInComment(const QTextCursor &cursor) const { return isInCommentHelper(cursor); } bool GolangTextLexer::isInString(const QTextCursor &cursor) const { Token token; if (isInCommentHelper(cursor, &token)) return false; if (token.isStringLiteral() || token.isCharLiteral()) { const unsigned pos = cursor.selectionEnd() - cursor.block().position(); if (pos <= token.end()) return true; } return false; } bool GolangTextLexer::isInEmptyString(const QTextCursor &cursor) const { Token token; if (isInCommentHelper(cursor, &token)) return false; if (token.isStringLiteral() || token.isCharLiteral()) { const unsigned pos = cursor.selectionEnd() - cursor.block().position(); if (pos <= token.end()) { return token.length() == 2; } } return false; } bool GolangTextLexer::isEndOfString(const QTextCursor &cursor) const { Token token; if (isInCommentHelper(cursor, &token)) return false; if (token.isStringLiteral() || token.isCharLiteral()) { const unsigned pos = cursor.selectionEnd() - cursor.block().position(); return (token.end()-pos == 1); } return false; } bool GolangTextLexer::isInStringOrComment(const QTextCursor &cursor) const { Token token; if (isInCommentHelper(cursor, &token)) return true; if (token.isStringLiteral() || token.isCharLiteral()) { const unsigned pos = cursor.selectionEnd() - cursor.block().position(); if (pos <= token.end()) return true; } return false; } bool GolangTextLexer::isLangSupport() const { return true; } bool GolangTextLexer::isInImportHelper(const QTextCursor &cursor) const { const int blockNumber = cursor.block().blockNumber(); QTextBlock block = cursor.document()->firstBlock(); int pos1 = -1; while (block.isValid()) { QString text = block.text().trimmed(); if (text.startsWith("/*")) { block = block.next(); while(block.isValid()) { if (block.text().endsWith("*/")) { break; } block = block.next(); } if (!block.isValid()) { break; } } else if (text.startsWith("var")) { break; } else if (text.startsWith("func")) { break; } else if (text.startsWith("package ")) { pos1 = block.position()+block.length(); } else if (pos1 != -1 && text.startsWith("import (")) { block = block.next(); while(block.isValid()) { QString text = block.text().trimmed(); if (text.startsWith(")")) { break; } //skip if (text.startsWith("/*")) { block = block.next(); while(block.isValid()) { if (block.text().endsWith("*/")) { break; } block = block.next(); } if (!block.isValid()) { break; } } if (text.startsWith("//")) { block = block.next(); continue; } if (block.blockNumber() == blockNumber) { return true; } block = block.next(); } } else if (pos1 != -1 && text.startsWith("import ")) { if (block.blockNumber() == blockNumber) { return true; } } block = block.next(); } return false; } bool GolangTextLexer::isInImport(const QTextCursor &cursor) const { Token token; if (isInCommentHelper(cursor, &token)) return false; if (token.isStringLiteral() || token.isCharLiteral()) { const unsigned pos = cursor.selectionEnd() - cursor.block().position(); QString tk = cursor.block().text().mid(token.begin(),token.length()); if (tk.endsWith('\"') || tk.endsWith('`')) { if (pos > token.begin() && pos < token.end()) { return isInImportHelper(cursor); } } else { if (pos > token.begin()) { return isInImportHelper(cursor); } } } return false; } bool GolangTextLexer::isCanAutoCompleter(const QTextCursor &cursor) const { return !isInStringOrComment(cursor); } int GolangTextLexer::startOfFunctionCall(const QTextCursor &cursor) const { LanguageFeatures features; features.golangEnable = true; BackwardsScanner scanner(features,cursor); int index = scanner.startToken(); forever { const Token &tk = scanner[index - 1]; if (tk.is(T_EOF_SYMBOL)) { break; } else if (tk.is(T_LPAREN)) { return scanner.startPosition() + tk.begin(); } else if (tk.is(T_RPAREN)) { int matchingBrace = scanner.startOfMatchingBrace(index); if (matchingBrace == index) // If no matching brace found return -1; index = matchingBrace; } else { --index; } } return -1; } QString GolangTextLexer::fetchFunctionTip(const QString &func, const QString &kind, const QString &info) { if (kind != "func" || info.startsWith("func()")) { return QString(); } return func+" "+info; } bool GolangTextLexer::fetchFunctionArgs(const QString &str, int &argnr, int &parcount) { LanguageFeatures features; features.golangEnable = true; argnr = 0; parcount = 0; SimpleLexer tokenize; tokenize.setLanguageFeatures(features); QList<Token> tokens = tokenize(str); for (int i = 0; i < tokens.count(); ++i) { const Token &tk = tokens.at(i); if (tk.is(T_LPAREN)) ++parcount; else if (tk.is(T_RPAREN)) --parcount; else if (! parcount && tk.is(T_COMMA)) ++argnr; } return true; } QString GolangTextLexer::stringQuoteList() const { return QString("\"\'`"); } bool GolangTextLexer::hasStringBackslash() const { return true; } bool GolangTextLexer::isInCommentHelper(const QTextCursor &cursor, Token *retToken) const { LanguageFeatures features; features.golangEnable = true; SimpleLexer tokenize; tokenize.setLanguageFeatures(features); const int prevState = BackwardsScanner::previousBlockState(cursor.block()) & 0xFF; const QList<Token> tokens = tokenize(cursor.block().text(), prevState); const unsigned pos = cursor.selectionEnd() - cursor.block().position(); if (tokens.isEmpty() || pos < tokens.first().begin()) return prevState > 0; if (pos >= tokens.last().end()) { const Token tk = tokens.last(); if (tk.is(T_CPP_COMMENT) || tk.is(T_CPP_DOXY_COMMENT)) return true; if (tk.is(T_RAW_STRING_LITERAL) && (cursor.block().userState() & 0xFF) ) { if (retToken) *retToken = tk; return false; } if (tk.isStringLiteral() || tk.isCharLiteral()) { if (retToken) *retToken = tk; return false; } return tk.isComment() && (cursor.block().userState() & 0xFF); } Token tk = tokenAtPosition(tokens, pos); if (retToken) *retToken = tk; return tk.isComment(); } const Token GolangTextLexer::tokenAtPosition(const QList<Token> &tokens, const unsigned pos) const { for (int i = tokens.size() - 1; i >= 0; --i) { const Token tk = tokens.at(i); if (pos >= tk.begin() && pos < tk.end()) return tk; } return Token(); }
9,477
C++
.cpp
280
26.296429
104
0.584061
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,401
goplsfilesearch.cpp
visualfc_liteide/liteidex/src/plugins/golangedit/goplsfilesearch.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2024 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: goplsfilesearch.cpp // Creator: visualfc <visualfc@gmail.com> #include "goplsfilesearch.h" #include "liteeditorapi/liteeditorapi.h" #include "liteenvapi/liteenvapi.h" #include "fileutil/fileutil.h" #include <QTextBlock> #include <qalgorithms.h> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end #include <QDebug> static QByteArray trimmedRight(const QByteArray &d) { if (d.size() == 0) { return d; } const char *s = d.data(); int end = d.size() - 1; while (end && isspace(uchar(s[end]))) // skip white space from end end--; return d.left(end+1); } GoplsFileSearch::GoplsFileSearch(LiteApi::IApplication *app, QObject *parent) : LiteApi::IFileSearch(parent), m_liteApp(app) { m_process = new ProcessEx(this); m_replaceMode = false; m_readOnly = true; m_bParserHead = true; // connect(m_process,SIGNAL(started()),this,SLOT(findUsagesStarted())); connect(m_process,SIGNAL(extOutput(QByteArray,bool)),this,SLOT(findUsagesOutput(QByteArray,bool))); connect(m_process,SIGNAL(extFinish(bool,int,QString)),this,SLOT(findUsagesFinish(bool,int,QString))); } GoplsFileSearch::~GoplsFileSearch() { } QString GoplsFileSearch::mimeType() const { return "find/goplsfileserch"; } QWidget *GoplsFileSearch::widget() const { return 0; } void GoplsFileSearch::start() { } void GoplsFileSearch::cancel() { } void GoplsFileSearch::activate() { } QString GoplsFileSearch::searchText() const { return m_searchText; } bool GoplsFileSearch::replaceMode() const { return m_replaceMode; } void GoplsFileSearch::setSearchInfo(const QString &/*text*/, const QString &/*filter*/, const QString &/*path*/) { } void GoplsFileSearch::findUsages(LiteApi::ITextEditor *editor, QTextCursor cursor, const QString &command, const QStringList &opts, bool replace) { if (!m_process->isStop()) { m_process->stopAndWait(100,2000); } bool moveLeft = false; int selectStart = 0; m_searchText = LiteApi::wordUnderCursor(cursor,&moveLeft,&selectStart); if (m_searchText.isEmpty() || m_searchText.contains(" ")) { return; } m_liteApp->editorManager()->saveAllEditors(false); //int offset = moveLeft ? editor->utf8Position(true)-1: editor->utf8Position(true); int offset = editor->utf8Position(true,selectStart); LiteApi::IFileSearchManager *manager = LiteApi::getFileSearchManager(m_liteApp); if (!manager) { return; } this->m_replaceMode = replace; manager->setCurrentSearch(this); m_results.clear(); QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); FileUtil::lookupGoBin("gopls",m_liteApp,env,false); QString gopls = FileUtil::lookupGoBin("gopls",m_liteApp,env,true); if (gopls.isEmpty()) { gopls = FileUtil::lookPath("dlv",env,false); } if (gopls.isEmpty()) { m_liteApp->appendLog("GolangEdit","gopls was not found on system PATH (hint: is gopls installed?)",true); return; } QFileInfo info(editor->filePath()); m_process->setEnvironment(LiteApi::getCustomGoEnvironment(m_liteApp,editor).toStringList()); m_process->setWorkingDirectory(info.path()); QStringList args; args << command; if (!opts.isEmpty()) { args << opts; } args << QString("\"%1:#%2\"").arg(info.fileName()).arg(offset); emit findStarted(); m_process->startEx(gopls,args); } void GoplsFileSearch::findUsagesStarted() { } void GoplsFileSearch::findUsagesOutput(QByteArray data, bool bStdErr) { if (bStdErr) { QString info = QString::fromUtf8(data).trimmed(); emit findError(info); m_liteApp->appendLog("find usage error",info,true); return; } QRegExp reg(":(\\d+):(\\d+)-(\\d*)"); foreach (QByteArray line, data.split('\n')) { QString info = QString::fromUtf8(line).trimmed(); int pos = reg.lastIndexIn(info); if (pos >= 0) { gopls_resinfo res; res.fileName = info.left(pos); res.line = reg.cap(1).toInt(); res.column = reg.cap(2).toInt(); res.columnEnd = reg.cap(3).toInt(); m_results.append(res); } } } struct resultComp { bool operator()(const gopls_resinfo &a, const gopls_resinfo &b) { if (a.fileName == b.fileName) { if (a.line == b.line) { return a.column < b.column; } return a.line < b.line; } return a.fileName < b.fileName; } }; void GoplsFileSearch::findUsagesFinish(bool b, int, QString) { if (!m_results.isEmpty()) { qSort(m_results.begin(),m_results.end(),resultComp()); } QFile file; int lastLine = 0; QString lastLineText; foreach(gopls_resinfo info, m_results) { QString fileName = info.fileName; int fileLine = info.line; int fileCol = info.column; int fileCol2 = info.columnEnd; if (file.fileName() != fileName) { file.close(); file.setFileName(fileName); } if (!file.isOpen()) { file.open(QFile::ReadOnly); lastLine = 0; } if (file.isOpen()) { if (fileLine != lastLine) { while(!file.atEnd()) { QByteArray line = file.readLine(); lastLine++; if (fileLine == lastLine) { lastLineText = QString::fromUtf8(trimmedRight(line)); if (fileCol > 0) { fileCol = QString::fromUtf8(line.left(fileCol)).length(); } break; } } } else { QByteArray line = lastLineText.toUtf8(); if (fileCol > 0) { fileCol = QString::fromUtf8(line.left(fileCol)).length(); } } int length = m_searchText.length(); if (fileCol2 > fileCol) { length = fileCol2-fileCol; } emit findResult(LiteApi::FileSearchResult(fileName,lastLineText,fileLine,fileCol-1,length)); } } m_results.clear(); emit findFinished(b); }
7,526
C++
.cpp
222
27.734234
145
0.621681
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
21,402
golangedit.cpp
visualfc_liteide/liteidex/src/plugins/golangedit/golangedit.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangedit.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangedit.h" #include "golangtextlexer.h" #include "golangedit_global.h" #include "qtc_editutil/uncommentselection.h" #include "litebuildapi/litebuildapi.h" #include "golangdocapi/golangdocapi.h" #include "fileutil/fileutil.h" #include "processex/processex.h" #include "goaddtagsdialog.h" #include "goremovetagsdialog.h" #include "quickopenapi/quickopenapi.h" #include <QMenu> #include <QToolBar> #include <QAction> #include <QTextStream> #include <QApplication> #include <QToolTip> #include <QRegExp> #include <QToolButton> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end //type gotools.s struct{} //type command.Command struct{Run func(cmd *Command, args []string);Short string;Long string;Flag flag.FlagSet;CustomFlags bool} static QString formatInfo(const QString &info) { if (!info.startsWith("type")) { return info; } QRegExp re("([\\w\\s\\.]+)\\{(.+)\\}"); if (re.indexIn(info) == 0) { if (re.matchedLength() == info.length()) { QString str = re.cap(1)+" {\n"; foreach (QString item, re.cap(2).split(";",qtSkipEmptyParts)) { str += "\t"+item.trimmed()+"\n"; } str += "}"; return str; } } return info; } static QString getGocode(LiteApi::IApplication *app) { #ifdef Q_OS_WIN return app->toolPath()+"/gocode.exe"; #else return app->toolPath()+"/gocode"; #endif } GolangEdit::GolangEdit(LiteApi::IApplication *app, QObject *parent) : QObject(parent), m_liteApp(app), m_gorootSourceReadOnly(false), m_useGoModule(false) { LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(this,"GolangEdit"); m_viewGodocAct = new QAction(tr("View import package use godoc"),this); actionContext->regAction(m_viewGodocAct,"ViewGodoc",""); m_findInfoAct = new QAction(tr("View Expression Information"),this); actionContext->regAction(m_findInfoAct,"ViewInfo","CTRL+SHIFT+I;F1"); m_jumpDeclAct = new QAction(tr("Jump to Declaration"),this); actionContext->regAction(m_jumpDeclAct,"JumpToDeclaration","CTRL+SHIFT+J;F2"); m_findUseAct = new QAction(tr("Find Usages"),this); actionContext->regAction(m_findUseAct,"FindUsages","CTRL+SHIFT+U"); m_renameSymbolAct = new QAction(tr("Rename Symbol Under Cursor"),this); actionContext->regAction(m_renameSymbolAct,"RenameSymbol","CTRL+SHIFT+R"); m_findAllUseSkipGorootAct = new QAction(QString("%1 (Module/GOPATH)").arg(tr("Find Usages")),this); actionContext->regAction(m_findAllUseSkipGorootAct,"FindAllUsagesSkipGOROOT","CTRL+ALT+U"); m_findAllUseSkipTestsAct = new QAction(QString("%1 (Module/GOPATH) skip tests").arg(tr("Find Usages")),this); actionContext->regAction(m_findAllUseSkipTestsAct,"FindAllUsagesSkipTests",""); m_findAllUseWithGorootAct = new QAction(QString(tr("%1 (Module/GOPATH) with GOROOT")).arg(tr("Find Usages")),this); actionContext->regAction(m_findAllUseWithGorootAct,"FindAllUsagesWithGOROOT",""); m_renameAllSymbolWithGorootAct = new QAction(QString(tr("%1 (Module/GOPATH) with GOROOT")).arg(tr("Rename Symbol Under Cursor")),this); actionContext->regAction(m_renameAllSymbolWithGorootAct,"RenameAllSymbolWithGOROOT",""); m_renameAllSymbolSkipGorootAct = new QAction(QString("%1 (Module/GOPATH)").arg(tr("Rename Symbol Under Cursor")),this); actionContext->regAction(m_renameAllSymbolSkipGorootAct,"RenameAllSymbolSkipGOROOT",""); m_fileSearch = new GolangFileSearch(app,m_liteApp); m_goplsSearch = new GoplsFileSearch(app,m_liteApp); LiteApi::IFileSearchManager *manager = LiteApi::getFileSearchManager(app); if (manager) { manager->addFileSearch(m_fileSearch); manager->addFileSearch(m_goplsSearch); } m_envManager = LiteApi::getEnvManager(m_liteApp); if (m_envManager) { connect(m_envManager,SIGNAL(currentEnvChanged(LiteApi::IEnv*)),this,SLOT(currentEnvChanged(LiteApi::IEnv*))); } m_findDefProcess = new Process(this); m_findInfoProcess = new Process(this); m_findLinkProcess = new Process(this); m_sourceQueryProcess = new Process(this); m_enableMouseUnderInfo = true; m_enableMouseNavigation = true; m_useGocodeInfo = true; connect(m_liteApp->editorManager(),SIGNAL(editorCreated(LiteApi::IEditor*)),this,SLOT(editorCreated(LiteApi::IEditor*))); connect(m_liteApp->editorManager(),SIGNAL(currentEditorChanged(LiteApi::IEditor*)),this,SLOT(currentEditorChanged(LiteApi::IEditor*))); connect(m_viewGodocAct,SIGNAL(triggered()),this,SLOT(editorViewGodoc())); connect(m_findInfoAct,SIGNAL(triggered()),this,SLOT(editorFindInfo())); connect(m_jumpDeclAct,SIGNAL(triggered()),this,SLOT(editorJumpToDecl())); connect(m_findUseAct,SIGNAL(triggered()),this,SLOT(editorFindUsages())); connect(m_renameSymbolAct,SIGNAL(triggered()),this,SLOT(editorRenameSymbol())); connect(m_findAllUseWithGorootAct,SIGNAL(triggered()),this,SLOT(editorFindUsagesGlobal())); connect(m_findAllUseSkipGorootAct,SIGNAL(triggered()),this,SLOT(editorFindUsagesSkipGoroot())); connect(m_findAllUseSkipTestsAct,SIGNAL(triggered()),this,SLOT(editorFindUsagesSkipTests())); connect(m_renameAllSymbolWithGorootAct,SIGNAL(triggered()),this,SLOT(editorRenameSymbolGlobal())); connect(m_renameAllSymbolSkipGorootAct,SIGNAL(triggered()),this,SLOT(editorRenameSymbolSkipGoroot())); connect(m_findDefProcess,SIGNAL(started()),this,SLOT(findDefStarted())); //connect(m_findDefProcess,SIGNAL(extOutput(QByteArray,bool)),this,SLOT(findDefOutput(QByteArray,bool))); connect(m_findDefProcess,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(findDefFinish(int,QProcess::ExitStatus))); connect(m_findInfoProcess,SIGNAL(started()),this,SLOT(findInfoStarted())); //connect(m_findInfoProcess,SIGNAL(extOutput(QByteArray,bool)),this,SLOT(findInfoOutput(QByteArray,bool))); connect(m_findInfoProcess,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(findInfoFinish(int,QProcess::ExitStatus))); connect(m_findLinkProcess,SIGNAL(started()),this,SLOT(findLinkStarted())); connect(m_findLinkProcess,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(findLinkFinish(int,QProcess::ExitStatus))); //connect(&m_findInfoGopher,SIGNAL(extOutput(QByteArray,bool)),this,SLOT(findInfoGopherOutput(QByteArray,bool))); if (m_fileSearch) { connect(m_fileSearch,SIGNAL(searchTextChanged(QString)),this,SLOT(searchTextChanged(QString))); } connect(m_sourceQueryProcess,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(sourceQueryFinished(int,QProcess::ExitStatus))); connect(m_sourceQueryProcess,SIGNAL(error(QProcess::ProcessError)),this,SLOT(sourcequeryError(QProcess::ProcessError))); connect(m_liteApp->optionManager(),SIGNAL(applyOption(QString)),this,SLOT(applyOption(QString))); m_sourceQueryOutput = new TextOutput(m_liteApp,true); m_sourceQueryOutput->setLineWrap(false); m_stopSourceQueryAct = new QAction(tr("Stop"),this); m_stopSourceQueryAct->setIcon(QIcon("icon:litebuild/images/stopaction.png")); connect(m_sourceQueryOutput,SIGNAL(dbclickEvent(QTextCursor)),this,SLOT(dbclickSourceQueryOutput(QTextCursor))); m_sourceQueryOutputAct = m_liteApp->toolWindowManager()->addToolWindow(Qt::BottomDockWidgetArea,m_sourceQueryOutput,"GoSourceQuery",tr("Go Source Query"),true, QList<QAction*>() << m_stopSourceQueryAct); connect(m_sourceQueryProcess,SIGNAL(stateChanged(QProcess::ProcessState)),this,SLOT(sourceQueryStateChanged(QProcess::ProcessState))); connect(m_stopSourceQueryAct,SIGNAL(triggered()),this,SLOT(stopSourceQueryProcess())); m_sourceWhatAct = new QAction(tr("SourceQuery What"),this); actionContext->regAction(m_sourceWhatAct,"SourceQueryWhat","Ctrl+Shift+H"); connect(m_sourceWhatAct,SIGNAL(triggered()),this,SLOT(sourceWhat())); m_sourceCalleesAct = new QAction(tr("Callees"),this); actionContext->regAction(m_sourceCalleesAct,"SourceQueryCallees",""); connect(m_sourceCalleesAct,SIGNAL(triggered()),this,SLOT(sourceCallees())); m_sourceCallersAct = new QAction(tr("Callers"),this); actionContext->regAction(m_sourceCallersAct,"SourceQueryCallers",""); connect(m_sourceCallersAct,SIGNAL(triggered()),this,SLOT(sourceCallers())); m_sourceCallstackAct = new QAction(tr("Callstack"),this); actionContext->regAction(m_sourceCallstackAct,"SourceQueryCallstack",""); connect(m_sourceCallstackAct,SIGNAL(triggered()),this,SLOT(sourceCallstack())); m_sourceDefinitionAct = new QAction(tr("Definition"),this); actionContext->regAction(m_sourceDefinitionAct,"SourceQueryDefinition",""); connect(m_sourceDefinitionAct,SIGNAL(triggered()),this,SLOT(sourceDefinition())); m_sourceDescribeAct = new QAction(tr("Describe"),this); actionContext->regAction(m_sourceDescribeAct,"SourceQueryDescribe",""); connect(m_sourceDescribeAct,SIGNAL(triggered()),this,SLOT(sourceDescribe())); m_sourceFreevarsAct = new QAction(tr("Freevars"),this); actionContext->regAction(m_sourceFreevarsAct,"SourceQueryFreevars",""); connect(m_sourceFreevarsAct,SIGNAL(triggered()),this,SLOT(sourceFreevars())); m_sourceImplementsAct = new QAction(tr("Implements"),this); actionContext->regAction(m_sourceImplementsAct,"SourceQueryImplements",""); connect(m_sourceImplementsAct,SIGNAL(triggered()),this,SLOT(sourceImplements())); m_sourceImplementsGopathAct = new QAction(tr("Implements(GOPATH)"),this); actionContext->regAction(m_sourceImplementsGopathAct,"SourceQueryImplementsGopath",""); connect(m_sourceImplementsGopathAct,SIGNAL(triggered()),this,SLOT(sourceImplementsGopath())); m_sourcePeersAct = new QAction(tr("Peers"),this); actionContext->regAction(m_sourcePeersAct,"SourceQueryPeers",""); connect(m_sourcePeersAct,SIGNAL(triggered()),this,SLOT(sourcePeers())); m_sourceReferrersAct = new QAction(tr("Referrers"),this); actionContext->regAction(m_sourceReferrersAct,"SourceQueryReferrers",""); connect(m_sourceReferrersAct,SIGNAL(triggered()),this,SLOT(sourceReferrers())); m_sourcePointstoAct = new QAction(tr("Pointsto"),this); actionContext->regAction(m_sourcePointstoAct,"SourceQueryPointsto",""); connect(m_sourcePointstoAct,SIGNAL(triggered()),this,SLOT(sourcePointsto())); m_sourceWhicherrs = new QAction(tr("Whicherrs"),this); actionContext->regAction(m_sourceWhicherrs,"SourceQueryWhicherrs",""); connect(m_sourceWhicherrs,SIGNAL(triggered()),this,SLOT(sourceWhicherrs())); m_goAddTagsAct = new QAction(tr("Add Tags To Struct Field"),this); actionContext->regAction(m_goAddTagsAct,"GoAddTags",""); connect(m_goAddTagsAct,SIGNAL(triggered()),this,SLOT(goAddTags())); m_goRemoveTagAct = new QAction(tr("Remove Tags From Struct Field"),this); actionContext->regAction(m_goRemoveTagAct,"GoRemoveTags",""); connect(m_goRemoveTagAct,SIGNAL(triggered()),this,SLOT(goRemoveTags())); m_goplsAllReferencesAct = new QAction(tr("Find All References (gopls)"),this); actionContext->regAction(m_goplsAllReferencesAct,"GoplsFindAllReferences",""); connect(m_goplsAllReferencesAct,SIGNAL(triggered()),this,SLOT(goplsFindAllReferences())); m_goplsAllImplementationsAct = new QAction(tr("Find All Implementations (gopls)"),this); actionContext->regAction(m_goplsAllImplementationsAct,"GoplsFindAllImplementations",""); connect(m_goplsAllImplementationsAct,SIGNAL(triggered()),this,SLOT(goplsFindAllImplementations())); m_addTagsDlg = 0; m_removeTagsDlg = 0; this->applyOption(OPTION_GOLANGEDIT); currentEnvChanged(NULL); } GolangEdit::~GolangEdit() { if (m_sourceQueryOutput) { delete m_sourceQueryOutput; } } //bool GolangEdit::eventFilter(QObject *obj, QEvent *event) //{ // if (obj == m_plainTextEdit && event->type() == QEvent::ShortcutOverride) { // QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event); //// int key = keyEvent->key(); //// Qt::KeyboardModifiers modifiers = keyEvent->modifiers(); //// if (modifiers & Qt::ShiftModifier) { //// key += Qt::SHIFT; //// } //// if (modifiers & Qt::ControlModifier) { //// key += Qt::CTRL; //// } //// if (modifiers & Qt::AltModifier) { //// key += Qt::ALT; //// } //// QKeySequence ks(key); //// if (m_findInfoAct->shortcuts().contains(ks)) { //// event->accept(); //// } // if ((mouseEvent->modifiers() & Qt::ControlModifier)) { // //findEditorCursorInfo(m_editor,this->textCursorForPos(QCursor::pos())); // return true; // } // } // return QObject::eventFilter(obj,event); //} QTextCursor GolangEdit::textCursorForPos(const QPoint &globalPos) { QPoint pos = m_plainTextEdit->viewport()->mapFromGlobal(globalPos); QTextCursor cur = m_plainTextEdit->textCursor(); QRect rc = m_plainTextEdit->cursorRect(cur); if (rc.contains(pos)) { return cur; } return m_plainTextEdit->cursorForPosition(pos); } void GolangEdit::currentEnvChanged(LiteApi::IEnv *) { QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); if (!env.contains("GO111MODULE")) { return; } QString value = env.value("GO111MODULE"); bool b = value.toLower() != "off"; if (b == m_useGoModule) { return; } m_useGoModule = b; if (!m_useGoModule) { m_findAllUseSkipGorootAct->setText(QString("%1 (Module/GOPATH)").arg(tr("Find Usages"))); m_findAllUseSkipTestsAct->setText(QString("%1 (Module/GOPATH) skip tests").arg(tr("Find Usages"))); m_findAllUseWithGorootAct->setText(QString(tr("%1 (Module/GOPATH) with GOROOT")).arg(tr("Find Usages"))); m_renameAllSymbolWithGorootAct->setText(QString(tr("%1 (Module/GOPATH) with GOROOT")).arg(tr("Rename Symbol Under Cursor"))); m_renameAllSymbolSkipGorootAct->setText(QString("%1 (Module/GOPATH)").arg(tr("Rename Symbol Under Cursor"))); } else { m_findAllUseSkipGorootAct->setText(QString("%1 (Module)").arg(tr("Find Usages"))); m_findAllUseSkipTestsAct->setText(QString("%1 (Module) skip tests").arg(tr("Find Usages"))); m_findAllUseWithGorootAct->setText(QString(tr("%1 (Module) and GOROOT")).arg(tr("Find Usages"))); m_renameAllSymbolWithGorootAct->setText(QString(tr("%1 (Module) and GOROOT")).arg(tr("Rename Symbol Under Cursor"))); m_renameAllSymbolSkipGorootAct->setText(QString("%1 (Module)").arg(tr("Rename Symbol Under Cursor"))); } m_renameAllSymbolWithGorootAct->setVisible(!m_useGoModule); } void GolangEdit::applyOption(const QString &option) { if (option != OPTION_GOLANGEDIT) { return; } m_enableMouseUnderInfo = m_liteApp->settings()->value(GOLANGEDIT_MOUSEINFO,true).toBool(); m_enableMouseNavigation = m_liteApp->settings()->value(GOLANGEDIT_MOUSENAVIGATIOIN,true).toBool(); bool gorootSourceReadOnly = m_liteApp->settings()->value(GOLANGEDIT_GOROOTSOURCEREADONLY,false).toBool(); if (gorootSourceReadOnly != m_gorootSourceReadOnly) { m_gorootSourceReadOnly = gorootSourceReadOnly; QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); QString goroot = env.value("GOROOT"); if (!goroot.isEmpty()) { foreach (LiteApi::IEditor *editor, m_liteApp->editorManager()->editorList()) { if (!editor) { continue; } QString filePath = editor->filePath(); if (filePath.isEmpty()) { continue; } if (QDir::fromNativeSeparators(filePath).startsWith(QDir::fromNativeSeparators(goroot))) { editor->setReadOnly(m_gorootSourceReadOnly); } } } } } void GolangEdit::editorCreated(LiteApi::IEditor *editor) { if (!editor) { return; } if (m_gorootSourceReadOnly) { QString path = editor->filePath(); if ( !path.isEmpty()) { QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); QString goroot = env.value("GOROOT"); if (!goroot.isEmpty()) { if (QDir::fromNativeSeparators(path).startsWith(QDir::fromNativeSeparators(goroot))) { editor->setReadOnly(true); } } } } if (editor->mimeType() != "text/x-gosrc") { return; } //editor->widget()->addAction(m_commentAct); QMenu *menu = LiteApi::getEditMenu(editor); if (menu) { menu->addSeparator(); menu->addAction(m_viewGodocAct); menu->addSeparator(); menu->addAction(m_findInfoAct); menu->addAction(m_jumpDeclAct); menu->addAction(m_findUseAct); menu->addAction(m_findAllUseSkipGorootAct); menu->addAction(m_findAllUseSkipTestsAct); menu->addAction(m_findAllUseWithGorootAct); menu->addSeparator(); QMenu *sub = menu->addMenu(tr("Refactor")); sub->addAction(m_renameSymbolAct); sub->addAction(m_renameAllSymbolSkipGorootAct); sub->addAction(m_renameAllSymbolWithGorootAct); menu->addSeparator(); menu->addAction(m_goplsAllReferencesAct); menu->addAction(m_goplsAllImplementationsAct); menu->addSeparator(); menu->addAction(m_sourceWhatAct); sub = menu->addMenu(tr("SourceQuery")); sub->addAction(m_sourceCalleesAct); sub->addAction(m_sourceCallersAct); sub->addAction(m_sourceCallstackAct); sub->addAction(m_sourceDefinitionAct); sub->addAction(m_sourceDescribeAct); sub->addAction(m_sourceFreevarsAct); sub->addAction(m_sourceImplementsAct); sub->addAction(m_sourceImplementsGopathAct); sub->addAction(m_sourcePeersAct); sub->addAction(m_sourcePointstoAct); sub->addAction(m_sourceReferrersAct); sub->addAction(m_sourceWhicherrs); menu->addSeparator(); menu->addAction(m_goAddTagsAct); menu->addAction(m_goRemoveTagAct); } menu = LiteApi::getContextMenu(editor); if (menu) { menu->addSeparator(); menu->addAction(m_viewGodocAct); menu->addSeparator(); menu->addAction(m_findInfoAct); menu->addAction(m_jumpDeclAct); menu->addAction(m_findUseAct); menu->addAction(m_findAllUseSkipGorootAct); menu->addAction(m_findAllUseSkipTestsAct); menu->addAction(m_findAllUseWithGorootAct); menu->addSeparator(); QMenu *sub = menu->addMenu(tr("Refactor")); sub->addAction(m_renameSymbolAct); sub->addAction(m_renameAllSymbolSkipGorootAct); sub->addAction(m_renameAllSymbolWithGorootAct); connect(menu,SIGNAL(aboutToShow()),this,SLOT(aboutToShowContextMenu())); menu->addSeparator(); menu->addAction(m_goplsAllReferencesAct); menu->addAction(m_goplsAllImplementationsAct); menu->addSeparator(); menu->addAction(m_sourceWhatAct); sub = menu->addMenu(tr("SourceQuery")); sub->addAction(m_sourceCalleesAct); sub->addAction(m_sourceCallersAct); sub->addAction(m_sourceCallstackAct); sub->addAction(m_sourceDefinitionAct); sub->addAction(m_sourceDescribeAct); sub->addAction(m_sourceFreevarsAct); sub->addAction(m_sourceImplementsAct); sub->addAction(m_sourceImplementsGopathAct); sub->addAction(m_sourcePeersAct); sub->addAction(m_sourcePointstoAct); sub->addAction(m_sourceReferrersAct); sub->addAction(m_sourceWhicherrs); menu->addSeparator(); menu->addAction(m_goAddTagsAct); menu->addAction(m_goRemoveTagAct); } m_editor = LiteApi::getLiteEditor(editor); if (m_editor) { m_editor->setTextLexer(new GolangTextLexer()); connect(m_editor,SIGNAL(updateLink(QTextCursor,QPoint,bool)),this,SLOT(updateLink(QTextCursor,QPoint,bool))); //new go src for unix line end if (m_editor->document()->isEmpty()) { m_editor->setLineEndUnix(true); } } QToolBar *toolBar = LiteApi::getEditToolBar(editor); if (toolBar) { toolBar->addSeparator(); //toolBar->addAction(m_jumpDeclAct); QToolButton *btn = new QToolButton(toolBar); btn->setDefaultAction(m_jumpDeclAct); btn->setIcon(QIcon("icon:liteeditor/images/goto.png")); toolBar->addWidget(btn); } } void GolangEdit::currentEditorChanged(LiteApi::IEditor *editor) { if (!editor || editor->mimeType() != "text/x-gosrc") { return; } m_editor = LiteApi::getLiteEditor(editor); m_plainTextEdit = LiteApi::getPlainTextEdit(editor); } QString parserImport(const QString &text,int &start, int &end) { QString sep = "\""; start = text.indexOf(sep); end = -1; if (start < 0) { sep = "`"; start = text.indexOf(sep); } if (start >= 0) { end = text.indexOf(sep,start+1); if (end > 0) { return text.mid(start+1,end-start-1); } } return QString(); } QString parser_import(const QString &text) { int start = -1; int end = -1; return parserImport(text,start,end); } void GolangEdit::updateLink(const QTextCursor &cursor, const QPoint &pos, bool nav) { if (nav) { if (!m_enableMouseNavigation) { return; } } else { if (!m_enableMouseUnderInfo) { return; } } QString text = cursor.selectedText(); //hack if (text == "(") { text.clear(); } if (text.isEmpty()) { m_lastLink.clear(); m_editor->clearLink(); return; } int linkStart = cursor.selectionStart(); int linkEnd = cursor.selectionEnd(); LiteApi::ITextLexer *textLexer = LiteApi::getTextLexer(m_editor); if (textLexer && textLexer->isInImport(cursor)) { int start = -1; int end = -1; QTextBlock block = cursor.block(); QString pkg = parserImport(block.text(),start,end); if (!pkg.isEmpty()) { int pkgStart = block.position()+start; int pkgEnd = block.position()+end; if (pkgStart <= linkStart && pkgEnd >= end) { linkStart = pkgStart; linkEnd = pkgEnd; } } } if (m_lastLink.linkTextStart == linkStart && m_lastLink.linkTextEnd == linkEnd) { if (m_lastLink.hasValidTarget() && m_lastLink.text == text) { m_lastLink.cursorPos = pos; m_lastLink.showTip = true; m_lastLink.showNav = nav; m_editor->showLink(m_lastLink); return; } } if (!m_findLinkProcess->isStop()) { m_findLinkProcess->stopAndWait(100,200); } m_lastLink.clear(); m_lastLink.showTip = true; m_lastLink.showNav = nav; m_lastLink.linkTextStart = linkStart; m_lastLink.linkTextEnd = linkEnd; m_lastLink.cursorPos = pos; m_lastLink.text = text; m_srcData = m_editor->utf8Data(); int offset = m_editor->utf8Position(false,cursor.selectionStart()); QFileInfo info(m_editor->filePath()); QString cmd; QStringList args; if (m_useGocodeInfo) { cmd = getGocode(m_liteApp); args << "liteide_typesinfo" << info.fileName() << QString("%1").arg(offset) << selectionUnderCursor(cursor); } else { cmd = LiteApi::getGotools(m_liteApp); args << "types"; QString tags = LiteApi::getGoBuildFlagsArgument(m_liteApp,m_editor,"-tags"); if (!tags.isEmpty()) { args << "-tags"; args << tags; } args << "-b"; args << "-pos"; args << QString("\"%1:%2\"").arg(info.fileName()).arg(offset); args << "-stdin"; args << "-info"; args << "-def"; args << "-doc"; args << "."; } m_findLinkProcess->setEnvironment(LiteApi::getCustomGoEnvironment(m_liteApp,m_editor).toStringList()); m_findLinkProcess->setWorkingDirectory(info.path()); m_findLinkProcess->startEx(cmd,args); } void GolangEdit::aboutToShowContextMenu() { LiteApi::ITextLexer *textLexer = LiteApi::getTextLexer(m_editor); if (!textLexer) { return; } QTextCursor cursor = m_editor->textCursor(); bool b = textLexer->isInImport(cursor); m_viewGodocAct->setVisible(b); } void GolangEdit::editorViewGodoc() { LiteApi::ITextLexer *textLexer = LiteApi::getTextLexer(m_editor); if (!textLexer) { return; } QTextCursor cursor = m_editor->textCursor(); bool b = textLexer->isInImport(cursor); if (!b) { return; } QString pkg = parser_import(cursor.block().text()); if (pkg.isEmpty()) { return; } QString pkgPath = pkg; QString addin; //check mod and vendor pkg QString gotools = LiteApi::getGotools(m_liteApp); if (!gotools.isEmpty()) { QProcess process(this); QFileInfo info(m_editor->filePath()); process.setEnvironment(LiteApi::getCustomGoEnvironment(m_liteApp,m_editor).toStringList()); process.setWorkingDirectory(info.path()); QStringList args; args << "pkgcheck" << "-pkg" << pkg; process.start(gotools,args); if (!process.waitForFinished(3000)) { process.kill(); } QByteArray ar = process.readAllStandardOutput(); QString pkgs = QString::fromUtf8(ar).trimmed(); if (!pkgs.isEmpty()) { QStringList pkgInfo = pkgs.split(","); //vendor_path,vendor //mod_fullpath,mod //pkg_path,pkg if (pkgInfo.size() == 2 && !pkgInfo[0].isEmpty()) { pkgPath = pkgInfo[0]; } if (pkgInfo[1] == "vendor" || pkgInfo[1] == "mod") { addin = pkg; } } } LiteApi::IGolangDoc *doc = LiteApi::getGolangDoc(m_liteApp); if (!doc) { return; } QUrl url; url.setScheme("pdoc"); url.setPath(pkgPath); doc->openUrl(url,addin); doc->activeBrowser(); } void GolangEdit::editorJumpToDecl() { bool moveLeft = false; int selectStart = 0; QString text = LiteApi::wordUnderCursor(m_plainTextEdit->textCursor(),&moveLeft,&selectStart); if (text.isEmpty() || text.contains(" ")) { return; } if (!m_findDefProcess->isStop()) { m_findDefProcess->stopAndWait(100,200); } m_lastCursor = m_plainTextEdit->textCursor(); int offset = m_editor->utf8Position(false,selectStart); m_srcData = m_editor->utf8Data(); QFileInfo info(m_editor->filePath()); QString cmd; QStringList args; if (m_useGocodeInfo) { cmd = getGocode(m_liteApp); args << "liteide_typesinfo" << info.fileName() << QString("%1").arg(offset) << selectionUnderCursor(m_lastCursor,moveLeft); } else { cmd = LiteApi::getGotools(m_liteApp); args << "types"; QString tags = LiteApi::getGoBuildFlagsArgument(m_liteApp,m_editor,"-tags"); if (!tags.isEmpty()) { args << "-tags"; args << tags; } args << "-pos"; args << QString("\"%1:%2\"").arg(info.fileName()).arg(offset); args << "-stdin"; args << "-def"; args << "."; } m_findDefProcess->setEnvironment(LiteApi::getCustomGoEnvironment(m_liteApp,m_editor).toStringList()); m_findDefProcess->setWorkingDirectory(info.path()); m_findDefProcess->startEx(cmd,args); } void GolangEdit::editorFindUsages() { QTextCursor cursor = m_plainTextEdit->textCursor(); m_fileSearch->findUsages(m_editor,cursor,false,false,false,false); } void GolangEdit::editorFindUsagesGlobal() { QTextCursor cursor = m_plainTextEdit->textCursor(); m_fileSearch->findUsages(m_editor,cursor,true,false,false,false); } void GolangEdit::editorFindUsagesSkipGoroot() { QTextCursor cursor = m_plainTextEdit->textCursor(); m_fileSearch->findUsages(m_editor,cursor,true,true,false,false); } void GolangEdit::editorFindUsagesSkipTests() { QTextCursor cursor = m_plainTextEdit->textCursor(); m_fileSearch->findUsages(m_editor,cursor,true,true,true,false); } void GolangEdit::editorRenameSymbol() { QTextCursor cursor = m_plainTextEdit->textCursor(); m_fileSearch->findUsages(m_editor,cursor,false,false,false,true); } void GolangEdit::editorRenameSymbolGlobal() { QTextCursor cursor = m_plainTextEdit->textCursor(); m_fileSearch->findUsages(m_editor,cursor,true,false,false,true); } void GolangEdit::editorRenameSymbolSkipGoroot() { QTextCursor cursor = m_plainTextEdit->textCursor(); m_fileSearch->findUsages(m_editor,cursor,true,true,false,true); } void GolangEdit::editorComment() { LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (!editor) { return; } QPlainTextEdit *textEdit = LiteApi::findExtensionObject<QPlainTextEdit*>(editor,"LiteApi.QPlainTextEdit"); if (!textEdit) { return; } Utils::CommentDefinition cd; cd.setAfterWhiteSpaces(false); Utils::unCommentSelection(textEdit,Utils::AutoComment,cd); } void GolangEdit::editorFindInfo() { m_srcData = m_editor->utf8Data(); QFileInfo info(m_editor->filePath()); bool moveLeft = false; int selectStart = 0; QString text = LiteApi::wordUnderCursor(m_plainTextEdit->textCursor(),&moveLeft,&selectStart); if (text.isEmpty() || text.contains(" ")) { return; } m_lastCursor = m_plainTextEdit->textCursor(); int offset = m_editor->utf8Position(false,selectStart); QString cmd; QStringList args; if (m_useGocodeInfo) { cmd = getGocode(m_liteApp); args << "liteide_typesinfo" << info.fileName() << QString("%1").arg(offset) << selectionUnderCursor(m_lastCursor,moveLeft); } else { cmd = LiteApi::getGotools(m_liteApp); args << "types"; QString tags = LiteApi::getGoBuildFlagsArgument(m_liteApp,m_editor,"-tags"); if (!tags.isEmpty()) { args << "-tags"; args << tags; } args << "-pos"; args << QString("\"%1:%2\"").arg(info.fileName()).arg(offset); args << "-stdin"; args << "-info"; args << "-def"; args << "-doc"; args << "."; } if (!m_findInfoProcess->isStop()) { m_findInfoProcess->stopAndWait(100,200); } m_findInfoProcess->setEnvironment(LiteApi::getCustomGoEnvironment(m_liteApp,m_editor).toStringList()); m_findInfoProcess->setWorkingDirectory(info.path()); m_findInfoProcess->startEx(cmd,args); } void GolangEdit::findDefStarted() { m_findDefProcess->write(m_srcData); m_findDefProcess->closeWriteChannel(); } void GolangEdit::findDefFinish(int code,QProcess::ExitStatus status) { if (code != 0) { QString err = ProcessEx::exitStatusText(code,status); m_liteApp->appendLog("find def error",err,true); return; } QByteArray data = m_findDefProcess->readAllStandardOutput(); if (data.isEmpty()) { QByteArray data = m_findDefProcess->readAllStandardError(); if (!data.isEmpty()) { m_liteApp->appendLog("GolangEdit",QString::fromUtf8(data),true); } return; } QStringList infos = QString::fromUtf8(data).trimmed().split("\n"); QString info = infos.at(0); QRegExp reg(":(\\d+):(\\d+)"); int pos = reg.lastIndexIn(info); if (pos >= 0) { //:fname:fpath:dir if(info.length() > (pos+reg.matchedLength()) ) { QStringList extra = info.mid(pos+reg.matchedLength()).split("::",qtSkipEmptyParts); if (extra.size() == 3) { QString targetOpenDir = extra[2]; QString targetOpenDirInfo = QString(tr("Below files in package %1").arg(extra[1])); if (!targetOpenDir.isEmpty()) { LiteApi::IQuickOpenManager *mgr = LiteApi::getQuickOpenManager(m_liteApp); if (mgr) { LiteApi::IQuickOpenFileSystem *fileSystem = LiteApi::getQuickOpenFileSystem(mgr); if (fileSystem) { fileSystem->setRootPath(targetOpenDir); fileSystem->setPlaceholderText(targetOpenDirInfo); mgr->setCurrentFilter(fileSystem); mgr->showPopup(); return; } } } } } QString fileName = info.left(pos); int line = reg.cap(1).toInt(); int col = reg.cap(2).toInt(); col = byteOffsetToColumn(fileName,line,col); LiteApi::gotoLine(m_liteApp,fileName,line-1,col-1,true,true); } } void GolangEdit::findInfoStarted() { m_findInfoProcess->write(m_srcData); m_findInfoProcess->closeWriteChannel(); } void GolangEdit::findInfoFinish(int code, QProcess::ExitStatus) { if (code != 0) { return; } QByteArray data = m_findInfoProcess->readAllStandardOutput(); if (data.isEmpty()) { return; } if ( m_editor == m_liteApp->editorManager()->currentEditor()) { if (m_plainTextEdit->textCursor() == m_lastCursor) { QStringList lines = QString::fromUtf8(data).trimmed().split("\n"); QString info; if (lines.size() >= 2) { info = formatInfo(lines[1]); if (lines.size() >= 3) { info += "\n"; for (int i = 2; i < lines.size(); i++) { info += "\n"+lines.at(i); } } } QRect rc = m_plainTextEdit->cursorRect(m_lastCursor); QPoint pt = m_plainTextEdit->mapToGlobal(rc.topRight()); m_editor->showToolTipInfo(pt,info); } } } void GolangEdit::findInfoGopherOutput(const QByteArray &data, bool bError) { qDebug() << bError << data; } void GolangEdit::findLinkStarted() { m_findLinkProcess->write(m_srcData); m_findLinkProcess->closeWriteChannel(); } static QStringList FindSourceInfo(LiteApi::IApplication *app, const QString &fileName, int line, int maxLine) { QStringList lines; LiteApi::IEditor *edit = app->editorManager()->findEditor(fileName,true); int digits = 2; int max = line+maxLine; while (max >= 100) { max /= 10; ++digits; } if (edit) { QPlainTextEdit *ed = LiteApi::getPlainTextEdit(edit); if (ed) { QTextBlock block = ed->document()->findBlockByLineNumber(line); int index = 0; while (block.isValid() && index < maxLine) { index++; lines.append(QString("%1 %2").arg(line+index,digits).arg(block.text())); block = block.next(); } } } else { QFile f(fileName); if (f.open(QFile::ReadOnly)) { QTextStream stream(&f); stream.setCodec("utf-8"); int curLine = 0; QString text; while(!stream.atEnd() && (curLine < (line+maxLine)) ) { text = stream.readLine(); if (curLine >= line) { lines.append(QString("%1 %2").arg(curLine,digits).arg(text)); } curLine++; } } } return lines; } static QString FindSourceBlock(LiteApi::IApplication *app, const QString &fileName, int blockNumber) { QString lines; LiteApi::IEditor *edit = app->editorManager()->findEditor(fileName,true); if (edit) { QPlainTextEdit *ed = LiteApi::getPlainTextEdit(edit); if (ed) { QTextBlock block = ed->document()->findBlockByNumber(blockNumber); if (block.isValid()) { lines = block.text(); } } } else { QFile f(fileName); if (f.open(QFile::ReadOnly)) { QTextStream stream(&f); stream.setCodec("utf-8"); int curLine = 0; QString text; while(!stream.atEnd()) { text = stream.readLine(); if (curLine == blockNumber) { lines = text; break; } curLine++; } } } return lines; } int GolangEdit::byteOffsetToColumn(const QString &fileName, int line, int col) { QString block = FindSourceBlock(m_liteApp,fileName,line-1); if (!block.isEmpty()) { QByteArray line = block.toUtf8(); if (col > 0) { return QString::fromUtf8(line.left(col)).length(); } } return col; } void GolangEdit::findLinkFinish(int code,QProcess::ExitStatus) { if (code != 0) { return; } QByteArray data = m_findLinkProcess->readAllStandardOutput(); if ( m_editor == m_liteApp->editorManager()->currentEditor()) { if (m_lastLink.hasValidLinkText()) { QStringList info = QString::fromUtf8(data).trimmed().split("\n"); if (info.size() >= 2) { if (info[0] != "-") { QString fileInfo = info[0]; QRegExp reg(":(\\d+):(\\d+)"); int pos = reg.lastIndexIn(fileInfo); if (pos >= 0) { QString fileName = fileInfo.left(pos); int line = reg.cap(1).toInt(); int col = reg.cap(2).toInt(); col = byteOffsetToColumn(fileName,line,col); bool importExtra = false; //parser import line extra info if(fileInfo.length() > (pos+reg.matchedLength()) ) { QStringList extra = fileInfo.mid(pos+reg.matchedLength()).split("::",qtSkipEmptyParts); //:fname:fpath:dir if (extra.size() == 3) { importExtra = true; m_lastLink.targetOpenDir = extra[2]; m_lastLink.targetOpenDirInfo = QString(tr("Below files in package %1").arg(extra[1])); m_lastLink.targetInfo = formatInfo(info[1]); m_lastLink.sourceInfo = QString("%1\n\n> %2").arg(formatInfo(info[1])).arg(extra[2]); } } m_lastLink.targetFileName = fileName; m_lastLink.targetLine = line-1; m_lastLink.targetColumn = col-1; if (!importExtra) { m_lastLink.targetInfo = formatInfo(info[1]); m_lastLink.sourceInfo = QString("%1\n\n> %2:%3").arg(formatInfo(info[1])).arg(fileName).arg(line); } if (m_lastLink.showNav) { int n = 7; if (info.size() >= 3) { for (int i = 2; i < info.size(); i++) { m_lastLink.sourceInfo += "\n// "+info.at(i); n--; if (i >= 5) { if (i+1 < info.size()) { m_lastLink.sourceInfo += "\t..."; } break; } } } if (!importExtra) { m_lastLink.sourceInfo += "\n\n"; m_lastLink.sourceInfo += FindSourceInfo(m_liteApp,fileName,line-1,n).join("\n").replace("\t"," "); } } // show doc if (m_lastLink.showTip && (info.size() >= 3) ) { m_lastLink.targetInfo += "\n"; for (int i = 2; i < info.size(); i++) { m_lastLink.targetInfo += "\n"+info.at(i); } } m_editor->showLink(m_lastLink); } } else if (info[0] == "-") { QString infos = info[1]; if (infos == "nil") { infos = "zero value nil"; } m_lastLink.targetInfo = infos; m_lastLink.sourceInfo = infos; m_editor->showLink(m_lastLink); } else { m_editor->clearLink(); } } } } } void GolangEdit::searchTextChanged(const QString &/*word*/) { } void GolangEdit::sourceQueryFinished(int code, QProcess::ExitStatus /*status*/) { m_sourceQueryOutputAct->setChecked(true); // m_oracleOutput->clear(); m_sourceQueryOutput->updateExistsTextColor(true); if (code != 0) { QByteArray data = m_sourceQueryProcess->readAllStandardError(); m_sourceQueryOutput->append(data,Qt::red); return; } QByteArray data = m_sourceQueryProcess->readAllStandardOutput(); if (data.isEmpty()) { data = m_sourceQueryProcess->readAllStandardError(); } if (data.isEmpty()) { m_sourceQueryOutput->append(QString("oracle \"%1\" output is nothing.").arg(m_sourceQueryInfo.action)); return; } m_sourceQueryInfo.output = QString::fromUtf8(data); m_sourceQueryInfo.success = true; // m_oracleOutput->append(m_oracleInfo.output); //remove referrers action foreach (QString line, QString::fromUtf8(data).split("\n")) { //-: modes: [callees callers callstack definition describe implements pointsto referrers] if (line.startsWith("-: modes:")) { QString mode = line.mid(9); // mode.remove(QRegExp("\\s?\\breferrers\\b")); if (mode.contains("implements")) { mode.replace("implements","implements implements_GOPATH"); } m_sourceQueryInfo.mode = mode; } m_sourceQueryOutput->append(line+"\n"); } if (!m_sourceQueryInfo.mode.isEmpty()) { m_sourceQueryOutput->appendTag(m_sourceQueryInfo.mode+"\n"); } } void GolangEdit::sourcequeryError(QProcess::ProcessError code) { QString data = ProcessEx::processErrorText(code); m_sourceQueryOutput->append(data,Qt::red); } //void GolangEdit::updateOracleInfo(const QString &action, const QString &text) //{ // //if (action == "what") { // QRegExp reg("((?:[a-zA-Z]:)?[\\w\\d_\\-\\\\/\\.]+):(\\d+)[\\.:]?(\\d+)?\\-?(\\d+)?\\.?(\\d+)?\\b"); // foreach (QString line, text.split("\n")) { // if (reg.indexIn(line) >= 0) { // //qDebug() << reg.capturedTexts(); // QString text = line.mid(reg.capturedTexts().at(0).length()); // QString html = QString("<a href=\"file://%1\">%2</a> %3").arg(reg.capturedTexts().at(0)).arg(reg.capturedTexts().at(0)).arg(text); // m_oracleOutput->appendHtml(html); // } // } // //} // m_oracleOutput->append(text); //} void GolangEdit::dbclickSourceQueryOutput(const QTextCursor &cursor) { QTextCursor cur = cursor; cur.select(QTextCursor::LineUnderCursor); QString text = cur.selectedText(); if (text.isEmpty()) { return; } bool hasGotoLine = false; QRegExp reg("((?:[a-zA-Z]:)?[\\w\\d_@\\s\\-\\\\/\\.]+):(\\d+)[\\.:]?(\\d+)?\\-?(\\d+)?\\.?(\\d+)?\\b"); if (reg.indexIn(text) >= 0) { hasGotoLine = true; } if (!hasGotoLine) { QTextCursor cur = cursor; cur.select(QTextCursor::WordUnderCursor); QString text = cur.selectedText(); QStringList actions; actions << "callees" << "callers" << "callstack" << "definition" << "describe" << "freevars" << "implements" << "implements_GOPATH" << "peers" << "referrers" << "pointsto" << "whicherrs"; if (actions.contains(text)) { if (text.endsWith("_GOPATH")) { runSourceQueryByInfo(text.replace("_GOPATH",""),"..."); } else { runSourceQueryByInfo(text); } } return; } QStringList capList = reg.capturedTexts(); if (capList.count() < 5) { return; } QString fileName = capList[1]; QString fileLine = capList[2]; QString fileCol = capList[3]; bool ok = false; int line = fileLine.toInt(&ok); if (!ok) return; int col = fileCol.toInt(&ok); if (!ok) { col = 1; } QDir dir(m_sourceQueryInfo.workPath); if (!QFileInfo(fileName).isAbsolute()) { fileName = dir.filePath(fileName); } col = byteOffsetToColumn(fileName,line,col); if (LiteApi::gotoLine(m_liteApp,fileName,line-1,col-1,true,true)) { m_sourceQueryOutput->setTextCursor(cur); } } void GolangEdit::runSourceQueryAction(const QString &action, const QString &scope) { QTextCursor cursor = m_plainTextEdit->textCursor(); if (!m_sourceQueryProcess->isStop()) { m_sourceQueryProcess->stopAndWait(100,200); } int offset = -1; int offset2 = -1; if (cursor.hasSelection()) { offset = m_editor->utf8Position(true,cursor.selectionStart()); offset2 = m_editor->utf8Position(true,cursor.selectionEnd()); } else { bool moveLeft = false; int selectStart = 0; QString text = LiteApi::wordUnderCursor(cursor,&moveLeft,&selectStart); if (text.isEmpty() || text.contains(" ")) { return; } m_liteApp->editorManager()->saveAllEditors(false); offset = m_editor->utf8Position(true,selectStart); } QString cmd; QString cmdName; QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); QString guruFilePath = FileUtil::lookupGoBin("guru",m_liteApp,env,true); if (!guruFilePath.isEmpty()) { cmd = guruFilePath; cmdName = "guru"; } else { m_liteApp->appendLog("GolangEdit","guru was not found on system PATH (hint: is guru installed? \"go install golang.org/x/tools/cmd/guru@latest\")",true); return; } m_sourceQueryOutputAct->setChecked(true); m_sourceQueryOutput->clear(); m_sourceQueryOutput->append(QString("\nwait for source query, command \"%1\" action \"%2\" scope \"%3\"\n\n").arg(cmdName).arg(action).arg(scope)); QFileInfo info(m_editor->filePath()); m_sourceQueryInfo.cmdName = cmdName; m_sourceQueryInfo.action = action; m_sourceQueryInfo.workPath = info.path(); m_sourceQueryInfo.filePath = info.filePath(); m_sourceQueryInfo.fileName = info.fileName(); m_sourceQueryInfo.output.clear(); m_sourceQueryInfo.success = false; m_sourceQueryInfo.mode.clear(); m_sourceQueryInfo.offset = offset; m_sourceQueryInfo.offset2 = offset2; m_sourceQueryProcess->setEnvironment(LiteApi::getCustomGoEnvironment(m_liteApp,m_editor).toStringList()); m_sourceQueryProcess->setWorkingDirectory(info.path()); QString fileName = info.fileName(); QStringList args; if (!guruFilePath.isEmpty()) { args << "-scope" << scope; args << action; if (offset2 -= 1) { args << QString("\"%1:#%2\"").arg(fileName).arg(offset); } else { args << QString("\"%1:#%2,#%3\"").arg(fileName).arg(offset).arg(offset2); } } else { args << "oracle"; if (offset2 -= 1) { args << QString("-pos \"%1:#%2\"").arg(fileName).arg(offset); } else { args << QString("-pos \"%1:#%2,#%3\"").arg(fileName).arg(offset).arg(offset2); } args << action; args << scope; } m_sourceQueryProcess->startEx(cmd,args); } void GolangEdit::runSourceQueryByInfo(const QString &action, const QString &scope) { if (!m_sourceQueryProcess->isStop()) { m_sourceQueryProcess->stopAndWait(100,200); } QString cmd; QString cmdName; QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); QString guruFilePath = FileUtil::lookupGoBin("guru",m_liteApp,env,true); if (!guruFilePath.isEmpty()) { cmd = guruFilePath; cmdName = "guru"; } else { cmd = LiteApi::getGotools(m_liteApp); cmdName = "oracle"; } m_sourceQueryInfo.cmdName = cmdName; int offset = m_sourceQueryInfo.offset; int offset2 = m_sourceQueryInfo.offset2; m_sourceQueryOutput->append(QString("\nwait for source query, command \"%1\" action \"%2\" scope \"%3\" \n\n").arg(cmdName).arg(action).arg(scope)); m_sourceQueryProcess->setEnvironment(LiteApi::getCustomGoEnvironment(m_liteApp,m_editor).toStringList()); m_sourceQueryProcess->setWorkingDirectory(m_sourceQueryInfo.workPath); QString fileName = m_sourceQueryInfo.fileName; QStringList args; if (!guruFilePath.isEmpty()) { args << "-scope" << scope; args << action; if (offset2 -= 1) { args << QString("\"%1:#%2\"").arg(fileName).arg(offset); } else { args << QString("\"%1:#%2,#%3\"").arg(fileName).arg(offset).arg(offset2); } } else { args << "oracle"; if (offset2 -= 1) { args << QString("-pos \"%1:#%2\"").arg(fileName).arg(offset); } else { args << QString("-pos \"%1:#%2,#%3\"").arg(fileName).arg(offset).arg(offset2); } args << action; args << scope; } m_sourceQueryProcess->startEx(cmd,args); } void GolangEdit::sourceWhat() { runSourceQueryAction("what"); } void GolangEdit::sourceCallees() { runSourceQueryAction("callees"); } void GolangEdit::sourceCallers() { runSourceQueryAction("callers"); } void GolangEdit::sourceCallstack() { runSourceQueryAction("callstack"); } void GolangEdit::sourceDefinition() { runSourceQueryAction("definition"); } void GolangEdit::sourceDescribe() { runSourceQueryAction("describe"); } void GolangEdit::sourceFreevars() { runSourceQueryAction("freevars"); } void GolangEdit::sourceImplements() { runSourceQueryAction("implements"); } void GolangEdit::sourceImplementsGopath() { runSourceQueryAction("implements","..."); } void GolangEdit::sourcePeers() { runSourceQueryAction("peers"); } void GolangEdit::sourceReferrers() { runSourceQueryAction("referrers"); } void GolangEdit::sourcePointsto() { runSourceQueryAction("pointsto"); } void GolangEdit::sourceWhicherrs() { runSourceQueryAction("whicherrs"); } void GolangEdit::sourceQueryStateChanged(QProcess::ProcessState state) { m_stopSourceQueryAct->setEnabled(state == QProcess::Running); } void GolangEdit::stopSourceQueryProcess() { if (m_sourceQueryProcess->isRunning()) { m_sourceQueryProcess->stop(200); } } void GolangEdit::goplsFindAllReferences() { QTextCursor cursor = m_plainTextEdit->textCursor(); m_goplsSearch->setReadOnly(false); m_goplsSearch->setDisplyName(tr("All References")); m_goplsSearch->findUsages(m_editor,cursor, GOPLS_references,QStringList() << "-d"); } void GolangEdit::goplsFindAllImplementations() { QTextCursor cursor = m_plainTextEdit->textCursor(); m_goplsSearch->setReadOnly(true); m_goplsSearch->setDisplyName(tr("All Implementation")); m_goplsSearch->findUsages(m_editor,cursor, GOPLS_implementation); } QString GolangEdit::getGoModifyTagsInfo() const { QString text; QString fileName = QFileInfo(m_editor->filePath()).fileName(); QTextCursor cursor = m_plainTextEdit->textCursor(); if (cursor.hasSelection()) { int start = cursor.selectionStart(); int end = cursor.selectionEnd(); int line1 = cursor.document()->findBlock(start).blockNumber()+1; int line2 = cursor.document()->findBlock(end).blockNumber()+1; if (line1 == line2) { text = QString("gomodifytags -file %1 -line %2").arg(fileName).arg(line1); } else { text = QString("gomodifytags -file %1 -line %2,%3").arg(fileName).arg(line1).arg(line2); } } else { text = QString("gomodifytags -file %1 -offset %2 (Inside a valid structure under the cursor)").arg(fileName).arg(m_editor->utf8Position(true)); } return text; } void GolangEdit::execGoModifyTags(const QString &args) { if (args.isEmpty()) { return; } QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); QString cmd = FileUtil::lookupGoBin("gomodifytags",m_liteApp,env,true); if (cmd.isEmpty()) { m_liteApp->appendLog("GolangEdit","Could not find gomodifytags (hint: is gomodifytags installed?)",true); return; } QFileInfo info(m_editor->filePath()); Process process(this); process.setEnvironment(env.toStringList()); process.setWorkingDirectory(info.path()); QString cmdArgs; QTextCursor cursor = m_plainTextEdit->textCursor(); if (cursor.hasSelection()) { int start = cursor.selectionStart(); int end = cursor.selectionEnd(); int line1 = cursor.document()->findBlock(start).blockNumber()+1; int line2 = cursor.document()->findBlock(end).blockNumber()+1; if (line1 == line2) { cmdArgs = QString("-file %1 -line %2 %3").arg(info.fileName()).arg(line1).arg(args); } else { cmdArgs = QString("-file %1 -line %2,%3 %4").arg(info.fileName()).arg(line1).arg(line2).arg(args); } } else { cmdArgs = QString("-file %1 -offset %2 %3").arg(info.fileName()).arg(m_editor->utf8Position(true)).arg(args); } process.startEx(cmd,cmdArgs.split(" ")); if (!process.waitForStarted(30000)) { m_liteApp->appendLog("GolangEdit","wait for gomodifytags started timeout",true); return; } if (!process.waitForFinished(30000)) { process.kill(); m_liteApp->appendLog("GolangEdit","wait for gomodifytags finished timeout",true); return; } int code = process.exitCode(); if (code != 0) { QByteArray error = process.readAllStandardError(); m_liteApp->appendLog("GolangEdit",QString("gomodifytags exit code %1, %2").arg(code).arg(QString::fromUtf8(error)),true); return; } QByteArray data = process.readAllStandardOutput(); if (data.isEmpty()) { return; } m_editor->loadTextUseDiff(QString::fromUtf8(data)); } void GolangEdit::goAddTags() { if (m_editor->isModified()) { m_liteApp->editorManager()->saveEditor(m_editor); } if (!m_addTagsDlg) { m_addTagsDlg = new GoAddTagsDialog(m_liteApp->mainWindow()); } m_addTagsDlg->setInfo(getGoModifyTagsInfo()); if (m_addTagsDlg->exec() != QDialog::Accepted) { return; } QString args = m_addTagsDlg->arguments(); if (args.isEmpty()) { return; } execGoModifyTags(args); } void GolangEdit::goRemoveTags() { if (m_editor->isModified()) { m_liteApp->editorManager()->saveEditor(m_editor); } if (!m_removeTagsDlg) { m_removeTagsDlg = new GoRemoveTagsDialog(m_liteApp->mainWindow()); } m_removeTagsDlg->setInfo(getGoModifyTagsInfo()); if (m_removeTagsDlg->exec() != QDialog::Accepted) { return; } QString args = m_removeTagsDlg->arguments(); if (args.isEmpty()) { return; } execGoModifyTags(args); }
58,868
C++
.cpp
1,403
33.22737
196
0.611536
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,403
goaddtagsdialog.cpp
visualfc_liteide/liteidex/src/plugins/golangedit/goaddtagsdialog.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2017 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: goaddtagsdialog.cpp // Creator: visualfc <visualfc@gmail.com> #include "goaddtagsdialog.h" #include "ui_goaddtagsdialog.h" #include "liteapi/liteqt.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GoAddTagsDialog::GoAddTagsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::GoAddTagsDialog) { ui->setupUi(this); connect(ui->jsonCheckBox,SIGNAL(toggled(bool)),this,SLOT(updateaAguments())); connect(ui->jsonCheckBox,SIGNAL(toggled(bool)),ui->jsonGroupBox,SLOT(setEnabled(bool))); connect(ui->jsonOptionsCheckBox,SIGNAL(toggled(bool)),this,SLOT(updateaAguments())); connect(ui->jsonOptionsLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateaAguments())); connect(ui->xmlCheckBox,SIGNAL(toggled(bool)),this,SLOT(updateaAguments())); connect(ui->xmlCheckBox,SIGNAL(toggled(bool)),ui->xmlGroupBox,SLOT(setEnabled(bool))); connect(ui->xmlOptionsCheckBox,SIGNAL(toggled(bool)),this,SLOT(updateaAguments())); connect(ui->xmlOptionsLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateaAguments())); connect(ui->customCheckBox,SIGNAL(toggled(bool)),this,SLOT(updateaAguments())); connect(ui->customCheckBox,SIGNAL(toggled(bool)),ui->customGroupBox,SLOT(setEnabled(bool))); connect(ui->customTagNameLineEdit1,SIGNAL(textChanged(QString)),this,SLOT(updateaAguments())); connect(ui->customTagOptionLineEdit1,SIGNAL(textChanged(QString)),this,SLOT(updateaAguments())); connect(ui->customTagNameLineEdit2,SIGNAL(textChanged(QString)),this,SLOT(updateaAguments())); connect(ui->customTagOptionlineEdit2,SIGNAL(textChanged(QString)),this,SLOT(updateaAguments())); connect(ui->snakeCaseRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateaAguments())); connect(ui->camelCaseRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateaAguments())); connect(ui->lispCaseRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateaAguments())); connect(ui->overrideCheckBox,SIGNAL(toggled(bool)),this,SLOT(updateaAguments())); connect(ui->sortCheckBox,SIGNAL(toggled(bool)),this,SLOT(updateaAguments())); ui->snakeCaseRadioButton->setChecked(true); ui->jsonGroupBox->setEnabled(false); ui->xmlGroupBox->setEnabled(false); ui->customGroupBox->setEnabled(false); } GoAddTagsDialog::~GoAddTagsDialog() { delete ui; } void GoAddTagsDialog::setInfo(const QString &info) { ui->infoLabel->setText(info); } QString GoAddTagsDialog::arguments() const { return ui->argumentsEdit->toPlainText().trimmed(); } static QString parserTag(const QString &tag) { int pos = tag.indexOf(":"); if (pos == -1) { return tag; } return tag.left(pos); } void GoAddTagsDialog::updateaAguments() { QStringList tagList; QStringList optList; QString tranform; if (ui->jsonCheckBox->isChecked()) { tagList << "json"; if (ui->jsonOptionsCheckBox->isChecked()) { QStringList opt = ui->jsonOptionsLineEdit->text().trimmed().split(",",qtSkipEmptyParts); foreach (QString o, opt) { optList << "json="+o; } } } if (ui->xmlCheckBox->isChecked()) { tagList << "xml"; if (ui->xmlOptionsCheckBox->isChecked()) { QStringList opt = ui->xmlOptionsLineEdit->text().trimmed().split(",",qtSkipEmptyParts); foreach (QString o, opt) { optList << "xml="+o; } } } if (ui->customCheckBox->isChecked()) { QString tag1 = ui->customTagNameLineEdit1->text().trimmed(); QStringList opt1 = ui->customTagOptionLineEdit1->text().trimmed().split(",",qtSkipEmptyParts); QString tag2 = ui->customTagNameLineEdit2->text().trimmed(); QStringList opt2 = ui->customTagOptionlineEdit2->text().trimmed().split(",",qtSkipEmptyParts); if (!tag1.isEmpty()) { tagList << tag1; foreach (QString o, opt1) { optList << parserTag(tag1)+"="+o; } } if (!tag2.isEmpty()) { tagList << tag2; foreach (QString o, opt2) { optList << parserTag(tag2)+"="+o; } } } QString info; if (ui->snakeCaseRadioButton->isChecked()) { tranform = "snakecase"; info = "BaseDomain -> base_domain"; } else if (ui->camelCaseRadioButton->isChecked()) { tranform = "camelcase"; info = "BaseDomain -> baseDomain"; } else if (ui->lispCaseRadioButton->isChecked()) { tranform = "lispcase"; info = "BaseDomain -> base-domain"; } if (ui->transformInfo->text() != info) { ui->transformInfo->setText(info); } QString command; if (!tagList.isEmpty()) { command += "-add-tags "+tagList.join(","); if (!optList.isEmpty()) { command += " -add-options "+optList.join(","); } command += " -transform "+tranform; if (ui->overrideCheckBox->isChecked()) { command += " -override"; } if (ui->sortCheckBox->isChecked()) { command += " -sort"; } } ui->argumentsEdit->setPlainText(command); }
6,574
C++
.cpp
154
35.818182
103
0.639837
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,404
golangfilesearch.cpp
visualfc_liteide/liteidex/src/plugins/golangedit/golangfilesearch.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangfilesearch.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangfilesearch.h" #include "litebuildapi/litebuildapi.h" #include <QTextBlock> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangFileSearch::GolangFileSearch(LiteApi::IApplication *app, QObject *parent) : LiteApi::IFileSearch(parent), m_liteApp(app) { m_process = new ProcessEx(this); m_replaceMode = false; m_bParserHead = true; // connect(m_process,SIGNAL(started()),this,SLOT(findUsagesStarted())); connect(m_process,SIGNAL(extOutput(QByteArray,bool)),this,SLOT(findUsagesOutput(QByteArray,bool))); connect(m_process,SIGNAL(extFinish(bool,int,QString)),this,SLOT(findUsagesFinish(bool,int,QString))); } GolangFileSearch::~GolangFileSearch() { } QString GolangFileSearch::mimeType() const { return "find/gofilesearch"; } QString GolangFileSearch::displayName() const { return tr("Golang Find Usages"); } QWidget *GolangFileSearch::widget() const { return 0; } void GolangFileSearch::start() { } void GolangFileSearch::cancel() { } void GolangFileSearch::activate() { } QString GolangFileSearch::searchText() const { return m_searchText; } bool GolangFileSearch::replaceMode() const { return m_replaceMode; } void GolangFileSearch::setSearchInfo(const QString &/*text*/, const QString &/*filter*/, const QString &/*path*/) { } void GolangFileSearch::findUsages(LiteApi::ITextEditor *editor, QTextCursor cursor, bool global, bool skip_goroot, bool skip_tests, bool replace) { if (!m_process->isStop()) { m_process->stopAndWait(100,2000); } bool moveLeft = false; int selectStart = 0; m_searchText = LiteApi::wordUnderCursor(cursor,&moveLeft,&selectStart); if (m_searchText.isEmpty() || m_searchText.contains(" ")) { return; } m_liteApp->editorManager()->saveAllEditors(false); //int offset = moveLeft ? editor->utf8Position(true)-1: editor->utf8Position(true); int offset = editor->utf8Position(true,selectStart); LiteApi::IFileSearchManager *manager = LiteApi::getFileSearchManager(m_liteApp); if (!manager) { return; } this->m_replaceMode = replace; manager->setCurrentSearch(this); m_lastLine = 0; m_bParserHead = true; m_file.close(); QString cmd = LiteApi::getGotools(m_liteApp); QFileInfo info(editor->filePath()); m_process->setEnvironment(LiteApi::getCustomGoEnvironment(m_liteApp,editor).toStringList()); m_process->setWorkingDirectory(info.path()); QStringList args; args << "types"; QString tags = LiteApi::getGoBuildFlagsArgument(m_liteApp,editor,"-tags"); if (!tags.isEmpty()) { args << "-tags"; args << tags; } args << "-pos"; args << QString("\"%1:%2\"").arg(info.fileName()).arg(offset); args << "-info"; args << "-use"; QString text = selectionUnderCursor(cursor,moveLeft); if (!text.isEmpty()) { args << "-text" << text; } if (global) { args << "-all"; } if (skip_goroot) { args << "-skip_goroot"; } if (skip_tests) { args << "-skip_tests"; } args << "."; emit findStarted(); m_process->startEx(cmd,args); } void GolangFileSearch::findUsagesStarted() { } void GolangFileSearch::findUsagesOutput(QByteArray data, bool bStdErr) { if (bStdErr) { QString info = QString::fromUtf8(data).trimmed(); emit findError(info); m_liteApp->appendLog("find usage error",info,true); return; } QRegExp reg(":(\\d+):(\\d+)-?(\\d*)"); foreach (QByteArray line, data.split('\n')) { QString info = QString::fromUtf8(line).trimmed(); if (m_bParserHead) { m_bParserHead = false; //package fmt //package ast ("go/ast") if (info.startsWith("package ") || info.startsWith("import ")) { int n = info.indexOf("("); if (n != -1) { info = info.left(n); } //change searchText //m_searchText = info.mid(7).trimmed(); QString pkgName = info.mid(7).trimmed(); if (pkgName != m_searchText) { m_searchText = pkgName; emit searchTextChanged(pkgName); } } continue; } int pos = reg.lastIndexIn(info); if (pos >= 0) { QString fileName = info.left(pos); int fileLine = reg.cap(1).toInt(); int fileCol = reg.cap(2).toInt(); bool hasCol2 = false; int fileCol2 = reg.cap(3).toInt(&hasCol2); if (m_file.fileName() != fileName) { m_file.close(); m_file.setFileName(fileName); } if (!m_file.isOpen()) { m_file.open(QFile::ReadOnly); m_lastLine = 0; } if (m_file.isOpen()) { if (fileLine != m_lastLine) { while(!m_file.atEnd()) { QByteArray line = m_file.readLine(); m_lastLine++; if (fileLine == m_lastLine) { m_lastLineText = QString::fromUtf8(trimmedRight(line)); if (fileCol > 0) { fileCol = QString::fromUtf8(line.left(fileCol)).length(); } break; } } } else { QByteArray line = m_lastLineText.toUtf8(); if (fileCol > 0) { fileCol = QString::fromUtf8(line.left(fileCol)).length(); } } int length = m_searchText.length(); if (hasCol2) { length = fileCol2-fileCol; } emit findResult(LiteApi::FileSearchResult(fileName,m_lastLineText,fileLine,fileCol-1,length)); } } } } void GolangFileSearch::findUsagesFinish(bool b, int, QString) { m_file.close(); m_lastLine = 0; emit findFinished(b); }
7,472
C++
.cpp
216
27.148148
145
0.588797
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,405
golangeditoptionfactory.cpp
visualfc_liteide/liteidex/src/plugins/golangedit/golangeditoptionfactory.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangeditoptionfactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangeditoption.h" #include "golangeditoptionfactory.h" #include "golangedit_global.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangEditOptionFactory::GolangEditOptionFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IOptionFactory(parent), m_liteApp(app) { } QStringList GolangEditOptionFactory::mimeTypes() const { return QStringList() << OPTION_GOLANGEDIT; } LiteApi::IOption *GolangEditOptionFactory::create(const QString &mimeType) { if (mimeType == OPTION_GOLANGEDIT) { return new GolangEditOption(m_liteApp,this); } return 0; }
1,936
C++
.cpp
50
36.46
93
0.692349
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,406
welcomeplugin.cpp
visualfc_liteide/liteidex/src/plugins/welcome/welcomeplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: welcomeplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "welcomeplugin.h" #include "../../liteapp/liteapp_global.h" #include "liteapi/liteids.h" #include <QAction> #include <QMenu> #include <QToolBar> #include <QUrl> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end WelcomePlugin::WelcomePlugin() : m_welcome(0) { } WelcomePlugin::~WelcomePlugin() { } void WelcomePlugin::home() { m_liteApp->editorManager()->activeBrowser(m_welcome); } void WelcomePlugin::godoc() { m_liteApp->editorManager()->activeBrowser(m_welcome); m_welcome->openUrl(QUrl("godoc:/doc/docs.html")); } bool WelcomePlugin::load(LiteApi::IApplication *app) { m_liteApp = app; m_welcome = new WelcomeBrowser(app,this); m_welcomeAct = m_liteApp->editorManager()->registerBrowser(m_welcome); m_liteApp->actionManager()->insertViewMenu(LiteApi::ViewMenuBrowserPos,m_welcomeAct); if (m_liteApp->settings()->value(LITEAPP_WELCOMEPAGEVISIBLE,true).toBool()) { m_welcomeAct->toggle(); } QToolBar *toolBar = m_liteApp->actionManager()->loadToolBar(ID_TOOLBAR_STD); if (toolBar) { toolBar->addSeparator(); m_homeAct = new QAction(QIcon("icon:images/home.png"),tr("Welcome"),this); m_homeAct->setShortcut(QKeySequence("Ctrl+Alt+H")); connect(m_homeAct,SIGNAL(triggered()),this,SLOT(home())); //m_godocAct = new QAction(QIcon("icon:images/godoc.png"),tr("View Golang Documents"),this); //connect(m_godocAct,SIGNAL(triggered()),this,SLOT(godoc())); toolBar->addAction(m_homeAct); //toolBar->addAction(m_godocAct); } m_liteDoc = new LiteDoc(m_liteApp,this); return true; } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
3,037
C++
.cpp
80
34.8875
100
0.683424
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,407
litedoc.cpp
visualfc_liteide/liteidex/src/plugins/welcome/litedoc.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: litedoc.cpp // Creator: visualfc <visualfc@gmail.com> #include "litedoc.h" #include "documentbrowser/documentbrowser.h" #include "htmlutil/htmlutil.h" #include "cmark/libcmark.h" #include <QAction> #include <QMenu> #include <QFile> #include <QTextCodec> #include <QFileInfo> #include <QDir> #include <QPlainTextEdit> #include <QDesktopServices> #include <QApplication> #include <QStatusBar> #include <QComboBox> #include <QUrl> #if QT_VERSION >= 0x050000 #include <QUrlQuery> #endif #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end LiteDoc::LiteDoc(LiteApi::IApplication *app, QObject *parent) : LiteApi::ILiteDoc(parent), m_liteApp(app) { m_docBrowser = new DocumentBrowser(app,this); m_docBrowser->urlComboBox()->setEditable(false); m_docBrowser->setName(tr("LiteIDE Documentation")); QStringList paths; paths << m_liteApp->resourcePath()+"/welcome" << localePath(m_liteApp->resourcePath()+"/welcome"); m_docBrowser->setSearchPaths(paths); m_browserAct = m_liteApp->editorManager()->registerBrowser(m_docBrowser); //m_liteApp->actionManager()->insertViewMenu(LiteApi::ViewMenuBrowserPos,m_browserAct); connect(m_docBrowser,SIGNAL(requestUrl(QUrl)),this,SLOT(openUrl(QUrl))); connect(m_docBrowser,SIGNAL(linkHovered(QUrl)),this,SLOT(highlighted(QUrl))); QString path = localeFile(m_liteApp->resourcePath()+"/welcome/liteide.html"); QFile file(path); if (file.open(QIODevice::ReadOnly)) { m_templateData = QString::fromUtf8(file.readAll()); file.close(); } m_liteApp->extension()->addObject("LiteApi.ILiteDoc",this); } static QString getAppLocale() { return qApp->property("liteide_locale").toString(); } QString LiteDoc::localeFile(const QString &fileName) { QString locale = getAppLocale(); if (locale.isEmpty()) { locale = "en"; } QFileInfo info(fileName); QString path = info.absolutePath()+"/"+locale+"/"+info.fileName(); if (QFileInfo(path).exists()) { return path; } return info.absolutePath()+"/en/"+info.fileName();; } QString LiteDoc::localePath(const QString &path) { QString locale = getAppLocale(); if (locale.isEmpty()) { locale = "en"; } QDir dir(path+"/"+locale); if (dir.exists()) { return dir.path(); } return path+"/en"; } void LiteDoc::activeBrowser() { m_liteApp->editorManager()->activeBrowser(m_docBrowser); } QUrl LiteDoc::parserUrl(const QUrl &_url) { QDir root(localePath(m_liteApp->resourcePath()+"/welcome")); QUrl url = _url; if (url.isRelative() && !url.path().isEmpty()) { QFileInfo info; if (url.path().at(0) == '/') { info.setFile(root,url.path().right(url.path().length()-1)); } else if (m_lastUrl.scheme() == "file") { info.setFile(QFileInfo(m_lastUrl.toLocalFile()).absoluteDir(),url.path()); } if (info.exists() && info.isFile()) { url.setScheme("file"); url.setPath(info.filePath()); } } return url; } void LiteDoc::openUrl(const QUrl &_url) { m_liteApp->mainWindow()->statusBar()->clearMessage(); QUrl url = parserUrl(_url); if (url.scheme() == "file") { openUrlFile(url); } else if (url.scheme() == "http" || url.scheme() == "https" || url.scheme() == "mailto") { QDesktopServices::openUrl(url); } } void LiteDoc::highlighted(const QUrl &url) { m_liteApp->mainWindow()->statusBar()->showMessage(url.toString()); } void LiteDoc::openUrlFile(const QUrl &url) { QFileInfo info(url.toLocalFile()); if (!info.exists()) { info.setFile(url.path()); } QString ext = info.suffix().toLower(); if (ext == "html") { QFile file(info.filePath()); if (file.open(QIODevice::ReadOnly)) { QByteArray ba = file.readAll(); file.close(); if (info.fileName().compare("docs.html",Qt::CaseInsensitive) == 0) { updateHtmlDoc(url,ba,QString(),false); } else { updateHtmlDoc(url,ba); } } } else if (ext == "md") { QFile file(info.filePath()); if (file.open(QIODevice::ReadOnly)) { QByteArray ba = md2html(file.readAll()); updateHtmlDoc(url,ba); } } else if (ext == "go") { LiteApi::IEditor *editor = m_liteApp->fileManager()->openEditor(info.filePath()); if (editor) { editor->setReadOnly(true); QPlainTextEdit *ed = LiteApi::findExtensionObject<QPlainTextEdit*>(editor,"LiteApi.QPlainTextEdit"); #if QT_VERSION >= 0x050000 if (ed && QUrlQuery(url).hasQueryItem("s")) { QStringList pos = QUrlQuery(url).queryItemValue("s").split(":"); #else if (ed && url.hasQueryItem("s")) { QStringList pos = url.queryItemValue("s").split(":"); #endif if (pos.length() == 2) { bool ok = false; int begin = pos.at(0).toInt(&ok); if (ok) { QTextCursor cur = ed->textCursor(); cur.setPosition(begin); ed->setTextCursor(cur); ed->centerCursor(); } } } } } else if (ext == "pdf") { QDesktopServices::openUrl(info.filePath()); } else { QFile file(info.filePath()); if (file.open(QIODevice::ReadOnly)) { QByteArray ba = file.readAll(); updateTextDoc(url,ba,info.fileName()); } } } void LiteDoc::updateTextDoc(const QUrl &url, const QByteArray &ba, const QString &header) { m_lastUrl = url; QTextCodec *codec = QTextCodec::codecForUtfText(ba,QTextCodec::codecForName("utf-8")); #if QT_VERSION >= 0x050000 QString html = codec->toUnicode(ba).toHtmlEscaped(); #else QString html = Qt::escape(codec->toUnicode(ba)); #endif QString data = m_templateData; data.replace("{header}",header); data.replace("{nav}",""); data.replace("{content}",QString("<pre>%1</pre>").arg(html)); m_docBrowser->setUrlHtml(url,data); } void LiteDoc::updateHtmlDoc(const QUrl &url, const QByteArray &ba, const QString &header, bool toNav) { m_lastUrl = url; QTextCodec *codec = QTextCodec::codecForName("utf-8"); QString genHeader; QString nav; QString content = HtmlUtil::docToNavdoc(codec->toUnicode(ba),genHeader,nav); QString data = m_templateData; if (!header.isEmpty()) { data.replace("{header}",header); } else { data.replace("{header}",genHeader); } if (toNav) { data.replace("{nav}",nav); } else { data.replace("{nav}",""); } data.replace("{content}",content); m_docBrowser->setUrlHtml(url,data); }
8,160
C++
.cpp
234
29.012821
112
0.618801
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,408
welcomebrowser.cpp
visualfc_liteide/liteidex/src/plugins/welcome/welcomebrowser.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: welcomebrowser.cpp // Creator: visualfc <visualfc@gmail.com> #include "welcomebrowser.h" #include "golangdocapi/golangdocapi.h" #include "litedoc.h" #include <QMenu> #include <QStatusBar> #include <QToolBar> #include <QDir> #include <QFileInfo> #include <QAction> #include <QFile> #include <QTextBrowser> #include <QDesktopServices> #include <QHBoxLayout> #include <QVBoxLayout> #include <QPushButton> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end WelcomeBrowser::WelcomeBrowser(LiteApi::IApplication *app, QObject *parent) : LiteApi::IBrowserEditor(parent), m_liteApp(app), m_extension(new Extension), m_widget(new QWidget) { m_browser = new DocumentBrowser(m_liteApp,this); m_browser->toolBar()->hide(); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->setMargin(0); mainLayout->addWidget(m_browser->widget()); QPushButton *newFile = new QPushButton(tr("New")); QPushButton *openFile = new QPushButton(tr("Open")); QPushButton *openFolder = new QPushButton(tr("Open Folder")); QPushButton *options = new QPushButton(tr("Options")); QHBoxLayout *layout = new QHBoxLayout; layout->addWidget(newFile); layout->addWidget(openFile); layout->addWidget(openFolder); layout->addStretch(1); layout->addWidget(options); mainLayout->addLayout(layout); m_widget->setLayout(mainLayout); connect(newFile,SIGNAL(clicked()),m_liteApp->fileManager(),SLOT(newFile())); connect(openFile,SIGNAL(clicked()),m_liteApp->fileManager(),SLOT(openFiles())); connect(openFolder,SIGNAL(clicked()),this,SLOT(openFolder())); connect(options,SIGNAL(clicked()),m_liteApp->optionManager(),SLOT(exec())); connect(m_browser,SIGNAL(requestUrl(QUrl)),this,SLOT(openUrl(QUrl))); connect(m_liteApp->recentManager(),SIGNAL(recentNameListChanged(QString)),this,SLOT(loadData())); connect(m_browser,SIGNAL(linkHovered(QUrl)),this,SLOT(highlightedUrl(QUrl))); QStringList paths; paths << m_liteApp->resourcePath()+"/welcome" << LiteDoc::localePath(m_liteApp->resourcePath()+"/welcome"); m_browser->setSearchPaths(paths); m_extension->addObject("LiteApi.QTextBrowser",m_browser->htmlWidget()->widget()); QString path = LiteDoc::localeFile(m_liteApp->resourcePath()+"/welcome/welcome.html"); QFile file(path); if (file.open(QIODevice::ReadOnly)) { m_templateData = QString::fromUtf8(file.readAll()); file.close(); } loadData(); } WelcomeBrowser::~WelcomeBrowser() { delete m_browser; delete m_widget; if (m_extension) { delete m_extension; } } void WelcomeBrowser::openFolder() { m_liteApp->fileManager()->openFolder(); } LiteApi::IExtension *WelcomeBrowser::extension() { return m_extension; } void WelcomeBrowser::highlightedUrl(const QUrl &url) { m_liteApp->mainWindow()->statusBar()->showMessage(url.toString(),2000); } void WelcomeBrowser::openUrl(const QUrl &url) { m_liteApp->mainWindow()->statusBar()->clearMessage(); if (url.scheme() == "http" || url.scheme() == "https" || url.scheme() == "mailto") { QDesktopServices::openUrl(url); } else if (url.scheme() == "doc") { LiteApi::ILiteDoc *doc = LiteApi::findExtensionObject<LiteApi::ILiteDoc*>(m_liteApp,"LiteApi.ILiteDoc"); if (doc) { doc->openUrl(url.path()); doc->activeBrowser(); } } else if (url.scheme() == "godoc") { LiteApi::IGolangDoc *doc = LiteApi::findExtensionObject<LiteApi::IGolangDoc*>(m_liteApp,"LiteApi.IGolangDoc"); if (doc) { doc->openUrl(url.path()); doc->activeBrowser(); } } else if (url.scheme() == "goplay") { LiteApi::IEditor *browser = LiteApi::findExtensionObject<LiteApi::IEditor*>(m_liteApp,"LiteApi.Goplay"); if (browser) { m_liteApp->editorManager()->activeBrowser(browser); } } else { QStringList typeList = m_liteApp->recentManager()->recentTypeList(); if (typeList.contains(url.scheme())) { m_liteApp->recentManager()->openRecent(url.path(),url.scheme()); } } } void WelcomeBrowser::loadData() { QString data = m_templateData; QStringList sessionList; sessionList.append("<ul>"); sessionList.append(QString("<li><a href=\"session:default\">default</a></li>")); sessionList.append("</ul>"); QStringList recentList; foreach (LiteApi::IRecent *recent, m_liteApp->recentManager()->recentList()) { recentList.append(QString("<h3><i>Recent %1</i></h3>").arg(recent->displyType())); recentList.append("<table border=\"0\"><tr><td>"); recentList.append("<ul>"); QStringList recentNameList = m_liteApp->recentManager()->recentNameList(recent->type()); int count = 0; foreach (QString name, recentNameList) { QFileInfo info(name); recentList.append(QString("<li><a href=\"%1:%2\">%3</a> <span class=\"recent\">%4</span></li>") .arg(recent->type()) .arg(info.filePath()) .arg(info.fileName()) .arg(QDir::toNativeSeparators(info.filePath()))); if (count++ > 8) { break; } } recentList.append("</ul>"); recentList.append("</td></tr></table>"); } data.replace("{liteide_version}",m_liteApp->ideVersion()); data.replace("{recent_files}",recentList.join("\n")); QUrl url(m_liteApp->resourcePath()+"/welcome/welcome.html"); m_browser->setUrlHtml(url,data); } QWidget *WelcomeBrowser::widget() { return m_widget; } QString WelcomeBrowser::name() const { return tr("Welcome"); } QString WelcomeBrowser::mimeType() const { return "browser/welcome"; }
7,148
C++
.cpp
185
33.275676
118
0.651911
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,409
imageeditorfile.cpp
visualfc_liteide/liteidex/src/plugins/imageeditor/imageeditorfile.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: imageeditorfile.cpp // Creator: visualfc <visualfc@gmail.com> #include "imageeditorfile.h" #include <QGraphicsItem> #include <QImageReader> #include <QGraphicsPixmapItem> #include <QMovie> #include <QPainter> #include <QStyleOptionGraphicsItem> #include <QPixmap> #ifndef QT_NO_SVG #include <QGraphicsSvgItem> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end #endif ImageEditorFile::ImageEditorFile(LiteApi::IApplication *app, QObject *parent) : QObject(parent), m_liteApp(app) { m_movie = 0; m_item = 0; m_type = Invalid; m_isPaused = true; } ImageEditorFile::~ImageEditorFile() { clear(); } bool ImageEditorFile::open(const QString &filePath, const QString &mimeType) { QByteArray format = QImageReader::imageFormat(filePath); if (format.isEmpty()) { m_liteApp->appendLog("ImageViewer", QString("Image format not supported. %1").arg(filePath)); return false; } #ifndef QT_NO_SVG else if (format.startsWith("svg")) { QGraphicsItem *item = new QGraphicsSvgItem(filePath); if (item->boundingRect().isEmpty()) { delete item; m_liteApp->appendLog("ImageViewer", QString("SVG file invalid. %1").arg(filePath)); return false; } m_item = item; m_type = Svg; } #endif else if (QMovie::supportedFormats().contains(format)) { m_movie = new QMovie(filePath,QByteArray(),this); if (!m_movie->isValid()) { delete m_movie; m_liteApp->appendLog("ImageViewer", QString("Movie file invalid. %1").arg(filePath)); return false; } m_movie->setCacheMode(QMovie::CacheAll); m_item = new GraphicsMovieItem(m_movie); m_type = Movie; connect(m_movie,SIGNAL(finished()),m_movie,SLOT(start())); connect(m_movie,SIGNAL(frameChanged(int)),this,SIGNAL(frameChanged(int))); m_movie->start(); m_isPaused = false; setPaused(true); } else { QPixmap pixmap(filePath); if (pixmap.isNull()) { m_liteApp->appendLog("ImageViewer", QString("Pixmap file invalid. %1").arg(filePath)); return false; } m_type = Pixmap; m_item = new QGraphicsPixmapItem(pixmap); ((QGraphicsPixmapItem*)m_item)->setTransformationMode(Qt::SmoothTransformation); } m_mimeType = mimeType; m_filePath = filePath; return true; } void ImageEditorFile::setPaused(bool paused) { if (!m_movie || m_isPaused == paused) return; m_isPaused = paused; m_movie->setPaused(paused); emit isPausedChanged(m_isPaused); } QSize ImageEditorFile::imageSize() const { if (m_item) { QRectF sz = m_item->boundingRect(); return QSize(sz.width(),sz.height()); } return QSize(); } int ImageEditorFile::frameCount() const { if (m_type != Movie) { return 1; } return m_movie->frameCount(); } int ImageEditorFile::currentFrame() const { if (m_type != Movie) { return 0; } return m_movie->currentFrameNumber(); } bool ImageEditorFile::jumpToNextFrame() { if (m_type != Movie) { return false; } int cur = m_movie->currentFrameNumber(); cur++; if (cur < m_movie->frameCount()) { return m_movie->jumpToFrame(cur); } return false; } bool ImageEditorFile::jumpToPrevFrame() { if (m_type != Movie) { return false; } int cur = m_movie->currentFrameNumber(); cur--; if (cur >= 0) { return m_movie->jumpToFrame(cur); } return false; } void ImageEditorFile::clear() { if (m_movie) { delete m_movie; } if (m_item) { delete m_item; } m_filePath.clear(); m_type = Invalid; } GraphicsMovieItem::GraphicsMovieItem(QMovie *movie) : m_movie(movie) { setPixmap(m_movie->currentPixmap()); connect(m_movie,SIGNAL(updated(QRect)),this,SLOT(movieUpdate(QRect))); } void GraphicsMovieItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { const bool smoothTransform = painter->worldTransform().m11() < 1; painter->setRenderHint(QPainter::SmoothPixmapTransform, smoothTransform); painter->drawPixmap(offset(), m_movie->currentPixmap()); } QRectF GraphicsMovieItem::boundingRect() const { QRect rc = m_movie->frameRect(); return QRectF(rc); } void GraphicsMovieItem::movieUpdate(const QRect &rc) { QGraphicsPixmapItem::update(rc); }
5,744
C++
.cpp
187
26.219251
101
0.650424
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,410
imageeditorplugin.cpp
visualfc_liteide/liteidex/src/plugins/imageeditor/imageeditorplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: imageeditorplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "imageeditorplugin.h" #include "imageeditorfactory.h" #include <QtPlugin> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end ImageEditorPlugin::ImageEditorPlugin() { } bool ImageEditorPlugin::load(LiteApi::IApplication *app) { app->editorManager()->addFactory(new ImageEditorFactory(app,this)); return true; } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
1,730
C++
.cpp
45
36.622222
82
0.690065
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,411
imageeditor.cpp
visualfc_liteide/liteidex/src/plugins/imageeditor/imageeditor.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: imageeditor.cpp // Creator: visualfc <visualfc@gmail.com> #include "imageeditor.h" #include "imageeditorfile.h" #include "imageeditorwidget.h" #include <QFileInfo> #include <QVBoxLayout> #include <QHBoxLayout> #include <QAction> #include <QLabel> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end #define EDITOR_TOOLBAR_VISIBLE "editor/toolbar_visible" #define EDITOR_NAVBAR_VISIBLE "editor/navbar_visible" ImageEditor::ImageEditor(LiteApi::IApplication *app) : m_liteApp(app) { m_file = new ImageEditorFile(m_liteApp,this); m_imageWidget = new ImageEditorWidget; m_widget = new QWidget; m_toolBar = new QToolBar; m_mvToolBar = new QToolBar; m_navBar = new NavigateBar(app,this); m_navBar->createToolBar("editor.nav",m_widget); m_navBar->toolBar()->setVisible(m_liteApp->settings()->value(EDITOR_NAVBAR_VISIBLE,true).toBool()); m_toolBar->setIconSize(LiteApi::getToolBarIconSize(m_liteApp)); m_mvToolBar->setIconSize(LiteApi::getToolBarIconSize(m_liteApp)); QAction *zoomInAct = new QAction(tr("ZoomIn"),this); zoomInAct->setIcon(QIcon("icon:/imageeditor/images/zoomin.png")); QAction *zoomOutAct = new QAction(tr("ZoomOut"),this); zoomOutAct->setIcon(QIcon("icon:/imageeditor/images/zoomout.png")); QAction *resetSizeAct = new QAction(tr("Reset to original size"),this); resetSizeAct->setIcon(QIcon("icon:/imageeditor/images/resetsize.png")); QAction *fitViewAct = new QAction(tr("Fit to view"),this); fitViewAct->setIcon(QIcon("icon:/imageeditor/images/fitview.png")); QAction *playAct = new QAction(tr("Play movie"),this); playAct->setIcon(QIcon("icon:/imageeditor/images/play.png")); playAct->setCheckable(true); QAction *prevFrameAct = new QAction(tr("Prev frame"),this); prevFrameAct->setIcon(QIcon("icon:/imageeditor/images/prevframe.png")); connect(prevFrameAct,SIGNAL(triggered()),m_file,SLOT(jumpToPrevFrame())); QAction *nextFrameAct = new QAction(tr("Next frame"),this); nextFrameAct->setIcon(QIcon("icon:/imageeditor/images/nextframe.png")); connect(nextFrameAct,SIGNAL(triggered()),m_file,SLOT(jumpToNextFrame())); m_playAct = playAct; connect(zoomInAct,SIGNAL(triggered()),m_imageWidget,SLOT(zoomIn())); connect(zoomOutAct,SIGNAL(triggered()),m_imageWidget,SLOT(zoomOut())); connect(resetSizeAct,SIGNAL(triggered()),m_imageWidget,SLOT(resetSize())); connect(fitViewAct,SIGNAL(triggered()),m_imageWidget,SLOT(fitToView())); connect(playAct,SIGNAL(toggled(bool)),this,SLOT(toggledPlay(bool))); connect(m_imageWidget,SIGNAL(scaleFactorChanged(qreal)),this,SLOT(scaleFactorChanged(qreal))); connect(m_file,SIGNAL(frameChanged(int)),this,SLOT(frameChanged(int))); m_imageInfo = new QLabel; m_imageInfo->setText("32x32"); m_scaleInfo = new QLabel; m_scaleInfo->setText("100.00%"); m_frameLabel = new QLabel; m_frameLabel->setText(""); m_toolBar->addAction(zoomInAct); m_toolBar->addAction(zoomOutAct); m_toolBar->addAction(resetSizeAct); m_toolBar->addAction(fitViewAct); m_toolBar->addSeparator(); m_toolBar->addWidget(m_imageInfo); m_toolBar->addSeparator(); m_toolBar->addWidget(m_scaleInfo); m_toolBar->addSeparator(); m_mvToolBar->addAction(playAct); m_mvToolBar->addSeparator(); m_mvToolBar->addAction(prevFrameAct); m_mvToolBar->addAction(nextFrameAct); m_mvToolBar->addSeparator(); m_mvToolBar->addWidget(m_frameLabel); m_mvToolBar->addSeparator(); QHBoxLayout *toolLayout = new QHBoxLayout; toolLayout->setMargin(0); toolLayout->setSpacing(0); toolLayout->addWidget(m_toolBar); toolLayout->addWidget(m_mvToolBar); toolLayout->addWidget(m_navBar->toolBar()); toolLayout->addSpacing(0); QVBoxLayout *layout = new QVBoxLayout; layout->setMargin(0); layout->setSpacing(0); layout->addLayout(toolLayout); layout->addWidget(m_imageWidget); m_widget->setLayout(layout); connect(m_liteApp,SIGNAL(broadcast(QString,QString,QVariant)),this,SLOT(broadcast(QString,QString,QVariant))); } ImageEditor::~ImageEditor() { delete m_widget; delete m_file; } void ImageEditor::broadcast(const QString &module, const QString &id, const QVariant &param) { if (module == "liteeditor" && id == "font" && param != this->filePath()) { } else if (module == "liteeditor" && id == EDITOR_NAVBAR_VISIBLE) { m_navBar->toolBar()->setVisible(param.toBool()); } else if (module == "liteeditor" && id == EDITOR_TOOLBAR_VISIBLE) { } } QWidget *ImageEditor::widget() { return m_widget; } QString ImageEditor::name() const { return QFileInfo(m_file->filePath()).fileName(); } bool ImageEditor::open(const QString &filePath, const QString &mimeType) { bool b = m_file->open(filePath,mimeType); m_imageWidget->setImageItem(m_file->graphicsItem()); QSize sz = m_file->imageSize(); m_imageInfo->setText(QString("%1x%2").arg(sz.width()).arg(sz.height())); m_mvToolBar->setVisible(m_file->isMovie()); m_navBar->LoadPath(filePath); return b; } bool ImageEditor::reload() { if (!m_file->isValid()) { return false; } QString filePath = m_file->filePath(); QString mimeType = m_file->mimeType(); m_file->clear(); bool b = m_file->open(filePath,mimeType); m_imageWidget->setImageItem(m_file->graphicsItem()); QSize sz = m_file->imageSize(); m_imageInfo->setText(QString("%1x%2").arg(sz.width()).arg(sz.height())); m_mvToolBar->setVisible(m_file->isMovie()); return b; } bool ImageEditor::save() { return false; } bool ImageEditor::saveAs(const QString &filePath) { return false; } void ImageEditor::setReadOnly(bool b) { } bool ImageEditor::isReadOnly() const { return true; } bool ImageEditor::isModified() const { return false; } QString ImageEditor::filePath() const { return m_file->filePath(); } QString ImageEditor::mimeType() const { return m_file->mimeType(); } QByteArray ImageEditor::saveState() const { return QByteArray(); } bool ImageEditor::restoreState(const QByteArray &array) { return false; } void ImageEditor::onActive() { } void ImageEditor::scaleFactorChanged(qreal factor) { QString info = QString::number(factor * 100, 'f', 2) + QLatin1Char('%'); m_scaleInfo->setText(info); } void ImageEditor::toggledPlay(bool checked) { if (checked) { m_playAct->setText(tr("Pause movie")); m_playAct->setIcon(QIcon("icon:/imageeditor/images/pause.png")); } else { m_playAct->setText(tr("Play movie")); m_playAct->setIcon(QIcon("icon:/imageeditor/images/play.png")); } m_file->setPaused(!checked); } void ImageEditor::frameChanged(int frameNumber) { m_frameLabel->setText(QString("%1/%2").arg(frameNumber+1).arg(m_file->frameCount())); }
8,147
C++
.cpp
221
33.289593
114
0.701599
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,412
imageeditorfactory.cpp
visualfc_liteide/liteidex/src/plugins/imageeditor/imageeditorfactory.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: imageeditorfactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "imageeditorfactory.h" #include "mimetype/mimetype.h" #include "imageeditor.h" #include <QImageReader> #if QT_VERSION >= 0x050000 #include <QMimeDatabase> #include <QMimeType> #endif #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end ImageEditorFactory::ImageEditorFactory(IApplication *app, QObject *parent) : LiteApi::IEditorFactory(parent), m_liteApp(app) { #if QT_VERSION >= 0x050000 QList<QByteArray> supportFormats = QImageReader::supportedImageFormats(); QMimeDatabase db; foreach (QByteArray _type, QImageReader::supportedMimeTypes()) { QString type = QString::fromUtf8(_type); QMimeType mt = db.mimeTypeForName(type); if (!mt.isValid()) { continue; } QStringList patterns; foreach(QString fmt, mt.suffixes()) { if (supportFormats.contains(fmt.toUtf8())) { patterns << "*."+fmt; } } if (patterns.isEmpty()) { continue; } MimeType *mimeType = new MimeType; mimeType->setType(type); mimeType->setComment(mt.comment()); foreach (QString p, patterns) { mimeType->appendGlobPatterns(p); } m_liteApp->mimeTypeManager()->addMimeType(mimeType); m_mimeTypes.append(type); } #else QString mimeTypeList = "image/bmp:bmp;image/gif:gif;image/jpeg:jpg,jpeg;image/png:png;image/x-portable-bitmap:pbm;image/x-portable-graymap:pgm;image/x-portable-pixmap:ppm;image/x-xbitmap:xbm;image/x-xpixmap:xpm;image/svg+xml:svg;"; QList<QByteArray> supportFormats = QImageReader::supportedImageFormats(); foreach (QString mtype, mimeTypeList.split(";",qtSkipEmptyParts)) { QStringList ar = mtype.split(":",qtSkipEmptyParts); if (ar.size() != 2) { continue; } QString type = ar[0]; QStringList fmts = ar[1].split(",",qtSkipEmptyParts); QStringList patterns; foreach (QString fmt, fmts) { if (supportFormats.contains(fmt.toUtf8())) { patterns << "*."+fmt; } } if (patterns.isEmpty()) { continue; } MimeType *mimeType = new MimeType; mimeType->setType(type); mimeType->setComment(QString("%1 Image").arg(type)); foreach (QString p, patterns) { mimeType->appendGlobPatterns(p); } m_liteApp->mimeTypeManager()->addMimeType(mimeType); m_mimeTypes.append(type); } #endif } QStringList ImageEditorFactory::mimeTypes() const { return m_mimeTypes; } IEditor *ImageEditorFactory::open(const QString &fileName, const QString &mimeType) { ImageEditor *view = new ImageEditor(m_liteApp); if (!view->open(fileName,mimeType)) { delete view; return 0; } return view; } IEditor *ImageEditorFactory::create(const QString &contents, const QString &mimeType) { return 0; } QString ImageEditorFactory::id() const { return "ImageViewer"; } QString ImageEditorFactory::displayName() const { return tr("Image Viewer"); } bool ImageEditorFactory::testMimeType(const QString &mimeType) { return m_mimeTypes.contains(mimeType); }
4,548
C++
.cpp
129
30.093023
235
0.654954
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,413
imageeditorwidget.cpp
visualfc_liteide/liteidex/src/plugins/imageeditor/imageeditorwidget.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: imageeditorwidget.cpp // Creator: visualfc <visualfc@gmail.com> #include "imageeditorwidget.h" #include <QPainter> #include <QGraphicsItem> #include <QWheelEvent> #include <QGestureEvent> #include <QPinchGesture> #include <QPanGesture> #include <QScrollBar> #include <math.h> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end ImageEditorWidget::ImageEditorWidget() { setScene(new QGraphicsScene(this)); setTransformationAnchor(AnchorUnderMouse); setDragMode(RubberBandDrag); setViewportUpdateMode(FullViewportUpdate); setFrameShape(QFrame::NoFrame); setRenderHint(QPainter::SmoothPixmapTransform); QPixmap tilePixmap(20, 20); tilePixmap.fill(QColor(229,229,229)); QPainter tilePainter(&tilePixmap); QColor color(177, 177, 177); tilePainter.fillRect(0, 0, 10, 10, color); tilePainter.fillRect(10, 10, 10, 10, color); tilePainter.end(); setBackgroundBrush(tilePixmap); m_scaleFactor = 1.2; m_imageItem = 0; grabGesture(Qt::PinchGesture); // grabGesture(Qt::PanGesture); } ImageEditorWidget::~ImageEditorWidget() { if (m_imageItem) { this->scene()->removeItem(m_imageItem); } ungrabGesture(Qt::PinchGesture); //ungrabGesture(Qt::PanGesture); } void ImageEditorWidget::setImageItem(QGraphicsItem *item) { QGraphicsScene *s = this->scene(); s->clear(); m_imageItem = item; if (item) { item->setZValue(0); s->addItem(item); } this->resetSize(); } void ImageEditorWidget::drawBackground(QPainter *p, const QRectF &) { p->save(); p->resetTransform(); p->fillRect(viewport()->rect(),QColor(236,236,236)); if (m_imageItem) { p->setClipRegion(this->mapFromScene(this->sceneRect())); } p->drawTiledPixmap(viewport()->rect(), backgroundBrush().texture()); p->restore(); } void ImageEditorWidget::doScale(qreal factor) { qreal currentScale = transform().m11(); qreal newScale = currentScale * factor; qreal actualFactor = factor; // cap to 0.001 - 1000 if (newScale > 1000) actualFactor = 1000./currentScale; else if (newScale < 0.001) actualFactor = 0.001/currentScale; scale(actualFactor, actualFactor); emitScaleFactor(); QGraphicsPixmapItem *pix = dynamic_cast<QGraphicsPixmapItem*>(m_imageItem); if (pix) { pix->setTransformationMode( transform().m11() < 1 ? Qt::SmoothTransformation : Qt::FastTransformation); } } void ImageEditorWidget::wheelEvent(QWheelEvent *event) { if (event->modifiers() & Qt::ControlModifier) { const int delta = event->delta(); if (delta < 0) zoomOut(); else if (delta > 0) zoomIn(); return; } if (event->delta() != 0) { int delta = event->delta(); #if QT_VERSION >= 0x050700 if (event->inverted()) { delta = -event->delta(); } #endif if (event->orientation() == Qt::Horizontal) { this->horizontalScrollBar()->setValue(this->horizontalScrollBar()->value()-delta); } else { this->verticalScrollBar()->setValue(this->verticalScrollBar()->value()-delta); } } event->accept(); } bool ImageEditorWidget::gestureEvent(QGestureEvent *event) { if (QGesture *pinch = event->gesture(Qt::PinchGesture)) pinchTriggered(static_cast<QPinchGesture *>(pinch)); return true; } void ImageEditorWidget::pinchTriggered(QPinchGesture *gesture) { QPinchGesture::ChangeFlags changeFlags = gesture->changeFlags(); if (changeFlags & QPinchGesture::ScaleFactorChanged) { qreal value = gesture->property("scaleFactor").toReal(); doScale(value); } } bool ImageEditorWidget::event(QEvent *event) { if (event->type() == QEvent::Gesture) { return gestureEvent(static_cast<QGestureEvent*>(event)); } return QGraphicsView::event(event); } void ImageEditorWidget::zoomIn() { doScale(m_scaleFactor); } void ImageEditorWidget::zoomOut() { doScale(1.0 / m_scaleFactor); } void ImageEditorWidget::resetSize() { resetTransform(); emitScaleFactor(); } void ImageEditorWidget::fitToView() { //fitInView(m_imageItem, Qt::KeepAspectRatio); QRect viewRect = this->viewport()->rect(); QRect sceneRect = this->mapFromScene(this->sceneRect()).boundingRect(); qreal x = qreal(viewRect.width())/sceneRect.width(); qreal y = qreal(viewRect.height())/sceneRect.height(); //scale(x,y); qreal v = qMin(x,y); scale(v,v); emitScaleFactor(); } void ImageEditorWidget::emitScaleFactor() { qreal factor = transform().m11(); emit scaleFactorChanged(factor); } qreal ImageEditorWidget::scaleFactor() const { return transform().m11(); }
6,045
C++
.cpp
192
27.348958
95
0.672955
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,414
webkithtmlwidgetplugin.cpp
visualfc_liteide/liteidex/src/plugins/webkithtmlwidget/webkithtmlwidgetplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: webkithtmlwidgetplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "webkithtmlwidgetplugin.h" #include "webviewhtmlwidget.h" #include "webkitbrowser.h" #include <QtPlugin> #include <QFileDialog> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end WebKitHtmlWidgetPlugin::WebKitHtmlWidgetPlugin() { } bool WebKitHtmlWidgetPlugin::load(LiteApi::IApplication *app) { m_liteApp = app; LiteApi::IHtmlWidgetFactory *factory = new WebViewHtmlWidgetFactory(this); app->htmlWidgetManager()->addFactory(factory); app->htmlWidgetManager()->setDefaultClassName(factory->className()); /* WebKitBrowser *wb = new WebKitBrowser(app,this); app->toolWindowManager()->addToolWindow(Qt::RightDockWidgetArea, wb->widget(),"WebKitBrowser",tr("WebKitBrowser"), false); */ m_browser = new WebKitBrowser(app,this); m_browserAct = app->editorManager()->registerBrowser(m_browser); app->actionManager()->insertViewMenu(LiteApi::ViewMenuBrowserPos,m_browserAct); // // QMenu *fileMenu = app->actionManager()->loadMenu("menu/file"); // IActionContext *actionContext = app->actionManager()->getActionContext(app,"App"); // LiteApi::ActionInfo *info = actionContext->actionInfo("AddFolder"); // if (fileMenu && info && info->action) { // QAction *openUrl = new QAction(tr("Open File With WebKit ..."),this); // connect(openUrl,SIGNAL(triggered()),this,SLOT(openHtmlWithWebkit())); // fileMenu->insertAction(info->action,openUrl); // } return true; } void WebKitHtmlWidgetPlugin::openHtmlWithWebkit() { QString dir = m_liteApp->settings()->value("WebKitBrowser/home","").toString(); QString filePath = QFileDialog::getOpenFileName(m_liteApp->mainWindow(),tr("Open Html or Markdown File"),dir, "Html or Markdown File (*.html *.htm *.md *.markdown);;Html File (*.html *.htm);; Markdown File (*.md *.markdown)"); if (!filePath.isEmpty()) { m_liteApp->settings()->setValue("WebKitBrowser/home",QFileInfo(filePath).absolutePath()); m_liteApp->editorManager()->activeBrowser(m_browser); m_browser->loadUrl(QUrl::fromLocalFile(filePath)); } } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
3,642
C++
.cpp
80
41.25
168
0.669665
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,415
webviewhtmlwidget.cpp
visualfc_liteide/liteidex/src/plugins/webkithtmlwidget/webviewhtmlwidget.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: webviewhtmlwidget.cpp // Creator: visualfc <visualfc@gmail.com> #include "webviewhtmlwidget.h" #include <QWebView> #include <QWebPage> #include <QWebFrame> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end WebViewHtmlWidget::WebViewHtmlWidget(QObject *parent) : IHtmlWidget(parent) { m_widget = new QWebView; m_widget->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks); connect(m_widget,SIGNAL(linkClicked(QUrl)),this,SIGNAL(linkClicked(QUrl))); connect(m_widget->page(),SIGNAL(linkHovered(QString,QString,QString)),this,SLOT(webLinkHovered(QString,QString,QString))); connect(m_widget->page(),SIGNAL(loadFinished(bool)),this,SIGNAL(loadFinished(bool))); connect(m_widget->page()->mainFrame(),SIGNAL(contentsSizeChanged(QSize)),this,SIGNAL(contentsSizeChanged())); } WebViewHtmlWidget::~WebViewHtmlWidget() { // if (m_widget) { // delete m_widget; // } } QWidget *WebViewHtmlWidget::widget() const { return m_widget; } QString WebViewHtmlWidget::className() const { return "QWebView"; } void WebViewHtmlWidget::setSearchPaths(const QStringList&) { } void WebViewHtmlWidget::setHtml(const QString &html, const QUrl &url) { m_widget->setHtml(html,url); } QUrl WebViewHtmlWidget::url() const { return m_widget->url(); } void WebViewHtmlWidget::clear() { m_widget->setHtml(""); } void WebViewHtmlWidget::scrollToAnchor(const QString &anchor) { m_widget->page()->mainFrame()->scrollToAnchor(anchor); emit anchorChanged(anchor); } void WebViewHtmlWidget::setScrollBarValue(Qt::Orientation orientation, int value) { m_widget->page()->mainFrame()->setScrollBarValue(orientation,value); } int WebViewHtmlWidget::scrollBarValue(Qt::Orientation orientation) const { return m_widget->page()->mainFrame()->scrollBarValue(orientation); } int WebViewHtmlWidget::scrollBarMinimum(Qt::Orientation orientation) const { return m_widget->page()->mainFrame()->scrollBarMinimum(orientation); } int WebViewHtmlWidget::scrollBarMaximum(Qt::Orientation orientation) const { return m_widget->page()->mainFrame()->scrollBarMaximum(orientation); } QString WebViewHtmlWidget::selectedText() const { return m_widget->selectedText(); } bool WebViewHtmlWidget::findText(const QString &exp, QTextDocument::FindFlags options) { QWebPage::FindFlags flag = QWebPage::HighlightAllOccurrences; if ( (options & QTextDocument::FindBackward) == QTextDocument::FindBackward) { flag |= QWebPage::FindBackward; } if ( (options & QTextDocument::FindCaseSensitively) == QTextDocument::FindCaseSensitively ) { flag |= QWebPage::FindCaseSensitively; } return m_widget->findText(exp,flag); } #ifndef QT_NO_PRINTER void WebViewHtmlWidget::print(QPrinter *printer) { m_widget->print(printer); } #endif void WebViewHtmlWidget::webLinkHovered(const QString &link, const QString&, const QString&) { emit linkHovered(QUrl(link)); } WebViewHtmlWidgetFactory::WebViewHtmlWidgetFactory(QObject *parent) : IHtmlWidgetFactory(parent) { } QString WebViewHtmlWidgetFactory::className() const { return "QWebView"; } IHtmlWidget *WebViewHtmlWidgetFactory::create(QObject *parent) { return new WebViewHtmlWidget(parent); } IHtmlDocument *WebViewHtmlWidgetFactory::createDocument(QObject *parent) { return new WebPageHtmlDocument(parent); } WebPageHtmlDocument::WebPageHtmlDocument(QObject *parent) : IHtmlDocument(parent) { m_doc = new QWebPage(this); connect(m_doc->mainFrame(),SIGNAL(loadFinished(bool)),this,SIGNAL(loadFinished(bool))); } WebPageHtmlDocument::~WebPageHtmlDocument() { delete m_doc; } void WebPageHtmlDocument::setHtml(const QString &html, const QUrl &url) { m_doc->mainFrame()->setHtml(html,url); } #ifndef QT_NO_PRINTER void WebPageHtmlDocument::print(QPrinter *printer) { m_doc->mainFrame()->print(printer); } #endif QString WebPageHtmlDocument::toHtml() const { return m_doc->mainFrame()->toHtml(); } QString WebPageHtmlDocument::toPlainText() const { return m_doc->mainFrame()->toPlainText(); }
5,336
C++
.cpp
164
30.134146
126
0.737651
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,416
webkitbrowser.cpp
visualfc_liteide/liteidex/src/plugins/webkithtmlwidget/webkitbrowser.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: webkitbrowser.cpp // Creator: visualfc <visualfc@gmail.com> #include "webkitbrowser.h" #include "cmark/libcmark.h" #include <QWebView> #include <QNetworkProxyFactory> #include <QToolBar> #include <QLineEdit> #include <QVBoxLayout> #include <QFile> #include <QFileInfo> #include <QStatusBar> #include <QProgressBar> #include <QRegExp> #include <QTextCodec> #include <QFileDialog> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end WebKitBrowser::WebKitBrowser(LiteApi::IApplication *app, QObject *parent) : LiteApi::IWebKitBrowser(parent), m_liteApp(app) { QNetworkProxyFactory::setUseSystemConfiguration(true); m_widget = new QWidget; m_view = new QWebView; m_view->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks); m_locationEdit = new QLineEdit; m_locationEdit->setSizePolicy(QSizePolicy::Expanding, m_locationEdit->sizePolicy().verticalPolicy()); connect(m_locationEdit, SIGNAL(returnPressed()), this,SLOT(changeLocation())); connect(m_view, SIGNAL(loadFinished(bool)), this,SIGNAL(loadFinished(bool))); connect(m_view, SIGNAL(loadFinished(bool)), this, SLOT(loadUrlFinished(bool))); connect(m_view, SIGNAL(linkClicked(QUrl)),this, SLOT(linkClicked(QUrl))); connect(m_view->page(), SIGNAL(linkHovered(QString,QString,QString)),this,SLOT(linkHovered(QString,QString,QString))); connect(m_view,SIGNAL(statusBarMessage(QString)),this,SLOT(statusBarMessage(QString))); connect(m_view,SIGNAL(loadStarted()),this,SLOT(loadStarted())); connect(m_view,SIGNAL(loadProgress(int)),this,SLOT(loadProgress(int))); QToolBar *toolBar = new QToolBar(tr("Navigation")); toolBar->setIconSize(QSize(16,16)); QAction *openFile = new QAction(tr("Open Html File"),this); openFile->setIcon(QIcon("icon:images/openfile.png")); connect(openFile,SIGNAL(triggered()),this,SLOT(openHtmlFile())); toolBar->addAction(openFile); toolBar->addSeparator(); toolBar->addAction(m_view->pageAction(QWebPage::Back)); toolBar->addAction(m_view->pageAction(QWebPage::Forward)); QAction *reload = m_view->pageAction(QWebPage::Reload); toolBar->addAction(reload); connect(reload,SIGNAL(triggered()),this,SLOT(reloadUrl())); toolBar->addAction(m_view->pageAction(QWebPage::Stop)); toolBar->addWidget(m_locationEdit); m_progressBar = new QProgressBar; m_progressBar->hide(); m_progressBar->setRange(0,100); QVBoxLayout *layout = new QVBoxLayout; layout->setMargin(0); layout->setSpacing(0); layout->addWidget(toolBar); layout->addWidget(m_view); layout->addWidget(m_progressBar); m_widget->setLayout(layout); m_liteApp->extension()->addObject("LiteApp.IWebKitBrowser",this); } WebKitBrowser::~WebKitBrowser() { if (m_progressBar) { delete m_progressBar; } if (m_widget) { delete m_widget; } } QWidget *WebKitBrowser::widget() { return m_widget; } QString WebKitBrowser::name() const { return tr("WebKitBrowser"); } QString WebKitBrowser::mimeType() const { return "browser/webkit"; } void WebKitBrowser::openUrl(const QUrl &url) { loadUrl(url); } static QByteArray html_data = "<html>" "<head>" "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>" "<title>__HTML_TITLE__</title>" "</head>" "<body>" "__HTML_CONTENT__" "</body>" "</html>"; void WebKitBrowser::changeLocation() { QString text = m_locationEdit->text(); if (text.isEmpty()) { return; } if (!text.startsWith("http:") && !text.startsWith("file:") && !text.startsWith("https:")) { text = "http://"+text; } loadUrl(text); } void WebKitBrowser::adjustLocation() { m_locationEdit->setText(m_view->url().toString()); } void WebKitBrowser::loadUrlFinished(bool b) { m_progressBar->hide(); QString url = m_view->url().toString(); if (b) { m_locationEdit->setText(url); } else { QString context = QString(tr("False load %1 !")).arg(url); #if QT_VERSION >= 0x050000 QString html = context.toHtmlEscaped(); #else QString html = Qt::escape(context); #endif QString data = html_data; data.replace("__HTML_TITLE__","LoadFalse"); data.replace("__HTML_CONTENT__",QString("<pre>%1</pre>").arg(html)); m_view->setHtml(data,url); } } void WebKitBrowser::linkClicked(QUrl url) { this->loadUrl(url); } void WebKitBrowser::loadUrl(const QUrl &url) { m_liteApp->mainWindow()->statusBar()->clearMessage(); if (url.scheme() == "http" || url.scheme() == "https") { m_view->load(url); } else if (url.scheme() == "file") { QFileInfo info(url.toLocalFile()); #ifdef Q_OS_WIN QString file = info.filePath(); if (file.length() > 4 && file[0] == '/' && file[1] == '/' && file[2].isLetter() && file[3] == '/') { info.setFile(file[2]+":"+file.right(file.length()-3)); } #endif if (info.exists()) { QFile file(info.filePath()); if (file.open(QFile::ReadOnly)) { QByteArray ba = file.readAll(); QString ext = info.suffix().toLower(); if (ext == "html" || ext == "htm") { //QTextCodec *codec = QTextCodec::codecForHtml(ba,QTextCodec::codecForName("utf-8")); //m_view->setHtml(codec->toUnicode(ba),url); m_view->load(url); } else if (ext == "md") { QString data = html_data; data.replace("__HTML_TITLE__",info.fileName()); data.replace("__HTML_CONTENT__",QString::fromUtf8(md2html(ba))); m_view->setHtml(data,url); } else { QTextCodec *codec = QTextCodec::codecForUtfText(ba,QTextCodec::codecForName("utf-8")); #if QT_VERSION >= 0x050000 QString html = codec->toUnicode(ba).toHtmlEscaped(); #else QString html = Qt::escape(codec->toUnicode(ba)); #endif QString data = html_data; data.replace("__HTML_TITLE__",info.fileName()); data.replace("__HTML_CONTENT__",QString("<pre>%1</pre>").arg(html)); m_view->setHtml(data,url); } } } } m_view->setFocus(); } void WebKitBrowser::linkHovered(const QString & link, const QString & /*title*/, const QString & /*textContent*/) { m_liteApp->mainWindow()->statusBar()->showMessage(link); } void WebKitBrowser::statusBarMessage(const QString &msg) { m_liteApp->mainWindow()->statusBar()->showMessage(msg); } void WebKitBrowser::loadStarted() { m_progressBar->show(); } void WebKitBrowser::loadProgress(int value) { m_progressBar->setValue(value); } void WebKitBrowser::openHtmlFile() { QString dir = m_liteApp->settings()->value("WebKitBrowser/home","").toString(); QString filePath = QFileDialog::getOpenFileName(m_liteApp->mainWindow(),tr("Open Html or Markdown File"),dir, "Html or Markdown File (*.html *.htm *.md *.markdown);;Html File (*.html *.htm);; Markdown File (*.md *.markdown)"); if (!filePath.isEmpty()) { m_liteApp->settings()->setValue("WebKitBrowser/home",QFileInfo(filePath).absolutePath()); loadUrl(QUrl::fromLocalFile(filePath)); } } void WebKitBrowser::reloadUrl() { this->loadUrl(m_view->url()); }
8,830
C++
.cpp
239
31.309623
168
0.63681
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,417
golangpresentedit.cpp
visualfc_liteide/liteidex/src/plugins/golangpresent/golangpresentedit.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangpresentedit.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangpresentedit.h" #include "editorutil/editorutil.h" #include "fileutil/fileutil.h" #include "liteenvapi/liteenvapi.h" #include "liteeditorapi/liteeditorapi.h" #include "exportdialog.h" #include <QToolBar> #include <QMenu> #include <QAction> #include <QTextCursor> #include <QTextBlock> #include <QProcess> #include <QFileDialog> #include <QDesktopServices> #include <QRegExp> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangPresentEdit::GolangPresentEdit(LiteApi::IApplication *app, LiteApi::IEditor *editor, QObject *parent) : QObject(parent), m_liteApp(app), m_htmldoc(0), m_process(0) { m_editor = LiteApi::getLiteEditor(editor); if (!m_editor) { return; } m_ed = LiteApi::getPlainTextEdit(editor); m_editor->setLineWrap(true); connect(m_liteApp->editorManager(),SIGNAL(editorSaved(LiteApi::IEditor*)),this,SLOT(editorSaved(LiteApi::IEditor*))); LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(this,"GoSlide"); QAction *s1 = new QAction(QIcon("icon:golangpresent/images/s1.png"),tr("Section (s1)"),this); actionContext->regAction(s1,"Section","Ctrl+1"); QAction *s2 = new QAction(QIcon("icon:golangpresent/images/s2.png"),tr("Subsection (s2)"),this); actionContext->regAction(s2,"Subsection","Ctrl+2"); QAction *s3 = new QAction(QIcon("icon:golangpresent/images/s3.png"),tr("Sub-subsection (s3)"),this); actionContext->regAction(s3,"Sub-subsection","Ctrl+3"); QAction *bold = new QAction(QIcon("icon:golangpresent/images/bold.png"),tr("Bold"),this); actionContext->regAction(bold,"Bold",QKeySequence::Bold); QAction *italic = new QAction(QIcon("icon:golangpresent/images/italic.png"),tr("Italic"),this); actionContext->regAction(italic,"Italic",QKeySequence::Italic); QAction *code = new QAction(QIcon("icon:golangpresent/images/code.png"),tr("Inline Code"),this); actionContext->regAction(code,"InlineCode","Ctrl+K"); QAction *bullets = new QAction(QIcon("icon:golangpresent/images/bullets.png"),tr("Switch Bullets"),this); actionContext->regAction(bullets,"Switch Bullets","Ctrl+Shift+U"); QAction *comment = new QAction(tr("Comment/Uncomment Selection"),this); actionContext->regAction(comment,"Comment","Ctrl+/"); QAction *exportHtml = new QAction(QIcon("icon:golangpresent/images/exporthtml.png"),tr("Export HTML"),this); actionContext->regAction(exportHtml,"Export HTML",""); QAction *verify = new QAction(QIcon("icon:golangpresent/images/verify.png"),tr("Verify Present"),this); actionContext->regAction(verify,"Verify Present",""); //QAction *exportPdf = new QAction(QIcon("icon:golangpresent/images/exportpdf.png"),tr("Export PDF"),this); //actionContext->regAction(exportPdf,"Export PDF",""); connect(m_editor,SIGNAL(destroyed()),this,SLOT(deleteLater())); connect(s1,SIGNAL(triggered()),this,SLOT(s1())); connect(s2,SIGNAL(triggered()),this,SLOT(s2())); connect(s3,SIGNAL(triggered()),this,SLOT(s3())); connect(bold,SIGNAL(triggered()),this,SLOT(bold())); connect(italic,SIGNAL(triggered()),this,SLOT(italic())); connect(code,SIGNAL(triggered()),this,SLOT(code())); connect(bullets,SIGNAL(triggered()),this,SLOT(bullets())); connect(comment,SIGNAL(triggered()),this,SLOT(comment())); connect(exportHtml,SIGNAL(triggered()),this,SLOT(exportHtml())); connect(verify,SIGNAL(triggered()),this,SLOT(verify())); //connect(exportPdf,SIGNAL(triggered()),this,SLOT(exportPdf())); QToolBar *toolBar = LiteApi::getEditToolBar(editor); if (toolBar) { toolBar->addSeparator(); toolBar->addAction(s1); toolBar->addAction(s2); toolBar->addAction(s3); toolBar->addSeparator(); toolBar->addAction(bold); toolBar->addAction(italic); toolBar->addAction(code); toolBar->addSeparator(); toolBar->addAction(bullets); toolBar->addSeparator(); toolBar->addAction(verify); toolBar->addSeparator(); toolBar->addAction(exportHtml); //toolBar->addAction(exportPdf); } QMenu *menu = LiteApi::getEditMenu(editor); if (menu) { menu->addSeparator(); menu->addAction(s1); menu->addAction(s2); menu->addAction(s3); menu->addSeparator(); menu->addAction(bold); menu->addAction(italic); menu->addAction(code); menu->addSeparator(); menu->addAction(bullets); menu->addSeparator(); menu->addAction(comment); menu->addSeparator(); menu->addAction(verify); menu->addSeparator(); menu->addAction(exportHtml); //menu->addAction(exportPdf); } menu = LiteApi::getContextMenu(editor); if (menu) { menu->addSeparator(); menu->addAction(s1); menu->addAction(s2); menu->addAction(s3); menu->addSeparator(); menu->addAction(bold); menu->addAction(italic); menu->addAction(code); menu->addSeparator(); menu->addAction(bullets); menu->addSeparator(); menu->addAction(comment); } } void GolangPresentEdit::editorSaved(LiteApi::IEditor *editor) { if (editor == m_editor) { this->verify(); } } void GolangPresentEdit::s1() { EditorUtil::InsertHead(m_ed,"* "); } void GolangPresentEdit::s2() { EditorUtil::InsertHead(m_ed,"** "); } void GolangPresentEdit::s3() { EditorUtil::InsertHead(m_ed,"*** "); } void GolangPresentEdit::bold() { EditorUtil::MarkSelection(m_ed,"*"); } void GolangPresentEdit::italic() { EditorUtil::MarkSelection(m_ed,"_"); } void GolangPresentEdit::code() { EditorUtil::MarkSelection(m_ed,"`"); } void GolangPresentEdit::bullets() { EditorUtil::SwitchHead(m_ed,"- ",QStringList() << "- "); } void GolangPresentEdit::comment() { EditorUtil::SwitchHead(m_ed,"# ",QStringList() << "# " << "#"); } void GolangPresentEdit::verify() { startExportHtmlDoc(EXPORT_TYPE_VERIFY); } void GolangPresentEdit::exportHtml() { startExportHtmlDoc(EXPORT_TYPE_HTML); } void GolangPresentEdit::exportPdf() { startExportHtmlDoc(EXPORT_TYPE_PDF); } void GolangPresentEdit::extOutput(const QByteArray &data, bool bError) { if (!bError) { m_exportData.append(data); } else { QString msg = QString::fromUtf8(data); m_editor->setNavigateHead(LiteApi::EditorNavigateError,msg); QRegExp re("(\\w?:?[\\w\\d_@\\-\\\\/\\.]+):(\\d+):"); if ((re.indexIn(msg)>=0) && re.captureCount() >= 2) { bool ok = false; int line = re.cap(2).toInt(&ok); if (ok) { QString errmsg = re.cap(0)+"\n"+msg.mid(re.cap(0).length()).trimmed(); m_editor->insertNavigateMark(line-1,LiteApi::EditorNavigateError,errmsg, GOPRESENT_TAG); m_errorMsg.append(errmsg); } } else { m_errorMsg.append(msg); } } } void GolangPresentEdit::extFinish(bool error, int code, QString /*msg*/) { int exportType = m_process->userData(0).toInt(); if (exportType == EXPORT_TYPE_VERIFY) { if (!error && code == 0) { m_editor->setNavigateHead(LiteApi::EditorNavigateNormal,tr("Present verify success")); } else { m_editor->setNavigateHead(LiteApi::EditorNavigateError,tr("Present verify false")+"\n"+m_errorMsg.join("\n")); } } else if (error || code != 0) { m_liteApp->appendLog("GolangPresent",m_errorMsg.join(";"),true); } if (!error && code == 0) { if (exportType == EXPORT_TYPE_HTML) { QFileInfo info(m_editor->filePath()); ExportDialog dlg(m_liteApp->mainWindow()); dlg.setWindowTitle(tr("Export HTML")); dlg.setFileName(info.completeBaseName()+".html"); if (!m_exportName.isEmpty()) { dlg.setFileName(m_exportName); } if (dlg.exec() == QDialog::Rejected) { return; } QString exportFile = dlg.fileName(); if (exportFile.isEmpty()) { return; } m_exportName = exportFile; QFileInfo exportInfo(exportFile); QString ext = exportInfo.suffix().toLower(); if (ext != "html" && ext != "htm") { exportInfo = QFileInfo(exportFile += ".html"); } if (!exportInfo.isAbsolute()) { exportInfo = QFileInfo(info.absolutePath(),exportInfo.fileName()); } QFile file(exportInfo.filePath()); if (!file.open(QFile::WriteOnly)) { return; } file.write(m_exportData); QDir dir(exportInfo.absolutePath()); dir.mkdir("static"); dir.mkdir("js"); FileUtil::CopyDirectory(m_liteApp->resourcePath()+"/packages/gopresent/static",dir.path()+"/static"); FileUtil::CopyDirectory(m_liteApp->resourcePath()+"/packages/gopresent/js",dir.path()+"/js"); m_liteApp->appendLog("GoPresent","export "+exportInfo.filePath(),false); if (dlg.isExportAndView()) { LiteApi::IWebKitBrowser *browser = LiteApi::getWebKitBrowser(m_liteApp); if (browser) { m_liteApp->editorManager()->activeBrowser(browser); browser->openUrl(QUrl::fromLocalFile(exportInfo.filePath())); } else { QDesktopServices::openUrl(QUrl::fromLocalFile(exportInfo.filePath())); } } } else if (exportType == EXPORT_TYPE_PDF) { QString init = QFileInfo(m_editor->filePath()).absolutePath()+"/"+QFileInfo(m_editor->filePath()).completeBaseName()+".pdf"; m_pdfFileName = QFileDialog::getSaveFileName(m_liteApp->mainWindow(),tr("Export PDF"),init,"*.pdf"); if (m_pdfFileName.isEmpty()) { return; } if (!m_htmldoc) { m_htmldoc = m_liteApp->htmlWidgetManager()->createDocument(this); connect(m_htmldoc,SIGNAL(loadFinished(bool)),this,SLOT(loadHtmlFinished(bool))); } QUrl url = QUrl::fromLocalFile(m_liteApp->resourcePath()+"/packages/gopresent/export.html"); m_htmldoc->setHtml(QString::fromUtf8(m_exportData),url); } } } void GolangPresentEdit::loadHtmlFinished(bool b) { if (!b) { m_liteApp->appendLog("GolangPresent","Failed export PDF document!"); return; } #ifndef QT_NO_PRINTER QPrinter printer(QPrinter::HighResolution); printer.setOutputFormat(QPrinter::PdfFormat); printer.setCreator("LiteIDE"); printer.setOutputFileName(m_pdfFileName); m_htmldoc->print(&printer); QDesktopServices::openUrl(QUrl::fromLocalFile(QFileInfo(m_pdfFileName).path())); #endif } bool GolangPresentEdit::startExportHtmlDoc(EXPORT_TYPE type) { m_liteApp->editorManager()->saveEditor(m_editor); QString cmd = LiteApi::getGotools(m_liteApp); QFileInfo info(m_editor->filePath()); if (!m_process) { m_process = new ProcessEx(this); m_process->setWorkingDirectory(info.absolutePath()); connect(m_process,SIGNAL(extOutput(QByteArray,bool)),this,SLOT(extOutput(QByteArray,bool))); connect(m_process,SIGNAL(extFinish(bool,int,QString)),this,SLOT(extFinish(bool,int,QString))); } m_process->stopAndWait(100,2000); m_exportData.clear(); m_errorMsg.clear(); m_process->setUserData(0,type); m_editor->clearAllNavigateMark(LiteApi::EditorNavigateBad, GOPRESENT_TAG); if (type == EXPORT_TYPE_VERIFY) { m_process->startEx(cmd,QStringList() << "gopresent" << "-v" << "-i" << info.fileName().toUtf8()); } else { m_process->startEx(cmd,QStringList() << "gopresent" << "-stdout" << "-i " << info.fileName().toUtf8()); } return true; }
13,350
C++
.cpp
327
34.16208
136
0.640129
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,418
exportdialog.cpp
visualfc_liteide/liteidex/src/plugins/golangpresent/exportdialog.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: exportdialog.cpp // Creator: visualfc <visualfc@gmail.com> #include "exportdialog.h" #include "ui_exportdialog.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end ExportDialog::ExportDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ExportDialog), m_bView(false) { ui->setupUi(this); } ExportDialog::~ExportDialog() { delete ui; } QString ExportDialog::fileName() const { return ui->fileName->text(); } void ExportDialog::setFileName(const QString &text) { ui->fileName->setText(text); } void ExportDialog::on_exportButton_clicked() { m_bView = false; this->accept(); } void ExportDialog::on_exportAndViewButton_clicked() { m_bView = true; this->accept(); }
1,971
C++
.cpp
62
29.564516
82
0.675605
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,419
golangpresentplugin.cpp
visualfc_liteide/liteidex/src/plugins/golangpresent/golangpresentplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangpresentplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangpresentplugin.h" #include "golangpresentedit.h" #include <QtPlugin> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangPresentPlugin::GolangPresentPlugin() { } bool GolangPresentPlugin::load(LiteApi::IApplication *app) { m_liteApp = app; connect(m_liteApp->editorManager(),SIGNAL(editorCreated(LiteApi::IEditor*)),this,SLOT(editorCreated(LiteApi::IEditor*))); return true; } void GolangPresentPlugin::editorCreated(LiteApi::IEditor *editor) { if (!editor || editor->mimeType() != "text/x-goslide") { return; } new GolangPresentEdit(m_liteApp,editor,this); } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
2,018
C++
.cpp
53
35.90566
125
0.691837
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,420
makefileprojectplugin.cpp
visualfc_liteide/liteidex/src/plugins/makefileproject/makefileprojectplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: makefileprojectplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "makefileprojectplugin.h" #include "makefilefilefactory.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end MakefileProjectPlugin::MakefileProjectPlugin() { m_info->setId("plugin/makefileproject"); m_info->setName("MakefileProject"); m_info->setAuthor("visualfc"); m_info->setVer("x2"); m_info->setInfo("Project Makefile Plugin"); } bool MakefileProjectPlugin::initWithApp(LiteApi::IApplication *app) { if (!LiteApi::IPlugin::initWithApp(app)) { return false; } MakefileFileFactory *factory = new MakefileFileFactory(app,this); app->projectManager()->addFactory(factory); return true; } Q_EXPORT_PLUGIN(MakefileProjectPlugin)
2,016
C++
.cpp
51
36.960784
82
0.686925
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,421
makefilefilefactory.cpp
visualfc_liteide/liteidex/src/plugins/makefileproject/makefilefilefactory.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: makefilefilefactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "makefilefilefactory.h" #include "makefileproject.h" #include "makefilefile.h" #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end MakefileFileFactory::MakefileFileFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IProjectFactory(parent), m_liteApp(app) { m_mimeTypes.append("text/x-makefile"); m_mimeTypes.append("text/x-gomake"); } QStringList MakefileFileFactory::mimeTypes() const { return m_mimeTypes; } LiteApi::IProject *MakefileFileFactory::open(const QString &fileName, const QString &mimeType) { if (!m_mimeTypes.contains(mimeType)) { return 0; } MakefileProject *project = new MakefileProject(m_liteApp); project->setModelFile(new MakefileFile(m_liteApp,project)); if (!project->open(fileName,mimeType)) { delete project; return 0; } return project; } bool MakefileFileFactory::findTargetInfo(const QString &fileName, const QString &mimeType, QMap<QString,QString>& targetInfo) const { if (!m_mimeTypes.contains(mimeType)) { return false; } MakefileFile *file = new MakefileFile(m_liteApp,0); bool b = file->open(fileName,mimeType); if (b) { targetInfo = file->targetInfo(); } delete file; return b; }
2,603
C++
.cpp
72
33.027778
131
0.685941
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,422
makefileproject.cpp
visualfc_liteide/liteidex/src/plugins/makefileproject/makefileproject.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: makefileproject.cpp // Creator: visualfc <visualfc@gmail.com> #include "makefileproject.h" #include "makefilefile.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end MakefileProject::MakefileProject(LiteApi::IApplication *app) : ModelProjectImpl(app) { }
1,520
C++
.cpp
37
39.216216
82
0.673649
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,423
makefilefile.cpp
visualfc_liteide/liteidex/src/plugins/makefileproject/makefilefile.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: makefilefile.cpp // Creator: visualfc <visualfc@gmail.com> #include "makefilefile.h" #include <QStandardItem> #include <QFileInfo> #include <QFile> #include <QDir> #include "fileutil/fileutil.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end MakefileFile::MakefileFile(LiteApi::IApplication *app,QObject *parent) : ModelFileImpl(app,parent) { } bool MakefileFile::loadFile(const QString &fileName) { QFile file(fileName); if (!file.open(QIODevice::ReadOnly|QIODevice::Text)) { return false; } QMap<QString,QStringList> context = FileUtil::readFileContext(&file); file.close(); if (context.isEmpty()) { //return false; } m_context = context; if (m_context.contains("GOFILES") || m_context.contains("CGOFILES")) { m_mimeType = "text/x-gomake"; } return true; } void MakefileFile::updateModel() { m_model->clear(); m_fileNameList.clear(); m_filePathList.clear(); QStandardItem *item = new QStandardItem(QFileInfo(m_fileName).fileName()); item->setData(ItemProFile); item->setIcon(QIcon("icon:images/projectitem.png")); m_model->appendRow(item); m_filePathList.append(m_fileName); QMap<QString,QString> fileMap; fileMap.insert("GOFILES",tr("GOFILES")); fileMap.insert("CGOFILES",tr("CGOFILES")); fileMap.insert("HEADERS",tr("Headers")); fileMap.insert("SOURCES",tr("Sources")); QMapIterator<QString,QString> i(fileMap); while(i.hasNext()) { i.next(); QStringList files = this->values(i.key()); if (!files.isEmpty()) { QStandardItem *folder = new QStandardItem(i.value()); folder->setData(ItemFolder); folder->setIcon(QIcon("icon:images/folderitem.png")); m_model->appendRow(folder); foreach(QString file, files) { QStandardItem *fileItem = new QStandardItem(file); fileItem->setData(ItemFile); fileItem->setIcon(QIcon("icon:images/fileitem.png")); folder->appendRow(fileItem); m_fileNameList.append(file); m_filePathList.append(fileNameToFullPath(file)); } } } } QString MakefileFile::target() const { QString target = QFileInfo(m_fileName).fileName(); QString val = value("TARG"); if (!val.isEmpty()) { target = val; } return target; } QMap<QString,QString> MakefileFile::targetInfo() const { QMap<QString,QString> m; if (m_fileName.isEmpty()) { return m; } QFileInfo info(m_fileName); QString target = info.fileName(); QString val = this->value("TARG"); if (!val.isEmpty()) { target = val; } m.insert("TARGETNAME",target); m.insert("TARGETPATH",QFileInfo(QDir(info.path()),target).filePath()); m.insert("TARGETDIR",info.path()); m.insert("WORKDIR",info.path()); return m; } QString MakefileFile::targetPath() const { QString target = QFileInfo(m_fileName).fileName(); QString val = value("TARG"); if (!val.isEmpty()) { target = val; } QString workPath = QFileInfo(m_fileName).absolutePath(); if (!workPath.isEmpty()) { target = QFileInfo(QDir(workPath),target).absoluteFilePath(); } return target; }
4,562
C++
.cpp
134
29.097015
82
0.645154
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,424
markdownplugin.cpp
visualfc_liteide/liteidex/src/plugins/markdown/markdownplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: markdownplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "markdownplugin.h" #include "htmlpreview.h" #include "markdownedit.h" #include "markdownbatchbrowser.h" #include <QtPlugin> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end MarkdownPlugin::MarkdownPlugin() { } bool MarkdownPlugin::load(LiteApi::IApplication *app) { m_liteApp = app; QAction *act = m_liteApp->editorManager()->registerBrowser(new MarkdownBatchBrowser(m_liteApp,this)); m_liteApp->actionManager()->insertViewMenu(LiteApi::ViewMenuBrowserPos,act); connect(m_liteApp->editorManager(),SIGNAL(editorCreated(LiteApi::IEditor*)),this,SLOT(editorCreated(LiteApi::IEditor*))); new HtmlPreview(m_liteApp,this); return true; } void MarkdownPlugin::editorCreated(LiteApi::IEditor *editor) { if (!editor || editor->mimeType() != "text/x-markdown") { return; } new MarkdownEdit(m_liteApp,editor,this); } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
2,284
C++
.cpp
59
36.389831
125
0.698105
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,425
htmlpreview.cpp
visualfc_liteide/liteidex/src/plugins/markdown/htmlpreview.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: htmlpreview.cpp // Creator: visualfc <visualfc@gmail.com> #include "markdown_global.h" #include "htmlpreview.h" #include "cmark/libcmark.h" #include <QScrollBar> #include <QMenu> #include <QAction> #include <QActionGroup> #include <QFileInfo> #include <QTextCodec> #include <QFile> #include <QDir> #include <QUrl> #include <QVBoxLayout> #include <QMessageBox> #include <QFileDialog> #include <QStatusBar> #include <QToolTip> #include <QTimer> #ifndef QT_NO_PRINTER #include <QPrinter> #include <QPrintPreviewDialog> #endif //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end HtmlPreview::HtmlPreview(LiteApi::IApplication *app,QObject *parent) : QObject(parent), m_liteApp(app) { m_curEditor = 0; m_curTextEditor = 0; m_widget = new QWidget; m_htmlWidget = 0; m_bWebkit = false; m_htmlUpdateTimer = new QTimer(this); m_htmlUpdateTimer->setSingleShot(true); m_htmlUpdateTimer->setInterval(500); m_cssMenu = new QMenu(tr("Page Style")); m_cssMenu->setIcon(QIcon("icon:/markdown/images/css.png")); m_cssActGroup = new QActionGroup(this); m_reloadAct = new QAction(QIcon("icon:images/reload.png"),tr("Reload"),this); m_exportHtmlAct = new QAction(QIcon("icon:liteeditor/images/exporthtml.png"),tr("Export Html"),this); m_exportPdfAct = new QAction(QIcon("icon:liteeditor/images/exportpdf.png"),tr("Export PDF"),this); m_printPreviewAct = new QAction(QIcon("icon:liteeditor/images/fileprintpreview.png"),tr("Print Preview"),this); m_printPreviewAct->setVisible(false); m_syncScrollAct = new QAction(tr("Synchronize preview and code scrollbars"),this); m_syncScrollAct->setCheckable(true); m_syncSwitchAct = new QAction(tr("Automatically display preview"),this); m_syncSwitchAct->setCheckable(true); m_configMenu = new QMenu(tr("Config"),m_widget); m_configMenu->setIcon(QIcon("icon:markdown/images/config.png")); m_configMenu->addAction(m_syncSwitchAct); m_configMenu->addAction(m_syncScrollAct); QList<QAction*> actions; actions << m_configMenu->menuAction() << m_reloadAct << m_exportHtmlAct << m_exportPdfAct << m_printPreviewAct << m_cssMenu->menuAction(); m_toolAct = m_liteApp->toolWindowManager()->addToolWindow(Qt::BottomDockWidgetArea, m_widget, QString("HtmlPreview"), QString(tr("HTML Preview")), false, actions); connect(m_liteApp,SIGNAL(loaded()),this,SLOT(appLoaded())); connect(m_liteApp->editorManager(),SIGNAL(currentEditorChanged(LiteApi::IEditor*)),this,SLOT(currentEditorChanged(LiteApi::IEditor*))); connect(m_toolAct,SIGNAL(toggled(bool)),this,SLOT(triggeredTool(bool))); connect(m_exportHtmlAct,SIGNAL(triggered()),this,SLOT(exportHtml())); connect(m_exportPdfAct,SIGNAL(triggered()),this,SLOT(exportPdf())); connect(m_printPreviewAct,SIGNAL(triggered()),this,SLOT(printPreview())); connect(m_cssActGroup,SIGNAL(triggered(QAction*)),this,SLOT(cssTtriggered(QAction*))); connect(m_syncSwitchAct,SIGNAL(toggled(bool)),this,SLOT(toggledSyncSwitch(bool))); connect(m_syncScrollAct,SIGNAL(toggled(bool)),this,SLOT(toggledSyncScroll(bool))); connect(m_reloadAct,SIGNAL(triggered()),this,SLOT(reload())); connect(m_htmlUpdateTimer,SIGNAL(timeout()),this,SLOT(htmlUpdate())); m_syncScrollAct->setChecked(m_liteApp->settings()->value(MARKDOWN_SYNCSCROLLHTML,true).toBool()); m_syncSwitchAct->setChecked(m_liteApp->settings()->value(MARKDOWN_SYNCVIEWHTML,false).toBool()); } HtmlPreview::~HtmlPreview() { delete m_htmlUpdateTimer; QAction *act = m_cssActGroup->checkedAction(); if (act != 0) { m_liteApp->settings()->setValue("markdown/css",act->text()); } m_liteApp->settings()->setValue(MARKDOWN_SYNCSCROLLHTML,m_syncScrollAct->isChecked()); m_liteApp->settings()->setValue(MARKDOWN_SYNCVIEWHTML,m_syncSwitchAct->isChecked()); delete m_configMenu; delete m_cssMenu; if (m_widget) { delete m_widget; } } static QByteArray defcss_data = "@media print {pre,code {word-wrap: break-word;}"; static QByteArray export_data = "<html>" "<head>" "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>" "<style type=\"text/css\">" "__MARKDOWN_CSS__" "</style>" "<title>__MARKDOWN_TITLE__</title>" "</head>" "<body>" "__MARKDOWN_CONTENT__" "</body>" "</html>"; void HtmlPreview::appLoaded() { m_htmlWidget = m_liteApp->htmlWidgetManager()->create(this); if (m_htmlWidget->className() == "QWebView") { m_bWebkit = true; } else { m_bWebkit = false; } //connect(m_htmlWidget,SIGNAL(loadFinished(bool)),this,SLOT(loadFinished(bool))); connect(m_htmlWidget,SIGNAL(contentsSizeChanged()),this,SLOT(htmlContentsSizeChanged())); connect(m_htmlWidget,SIGNAL(linkClicked(QUrl)),this,SLOT(linkClicked(QUrl))); connect(m_htmlWidget,SIGNAL(linkHovered(QUrl)),this,SLOT(linkHovered(QUrl))); QAction *nocssAct = new QAction(tr("Plain HTML"),this); nocssAct->setCheckable(true); nocssAct->setObjectName("nocss"); m_cssActGroup->addAction(nocssAct); QAction *sep = new QAction(this); sep->setSeparator(true); m_cssActGroup->addAction(sep); QFile file(m_liteApp->resourcePath()+"/packages/markdown/export.html"); if (file.open(QFile::ReadOnly)) { m_exportOrgTemple = file.readAll(); } else { m_exportOrgTemple = export_data; } m_exportTemple = m_exportOrgTemple; m_exportTemple.replace("__MARKDOWN_CSS__",defcss_data); QString defcss; if (m_bWebkit) { QDir dir(m_liteApp->resourcePath()+"/packages/markdown/css"); foreach (QFileInfo info, dir.entryInfoList(QStringList()<<"*.css",QDir::Files)) { QAction *act = new QAction(info.fileName(),this); act->setCheckable(true); m_cssActGroup->addAction(act); } defcss = "github.css"; } else { QAction *act = new QAction("textbrowser.css",this); act->setCheckable(true); m_cssActGroup->addAction(act); //fix_qt_textbrowser(true); defcss = "textbrowser.css"; } m_cssMenu->addActions(m_cssActGroup->actions()); QVBoxLayout *layout = new QVBoxLayout; layout->setMargin(0); layout->setSpacing(0); layout->addWidget(m_htmlWidget->widget(),1); m_widget->setLayout(layout); QString css = m_liteApp->settings()->value("markdown/css",defcss).toString(); foreach (QAction *act, m_cssActGroup->actions()) { if (act->text() == css) { act->trigger(); break; } } } QByteArray HtmlPreview::loadCssData(const QString &fileName) { QFile f(fileName); if (f.open(QFile::ReadOnly)) { return f.readAll(); } return QByteArray(); } void HtmlPreview::currentEditorChanged(LiteApi::IEditor *editor) { if (m_curEditor != 0) { m_curEditor->disconnect(this); } if (m_curTextEditor != 0) { m_curTextEditor->verticalScrollBar()->disconnect(this); } if (editor && ( (editor->mimeType() == "text/x-markdown") || (editor->mimeType() == "text/html")) ) { if (m_syncSwitchAct->isChecked()) { m_toolAct->setChecked(true); } QPlainTextEdit *textEdit = LiteApi::findExtensionObject<QPlainTextEdit*>(editor,"LiteApi.QPlainTextEdit"); if (textEdit) { m_curTextEditor = textEdit; connect(m_curTextEditor->verticalScrollBar(),SIGNAL(valueChanged(int)),this,SLOT(scrollValueChanged())); } LiteApi::ITextEditor *ed = LiteApi::getTextEditor(editor); if (ed) { m_curEditor = ed; connect(m_curEditor,SIGNAL(contentsChanged()),this,SLOT(contentsChanged())); } m_bFileChanged = true; editorHtmlPrivew(true); } else { if (m_syncSwitchAct->isChecked()) { m_toolAct->setChecked(false); } m_curEditor = 0; m_curTextEditor = 0; if (m_htmlWidget && !m_lastData.isEmpty()) { m_htmlWidget->clear(); } m_lastData.clear(); } } void HtmlPreview::contentsChanged() { m_htmlUpdateTimer->start(); } void HtmlPreview::htmlUpdate() { editorHtmlPrivew(); } void HtmlPreview::scrollValueChanged() { if (m_syncScrollAct->isChecked()) { syncScrollValue(); } } void HtmlPreview::syncScrollValue() { if (!m_curTextEditor || !m_htmlWidget || !m_toolAct->isChecked()) { return; } int max0 = m_curTextEditor->verticalScrollBar()->maximum(); int min0 = m_curTextEditor->verticalScrollBar()->minimum(); int value0 = m_curTextEditor->verticalScrollBar()->value(); if ((max0-min0) == 0) { return; } int max1 = m_htmlWidget->scrollBarMaximum(Qt::Vertical); int min1 = m_htmlWidget->scrollBarMinimum(Qt::Vertical); int value1 = 1.0*value0*(max1-min1)/(max0-min0); m_htmlWidget->setScrollBarValue(Qt::Vertical,value1); } void HtmlPreview::toggledSyncSwitch(bool b) { if (b) { //this->editorHtmlPrivew(true); } } void HtmlPreview::toggledSyncScroll(bool b) { if (b) { this->syncScrollValue(); } } void HtmlPreview::editorHtmlPrivew(bool force) { if (!m_curEditor || !m_htmlWidget || !m_toolAct->isChecked()) { return; } QByteArray data = m_curEditor->utf8Data(); if (!force && (m_lastData == data)) { return; } loadHtmlData(data,QFileInfo(m_curEditor->filePath()).fileName().toUtf8(),m_curEditor->mimeType(),QUrl::fromLocalFile(m_curEditor->filePath())); } void HtmlPreview::loadHtmlData(const QByteArray &data, const QByteArray &title, const QString &mime, const QUrl &url) { m_lastData = data; // int h = m_htmlWidget->scrollBarValue(Qt::Horizontal); // int v = m_htmlWidget->scrollBarValue(Qt::Vertical); // m_prevPos = QPoint(h,v); if (mime == "text/html") { QTextCodec *codec = QTextCodec::codecForHtml(data,QTextCodec::codecForName("utf-8")); m_htmlWidget->setHtml(codec->toUnicode(data),QUrl::fromLocalFile(m_curEditor->filePath())); } else if (mime == "text/x-markdown") { m_exportHtml = m_exportTemple; m_exportHtml.replace("__MARKDOWN_TITLE__",title); m_exportHtml.replace("__MARKDOWN_CONTENT__",md2html(data)); m_htmlWidget->setHtml(QString::fromUtf8(m_exportHtml),url); } else { m_exportHtml = m_exportTemple; QTextCodec *codec = QTextCodec::codecForName("utf-8"); m_exportHtml.replace("__MARKDOWN_TITLE__",title); #if QT_VERSION >= 0x050000 m_exportHtml.replace("__MARKDOWN_CONTENT__","<pre>"+codec->toUnicode(data).toHtmlEscaped().toUtf8()+"</pre>"); #else m_exportHtml.replace("__MARKDOWN_CONTENT__","<pre>"+Qt::escape(codec->toUnicode(data)).toUtf8()+"</pre>"); #endif m_htmlWidget->setHtml(QString::fromUtf8(m_exportHtml),url); } } void HtmlPreview::triggeredTool(bool b) { if (b) { currentEditorChanged(m_liteApp->editorManager()->currentEditor()); } } void HtmlPreview::reload() { this->editorHtmlPrivew(true); this->syncScrollValue(); } void HtmlPreview::exportHtml() { if (m_curEditor == 0) { return; } QFileInfo info(m_curEditor->filePath()); QString path = info.path()+"//"+info.completeBaseName(); QString fileName = QFileDialog::getSaveFileName(m_widget, tr("Export Html"), path, "*.html"); if (!fileName.isEmpty()) { if (QFileInfo(fileName).suffix().isEmpty()) fileName.append(".html"); QFile file(fileName); if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { QMessageBox::critical(m_widget, tr("Export Failed"), QString(tr("Could not open %1 for writing!")).arg(fileName) ); return; } if (m_curEditor->mimeType() == "text/html") { file.write(m_lastData); } else { file.write(m_exportHtml); } file.close(); QDesktopServices::openUrl(QUrl::fromLocalFile(QFileInfo(fileName).path())); } } void HtmlPreview::exportPdf() { if (m_curEditor == 0) { return; } #ifndef QT_NO_PRINTER QFileInfo info(m_curEditor->filePath()); QString path = info.path()+"//"+info.completeBaseName(); QString fileName = QFileDialog::getSaveFileName(m_widget, tr("Export PDF"), path, "*.pdf"); if (!fileName.isEmpty()) { if (QFileInfo(fileName).suffix().isEmpty()) fileName.append(".pdf"); QPrinter printer(QPrinter::HighResolution); printer.setOutputFormat(QPrinter::PdfFormat); printer.setCreator("LiteIDE"); printer.setOutputFileName(fileName); m_htmlWidget->print(&printer); QDesktopServices::openUrl(QUrl::fromLocalFile(QFileInfo(fileName).path())); } #endif } void HtmlPreview::printPreview() { if (m_curEditor == 0) { return; } #ifndef QT_NO_PRINTER QPrinter printer(QPrinter::HighResolution); printer.setPageMargins(10,10,10,10,QPrinter::Millimeter); printer.setPageSize(QPrinter::A4); QPrintPreviewDialog dlg(&printer,m_widget); connect(&dlg,SIGNAL(paintRequested(QPrinter*)),m_htmlWidget,SLOT(print(QPrinter*))); dlg.exec(); #endif } void HtmlPreview::cssTtriggered(QAction *act) { if (!act) { return; } QByteArray cssData; if (act->objectName() != "nocss") { QString fileName; if (!m_bWebkit) { fileName = ":/markdown/css/"+act->text(); } else { fileName = m_liteApp->resourcePath()+"/packages/markdown/css/"+act->text(); } cssData = this->loadCssData(fileName); } if (cssData.isEmpty()) { cssData = "@media print {pre,code {word-wrap: break-word;}"; } m_exportTemple = m_exportOrgTemple; m_exportTemple.replace("__MARKDOWN_CSS__",cssData); this->editorHtmlPrivew(true); } void HtmlPreview::linkClicked(const QUrl &url) { m_liteApp->mainWindow()->statusBar()->clearMessage(); if (url.scheme() == "file") { QFileInfo info(url.toLocalFile()); QFile f(info.filePath()); if (!f.open(QFile::ReadOnly)) { return; } QByteArray data = f.readAll(); QString mime = m_liteApp->mimeTypeManager()->findMimeTypeByFile(info.filePath()); loadHtmlData(data,info.fileName().toUtf8(),mime,url); } else { QDesktopServices::openUrl(url); } } void HtmlPreview::linkHovered(const QUrl &url) { m_liteApp->mainWindow()->statusBar()->showMessage(url.toString()); } void HtmlPreview::loadFinished(bool b) { if (!b) { return; } if (m_bFileChanged) { this->syncScrollValue(); this->m_bFileChanged = false; } else { m_htmlWidget->setScrollBarValue(Qt::Horizontal,m_prevPos.x()); m_htmlWidget->setScrollBarValue(Qt::Vertical,m_prevPos.y()); } } void HtmlPreview::htmlContentsSizeChanged() { this->syncScrollValue(); }
16,694
C++
.cpp
450
31.011111
147
0.64453
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,426
markdownedit.cpp
visualfc_liteide/liteidex/src/plugins/markdown/markdownedit.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: markdownedit.cpp // Creator: visualfc <visualfc@gmail.com> #include "markdownedit.h" #include "liteeditorapi/liteeditorapi.h" #include <QMenu> #include <QAction> #include <QToolBar> #include <QTextCursor> #include <QTextBlock> #include <QPlainTextEdit> #include <QTextDocument> #include <QRegExp> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end //class Separator : public QAction //{ //public: // Separator(QObject *parent) : // QAction(parent) // { // setSeparator(true); // } //}; //static void updateToolTip(QToolBar *toolBar) //{ // foreach(QAction *act, toolBar->actions()) { // if (act->isSeparator()) { // continue; // } // if (act->toolTip() == act->text() && !act->shortcut().isEmpty()) { // act->setToolTip(QString("%1 (%2)").arg(act->text()).arg(act->shortcut().toString())); // } // } //} MarkdownEdit::MarkdownEdit(LiteApi::IApplication *app, LiteApi::IEditor *editor, QObject *parent) : QObject(parent), m_liteApp(app) { m_editor = LiteApi::getTextEditor(editor); if (!m_editor) { return; } m_ed = LiteApi::getPlainTextEdit(editor); if (!m_ed) { return; } m_editor->setLineWrap(true); LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(this,"Markdown"); QAction *h1 = new QAction(QIcon("icon:markdown/images/h1.png"),tr("Header (h1)"),this); actionContext->regAction(h1,"Header1","Ctrl+1"); QAction *h2 = new QAction(QIcon("icon:markdown/images/h2.png"),tr("Header (h2)"),this); actionContext->regAction(h2,"Header2","Ctrl+2"); QAction *h3 = new QAction(QIcon("icon:markdown/images/h3.png"),tr("Header (h3)"),this); actionContext->regAction(h3,"Header3","Ctrl+3"); QAction *h4 = new QAction(QIcon("icon:markdown/images/h4.png"),tr("Header (h4)"),this); actionContext->regAction(h4,"Header4","Ctrl+4"); QAction *h5 = new QAction(QIcon("icon:markdown/images/h5.png"),tr("Header (h5)"),this); actionContext->regAction(h5,"Header5","Ctrl+5"); QAction *h6 = new QAction(QIcon("icon:markdown/images/h6.png"),tr("Header (h6)"),this); actionContext->regAction(h6,"Header6","Ctrl+6"); QAction *bold = new QAction(QIcon("icon:markdown/images/bold.png"),tr("Bold"),this); actionContext->regAction(bold,"Bold",QKeySequence::Bold); QAction *italic = new QAction(QIcon("icon:markdown/images/italic.png"),tr("Italic"),this); actionContext->regAction(italic,"Italic",QKeySequence::Italic); QAction *code = new QAction(QIcon("icon:markdown/images/code.png"),tr("Inline Code"),this); actionContext->regAction(code,"InlineCode","Ctrl+K"); QAction *link = new QAction(QIcon("icon:markdown/images/link.png"),tr("Link"),this); actionContext->regAction(link,"Link","Ctrl+Shift+L"); QAction *image = new QAction(QIcon("icon:markdown/images/image.png"),tr("Image"),this); actionContext->regAction(image,"Image","Ctrl+Shift+I"); QAction *ul = new QAction(QIcon("icon:markdown/images/ul.png"),tr("Unordered List"),this); actionContext->regAction(ul,"UnorderedList","Ctrl+Shift+U"); QAction *ol = new QAction(QIcon("icon:markdown/images/ol.png"),tr("Ordered List"),this); actionContext->regAction(ol,"OrderedList","Ctrl+Shift+O"); QAction *bq = new QAction(QIcon("icon:markdown/images/quote.png"),tr("Blockquote"),this); actionContext->regAction(bq,"Blockquote","Ctrl+Shift+Q"); QAction *hr = new QAction(QIcon("icon:markdown/images/hr.png"),tr("Horizontal Rule"),this); actionContext->regAction(hr,"HorizontalRule","Ctrl+Shift+H"); QMenu *menu = LiteApi::getEditMenu(editor); if (menu) { menu->addSeparator(); QMenu *h = menu->addMenu(tr("Heading")); h->addAction(h1); h->addAction(h2); h->addAction(h3); h->addAction(h4); h->addAction(h5); h->addAction(h6); menu->addSeparator(); menu->addAction(link); menu->addAction(image); menu->addSeparator(); menu->addAction(bold); menu->addAction(italic); menu->addAction(code); menu->addSeparator(); menu->addAction(ul); menu->addAction(ol); menu->addSeparator(); menu->addAction(bq); menu->addAction(hr); } menu = LiteApi::getContextMenu(editor); if (menu) { QMenu *h = menu->addMenu(tr("Heading")); h->addAction(h1); h->addAction(h2); h->addAction(h3); h->addAction(h4); h->addAction(h5); h->addAction(h6); menu->addSeparator(); menu->addAction(link); menu->addAction(image); menu->addSeparator(); menu->addAction(bold); menu->addAction(italic); menu->addAction(code); menu->addSeparator(); menu->addAction(ul); menu->addAction(ol); menu->addSeparator(); menu->addAction(bq); menu->addAction(hr); } QToolBar *toolBar = LiteApi::getEditToolBar(editor); if (toolBar) { toolBar->addSeparator(); toolBar->addAction(h1); toolBar->addAction(h2); toolBar->addAction(h3); toolBar->addSeparator(); toolBar->addAction(link); toolBar->addAction(image); toolBar->addSeparator(); toolBar->addAction(bold); toolBar->addAction(italic); toolBar->addAction(code); toolBar->addSeparator(); toolBar->addAction(ul); toolBar->addAction(ol); toolBar->addSeparator(); toolBar->addAction(bq); toolBar->addAction(hr); //updateToolTip(toolBar); } connect(editor,SIGNAL(destroyed()),this,SLOT(deleteLater())); connect(h1,SIGNAL(triggered()),this,SLOT(h1())); connect(h2,SIGNAL(triggered()),this,SLOT(h2())); connect(h3,SIGNAL(triggered()),this,SLOT(h3())); connect(h4,SIGNAL(triggered()),this,SLOT(h4())); connect(h5,SIGNAL(triggered()),this,SLOT(h5())); connect(h6,SIGNAL(triggered()),this,SLOT(h6())); connect(bold,SIGNAL(triggered()),this,SLOT(bold())); connect(italic,SIGNAL(triggered()),this,SLOT(italic())); connect(code,SIGNAL(triggered()),this,SLOT(code())); connect(link,SIGNAL(triggered()),this,SLOT(link())); connect(image,SIGNAL(triggered()),this,SLOT(image())); connect(ul,SIGNAL(triggered()),this,SLOT(ul())); connect(ol,SIGNAL(triggered()),this,SLOT(ol())); connect(bq,SIGNAL(triggered()),this,SLOT(bq())); connect(hr,SIGNAL(triggered()),this,SLOT(hr())); //m_ed->installEventFilter(this); } MarkdownEdit::~MarkdownEdit() { } void MarkdownEdit::insert_head(const QString &tag, bool blockStart) { QTextCursor cur = m_ed->textCursor(); cur.beginEditBlock(); if (cur.hasSelection()) { QTextBlock begin = m_ed->document()->findBlock(cur.selectionStart()); QTextBlock end = m_ed->document()->findBlock(cur.selectionEnd()); if (end.position() == cur.selectionEnd()) { end = end.previous(); } QTextBlock block = begin; do { if (block.text().length() > 0) { if (blockStart) { cur.setPosition(block.position()); } else { QString text = block.text(); foreach(QChar c, text) { if (!c.isSpace()) { cur.setPosition(block.position()+text.indexOf(c)); break; } } } cur.insertText(tag); } block = block.next(); } while(block.isValid() && block.position() <= end.position()); } else { if (blockStart) { cur.setPosition(cur.block().position()); } else { QTextBlock block = cur.block(); QString text = block.text(); foreach(QChar c, text) { if (!c.isSpace()) { cur.setPosition(block.position()+text.indexOf(c)); break; } } } cur.insertText(tag); } cur.endEditBlock(); m_ed->setTextCursor(cur); } void MarkdownEdit::mark_selection(const QString &mark) { mark_selection(mark,mark); } void MarkdownEdit::mark_selection(const QString &mark1, const QString &mark2) { QTextCursor cur = m_ed->textCursor(); cur.beginEditBlock(); if (cur.hasSelection()) { QTextBlock begin = m_ed->document()->findBlock(cur.selectionStart()); QTextBlock end = m_ed->document()->findBlock(cur.selectionEnd()); if (end.position() == cur.selectionEnd()) { end = end.previous(); } int n1 = cur.selectionStart(); int n2 = cur.selectionEnd(); QTextBlock block = begin; do { int c1 = block.position(); int c2 = c1+block.text().length(); if (block.position() == begin.position() && c1 < n1) { c1 = n1; } if (c2 > n2) { c2 = n2; } if (c2 > c1) { if (!mark1.isEmpty()) { cur.setPosition(c1); cur.insertText(mark1); n2 += mark1.length(); } if (!mark2.isEmpty()) { cur.setPosition(c2+mark1.length()); cur.insertText(mark2); n2 += mark2.length(); } } block = block.next(); } while(block.isValid() && block.position() <= end.position()); } else { int pos = cur.position(); cur.insertText(mark1+mark2); cur.setPosition(pos+mark1.length()); } cur.endEditBlock(); m_ed->setTextCursor(cur); } void MarkdownEdit::h1() { insert_head("# "); } void MarkdownEdit::h2() { insert_head("## "); } void MarkdownEdit::h3() { insert_head("### "); } void MarkdownEdit::h4() { insert_head("#### "); } void MarkdownEdit::h5() { insert_head("#####"); } void MarkdownEdit::h6() { insert_head("###### "); } void MarkdownEdit::bold() { mark_selection("**"); } void MarkdownEdit::italic() { mark_selection("_"); } void MarkdownEdit::code() { mark_selection("`"); } void MarkdownEdit::link() { QTextCursor cursor = m_ed->textCursor(); cursor.beginEditBlock(); if (cursor.hasSelection()) { int n1 = cursor.selectionStart(); int n2 = cursor.selectionEnd(); cursor.setPosition(n1); cursor.insertText("["); cursor.setPosition(n2+1); cursor.insertText("]()"); cursor.setPosition(n2+3); } else { int n = cursor.position(); cursor.insertText("[]()"); cursor.setPosition(n+1); } cursor.endEditBlock(); m_ed->setTextCursor(cursor); } void MarkdownEdit::image() { QTextCursor cursor = m_ed->textCursor(); cursor.beginEditBlock(); if (cursor.hasSelection()) { int n1 = cursor.selectionStart(); int n2 = cursor.selectionEnd(); cursor.setPosition(n1); cursor.insertText("!["); cursor.setPosition(n2+2); cursor.insertText("]()"); cursor.setPosition(n2+4); } else { int n = cursor.position(); cursor.insertText("![]()"); cursor.setPosition(n+2); } cursor.endEditBlock(); m_ed->setTextCursor(cursor); } void MarkdownEdit::ul() { insert_head("* ",false); } void MarkdownEdit::ol() { insert_head("1. ",false); } void MarkdownEdit::bq() { insert_head("> "); } void MarkdownEdit::hr() { QTextCursor cursor = m_ed->textCursor(); if (cursor.hasSelection()) { cursor.setPosition(cursor.selectionEnd()); } cursor.insertText("\n***\n"); m_ed->setTextCursor(cursor); } void MarkdownEdit::gotoLine(int line, int column) { const int blockNumber = line; const QTextBlock &block = m_ed->document()->findBlockByLineNumber(blockNumber); if (block.isValid()) { QTextCursor cursor(block); if (column > 0) { cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, column); } else { int pos = cursor.position(); while (m_ed->document()->characterAt(pos).category() == QChar::Separator_Space) { ++pos; } cursor.setPosition(pos); } m_ed->setTextCursor(cursor); m_ed->ensureCursorVisible(); } } bool MarkdownEdit::eventFilter(QObject *obj, QEvent *event) { if (obj == m_ed && event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Return) { // QObject::eventFilter(obj, event); // QTextCursor cur = m_ed->textCursor(); // QTextBlock prev = cur.block().previous(); // if (prev.isValid()) { // QString text = prev.text(); // qDebug() << text; // if (text.length() > 2 && text.at(1) == ' ' && QString("*+-").contains(text.at(0))) { // cur.insertText(text.left(2)); // } // } // m_ed->setTextCursor(cur); return false; } } return QObject::eventFilter(obj, event); }
14,694
C++
.cpp
425
28.138824
107
0.59135
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,427
markdownbatchbrowser.cpp
visualfc_liteide/liteidex/src/plugins/markdown/markdownbatchbrowser.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: markdownbatchbrowser.cpp // Creator: visualfc <visualfc@gmail.com> #include "markdownbatchbrowser.h" #include "ui_markdownbatchwidget.h" #include "cmark/libcmark.h" #include <QFileDialog> #include <QStandardItemModel> #include <QStandardItem> #include <QStringListModel> #include <QFileInfo> #include <QTextCodec> #include <QUrl> #ifndef QT_NO_PRINTER #include <QPrinter> #include <QPrintPreviewDialog> #endif //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end static QByteArray defcss_data = "@media print {pre,code {word-wrap: break-word;}"; static QByteArray export_data = "<html>" "<head>" "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>" "<style type=\"text/css\">" "__MARKDOWN_CSS__" "</style>" "<title>__MARKDOWN_TITLE__</title>" "</head>" "<body>" "__MARKDOWN_CONTENT__" "</body>" "</html>"; MarkdownBatchBrowser::MarkdownBatchBrowser(LiteApi::IApplication *app, QObject *parent) : LiteApi::IBrowserEditor(parent), m_liteApp(app), ui(new Ui::MarkdownBatchWidget) { m_widget = new QWidget; m_doc = 0; m_mode = 0; m_model = new QStandardItemModel(this); m_model->setHorizontalHeaderLabels(QStringList()<< "FilePath"); ui->setupUi(m_widget); ui->filesTreeView->setModel(m_model); ui->filesTreeView->setEditTriggers(0); ui->filesTreeView->setDragDropMode(QAbstractItemView::NoDragDrop); connect(ui->importFolderPushButton,SIGNAL(clicked()),this,SLOT(browserImportFolder())); connect(ui->addFilesPushButton,SIGNAL(clicked()),this,SLOT(addFiles())); connect(ui->removePushButton,SIGNAL(clicked()),this,SLOT(remove())); connect(ui->removeAllPushButton,SIGNAL(clicked()),this,SLOT(removeAll())); connect(ui->moveDownPushButton,SIGNAL(clicked()),this,SLOT(moveDown())); connect(ui->moveUpPushButton,SIGNAL(clicked()),this,SLOT(moveUp())); connect(ui->useCssCheckBox,SIGNAL(toggled(bool)),ui->cssComboBox,SLOT(setEnabled(bool))); connect(ui->browserExportFolderPushButton,SIGNAL(clicked()),this,SLOT(browserExportFolder())); connect(ui->splitHtmlPushButton,SIGNAL(clicked()),this,SLOT(splitHtml())); connect(ui->mergetHtmlPushButton,SIGNAL(clicked()),this,SLOT(mergeHtml())); connect(ui->splitPdfPushButton,SIGNAL(clicked()),this,SLOT(splitPdf())); connect(ui->mergePdfPushButton,SIGNAL(clicked()),this,SLOT(mergePdf())); connect(ui->mergetPrintPushButton,SIGNAL(clicked()),this,SLOT(mergePrint())); connect(ui->mergePrintPreviwPushButton,SIGNAL(clicked()),this,SLOT(mergePrintPreview())); QDir dir(m_liteApp->resourcePath()+"/packages/markdown/css"); QStringList csss; foreach (QFileInfo info, dir.entryInfoList(QStringList()<<"*.css",QDir::Files)) { csss.append(info.fileName()); } if (!csss.isEmpty()) { ui->cssComboBox->addItems(csss); int index = m_liteApp->settings()->value("markdown/batch_css",0).toInt(); if (index >= 0 && index <= csss.size()-1) { ui->cssComboBox->setCurrentIndex(index); } else { ui->cssComboBox->setCurrentIndex(0); } bool useCss = m_liteApp->settings()->value("markdown/batch_usecss",true).toBool(); ui->useCssCheckBox->setChecked(useCss); } else { ui->useCssCheckBox->setChecked(false); ui->useCssCheckBox->setEnabled(false); } ui->cssComboBox->setEnabled(ui->useCssCheckBox->isChecked()); ui->exportFolderLineEdit->setText(m_liteApp->settings()->value("markdown/batch_oupath").toString()); ui->mergeHrCheckBox->setChecked(m_liteApp->settings()->value("markdown/batch_hr",false).toBool()); ui->mergePageBreakCheckBox->setChecked(m_liteApp->settings()->value("markdown/batch_page-break",true).toBool()); ui->mergePrintPreviwPushButton->setVisible(false); ui->mergetPrintPushButton->setVisible(false); } MarkdownBatchBrowser::~MarkdownBatchBrowser() { m_liteApp->settings()->setValue("markdown/batch_usecss",ui->useCssCheckBox->isChecked()); m_liteApp->settings()->setValue("markdown/batch_css",ui->cssComboBox->currentIndex()); m_liteApp->settings()->setValue("markdown/batch_oupath",ui->exportFolderLineEdit->text()); m_liteApp->settings()->setValue("markdown/batch_hr",ui->mergeHrCheckBox->isChecked()); m_liteApp->settings()->setValue("markdown/batch_page-break",ui->mergePageBreakCheckBox->isChecked()); delete ui; delete m_widget; } QWidget *MarkdownBatchBrowser::widget() { return m_widget; } QString MarkdownBatchBrowser::name() const { return tr("Markdown Exporter"); } QString MarkdownBatchBrowser::mimeType() const { return "browser/markdown"; } QString MarkdownBatchBrowser::markdownOpenFilter() const { QStringList types; QStringList filter; LiteApi::IMimeType *mimeType = m_liteApp->mimeTypeManager()->findMimeType("text/x-markdown"); if (mimeType) { QStringList patterns = mimeType->allPatterns(); types.append(patterns); filter.append(QString("%1 (%2)").arg(mimeType->comment()).arg(patterns.join(" "))); types.removeDuplicates(); filter.removeDuplicates(); } filter.append(tr("All Files (*)")); return filter.join(";;"); } QStringList MarkdownBatchBrowser::markdonwFilter() const { LiteApi::IMimeType *mimeType = m_liteApp->mimeTypeManager()->findMimeType("text/x-markdown"); if (mimeType) { return mimeType->globPatterns(); } return QStringList() << "*.md"; } void MarkdownBatchBrowser::addFile(const QString &file) { m_model->appendRow(new QStandardItem(file)); } static QByteArray head = "<html>" "<head>" "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>" "</head>" "<body>"; static QByteArray end = "</body>" "</html>"; void MarkdownBatchBrowser::appendLog(const QString &log) { ui->logPlainTextEdit->appendPlainText(log); } void MarkdownBatchBrowser::loadFinished(bool b) { if (!b) { this->appendLog("Failed loading the HTML document!"); return; } #ifndef QT_NO_PRINTER if (m_mode == MODE_MERGE_PDF || m_mode == MODE_SPLIT_PDF) { QPrinter printer(QPrinter::HighResolution); printer.setOutputFormat(QPrinter::PdfFormat); printer.setCreator("LiteIDE"); printer.setOutputFileName(m_pdfFileName); m_doc->print(&printer); this->appendLog("Printing PDF "+m_pdfFileName); if (m_mode == MODE_SPLIT_PDF) { this->processPdfList(); } else { QDesktopServices::openUrl(QUrl::fromLocalFile(QFileInfo(m_pdfFileName).path())); } } else if (m_mode == MODE_MERGE_PRINT) { QPrinter printer(QPrinter::HighResolution); printer.setPageMargins(10,10,10,10,QPrinter::Millimeter); m_doc->print(&printer); } else if (m_mode == MODE_MERGE_PRINTPREVIEW) { QPrinter printer(QPrinter::HighResolution); printer.setPageMargins(10,10,10,10,QPrinter::Millimeter); QPrintPreviewDialog dlg(&printer); connect(&dlg,SIGNAL(paintRequested(QPrinter*)),m_doc,SLOT(print(QPrinter*))); dlg.exec(); } #endif } void MarkdownBatchBrowser::browserImportFolder() { QString folder = QFileDialog::getExistingDirectory(m_widget,tr("Select the folder containing your markdown files:")); if (!folder.isEmpty()) { QDir dir(folder); foreach(QFileInfo info, dir.entryInfoList(markdonwFilter(),QDir::Files,QDir::Name)) { addFile(info.filePath()); } } } void MarkdownBatchBrowser::addFiles() { QStringList files = QFileDialog::getOpenFileNames(m_widget,tr("Select Markdown Files"),QString(),this->markdownOpenFilter()); foreach(QString file, files) { this->addFile(file); } } void MarkdownBatchBrowser::remove() { QModelIndex index = ui->filesTreeView->currentIndex(); if (!index.isValid()) { return; } m_model->removeRow(index.row()); } void MarkdownBatchBrowser::removeAll() { int size = m_model->rowCount(); if (size == 0) { return; } m_model->removeRows(0,size); } void MarkdownBatchBrowser::moveUp() { QModelIndex index = ui->filesTreeView->currentIndex(); if (!index.isValid() || index.row() == 0) { return; } int row = index.row(); m_model->insertRow(row-1,m_model->takeRow(row)); ui->filesTreeView->setCurrentIndex(m_model->index(row-1,0)); } void MarkdownBatchBrowser::moveDown() { QModelIndex index = ui->filesTreeView->currentIndex(); if (!index.isValid() || index.row() >= m_model->rowCount()-1) { return; } int row = index.row(); m_model->insertRow(row+1,m_model->takeRow(row)); ui->filesTreeView->setCurrentIndex(m_model->index(row+1,0)); } void MarkdownBatchBrowser::browserExportFolder() { QString folder = QFileDialog::getExistingDirectory(m_widget,tr("Select the folder to contain separated markdown exports:")); if (!folder.isEmpty()) { ui->exportFolderLineEdit->setText(folder); } } void MarkdownBatchBrowser::mergeHtml() { this->init(); if (m_fileList.isEmpty()) { return; } QString fileName = QFileDialog::getSaveFileName(m_widget, tr("Export Merged HTML"), "merge", "*.html"); if (fileName.isEmpty()) { return; } QFileInfo info(fileName); if (info.suffix().isEmpty()) { fileName.append(".html"); } this->appendLog("\nExporting merged HTML to "+fileName+"\n"); QFile f(fileName); if (f.open(QFile::WriteOnly|QFile::Truncate)) { QByteArray datas; foreach (QString file, m_fileList) { if (!datas.isEmpty()) { if (ui->mergeHrCheckBox->isChecked()) { datas.append("\n<hr>\n"); } if (ui->mergePageBreakCheckBox->isChecked()) { datas.append("\n<div STYLE=\"page-break-after: always;\"></div>\n"); } } datas.append(m_fileHtmlMap.value(file)); } QByteArray exportData = m_exportTemple; exportData.replace("__MARKDOWN_TITLE__",fileName.toUtf8()); exportData.replace("__MARKDOWN_CONTENT__",datas); f.write(exportData); QDesktopServices::openUrl(QUrl::fromLocalFile(info.path())); } } void MarkdownBatchBrowser::splitPdf() { this->init(); if (m_fileList.isEmpty()) { return; } this->appendLog("\nExporting split PDF\n"); if (m_exportPath.isEmpty()) { this->appendLog("The output path is empty!"); return; } m_mode = MODE_SPLIT_PDF; this->processPdfList(); } void MarkdownBatchBrowser::processPdfList() { if (m_fileList.isEmpty()) { QDesktopServices::openUrl(QUrl::fromLocalFile(m_exportPath)); return; } QString file = m_fileList.takeFirst(); QFileInfo info(file); QByteArray exportData = m_exportTemple; exportData.replace("__MARKDOWN_TITLE__",info.fileName().toUtf8()); exportData.replace("__MARKDOWN_CONTENT__",m_fileHtmlMap.value(file)); m_pdfFileName = m_exportPath+"/"+info.completeBaseName()+".pdf"; QTextCodec *codec = QTextCodec::codecForName("utf-8"); m_doc->setHtml(codec->toUnicode(exportData),QUrl::fromLocalFile(file)); } void MarkdownBatchBrowser::mergePdf() { this->init(); if (m_fileList.isEmpty()) { return; } QString fileName = QFileDialog::getSaveFileName(m_widget, tr("Export Merged PDF"), "merge", "*.pdf"); if (fileName.isEmpty()) { return; } QFileInfo info(fileName); if (info.suffix().isEmpty()) { fileName.append(".pdf"); } m_pdfFileName = fileName; this->m_mode = MODE_MERGE_PDF; this->appendLog("\nExporting merged PDF"+fileName+"\n"); QByteArray datas; foreach (QString file, m_fileList) { if (!datas.isEmpty()) { if (ui->mergeHrCheckBox->isChecked()) { datas.append("\n<hr>\n"); } if (ui->mergePageBreakCheckBox->isChecked()) { datas.append("\n<div STYLE=\"page-break-after: always;\"></div>\n"); } } datas.append(m_fileHtmlMap.value(file)); } QByteArray exportData = m_exportTemple; exportData.replace("__MARKDOWN_TITLE__",fileName.toUtf8()); exportData.replace("__MARKDOWN_CONTENT__",datas); QTextCodec *codec = QTextCodec::codecForName("utf-8"); m_doc->setHtml(codec->toUnicode(exportData),QUrl::fromLocalFile(m_fileList.first())); } void MarkdownBatchBrowser::mergePrint() { this->init(); if (m_fileList.isEmpty()) { return; } this->m_mode = MODE_MERGE_PRINT; this->appendLog("\nPrinting merged document\n"); QByteArray datas; foreach (QString file, m_fileList) { if (!datas.isEmpty()) { if (ui->mergeHrCheckBox->isChecked()) { datas.append("\n<hr>\n"); } if (ui->mergePageBreakCheckBox->isChecked()) { datas.append("\n<div STYLE=\"page-break-after: always;\"></div>\n"); } } datas.append(m_fileHtmlMap.value(file)); } QByteArray exportData = m_exportTemple; exportData.replace("__MARKDOWN_TITLE__","doc"); exportData.replace("__MARKDOWN_CONTENT__",datas); QTextCodec *codec = QTextCodec::codecForName("utf-8"); m_doc->setHtml(codec->toUnicode(exportData),QUrl::fromLocalFile(m_fileList.first())); } void MarkdownBatchBrowser::mergePrintPreview() { this->init(); if (m_fileList.isEmpty()) { return; } this->m_mode = MODE_MERGE_PRINTPREVIEW; this->appendLog("\nPreviewing merged document\n"); QByteArray datas; foreach (QString file, m_fileList) { if (!datas.isEmpty()) { if (ui->mergeHrCheckBox->isChecked()) { datas.append("\n<hr>\n"); } if (ui->mergePageBreakCheckBox->isChecked()) { datas.append("\n<div STYLE=\"page-break-after: always;\"></div>\n"); } } datas.append(m_fileHtmlMap.value(file)); } QByteArray exportData = m_exportTemple; exportData.replace("__MARKDOWN_TITLE__","doc"); exportData.replace("__MARKDOWN_CONTENT__",datas); QTextCodec *codec = QTextCodec::codecForName("utf-8"); m_doc->setHtml(codec->toUnicode(exportData),QUrl::fromLocalFile(m_fileList.first())); } void MarkdownBatchBrowser::splitHtml() { this->init(); if (m_fileList.isEmpty()) { return; } this->appendLog("\nExporting split HTML\n"); if (m_exportPath.isEmpty()) { this->appendLog("The output path is empty!"); return; } foreach (QString file, m_fileList) { QFileInfo info(file); QString out = m_exportPath+"/"+info.completeBaseName()+".html"; QFile f(out); if (f.open(QFile::WriteOnly|QFile::Truncate)) { this->appendLog(file+" => "+out); QByteArray exportData = m_exportTemple; exportData.replace("__MARKDOWN_TITLE__",info.fileName().toUtf8()); exportData.replace("__MARKDOWN_CONTENT__",m_fileHtmlMap.value(file)); f.write(exportData); } } QDesktopServices::openUrl(QUrl::fromLocalFile(m_exportPath)); } void MarkdownBatchBrowser::init() { if (m_doc == 0) { m_doc = m_liteApp->htmlWidgetManager()->createDocument(this); connect(m_doc,SIGNAL(loadFinished(bool)),this,SLOT(loadFinished(bool))); QFile file(m_liteApp->resourcePath()+"/packages/markdown/export.html"); if (file.open(QFile::ReadOnly)) { m_exportOrgTemple = file.readAll(); } else { m_exportOrgTemple = export_data; } } m_exportTemple = m_exportOrgTemple; QByteArray css; if (ui->useCssCheckBox->isChecked()) { QString fileName = ui->cssComboBox->currentText(); QFile f(m_liteApp->resourcePath()+"/packages/markdown/css/"+fileName); if (f.open(QFile::ReadOnly)) { css = f.readAll(); } } if (css.isEmpty()) { css = defcss_data; } m_exportTemple.replace("__MARKDOWN_CSS__",css); m_fileList = getFiles(); m_fileHtmlMap = getFileHtmlDataMap(m_fileList); m_exportPath.clear(); QString path = ui->exportFolderLineEdit->text(); if (!path.isEmpty()) { QDir dir(path); if (!dir.exists()) { dir.mkpath(path); } if (dir.exists()) { m_exportPath = dir.path(); } } } QStringList MarkdownBatchBrowser::getFiles() const { QStringList files; for(int i = 0; i < m_model->rowCount(); i++) { QModelIndex index = m_model->index(i,0); if (index.isValid()) { files.append(index.data().toString()); } } return files; } QMap<QString, QByteArray> MarkdownBatchBrowser::getFileHtmlDataMap(const QStringList &files) const { QMap<QString, QByteArray> map; foreach(QString file, files) { QFile f(file); if (f.open(QFile::ReadOnly)) { map.insert(file,md2html(f.readAll())); } } return map; }
18,459
C++
.cpp
508
30.55315
129
0.649413
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,428
syntaxtexteditor.cpp
visualfc_liteide/liteidex/src/plugins/syntaxeditor/syntaxtexteditor.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: syntaxtexteditor.cpp // Creator: visualfc <visualfc@gmail.com> #include <QtGui> #include "syntaxtexteditor.h" #include "golanghighlighter.h" #include "QCompleter" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end SyntaxTextEditor::SyntaxTextEditor(QWidget *parent) : QPlainTextEdit(parent),editCompleter(0) { setAttribute(Qt::WA_DeleteOnClose); setLineWrapMode(QPlainTextEdit::NoWrap); isUntitled = true; editorArea = new SyntaxTextEditorArea(this); connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updateAreaWidth(int))); connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updateEditorArea(QRect,int))); connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(highlightCurrentLine())); setCursorWidth(2); updateAreaWidth(0); highlightCurrentLine(); this->autoBlock = true; this->autoIndent = true; this->autoWord = false; } void SyntaxTextEditor::reload() { QFile file(curFile); if (!file.open(QFile::ReadOnly | QFile::Text)) { QMessageBox::warning(this, tr("LiteIDE"), tr("Cannot read file %1:\n%2.") .arg(curFile) .arg(file.errorString())); return; } QApplication::setOverrideCursor(Qt::WaitCursor); QTextCodec *codec = QTextCodec::codecForName("UTF-8"); setPlainText(codec->toUnicode(file.readAll())); /* QTextCursor cursor(document()); cursor.beginEditBlock(); cursor.select(QTextCursor::Document); cursor.insertText(codec->toUnicode(file.readAll())); cursor.endEditBlock(); */ QApplication::restoreOverrideCursor(); } void SyntaxTextEditor::newFile() { static int sequenceNumber = 1; isUntitled = true; curFile = tr("document%1.go").arg(sequenceNumber++); curText = curFile + "[*]"; setWindowTitle(curText); } bool SyntaxTextEditor::loadFile(const QString &fileName) { QFile file(fileName); if (!file.open(QFile::ReadOnly | QFile::Text)) { QMessageBox::warning(this, tr("LiteIDE"), tr("Cannot read file %1:\n%2.") .arg(fileName) .arg(file.errorString())); return false; } QApplication::setOverrideCursor(Qt::WaitCursor); QTextCodec *codec = QTextCodec::codecForName("UTF-8"); setPlainText(codec->toUnicode(file.readAll())); QApplication::restoreOverrideCursor(); setCurrentFile(fileName); return true; } bool SyntaxTextEditor::save() { if (isUntitled) { return saveAs(); } else { return saveFile(curFile); } } bool SyntaxTextEditor::saveAs() { QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"), curFile); if (fileName.isEmpty()) return false; return saveFile(fileName); } QByteArray SyntaxTextEditor::data() const { QTextCodec *codec = QTextCodec::codecForName("UTF-8"); return codec->fromUnicode(toPlainText()); } bool SyntaxTextEditor::saveFile(const QString &fileName) { if (!this->document()->isModified()) return true; QFile file(fileName); if (!file.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::warning(this, tr("LiteIDE"), tr("Cannot write file %1:\n%2.") .arg(fileName) .arg(file.errorString())); return false; } QApplication::setOverrideCursor(Qt::WaitCursor); QTextCodec *codec = QTextCodec::codecForName("UTF-8"); file.write(codec->fromUnicode(toPlainText())); QApplication::restoreOverrideCursor(); setCurrentFile(fileName); return true; } QString SyntaxTextEditor::userFriendlyCurrentFile() { return strippedName(curFile); } void SyntaxTextEditor::closeEvent(QCloseEvent *event) { if (maybeSave()) { event->accept(); } else { event->ignore(); } } bool SyntaxTextEditor::maybeSave() { if (document()->isModified()) { QMessageBox::StandardButton ret; ret = QMessageBox::warning(this, tr("LiteIDE"), tr("'%1' has been modified.\n" "Do you want to save your changes?") .arg(userFriendlyCurrentFile()), QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); if (ret == QMessageBox::Save) return save(); else if (ret == QMessageBox::Cancel) return false; } return true; } void SyntaxTextEditor::setCurrentFile(const QString &fileName) { curFile = QFileInfo(fileName).canonicalFilePath(); isUntitled = false; document()->setModified(false); setWindowModified(false); curText = userFriendlyCurrentFile(); } QString SyntaxTextEditor::strippedName(const QString &fullFileName) { return QFileInfo(fullFileName).fileName(); } int SyntaxTextEditor::editorAreaWidth() { int digits = 1; int max = qMax(1, blockCount()); while (max >= 10) { max /= 10; ++digits; } int space = 6 + fontMetrics().width(QLatin1Char('9')) * digits; return space; } void SyntaxTextEditor::areaPaintEvent(QPaintEvent *event) { QPainter painter(editorArea); painter.fillRect(event->rect(), Qt::lightGray);//lightGray); //![extraAreaPaintEvent_0] //![extraAreaPaintEvent_1] QTextBlock block = firstVisibleBlock(); int blockNumber = block.blockNumber(); int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top(); int bottom = top + (int) blockBoundingRect(block).height(); //![extraAreaPaintEvent_1] //![extraAreaPaintEvent_2] while (block.isValid() && top <= event->rect().bottom()) { if (block.isVisible() && bottom >= event->rect().top()) { QString number = QString::number(blockNumber + 1); painter.setPen(Qt::black); painter.drawText(0, top, editorArea->width()-3, fontMetrics().height(), Qt::AlignRight, number); } block = block.next(); top = bottom; bottom = top + (int) blockBoundingRect(block).height(); ++blockNumber; } } void SyntaxTextEditor::resizeEvent(QResizeEvent *e) { QPlainTextEdit::resizeEvent(e); QRect cr = contentsRect(); editorArea->setGeometry(QRect(cr.left(), cr.top(), editorAreaWidth(), cr.height())); } void SyntaxTextEditor::updateAreaWidth(int /* newBlockCount */) { setViewportMargins(editorAreaWidth(), 0, 0, 0); } void SyntaxTextEditor::updateEditorArea(const QRect &rect, int dy) { if (dy) editorArea->scroll(0, dy); else editorArea->update(0, rect.y(), editorArea->width(), rect.height()); if (rect.contains(viewport()->rect())) { updateAreaWidth(0); } } void SyntaxTextEditor::setCompleter(SyntaxCompleter *completer) { if (editCompleter) QObject::disconnect(editCompleter, 0, this, 0); editCompleter = completer; if (!editCompleter) return; editCompleter->setFileName(this->curFile); editCompleter->setWidget(this); QObject::connect(editCompleter, SIGNAL(activated(QString)), this, SLOT(insertCompletion(QString))); } SyntaxCompleter *SyntaxTextEditor::completer() const { return this->editCompleter; } QString SyntaxTextEditor::wordUnderCursor() const { QTextCursor tc = textCursor(); tc.select(QTextCursor::WordUnderCursor); return tc.selectedText(); } QString SyntaxTextEditor::textUnderCursor() const { QTextCursor tc = textCursor(); tc.select(QTextCursor::BlockUnderCursor); QString block = tc.selectedText(); QStringList all = block.split(QRegExp("[\t| |(|)]")); if (all.isEmpty()) return ""; return all.last(); } void SyntaxTextEditor::focusInEvent(QFocusEvent *e) { if (editCompleter) editCompleter->setWidget(this); QPlainTextEdit::focusInEvent(e); } void SyntaxTextEditor::keyPressEvent(QKeyEvent *e) { if (editCompleter && editCompleter->popup()->isVisible()) { // The following keys are forwarded by the completer to the widget switch (e->key()) { case Qt::Key_Enter: case Qt::Key_Return: case Qt::Key_Escape: case Qt::Key_Tab: case Qt::Key_Backtab: e->ignore(); return; // let the completer do default behavior default: break; } } if (e->key() == Qt::Key_Tab) { indentText(document(), textCursor(),true); e->accept(); return; } else if (e->key() == Qt::Key_Backtab) { indentText(document(),textCursor(),false); e->accept(); return; } if ( e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return ) { if (this->autoIndent) { indentEnter(textCursor()); } else { e->accept(); } emit update(); return; } if (this->autoBlock && e->key() == '{') { QTextCursor cursor(this->textCursor()); cursor.insertText("{}"); cursor.movePosition(QTextCursor::PreviousCharacter); setTextCursor(cursor); e->accept(); return; } if (!this->autoWord) { QPlainTextEdit::keyPressEvent(e); return; } bool isShortcut = ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_E); // CTRL+E if (!editCompleter || !isShortcut) // do not process the shortcut when we have a completer QPlainTextEdit::keyPressEvent(e); const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier); if (!editCompleter || (ctrlOrShift && e->text().isEmpty())) return; static QString eow("~!@#$%^&*()+{}|:\"<>?,./;'[]\\-= "); // end of word bool hasModifier = (e->modifiers() != Qt::NoModifier) && !ctrlOrShift; QString word = wordUnderCursor(); QString text = textUnderCursor(); if (editCompleter->underCursor(e->key(),textCursor(), text,word)) { return; } if (!isShortcut && (hasModifier || e->text().isEmpty() || text.length() <= 2 || eow.contains(e->text().right(1)))) { editCompleter->hidePopup(); return; } editCompleter->showPopup(word); } void SyntaxTextEditor::insertCompletion(const QString& completion) { if (editCompleter->widget() != this) return; QTextCursor tc = textCursor(); int extra = completion.length() - editCompleter->completionPrefix().length(); tc.movePosition(QTextCursor::Left); tc.movePosition(QTextCursor::EndOfWord); tc.insertText(completion.right(extra)); setTextCursor(tc); editCompleter->endCompletion(); } void SyntaxTextEditor::loadConfig(QSettings *settings, const QString &mimeType) { autoIndent = settings->value(mimeType+"/autoindent",true).toBool(); autoBlock = settings->value(mimeType+"/autoblock",true).toBool(); curFont.setFamily(settings->value(mimeType+"/family","Courier").toString()); curFont.setPointSize(settings->value(mimeType+"/fontsize",12).toInt()); setFont(curFont); setTabStopWidth(fontMetrics().width("main")); autoWord = settings->value(mimeType+"/autoword",false).toBool(); } void SyntaxTextEditor::highlightCurrentLine() { QList<QTextEdit::ExtraSelection> extraSelections; if (!isReadOnly()) { QTextEdit::ExtraSelection selection; QColor lineColor = QColor(180,200,200,128); selection.format.setBackground(lineColor); selection.format.setProperty(QTextFormat::FullWidthSelection, true); selection.cursor = textCursor(); selection.cursor.clearSelection(); extraSelections.append(selection); } setExtraSelections(extraSelections); } void SyntaxTextEditor::gotoLine(int line, int column) { const int blockNumber = line - 1; const QTextBlock &block = document()->findBlockByNumber(blockNumber); if (block.isValid()) { QTextCursor cursor(block); if (column > 0) { cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, column); } else { int pos = cursor.position(); while (document()->characterAt(pos).category() == QChar::Separator_Space) { ++pos; } cursor.setPosition(pos); } setTextCursor(cursor); centerCursor(); } } void SyntaxTextEditor::indentBlock(QTextBlock block, bool bIndent) { QTextCursor cursor(block); cursor.beginEditBlock(); cursor.movePosition(QTextCursor::StartOfBlock); cursor.removeSelectedText(); if (bIndent) { cursor.insertText("\t"); } else { QString text = block.text(); if (!text.isEmpty() && (text.at(0) == '\t' || text.at(0) == ' ')) { cursor.deleteChar(); } } cursor.endEditBlock(); } void SyntaxTextEditor::indentCursor(QTextCursor cur, bool bIndent) { if (bIndent) { cur.insertText("\t"); } else { QString text = cur.block().text(); int pos = cur.position()-cur.block().position()-1; int count = text.count(); if (count > 0 && pos >= 0 && pos < count) { if (text.at(pos) == '\t' || text.at(pos) == ' ') { cur.deletePreviousChar(); } } } } void SyntaxTextEditor::indentText(QTextDocument *doc, QTextCursor cur, bool bIndent) { cur.beginEditBlock(); if (!cur.hasSelection()) { indentCursor(cur,bIndent); } else { QTextBlock block = doc->findBlock(cur.selectionStart()); QTextBlock end = doc->findBlock(cur.selectionEnd()); if (!cur.atBlockStart()) { end = end.next(); } do { indentBlock(block,bIndent); block = block.next(); } while (block.isValid() && block != end); } cur.endEditBlock(); } void SyntaxTextEditor::indentEnter(QTextCursor cur) { cur.beginEditBlock(); int pos = cur.position()-cur.block().position(); QString text = cur.block().text(); int i = 0; int tab = 0; int space = 0; QString inText = "\n"; while (i < text.size()) { if (!text.at(i).isSpace()) break; if (text.at(0) == ' ') { space++; } else if (text.at(0) == '\t') { inText += "\t"; tab++; } i++; } text.trimmed(); if (!text.isEmpty()) { if (pos >= text.size()) { const QChar ch = text.at(text.size()-1); if (ch == '{' || ch == '(') { inText += "\t"; } } else if (pos == text.size()-1 && text.size() >= 3) { const QChar l = text.at(text.size()-2); const QChar r = text.at(text.size()-1); if ( (l == '{' && r == '}') || (l == '(' && r== ')') ) { cur.insertText(inText); int pos = cur.position(); cur.insertText(inText); cur.setPosition(pos); this->setTextCursor(cur); cur.insertText("\t"); cur.endEditBlock(); return; } } } cur.insertText(inText); cur.endEditBlock(); ensureCursorVisible(); }
16,670
C++
.cpp
492
27.197154
98
0.614568
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,429
syntaxeditorplugin.cpp
visualfc_liteide/liteidex/src/plugins/syntaxeditor/syntaxeditorplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: syntaxeditorplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "syntaxeditorplugin.h" #include "syntaxfilefactory.h" #include <QFile> #include "utils/mimetype.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end SyntaxEditorPlugin::SyntaxEditorPlugin() { } void SyntaxEditorPlugin::install(LiteApi::IApplication *app) { SyntaxFileFactory *factory = new SyntaxFileFactory(app,this); app->editorManager()->addFactory(factory); QString fileName = app->pluginPath()+"/syntaxeditor.xml"; MimeType::loadMimeTypes(app->mimeTypeManager(),fileName); } const LiteApi::PluginInfo & SyntaxEditorPlugin::info() const { static LiteApi::PluginInfo s_info; s_info.anchor = "visualfc"; s_info.name = "SyntaxEditor"; s_info.ver = "1.0"; s_info.info = "info"; return s_info; } Q_EXPORT_PLUGIN(SyntaxEditorPlugin)
2,109
C++
.cpp
55
36.036364
82
0.690278
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,430
golangcompleter.cpp
visualfc_liteide/liteidex/src/plugins/syntaxeditor/golangcompleter.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangcompleter.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangcompleter.h" #include <QTextBlock> #include <QStringListModel> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangCompleter::GolangCompleter(QObject *parent) : SyntaxCompleter(parent) { model = new QStringListModel; setModel(model); setCaseSensitivity(Qt::CaseSensitive); setWrapAround(false); setCompletionMode(PopupCompletion); } bool GolangCompleter::underCursor(const QTextCursor &cur, const QString &text) { //qDebug() << this->fileName << cur.position() << cur.block().blockNumber(); return true; } void GolangCompleter::updateEditor() { model->setStringList(this->allWords->toList()); }
1,972
C++
.cpp
51
36.431373
82
0.689295
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,431
syntaxeditor.cpp
visualfc_liteide/liteidex/src/plugins/syntaxeditor/syntaxeditor.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: syntaxeditor.cpp // Creator: visualfc <visualfc@gmail.com> #include "syntaxeditor.h" #include "syntaxtexteditor.h" #include <QTextDocument> #include <QFile> #include <QFileInfo> #include <QMessageBox> #include <QToolBar> #include <QAction> #include <QTextCodec> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end TextFile::TextFile(QObject *parent) : LiteApi::IFile(parent) { m_codec = QTextCodec::codecForName("UTF-8"); } QString TextFile::fileName() const { return m_fileName; } bool TextFile::save(const QString &fileName) { QFile file(fileName); if (!file.open(QFile::WriteOnly | QFile::Text)) { return false; } QString text = m_document->toPlainText(); if (m_codec) { file.write(m_codec->fromUnicode(text)); } else { file.write(text.toLocal8Bit()); } m_document->setModified(false); return true; } bool TextFile::reload() { if (m_document->isModified()) { QString text = QString(tr("Cancel file %1 modify and reload ?")).arg(m_fileName); int ret = QMessageBox::question(0,"Question",text,QMessageBox::Yes|QMessageBox::No); if (ret != QMessageBox::Ok) { return false; } } bool ret = open(m_fileName,m_mimeType); if (ret) { emit reloaded(); } return ret; } QString TextFile::mimeType() const { return m_mimeType; } QString TextFile::subType() const { return QString(); } void TextFile::setDocument(QTextDocument *document) { m_document = document; } QTextDocument *TextFile::document() { return m_document; } bool TextFile::open(const QString &fileName, const QString &mimeType) { QFile file(fileName); if (!file.open(QFile::ReadOnly | QFile::Text)) { return false; } m_mimeType = mimeType; m_fileName = fileName; QByteArray text = file.readAll(); if (m_codec) { m_document->setPlainText(m_codec->toUnicode(text)); } else { m_document->setPlainText(text); } m_document->setModified(false); return true; } SyntaxEditor::SyntaxEditor(QObject *parent) : LiteApi::IEditor(parent) { m_editor = new SyntaxTextEditor(0); m_file = new TextFile(this); m_file->setDocument(m_editor->document()); m_toolBar = new QToolBar(tr("SyntaxEditor ToolBar")); m_undoAct = new QAction(QIcon(":/images/undo.png"),tr("Undo"),m_toolBar); m_redoAct = new QAction(QIcon(":/images/redo.png"),tr("Redo"),m_toolBar); m_toolBar->addAction(m_undoAct); m_toolBar->addAction(m_redoAct); m_undoAct->setEnabled(false); m_redoAct->setEnabled(false); connect(m_editor,SIGNAL(textChanged()),this,SIGNAL(contentsChanged())); connect(m_editor,SIGNAL(modificationChanged(bool)),this,SIGNAL(modificationChanged(bool))); connect(m_undoAct,SIGNAL(triggered()),m_editor,SLOT(undo())); connect(m_redoAct,SIGNAL(triggered()),m_editor,SLOT(redo())); connect(m_editor,SIGNAL(undoAvailable(bool)),m_undoAct,SLOT(setEnabled(bool))); connect(m_editor,SIGNAL(redoAvailable(bool)),m_redoAct,SLOT(setEnabled(bool))); } bool SyntaxEditor::autoDelete() const { return true; } QWidget *SyntaxEditor::widget() { return m_editor; } QToolBar* SyntaxEditor::toolBar() const { return m_toolBar; } QString SyntaxEditor::displayName() const { QFileInfo info(m_file->fileName()); return info.fileName(); } QIcon SyntaxEditor::icon() const { return QIcon(); } void SyntaxEditor::setDisplayName(const QString &title) { } bool SyntaxEditor::createNew(const QString &contents) { return true; } bool SyntaxEditor::open(const QString &fileName,const QString &mimeType) { if (!m_file->open(fileName,mimeType)) { return false; } m_editor->moveCursor(QTextCursor::Start); return true; } bool SyntaxEditor::save() { bool ret = m_file->save(m_file->fileName()); if (ret) { m_editor->document()->setModified(false); } return ret; } bool SyntaxEditor::isModified() { return m_editor->document()->isModified(); } LiteApi::IFile *SyntaxEditor::file() { return m_file; } int SyntaxEditor::line() const { return 0; } int SyntaxEditor::column() const { return 0; } void SyntaxEditor::gotoLine(int line, int column) { m_editor->gotoLine(line,column); } SyntaxTextEditor *SyntaxEditor::editor() { return m_editor; }
5,623
C++
.cpp
200
24.825
95
0.682189
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,432
golanghighlighter.cpp
visualfc_liteide/liteidex/src/plugins/syntaxeditor/golanghighlighter.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golanghighlighter.cpp // Creator: visualfc <visualfc@gmail.com> #include "golanghighlighter.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangHighlighter::GolangHighlighter(QTextDocument* document): QSyntaxHighlighter(document), allWords(new QSet<QString>) { keywordFormat.setForeground(Qt::darkBlue); keywordFormat.setFontWeight(QFont::Bold); identFormat.setForeground(Qt::darkBlue); functionFormat.setForeground(Qt::blue); numberFormat.setForeground(Qt::darkMagenta); quotesFormat.setForeground(Qt::darkGreen); singleLineCommentFormat.setForeground(Qt::darkCyan); multiLineCommentFormat.setForeground(Qt::darkCyan); QString word; HighlightingRule rule; //number rule.pattern = QRegExp("(\\b|\\.)([0-9]+|0[xX][0-9a-fA-F]+|0[0-7]+)(\\.[0-9]+)?([eE][+-]?[0-9]+i?)?\\b"); rule.format = numberFormat; highlightingRules.push_back(rule); //function rule.pattern = QRegExp("\\b[a-zA-Z_][a-zA-Z0-9_]+\\s*(?=\\()"); rule.format = functionFormat; highlightingRules.push_back(rule); //indent rule.pattern = QRegExp("\\b" "(bool|byte|complex64|complex128|float32|float64|" "int8|int16|int32|int64|string|uint8|uint16|uint32|uint64|" "int|uint|uintptr|" "true|false|iota|" "nil|" "append|cap|close|closed|complex|copy|imag|len|" "make|new|panic|print|println|real|recover)" "\\b"); rule.format = identFormat; highlightingRules.append(rule); // word = rule.pattern.pattern(); word.remove("\\b"); word.remove("("); word.remove(")"); foreach(QString v, word.split("|")) { allWords->insert(v); } //keyword rule.pattern = QRegExp("\\b" "(break|default|func|interface|select|" "case|defer|go|map|struct|" "chan|else|goto|package|switch|" "const|fallthrough|if|range|type|" "continue|for|import|return|var)" "\\b"); rule.format = keywordFormat; highlightingRules.append(rule); word = rule.pattern.pattern(); word.remove("\\b"); word.remove("("); word.remove(")"); foreach(QString v, word.split("|")) { allWords->insert(v); } //quotes and comment regexpQuotesAndComment = QRegExp("//|\\\"|'|`|/\\*"); } bool GolangHighlighter::highlightPreBlock(QString const& text, int& startPos, int& endPos) { int state = previousBlockState(); if (state == -1) state = 0; if (state & STATE_BACKQUOTES) { endPos = findQuotesEndPos(text, startPos, '`'); if (endPos == -1) { setFormat(0, text.length(), quotesFormat); setCurrentBlockState(STATE_BACKQUOTES); return true; } else { endPos += 1; setFormat(0, endPos - startPos, quotesFormat); startPos = endPos; } } else if (state & STATE_MULTILINE_COMMENT) { endPos = text.indexOf("*/", startPos); if (endPos == -1) { setFormat(0, text.length(), multiLineCommentFormat); setCurrentBlockState(previousBlockState()); return true; } else { endPos += 2; setFormat(0, endPos - startPos, multiLineCommentFormat); startPos = endPos; } } else if (state & STATE_SINGLELINE_COMMENT) { setFormat(0, text.length(), singleLineCommentFormat); if (text.endsWith("\\")) { setCurrentBlockState(STATE_SINGLELINE_COMMENT); } return true; } return false; } void GolangHighlighter::highlightBlock(const QString &text) { int startPos = 0; int endPos = text.length(); setCurrentBlockState(0); if (highlightPreBlock(text, startPos, endPos)) { return; } //keyword and func foreach (const HighlightingRule &rule, highlightingRules) { QRegExp expression(rule.pattern); int index = expression.indexIn(text,startPos); while (index >= 0) { int length = expression.matchedLength(); setFormat(index, length, rule.format); allWords->insert(text.mid(index,length)); index = expression.indexIn(text, startPos+index + length); } } //quote and comment while (true) { startPos = text.indexOf(regexpQuotesAndComment, startPos); if (startPos == -1) break; QString cap = regexpQuotesAndComment.cap(); if ((cap == "\"") || (cap == "'") || (cap == "`")) { endPos = findQuotesEndPos(text, startPos + 1, cap.at(0)); if (endPos == -1) { //multiline setFormat(startPos, text.length() - startPos, quotesFormat); if (cap == "`") { setCurrentBlockState(STATE_BACKQUOTES); } return; } else { endPos += 1; setFormat(startPos, endPos - startPos, quotesFormat); startPos = endPos; } } else if (cap == "//") { setFormat(startPos, text.length() - startPos, singleLineCommentFormat); if (text.endsWith("\\")) setCurrentBlockState(STATE_SINGLELINE_COMMENT); return; } else if (cap == "/*") { endPos = text.indexOf("*/", startPos+2); if (endPos == -1) { //miltiline setFormat(startPos, text.length() - startPos, multiLineCommentFormat); setCurrentBlockState(STATE_MULTILINE_COMMENT); return; } else { endPos += 2; setFormat(startPos, endPos - startPos, multiLineCommentFormat); startPos = endPos; } } } } int GolangHighlighter::findQuotesEndPos(const QString &text, int startPos, const QChar &endChar) { for (int pos = startPos; pos < text.length(); pos++) { if (text.at(pos) == endChar) { return pos; } else if (text.at(pos) == QChar('\\') && endChar != QChar('`')) { ++pos; } } return -1; }
7,808
C++
.cpp
212
27.707547
109
0.56269
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,433
syntaxfilefactory.cpp
visualfc_liteide/liteidex/src/plugins/syntaxeditor/syntaxfilefactory.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: syntaxfilefactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "syntaxfilefactory.h" #include "syntaxtexteditor.h" #include "syntaxeditor.h" #include "golanghighlighter.h" #include "projecthighlighter.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end SyntaxFileFactory::SyntaxFileFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IFileFactory(parent), m_liteApp(app) { m_mimeTypes.append("text/x-gosrc"); m_mimeTypes.append("text/x-gopro"); m_mimeTypes.append("text/x-profile"); m_mimeTypes.append("text/liteide.default.editor"); } QStringList SyntaxFileFactory::mimeTypes() const { return m_mimeTypes; } LiteApi::IFile *SyntaxFileFactory::open(const QString &fileName, const QString &mimeType) { SyntaxEditor *edit = new SyntaxEditor(this); if (!edit->open(fileName,mimeType)) { delete edit; return 0; } if (mimeType == "text/x-gosrc") { new GolangHighlighter(edit->editor()->document()); } else if (mimeType == "text/x-gopro") { new ProjectHighlighter(edit->editor()->document()); } edit->editor()->loadConfig(m_liteApp->settings(),mimeType); m_liteApp->editorManager()->openEditor(edit); return edit->file(); }
2,502
C++
.cpp
65
35.507692
89
0.679967
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,434
projecthighlighter.cpp
visualfc_liteide/liteidex/src/plugins/syntaxeditor/projecthighlighter.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: projecthighlighter.cpp // Creator: visualfc <visualfc@gmail.com> #include "projecthighlighter.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end ProjectHighlighter::ProjectHighlighter(QTextDocument *document) : QSyntaxHighlighter(document) { keywordFormat.setForeground(Qt::darkBlue); commentFormat.setForeground(Qt::darkCyan); HighlightingRule rule; //keyword rule.pattern = QRegExp("\\b" "(TARGET|DESTDIR|GOFILES|CGOFILES|GCOPT|GLOPT)" "\\b"); rule.format = keywordFormat; highlightingRules.append(rule); rule.pattern = QRegExp("^\\s*#.*"); rule.format = commentFormat; highlightingRules.append(rule); } void ProjectHighlighter::highlightBlock(const QString &text) { int startPos = 0; //int endPos = text.length(); foreach (const HighlightingRule &rule, highlightingRules) { QRegExp expression(rule.pattern); int index = expression.indexIn(text,startPos); while (index >= 0) { int length = expression.matchedLength(); setFormat(index, length, rule.format); index = expression.indexIn(text, startPos+index + length); } } }
2,471
C++
.cpp
62
35.419355
82
0.660008
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,435
selectexternaldialog.cpp
visualfc_liteide/liteidex/src/plugins/litedebug/selectexternaldialog.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: selectexternaldialog.cpp // Creator: visualfc <visualfc@gmail.com> #include "selectexternaldialog.h" #include "ui_selectexternaldialog.h" #include <QFileDialog> #include <QFileInfo> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end SelectExternalDialog::SelectExternalDialog(LiteApi::IApplication *app, QWidget *parent) : QDialog(parent), m_liteApp(app),ui(new Ui::SelectExternalDialog) { ui->setupUi(this); } SelectExternalDialog::~SelectExternalDialog() { delete ui; } QString SelectExternalDialog::getCmd() const { return ui->cmdLineEdit->text(); } QString SelectExternalDialog::getArgs() const { return ui->argsLineEdit->text(); } QString SelectExternalDialog::getWork() const { return ui->workLineEdit->text(); } void SelectExternalDialog::loadSetting() { ui->cmdLineEdit->setText(m_liteApp->settings()->value("litedebug/external/cmd").toString()); ui->argsLineEdit->setText(m_liteApp->settings()->value("litedebug/external/args").toString()); ui->workLineEdit->setText(m_liteApp->settings()->value("litedebug/external/work").toString()); } void SelectExternalDialog::saveSetting() { m_liteApp->settings()->setValue("litedebug/external/cmd",getCmd()); m_liteApp->settings()->setValue("litedebug/external/args",getArgs()); m_liteApp->settings()->setValue("litedebug/external/work",getWork()); } void SelectExternalDialog::on_cmbPushButton_clicked() { QString filePath = QFileDialog::getOpenFileName(this,tr("Select Executable")); if (!filePath.isEmpty()) { ui->cmdLineEdit->setText(filePath); QFileInfo info(filePath); ui->workLineEdit->setText(info.path()); } } void SelectExternalDialog::on_workPushButton_clicked() { QString path = QFileDialog::getExistingDirectory(this,tr("Select the working directory:")); if (!path.isEmpty()) { ui->workLineEdit->setText(path); } }
3,152
C++
.cpp
85
34.388235
98
0.703861
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,436
litedebugplugin.cpp
visualfc_liteide/liteidex/src/plugins/litedebug/litedebugplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: litedebugplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "litedebugplugin.h" #include "litedebug.h" #include "litedebugoptionfactory.h" #include <QMenu> #include <QLayout> #include <QAction> #include <QSplitter> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end LiteDebugPlugin::LiteDebugPlugin() { } bool LiteDebugPlugin::load(LiteApi::IApplication *app) { app->optionManager()->addFactory(new LiteDebugOptionFactory(app,this)); QSplitter *splitter = LiteApi::findExtensionObject<QSplitter*>(app,"LiteApi.QMainWindow.QSplitter"); if (!splitter) { return false; } m_liteDebug = new LiteDebug(app,this); m_liteDebug->widget()->hide(); splitter->addWidget(m_liteDebug->widget()); m_viewDebug = new QAction(tr("Debug Window"),this); m_viewDebug->setCheckable(true); connect(m_viewDebug,SIGNAL(triggered(bool)),m_liteDebug->widget(),SLOT(setVisible(bool))); connect(m_liteDebug,SIGNAL(debugVisible(bool)),m_viewDebug,SLOT(setChecked(bool))); app->actionManager()->insertViewMenu(LiteApi::ViewMenuBrowserPos,m_viewDebug); return true; } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
2,451
C++
.cpp
61
37.639344
104
0.699706
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,437
litedebugoption.cpp
visualfc_liteide/liteidex/src/plugins/litedebug/litedebugoption.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: litedebugoption.cpp // Creator: visualfc <visualfc@gmail.com> #include "litedebugoption.h" #include "ui_litedebugoption.h" #include "litedebug_global.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end LiteDebugOption::LiteDebugOption(LiteApi::IApplication *app,QObject *parent) : LiteApi::IOption(parent), m_liteApp(app), m_widget(new QWidget), ui(new Ui::LiteDebugOption) { ui->setupUi(m_widget); } LiteDebugOption::~LiteDebugOption() { delete m_widget; delete ui; } QWidget *LiteDebugOption::widget() { return m_widget; } QString LiteDebugOption::name() const { return "LiteDebug"; } QString LiteDebugOption::mimeType() const { return OPTION_LITEDEBUG; } void LiteDebugOption::load() { bool b = m_liteApp->settings()->value(LITEDEBUG_AUTOBREAKMAIN,false).toBool(); ui->autoBreakMainCheckBox->setChecked(b); } void LiteDebugOption::save() { bool b = ui->autoBreakMainCheckBox->isChecked(); m_liteApp->settings()->setValue(LITEDEBUG_AUTOBREAKMAIN,b); }
2,276
C++
.cpp
69
30.695652
82
0.692133
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,438
debugwidget.cpp
visualfc_liteide/liteidex/src/plugins/litedebug/debugwidget.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: debugwidget.cpp // Creator: visualfc <visualfc@gmail.com> #include "debugwidget.h" #include <QTreeView> #include <QTabWidget> #include <QVBoxLayout> #include <QHBoxLayout> #include <QLineEdit> #include <QPushButton> #include <QHeaderView> #include <QPlainTextEdit> #include <QVariant> #include <QDebug> #include <QFile> #include <QMenu> #include <QAction> #include <QInputDialog> #include <QItemDelegate> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end class WatchDelegate : public QItemDelegate { public: WatchDelegate(QObject *parent) : QItemDelegate(parent) { } QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (index.column() == 0) { return QItemDelegate::createEditor(parent,option,index); } return 0; } }; DebugWidget::DebugWidget(LiteApi::IApplication *app, QObject *parent) : QObject(parent), m_liteApp(app), m_widget(new QWidget), m_debugger(0) { m_tabWidget = new QTabWidget; m_asyncView = new QTreeView; m_varsView = new SymbolTreeView(false); m_watchView = new SymbolTreeView(false); m_framesView = new QTreeView; m_libraryView = new QTreeView; m_goroutinesView = new SymbolTreeView(false); m_threadsView = new QTreeView; m_regsView = new QTreeView; m_asmView = new QTreeView; m_asyncView->setEditTriggers(0); m_varsView->setEditTriggers(0); m_varsView->setContextMenuPolicy(Qt::CustomContextMenu); m_watchView->setEditTriggers(0); m_watchView->setContextMenuPolicy(Qt::CustomContextMenu); m_framesView->setEditTriggers(0); #if QT_VERSION >= 0x050000 m_framesView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); m_threadsView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); m_goroutinesView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); m_asmView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); #else m_framesView->header()->setResizeMode(QHeaderView::ResizeToContents); m_threadsView->header()->setResizeMode(QHeaderView::ResizeToContents); m_goroutinesView->header()->setResizeMode(QHeaderView::ResizeToContents); m_asmView->header()->setResizeMode(QHeaderView::ResizeToContents); #endif m_libraryView->setEditTriggers(0); m_threadsView->setEditTriggers(0); m_goroutinesView->setEditTriggers(0); m_regsView->setEditTriggers(0); m_asmView->setEditTriggers(0); m_watchView->setEditTriggers(QAbstractItemView::DoubleClicked); m_watchView->setItemDelegate(new WatchDelegate(this)); m_debugLogEdit = new TextOutput(m_liteApp); m_debugLogEdit->setReadOnly(false); m_debugLogEdit->setFilterTermColor(true); m_debugLogEdit->setMaximumBlockCount(10000); m_debugLogEdit->setLineWrapMode(QPlainTextEdit::NoWrap); QVBoxLayout *layout = new QVBoxLayout; layout->setMargin(0); layout->addWidget(m_tabWidget); m_widget->setLayout(layout); m_watchMenu = new QMenu(m_widget); m_addWatchAct = new QAction(tr("Add Watch"),this); //m_addLocalWatchAct = new QAction(tr("Add Local Watch"),this); m_removeWatchAct = new QAction(tr("Remove Watch"),this); m_removeAllWatchAct = new QAction(tr("Remove All Watches"),this); m_watchMenu->addAction(m_addWatchAct); //m_watchMenu->addAction(m_addLocalWatchAct); m_watchMenu->addSeparator(); m_watchMenu->addAction(m_removeWatchAct); m_watchMenu->addAction(m_removeAllWatchAct); connect(m_debugLogEdit,SIGNAL(enterText(QString)),this,SLOT(enterText(QString))); connect(m_varsView,SIGNAL(expanded(QModelIndex)),this,SLOT(expandedVarsView(QModelIndex))); connect(m_watchView,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(watchViewContextMenu(QPoint))); connect(m_addWatchAct,SIGNAL(triggered()),this,SLOT(addWatch())); //connect(m_addLocalWatchAct,SIGNAL(triggered()),this,SLOT(addLocalWatch())); connect(m_removeWatchAct,SIGNAL(triggered()),this,SLOT(removeWatch())); connect(m_removeAllWatchAct,SIGNAL(triggered()),this,SLOT(removeAllWatchAct())); connect(m_asyncView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(dbclickView(QModelIndex))); connect(m_watchView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(dbclickView(QModelIndex))); connect(m_varsView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(dbclickView(QModelIndex))); connect(m_framesView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(dbclickView(QModelIndex))); connect(m_threadsView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(dbclickView(QModelIndex))); connect(m_goroutinesView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(dbclickView(QModelIndex))); connect(m_regsView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(dbclickView(QModelIndex))); connect(m_libraryView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(dbclickView(QModelIndex))); connect(m_asmView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(dbclickView(QModelIndex))); } DebugWidget::~DebugWidget() { delete m_asyncView; delete m_varsView; delete m_watchView; delete m_framesView; delete m_threadsView; delete m_goroutinesView; delete m_regsView; delete m_libraryView; delete m_asmView; if (m_widget) { delete m_widget; } } QWidget *DebugWidget::widget() { return m_widget; } void DebugWidget::enterText(const QString &text) { QString cmd = text.simplified(); if (!cmd.isEmpty() && m_debugger && m_debugger->isRunning()) { emit debugCmdInput(); m_debugger->enterDebugText(cmd); } } void DebugWidget::clearLog() { m_debugLogEdit->clear(); } void DebugWidget::appendLog(const QString &log) { m_debugLogEdit->append(log); } static void setResizeView(QTreeView *view) { QAbstractItemModel *model = view->model(); if (!model) { return; } if (model->columnCount() <= 1) { view->setHeaderHidden(true); return; } else { view->setHeaderHidden(false); } #if QT_VERSION >= 0x050000 view->header()->setSectionResizeMode(0,QHeaderView::ResizeToContents); #else view->header()->setResizeMode(0,QHeaderView::ResizeToContents); #endif } void DebugWidget::updateView(QTreeView *view, LiteApi::IDebugger *debug, LiteApi::DEBUG_MODEL_TYPE type, const QString &title) { QAbstractItemModel *model = debug->debugModel(type); view->setModel(model); setResizeView(view); if (model != 0) { m_tabWidget->addTab(view,title); } } void DebugWidget::setDebugger(LiteApi::IDebugger *debug) { if (m_debugger == debug) { return; } m_debugger = debug; if (!m_debugger) { return; } m_tabWidget->clear(); updateView(m_asyncView,debug,LiteApi::ASYNC_MODEL,tr("Async Record")); updateView(m_varsView,debug,LiteApi::VARS_MODEL,tr("Variables")); updateView(m_watchView,debug,LiteApi::WATCHES_MODEL,tr("Watch")); updateView(m_framesView,debug,LiteApi::FRAMES_MODEL,tr("Call Stack")); updateView(m_threadsView,debug,LiteApi::THREADS_MODEL,tr("Threads")); updateView(m_goroutinesView,debug,LiteApi::GOROUTINES_MODEL,tr("Goroutines")); updateView(m_regsView,debug,LiteApi::REGS_MODEL,tr("Registers")); updateView(m_libraryView,debug,LiteApi::LIBRARY_MODEL,tr("Libraries")); updateView(m_asmView,debug,LiteApi::ASM_MODEL,tr("Disassemble")); m_tabWidget->addTab(m_debugLogEdit,tr("Console")); connect(m_debugger,SIGNAL(setExpand(LiteApi::DEBUG_MODEL_TYPE,QModelIndex,bool)),this,SLOT(setExpand(LiteApi::DEBUG_MODEL_TYPE,QModelIndex,bool))); connect(m_debugger,SIGNAL(watchCreated(QString,QString)),this,SLOT(watchCreated(QString,QString))); connect(m_debugger,SIGNAL(watchRemoved(QString)),this,SLOT(watchRemoved(QString))); connect(m_debugger,SIGNAL(beginUpdateModel(LiteApi::DEBUG_MODEL_TYPE)),this,SLOT(beginUpdateModel(LiteApi::DEBUG_MODEL_TYPE))); connect(m_debugger,SIGNAL(endUpdateModel(LiteApi::DEBUG_MODEL_TYPE)),this,SLOT(endUpdateModel(LiteApi::DEBUG_MODEL_TYPE))); connect(m_debugger,SIGNAL(scrollTo(LiteApi::DEBUG_MODEL_TYPE,QModelIndex)),this,SLOT(scrollTo(LiteApi::DEBUG_MODEL_TYPE,QModelIndex))); } void DebugWidget::expandedVarsView(QModelIndex index) { if (!index.isValid()) { return; } if (!m_debugger) { return; } m_debugger->expandItem(index,LiteApi::VARS_MODEL); } QTreeView* DebugWidget::viewForType(LiteApi::DEBUG_MODEL_TYPE type) { QTreeView *view = 0; switch (type) { case LiteApi::VARS_MODEL: view = m_varsView; break; case LiteApi::WATCHES_MODEL: view = m_watchView; break; case LiteApi::ASYNC_MODEL: view = m_asyncView; break; case LiteApi::FRAMES_MODEL: view = m_framesView; break; case LiteApi::THREADS_MODEL: view = m_threadsView; break; case LiteApi::GOROUTINES_MODEL: view = m_goroutinesView; break; case LiteApi::REGS_MODEL: view = m_regsView; break; case LiteApi::LIBRARY_MODEL: view = m_libraryView; break; case LiteApi::ASM_MODEL: view = m_asmView; break; } return view; } void DebugWidget::setExpand(LiteApi::DEBUG_MODEL_TYPE type, const QModelIndex &index, bool expanded) { if (!index.isValid()) { return; } if (!m_debugger) { return; } QTreeView *view = viewForType(type); if (view) { view->setExpanded(index,expanded); } } void DebugWidget::watchViewContextMenu(QPoint pos) { QMenu *contextMenu = m_watchMenu; if (contextMenu && contextMenu->actions().count() > 0) { contextMenu->popup(m_watchView->mapToGlobal(pos)); } } void DebugWidget::loadDebugInfo(const QString &id) { m_watchMap.clear(); QString key = QString("litedebug_watch/%1").arg(id); QStringList all = m_liteApp->settings()->value(key).toStringList(); m_debugger->setInitWatchList(all); } void DebugWidget::saveDebugInfo(const QString &id) { QStringList vars; foreach(QString var, m_watchMap.values()) { vars.append(var); } QString key = QString("litedebug_watch/%1").arg(id); if (vars.isEmpty()) { m_liteApp->settings()->remove(key); } else { m_liteApp->settings()->setValue(key,vars); } } void DebugWidget::addWatch() { QString text = QInputDialog::getText(this->m_widget,tr("Add Watch"),tr("Watch expression (e.g. buf main.var os.Stdout):")); if (text.isEmpty()) { return; } m_debugger->createWatch(text); } void DebugWidget::removeWatch() { QModelIndex index = m_watchView->currentIndex(); if (!index.isValid()) { return; } QModelIndex head = m_watchView->model()->index(index.row(),0); if (!head.isValid()) { return; } QString name = head.data(Qt::UserRole + 1).toString(); m_debugger->removeWatch(name); } void DebugWidget::removeAllWatchAct() { m_debugger->removeAllWatch(); m_watchMap.clear(); } void DebugWidget::watchCreated(QString var,QString name) { if (!m_watchMap.keys().contains(var)) { m_watchMap.insert(var,name); } } void DebugWidget::watchRemoved(QString var) { m_watchMap.remove(var); } void DebugWidget::setInputFocus() { m_debugLogEdit->setFocus(); } void DebugWidget::dbclickView(QModelIndex index) { if (!index.isValid()) { return; } if (!m_debugger) { return; } QTreeView *view = (QTreeView*)sender(); if (view == m_asyncView) { m_debugger->dbclickItem(index,LiteApi::ASYNC_MODEL); } else if (view == m_varsView) { m_debugger->dbclickItem(index,LiteApi::VARS_MODEL); } else if (view == m_watchView) { m_debugger->dbclickItem(index,LiteApi::WATCHES_MODEL); } else if (view == m_framesView) { m_debugger->dbclickItem(index,LiteApi::FRAMES_MODEL); } else if (view == m_threadsView) { m_debugger->dbclickItem(index,LiteApi::THREADS_MODEL); } else if (view == m_libraryView) { m_debugger->dbclickItem(index,LiteApi::LIBRARY_MODEL); } else if (view == m_regsView) { m_debugger->dbclickItem(index,LiteApi::REGS_MODEL); } else if (view == m_goroutinesView) { m_debugger->dbclickItem(index,LiteApi::GOROUTINES_MODEL); } else if (view == m_asmView) { m_debugger->dbclickItem(index,LiteApi::ASM_MODEL); } } void DebugWidget::beginUpdateModel(LiteApi::DEBUG_MODEL_TYPE type) { if (type == LiteApi::VARS_MODEL) { m_varsView->saveState(&m_varsState); } else if (type == LiteApi::WATCHES_MODEL) { m_watchView->saveState(&m_watchState); } else if (type == LiteApi::GOROUTINES_MODEL) { m_goroutinesView->saveState(&m_goroutinesState); } } void DebugWidget::endUpdateModel(LiteApi::DEBUG_MODEL_TYPE type) { if (type == LiteApi::VARS_MODEL) { m_varsView->loadState(m_varsView->model(),&m_varsState); } else if (type == LiteApi::WATCHES_MODEL) { m_watchView->loadState(m_watchView->model(),&m_watchState); } else if (type == LiteApi::GOROUTINES_MODEL) { m_goroutinesView->loadState(m_goroutinesView->model(),&m_goroutinesState); } } void DebugWidget::scrollTo(LiteApi::DEBUG_MODEL_TYPE type, const QModelIndex &index) { QTreeView *view = viewForType(type); if (view) { view->scrollTo(index,QAbstractItemView::EnsureVisible); } }
15,264
C++
.cpp
409
31.611247
152
0.67766
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,439
litedebug.cpp
visualfc_liteide/liteidex/src/plugins/litedebug/litedebug.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: litedebug.cpp // Creator: visualfc <visualfc@gmail.com> #include "litedebug.h" #include "debugmanager.h" #include "debugwidget.h" #include "fileutil/fileutil.h" #include "liteapi/liteids.h" #include "litedebug_global.h" #include "selectexternaldialog.h" #include <QDir> #include <QFileInfo> #include <QLayout> #include <QMenu> #include <QToolBar> #include <QAction> #include <QVBoxLayout> #include <QFileInfo> #include <QPushButton> #include <QLabel> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end LiteDebug::LiteDebug(LiteApi::IApplication *app, QObject *parent) : LiteApi::ILiteDebug(parent), m_liteApp(app), m_envManager(0), m_liteBuild(0), m_debugger(0), m_manager(new DebugManager(this)), m_widget(new QWidget), m_dbgWidget(new DebugWidget(app,this)) { m_manager->initWithApp(app); m_liteApp->extension()->addObject("LiteApi.ILiteDebug",this); m_liteApp->extension()->addObject("LiteApi.IDebuggerManager",m_manager); m_debugMimeTypes << "text/x-gosrc" << "text/x-csrc" << "text/x-chdr" << "text/x-c++src"; m_output = new TextOutput(m_liteApp); m_output->setReadOnly(true); m_output->setFilterTermColor(true); QAction *clearAct = new QAction(tr("Clear"),this); clearAct->setIcon(QIcon("icon:images/cleanoutput.png")); connect(clearAct,SIGNAL(triggered()),m_output,SLOT(clear())); QVBoxLayout *layout = new QVBoxLayout; QToolBar *widgetToolBar = new QToolBar; widgetToolBar->setIconSize(LiteApi::getToolBarIconSize(m_liteApp)); layout->setMargin(0); layout->setSpacing(0); QHBoxLayout *hbox = new QHBoxLayout; hbox->setMargin(0); hbox->setSpacing(0); hbox->addWidget(widgetToolBar); QPushButton *close = new QPushButton(); close->setIcon(QIcon("icon:images/close.png")); close->setIconSize(QSize(16,16)); close->setFlat(true); close->setToolTip(tr("Close")); connect(close,SIGNAL(clicked()),this,SLOT(hideDebug())); hbox->addStretch(1); hbox->addWidget(close); layout->addLayout(hbox); layout->addWidget(m_dbgWidget->widget()); m_widget->setLayout(layout); LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(this,"Debug"); m_startDebugExternal = new QAction(tr("Start Debugging External Application..."),this); actionContext->regAction(m_startDebugExternal,"StartDebugExternal",""); m_startDebugAct = new QAction(QIcon("icon:litedebug/images/startdebug.png"),tr("Start Debugging"),this); actionContext->regAction(m_startDebugAct,"StartDebug","F5"); m_continueAct = new QAction(QIcon("icon:litedebug/images/continue.png"),tr("Continue"),this); actionContext->regAction(m_continueAct,"Continue","F5"); m_stopDebugAct = new QAction(QIcon("icon:litedebug/images/stopdebug.png"),tr("Stop"),this); actionContext->regAction(m_stopDebugAct,"StopDebug","Shift+F5"); m_showLineAct = new QAction(QIcon("icon:litedebug/images/showline.png"),tr("Show Current Line"),this); actionContext->regAction(m_showLineAct,"ShowLine",""); m_stepIntoAct = new QAction(QIcon("icon:litedebug/images/stepinto.png"),tr("Step Into"),this); actionContext->regAction(m_stepIntoAct,"StepInfo","F11"); m_stepOverAct = new QAction(QIcon("icon:litedebug/images/stepover.png"),tr("Step Over"),this); actionContext->regAction(m_stepOverAct,"LiteDebug.StepOver","F10"); m_stepOutAct = new QAction(QIcon("icon:litedebug/images/stepout.png"),tr("Step Out"),this); actionContext->regAction(m_stepOutAct,"StepOut","Shift+F11"); m_runToLineAct = new QAction(QIcon("icon:litedebug/images/runtoline.png"),tr("Run to Line"),this); actionContext->regAction(m_runToLineAct,"RunToLine","Ctrl+F10"); m_switchBreakAct = new QAction(QIcon("icon:litedebug/images/insertbreak.png"),tr("Insert/Remove Breakpoint"),this); actionContext->regAction(m_switchBreakAct,"Breakpoint","F9"); m_removeAllBreakAct = new QAction(tr("Remove All Breakpoints"),this); actionContext->regAction(m_removeAllBreakAct,"RemoveAllBreakPoints",""); // m_toolBar->addSeparator(); // m_toolBar->addAction(m_startDebugAct); // m_toolBar->addAction(m_insertBreakAct); m_bLastDebugCmdInput = false; widgetToolBar->addAction(m_continueAct); widgetToolBar->addAction(m_stopDebugAct); widgetToolBar->addSeparator(); widgetToolBar->addAction(m_switchBreakAct); widgetToolBar->addAction(m_showLineAct); widgetToolBar->addAction(m_stepIntoAct); widgetToolBar->addAction(m_stepOverAct); widgetToolBar->addAction(m_stepOutAct); widgetToolBar->addAction(m_runToLineAct); m_debugMenu = m_liteApp->actionManager()->loadMenu(ID_MENU_DEBUG); m_debugMenu->addAction(m_startDebugExternal); m_debugMenu->addSeparator(); m_debugMenu->addAction(m_startDebugAct); m_debugMenu->addAction(m_continueAct); m_debugMenu->addAction(m_stopDebugAct); m_debugMenu->addSeparator(); m_debugMenu->addAction(m_showLineAct); m_debugMenu->addAction(m_stepIntoAct); m_debugMenu->addAction(m_stepOverAct); m_debugMenu->addAction(m_stepOutAct); m_debugMenu->addAction(m_runToLineAct); connect(m_manager,SIGNAL(currentDebuggerChanged(LiteApi::IDebugger*)),this,SLOT(setDebugger(LiteApi::IDebugger*))); connect(m_liteApp,SIGNAL(loaded()),this,SLOT(appLoaded())); connect(m_startDebugExternal,SIGNAL(triggered()),this,SLOT(startDebugExternal())); connect(m_startDebugAct,SIGNAL(triggered()),this,SLOT(startDebug())); connect(m_continueAct,SIGNAL(triggered()),this,SLOT(continueRun())); connect(m_runToLineAct,SIGNAL(triggered()),this,SLOT(runToLine())); connect(m_stopDebugAct,SIGNAL(triggered()),this,SLOT(stopDebug())); connect(m_stepOverAct,SIGNAL(triggered()),this,SLOT(stepOver())); connect(m_stepIntoAct,SIGNAL(triggered()),this,SLOT(stepInto())); connect(m_stepOutAct,SIGNAL(triggered()),this,SLOT(stepOut())); connect(m_switchBreakAct,SIGNAL(triggered()),this,SLOT(toggleBreakPoint())); connect(m_removeAllBreakAct,SIGNAL(triggered()),this,SLOT(removeAllBreakPoints())); connect(m_showLineAct,SIGNAL(triggered()),this,SLOT(showLine())); connect(m_liteApp->editorManager(),SIGNAL(editorCreated(LiteApi::IEditor*)),this,SLOT(editorCreated(LiteApi::IEditor*))); connect(m_liteApp->editorManager(),SIGNAL(editorAboutToClose(LiteApi::IEditor*)),this,SLOT(editorAboutToClose(LiteApi::IEditor*))); connect(m_liteApp->editorManager(),SIGNAL(currentEditorChanged(LiteApi::IEditor*)),this,SLOT(currentEditorChanged(LiteApi::IEditor*))); connect(m_output,SIGNAL(enterText(QString)),this,SLOT(enterAppInputText(QString))); connect(m_dbgWidget,SIGNAL(debugCmdInput()),this,SLOT(debugCmdInput())); m_outputAct = m_liteApp->toolWindowManager()->addToolWindow( Qt::BottomDockWidgetArea,m_output,"DebugOutput",tr("Debug Output"),false, QList<QAction*>() << clearAct); m_continueAct->setEnabled(false); m_stopDebugAct->setEnabled(false); m_stepOverAct->setEnabled(false); m_showLineAct->setEnabled(false); m_stepIntoAct->setEnabled(false); m_stepOutAct->setEnabled(false); m_runToLineAct->setEnabled(false); } LiteDebug::~LiteDebug() { if (m_output) { delete m_output; } } void LiteDebug::appLoaded() { m_liteBuild = LiteApi::findExtensionObject<LiteApi::ILiteBuild*>(m_liteApp,"LiteApi.ILiteBuild"); m_envManager = LiteApi::findExtensionObject<LiteApi::IEnvManager*>(m_liteApp,"LiteApi.IEnvManager"); LiteApi::IEditorMarkManager *markManager = LiteApi::getEditorMarkManager(m_liteApp); if (markManager) { markManager->registerMark(BreakPointMarkType,QIcon("icon:litedebug/images/breakmark.png")); markManager->registerMark(CurrentLineMarkType,QIcon("icon:litedebug/images/linemark.png")); } //QMenu *menu = new QMenu(tr("Select Debug")); QActionGroup *group = new QActionGroup(this); QString mimeType = m_liteApp->settings()->value(LITEDEBUG_CURDEBUGGER,"debugger/delve").toString(); foreach (LiteApi::IDebugger *debug, m_manager->debuggerList()) { QAction *act = new QAction(debug->mimeType(),this); act->setObjectName(debug->mimeType()); act->setCheckable(true); group->addAction(act); if (mimeType == debug->mimeType()) { act->setChecked(true); m_manager->setCurrentDebugger(debug); } } // menu->addActions(group->actions()); connect(group,SIGNAL(triggered(QAction*)),this,SLOT(selectedDebug(QAction*))); QAction *first = m_debugMenu->actions().at(0); //m_debugMenu->insertMenu(first,menu); m_debugMenu->insertActions(first,group->actions()); m_debugMenu->insertSeparator(first); } void LiteDebug::selectedDebug(QAction *act) { stopDebug(); QString mimeType = act->objectName(); LiteApi::IDebugger *debug = m_manager->findDebugger(mimeType); if (debug) { m_manager->setCurrentDebugger(debug); m_liteApp->settings()->setValue(LITEDEBUG_CURDEBUGGER,mimeType); } } void LiteDebug::editorCreated(LiteApi::IEditor *editor) { if (!canDebug(editor)) { return; } LiteApi::IEditorMark *editorMark = LiteApi::findExtensionObject<LiteApi::IEditorMark*>(editor,"LiteApi.IEditorMark"); if (!editorMark) { return; } QMenu *menu = LiteApi::getEditMenu(editor); if (menu) { menu->addSeparator(); menu->addAction(m_switchBreakAct); menu->addAction(m_removeAllBreakAct); } menu = LiteApi::getContextMenu(editor); if (menu) { menu->addSeparator(); menu->addAction(m_switchBreakAct); } QString filePath = editor->filePath(); bool ok; m_fileBpMap.remove(filePath); QString key = QString("litedebug_bp/%1").arg(editor->filePath()); QList<int> bpList; foreach(QString bp, m_liteApp->settings()->value(key).toStringList()) { int i = bp.toInt(&ok); if (ok) { bpList << i; m_fileBpMap.insert(filePath,i); } } editorMark->addMarkList(bpList,LiteApi::BreakPointMarkType); // foreach(QString bp, m_liteApp->globalCookie().value(key).toStringList()) { // int i = bp.toInt(&ok); // if (ok) { // editorMark->addMark(i,LiteApi::BreakPointMark); // m_fileBpMap.insert(filePath,i); // } // } if (m_lastLine.fileName == filePath) { editorMark->addMark(m_lastLine.line,LiteApi::CurrentLineMarkType); } QToolBar *toolBar = LiteApi::getEditToolBar(editor); if (toolBar) { toolBar->addSeparator(); toolBar->addAction(m_switchBreakAct); toolBar->addAction(m_startDebugAct); } } void LiteDebug::editorAboutToClose(LiteApi::IEditor *editor) { if (!canDebug(editor)) { return; } LiteApi::IEditorMark *editorMark = LiteApi::findExtensionObject<LiteApi::IEditorMark*>(editor,"LiteApi.IEditorMark"); if (!editorMark) { return; } QList<int> bpList = editorMark->markLinesByType(LiteApi::BreakPointMarkType); QStringList save; foreach(int bp, bpList) { save.append(QString("%1").arg(bp)); } QString key = QString("litedebug_bp/%1").arg(editor->filePath()); //m_liteApp->globalCookie().insert(key,save); if (save.isEmpty()) { m_liteApp->settings()->remove(key); } else { m_liteApp->settings()->setValue(key,save); } editorMark->removeMarkList(bpList,LiteApi::BreakPointMarkType); } void LiteDebug::currentEditorChanged(IEditor *editor) { if (canDebug(editor)) { m_startDebugAct->setEnabled(true); } else { m_startDebugAct->setEnabled(false); } } void LiteDebug::startDebugExternal() { SelectExternalDialog dlg(m_liteApp); dlg.loadSetting(); if (dlg.exec() == QDialog::Accepted) { QString cmd = dlg.getCmd(); QString args = dlg.getArgs(); QString work = dlg.getWork(); dlg.saveSetting(); this->startDebug(cmd,args,work); } } void LiteDebug::startDebug(const QString &cmd, const QString &args, const QString &work) { if (!m_debugger) { return; } if (m_debugger->isRunning()) { this->continueRun(); return; } if (!m_envManager) { return; } emit debugBefore(); m_dbgWidget->clearLog(); if (cmd.isEmpty()) { m_liteApp->appendLog("LiteDebug","No debugger command specified",true); return; } if (QFileInfo(cmd).isAbsolute()) { m_debugInfoId = "litedebug/"+cmd; } else { m_debugInfoId = "litedebug/"+work+"/"+cmd; } QDir dir(work); foreach (QFileInfo info, dir.entryInfoList(QStringList() << "*.go",QDir::Files)) { QString filePath = info.filePath(); bool ok = false; if (m_liteApp->editorManager()->findEditor(filePath,true)) { continue; } m_fileBpMap.remove(filePath); foreach(QString bp,m_liteApp->globalCookie().value(QString("bp_%1").arg(filePath)).toStringList()) { int i = bp.toInt(&ok); if (ok && i >= 0) { m_fileBpMap.insert(filePath,i); } } } foreach(LiteApi::IEditor *editor, m_liteApp->editorManager()->editorList()) { LiteApi::IEditorMark *editorMark = LiteApi::findExtensionObject<LiteApi::IEditorMark*>(editor,"LiteApi.IEditorMark"); if (!editorMark) { continue; } QString path = editor->filePath(); m_fileBpMap.remove(path); foreach(int i,editorMark->markLinesByType(LiteApi::BreakPointMarkType)) { m_fileBpMap.insert(path,i); } } LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (editor) { m_startDebugFile = editor->filePath(); } m_debugger->setInitBreakTable(m_fileBpMap); m_debugger->setEnvironment(LiteApi::getGoEnvironment(m_liteApp).toStringList()); m_debugger->setWorkingDirectory(work); QString icmd = cmd; if (icmd.contains(" ")) { icmd = "\""+icmd+"\""; } if (!m_debugger->start(icmd,args)) { m_liteApp->appendLog("LiteDebug","Failed to start debugger",true); } } QWidget *LiteDebug::widget() { return m_widget; } bool LiteDebug::canDebug(IEditor *editor) const { if (editor && m_debugMimeTypes.contains(editor->mimeType())) { return true; } return false; } LiteApi::IDebuggerManager *LiteDebug::debugManager() const { return m_manager; } bool LiteDebug::isRunning() const { return m_debugger && m_debugger->isRunning(); } void LiteDebug::setDebugger(LiteApi::IDebugger *debug) { if (m_debugger) { disconnect(m_debugger,0,this,0); } m_debugger = debug; if (m_debugger) { connect(m_debugger,SIGNAL(debugStarted()),this,SLOT(debugStarted())); connect(m_debugger,SIGNAL(debugStoped()),this,SLOT(debugStoped())); connect(m_debugger,SIGNAL(debugLog(LiteApi::DEBUG_LOG_TYPE,QString)),this,SLOT(debugLog(LiteApi::DEBUG_LOG_TYPE,QString))); connect(m_debugger,SIGNAL(setCurrentLine(QString,int)),this,SLOT(setCurrentLine(QString,int))); connect(m_debugger,SIGNAL(gotoLine(QString,int)),this,SLOT(gotoLine(QString,int))); connect(m_debugger,SIGNAL(debugLoaded()),this,SLOT(debugLoaded())); } m_dbgWidget->setDebugger(m_debugger); } void LiteDebug::debugLog(LiteApi::DEBUG_LOG_TYPE type, const QString &log) { switch(type) { case LiteApi::DebugConsoleLog: m_dbgWidget->appendLog(log); break; case LiteApi::DebugRuntimeLog: m_output->appendTag(QString("%1\n").arg(log)); break; case LiteApi::DebugErrorLog: m_output->append(QString("%1\n").arg(log)); break; case LiteApi::DebugApplationLog: m_output->append(log); break; } } void LiteDebug::startDebug() { if (!m_debugger) { return; } if (m_debugger->isRunning()) { m_debugger->continueRun(); return; } if (!m_liteBuild) { return; } LiteApi::IBuild *build = m_liteBuild->buildManager()->currentBuild(); if (!build) { return; } foreach (LiteApi::BuildAction *act, build->actionList()) { if (act && act->isDebug() && act->id().toLower() == "debug") { m_liteBuild->execBuildAction(build,act); return; } } } void LiteDebug::continueRun() { if (!m_debugger || !m_debugger->isRunning()) { return; } m_debugger->continueRun(); } void LiteDebug::runToLine() { if (!m_debugger || !m_debugger->isRunning()) { return; } LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (!editor) { return; } LiteApi::ITextEditor *textEditor = LiteApi::findExtensionObject<LiteApi::ITextEditor*>(editor,"LiteApi.ITextEditor"); if (!textEditor) { return; } QString filePath = textEditor->filePath(); if (filePath.isEmpty()) { return; } //QString fileName = QFileInfo(filePath).fileName(); m_debugger->runToLine(filePath,textEditor->line()); } void LiteDebug::stopDebug() { if (!m_debugger || !m_debugger->isRunning()) { return; } m_debugger->stop(); } void LiteDebug::stepOver() { if (!m_debugger || !m_debugger->isRunning()) { return; } m_debugger->stepOver(); } void LiteDebug::stepInto() { if (!m_debugger || !m_debugger->isRunning()) { return; } m_debugger->stepInto(); } void LiteDebug::stepOut() { if (!m_debugger || !m_debugger->isRunning()) { return; } m_debugger->stepOut(); } void LiteDebug::showLine() { if (m_lastLine.fileName.isEmpty()) { return; } LiteApi::gotoLine(m_liteApp,m_lastLine.fileName,m_lastLine.line,0,true,true); } void LiteDebug::removeAllBreakPoints() { LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (!editor) { return; } LiteApi::IEditorMark *editorMark = LiteApi::findExtensionObject<LiteApi::IEditorMark*>(editor,"LiteApi.IEditorMark"); if (!editorMark) { return; } LiteApi::ITextEditor *textEditor = LiteApi::findExtensionObject<LiteApi::ITextEditor*>(editor,"LiteApi.ITextEditor"); if (!textEditor) { return; } QString filePath = textEditor->filePath(); QList<int> bpList = editorMark->markLinesByType(LiteApi::BreakPointMarkType); foreach(int line, bpList) { m_fileBpMap.remove(filePath,line); if (m_debugger && m_debugger->isRunning()) { m_debugger->removeBreakPoint(filePath,line); } } editorMark->removeMarkList(bpList,LiteApi::BreakPointMarkType); } void LiteDebug::toggleBreakPoint() { LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (!editor) { return; } LiteApi::IEditorMark *editorMark = LiteApi::findExtensionObject<LiteApi::IEditorMark*>(editor,"LiteApi.IEditorMark"); if (!editorMark) { return; } LiteApi::ITextEditor *textEditor = LiteApi::findExtensionObject<LiteApi::ITextEditor*>(editor,"LiteApi.ITextEditor"); if (!textEditor) { return; } int line = textEditor->line(); QString fileName = editor->filePath(); if (fileName.isEmpty()) { return; } QList<int> marks = editorMark->markTypesByLine(line); if (marks.contains(LiteApi::BreakPointMarkType)) { editorMark->removeMark(line,LiteApi::BreakPointMarkType); m_fileBpMap.remove(fileName,line); if (m_debugger && m_debugger->isRunning()) { m_debugger->removeBreakPoint(fileName,line); } } else { editorMark->addMark(line,LiteApi::BreakPointMarkType); m_fileBpMap.insert(fileName,line); if (m_debugger && m_debugger->isRunning()) { m_debugger->insertBreakPoint(fileName,line); } } } void LiteDebug::clearLastLine() { if (!m_lastLine.fileName.isEmpty()) { LiteApi::IEditor *lastEditor = m_liteApp->editorManager()->findEditor(m_lastLine.fileName,true); if (lastEditor) { LiteApi::IEditorMark *lastMark = LiteApi::findExtensionObject<LiteApi::IEditorMark*>(lastEditor,"LiteApi.IEditorMark"); if (lastMark) { lastMark->removeMark(m_lastLine.line,LiteApi::CurrentLineMarkType); } } } m_lastLine.fileName.clear(); } void LiteDebug::debugLoaded() { if (!m_debugInfoId.isEmpty()) { m_dbgWidget->loadDebugInfo(m_debugInfoId); } } void LiteDebug::debugStarted() { m_startDebugAct->setEnabled(false); m_continueAct->setEnabled(true); m_stopDebugAct->setEnabled(true); m_showLineAct->setEnabled(true); m_stepOverAct->setEnabled(true); m_stepIntoAct->setEnabled(true); m_stepOutAct->setEnabled(true); m_runToLineAct->setEnabled(true); m_output->setReadOnly(false); //m_liteApp->outputManager()->setCurrentOutput(m_output); m_outputAct->setChecked(true); m_widget->show(); emit debugVisible(true); } void LiteDebug::debugStoped() { m_startDebugAct->setEnabled(true); m_continueAct->setEnabled(false); m_stopDebugAct->setEnabled(false); m_stepOverAct->setEnabled(false); m_showLineAct->setEnabled(false); m_stepIntoAct->setEnabled(false); m_stepOutAct->setEnabled(false); m_runToLineAct->setEnabled(false); clearLastLine(); m_output->setReadOnly(true); //m_liteApp->outputManager()->setCurrentOutput(m_output); if (!m_debugInfoId.isEmpty()) m_dbgWidget->saveDebugInfo(m_debugInfoId); m_widget->hide(); if (!m_startDebugFile.isEmpty()) { m_liteApp->fileManager()->openEditor(m_startDebugFile,true); } if (!m_removeDebugFilePath.isEmpty()) { QFile::remove(m_removeDebugFilePath); } m_removeDebugFilePath.clear(); emit debugVisible(false); emit debugEnd(); } void LiteDebug::setCurrentLine(const QString &fileName, int line) { bool center = true; if (m_lastLine.fileName == fileName) { center = false; } clearLastLine(); if (QFile::exists(fileName)) { LiteApi::IEditor *editor = m_liteApp->fileManager()->openEditor(fileName,true); if (editor) { m_lastLine.fileName = fileName; m_lastLine.line = line; LiteApi::ITextEditor *textEditor = LiteApi::findExtensionObject<LiteApi::ITextEditor*>(editor,"LiteApi.ITextEditor"); if (textEditor) { textEditor->gotoLine(line,0,center); } LiteApi::IEditorMark *editMark = LiteApi::findExtensionObject<LiteApi::IEditorMark*>(editor,"LiteApi.IEditorMark"); if (editMark) { editMark->addMark(line,LiteApi::CurrentLineMarkType); } } } if (m_bLastDebugCmdInput) { m_bLastDebugCmdInput = false; m_dbgWidget->setInputFocus(); } } void LiteDebug::gotoLine(const QString &fileName, int line) { if (QFile::exists(fileName)) { LiteApi::IEditor *editor = m_liteApp->fileManager()->openEditor(fileName,true); if (editor) { LiteApi::ITextEditor *textEditor = LiteApi::findExtensionObject<LiteApi::ITextEditor*>(editor,"LiteApi.ITextEditor"); if (textEditor) { textEditor->gotoLine(line,0,true); } // LiteApi::IEditorMark *editMark = LiteApi::findExtensionObject<LiteApi::IEditorMark*>(editor,"LiteApi.IEditorMark"); // if (editMark) { // editMark->addMark(line,LiteApi::CurrentLineMarkType); // } } } } void LiteDebug::debugCmdInput() { m_bLastDebugCmdInput = true; } bool LiteDebug::execGocommand(const QStringList &args, const QString &work, bool showLog) { QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); QString gocmd = FileUtil::lookupGoBin("go",m_liteApp,env,false); if (gocmd.isEmpty()) { debugLog(LiteApi::DebugRuntimeLog,QString("go command not find!").arg(args.join(" "),work)); return false; } debugLog(LiteApi::DebugRuntimeLog,QString("%1 %2 [%3]").arg(gocmd).arg(args.join(" "),work)); QProcess process; process.setWorkingDirectory(work); process.setEnvironment(LiteApi::getGoEnvironment(m_liteApp).toStringList()); process.start(gocmd,args); if (!process.waitForFinished()) { return false; } int code = process.exitCode(); if (code == 0) { return true; } if (showLog) { QByteArray data = process.readAllStandardError(); debugLog(LiteApi::DebugErrorLog,QString::fromUtf8(data)); } return false; } void LiteDebug::enterAppInputText(QString text) { if (m_debugger && m_debugger->isRunning()) { m_debugger->enterAppText(text); } } void LiteDebug::hideDebug() { m_widget->hide(); emit debugVisible(false); }
27,136
C++
.cpp
708
31.75565
140
0.653764
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,440
litedebugoptionfactory.cpp
visualfc_liteide/liteidex/src/plugins/litedebug/litedebugoptionfactory.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: litedebugoptionfactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "litedebugoption.h" #include "litedebugoptionfactory.h" #include "litedebug_global.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end LiteDebugOptionFactory::LiteDebugOptionFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IOptionFactory(parent), m_liteApp(app) { } QStringList LiteDebugOptionFactory::mimeTypes() const { return QStringList() << OPTION_LITEDEBUG; } LiteApi::IOption *LiteDebugOptionFactory::create(const QString &mimeType) { if (mimeType == OPTION_LITEDEBUG) { return new LiteDebugOption(m_liteApp,this); } return 0; }
1,925
C++
.cpp
50
36.24
91
0.69054
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,441
debugmanager.cpp
visualfc_liteide/liteidex/src/plugins/litedebug/debugmanager.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: debugmanager.cpp // Creator: visualfc <visualfc@gmail.com> #include "debugmanager.h" #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end DebugManager::DebugManager(QObject *parent) : IDebuggerManager(parent), m_currentDebug(0) { } DebugManager::~DebugManager() { qDeleteAll(m_debugList); } void DebugManager::addDebugger(IDebugger *debug) { m_debugList.append(debug); } void DebugManager::removeDebugger(IDebugger *debug) { m_debugList.removeOne(debug); } IDebugger *DebugManager::findDebugger(const QString &mimeType) { foreach(IDebugger *debug, m_debugList) { if (debug->mimeType() == mimeType) { return debug; } } return 0; } QList<IDebugger*> DebugManager::debuggerList() const { return m_debugList; } void DebugManager::setCurrentDebugger(IDebugger *debug) { m_currentDebug = debug; emit currentDebuggerChanged(m_currentDebug); } IDebugger *DebugManager::currentDebugger() { return m_currentDebug; }
2,263
C++
.cpp
72
28.902778
82
0.689276
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,442
gdbdebuggeroption.cpp
visualfc_liteide/liteidex/src/plugins/gdbdebugger/gdbdebuggeroption.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: gdbdebuggeroption.cpp // Creator: visualfc <visualfc@gmail.com> #include "gdbdebuggeroption.h" #include "ui_gdbdebuggeroption.h" #include "gdbdebugger_global.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GdbDebuggerOption::GdbDebuggerOption(LiteApi::IApplication *app,QObject *parent) : LiteApi::IOption(parent), m_liteApp(app), m_widget(new QWidget), ui(new Ui::GdbDebuggerOption) { ui->setupUi(m_widget); } GdbDebuggerOption::~GdbDebuggerOption() { delete m_widget; delete ui; } QWidget *GdbDebuggerOption::widget() { return m_widget; } QString GdbDebuggerOption::name() const { return "GdbDebugger"; } QString GdbDebuggerOption::mimeType() const { return OPTION_GDBDEBUGGER; } void GdbDebuggerOption::load() { ui->useTtyCheckBox->setChecked(isGdbDebuggerUseTty(m_liteApp)); } void GdbDebuggerOption::save() { m_liteApp->settings()->setValue(GDBDEBUGGER_USETTY,ui->useTtyCheckBox->isChecked()); } bool isGdbDebuggerUseTty(LiteApi::IApplication *app) { #ifdef Q_OS_WIN return app->settings()->value(GDBDEBUGGER_USETTY,true).toBool(); #else return app->settings()->value(GDBDEBUGGER_USETTY,false).toBool(); #endif }
2,445
C++
.cpp
75
30.4
88
0.703092
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,443
gdbdebuggeroptionfactory.cpp
visualfc_liteide/liteidex/src/plugins/gdbdebugger/gdbdebuggeroptionfactory.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: gdbdebuggeroptionfactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "gdbdebuggeroption.h" #include "gdbdebuggeroptionfactory.h" #include "gdbdebugger_global.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GdbDebuggerOptionFactory::GdbDebuggerOptionFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IOptionFactory(parent), m_liteApp(app) { } QStringList GdbDebuggerOptionFactory::mimeTypes() const { return QStringList() << OPTION_GDBDEBUGGER; } LiteApi::IOption *GdbDebuggerOptionFactory::create(const QString &mimeType) { if (mimeType == OPTION_GDBDEBUGGER) { return new GdbDebuggerOption(m_liteApp,this); } return 0; }
1,947
C++
.cpp
50
36.68
95
0.694136
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,444
gdbdebugger.cpp
visualfc_liteide/liteidex/src/plugins/gdbdebugger/gdbdebugger.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: gdbdebugger.cpp // Creator: visualfc <visualfc@gmail.com> #include "gdbdebugger.h" #include "fileutil/fileutil.h" #include "processex/processex.h" #include "gdbdebuggeroption.h" #include "../litedebug/litedebug_global.h" #include <QStandardItemModel> #include <QProcess> #include <QFile> #include <QDir> #include <QFileInfo> #include <QTextCodec> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end static void GdbMiValueToItem(QStandardItem *item, const GdbMiValue &value) { switch (value.type()) { case GdbMiValue::Invalid: item->appendRow(new QStandardItem("Invalid")); break; case GdbMiValue::Const: if (value.name().isEmpty()) { item->appendRow(new QStandardItem(QString(value.data()))); } else { item->appendRow(new QStandardItem(QString(value.name()+"="+value.data()))); } break; case GdbMiValue::List: { QStandardItem *in = new QStandardItem(QString(value.name())); item->appendRow(in); for (int i = 0; i < value.childCount(); i++) { QStandardItem *iv = new QStandardItem(QString("[%1]").arg(i)); in->appendRow(iv); GdbMiValueToItem(iv,value.childAt(i)); } break; } case GdbMiValue::Tuple: { QStandardItem *iv = item; if (!value.name().isEmpty()) { iv = new QStandardItem(QString(value.name())); item->appendRow(iv); } foreach (const GdbMiValue &v, value.children()) { GdbMiValueToItem(iv,v); } break; } } } GdbDebugger::GdbDebugger(LiteApi::IApplication *app, QObject *parent) : LiteApi::IDebugger(parent), m_liteApp(app), m_envManager(0), m_tty(0) { m_process = new QProcess(this); m_asyncModel = new QStandardItemModel(this); m_asyncItem = new QStandardItem; m_asyncModel->appendRow(m_asyncItem); /* m_asyncModel->setHeaderData(0,Qt::Horizontal,"Reason"); m_asyncModel->setHeaderData(1,Qt::Horizontal,"Address"); m_asyncModel->setHeaderData(2,Qt::Horizontal,"Function"); m_asyncModel->setHeaderData(3,Qt::Horizontal,"File"); m_asyncModel->setHeaderData(4,Qt::Horizontal,"Line"); m_asyncModel->setHeaderData(5,Qt::Horizontal,"Thread ID"); m_asyncModel->setHeaderData(6,Qt::Horizontal,"Stoped Threads"); */ m_varsModel = new QStandardItemModel(0,3,this); m_varsModel->setHeaderData(0,Qt::Horizontal,"Name"); m_varsModel->setHeaderData(1,Qt::Horizontal,"Value"); m_varsModel->setHeaderData(2,Qt::Horizontal,"Type"); m_watchModel = new QStandardItemModel(0,3,this); m_watchModel->setHeaderData(0,Qt::Horizontal,"Name"); m_watchModel->setHeaderData(1,Qt::Horizontal,"Value"); m_watchModel->setHeaderData(2,Qt::Horizontal,"Type"); m_framesModel = new QStandardItemModel(0,5,this); m_framesModel->setHeaderData(0,Qt::Horizontal,"Level"); m_framesModel->setHeaderData(1,Qt::Horizontal,"Address"); m_framesModel->setHeaderData(2,Qt::Horizontal,"Function"); m_framesModel->setHeaderData(3,Qt::Horizontal,"File"); m_framesModel->setHeaderData(4,Qt::Horizontal,"Line"); m_libraryModel = new QStandardItemModel(0,2,this); m_libraryModel->setHeaderData(0,Qt::Horizontal,"Id"); m_libraryModel->setHeaderData(1,Qt::Horizontal,"Thread Groups"); m_gdbinit = false; m_gdbexit = false; connect(app,SIGNAL(loaded()),this,SLOT(appLoaded())); connect(m_process,SIGNAL(started()),this,SIGNAL(debugStarted())); connect(m_process,SIGNAL(finished(int)),this,SLOT(finished(int))); connect(m_process,SIGNAL(error(QProcess::ProcessError)),this,SLOT(error(QProcess::ProcessError))); connect(m_process,SIGNAL(readyReadStandardError()),this,SLOT(readStdError())); connect(m_process,SIGNAL(readyReadStandardOutput()),this,SLOT(readStdOutput())); } GdbDebugger::~GdbDebugger() { if (m_process) { delete m_process; } } void GdbDebugger::appLoaded() { m_envManager = LiteApi::findExtensionObject<LiteApi::IEnvManager*>(m_liteApp,"LiteApi.IEnvManager"); } QString GdbDebugger::mimeType() const { return QLatin1String("debugger/gdb"); } QAbstractItemModel *GdbDebugger::debugModel(LiteApi::DEBUG_MODEL_TYPE type) { if (type == LiteApi::ASYNC_MODEL) { return m_asyncModel; } else if (type == LiteApi::VARS_MODEL) { return m_varsModel; } else if (type == LiteApi::WATCHES_MODEL) { return m_watchModel; }else if (type == LiteApi::FRAMES_MODEL) { return m_framesModel; } else if (type == LiteApi::LIBRARY_MODEL) { return m_libraryModel; } return 0; } void GdbDebugger::setWorkingDirectory(const QString &dir) { m_process->setWorkingDirectory(dir); } void GdbDebugger::setEnvironment (const QStringList &environment) { m_process->setEnvironment(environment); } bool GdbDebugger::start(const QString &program, const QString &arguments) { if (!m_envManager) { return false; } QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); QString goroot = env.value("GOROOT"); if (!goroot.isEmpty()) { m_runtimeFilePath = QFileInfo(QDir(goroot),"src/pkg/runtime/").path(); } QStringList argsList; if (isGdbDebuggerUseTty(m_liteApp)) { if (!m_tty) { m_tty = LiteApi::createTty(m_liteApp,this); if (m_tty) { connect(m_tty,SIGNAL(byteDelivery(QByteArray)),this,SLOT(readTty(QByteArray))); } } if (m_tty && m_tty->listen()) { argsList << "--tty="+m_tty->serverName(); } else if (m_tty) { qDebug() << "error" << m_tty->errorString() << m_tty->serverName(); } } QStringList argsListInfo; argsList << "--interpreter=mi"; argsList << "--args " << program; argsListInfo << "--args " << program; if (!arguments.isEmpty()) { argsList << arguments; argsListInfo << arguments; } QString gdb = env.value("LITEIDE_GDB",""); if (gdb.isEmpty()) { #ifdef Q_OS_WIN if (env.value("GOARCH") != "386") { if (FileUtil::lookPath("gdb64",env,true).isEmpty()) { gdb = "gdb"; } } else { gdb = "gdb"; } #else gdb = "gdb"; #endif } m_gdbFilePath = FileUtil::lookPath(gdb,env,true); if (m_gdbFilePath.isEmpty()) { m_liteApp->appendLog("GdbDebugger",gdb+" was not found on system PATH (hint: is GDB installed?)",true); return false; } clear(); #ifdef Q_OS_WIN m_process->setNativeArguments(argsList.join(" ")); m_process->start("\""+m_gdbFilePath+"\""); #else m_process->start(m_gdbFilePath + " " + argsList.join(" ")); #endif QString log = QString("%1 %2 [%3]").arg(m_gdbFilePath).arg(argsList.join(" ")).arg(m_process->workingDirectory()); emit debugLog(LiteApi::DebugRuntimeLog,log); return true; } void GdbDebugger::stop() { command("-gdb-exit"); if (!m_process->waitForFinished(300)) { m_process->kill(); } } bool GdbDebugger::isRunning() { return m_process->state() != QProcess::NotRunning; } void GdbDebugger::continueRun() { command("-exec-continue"); } void GdbDebugger::stepOver() { command("-exec-next"); } void GdbDebugger::stepInto() { command("-exec-step"); } void GdbDebugger::stepOut() { command("-exec-finish"); } void GdbDebugger::runToLine(const QString &fileName, int line) { line++; GdbCmd cmd; QStringList args; args << "-break-insert"; args << "-t"; args << QString("%1:%2").arg(fileName).arg(line); cmd.setCmd(args); command(cmd); command("-exec-continue"); } void GdbDebugger::createWatch(const QString &var) { QString value; if (value.contains(".")) { value = "\'"+var+"\'"; } else { value = var; } createWatchHelp(var,false,true); } void GdbDebugger::removeWatch(const QString &name) { removeWatchHelp(name,true,true); } void GdbDebugger::removeAllWatch() { //removeWatchHelp foreach (QString name, m_watchList) { removeWatchHelp(name,true,true); } } void GdbDebugger::createWatchHelp(const QString &var, bool floating, bool watchModel) { GdbCmd cmd; QStringList args; args << "-var-create"; args << "-"; if (floating) { args << "@"; } else { args << "*"; } args << var; cmd.setCmd(args); cmd.insert("var",var); if (watchModel) { cmd.insert("watchModel",true); } command(cmd); } void GdbDebugger::removeWatchHelp(const QString &value, bool byName, bool children) { QString name; QString var; if (byName) { name = value; var = m_varNameMap.key(name); } else { var = value; name = m_varNameMap.value(var); } QStringList args; args << "-var-delete"; if (children) { args << "-c"; } args << name; GdbCmd cmd; cmd.setCmd(args); cmd.insert("var",var); cmd.insert("name",name); cmd.insert("children",children); command(cmd); } void GdbDebugger::showFrame(QModelIndex index) { QStandardItem* file = m_framesModel->item( index.row(), 3 ); QStandardItem* line = m_framesModel->item( index.row(), 4 ); if( !file || !line ) { return; } QString filename = file->text(); int lineno = line->text().toInt(); if( lineno <= 0 ) { return; } emit gotoLine(filename, lineno - 1 ); } void GdbDebugger::dbclickItem(QModelIndex index, LiteApi::DEBUG_MODEL_TYPE type) { } void GdbDebugger::expandItem(QModelIndex index, LiteApi::DEBUG_MODEL_TYPE type) { QStandardItem *parent = 0; if (type == LiteApi::VARS_MODEL) { parent = m_varsModel->itemFromIndex(index); } else if (type == LiteApi::WATCHES_MODEL) { parent = m_watchModel->itemFromIndex(index); } if (!parent) { return; } if (parent->data(VarExpanded).toInt() == 1) { return; } parent->setData(1,VarExpanded); for (int i = 0; i < parent->rowCount(); i++) { QStandardItem *item = parent->child(i); QString name = item->data(VarNameRole).toString(); int num = item->data(VarNumChildRole).toInt(); if (num > 0) { updateVarListChildren(name); } } } void GdbDebugger::setInitBreakTable(const QMultiMap<QString,int> &bks) { m_initBks = bks; } void GdbDebugger::setInitWatchList(const QStringList &names) { foreach (QString name, names) { createWatch(name); } } void GdbDebugger::insertBreakPoint(const QString &fileName, int line) { line++; QString location = QString("%1:%2").arg(fileName).arg(line); if (m_locationBkMap.contains(location)) { return; } QStringList args; args << "-break-insert"; args << QString("%1:%2").arg(fileName).arg(line); GdbCmd cmd; cmd.setCmd(args); cmd.insert("file",fileName); cmd.insert("line",line); command(cmd); } void GdbDebugger::removeBreakPoint(const QString &fileName, int line) { line++; QString location = QString("%1:%2").arg(fileName).arg(line); QString number = m_locationBkMap.key(location); if (number.isEmpty()) { return; } QStringList args; args << "-break-delete"; args << number; GdbCmd cmd; cmd.setCmd(args); command(cmd); } void GdbDebugger::command_helper(const GdbCmd &cmd, bool emitOut) { m_token++; QByteArray buf = cmd.makeCmd(m_token); if (emitOut) { emit debugLog(LiteApi::DebugConsoleLog,">>> "+QString::fromUtf8(buf)); } #ifdef Q_OS_WIN buf.append("\r\n"); #else buf.append("\n"); #endif m_tokenCookieMap.insert(m_token,cmd.cookie()); m_process->write(buf); } void GdbDebugger::command(const GdbCmd &cmd) { command_helper(cmd,true); } void GdbDebugger::enterAppText(const QString &text) { if (m_tty) { m_tty->write(text.toUtf8()); } else { m_process->write(text.toUtf8()); } } void GdbDebugger::enterDebugText(const QString &text) { command(text); } void GdbDebugger::command(const QByteArray &cmd) { command_helper(GdbCmd(cmd),false); } void GdbDebugger::readStdError() { emit debugLog(LiteApi::DebugErrorLog,QString::fromUtf8(m_process->readAllStandardError())); } static bool isNameChar(char c) { // could be 'stopped' or 'shlibs-added' return (c >= 'a' && c <= 'z') || c == '-'; } /* 27.4.2 gdb/mi Output Syntax The output from gdb/mi consists of zero or more out-of-band records followed, optionally, by a single result record. This result record is for the most recent command. The sequence of output records is terminated by (gdb). If an input command was prefixed with a token then the corresponding output for that command will also be prefixed by that same token. If an input command was prefixed with a token then the corresponding output for that command will also be prefixed by that same token. output -> ( out-of-band-record )* [ result-record ] "(gdb)" nl result-record -> [ token ] "^" result-class ( "," result )* nl out-of-band-record -> async-record | stream-record async-record -> exec-async-output | status-async-output | notify-async-output exec-async-output -> [ token ] "*" async-output status-async-output -> [ token ] "+" async-output notify-async-output -> [ token ] "=" async-output async-output -> async-class ( "," result )* nl result-class -> "done" | "running" | "connected" | "error" | "exit" async-class -> "stopped" | others (where others will be added depending on the needs¡ªthis is still in development). result -> variable "=" value variable -> string value -> const | tuple | list const -> c-string tuple -> "{}" | "{" result ( "," result )* "}" list -> "[]" | "[" value ( "," value )* "]" | "[" result ( "," result )* "]" stream-record -> console-stream-output | target-stream-output | log-stream-output console-stream-output -> "~" c-string target-stream-output -> "@" c-string log-stream-output -> "&" c-string nl -> CR | CR-LF */ void GdbDebugger::handleResponse(const QByteArray &buff) { if (buff.isEmpty() || buff == "(gdb) ") return; const char *from = buff.constData(); const char *to = from + buff.size(); const char *inner; int token = -1; // Token is a sequence of numbers. for (inner = from; inner != to; ++inner) if (*inner < '0' || *inner > '9') break; if (from != inner) { token = QByteArray(from, inner - from).toInt(); from = inner; } // Next char decides kind of response. const char c = *from++; switch (c) { case '*': case '+': case '=': { QByteArray asyncClass; for (; from != to; ++from) { const char c = *from; if (!isNameChar(c)) break; asyncClass += *from; } GdbMiValue result; while (from != to) { GdbMiValue data; if (*from != ',') { // happens on archer where we get // 23^running <NL> *running,thread-id="all" <NL> (gdb) result.m_type = GdbMiValue::Tuple; break; } ++from; // skip ',' data.parseResultOrValue(from, to); if (data.isValid()) { //qDebug() << "parsed result:" << data.toString(); result.m_children += data; result.m_type = GdbMiValue::Tuple; } } handleAsyncClass(asyncClass,result); break; } case '~': handleConsoleStream(GdbMiValue::parseCString(from, to)); break; case '@': handleTargetStream(GdbMiValue::parseCString(from, to)); break; case '&': handleLogStream(GdbMiValue::parseCString(from, to)); break; case '^': { GdbResponse response; response.token = token; for (inner = from; inner != to; ++inner) if (*inner < 'a' || *inner > 'z') break; QByteArray resultClass = QByteArray::fromRawData(from, inner - from); if (resultClass == "done") { response.resultClass = GdbResultDone; } else if (resultClass == "running") { response.resultClass = GdbResultRunning; } else if (resultClass == "connected") { response.resultClass = GdbResultConnected; } else if (resultClass == "error") { response.resultClass = GdbResultError; } else if (resultClass == "exit") { response.resultClass = GdbResultExit; } else { response.resultClass = GdbResultUnknown; } from = inner; if (from != to) { if (*from == ',') { ++from; response.data.parseTuple_helper(from, to); response.data.m_type = GdbMiValue::Tuple; response.data.m_name = "data"; } else { // Archer has this. response.data.m_type = GdbMiValue::Tuple; response.data.m_name = "data"; } } if (m_tokenCookieMap.contains(token)) { response.cookie = m_tokenCookieMap.take(token); } handleResultRecord(response); break; } default: { from--; QByteArray out(from,to-from); out.append("\n"); emit debugLog(LiteApi::DebugApplationLog,QString::fromUtf8(out)); break; } } } void GdbDebugger::handleStopped(const GdbMiValue &result) { QByteArray reason = result.findChild("reason").data(); m_handleState.setReason(reason); m_handleState.setStopped(true); if (reason.startsWith("exited")) { m_handleState.setExited(true); m_handleState.setReason(reason); return; } GdbMiValue frame = result.findChild("frame"); if (frame.isValid()) { QString fullname = frame.findChild("fullname").data(); QString file = frame.findChild("file").data(); QString line = frame.findChild("line").data(); if (!fullname.isEmpty()) { emit setCurrentLine(fullname,line.toInt()-1); } else if (!file.isEmpty()) { //fix go build bug, not find fullname //file="C:/Users/ADMINI~1/AppData/Local/Temp/2/bindist308287094/go/src/pkg/fmt/print.go" int i = file.indexOf("/go/src/pkg"); if (i > 0) { QString fullname = LiteApi::getGOROOT(m_liteApp)+file.right(file.length()-i-3); emit setCurrentLine(fullname,line.toInt()-1); } } } } void GdbDebugger::handleLibrary(const GdbMiValue &result) { QString id = result.findChild("id").data(); QString thread_group = result.findChild("thread-group").data(); m_libraryModel->appendRow(QList<QStandardItem*>() << new QStandardItem(id) << new QStandardItem(thread_group) ); } void GdbDebugger::handleAsyncClass(const QByteArray &asyncClass, const GdbMiValue &result) { m_asyncItem->removeRows(0,m_asyncItem->rowCount()); m_asyncItem->setText(asyncClass); //QStandardItem *item = new QStandardItem(QString(asyncClass)); GdbMiValueToItem(m_asyncItem,result); //m_asyncModel->clear(); //m_asyncModel->appendRow(item); if (asyncClass == "stopped") { handleStopped(result); } else if (asyncClass == "library-loaded") { handleLibrary(result); } emit setExpand(LiteApi::ASYNC_MODEL,m_asyncModel->indexFromItem(m_asyncItem),true); } void GdbDebugger::handleConsoleStream(const QByteArray&) { } void GdbDebugger::handleTargetStream(const QByteArray&) { } void GdbDebugger::handleLogStream(const QByteArray&) { } void GdbDebugger::handleResultStackListFrame(const GdbResponse &response, QMap<QString,QVariant>&) { //10000015^done,stack=[frame={level="0",addr="0x0040113f",func="main.main",file="F:/hg/debug_test/hello/main.go",fullname="F:/hg/debug_test/hello/main.go",line="36"},frame={level="1",addr="0x00401f8a",func="runtime.mainstart",file="386/asm.s",fullname="c:/go/src/pkg/runtime/386/asm.s",line="96"},frame={level="2",addr="0x0040bcfe",func="runtime.initdone",file="/go/src/pkg/runtime/proc.c",fullname="c:/go/src/pkg/runtime/proc.c",line="242"},frame={level="3",addr="0x00000000",func="??"}] m_framesModel->removeRows(0,m_framesModel->rowCount()); if (response.resultClass != GdbResultDone) { return; } GdbMiValue stack = response.data.findChild("stack"); if (stack.isList()) { for (int i = 0; i < stack.childCount(); i++) { GdbMiValue child = stack.childAt(i); if (child.isValid() && child.name() == "frame") { QString level = child.findChild("level").data(); QString addr = child.findChild("addr").data(); QString func = child.findChild("func").data(); QString file = child.findChild("file").data(); QString line = child.findChild("line").data(); m_framesModel->appendRow(QList<QStandardItem*>() << new QStandardItem(level) << new QStandardItem(addr) << new QStandardItem(func) << new QStandardItem(file) << new QStandardItem(line) ); } } } } void GdbDebugger::handleResultStackListVariables(const GdbResponse &response, QMap<QString,QVariant>&) { //10000014^done,variables=[{name="v"},{name="x"},{name="pt"},{name="str"},{name="sum1"},{name="y"}] if (response.resultClass != GdbResultDone) { return; } GdbMiValue vars = response.data.findChild("variables"); if (vars.isList()) { foreach (const GdbMiValue &child, vars.m_children) { if (child.isValid()) { QString var = child.findChild("name").data(); if (!m_varNameMap.contains(var)) { createWatchHelp(var,true,false); } } } } } void GdbDebugger::handleResultVarCreate(const GdbResponse &response, QMap<QString,QVariant> &map) { //10000018^done,name="var4",numchild="0",value="4265530",type="int",thread-id="1",has_more="0" //10000019^done,name="var5",numchild="2",value="{...}",type="struct string",thread-id="1",has_more="0" //10000020^done,name="var6",numchild="3",value="0x40bc38",type="struct main.pt *",thread-id="1",has_more="0" if (response.resultClass != GdbResultDone) { return; } QString name = response.data.findChild("name").data(); QString numchild = response.data.findChild("numchild").data(); QString value = response.data.findChild("value").data(); QString type = response.data.findChild("type").data(); QString var = map.value("var").toString(); if (var.isEmpty()) { var = map.value("cmdList").toStringList().last(); } if (m_varNameMap.contains(var)) { var += QString("-%1").arg(response.token); } m_varNameMap.insert(var,name); QStandardItem *item = new QStandardItem(var); item->setData(name,VarNameRole); m_nameItemMap.insert(name,item); if (map.value("watchModel",false).toBool()) { emit watchCreated(name,map.value("var").toString()); m_watchList.append(name); m_watchModel->appendRow(QList<QStandardItem*>() << item << new QStandardItem(value) << new QStandardItem(type) ); } else { m_varsModel->appendRow(QList<QStandardItem*>() << item << new QStandardItem(value) << new QStandardItem(type) ); } int num = numchild.toInt(); item->setData(num,VarNumChildRole); if (num > 0 ){ updateVarListChildren(name); } } void GdbDebugger::handleResultVarListChildren(const GdbResponse &response, QMap<QString,QVariant> &map) { //10000022^done,numchild="2",children=[child={name="var5.str",exp="str",numchild="1",value="0x4115c6 \"\\203\\304\\b\\303d\\213\\r,\"",type="uint8 *",thread-id="1"},child={name="var5.len",exp="len",numchild="0",value="4242460",type="int",thread-id="1"}],has_more="0" if (response.resultClass != GdbResultDone) { return; } GdbMiValue children = response.data.findChild("children"); if (children.isList()) { QString name = map.value("name").toString(); QStandardItem *parent = m_nameItemMap.value(name); if (parent == 0) { return; } int num = response.data.findChild("numchild").data().toInt(); parent->setData(num,VarNumChildRole); for (int i = 0; i < children.childCount(); i++) { GdbMiValue child = children.childAt(i); if (child.name() == "child" && child.isTuple()) { QString name = child.findChild("name").data(); QString exp = child.findChild("exp").data(); QString numchild = response.data.findChild("numchild").data(); QString value = child.findChild("value").data(); QString type = child.findChild("type").data(); QStandardItem *item = new QStandardItem(exp); item->setData(name,VarNameRole); m_nameItemMap.insert(name,item); parent->appendRow(QList<QStandardItem*>() << item << new QStandardItem(value) << new QStandardItem(type) ); int num = numchild.toInt(); item->setData(num,VarNumChildRole); } } } } void GdbDebugger::handleResultVarUpdate(const GdbResponse &response, QMap<QString,QVariant>&) { //10000040^done,changelist=[{name="var2",in_scope="true",type_changed="false",has_more="0"}] if (response.resultClass != GdbResultDone) { return; } GdbMiValue list = response.data.findChild("changelist"); if (list.isList()) { for (int i = 0; i < list.childCount(); i++) { GdbMiValue child = list.childAt(i); if (child.isValid()) { QString name = child.findChild("name").data(); QString in_scope = child.findChild("in_scope").data(); QString type_changed = child.findChild("type_changed").data(); QString var = m_varNameMap.key(name); if (in_scope == "false") { removeWatchHelp(var,false,false); } else { if (type_changed == "true") { //remove watch children removeWatchHelp(var,false,true); //update type updateVarTypeInfo(name); //udpate children updateVarListChildren(name); } //update value updateVarValue(name); } } } } } void GdbDebugger::handleResultVarDelete(const GdbResponse &response, QMap<QString,QVariant> &map) { //10000062^done,ndeleted="1" //10000063^done,ndeleted="0" if (response.resultClass != GdbResultDone) { return; } bool ndeleted = true; if (response.data.findChild("ndeleted").data() == "0") { ndeleted = false; } QString var = map.value("var").toString(); QString name = map.value("name").toString(); QMutableMapIterator<QString,QStandardItem*> i(m_nameItemMap); QString cls = name+"."; while (i.hasNext()) { i.next(); if (i.key().startsWith(cls)) { i.remove(); } } QStandardItemModel *model = m_varsModel; if (m_watchList.contains(name)) { emit watchRemoved(name); m_watchList.removeAll(name); model = m_watchModel; ndeleted = 1; } if (ndeleted) { m_varNameMap.remove(var); m_nameItemMap.remove(name); } for (int i = 0; i < model->rowCount(); i++) { QStandardItem *item = model->item(i,0); if (item->data() == name) { if (ndeleted) { model->removeRow(i); } else { item->removeRows(0,item->rowCount()); item->setData(0,VarExpanded); emit setExpand(LiteApi::VARS_MODEL,model->indexFromItem(item),false); } break; } } } void GdbDebugger::handleResultVarUpdateValue(const GdbResponse &response, QMap<QString,QVariant> &map) { //10000035^done,value="100" if (response.resultClass != GdbResultDone) { return; } QString value = response.data.findChild("value").data(); QString name = map.value("name").toString(); QStandardItem *item = m_nameItemMap.value(name); if (!item) { return; } QStandardItem *parent = item->parent(); QStandardItem *v = 0; if (parent) { v = parent->child(item->row(),1); } else { v = item->model()->item(item->row(),1); } if (v) { v->setData(value,Qt::DisplayRole); #if QT_VERSION >= 0x050000 v->setData(QColor(Qt::red),Qt::TextColorRole); #else v->setData(Qt::red,Qt::TextColorRole); #endif m_varChangedItemList.insert(v); } } void GdbDebugger::handleResultVarUpdateType(const GdbResponse &response, QMap<QString,QVariant> &map) { //10000060^done,type="struct string" if (response.resultClass != GdbResultDone) { return; } QString type = response.data.findChild("type").data(); QString name = map.value("name").toString(); QStandardItem *item = m_nameItemMap.value(name); if (!item) { return; } QStandardItem *parent = item->parent(); QStandardItem *v = 0; if (parent) { v = parent->child(item->row(),2); } else { v = item->model()->item(item->row(),2); } if (v) { v->setData(type,Qt::DisplayRole); #if QT_VERSION >= 0x050000 v->setData(QColor(Qt::red),Qt::TextColorRole); #else v->setData(Qt::red,Qt::TextColorRole); #endif m_varChangedItemList.insert(v); } } void GdbDebugger::handleBreakInsert(const GdbResponse &response, QMap<QString,QVariant>&) { // >>> 10000029-break-insert F:/hg/debug_test/hello/main.go:31 // 10000029^done,bkpt={number="2",type="breakpoint",disp="keep",enabled="y",addr="0x004010dd",func="main.test",file="F:/hg/debug_test/hello/main.go",fullname="F:/hg/debug_test/hello/main.go",line="31",times="0",original-location="F:/hg/debug_test/hello/main.go:31"} // >>> 10000046-break-insert F:/hg/debug_test/hello/main.go:37 // 10000046^done,bkpt={number="3",type="breakpoint",disp="keep",enabled="y",addr="0x0040118a",func="main.main",file="F:/hg/debug_test/hello/main.go",fullname="F:/hg/debug_test/hello/main.go",line="37",times="0",original-location="F:/hg/debug_test/hello/main.go:37"} if (response.resultClass != GdbResultDone) { return; } GdbMiValue bkpt = response.data.findChild("bkpt"); if (bkpt.isTuple()) { QString number = bkpt.findChild("number").data(); QString org_location= bkpt.findChild("original-location").data(); m_locationBkMap.insert(number,org_location); } } void GdbDebugger::handleBreakDelete(const GdbResponse &response, QMap<QString,QVariant> &map) { if (response.resultClass != GdbResultDone) { return; } QStringList cmdList = map.value("cmdList").toStringList(); if (cmdList.size() != 2) { return; } QString number = cmdList.at(1); m_locationBkMap.remove(number); } void GdbDebugger::handleResultRecord(const GdbResponse &response) { if (response.cookie.type() != QVariant::Map) { return; } QMap<QString,QVariant> map = response.cookie.toMap(); QString cmd = map.value("cmd").toString(); if (cmd.isEmpty()) { return; } QStringList cmdList = map.value("cmdList").toStringList(); if (cmdList.isEmpty()) { return; } if (cmdList.at(0) == "-stack-list-variables") { handleResultStackListVariables(response,map); } else if (cmdList.at(0) == "-stack-list-frames") { handleResultStackListFrame(response,map); } else if (cmdList.at(0) == "-var-create") { handleResultVarCreate(response,map); } else if (cmdList.at(0) == "-var-list-children") { handleResultVarListChildren(response,map); } else if (cmdList.at(0) == "-var-update") { handleResultVarUpdate(response,map); } else if (cmdList.at(0) == "-var-delete") { handleResultVarDelete(response,map); } else if (cmdList.at(0) == "-var-evaluate-expression") { handleResultVarUpdateValue(response,map); } else if (cmdList.at(0) == "-var-info-type") { handleResultVarUpdateType(response,map); } else if (cmdList.at(0) == "-break-insert") { handleBreakInsert(response,map); } else if (cmdList.at(0) == "-break-delete") { handleBreakDelete(response,map); } } void GdbDebugger::clear() { m_gdbinit = false; m_gdbexit = false; m_busy = false; m_token = 10000000; m_handleState.clear(); m_varNameMap.clear(); m_watchList.clear(); m_nameItemMap.clear(); m_tokenCookieMap.clear(); m_varChangedItemList.clear(); m_inbuffer.clear(); m_locationBkMap.clear(); m_framesModel->removeRows(0,m_framesModel->rowCount()); m_libraryModel->removeRows(0,m_libraryModel->rowCount()); m_varsModel->removeRows(0,m_varsModel->rowCount()); m_watchModel->removeRows(0,m_watchModel->rowCount()); } void GdbDebugger::initGdb() { command("set unwindonsignal on"); command("set overload-resolution off"); command("handle SIGSEGV nopass stop print"); command("set breakpoint pending on"); command("set width 0"); command("set height 0"); command("set auto-solib-add on"); if (!m_runtimeFilePath.isEmpty()) { #ifdef Q_OS_WIN QStringList pathList = LiteApi::getGOPATH(m_liteApp,false); QString paths; foreach(QString path, pathList) { paths += QDir::fromNativeSeparators(path)+"/src"; paths += ";"; } command("-environment-directory "+m_runtimeFilePath.toLatin1()); //command("-environment-directory "+m_runtimeFilePath.toLatin1()+";"+paths.toLatin1()); command("set substitute-path /go/src/pkg/runtime "+m_runtimeFilePath.toLatin1()); #else command("-environment-directory "+m_runtimeFilePath.toUtf8()); command("set substitute-path /go/src/pkg/runtime "+m_runtimeFilePath.toUtf8()); #endif } //command("set "); QMapIterator<QString,int> i(m_initBks); while (i.hasNext()) { i.next(); QString fileName = i.key(); QList<int> lines = m_initBks.values(fileName); foreach(int line, lines) { insertBreakPoint(fileName,line); } } if (m_liteApp->settings()->value(LITEDEBUG_AUTOBREAKMAIN,false).toBool()) { command("-break-insert main.main"); } command("-exec-run"); debugLoaded(); } void GdbDebugger::updateWatch() { foreach(QStandardItem *item, m_varChangedItemList) { #if QT_VERSION >= 0x050000 item->setData(QColor(Qt::black),Qt::TextColorRole); #else item->setData(Qt::black,Qt::TextColorRole); #endif } m_varChangedItemList.clear(); command("-var-update *"); } void GdbDebugger::updateLocals() { command("-stack-list-variables 0"); } void GdbDebugger::updateFrames() { command("-stack-list-frames"); } void GdbDebugger::updateBreaks() { command("-break-info"); } void GdbDebugger::updateVarTypeInfo(const QString &name) { QStringList args; args << "-var-info-type"; args << name; GdbCmd cmd; cmd.setCmd(args); cmd.insert("name",name); command(cmd); } void GdbDebugger::updateVarListChildren(const QString &name) { GdbCmd cmd; QStringList args; args << "-var-list-children"; args << "1"; args << name; cmd.setCmd(args); cmd.insert("name",name); command(cmd); } void GdbDebugger::updateVarValue(const QString &name) { QStringList args; args << "-var-evaluate-expression"; args << name; GdbCmd cmd; cmd.setCmd(args); cmd.insert("name",name); command(cmd); } void GdbDebugger::readStdOutput() { int newstart = 0; int scan = m_inbuffer.size(); m_inbuffer.append(m_process->readAllStandardOutput()); // This can trigger when a dialog starts a nested event loop. if (m_busy) return; while (newstart < m_inbuffer.size()) { int start = newstart; int end = m_inbuffer.indexOf('\n', scan); if (end < 0) { m_inbuffer.remove(0, start); return; } newstart = end + 1; scan = newstart; if (end == start) continue; #ifdef Q_OS_WIN if (m_inbuffer.at(end - 1) == '\r') { --end; if (end == start) continue; } #endif m_busy = true; QByteArray data = QByteArray::fromRawData(m_inbuffer.constData() + start, end - start); handleResponse(data); m_busy = false; } emit debugLog(LiteApi::DebugConsoleLog,QString::fromUtf8(m_inbuffer)); m_inbuffer.clear(); if (!m_gdbinit) { m_gdbinit = true; initGdb(); } if (m_handleState.exited() && !m_gdbexit) { m_gdbexit = true; stop(); } else if (m_handleState.stopped()) { updateWatch(); updateLocals(); updateFrames(); } m_handleState.clear(); } void GdbDebugger::finished(int code) { clear(); if (m_tty) { m_tty->shutdown(); } emit debugStoped(); emit debugLog(LiteApi::DebugRuntimeLog,QString("Program exited with code %1").arg(code)); } void GdbDebugger::error(QProcess::ProcessError err) { clear(); if (m_tty) { m_tty->shutdown(); } emit debugStoped(); emit debugLog(LiteApi::DebugRuntimeLog,QString("Error! %1").arg(ProcessEx::processErrorText(err))); } void GdbDebugger::readTty(const QByteArray &data) { emit debugLog(LiteApi::DebugApplationLog,QString::fromUtf8(data)); }
40,066
C++
.cpp
1,178
27.366723
492
0.611517
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,445
gdbdebuggerplugin.cpp
visualfc_liteide/liteidex/src/plugins/gdbdebugger/gdbdebuggerplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: gdbdebuggerplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "gdbdebuggerplugin.h" #include "gdbdebugger.h" #include "gdbdebuggeroptionfactory.h" #include "litedebugapi/litedebugapi.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GdbDebuggerPlugin::GdbDebuggerPlugin() { } bool GdbDebuggerPlugin::load(LiteApi::IApplication *app) { LiteApi::IDebuggerManager *manager = LiteApi::getDebugManager(app); if (!manager) { return false; } GdbDebugger *debug = new GdbDebugger(app); manager->addDebugger(debug); manager->setCurrentDebugger(debug); app->optionManager()->addFactory(new GdbDebuggerOptionFactory(app,this)); return true; } QStringList GdbDebuggerPlugin::dependPluginList() const { return QStringList() << "plugin/litedebug"; } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
2,135
C++
.cpp
57
35.157895
82
0.699469
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,446
jsonedit.cpp
visualfc_liteide/liteidex/src/plugins/jsonedit/jsonedit.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: jsonedit.cpp // Creator: visualfc <visualfc@gmail.com> #include "jsonedit.h" #include "liteenvapi/liteenvapi.h" #include "editorutil/editorutil.h" #include <qjson/include/QJson/Parser> #include <qjson/include/QJson/Serializer> #include <QPlainTextEdit> #include <QProcess> #include <QToolBar> #include <QToolButton> #include <QTextCodec> #include <QMenu> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end JsonEdit::JsonEdit(LiteApi::IApplication *app, QObject *parent) : QObject(parent), m_liteApp(app) { LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(this,"JsonEdit"); m_verifyAct = new QAction(tr("Verify"),this); actionContext->regAction(m_verifyAct,"VerifyJson",""); m_formatAct = new QAction(tr("Format Json"),this); actionContext->regAction(m_formatAct,"FormatJson","Ctrl+I"); m_compactAct = new QAction(tr("Compact Json"),this); actionContext->regAction(m_compactAct,"CompactJson",""); connect(m_liteApp->editorManager(),SIGNAL(editorCreated(LiteApi::IEditor*)),this,SLOT(editorCreated(LiteApi::IEditor*))); connect(m_liteApp->editorManager(),SIGNAL(editorSaved(LiteApi::IEditor*)),this,SLOT(editorSaved(LiteApi::IEditor*))); connect(m_verifyAct,SIGNAL(triggered()),this,SLOT(verify())); connect(m_formatAct,SIGNAL(triggered()),this,SLOT(format())); connect(m_compactAct,SIGNAL(triggered()),this,SLOT(compact())); } //void JsonEdit::indentNone() //{ // format(QJson::IndentNone); //} //void JsonEdit::indentCompact() //{ // format(QJson::IndentCompact); //} //void JsonEdit::indentMinimum() //{ // format(QJson::IndentMinimum); //} //void JsonEdit::indentMedium() //{ // format(QJson::IndentMedium); //} //void JsonEdit::indentFull() //{ // format(QJson::IndentFull); //} bool JsonEdit::verifyJson(LiteApi::IEditor *editor) { LiteApi::ILiteEditor *ed = LiteApi::getLiteEditor(editor); if (!ed) { return false; } QJson::Parser parser; bool ok = true; parser.parse(ed->utf8Data(),&ok); if (!ok) { ed->setNavigateHead(LiteApi::EditorNavigateError,"json verify error"); if (parser.errorLine() > 0) { ed->insertNavigateMark(parser.errorLine()-1,LiteApi::EditorNavigateError,parser.errorString(),"Json"); } } else { ed->setNavigateHead(LiteApi::EditorNavigateNormal,"json verify success"); ed->clearAllNavigateMark(LiteApi::EditorNavigateError,"Json"); } return ok; } void JsonEdit::verify() { LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (!editor || editor->mimeType() != "application/json") { return; } verifyJson(editor); } void JsonEdit::format() { LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (!editor || editor->mimeType() != "application/json") { return; } if (!verifyJson(editor)) { return; } fmtEditor(editor,false,false,true,1000); } void JsonEdit::compact() { LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (!editor || editor->mimeType() != "application/json") { return; } if (!verifyJson(editor)) { return; } fmtEditor(editor,true,false,true,1000); } void JsonEdit::fmtEditor(LiteApi::IEditor *editor, bool compact, bool tabs, bool diff,int timeout) { LiteApi::ITextEditor *textEditor = LiteApi::getTextEditor(editor); if (!textEditor) { return; } bool save = !editor->isModified(); QPlainTextEdit *ed = LiteApi::findExtensionObject<QPlainTextEdit*>(editor,"LiteApi.QPlainTextEdit"); if (!ed) { return; } QString text = ed->toPlainText(); if (text.isEmpty()) { return; } QProcess process; process.setEnvironment(LiteApi::getGoEnvironment(m_liteApp).toStringList()); QStringList args; args << "jsonfmt"; if (compact) { args << "-c"; } if (tabs) { args << "-tabs"; } if (diff) { args << "-d"; } QString cmd = LiteApi::getGotools(m_liteApp); process.start(cmd,args); if (!process.waitForStarted(timeout)) { m_liteApp->appendLog("jsonfmt",QString("Timed out after %1ms when starting json format").arg(timeout),false); return; } process.write(text.toUtf8()); process.closeWriteChannel(); if (!process.waitForFinished(timeout*4)) { m_liteApp->appendLog("jsonfmt",QString("Timed out after %1ms while running json format").arg(timeout*4),false); return; } LiteApi::ILiteEditor *liteEditor = LiteApi::getLiteEditor(editor); liteEditor->clearAllNavigateMark(LiteApi::EditorNavigateBad, "Json"); QTextCodec *codec = QTextCodec::codecForName("utf-8"); if (process.exitCode() != 0) { m_liteApp->appendLog("jsonfmt",QString::fromUtf8(process.readAll()),true); return; } QByteArray data = process.readAllStandardOutput(); /* int vpos = -1; QScrollBar *bar = ed->verticalScrollBar(); if (bar) { vpos = bar->sliderPosition(); } */ QByteArray state = editor->saveState(); QTextCursor cur = ed->textCursor(); //int pos = cur.position(); cur.beginEditBlock(); if (diff) { EditorUtil::loadDiff(cur,codec->toUnicode(data)); } else { cur.select(QTextCursor::Document); cur.removeSelectedText(); cur.insertText(codec->toUnicode(data)); } //cur.setPosition(pos); cur.endEditBlock(); ed->setTextCursor(cur); editor->restoreState(state); //ed->setTextCursor(cur); //if (vpos != -1) { // bar->setSliderPosition(vpos); //} if (save) { m_liteApp->editorManager()->saveEditor(editor,false); } } void JsonEdit::editorCreated(LiteApi::IEditor *editor) { if (editor->mimeType() != "application/json") { return; } LiteApi::ILiteEditor *ed = LiteApi::getLiteEditor(editor); if (!ed) { return; } ed->setLineWrap(true); ed->setEnableAutoIndentAction(false); QMenu *menu = LiteApi::getContextMenu(editor); if (menu) { menu->addSeparator(); menu->addAction(m_verifyAct); menu->addAction(m_formatAct); menu->addAction(m_compactAct); } menu = LiteApi::getEditMenu(editor); if (menu) { menu->addSeparator(); menu->addAction(m_verifyAct); menu->addAction(m_formatAct); menu->addAction(m_compactAct); } } void JsonEdit::editorSaved(LiteApi::IEditor *editor) { if (editor->mimeType() != "application/json") { return; } verifyJson(editor); } //void JsonEdit::format(QJson::IndentMode mode) //{ // QJson::Parser parser; // bool ok = true; // QVariant json = parser.parse(m_editor->utf8Data(),&ok); // if (!ok) { // return; // } // QJson::Serializer stream; // stream.setIndentMode(mode); // QByteArray data = stream.serialize(json); // QPlainTextEdit *ed = LiteApi::getPlainTextEdit(m_editor); // if (ed) { // QTextCursor cursor = ed->textCursor(); // cursor.beginEditBlock(); // cursor.select(QTextCursor::Document); // cursor.removeSelectedText(); // cursor.insertText(QString::fromUtf8(data)); // cursor.endEditBlock(); // ed->setTextCursor(cursor); // } //}
8,641
C++
.cpp
262
28.812977
125
0.655135
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,447
jsoneditplugin.cpp
visualfc_liteide/liteidex/src/plugins/jsonedit/jsoneditplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: jsoneditplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "jsoneditplugin.h" #include "jsonedit.h" #include <QtPlugin> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end JsonEditPlugin::JsonEditPlugin() { } bool JsonEditPlugin::load(LiteApi::IApplication *app) { m_liteApp = app; new JsonEdit(m_liteApp,this); return true; } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
1,689
C++
.cpp
46
34.804348
82
0.680708
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,448
gopathmodel.cpp
visualfc_liteide/liteidex/src/plugins/golangtool/gopathmodel.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: gopathmodel.cpp // Creator: visualfc <visualfc@gmail.com> #include "gopathmodel.h" #include <QFileInfo> #include <QDir> #include <QIcon> #include <QFont> #include <QFileIconProvider> #include <QFileSystemWatcher> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end PathNode::PathNode(GopathModel *model) : m_model(model), m_parent(0), m_children(0) { } PathNode::PathNode(GopathModel *model, const QString &path, PathNode *parent) : m_model(model), m_parent(parent), m_children(0), m_path(path) { QFileInfo info(path); if (parent && parent->parent() == 0) { m_text = info.filePath(); } else { m_text = info.fileName(); } if (info.isDir() && !m_path.isEmpty()) { m_model->fileWatcher()->addPath(m_path); } } PathNode::~PathNode() { if (this->isDir() && !m_path.isEmpty()) { m_model->fileWatcher()->removePath(m_path); } if (m_children) { qDeleteAll(m_children->begin(),m_children->end()); delete m_children; } } QList<PathNode*>* PathNode::children() { if (m_children == 0) { m_children = new QList<PathNode*>(); if (!m_path.isEmpty()) { QFileInfo info(m_path); if (info.isDir()) { QDir dir(m_path); foreach(QFileInfo childInfo, dir.entryInfoList(QDir::Dirs|QDir::Files|QDir::NoDotAndDotDot,QDir::DirsFirst)) { m_children->append(new PathNode(this->m_model,childInfo.filePath(),this)); } } } } return m_children; } PathNode* PathNode::parent() { return m_parent; } PathNode* PathNode::child(int row) { return children()->at(row); } int PathNode::childCount() { return children()->count(); } int PathNode::row() const { if (m_parent) { return m_parent->children()->indexOf(const_cast<PathNode*>(this)); } return 0; } QString PathNode::path() const { return m_path; } QString PathNode::text() const { return m_text; } bool PathNode::isDir() const { return QFileInfo(m_path).isDir(); } bool PathNode::isFile() const { return QFileInfo(m_path).isFile(); } QFileInfo PathNode::fileInfo() const { return QFileInfo(m_path); } void PathNode::clear() { if (m_children) { qDeleteAll(m_children->begin(),m_children->end()); m_children->clear(); } } void PathNode::reload() { clear(); if (m_children == 0) { m_children = new QList<PathNode*>(); } if (!m_path.isEmpty()) { QFileInfo info(m_path); if (info.isDir()) { QDir dir(m_path); foreach(QFileInfo childInfo, dir.entryInfoList(QDir::Dirs|QDir::Files|QDir::NoDotAndDotDot,QDir::DirsFirst)) { m_children->append(new PathNode(this->m_model,childInfo.filePath(),this)); } } } } PathNode *PathNode::findPath(const QString &path) { if (!path.startsWith(m_path)) { return 0; } if (path == m_path) { return this; } QStringList nameList = path.right(path.length()-m_path.length()).split("/",QString::SkipEmptyParts); PathNode *parent = this; bool find = false; foreach (QString name,nameList) { find = false; QList<PathNode*>* chilren = parent->children(); for (int i = 0; i < chilren->count(); i++) { PathNode *node = chilren->at(i); if (!node->isDir()) { continue; } if (node->m_text == name) { parent = node; find = true; break; } } if (!find) { return 0; } } return parent; } GopathModel::GopathModel(QObject *parent) : QAbstractItemModel(parent), m_rootNode(new PathNode(this)), m_iconProvider(new QFileIconProvider), m_fileWatcher(new QFileSystemWatcher(this)) { connect(m_fileWatcher,SIGNAL(directoryChanged(QString)),this,SLOT(directoryChanged(QString))); } GopathModel::~GopathModel() { delete m_rootNode; delete m_iconProvider; } void GopathModel::directoryChanged(const QString &path) { foreach(QModelIndex index,this->findPaths(path)) { PathNode *node = nodeFromIndex(index); this->beginRemoveRows(index,0,this->rowCount(index)-1); node->reload(); this->endRemoveRows(); } } PathNode *GopathModel::nodeFromIndex(const QModelIndex &index) const { if (index.isValid()) { return static_cast<PathNode*>(index.internalPointer()); } return m_rootNode; } void GopathModel::setStartIndex(const QModelIndex &index) { m_startPath = filePath(index); } void GopathModel::setStartPath(const QString &path) { m_startPath = path; } QModelIndex GopathModel::startIndex() const { return findPath(m_startPath); } QString GopathModel::startPath() const { return m_startPath; } QString GopathModel::filePath(const QModelIndex &index) const { return nodeFromIndex(index)->path(); } void GopathModel::setPathList(const QStringList &pathList) { this->beginResetModel(); m_rootNode->clear(); m_pathList.clear(); foreach(QString path, pathList) { QString spath = QDir::fromNativeSeparators(QDir::cleanPath(path)); m_pathList.append(spath); m_rootNode->children()->append(new PathNode(this,spath,m_rootNode)); } /* if (m_startPath.isEmpty() && !pathList.isEmpty()) { m_startPath = pathList.last(); } */ this->endResetModel(); } QModelIndex GopathModel::findPathHelper(const QString &path, const QModelIndex &parentIndex) const { PathNode *node = nodeFromIndex(parentIndex); if (!path.startsWith(node->path())) { return QModelIndex(); } if (path == node->path()) { return parentIndex; } QStringList nameList = path.right(path.length()-node->path().length()).split("/",QString::SkipEmptyParts); QModelIndex parent = parentIndex; bool find = false; int count = nameList.count(); for (int i = 0; i < count; i++) { find = false; for (int j = 0; j < this->rowCount(parent); j++) { QModelIndex index = this->index(j,0,parent); PathNode *node = nodeFromIndex(index); if ( ( (i == count-1) || node->isDir()) && node->text() == nameList.at(i)) { parent = index; find = true; break; } } if (!find) { return QModelIndex(); } } return parent; } QList<QModelIndex> GopathModel::findPaths(const QString &path) const { QList<QModelIndex> list; QString cpath = QDir::fromNativeSeparators(QDir::cleanPath(path)); for (int i = 0; i < this->rowCount(); i++) { QModelIndex find = findPathHelper(cpath,this->index(i,0)); if (find.isValid()) { list.append(find); } } return list; } QModelIndex GopathModel::findPath(const QString &path) const { QList<QModelIndex> list = this->findPaths(path); if (!list.isEmpty()) { return list.last(); } return QModelIndex(); } int GopathModel::rowCount(const QModelIndex &parent) const { PathNode *node = nodeFromIndex(parent); return node->childCount(); } int GopathModel::columnCount(const QModelIndex &parent) const { return 1; } QModelIndex GopathModel::parent(const QModelIndex &child) const { PathNode *node = nodeFromIndex(child); PathNode *parent = node->parent(); if (parent == m_rootNode) { return QModelIndex(); } return createIndex(parent->row(),0,parent); } QModelIndex GopathModel::index(int row, int column,const QModelIndex &parent) const { if (!hasIndex(row,column,parent)) return QModelIndex(); PathNode *node = nodeFromIndex(parent); return createIndex(row,column,node->child(row)); } QVariant GopathModel::data(const QModelIndex &index, int role) const { PathNode *node = nodeFromIndex(index); if (!node) { return QVariant(); } switch(role) { case Qt::DisplayRole: return node->text(); case Qt::DecorationRole: return m_iconProvider->icon(node->fileInfo()); case Qt::FontRole: { QFont font; if (node->path() == m_startPath) { font.setBold(true); } return font; } } return QVariant(); } QFileSystemWatcher* GopathModel::fileWatcher() const { return m_fileWatcher; }
9,749
C++
.cpp
346
23.176301
126
0.628404
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,449
gopathbrowser.cpp
visualfc_liteide/liteidex/src/plugins/golangtool/gopathbrowser.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: gopathbrowser.cpp // Creator: visualfc <visualfc@gmail.com> #include "gopathbrowser.h" #include "gopathmodel.h" #include "liteapi/litefindobj.h" #include "../filebrowser/createdirdialog.h" #include "../filebrowser/createfiledialog.h" #include <QTreeView> #include <QVBoxLayout> #include <QHBoxLayout> #include <QPushButton> #include <QMenu> #include <QAction> #include <QMessageBox> #include <QDesktopServices> #include <QProcess> #include <QInputDialog> #include <QLineEdit> #include <QUrl> #include <QToolBar> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GopathBrowser::GopathBrowser(LiteApi::IApplication *app, QObject *parent) : QObject(parent), m_liteApp(app) { m_widget = new QWidget; m_toolBar = new QToolBar; m_toolBar->setIconSize(QSize(16,16)); m_syncEditor = new QAction(QIcon(":/images/synceditor.png"),tr("Synchronize Editor"),this); m_syncEditor->setCheckable(true); m_syncProject = new QAction(QIcon(":/images/syncproject.png"),tr("Synchronize Project"),this); m_syncProject->setCheckable(true); m_startPathLabel = new QLabel; m_toolBar->addAction(m_syncEditor); m_toolBar->addAction(m_syncProject); m_toolBar->addSeparator(); m_toolBar->addWidget(m_startPathLabel); m_pathTree = new QTreeView; m_pathTree->setHeaderHidden(true); m_model = new GopathModel(this); m_pathTree->setContextMenuPolicy(Qt::CustomContextMenu); m_pathTree->setModel(m_model); QVBoxLayout *layout = new QVBoxLayout; layout->setMargin(0); layout->addWidget(m_toolBar); layout->addWidget(m_pathTree); m_widget->setLayout(layout); m_pathList = m_liteApp->settings()->value("golangtool/gopath").toStringList(); //connect(m_pathTree->selectionModel(),SIGNAL(currentChanged(QModelIndex,QModelIndex)),this,SLOT(pathIndexChanged(QModelIndex))); connect(m_pathTree,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(openPathIndex(QModelIndex))); LiteApi::IEnvManager* envManager = LiteApi::findExtensionObject<LiteApi::IEnvManager*>(m_liteApp,"LiteApi.IEnvManager"); connect(envManager,SIGNAL(currentEnvChanged(LiteApi::IEnv*)),this,SLOT(reloadEnv())); connect(m_liteApp->editorManager(),SIGNAL(currentEditorChanged(LiteApi::IEditor*)),this,SLOT(currentEditorChanged(LiteApi::IEditor*))); m_fileMenu = new QMenu(m_widget); m_folderMenu = new QMenu(m_widget); m_setStartAct = new QAction(tr("Set Active Project"),this); m_openEditorAct = new QAction(tr("Open Editor"),this); m_newFileAct = new QAction(tr("New File..."),this); m_newFileWizardAct = new QAction(tr("New File Wizard..."),this); m_renameFileAct = new QAction(tr("Rename File..."),this); m_removeFileAct = new QAction(tr("Delete File"),this); m_newFolderAct = new QAction(tr("New Folder..."),this); m_renameFolderAct = new QAction(tr("Rename Folder..."),this); m_removeFolderAct = new QAction(tr("Delete Folder"),this); m_openShellAct = new QAction(tr("Open Terminal Here"),this); m_openExplorerAct = new QAction(tr("Open Explorer Here"),this); m_fileMenu->addAction(m_openEditorAct); m_fileMenu->addSeparator(); m_fileMenu->addAction(m_newFileAct); m_fileMenu->addAction(m_newFileWizardAct); m_fileMenu->addAction(m_renameFileAct); m_fileMenu->addAction(m_removeFileAct); m_fileMenu->addSeparator(); m_fileMenu->addAction(m_openShellAct); m_fileMenu->addAction(m_openExplorerAct); m_folderMenu->addAction(m_setStartAct); m_folderMenu->addSeparator(); m_folderMenu->addAction(m_newFileAct); m_folderMenu->addAction(m_newFileWizardAct); m_folderMenu->addAction(m_newFolderAct); m_folderMenu->addAction(m_renameFolderAct); m_folderMenu->addAction(m_removeFolderAct); m_folderMenu->addSeparator(); m_folderMenu->addAction(m_openShellAct); m_folderMenu->addAction(m_openExplorerAct); connect(m_startPathLabel,SIGNAL(linkActivated(QString)),this,SLOT(expandStartPath(QString))); connect(m_syncEditor,SIGNAL(triggered(bool)),this,SLOT(syncEditor(bool))); connect(m_syncProject,SIGNAL(triggered(bool)),this,SLOT(syncProject(bool))); connect(m_setStartAct,SIGNAL(triggered()),this,SLOT(setActivate())); connect(m_openEditorAct,SIGNAL(triggered()),this,SLOT(openEditor())); connect(m_newFileAct,SIGNAL(triggered()),this,SLOT(newFile())); connect(m_newFileWizardAct,SIGNAL(triggered()),this,SLOT(newFileWizard())); connect(m_renameFileAct,SIGNAL(triggered()),this,SLOT(renameFile())); connect(m_removeFileAct,SIGNAL(triggered()),this,SLOT(removeFile())); connect(m_newFolderAct,SIGNAL(triggered()),this,SLOT(newFolder())); connect(m_renameFolderAct,SIGNAL(triggered()),this,SLOT(renameFolder())); connect(m_removeFolderAct,SIGNAL(triggered()),this,SLOT(removeFolder())); connect(m_openShellAct,SIGNAL(triggered()),this,SLOT(openShell())); connect(m_openExplorerAct,SIGNAL(triggered()),this,SLOT(openExplorer())); connect(m_pathTree,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(treeViewContextMenuRequested(QPoint))); bool b = m_liteApp->settings()->value("GolangTool/synceditor",true).toBool(); if (b) { m_syncEditor->toggle(); } b = m_liteApp->settings()->value("GolangTool/syncproject",false).toBool(); if (b) { m_syncProject->toggle(); } m_startPathLabel->setText("null project"); } GopathBrowser::~GopathBrowser() { m_liteApp->settings()->setValue("GolangTool/synceditor",m_syncEditor->isChecked()); m_liteApp->settings()->setValue("GolangTool/syncproject",m_syncProject->isChecked()); m_liteApp->settings()->setValue("golangtool/gopath",m_pathList); delete m_widget; } QDir GopathBrowser::contextDir() const { if (m_contextInfo.isDir()) { return m_contextInfo.filePath(); } return m_contextInfo.dir(); } QFileInfo GopathBrowser::contextFileInfo() const { return m_contextInfo; } void GopathBrowser::setActivate() { setStartIndex(m_contextIndex); } void GopathBrowser::openEditor() { if (m_contextInfo.isFile()) { m_liteApp->fileManager()->openEditor(m_contextInfo.filePath()); } } void GopathBrowser::newFile() { QDir dir = contextDir(); CreateFileDialog dlg; dlg.setDirectory(dir.path()); if (dlg.exec() == QDialog::Rejected) { return; } QString fileName = dlg.getFileName(); if (!fileName.isEmpty()) { QString filePath = QFileInfo(dir,fileName).filePath(); if (QFile::exists(filePath)) { QMessageBox::information(m_liteApp->mainWindow(),tr("Create File"), tr("A file with that name already exists!")); } else { QFile file(filePath); if (file.open(QIODevice::WriteOnly)) { file.close(); if (dlg.isOpenEditor()) { m_liteApp->fileManager()->openEditor(filePath,true); } } else { QMessageBox::information(m_liteApp->mainWindow(),tr("Create File"), tr("Failed to create the file!")); } } } } void GopathBrowser::newFileWizard() { QString filePath; QString projPath; QFileInfo info = contextFileInfo(); QDir dir = contextDir(); if (!info.isFile()) { filePath = dir.absolutePath(); projPath = dir.absolutePath(); } else { filePath = dir.absolutePath(); dir.cdUp(); projPath = dir.absolutePath(); } m_liteApp->fileManager()->execFileWizard(projPath,filePath); } void GopathBrowser::renameFile() { QFileInfo info = contextFileInfo(); if (!info.isFile()) { return; } QString fileName = QInputDialog::getText(m_liteApp->mainWindow(), tr("Rename File"),tr("New Name:"), QLineEdit::Normal,info.fileName()); if (!fileName.isEmpty() && fileName != info.fileName()) { QDir dir = contextDir(); if (!QFile::rename(info.filePath(),QFileInfo(dir,fileName).filePath())) { QMessageBox::information(m_liteApp->mainWindow(),tr("Rename File"), tr("Failed to rename the file!")); } } } void GopathBrowser::removeFile() { QFileInfo info = contextFileInfo(); if (!info.isFile()) { return; } int ret = QMessageBox::question(m_liteApp->mainWindow(),tr("Delete File"), tr("Are you sure that you want to permanently delete this file?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::Yes) { if (!QFile::remove(info.filePath())) { QMessageBox::information(m_liteApp->mainWindow(),tr("Delete File"), tr("Failed to delete the file!")); } } } void GopathBrowser::newFolder() { QDir dir = contextDir(); CreateDirDialog dlg; dlg.setDirectory(dir.path()); if (dlg.exec() == QDialog::Rejected) { return; } QString folderName = dlg.getDirPath(); if (!folderName.isEmpty()) { if (!dir.entryList(QStringList() << folderName,QDir::Dirs).isEmpty()) { QMessageBox::information(m_liteApp->mainWindow(),tr("Create Folder"), tr("A folder with that name already exists!")); } else if (!dir.mkpath(folderName)) { QMessageBox::information(m_liteApp->mainWindow(),tr("Create Folder"), tr("Failed to create the folder!")); } } } void GopathBrowser::renameFolder() { QFileInfo info = contextFileInfo(); if (!info.isDir()) { return; } QString folderName = QInputDialog::getText(m_liteApp->mainWindow(), tr("Rename Folder"),tr("Folder Name"), QLineEdit::Normal,info.fileName()); if (!folderName.isEmpty() && folderName != info.fileName()) { QDir dir = contextDir(); dir.cdUp(); if (!dir.rename(info.fileName(),folderName)) { QMessageBox::information(m_liteApp->mainWindow(),tr("Rename Folder"), tr("Failed to rename the folder!")); } } } void GopathBrowser::removeFolder() { QFileInfo info = contextFileInfo(); if (!info.isDir()) { return; } int ret = QMessageBox::warning(m_liteApp->mainWindow(),tr("Delete Folder"), tr("Are you sure that you want to permanently delete this folder and all of its contents?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::Yes) { QDir dir = info.dir(); if (!dir.rmdir(info.fileName())) { QMessageBox::information(m_liteApp->mainWindow(),tr("Delete Folder"), tr("Failed to delete the folder!")); } } } void GopathBrowser::openExplorer() { QDir dir = contextDir(); QDesktopServices::openUrl(QUrl::fromLocalFile(dir.path())); } void GopathBrowser::openShell() { QDir dir = contextDir(); QProcessEnvironment env = LiteApi::getCurrentEnvironment(m_liteApp); QString cmd = env.value("LITEIDE_TERM"); QStringList args = env.value("LITEIDE_TERMARGS").split(" "); QString path = dir.path(); #ifdef Q_OS_WIN if (path.length() == 2 && path.right(1) == ":") { path += "/"; } #endif QProcess::startDetached(cmd,args,path); } QWidget *GopathBrowser::widget() const { return m_widget; } void GopathBrowser::treeViewContextMenuRequested(const QPoint &pos) { QModelIndex index = m_pathTree->indexAt(pos); if (!index.isValid()) { return; } PathNode *node = m_model->nodeFromIndex(index); if (!node) { return; } m_contextInfo = node->fileInfo(); m_contextIndex = index; QMenu *contextMenu = 0; if (node->isDir()) { contextMenu = m_folderMenu; } else { contextMenu = m_fileMenu; } if (contextMenu && contextMenu->actions().count() > 0) { contextMenu->popup(m_pathTree->mapToGlobal(pos)); } } void GopathBrowser::addPathList(const QString &path) { QStringList pathList = m_pathList; pathList.append(path); this->setPathList(pathList); } void GopathBrowser::setPathList(const QStringList &pathList) { m_pathList = pathList; QStringList allPathList = systemGopathList()+m_pathList; m_model->setPathList(allPathList); m_pathTree->setCurrentIndex(m_model->startIndex()); m_pathTree->expand(m_model->startIndex()); LiteApi::IEnvManager* envManager = LiteApi::findExtensionObject<LiteApi::IEnvManager*>(m_liteApp,"LiteApi.IEnvManager"); LiteApi::IEnv *env = envManager->currentEnv(); if (env) { #ifdef Q_OS_WIN env->environment().insert("LITEIDE_GOPATH",allPathList.join(";")); #else env->environment().insert("LITEIDE_GOPATH",allPathList.join(":")); #endif } currentEditorChanged(m_liteApp->editorManager()->currentEditor()); } QStringList GopathBrowser::pathList() const { return m_pathList; } QStringList GopathBrowser::systemGopathList() const { LiteApi::IEnvManager* envManager = LiteApi::findExtensionObject<LiteApi::IEnvManager*>(m_liteApp,"LiteApi.IEnvManager"); QString gopath= envManager->currentEnvironment().value("GOPATH"); if (gopath.isEmpty()) { gopath = envManager->currentEnvironment().value("GOROOT"); } QStringList list; #ifdef Q_OS_WIN list = gopath.split(";",QString::SkipEmptyParts); #else list = gopath.split(":",QString::SkipEmptyParts); #endif return list; } void GopathBrowser::reloadEnv() { this->setPathList(m_pathList); } void GopathBrowser::setStartIndex(const QModelIndex &index) { QModelIndex oldIndex = m_model->startIndex(); if (oldIndex != index) { m_model->setStartIndex(index); m_pathTree->update(oldIndex); m_pathTree->update(index); emit startPathChanged(m_model->filePath(index)); PathNode *node = m_model->nodeFromIndex(index); if (node) { m_startPathLabel->setText(QString("<p><a href file://%1>%2</p>").arg(node->path()).arg(node->text())); m_startPathLabel->setToolTip(node->path()); } } } QString GopathBrowser::startPath() const { QModelIndex index = m_model->startIndex(); return m_model->filePath(index); } void GopathBrowser::pathIndexChanged(const QModelIndex & index) { PathNode *node = m_model->nodeFromIndex(index); if (node) { QFileInfo info = node->fileInfo(); QModelIndex newIndex = index; if (info.isDir()) { newIndex = index; } else { newIndex = index.parent(); } this->setStartIndex(newIndex); } } void GopathBrowser::openPathIndex(const QModelIndex &index) { PathNode *node = m_model->nodeFromIndex(index); if (!node) { return; } if (node->isDir()) { this->setStartIndex(index); } else if (node->isFile()) { if (m_syncProject->isChecked()) { this->setStartIndex(index.parent()); } m_liteApp->fileManager()->openEditor(node->path(),true); } } void GopathBrowser::currentEditorChanged(LiteApi::IEditor* editor) { if (!m_syncEditor->isChecked()) { return; } if (editor && !editor->filePath().isEmpty()) { QModelIndex index = m_model->findPath(editor->filePath()); if (index.isValid()) { m_pathTree->setCurrentIndex(index); m_pathTree->scrollTo(index,QAbstractItemView::EnsureVisible); if (m_syncProject->isChecked()) { setStartIndex(index.parent()); } } } } void GopathBrowser::syncEditor(bool b) { if (!b) { m_syncProject->setChecked(false); } } void GopathBrowser::syncProject(bool b) { if (b) { m_syncEditor->setChecked(true); } } void GopathBrowser::expandStartPath(QString) { m_pathTree->scrollTo(m_model->startIndex(),QAbstractItemView::EnsureVisible); }
17,526
C++
.cpp
471
31.11465
139
0.652194
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,450
golangtoolplugin.cpp
visualfc_liteide/liteidex/src/plugins/golangtool/golangtoolplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangtoolplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangtoolplugin.h" #include "gopathprojectfactor.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangToolPlugin::GolangToolPlugin() { m_info->setId("plugin/GolangTool"); m_info->setName("GolangTool"); m_info->setAuthor("visualfc"); m_info->setInfo("Golang Tool Plugin"); } bool GolangToolPlugin::initWithApp(LiteApi::IApplication *app) { if (!LiteApi::IPlugin::initWithApp(app)) { return false; } app->projectManager()->addFactory(new GopathProjectFactor(app,this)); return true; } QStringList GolangToolPlugin::dependPluginList() const { return QStringList() << "plugin/liteenv"; } Q_EXPORT_PLUGIN(GolangToolPlugin)
2,005
C++
.cpp
53
35.415094
82
0.684481
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,451
gopathprojectfactor.cpp
visualfc_liteide/liteidex/src/plugins/golangtool/gopathprojectfactor.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: gopathprojectfactor.cpp // Creator: visualfc <visualfc@gmail.com> #include "gopathprojectfactor.h" #include "gopathproject.h" #include "gopathbrowser.h" #include "importgopathdialog.h" #include <QAction> #include <QFileDialog> #include <QToolBar> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GopathProjectFactor::GopathProjectFactor(LiteApi::IApplication *app, QObject *parent) : LiteApi::IProjectFactory(parent), m_liteApp(app) { m_mimeTypes << "text/x-gopath"; m_browser = new GopathBrowser(app,this); QAction *act = new QAction(QIcon(":/images/gopath.png"),tr("<GOPATH> Project"),this); connect(act,SIGNAL(triggered()),this,SLOT(importGopath())); m_liteApp->projectManager()->addImportAction(act); QToolBar *toolBar = m_liteApp->actionManager()->loadToolBar("toolbar/nav"); if (toolBar) { toolBar->addAction(act); } connect(m_liteApp,SIGNAL(loaded()),this,SLOT(loadApp())); } GopathProjectFactor::~GopathProjectFactor() { if (m_browser) { delete m_browser; } } void GopathProjectFactor::loadApp() { m_browser->reloadEnv(); GopathProject *project = new GopathProject(m_browser); m_liteApp->projectManager()->setCurrentProject(project); } void GopathProjectFactor::importGopath() { ImportGopathDialog *dlg = new ImportGopathDialog(m_liteApp->mainWindow()); dlg->setSysPathList(m_browser->systemGopathList()); dlg->setPathList(m_browser->pathList()); if (dlg->exec() == QDialog::Accepted) { m_browser->setPathList(dlg->pathList()); GopathProject *project = new GopathProject(m_browser); m_liteApp->projectManager()->setCurrentProject(project); } delete dlg; } QStringList GopathProjectFactor::mimeTypes() const { return m_mimeTypes; } LiteApi::IProject *GopathProjectFactor::open(const QString &fileName, const QString &mimeType) { if (m_mimeTypes.contains(mimeType)) { GopathProject *project = new GopathProject(m_browser); project->browser()->addPathList(fileName); return project; } return 0; } bool GopathProjectFactor::findProjectInfo(const QString &fileName, const QString &mimetype, QMap<QString,QString>& projectInfo, QMap<QString,QString>& findProjectInfo) const { return false; }
3,566
C++
.cpp
95
34.231579
173
0.697688
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,452
importgopathdialog.cpp
visualfc_liteide/liteidex/src/plugins/golangtool/importgopathdialog.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: importgopathdialog.cpp // Creator: visualfc <visualfc@gmail.com> #include "importgopathdialog.h" #include "ui_importgopathdialog.h" #include <QFileDialog> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end ImportGopathDialog::ImportGopathDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ImportGopathDialog) { ui->setupUi(this); connect(ui->browserButton,SIGNAL(clicked()),this,SLOT(browser())); connect(ui->clearButton,SIGNAL(clicked()),ui->pathTextEdit,SLOT(clear())); } ImportGopathDialog::~ImportGopathDialog() { delete ui; } void ImportGopathDialog::setSysPathList(const QStringList &pathList) { foreach (QString path, pathList) { ui->sysPathTextEdit->appendPlainText(path); } } void ImportGopathDialog::setPathList(const QStringList &pathList) { foreach (QString path, pathList) { ui->pathTextEdit->appendPlainText(path); } } QStringList ImportGopathDialog::pathList() const { return ui->pathTextEdit->toPlainText().split("\n",QString::SkipEmptyParts); } void ImportGopathDialog::browser() { QString dir = QFileDialog::getExistingDirectory(this, tr("Load GOPATH Directory"), "/home", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if (!dir.isEmpty()) { ui->pathTextEdit->appendPlainText(dir); } }
2,723
C++
.cpp
72
33.083333
88
0.6591
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,453
gopathproject.cpp
visualfc_liteide/liteidex/src/plugins/golangtool/gopathproject.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2013 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: gopathproject.cpp // Creator: visualfc <visualfc@gmail.com> #include "gopathproject.h" #include "gopathmodel.h" #include "liteapi/litefindobj.h" #include "gopathbrowser.h" #include <QVBoxLayout> #include <QHBoxLayout> #include <QTreeView> #include <QFileInfo> #include <QDir> #include <QStringList> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GopathProject::GopathProject(GopathBrowser *browser) : m_browser(browser) { connect(m_browser,SIGNAL(startPathChanged(QString)),this,SLOT(startPathChanged(QString))); m_path = m_browser->startPath(); } GopathProject::~GopathProject() { disconnect(m_browser); m_browser->widget()->hide(); } GopathBrowser *GopathProject::browser() { return m_browser; } void GopathProject::startPathChanged(const QString &path) { m_path = path; emit reloaded(); } QWidget *GopathProject::widget() { return m_browser->widget(); } QString GopathProject::name() const { return m_path; } QString GopathProject::filePath() const { return m_path; } QString GopathProject::mimeType() const { return "text/x-gopath"; } QStringList GopathProject::fileNameList() const { QDir dir(m_path); QStringList list; foreach(QFileInfo info,dir.entryInfoList(QDir::Files)) { list.append(info.fileName()); } return list; } QStringList GopathProject::filePathList() const { QDir dir(m_path); QStringList list; foreach(QFileInfo info, dir.entryInfoList(QStringList() <<"*.go",QDir::Files)) { list.append(info.filePath()); } return list; } QString GopathProject::fileNameToFullPath(const QString &filePath) { return QFileInfo(m_path,filePath).filePath(); } QMap<QString,QString> GopathProject::projectInfo() const { QMap<QString,QString> m; if (m_path.isEmpty()) { return m; } QFileInfo info(m_path); m.insert("PROJECTNAME",info.fileName()); m.insert("PROJECTPATH",info.filePath()); m.insert("PROJECTDIR",info.filePath()); return m; } QMap<QString,QString> GopathProject::targetInfo() const { QMap<QString,QString> m; if (m_path.isEmpty()) { return m; } QFileInfo info(m_path); QString target = info.fileName(); #ifdef Q_OS_WIN target += ".exe"; #endif m.insert("TARGETNAME",target); m.insert("TARGETPATH",QFileInfo(QDir(m_path),target).filePath()); m.insert("TARGETDIR",info.filePath()); m.insert("WORKDIR",info.filePath()); return m; } void GopathProject::load() { m_browser->widget()->show(); }
3,796
C++
.cpp
132
25.924242
94
0.690705
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,454
litefindplugin.cpp
visualfc_liteide/liteidex/src/plugins/litefind/litefindplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: litefindplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "litefindplugin.h" #include "findeditor.h" #include "filesearch.h" #include "filesearchmanager.h" #include "liteapi/liteids.h" #include <QMenu> #include <QAction> #include <QLayout> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end LiteFindPlugin::LiteFindPlugin() : m_findEditor(0) { } LiteFindPlugin::~LiteFindPlugin() { } bool LiteFindPlugin::load(LiteApi::IApplication *app) { m_liteApp = app; QLayout *layout = m_liteApp->editorManager()->widget()->layout(); if (!layout) { return false; } QMenu *menu = m_liteApp->actionManager()->loadMenu(ID_MENU_FIND); if (!menu) { return false; } m_findEditor = new FindEditor(m_liteApp,this); m_findEditor->widget()->hide(); layout->addWidget(m_findEditor->widget()); LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(this,"Find"); m_findAct = new QAction(tr("Find"),this); actionContext->regAction(m_findAct,"Find",QKeySequence::Find); m_findNextAct = new QAction(tr("Find Next"),this); actionContext->regAction(m_findNextAct,"FindNext",QKeySequence::FindNext); m_findPrevAct = new QAction(tr("Find Previous"),this); actionContext->regAction(m_findPrevAct,"FindPrevious",QKeySequence::FindPrevious); m_replaceAct = new QAction(tr("Replace"),this); #ifdef Q_OS_MAC actionContext->regAction(m_replaceAct,"Replace","ALT+CTRL+F"); #else actionContext->regAction(m_replaceAct,"Replace",QKeySequence::Replace); #endif m_fileSearchAct = new QAction(tr("File Search"),this); #ifdef Q_OS_WIN actionContext->regAction(m_fileSearchAct,"FileSearch","Ctrl+Shift+F;Ctrl+Alt+F"); #else actionContext->regAction(m_fileSearchAct,"FileSearch","Ctrl+Shift+F"); #endif menu->addAction(m_findAct); menu->addAction(m_findNextAct); menu->addAction(m_findPrevAct); menu->addSeparator(); menu->addAction(m_replaceAct); menu->addSeparator(); menu->addAction(m_fileSearchAct); connect(m_findAct,SIGNAL(triggered()),this,SLOT(find())); connect(m_findNextAct,SIGNAL(triggered()),m_findEditor,SLOT(findNext())); connect(m_findPrevAct,SIGNAL(triggered()),m_findEditor,SLOT(findPrev())); connect(m_replaceAct,SIGNAL(triggered()),this,SLOT(replace())); connect(m_liteApp,SIGNAL(key_escape()),this,SLOT(hideFind())); FileSearchManager *manager = new FileSearchManager(m_liteApp,this); FileSearch *fileSearch = new FileSearch(m_liteApp,manager); manager->addFileSearch(fileSearch); connect(m_fileSearchAct,SIGNAL(triggered()),manager,SLOT(newSearch())); return true; } void LiteFindPlugin::hideFind() { m_findEditor->setVisible(false); } void LiteFindPlugin::find() { if (!m_findEditor->isVisible()) { m_findEditor->setReplaceMode(false); } m_findEditor->setVisible(true); } void LiteFindPlugin::replace() { m_findEditor->setReplaceMode(true); m_findEditor->setVisible(true); } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
4,362
C++
.cpp
116
34.387931
103
0.703502
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,455
filesearch.cpp
visualfc_liteide/liteidex/src/plugins/litefind/filesearch.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: filesearch.cpp // Creator: visualfc <visualfc@gmail.com> #include "filesearch.h" #include "litefind_global.h" #include <QFile> #include <QTableWidget> #include <QTextStream> #include <QTextDocument> #include <QRegExp> #include <QVBoxLayout> #include <QHBoxLayout> #include <QComboBox> #include <QCheckBox> #include <QLabel> #include <QLineEdit> #include <QPushButton> #include <QDir> #include <QTextBlock> #include <QTextCursor> #include <QPlainTextEdit> #include <QTextBrowser> #include <QFileDialog> #include <QAction> #include <QCompleter> #include <QDebug> #include "editorutil/checkdata.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end FindThread::FindThread(QObject *parent) : QThread(parent), useRegExp(true), matchWord(true), matchCase(true), findSub(true) { qRegisterMetaType<LiteApi::FileSearchResult>("LiteApi::FileSearchResult"); } void FindThread::findDir(const QRegExp &reg, const QString &path) { QDir dir(path); if (!dir.exists()) { return; } foreach(QFileInfo info, dir.entryInfoList(nameFilter,QDir::Files|QDir::NoSymLinks)) { findFile(reg,info.filePath()); if (!finding) { return; } } if (findSub) { foreach(QFileInfo info, dir.entryInfoList(QDir::Dirs|QDir::NoDotAndDotDot)) { findDir(reg,info.filePath()); if(!finding) { return; } } } } void FindThread::findFile(const QRegExp &reg, const QString &fileName) { QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { return; } //skip binary data QByteArray head = file.read(32); if (HasBinaryData(head,32)) { return; } file.seek(0); QTextStream stream(&file); stream.setCodec("utf-8"); QString line; int lineNr = 1; while (!stream.atEnd()) { line = stream.readLine(); int pos = 0; while ((pos = reg.indexIn(line, pos)) != -1) { if (!useRegExp && matchWord) { const int start = pos; const int end = start + reg.matchedLength(); if ((start != 0 && line.at(start - 1).isLetterOrNumber()) || (end != line.length() && line.at(end).isLetterOrNumber())) { //if this is not a whole word, continue the search in the string pos = end+1; continue; } } emit findResult(LiteApi::FileSearchResult(fileName, line,lineNr,pos, reg.matchedLength())); pos += reg.matchedLength(); } lineNr++; if (!finding) { break; } } } void FindThread::stop() { finding = false; if (this->isRunning()) { if (!this->wait(200)) this->terminate(); } } void FindThread::run() { finding = true; QRegExp reg; reg.setCaseSensitivity(matchCase ? Qt::CaseSensitive : Qt::CaseInsensitive); if (useRegExp) { if (matchWord) { reg.setPattern(QString::fromLatin1("\\b%1\\b").arg(findText)); } else { reg.setPattern(findText); } } else { reg.setPattern(findText); reg.setPatternSyntax(QRegExp::FixedString); } findDir(reg,findPath); finding = false; } ResultTextEdit::ResultTextEdit(QWidget *parent) : QPlainTextEdit(parent) { this->setWordWrapMode(QTextOption::NoWrap); connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(slotCursorPositionChanged())); } void ResultTextEdit::slotCursorPositionChanged() { QList<QTextEdit::ExtraSelection> extraSelections; QTextEdit::ExtraSelection selection; QColor lineColor = QColor(180,200,200,128); selection.format.setBackground(lineColor); selection.format.setProperty(QTextFormat::FullWidthSelection, true); selection.cursor = textCursor(); selection.cursor.clearSelection(); extraSelections.append(selection); setExtraSelections(extraSelections); } void ResultTextEdit::mouseDoubleClickEvent(QMouseEvent *e) { QTextCursor cur = cursorForPosition(e->pos()); cur.select(QTextCursor::LineUnderCursor); emit dbclickEvent(cur); } FileSearch::FileSearch(LiteApi::IApplication *app, QObject *parent) : LiteApi::IFileSearch(parent), m_liteApp(app) { m_thread = new FindThread; m_findWidget = new QWidget; QGridLayout *topLayout = new QGridLayout; topLayout->setSpacing(1); m_findCombo = new QComboBox; m_findCombo->setEditable(true); m_findCombo->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); QCompleter *c = m_findCombo->completer(); if (c) { c->setCaseSensitivity(Qt::CaseSensitive); } QHBoxLayout *optLayout = new QHBoxLayout; optLayout->setSpacing(6); m_matchWordCheckBox = new QCheckBox(tr("Match whole word")); m_matchCaseCheckBox = new QCheckBox(tr("Match case")); m_useRegexCheckBox = new QCheckBox(tr("Regular expression")); m_findSubCheckBox = new QCheckBox(tr("Scan subdirectories")); optLayout->addWidget(m_matchWordCheckBox); optLayout->addWidget(m_matchCaseCheckBox); optLayout->addWidget(m_useRegexCheckBox); optLayout->addWidget(m_findSubCheckBox); optLayout->addStretch(); QHBoxLayout *findLayout = new QHBoxLayout; findLayout->setSpacing(6); //findLayout->setMargin(0); m_findButton = new QPushButton(tr("Search")); m_stopButton = new QPushButton(tr("Cancel")); m_stopButton->setEnabled(false); //findLayout->addWidget(); findLayout->addWidget(m_findCombo); findLayout->addWidget(m_findButton); findLayout->addWidget(m_stopButton); //findLayout->addStretch(0); //topLayout->addLayout(findLayout,4,1); topLayout->addWidget(new QLabel(tr("Search for:")),0,0); topLayout->addLayout(findLayout,0,1); topLayout->addWidget(new QLabel(tr("Options:")),1,0); topLayout->addLayout(optLayout,1,1); QHBoxLayout *dirLayout = new QHBoxLayout; dirLayout->setSpacing(6); m_findPathCombo = new QComboBox; m_findPathCombo->setEditable(true); QPushButton *browserBtn = new QPushButton(tr("Browse...")); QPushButton *currentBtn = new QPushButton(tr("Current Folder")); m_autoSwitchPathCheckBox = new QCheckBox; m_autoSwitchPathCheckBox->setText(tr("Auto Switch")); dirLayout->addWidget(m_findPathCombo,1); dirLayout->addWidget(m_autoSwitchPathCheckBox); dirLayout->addWidget(currentBtn); dirLayout->addWidget(browserBtn); topLayout->addWidget(new QLabel("Directory:"),2,0); topLayout->addLayout(dirLayout,2,1); m_filterCombo = new QComboBox; m_filterCombo->setEditable(true); m_filterCombo->addItem("*.go"); m_filterCombo->addItem("*.lua;*.wlua"); m_filterCombo->addItem("*.c;*.cpp;*.cxx;*.cc;*.c++;*.h;*.hpp;*.hh;*.hxx;*.h++;*.hcc;*.moc"); m_filterCombo->addItem("*.htm;*.html;*.shtml;*.shtm"); m_filterCombo->addItem("*"); topLayout->addWidget(new QLabel(tr("Filter:")),3,0); topLayout->addWidget(m_filterCombo,3,1); m_findWidget->setLayout(topLayout); QAction *clearAct = new QAction(tr("Clear"),this); clearAct->setIcon(QIcon("icon:images/cleanoutput.png")); m_findPathCombo->setEditText(QDir::homePath()); m_liteApp->settings()->beginGroup("findfiles"); m_matchWordCheckBox->setChecked(m_liteApp->settings()->value("matchWord",false).toBool()); m_matchCaseCheckBox->setChecked(m_liteApp->settings()->value("matchCase",false).toBool()); m_useRegexCheckBox->setChecked(m_liteApp->settings()->value("useRegexp",false).toBool()); m_findSubCheckBox->setChecked(m_liteApp->settings()->value("findSub",true).toBool()); m_liteApp->settings()->endGroup(); connect(browserBtn,SIGNAL(clicked()),this,SLOT(browser())); connect(currentBtn,SIGNAL(clicked()),this,SLOT(currentDir())); connect(m_findButton,SIGNAL(clicked()),this,SLOT(findInFiles())); connect(m_stopButton,SIGNAL(clicked()),m_thread,SLOT(stop())); connect(m_thread,SIGNAL(started()),this,SIGNAL(findStarted())); connect(m_thread,SIGNAL(finished()),this,SIGNAL(findFinished())); connect(m_thread,SIGNAL(findResult(LiteApi::FileSearchResult)),this,SIGNAL(findResult(LiteApi::FileSearchResult))); connect(m_findCombo->lineEdit(),SIGNAL(returnPressed()),this,SLOT(findInFiles())); connect(m_findPathCombo->lineEdit(),SIGNAL(returnPressed()),this,SLOT(findInFiles())); bool b = m_liteApp->settings()->value(FILESEARCH_AUTOSWITCHDIR,true).toBool(); m_autoSwitchPathCheckBox->setChecked(b); } FileSearch::~FileSearch() { m_liteApp->settings()->beginGroup("findfiles"); m_liteApp->settings()->setValue("matchWord",m_matchWordCheckBox->isChecked()); m_liteApp->settings()->setValue("matchCase",m_matchCaseCheckBox->isChecked()); m_liteApp->settings()->setValue("useRegexp",m_useRegexCheckBox->isChecked()); m_liteApp->settings()->setValue("findSub",m_findSubCheckBox->isChecked()); m_liteApp->settings()->endGroup(); m_liteApp->settings()->setValue(FILESEARCH_AUTOSWITCHDIR,m_autoSwitchPathCheckBox->isChecked()); if (m_thread) { m_thread->stop(); delete m_thread; } if (m_findWidget) { delete m_findWidget; } } void FileSearch::setVisible(bool b) { if (b) { LiteApi::IProject *proj = m_liteApp->projectManager()->currentProject(); if (proj && !LiteApi::mimeIsFolder(proj->mimeType())) { QFileInfo info(proj->filePath()); if (info.isDir()) m_findPathCombo->setEditText(info.filePath()); else m_findPathCombo->setEditText(info.path()); } m_findCombo->setFocus(); m_findCombo->lineEdit()->selectAll(); LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (editor) { QString text; QPlainTextEdit *ed = LiteApi::findExtensionObject<QPlainTextEdit*>(editor,"LiteApi.QPlainTextEdit"); if (ed) { text = ed->textCursor().selectedText(); } else { QTextBrowser *ed = LiteApi::findExtensionObject<QTextBrowser*>(editor,"LiteApi.QTextBrowser"); if (ed) { text = ed->textCursor().selectedText(); } } if (!text.isEmpty()) { this->m_findCombo->setEditText(text); } if (editor && !editor->filePath().isEmpty() && m_autoSwitchPathCheckBox->isChecked()) { QFileInfo info(editor->filePath()); m_findPathCombo->setEditText(info.path()); } } } } QString FileSearch::mimeType() const { return "search/filesystem"; } QString FileSearch::displayName() const { return tr("Files on File System"); } QWidget *FileSearch::widget() const { return m_findWidget; } void FileSearch::start() { this->findInFiles(); } void FileSearch::cancel() { m_thread->stop(); } void FileSearch::activate() { LiteApi::IProject *proj = m_liteApp->projectManager()->currentProject(); if (proj && !LiteApi::mimeIsFolder(proj->mimeType())) { QFileInfo info(proj->filePath()); if (info.isDir()) m_findPathCombo->setEditText(info.filePath()); else m_findPathCombo->setEditText(info.path()); } m_findCombo->setFocus(); m_findCombo->lineEdit()->selectAll(); LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (editor) { QString text; QPlainTextEdit *ed = LiteApi::findExtensionObject<QPlainTextEdit*>(editor,"LiteApi.QPlainTextEdit"); if (ed) { text = ed->textCursor().selectedText(); } else { QTextBrowser *ed = LiteApi::findExtensionObject<QTextBrowser*>(editor,"LiteApi.QTextBrowser"); if (ed) { text = ed->textCursor().selectedText(); } } if (!text.isEmpty()) { this->m_findCombo->setEditText(text); } if (editor && !editor->filePath().isEmpty() && m_autoSwitchPathCheckBox->isChecked()) { QFileInfo info(editor->filePath()); m_findPathCombo->setEditText(info.path()); } } } QString FileSearch::searchText() const { return m_thread->findText; } void FileSearch::setSearchInfo(const QString &text, const QString &filter, const QString &path) { m_findCombo->setEditText(text); m_filterCombo->setEditText(filter); m_findPathCombo->setEditText(path); } void FileSearch::findInFiles() { if (m_thread->isRunning()) { m_thread->stop(); } QString text = m_findCombo->currentText(); QString path = m_findPathCombo->currentText(); if (text.isEmpty() || path.isEmpty()) { return; } m_liteApp->editorManager()->saveAllEditors(false); m_thread->findPath = path; m_thread->findText = text; m_thread->useRegExp = m_useRegexCheckBox->isChecked(); m_thread->matchCase = m_matchCaseCheckBox->isChecked(); m_thread->matchWord = m_matchWordCheckBox->isChecked(); m_thread->findSub = m_findSubCheckBox->isChecked(); m_thread->nameFilter = m_filterCombo->currentText().split(";"); m_thread->start(QThread::LowPriority); if (m_findCombo->findText(text) < 0) { m_findCombo->addItem(text); } if (m_findPathCombo->findText(path) < 0) { m_findPathCombo->addItem(path); } } void FileSearch::currentDir() { LiteApi::IProject *proj = m_liteApp->projectManager()->currentProject(); if (proj && !LiteApi::mimeIsFolder(proj->mimeType())) { QFileInfo info(proj->filePath()); if (info.isDir()) { m_findPathCombo->setEditText(info.filePath()); } else { m_findPathCombo->setEditText(info.path()); } } else { LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (editor && !editor->filePath().isEmpty()) { QFileInfo info(editor->filePath()); m_findPathCombo->setEditText(info.path()); } } m_findPathCombo->setFocus(); } void FileSearch::browser() { QString dir = QFileDialog::getExistingDirectory(m_liteApp->mainWindow(), tr("Open Directory"), m_findPathCombo->currentText(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if (!dir.isEmpty()) { m_findPathCombo->setEditText(dir); } }
15,844
C++
.cpp
430
30.727907
119
0.650453
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,456
findeditor.cpp
visualfc_liteide/liteidex/src/plugins/litefind/findeditor.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: findeditor.cpp // Creator: visualfc <visualfc@gmail.com> #include "findeditor.h" #include "litefind_global.h" #include <QGridLayout> #include <QLineEdit> #include <QPlainTextEdit> #include <QTextEdit> #include <QLabel> #include <QPushButton> #include <QCheckBox> #include <QTextBlock> #include <QTextBrowser> #include <QStatusBar> #include <QRegExp> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end FindEditor::FindEditor(LiteApi::IApplication *app, QObject *parent) : QObject(parent), m_liteApp(app), m_widget(new QWidget) { m_findEdit = new QLineEdit; m_replaceEdit = new QLineEdit; m_findNext = new QPushButton(tr("Find Next")); m_findPrev = new QPushButton(tr("Find Previous")); m_replaceLabel = new QLabel(tr("Replace With:")); m_replace = new QPushButton(tr("Replace")); m_replaceAll = new QPushButton(tr("Replace All")); m_matchWordCheckBox = new QCheckBox(tr("Match whole word only")); m_matchCaseCheckBox = new QCheckBox(tr("Match case")); m_useRegexCheckBox = new QCheckBox(tr("Regular expression")); m_wrapAroundCheckBox = new QCheckBox(tr("Wrap around")); m_matchWordCheckBox->setChecked(m_liteApp->settings()->value(FIND_MATCHWORD,true).toBool()); m_matchCaseCheckBox->setChecked(m_liteApp->settings()->value(FIND_MATCHCASE,true).toBool()); m_useRegexCheckBox->setChecked(m_liteApp->settings()->value(FIND_USEREGEXP,false).toBool()); m_wrapAroundCheckBox->setChecked(m_liteApp->settings()->value(FIND_WRAPAROUND,true).toBool()); m_status = new QLabel(tr("Ready")); m_status->setFrameStyle(QFrame::Panel | QFrame::Sunken); m_status->setAlignment(Qt::AlignRight); m_status->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); QPushButton *close = new QPushButton(); close->setIcon(QIcon("icon:images/close.png")); close->setIconSize(QSize(16,16)); close->setFlat(true); close->setToolTip(tr("Close")); m_showReplaceCheckBox = new QCheckBox; m_showReplaceCheckBox->setText(tr("Show Replace")); connect(m_showReplaceCheckBox,SIGNAL(toggled(bool)),this,SLOT(setReplaceMode(bool))); connect(close,SIGNAL(clicked()),this,SLOT(hideFind())); QGridLayout *layout = new QGridLayout; layout->setMargin(0); layout->setVerticalSpacing(1); QHBoxLayout *optLayout = new QHBoxLayout; optLayout->setMargin(0); optLayout->addWidget(m_matchWordCheckBox); optLayout->addWidget(m_matchCaseCheckBox); optLayout->addWidget(m_useRegexCheckBox); optLayout->addWidget(m_wrapAroundCheckBox); optLayout->addStretch(); optLayout->addWidget(m_status); layout->addWidget(new QLabel(tr("Find What:")),0,0); layout->addWidget(m_findEdit,0,1); layout->addWidget(m_findNext,0,2); layout->addWidget(m_findPrev,0,3); layout->addWidget(m_showReplaceCheckBox,0,4); layout->addWidget(close,0,5); layout->addWidget(m_replaceLabel,1,0); layout->addWidget(m_replaceEdit,1,1); layout->addWidget(m_replace,1,2); layout->addWidget(m_replaceAll,1,3); layout->addWidget(new QLabel(tr("Options:")),3,0); layout->addLayout(optLayout,3,1,1,4); m_widget->setLayout(layout); QWidget::setTabOrder(m_findEdit,m_replaceEdit); connect(m_findEdit,SIGNAL(returnPressed()),this,SLOT(findNext())); connect(m_findNext,SIGNAL(clicked()),this,SLOT(findNext())); connect(m_findPrev,SIGNAL(clicked()),this,SLOT(findPrev())); connect(m_replaceEdit,SIGNAL(returnPressed()),this,SLOT(replace())); connect(m_replace,SIGNAL(clicked()),this,SLOT(replace())); connect(m_replaceAll,SIGNAL(clicked()),this,SLOT(replaceAll())); connect(m_matchCaseCheckBox,SIGNAL(toggled(bool)),this,SLOT(findOptionChanged())); connect(m_matchWordCheckBox,SIGNAL(toggled(bool)),this,SLOT(findOptionChanged())); connect(m_useRegexCheckBox,SIGNAL(toggled(bool)),this,SLOT(findOptionChanged())); connect(m_wrapAroundCheckBox,SIGNAL(toggled(bool)),this,SLOT(findOptionChanged())); connect(m_findEdit,SIGNAL(textChanged(QString)),this,SLOT(findOptionChanged())); connect(m_replaceEdit,SIGNAL(textChanged(QString)),this,SLOT(replaceChanged())); connect(m_liteApp->editorManager(),SIGNAL(currentEditorChanged(LiteApi::IEditor*)),this,SLOT(updateCurrentEditor(LiteApi::IEditor*))); } FindEditor::~FindEditor() { m_liteApp->settings()->setValue(FIND_MATCHWORD,m_matchWordCheckBox->isChecked()); m_liteApp->settings()->setValue(FIND_MATCHCASE,m_matchCaseCheckBox->isChecked()); m_liteApp->settings()->setValue(FIND_USEREGEXP,m_useRegexCheckBox->isChecked()); m_liteApp->settings()->setValue(FIND_WRAPAROUND,m_wrapAroundCheckBox->isChecked()); if (m_widget) { delete m_widget; } } QWidget *FindEditor::widget() { return m_widget; } void FindEditor::setVisible(bool b) { this->m_widget->setVisible(b); if (b) { LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (editor) { QString text; QPlainTextEdit *ed = LiteApi::findExtensionObject<QPlainTextEdit*>(editor,"LiteApi.QPlainTextEdit"); if (ed) { QTextCursor cur = ed->textCursor(); if (!cur.hasSelection()) { cur.select(QTextCursor::WordUnderCursor); } text = cur.selectedText(); } if (!text.isEmpty()) { this->m_findEdit->setText(text); } this->m_findEdit->setFocus(); this->m_findEdit->selectAll(); } } updateCurrentEditor(m_liteApp->editorManager()->currentEditor()); } bool FindEditor::isVisible() const { return m_widget->isVisible(); } void FindEditor::setReplaceMode(bool b) { m_replaceLabel->setVisible(b); m_replaceEdit->setVisible(b); m_replace->setVisible(b); m_replaceAll->setVisible(b); m_showReplaceCheckBox->setChecked(b); } void FindEditor::findHelper(FindOption *opt) { bool bFocus = m_findEdit->hasFocus(); LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (!editor) { return; } LiteApi::ITextEditor *textEditor = LiteApi::getTextEditor(editor); QTextCursor find; if (textEditor) { QPlainTextEdit *ed = LiteApi::getPlainTextEdit(editor); if (ed) { find = findEditor(ed->document(),ed->textCursor(),opt); if (!find.isNull()) { ed->setTextCursor(find); ed->repaint(); } } } else { QTextBrowser *ed = LiteApi::findExtensionObject<QTextBrowser*>(editor,"LiteApi.QTextBrowser"); if (ed) { find = findEditor(ed->document(),ed->textCursor(),opt); if (!find.isNull()) { ed->setTextCursor(find); } } } if (find.isNull()) { m_status->setText(tr("Not found")); } else { m_status->setText(QString("Ln:%1 Col:%2"). arg(find.blockNumber()+1). arg(find.columnNumber()+1)); } if (bFocus) { m_findEdit->setFocus(); } else if (textEditor) { textEditor->onActive(); } } void FindEditor::hideFind() { this->setVisible(false); } void FindEditor::setReady(const QString &findText) { m_widget->setFocus(); if (!findText.isEmpty()) { m_findEdit->setText(findText); } if (m_findEdit->text().isEmpty()) { m_findEdit->setFocus(); } else { m_replaceEdit->setFocus(); } m_status->setText(tr("Ready")); } void FindEditor::getFindOption(FindOption *opt, bool backWard) { opt->findText = m_findEdit->text(); opt->replaceText = m_replaceEdit->text(); opt->matchWord = m_matchWordCheckBox->isChecked(); opt->matchCase = m_matchCaseCheckBox->isChecked(); opt->useRegexp = m_useRegexCheckBox->isChecked(); opt->wrapAround = m_wrapAroundCheckBox->isChecked(); opt->backWard = backWard; } QTextCursor FindEditor::findEditor(QTextDocument *doc, const QTextCursor &cursor, FindOption *opt, bool wrap) { int from = cursor.position(); if (cursor.hasSelection()) { if (opt->backWard) { from = cursor.selectionStart(); } else { from = cursor.selectionEnd(); } } return findEditorHelper(doc,from,opt,wrap); } QTextCursor FindEditor::findEditorHelper(QTextDocument *doc, int from, FindOption *opt, bool wrap) { QTextDocument::FindFlags flags = 0; if (opt->backWard) { flags |= QTextDocument::FindBackward; } if (opt->matchCase) { flags |= QTextDocument::FindCaseSensitively; } if (opt->matchWord) { flags |= QTextDocument::FindWholeWords; } Qt::CaseSensitivity cs = Qt::CaseInsensitive; if (opt->matchCase) { cs = Qt::CaseSensitive; } QTextCursor find; if (opt->useRegexp) { find = doc->find(QRegExp(opt->findText,cs),from,flags); } else { find = doc->find(opt->findText,from,flags); } if (find.isNull() && opt->wrapAround && wrap) { if (opt->backWard) { from = doc->lastBlock().position()+doc->lastBlock().length(); } else { from = 0; } if (opt->useRegexp) { find = doc->find(QRegExp(opt->findText,cs),from,flags); } else { find = doc->find(opt->findText,from,flags); } } return find; } void FindEditor::replaceHelper(LiteApi::ITextEditor *editor, FindOption *opt, int replaceCount) { bool bFocus = m_replaceEdit->hasFocus(); QPlainTextEdit *ed = LiteApi::getPlainTextEdit(editor); if (!ed) { return; } QTextCursor find; QTextCursor cursor = ed->textCursor(); int startLine = cursor.blockNumber(); int startColumn = cursor.columnNumber(); Qt::CaseSensitivity cs = Qt::CaseInsensitive; if (opt->matchCase) { cs = Qt::CaseSensitive; } int from = cursor.position(); if ( cursor.hasSelection() ) { // QString text = cursor.selectedText(); // if (opt->useRegexp) { // if (text.indexOf(QRegExp(opt->findText,cs),0) != -1) { // find = cursor; // } // } else { // if (text.indexOf(opt->findText,0,cs) != -1) { // find = cursor; // } // } from = cursor.selectionStart(); startColumn -= cursor.selectedText().length(); } int number = 0; bool wrap = opt->wrapAround; ed->textCursor().beginEditBlock(); do { if (!find.isNull()) { number++; //find.beginEditBlock(); QString text = find.selectedText(); bool changed = find.blockNumber() == startLine && find.columnNumber() < startColumn; if (changed) { startColumn -= text.length(); } if (opt->useRegexp) { text.replace(QRegExp(opt->findText,cs),opt->replaceText); } else { text.replace(QRegExp(opt->findText,cs,QRegExp::FixedString),opt->replaceText); } find.removeSelectedText(); from = find.position()+ text.length(); find.insertText(text); //find.endEditBlock(); //ed->setTextCursor(find); if (changed) { startColumn += text.length(); } } //cursor = ed->textCursor(); find = findEditorHelper(ed->document(),from,opt,false); if (find.isNull() && wrap) { wrap = false; find = findEditorHelper(ed->document(),0,opt,true); } if (!find.isNull() && opt->wrapAround && !wrap) { if (find.blockNumber() > startLine || (find.blockNumber() == startLine && (find.columnNumber()-find.selectedText().length()) >= startColumn) ) { break; } } if (replaceCount != -1 && number >= replaceCount) { if (!find.isNull()) { ed->setTextCursor(find); m_status->setText(QString("Ln:%1 Col:%2"). arg(find.blockNumber()+1). arg(find.columnNumber()+1)); } else { m_status->setText(tr("Not found")); } break; } } while(!find.isNull()); ed->textCursor().endEditBlock(); ed->repaint(); if (replaceCount == -1) { m_status->setText(QString("Replace:%1").arg(number)); } if (bFocus) { m_replaceEdit->setFocus(); } else if (editor) { editor->onActive(); } } void FindEditor::findNext() { if (!m_option.isValid()) { return; } m_option.backWard = false; findHelper(&m_option); } void FindEditor::findPrev() { if (!m_option.isValid()) { return; } m_option.backWard = true; findHelper(&m_option); } void FindEditor::replace() { if (!m_option.isValid()) { return; } m_option.backWard = false; LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (!editor) { return; } LiteApi::ITextEditor *textEditor = LiteApi::getTextEditor(editor); if (!textEditor) { return; } replaceHelper(textEditor,&m_option,1); } void FindEditor::replaceAll() { if (!m_option.isValid()) { return; } m_option.backWard = false; LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (!editor) { return; } LiteApi::ITextEditor *textEditor = LiteApi::getTextEditor(editor); if (!textEditor) { return; } replaceHelper(textEditor,&m_option,-1); } void FindEditor::findOptionChanged() { getFindOption(&m_option,false); m_status->setText(tr("Ready")); if (m_option.useRegexp) { QRegExp reg(m_option.findText); if (!reg.isValid()) { m_status->setText(reg.errorString()); } } updateCurrentEditor(m_liteApp->editorManager()->currentEditor()); } void FindEditor::replaceChanged() { m_option.replaceText = m_replaceEdit->text(); } void FindEditor::updateCurrentEditor(LiteApi::IEditor *editor) { if (!editor) { return; } LiteApi::ITextEditor *textEditor = LiteApi::getTextEditor(editor); if (!textEditor) { return; } if (m_widget->isVisible()) { textEditor->setFindOption(&m_option); } else { textEditor->setFindOption(0); } }
15,867
C++
.cpp
452
28.811947
138
0.625382
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,457
replacedocument.cpp
visualfc_liteide/liteidex/src/plugins/litefind/replacedocument.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: replacedocument.cpp // Creator: visualfc <visualfc@gmail.com> #include "replacedocument.h" #include <QTextBlock> #include <QTextCursor> #include <QTextDocument> #include <QMutableListIterator> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end ReplaceDocument::ReplaceDocument(LiteApi::IApplication *app, QObject *parent) : QObject(parent), m_liteApp(app), m_document(0) { } ReplaceDocument::~ReplaceDocument() { if (m_document) { delete m_document; } } QList<Find::SearchResultItem> ReplaceDocument::replace(const QString &fileName, const QString &text, const QList<Find::SearchResultItem> &items) { QTextCursor cursor; bool crlf = false; QTextDocument *doc = fileDocument(fileName,cursor,crlf); if (!doc) { return QList<Find::SearchResultItem>(); } cursor.movePosition(QTextCursor::Start); cursor.beginEditBlock(); QList<Find::SearchResultItem> update_items; QTextBlock block = cursor.block(); int offset = 0; foreach(Find::SearchResultItem item, items) { if (!block.isValid()) { break; } while (block.blockNumber() < item.lineNumber-1 ) { block = block.next(); offset = 0; if (!block.isValid()) { break; } } cursor.setPosition(block.position()); cursor.movePosition(QTextCursor::Right,QTextCursor::MoveAnchor,offset+item.textMarkPos); cursor.movePosition(QTextCursor::Right,QTextCursor::KeepAnchor,item.textMarkLength); cursor.removeSelectedText(); cursor.insertText(text); int newoffset = text.length()-item.textMarkLength; item.textMarkPos = offset+item.textMarkPos; item.textMarkLength = text.length(); //item.text = block.text(); offset += newoffset; update_items.push_back(item); //update update_items same line number text int lineNumber = block.blockNumber()+1; QMutableListIterator<Find::SearchResultItem> i(update_items); i.toBack(); while (i.hasPrevious()) { Find::SearchResultItem &item = i.previous(); if (item.lineNumber == lineNumber) { item.text = block.text(); } else if (item.lineNumber < lineNumber) { break; } } } cursor.endEditBlock(); if (m_document) { QFile f(fileName); if (!f.open(QFile::WriteOnly)) { return QList<Find::SearchResultItem>(); } QString text = m_document->toPlainText(); if (crlf) { text.replace(QLatin1Char('\n'), QLatin1String("\r\n")); } f.write(text.toUtf8()); } return update_items; } QTextDocument *ReplaceDocument::fileDocument(const QString &fileName, QTextCursor &cursor, bool &crlf) { LiteApi::IEditor *editor = m_liteApp->editorManager()->findEditor(fileName,true); if (editor) { QPlainTextEdit *ed = LiteApi::getPlainTextEdit(editor); if (ed) { cursor = ed->textCursor(); return ed->document(); } } QFile file(fileName); if (file.open(QFile::ReadOnly)) { QByteArray data = file.readAll(); QString text = QString::fromUtf8(data); int lf = text.indexOf('\n'); if (lf <= 0) { crlf = false; } else { lf = text.indexOf(QRegExp("[^\r]\n"),lf-1); if (lf >= 0) { crlf = false; } else { crlf = true; } } m_document = new QTextDocument(text); cursor = QTextCursor(m_document); return m_document; } return 0; }
4,970
C++
.cpp
140
29.021429
144
0.617123
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,458
filesearchmanager.cpp
visualfc_liteide/liteidex/src/plugins/litefind/filesearchmanager.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: filesearchmanager.cpp // Creator: visualfc <visualfc@gmail.com> #include "filesearchmanager.h" #include "qtc_searchresult/searchresultcolor.h" #include "replacedocument.h" #include <QStackedWidget> #include <QVBoxLayout> #include <QHBoxLayout> #include <QLabel> #include <QComboBox> #include <QMessageBox> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end FileSearchManager::FileSearchManager(LiteApi::IApplication *app, QObject *parent) : LiteApi::IFileSearchManager(parent), m_liteApp(app) { m_currentSearch = 0; m_widget = new QStackedWidget; QHBoxLayout *hbox = new QHBoxLayout; QLabel *label = new QLabel(tr("Search Item:")); m_searchItemCombox = new QComboBox; hbox->addWidget(label); hbox->addWidget(m_searchItemCombox); hbox->addStretch(); QVBoxLayout *vbox = new QVBoxLayout; m_searchItemStackedWidget = new QStackedWidget; vbox->addLayout(hbox); vbox->addWidget(m_searchItemStackedWidget); vbox->addStretch(); m_searchWidget = new QWidget; m_searchWidget->setLayout(vbox);; m_searchResultWidget = new Find::Internal::SearchResultWidget(m_widget); m_searchResultWidget->setPreserveCaseSupported(false); m_searchResultWidget->setSearchAgainSupported(false); m_searchResultWidget->setAutoExpandResults(true); m_searchResultWidget->setInfoWidgetLabel(tr("Only golang file changes can be revert!")); QPalette pal = m_searchWidget->palette(); Find::Internal::SearchResultColor color; color.textForeground = pal.color(QPalette::Text); color.textBackground = pal.color(QPalette::Base); color.highlightForeground = pal.color(QPalette::Text); color.highlightBackground = QColor(56,169,235);//pal.color(QPalette::ToolTipBase); QFont font = m_searchWidget->font(); m_searchResultWidget->setTextEditorFont(font,color); m_widget->addWidget(m_searchWidget); m_widget->addWidget(m_searchResultWidget); QAction *newSearch = new QAction(tr("New Search"),this); m_fmctxFileSearchAction = new QAction(tr("File Search"),this); connect(m_fmctxFileSearchAction,SIGNAL(triggered(bool)),this,SLOT(fmctxFileSearch())); m_toolAct = m_liteApp->toolWindowManager()->addToolWindow(Qt::BottomDockWidgetArea, m_widget,"SearchResult",tr("Search Result"),true, QList<QAction*>() << newSearch); m_liteApp->extension()->addObject("LiteApi.IFileSearchManager",this); connect(newSearch,SIGNAL(triggered()),this,SLOT(newSearch())); connect(m_searchItemCombox,SIGNAL(currentIndexChanged(int)),this,SLOT(currentSearchItemChanged(int))); connect(m_searchResultWidget,SIGNAL(activated(Find::SearchResultItem)),this,SLOT(activated(Find::SearchResultItem))); connect(m_searchResultWidget,SIGNAL(replaceButtonClicked(QString,QList<Find::SearchResultItem>,bool)),this,SLOT(doReplace(QString,QList<Find::SearchResultItem>,bool))); connect(m_liteApp->fileManager(),SIGNAL(aboutToShowFolderContextMenu(QMenu*,LiteApi::FILESYSTEM_CONTEXT_FLAG,QFileInfo,QString)),this,SLOT(aboutToShowFolderContextMenu(QMenu*,LiteApi::FILESYSTEM_CONTEXT_FLAG,QFileInfo,QString))); } FileSearchManager::~FileSearchManager() { foreach (LiteApi::IFileSearch *search, m_fileSearchList) { delete search; } m_fileSearchList.clear(); delete m_widget; } void FileSearchManager::addFileSearch(LiteApi::IFileSearch *search) { m_fileSearchList.push_back(search); if (search->widget()) { m_searchItemStackedWidget->addWidget(search->widget()); m_searchItemCombox->addItem(search->displayName(),search->mimeType()); } connect(search,SIGNAL(findStarted()),this,SLOT(findStarted())); connect(search,SIGNAL(findFinished(bool)),this,SLOT(findFinished(bool))); connect(search,SIGNAL(findResult(LiteApi::FileSearchResult)),this,SLOT(findResult(LiteApi::FileSearchResult))); connect(search,SIGNAL(searchTextChanged(QString)),this,SLOT(searchTextChanged(QString))); connect(search,SIGNAL(findError(QString)),this,SLOT(findError(QString))); } LiteApi::IFileSearch *FileSearchManager::findFileSearch(const QString &mime) { foreach (LiteApi::IFileSearch *i, m_fileSearchList) { if (i->mimeType() == mime) { return i; } } return 0; } QList<LiteApi::IFileSearch *> FileSearchManager::fileSearchList() const { return m_fileSearchList; } void FileSearchManager::setCurrentSearch(LiteApi::IFileSearch *search) { m_currentSearch = search; if (m_currentSearch->widget()) { m_searchItemStackedWidget->setCurrentWidget(search->widget()); } m_searchResultWidget->setShowReplaceUI(m_currentSearch->replaceMode()); m_searchResultWidget->setCancelSupported(m_currentSearch->canCancel()); m_searchResultWidget->setReadOnly(m_currentSearch->readOnly()); m_currentSearch->activate(); } void FileSearchManager::showFileSearch(const QString &text, const QString &filter, const QString &path) { LiteApi::IFileSearch *search = this->findFileSearch("search/filesystem"); if (!search) { return; } m_toolAct->setChecked(true); m_widget->setCurrentWidget(m_searchWidget); setCurrentSearch(search); search->setSearchInfo(text,filter,path); } void FileSearchManager::aboutToShowFolderContextMenu(QMenu *menu, LiteApi::FILESYSTEM_CONTEXT_FLAG /*flag*/, const QFileInfo &info, const QString &context) { if (!info.isDir()) { return; } menu->addSeparator(); menu->addAction(m_fmctxFileSearchAction); m_fmctxFileInfo = info; } void FileSearchManager::fmctxFileSearch() { bool hasGo = false; foreach(QFileInfo info, QDir(m_fmctxFileInfo.filePath()).entryInfoList(QDir::Files)) { if (info.suffix() == "go") { hasGo = true; break; } } showFileSearch("",hasGo ? "*.go": "*",m_fmctxFileInfo.filePath()); } void FileSearchManager::activated(const Find::SearchResultItem &item) { if (item.path.isEmpty()) { return; } //QString fileName = item.path.at(0); LiteApi::gotoLine(m_liteApp,item.path.at(0),item.lineNumber-1,item.textMarkPos,true,true); // LiteApi::IEditor *editor = m_liteApp->fileManager()->openEditor(fileName,true); // if (!editor) { // return; // } // LiteApi::ITextEditor *textEditor = LiteApi::getTextEditor(editor); // if (!textEditor) { // return; // } // textEditor->gotoLine(item.lineNumber-1,item.textMarkPos,false); } void FileSearchManager::newSearch() { m_toolAct->setChecked(true); m_widget->setCurrentWidget(m_searchWidget); currentSearchItemChanged(0); } void FileSearchManager::currentSearchItemChanged(int item) { QString mimeType = m_searchItemCombox->itemData(item,Qt::UserRole).toString(); LiteApi::IFileSearch *search = this->findFileSearch(mimeType); if (search) { setCurrentSearch(search); } } void FileSearchManager::findStarted() { m_toolAct->setChecked(true); m_widget->setCurrentWidget(m_searchResultWidget); m_searchResultWidget->restart(); m_searchResultWidget->setInfo(m_currentSearch->displayName()+":",QString(),m_currentSearch->searchText()); m_searchResultWidget->setTextToReplace(m_currentSearch->searchText()); } void FileSearchManager::findFinished(bool) { m_searchResultWidget->finishSearch(false); } void FileSearchManager::findError(const QString &error) { m_searchResultWidget->setInfo(m_currentSearch->displayName()+" Error:",error,error); } void FileSearchManager::findResult(const LiteApi::FileSearchResult &result) { m_searchResultWidget->addResult(result.path, result.line, result.lineText, result.col, result.len); } void FileSearchManager::doReplace(const QString &text, const QList<Find::SearchResultItem> &items, bool /*preserveCase*/) { if (text.isEmpty()) { int ret = QMessageBox::warning(m_liteApp->mainWindow(),tr("LiteIDE X"),tr("Warning! Replace text is empty.\nWant to remove all the search items?"), QMessageBox::Cancel|QMessageBox::Yes|QMessageBox::No); if (ret != QMessageBox::Yes) { return; } } else if (text.trimmed().isEmpty()) { int ret = QMessageBox::warning(m_liteApp->mainWindow(),tr("LiteIDE X"),tr("Warning! Replace text is whitespace.\nWant to replace to all the search items to whitespace?"), QMessageBox::Cancel|QMessageBox::Yes|QMessageBox::No); if (ret != QMessageBox::Yes) { return; } } if (text == m_searchResultWidget->searchText()) { return; } if (items.isEmpty()) { return; } QHash<QString, QList<Find::SearchResultItem> > changes; foreach (const Find::SearchResultItem &item, items) changes[QDir::fromNativeSeparators(item.path.first())].append(item); // Checking for files without write permissions QHashIterator<QString, QList<Find::SearchResultItem> > it(changes); QStringList roFiles; while (it.hasNext()) { it.next(); const QFileInfo fileInfo(it.key()); if (!fileInfo.isWritable()) { roFiles.append(it.key()); } } if (!roFiles.isEmpty()) { QString text = tr("The following files have no write permissions. Do you want to change the permissions?"); text += "\n"; text += roFiles.join("\n"); int ret = QMessageBox::warning(m_liteApp->mainWindow(),tr("File is readonly"),text,QMessageBox::Yes|QMessageBox::Cancel,QMessageBox::Cancel); if (ret != QMessageBox::Yes) { return; } foreach(QString fileName, roFiles) { QFile::setPermissions(fileName, QFile::permissions(fileName) | QFile::WriteUser); } } //revert mode m_searchResultWidget->clear(); it.toFront(); while(it.hasNext()) { it.next(); ReplaceDocument doc(m_liteApp); QList<Find::SearchResultItem> items = doc.replace(it.key(),text,it.value()); m_searchResultWidget->addResults(items,Find::AddOrdered,true); } m_liteApp->editorManager()->saveAllEditors(false); LiteApi::IEditor *edit = m_liteApp->editorManager()->currentEditor(); if (edit) { QPlainTextEdit *ed = LiteApi::getPlainTextEdit(edit); if (ed) { ed->repaint(); } } m_searchResultWidget->setRevertMode(text,m_currentSearch->searchText()); m_searchResultWidget->repaint(); } void FileSearchManager::searchTextChanged(const QString &text) { m_searchResultWidget->setInfo(m_currentSearch->displayName()+":",QString(),text); m_searchResultWidget->setTextToReplace(text); }
12,066
C++
.cpp
286
36.84965
233
0.694161
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,459
terminaloptionfactory.cpp
visualfc_liteide/liteidex/src/plugins/terminal/terminaloptionfactory.cpp
#include "terminal_global.h" #include "terminaloption.h" #include "terminaloptionfactory.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end TerminalOptionFactory::TerminalOptionFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IOptionFactory(parent), m_liteApp(app) { } QStringList TerminalOptionFactory::mimeTypes() const { return QStringList() << OPTION_TERMIANL; } LiteApi::IOption *TerminalOptionFactory::create(const QString &mimeType) { if (mimeType == OPTION_TERMIANL) { return new TerminalOption(m_liteApp,this); } return 0; }
827
C++
.cpp
28
26.321429
89
0.722362
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,460
terminal.cpp
visualfc_liteide/liteidex/src/plugins/terminal/terminal.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2020 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: terminal.cpp // Creator: visualfc <visualfc@gmail.com> #include "terminal.h" #include "terminal_global.h" #include "../liteapp/liteapp_global.h" #include "vterm/vtermwidget.h" #include "vterm/vtermcolor.h" #include "liteenvapi/liteenvapi.h" #include <QTabWidget> #include <QFileInfo> #include <QDir> #include <QTime> #include <QFontMetrics> #include <QHBoxLayout> #include <QVBoxLayout> #include <QToolBar> #include <QInputDialog> #include <QActionGroup> #include <QTemporaryFile> #include <QApplication> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end #ifdef Q_OS_WIN static Command makeCommand(const QString &name, const QString &path, const QStringList &args = QStringList(), const QStringList &loginArgs = QStringList()) { Command cmd; cmd.name = name; cmd.path = path; cmd.args = args; cmd.loginArgs = loginArgs; return cmd; } static QString checkFile(const QStringList &dirList, const QString &filePath) { foreach (QString root, dirList) { QFileInfo info(root,filePath); if (info.exists()) { return QDir::toNativeSeparators(info.filePath()); } } return QString(); } static QString GetWindowGitBash() { QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); QStringList dirList; dirList << env.value("ProgramW6432","C:\\Program Files"); dirList << env.value("ProgramFiles","C:\\Program Files"); return checkFile(dirList,"Git\\bin\\bash.exe"); } static QString GetWindowPowerShell() { QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); QStringList dirList; dirList << env.value("windir","C:\\Windows"); return checkFile(dirList,"System32\\WindowsPowerShell\\v1.0\\powershell.exe"); } static QString GetWindowsShell() { QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); QString windir = env.value("windir","C:\\Windows"); QFileInfo info(windir,"System32\\cmd.exe"); return QDir::toNativeSeparators(info.filePath()); } #endif static QStringList GetUnixShellList() { QFile f("/etc/shells"); if (!f.open(QFile::ReadOnly)) { return QStringList(); } QStringList shells; QString ar = QString::fromUtf8(f.readAll()); foreach (QString line, ar.split("\n")) { line = line.trimmed(); if (line.isEmpty() || line.startsWith("#")) { continue; } int pos = line.indexOf("#"); if (pos > 0) { line = line.left(pos).trimmed(); } shells << line; } return shells; } Terminal::Terminal(LiteApi::IApplication *app, QObject *parent) : LiteApi::ITerminal(parent), m_liteApp(app), m_indexId(0) { qRegisterMetaType<TabInfoData>("TabInfoData"); qRegisterMetaTypeStreamOperators<TabInfoData>("TabInfoData"); m_widget = new QWidget; m_tab = new LiteTabWidget(QSize(16,16)); m_tab->tabBar()->setTabsClosable(true); m_tab->tabBar()->setElideMode(Qt::ElideNone); QVBoxLayout *layout = new QVBoxLayout(m_widget); layout->setMargin(0); layout->setSpacing(0); layout->addWidget(m_tab->tabBarWidget()); layout->addWidget(m_tab->stackedWidget()); m_newTabAct = new QAction(tr("New"),this); m_newTabAct->setToolTip(tr("Open a new terminal")); connect(m_newTabAct,SIGNAL(triggered()),this,SLOT(newTerminal())); m_closeTabAct = new QAction(tr("Close"),this); m_closeTabAct->setToolTip(tr("Close current terminal")); connect(m_closeTabAct,SIGNAL(triggered()),this,SLOT(closeCurrenTab())); m_closeAllTabAct = new QAction(tr("CloseAll"),this); m_closeAllTabAct->setToolTip(tr("Close all terminal")); connect(m_closeAllTabAct,SIGNAL(triggered()),this,SLOT(closeAllTab())); #ifndef Q_OS_WIN m_loadEnvAct = new QAction(tr("LoadEnv"),this); m_loadEnvAct->setToolTip(tr("Current terminal load environment from LiteIDE")); connect(m_loadEnvAct,SIGNAL(triggered()),this,SLOT(tabLoadEnv())); #endif QList<QAction*> actions; m_filterMenu = new QMenu(tr("Filter")); m_filterMenu->setIcon(QIcon("icon:images/filter.png")); #ifdef Q_OS_WIN QString bash = GetWindowGitBash(); QString powershell = GetWindowPowerShell(); QString shell = GetWindowsShell(); m_cmdList.append(makeCommand("cmd",shell)); if (!powershell.isEmpty()) { m_cmdList.append(makeCommand("powershell",powershell)); } if (!bash.isEmpty()) { m_cmdList.append(makeCommand("bash",bash)); } #else QStringList shellList = GetUnixShellList(); shellList.prepend("/bin/bash"); shellList.removeDuplicates(); foreach (QString shell, shellList) { QFileInfo info(shell); if (!info.exists()) { continue; } Command cmd; cmd.name = info.fileName(); cmd.path = info.filePath(); cmd.loginArgs << "-l"; m_cmdList << cmd; } #endif m_curName = m_liteApp->settings()->value(TERMINAL_CURCMD,m_cmdList[0].name).toString(); m_darkMode = m_liteApp->settings()->value(TERMINAL_DARKMODE,false).toBool(); m_loginMode = m_liteApp->settings()->value(TERMINAL_LOGINSHELL,false).toBool(); #ifdef Q_OS_WIN m_loginMode = false; #endif m_darkModeAct = new QAction(tr("Dark Mode"),this); m_darkModeAct->setCheckable(true); m_darkModeAct->setChecked(m_darkMode); m_newTabAct->setText(tr("New")+" ["+m_curName+"]"); connect(m_darkModeAct,SIGNAL(toggled(bool)),this,SLOT(toggledDarkMode(bool))); m_filterMenu->addAction(m_darkModeAct); #ifndef Q_OS_WIN m_loginModeAct = new QAction(tr("Login Mode (shell --login)"),this); m_loginModeAct->setCheckable(true); m_loginModeAct->setChecked(m_loginMode); m_filterMenu->addAction(m_loginModeAct); connect(m_loginModeAct,SIGNAL(toggled(bool)),this,SLOT(toggledLoginMode(bool))); #endif if (m_cmdList.size() > 1) { QActionGroup *group = new QActionGroup(this); foreach (Command cmd, m_cmdList) { QString info = cmd.name+"\t"+cmd.path; if (!cmd.args.isEmpty()) { info += " "+cmd.args.join(" "); } QAction *act = new QAction(info,this); act->setData(cmd.name); act->setCheckable(true); act->setToolTip(cmd.path); if (m_curName == cmd.name) { act->setChecked(true); } group->addAction(act); } connect(group,SIGNAL(triggered(QAction*)),this,SLOT(triggeredCmd(QAction*))); m_filterMenu->addSeparator(); m_filterMenu->addActions(group->actions()); actions << m_filterMenu->menuAction(); } actions << m_newTabAct << m_closeTabAct << m_closeAllTabAct; #ifndef Q_OS_WIN actions << m_loadEnvAct; #endif m_listMenu = new QMenu; m_listGroup = new QActionGroup(this); m_tab->setListMenu(m_listMenu); connect(m_listMenu,SIGNAL(aboutToShow()),this,SLOT(aboutToShowListMenu())); connect(m_listGroup,SIGNAL(triggered(QAction*)),this,SLOT(triggeredListAction(QAction*))); m_toolWindowAct = m_liteApp->toolWindowManager()->addToolWindow(Qt::BottomDockWidgetArea,m_widget,"Terminal",tr("Terminal"),true,actions); connect(m_toolWindowAct,SIGNAL(toggled(bool)),this,SLOT(visibilityChanged(bool))); connect(m_tab,SIGNAL(tabCloseRequested(int)),this,SLOT(tabCloseRequested(int))); connect(m_tab,SIGNAL(currentChanged(int)),this,SLOT(tabCurrentChanged(int))); applyOption(OPTION_TERMIANL); connect(m_liteApp,SIGNAL(loaded()),this,SLOT(appLoaded())); connect(m_liteApp->optionManager(),SIGNAL(applyOption(QString)),this,SLOT(applyOption(QString))); #if QT_VERSION >= 0x050000 // connect(m_tab->tabBar(),SIGNAL(tabBarDoubleClicked(int)),this,SLOT(tabBarDoubleClicked(int))); #endif applyOption(OPTION_LITEAPP); m_liteApp->extension()->addObject("LiteApi.ITerminal",this); //m_fmctxOpenTerminalAct = new QAction(tr("Open in Integrated Terminal"),this); //connect(m_fmctxOpenTerminalAct,SIGNAL(triggered()),this,SLOT(fmctxOpenTerminal())); //connect(m_liteApp->fileManager(),SIGNAL(aboutToShowFolderContextMenu(QMenu*,LiteApi::FILESYSTEM_CONTEXT_FLAG,QFileInfo,QString)),this,SLOT(aboutToShowFolderContextMenu(QMenu*,LiteApi::FILESYSTEM_CONTEXT_FLAG,QFileInfo,QString))); qApp->installEventFilter(this); } #ifdef Q_OS_MAC static QMap<QString,QString> getProcessWorkDirList(const QStringList &pids) { QString cmd = QString("lsof -a -p %1 -d cwd -Fn").arg(pids.join(",")); QMap<QString,QString> kv; QProcess p; p.start(cmd); if (!p.waitForStarted(1000)) { return kv; } if (!p.waitForFinished(3000)) { p.kill(); return kv; } QByteArray ar = p.readAllStandardOutput(); QStringList lines = QString::fromUtf8(ar).split("\n",qtSkipEmptyParts); // p4153 // fcwd // n/Users/vfc int index = 0; foreach (QString line, lines) { if (index %3 == 2) { QString pid = lines[index-2]; if (line.startsWith("n") && pid.startsWith("p")) { kv[pid.mid(1)] = line.mid(1); } } index++; } return kv; } #elif defined(Q_OS_WIN) static QMap<QString,QString> getProcessWorkDirList(const QStringList &pids) { QMap<QString,QString> kv; return kv; } #else static QMap<QString,QString> getProcessWorkDirList(const QStringList &pids) { QMap<QString,QString> kv; if (QDir("/proc").exists()) { foreach (QString pid, pids) { QFileInfo info("/proc/"+pid+"/cwd"); if (info.isSymLink()) { kv[pid] = info.symLinkTarget(); } } } else { // pwdx 9194 9947 // 9194: /home/my // 9947: /home/my QString cmd = QString("pwdx %1").arg(pids.join(" ")); QProcess p; p.start(cmd); if (!p.waitForStarted(1000)) { return kv; } if (!p.waitForFinished(3000)) { p.kill(); return kv; } QByteArray ar = p.readAllStandardOutput(); QStringList lines = QString::fromUtf8(ar).split("\n",qtSkipEmptyParts); foreach (QString line, lines) { QStringList ar = line.split(":",qtSkipEmptyParts); QString path = ar[1].trimmed(); if (ar.size() == 2 && path.startsWith("/")) { kv[ar[0].trimmed()] = path; } } } return kv; } #endif Terminal::~Terminal() { m_liteApp->settings()->beginGroup("terminal/tabs"); m_liteApp->settings()->remove(""); QStringList pids; for (int i = 0; i < m_tab->count(); i++) { TabInfoData data = m_tab->tabData(i).value<TabInfoData>(); if (!data.pid.isEmpty()) { pids << data.pid; } } // check pid QMap<QString,QString> kv = getProcessWorkDirList(pids); for (int i = 0; i < m_tab->count(); i++) { QString key = QString("%1").arg(i); TabInfoData data = m_tab->tabData(i).value<TabInfoData>(); data.title = m_tab->tabBar()->tabText(i); if (!data.pid.isEmpty()) { QString dir = kv[data.pid]; if (!dir.isEmpty()) { data.dir = dir; data.title = makeTitle(QFileInfo(dir).fileName()); } } m_liteApp->settings()->setValue(key,QVariant::fromValue(data)); } m_liteApp->settings()->endGroup(); closeAllTab(); m_listMenu->clear(); delete m_listMenu; delete m_filterMenu; qDeleteAll(m_listGroup->actions()); delete m_listGroup; delete m_tab; delete m_widget; } void Terminal::openDefaultTerminal(const QString &workDir) { m_toolWindowAct->setChecked(true); QString dir = QDir::cleanPath(QDir::fromNativeSeparators(workDir)); for (int i = 0; i < m_tab->count(); i++) { TabInfoData data = m_tab->tabData(i).value<TabInfoData>(); QString pwd = getTabCurrentWorkDir(i); // check current work dir is same if (data.dir == dir && pwd == dir && data.cmd == m_curName) { if (!data.open) { m_tab->setCurrentIndex(i); return; } else { VTermWidget *widget = (VTermWidget*)m_tab->widget(i); if (widget && widget->process()->processList() == 1) { m_tab->setCurrentIndex(i); widget->setFocus(); return; } } } } QString cmdName = m_curName; //QString title = QString("%1 %2").arg(m_curName).arg(++m_indexId); dir = QDir::toNativeSeparators(workDir); //openNewTerminal(cmdName,m_loginMode,title,dir,env); VTermWidget *term = new VTermWidget(m_liteApp, m_terminalFont, m_widget); QString title = makeTitle(QFileInfo(dir).fileName()); int index = m_tab->addTab(term,title,dir); m_tab->setCurrentIndex(index); openTerminal(index,term,cmdName,m_loginMode,dir); } void Terminal::appLoaded() { QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); m_liteApp->settings()->beginGroup("terminal/tabs"); foreach(QString key,m_liteApp->settings()->childKeys()) { TabInfoData data = m_liteApp->settings()->value(key).value<TabInfoData>(); if (!data.cmd.isEmpty() && !data.title.isEmpty()) { VTermWidget *widget = new VTermWidget(m_liteApp,m_terminalFont, m_widget); int index = m_tab->addTab(widget,data.title,QDir::toNativeSeparators(data.dir)); data.open = false; m_tab->setTabData(index,QVariant::fromValue(data)); } } m_liteApp->settings()->endGroup(); m_indexId = m_tab->count(); if (m_tab->count() >= 1) { m_tab->setCurrentIndex(m_tab->count()-1); } } void Terminal::aboutToShowListMenu() { m_listMenu->clear(); QList<QAction*> actions = m_listGroup->actions(); qDeleteAll(actions); for (int i = 0; i < m_tab->count(); i++) { TabInfoData data = m_tab->tabData(i).value<TabInfoData>(); QString info; if (data.login) { info = QString("%1\t[%2 --login]").arg(m_tab->tabText(i),data.cmd); } else { info = QString("%1\t[%2]").arg(m_tab->tabText(i),data.cmd); } QAction *act = new QAction(info,m_listGroup); act->setData(i); act->setCheckable(true); m_listGroup->addAction(act); if (m_tab->currentIndex() == i) { act->setChecked(true); } } m_listMenu->addActions(m_listGroup->actions()); } void Terminal::triggeredListAction(QAction *act) { int index = act->data().toInt(); m_tab->setCurrentIndex(index); } void Terminal::aboutToShowFolderContextMenu(QMenu *menu, LiteApi::FILESYSTEM_CONTEXT_FLAG flag, const QFileInfo &info,const QString &context) { // menu->addSeparator(); // menu->addAction(m_fmctxOpenTerminalAct); // m_fmctxFileInfo = info; } void Terminal::fmctxOpenTerminal() { QString dir; if (m_fmctxFileInfo.isDir()) { dir = m_fmctxFileInfo.filePath(); } else { dir = m_fmctxFileInfo.path(); } openDefaultTerminal(dir); } void Terminal::updateFont() { QString fontFamily = m_liteApp->settings()->value(TERMINAL_FAMILY,TERMINAL_FAMILY_DEFAULT).toString(); int fontSize = m_liteApp->settings()->value(TERMINAL_FONTSIZE,12).toInt(); int fontZoom = m_liteApp->settings()->value(TERMINAL_FONTZOOM,100).toInt(); bool antialias = m_liteApp->settings()->value(TERMINAL_ANTIALIAS,true).toBool(); if (!QFontDatabase().hasFamily(fontFamily)) { #if QT_VERSION >= 0x050200 fontFamily = QFontDatabase::systemFont(QFontDatabase::FixedFont).family(); #else fontFamily = QApplication::font().family(); #endif } m_terminalFont.setFamily(fontFamily); m_terminalFont.setPointSize(fontSize*fontZoom/100.0); if (antialias) { m_terminalFont.setStyleStrategy(QFont::PreferAntialias); } else { m_terminalFont.setStyleStrategy(QFont::NoAntialias); } } Command Terminal::lookupCommand(const QString &name) { foreach(Command cmd, m_cmdList) { if (cmd.name == name) { return cmd; } } return m_cmdList[0]; } void Terminal::openTerminal(int index, VTermWidget *term, const QString &cmdName, bool login, const QString &workdir) { Command cmd = lookupCommand(cmdName); term->setFocus(); term->updateGeometry(); term->setDarkMode(m_darkMode); connect(term,SIGNAL(titleChanged(QString)),this,SLOT(termTitleChanged(QString))); connect(term,SIGNAL(exited()),this,SLOT(termExited())); connect(term,SIGNAL(started()),this,SLOT(termStarted())); // check valid or home QString dir; if (QDir(workdir).exists()) { dir = workdir; } else { dir = QDir::homePath(); } dir = QDir::cleanPath(dir); QString info; QString attr; if (!cmd.loginArgs.isEmpty()) { if (login) { attr = "login shell"; } else { attr = "non-login shell"; } } else { login = false; attr = "open shell"; } info = QString("%1: %2 [%3] in %4").arg(QTime::currentTime().toString("hh:mm:ss")).arg(attr).arg(cmd.path).arg(dir); term->inputWrite(term_color(info,TERM_COLOR_DEFAULT,TERM_COLOR_DEFAULT,TERM_ATTR_BOLD).toUtf8()); term->inputWrite("\r\n"); if (login) { term->inputWrite(term_color("Warning, the Login Shell Go environment may be different from LiteIDE.",TERM_COLOR_RED,TERM_COLOR_DEFAULT,TERM_ATTR_BOLD).toUtf8()); term->inputWrite("\r\n"); term->inputWrite(term_color("Please use LoadEnv action to load environment from LiteIDE if need.",TERM_COLOR_RED,TERM_COLOR_DEFAULT,TERM_ATTR_BOLD).toUtf8()); term->inputWrite("\r\n"); } QStringList args = cmd.args; QProcessEnvironment env; if (login) { args.append(cmd.loginArgs); env = QProcessEnvironment::systemEnvironment(); } else { env = LiteApi::getGoEnvironment(m_liteApp); } TabInfoData data; data.cmd = cmdName; data.dir = QDir::fromNativeSeparators(dir); data.login = login; m_tab->setTabData(index,QVariant::fromValue(data)); term->start(cmd.path,args,dir,env.toStringList()); data.open = true; data.pid = QString("%1").arg(term->process()->pid()); m_tab->setTabData(index,QVariant::fromValue(data)); } QString Terminal::makeTitle(const QString &baseName) const { bool rename = false; int index = 0; for (int i = 0; i < m_tab->count(); i++) { QString name = m_tab->tabText(i); if (name == baseName) { rename = true; index++; } if (name.startsWith(baseName+" (")) { index++; } } if (!rename) { return baseName; } return QString("%1 (%2)").arg(baseName).arg(index); } QString Terminal::getTabCurrentWorkDir(int index) const { TabInfoData data = m_tab->tabData(index).value<TabInfoData>(); if (!data.open) { return data.dir; } VTermWidget *widget = static_cast<VTermWidget*>(m_tab->widget(index)); QString pid = QString("%1").arg(widget->process()->pid()); QMap<QString,QString> kv = getProcessWorkDirList(QStringList() << pid); QString dir = kv[pid]; if (!dir.isEmpty()) { return dir; } return data.dir; } bool Terminal::eventFilter(QObject *obj, QEvent *e) { switch (e->type()) { case QEvent::ShortcutOverride: if (qApp->focusWidget() == m_tab->currentWidget() && static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape) { e->accept(); } break; } return QObject::eventFilter(obj,e); } void Terminal::newTerminal() { QString cmdName = m_curName; //QString title = QString("%1 %2").arg(m_curName).arg(++m_indexId); QString dir; LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (editor && !editor->filePath().isEmpty()) { dir = QFileInfo(editor->filePath()).path(); } if (dir.isEmpty()) { dir = QDir::homePath(); } dir = QDir::toNativeSeparators(dir); QString title = makeTitle(QFileInfo(dir).fileName()); //openNewTerminal(cmdName,m_loginMode,title,dir,env); VTermWidget *term = new VTermWidget(m_liteApp, m_terminalFont, m_widget); int index = m_tab->addTab(term,title,QDir::toNativeSeparators(dir)); m_tab->setCurrentIndex(index); openTerminal(index,term,cmdName,m_loginMode,dir); } void Terminal::tabLoadEnv() { int index = m_tab->currentIndex(); if (index >= 0) { this->loadEnv(index); } } void Terminal::visibilityChanged(bool b) { if (!b) { return; } if (m_tab->count() == 0) { newTerminal(); } QWidget *widget = m_tab->currentWidget(); if (widget) { widget->setFocus(); } //deploy load tabCurrentChanged(m_tab->currentIndex()); } void Terminal::termExited() { VTermWidget *widget = static_cast<VTermWidget*>(sender()); int index = m_tab->indexOf(widget); if (index >= 0) { m_tab->removeTab(index); } widget->deleteLater(); } void Terminal::termStarted() { // VTermWidget *widget = static_cast<VTermWidget*>(sender()); // int index = m_tab->indexOf(widget); // if (index >= 0) { // this->loadEnv(index); // } } void Terminal::loadEnv(int index) { VTermWidget *widget = static_cast<VTermWidget*>(m_tab->widget(index)); if (widget->process()->processList() > 1) { return; } TabInfoData data = m_tab->tabData(index).value<TabInfoData>(); QTemporaryFile file; file.setAutoRemove(false); if (file.open()) { QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); QStringList list; foreach (QString key, env.keys()) { if (key.contains("(")) { continue; } list << QString("export %1=\"%2\"").arg(key).arg(env.value(key)); } file.write("#!/bin/sh\n"); file.write("echo \"load environment form LiteIDE.\""); file.write("\n"); file.write(list.join("\n").toUtf8()); file.write("\n"); file.write("rm "+file.fileName().toUtf8()); file.write("\n"); file.close(); } file.setPermissions(file.permissions() | QFile::ExeUser | QFile::ExeOwner); widget->process()->write("source "+file.fileName().toUtf8()+"\n"); } void Terminal::termTitleChanged(QString title) { VTermWidget *widget = static_cast<VTermWidget*>(sender()); int index = m_tab->indexOf(widget); if (index >= 0) { m_tab->setTabToolTip(index,title); } } void Terminal::tabCloseRequested(int index) { VTermWidget *widget = static_cast<VTermWidget*>(m_tab->widget(index)); m_tab->removeTab(index); if (widget) { this->disconnect(widget,0,this,0); widget->deleteLater(); } } void Terminal::tabCurrentChanged(int index) { //deploy load if (!m_widget->isVisible()) { return; } TabInfoData data = m_tab->tabData(index).value<TabInfoData>(); if (data.cmd.isEmpty()) { return; } if (data.open) { VTermWidget *term = static_cast<VTermWidget*>(m_tab->widget(index)); term->setFocus(); return; } data.open = true; m_tab->setTabData(index,QVariant::fromValue(data)); VTermWidget *term = static_cast<VTermWidget*>(m_tab->widget(index)); openTerminal(index,term,data.cmd,data.login,data.dir); } void Terminal::tabBarDoubleClicked(int index) { QString text = m_tab->tabText(index); bool ok = false; text = QInputDialog::getText(m_widget,tr("Terminal"),tr("Rename Tab Title"),QLineEdit::Normal,text,&ok); if (ok && !text.isEmpty()) { m_tab->setTabText(index,text); TabInfoData data = m_tab->tabData(index).value<TabInfoData>(); data.title = text; m_tab->setTabData(index,QVariant::fromValue(data)); } } void Terminal::closeCurrenTab() { int index = m_tab->currentIndex(); if (index >= 0) { tabCloseRequested(index); } } void Terminal::closeAllTab() { for (int i = m_tab->count()-1; i >= 0; i--) { VTermWidget *widget = static_cast<VTermWidget*>(m_tab->widget(i)); m_tab->removeTab(i); if (widget) { disconnect(widget,0,this,0); widget->deleteLater(); } } } void Terminal::triggeredCmd(QAction *act) { m_curName = act->data().toString(); m_liteApp->settings()->setValue(TERMINAL_CURCMD,m_curName); m_newTabAct->setText(tr("New")+ " ["+m_curName+"]"); } void Terminal::toggledDarkMode(bool checked) { m_darkMode = checked; m_liteApp->settings()->setValue(TERMINAL_DARKMODE,m_darkMode); } void Terminal::toggledLoginMode(bool checked) { m_loginMode = checked; m_liteApp->settings()->setValue(TERMINAL_LOGINSHELL,m_loginMode); } void Terminal::applyOption(const QString &opt) { if (opt == OPTION_TERMIANL) { updateFont(); } else if (opt == OPTION_LITEAPP) { #ifdef Q_OS_MAC #if QT_VERSION >= 0x050900 QString qss = m_liteApp->settings()->value(LITEAPP_QSS,"default.qss").toString(); if (qss == "default.qss") { m_tab->tabBar()->setStyleSheet( "QTabBar::tab {" "border: 1px solid #C4C4C3;" "border-bottom-color: #C2C7CB; /* same as the pane color */" "min-width: 8ex;" "padding: 4px 2px 4px 2px;" "}" "QTabBar::close-button:hover,QTabBar::close-button:selected {" "margin: 0px;" "image: url(:/images/close.png);" "subcontrol-position: left;" "padding: 1px;" "}" "QTabBar::tab:selected, QTabBar::tab:hover {" "background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1," "stop: 0 #fafafa, stop: 0.4 #f4f4f4," "stop: 0.5 #e7e7e7, stop: 1.0 #fafafa);" "}" "QTabBar::tab:selected {" "border-color: #9B9B9B;" "border-bottom-color: #C2C7CB; /* same as pane color */" "}" "QTabBar::tab:!selected {" "margin-top: 2px; /* make non-selected tabs look smaller */" "}"); } else { m_tab->tabBar()->setStyleSheet("QTabBar::close-button:hover,QTabBar::close-button:selected {margin: 0px; image: url(:/images/close.png); subcontrol-position: left; }"); } #endif #endif } }
27,982
C++
.cpp
786
29.475827
235
0.627457
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,461
terminalplugin.cpp
visualfc_liteide/liteidex/src/plugins/terminal/terminalplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2022 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: terminalplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "terminalplugin.h" #include "terminal.h" #include "terminaloptionfactory.h" #include <QtPlugin> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end TerminalPlugin::TerminalPlugin() { } bool TerminalPlugin::load(LiteApi::IApplication *app) { new Terminal(app,this); app->optionManager()->addFactory(new TerminalOptionFactory(app,this)); return true; } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
1,771
C++
.cpp
47
35.808511
82
0.688953
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,462
terminaloption.cpp
visualfc_liteide/liteidex/src/plugins/terminal/terminaloption.cpp
#include "terminaloption.h" #include "ui_terminaloption.h" #include "terminal_global.h" #include <QFontDatabase> #include <QApplication> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end TerminalOption::TerminalOption(LiteApi::IApplication *app,QObject *parent) : LiteApi::IOption(parent), m_liteApp(app), m_widget(new QWidget), ui(new Ui::TermianlOption) { ui->setupUi(m_widget); } TerminalOption::~TerminalOption() { delete m_widget; delete ui; } QWidget *TerminalOption::widget() { return m_widget; } QString TerminalOption::name() const { return "Terminal"; } QString TerminalOption::mimeType() const { return OPTION_TERMIANL; } void TerminalOption::save() { m_fontFamily = ui->fontComboBox->currentText(); if (ui->sizeComboBox->count()) { const QString curSize = ui->sizeComboBox->currentText(); bool ok = true; int size = curSize.toInt(&ok); if (ok) { m_fontSize = size; } } int fontZoom = ui->fontZoomSpinBox->value(); if (fontZoom <= 10) { fontZoom = 10; } m_liteApp->settings()->setValue(TERMINAL_FAMILY,m_fontFamily); m_liteApp->settings()->setValue(TERMINAL_FONTSIZE,m_fontSize); m_liteApp->settings()->setValue(TERMINAL_FONTZOOM,fontZoom); bool antialias = ui->antialiasCheckBox->isChecked(); m_liteApp->settings()->setValue(TERMINAL_ANTIALIAS,antialias); } void TerminalOption::load() { m_fontFamily = m_liteApp->settings()->value(TERMINAL_FAMILY,TERMINAL_FAMILY_DEFAULT).toString(); m_fontSize = m_liteApp->settings()->value(TERMINAL_FONTSIZE,12).toInt(); int fontZoom = m_liteApp->settings()->value(TERMINAL_FONTZOOM,100).toInt(); bool antialias = m_liteApp->settings()->value(TERMINAL_ANTIALIAS,true).toBool(); ui->antialiasCheckBox->setChecked(antialias); if (!QFontDatabase().hasFamily(m_fontFamily)) { #if QT_VERSION >= 0x050200 m_fontFamily = QFontDatabase::systemFont(QFontDatabase::FixedFont).family(); #else m_fontFamily = QApplication::font().family(); #endif } ui->fontComboBox->setEditText(m_fontFamily); int index = ui->fontComboBox->findText(m_fontFamily); if (index >= 0) { ui->fontComboBox->setCurrentIndex(index); } updatePointSizes(); ui->fontZoomSpinBox->setValue(fontZoom); } void TerminalOption::updatePointSizes() { // Update point sizes const int oldSize = m_fontSize; if (ui->sizeComboBox->count()) { ui->sizeComboBox->clear(); } const QList<int> sizeLst = pointSizesForSelectedFont(); int idx = 0; int i = 0; for (; i < sizeLst.count(); ++i) { if (idx == 0 && sizeLst.at(i) >= oldSize) idx = i; ui->sizeComboBox->addItem(QString::number(sizeLst.at(i))); } if (ui->sizeComboBox->count()) ui->sizeComboBox->setCurrentIndex(idx); } QList<int> TerminalOption::pointSizesForSelectedFont() const { QFontDatabase db; const QString familyName = ui->fontComboBox->currentText(); QList<int> sizeLst = db.pointSizes(familyName); if (!sizeLst.isEmpty()) return sizeLst; QStringList styles = db.styles(familyName); if (!styles.isEmpty()) sizeLst = db.pointSizes(familyName, styles.first()); if (sizeLst.isEmpty()) sizeLst = QFontDatabase::standardSizes(); return sizeLst; }
3,617
C++
.cpp
114
27.192982
100
0.678049
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
21,463
litebuildoptionfactory.cpp
visualfc_liteide/liteidex/src/plugins/litebuild/litebuildoptionfactory.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: litebuildoptionfactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "litebuildoptionfactory.h" #include "litebuildoption.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end LiteBuildOptionFactory::LiteBuildOptionFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IOptionFactory(parent), m_liteApp(app) { } QStringList LiteBuildOptionFactory::mimeTypes() const { return QStringList() << "option/litebuild"; } LiteApi::IOption *LiteBuildOptionFactory::create(const QString &mimeType) { if (mimeType == "option/litebuild") { return new LiteBuildOption(m_liteApp,this); } return 0; }
1,900
C++
.cpp
49
36.469388
91
0.687432
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,464
litebuild.cpp
visualfc_liteide/liteidex/src/plugins/litebuild/litebuild.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: litebuild.cpp // Creator: visualfc <visualfc@gmail.com> #include "litebuild.h" #include "litebuild_global.h" #include "buildmanager.h" #include "liteapi/liteapi.h" #include "liteapi/liteutil.h" #include "liteapi/liteids.h" #include "golangdocapi/golangdocapi.h" #include "fileutil/fileutil.h" #include "processex/processex.h" #include "textoutput/textoutput.h" #include "buildconfigdialog.h" #include "litedebugapi/litedebugapi.h" #include "liteeditorapi/liteeditorapi.h" #include "qtc_texteditor/basetextdocumentlayout.h" #include "../liteeditor/liteeditor_global.h" #include <QToolBar> #include <QComboBox> #include <QAction> #include <QMenu> #include <QDir> #include <QFileInfo> #include <QTextBlock> #include <QTextCodec> #include <QProcessEnvironment> #include <QStandardItemModel> #include <QStandardItem> #include <QLabel> #include <QCheckBox> #include <QToolButton> #include <QTime> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end /* ### liteide app info LITEIDE_BIN_DIR LITEIDE_RES_DIR ### build dir info BUILD_DIR_PATH BUILD_DIR_NAME BUILD_DIR_BASENAME ### editor file info EDITOR_FILE_PATH EDITOR_FILE_NAME EDITOR_FILE_BASENAME EDITOR_FILE_SUFFIX ### editor dir info EDITOR_DIR_PATH EDITOR_DIR_NAME EDITOR_DIR_BASENAME */ enum { INPUT_ACTION = 0, INPUT_COMMAND = 1 }; enum { ID_CMD = 0, ID_ARGS = 1, ID_CODEC = 2, ID_MIMETYPE = 3, ID_TASKLIST = 4, ID_EDITOR = 5, ID_INPUTTYPE = 6, //action - 0, command - 1 ID_NAVIGATE = 7, ID_REGEXP = 8, ID_ACTIONID = 9, ID_TAKEALL = 10, ID_ACTIVATEOUTPUT_CHECK = 11 }; struct BuildBarInfo { BuildBarInfo() : build(0), buildMenu(0) { } ~BuildBarInfo() { if (buildMenu) { buildMenu->deleteLater(); } } LiteApi::IBuild *build; QMenu *buildMenu; QList<QAction*> toolbarActions; }; LiteBuild::LiteBuild(LiteApi::IApplication *app, QObject *parent) : LiteApi::ILiteBuild(parent), m_liteApp(app), m_buildManager(new BuildManager(this)), m_build(0), m_envManager(0) { m_bDynamicBuild = true; m_bLockBuildRoot = false; m_bFirstRunOutput = false; m_nullMenu = new QMenu; if (m_buildManager->initWithApp(m_liteApp)) { m_buildManager->load(m_liteApp->resourcePath()+"/litebuild"); m_liteApp->extension()->addObject("LiteApi.IBuildManager",m_buildManager); } m_bProjectBuild = false; m_buildToolBar = m_liteApp->actionManager()->insertToolBar(ID_TOOLBAR_BUILD,tr("Build Toolbar")); m_liteApp->actionManager()->insertViewMenu(LiteApi::ViewMenuToolBarPos,m_buildToolBar->toggleViewAction()); m_buildMenu = m_liteApp->actionManager()->loadMenu(ID_MENU_BUILD); //m_liteApp->actionManager()->insertViewMenu(LiteApi::ViewMenuToolBarPos,m_toolBar->toggleViewAction()); LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(this,"Build"); m_configAct = new QAction(QIcon("icon:litebuild/images/config.png"),tr("Build Configuration..."),this); actionContext->regAction(m_configAct,"Config",""); m_buildToolBar->addAction(m_configAct); m_buildToolBar->addSeparator(); m_checkBoxLockBuild = new QCheckBox; m_buildToolBar->addWidget(m_checkBoxLockBuild); m_buildToolBar->addSeparator(); m_process = new ProcessEx(this); m_debugEnvProcess = new ProcessEx(this); m_output = new TextOutput(m_liteApp); m_output->setFilterTermColor(true); m_output->setTerminalInput(true); m_stopAct = new QAction(tr("Stop Action"),this); m_stopAct->setIcon(QIcon("icon:litebuild/images/stopaction.png")); actionContext->regAction(m_stopAct,"Stop",""); m_clearAct = new QAction(tr("Clear Output"),this); m_clearAct->setIcon(QIcon("icon:images/cleanoutput.png")); actionContext->regAction(m_clearAct,"ClearOutput",""); m_fmctxExecuteFileAct = new QAction(tr("Execute File"),this); connect(m_fmctxExecuteFileAct,SIGNAL(triggered()),this,SLOT(fmctxExecuteFile())); m_fmctxDebugFileAct = new QAction(tr("Debug File"),this); connect(m_fmctxDebugFileAct,SIGNAL(triggered()),this,SLOT(fmctxDebugFile())); m_fmctxGoLockBuildAct = new QAction(tr("Lock Build Path"),this); m_fmctxGoBuildConfigAct = new QAction(tr("Build Path Configuration"),this); m_fmctxGoToolMenu = new QMenu("Go Tool"); m_fmctxNoGoToolMenu = new QMenu("Go Tool"); m_fmctxGoBuildAct = new QAction("Go Build",this); m_fmctxGoBuildAct->setData("build $(BUILDARGS)"); m_fmctxGoBuildAllAct = new QAction("Go Build All",this); m_fmctxGoBuildAllAct->setData("build $(BUILDARGS) ./..."); m_fmctxGoInstallAct = new QAction("Go Install",this); m_fmctxGoInstallAct->setData("install $(INSTALLARGS)"); m_fmctxGoInstallAllAct = new QAction("Go Install All",this); m_fmctxGoInstallAllAct->setData("install $(INSTALLARGS) ./..."); m_fmctxGoTestAct = new QAction("Go Test",this); m_fmctxGoTestAct->setData("test $(TESTARGS)"); m_fmctxGoTestAllAct = new QAction("Go Test All",this); m_fmctxGoTestAllAct->setData("test $(TESTARGS) ./..."); m_fmctxGoCleanAct = new QAction("Go Clean",this); m_fmctxGoCleanAct->setData("clean -i -x"); m_fmctxGoCleanAllAct = new QAction("Go Clean All",this); m_fmctxGoCleanAllAct->setData("clean -i -x ./..."); m_fmctxGoGetAct = new QAction("Go Get",this); m_fmctxGoGetAct->setData("get $(GETARGS)"); m_fmctxGoGetUpdateAct = new QAction("Go Get Update",this); m_fmctxGoGetUpdateAct->setData("get $(UPDATEGETARGS)"); m_fmctxGoGetForceAct = new QAction("Go Get Force",this); m_fmctxGoGetForceAct->setData("get $(GORCEGETARGS)"); m_fmctxGoVetAct = new QAction("Go Vet",this); m_fmctxGoVetAct->setData("vet $(VETARGS)"); m_fmctxGoVetAllCheckAct = new QAction("Go Vet (enable all checks)",this); m_fmctxGoVetAllCheckAct->setData("tool vet $(TOOLVETARGS) ."); m_fmctxGoFmtAct = new QAction("GoFmt",this); m_fmctxGodocAct = new QAction(tr("Use godoc View"),this); m_fmctxGoToolMenu->addAction(m_fmctxGoBuildAct); m_fmctxGoToolMenu->addAction(m_fmctxGoBuildAllAct); m_fmctxGoToolMenu->addSeparator(); m_fmctxGoToolMenu->addAction(m_fmctxGoInstallAct); m_fmctxGoToolMenu->addAction(m_fmctxGoInstallAllAct); m_fmctxGoToolMenu->addSeparator(); m_fmctxGoToolMenu->addAction(m_fmctxGoGetAct); m_fmctxGoToolMenu->addAction(m_fmctxGoGetUpdateAct); m_fmctxGoToolMenu->addAction(m_fmctxGoGetForceAct); m_fmctxGoToolMenu->addSeparator(); m_fmctxGoToolMenu->addAction(m_fmctxGoTestAct); m_fmctxGoToolMenu->addAction(m_fmctxGoTestAllAct); m_fmctxGoToolMenu->addSeparator(); m_fmctxGoToolMenu->addAction(m_fmctxGoCleanAct); m_fmctxGoToolMenu->addAction(m_fmctxGoCleanAllAct); m_fmctxGoToolMenu->addSeparator(); m_fmctxGoToolMenu->addAction(m_fmctxGoVetAct); m_fmctxGoToolMenu->addAction(m_fmctxGoVetAllCheckAct); m_fmctxGoToolMenu->addSeparator(); m_fmctxGoToolMenu->addAction(m_fmctxGoFmtAct); // m_fmctxNoGoToolMenu->addAction(m_fmctxGoBuildAllAct); m_fmctxNoGoToolMenu->addAction(m_fmctxGoInstallAllAct); m_fmctxNoGoToolMenu->addAction(m_fmctxGoTestAllAct); m_fmctxNoGoToolMenu->addAction(m_fmctxGoCleanAllAct); connect(m_fmctxGoLockBuildAct,SIGNAL(triggered()),this,SLOT(fmctxGoLockBuild())); connect(m_fmctxGoBuildConfigAct,SIGNAL(triggered()),this,SLOT(fmctxGoBuildConfigure())); connect(m_fmctxGoBuildAct,SIGNAL(triggered()),this,SLOT(fmctxGoTool())); connect(m_fmctxGoBuildAllAct,SIGNAL(triggered()),this,SLOT(fmctxGoTool())); connect(m_fmctxGoInstallAct,SIGNAL(triggered()),this,SLOT(fmctxGoTool())); connect(m_fmctxGoInstallAllAct,SIGNAL(triggered()),this,SLOT(fmctxGoTool())); connect(m_fmctxGoTestAct,SIGNAL(triggered()),this,SLOT(fmctxGoTool())); connect(m_fmctxGoTestAllAct,SIGNAL(triggered()),this,SLOT(fmctxGoTool())); connect(m_fmctxGoCleanAct,SIGNAL(triggered()),this,SLOT(fmctxGoTool())); connect(m_fmctxGoCleanAllAct,SIGNAL(triggered()),this,SLOT(fmctxGoTool())); connect(m_fmctxGoGetAct,SIGNAL(triggered()),this,SLOT(fmctxGoTool())); connect(m_fmctxGoGetUpdateAct,SIGNAL(triggered()),this,SLOT(fmctxGoTool())); connect(m_fmctxGoGetForceAct,SIGNAL(triggered()),this,SLOT(fmctxGoTool())); connect(m_fmctxGoVetAct,SIGNAL(triggered()),this,SLOT(fmctxGoTool())); connect(m_fmctxGoVetAllCheckAct,SIGNAL(triggered()),this,SLOT(fmctxGoTool())); connect(m_fmctxGoFmtAct,SIGNAL(triggered()),this,SLOT(fmctxGofmt())); connect(m_fmctxGodocAct,SIGNAL(triggered(bool)),this,SLOT(fmctxGodoc())); connect(m_stopAct,SIGNAL(triggered()),this,SLOT(stopAction())); connect(m_clearAct,SIGNAL(triggered()),m_output,SLOT(clear())); m_buildMenu->addAction(m_configAct); m_buildMenu->addSeparator(); m_buildMenu->addAction(m_stopAct); m_buildMenu->addAction(m_clearAct); m_buildMenu->addSeparator(); //m_liteApp->outputManager()->addOutuput(m_output,tr("Build Output")); m_outputLineWrapAct = new QAction(tr("Line Wrap"),this); m_outputLineWrapAct->setCheckable(true); connect(m_outputLineWrapAct,SIGNAL(toggled(bool)),this,SLOT(setOutputLineWrap(bool))); m_outputAutoClearAct = new QAction(tr("Auto Clear"),this); m_outputAutoClearAct->setCheckable(true); connect(m_outputAutoClearAct,SIGNAL(triggered(bool)),this,SLOT(setOutputAutoClear(bool))); m_outputAutoPosCursorAct = new QAction(tr("Automatic positioning cursor"),this); m_outputAutoPosCursorAct->setCheckable(true); connect(m_outputAutoPosCursorAct,SIGNAL(triggered(bool)),this,SLOT(setOutputAutoPosCursor(bool))); bool bLineWrap = m_liteApp->settings()->value(LITEBUILD_OUTPUTLINEWRAP,false).toBool(); m_bOutputAutoClear = m_liteApp->settings()->value(LITEBUILD_OUTPUTAUTOCLEAR,true).toBool(); bool bAutoPosCursor = m_liteApp->settings()->value(LITEBUILD_OUTPUTAUTOPOSCURSOR,true).toBool(); m_output->setLineWrap(bLineWrap); m_outputLineWrapAct->setChecked(bLineWrap); m_outputAutoClearAct->setChecked(m_bOutputAutoClear); m_outputAutoPosCursorAct->setChecked(bAutoPosCursor); m_output->setAutoPosCursor(bAutoPosCursor); m_outputMenu = new QMenu(tr("Setup")); m_outputMenu->setIcon(QIcon(":/images/setup.png")); m_outputMenu->addAction(m_outputAutoClearAct); m_outputMenu->addAction(m_outputLineWrapAct); m_outputMenu->addAction(m_outputAutoPosCursorAct); m_outputAct = m_liteApp->toolWindowManager()->addToolWindow(Qt::BottomDockWidgetArea, m_output,"BuildOutput", tr("Build Output"), false, QList<QAction*>() << m_stopAct << m_clearAct << m_outputMenu->menuAction()); connect(m_liteApp,SIGNAL(loaded()),this,SLOT(appLoaded())); connect(m_liteApp->optionManager(),SIGNAL(applyOption(QString)),this,SLOT(applyOption(QString))); //connect(m_liteApp->projectManager(),SIGNAL(currentProjectChanged(LiteApi::IProject*)),this,SLOT(currentProjectChanged(LiteApi::IProject*))); connect(m_liteApp->editorManager(),SIGNAL(editorCreated(LiteApi::IEditor*)),this,SLOT(editorCreated(LiteApi::IEditor*))); connect(m_liteApp->editorManager(),SIGNAL(currentEditorChanged(LiteApi::IEditor*)),this,SLOT(currentEditorChanged(LiteApi::IEditor*))); connect(m_process,SIGNAL(extOutput(QByteArray,bool)),this,SLOT(extOutput(QByteArray,bool))); connect(m_process,SIGNAL(extFinish(bool,int,QString)),this,SLOT(extFinish(bool,int,QString))); connect(m_debugEnvProcess,SIGNAL(extOutput(QByteArray,bool)),this,SLOT(debugEnvOutput(QByteArray,bool))); connect(m_output,SIGNAL(dbclickEvent(QTextCursor)),this,SLOT(dbclickBuildOutput(QTextCursor))); connect(m_output,SIGNAL(enterText(QString)),this,SLOT(enterTextBuildOutput(QString))); connect(m_output,SIGNAL(tabText(QString)),this,SLOT(enterTextBuildOutput(QString))); connect(m_output,SIGNAL(keyUpdown(int)),this,SLOT(keyUpdownBuildOutput(int))); connect(m_configAct,SIGNAL(triggered()),this,SLOT(config())); connect(m_liteApp->fileManager(),SIGNAL(aboutToShowFolderContextMenu(QMenu*,LiteApi::FILESYSTEM_CONTEXT_FLAG,QFileInfo,QString)),this,SLOT(aboutToShowFolderContextMenu(QMenu*,LiteApi::FILESYSTEM_CONTEXT_FLAG,QFileInfo,QString))); connect(m_checkBoxLockBuild,SIGNAL(toggled(bool)),this,SLOT(lockBuildRoot(bool))); m_liteAppInfo.insert("LITEIDE_ROOT_PATH",m_liteApp->rootPath()); m_liteAppInfo.insert("LITEIDE_APP_PATH",m_liteApp->applicationPath()); m_liteAppInfo.insert("LITEIDE_RES_PATH",m_liteApp->resourcePath()); m_liteAppInfo.insert("LITEIDE_PLUGIN_PATH",m_liteApp->pluginPath()); m_liteAppInfo.insert("LITEIDE_TOOL_PATH",m_liteApp->toolPath()); m_liteAppInfo.insert("LITEIDE_DEBUG_GCFLAGS","-gcflags=\"-N -l\""); m_liteApp->extension()->addObject("LiteApi.ILiteBuild",this); foreach(LiteApi::IBuild *build, m_buildManager->buildList()) { connect(build,SIGNAL(buildAction(LiteApi::IBuild*,LiteApi::BuildAction*)),this,SLOT(execBuildAction(LiteApi::IBuild*,LiteApi::BuildAction*))); QList<QAction*> actionList; foreach(QAction *act, build->actions()) { QMenu *subMenu = act->menu(); if (subMenu) { actionList.append(subMenu->actions()); } else { actionList.append(act); } } foreach(QAction *act, actionList) { QStringList shortcuts; foreach(QKeySequence key, act->shortcuts()) { shortcuts.append(key.toString()); } actionContext->regAction(act,act->objectName(),shortcuts.join(";")); } } m_envManager = LiteApi::getEnvManager(m_liteApp); if (m_envManager) { connect(m_envManager,SIGNAL(currentEnvChanged(LiteApi::IEnv*)),this,SLOT(currentEnvChanged(LiteApi::IEnv*))); } applyOption(OPTION_LITEEDITOR); } LiteBuild::~LiteBuild() { qDeleteAll(m_buildBarInfoMap); stopAction(); delete m_output; delete m_outputMenu; if (!m_nullMenu->parent()) { delete m_nullMenu; } delete m_fmctxGoToolMenu; delete m_fmctxNoGoToolMenu; } bool LiteBuild::execGoCommand(const QStringList &args, const QString &workDir, bool waitFinish) { m_process->stopAndWait(100,2000); m_process->setWorkingDirectory(workDir); QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); QString gocmd = FileUtil::lookupGoBin("go",m_liteApp,env,false); if (gocmd.isEmpty()) { return false; } this->execCommand(gocmd,args.join(" "),workDir); if (!waitFinish) { return true; } if (!m_process->waitForFinished(30000)) { m_process->kill(); return false; } return m_process->exitCode() == 0; } QString LiteBuild::envValue(LiteApi::IBuild *build, const QString &value) { QString buildFilePath; if (m_buildRootPath.isEmpty()) { LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (editor) { QString filePath = editor->filePath(); if (!filePath.isEmpty()) { buildFilePath = QFileInfo(filePath).path(); } } } else { buildFilePath = m_buildRootPath; } QMap<QString,QString> env = buildEnvMap(build,buildFilePath); QProcessEnvironment sysenv = LiteApi::getGoEnvironment(m_liteApp); return this->envToValue(value,env,sysenv); } QString LiteBuild::buildPathEnvValue(IBuild *build, const QString &buildFilePath, const QString &value) { if (!build) { return value; } QMap<QString,QString> env = buildEnvMap(build,buildFilePath); QProcessEnvironment sysenv = LiteApi::getGoEnvironment(m_liteApp); return this->envToValue(value,env,sysenv); } QString LiteBuild::envToValue(const QString &value,QMap<QString,QString> &liteEnv,const QProcessEnvironment &env) { QString v = value; QMapIterator<QString,QString> i(liteEnv); while(i.hasNext()) { i.next(); v.replace("$("+i.key()+")",i.value()); } QRegExp rx("\\$\\((\\w+)\\)"); int pos = 0; QStringList list; while ((pos = rx.indexIn(v, pos)) != -1) { list << rx.cap(1); pos += rx.matchedLength(); } foreach (QString str, list) { if (env.contains(str)) { v.replace("$("+str+")",env.value(str)); } } return v; } QString LiteBuild::buildTag() const { return m_buildRootPath; } LiteApi::IBuildManager *LiteBuild::buildManager() const { return m_buildManager; } void LiteBuild::appendOutput(const QString &str, const QBrush &brush, bool active, bool updateExistsTextColor) { if (updateExistsTextColor) { m_output->updateExistsTextColor(); } if (active) { m_outputAct->setChecked(true); } m_output->append(str,brush); } void LiteBuild::appLoaded() { } void LiteBuild::debugBefore() { } void LiteBuild::config() { if (!m_build) { return; } BuildConfigDialog dlg(m_liteApp); dlg.setBuild(m_build,m_buildRootPath, this->liteideEnvMap()); if (dlg.exec() == QDialog::Accepted) { updateBuildConfig(m_build); } } void LiteBuild::aboutToShowFolderContextMenu(QMenu *menu, LiteApi::FILESYSTEM_CONTEXT_FLAG flag, const QFileInfo &info,const QString &context) { m_fmctxInfo = info; if (flag == LiteApi::FILESYSTEM_FILES) { QString cmd = FileUtil::lookPathInDir(info.fileName(),info.path()); if (!cmd.isEmpty()) { QAction *act = 0; if (!menu->actions().isEmpty()) { act = menu->actions().at(0); } menu->insertAction(act,m_fmctxExecuteFileAct); bool hasGo = false; foreach(QFileInfo info, QDir(info.path()).entryInfoList(QDir::Files)) { if (info.suffix() == "go") { hasGo = true; break; } } if (hasGo) { menu->insertAction(act,m_fmctxDebugFileAct); } menu->insertSeparator(act); } } else if (flag == LiteApi::FILESYSTEM_FOLDER || flag == LiteApi::FILESYSTEM_ROOTFOLDER) { #ifdef Q_OS_MAC if (m_fmctxInfo.isBundle()) { return; } #endif bool hasGo = false; bool hasTest = false; foreach(QFileInfo info, QDir(info.filePath()).entryInfoList(QDir::Files)) { if (info.fileName().endsWith("_test.go")) { hasGo = true; hasTest = true; break; } if (info.suffix() == "go") { hasGo = true; } } if (hasGo) { QAction *act = 0; if (!menu->actions().isEmpty()) { act = menu->actions().at(0); } menu->insertAction(act,m_fmctxGoLockBuildAct); menu->insertAction(act,m_fmctxGoBuildConfigAct); menu->insertSeparator(act); //m_fmctxGoTestAct->setEnabled(hasTest); menu->insertMenu(act,m_fmctxGoToolMenu); LiteApi::IGolangDoc *doc = LiteApi::findExtensionObject<LiteApi::IGolangDoc*>(m_liteApp,"LiteApi.IGolangDoc"); if (doc) { menu->insertSeparator(act); menu->insertAction(act,m_fmctxGodocAct); } menu->insertSeparator(act); } else { QAction *act = 0; if (!menu->actions().isEmpty()) { act = menu->actions().at(0); } menu->insertSeparator(act); menu->insertMenu(act,m_fmctxNoGoToolMenu); } } } void LiteBuild::fmctxExecuteFile() { QString cmd = FileUtil::lookPathInDir(m_fmctxInfo.fileName(),m_fmctxInfo.path()); if (!cmd.isEmpty()) { this->stopAction(); this->execCommand(cmd,QString(),m_fmctxInfo.path(),true,true,false); } } void LiteBuild::fmctxDebugFile() { QString cmd = FileUtil::lookPathInDir(m_fmctxInfo.fileName(),m_fmctxInfo.path()); if (!cmd.isEmpty()) { LiteApi::ILiteDebug *debug = LiteApi::getLiteDebug(m_liteApp); if (debug) { debug->startDebug(m_fmctxInfo.fileName(),"",m_fmctxInfo.path()); } } } void LiteBuild::fmctxGoLockBuild() { QString buildPath = m_fmctxInfo.filePath(); this->lockBuildRootByMimeType(buildPath,"text/x-gosrc"); } void LiteBuild::fmctxGoBuildConfigure() { QString buildPath = m_fmctxInfo.filePath(); //this->lockBuildRootByMimeType(buildPath,"text/x-gosrc"); LiteApi::IBuild *build = m_buildManager->findBuild("text/x-gosrc"); if (!build) { m_liteApp->appendLog("LiteBuild","not found LiteApi::IBuild interface by mime type text/x-gosrc"); return; } BuildConfigDialog dlg(m_liteApp); dlg.setBuild(build,buildPath, this->liteideEnvMap()); dlg.exec(); } void LiteBuild::fmctxGoTool() { QAction *act = (QAction*)sender(); if (!act) { return; } LiteApi::IBuild *build = m_buildManager->findBuild("text/x-gosrc"); if (!build) { m_liteApp->appendLog("litebuild","not found LiteApi::IBuild interface by mime type text/x-gosrc",true); return; } QString args = act->data().toString(); QMap<QString,QString> env = buildEnvMap(build,m_fmctxInfo.filePath()); QProcessEnvironment sysenv = LiteApi::getGoEnvironment(m_liteApp); QString cmd = FileUtil::lookupGoBin("go",m_liteApp,sysenv,false); args = this->envToValue(args,env,sysenv); m_outputRegex = "(\\w?:?[\\w\\d_@\\-\\\\/\\.]+):(\\d+):"; m_process->setUserData(ID_REGEXP,m_outputRegex); if (!cmd.isEmpty()) { m_liteApp->editorManager()->saveAllEditors(); this->stopAction(); this->execCommand(cmd,args,m_fmctxInfo.filePath(),true,true,true,false); } } void LiteBuild::fmctxGofmt() { QString args = "gofmt -l -w ."; QString cmd = LiteApi::getGotools(m_liteApp); m_outputRegex = "(\\w?:?[\\w\\d_@\\-\\\\/\\.]+):(\\d+):"; m_process->setUserData(ID_REGEXP,m_outputRegex); if (!cmd.isEmpty()) { m_liteApp->editorManager()->saveAllEditors(); this->stopAction(); this->execCommand(cmd,args,m_fmctxInfo.filePath(),true,true,true,false); } } void LiteBuild::fmctxGodoc() { QString path = m_fmctxInfo.filePath(); LiteApi::IGolangDoc *doc = LiteApi::findExtensionObject<LiteApi::IGolangDoc*>(m_liteApp,"LiteApi.IGolangDoc"); if (doc) { QUrl url; url.setScheme("pdoc"); url.setPath(path); doc->openUrl(url); doc->activeBrowser(); } } void LiteBuild::applyOption(QString /*opt*/) { // if (opt == OPTION_LITEEDITOR) { // QFont font = m_output->font(); // font.setFamily(m_liteApp->settings()->value(EDITOR_FAMILY,font.family()).toString()); // m_output->setFont(font); // } } void LiteBuild::lockBuildRoot(bool b) { m_bLockBuildRoot = b; if (!b) { this->currentEditorChanged(m_liteApp->editorManager()->currentEditor()); } } void LiteBuild::setOutputLineWrap(bool b) { m_output->setLineWrap(b); m_liteApp->settings()->setValue(LITEBUILD_OUTPUTLINEWRAP,b); } void LiteBuild::setOutputAutoClear(bool b) { m_bOutputAutoClear = b; m_liteApp->settings()->setValue(LITEBUILD_OUTPUTAUTOCLEAR,b); } void LiteBuild::setOutputAutoPosCursor(bool b) { m_liteApp->settings()->setValue(LITEBUILD_OUTPUTAUTOPOSCURSOR,b); m_output->setAutoPosCursor(b); } bool LiteBuild::isLockBuildRoot() const { return m_bLockBuildRoot; } QString LiteBuild::currentBuildPath() const { return m_buildRootPath; } void LiteBuild::currentEnvChanged(LiteApi::IEnv*) { LiteApi::IEnv *ienv = m_envManager->currentEnv(); if (!ienv) { return; } QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); // if (!LiteApi::hasGoEnv(env)) { // return; // } m_liteApp->appendLog("LiteBuild","go environment changed"); m_process->setEnvironment(env.toStringList()); m_output->updateExistsTextColor(); m_output->appendTag(tr("Current environment change id \"%1\"").arg(ienv->id())+"\n"); m_debugEnvProcess->setEnvironment(env.toStringList()); if (!m_debugEnvProcess->isStop()) { m_debugEnvProcess->stop(100); } QString gotools = LiteApi::getGotools(m_liteApp); if (!gotools.isEmpty()) { m_debugEnvProcess->start(gotools,QStringList() << "debugflags"); } bool b = m_liteApp->settings()->value(LITEBUILD_ENVCHECK,true).toBool(); if (!b) { return; } QString go = FileUtil::lookupGoBin("go",m_liteApp,env,false); QString goroot = env.value("GOROOT"); QString goarch = env.value("GOARCH"); QString goos = env.value("GOOS"); if (!go.isEmpty()) { m_output->append("Found go bin at "+QDir::toNativeSeparators(go)); } else { m_output->append("Could not find go bin, (hint: is Go installed?)",Qt::red); } m_output->append("\nGOROOT="+goroot); m_output->append("\nGOARCH="+goarch); m_output->append("\nGOOS="+goos); m_output->append("\n"); // QString gobin = FileUtil::lookupGoBin("go",m_liteApp,true); // if (gobin.isEmpty()) { // m_output->updateExistsTextColor(); // m_output->appendTag(tr("Current environment change id \"%1\"").arg(ienv->id())+"\n"); // m_output->append("go bin not found!",Qt::red); // return; // } // if (m_process->isStop()) { // m_output->updateExistsTextColor(); // m_output->appendTag(tr("Current environment change id \"%1\"").arg(ienv->id())+"\n"); // this->execCommand(gobin,"env",LiteApi::getGOROOT(m_liteApp),false,false); // } } void LiteBuild::loadProjectInfo(const QString &filePath) { m_projectInfo.clear(); if (filePath.isEmpty()) { return; } QFileInfo info(filePath); /* PROJECT_NAME PROJECT_PATH PROJECT_DIR PROJECT_DIRNAME PROJECT_TARGETNAME PROJECT_TARGETATH */ if (info.isDir()) { m_projectInfo.insert("PROJECT_NAME",info.fileName()); m_projectInfo.insert("PROJECT_PATH",info.filePath()); m_projectInfo.insert("PROJECT_DIR",info.filePath()); m_projectInfo.insert("PROJECT_DIRNAME",info.fileName()); } else { m_projectInfo.insert("PROJECT_NAME",info.fileName()); m_projectInfo.insert("PROJECT_PATH",info.filePath()); m_projectInfo.insert("PROJECT_DIR",info.path()); m_projectInfo.insert("PROJECT_DIRNAME",QFileInfo(info.path()).fileName()); } } LiteApi::IBuild *LiteBuild::findProjectBuild(LiteApi::IProject *project) { if (!project) { return 0; } LiteApi::IBuild *build = m_buildManager->findBuild(project->mimeType()); return build; } void LiteBuild::reloadProject() { LiteApi::IProject *project = (LiteApi::IProject*)sender(); if (project) { loadProjectInfo(project->filePath()); m_targetInfo = project->targetInfo(); } } void LiteBuild::currentProjectChanged(LiteApi::IProject */*project*/) { return; // m_buildRootPath.clear(); // m_projectInfo.clear(); // m_targetInfo.clear(); // m_bProjectBuild = false; // if (project) { // connect(project,SIGNAL(reloaded()),this,SLOT(reloadProject())); // loadProjectInfo(project->filePath()); // m_targetInfo = project->targetInfo(); // m_buildRootPath = project->filePath(); // LiteApi::IBuild *build = findProjectBuild(project); // if (build) { // m_bProjectBuild = true; // setCurrentBuild(build); // } else { // currentEditorChanged(m_liteApp->editorManager()->currentEditor()); // } // } else { // LiteApi::IBuild *build = findProjectBuildByEditor(m_liteApp->editorManager()->currentEditor()); // if (build) { // m_bProjectBuild = true; // } // setCurrentBuild(build); // } } QMap<QString,QString> LiteBuild::liteideEnvMap() const { QMap<QString,QString> env = m_liteAppInfo; QMapIterator<QString,QString> p(m_projectInfo); while(p.hasNext()) { p.next(); env.insert(p.key(),p.value()); } QMapIterator<QString,QString> b(m_buildInfo); while(b.hasNext()) { b.next(); env.insert(b.key(),b.value()); } QMapIterator<QString,QString> e(m_editorInfo); while(e.hasNext()) { e.next(); env.insert(e.key(),e.value()); } QMapIterator<QString,QString> t(m_targetInfo); while(t.hasNext()) { t.next(); env.insert(t.key(),t.value()); } return env; } LiteApi::TargetInfo LiteBuild::getTargetInfo() { LiteApi::TargetInfo info; if (!m_build) { return info; } QList<BuildTarget*> lists = m_build->targetList(); if (!lists.isEmpty()) { BuildTarget *target = lists.first(); QMap<QString,QString> env = buildEnvMap(m_build,m_buildRootPath); QProcessEnvironment sysenv = LiteApi::getGoEnvironment(m_liteApp); info.buildRootPath = m_buildRootPath; info.targetName = this->envToValue(target->cmd(),env,sysenv); info.debugName = this->envToValue(target->debug(),env,sysenv); info.buildArgs = this->envToValue(target->buildArgs(),env,sysenv); info.targetArgs = this->envToValue(target->args(),env,sysenv); info.targetWorkDir = this->envToValue(target->work(),env,sysenv); } return info; } QMap<QString,QString> LiteBuild::buildEnvMap(LiteApi::IBuild *build, const QString &buildFilePath) const { QMap<QString,QString> env = liteideEnvMap(); if (!build) { return env; } QString customkey; if (!buildFilePath.isEmpty()) { customkey = "litebuild-custom/"+buildFilePath; } QString configkey = "litebuild-config/"+build->id(); foreach(LiteApi::BuildConfig *cf, build->configList()) { QString name = cf->name(); QString value = cf->value(); if (!configkey.isEmpty()) { value = m_liteApp->settings()->value(configkey+"#"+cf->id(),value).toString(); } QMapIterator<QString,QString> m(env); while(m.hasNext()) { m.next(); value.replace("$("+m.key()+")",m.value()); } env.insert(name,value); } foreach(LiteApi::BuildCustom *cf, build->customList()) { QString name = cf->name(); QString value = cf->value(); QString sharedValue = cf->sharedValue(); bool hasShared = cf->hasShared(); if (!customkey.isEmpty()) { value = m_liteApp->settings()->value(customkey+"#"+cf->id(),value).toString(); hasShared = m_liteApp->settings()->value(customkey+"#"+cf->id()+"#shared",hasShared).toBool(); } QMapIterator<QString,QString> m(env); while(m.hasNext()) { m.next(); value.replace("$("+m.key()+")",m.value()); if (hasShared) { sharedValue.replace("$("+m.key()+")",m.value()); } } if (cf->isEscaped()) { if (value.contains(" ")) { value = "\""+value+"\""; } } if (hasShared && !sharedValue.isEmpty()) { value += " "+sharedValue; } env.insert(name,value); } return env; } QMap<QString,QString> LiteBuild::buildEnvMap() const { return buildEnvMap(m_build,m_buildRootPath); /* LiteApi::IBuild *build = m_build; QString buildFilePath = m_buildFilePath; if (!build) { LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (editor && !editor->filePath().isEmpty()) { build = m_manager->findBuild(editor->mimeType()); buildFilePath = QFileInfo(editor->filePath()).path(); } } return buildEnvMap(build,buildFilePath); */ /* QMap<QString,QString> env = liteideEnvMap(); QMapIterator<QString,QString> i(m_configMap); while(i.hasNext()) { i.next(); QString k = i.key(); QString v = i.value(); QMapIterator<QString,QString> m(env); while(m.hasNext()) { m.next(); v.replace("$("+m.key()+")",m.value()); } env.insert(k,v); } QMapIterator<QString,QString> c(m_customMap); while(c.hasNext()) { c.next(); QString k = c.key(); QString v = c.value(); QMapIterator<QString,QString> m(env); while(m.hasNext()) { m.next(); v.replace("$("+m.key()+")",m.value()); } env.insert(k,v); } QMapIterator<QString,QString> p(m_projectInfo); while(p.hasNext()) { p.next(); env.insert(p.key(),p.value()); } QMapIterator<QString,QString> e(m_editorInfo); while(e.hasNext()) { e.next(); env.insert(e.key(),e.value()); } QMapIterator<QString,QString> t(m_targetInfo); while(t.hasNext()) { t.next(); env.insert(t.key(),t.value()); } return env; */ } void LiteBuild::updateBuildConfigHelp(LiteApi::IBuild *build, const QString &buildRootPath, QStandardItemModel *liteideModel, QStandardItemModel *configModel, QStandardItemModel *customModel, QStandardItemModel *actionModel) { liteideModel->removeRows(0,liteideModel->rowCount()); QMapIterator<QString,QString> i(this->liteideEnvMap()); while (i.hasNext()) { i.next(); liteideModel->appendRow(QList<QStandardItem*>() << new QStandardItem(i.key()) << new QStandardItem(i.value())); } if (build) { configModel->removeRows(0,configModel->rowCount()); customModel->removeRows(0,customModel->rowCount()); actionModel->removeRows(0,actionModel->rowCount()); QString customkey; if (!buildRootPath.isEmpty()) { customkey = "litebuild-custom/"+buildRootPath; } QString configkey = "litebuild-config/"+build->id(); foreach(LiteApi::BuildCustom *cf, build->customList()) { QString name = cf->name(); QString value = cf->value(); QString sharedValue = cf->sharedValue(); bool sharedChecked = cf->hasShared(); if (!customkey.isEmpty()) { value = m_liteApp->settings()->value(customkey+"#"+cf->id(),value).toString(); sharedChecked = m_liteApp->settings()->value(customkey+"#"+cf->id()+"#shared",true).toBool(); } QStandardItem *nameItem = new QStandardItem(name); QStandardItem *valueItem = new QStandardItem(value); if (cf->isReadOnly()) { valueItem->setEnabled(false); } QStandardItem *sharedItem = new QStandardItem(sharedValue); sharedItem->setEnabled(cf->hasShared()); if (cf->hasShared()) { sharedItem->setCheckable(true); sharedItem->setCheckState(sharedChecked ? Qt::Checked : Qt::Unchecked); } nameItem->setData(cf->id()); valueItem->setData(cf->value()); sharedItem->setData(cf->hasShared()); customModel->appendRow(QList<QStandardItem*>() << nameItem << valueItem << sharedItem ); } foreach(LiteApi::BuildConfig *cf, build->configList()) { QString name = cf->name(); QString value = cf->value(); if (!configkey.isEmpty()) { value = m_liteApp->settings()->value(configkey+"#"+cf->id(),value).toString(); } QStandardItem *item = new QStandardItem(name); item->setData(cf->id()); configModel->appendRow(QList<QStandardItem*>() << item << new QStandardItem(value)); } foreach (LiteApi::BuildAction *ba, build->actionList()) { QString id = ba->id(); QString cmd = ba->cmd(); QString args = ba->args(); QStandardItem *item = new QStandardItem(id); actionModel->appendRow(QList<QStandardItem*>() << item << new QStandardItem(cmd) << new QStandardItem(args)); } } } void LiteBuild::updateBuildConfig(IBuild */*build*/) { } void LiteBuild::setCurrentBuild(LiteApi::IBuild *build) { //update buildconfig if (build) { updateBuildConfig(build); } if (m_build == build) { return; } m_build = build; m_buildManager->setCurrentBuild(build); m_outputRegex.clear(); } /* BUILD_DIR_PATH BUILD_DIR_NAME BUILD_DIR_BASENAME EDITOR_FILE_PATH EDITOR_FILE_NAME EDITOR_FILE_BASENAME EDITOR_FILE_SUFFIX EDITOR_DIR_PATH EDITOR_DIR_NAME EDITOR_DIR_BASENAME */ void LiteBuild::loadEditorInfo(const QString &filePath) { m_editorInfo.clear(); if (filePath.isEmpty()) { return; } QFileInfo info(filePath); m_editorInfo.insert("EDITOR_FILE_PATH",info.filePath()); m_editorInfo.insert("EDITOR_FILE_NAME",info.fileName()); m_editorInfo.insert("EDITOR_FILE_BASENAME",info.baseName()); m_editorInfo.insert("EDITOR_FILE_SUFFIX",info.suffix()); m_editorInfo.insert("EDITOR_DIR_PATH",info.path()); m_editorInfo.insert("EDITOR_DIR_NAME",QFileInfo(info.path()).fileName()); m_editorInfo.insert("EDITOR_DIR_BASENAME",QFileInfo(info.path()).baseName()); } void LiteBuild::loadBuildPath(const QString &buildPath, const QString &buildName, const QString &buildInfo) { m_buildInfo.clear(); m_buildRootPath = buildPath; m_buildRootName = buildName; if (buildName.isEmpty()) { m_checkBoxLockBuild->setEnabled(false); m_checkBoxLockBuild->setText(""); m_checkBoxLockBuild->setToolTip(""); } else { m_checkBoxLockBuild->setEnabled(true); m_checkBoxLockBuild->setText(buildName); m_checkBoxLockBuild->setToolTip(QString("%1 : %2").arg(tr("Lock Build")).arg(buildInfo)); } emit buildPathChanged(buildPath); if (buildPath.isEmpty()) { return; } QFileInfo info(buildPath); m_buildInfo.insert("BUILD_DIR_PATH",info.filePath()); m_buildInfo.insert("BUILD_DIR_NAME",info.fileName()); m_buildInfo.insert("BUILD_DIR_BASENAME",info.baseName()); } void LiteBuild::loadTargetInfo(LiteApi::IBuild *build) { m_targetInfo.clear(); if (!build) { return; } QList<BuildTarget*> lists = build->targetList(); if (!lists.isEmpty()) { BuildTarget *target = lists.first(); QString cmd = this->envValue(build,target->cmd()); QString args = this->envValue(build,target->args()); QString work = this->envValue(build,target->work()); m_targetInfo.insert("TARGET_CMD",cmd); m_targetInfo.insert("TARGET_ARGS",args); m_targetInfo.insert("TARGET_WORK",work); } } LiteApi::IBuild *LiteBuild::findProjectBuildByEditor(IEditor *editor) { m_buildRootPath.clear(); m_projectInfo.clear(); m_targetInfo.clear(); if (!editor) { return 0; } QString filePath = editor->filePath(); if (filePath.isEmpty()) { return 0; } QString workDir = QFileInfo(filePath).path(); LiteApi::IBuild *build = m_buildManager->findBuild(editor->mimeType()); LiteApi::IBuild *projectBuild = 0; QString projectPath; if (build != 0) { foreach (LiteApi::BuildLookup *lookup,build->lookupList()) { QDir dir(workDir); for (int i = 0; i <= lookup->top(); i++) { QFileInfoList infos = dir.entryInfoList(QStringList() << lookup->file(),QDir::Files); if (infos.size() >= 1) { projectBuild = m_buildManager->findBuild(lookup->mimeType()); if (projectBuild != 0) { projectPath = infos.at(0).filePath(); m_buildRootPath = projectPath; break; } } dir.cdUp(); } } } if (!projectBuild) { return 0; } loadProjectInfo(projectPath); QMap<QString,QString> targetInfo; if (m_liteApp->fileManager()->findProjectTargetInfo(projectPath,targetInfo)) { m_targetInfo = targetInfo; } return projectBuild; } void LiteBuild::setDynamicBuild() { m_bDynamicBuild = true; } void LiteBuild::loadBuildType(const QString &mimeType) { LiteApi::IBuild *build = m_buildManager->findBuild(mimeType); updateBuildConfig(build); if (build == m_build) { return; } m_build = build; m_buildMimeType = mimeType; m_buildManager->setCurrentBuild(m_build); m_outputRegex.clear(); QMenu *menu = 0; BuildBarInfo *info = m_buildBarInfoMap.value(mimeType); if (info) { menu = info->buildMenu; } if (menu) { #if defined(Q_OS_OSX) // dirty trick to show the correct build menu at the first time on Mac OS X m_buildMenu->setEnabled(false); #endif m_buildMenu->menuAction()->setMenu(menu); } else { m_buildMenu->menuAction()->setMenu(m_nullMenu); } m_buildMenu->setEnabled(menu != 0); m_checkBoxLockBuild->setEnabled(m_build != 0); QMapIterator<QString,BuildBarInfo*> i(m_buildBarInfoMap); while(i.hasNext()) { i.next(); bool visible = (i.key() == mimeType); foreach (QAction *act, i.value()->toolbarActions) { act->setVisible(visible); } } } void LiteBuild::editorCreated(LiteApi::IEditor *editor) { if (!editor) { return; } IBuild *build = m_buildManager->findBuild(editor->mimeType()); if (!build) { return; } if (!m_buildBarInfoMap.contains(build->mimeType())) { BuildBarInfo *info = new BuildBarInfo; QList<QAction*> actions = build->actions(); QList<QAction*> acts; foreach (QAction *act, actions) { QMenu *subMenu = act->menu(); if (subMenu) { BuildAction *ba = build->findAction(subMenu->menuAction()->objectName()); if (ba) { QToolButton *btn = new QToolButton(m_buildToolBar); btn->setIcon(subMenu->menuAction()->icon()); btn->setText(subMenu->title()); btn->setMenu(subMenu); if (ba->isFolder()) { btn->setPopupMode(QToolButton::InstantPopup); } else { btn->setPopupMode(QToolButton::MenuButtonPopup); btn->setDefaultAction(subMenu->menuAction()); } QAction *cb = m_buildToolBar->addWidget(btn); acts.push_back(cb); } } else { QToolButton *btn = new QToolButton(m_buildToolBar); btn->setDefaultAction(act); QAction *cb = m_buildToolBar->addWidget(btn); acts.push_back(cb); } } QMenu *menu = new QMenu; menu->addAction(m_configAct); menu->addSeparator(); menu->addAction(m_stopAct); menu->addAction(m_clearAct); menu->addSeparator(); foreach (QAction *act, actions) { QMenu *subMenu = act->menu(); if (subMenu) { if (!menu->isEmpty()) menu->addSeparator(); menu->addActions(subMenu->actions()); } else { menu->addAction(act); } } info->build = build; info->toolbarActions = acts; info->buildMenu = menu; foreach (QAction *act, acts) { act->setVisible(false); } m_buildBarInfoMap.insert(build->mimeType(),info); } } void LiteBuild::lockBuildRootByMimeType(const QString &path, const QString &mimeType) { LiteApi::IBuild *build = m_buildManager->findBuild(mimeType); if (!build) { return; } if (build->lock() != "dir") { return; } m_bLockBuildRoot = true; m_checkBoxLockBuild->setChecked(true); QString buildPath; QString buildName; QString buildInfo; QFileInfo info(path); buildPath = info.filePath(); buildName = info.fileName(); buildInfo = QDir::toNativeSeparators(buildPath); loadBuildPath(buildPath,buildName,buildInfo); loadBuildType(mimeType); } void LiteBuild::currentEditorChanged(LiteApi::IEditor *editor) { //check lock build file if (m_bLockBuildRoot) { if (m_build && m_build->lock() == "file") { return; } } if (editor) { loadEditorInfo(editor->filePath()); } else { loadEditorInfo(""); } //check lock build dir if (m_bLockBuildRoot) { if (m_build && m_build->lock() == "dir") { return; } } QString mimeType; if (editor) { mimeType = editor->mimeType(); } QString buildPath; QString buildName; QString buildInfo; if (editor && !editor->filePath().isEmpty()) { LiteApi::IBuild *build = m_buildManager->findBuild(mimeType); if (build) { QFileInfo info(editor->filePath()); if (build->lock() == "dir") { buildPath = info.path(); buildName = QFileInfo(info.path()).fileName(); buildInfo = QDir::toNativeSeparators(buildPath); } else if (build->lock() == "file") { buildName = info.fileName(); buildPath = info.path(); buildInfo = QDir::toNativeSeparators(info.filePath()); } } else { QFileInfo info(editor->filePath()); buildPath = info.path(); } } loadBuildPath(buildPath,buildName,buildInfo); loadBuildType(mimeType); } void LiteBuild::extOutput(const QByteArray &data, bool bError) { if (data.isEmpty()) { return; } //m_liteApp->outputManager()->setCurrentOutput(m_output); if (m_bFirstRunOutput && m_process->userData(ID_ACTIVATEOUTPUT_CHECK).toBool()) { m_outputAct->setChecked(true); } m_bFirstRunOutput = false; QString codecName = m_process->userData(2).toString(); QTextCodec *codec = QTextCodec::codecForLocale(); if (!codecName.isEmpty()) { codec = QTextCodec::codecForName(codecName.toLatin1()); } QString msg = codec->toUnicode(data); m_output->append(msg); if (!m_process->userData(ID_NAVIGATE).toBool()) { return; } if (bError || m_process->userData(ID_TAKEALL).toBool() ) { QString regexp = m_process->userData(ID_REGEXP).toString(); if (regexp.isEmpty()) { return; } QRegExp re(regexp); foreach (QString info, msg.split("\n",qtSkipEmptyParts)) { if (re.indexIn(info) >= 0 && re.captureCount() >= 2) { QString fileName = re.cap(1); QString fileLine = re.cap(2); bool ok = false; int line = fileLine.toInt(&ok); if (ok) { QDir dir(m_workDir); QString filePath = dir.filePath(fileName); if (QFile::exists(filePath)) { fileName = filePath; } else { foreach(QFileInfo info,dir.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot)) { QString filePath = info.absoluteDir().filePath(fileName); if (QFile::exists(filePath)) { fileName = filePath; break; } } } LiteApi::IEditor *editor = m_liteApp->editorManager()->findEditor(fileName,true); if (editor) { LiteApi::ILiteEditor *liteEditor = LiteApi::getLiteEditor(editor); if (liteEditor) { QString str = m_process->userData(ID_ACTIONID).toString(); if (bError) { str += " Error"; liteEditor->setNavigateHead(LiteApi::EditorNavigateError,str); liteEditor->insertNavigateMark(line-1,LiteApi::EditorNavigateError,info, LITEBUILD_TAG); } else { str += " Export"; liteEditor->setNavigateHead(LiteApi::EditorNavigateWarning,str); liteEditor->insertNavigateMark(line-1,LiteApi::EditorNavigateWarning,info, LITEBUILD_TAG); } } } } } } } } void LiteBuild::extFinish(bool error,int exitCode, QString msg) { m_output->setReadOnly(true); if (m_process->userData(ID_ACTIVATEOUTPUT_CHECK).toBool()) { m_outputAct->setChecked(true); } bool isCommand = m_process->userData(ID_INPUTTYPE).toInt() == INPUT_COMMAND; if (!isCommand && exitCode != 0) { error = true; } if (error) { m_output->appendTag(tr("Error: %1.").arg(msg)+"\n",true); } else { if (isCommand) { m_output->appendTag(tr("Command exited with code %1.").arg(exitCode)+"\n"); } else { m_output->appendTag(tr("Success: %1.").arg(msg)+"\n"); } } if (!error) { QStringList task = m_process->userData(ID_TASKLIST).toStringList(); if (!task.isEmpty()) { QString id = task.takeFirst(); QString mime = m_process->userData(ID_MIMETYPE).toString(); m_process->setUserData(ID_TASKLIST,task); execAction(mime,id); } } else { m_process->setUserData(ID_TASKLIST,QStringList()); } } void LiteBuild::debugEnvOutput(const QByteArray &output, bool bError) { if (bError) { return; } QString flags = QString::fromUtf8(output).trimmed(); m_liteAppInfo.insert("LITEIDE_DEBUG_GCFLAGS",flags); } void LiteBuild::stopAction() { if (!m_process->isStop()) { #ifdef Q_OS_WIN m_process->stop(100); #else SendProcessCtrlC(m_process); if (!m_process->waitForFinished(200)) { m_process->stop(100); } #endif } } void LiteBuild::execCommand(const QString &cmd1, const QString &args, const QString &workDir, bool updateExistsTextColor, bool activateOutputCheck, bool navigate, bool command) { if (updateExistsTextColor) { m_output->updateExistsTextColor(); } if (activateOutputCheck) { m_outputAct->setChecked(activateOutputCheck); } if (!m_process->isStop()) { m_output->append(tr("A process is currently running. Stop the current action first.")+"\n",Qt::red); return; } //QProcessEnvironment sysenv = LiteApi::getGoEnvironment(m_liteApp); QProcessEnvironment sysenv = LiteApi::getCustomGoEnvironment(m_liteApp,workDir); QString cmd = cmd1.trimmed(); m_output->setReadOnly(false); m_process->setEnvironment(sysenv.toStringList()); m_process->setUserData(ID_CMD,cmd); m_process->setUserData(ID_ARGS,args); m_process->setUserData(ID_CODEC,"utf-8"); m_process->setUserData(ID_INPUTTYPE,command ? INPUT_COMMAND: INPUT_ACTION); m_process->setUserData(ID_NAVIGATE,navigate); m_process->setUserData(ID_ACTIVATEOUTPUT_CHECK,activateOutputCheck); QString shell = FileUtil::lookPathInDir(cmd,workDir); if (shell.isEmpty()) { shell = FileUtil::lookPath(cmd,sysenv,false); } if (!shell.isEmpty()) { cmd = shell; } m_workDir = workDir; m_process->setWorkingDirectory(workDir); m_output->appendTag(QString("%1 %2 [%3]\n") .arg(cmd).arg(args).arg(workDir)); m_bFirstRunOutput = true; m_process->startEx(cmd,args); } void LiteBuild::execBuildAction(LiteApi::IBuild* build,LiteApi::BuildAction* ba) { if (m_bOutputAutoClear) { m_output->clear(); } else { m_output->updateExistsTextColor(true); } m_outputAct->setChecked(true); if (!m_process->isStop()) { if (ba->isKillOld()) { m_output->append(tr("Killing current process...")+"\n"); #ifdef Q_OS_WIN m_process->stop(100); #else SendProcessCtrlC(m_process); if (!m_process->waitForFinished(200)) { m_process->stop(100); } #endif if (!m_process->isStop() && !m_process->waitForFinished(2000)) { m_output->append(tr("Failed to terminate the existing process!")+"\n",Qt::red); return; } } else { m_output->append(tr("A process is currently running. Stop the current action first.")+"\n",Qt::red); return; } } QString mime = build->mimeType(); QString id = ba->id(); QString editor; LiteApi::IEditor *ed = m_liteApp->editorManager()->currentEditor(); if (ed) { editor = ed->filePath(); } m_output->updateExistsTextColor(); m_process->setUserData(ID_MIMETYPE,mime); m_process->setUserData(ID_EDITOR,editor); m_process->setUserData(ID_ACTIVATEOUTPUT_CHECK,true); if (ba->task().isEmpty()) { execAction(mime,id); } else { QStringList task = ba->task(); QString id = task.takeFirst(); m_process->setUserData(ID_TASKLIST,task); execAction(mime,id); } } void LiteBuild::buildTask(IBuild *build, bool killOld, const QStringList &taskList) { if (m_bOutputAutoClear) { m_output->clear(); } else { m_output->updateExistsTextColor(true); } m_outputAct->setChecked(true); if (!m_process->isStop()) { if (!killOld) { return; } m_process->stopAndWait(100,2000); } QString mime = build->mimeType(); QString editor; LiteApi::IEditor *ed = m_liteApp->editorManager()->currentEditor(); if (ed) { editor = ed->filePath(); } m_output->updateExistsTextColor(); m_process->setUserData(ID_MIMETYPE,mime); m_process->setUserData(ID_EDITOR,editor); m_process->setUserData(ID_ACTIVATEOUTPUT_CHECK,true); QStringList task; foreach (QString id, taskList) { LiteApi::BuildAction *ba = build->findAction(id); if (!ba) { continue; } if (!ba->task().isEmpty()) { task.append(ba->task()); } else if (!ba->cmd().isEmpty()) { task.push_back(ba->id()); } } QString id = task.takeFirst(); m_process->setUserData(ID_TASKLIST,task); execAction(mime,id); } void LiteBuild::execAction(const QString &mime, const QString &id) { if (!m_process->isStop()) { return; } LiteApi::IBuild *build = m_buildManager->findBuild(mime); if (!build) { return; } LiteApi::BuildAction *ba = build->findAction(id); if (!ba) { return; } QString codec = ba->codec(); LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (ba->save() == "project") { if (editor && editor->isModified()) { m_liteApp->editorManager()->saveEditor(); } m_liteApp->projectManager()->saveProject(); } else if(ba->save() == "editor") { if (editor && editor->isModified()) { m_liteApp->editorManager()->saveEditor(); } } else if (ba->save() == "all") { m_liteApp->editorManager()->saveAllEditors(); } QString editorPath = m_process->userData(ID_EDITOR).toString(); QString buildFilePath; if (!editorPath.isEmpty() && !m_bLockBuildRoot) { buildFilePath = QFileInfo(editorPath).path(); } else { buildFilePath = m_buildRootPath; } QMap<QString,QString> env = buildEnvMap(build,buildFilePath); //QProcessEnvironment sysenv = LiteApi::getGoEnvironment(m_liteApp); QProcessEnvironment sysenv = LiteApi::getCustomGoEnvironment(m_liteApp,buildFilePath); QString cmd = this->envToValue(ba->cmd(),env,sysenv); QString args = this->envToValue(ba->args(),env,sysenv); m_workDir = this->envToValue(build->work(),env,sysenv); QString work = ba->work(); if (!work.isEmpty()) { m_workDir = this->envToValue(work,env,sysenv); } // if (!QFileInfo(cmd).exists()) { // QString findCmd = FileUtil::lookPathInDir(cmd,m_workDir); // if (!findCmd.isEmpty()) { // cmd = findCmd; // } // } QString shell; if (ba->cmd() == "$(GO)") { shell = FileUtil::lookupGoBin(cmd,m_liteApp,sysenv,false); } else { if (cmd.startsWith("\"") && cmd.endsWith("\"")) { cmd = cmd.mid(1,cmd.length()-2).trimmed(); } shell = FileUtil::lookPathInDir(cmd,m_workDir); } if (shell.isEmpty()) { shell = FileUtil::lookPath(cmd,sysenv,false); } if (!shell.isEmpty()) { cmd = shell; } // if (cmd.indexOf("$(") >= 0 || args.indexOf("$(") >= 0 || m_workDir.isEmpty()) { // m_output->appendTag(tr("> Could not parse action '%1'").arg(ba->id())+"\n"); // m_process->setUserData(ID_TASKLIST,QStringList()); // return; // } if (!ba->regex().isEmpty()) { m_outputRegex = this->envToValue(ba->regex(),env,sysenv); m_process->setUserData(ID_REGEXP,m_outputRegex); } else { m_process->setUserData(ID_REGEXP,""); } if (ba->isOutput() && ba->isReadline()) { m_output->setReadOnly(false); } else { m_output->setReadOnly(true); } // if (ba->func() == "debug") { // LiteApi::ILiteDebug *debug = LiteApi::getLiteDebug(m_liteApp); // if (debug) { // debug->startDebug(cmd,args,work); // } // return; // } m_process->setEnvironment(sysenv.toStringList()); m_process->setUserData(ID_NAVIGATE,ba->isNavigate()); m_process->setUserData(ID_ACTIONID,ba->id()); m_process->setUserData(ID_TAKEALL,ba->isTakeall()); if (ba->isNavigate()) { foreach(LiteApi::IEditor *editor, m_liteApp->editorManager()->editorList()) { LiteApi::ILiteEditor *liteEditor = LiteApi::getLiteEditor(editor); if (liteEditor) { liteEditor->clearAllNavigateMark(LiteApi::EditorNavigateBad); liteEditor->setNavigateHead(LiteApi::EditorNavigateNormal,"Normal"); } } } args = args.trimmed(); //run debug cmd if (ba->isDebug()) { LiteApi::ILiteDebug *debug = LiteApi::getLiteDebug(m_liteApp); if (debug) { debug->startDebug(cmd,args,m_workDir); } return; } if (!ba->isOutput()) { bool b = QProcess::startDetached(cmd,args.split(" "),m_workDir); m_output->appendTag(QString("%1 %2 [%3]\n") .arg(QDir::cleanPath(cmd)).arg(args).arg(m_workDir)); m_output->appendTag(b?tr("Started process successfully"):tr("Failed to start process")+"\n"); } else { m_process->setUserData(ID_CMD,cmd); m_process->setUserData(ID_ARGS,args); m_process->setUserData(ID_CODEC,codec); m_process->setUserData(ID_INPUTTYPE,INPUT_ACTION); m_process->setWorkingDirectory(m_workDir); m_output->appendTag(QString("%1 %2 [%3]\n") .arg(QDir::cleanPath(cmd)) .arg(args) .arg(m_workDir)); m_bFirstRunOutput = true; m_process->startEx(cmd,args); } } void LiteBuild::enterTextBuildOutput(QString text) { if (m_process->isStop()) { return; } QTextCodec *codec = QTextCodec::codecForLocale(); QString codecName = m_process->userData(2).toString(); if (!codecName.isEmpty()) { codec = QTextCodec::codecForName(codecName.toLatin1()); } if (codec) { m_process->write(codec->fromUnicode(text)); } else { m_process->write(text.toLatin1()); } } void LiteBuild::keyUpdownBuildOutput(int key) { if (m_process->isStop()) { return; } if (key == Qt::Key_Up) { char buf[] = {0x1b,0x5b,0x41}; m_process->write(buf,3); } else if (key == Qt::Key_Down) { char buf[] = {0x1b,0x5b,0x42}; m_process->write(buf,3); } } void LiteBuild::dbclickBuildOutput(const QTextCursor &cur) { if (m_outputRegex.isEmpty()) { //m_outputRegex = "([\\w\\d_\\\\/\\.]+):(\\d+):"; m_outputRegex = "(\\w?:?[\\w\\d_@\\-\\\\/\\.]+):(\\d+):"; } QRegExp rep(m_outputRegex);//"([\\w\\d:_\\\\/\\.]+):(\\d+)"); int index = rep.indexIn(cur.block().text()); if (index < 0) return; QStringList capList = rep.capturedTexts(); if (capList.count() < 3) return; QString fileName = capList[1]; QString fileLine = capList[2]; bool ok = false; int line = fileLine.toInt(&ok); if (!ok) return; QDir dir(m_workDir); QString filePath = dir.filePath(fileName); if (QFile::exists(filePath)) { fileName = filePath; } else { foreach(QFileInfo info,dir.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot)) { QString filePath = info.absoluteDir().filePath(fileName); if (QFile::exists(filePath)) { fileName = filePath; break; } } } if (LiteApi::gotoLine(m_liteApp,fileName,line-1,0,true,true)) { QTextCursor lineCur = cur; lineCur.select(QTextCursor::LineUnderCursor); m_output->setTextCursor(lineCur); } // return; // LiteApi::IEditor *editor = m_liteApp->fileManager()->openEditor(fileName); // if (editor) { // QTextCursor lineCur = cur; // lineCur.select(QTextCursor::LineUnderCursor); // m_output->setTextCursor(lineCur); // editor->widget()->setFocus(); // LiteApi::ITextEditor *textEditor = LiteApi::findExtensionObject<LiteApi::ITextEditor*>(editor,"LiteApi.ITextEditor"); // if (textEditor) { // textEditor->gotoLine(line-1,0,true); // } // } }
66,108
C++
.cpp
1,713
30.273789
234
0.601806
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,465
buildmanager.cpp
visualfc_liteide/liteidex/src/plugins/litebuild/buildmanager.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: buildmanager.cpp // Creator: visualfc <visualfc@gmail.com> #include "buildmanager.h" #include "build.h" #include <QDir> #include <QFileInfo> #include <QFile> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end BuildManager::BuildManager(QObject *parent) : LiteApi::IBuildManager(parent) { m_build = 0; } BuildManager::~BuildManager() { qDeleteAll(m_buildList); } void BuildManager::addBuild(IBuild *build) { m_buildList.append(build); } void BuildManager::removeBuild(IBuild *build) { m_buildList.removeAll(build); } IBuild *BuildManager::findBuild(const QString &mimeType) { foreach(IBuild *build, m_buildList) { if (build->mimeType() == mimeType) { return build; } } return 0; } QList<IBuild*> BuildManager::buildList() const { return m_buildList; } void BuildManager::setCurrentBuild(LiteApi::IBuild *build) { if (m_build == build) { return; } m_build = build; emit buildChanged(m_build); } IBuild *BuildManager::currentBuild() const { return m_build; } void BuildManager::load(const QString &path) { QDir dir = path; m_liteApp->appendLog("BuildManager","Loading "+path); dir.setFilter(QDir::Files | QDir::NoSymLinks); dir.setNameFilters(QStringList("*.xml")); foreach (QString fileName, dir.entryList()) { Build::loadBuild(this,QFileInfo(dir,fileName).absoluteFilePath()); } }
2,689
C++
.cpp
89
27.41573
82
0.677868
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,466
litebuildplugin.cpp
visualfc_liteide/liteidex/src/plugins/litebuild/litebuildplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: litebuildplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "litebuildplugin.h" #include "litebuild.h" #include "litebuildoptionfactory.h" #include "liteapi/liteids.h" #include <QHBoxLayout> #include <QLineEdit> #include <QComboBox> #include <QCompleter> #include <QLabel> #include <QPushButton> #include <QFileInfo> #include <QDir> #include <QTextStream> #include <QApplication> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end LiteBuildPlugin::LiteBuildPlugin() { } void LiteBuildPlugin::load_execute(const QString& path, QComboBox *combo) { QDir dir = path; m_liteApp->appendLog("Execute commands","Loading "+path); dir.setFilter(QDir::Files | QDir::NoSymLinks); dir.setNameFilters(QStringList("*.api")); foreach (QFileInfo info, dir.entryInfoList()) { QFile f(info.filePath()); if (f.open(QFile::ReadOnly)) { foreach (QByteArray line, f.readAll().split('\n')) { combo->addItem(QString(line.trimmed())); } } } } bool LiteBuildPlugin::load(LiteApi::IApplication *app) { m_liteApp = app; m_build = new LiteBuild(app,this); app->optionManager()->addFactory(new LiteBuildOptionFactory(app,this)); connect(m_build,SIGNAL(buildPathChanged(QString)),this,SLOT(buildPathChanged(QString))); //execute editor QLayout *layout=app->editorManager()->widget()->layout(); m_executeWidget = new QWidget; m_executeWidget->hide(); QHBoxLayout *hbox = new QHBoxLayout; hbox->setMargin(1); m_executeWidget->setLayout(hbox); m_commandCombo = new QComboBox; m_commandCombo->setEditable(true); m_commandCombo->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); QCompleter *c = m_commandCombo->completer(); if (c != 0) { c->setCaseSensitivity(Qt::CaseSensitive); } load_execute(m_liteApp->resourcePath()+"/litebuild/command",m_commandCombo); m_commandCombo->installEventFilter(this); m_workLabel = new ElidedLabel(""); m_workLabel->setElideMode(Qt::ElideMiddle); QPushButton *close = new QPushButton(); close->setIcon(QIcon("icon:images/close.png")); close->setIconSize(QSize(16,16)); close->setFlat(true); close->setToolTip(tr("Close")); connect(close,SIGNAL(clicked()),m_executeWidget,SLOT(hide())); hbox->addWidget(new QLabel(tr("Execute:"))); hbox->addWidget(m_commandCombo,1); hbox->addWidget(m_workLabel,1); hbox->addWidget(close); layout->addWidget(m_executeWidget); LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(m_build,"Build"); QAction *execAct = new QAction(tr("Execute File"),this); actionContext->regAction(execAct,"ExecuteFile","Ctrl+`"); m_liteApp->actionManager()->insertMenuActions(ID_MENU_TOOLS,"sep/exec",true,QList<QAction*>() << execAct); connect(execAct,SIGNAL(triggered()),this,SLOT(showExecute())); connect(m_commandCombo->lineEdit(),SIGNAL(returnPressed()),this,SLOT(execute())); connect(m_liteApp,SIGNAL(key_escape()),this,SLOT(closeRequest())); return true; } void LiteBuildPlugin::showExecute() { m_executeWidget->show(); m_commandCombo->lineEdit()->selectAll(); m_commandCombo->lineEdit()->setFocus(); // QString work = m_liteApp->applicationPath(); // LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); // LiteApi::ITextEditor *textEditor = LiteApi::getTextEditor(editor); // if (textEditor) { // work = QFileInfo(textEditor->filePath()).path(); // } // m_workLabel->setText(work); } void LiteBuildPlugin::execute() { QString text = m_commandCombo->lineEdit()->text().trimmed(); if (text.isEmpty()) { return; } m_commandCombo->lineEdit()->selectAll(); QString cmd = text; QString args; int find = text.indexOf(" "); if (find != -1) { cmd = text.left(find); args = text.right(text.length()-find-1); } QString work = m_build->currentBuildPath(); if (work.isEmpty()) { work = m_liteApp->applicationPath(); } // m_liteApp->applicationPath(); // LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); // LiteApi::ITextEditor *textEditor = LiteApi::getTextEditor(editor); // if (textEditor) { // work = QFileInfo(textEditor->filePath()).path(); // } m_build->execCommand(cmd.trimmed(),args.trimmed(),work); } void LiteBuildPlugin::buildPathChanged(const QString &buildPath) { m_workLabel->setText(buildPath); m_workLabel->setToolTip(buildPath); } void LiteBuildPlugin::closeRequest() { m_executeWidget->hide(); } bool LiteBuildPlugin::eventFilter(QObject *obj, QEvent *event) { if (obj == m_commandCombo) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event); if (keyEvent->key() == Qt::Key_Tab) { QLineEdit *edit = m_commandCombo->lineEdit(); if (edit->completer()->widget()->isVisible()) { edit->setText(edit->completer()->currentCompletion()); } return true; } } } return LiteApi::IPlugin::eventFilter(obj,event); } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
6,587
C++
.cpp
174
33.66092
110
0.669847
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,467
buildconfigdialog.cpp
visualfc_liteide/liteidex/src/plugins/litebuild/buildconfigdialog.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: buildconfigdialog.cpp // Creator: visualfc <visualfc@gmail.com> #include "buildconfigdialog.h" #include "ui_buildconfigdialog.h" #include "liteenvapi/liteenvapi.h" #include "liteapi/liteutil.h" #include <QAbstractItemModel> #include <QStandardItemModel> #include <QStandardItem> #include <QDebug> #include <QFileDialog> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end int BuildConfigDialog::s_lastViewIndex = 4; BuildConfigDialog::BuildConfigDialog(LiteApi::IApplication *app, QWidget *parent) : QDialog(parent), m_liteApp(app), ui(new Ui::BuildConfigDialog) { ui->setupUi(this); ui->liteideTableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->liteideTableView->resizeColumnsToContents(); ui->liteideTableView->verticalHeader()->hide(); ui->configTableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->configTableView->resizeColumnsToContents(); ui->configTableView->verticalHeader()->hide(); ui->customTableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->customTableView->resizeColumnsToContents(); ui->customTableView->verticalHeader()->hide(); ui->actionTableView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->actionTableView->resizeColumnsToContents(); ui->actionTableView->verticalHeader()->hide(); m_liteideModel = new QStandardItemModel(0,2,this); m_liteideModel->setHeaderData(0,Qt::Horizontal,tr("Name")); m_liteideModel->setHeaderData(1,Qt::Horizontal,tr("Value")); m_configModel = new QStandardItemModel(0,2,this); m_configModel->setHeaderData(0,Qt::Horizontal,tr("Name")); m_configModel->setHeaderData(1,Qt::Horizontal,tr("Value")); m_customModel = new QStandardItemModel(0,3,this); m_customModel->setHeaderData(0,Qt::Horizontal,tr("Name")); m_customModel->setHeaderData(1,Qt::Horizontal,tr("Value")); m_customModel->setHeaderData(2,Qt::Horizontal,tr("SharedValue")); m_actionModel = new QStandardItemModel(0,2,this); m_actionModel->setHeaderData(0,Qt::Horizontal,tr("Id")); m_actionModel->setHeaderData(1,Qt::Horizontal,tr("Cmd")); ui->liteideTableView->setModel(m_liteideModel); ui->configTableView->setModel(m_configModel); ui->customTableView->setModel(m_customModel); ui->actionTableView->setModel(m_actionModel); ui->actionTableView->setTextElideMode(Qt::ElideNone); connect(ui->customTableView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(editCustomeTabView(QModelIndex))); ui->tabWidget->setFocus(); ui->tabWidget->setCurrentIndex(s_lastViewIndex); ui->customTableView->setFocus(); connect(ui->buttonBox,SIGNAL(clicked(QAbstractButton*)),this,SLOT(buttonBoxClicked(QAbstractButton*))); } BuildConfigDialog::~BuildConfigDialog() { s_lastViewIndex = ui->tabWidget->currentIndex(); delete ui; } void BuildConfigDialog::editCustomeTabView(QModelIndex index) { if (!index.isValid()) { return; } if (index.column() == 1) { ui->customTableView->edit(index); } } void BuildConfigDialog::buttonBoxClicked(QAbstractButton *button) { QDialogButtonBox::ButtonRole role = ui->buttonBox->buttonRole(button); if (role == QDialogButtonBox::AcceptRole) { this->saveBuild(); } else if (role == QDialogButtonBox::RejectRole) { this->reject(); } else if (role == QDialogButtonBox::ApplyRole) { this->saveBuild(); this->updat_gopath_info(); } } void BuildConfigDialog::resizeTableView(QTableView *tableView) { QAbstractItemModel *model = tableView->model(); if (model && model->columnCount() >= 2) { tableView->resizeColumnToContents(0); #if QT_VERSION >= 0x050000 tableView->horizontalHeader()->setSectionResizeMode(0,QHeaderView::Interactive); for (int i = 1; i < model->columnCount(); i++) { tableView->horizontalHeader()->setSectionResizeMode(i,QHeaderView::Stretch); } #else tableView->horizontalHeader()->setResizeMode(0,QHeaderView::Interactive); for (int i = 1; i < model->columnCount(); i++) { tableView->horizontalHeader()->setResizeMode(i,QHeaderView::Stretch); } #endif } } void BuildConfigDialog::setBuild(LiteApi::IBuild *build, const QString &buildPath, const QMap<QString, QString> &liteEnvMap) { m_buildPath = buildPath; updateBuildConfigHelp(build,buildPath,liteEnvMap,m_liteideModel,m_configModel,m_customModel,m_actionModel); resizeTableView(ui->liteideTableView); resizeTableView(ui->configTableView); resizeTableView(ui->actionTableView); resizeTableView(ui->customTableView); #if QT_VERSION >= 0x050000 ui->customTableView->horizontalHeader()->setSectionResizeMode(2,QHeaderView::ResizeToContents); #else ui->customTableView->horizontalHeader()->setResizeMode(2,QHeaderView::ResizeToContents); #endif ui->buildIdLabel->setText(build->id()); ui->buildFileLabel->setText(buildPath); QString customKey = "litebuild-custom/"+buildPath; bool use_custom_gopath = m_liteApp->settings()->value(customKey+"#use_custom_gopath",false).toBool(); ui->useCustomGopathGroupBox->setChecked(use_custom_gopath); bool inherit_sys_gopath = m_liteApp->settings()->value(customKey+"#inherit_sys_gopath",true).toBool(); bool inherit_lite_gopath = m_liteApp->settings()->value(customKey+"#inherit_lite_gopath",true).toBool(); bool custom_gopath = m_liteApp->settings()->value(customKey+"#custom_gopath",false).toBool(); ui->inheritSysGopathCheckBox->setChecked(inherit_sys_gopath); ui->inheritLiteGopathCheckBox->setChecked(inherit_lite_gopath); ui->customGopathCheckBox->setChecked(custom_gopath); QProcessEnvironment env = LiteApi::getSysEnvironment(m_liteApp); #ifdef Q_OS_WIN QString sep = ";"; #else QString sep = ":"; #endif QStringList pathList; foreach (QString path, env.value("GOPATH").split(sep,qtSkipEmptyParts)) { pathList.append(QDir::toNativeSeparators(path)); } pathList.removeDuplicates(); ui->sysGopathLabel->setText(pathList.join("\n")); pathList.clear(); foreach (QString path, m_liteApp->settings()->value("liteide/gopath").toStringList()) { pathList.append(QDir::toNativeSeparators(path)); } pathList.removeDuplicates(); ui->liteGopathLabel->setText(pathList.join("\n")); pathList.clear(); foreach (QString path, m_liteApp->settings()->value(customKey+"#gopath").toStringList()) { pathList.append(QDir::toNativeSeparators(path)); } pathList.removeDuplicates(); ui->customGopathEdit->setPlainText(pathList.join("\n")); // QStringList saveAutoRun = m_liteApp->settings()->value(customKey+"#saveautorun").toStringList(); // ui->saveAutoRunEdit->setText(saveAutoRun.join(";")); updat_gopath_info(); } void BuildConfigDialog::saveBuild() { saveGopath(); saveCustom(); saveAction(); } void BuildConfigDialog::saveGopath() { if (m_buildPath.isEmpty()) { return; } QString customKey = "litebuild-custom/"+m_buildPath; bool use_custom_gopath = ui->useCustomGopathGroupBox->isChecked(); bool inherit_sys_gopath = ui->inheritSysGopathCheckBox->isChecked(); bool inherit_lite_gopath = ui->inheritLiteGopathCheckBox->isChecked(); bool custom_gopath = ui->customGopathCheckBox->isChecked(); // m_liteApp->settings()->setValue(customKey+"#use_custom_gopath",use_custom_gopath); // m_liteApp->settings()->setValue(customKey+"#inherit_sys_gopath",inherit_sys_gopath); // m_liteApp->settings()->setValue(customKey+"#inherit_lite_gopath",inherit_lite_gopath); // m_liteApp->settings()->setValue(customKey+"#custom_gopath",custom_gopath); // m_liteApp->settings()->setValue(customKey+"#gopath",ui->customGopathEdit->toPlainText().split("\n")); LiteApi::updateAppSetting(m_liteApp,customKey+"#use_custom_gopath",use_custom_gopath,false); LiteApi::updateAppSetting(m_liteApp,customKey+"#inherit_sys_gopath",inherit_sys_gopath,true); LiteApi::updateAppSetting(m_liteApp,customKey+"#inherit_lite_gopath",inherit_lite_gopath,true); LiteApi::updateAppSetting(m_liteApp,customKey+"#custom_gopath",custom_gopath,false); LiteApi::updateAppSetting(m_liteApp,customKey+"#gopath",ui->customGopathEdit->toPlainText().split("\n"),""); LiteApi::IGoEnvManger *goEnv = LiteApi::getGoEnvManager(m_liteApp); if (goEnv) { goEnv->updateCustomGOPATH(m_buildPath); } } void BuildConfigDialog::saveCustom() { if (m_buildPath.isEmpty()) { return; } QString key; key = "litebuild-custom/"+m_buildPath; for (int i = 0; i < m_customModel->rowCount(); i++) { QStandardItem *name = m_customModel->item(i,0); QStandardItem *value = m_customModel->item(i,1); QStandardItem *sharedValue = m_customModel->item(i,2); QString id = name->data().toString(); if (!key.isEmpty()) { QString defValue = value->data().toString(); bool defShared = sharedValue->data().toBool(); LiteApi::updateAppSetting(m_liteApp,key+"#"+id,value->text(),defValue); LiteApi::updateAppSetting(m_liteApp,key+"#"+id+"#shared",sharedValue->checkState() == Qt::Checked ? true:false,defShared); } } } void BuildConfigDialog::saveAction() { // if (m_buildPath.isEmpty()) { // return; // } // QString key; // key = "litebuild-custom/"+m_buildPath; // QStringList task; // foreach (QString id, ui->saveAutoRunEdit->text().split(";")) { // id = id.trimmed(); // if (!id.isEmpty()) { // task.push_back(id); // } // } // LiteApi::updateAppSetting(m_liteApp,key+"#saveautorun",task,QStringList()); } void BuildConfigDialog::on_customGopathBrowserButton_clicked() { static QString last = QDir::homePath(); QString dir = QFileDialog::getExistingDirectory(this, tr("Choose directory to add to GOPATH:"), last, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if (!dir.isEmpty()) { last = dir; ui->customGopathEdit->appendPlainText(dir); } } void BuildConfigDialog::on_customGopathClear_clicked() { ui->customGopathEdit->clear(); } void BuildConfigDialog::on_customResetAllButton_clicked() { QStandardItemModel *model = (QStandardItemModel*)(ui->customTableView->model()); for (int i = 0; i < model->rowCount(); i++) { // QStandardItem *name = model->item(i,0); QStandardItem *value = model->item(i,1); QStandardItem *sharedValue = model->item(i,2); value->setText(value->data().toString()); if (sharedValue->data().toBool()) { sharedValue->setCheckState(Qt::Checked); } } } void BuildConfigDialog::updat_gopath_info() { #ifdef Q_OS_WIN QString sep = ";"; #else QString sep = ":"; #endif QString customPath; QProcessEnvironment env = LiteApi::getCustomGoEnvironment(m_liteApp,m_buildPath,&customPath); QString infoHead; if (!customPath.isEmpty()) { infoHead = QString("Use custom GOPATH for build path <b>%1</b>").arg(QDir::toNativeSeparators(customPath)); } else { infoHead = "Use LiteIDE Global GOPATH"; } QStringList gopathList = env.value("GOPATH").split(sep); ui->gopathInfoHeadLabel->setText(infoHead); ui->gopathInfoLabel->setText(gopathList.join("\n")); } void BuildConfigDialog::updateBuildConfigHelp(LiteApi::IBuild *build, const QString &buildRootPath, const QMap<QString,QString> &liteEnvMap, QStandardItemModel *liteideModel, QStandardItemModel *configModel, QStandardItemModel *customModel, QStandardItemModel *actionModel) { liteideModel->removeRows(0,liteideModel->rowCount()); QMapIterator<QString,QString> i(liteEnvMap); while (i.hasNext()) { i.next(); liteideModel->appendRow(QList<QStandardItem*>() << new QStandardItem(i.key()) << new QStandardItem(i.value())); } if (build) { configModel->removeRows(0,configModel->rowCount()); customModel->removeRows(0,customModel->rowCount()); actionModel->removeRows(0,actionModel->rowCount()); QString customkey; if (!buildRootPath.isEmpty()) { customkey = "litebuild-custom/"+buildRootPath; } QString configkey = "litebuild-config/"+build->id(); foreach(LiteApi::BuildCustom *cf, build->customList()) { QString name = cf->name(); QString value = cf->value(); QString sharedValue = cf->sharedValue(); bool sharedChecked = cf->hasShared(); if (!customkey.isEmpty()) { value = m_liteApp->settings()->value(customkey+"#"+cf->id(),value).toString(); sharedChecked = m_liteApp->settings()->value(customkey+"#"+cf->id()+"#shared",true).toBool(); } QStandardItem *nameItem = new QStandardItem(name); QStandardItem *valueItem = new QStandardItem(value); if (cf->isReadOnly()) { valueItem->setEnabled(false); } QStandardItem *sharedItem = new QStandardItem(sharedValue); sharedItem->setEnabled(cf->hasShared()); if (cf->hasShared()) { sharedItem->setCheckable(true); sharedItem->setCheckState(sharedChecked ? Qt::Checked : Qt::Unchecked); } nameItem->setData(cf->id()); valueItem->setData(cf->value()); sharedItem->setData(cf->hasShared()); customModel->appendRow(QList<QStandardItem*>() << nameItem << valueItem << sharedItem ); } foreach(LiteApi::BuildConfig *cf, build->configList()) { QString name = cf->name(); QString value = cf->value(); if (!configkey.isEmpty()) { value = m_liteApp->settings()->value(configkey+"#"+cf->id(),value).toString(); } QStandardItem *item = new QStandardItem(name); item->setData(cf->id()); configModel->appendRow(QList<QStandardItem*>() << item << new QStandardItem(value)); } foreach (LiteApi::BuildAction *ba, build->actionList()) { QString id = ba->id(); QString cmd = ba->cmd(); QString args = ba->args(); QStringList task = ba->task(); if (task.isEmpty() && cmd.isEmpty()) { continue; } QStandardItem *item = new QStandardItem(id); QString value; if (!task.isEmpty()) { value = task.join(";"); } else { value = cmd+" "+args; } actionModel->appendRow(QList<QStandardItem*>() << item << new QStandardItem(value) ); } } }
16,522
C++
.cpp
374
37.280749
273
0.656023
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,468
build.cpp
visualfc_liteide/liteidex/src/plugins/litebuild/build.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: build.cpp // Creator: visualfc <visualfc@gmail.com> #include "build.h" #include "fileutil/fileutil.h" #include <QFile> #include <QXmlStreamReader> #include <QFileInfo> #include <QDir> #include <QMenu> #include <QAction> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end Build::Build(QObject *parent) : LiteApi::IBuild(parent) { } Build::~Build() { qDeleteAll(m_lookupList); qDeleteAll(m_actionList); qDeleteAll(m_configList); qDeleteAll(m_customList); qDeleteAll(m_targetList); qDeleteAll(m_idMenuMap); } QString Build::mimeType() const { return m_mimeType; } QString Build::id() const { return m_id; } QString Build::work() const { return m_work; } QString Build::lock() const { return m_lock; } QList<BuildAction*> Build::actionList() const { return m_actionList; } QList<BuildLookup*> Build::lookupList() const { return m_lookupList; } QList<BuildConfig*> Build::configList() const { return m_configList; } QList<BuildCustom*> Build::customList() const { return m_customList; } QList<BuildTarget*> Build::targetList() const { return m_targetList; } BuildAction *Build::findAction(const QString &id) { foreach(BuildAction *act, m_actionList) { if (act->id() == id) { return act; } } return 0; } QList<QAction*> Build::actions() { if (m_actions.isEmpty()) { this->make(); } return m_actions; } void Build::make() { foreach(LiteApi::BuildAction *ba, m_actionList) { QString id = ba->menu(); if (!id.isEmpty()) { QMenu *menu = m_idMenuMap[id]; if (!menu) { menu = new QMenu; m_idMenuMap.insert(id,menu); } } } foreach(LiteApi::BuildAction *ba,m_actionList) { if (ba->isHidden()) { continue; } QAction *act = this->makeAction(ba); QString idMenu = ba->menu(); if (idMenu.isEmpty()) { QMenu *menu = m_idMenuMap[ba->id()]; if (menu) { QAction *menuAction = menu->menuAction(); menuAction->setObjectName(act->objectName()); menuAction->setText(act->text()); //menuAction->setToolTip(act->toolTip()); menuAction->setIcon(act->icon()); if (!ba->isFolder()) { connect(menuAction,SIGNAL(triggered()),this,SLOT(slotBuildAction())); menu->addAction(act); } m_actions.append(menuAction); } else { m_actions.append(act); } } else { QMenu *menu = m_idMenuMap[idMenu]; if (menu) { menu->addAction(act); } else { m_actions.append(act); } } } } QAction *Build::makeAction(BuildAction *ba) { QAction *act = new QAction(ba->id(),this); act->setObjectName(ba->id()); if (ba->isSeparator()) { act->setSeparator(true); } else { if (!ba->key().isEmpty()) { QList<QKeySequence> list; foreach(QString key, ba->key().split(";")) { list.append(QKeySequence(key)); } act->setShortcuts(list); act->setToolTip(QString("%1 (%2)").arg(ba->id()).arg(ba->key())); } if (!ba->img().isEmpty()) { QIcon icon(ba->img()); if (!icon.isNull()) { act->setIcon(icon); } } if (!ba->isFolder()) { connect(act,SIGNAL(triggered()),this,SLOT(slotBuildAction())); } } return act; } void Build::slotBuildAction() { QAction *act = (QAction*)sender(); if (act) { BuildAction *ba = this->findAction(act->objectName()); if (ba) { emit buildAction(this,ba); } } } void Build::setType(const QString &mimeType) { m_mimeType = mimeType; } void Build::setId(const QString &id) { m_id = id; } void Build::setWork(const QString &work) { m_work = work; } void Build::setLock(const QString &lock) { m_lock = lock; } static QString action_os_name() { #ifdef Q_OS_MAC return "macosx"; #endif #ifdef Q_OS_WIN return "windows"; #endif #ifdef Q_OS_LINUX return "linux"; #endif #ifdef Q_OS_FREEBSD return "freebsd"; #endif #ifdef Q_OS_OPENBD return "openbsd"; #endif return "unknown-os"; } void Build::appendAction(BuildAction *act) { for (int i = 0; i < m_actionList.size(); i++) { BuildAction *ba = m_actionList[i]; if (ba->id() == act->id()) { if (act->os().contains(action_os_name(),Qt::CaseInsensitive)) { m_actionList[i] = act; delete ba; } else { delete act; } return; } } m_actionList.append(act); } void Build::appendLookup(BuildLookup *lookup) { m_lookupList.append(lookup); } void Build::appendConfig(BuildConfig *config) { m_configList.append(config); } void Build::appendCustom(BuildCustom *custom) { m_customList.append(custom); } void Build::appendDebug(BuildTarget *debug) { m_targetList.append(debug); } bool Build::loadBuild(LiteApi::IBuildManager *manager, const QString &fileName) { QFile file(fileName); if (!file.open(QIODevice::ReadOnly|QIODevice::Text)) { return false; } return Build::loadBuild(manager,&file,fileName); } static int build_ver = 2; bool Build::loadBuild(LiteApi::IBuildManager *manager, QIODevice *dev, const QString &fileName) { QXmlStreamReader reader(dev); QXmlStreamAttributes attrs; QDir dir = QFileInfo(fileName).absoluteDir(); Build *build = 0; BuildAction *act = 0; BuildLookup *lookup = 0; BuildConfig *config = 0; BuildCustom *custom = 0; BuildTarget *target = 0; while (!reader.atEnd()) { switch (reader.readNext()) { case QXmlStreamReader::StartElement: attrs = reader.attributes(); if (reader.name() == "mime-type" && build == 0) { int ver = attrs.value("ver").toString().toInt(); if (ver >= build_ver) { build = new Build; build->setType(attrs.value("type").toString()); build->setId(attrs.value("id").toString()); build->setWork(attrs.value("work").toString()); build->setLock(attrs.value("lock").toString()); } } else if (reader.name() == "lookup" && lookup == 0 && build != 0) { lookup = new BuildLookup; lookup->setMimeType(attrs.value("mime-type").toString()); lookup->setFile(attrs.value("file").toString()); lookup->setTop(attrs.value("top").toString()); } else if (reader.name() == "action" && act == 0 && build != 0) { act = new BuildAction; act->setId(attrs.value("id").toString()); act->setOs(attrs.value("os").toString()); act->setMenu(attrs.value("menu").toString()); act->setKey(attrs.value("key").toString()); act->setCmd(attrs.value("cmd").toString()); act->setDebug(attrs.value("debug").toString()); act->setFunc(attrs.value("func").toString()); act->setArgs(attrs.value("args").toString()); act->setSave(attrs.value("save").toString()); act->setOutput(attrs.value("output").toString()); act->setReadline(attrs.value("readline").toString()); act->setCodec(attrs.value("codec").toString()); act->setRegex(attrs.value("regex").toString()); act->setWork(attrs.value("work").toString()); act->setKillold(attrs.value("killold").toString()); act->setSeparator(attrs.value("separator").toString()); act->setNavigate(attrs.value("navigate").toString()); act->setFolder(attrs.value("folder").toString()); act->setTakeall(attrs.value("takeall").toString()); QString img = attrs.value("img").toString(); if (!img.isEmpty()) { if (!img.contains(":")) { img = "icon:/litebuild/images/"+img;//QFileInfo(dir,img).canonicalFilePath(); } act->setImg(img); } QString task = attrs.value("task").toString(); if (!task.isEmpty()) { act->setTask(task.split(";",qtSkipEmptyParts)); } } else if (reader.name() == "config" && config == 0 && build != 0) { config = new BuildConfig; config->setId(attrs.value("id").toString()); config->setName(attrs.value("name").toString()); config->setValue(attrs.value("value").toString()); } else if (reader.name() == "custom" && custom == 0 && build != 0) { custom = new BuildCustom; custom->setId(attrs.value("id").toString()); custom->setName(attrs.value("name").toString()); custom->setValue(attrs.value("value").toString()); if (attrs.hasAttribute("shared-value")) { custom->setSharedValue(attrs.value("shared-value").toString()); } if (attrs.hasAttribute("readonly")) { custom->setReadOnly(attrs.value("readonly").toString()); } if (attrs.hasAttribute("escaped")) { custom->setEscaped(attrs.value("escaped").toString()); } } else if (reader.name() == "target" && target == 0 && build != 0) { target = new BuildTarget; target->setId(attrs.value("id").toString()); target->setCmd(attrs.value("cmd").toString()); target->setDebug(attrs.value("debug").toString()); target->setArgs(attrs.value("args").toString()); target->setWork(attrs.value("work").toString()); target->setBuildArgs(attrs.value("buildargs").toString()); } break; case QXmlStreamReader::EndElement: if (reader.name() == "mime-type") { if (build) { manager->addBuild(build); } build = 0; } else if (reader.name() == "action") { if (build && act) { build->appendAction(act); } act = 0; } else if (reader.name() == "lookup") { if (build && lookup) { build->appendLookup(lookup); } lookup = 0; } else if (reader.name() == "config") { if (build && config) { build->appendConfig(config); } config = 0; } else if (reader.name() == "custom") { if (build && custom) { build->appendCustom(custom); } custom = 0; } else if (reader.name() == "target") { if (build && target) { build->appendDebug(target); } target = 0; } break; default: break; } } return true; }
12,883
C++
.cpp
391
24.283887
101
0.54077
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
21,469
litebuildoption.cpp
visualfc_liteide/liteidex/src/plugins/litebuild/litebuildoption.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: litebuildoption.cpp // Creator: visualfc <visualfc@gmail.com> #include "litebuildoption.h" #include "litebuild_global.h" #include "ui_litebuildoption.h" #include <QFileSystemModel> #include <QFileInfo> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end LiteBuildOption::LiteBuildOption(LiteApi::IApplication *app,QObject *parent) : LiteApi::IOption(parent), m_liteApp(app), m_widget(new QWidget), ui(new Ui::LiteBuildOption) { ui->setupUi(m_widget); m_fileModel = new QFileSystemModel(this); QString path = m_liteApp->resourcePath()+"/litebuild"; QModelIndex root = m_fileModel->setRootPath(path); ui->fileTreeView->setEditTriggers(0); ui->fileTreeView->setModel(m_fileModel); ui->fileTreeView->setRootIndex(root); #if QT_VERSION >= 0x050000 ui->fileTreeView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); #else ui->fileTreeView->header()->setResizeMode(QHeaderView::ResizeToContents); #endif connect(ui->fileTreeView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(doubleClickedFile(QModelIndex))); } LiteBuildOption::~LiteBuildOption() { delete ui; delete m_widget; } QWidget *LiteBuildOption::widget() { return m_widget; } QString LiteBuildOption::name() const { return "LiteBuild"; } QString LiteBuildOption::mimeType() const { return "option/litebuild"; } void LiteBuildOption::load() { bool b = m_liteApp->settings()->value(LITEBUILD_ENVCHECK,true).toBool(); ui->goenvCheckBox->setChecked(b); } void LiteBuildOption::save() { bool b = ui->goenvCheckBox->isChecked(); m_liteApp->settings()->setValue(LITEBUILD_ENVCHECK,b); } void LiteBuildOption::doubleClickedFile(QModelIndex index) { if (!index.isValid()) { return; } QFileInfo info = m_fileModel->fileInfo(index); if (!info.isFile()) { return; } if (info.suffix() == "png") { return; } m_liteApp->fileManager()->openEditor(info.filePath()); }
3,246
C++
.cpp
98
30.265306
107
0.695126
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,470
golangfmt.cpp
visualfc_liteide/liteidex/src/plugins/golangfmt/golangfmt.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangfmt.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangfmt.h" #include "golangfmt_global.h" #include "fileutil/fileutil.h" #include "processex/processex.h" #include "litebuildapi/litebuildapi.h" #include "liteeditorapi/liteeditorapi.h" #include "qtc_texteditor/basetextdocumentlayout.h" #include <QDebug> #include <QProcess> #include <QFileInfo> #include <QPlainTextEdit> #include <QTextCodec> #include <QTextCursor> #include <QTextBlock> #include <QScrollBar> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangFmt::GolangFmt(LiteApi::IApplication *app,QObject *parent) : QObject(parent), m_liteApp(app), m_diff(true), m_fixImports(false), m_autofmt(true), m_syncfmt(false), m_timeout(600) { m_process = new ProcessEx(this); connect(m_process,SIGNAL(extOutput(QByteArray,bool)),this,SLOT(fmtOutput(QByteArray,bool))); connect(m_process,SIGNAL(started()),this,SLOT(fmtStarted())); connect(m_process,SIGNAL(extFinish(bool,int,QString)),this,SLOT(fmtFinish(bool,int,QString))); m_envManager = LiteApi::findExtensionObject<LiteApi::IEnvManager*>(m_liteApp,"LiteApi.IEnvManager"); if (m_envManager) { connect(m_envManager,SIGNAL(currentEnvChanged(LiteApi::IEnv*)),this,SLOT(currentEnvChanged(LiteApi::IEnv*))); } connect(m_liteApp->editorManager(),SIGNAL(editorAboutToSave(LiteApi::IEditor*)),this,SLOT(editorAboutToSave(LiteApi::IEditor*))); connect(m_liteApp->optionManager(),SIGNAL(applyOption(QString)),this,SLOT(applyOption(QString))); applyOption("option/golangfmt"); } void GolangFmt::applyOption(QString id) { if (id != "option/golangfmt") { return; } m_fixImports = m_liteApp->settings()->value(GOLANGFMT_FIXIMPORTS,false).toBool(); m_autofmt = m_liteApp->settings()->value(GOLANGFMT_AUTOFMT,true).toBool(); m_syncfmt = m_liteApp->settings()->value(GOLANGFMT_USESYNCFMT,true).toBool(); m_timeout = m_liteApp->settings()->value(GOLANGFMT_SYNCTIMEOUT,500).toInt(); } void GolangFmt::syncfmtEditor(LiteApi::IEditor *editor, bool save, bool check, int timeout, int fmtStyle) { LiteApi::ITextEditor *textEditor = LiteApi::getTextEditor(editor); if (!textEditor) { return; } QString fileName = editor->filePath(); if (fileName.isEmpty() && check) { return; } QFileInfo info(fileName); if (info.suffix() != "go" && check) { return; } QPlainTextEdit *ed = LiteApi::findExtensionObject<QPlainTextEdit*>(editor,"LiteApi.QPlainTextEdit"); if (!ed) { return; } QString text = ed->toPlainText(); if (text.isEmpty()) { return; } if (timeout < 0) { timeout = m_timeout; } QStringList args; args << "gofmt"; //format style 0: auto, 1: gofmt 2: fiximports if (fmtStyle == 0) { if (m_fixImports) { args << "-fiximports"; } } else if (fmtStyle == 1) { } else if (fmtStyle == 2) { args << "-fiximports"; } if (m_diff) { args << "-d"; } bool bresult = false; QString output,errmsg; // if (isUseGopher(m_liteApp) && m_gopher.isValid()) { // QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); // m_gopher.setEnvironment(env); // bresult = m_gopher.invokeArgs(args,text,output,errmsg); // } else { // QString cmd = LiteApi::getGotools(m_liteApp); QProcess process; process.setProcessEnvironment(LiteApi::getGoEnvironment(m_liteApp)); process.start(cmd,args); if (!process.waitForStarted(timeout)) { m_liteApp->appendLog("gofmt",QString("Timed out after %1ms when starting go code format").arg(timeout),false); return; } process.write(text.toUtf8()); process.closeWriteChannel(); if (!process.waitForFinished(timeout*4)) { m_liteApp->appendLog("gofmt",QString("Timed out after %1ms while running go code format").arg(timeout*4),false); return; } if (process.exitCode() != 0) { errmsg = QString::fromUtf8(process.readAllStandardError()); } else { bresult = true; output = QString::fromUtf8(process.readAllStandardOutput()); } // } LiteApi::ILiteEditor *liteEditor = LiteApi::getLiteEditor(editor); liteEditor->clearAllNavigateMark(LiteApi::EditorNavigateBad, GOLANGFMT_TAG); if (!bresult) { if (!errmsg.isEmpty()) { //<standard input>:23:1: expected declaration, found 'INT' 1 foreach(QString msg,errmsg.split("\n")) { QRegExp re(":(\\d+):"); if (re.indexIn(msg,16) >= 0) { bool ok = false; int line = re.cap(1).toInt(&ok); if (ok) { liteEditor->insertNavigateMark(line-1,LiteApi::EditorNavigateError,msg.mid(16), GOLANGFMT_TAG); } } } } QString log = errmsg; errmsg.replace("<standard input>",""); liteEditor->setNavigateHead(LiteApi::EditorNavigateError,"go code format error\n"+errmsg); log.replace("<standard input>",info.filePath()); m_liteApp->appendLog("go code format error",log,fmtStyle == 0 ? false: true); return; } liteEditor->setNavigateHead(LiteApi::EditorNavigateNormal,"go code format success"); liteEditor->loadDiff(output); if (save) { m_liteApp->editorManager()->saveEditor(editor,false); } } void GolangFmt::fmtEditor(LiteApi::IEditor *editor, bool save) { if (!editor) { return; } if (editor->filePath().isEmpty()) { return; } QFileInfo info(editor->filePath()); if (info.suffix() != "go") { return; } if (!m_process->isStop()) { return; } QPlainTextEdit *edit = LiteApi::getPlainTextEdit(editor); if (!edit) { return; } m_data.clear();; m_errData.clear(); m_process->setUserData(0,editor->filePath()); m_process->setUserData(1,edit->toPlainText()); m_process->setUserData(2,save); QStringList args; args << "gofmt"; if (m_fixImports) { args << "-fiximports"; } if (m_diff) { args << "-d"; } QString cmd = LiteApi::getGotools(m_liteApp); m_process->start(cmd,args); } void GolangFmt::editorAboutToSave(LiteApi::IEditor* editor) { if (!m_autofmt) { return; } if (m_syncfmt) { syncfmtEditor(editor,true); } else { fmtEditor(editor,true); } } void GolangFmt::currentEnvChanged(LiteApi::IEnv*) { QProcessEnvironment env = LiteApi::getGoEnvironment(m_liteApp); m_process->setProcessEnvironment(env); // if (!LiteApi::hasGoEnv(env)) { // m_liteApp->appendLog("GolangFmt","Could not find go env", false); // return; // } // m_liteApp->appendLog("GolangFmt","go environment changed"); // m_gofmtCmd = FileUtil::lookupGoBin("gofmt",m_liteApp,false); // if (m_gofmtCmd.isEmpty()) { // m_liteApp->appendLog("GolangFmt",QString("Could not find %1").arg(m_gofmtCmd),false); // } } void GolangFmt::gofmt() { LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (!editor) { return; } m_liteApp->editorManager()->saveEditor(editor,false); syncfmtEditor(editor,false,true,30000,1); } void GolangFmt::goimports() { LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (!editor) { return; } m_liteApp->editorManager()->saveEditor(editor,false); syncfmtEditor(editor,false,true,30000,2); } void GolangFmt::fmtStarted() { QString text = m_process->userData(1).toString(); m_process->write(text.toUtf8()); m_process->closeWriteChannel(); } void GolangFmt::fmtOutput(QByteArray data,bool stdErr) { if (stdErr) { m_errData.append(data); return; } m_data.append(data); } void GolangFmt::fmtFinish(bool error,int code,QString) { QString fileName = m_process->userData(0).toString(); if (fileName.isEmpty()) { return; } bool save = m_process->userData(2).toBool(); LiteApi::IEditor *editor = m_liteApp->editorManager()->findEditor(fileName,true); if (!editor) { return; } LiteApi::ILiteEditor *liteEditor = LiteApi::getLiteEditor(editor); if (!liteEditor) { return; } QPlainTextEdit *ed = LiteApi::getPlainTextEdit(editor); if (!ed) { return; } //qDebug() << ed->document()->isModified(); if (ed->document()->isModified()) { return; } liteEditor->clearAllNavigateMark(LiteApi::EditorNavigateBad, GOLANGFMT_TAG); QTextCodec *codec = QTextCodec::codecForName("utf-8"); if (!error && code == 0) { liteEditor->setNavigateHead(LiteApi::EditorNavigateNormal,"go code format success"); liteEditor->loadDiff(codec->toUnicode(m_data)); if (save) { m_liteApp->editorManager()->saveEditor(editor,false); } } else if (!m_errData.isEmpty()) { QString errmsg = codec->toUnicode(m_errData); if (!errmsg.isEmpty()) { //<standard input>:23:1: expected declaration, found 'INT' 1 foreach(QString msg,errmsg.split("\n")) { QRegExp re(":(\\d+):"); if (re.indexIn(msg,16) >= 0) { bool ok = false; int line = re.cap(1).toInt(&ok); if (ok) { liteEditor->insertNavigateMark(line-1,LiteApi::EditorNavigateError,msg.mid(16), GOLANGFMT_TAG); } } } } QString log = errmsg; errmsg.replace("<standard input>",""); liteEditor->setNavigateHead(LiteApi::EditorNavigateError,"go code format error\n"+errmsg); log.replace("<standard input>",fileName); m_liteApp->appendLog("go code format error",log,false); } m_data.clear(); }
11,241
C++
.cpp
320
29.45
133
0.634411
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,471
golangfmtplugin.cpp
visualfc_liteide/liteidex/src/plugins/golangfmt/golangfmtplugin.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangfmtplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangfmtplugin.h" #include "golangfmt.h" #include "golangfmtoptionfactory.h" #include "liteeditorapi/liteeditorapi.h" #include "fileutil/fileutil.h" #include <QMenu> #include <QAction> #include <QToolButton> #include <QFileInfo> #include <QDir> #include <QDebug> //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangFmtPlugin::GolangFmtPlugin() : m_fmt(0) { } bool GolangFmtPlugin::load(LiteApi::IApplication *app) { m_liteApp = app; app->optionManager()->addFactory(new GolangFmtOptionFactory(app,this)); m_fmt = new GolangFmt(app,this); m_gofmtAct = new QAction(QIcon("icon:golangfmt/images/gofmt.png"),tr("Format Code"),this); m_goimportsAct = new QAction(QIcon("icon:golangfmt/images/gofmt.png"),tr("Format Code (Adjusts Imports)"),this); LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(this,"GoFmt"); actionContext->regAction(m_gofmtAct,"Gofmt","Ctrl+I"); actionContext->regAction(m_goimportsAct,"GoImports","Ctrl+Alt+I"); m_goplayAct = new QAction(QIcon("icon:golangfmt/images/gofmt.png"),tr("Format Code"),this); actionContext->regAction(m_goplayAct,"Goplayfmt","Ctrl+I"); connect(m_gofmtAct,SIGNAL(triggered()),m_fmt,SLOT(gofmt())); connect(m_goimportsAct,SIGNAL(triggered()),m_fmt,SLOT(goimports())); connect(m_goplayAct,SIGNAL(triggered()),this,SLOT(goplayFmt())); connect(app->editorManager(),SIGNAL(editorCreated(LiteApi::IEditor*)),this,SLOT(editorCreated(LiteApi::IEditor*))); connect(app,SIGNAL(loaded()),this,SLOT(appLoaded())); return true; } QStringList GolangFmtPlugin::dependPluginList() const{ return QStringList() << "plugin/liteenv"; } void GolangFmtPlugin::goplayFmt() { m_fmt->syncfmtEditor(m_playEditor,false,false,2000); /* QPlainTextEdit* ed=LiteApi::getPlainTextEdit(m_playEditor); ed->document()->setModified(false); m_fmt->fmtEditor(m_playEditor,false); */ } void GolangFmtPlugin::appLoaded() { m_playEditor = LiteApi::findExtensionObject<LiteApi::IEditor*>(m_liteApp->extension(),"LiteApi.Goplay.IEditor"); if (m_playEditor) { if (m_playEditor->mimeType() != "text/x-gosrc") { return; } m_playEditor->widget()->addAction(m_goplayAct); QMenu *menu = LiteApi::getContextMenu(m_playEditor); if (menu) { menu->addSeparator(); menu->addAction(m_goplayAct); } LiteApi::ILiteEditor *ed = LiteApi::getLiteEditor(m_playEditor); if (ed) { ed->setEnableAutoIndentAction(false); } } } void GolangFmtPlugin::editorCreated(LiteApi::IEditor *editor) { if (!editor) { return; } if (editor->mimeType() != "text/x-gosrc") { return; } QMenu *menu = LiteApi::getEditMenu(editor); if (menu) { menu->addSeparator(); menu->addAction(m_gofmtAct); menu->addAction(m_goimportsAct); } menu = LiteApi::getContextMenu(editor); if (menu) { menu->addSeparator(); menu->addAction(m_gofmtAct); menu->addAction(m_goimportsAct); } LiteApi::ILiteEditor *ed = LiteApi::getLiteEditor(editor); if (ed) { ed->setEnableAutoIndentAction(false); } } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
4,670
C++
.cpp
124
33.387097
119
0.676971
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,472
golangfmtoption.cpp
visualfc_liteide/liteidex/src/plugins/golangfmt/golangfmtoption.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangfmtoption.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangfmtoption.h" #include "golangfmt_global.h" #include "ui_golangfmtoption.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangFmtOption::GolangFmtOption(LiteApi::IApplication *app,QObject *parent) : LiteApi::IOption(parent), m_liteApp(app), m_widget(new QWidget), ui(new Ui::GolangFmtOption) { ui->setupUi(m_widget); } GolangFmtOption::~GolangFmtOption() { delete m_widget; delete ui; } QWidget *GolangFmtOption::widget() { return m_widget; } QString GolangFmtOption::name() const { return "GolangFmt"; } QString GolangFmtOption::mimeType() const { return "option/golangfmt"; } void GolangFmtOption::load() { bool fixImports = m_liteApp->settings()->value(GOLANGFMT_FIXIMPORTS,false).toBool(); bool autofmt = m_liteApp->settings()->value(GOLANGFMT_AUTOFMT,true).toBool(); bool syncfmt = m_liteApp->settings()->value(GOLANGFMT_USESYNCFMT,true).toBool(); int timeout = m_liteApp->settings()->value(GOLANGFMT_SYNCTIMEOUT,500).toInt(); ui->checkBoxUseGoimports->setChecked(fixImports); ui->checkBoxAutoFmt->setChecked(autofmt); ui->enableSyncCheckBox->setChecked(syncfmt); ui->syncTimeoutLineEdit->setText(QString("%1").arg(timeout)); } void GolangFmtOption::save() { bool goimports = ui->checkBoxUseGoimports->isChecked(); bool autofmt = ui->checkBoxAutoFmt->isChecked(); bool syncfmt = ui->enableSyncCheckBox->isChecked(); m_liteApp->settings()->setValue(GOLANGFMT_FIXIMPORTS,goimports); m_liteApp->settings()->setValue(GOLANGFMT_AUTOFMT,autofmt); m_liteApp->settings()->setValue(GOLANGFMT_USESYNCFMT,syncfmt); int timeout = ui->syncTimeoutLineEdit->text().toInt(); if (timeout < 500) { timeout = 500; } ui->syncTimeoutLineEdit->setText(QString("%1").arg(timeout)); m_liteApp->settings()->setValue(GOLANGFMT_SYNCTIMEOUT,timeout); }
3,203
C++
.cpp
85
34.823529
88
0.699904
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,473
golangfmtoptionfactory.cpp
visualfc_liteide/liteidex/src/plugins/golangfmt/golangfmtoptionfactory.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: golangfmtoptionfactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangfmtoption.h" #include "golangfmtoptionfactory.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end GolangFmtOptionFactory::GolangFmtOptionFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IOptionFactory(parent), m_liteApp(app) { } QStringList GolangFmtOptionFactory::mimeTypes() const { return QStringList() << "option/golangfmt"; } LiteApi::IOption *GolangFmtOptionFactory::create(const QString &mimeType) { if (mimeType == "option/golangfmt") { return new GolangFmtOption(m_liteApp,this); } return 0; }
1,899
C++
.cpp
49
36.469388
91
0.687432
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
21,474
fakevimeditoptionfactory.cpp
visualfc_liteide/liteidex/src/plugins/fakevimedit/fakevimeditoptionfactory.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2019 LiteIDE. All rights reserved. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** In addition, as a special exception, that plugins developed for LiteIDE, ** are allowed to remain closed sourced and can be distributed under any license . ** These rights are included in the file LGPL_EXCEPTION.txt in this package. ** **************************************************************************/ // Module: fakevimeditoptionfactory.cpp // Creator: jsuppe <jon.suppe@gmail.com> #include "fakevimeditoption.h" #include "fakevimeditoptionfactory.h" #include "fakevimedit_global.h" //lite_memory_check_begin #if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG) #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ ) #define new DEBUG_NEW #endif //lite_memory_check_end FakeVimEditOptionFactory::FakeVimEditOptionFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IOptionFactory(parent), m_liteApp(app) { } QStringList FakeVimEditOptionFactory::mimeTypes() const { return QStringList() << OPTION_FAKEVIMEDIT; } LiteApi::IOption *FakeVimEditOptionFactory::create(const QString &mimeType) { if (mimeType == OPTION_FAKEVIMEDIT) { return new FakeVimEditOption(m_liteApp,this); } return 0; }
1,946
C++
.cpp
50
36.66
95
0.693446
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false