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,475
fakevimeditplugin.cpp
visualfc_liteide/liteidex/src/plugins/fakevimedit/fakevimeditplugin.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: fakevimeditplugin.cpp // Creator: jsuppe <jon.suppe@gmail.com> #include "fakevimedit.h" #include "fakevimeditplugin.h" #include "fakevimeditoptionfactory.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 FakeVimEditPlugin::FakeVimEditPlugin() { } bool FakeVimEditPlugin::load(LiteApi::IApplication *app) { app->optionManager()->addFactory(new FakeVimEditOptionFactory(app,this)); new FakeVimEdit(app,this); return true; } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
1,892
C++
.cpp
48
36.4375
83
0.678299
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,476
fakevimeditoption.cpp
visualfc_liteide/liteidex/src/plugins/fakevimedit/fakevimeditoption.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: fakevimeditoption.cpp // Creator: jsuppe <jon.suppe@gmail.com> #include "fakevimeditoption.h" #include "ui_fakevimeditoption.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 FakeVimEditOption::FakeVimEditOption(LiteApi::IApplication *app,QObject *parent) : LiteApi::IOption(parent), m_liteApp(app), m_widget(new QWidget), ui(new Ui::FakeVimEditOption) { ui->setupUi(m_widget); connect(ui->resetCommandsButton,SIGNAL(clicked(bool)),this,SLOT(on_resetCommandsButton_clicked())); } FakeVimEditOption::~FakeVimEditOption() { delete m_widget; delete ui; } QWidget *FakeVimEditOption::widget() { return m_widget; } QString FakeVimEditOption::name() const { return "FakeVimEdit"; } QString FakeVimEditOption::mimeType() const { return OPTION_FAKEVIMEDIT; } void FakeVimEditOption::load() { QStringList cmds = m_liteApp->settings()->value(FAKEVIMEDIT_INITCOMMANDS,initCommandList()).toStringList(); ui->textInitCommands->setPlainText(cmds.join("\n")); } void FakeVimEditOption::save() { //bool useFakeVim = ui->enableUseFakeVimCheckBox->isChecked(); QStringList cmds = ui->textInitCommands->toPlainText().split("\n",qtSkipEmptyParts); m_liteApp->settings()->setValue(FAKEVIMEDIT_INITCOMMANDS,cmds); } void FakeVimEditOption::on_resetCommandsButton_clicked() { ui->textInitCommands->setPlainText(initCommandList().join("\n")); }
2,774
C++
.cpp
75
33.506667
112
0.688549
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,477
fakevimedit.cpp
visualfc_liteide/liteidex/src/plugins/fakevimedit/fakevimedit.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: fakevimedit.cpp // Creator: jsuppe <jon.suppe@gmail.com> #include "fakevim/fakevim/fakevimhandler.h" #include "fakevim/fakevim/fakevimactions.h" #include "fakevimedit.h" #include "fakevimedit_global.h" #include "qtc_editutil/uncommentselection.h" #include "litebuildapi/litebuildapi.h" #include "fileutil/fileutil.h" #include <QMenu> #include <QToolBar> #include <QAction> #include <QTextStream> #include <QApplication> #include <QToolTip> #include <QLabel> #include <QStatusBar> #include "liteeditorapi/liteeditorapi.h" #include "../liteeditor/liteeditor_global.h" using namespace FakeVim::Internal; //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 FakeVimEdit::FakeVimEdit(LiteApi::IApplication *app, QObject *parent) : QObject(parent), m_liteApp(app), m_enableUseFakeVim(false), m_commandLabel(0) { 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_liteApp->optionManager(),SIGNAL(applyOption(QString)),this,SLOT(applyOption(QString))); this->applyOption(OPTION_FAKEVIMEDIT); m_enableUseFakeVim = m_liteApp->settings()->value(FAKEVIMEDIT_USEFAKEVIM,false).toBool(); m_enableUseFakeVimAct = new QAction(tr("Use FakeVim Editing"),this); m_enableUseFakeVimAct->setCheckable(true); m_enableUseFakeVimAct->setChecked(m_enableUseFakeVim); connect(m_enableUseFakeVimAct,SIGNAL(toggled(bool)),this,SLOT(toggledEnableUseFakeVim(bool))); if (m_enableUseFakeVim) { _enableFakeVim(); } } void FakeVimEdit::toggledEnableUseFakeVim(bool b) { m_enableUseFakeVim = b; m_liteApp->settings()->setValue(FAKEVIMEDIT_USEFAKEVIM,b); if(m_enableUseFakeVim){ _enableFakeVim(); }else{ _disableFakeVim(); } } void FakeVimEdit::applyOption(const QString &option) { if (option != OPTION_FAKEVIMEDIT) { return; } m_initCommandList = m_liteApp->settings()->value(FAKEVIMEDIT_INITCOMMANDS,initCommandList()).toStringList(); } void FakeVimEdit::_enableFakeVim(){ LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); _addCommandLabel(); _addFakeVimToEditor(editor); } void FakeVimEdit::_disableFakeVim(){ LiteApi::IEditor *editor = m_liteApp->editorManager()->currentEditor(); _removeFakeVimFromEditor(editor); _removeCommandLabel(); } QFont FakeVimEdit::commandLabelFont(){ QFont font; font.setStyleHint(QFont::Monospace); font.setBold(true); return font; } void FakeVimEdit::_addCommandLabel(){ QFont font = commandLabelFont(); _removeCommandLabel(); m_commandLabel = new QLabel(m_liteApp->mainWindow()); m_commandLabel->setFont(font); m_liteApp->mainWindow()->statusBar()->addPermanentWidget(m_commandLabel); } void FakeVimEdit::_removeCommandLabel(){ if(!m_commandLabel){ return; } m_liteApp->mainWindow()->statusBar()->removeWidget(m_commandLabel); delete m_commandLabel; m_commandLabel = NULL; } void FakeVimEdit::_removeFakeVimFromEditor(LiteApi::IEditor *editor){ LiteApi::ILiteEditor *ed = LiteApi::getLiteEditor(editor); if (!ed) { return; } QString mime = editor->mimeType(); bool tabToSpace = false; int tabWidth = 4; LiteApi::IMimeType *im = m_liteApp->mimeTypeManager()->findMimeType(mime); if (im) { tabToSpace = im->tabToSpace(); tabWidth = im->tabWidth(); } tabWidth = m_liteApp->settings()->value(MIMETYPE_TABWIDTH+mime,tabWidth).toInt(); tabToSpace = m_liteApp->settings()->value(MIMETYPE_TABTOSPACE+mime,tabToSpace).toBool(); ed->setTabOption(tabWidth,tabToSpace); QPlainTextEdit *ped = LiteApi::getPlainTextEdit(ed); if(!ped){ return; } if(FakeVimHandler *fakeVimHandler = m_editorMap.value(ped)){ delete fakeVimHandler; m_editorMap.remove(ped); } } void FakeVimEdit::_addFakeVimToEditor(LiteApi::IEditor *editor){ LiteApi::ILiteEditor *ed = LiteApi::getLiteEditor(editor); if (!ed) { return; } QPlainTextEdit *ped = LiteApi::getPlainTextEdit(ed); if(!ped){ return; } if(m_editorMap.contains(ped)){ return; } FakeVimHandler *fakeVimHandler; fakeVimHandler = new FakeVimHandler(ped,0); connect(fakeVimHandler, SIGNAL(handleExCommandRequested(bool*,ExCommand)), this, SLOT(handleExCommandRequested(bool*,ExCommand))); connect(fakeVimHandler, SIGNAL(commandBufferChanged(QString,int,int,int,QObject*)), this, SLOT(showMessage(QString,int))); connect(fakeVimHandler, SIGNAL(moveToMatchingParenthesis(bool *, bool *, QTextCursor *)), this, SLOT(moveToMatchingParenthesis(bool *, bool *,QTextCursor *))); //init command list { fakeVimHandler->handleCommand("set shiftwidth=4"); fakeVimHandler->handleCommand("set tabstop=4"); foreach(QString cmd, m_initCommandList) { if (cmd.startsWith("#")) { continue; } fakeVimHandler->handleCommand(cmd); } fakeVimHandler->handleInput("<esc>"); } fakeVimHandler->setCurrentFileName(ed->filePath()); fakeVimHandler->installEventFilter(); fakeVimHandler->setupWidget(); connect(ped, SIGNAL(destroyed(QObject*)), this, SLOT(plainTextEditDestroyed(QObject*))); m_editorMap[ped] = fakeVimHandler; } void FakeVimEdit::plainTextEditDestroyed(QObject *obj) { m_editorMap.remove(obj); } void FakeVimEdit::handleExCommandRequested(bool *b, ExCommand c) { // Save if(c.cmd == "w" ){ m_liteApp->editorManager()->saveEditor(m_editor); *b = true; } // Save & Close if(c.cmd == "x"){ m_liteApp->editorManager()->saveEditor(m_editor); m_liteApp->editorManager()->closeEditor(m_editor); *b = true; } // Close if(c.cmd == "q"){ if(c.hasBang){ m_editor->reload(); } m_liteApp->editorManager()->closeEditor(m_editor); *b = true; } } void FakeVimEdit::moveToMatchingParenthesis(bool *moved, bool *forward, QTextCursor *cursor) { LiteApi::IEditor *editor = m_editor; LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(editor,"Editor"); LiteApi::ActionInfo *info = actionContext->actionInfo("GotoMatchBrace"); info->action->trigger(); int oldPos = cursor->position(); int newPos = this->m_editor->textCursor().position(); cursor->setPosition(newPos); if(oldPos <= newPos){ *forward = true; }else{ *forward = false; } if(oldPos == newPos){ *moved = false; }else{ *moved = true; } } void FakeVimEdit::editorCreated(LiteApi::IEditor *editor) { if (!editor) { return; } QMenu *menu = LiteApi::getEditMenu(editor); if (menu) { menu->addSeparator(); menu->addAction(m_enableUseFakeVimAct); } if (!m_enableUseFakeVim){ return; } m_editor = LiteApi::getLiteEditor(editor); if (m_editor) { m_plainTextEdit = LiteApi::getPlainTextEdit(editor); }else{ return; } if(!m_enableUseFakeVim) return; _addFakeVimToEditor(editor); } void FakeVimEdit::currentEditorChanged(LiteApi::IEditor *editor) { if (!editor) { return; } m_editor = LiteApi::getLiteEditor(editor); QPlainTextEdit *ped = LiteApi::getPlainTextEdit(editor); if (m_enableUseFakeVim){ if(!m_editorMap.contains(ped)) { _addFakeVimToEditor(editor); } }else{ if (m_editorMap.contains(ped)) { _removeFakeVimFromEditor(editor); } } } void FakeVimEdit::showMessage(QString contents, int cursorPos) { if(!m_commandLabel){ return; } QString m_statusMessage = cursorPos == -1 ? contents : contents.left(cursorPos) + QChar(10073) + contents.mid(cursorPos); int slack = 14 - m_statusMessage.size(); QString msg = m_statusMessage + QString(slack, QLatin1Char(' ')); m_commandLabel->setText(msg); }
9,864
C++
.cpp
276
29.576087
140
0.659244
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,478
liteeditor.cpp
visualfc_liteide/liteidex/src/plugins/liteeditor/liteeditor.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: liteeditor.cpp // Creator: visualfc <visualfc@gmail.com> #include "liteeditor.h" #include "liteeditorwidget.h" #include "liteeditorfile.h" #include "litecompleter.h" #include "litewordcompleter.h" #include "liteeditor_global.h" #include "colorstyle/colorstyle.h" #include "qtc_texteditor/generichighlighter/highlighter.h" #include "qtc_editutil/uncommentselection.h" #include "functiontooltip.h" #include "quickopenapi/quickopenapi.h" #include "diff_match_patch/diff_match_patch.h" #include "editorutil/editorutil.h" #include <QFileInfo> #include <QVBoxLayout> #include <QToolBar> #include <QAction> #include <QApplication> #include <QClipboard> #include <QMimeData> #include <QComboBox> #include <QLabel> #include <QLineEdit> #include <QTextDocument> #include <QStringListModel> #include <QStandardItemModel> #include <QStandardItem> #include <QTextCursor> #include <QToolTip> #include <QFileDialog> #include <QPrinter> #include <QTextDocumentWriter> #include <QPrintDialog> #include <QPrintPreviewDialog> #include <QPageSetupDialog> #include <QTextCodec> #include <QDebug> #include <QPalette> #include <QTimer> #include <QMessageBox> #include <QTextBlock> #include <QMenu> #include <QInputDialog> #include <QToolButton> #include <QFileSystemModel> //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 LiteEditor::LiteEditor(LiteApi::IApplication *app) : m_liteApp(app), m_extension(new Extension), m_completer(0), m_funcTip(0), m_bReadOnly(false) { m_cleanCompleterCache = false; m_cleanWhiteSpace = false; m_offsetVisible = false; m_syntax = 0; m_widget = new QWidget; m_editorWidget = new LiteEditorWidget(app,m_widget); m_document = m_editorWidget->document(); m_editorWidget->setCursorWidth(2); //m_editorWidget->setAcceptDrops(false); m_defEditorPalette = m_editorWidget->palette(); createActions(); createToolBars(); createMenu(); m_editorWidget->setContextMenu(m_contextMenu); QVBoxLayout *layout = new QVBoxLayout; layout->setMargin(0); layout->setSpacing(0); /* m_toolBar->setStyleSheet("QToolBar {border: 1px ; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #eeeeee, stop: 1 #ababab); }"\ "QToolBar QToolButton { border:1px ; border-radius: 1px; }"\ "QToolBar QToolButton::hover { background-color: #ababab;}"\ "QToolBar::separator {width:2px; margin-left:2px; margin-right:2px; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #dedede, stop: 1 #a0a0a0);}"); */ QHBoxLayout *toolLayout = new QHBoxLayout; toolLayout->setMargin(0); toolLayout->setSpacing(0); toolLayout->addWidget(m_editToolBar); //toolLayout->addWidget(m_editNavBar); toolLayout->addWidget(m_navBar->toolBar()); toolLayout->addSpacing(0); // //toolLayout->addWidget(m_infoToolBar); layout->addLayout(toolLayout); // QHBoxLayout *hlayout = new QHBoxLayout; // hlayout->addWidget(m_editorWidget); // hlayout->addWidget(m_editorWidget->navigateArea()); layout->addWidget(m_editorWidget); m_widget->setLayout(layout); m_file = new LiteEditorFile(m_liteApp,this); // QTextOption option = m_editorWidget->document()->defaultTextOption(); // option.setFlags(option.flags() | QTextOption::ShowTabsAndSpaces); // option.setFlags(option.flags() | QTextOption::AddSpaceForLineAndParagraphSeparators); // option.setTabs(tabs); // m_editorWidget->document()->setDefaultTextOption(option); connect(m_editorWidget->document(),SIGNAL(modificationChanged(bool)),this,SIGNAL(modificationChanged(bool))); connect(m_editorWidget->document(),SIGNAL(contentsChanged()),this,SIGNAL(contentsChanged())); connect(m_liteApp->optionManager(),SIGNAL(applyOption(QString)),this,SLOT(applyOption(QString))); connect(m_liteApp->editorManager(),SIGNAL(colorStyleSchemeChanged()),this,SLOT(loadColorStyleScheme())); //applyOption("option/liteeditor"); LiteApi::IEditContext *editContext = new EditContext(this,this); m_extension->addObject("LiteApi.ITextEditor",this); m_extension->addObject("LiteApi.ILiteEditor",this); m_extension->addObject("LiteApi.QToolBar.Edit",m_editToolBar); m_extension->addObject("LiteApi.QToolBar.Edit.Nav",m_navBar->toolBar()); m_extension->addObject("LiteApi.QPlainTextEdit",m_editorWidget); m_extension->addObject("LiteApi.ContextMenu",m_contextMenu); m_extension->addObject("LiteApi.Menu.Edit",m_editMenu); m_extension->addObject("LiteApi.IEditContext",editContext); m_editorWidget->installEventFilter(m_liteApp->editorManager()); connect(m_editorWidget,SIGNAL(cursorPositionChanged()),this,SLOT(editPositionChanged())); connect(m_editorWidget,SIGNAL(navigationStateChanged(QByteArray)),this,SLOT(navigationStateChanged(QByteArray))); connect(m_editorWidget,SIGNAL(overwriteModeChanged(bool)),m_overInfoAct,SLOT(setVisible(bool))); connect(m_editorWidget,SIGNAL(requestFontZoom(int)),this,SLOT(requestFontZoom(int))); connect(m_editorWidget,SIGNAL(updateLink(QTextCursor,QPoint,bool)),this,SIGNAL(updateLink(QTextCursor,QPoint,bool))); //connect(m_lineInfo,SIGNAL(doubleClickEvent()),this,SLOT(gotoLine())); //connect(m_closeEditorAct,SIGNAL(triggered()),m_liteApp->editorManager(),SLOT(closeEditor())); connect(m_liteApp,SIGNAL(broadcast(QString,QString,QVariant)),this,SLOT(broadcast(QString,QString,QVariant))); } LiteEditor::~LiteEditor() { if (m_completer) { delete m_completer; } if (m_funcTip) { delete m_funcTip; } delete m_contextMenu; delete m_editMenu; delete m_extension; delete m_editorWidget; delete m_widget; delete m_file; } QTextDocument *LiteEditor::document() const { return m_document; } void LiteEditor::setEditorMark(LiteApi::IEditorMark *mark) { m_editorWidget->setEditorMark(mark); m_extension->addObject("LiteApi.IEditorMark",mark); } void LiteEditor::setTextLexer(LiteApi::ITextLexer *lexer) { m_extension->addObject("LiteApi.ITextLexer",lexer); m_editorWidget->setTextLexer(lexer); } void LiteEditor::setSyntaxHighlighter(TextEditor::SyntaxHighlighter *syntax) { m_syntax = syntax; m_extension->addObject("TextEditor::SyntaxHighlighter",syntax); m_commentAct->setVisible(m_syntax && !m_syntax->comment().isEmpty()); } TextEditor::SyntaxHighlighter *LiteEditor::syntaxHighlighter() const { return m_syntax; } void LiteEditor::setCompleter(LiteApi::ICompleter *complter) { if (m_completer) { QObject::disconnect(m_completer, 0, m_editorWidget, 0); delete m_completer; m_completer = 0; } m_completer = complter; if (!m_completer) { return; } m_completer->setEditor(m_editorWidget); m_editorWidget->setCompleter(m_completer); m_extension->addObject("LiteApi.ICompleter",m_completer); connect(m_editorWidget,SIGNAL(completionPrefixChanged(QString,bool)),m_completer,SLOT(completionPrefixChanged(QString,bool))); connect(m_completer,SIGNAL(wordCompleted(QString,QString,QString)),this,SLOT(updateTip(QString,QString,QString))); } void LiteEditor::clipbordDataChanged() { QClipboard *clipboard = QApplication::clipboard(); if (clipboard->mimeData()->hasText() || clipboard->mimeData()->hasHtml()) { m_pasteAct->setEnabled(true); } else { m_pasteAct->setEnabled(false); } } static void setActionsShortcutContext(const QList<QAction*> &actionList, Qt::ShortcutContext context) { foreach (QAction *act, actionList) { act->setShortcutContext(context); } } void LiteEditor::createActions() { LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(this,"Editor"); m_undoAct = new QAction(QIcon("icon:liteeditor/images/undo.png"),tr("Undo"),this); m_undoAct->setEnabled(false); m_redoAct = new QAction(QIcon("icon:liteeditor/images/redo.png"),tr("Redo"),this); m_redoAct->setEnabled(false); m_cutAct = new QAction(QIcon("icon:liteeditor/images/cut.png"),tr("Cut"),this); m_cutAct->setEnabled(false); m_copyAct = new QAction(QIcon("icon:liteeditor/images/copy.png"),tr("Copy"),this); m_copyAct->setEnabled(false); m_pasteAct = new QAction(QIcon("icon:liteeditor/images/paste.png"),tr("Paste"),this); m_selectAllAct = new QAction(tr("Select All"),this); #ifndef Q_OS_MAC actionContext->regAction(m_copyAct,"Copy",QKeySequence::Copy); actionContext->regAction(m_pasteAct,"Paste",QKeySequence::Paste); actionContext->regAction(m_cutAct,"Cut",QKeySequence::Cut); actionContext->regAction(m_selectAllAct,"SelectAll",QKeySequence::SelectAll); actionContext->regAction(m_undoAct,"Undo",QKeySequence::Undo); actionContext->regAction(m_redoAct,"Redo",QKeySequence::Redo); setActionsShortcutContext(QList<QAction*>() << m_undoAct << m_redoAct << m_copyAct << m_cutAct << m_pasteAct << m_selectAllAct, Qt::WidgetShortcut); #endif m_exportHtmlAct = new QAction(QIcon("icon:liteeditor/images/exporthtml.png"),tr("Export HTML..."),this); #ifndef QT_NO_PRINTER m_exportPdfAct = new QAction(QIcon("icon:liteeditor/images/exportpdf.png"),tr("Export PDF..."),this); m_filePrintAct = new QAction(QIcon("icon:liteeditor/images/fileprint.png"),tr("Print..."),this); m_filePrintPreviewAct = new QAction(QIcon("icon:liteeditor/images/fileprintpreview.png"),tr("Print Preview..."),this); #endif m_gotoPrevBlockAct = new QAction(tr("Go to Previous Block"),this); actionContext->regAction(m_gotoPrevBlockAct,"GotoPreviousBlock","Ctrl+["); m_gotoNextBlockAct = new QAction(tr("Go to Next Block"),this); actionContext->regAction(m_gotoNextBlockAct,"GotoNextBlock","Ctrl+]"); m_selectBlockAct = new QAction(tr("Select Block"),this); actionContext->regAction(m_selectBlockAct,"SelectBlock","Ctrl+U"); m_gotoMatchBraceAct = new QAction(tr("Go to Matching Brace"),this); actionContext->regAction(m_gotoMatchBraceAct,"GotoMatchBrace","Ctrl+E"); m_gotoDocStartAct = new QAction(tr("Go to Doc Start"),this); actionContext->regAction(m_gotoDocStartAct,"GotoDocStart",""); connect(m_gotoDocStartAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoDocStart())); m_gotoDocEndAct = new QAction(tr("Go to Doc End"),this); actionContext->regAction(m_gotoDocEndAct,"GotoDocEnd",""); connect(m_gotoDocEndAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoDocEnd())); m_gotoLineStartAct = new QAction(tr("Go to Line Start"),this); actionContext->regAction(m_gotoLineStartAct,"GotoLineStart",""); connect(m_gotoLineStartAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoLineStart())); m_gotoLineEndAct = new QAction(tr("Go to Line End"),this); actionContext->regAction(m_gotoLineEndAct,"GotoLineEnd",""); connect(m_gotoLineEndAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoLineEnd())); m_gotoPrevLineAct = new QAction(tr("Go to Previous Line"),this); actionContext->regAction(m_gotoPrevLineAct,"GotoPreviousLine",""); connect(m_gotoPrevLineAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoPreviousLine())); m_gotoNextLineAct = new QAction(tr("Go to Next Line"),this); actionContext->regAction(m_gotoNextLineAct,"GotoNextLine",""); connect(m_gotoNextLineAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoNextLine())); m_gotoPrevCharacterAct = new QAction(tr("Go to Previous Character"),this); actionContext->regAction(m_gotoPrevCharacterAct,"GotoPreviousCharacter",""); connect(m_gotoPrevCharacterAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoPreviousCharacter())); m_gotoNextCharacterAct = new QAction(tr("Go to Next Charater"),this); actionContext->regAction(m_gotoNextCharacterAct,"GotoNextCharater",""); connect(m_gotoNextCharacterAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoNextCharacter())); m_gotoPrevWordAct = new QAction(tr("Go to Previous Word"),this); actionContext->regAction(m_gotoPrevWordAct,"GotoPreviousWord",""); connect(m_gotoPrevWordAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoPreviousWord())); m_gotoNextWordAct = new QAction(tr("Go to Next Word"),this); actionContext->regAction(m_gotoNextWordAct,"GotoNextWord",""); connect(m_gotoNextWordAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoNextWord())); m_foldAct = new QAction(tr("Fold"),this); actionContext->regAction(m_foldAct,"Fold","Ctrl+<"); m_unfoldAct = new QAction(tr("Unfold"),this); actionContext->regAction(m_unfoldAct,"Unfold","Ctrl+>"); m_foldAllAct = new QAction(tr("Fold All"),this); actionContext->regAction(m_foldAllAct,"FoldAll",""); m_unfoldAllAct = new QAction(tr("Unfold All"),this); actionContext->regAction(m_unfoldAllAct,"UnfoldAll",""); connect(m_foldAct,SIGNAL(triggered()),m_editorWidget,SLOT(fold())); connect(m_unfoldAct,SIGNAL(triggered()),m_editorWidget,SLOT(unfold())); connect(m_foldAllAct,SIGNAL(triggered()),m_editorWidget,SLOT(foldAll())); connect(m_unfoldAllAct,SIGNAL(triggered()),m_editorWidget,SLOT(unfoldAll())); m_gotoLineAct = new QAction(tr("Go to Line"),this); actionContext->regAction(m_gotoLineAct,"GotoLine","Ctrl+L"); m_lockAct = new QAction(QIcon("icon:liteeditor/images/lock.png"),tr("File is readonly"),this); m_lockAct->setEnabled(false); m_unlockAct = new QAction(QIcon("icon:liteeditor/images/unlock.png"),tr("File is writable"),this); m_unlockAct->setEnabled(false); m_duplicateAct = new QAction(tr("Duplicate"),this); actionContext->regAction(m_duplicateAct,"Duplicate","Ctrl+Shift+D"); connect(m_duplicateAct,SIGNAL(triggered()),m_editorWidget,SLOT(duplicate())); m_deleteLineAct = new QAction(tr("Delete Line"),this); actionContext->regAction(m_deleteLineAct,"DeleteLine","Ctrl+Shift+K"); connect(m_deleteLineAct,SIGNAL(triggered()),m_editorWidget,SLOT(deleteLine())); m_copyLineAct = new QAction(tr("Copy Line"),this); actionContext->regAction(m_copyLineAct,"CopyLine","Ctrl+Ins"); connect(m_copyLineAct,SIGNAL(triggered()),m_editorWidget,SLOT(copyLine())); m_cutLineAct = new QAction(tr("Cut Line"),this); actionContext->regAction(m_cutLineAct,"CutLine","Shift+Del"); connect(m_cutLineAct,SIGNAL(triggered()),m_editorWidget,SLOT(cutLine())); m_insertLineBeforeAct = new QAction(tr("Insert Line Before"),this); actionContext->regAction(m_insertLineBeforeAct,"InsertLineBefore","Ctrl+Shift+Return"); connect(m_insertLineBeforeAct,SIGNAL(triggered()),m_editorWidget,SLOT(insertLineBefore())); m_insertLineAfterAct = new QAction(tr("Insert Line After"),this); actionContext->regAction(m_insertLineAfterAct,"InsertLineAfter","Ctrl+Return"); connect(m_insertLineAfterAct,SIGNAL(triggered()),m_editorWidget,SLOT(insertLineAfter())); m_increaseFontSizeAct = new QAction(tr("Increase Font Size"),this); actionContext->regAction(m_increaseFontSizeAct,"IncreaseFontSize","Ctrl++"); m_decreaseFontSizeAct = new QAction(tr("Decrease Font Size"),this); actionContext->regAction(m_decreaseFontSizeAct,"DecreaseFontSize","Ctrl+-"); m_resetFontSizeAct = new QAction(tr("Reset Font Size"),this); actionContext->regAction(m_resetFontSizeAct,"ResetFontSize","Ctrl+0"); m_cleanWhitespaceAct = new QAction(tr("Clean Whitespace"),this); actionContext->regAction(m_cleanWhitespaceAct,"CleanWhitespace",""); m_mimeLineWrapAct = new QAction(tr("Line Wrap (MimeType)"),this); m_mimeLineWrapAct->setCheckable(true); actionContext->regAction(m_mimeLineWrapAct,"LineWrap",""); m_codeCompleteAct = new QAction(tr("Code Complete"),this); #ifdef Q_OS_MAC actionContext->regAction(m_codeCompleteAct,"CodeComplete","Meta+Space"); #else actionContext->regAction(m_codeCompleteAct,"CodeComplete","Ctrl+Space"); #endif m_commentAct = new QAction(tr("Toggle Comment"),this); actionContext->regAction(m_commentAct,"Comment","Ctrl+/"); m_blockCommentAct = new QAction(tr("Toggle Block Commnet"),this); actionContext->regAction(m_blockCommentAct,"BlockComment","Ctrl+Shift+/"); m_autoIndentAct = new QAction(tr("Auto-indent Selection"),this); actionContext->regAction(m_autoIndentAct,"AutoIndent","Ctrl+I"); m_autoIndentAct->setVisible(false); m_mimeTabToSpacesAct = new QAction(tr("Tab To Spaces (MimeType)"),this); actionContext->regAction(m_mimeTabToSpacesAct,"TabToSpaces",""); m_mimeTabToSpacesAct->setCheckable(true); m_lineEndingWindowAct = new QAction(tr("Line End Windows (\\r\\n)"),this); actionContext->regAction(m_lineEndingWindowAct,"LineEndingWindow",""); m_lineEndingWindowAct->setCheckable(true); m_lineEndingUnixAct = new QAction(tr("Line End Unix (\\n)"),this); actionContext->regAction(m_lineEndingUnixAct,"LineEndingUnix",""); m_lineEndingUnixAct->setCheckable(true); m_visualizeWhitespaceAct = new QAction(tr("Visualize Whitespace (Global)"),this); actionContext->regAction(m_visualizeWhitespaceAct,"VisualizeWhitespace",""); m_visualizeWhitespaceAct->setCheckable(true); m_commentAct->setVisible(false); m_blockCommentAct->setVisible(false); m_moveLineUpAction = new QAction(tr("Move Line Up"),this); actionContext->regAction(m_moveLineUpAction,"MoveLineUp","Ctrl+Shift+Up"); m_moveLineDownAction = new QAction(tr("Move Line Down"),this); actionContext->regAction(m_moveLineDownAction,"MoveLineDown","Ctrl+Shift+Down"); m_copyLineUpAction = new QAction(tr("Copy Line Up"),this); actionContext->regAction(m_copyLineUpAction,"CopyLineUp","Ctrl+Alt+Up"); m_copyLineDownAction = new QAction(tr("Copy Line Down"),this); actionContext->regAction(m_copyLineDownAction,"CopyLineDown","Ctrl+Alt+Down"); m_joinLinesAction = new QAction(tr("Join Lines"),this); actionContext->regAction(m_joinLinesAction,"JoinLines","Ctrl+J"); m_convertCaseTitleAct = new QAction(tr("Title Case"),this); actionContext->regAction(m_convertCaseTitleAct,"TitleCase",""); connect(m_convertCaseTitleAct,SIGNAL(triggered()),m_editorWidget,SLOT(convertCaseTitle())); m_convertCaseUpperAct = new QAction(tr("Upper Case"),this); actionContext->regAction(m_convertCaseUpperAct,"UpperCase",""); connect(m_convertCaseUpperAct,SIGNAL(triggered()),m_editorWidget,SLOT(convertCaseUpper())); m_convertCaseLowerAct = new QAction(tr("Lower Case"),this); actionContext->regAction(m_convertCaseLowerAct,"LowerCase",""); connect(m_convertCaseLowerAct,SIGNAL(triggered()),m_editorWidget,SLOT(convertCaseLower())); m_convertCaseSwapAct = new QAction(tr("Swap Case"),this); actionContext->regAction(m_convertCaseSwapAct,"SwapCase",""); connect(m_convertCaseSwapAct,SIGNAL(triggered()),m_editorWidget,SLOT(convertCaseSwap())); m_convertTabToSpaces = new QAction(tr("Tab To Spaces"),this); actionContext->regAction(m_convertTabToSpaces,"TabToSpaces",""); connect(m_convertTabToSpaces,SIGNAL(triggered()),m_editorWidget,SLOT(convertTabToSpaces())); m_convertSpacesToTab = new QAction(tr("Spaces To Tab"),this); actionContext->regAction(m_convertSpacesToTab,"SpacesToTab",""); connect(m_convertSpacesToTab,SIGNAL(triggered()),m_editorWidget,SLOT(convertSpacesToTab())); connect(m_codeCompleteAct,SIGNAL(triggered()),m_editorWidget,SLOT(codeCompleter())); // m_widget->addAction(m_foldAct); // m_widget->addAction(m_unfoldAct); // m_widget->addAction(m_gotoLineAct); // m_widget->addAction(m_gotoPrevBlockAct); // m_widget->addAction(m_gotoNextBlockAct); // m_widget->addAction(m_selectBlockAct); // m_widget->addAction(m_gotoMatchBraceAct); connect(m_editorWidget,SIGNAL(undoAvailable(bool)),m_undoAct,SLOT(setEnabled(bool))); connect(m_editorWidget,SIGNAL(redoAvailable(bool)),m_redoAct,SLOT(setEnabled(bool))); connect(m_editorWidget,SIGNAL(copyAvailable(bool)),m_cutAct,SLOT(setEnabled(bool))); connect(m_editorWidget,SIGNAL(copyAvailable(bool)),m_copyAct,SLOT(setEnabled(bool))); connect(m_undoAct,SIGNAL(triggered()),m_editorWidget,SLOT(undo())); connect(m_redoAct,SIGNAL(triggered()),m_editorWidget,SLOT(redo())); connect(m_cutAct,SIGNAL(triggered()),m_editorWidget,SLOT(cut())); connect(m_copyAct,SIGNAL(triggered()),m_editorWidget,SLOT(copy())); connect(m_pasteAct,SIGNAL(triggered()),m_editorWidget,SLOT(paste())); connect(m_selectAllAct,SIGNAL(triggered()),m_editorWidget,SLOT(selectAll())); connect(m_selectBlockAct,SIGNAL(triggered()),m_editorWidget,SLOT(selectBlock())); connect(m_exportHtmlAct,SIGNAL(triggered()),this,SLOT(exportHtml())); #ifndef QT_NO_PRINTER connect(m_exportPdfAct,SIGNAL(triggered()),this,SLOT(exportPdf())); connect(m_filePrintAct,SIGNAL(triggered()),this,SLOT(filePrint())); connect(m_filePrintPreviewAct,SIGNAL(triggered()),this,SLOT(filePrintPreview())); #endif connect(m_gotoPrevBlockAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoPrevBlock())); connect(m_gotoNextBlockAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoNextBlock())); connect(m_gotoMatchBraceAct,SIGNAL(triggered()),m_editorWidget,SLOT(gotoMatchBrace())); connect(m_gotoLineAct,SIGNAL(triggered()),this,SLOT(gotoLine())); connect(m_increaseFontSizeAct,SIGNAL(triggered()),this,SLOT(increaseFontSize())); connect(m_decreaseFontSizeAct,SIGNAL(triggered()),this,SLOT(decreaseFontSize())); connect(m_resetFontSizeAct,SIGNAL(triggered()),this,SLOT(resetFontSize())); connect(m_cleanWhitespaceAct,SIGNAL(triggered()),m_editorWidget,SLOT(cleanWhitespace())); connect(m_commentAct,SIGNAL(triggered()),this,SLOT(comment())); connect(m_blockCommentAct,SIGNAL(triggered()),this,SLOT(blockComment())); connect(m_autoIndentAct,SIGNAL(triggered()),this,SLOT(autoIndent())); connect(m_mimeLineWrapAct,SIGNAL(triggered(bool)),this,SLOT(toggledLineWrapMode(bool))); connect(m_mimeTabToSpacesAct,SIGNAL(toggled(bool)),this,SLOT(toggledTabToSpaces(bool))); connect(m_visualizeWhitespaceAct,SIGNAL(toggled(bool)),this,SLOT(toggledVisualizeWhitespace(bool))); connect(m_moveLineUpAction,SIGNAL(triggered()),m_editorWidget,SLOT(moveLineUp())); connect(m_moveLineDownAction,SIGNAL(triggered()),m_editorWidget,SLOT(moveLineDown())); connect(m_copyLineUpAction,SIGNAL(triggered()),m_editorWidget,SLOT(copyLineUp())); connect(m_copyLineDownAction,SIGNAL(triggered()),m_editorWidget,SLOT(copyLineDown())); connect(m_joinLinesAction,SIGNAL(triggered()),m_editorWidget,SLOT(joinLines())); //connect(m_lineEndingWindowAct,SIGNAL(triggered()),this,SLOT(lineEndingWindow())); //connect(m_lineEndingUnixAct,SIGNAL(triggered()),this,SLOT(lineEndingUnixAct())); QActionGroup *group = new QActionGroup(this); group->addAction(m_lineEndingWindowAct); group->addAction(m_lineEndingUnixAct); connect(group,SIGNAL(triggered(QAction*)),this,SLOT(triggeredLineEnding(QAction*))); #ifdef Q_OS_WIN QClipboard *clipboard = QApplication::clipboard(); connect(clipboard,SIGNAL(dataChanged()),this,SLOT(clipbordDataChanged())); clipbordDataChanged(); #endif } void LiteEditor::findCodecs() { QMap<QString, QTextCodec *> codecMap; QRegExp iso8859RegExp("ISO[- ]8859-([0-9]+).*"); foreach (int mib, QTextCodec::availableMibs()) { QTextCodec *codec = QTextCodec::codecForMib(mib); QString sortKey = codec->name().toUpper(); int rank; if (sortKey.startsWith("UTF-8")) { rank = 1; } else if (sortKey.startsWith("UTF-16")) { rank = 2; } else if (iso8859RegExp.exactMatch(sortKey)) { if (iso8859RegExp.cap(1).size() == 1) rank = 3; else rank = 4; } else { rank = 5; } sortKey.prepend(QChar('0' + rank)); codecMap.insert(sortKey, codec); } m_codecs = codecMap.values(); } void LiteEditor::createToolBars() { m_editToolBar = new QToolBar("editor",m_widget); m_editToolBar->setIconSize(LiteApi::getToolBarIconSize(m_liteApp)); m_editToolBar->setVisible(m_liteApp->settings()->value(EDITOR_TOOLBAR_VISIBLE,true).toBool()); // m_editNavBar = new QToolBar("editor.nav",m_widget); // m_editNavBar->setIconSize(LiteApi::getToolBarIconSize(m_liteApp)); m_navBar = new NavigateBar(m_liteApp,this); m_navBar->createToolBar("editor.nav",m_widget); m_navBar->toolBar()->setVisible(m_liteApp->settings()->value(EDITOR_NAVBAR_VISIBLE,true).toBool()); //editor toolbar // m_editToolBar->addSeparator(); m_editToolBar->addAction(m_undoAct); m_editToolBar->addAction(m_redoAct); m_editToolBar->addSeparator(); m_editToolBar->addAction(m_cutAct); m_editToolBar->addAction(m_copyAct); m_editToolBar->addAction(m_pasteAct); #ifdef LITEEDITOR_FIND m_findComboBox = new QComboBox(m_widget); m_findComboBox->setEditable(true); m_findComboBox->setMinimumWidth(120); m_findComboBox->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred); m_toolBar->addWidget(m_findComboBox); m_toolBar->addSeparator(); connect(m_findComboBox->lineEdit(),SIGNAL(returnPressed()),this,SLOT(findNextText())); #endif //info toolbar m_editToolBar->addSeparator(); //add lock info m_editToolBar->addAction(m_lockAct); m_editToolBar->addAction(m_unlockAct); //add over info QLabel *overInfo = new QLabel("[Over]"); m_overInfoAct = m_editToolBar->addWidget(overInfo); m_overInfoAct->setVisible(false); //add line info // m_lineInfo = new QLabelEx("000:000"); // m_editToolBar->addWidget(m_lineInfo); //add close //m_closeEditorAct = new QAction(QIcon("icon:images/close.png"),tr("Close Document"),this); //m_infoToolBar->addAction(m_closeEditorAct); } void LiteEditor::createMenu() { m_editMenu = new QMenu(m_editorWidget); m_contextMenu = new QMenu(m_editorWidget); //editor menu m_editMenu->addAction(m_undoAct); m_editMenu->addAction(m_redoAct); m_editMenu->addSeparator(); m_editMenu->addAction(m_cutAct); m_editMenu->addAction(m_copyAct); m_editMenu->addAction(m_pasteAct); m_editMenu->addSeparator(); m_editMenu->addAction(m_selectAllAct); m_editMenu->addSeparator(); QMenu *subMenu = m_editMenu->addMenu(tr("Advanced")); subMenu->addAction(m_duplicateAct); subMenu->addAction(m_copyLineAct); subMenu->addAction(m_deleteLineAct); subMenu->addAction(m_cutLineAct); subMenu->addAction(m_moveLineUpAction); subMenu->addAction(m_moveLineDownAction); subMenu->addAction(m_copyLineUpAction); subMenu->addAction(m_copyLineDownAction); subMenu->addAction(m_joinLinesAction); subMenu->addAction(m_insertLineBeforeAct); subMenu->addAction(m_insertLineAfterAct); subMenu->addSeparator(); subMenu->addAction(m_cleanWhitespaceAct); subMenu->addSeparator(); subMenu->addAction(m_selectBlockAct); subMenu->addAction(m_selectAllAct); #ifndef QT_NO_PRINTER subMenu->addSeparator(); subMenu->addAction(m_exportPdfAct); subMenu->addSeparator(); subMenu->addAction(m_filePrintPreviewAct); subMenu->addAction(m_filePrintAct); #endif subMenu = m_editMenu->addMenu(tr("Goto")); subMenu->addAction(m_gotoLineAct); subMenu->addAction(m_gotoMatchBraceAct); subMenu->addSeparator(); subMenu->addAction(m_gotoPrevBlockAct); subMenu->addAction(m_gotoNextBlockAct); subMenu->addAction(m_gotoLineStartAct); subMenu->addAction(m_gotoLineEndAct); subMenu->addAction(m_gotoPrevLineAct); subMenu->addAction(m_gotoNextLineAct); subMenu->addAction(m_gotoPrevCharacterAct); subMenu->addAction(m_gotoNextCharacterAct); subMenu->addAction(m_gotoPrevWordAct); subMenu->addAction(m_gotoNextWordAct); subMenu->addAction(m_gotoDocStartAct); subMenu->addAction(m_gotoDocEndAct); subMenu = m_editMenu->addMenu(tr("Convert Case")); subMenu->addAction(m_convertCaseTitleAct); subMenu->addAction(m_convertCaseUpperAct); subMenu->addAction(m_convertCaseLowerAct); subMenu->addAction(m_convertCaseSwapAct); subMenu = m_editMenu->addMenu(tr("Convert Tab")); subMenu->addAction(m_convertTabToSpaces); subMenu->addAction(m_convertSpacesToTab); subMenu = m_editMenu->addMenu(tr("Code Folding")); subMenu->addAction(m_foldAct); subMenu->addAction(m_unfoldAct); subMenu->addAction(m_foldAllAct); subMenu->addAction(m_unfoldAllAct); subMenu = m_editMenu->addMenu(tr("Settings")); subMenu->menuAction()->setMenuRole(QAction::NoRole); subMenu->addAction(m_visualizeWhitespaceAct); subMenu->addSeparator(); subMenu->addAction(m_mimeLineWrapAct); subMenu->addAction(m_mimeTabToSpacesAct); subMenu->addSeparator(); subMenu->addAction(m_increaseFontSizeAct); subMenu->addAction(m_decreaseFontSizeAct); subMenu->addAction(m_resetFontSizeAct); subMenu->addSeparator(); subMenu->addAction(m_lineEndingWindowAct); subMenu->addAction(m_lineEndingUnixAct); m_editMenu->addSeparator(); m_editMenu->addAction(m_codeCompleteAct); m_editMenu->addSeparator(); m_editMenu->addAction(m_commentAct); m_editMenu->addAction(m_blockCommentAct); m_editMenu->addAction(m_autoIndentAct); //context menu m_contextMenu->addAction(m_cutAct); m_contextMenu->addAction(m_copyAct); m_contextMenu->addAction(m_pasteAct); m_contextMenu->addSeparator(); subMenu = m_contextMenu->addMenu(tr("Advanced")); subMenu->addAction(m_duplicateAct); subMenu->addAction(m_copyLineAct); subMenu->addAction(m_deleteLineAct); subMenu->addAction(m_cutLineAct); subMenu->addAction(m_moveLineUpAction); subMenu->addAction(m_moveLineDownAction); subMenu->addAction(m_copyLineUpAction); subMenu->addAction(m_copyLineDownAction); subMenu->addAction(m_joinLinesAction); subMenu->addAction(m_insertLineBeforeAct); subMenu->addAction(m_insertLineAfterAct); subMenu->addSeparator(); subMenu->addAction(m_cleanWhitespaceAct); subMenu->addSeparator(); subMenu->addAction(m_selectBlockAct); subMenu->addAction(m_selectAllAct); subMenu = m_contextMenu->addMenu(tr("Goto")); subMenu->addAction(m_gotoLineAct); subMenu->addAction(m_gotoMatchBraceAct); subMenu->addSeparator(); subMenu->addAction(m_gotoPrevBlockAct); subMenu->addAction(m_gotoNextBlockAct); subMenu->addAction(m_gotoLineStartAct); subMenu->addAction(m_gotoLineEndAct); subMenu->addAction(m_gotoPrevLineAct); subMenu->addAction(m_gotoNextLineAct); subMenu->addAction(m_gotoPrevCharacterAct); subMenu->addAction(m_gotoNextCharacterAct); subMenu->addAction(m_gotoPrevWordAct); subMenu->addAction(m_gotoNextWordAct); subMenu->addAction(m_gotoDocStartAct); subMenu->addAction(m_gotoDocEndAct); subMenu = m_contextMenu->addMenu(tr("Convert Case")); subMenu->addAction(m_convertCaseTitleAct); subMenu->addAction(m_convertCaseUpperAct); subMenu->addAction(m_convertCaseLowerAct); subMenu->addAction(m_convertCaseSwapAct); subMenu = m_contextMenu->addMenu(tr("Convert Tab")); subMenu->addAction(m_convertTabToSpaces); subMenu->addAction(m_convertSpacesToTab); subMenu = m_contextMenu->addMenu(tr("Code Folding")); subMenu->addAction(m_foldAct); subMenu->addAction(m_unfoldAct); subMenu->addAction(m_foldAllAct); subMenu->addAction(m_unfoldAllAct); subMenu = m_contextMenu->addMenu(tr("Settings")); subMenu->menuAction()->setMenuRole(QAction::NoRole); subMenu->addAction(m_visualizeWhitespaceAct); subMenu->addSeparator(); subMenu->addAction(m_mimeLineWrapAct); subMenu->addAction(m_mimeTabToSpacesAct); subMenu->addSeparator(); subMenu->addAction(m_increaseFontSizeAct); subMenu->addAction(m_decreaseFontSizeAct); subMenu->addAction(m_resetFontSizeAct); subMenu->addSeparator(); subMenu->addAction(m_lineEndingWindowAct); subMenu->addAction(m_lineEndingUnixAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_commentAct); m_contextMenu->addAction(m_blockCommentAct); m_contextMenu->addAction(m_autoIndentAct); } #ifdef LITEEDITOR_FIND void LiteEditor::findNextText() { QString text = m_findComboBox->lineEdit()->text(); if (text.isEmpty()) { return; } m_editorWidget->find(text); } #endif LiteApi::IExtension *LiteEditor::extension() { return m_extension; } QWidget *LiteEditor::widget() { return m_widget; } QString LiteEditor::name() const { return QFileInfo(m_file->filePath()).fileName(); } QIcon LiteEditor::icon() const { return QIcon(); } static QString escaped(const QString &text) { #if QT_VERSION >= 0x050000 return text.toHtmlEscaped(); #else return Qt::escape(text); #endif } void LiteEditor::initLoad() { m_editorWidget->initLoadDocument(); updateEditorInfo(); if (m_file->filePath().isEmpty()) { return; } m_navBar->LoadPath(m_file->filePath()); } void LiteEditor::updateEditorInfo() { setReadOnly(m_file->isReadOnly()); m_lineEndingUnixAct->setChecked(m_file->isLineEndUnix()); m_lineEndingWindowAct->setChecked(!m_file->isLineEndUnix()); editPositionChanged(); } bool LiteEditor::createNew(const QString &contents, const QString &mimeType) { m_editorWidget->setPlainText(contents); m_file->setMimeType(mimeType); m_file->setLineEndUnix(true); initLoad(); return true; } bool LiteEditor::open(const QString &fileName,const QString &mimeType) { QString outText; bool success = m_file->loadText(fileName,mimeType,outText); if (success) { m_document->setPlainText(outText); initLoad(); } return success; } bool LiteEditor::reload() { // QByteArray state = this->saveState(); QString outText; bool success = m_file->loadText(filePath(),mimeType(),outText); if (success) { loadTextUseDiff(outText); m_document->setModified(false); this->setNavigateHead(LiteApi::EditorNavigateReload,tr("Reload File")); updateEditorInfo(); emit reloaded(); } return success; } bool LiteEditor::save() { if (m_bReadOnly) { return false; } return saveAs(m_file->filePath()); } bool LiteEditor::saveAs(const QString &fileName) { if (m_cleanWhiteSpace) { m_editorWidget->cleanWhitespace(true); } if (m_cleanCompleterCache) { m_completer->clearTemp(); } bool b = m_file->saveText(fileName, m_document->toPlainText()); if (b) { m_editorWidget->document()->setModified(false); } return b; } void LiteEditor::setReadOnly(bool b) { m_lockAct->setVisible(b); m_unlockAct->setVisible(!b); m_bReadOnly = b; m_editorWidget->setReadOnly(m_file->isBinary()); // m_editorWidget->setReadOnly(b); } bool LiteEditor::isReadOnly() const { return m_bReadOnly; } bool LiteEditor::isModified() const { if (!m_file) { return false; } return m_editorWidget->document()->isModified(); } QString LiteEditor::filePath() const { if (!m_file) { return QString(); } return m_file->filePath(); } QString LiteEditor::mimeType() const { if (!m_file) { return QString(); } return m_file->mimeType(); } LiteApi::IFile *LiteEditor::file() { return m_file; } int LiteEditor::line() const { return m_editorWidget->textCursor().blockNumber(); } int LiteEditor::column() const { return m_editorWidget->textCursor().columnNumber(); } int LiteEditor::utf8Position(bool realFile, int pos) const { QTextCursor cur = m_editorWidget->textCursor(); QString src = cur.document()->toPlainText().left(pos >= 0 ? pos : cur.position()); int offset = 0; if (realFile && m_file->isLineEndWindow()) { offset = cur.blockNumber(); } return src.toUtf8().length()+offset+1; } QByteArray LiteEditor::utf8Data() const { QString src = m_editorWidget->document()->toPlainText(); // if (m_file->m_lineTerminatorMode == LiteEditorFile::CRLFLineTerminator) { // src = src.replace("\n","\r\n"); // } return src.toUtf8(); } void LiteEditor::setLineWrap(bool wrap) { m_editorWidget->setLineWrap(wrap); m_mimeLineWrapAct->setChecked(wrap); } bool LiteEditor::isLineWrap() const { return m_editorWidget->isLineWrap(); } void LiteEditor::gotoLine(int blockNumber, int column, bool center, int selection) { m_editorWidget->setFocus(); m_editorWidget->gotoLine(blockNumber,column,center,selection); } int LiteEditor::position(LiteApi::ITextEditor::PositionOperation posOp, int at) const { QTextCursor tc = m_editorWidget->textCursor(); if (at != -1) tc.setPosition(at); if (posOp == ITextEditor::Current) return tc.position(); switch (posOp) { case ITextEditor::EndOfLine: tc.movePosition(QTextCursor::EndOfLine); return tc.position(); case ITextEditor::StartOfLine: tc.movePosition(QTextCursor::StartOfLine); return tc.position(); case ITextEditor::Anchor: if (tc.hasSelection()) return tc.anchor(); break; case ITextEditor::EndOfDoc: tc.movePosition(QTextCursor::End); return tc.position(); default: break; } return -1; } QString LiteEditor::textAt(int pos, int length) const { QTextCursor c = m_editorWidget->textCursor(); if (pos < 0) pos = 0; c.movePosition(QTextCursor::End); if (pos + length > c.position()) length = c.position() - pos; c.setPosition(pos); c.setPosition(pos + length, QTextCursor::KeepAnchor); return c.selectedText(); } QRect LiteEditor::cursorRect(int pos) const { QTextCursor tc = m_editorWidget->textCursor(); if (pos >= 0) tc.setPosition(pos); QRect result = m_editorWidget->cursorRect(tc); result.moveTo(m_editorWidget->viewport()->mapToGlobal(result.topLeft())); return result; } LiteEditorWidget *LiteEditor::editorWidget() const { return m_editorWidget; } QTextCursor LiteEditor::textCursor() const { return m_editorWidget->textCursor(); } void LiteEditor::applyOption(QString id) { if (id != OPTION_LITEEDITOR) { return; } bool autoIndent = m_liteApp->settings()->value(EDITOR_AUTOINDENT,true).toBool(); bool autoBraces0 = m_liteApp->settings()->value(EDITOR_AUTOBRACE0,true).toBool(); bool autoBraces1 = m_liteApp->settings()->value(EDITOR_AUTOBRACE1,true).toBool(); bool autoBraces2 = m_liteApp->settings()->value(EDITOR_AUTOBRACE2,true).toBool(); bool autoBraces3 = m_liteApp->settings()->value(EDITOR_AUTOBRACE3,true).toBool(); bool autoBraces4 = m_liteApp->settings()->value(EDITOR_AUTOBRACE4,true).toBool(); bool autoBraces5 = m_liteApp->settings()->value(EDITOR_AUTOBRACE5,true).toBool(); bool caseSensitive = m_liteApp->settings()->value(EDITOR_COMPLETER_CASESENSITIVE,false).toBool(); bool fuzzyCompleter = m_liteApp->settings()->value(EDITOR_COMPLETER_FUZZY,true).toBool(); bool lineNumberVisible = m_liteApp->settings()->value(EDITOR_LINENUMBERVISIBLE,true).toBool(); bool codeFoldVisible = m_liteApp->settings()->value(EDITOR_CODEFOLDVISIBLE,true).toBool(); bool rightLineVisible = m_liteApp->settings()->value(EDITOR_RIGHTLINEVISIBLE,true).toBool(); bool eofVisible = m_liteApp->settings()->value(EDITOR_EOFVISIBLE,false).toBool(); bool defaultWordWrap = m_liteApp->settings()->value(EDITOR_DEFAULTWORDWRAP,false).toBool(); bool indentLineVisible = m_liteApp->settings()->value(EDITOR_INDENTLINEVISIBLE,true).toBool(); bool wheelZooming = m_liteApp->settings()->value(EDITOR_WHEEL_SCROLL,true).toBool(); bool visualizeWhitespace = m_liteApp->settings()->value(EDITOR_VISUALIZEWHITESPACE,false).toBool(); int rightLineWidth = m_liteApp->settings()->value(EDITOR_RIGHTLINEWIDTH,80).toInt(); int min = m_liteApp->settings()->value(EDITOR_PREFIXLENGTH,1).toInt(); bool copyToHtml = m_liteApp->settings()->value(EDITOR_ENABLE_COPYTOHTML,true).toBool(); bool allowVscrollLastLine = m_liteApp->settings()->value(EDITOR_ALLOW_VSCROLL_LASTLINE,true).toBool(); m_cleanCompleterCache = m_liteApp->settings()->value(EDITOR_CLEAN_COMPLETERCACHE_SAVE,false).toBool(); m_cleanWhiteSpace = m_liteApp->settings()->value(EDITOR_CLEANWHITESPACEONSAVE,false).toBool(); m_offsetVisible = m_liteApp->settings()->value(EDITOR_OFFSETVISIBLE,false).toBool(); m_editorWidget->setAutoIndent(autoIndent); m_editorWidget->setAutoBraces0(autoBraces0); m_editorWidget->setAutoBraces1(autoBraces1); m_editorWidget->setAutoBraces2(autoBraces2); m_editorWidget->setAutoBraces3(autoBraces3); m_editorWidget->setAutoBraces4(autoBraces4); m_editorWidget->setAutoBraces5(autoBraces5); m_editorWidget->setLineNumberVisible(lineNumberVisible); m_editorWidget->setCodeFoldVisible(codeFoldVisible); m_editorWidget->setEofVisible(eofVisible); m_editorWidget->setIndentLineVisible(indentLineVisible); m_editorWidget->setRightLineVisible(rightLineVisible); m_editorWidget->setRightLineWidth(rightLineWidth); m_editorWidget->setScrollWheelZooming(wheelZooming); m_editorWidget->setVisualizeWhitespace(visualizeWhitespace); m_editorWidget->setCopyToHtml(copyToHtml); m_editorWidget->setAllowVscrollLastLine(allowVscrollLastLine); if (m_completer) { m_completer->setCaseSensitivity(caseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive); m_completer->setFuzzy(fuzzyCompleter); m_completer->setPrefixMin(min); } updateFont(); QString mime = this->m_file->mimeType(); m_editorWidget->setMimeType(mime); bool tabToSpace = false; int tabWidth = 4; LiteApi::IMimeType *im = m_liteApp->mimeTypeManager()->findMimeType(mime); if (im) { tabToSpace = im->tabToSpace(); tabWidth = im->tabWidth(); } bool linewrap = m_liteApp->settings()->value(MIMETYPE_LINEWRAP+mime,defaultWordWrap).toBool(); tabToSpace = m_liteApp->settings()->value(MIMETYPE_TABTOSPACE+mime,tabToSpace).toBool(); tabWidth = m_liteApp->settings()->value(MIMETYPE_TABWIDTH+mime,tabWidth).toInt(); this->setTabOption(tabWidth,tabToSpace); this->setLineWrap(linewrap); m_visualizeWhitespaceAct->setChecked(visualizeWhitespace); } void LiteEditor::updateTip(const QString &func,const QString &kind,const QString &info) { QString tip = m_editorWidget->textLexer()->fetchFunctionTip(func,kind,info); if (tip.isEmpty()) { return; } if (!m_funcTip) { m_funcTip = new FunctionTooltip(m_liteApp,this,m_editorWidget->textLexer(),20); } m_funcTip->showFunctionHint(this->position(),tip); } void LiteEditor::filePrintPreview() { #ifndef QT_NO_PRINTER QPrinter printer(QPrinter::HighResolution); QPrintPreviewDialog preview(&printer, m_widget); preview.resize(this->m_editorWidget->size()); connect(&preview, SIGNAL(paintRequested(QPrinter*)), SLOT(printPreview(QPrinter*))); preview.exec(); #endif } void LiteEditor::printPreview(QPrinter *printer) { #ifdef QT_NO_PRINTER Q_UNUSED(printer); #else QPlainTextEdit::LineWrapMode mode = m_editorWidget->lineWrapMode(); m_editorWidget->setLineWrapMode(QPlainTextEdit::WidgetWidth); m_editorWidget->print(printer); m_editorWidget->setLineWrapMode(mode); #endif } void LiteEditor::exportHtml() { QString title; if (m_file) { title = QFileInfo(m_file->filePath()).completeBaseName(); } QString fileName = QFileDialog::getSaveFileName(m_widget, tr("Export HTML"), title, "*.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; } QTextCursor cur = m_editorWidget->textCursor(); cur.select(QTextCursor::Document); file.write(m_editorWidget->cursorToHtml(cur).toUtf8()); file.close(); } } void LiteEditor::exportPdf() { #ifndef QT_NO_PRINTER //! [0] QString title; if (m_file) { title = QFileInfo(m_file->filePath()).completeBaseName(); } QString fileName = QFileDialog::getSaveFileName(m_widget, tr("Export PDF"), title, "*.pdf"); if (!fileName.isEmpty()) { if (QFileInfo(fileName).suffix().isEmpty()) { fileName.append(".pdf"); } QPrinter printer(QPrinter::HighResolution); printer.setOutputFormat(QPrinter::PdfFormat); printer.setOutputFileName(fileName); QPlainTextEdit::LineWrapMode mode = m_editorWidget->lineWrapMode(); m_editorWidget->setLineWrapMode(QPlainTextEdit::WidgetWidth); m_editorWidget->print(&printer); m_editorWidget->setLineWrapMode(mode); } //! [0] #endif } void LiteEditor::filePrint() { #ifndef QT_NO_PRINTER QPrinter printer(QPrinter::HighResolution); QPrintDialog *dlg = new QPrintDialog(&printer, m_widget); if (m_editorWidget->textCursor().hasSelection()) dlg->addEnabledOption(QAbstractPrintDialog::PrintSelection); dlg->setWindowTitle(tr("Print Document")); if (dlg->exec() == QDialog::Accepted) { QPlainTextEdit::LineWrapMode mode = m_editorWidget->lineWrapMode(); m_editorWidget->setLineWrapMode(QPlainTextEdit::WidgetWidth); m_editorWidget->print(&printer); m_editorWidget->setLineWrapMode(mode); } delete dlg; #endif } void LiteEditor::codecComboBoxChanged(QString codec) { if (!m_file) { return; } if (m_editorWidget->document()->isModified()) { QString text = QString(tr("Do you want to permanently discard unsaved modifications and reload %1?")).arg(m_file->filePath()); int ret = QMessageBox::question(m_liteApp->mainWindow(),"Unsaved Modifications",text,QMessageBox::Yes|QMessageBox::No); if (ret != QMessageBox::Yes) { return; } } QString outText; bool success = m_file->reloadTextByCodec(codec,outText); if (success) { this->loadTextUseDiff(outText); m_document->setModified(false); updateEditorInfo(); emit reloaded(); } return; } void LiteEditor::editPositionChanged() { QTextCursor cur = m_editorWidget->textCursor(); //QString src = cur.document()->toPlainText().left(cur.position()); // int offset = 0; // if (m_file->isLineEndWindow()) { // offset = cur.blockNumber(); // } QStringList infos; infos << QString("%1,%2").arg(cur.blockNumber()+1,3).arg(cur.columnNumber()+1,3); if (m_offsetVisible) { infos << QString("%1").arg(this->utf8Position(true),3); } if (m_bReadOnly) { infos << QString(tr("ReadOnly")); } infos << m_file->textCodec(); if (m_file->isLineEndUnix()) { infos << "LF"; } else { infos << "CRLF"; } m_liteApp->editorManager()->updateEditInfo(infos.join(" | ")); } void LiteEditor::gotoLine() { LiteApi::IQuickOpenManager *mgr = LiteApi::getQuickOpenManager(m_liteApp); if (mgr) { LiteApi::IQuickOpen *p = mgr->findById("quickopen/lines"); if (p) { mgr->setCurrentFilter(p); mgr->showPopup(); return; } } int min = 1; int max = m_editorWidget->document()->blockCount(); int old = m_editorWidget->textCursor().blockNumber()+1; bool ok = false; int v = QInputDialog::getInt(this->m_widget,tr("Go To Line"),tr("Line: ")+QString("%1-%2").arg(min).arg(max),old,min,max,1,&ok); if (!ok) { return; } if (v == old) { return; } m_liteApp->editorManager()->addNavigationHistory(); this->gotoLine(v-1,0,true); } QString LiteEditor::textCodec() const { return m_file->textCodec(); } void LiteEditor::setTextCodec(const QString &codec) { QString outText; bool success = m_file->reloadTextByCodec(codec,outText); if (success) { this->loadTextUseDiff(outText); m_document->setModified(false); updateEditorInfo(); emit reloaded(); } } QByteArray LiteEditor::saveState() const { return m_editorWidget->saveState(); } bool LiteEditor::restoreState(const QByteArray &array) { return m_editorWidget->restoreState(array); } void LiteEditor::navigationStateChanged(const QByteArray &state) { m_liteApp->editorManager()->addNavigationHistory(this,state); } void LiteEditor::onActive() { m_editorWidget->setFocus(); //clipbordDataChanged(); editPositionChanged(); //m_editorWidget->saveCurrentCursorPositionForNavigation(); } void LiteEditor::setFindOption(LiteApi::FindOption *opt) { m_editorWidget->setFindOption(opt); } void LiteEditor::setSpellCheckZoneDontComplete(bool b) { m_editorWidget->setSpellCheckZoneDontComplete(b); } void LiteEditor::setNavigateHead(LiteApi::EditorNaviagteType type, const QString &msg) { m_editorWidget->setNavigateHead(type,msg); } void LiteEditor::insertNavigateMark(int line, LiteApi::EditorNaviagteType type, const QString &msg, const QString &tag, int offset, int selection) { m_editorWidget->insertNavigateMark(line,type,msg, tag,offset, selection); } void LiteEditor::clearNavigateMarak(int /*line*/) { } void LiteEditor::clearAllNavigateMarks() { m_editorWidget->clearAllNavigateMarks(); } void LiteEditor::clearAllNavigateMark(LiteApi::EditorNaviagteType types, const QString &tag) { m_editorWidget->clearAllNavigateMark(types, tag); } void LiteEditor::showLink(const LiteApi::Link &link) { m_editorWidget->showLink(link); } void LiteEditor::clearLink() { m_editorWidget->clearLink(); } void LiteEditor::setTabOption(int tabSize, bool tabToSpace) { m_editorWidget->setTabSize(tabSize); m_editorWidget->setTabToSpaces(tabToSpace); if (m_syntax) { m_syntax->setTabSize(tabSize); } m_mimeTabToSpacesAct->setChecked(tabToSpace); } void LiteEditor::setEnableAutoIndentAction(bool b) { m_autoIndentAct->setVisible(b); } bool LiteEditor::isLineEndUnix() const { return m_file->isLineEndUnix(); } void LiteEditor::setLineEndUnix(bool b) { if (m_file->setLineEndUnix(b)) { m_editorWidget->document()->setModified(true); m_liteApp->editorManager()->saveEditor(this,false); this->updateEditorInfo(); } } void LiteEditor::showToolTipInfo(const QPoint &pos, const QString &text) { m_editorWidget->showToolTipInfo(pos,text); } void LiteEditor::loadDiff(const QString &diff) { if (diff.isEmpty()) { return; } QByteArray state = saveState(); QTextCursor cur = m_editorWidget->textCursor(); cur.beginEditBlock(); EditorUtil::loadDiff(cur,diff); cur.endEditBlock(); m_editorWidget->setTextCursor(cur); restoreState(state); } void LiteEditor::loadTextUseDiff(const QString &text) { QString diff = EditorUtil::unifiedDiffText(m_document->toPlainText(),text); loadDiff(diff); } QMenu *LiteEditor::editorMenu() const { return m_editMenu; } bool LiteEditor::enableSyntax() const { QSizeF sz = m_editorWidget->document()->size(); if (sz.width() > 4096) { m_liteApp->appendLog("LiteEditor",QString("document line too long %1(max line length %2), disable syntax!").arg(this->filePath()).arg(sz.width()),true); return false; } return true; } void LiteEditor::selectNextParam() { QTextCursor cur = m_editorWidget->textCursor(); int pos = cur.position(); if (cur.hasSelection()) { pos = cur.selectionEnd(); } QTextBlock block = cur.block(); int offset = pos-block.position(); QRegExp reg("[\\,\\(\\)\\.\\s](\\s*)([\"\'\\w]+)"); int index = reg.indexIn(block.text().mid(offset)); if (index >= 0) { //qDebug() << reg.capturedTexts(); int start = block.position()+offset+index+1+reg.cap(1).length(); cur.setPosition(start); cur.movePosition(QTextCursor::Right,QTextCursor::KeepAnchor,reg.cap(2).length()); m_editorWidget->setTextCursor(cur); } } void LiteEditor::increaseFontSize() { this->requestFontZoom(10); } void LiteEditor::decreaseFontSize() { this->requestFontZoom(-10); } void LiteEditor::resetFontSize() { int fontSize = m_liteApp->settings()->value(EDITOR_FONTSIZE,12).toInt(); m_liteApp->settings()->setValue(EDITOR_FONTZOOM,100); QFont font = m_editorWidget->font(); font.setPointSize(fontSize); m_editorWidget->updateFont(font); this->sendUpdateFont(); } void LiteEditor::comment() { if (!m_syntax) { return; } TextEditor::SyntaxComment comment = m_syntax->comment(); Utils::CommentDefinition cd; cd.setAfterWhiteSpaces(comment.isCommentAfterWhiteSpaces); cd.setAfterWhiteSpacesAddSpace(comment.isCommentAfterWhiteSpacesAddSpace); cd.setSingleLine(comment.singleLineComment); cd.setMultiLineStart(comment.multiLineCommentStart); cd.setMultiLineEnd(comment.multiLineCommentEnd); Utils::unCommentSelection(m_editorWidget,Utils::AutoComment,cd); } void LiteEditor::blockComment() { } void LiteEditor::autoIndent() { m_editorWidget->autoIndent(); } void LiteEditor::toggledTabToSpaces(bool b) { m_liteApp->settings()->setValue(MIMETYPE_TABTOSPACE+this->mimeType(),b); m_liteApp->optionManager()->emitApplyOption(OPTION_LITEEDITOR); //m_editorWidget->setTabToSpaces(b); } void LiteEditor::toggledVisualizeWhitespace(bool b) { m_liteApp->settings()->setValue(EDITOR_VISUALIZEWHITESPACE,b); m_liteApp->optionManager()->emitApplyOption(OPTION_LITEEDITOR); //m_editorWidget->setVisualizeWhitespace(b); } void LiteEditor::toggledLineWrapMode(bool b) { m_liteApp->settings()->setValue(MIMETYPE_LINEWRAP+this->mimeType(),b); m_liteApp->optionManager()->emitApplyOption(OPTION_LITEEDITOR); } void LiteEditor::triggeredLineEnding(QAction *action) { this->setLineEndUnix(action == m_lineEndingUnixAct); } void LiteEditor::broadcast(const QString &module, const QString &id, const QVariant &param) { if (module == "liteeditor" && id == "font" && param != this->filePath()) { this->updateFont(); } else if (module == "liteeditor" && id == EDITOR_NAVBAR_VISIBLE) { m_navBar->toolBar()->setVisible(param.toBool()); } else if (module == "liteeditor" && id == EDITOR_TOOLBAR_VISIBLE) { m_editToolBar->setVisible(param.toBool()); } } void LiteEditor::updateFont() { #if defined(Q_OS_WIN) QString fontFamily = m_liteApp->settings()->value(EDITOR_FAMILY,"Courier").toString(); #elif defined(Q_OS_LINUX) QString fontFamily = m_liteApp->settings()->value(EDITOR_FAMILY,"Monospace").toString(); #elif defined(Q_OS_MAC) QString fontFamily = m_liteApp->settings()->value(EDITOR_FAMILY,"Menlo").toString(); #else QString fontFamily = m_liteApp->settings()->value(EDITOR_FAMILY,"Monospace").toString(); #endif int fontSize = m_liteApp->settings()->value(EDITOR_FONTSIZE,12).toInt(); int fontZoom = m_liteApp->settings()->value(EDITOR_FONTZOOM,100).toInt(); bool antialias = m_liteApp->settings()->value(EDITOR_ANTIALIAS,true).toBool(); QFont font = m_editorWidget->font(); font.setFamily(fontFamily); font.setPointSize(fontSize*fontZoom/100.0); if (antialias) { font.setStyleStrategy(QFont::PreferAntialias); } else { font.setStyleStrategy(QFont::NoAntialias); } m_editorWidget->updateFont(font); } void LiteEditor::sendUpdateFont() { m_liteApp->sendBroadcast("liteeditor","font",this->filePath()); } QLabelEx::QLabelEx(const QString &text, QWidget *parent) : QLabel(text,parent) { } void QLabelEx::mouseDoubleClickEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { emit doubleClickEvent(); } } void LiteEditor::requestFontZoom(int zoom) { int fontSize = m_liteApp->settings()->value(EDITOR_FONTSIZE,12).toInt(); int fontZoom = m_liteApp->settings()->value(EDITOR_FONTZOOM,100).toInt(); fontZoom += zoom; if (fontZoom <= 10) { return; } m_liteApp->settings()->setValue(EDITOR_FONTZOOM,fontZoom); QFont font = m_editorWidget->font(); font.setPointSize(fontSize*fontZoom/100.0); m_editorWidget->updateFont(font); this->sendUpdateFont(); } void LiteEditor::loadColorStyleScheme() { const ColorStyleScheme *colorScheme = m_liteApp->editorManager()->colorStyleScheme(); const ColorStyle *extra = colorScheme->findStyle("Extra"); const ColorStyle *indentLine = colorScheme->findStyle("IndentLine"); const ColorStyle *text = colorScheme->findStyle("Text"); const ColorStyle *selection = colorScheme->findStyle("Selection"); const ColorStyle *currentLine = colorScheme->findStyle("CurrentLine"); const ColorStyle *matchBrackets = colorScheme->findStyle("MatchBrackets"); const ColorStyle *visualWhitespace = colorScheme->findStyle("VisualWhitespace"); if (extra) { m_editorWidget->setExtraColor(extra->foregound(),extra->background()); } if (indentLine) { m_editorWidget->setIndentLineColor(indentLine->foregound()); } if (currentLine) { m_editorWidget->setCurrentLineColor(currentLine->background()); } if (matchBrackets) { m_editorWidget->setMatchBracketsColor(matchBrackets->background()); } if (visualWhitespace) { m_editorWidget->setVisualizeWhitespaceColor(visualWhitespace->foregound()); } QPalette p = m_defEditorPalette; if (text) { if (text->foregound().isValid()) { p.setColor(QPalette::Text,text->foregound()); p.setColor(QPalette::Foreground, text->foregound()); } if (text->background().isValid()) { p.setColor(QPalette::Base, text->background()); } } if (selection) { if (selection->foregound().isValid()) { p.setColor(QPalette::HighlightedText, selection->foregound()); } if (selection->background().isValid()) { p.setColor(QPalette::Highlight, selection->background()); } p.setBrush(QPalette::Inactive, QPalette::Highlight, p.highlight()); p.setBrush(QPalette::Inactive, QPalette::HighlightedText, p.highlightedText()); } QString sheet = QString("QPlainTextEdit{color:%1;background-color:%2;selection-color:%3;selection-background-color:%4;}") .arg(p.text().color().name()) .arg(p.base().color().name()) .arg(p.highlightedText().color().name()) .arg(p.highlight().color().name()); m_editorWidget->setPalette(p); //#ifdef Q_OS_MAC // #if QT_VERSION >= 0x050000 // m_editorWidget->setStyleSheet(sheet); // #else // if (QSysInfo::MacintoshVersion <= QSysInfo::MV_10_8) { // m_editorWidget->setStyleSheet(sheet); // } // #endif //#else m_editorWidget->setStyleSheet(sheet); //#endif emit colorStyleChanged(); } EditContext::EditContext(LiteEditor *editor, QObject *parent) : LiteApi::IEditContext(parent), m_editor(editor) { } QWidget *EditContext::focusWidget() const { return m_editor->editorWidget(); } QMenu *EditContext::focusMenu() const { return m_editor->editorMenu(); } QToolBar *EditContext::focusToolBar() const { return 0;//m_editor->m_editToolBar; }
62,960
C++
.cpp
1,491
36.340711
197
0.694461
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,479
liteeditorfilefactory.cpp
visualfc_liteide/liteidex/src/plugins/liteeditor/liteeditorfilefactory.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: liteeditorfilefactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "liteeditorfilefactory.h" #include "liteeditor.h" #include "liteeditorwidget.h" #include "litewordcompleter.h" #include "editorapimanager.h" #include "liteeditormark.h" #include "liteeditor_global.h" #include "katehighlighterfactory.h" #include "katetextlexer.h" #include "liteeditorapi/liteeditorapi.h" #include <QDir> #include <QFileInfo> #include "mimetype/mimetype.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 LiteEditorFileFactory::LiteEditorFileFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IEditorFactory(parent), m_liteApp(app) { m_mimeTypes.append("text/x-gosrc"); m_mimeTypes.append("text/x-lua"); m_mimeTypes.append("liteide/default.editor"); m_highlighterManager = new HighlighterManager(this); if (m_highlighterManager->initWithApp(app)) { m_liteApp->extension()->addObject("LiteApi.IHighlighterManager",m_highlighterManager); QDir dir(m_liteApp->resourcePath()+"/liteeditor/kate"); if (dir.exists()) { KateHighlighterFactory *factory = new KateHighlighterFactory(this); factory->loadPath(dir.absolutePath()); m_highlighterManager->addFactory(factory); KateHighlighter *kate = factory->kate(); foreach (QString type, kate->mimeTypes()) { if (!m_liteApp->mimeTypeManager()->findMimeType(type)) { MimeType *mimeType = new MimeType; mimeType->setType(type); foreach(QString pattern, kate->mimeTypePatterns(type)) { mimeType->appendGlobPatterns(pattern); } mimeType->setComment(kate->mimeTypeName(type)); m_liteApp->mimeTypeManager()->addMimeType(mimeType); } m_mimeTypes.append(type); } } } m_mimeTypes.removeDuplicates(); m_wordApiManager = new EditorApiManager(this); if (m_wordApiManager->initWithApp(app)) { m_liteApp->extension()->addObject("LiteApi.IWordApiManager",m_wordApiManager); m_wordApiManager->load(m_liteApp->resourcePath()+"/packages"); } m_markManager = new LiteEditorMarkManager(this); if (m_markManager->initWithApp(app)) { m_liteApp->extension()->addObject("LiteApi.IEditorMarkManager",m_markManager); } } QStringList LiteEditorFileFactory::mimeTypes() const { return m_mimeTypes; } void LiteEditorFileFactory::colorStyleChanged() { LiteEditor *editor = static_cast<LiteEditor *>(sender()); if (!editor) { return; } TextEditor::SyntaxHighlighter *h = editor->syntaxHighlighter(); if (h) { m_highlighterManager->setColorStyle(h,m_liteApp->editorManager()->colorStyleScheme()); } } void LiteEditorFileFactory::tabSettingChanged(int tabSize) { LiteEditor *editor = static_cast<LiteEditor *>(sender()); if (!editor) { return; } TextEditor::SyntaxHighlighter *h = editor->syntaxHighlighter(); if (h) { m_highlighterManager->setTabSize(h,tabSize); } } LiteApi::IEditor *LiteEditorFileFactory::open(const QString &fileName, const QString &mimeType) { // m_liteApp->editorManager()->cutForwardNavigationHistory(); //m_liteApp->editorManager()->addNavigationHistory(); LiteEditor *editor = new LiteEditor(m_liteApp); editor->setEditorMark(new LiteEditorMark(m_markManager,editor)); if (!editor->open(fileName,mimeType)) { delete editor; return 0; } return setupEditor(editor,mimeType); } LiteApi::IEditor *LiteEditorFileFactory::create(const QString &contents, const QString &mimeType) { LiteEditor *editor = new LiteEditor(m_liteApp); editor->setEditorMark(new LiteEditorMark(m_markManager,editor)); if (!editor->createNew(contents,mimeType)) { delete editor; return 0; } return setupEditor(editor,mimeType); } LiteApi::IEditor *LiteEditorFileFactory::setupEditor(LiteEditor *editor, const QString &mimeType) { QTextDocument *doc = editor->document(); LiteApi::IHighlighterFactory *factory = m_highlighterManager->findFactory(mimeType); if (factory && editor->enableSyntax()) { TextEditor::SyntaxHighlighter *h = factory->create(editor,doc,mimeType); if (h) { editor->setSyntaxHighlighter(h); editor->setTextLexer(new KateTextLexer(editor)); connect(editor,SIGNAL(colorStyleChanged()),this,SLOT(colorStyleChanged())); //connect(editor,SIGNAL(tabSettingChanged(int)),this,SLOT(tabSettingChanged(int))); connect(h,SIGNAL(foldIndentChanged(QTextBlock)),editor->editorWidget(),SLOT(foldIndentChanged(QTextBlock))); } } LiteWordCompleter *wordCompleter = new LiteWordCompleter(editor); editor->setCompleter(wordCompleter); if (wordCompleter) { LiteApi::IWordApi *wordApi = m_wordApiManager->findWordApi(mimeType); if (wordApi && wordApi->loadApi()) { QIcon icon("icon:liteeditor/images/keyword.png"); QIcon exp("icon:liteeditor/images/findword.png"); QIcon func("icon:liteeditor/images/func.png"); foreach(QString item, wordApi->wordList()) { int pos = item.indexOf("("); if (pos != -1) { wordCompleter->appendItemEx(item.left(pos).trimmed(),"func","func"+item.right(item.length()-pos),func,false); } else { wordCompleter->appendItemEx(item,"keyword",QString(""),icon,false); } } wordCompleter->appendItems(wordApi->expList(),"","",exp,false); wordCompleter->model()->sort(0); } } LiteApi::ISnippetApi *snippetApi = m_wordApiManager->findSnippetApi(mimeType); if (snippetApi && snippetApi->loadApi()) { foreach (LiteApi::Snippet *snippet, snippetApi->snippetList()) { wordCompleter->appendSnippetItem(snippet->Name,snippet->Info,snippet->Text); } } editor->applyOption(OPTION_LITEEDITOR); editor->loadColorStyleScheme(); return editor; } QString LiteEditorFileFactory::id() const { return "TextEditor"; } QString LiteEditorFileFactory::displayName() const { return tr("Text Editor"); } bool LiteEditorFileFactory::testMimeType(const QString &mimeType) { return true; }
7,724
C++
.cpp
190
34.489474
129
0.670526
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,480
codecompleter.cpp
visualfc_liteide/liteidex/src/plugins/liteeditor/codecompleter.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: codecompleter.cpp // Creator: visualfc <visualfc@gmail.com> #include "codecompleter.h" #include "faketooltip.h" #include <QApplication> #include <QListView> #include <QStandardItemModel> #include <QKeyEvent> #include <QVBoxLayout> #include <QScrollBar> #include <QSortFilterProxyModel> #include <QItemSelectionModel> #include <QDesktopWidget> #include <QItemDelegate> #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 CodeCompleter::CodeCompleter(QObject *parent) : QCompleter(parent) { this->setCompletionMode(QCompleter::UnfilteredPopupCompletion); this->setWrapAround(true); m_popup = new QListView; m_popup->setEditTriggers(QAbstractItemView::NoEditTriggers); m_popup->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_popup->setSelectionBehavior(QAbstractItemView::SelectRows); m_popup->setSelectionMode(QAbstractItemView::SingleSelection); m_popup->setModelColumn(0); this->setPopup(m_popup); m_proxy = new QSortFilterProxyModel(this); } CodeCompleter::~CodeCompleter() { } void CodeCompleter::setModel(QAbstractItemModel *c) { m_proxy->setSourceModel(c); QCompleter::setModel(m_proxy); } void CodeCompleter::setSeparator(const QString &separator) { m_seperator = separator; } void CodeCompleter::setCompletionPrefix(const QString &prefix) { QCompleter::setCompletionPrefix(prefix); } QString CodeCompleter::completionPrefix() const { return QCompleter::completionPrefix(); } void CodeCompleter::updateFilter() { } bool CodeCompleter::eventFilter(QObject *o, QEvent *e) { switch (e->type()) { case QEvent::KeyPress: { QKeyEvent *ke = static_cast<QKeyEvent *>(e); switch (ke->key()) { case Qt::Key_Up: if ( this->popup() && this->popup()->isVisible()) { QModelIndex index = this->popup()->currentIndex(); if (index.isValid() && (index.row() == 0)) { this->popup()->setCurrentIndex(this->popup()->model()->index(this->popup()->model()->rowCount()-1,0)); return true; } } break; case Qt::Key_Down: if (this->popup() && this->popup()->isVisible()) { QModelIndex index = this->popup()->currentIndex(); if (index.isValid() && (index.row() == this->popup()->model()->rowCount()-1)) { this->popup()->setCurrentIndex(this->popup()->model()->index(0,0)); return true; } } break; default: break; } break; } default: break; } return QCompleter::eventFilter(o,e); } QString CodeCompleter::separator() const { return m_seperator; } QStringList CodeCompleter::splitPath(const QString &path) const { if (m_seperator.isNull()) { return QCompleter::splitPath(path); } return path.split(m_seperator); } QString CodeCompleter::pathFromIndex(const QModelIndex &index) const { if (m_seperator.isNull()) { return QCompleter::pathFromIndex(index); } // navigate up and accumulate data QStringList dataList; for (QModelIndex i = index; i.isValid(); i = i.parent()) { dataList.prepend(model()->data(i, completionRole()).toString()); } return dataList.join(m_seperator); } class CodeCompleterInfo : public FakeToolTip { public: CodeCompleterInfo(QWidget *parent = 0) : FakeToolTip(parent), m_label(new QLabel(this)) { QVBoxLayout *layout = new QVBoxLayout(this); layout->setMargin(0); layout->setSpacing(0); layout->addWidget(m_label); // Limit horizontal width m_label->setSizePolicy(QSizePolicy::Fixed, m_label->sizePolicy().verticalPolicy()); m_label->setForegroundRole(QPalette::ToolTipText); m_label->setBackgroundRole(QPalette::ToolTipBase); } void setText(const QString &text) { m_label->setText(text); } // Workaround QTCREATORBUG-11653 void calculateMaximumWidth() { const QDesktopWidget *desktopWidget = QApplication::desktop(); const int desktopWidth = desktopWidget->isVirtualDesktop() ? desktopWidget->width() : desktopWidget->availableGeometry(desktopWidget->primaryScreen()).width(); const QMargins widgetMargins = contentsMargins(); const QMargins layoutMargins = layout()->contentsMargins(); const int margins = widgetMargins.left() + widgetMargins.right() + layoutMargins.left() + layoutMargins.right(); m_label->setMaximumWidth(desktopWidth - this->pos().x() - margins); } private: QLabel *m_label; }; CodeCompleterListView::CodeCompleterListView(QWidget *parent) : QListView(parent) { setVerticalScrollMode(QAbstractItemView::ScrollPerItem); m_infoFrame = new CodeCompleterInfo(this); m_infoTimer.setInterval(100); m_infoTimer.setSingleShot(true); connect(&m_infoTimer, SIGNAL(timeout()), SLOT(maybeShowInfoTip())); } void CodeCompleterListView::setModel(QAbstractItemModel *model) { QListView::setModel(model); connect(this->selectionModel(),SIGNAL(currentChanged(QModelIndex,QModelIndex)),&m_infoTimer,SLOT(start())); } QSize CodeCompleterListView::calculateSize() const { static const int maxVisibleItems = 10; // Determine size by calculating the space of the visible items const int visibleItems = qMin(model()->rowCount(), maxVisibleItems); const int firstVisibleRow = verticalScrollBar()->value(); const QStyleOptionViewItem &option = viewOptions(); QSize shint; for (int i = 0; i < visibleItems; ++i) { QSize tmp = itemDelegate()->sizeHint(option, model()->index(i + firstVisibleRow, 0)); if (shint.width() < tmp.width()) shint = tmp; } shint.rheight() *= visibleItems; return shint; } QPoint CodeCompleterListView::infoFramePos() const { const QRect &r = rectForIndex(currentIndex()); int xoffset = this->frameWidth()+3; int yoffset = this->frameWidth()-verticalOffset(); QScrollBar *vsb = this->verticalScrollBar(); if (vsb && vsb->isVisible()) xoffset += this->horizontalScrollBar()->sizeHint().height(); QPoint pt = this->mapToGlobal(r.topRight()); pt.rx() += xoffset; pt.ry() += yoffset; return pt; } void CodeCompleterListView::maybeShowInfoTip() { const QModelIndex &current = this->currentIndex(); if (!current.isValid()) return; if (!this->isVisible()) { if (m_infoFrame->isVisible()) { m_infoFrame->hide(); } m_infoTimer.setInterval(100); return; } const QString &infoTip = current.data(Qt::ToolTipRole).toString(); if (infoTip.isEmpty()) { m_infoFrame->hide(); return; } m_infoFrame->move(this->infoFramePos()); m_infoFrame->setText(infoTip); m_infoFrame->calculateMaximumWidth(); m_infoFrame->adjustSize(); m_infoFrame->show(); m_infoFrame->raise(); m_infoTimer.setInterval(0); } void CodeCompleterListView::hideEvent(QHideEvent *e) { m_infoFrame->hide(); QListView::hideEvent(e); } class CodeCompleterItemDelegate : public QItemDelegate { public: CodeCompleterItemDelegate(QAbstractItemView *view) : QItemDelegate(view), view(view) { } void paint(QPainter *p, const QStyleOptionViewItem& opt, const QModelIndex& idx) const { QStyleOptionViewItem optCopy = opt; optCopy.showDecorationSelected = true; if (view->currentIndex() == idx) optCopy.state |= QStyle::State_HasFocus; QItemDelegate::paint(p, optCopy, idx); } private: QAbstractItemView *view; }; CodeCompleterProxyModel::CodeCompleterProxyModel(QObject *parent) : QAbstractListModel(parent),m_model(0) { m_seperator = "::"; m_fuzzy = false; } CodeCompleterProxyModel::~CodeCompleterProxyModel() { clearItems(); } int CodeCompleterProxyModel::rowCount(const QModelIndex &) const { return m_items.size(); } QVariant CodeCompleterProxyModel::data(const QModelIndex &index, int role) const { if (index.row() >= m_items.size()) return QVariant(); QStandardItem *item = m_items[index.row()]; if (role == Qt::DisplayRole) { return item->text(); } return item->data(role); } void CodeCompleterProxyModel::setSourceModel(QStandardItemModel *model) { m_model = model; } void CodeCompleterProxyModel::setImportList(const QStringList &importList) { m_importList = importList; } QStandardItemModel *CodeCompleterProxyModel::sourceModel() const { return m_model; } QStandardItem *CodeCompleterProxyModel::item(const QModelIndex &index) const { if (index.row() >= m_items.size()) return 0; return m_items[index.row()]; } bool CodeCompleterProxyModel::splitFilter(const QString &filter, QModelIndex &parent, QString &prefix, const QString &sep) { if (filter.isEmpty()) { parent = QModelIndex(); prefix = filter; return true; } QStringList filterList = filter.split(sep); if (filterList.size() == 1) { parent = QModelIndex(); prefix = filter; return true; } prefix = filterList.last(); filterList.removeLast(); QStandardItem *root = 0; QStandardItem *item = 0; foreach (QString word, filterList) { item = 0; QModelIndex parent = m_model->indexFromItem(root); for (int i = 0; i < m_model->rowCount(parent); i++) { QModelIndex index = m_model->index(i,0,parent); QStandardItem *tmp = m_model->itemFromIndex(index); if (tmp->text() == word) { item = tmp; break; } } if (item == 0) { break; } root = item; } if (!item) { return false; } parent = m_model->indexFromItem(item); return true; } void CodeCompleterProxyModel::clearItems() { for (int i = 0; i < m_items.size(); i++) { delete m_items[i]; } m_items.clear(); } //copy ContentLessThan from QtCreator source struct ContentLessThan { ContentLessThan(const QString &prefix) : m_prefix(prefix) {} bool operator()(const QStandardItem *a, const QStandardItem *b) { // The order is case-insensitive in principle, but case-sensitive when this // would otherwise mean equality const QString &lowera = a->text().toLower(); const QString &lowerb = b->text().toLower(); if (!m_prefix.isEmpty()) { const QString &lowerprefix = m_prefix.toLower(); // All continuations should go before all fuzzy matches if (int diff = lowera.startsWith(lowerprefix) - lowerb.startsWith(lowerprefix)) return diff > 0; if (int diff = a->text().startsWith(m_prefix) - b->text().startsWith(m_prefix)) return diff > 0; } if (lowera == lowerb) return lessThan(a->text(), b->text()); else return lessThan(lowera, lowerb); } bool lessThan(const QString &a, const QString &b) { QString::const_iterator pa = a.begin(); QString::const_iterator pb = b.begin(); CharLessThan charLessThan; enum { Letter, SmallerNumber, BiggerNumber } state = Letter; for (; pa != a.end() && pb != b.end(); ++pa, ++pb) { if (*pa == *pb) continue; if (state != Letter) { if (!pa->isDigit() || !pb->isDigit()) break; } else if (pa->isDigit() && pb->isDigit()) { if (charLessThan(*pa, *pb)) state = SmallerNumber; else state = BiggerNumber; } else { return charLessThan(*pa, *pb); } } if (state == Letter) return pa == a.end() && pb != b.end(); if (pa != a.end() && pa->isDigit()) return false; //more digits if (pb != b.end() && pb->isDigit()) return true; //fewer digits return state == SmallerNumber; //same length, compare first different digit in the sequence } struct CharLessThan { bool operator()(const QChar &a, const QChar &b) { if (a == QLatin1Char('_')) return false; else if (b == QLatin1Char('_')) return true; else return a < b; } }; private: QString m_prefix; }; int CodeCompleterProxyModel::filter(const QString &filter, int cs, LiteApi::CompletionContext ctx) { if (!m_model) { return 0; } clearItems(); if (ctx == LiteApi::CompleterImportContext) { QIcon icon("icon:liteeditor/images/keyword.png"); if (filter.isEmpty()) { foreach (QString import, m_importList) { m_items.append(new QStandardItem(icon,import)); } return m_items.size(); } QList<QStandardItem*> best; QList<QStandardItem*> second; QList<QStandardItem*> other; int sep = filter.lastIndexOf("/"); QString root = filter.left(sep+1); QString check = filter.mid(sep+1); foreach (QString import, m_importList) { if (import.startsWith(root)) { QString text = import.mid(sep+1); if (text.contains("/")) { foreach (QString path, text.split("/")) { int n = path.indexOf(check); if (n == 0) { if (check == path) { best.append(new QStandardItem(icon,import)); } else { second.append(new QStandardItem(icon,import)); } break; } else if (n > 0) { other.append(new QStandardItem(icon,import)); break; } } } else { int n = text.indexOf(check); if (n == 0) { if (check == text) { best.append(new QStandardItem(icon,import)); } else { second.append(new QStandardItem(icon,import)); } } else if (n > 0) { other.append(new QStandardItem(icon,import)); } } } } qStableSort(best.begin(), best.end(), ContentLessThan(filter)); qStableSort(second.begin(), second.end(), ContentLessThan(filter)); qStableSort(other.begin(), other.end(), ContentLessThan(filter)); m_items.append(best); m_items.append(second); m_items.append(other); return m_items.size(); } QModelIndex parentIndex; QString prefix; if (!splitFilter(filter,parentIndex,prefix,m_seperator)) { return 0; } m_prefix = prefix; if (prefix.isEmpty()) { int count = m_model->rowCount(parentIndex); for (int i = 0; i < count; i++) { QModelIndex index = m_model->index(i,0,parentIndex); QStandardItem *item = m_model->itemFromIndex(index); m_items.append(item->clone()); } qStableSort(m_items.begin(), m_items.end(), ContentLessThan(prefix)); return m_items.size(); } //fuzzy completer if (m_fuzzy) { if (!prefix.isEmpty() && !( prefix[0].isLetter() || prefix[0] == '_') ) { return 0; } QString keyRegExp; if (!parentIndex.isValid()) { keyRegExp = "^"; } foreach (const QChar &c, prefix) { keyRegExp += c; keyRegExp += "[0-9a-z_]*"; } QRegExp regExp(keyRegExp); regExp.setCaseSensitivity(Qt::CaseInsensitive); int count = m_model->rowCount(parentIndex); QList<QStandardItem*> otherItems; for (int i = 0; i < count; i++) { QModelIndex index = m_model->index(i,0,parentIndex); QStandardItem *item = m_model->itemFromIndex(index); int n = regExp.indexIn(item->text()); if (n == 0) { m_items.append(item->clone()); } else if (n > 0) { otherItems.append(item->clone()); } } qStableSort(m_items.begin(), m_items.end(), ContentLessThan(prefix)); qStableSort(otherItems.begin(), otherItems.end(), ContentLessThan(prefix)); m_items.append(otherItems); return m_items.size(); } QString keyRegExp; keyRegExp += QLatin1Char('^'); bool first = true; const QLatin1String uppercaseWordContinuation("[a-z0-9_]*"); const QLatin1String lowercaseWordContinuation("(?:[a-zA-Z0-9]*_)?"); foreach (const QChar &c, prefix) { if (cs == LiteApi::CaseInsensitive || (cs == LiteApi::FirstLetterCaseSensitive && !first)) { keyRegExp += QLatin1String("(?:"); if (!first) keyRegExp += uppercaseWordContinuation; keyRegExp += QRegExp::escape(c.toUpper()); keyRegExp += QLatin1Char('|'); if (!first) keyRegExp += lowercaseWordContinuation; keyRegExp += QRegExp::escape(c.toLower()); keyRegExp += QLatin1Char(')'); } else { if (!first) { if (c.isUpper()) keyRegExp += uppercaseWordContinuation; else keyRegExp += lowercaseWordContinuation; } keyRegExp += QRegExp::escape(c); } first = false; } QRegExp regExp(keyRegExp); int count = m_model->rowCount(parentIndex); for (int i = 0; i < count; i++) { QModelIndex index = m_model->index(i,0,parentIndex); QStandardItem *item = m_model->itemFromIndex(index); if (regExp.indexIn(item->text()) == 0) { m_items.append(item->clone()); } } qStableSort(m_items.begin(), m_items.end(), ContentLessThan(prefix)); return m_items.size(); } void CodeCompleterProxyModel::setSeparator(const QString &separator) { m_seperator = separator; } QString CodeCompleterProxyModel::separator() const { return m_seperator; } void CodeCompleterProxyModel::setFuzzy(bool b) { m_fuzzy = b; } bool CodeCompleterProxyModel::isFuzzy() const { return m_fuzzy; } QString CodeCompleterProxyModel::lastPrefix() const { return m_prefix; } CodeCompleterEx::CodeCompleterEx(QObject *parent) : QObject(parent), m_widget(0) { maxVisibleItems = 10; m_eatFocusOut = true; m_hiddenBecauseNoMatch = false; m_cs = Qt::CaseInsensitive; m_ctx = LiteApi::CompleterCodeContext; m_wrap = true; m_popup = new CodeCompleterListView; m_popup->setUniformItemSizes(true); m_popup->setEditTriggers(QAbstractItemView::NoEditTriggers); m_popup->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); m_popup->setSelectionBehavior(QAbstractItemView::SelectRows); m_popup->setSelectionMode(QAbstractItemView::SingleSelection); m_popup->setItemDelegate(new CodeCompleterItemDelegate(m_popup)); m_popup->setModelColumn(0); m_popup->setParent(0, Qt::Popup); m_popup->setFocusPolicy(Qt::NoFocus); m_popup->installEventFilter(this); m_proxy = new CodeCompleterProxyModel(this); m_popup->setModel(m_proxy); QObject::connect(m_popup, SIGNAL(clicked(QModelIndex)), this, SLOT(completerActivated(QModelIndex))); QObject::connect(m_popup, SIGNAL(activated(QModelIndex)), m_popup, SLOT(hide())); } CodeCompleterEx::~CodeCompleterEx() { if (m_popup) { delete m_popup; } } void CodeCompleterEx::setModel(QStandardItemModel *c) { m_proxy->setSourceModel(c); } QAbstractItemModel *CodeCompleterEx::model() const { return m_proxy->sourceModel(); } void CodeCompleterEx::setImportList(const QStringList &importList) { m_proxy->setImportList(importList); } void CodeCompleterEx::setSeparator(const QString &separator) { m_proxy->setSeparator(separator); } QString CodeCompleterEx::separator() const { return m_proxy->separator(); } void CodeCompleterEx::setCompletionPrefix(const QString &prefix) { m_prefix = prefix; if (m_proxy->filter(prefix,m_cs,m_ctx) <= 0) { if (m_popup->isVisible()) { m_popup->close(); } return; } m_popup->reset(); } QString CodeCompleterEx::completionPrefix() const { return m_prefix; } QString CodeCompleterEx::lastPrefix() const { return m_proxy->lastPrefix(); } void CodeCompleterEx::setCompletionContext(LiteApi::CompletionContext ctx) { m_ctx = ctx; } LiteApi::CompletionContext CodeCompleterEx::completionContext() const { return m_ctx; } void CodeCompleterEx::updateFilter() { if (m_proxy->filter(m_prefix,m_cs) <= 0) { if (m_popup->isVisible()) { m_popup->close(); } return; } m_popup->reset(); } void CodeCompleterEx::complete(const QRect &rect) { if (m_proxy->rowCount() == 0) { return; } const QRect screen = QApplication::desktop()->availableGeometry(m_widget); Qt::LayoutDirection dir = m_widget->layoutDirection(); QPoint pos; int rh, w; int h = (m_popup->sizeHintForRow(0) * qMin(maxVisibleItems, m_popup->model()->rowCount()) + 3)+3; QScrollBar *hsb = m_popup->horizontalScrollBar(); if (hsb && hsb->isVisible()) h += m_popup->horizontalScrollBar()->sizeHint().height(); if (rect.isValid()) { rh = rect.height(); w = rect.width(); pos = m_widget->mapToGlobal(dir == Qt::RightToLeft ? rect.bottomRight() : rect.bottomLeft()); } else { rh = m_widget->height(); pos = m_widget->mapToGlobal(QPoint(0, m_widget->height() - 2)); w = m_widget->width(); } if (w > screen.width()) w = screen.width(); if ((pos.x() + w) > (screen.x() + screen.width())) pos.setX(screen.x() + screen.width() - w); if (pos.x() < screen.x()) pos.setX(screen.x()); int top = pos.y() - rh - screen.top() + 2; int bottom = screen.bottom() - pos.y(); h = qMax(h, m_popup->minimumHeight()); if (h > bottom) { h = qMin(qMax(top, bottom), h); if (top > bottom) pos.setY(pos.y() - h - rh + 2); } w = qMax(w,200); m_popup->setGeometry(pos.x(), pos.y(), w, h); if (!m_popup->isVisible()) m_popup->show(); } QWidget *CodeCompleterEx::widget() const { return m_widget; } void CodeCompleterEx::setWidget(QWidget *widget) { if (m_widget == widget) { return; } if (m_widget) { m_widget->removeEventFilter(this); } m_widget = widget; // Qt::FocusPolicy origPolicy = Qt::NoFocus; // if (widget) // origPolicy = widget->focusPolicy(); // m_popup->setParent(0, Qt::Popup); // m_popup->setFocusPolicy(Qt::NoFocus); // if (widget) // widget->setFocusPolicy(origPolicy); if (m_widget) { m_widget->installEventFilter(this); m_popup->setFocusProxy(m_widget); } } QModelIndex CodeCompleterEx::currentIndex() const { return m_popup->currentIndex(); } QString CodeCompleterEx::currentCompletion() const { QModelIndex index = m_popup->currentIndex(); if (index.isValid()) { QStandardItem *item = m_proxy->item(index); if (item) { return item->text(); } } return QString(); } void CodeCompleterEx::setCaseSensitivity(Qt::CaseSensitivity cs) { m_cs = cs; } Qt::CaseSensitivity CodeCompleterEx::caseSensitivity() const { return m_cs; } QAbstractItemView *CodeCompleterEx::popup() const { return m_popup; } QAbstractItemModel *CodeCompleterEx::completionModel() const { return m_proxy; } void CodeCompleterEx::setWrapAround(bool wrap) { m_wrap = wrap; } bool CodeCompleterEx::wrapAround() const { return m_wrap; } void CodeCompleterEx::setFuzzy(bool b) { m_proxy->setFuzzy(b); } bool CodeCompleterEx::isFuzzy() const { return m_proxy->isFuzzy(); } void CodeCompleterEx::completerActivated(QModelIndex index) { if (m_popup->isVisible()) { m_popup->close(); } emit activated(index); } bool CodeCompleterEx::eventFilter(QObject *o, QEvent *e) { if (m_eatFocusOut && o == m_widget && e->type() == QEvent::FocusOut) { m_hiddenBecauseNoMatch = false; if (m_popup && m_popup->isVisible()) return true; } if (o != m_popup) return QObject::eventFilter(o, e); switch (e->type()) { case QEvent::KeyPress: { QKeyEvent *ke = static_cast<QKeyEvent *>(e); QModelIndex curIndex = m_popup->currentIndex(); //QModelIndexList selList = m_popup->selectionModel()->selectedIndexes(); const int key = ke->key(); // In UnFilteredPopup mode, select the current item // if ((key == Qt::Key_Up || key == Qt::Key_Down) && selList.isEmpty() && curIndex.isValid() // && m_mode == QCompleter::UnfilteredPopupCompletion) { // m_popup->setCurrentIndex(curIndex); // return true; // } // Handle popup navigation keys. These are hardcoded because up/down might make the // widget do something else (lineedit cursor moves to home/end on mac, for instance) switch (key) { case Qt::Key_End: case Qt::Key_Home: if (ke->modifiers() & Qt::ControlModifier) return false; break; case Qt::Key_N: case Qt::Key_P: // select next/previous completion if (ke->modifiers() == Qt::ControlModifier) { int change = (ke->key() == Qt::Key_N) ? 1 : -1; int nrows = m_proxy->rowCount(); int row = m_popup->currentIndex().row(); int newRow = (row + change + nrows) % nrows; if (newRow == row + change || !ke->isAutoRepeat()) { QModelIndex index = m_proxy->index(newRow, 0); m_popup->setCurrentIndex(index); } return true; } break; case Qt::Key_Up: if (curIndex.row() == 0) { if (m_wrap) { int rowCount = m_proxy->rowCount(); QModelIndex lastIndex = m_proxy->index(rowCount - 1, 0); m_popup->setCurrentIndex(lastIndex); } return true; } return false; case Qt::Key_Down: if (curIndex.row() == m_proxy->rowCount() - 1) { if (m_wrap) { QModelIndex firstIndex = m_proxy->index(0, 0); m_popup->setCurrentIndex(firstIndex); } return true; } return false; case Qt::Key_PageUp: case Qt::Key_PageDown: return false; } // Send the event to the widget. If the widget accepted the event, do nothing // If the widget did not accept the event, provide a default implementation m_eatFocusOut = false; (static_cast<QObject *>(m_widget))->event(ke); m_eatFocusOut = true; if (!m_widget || e->isAccepted() || !m_popup->isVisible()) { // widget lost focus, hide the popup if (m_widget && (!m_widget->hasFocus() #ifdef QT_KEYPAD_NAVIGATION || (QApplication::keypadNavigationEnabled() && !m_widget->hasEditFocus()) #endif )) m_popup->hide(); if (e->isAccepted()) return true; } // default implementation for keys not handled by the widget when popup is open switch (key) { #ifdef QT_KEYPAD_NAVIGATION case Qt::Key_Select: if (!QApplication::keypadNavigationEnabled()) break; #endif case Qt::Key_Return: case Qt::Key_Enter: case Qt::Key_Tab: m_popup->hide(); if (curIndex.isValid()) //m__q_complete(curIndex); this->completerActivated(curIndex); break; case Qt::Key_F4: if (ke->modifiers() & Qt::AltModifier) m_popup->hide(); break; case Qt::Key_Backtab: case Qt::Key_Escape: m_popup->hide(); break; default: break; } return true; } #ifdef QT_KEYPAD_NAVIGATION case QEvent::KeyRelease: { QKeyEvent *ke = static_cast<QKeyEvent *>(e); if (QApplication::keypadNavigationEnabled() && ke->key() == Qt::Key_Back) { // Send the event to the 'widget'. This is what we did for KeyPress, so we need // to do the same for KeyRelease, in case the widget's KeyPress event set // up something (such as a timer) that is relying on also receiving the // key release. I see this as a bug in Qt, and should really set it up for all // the affected keys. However, it is difficult to tell how this will affect // existing code, and I can't test for every combination! m_eatFocusOut = false; static_cast<QObject *>(m_widget)->event(ke); m_eatFocusOut = true; } break; } #endif case QEvent::MouseButtonPress: { #ifdef QT_KEYPAD_NAVIGATION if (QApplication::keypadNavigationEnabled()) { // if we've clicked in the widget (or its descendant), let it handle the click QWidget *source = qobject_cast<QWidget *>(o); if (source) { QPoint pos = source->mapToGlobal((static_cast<QMouseEvent *>(e))->pos()); QWidget *target = QApplication::widgetAt(pos); if (target && (m_widget->isAncestorOf(target) || target == m_widget)) { m_eatFocusOut = false; static_cast<QObject *>(target)->event(e); m_eatFocusOut = true; return true; } } } #endif if (!m_popup->underMouse()) { m_popup->hide(); return true; } } return false; case QEvent::InputMethod: QApplication::sendEvent(m_widget, e); break; case QEvent::ShortcutOverride: { QKeyEvent *ke = static_cast<QKeyEvent *>(e); switch (ke->key()) { case Qt::Key_Escape: e->accept(); return true; case Qt::Key_N: case Qt::Key_P: if (ke->modifiers() == Qt::ControlModifier) { e->accept(); return true; } } QApplication::sendEvent(m_widget, e); break; } default: return false; } return false; }
33,756
C++
.cpp
973
26.029805
123
0.576078
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,481
highlightermanager.cpp
visualfc_liteide/liteidex/src/plugins/liteeditor/highlightermanager.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: highlightermanager.cpp // Creator: visualfc <visualfc@gmail.com> #include "highlightermanager.h" #include "colorstyle/colorstyle.h" #include "qtc_texteditor/syntaxhighlighter.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 TextEditor; HighlighterManager::HighlighterManager(QObject *parent) : LiteApi::IHighlighterManager(parent) { } void HighlighterManager::addFactory(LiteApi::IHighlighterFactory *factory) { m_factoryList.push_front(factory); } void HighlighterManager::removeFactory(LiteApi::IHighlighterFactory *factory) { m_factoryList.removeOne(factory); } QList<LiteApi::IHighlighterFactory *> HighlighterManager::factoryList() const { return m_factoryList; } QStringList HighlighterManager::mimeTypeList() const { QStringList mimeTypes; foreach(LiteApi::IHighlighterFactory *factory, m_factoryList) { mimeTypes.append(factory->mimeTypes()); } mimeTypes.removeDuplicates(); return mimeTypes; } LiteApi::IHighlighterFactory *HighlighterManager::findFactory(const QString &mimeType) const { foreach(LiteApi::IHighlighterFactory *factory, m_factoryList) { if (factory->mimeTypes().contains(mimeType)) { return factory; } } return 0; } static bool setTextCharStyle(QTextCharFormat &fmt, const QString &name, const ColorStyleScheme *scheme) { const ColorStyle *style = scheme->findStyle(name); if (!style) { return false; } QColor fore = style->foregound(); if (fore.isValid()) { fmt.setForeground(fore); } QColor back = style->background(); if (back.isValid()) { fmt.setBackground(back); } fmt.setFontItalic(style->italic()); if (style->bold()) { fmt.setFontWeight(QFont::Bold); } else { fmt.setFontWeight(QFont::Normal); } return true; } void HighlighterManager::setColorStyle(TextEditor::SyntaxHighlighter *highlighter, const ColorStyleScheme *scheme) { QTextCharFormat fmt_nm; highlighter->configureFormat(SyntaxHighlighter::Normal, fmt_nm); QTextCharFormat fmt_vw; if (!setTextCharStyle(fmt_vw,"VisualWhitespace",scheme)) { fmt_vw.setForeground(Qt::lightGray); } highlighter->configureFormat(SyntaxHighlighter::VisualWhitespace, fmt_vw); QTextCharFormat fmt_kw; if (!setTextCharStyle(fmt_kw,"Keyword",scheme)) { fmt_kw.setForeground(Qt::darkBlue); fmt_kw.setFontWeight(QFont::Bold); } highlighter->configureFormat(SyntaxHighlighter::Keyword, fmt_kw); QTextCharFormat fmt_dt; if (!setTextCharStyle(fmt_dt,"DataType",scheme)) { fmt_dt.setForeground(Qt::darkBlue);//Qt::darkMagenta); } highlighter->configureFormat(SyntaxHighlighter::DataType, fmt_dt); QTextCharFormat fmt_fn; if (!setTextCharStyle(fmt_fn,"Function",scheme)) { fmt_fn.setForeground(Qt::blue); } highlighter->configureFormat(SyntaxHighlighter::Function,fmt_fn); QTextCharFormat fmt_cmn; if (!setTextCharStyle(fmt_cmn,"Comment",scheme)) { fmt_cmn.setForeground(Qt::darkGreen); } highlighter->configureFormat(SyntaxHighlighter::Comment, fmt_cmn); QTextCharFormat fmt_dd; if (!setTextCharStyle(fmt_dd,"Decimal",scheme)) { fmt_dd.setForeground(Qt::darkMagenta); } // Using C_NUMBER for all kinds of numbers. highlighter->configureFormat(SyntaxHighlighter::Decimal, fmt_dd); QTextCharFormat fmt_db; if (!setTextCharStyle(fmt_db,"BaseN",scheme)) { fmt_db.setForeground(Qt::darkMagenta); } highlighter->configureFormat(SyntaxHighlighter::BaseN, fmt_db); QTextCharFormat fmt_df; if (!setTextCharStyle(fmt_df,"Float",scheme)) { fmt_df.setForeground(Qt::darkMagenta); } highlighter->configureFormat(SyntaxHighlighter::Float, fmt_df); QTextCharFormat fmt_ch; if (!setTextCharStyle(fmt_ch,"Char",scheme)) { fmt_ch.setForeground(Qt::darkGreen); } // Using C_STRING for strings and chars. highlighter->configureFormat(SyntaxHighlighter::Char, fmt_ch); QTextCharFormat fmt_cs; if (!setTextCharStyle(fmt_cs,"String",scheme)) { fmt_cs.setForeground(Qt::darkGreen); } highlighter->configureFormat(SyntaxHighlighter::String, fmt_cs); QTextCharFormat fmt_rm; if (!setTextCharStyle(fmt_rm,"RegionMarker",scheme)) { fmt_rm.setForeground(Qt::yellow); } highlighter->configureFormat(SyntaxHighlighter::RegionMarker,fmt_rm); QTextCharFormat fmt_alert; if (!setTextCharStyle(fmt_alert,"Alert",scheme)) { fmt_alert.setForeground(Qt::red); } highlighter->configureFormat(SyntaxHighlighter::Alert,fmt_alert); QTextCharFormat fmt_err; if (!setTextCharStyle(fmt_err,"Error",scheme)) { fmt_err.setForeground(Qt::red); } highlighter->configureFormat(SyntaxHighlighter::Error,fmt_err); QTextCharFormat fmt_sym; if (!setTextCharStyle(fmt_sym,"Symbol",scheme)) { fmt_sym.setForeground(Qt::red); } highlighter->configureFormat(SyntaxHighlighter::Symbol,fmt_sym); QTextCharFormat fmt_bf; if (!setTextCharStyle(fmt_bf,"BuiltinFunc",scheme)) { fmt_bf.setForeground(Qt::blue); } highlighter->configureFormat(SyntaxHighlighter::BuiltinFunc,fmt_bf); QTextCharFormat fmt_pre; if (!setTextCharStyle(fmt_pre,"Predeclared",scheme)) { fmt_pre.setForeground(Qt::blue); } highlighter->configureFormat(SyntaxHighlighter::Predeclared,fmt_pre); QTextCharFormat fmt_fc; if (!setTextCharStyle(fmt_fc,"FuncDecl",scheme)) { fmt_fc.setForeground(Qt::blue); } highlighter->configureFormat(SyntaxHighlighter::FuncDecl,fmt_fc); QTextCharFormat fmt_plc; if (!setTextCharStyle(fmt_plc,"Placeholder",scheme)) { fmt_plc.setForeground(fmt_cs.foreground()); } highlighter->configureFormat(SyntaxHighlighter::Placeholder,fmt_plc); QTextCharFormat fmt_todo; if (!setTextCharStyle(fmt_todo,"ToDo",scheme)) { fmt_todo.setForeground(fmt_cmn.foreground()); } highlighter->configureFormat(SyntaxHighlighter::ToDo,fmt_todo); QTextCharFormat fmt_processer; if (!setTextCharStyle(fmt_processer,"PreprocessorFormat",scheme)) { fmt_processer.setForeground(fmt_cmn.foreground()); } highlighter->configureFormat(SyntaxHighlighter::PreprocessorFormat,fmt_processer); highlighter->rehighlight(); } void HighlighterManager::setTabSize(TextEditor::SyntaxHighlighter *highlighter, int tabSize) { if (!highlighter) { return; } highlighter->setTabSize(tabSize); }
7,869
C++
.cpp
207
33.299517
114
0.709546
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,482
litecompleter.cpp
visualfc_liteide/liteidex/src/plugins/liteeditor/litecompleter.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: litecompleter.cpp // Creator: visualfc <visualfc@gmail.com> #include "litecompleter.h" #include "codecompleter.h" #include <QCompleter> #include <QPlainTextEdit> #include <QTextCursor> #include <QStandardItem> #include <QStandardItemModel> #include <QAbstractItemView> #include <QScrollBar> #include <QTextBlock> #include <QTimer> #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 WordItem : public QStandardItem { public: WordItem(const QString &text) : QStandardItem(text) { } enum { KindRole = Qt::UserRole+2, TempRole, SnippetRole, }; void setKind(const QString &kind) { this->setData(kind,KindRole); } QString kind() const { return QStandardItem::data(KindRole).toString(); } void setTemp(bool temp) { this->setData(temp,TempRole); } bool isTemp() const { return QStandardItem::data(TempRole).toBool(); } }; LiteCompleter::LiteCompleter(QObject *parent) : LiteApi::ICompleter(parent), m_completer( new CodeCompleterEx(this)), m_model(new QStandardItemModel(this)), m_bSearchSeparator(true), m_bExternalMode(false) { m_completer->setModel(m_model); m_completer->setCaseSensitivity(Qt::CaseSensitive); m_completer->setSeparator("."); m_stop = '('; m_prefixMin = 1; QObject::connect(m_completer, SIGNAL(activated(QModelIndex)), this, SLOT(insertCompletion(QModelIndex))); } LiteCompleter::~LiteCompleter() { delete m_completer; delete m_model; } void LiteCompleter::setEditor(QPlainTextEdit *editor) { m_editor = editor; m_completer->setWidget(m_editor); } QStandardItem *LiteCompleter::findRoot(const QString &name) { QStringList words = name.split(m_completer->separator(),qtSkipEmptyParts); WordItem *root = 0; WordItem *item = 0; foreach (QString word, words) { item = 0; QModelIndex parent = m_model->indexFromItem(root); for (int i = 0; i < m_model->rowCount(parent); i++) { QModelIndex index = m_model->index(i,0,parent); if (index.data().toString() == word) { item = static_cast<WordItem*>(m_model->itemFromIndex(index)); break; } } if (item == 0) { item = new WordItem(word); if (root == 0) { m_model->appendRow(item); } else { root->appendRow(item); } } root = item; } return root; } void LiteCompleter::clearChildItem(QStandardItem *root) { if (root) { QModelIndex index = m_model->indexFromItem(root); m_model->removeRows(0,m_model->rowCount(index),index); } } void LiteCompleter::appendChildItem(QStandardItem *root, QString name, const QString &kind, const QString &info, const QIcon &icon, bool temp) { if (root == 0) { WordItem *item = 0; QModelIndex parent = m_model->indexFromItem(root); int count = m_model->rowCount(parent); while(count--) { QModelIndex index = m_model->index(count,0,parent); if (index.data().toString() == name) { item = static_cast<WordItem*>(m_model->itemFromIndex(index)); break; } } if (item == 0) { item = new WordItem(name); if (root == 0) { m_model->appendRow(item); } else { root->appendRow(item); } } if (item) { item->setKind(kind); item->setToolTip(info); item->setTemp(temp); item->setIcon(icon); } } else { WordItem *item = new WordItem(name); root->appendRow(item); item->setKind(kind); item->setToolTip(info); item->setTemp(temp); item->setIcon(icon); } } void LiteCompleter::clear() { m_model->clear(); } static void clearTempIndex(QStandardItemModel *model, QModelIndex parent, const QString &prefix) { int i = model->rowCount(parent); while (i--) { QModelIndex index = model->index(i,0,parent); if (prefix.startsWith(index.data().toString())) { return; } if (index.data(WordItem::TempRole).toBool() == true || index.data(WordItem::KindRole).toString().isEmpty()) { model->removeRow(i,parent); } else { clearTempIndex(model,index, prefix); } } } void LiteCompleter::clearTemp() { clearTempIndex(m_model,QModelIndex(), this->completionPrefix()); } void LiteCompleter::showPopup() { if (!m_editor) { return; } //m_completer->model()->sort(0); m_completer->popup()->setCurrentIndex(m_completer->completionModel()->index(0, 0)); QString prefix = m_completer->lastPrefix(); if (!prefix.isEmpty()) { bool found = false; for (int i = 0; i < m_completer->completionModel()->rowCount(); i++) { QModelIndex index = m_completer->completionModel()->index(i,0); QString text = index.data().toString(); if (text.startsWith(prefix,Qt::CaseInsensitive)) { if (text.compare(prefix,Qt::CaseInsensitive) == 0) { m_completer->popup()->setCurrentIndex(index); break; } if (!found) { m_completer->popup()->setCurrentIndex(index); } found = true; } else if (found) { break; } } } QTextCursor cursor = m_editor->textCursor(); int offset = m_completer->completionPrefix().length(); if (m_completer->completionContext() != LiteApi::CompleterImportContext) { int pos = m_completer->completionPrefix().indexOf(m_completer->separator()); if (pos != -1) { offset -= pos+1; } } cursor.movePosition(QTextCursor::Left,QTextCursor::MoveAnchor,offset); QRect cr = m_editor->cursorRect(cursor); cr.setLeft(cr.left()+m_editor->viewport()->x()-24); cr.setWidth(m_completer->popup()->sizeHintForColumn(0) + m_completer->popup()->verticalScrollBar()->sizeHint().width()); m_completer->complete(cr); // popup it up! } void LiteCompleter::hidePopup() { if (m_completer->popup()->isVisible()) { m_completer->popup()->hide(); } } bool LiteCompleter::isShowPopup() { return m_completer->popup()->isVisible(); } void LiteCompleter::setCaseSensitivity(Qt::CaseSensitivity caseSensitivity) { m_completer->setCaseSensitivity(caseSensitivity); } void LiteCompleter::setFuzzy(bool fuzzy) { m_completer->setFuzzy(fuzzy); } void LiteCompleter::setCompletionPrefix(const QString &prefix) { m_completer->setCompletionPrefix(prefix); } QString LiteCompleter::completionPrefix() const { return m_completer->completionPrefix(); } void LiteCompleter::setCompletionContext(LiteApi::CompletionContext ctx) { m_completer->setCompletionContext(ctx); } LiteApi::CompletionContext LiteCompleter::completionContext() const { return m_completer->completionContext(); } void LiteCompleter::setSeparator(const QString &sep) { m_completer->setSeparator(sep); } QString LiteCompleter::separator() const { return m_completer->separator(); } QAbstractItemView *LiteCompleter::popup() const { return m_completer->popup(); } QModelIndex LiteCompleter::currentIndex() const { return m_completer->currentIndex(); } QString LiteCompleter::currentCompletion() const { return m_completer->currentCompletion(); } QAbstractItemModel *LiteCompleter::model() const { return m_model; } QAbstractItemModel *LiteCompleter::completionModel() const { return m_completer->completionModel(); } bool LiteCompleter::startCompleter(const QString &completionPrefix) { if (completionPrefix != this->completionPrefix()) { this->setCompletionPrefix(completionPrefix); this->popup()->setCurrentIndex(this->completionModel()->index(0, 0)); } if (this->completionContext() == LiteApi::CompleterImportContext && completionPrefix.endsWith("/")) { goto end; } if (!completionPrefix.isEmpty() && this->currentCompletion() == completionPrefix) { this->popup()->hide(); return false; } end: this->showPopup(); return true; } void LiteCompleter::updateCompleterModel() { this->m_completer->updateFilter(); } void LiteCompleter::setImportList(const QStringList &importList) { this->m_completer->setImportList(importList); } void LiteCompleter::setPrefixMin(int min) { m_prefixMin = min; } int LiteCompleter::prefixMin() const { return m_prefixMin; } void LiteCompleter::setSearchSeparator(bool b) { m_bSearchSeparator = b; } bool LiteCompleter::searchSeparator() const { return m_bSearchSeparator; } bool LiteCompleter::externalMode() const { return m_bExternalMode; } void LiteCompleter::setExternalMode(bool b) { m_bExternalMode = b; } void LiteCompleter::appendItems(QStringList items,const QString &kind, const QString &info,const QIcon &icon, bool temp) { foreach(QString item,items) { appendItemEx(item,kind,info,icon,temp); } } void LiteCompleter::appendSnippetItem(const QString &name, const QString &info, const QString &content) { WordItem *item = new WordItem(name); item->setKind("snippet"); item->setToolTip(info); item->setIcon(QIcon(":liteeditor/images/snippet.png")); item->setData(content,WordItem::SnippetRole); m_model->appendRow(item); } bool LiteCompleter::appendItem(const QString &name, const QIcon &icon, bool temp) { QString func; int pos = name.indexOf(m_stop); if (pos == -1) { func = name.trimmed(); } else { func = name.left(pos).trimmed(); //arg = text.right(text.length()-pos).trimmed(); } return this->appendItemEx(func,"","",icon,temp); } void LiteCompleter::clearItemChilds(const QString &name) { QStringList words = name.split(m_completer->separator(),qtSkipEmptyParts); WordItem *root = 0; WordItem *item = 0; foreach (QString word, words) { item = 0; QModelIndex parent = m_model->indexFromItem(root); int count = m_model->rowCount(parent); while(count--) { QModelIndex index = m_model->index(count,0,parent); if (index.data().toString() == word) { item = static_cast<WordItem*>(m_model->itemFromIndex(index)); break; } } root = item; } if (item) { QModelIndex index = m_model->indexFromItem(item); m_model->removeRows(0,m_model->rowCount(index),index); } } bool LiteCompleter::appendItemEx(const QString &name,const QString &kind, const QString &info, const QIcon &icon, bool temp) { QStringList words = name.split(m_completer->separator(),qtSkipEmptyParts); WordItem *root = 0; WordItem *item = 0; bool bnew = false; foreach (QString word, words) { item = 0; QModelIndex parent = m_model->indexFromItem(root); for (int i = 0; i < m_model->rowCount(parent); i++) { QModelIndex index = m_model->index(i,0,parent); if (index.data().toString() == word) { item = static_cast<WordItem*>(m_model->itemFromIndex(index)); break; } } if (item == 0) { item = new WordItem(word); item->setIcon(icon); if (root == 0) { m_model->appendRow(item); } else { root->appendRow(item); } bnew = true; } root = item; } if (item && item->kind().isEmpty()) { item->setKind(kind); item->setToolTip(info); item->setTemp(temp); item->setIcon(icon); } return bnew; } void LiteCompleter::completionPrefixChanged(QString prefix, bool force) { if (!m_editor) { return; } if (m_completer->widget() != m_editor) { return; } emit prefixChanged(m_editor->textCursor(),prefix, force); } void LiteCompleter::insertCompletion(QModelIndex index) { if (!m_editor) { return; } if (m_completer->widget() != m_editor) return; if (!index.isValid()) { return; } QString text = index.data().toString(); QString kind = index.data(WordItem::KindRole).toString(); QString info = index.data(Qt::ToolTipRole).toString(); QString prefix = m_completer->completionPrefix(); //IsAbs r.URL. int length = prefix.length(); if (m_completer->completionContext() == LiteApi::CompleterCodeContext) { int pos = prefix.lastIndexOf(m_completer->separator()); if (pos != -1) { length = prefix.length()-pos-m_completer->separator().length(); } } QString extra = text; QString wordText = text; QTextCursor tc = m_editor->textCursor(); tc.beginEditBlock(); while (length--) { tc.deletePreviousChar(); } extra = text; wordText = text; if (kind == "func") { //qDebug() << "->" << tc.positionInBlock() << tc.block().text() << tc.block().text().size(); int pos = tc.positionInBlock(); if (pos == tc.block().text().size() || tc.block().text().at(tc.positionInBlock()) != '(') { extra += "()"; tc.insertText(extra); if (!info.startsWith("func()")) { tc.movePosition(QTextCursor::Left,QTextCursor::MoveAnchor,1); } } else { tc.insertText(extra); kind.clear(); } } else if (kind == "snippet") { QString content = index.data(WordItem::SnippetRole).toString(); QString text = m_editor->textCursor().block().text(); int space = 0; for (int i = 0; i < text.size(); i++) { if (text.at(i).isSpace()) { space++; } else { break; } } QString head = text.left(space); QStringList srcList = content.split("\n"); QStringList targetList; for (int i = 0; i < srcList.size(); i++) { if (i == 0) { targetList.append(srcList[i]); } else { targetList.append(head+srcList[i]); } } QString target = targetList.join("\n"); int startpos = tc.position(); int pos1 = target.indexOf("$"); int pos2 = -1; if (pos1 > 0) { pos2 = target.indexOf("$",pos1+1); } target.replace("$",""); extra = target; tc.insertText(extra); if (pos1 >= 0) { tc.setPosition(startpos+pos1); if (pos2 > 0) { tc.movePosition(QTextCursor::Right,QTextCursor::KeepAnchor,pos2-pos1-1); } } } else { tc.insertText(extra); } tc.endEditBlock(); m_editor->setTextCursor(tc); emit wordCompleted(wordText,kind,info); } void LiteCompleter::updateCompleteInfo(QModelIndex index) { if (!m_editor) { return; } if (m_completer->widget() != m_editor) return; if (!index.isValid()) { return; } QString text = index.data().toString(); QString kind = index.data(WordItem::KindRole).toString(); QString info = index.data(Qt::ToolTipRole).toString(); emit wordCompleted(text,kind,info); }
17,425
C++
.cpp
540
24.898148
143
0.593588
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,483
liteeditorfile.cpp
visualfc_liteide/liteidex/src/plugins/liteeditor/liteeditorfile.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: liteeditorfile.cpp // Creator: visualfc <visualfc@gmail.com> #include "liteeditorfile.h" #include "liteeditor_global.h" #include "editorutil/checkdata.h" #include <QFile> #include <QTextDocument> #include <QTextCodec> #include <QTextStream> #include <QMessageBox> #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 LiteEditorFile::LiteEditorFile(LiteApi::IApplication *app, QObject *parent) : LiteApi::IFile(parent), m_liteApp(app) { //m_codec = QTextCodec::codecForLocale(); m_codec = QTextCodec::codecForName("utf-8"); m_hasDecodingError = false; m_bReadOnly = false; m_bBinary = false; m_hasUtf8Bom = false; m_lineTerminatorMode = NativeLineTerminator; } QString LiteEditorFile::filePath() const { return m_fileName; } bool LiteEditorFile::isReadOnly() const { if (m_hasDecodingError) { return true; } return m_bReadOnly; } bool LiteEditorFile::isBinary() const { return m_bBinary; } bool LiteEditorFile::saveText(const QString &fileName, const QString &text) { QFile file(fileName); if (!file.open(QFile::WriteOnly | QIODevice::Truncate)) { return false; } m_fileName = fileName; QString saveText = text; if (m_lineTerminatorMode == CRLFLineTerminator) { saveText.replace(QLatin1Char('\n'), QLatin1String("\r\n")); } QByteArray data; if (m_codec) { if (m_hasUtf8Bom && m_codec->name() == "UTF-8") { if (file.write("\xef\xbb\xbf", 3) !=3 ) { m_liteApp->appendLog("LiteEditor",QString("write file %1 false, %2").arg(fileName).arg(file.errorString()),true); return false; } } data = m_codec->fromUnicode(saveText); } else { data = saveText.toLocal8Bit(); } int size = file.write(data); if (size != data.size()) { m_liteApp->appendLog("LiteEditor",QString("write file %1 false, %2").arg(fileName).arg(file.errorString()),true); return false; } return true; } bool LiteEditorFile::reloadTextByCodec(const QString &codecName, QString &outText) { setTextCodec(codecName); return loadFileHelper(m_fileName,m_mimeType,false,outText); } bool LiteEditorFile::reloadText(QString &outText) { return loadText(m_fileName,m_mimeType,outText); } QString LiteEditorFile::mimeType() const { return m_mimeType; } void LiteEditorFile::setTextCodec(const QString &name) { QTextCodec *codec = QTextCodec::codecForName(name.toLatin1()); if (codec) { m_codec = codec; } } QString LiteEditorFile::textCodec() const { return m_codec->name(); } bool LiteEditorFile::loadFileHelper(const QString &fileName, const QString &mimeType, bool bCheckCodec, QString &outText) { QFile file(fileName); if (!file.open(QFile::ReadOnly)) { return false; } const QFileInfo fi(fileName); m_bReadOnly = !fi.isWritable(); m_mimeType = mimeType; m_fileName = fileName; if (file.size() > (3 << 24)) { m_liteApp->appendLog("LiteEditor","Large file not open in the text editor! "+fileName,true); m_hasDecodingError = true; return false; } QByteArray buf = file.readAll(); m_hasDecodingError = false; m_bBinary = false; if (HasBinaryData(buf,32)) { m_liteApp->appendLog("LiteEditor","Open binary file in the text editor! "+fileName,true); m_bBinary = true; QByteArray testName = m_libucd.parse(buf); if (!testName.isEmpty()) { QTextCodec *c = QTextCodec::codecForName(testName); if (c && (c->mibEnum() != m_codec->mibEnum()) ) { m_codec = c; } } QTextCodec::ConverterState state; outText = m_codec->toUnicode(buf,buf.size(),&state); if (state.invalidChars > 0 || state.remainingChars > 0) { m_hasDecodingError = true; } } else { if (bCheckCodec) { m_codec = QTextCodec::codecForName("UTF-8"); m_hasUtf8Bom = false; if (mimeType == "text/html" || mimeType == "text/xml") { m_codec = QTextCodec::codecForHtml(buf,QTextCodec::codecForName("utf-8")); } else { LiteApi::IMimeType *im = m_liteApp->mimeTypeManager()->findMimeType(mimeType); if (im) { QString codecName = im->codec(); if (!codecName.isEmpty()) { m_codec = QTextCodec::codecForName(codecName.toLatin1()); } } int bytesRead = buf.size(); QTextCodec *codec = m_codec; // code taken from qtextstream if (bytesRead >= 4 && ((uchar(buf[0]) == 0xff && uchar(buf[1]) == 0xfe && uchar(buf[2]) == 0 && uchar(buf[3]) == 0) || (uchar(buf[0]) == 0 && uchar(buf[1]) == 0 && uchar(buf[2]) == 0xfe && uchar(buf[3]) == 0xff))) { codec = QTextCodec::codecForName("UTF-32"); } else if (bytesRead >= 2 && ((uchar(buf[0]) == 0xff && uchar(buf[1]) == 0xfe) || (uchar(buf[0]) == 0xfe && uchar(buf[1]) == 0xff))) { codec = QTextCodec::codecForName("UTF-16"); } else if (bytesRead >= 3 && uchar(buf[0]) == 0xef && uchar(buf[1]) == 0xbb && uchar(buf[2])== 0xbf) { codec = QTextCodec::codecForName("UTF-8"); buf.remove(0,3); m_hasUtf8Bom = true; } else if (!codec){ codec = QTextCodec::codecForLocale(); } // end code taken from qtextstream m_codec = codec; } } QTextCodec::ConverterState state; outText = m_codec->toUnicode(buf,buf.size(),&state); if (state.invalidChars > 0 || state.remainingChars > 0) { m_hasDecodingError = true; } if (m_hasDecodingError && bCheckCodec) { QByteArray testName = m_libucd.parse(buf); if (!testName.isEmpty()) { QTextCodec *c = QTextCodec::codecForName(testName); if (c && (c->mibEnum() != m_codec->mibEnum()) ) { QTextCodec::ConverterState testState; QString testText = c->toUnicode(buf,buf.size(),&testState); if (testState.invalidChars == 0 && testState.remainingChars == 0) { m_hasDecodingError = false; m_codec = c; outText = testText; } } } } } int lf = outText.indexOf('\n'); if (lf < 0) { m_lineTerminatorMode = NativeLineTerminator; } else if (lf == 0) { m_lineTerminatorMode = LFLineTerminator; } else { lf = outText.indexOf(QRegExp("[^\r]\n"),lf-1); if (lf >= 0) { m_lineTerminatorMode = LFLineTerminator; } else { m_lineTerminatorMode = CRLFLineTerminator; } } if (m_lineTerminatorMode == CRLFLineTerminator) { outText.replace("\r\n","\n"); } bool noprintCheck = m_liteApp->settings()->value(EDITOR_NOPRINTCHECK,true).toBool(); if (noprintCheck && !LiteApi::mimeIsText(mimeType)) { for (int i = 0; i < outText.length(); i++) { // if (!outText[i].isPrint() && !outText[i].isSpace() && outText[i] != '\r' && outText[i] != '\n') { // outText[i] = '.'; // m_hasDecodingError = true; // } if (IsBinaryCode(outText[i].unicode())) { outText[i] = '.'; m_hasDecodingError = true; } } } if (m_hasDecodingError) { m_liteApp->appendLog("LiteEditor",QString("Decode file error! file:\"%1\" codec:%2").arg(fileName).arg(textCodec()),true); } return true; } bool LiteEditorFile::setLineEndUnix(bool b) { if (this->isLineEndUnix() == b) { return false; } if (b) { m_lineTerminatorMode = LFLineTerminator; } else { m_lineTerminatorMode = CRLFLineTerminator; } return true; } bool LiteEditorFile::hasDecodingError() const { return m_hasDecodingError; } bool LiteEditorFile::isLineEndUnix() const { return m_lineTerminatorMode == LFLineTerminator; } bool LiteEditorFile::isLineEndWindow() const { return m_lineTerminatorMode == CRLFLineTerminator; } void LiteEditorFile::setMimeType(const QString &mimeType) { m_mimeType = mimeType; } bool LiteEditorFile::loadText(const QString &fileName, const QString &mimeType, QString &outText) { return loadFileHelper(fileName,mimeType,true,outText); }
10,064
C++
.cpp
276
29.155797
138
0.590466
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,484
litewordcompleter.cpp
visualfc_liteide/liteidex/src/plugins/liteeditor/litewordcompleter.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: litewordcompleter.cpp // Creator: visualfc <visualfc@gmail.com> #include "litewordcompleter.h" #include "codecompleter.h" #include <QPlainTextEdit> #include <QStandardItem> #include <QStandardItemModel> #include <QTextCursor> #include <QTextBlock> #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 LiteWordCompleter::LiteWordCompleter(QObject *parent) : LiteCompleter(parent), m_icon(QIcon("icon:liteeditor/images/findword.png")) { } QString LiteWordCompleter::textUnderCursor(QTextCursor tc) const { QString text = tc.block().text().left(tc.positionInBlock()); if (text.isEmpty()) { return QString(); } static QRegExp reg("[a-zA-Z_]+[a-zA-Z0-9_\\.@]*$"); int index = reg.indexIn(text); if (index < 0) { return QString(); } return text.right(reg.matchedLength()); } void LiteWordCompleter::completionPrefixChanged(QString prefix,bool force) { LiteCompleter::completionPrefixChanged(prefix,force); if (m_bExternalMode) { return; } if (!m_editor) { return; } if (!m_bSearchSeparator) { if (prefix.indexOf(this->separator()) >= 0) { return; } } bool isSep = false; if (prefix.startsWith("@.")) { isSep = true; prefix = prefix.mid(1); } QTextCursor tc = m_editor->textCursor(); QTextDocument *doc = m_editor->document(); int maxNumber = tc.blockNumber(); int blockNumber = tc.blockNumber(); QTextBlock block = doc->firstBlock(); if (maxNumber < 500) { maxNumber = 500; } else { int firstNumber = maxNumber-500; if (firstNumber > 0) { block = doc->findBlockByNumber(firstNumber); } } QRegExp rx("([\\w\\-\\_\\.]+)"); Qt::CaseSensitivity cs = m_completer->caseSensitivity(); int count = 0; 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); if (cap.length() < 20 && cap.startsWith(prefix,cs)) { if (isSep) { cap = "@"+cap; } count++; appendItem(cap,m_icon,true); } pos += rx.matchedLength(); } } block = block.next(); } if (count > 0) { this->updateCompleterModel(); this->showPopup(); } }
4,033
C++
.cpp
123
26.691057
82
0.591795
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,485
katehighlighterfactory.cpp
visualfc_liteide/liteidex/src/plugins/liteeditor/katehighlighterfactory.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: katehighlighterfactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "katehighlighterfactory.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 KateHighlighterFactory::KateHighlighterFactory(QObject *parent) : LiteApi::IHighlighterFactory(parent) { m_kate = new KateHighlighter(this); } QStringList KateHighlighterFactory::mimeTypes() const { return m_kate->mimeTypes(); } TextEditor::SyntaxHighlighter *KateHighlighterFactory::create(LiteApi::ITextEditor */*editor*/, QTextDocument *doc, const QString &mimeType) { return m_kate->create(doc,mimeType); } void KateHighlighterFactory::loadPath(const QString &dir) { m_kate->loadPath(dir); }
1,933
C++
.cpp
49
37.428571
140
0.697712
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,486
editorapimanager.cpp
visualfc_liteide/liteidex/src/plugins/liteeditor/editorapimanager.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: editorapimanager.cpp // Creator: visualfc <visualfc@gmail.com> #include "editorapimanager.h" #include "wordapi.h" #include "snippetapi.h" #include <QDir> #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 EditorApiManager::EditorApiManager(QObject *parent) : IEditorApiManager(parent) { } EditorApiManager::~EditorApiManager() { qDeleteAll(m_wordApiList); qDeleteAll(m_snippetApiList); } void EditorApiManager::addWordApi(IWordApi *api) { m_wordApiList.append(api); } void EditorApiManager::removeWordApi(IWordApi *api) { m_wordApiList.removeAll(api); } IWordApi *EditorApiManager::findWordApi(const QString &mimeType) { QString package = LiteApi::findPackageByMimeType(m_liteApp,mimeType); if (package.isEmpty()) { return 0; } foreach (IWordApi *wordApi, m_wordApiList) { if (wordApi->package() == package) { return wordApi; } } return 0; } QList<IWordApi*> EditorApiManager::wordApiList() const { return m_wordApiList; } void EditorApiManager::addSnippetApi(ISnippetApi *api) { m_snippetApiList.append(api); } void EditorApiManager::removeSnippetApi(ISnippetApi *api) { m_snippetApiList.removeAll(api); } ISnippetApi *EditorApiManager::findSnippetApi(const QString &mimeType) { QString package = LiteApi::findPackageByMimeType(m_liteApp,mimeType); if (package.isEmpty()) { return 0; } foreach (ISnippetApi *api, m_snippetApiList) { if (api->package() == package) { return api; } } return 0; } QList<ISnippetApi *> EditorApiManager::snippetApiList() const { return m_snippetApiList; } void EditorApiManager::load(const QString &path) { QDir dir = path; m_liteApp->appendLog("WordApiManager","Loading "+path); QStringList nameFilter; nameFilter << "*.api" << "*.snippet.json"; foreach(QFileInfo info, dir.entryInfoList(QDir::Dirs|QDir::NoDotAndDotDot)) { QStringList wordFiles; QStringList snippetFiles; if (info.isDir()) { foreach (QFileInfo i, QDir(info.absoluteFilePath()).entryInfoList(nameFilter)) { if (i.fileName().endsWith(".api")) { wordFiles.append(i.filePath()); } else if (i.fileName().endsWith(".snippet.json")) { snippetFiles.append(i.filePath()); } } } if (!wordFiles.isEmpty()) { WordApi *api = new WordApi(info.fileName()); api->setApiFiles(wordFiles); this->addWordApi(api); m_liteApp->appendLog("load word api",wordFiles.join(",")); } if (!snippetFiles.isEmpty()) { SnippetApi *api = new SnippetApi(info.fileName()); api->setApiFiles(snippetFiles); this->addSnippetApi(api); m_liteApp->appendLog("load snippet api",snippetFiles.join(",")); } } }
4,217
C++
.cpp
127
28.267717
92
0.653252
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,487
liteeditormark.cpp
visualfc_liteide/liteidex/src/plugins/liteeditor/liteeditormark.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: liteeditormark.cpp // Creator: visualfc <visualfc@gmail.com> #include "liteeditormark.h" #include "qtc_texteditor/basetextdocumentlayout.h" #include "liteeditorwidget.h" #include <QTextDocument> #include <QTextBlock> #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 LiteEditorMarkNode::LiteEditorMarkNode(LiteEditorMark *editorMark, int type, int indexOfType, int lineNumber, const QTextBlock &block, QObject *parent) : TextEditor::ITextMark(parent), m_editorMark(editorMark) { m_blockNumber = lineNumber; m_type = type; m_indexOfType = indexOfType; m_block = block; } LiteEditorMarkNode::~LiteEditorMarkNode() { // qDebug() << "~LiteTextMark" << m_type << this->lineNumber(); } void LiteEditorMarkNode::removedFromEditor() { m_editorMark->removedFromEditor(this); } void LiteEditorMarkNode::updateBlockNumber(int lineNumber) { if (m_blockNumber == lineNumber) { return; } int old = m_blockNumber; m_blockNumber = lineNumber; m_editorMark->updateBlockNumber(this, m_blockNumber, old); } void LiteEditorMarkNode::updateBlock(const QTextBlock &block) { m_block = block; m_editorMark->updateLineBlock(this); } QTextBlock LiteEditorMarkNode::block() const { return m_block; } LiteEditorMarkManager::LiteEditorMarkManager(QObject *parent) : LiteApi::IEditorMarkManager(parent) { } LiteEditorMarkManager::~LiteEditorMarkManager() { } void LiteEditorMarkManager::registerMark(int type, const QIcon &icon) { if (m_typeIconMap.contains(type)) { qDebug() << "warning!!!" << "LiteEditorMarkTypeManager register mark type" << type << "exist!"; } m_typeIconMap.insert(type,icon); } QList<int> LiteEditorMarkManager::markTypeList() const { return m_typeIconMap.keys(); } QIcon LiteEditorMarkManager::iconForType(int type) const { return m_typeIconMap.value(type); } int LiteEditorMarkManager::indexOfType(int type) const { return m_typeIconMap.keys().indexOf(type); } QList<LiteApi::IEditorMark *> LiteEditorMarkManager::editorMarkList() const { return m_markList; } void LiteEditorMarkManager::addMark(LiteApi::IEditorMark *mark) { m_markList.append(mark); emit editorMarkCreated(mark); connect(mark,SIGNAL(markListChanged(int)),this,SLOT(markListChanged(int))); } void LiteEditorMarkManager::removeMark(LiteApi::IEditorMark *mark) { m_markList.removeAll(mark); emit editorMarkRemoved(mark); } void LiteEditorMarkManager::addMarkNode(LiteApi::IEditorMark *mark, LiteApi::IEditorMarkNode *node) { emit editorMarkNodeCreated(mark,node); } void LiteEditorMarkManager::removeMarkNode(LiteApi::IEditorMark *mark, LiteApi::IEditorMarkNode *node) { emit editorMarkNodeRemoved(mark,node); } void LiteEditorMarkManager::updateMarkNode(LiteApi::IEditorMark *mark, LiteApi::IEditorMarkNode *node) { emit editorMarkNodeChanged(mark,node); } void LiteEditorMarkManager::markListChanged(int type) { emit editorMarkListChanged((LiteApi::IEditorMark*)sender(),type); } LiteEditorMark::LiteEditorMark(LiteEditorMarkManager *manager, LiteEditor *editor) : LiteApi::IEditorMark(editor), m_manager(manager), m_editor(editor), m_document(editor->document()) { m_manager->addMark(this); } LiteEditorMark::~LiteEditorMark() { m_manager->removeMark(this); } static TextEditor::ITextMark *findMarkByType(TextEditor::TextBlockUserData *data, int type) { foreach(TextEditor::ITextMark *mark, data->marks()) { if ( mark->type() == type ) { return mark; } } return 0; } LiteEditorMarkNode *LiteEditorMark::createMarkByType(int type, int line, const QTextBlock &block) { int index = m_manager->indexOfType(type); if (index < 0) { return 0; } QIcon icon = m_manager->iconForType(type); LiteEditorMarkNode *mark = new LiteEditorMarkNode(this,type,index,line,block,this); mark->setIcon(icon); return mark; } void LiteEditorMark::removedFromEditor(LiteEditorMarkNode *mark) { int type = mark->type(); m_typeLineMarkMap[type].remove(mark->blockNumber()); m_manager->removeMarkNode(this,mark); emit markListChanged(type); delete mark; } void LiteEditorMark::updateBlockNumber(LiteEditorMarkNode *mark, int newLine, int oldLine) { int type = mark->type(); m_typeLineMarkMap[type].remove(oldLine); m_typeLineMarkMap[type].insert(newLine,mark); m_manager->updateMarkNode(this,mark); emit markListChanged(type); } void LiteEditorMark::updateLineBlock(LiteEditorMarkNode *mark) { m_manager->updateMarkNode(this,mark); } QMap<int, QList<int> > LiteEditorMark::saveTypeLinesMap(bool clearAll) { QMap<int, QList<int> > maps; QTextBlock block = m_document->firstBlock(); while(block.isValid()) { TextEditor::TextBlockUserData *data = TextEditor::BaseTextDocumentLayout::testUserData(block); if (data) { foreach (LiteApi::IEditorMarkNode *mark, data->marks()) { maps[mark->type()].push_back(mark->blockNumber()); } if (clearAll) { qDeleteAll(data->marks()); data->clearMarks(); } } block = block.next(); } if (clearAll) { m_typeLineMarkMap.clear(); } return maps; } void LiteEditorMark::restoreTypeLinesMap(const QMap<int, QList<int> > &maps) { QMapIterator<int, QList<int> > i(maps); while (i.hasNext()) { i.next(); this->addMarkList(i.value(),i.key()); } } void LiteEditorMark::addMark(int line, int type) { addMarkList(QList<int>() << line, type); } void LiteEditorMark::addMarkList(const QList<int> &lines, int type) { bool changed = false; foreach (int line, lines) { const QTextBlock &block = m_document->findBlockByNumber(line); if (!block.isValid()) { continue; } TextEditor::TextBlockUserData *data = TextEditor::BaseTextDocumentLayout::userData(block); if (!data) { continue; } TextEditor::ITextMark *findMark = findMarkByType(data,type); if (findMark) { continue; } LiteEditorMarkNode *mark = createMarkByType(type, line, block); data->addMark(mark); m_typeLineMarkMap[type].insert(line,mark); m_manager->addMarkNode(this,mark); changed = true; } if (changed) { emit markListChanged(type); } } void LiteEditorMark::removeMark(int line, int type) { removeMarkList(QList<int>() << line, type); } void LiteEditorMark::removeMarkList(const QList<int> &lines, int type) { bool changed = false; foreach (int line, lines) { const QTextBlock &block = m_document->findBlockByNumber(line); if (!block.isValid()) { continue; } TextEditor::TextBlockUserData *data = TextEditor::BaseTextDocumentLayout::testUserData(block); if (!data) { continue; } TextEditor::ITextMark *mark = findMarkByType(data,type); if (!mark) { continue; } data->removeMark(mark); m_typeLineMarkMap[type].remove(line); m_manager->removeMarkNode(this,mark); delete mark; changed = true; } if (changed) { emit markListChanged(type); } } QList<int> LiteEditorMark::markLinesByType(int type) const { // qDebug return m_typeLineMarkMap[type].keys(); // QList<int> lineList; // QTextBlock block = m_document->firstBlock(); // while (block.isValid()) { // TextEditor::TextBlockUserData *data = TextEditor::BaseTextDocumentLayout::testUserData(block); // if (data) { // foreach(TextEditor::ITextMark *mark, data->marks() ) { // if ( ((LiteTextMark*)mark)->type() == type ) { // lineList.append(block.blockNumber()); // break; // } // } // } // block = block.next(); // } // return lineList; } QList<QTextBlock> LiteEditorMark::markBlocksByType(int type) const { QList<QTextBlock> blocks; foreach (TextEditor::ITextMark *mark, m_typeLineMarkMap[type].values()) { blocks.push_back(((LiteEditorMarkNode*)mark)->block()); } return blocks; } QList<int> LiteEditorMark::markTypesByLine(int line) const { QList<int> typeList; TypeLineMarkMapIterator i(m_typeLineMarkMap); while (i.hasNext()) { i.next(); if (i.value().contains(line)) { typeList.push_back(i.key()); } } return typeList; // QList<int> typeList; // const QTextBlock &block = m_document->findBlockByNumber(line); // if (!block.isValid()) { // return typeList; // } // TextEditor::TextBlockUserData *data = TextEditor::BaseTextDocumentLayout::testUserData(block); // if (data) { // foreach(TextEditor::ITextMark *mark, data->marks()) { // typeList.append(((LiteTextMark*)mark)->type()); // } // } // return typeList; } LiteEditor *LiteEditorMark::editor() const { return m_editor; } QString LiteEditorMark::filePath() const { return m_editor->filePath(); }
10,497
C++
.cpp
332
27.557229
151
0.676354
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,488
snippetapi.cpp
visualfc_liteide/liteidex/src/plugins/liteeditor/snippetapi.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: snippet.cpp // Creator: visualfc <visualfc@gmail.com> #include "snippetapi.h" #include "qjson/include/QJson/Parser" #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 SnippetApi::SnippetApi(const QString &package) : m_package(package), m_bLoad(false) { } SnippetApi::~SnippetApi() { foreach (LiteApi::Snippet *s, m_snippetList) { delete s; } m_snippetList.clear(); } QString SnippetApi::package() const { return m_package; } QStringList SnippetApi::apiFiles() const { return m_apiFiles; } QList<LiteApi::Snippet*> SnippetApi::snippetList() const { return m_snippetList; } bool SnippetApi::loadApi() { if (m_bLoad) { return true; } m_bLoad = true; QJson::Parser parser; QString name; QString info; QString text; foreach (QString file, m_apiFiles) { QFile f(file); if (!f.open(QIODevice::ReadOnly)) { continue; } QByteArray data = f.readAll(); bool ok; QVariant json = parser.parse(data, &ok); if (ok) { foreach (QVariant v, json.toList()) { QMap<QString,QVariant> m = v.toMap(); name = m.value("name").toString(); info = m.value("info").toString(); text = m.value("text").toString(); if (!name.isEmpty() && !info.isEmpty() && !text.isEmpty()) { LiteApi::Snippet *snippet = new LiteApi::Snippet; snippet->Name = name; snippet->Info = info; snippet->Text = text; m_snippetList.append(snippet); } } } } return !m_snippetList.isEmpty(); } void SnippetApi::appendApiFile(const QString &file) { m_apiFiles.append(file); } void SnippetApi::setApiFiles(const QStringList &files) { m_apiFiles = files; } bool SnippetApi::isEmpty() const { return m_apiFiles.isEmpty(); }
3,255
C++
.cpp
106
25.660377
82
0.615556
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,489
liteeditorplugin.cpp
visualfc_liteide/liteidex/src/plugins/liteeditor/liteeditorplugin.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: liteeditorplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "liteeditorplugin.h" #include "liteeditorfilefactory.h" #include "liteeditoroptionfactory.h" #include "liteeditor_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 LiteEditorPlugin::LiteEditorPlugin() { } bool LiteEditorPlugin::load(LiteApi::IApplication *app) { m_liteApp = app; QString style = app->settings()->value(EDITOR_STYLE,"default.xml").toString(); if (!style.isEmpty()) { QString styleFileName = app->resourcePath()+"/liteeditor/color/"+style; if (!QFileInfo(styleFileName).exists()) { styleFileName = app->resourcePath()+"/liteeditor/color/default.xml"; } app->editorManager()->loadColorStyleScheme(styleFileName); } LiteEditorFileFactory *factory = new LiteEditorFileFactory(app,this); app->editorManager()->addFactory(factory); foreach(QString mime, app->editorManager()->mimeTypeList()) { if (mime.startsWith("text/") || mime.startsWith("application/")) { LiteApi::IMimeType *imt = app->mimeTypeManager()->findMimeType(mime); if (imt) { QString custom = app->settings()->value(EDITOR_CUSTOMEXTENSION+mime,"").toString(); if (!custom.isEmpty()) { imt->setCustomPatterns(custom.split(";")); } } } } app->optionManager()->addFactory(new LiteEditorOptionFactory(app,this)); m_toolBarAct = new QAction(tr("Edit ToolBar"),this); m_toolBarAct->setCheckable(true); m_toolBarAct->setChecked(m_liteApp->settings()->value(EDITOR_TOOLBAR_VISIBLE,true).toBool()); app->actionManager()->insertViewMenu(LiteApi::ViewMenuToolBarPos,m_toolBarAct); connect(m_toolBarAct,SIGNAL(triggered(bool)),this,SLOT(editorToolBarVisibleChanged(bool))); m_navBarAct = new QAction(tr("Edit Navigation Bar"),this); m_navBarAct->setCheckable(true); m_navBarAct->setChecked(m_liteApp->settings()->value(EDITOR_NAVBAR_VISIBLE,true).toBool()); app->actionManager()->insertViewMenu(LiteApi::ViewMenuToolBarPos,m_navBarAct); connect(m_navBarAct,SIGNAL(triggered(bool)),this,SLOT(editorNavigateVisibleChanged(bool))); return true; } void LiteEditorPlugin::editorToolBarVisibleChanged(bool b) { m_liteApp->settings()->setValue(EDITOR_TOOLBAR_VISIBLE,b); m_liteApp->sendBroadcast("liteeditor",EDITOR_TOOLBAR_VISIBLE,b); } void LiteEditorPlugin::editorNavigateVisibleChanged(bool b) { m_liteApp->settings()->setValue(EDITOR_NAVBAR_VISIBLE,b); m_liteApp->sendBroadcast("liteeditor",EDITOR_NAVBAR_VISIBLE,b); } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
3,972
C++
.cpp
88
40.75
99
0.691374
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,490
wordapi.cpp
visualfc_liteide/liteidex/src/plugins/liteeditor/wordapi.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: wordapi.cpp // Creator: visualfc <visualfc@gmail.com> #include "wordapi.h" #include <QFile> #include <QXmlStreamReader> #include <QCoreApplication> #include <QFile> #include <QDir> #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 WordApi::WordApi(const QString &package) : m_package(package), m_bLoad(false) { } QString WordApi::package() const { return m_package; } QStringList WordApi::apiFiles() const { return m_apiFiles; } QStringList WordApi::wordList() const { return m_wordList; } QStringList WordApi::expList() const { return m_expList; } void WordApi::appendExp(const QStringList &list) { m_expList.append(list); } bool WordApi::loadApi() { if (m_bLoad) { return true; } m_bLoad = true; m_wordList.clear(); foreach (QString file, m_apiFiles) { QFile f(file); if (!f.open(QIODevice::ReadOnly)) { continue; } while (!f.atEnd()) { QString line = f.readLine().trimmed(); if (!line.isEmpty()) { m_wordList.append(line); } } } return !m_wordList.isEmpty(); } void WordApi::appendApiFile(const QString &file) { m_apiFiles.append(file); } void WordApi::setApiFiles(const QStringList &files) { m_apiFiles = files; } bool WordApi::isEmpty() const { return m_apiFiles.isEmpty(); }
2,667
C++
.cpp
96
24.541667
82
0.655065
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,491
liteeditorwidget.cpp
visualfc_liteide/liteidex/src/plugins/liteeditor/liteeditorwidget.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: liteeditorwidget.cpp // Creator: visualfc <visualfc@gmail.com> #include "liteeditorwidget.h" #include <QCompleter> #include <QKeyEvent> #include <QAbstractItemView> #include <QApplication> #include <QModelIndex> #include <QAbstractItemModel> #include <QScrollBar> #include <QTextDocument> #include <QTextCursor> #include <QTextBlock> #include <QTextBlockFormat> #include <QTextDocumentFragment> #include <QMimeData> #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 LiteEditorWidget::LiteEditorWidget(LiteApi::IApplication *app, QWidget *parent) : LiteEditorWidgetBase(app,parent), m_completer(0), m_contextMenu(0), m_scrollWheelZooming(true), m_bSpellCheckZoneDontComplete(false), m_bCopyToHtml(true) { this->m_averageCharWidth = QFontMetrics(this->font()).averageCharWidth(); } void LiteEditorWidget::setContextMenu(QMenu *contextMenu) { m_contextMenu = contextMenu; } void LiteEditorWidget::setCompleter(LiteApi::ICompleter *completer) { m_completer = completer; } void LiteEditorWidget::codeCompleter() { QTextCursor cursor = this->textCursor(); bool isInImport = false; if (m_textLexer->isInStringOrComment(cursor)) { isInImport = m_textLexer->isInImport(cursor); if (!isInImport) { return; } } if (isInImport) { QString completionPrefix = importUnderCursor(textCursor()); m_completer->setCompletionContext(LiteApi::CompleterImportContext); m_completer->setCompletionPrefix(""); m_completer->startCompleter(completionPrefix); } else { QString completionPrefix = textUnderCursor(textCursor()); if (completionPrefix.startsWith(".")) { completionPrefix.insert(0,'@'); } m_completer->setCompletionContext(LiteApi::CompleterCodeContext); m_completer->setCompletionPrefix(""); emit completionPrefixChanged(completionPrefix,true); m_completer->startCompleter(completionPrefix); } } QString LiteEditorWidget::wordUnderCursor() const { QTextCursor tc = textCursor(); tc.select(QTextCursor::WordUnderCursor); return tc.selectedText(); } QString LiteEditorWidget::importUnderCursor(QTextCursor tc) const { QString text = tc.block().text().left(tc.positionInBlock()); if (text.isEmpty()) { return QString(); } static QRegExp reg("[\"`][a-zA-Z0-9_\\-\\.\\/]*$"); int index = reg.indexIn(text); if (index < 0) { return QString(); } return text.right(reg.matchedLength()-1); } QString LiteEditorWidget::textUnderCursor(QTextCursor tc) const { QString text = tc.block().text().left(tc.positionInBlock()); if (text.isEmpty()) { return QString(); } //int index = text.lastIndexOf(QRegExp("\\b[a-zA-Z_][a-zA-Z0-9_\.]+")); static QRegExp reg("[a-zA-Z0-9_\\.]+[a-zA-Z0-9_\\.\\:]*$"); int index = reg.indexIn(text); if (index < 0) { return QString(); } return text.right(reg.matchedLength()); //int index = text.lastIndexOf(QRegExp("[\w]+$")); // qDebug() << ">" << text << index; // int left = text.lastIndexOf(QRegExp("[ |\t|\"|\(|\)|\'|<|>]")); // text = text.right(text.length()-left+1); //return ""; } void LiteEditorWidget::focusInEvent(QFocusEvent *e) { LiteEditorWidgetBase::focusInEvent(e); } void LiteEditorWidget::wheelEvent(QWheelEvent *e) { if (m_scrollWheelZooming && e->modifiers() & Qt::ControlModifier) { const int delta = e->delta(); if (delta < 0) zoomOut(); else if (delta > 0) zoomIn(); return; } LiteEditorWidgetBase::wheelEvent(e); } void LiteEditorWidget::contextMenuEvent(QContextMenuEvent *e) { QTextCursor cur = this->textCursor(); if (!cur.hasSelection()) { cur = this->cursorForPosition(e->pos()); this->setTextCursor(cur); } if (m_contextMenu) { m_contextMenu->exec(e->globalPos()); } } void LiteEditorWidget::keyPressEvent(QKeyEvent *e) { if (!m_completer) { LiteEditorWidgetBase::keyPressEvent(e); return; } if (m_inputCursorOffset > 0) { m_completer->hidePopup(); LiteEditorWidgetBase::keyPressEvent(e); return; } if (m_completer->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: case Qt::Key_Shift: e->ignore(); return; // let the completer do default behavior case Qt::Key_N: case Qt::Key_P: if (e->modifiers() == Qt::ControlModifier) { e->ignore(); return; } default: break; } } LiteEditorWidgetBase::keyPressEvent(e); bool isInImport = false; if (m_textLexer->isInStringOrComment(this->textCursor())) { isInImport = m_textLexer->isInImport(this->textCursor()); if (!isInImport) { m_completer->hidePopup(); return; } } const bool ctrlOrShift = e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier); //always break if ctrl is pressed and there's a key // if (((e->modifiers() & Qt::ControlModifier) && !e->text().isEmpty())) { // return; // } if (e->modifiers() & Qt::ControlModifier) { if (!e->text().isEmpty()) { m_completer->hidePopup(); } return; } if (e->key() == Qt::Key_Tab || e->key() == Qt::Key_Backtab) { return; } if (e->text().isEmpty()) { if (e->key() != Qt::Key_Backspace) { m_completer->hidePopup(); return; } } //import line if (isInImport) { QString completionPrefix = importUnderCursor(textCursor()); m_completer->setCompletionContext(LiteApi::CompleterImportContext); m_completer->setCompletionPrefix(""); m_completer->startCompleter(completionPrefix); return; } //static QString eow("~!@#$%^&*()+{}|:\"<>?,/;'[]\\-="); // end of word static QString eow("~!@#$%^&*()+{}|\"<>?,/;'[]\\-="); // end of word QString completionPrefix = textUnderCursor(textCursor()); bool hasModifier = ((e->modifiers() != Qt::NoModifier) && !ctrlOrShift) && completionPrefix.right(1) != "."; if (completionPrefix.startsWith("...")) { completionPrefix = completionPrefix.mid(3); } else if (completionPrefix.startsWith(".")) { completionPrefix.insert(0,'@'); } if (hasModifier || e->text().isEmpty() || ( (completionPrefix.length() < m_completer->prefixMin()) && (completionPrefix.right(1) != ".") ) || eow.contains(e->text().right(1))) { if (m_completer->popup()->isVisible()) { m_completer->popup()->hide(); //fmt.Print( -> Print if (e->text() == "(") { QTextCursor cur = textCursor(); cur.movePosition(QTextCursor::Left); QString lastPrefix = textUnderCursor(cur); if (lastPrefix.startsWith(".")) { lastPrefix.insert(0,"@"); } if (!lastPrefix.isEmpty() && lastPrefix == m_completer->completionPrefix() ) { if (lastPrefix == m_completer->currentCompletion() || lastPrefix.endsWith("."+m_completer->currentCompletion())) { m_completer->updateCompleteInfo(m_completer->currentIndex()); } } } } if (e->key() == Qt::Key_Backspace && completionPrefix.isEmpty()) { m_completer->setCompletionPrefix("$"); } return; } m_completer->setCompletionContext(LiteApi::CompleterCodeContext); emit completionPrefixChanged(completionPrefix,false); m_completer->startCompleter(completionPrefix); } void LiteEditorWidget::inputMethodEvent(QInputMethodEvent *e) { if (!e->preeditString().isEmpty()) { m_completer->hidePopup(); } LiteEditorWidgetBase::inputMethodEvent(e); } static void convertToPlainText(QString &txt) { QChar *uc = txt.data(); QChar *e = uc + txt.size(); for (; uc != e; ++uc) { switch (uc->unicode()) { case 0xfdd0: // QTextBeginningOfFrame case 0xfdd1: // QTextEndOfFrame case QChar::ParagraphSeparator: case QChar::LineSeparator: *uc = QLatin1Char('\n'); break; case QChar::Nbsp: *uc = QLatin1Char(' '); break; default: ; } } } QString LiteEditorWidget::cursorToHtml(QTextCursor cursor) const { QTextDocument *tempDocument = new QTextDocument; QTextCursor tempCursor(tempDocument); tempCursor.insertFragment(cursor.selection()); // Apply the additional formats set by the syntax highlighter QTextBlock start = document()->findBlock(cursor.selectionStart()); QTextBlock end = document()->findBlock(cursor.selectionEnd()); end = end.next(); const int selectionStart = cursor.selectionStart(); const int endOfDocument = tempDocument->characterCount() - 1; for (QTextBlock current = start; current.isValid() && current != end; current = current.next()) { const QTextLayout *layout = current.layout(); foreach (const QTextLayout::FormatRange &range, layout->additionalFormats()) { const int start = current.position() + range.start - selectionStart; const int end = start + range.length; if (end <= 0 || start >= endOfDocument) continue; tempCursor.setPosition(qMax(start, 0)); tempCursor.setPosition(qMin(end, endOfDocument), QTextCursor::KeepAnchor); tempCursor.setCharFormat(range.format); } } // Reset the user states since they are not interesting for (QTextBlock block = tempDocument->begin(); block.isValid(); block = block.next()) block.setUserState(-1); // Make sure the text appears pre-formatted tempCursor.setPosition(0); tempCursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor); QTextBlockFormat blockFormat = tempCursor.blockFormat(); blockFormat.setNonBreakableLines(true); tempCursor.setBlockFormat(blockFormat); QString html = tempCursor.selection().toHtml();//("utf-8"); //html.replace("\t","&nbsp&nbsp&nbsp&nbsp"); delete tempDocument; return html; } static const char kVerticalTextBlockMimeType[] = "application/vnd.liteide.vblocktext"; QMimeData *LiteEditorWidget::createMimeDataFromSelection() const { QTextCursor cursor = textCursor(); if (m_inBlockSelectionMode) { QMimeData *mimeData = new QMimeData; QString text = this->copyBlockSelection(); mimeData->setData(QLatin1String(kVerticalTextBlockMimeType), text.toUtf8()); mimeData->setText(text); // for exchangeability return mimeData; } else if (cursor.hasSelection()) { QMimeData *mimeData = new QMimeData; QString text = cursor.selectedText(); convertToPlainText(text); mimeData->setText(text); // Copy the selected text as HTML if (m_bCopyToHtml) { mimeData->setHtml(cursorToHtml(cursor)); } return mimeData; } return 0; } bool LiteEditorWidget::canInsertFromMimeData(const QMimeData *source) const { return QPlainTextEdit::canInsertFromMimeData(source); } void LiteEditorWidget::insertFromMimeData(const QMimeData *source) { if (isReadOnly()) return; if (source->hasFormat(QLatin1String(kVerticalTextBlockMimeType))) { QString text = QString::fromUtf8(source->data(QLatin1String(kVerticalTextBlockMimeType))); if (text.isEmpty()) return; QStringList lines = text.split(QLatin1Char('\n')); QTextCursor cursor = textCursor(); cursor.beginEditBlock(); const TextEditor::TabSettings &ts = this->tabSettings(); int initialCursorPosition = cursor.position(); int column = ts.columnAt(cursor.block().text(), cursor.positionInBlock()); cursor.insertText(lines.first()); for (int i = 1; i < lines.count(); ++i) { QTextBlock next = cursor.block().next(); if (next.isValid()) { cursor.setPosition(next.position()); } else { cursor.movePosition(QTextCursor::EndOfBlock); cursor.insertBlock(); } int offset = 0; int position = ts.positionAtColumn(cursor.block().text(), column, &offset); cursor.setPosition(cursor.block().position() + position); if (offset < 0) { cursor.deleteChar(); cursor.insertText(QString(-offset, QLatin1Char(' '))); } else { cursor.insertText(QString(offset, QLatin1Char(' '))); } cursor.insertText(lines.at(i)); } cursor.setPosition(initialCursorPosition); cursor.endEditBlock(); setTextCursor(cursor); ensureCursorVisible(); return; } QPlainTextEdit::insertFromMimeData(source); } void LiteEditorWidget::zoomIn(int range) { emit requestFontZoom(range*10); } void LiteEditorWidget::zoomOut(int range) { emit requestFontZoom(-range*10); } void LiteEditorWidget::updateFont(const QFont &font) { this->setFont(font); this->extraArea()->setFont(font); this->m_averageCharWidth = QFontMetrics(font).averageCharWidth(); this->updateTabWidth(); this->slotUpdateExtraAreaWidth(); if (this->m_completer) { this->m_completer->popup()->setFont(font); } } void LiteEditorWidget::dropEvent(QDropEvent *event) { QList<QUrl> urls = event->mimeData()->urls(); if (urls.isEmpty()) { LiteEditorWidgetBase::dropEvent(event); return; } bool hasFile = false; foreach (QUrl url, urls) { QString fileName = url.toLocalFile(); if (!fileName.isEmpty()) { QFileInfo info(fileName); if (info.isFile()) { m_liteApp->fileManager()->openEditor(fileName,true); } else if(info.isDir()) { m_liteApp->fileManager()->addFolderList(fileName); } hasFile = true; } } if (hasFile) { event->accept(); return; } LiteEditorWidgetBase::dropEvent(event); }
16,450
C++
.cpp
444
29.150901
113
0.606883
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,492
liteeditorwidgetbase.cpp
visualfc_liteide/liteidex/src/plugins/liteeditor/liteeditorwidgetbase.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: liteeditorwidgetbase.cpp // Creator: visualfc <visualfc@gmail.com> #include "liteeditorwidgetbase.h" #include "qtc_texteditor/basetextdocumentlayout.h" #include "quickopenapi/quickopenapi.h" #include <QCoreApplication> #include <QApplication> #include <QTextBlock> #include <QPainter> #include <QPainterPath> #include <QStyle> #include <QDebug> #include <QMessageBox> #include <QToolTip> #include <QTextCursor> #include <QTextDocumentFragment> #include <QScrollBar> #include <QInputMethodEvent> #include <QTimer> #include <cmath> //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 const int PRIORITYLIST_LENGTH = 7; const LiteApi::EditorNaviagteType MARKTYPE_PRIORITYLIST[PRIORITYLIST_LENGTH] = { LiteApi::EditorNavigateError, LiteApi::EditorNavigateBad, LiteApi::EditorNavigateWarning, LiteApi::EditorNavigateReload, LiteApi::EditorNavigateFind, LiteApi::EditorNavigateSelection, LiteApi::EditorNavigateNormal }; inline QColor markTypeColor(LiteApi::EditorNaviagteType type) { switch(type) { case LiteApi::EditorNavigateBad: case LiteApi::EditorNavigateError: return Qt::darkRed; case LiteApi::EditorNavigateWarning: //Returns orange color return QColor::fromRgb(255, 125, 0); case LiteApi::EditorNavigateNormal: return Qt::darkGreen; case LiteApi::EditorNavigateReload: return Qt::darkBlue; case LiteApi::EditorNavigateFind: return Qt::darkYellow; case LiteApi::EditorNavigateSelection: return Qt::darkBlue; } return Qt::darkGreen; } struct NavigateMark { NavigateMark() {} ~NavigateMark() { foreach (Node *node, m_nodeList) { delete node; } m_nodeList.clear(); } struct Node { LiteApi::EditorNaviagteType type; QString msg; QString tag; int offset; int selection; QColor markColor() { return markTypeColor(type); } }; void addNode(LiteApi::EditorNaviagteType type, const QString & msg, const QString &tag = "", int offset = 0, int selection = 0) { Node *node = new Node; node->type = type; node->msg = msg; node->offset = offset; node->selection = selection; node->tag = QString(tag); m_nodeList.append(node); } Node* findNode(LiteApi::EditorNaviagteType type) { foreach (Node *node, m_nodeList) { if (node->type == type) { return node; } } return 0; } void removeNode(LiteApi::EditorNaviagteType types, const QString &tag = "") { QMutableListIterator<Node*> i(m_nodeList); while (i.hasNext()) { Node *node = i.next(); if ((node->type&types) && (tag.isEmpty() || tag == node->tag)) { i.remove(); delete node; } } } bool isEmpty() const { return m_nodeList.isEmpty(); } QList<Node*> m_nodeList; }; typedef QMap<int,NavigateMark*> NavigateMarkMap; class NavigateManager : public QObject { public: NavigateManager(QObject *parent) : QObject(parent) { m_type = LiteApi::EditorNavigateNormal; } ~NavigateManager() { clearAll(); } void insertMark(int blockNumber, const QString &msg, LiteApi::EditorNaviagteType type, const QString &tag = "", int offset = 0, int selection = 0) { NavigateMarkMap::iterator it = markMap.find(blockNumber); if (it == markMap.end()) { NavigateMark *mark = new NavigateMark; mark->addNode(type, msg, tag, offset, selection); markMap.insert(blockNumber,mark); } else { NavigateMark *mark = it.value(); NavigateMark::Node *node = mark->findNode(type); if (node) { node->msg = msg; node->tag = tag; node->offset = offset; node->selection = selection; } else { mark->addNode(type,msg,tag,offset,selection); } } } void clearAllNavigateMark(LiteApi::EditorNaviagteType types, const QString &tag = "") { QMutableMapIterator<int,NavigateMark*> i(markMap); while (i.hasNext()) { i.next(); NavigateMark *mark = i.value(); mark->removeNode(types, tag); if (mark->isEmpty()) { delete mark; i.remove(); } } } void clearAll() { foreach(NavigateMark *mark,markMap.values()) { delete mark; } markMap.clear(); } void setType(LiteApi::EditorNaviagteType type, const QString &msg) { m_type = type; m_msg = msg; } QColor headMarkColor() { return markTypeColor(m_type); } public: NavigateMarkMap markMap; LiteApi::EditorNaviagteType m_type; QString m_msg; }; class TextEditExtraArea : public QWidget { public: TextEditExtraArea(LiteEditorWidgetBase *edit):QWidget(edit) { textEdit = edit; setAutoFillBackground(true); } public: QSize sizeHint() const { return QSize(textEdit->extraAreaWidth(), 0); } protected: void paintEvent(QPaintEvent *event){ textEdit->extraAreaPaintEvent(event); } void mousePressEvent(QMouseEvent *event){ textEdit->extraAreaMouseEvent(event); } void mouseMoveEvent(QMouseEvent *event){ textEdit->extraAreaMouseEvent(event); } void mouseReleaseEvent(QMouseEvent *event){ textEdit->extraAreaMouseEvent(event); } void leaveEvent(QEvent *event){ textEdit->extraAreaLeaveEvent(event); } void wheelEvent(QWheelEvent *event) { QCoreApplication::sendEvent(textEdit->viewport(), event); } protected: LiteEditorWidgetBase *textEdit; }; class TextEditNavigateArea : public QWidget { public: TextEditNavigateArea(LiteEditorWidgetBase *edit):QWidget(edit) { textEdit = edit; setAutoFillBackground(true); } public: QSize sizeHint() const { return QSize(textEdit->navigateAreaWidth(), 0); } protected: void paintEvent(QPaintEvent *event){ textEdit->navigateAreaPaintEvent(event); } void mousePressEvent(QMouseEvent *event){ textEdit->navigateAreaMouseEvent(event); } void mouseMoveEvent(QMouseEvent *event){ textEdit->navigateAreaMouseEvent(event); } void mouseReleaseEvent(QMouseEvent *event){ textEdit->navigateAreaMouseEvent(event); } void enterEvent(QEvent * event) { this->setMouseTracking(true); textEdit->navigateAreaEnterEvent(event); } void leaveEvent(QEvent *event){ this->setMouseTracking(false); textEdit->navigateAreaLeaveEvent(event); } protected: LiteEditorWidgetBase *textEdit; }; class BaseTextLexer : public LiteApi::ITextLexer { public: BaseTextLexer(QObject *parent = 0) : LiteApi::ITextLexer(parent), m_bAC(true), m_bCC(true) { } virtual bool isLangSupport() const { return false; } virtual bool isInComment(const QTextCursor &/*cursor*/) const { return false; } virtual bool isInString(const QTextCursor &cursor) const { int pos = cursor.positionInBlock(); if (pos == 0) { return false; } QString text = cursor.block().text(); if (text.mid(pos).indexOf("\"") < 0) { return false; } if (text.left(pos).indexOf("\"") < 0) { return false; } return true; } virtual bool isInEmptyString(const QTextCursor &cursor) const { int pos = cursor.positionInBlock(); if (pos > 0) { QString text = cursor.block().text(); return text.at(pos-1) == '\"' && text.at(pos) == '\"'; } return false; } virtual bool isEndOfString(const QTextCursor &cursor) const { int pos = cursor.positionInBlock(); return cursor.block().text().at(pos) == '\"'; } virtual bool isInStringOrComment(const QTextCursor &cursor) const { if (isInString(cursor)) { return true; } return false; } virtual bool isInImport(const QTextCursor &/*cursor*/) const { return false; } virtual bool isCanAutoCompleter(const QTextCursor &/*cursor*/) const { return m_bAC; } virtual void setCanCodeCompleter(bool b) { m_bCC = b; } virtual void setCanAutoCompleter(bool b) { m_bAC = b; } virtual int startOfFunctionCall(const QTextCursor &/*cursor*/) const { return -1; } virtual QString fetchFunctionTip(const QString &/*func*/, const QString &/*kind*/, const QString &/*info*/) { return QString(); } virtual bool fetchFunctionArgs(const QString &/*str*/, int &/*argnr*/, int &/*parcount*/) { return false; } virtual QString stringQuoteList() const { return QString("\""); } virtual bool hasStringBackslash() const { return false; } protected: bool m_bAC; bool m_bCC; }; LiteEditorWidgetBase::LiteEditorWidgetBase(LiteApi::IApplication *app, QWidget *parent) : QPlainTextEdit(parent), m_liteApp(app), m_editorMark(0), m_textLexer(new BaseTextLexer()), m_contentsChanged(false), m_lastCursorChangeWasInteresting(false) { m_inputCursorOffset = 0; m_upToolTipTime = 200; m_linkPressed = false; m_moveLineUndoHack = false; setLineWrapMode(QPlainTextEdit::NoWrap); m_extraArea = new TextEditExtraArea(this); m_navigateArea = new TextEditNavigateArea(this); m_navigateManager = new NavigateManager(this); m_indentLineForeground = QColor(Qt::darkCyan); m_visualizeWhitespaceForeground = QColor(Qt::darkGray); m_extraForeground = QColor(Qt::darkCyan); m_extraBackground = m_extraArea->palette().color(QPalette::Background); m_currentLineBackground = QColor(180,200,200,128); m_matchBracketsBackground = QColor(Qt::gray); m_matchBracketsBackground.setAlpha(128); setLayoutDirection(Qt::LeftToRight); viewport()->setMouseTracking(true); m_allowVscrollLastLine = true; m_lineNumbersVisible = true; m_navigateWidgetVisible = true; m_marksVisible = true; m_codeFoldingVisible = true; m_rightLineVisible = true; m_eofVisible = false; m_indentLineVisible = true; m_rightLineWidth = 80; m_lastSaveRevision = 0; m_extraAreaSelectionNumber = -1; m_autoIndent = true; m_bLastBraces = false; m_bTabUseSpace = false; m_nTabSize = 4; m_mouseOnFoldedMarker = false; m_uplinkSkip = false; m_mouseNavigation = true; m_showLinkNavigation = false; m_showLinkInfomation = false; m_visualizeWhitespace = false; m_lastLine = -1; m_inBlockSelectionMode = false; m_maxTipInfoLines = 10; m_upToolTipDeployTimer = new QTimer(this); m_upToolTipDeployTimer->setSingleShot(true); connect(m_upToolTipDeployTimer,SIGNAL(timeout()),this,SLOT(uplinkDeployTimeout())); m_upToolTipTimer = new QTimer(this); m_upToolTipTimer->setSingleShot(true); connect(m_upToolTipTimer,SIGNAL(timeout()),this,SLOT(uplinkInfoTimeout())); m_selectionExpression.setCaseSensitivity(Qt::CaseSensitive); m_selectionExpression.setPatternSyntax(QRegExp::FixedString); connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(slotUpdateExtraAreaWidth())); connect(this, SIGNAL(modificationChanged(bool)), this, SLOT(slotModificationChanged(bool))); connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(slotCursorPositionChanged())); //connect(this, SIGNAL(selectionChanged()),this,SLOT(updateSelection())); connect(this, SIGNAL(updateRequest(QRect, int)), this, SLOT(slotUpdateRequest(QRect, int))); connect(this->document(),SIGNAL(contentsChange(int,int,int)),this,SLOT(editContentsChanged(int,int,int))); connect(this,SIGNAL(selectionChanged()),this,SLOT(slotSelectionChanged())); connect(this->verticalScrollBar(),SIGNAL(rangeChanged(int,int)),this,SLOT(verticalScrollBarRangeChanged(int,int))); QTextDocument *doc = this->document(); if (doc) { TextEditor::BaseTextDocumentLayout *layout = new TextEditor::BaseTextDocumentLayout(doc); layout->m_tabSettings.m_autoIndent = true; layout->m_tabSettings.m_autoSpacesForTabs = m_bTabUseSpace; layout->m_tabSettings.m_tabSize = m_nTabSize; doc->setDocumentLayout(layout); connect(layout,SIGNAL(updateBlock(QTextBlock)),this,SLOT(updateBlock(QTextBlock))); connect(layout,SIGNAL(documentSizeChanged(QSizeF)),this,SLOT(documentSizeChanged(QSizeF))); } updateTabWidth(); } LiteEditorWidgetBase::~LiteEditorWidgetBase() { } static void indentBlock(QTextDocument *doc, const QTextBlock &block, const QChar &typedChar, const TextEditor::TabSettings &tabSettings) { Q_UNUSED(typedChar) // At beginning: Leave as is. if (block == doc->begin()) return; if (block.text().isEmpty()) { return; } QString previousText; QTextBlock previous = block.previous(); while (previous.isValid()) { previousText = previous.text(); if (!previousText.isEmpty() && !previousText.trimmed().isEmpty()) { break; } previous = previous.previous(); } // Empty line indicates a start of a new paragraph. Leave as is. if (previousText.isEmpty() || previousText.trimmed().isEmpty()) return; int offset = 0; QString text = previousText.trimmed(); if (text.endsWith("{") || text.endsWith("(")) { offset += tabSettings.m_tabSize; } text = block.text().trimmed(); if (text.startsWith("}") || text.startsWith(")")) { offset -= tabSettings.m_tabSize; } int i = 0; while (i < previousText.size()) { if (!previousText.at(i).isSpace()) { tabSettings.indentLine(block, tabSettings.columnAt(previousText, i+offset)); break; } ++i; } } static void autoIndent(QTextDocument *doc, const QTextCursor &cursor, const TextEditor::TabSettings &tabSettings) { if (cursor.hasSelection()) { QTextBlock block = doc->findBlock(cursor.selectionStart()); const QTextBlock end = doc->findBlock(cursor.selectionEnd()).next(); // skip empty blocks while (block.isValid() && block != end) { // QString bt = block.text(); // if (tabSettings.firstNonSpace(bt) < bt.size()) // break; indentBlock(doc, block, QChar::Null, tabSettings); block = block.next(); } // int previousIndentation = tabSettings.indentationColumn(block.text()); // indentBlock(doc, block, QChar::Null, tabSettings); // int currentIndentation = tabSettings.indentationColumn(block.text()); // int delta = currentIndentation - previousIndentation; // block = block.next(); // while (block.isValid() && block != end) { // tabSettings.reindentLine(block, delta); // block = block.next(); // } } else { indentBlock(doc, cursor.block(), QChar::Null, tabSettings); } } void LiteEditorWidgetBase::setEditorMark(LiteApi::IEditorMark *mark) { m_editorMark = mark; if (m_editorMark) { connect(m_editorMark,SIGNAL(markListChanged(int)),m_extraArea,SLOT(update())); } } void LiteEditorWidgetBase::setTextLexer(LiteApi::ITextLexer *lexer) { m_textLexer.reset(lexer); } void LiteEditorWidgetBase::setTabSize(int n) { m_nTabSize = n; updateTabWidth(); TextEditor::BaseTextDocumentLayout *layout = (TextEditor::BaseTextDocumentLayout*)document()->documentLayout(); if (layout) { layout->m_tabSettings.m_tabSize = m_nTabSize; } } int LiteEditorWidgetBase::tabSize() const { return m_nTabSize; } void LiteEditorWidgetBase::updateTabWidth() { setTabStopWidth(QFontMetrics(font()).averageCharWidth() * m_nTabSize); } void LiteEditorWidgetBase::setTabToSpaces(bool b) { m_bTabUseSpace = b; TextEditor::BaseTextDocumentLayout *layout = (TextEditor::BaseTextDocumentLayout*)document()->documentLayout(); if (layout) { layout->m_tabSettings.m_autoSpacesForTabs = m_bTabUseSpace; } } void LiteEditorWidgetBase::initLoadDocument() { m_lastSaveRevision = document()->revision(); document()->setModified(false); this->moveCursor(QTextCursor::Start); } void LiteEditorWidgetBase::editContentsChanged(int position, int charsRemoved, int charsAdded) { m_contentsChanged = true; QTextDocument *doc = this->document(); TextEditor::BaseTextDocumentLayout *documentLayout = static_cast<TextEditor::BaseTextDocumentLayout*>(doc->documentLayout()); const QTextBlock posBlock = doc->findBlock(position); // Keep the line numbers and the block information for the text marks updated if (charsRemoved != 0) { documentLayout->updateMarksLineNumber(); documentLayout->updateMarksBlock(posBlock); } else { const QTextBlock nextBlock = doc->findBlock(position + charsAdded); if (posBlock != nextBlock) { documentLayout->updateMarksLineNumber(); documentLayout->updateMarksBlock(posBlock); documentLayout->updateMarksBlock(nextBlock); } else { documentLayout->updateMarksBlock(posBlock); } } if (!m_findExpression.isEmpty()) { this->updateFindOrSelectionMark(LiteApi::EditorNavigateFind); } } struct MatchBracePos { int startPos; int matchPos; bool startIsLeft; bool startIsOpen; TextEditor::TextBlockUserData::MatchType matchType; }; static bool findMatchBrace(QTextCursor &cur, MatchBracePos &mb) { QTextBlock block = cur.block(); int pos = cur.positionInBlock(); mb.startPos = -1; mb.matchPos = -1; if (block.isValid()) { TextEditor::TextBlockUserData *data = static_cast<TextEditor::TextBlockUserData*>(block.userData()); if (data) { TextEditor::Parentheses ses = data->parentheses(); QChar chr; int i = ses.size(); while(i--) { TextEditor::Parenthesis s = ses.at(i); if (s.pos == pos || s.pos+1 == pos) { mb.startPos = cur.block().position()+s.pos; mb.startIsLeft = (s.pos == pos); mb.startIsOpen = (s.type == TextEditor::Parenthesis::Opened); chr = s.chr; break; } } if (mb.startPos != -1) { if (mb.startIsOpen) { cur.setPosition(mb.startPos); mb.matchType = TextEditor::TextBlockUserData::checkOpenParenthesis(&cur,chr); mb.matchPos = cur.position()-1; } else { cur.setPosition(mb.startPos+1); mb.matchType = TextEditor::TextBlockUserData::checkClosedParenthesis(&cur,chr); mb.matchPos = cur.position(); } return true; } } } return false; } void LiteEditorWidgetBase::gotoMatchBrace() { QTextCursor cur = this->textCursor(); MatchBracePos mb; if (findMatchBrace(cur,mb) && mb.matchType == TextEditor::TextBlockUserData::Match) { if (mb.startIsLeft) { cur.setPosition(mb.matchPos+1); } else { cur.setPosition(mb.matchPos); } this->setTextCursor(cur); if (!cur.block().isVisible()) { unfold(); } ensureCursorVisible(); } } void LiteEditorWidgetBase::highlightCurrentLine() { QTextCursor cur = textCursor(); if (!cur.block().isVisible()) { unfold(); } // if (!isReadOnly()) { // QTextEdit::ExtraSelection full; // full.format.setBackground(m_currentLineBackground); // full.format.setProperty(QTextFormat::FullWidthSelection, true); // full.cursor = this->textCursor(); // //full.cursor.select(QTextCursor::LineUnderCursor); // setExtraSelections(LiteApi::CurrentLineSelection,QList<QTextEdit::ExtraSelection>() << full ); // } QList<QTextEdit::ExtraSelection> extraSelections; MatchBracePos mb; if (findMatchBrace(cur,mb)) { if (mb.matchType == TextEditor::TextBlockUserData::Match) { QTextEdit::ExtraSelection selection; cur.setPosition(mb.startPos); cur.movePosition(QTextCursor::Right,QTextCursor::KeepAnchor,1); selection.cursor = cur; selection.format.setFontUnderline(true); selection.format.setBackground(m_matchBracketsBackground); selection.format.setProperty(LiteEditorWidgetBase::MatchBrace,true); extraSelections.append(selection); cur.setPosition(mb.matchPos); cur.movePosition(QTextCursor::Right,QTextCursor::KeepAnchor,1); selection.cursor = cur; selection.format.setFontUnderline(true); selection.format.setProperty(LiteEditorWidgetBase::MatchBrace,true); extraSelections.append(selection); } else if (mb.matchType == TextEditor::TextBlockUserData::Mismatch) { QTextEdit::ExtraSelection selection; cur.setPosition(mb.startPos); cur.movePosition(QTextCursor::Right,QTextCursor::KeepAnchor,1); selection.cursor = cur; selection.format.setFontUnderline(true); selection.format.setUnderlineStyle(QTextCharFormat::SpellCheckUnderline); selection.format.setProperty(LiteEditorWidgetBase::MatchBrace,true); selection.format.setForeground(Qt::red); extraSelections.append(selection); } } setExtraSelections(LiteApi::ParenthesesMatchingSelection,extraSelections); viewport()->update(); } static int foldBoxWidth(const QFontMetrics &fm) { const int lineSpacing = fm.lineSpacing(); return lineSpacing/2+lineSpacing%2+1; } QWidget* LiteEditorWidgetBase::extraArea() { return m_extraArea; } QWidget *LiteEditorWidgetBase::navigateArea() { return m_navigateArea; } void LiteEditorWidgetBase::setCurrentLineColor(const QColor &background) { if (background.isValid()) { m_currentLineBackground = background; } else { m_currentLineBackground = QColor(180,200,200,128); } m_currentLineBackground.setAlpha(128); } void LiteEditorWidgetBase::setMatchBracketsColor(const QColor &background) { if (background.isValid()) { m_matchBracketsBackground = background; } else { m_matchBracketsBackground = Qt::gray; } m_matchBracketsBackground.setAlpha(128); } void LiteEditorWidgetBase::setIndentLineColor(const QColor &foreground) { if (foreground.isValid()) { m_indentLineForeground = foreground; } else { m_indentLineForeground = QColor(Qt::darkCyan); } m_indentLineForeground.setAlpha(128); } void LiteEditorWidgetBase::setVisualizeWhitespaceColor(const QColor &foreground) { if (foreground.isValid()) { m_visualizeWhitespaceForeground = foreground; } else { m_visualizeWhitespaceForeground = QColor(Qt::darkGray); } m_visualizeWhitespaceForeground.setAlpha(200); } void LiteEditorWidgetBase::setExtraColor(const QColor &foreground,const QColor &background) { if (foreground.isValid()) { m_extraForeground = foreground; } else { m_extraForeground = QColor(Qt::darkCyan); } if (background.isValid()) { m_extraBackground = background; } else { m_extraBackground = m_extraArea->palette().color(QPalette::Background); } } int LiteEditorWidgetBase::extraAreaWidth() { int space = 0; const QFontMetrics fm(m_extraArea->fontMetrics()); if (m_lineNumbersVisible) { QFont fnt = m_extraArea->font(); fnt.setBold(true); const QFontMetrics linefm(fnt); int digits = 2; int max = qMax(1, blockCount()); while (max >= 100) { max /= 10; ++digits; } space += linefm.width(QLatin1Char('9')) * digits; } if (m_marksVisible) { int markWidth = fm.lineSpacing(); space += markWidth; } else { space += 3; } if (m_codeFoldingVisible) { space += foldBoxWidth(fm); } space += 4; return space; } void LiteEditorWidgetBase::drawFoldingMarker(QPainter *painter, const QPalette&, const QRect &rect, bool expanded) const { painter->save(); painter->setPen(Qt::NoPen); int size = rect.size().width(); int sqsize = 2*(size/2); QColor textColor = m_extraForeground; QColor brushColor = m_extraBackground; textColor.setAlpha(128); brushColor.setAlpha(128); QPolygon a; if (expanded) { // down arrow //a.setPoints(3, 0, sqsize/3, sqsize/2, sqsize - sqsize/3, sqsize, sqsize/3); a.setPoints(3, 1, sqsize/2+sqsize/3, sqsize/2+sqsize/3, sqsize/2+sqsize/3,sqsize/2+sqsize/3,1); } else { // right arrow a.setPoints(3, sqsize - sqsize/3, sqsize/2, sqsize/2 - sqsize/3, 0, sqsize/2 - sqsize/3, sqsize); } painter->translate(0.5, 0.5); painter->setRenderHint(QPainter::Antialiasing); painter->translate(rect.topLeft()); painter->setPen(textColor); if (expanded) { painter->setBrush(textColor); } else { painter->setBrush(brushColor); } painter->drawPolygon(a); painter->restore(); } void LiteEditorWidgetBase::extraAreaPaintEvent(QPaintEvent *e) { QTextDocument *doc = document(); int selStart = textCursor().selectionStart(); int selEnd = textCursor().selectionEnd(); QPalette pal = m_extraArea->palette(); pal.setCurrentColorGroup(QPalette::Active); QPainter painter(m_extraArea); const QFontMetrics fm(m_extraArea->font()); int fmLineSpacing = fm.lineSpacing(); int markWidth = 0; if (m_marksVisible) markWidth += fm.lineSpacing(); const int collapseColumnWidth = m_codeFoldingVisible ? foldBoxWidth(fm): 0; const int extraAreaWidth = m_extraArea->width() - collapseColumnWidth; // painter.fillRect(e->rect(), pal.color(QPalette::Base)); // painter.fillRect(e->rect().intersected(QRect(0, 0, m_extraArea->width(), INT_MAX)), // m_extraBackground); painter.fillRect(e->rect(),m_extraBackground); //painter.setPen(QPen(m_extraForeground,1,Qt::DotLine)); // painter.drawLine(extraAreaWidth - 3, e->rect().top(), extraAreaWidth - 3, e->rect().bottom()); //painter.drawLine(e->rect().width()-1, e->rect().top(), e->rect().width()-1, e->rect().bottom()); QTextBlock block = firstVisibleBlock(); int blockNumber = block.blockNumber(); qreal top = blockBoundingGeometry(block).translated(contentOffset()).top(); qreal bottom = top; painter.setPen(QPen(m_extraForeground,1)); while (block.isValid() && top <= e->rect().bottom()) { top = bottom; const qreal height = blockBoundingRect(block).height(); bottom = top + height; QTextBlock nextBlock = block.next(); QTextBlock nextVisibleBlock = nextBlock; int nextVisibleBlockNumber = blockNumber + 1; if (!nextVisibleBlock.isVisible()) { // invisible blocks do have zero line count nextVisibleBlock = doc->findBlockByLineNumber(nextVisibleBlock.firstLineNumber()); nextVisibleBlockNumber = nextVisibleBlock.blockNumber(); } if (bottom < e->rect().top()) { block = nextVisibleBlock; blockNumber = nextVisibleBlockNumber; continue; } if (m_codeFoldingVisible || m_marksVisible) { painter.save(); painter.setRenderHint(QPainter::Antialiasing, false); int previousBraceDepth = block.previous().userState(); if (previousBraceDepth >= 0) previousBraceDepth >>= 8; else previousBraceDepth = 0; int braceDepth = block.userState(); if (!nextBlock.isVisible()) { QTextBlock lastInvisibleBlock = nextVisibleBlock.previous(); if (!lastInvisibleBlock.isValid()) lastInvisibleBlock = doc->lastBlock(); braceDepth = lastInvisibleBlock.userState(); } if (braceDepth >= 0) braceDepth >>= 8; else braceDepth = 0; if (TextEditor::TextBlockUserData *userData = static_cast<TextEditor::TextBlockUserData*>(block.userData())) { if (m_marksVisible) { int xoffset = 2; foreach (TextEditor::ITextMark *mrk, userData->marks()) { int radius = fmLineSpacing - 1; QRect r(xoffset*mrk->indexOfType(), top, radius, radius); mrk->paint(&painter, r); } } } if (m_codeFoldingVisible) { TextEditor::TextBlockUserData *nextBlockUserData = TextEditor::BaseTextDocumentLayout::testUserData(nextBlock); bool drawBox = nextBlockUserData && TextEditor::BaseTextDocumentLayout::foldingIndent(block) < nextBlockUserData->foldingIndent(); int boxWidth = foldBoxWidth(fm)+1; if (drawBox) { bool expanded = nextBlock.isVisible(); QRect box(extraAreaWidth-2, top + (fm.lineSpacing()-boxWidth)/2, boxWidth-1,boxWidth-1); drawFoldingMarker(&painter, pal, box, expanded); } } painter.restore(); } if (block.revision() != m_lastSaveRevision) { painter.save(); painter.setRenderHint(QPainter::Antialiasing, false); if (block.revision() < 0) painter.setPen(QPen(Qt::darkGreen, 2)); else painter.setPen(QPen(Qt::red, 2)); painter.drawLine(extraAreaWidth - 1, top, extraAreaWidth - 1, bottom - 1); painter.restore(); } // if (/*m_marksVisible &&*/ m_editorMark) { // m_editorMark->paint(&painter,blockNumber,0,top,fmLineSpacing-0.5,fmLineSpacing-1); // } if (m_lineNumbersVisible) { painter.setPen(QPen(m_extraForeground,2));//pal.color(QPalette::BrightText)); //int indent = TextEditor::BaseTextDocumentLayout::foldingIndent(block); const QString &number = QString::number(blockNumber + 1); //const QString &number2 = QString::number(indent); bool selected = ( (selStart < block.position() + block.length() && selEnd > block.position()) || (selStart == selEnd && selStart == block.position()) ); if (selected) { painter.save(); QFont f = painter.font(); f.setBold(true); painter.setFont(f); //painter.setPen(QPen(Qt::black,2)); } painter.drawText(QRectF(markWidth, top, extraAreaWidth - markWidth - 4, height), Qt::AlignRight, number); if (selected) painter.restore(); painter.setPen(QPen(m_extraForeground,1));//pal.color(QPalette::BrightText)); } block = nextVisibleBlock; blockNumber = nextVisibleBlockNumber; } } void LiteEditorWidgetBase::extraAreaMouseEvent(QMouseEvent *e) { QTextCursor cursor = cursorForPosition(QPoint(0, e->pos().y())); if (e->type() == QEvent::MouseButtonPress || e->type() == QEvent::MouseButtonDblClick) { if (e->button() == Qt::LeftButton) { int boxWidth = foldBoxWidth(fontMetrics()); QTextBlock block = cursor.block(); bool canFold = TextEditor::BaseTextDocumentLayout::canFold(block); if (m_codeFoldingVisible && canFold && e->pos().x() >= extraAreaWidth() - boxWidth-4) { if (!cursor.block().next().isVisible()) { toggleBlockVisible(cursor.block()); //moveCursorVisible(false); } else { QTextBlock c = cursor.block(); toggleBlockVisible(c); moveCursorVisible(false); } } else { QTextCursor selection = cursor; selection.setVisualNavigation(true); m_extraAreaSelectionNumber = selection.blockNumber(); selection.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); selection.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor); setTextCursor(selection); } } } else if (m_extraAreaSelectionNumber >= 0) { QTextCursor selection = cursor; selection.setVisualNavigation(true); if (e->type() == QEvent::MouseMove) { QTextBlock anchorBlock = document()->findBlockByNumber(m_extraAreaSelectionNumber); selection.setPosition(anchorBlock.position()); if (cursor.blockNumber() < m_extraAreaSelectionNumber) { selection.movePosition(QTextCursor::EndOfBlock); selection.movePosition(QTextCursor::Right); } selection.setPosition(cursor.block().position(), QTextCursor::KeepAnchor); if (cursor.blockNumber() >= m_extraAreaSelectionNumber) { selection.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); selection.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor); } } else { m_extraAreaSelectionNumber = -1; return; } setTextCursor(selection); } } void LiteEditorWidgetBase::extraAreaLeaveEvent(QEvent *) { } int LiteEditorWidgetBase::navigateAreaWidth() { return 16; #ifdef Q_OS_MAC return qApp->style()->pixelMetric(QStyle::PM_ScrollBarExtent); #else return 16; #endif } void LiteEditorWidgetBase::navigateAreaPaintEvent(QPaintEvent *e) { QPalette pal = m_navigateArea->palette(); pal.setCurrentColorGroup(QPalette::Active); QPainter painter(m_navigateArea); //painter.fillRect(e->rect(), pal.color(QPalette::Base)); //painter.fillRect(e->rect().intersected(QRect(0, 0, m_navigateArea->width(), m_navigateArea->height())), // m_extraBackground); painter.fillRect(e->rect(),m_extraBackground); int width = this->navigateAreaWidth(); painter.fillRect(2,2,width-4,width-4,m_navigateManager->headMarkColor()); int count = this->blockCount(); int height = this->viewport()->rect().height()-2*m_navigateArea->width(); QMapIterator<int,NavigateMark*> i(m_navigateManager->markMap); while(i.hasNext()) { i.next(); if (!i.value()->isEmpty()) { int pos = i.key()*height*1.0/count; //QColor markColor; NavigateMark::Node *node; const LiteApi::EditorNaviagteType * pList = MARKTYPE_PRIORITYLIST; for (int j=0; j<PRIORITYLIST_LENGTH; j++) { node = i.value()->findNode(pList[j]); if (node) { painter.fillRect(2,width+pos,width-4,4,node->markColor()); break; } } } } } NavigateMark* LiteEditorWidgetBase::findNavigateMarkByPos(const QPoint &pos, int *poffset, int *pLine) { int count = this->blockCount(); int height = this->viewport()->rect().height()-2*m_navigateArea->width(); int width = m_navigateArea->width(); QMapIterator<int,NavigateMark*> i(m_navigateManager->markMap); while(i.hasNext()) { i.next(); if (!i.value()->isEmpty()) { int offset = i.key()*height*1.0/count; QRect rect(0,width+offset-1,width,4+1); if (rect.contains(pos)) { if (poffset) { *poffset = offset+width; } if (pLine) { *pLine = i.key(); } return i.value(); } } } return 0; } int LiteEditorWidgetBase::isInNavigateMark(const QPoint &pos, int *poffset) { int count = this->blockCount(); int height = this->viewport()->rect().height()-2*m_navigateArea->width(); int width = m_navigateArea->width(); QMapIterator<int,NavigateMark*> i(m_navigateManager->markMap); while(i.hasNext()) { i.next(); if (!i.value()->isEmpty()) { int offset = i.key()*height*1.0/count; QRect rect(0,width+offset-1,width,4+1); if (rect.contains(pos)) { if (poffset) { *poffset = offset+width; } return i.key(); } } } return -1; } bool LiteEditorWidgetBase::isInNavigateHead(const QPoint &pos) { int width = m_navigateArea->width(); QRect rect(0,0,width,width); if (rect.contains(pos)) { return true; } return false; } static NavigateMark::Node *findMarkPriorityNode(NavigateMark *mark) { const LiteApi::EditorNaviagteType * pList = MARKTYPE_PRIORITYLIST; for (int j=0; j<PRIORITYLIST_LENGTH; j++) { NavigateMark::Node *node = mark->findNode(pList[j]); if (node) { return node; } } return 0; } void LiteEditorWidgetBase::navigateAreaMouseEvent(QMouseEvent *e) { if (e->button() == Qt::LeftButton && (e->type() == QEvent::MouseButtonPress || e->type() == QEvent::MouseButtonDblClick)) { int line = -1; NavigateMark *mark = findNavigateMarkByPos(e->pos(),0,&line); if (mark) { NavigateMark::Node *node = findMarkPriorityNode(mark); if (node) { this->gotoLine(line,node->offset,true,node->selection); } } } else if (e->type() == QEvent::MouseMove) { bool tooltip = false; if (isInNavigateHead(e->pos())) { tooltip = true; QPoint pos(1,1); showTipText(m_navigateArea->mapToGlobal(pos),this->m_navigateManager->m_msg,this->m_navigateArea); } else { int offset = 0; NavigateMark *mark = findNavigateMarkByPos(e->pos(),&offset,0); if (mark) { NavigateMark::Node *node = findMarkPriorityNode(mark); if (node) { tooltip = true; QPoint pos(1,offset); showTipText(m_navigateArea->mapToGlobal(pos),node->msg,this->m_navigateArea); } } } if (!tooltip) { hideTipText(); } } } void LiteEditorWidgetBase::navigateAreaLeaveEvent(QEvent */*e*/) { } void LiteEditorWidgetBase::navigateAreaEnterEvent(QEvent */*e*/) { } void LiteEditorWidgetBase::resizeEvent(QResizeEvent *e) { QPlainTextEdit::resizeEvent(e); QRect cr = contentsRect(); m_extraArea->setGeometry( QStyle::visualRect(layoutDirection(), cr, QRect(cr.left(), cr.top(), extraAreaWidth(), cr.height()))); m_navigateArea->setGeometry( QStyle::visualRect(layoutDirection(), cr, QRect(cr.left()+extraAreaWidth()+viewport()->rect().width(), cr.top(), navigateAreaWidth(), cr.height()))); m_navigateArea->update(); } void LiteEditorWidgetBase::slotUpdateExtraAreaWidth() { if (isLeftToRight()) setViewportMargins(extraAreaWidth(), 0, navigateAreaWidth(), 0); else setViewportMargins(navigateAreaWidth(), 0, extraAreaWidth(), 0); } void LiteEditorWidgetBase::slotModificationChanged(bool m) { if (m) return; int oldLastSaveRevision = m_lastSaveRevision; m_lastSaveRevision = document()->revision(); if (oldLastSaveRevision != m_lastSaveRevision) { QTextBlock block = document()->begin(); while (block.isValid()) { if (block.revision() < 0 || block.revision() != oldLastSaveRevision) { block.setRevision(-m_lastSaveRevision - 1); } else { block.setRevision(m_lastSaveRevision); } block = block.next(); } } m_extraArea->update(); } void LiteEditorWidgetBase::slotUpdateRequest(const QRect &r, int dy) { if (dy) m_extraArea->scroll(0, dy); else if (r.width() > 4) { // wider than cursor width, not just cursor blinking m_extraArea->update(0, r.y(), m_extraArea->width(), r.height()); //if (!d->m_searchExpr.isEmpty()) { // const int m = d->m_searchResultOverlay->dropShadowWidth(); // viewport()->update(r.adjusted(-m, -m, m, m)); //} } if (r.contains(viewport()->rect())) slotUpdateExtraAreaWidth(); } static bool convertPosition(const QTextDocument *document, int pos, int *line, int *column) { QTextBlock block = document->findBlock(pos); if (!block.isValid()) { (*line) = -1; (*column) = -1; return false; } else { (*line) = block.blockNumber() + 1; (*column) = pos - block.position(); return true; } } QByteArray LiteEditorWidgetBase::saveState() const { QByteArray state; QDataStream stream(&state, QIODevice::WriteOnly); stream << 2; // version number stream << verticalScrollBar()->value(); stream << horizontalScrollBar()->value(); int line, column; convertPosition(document(),textCursor().position(), &line, &column); stream << line-1; stream << column; // store code folding state QList<int> foldedBlocks; QTextBlock block = document()->firstBlock(); while (block.isValid()) { if (block.userData() && static_cast<TextEditor::TextBlockUserData*>(block.userData())->folded()) { int number = block.blockNumber(); foldedBlocks += number; } block = block.next(); } stream << foldedBlocks; return state; } void LiteEditorWidgetBase::verticalScrollBarRangeChanged(int minnum, int /*maxnum*/) { if (!m_allowVscrollLastLine) { return; } QScrollBar *bar = this->verticalScrollBar(); bar->blockSignals(true); int h = this->document()->size().height(); if (h > 1) { h--; } bar->setMaximum(minnum+h); bar->blockSignals(false); } void LiteEditorWidgetBase::setAllowVscrollLastLine(bool b) { m_allowVscrollLastLine = b; } bool LiteEditorWidgetBase::restoreState(const QByteArray &state) { if (state.isEmpty()) { return false; } int version; int vval; int hval; int lval; int cval; QDataStream stream(state); stream >> version; stream >> vval; stream >> hval; stream >> lval; stream >> cval; if (version >= 1) { QList<int> collapsedBlocks; stream >> collapsedBlocks; QTextDocument *doc = document(); foreach(int blockNumber, collapsedBlocks) { QTextBlock block = doc->findBlockByNumber(qMax(0, blockNumber)); if (block.isValid()) TextEditor::BaseTextDocumentLayout::doFoldOrUnfold(block, false); } if (!collapsedBlocks.empty()) { this->update(); } } m_lastCursorChangeWasInteresting = false; // avoid adding last position to history gotoLine(lval, cval,false); verticalScrollBar()->setValue(vval); horizontalScrollBar()->setValue(hval); saveCurrentCursorPositionForNavigation(); return true; } void LiteEditorWidgetBase::saveCurrentCursorPositionForNavigation() { m_lastCursorChangeWasInteresting = true; m_tempNavigationState = saveState(); } void LiteEditorWidgetBase::slotCursorPositionChanged() { if (m_lastCursorChangeWasInteresting) { //navigate change int lastLine = this->textCursor().blockNumber(); if (lastLine != m_lastLine) { m_lastLine = lastLine; emit navigationStateChanged(m_tempNavigationState); m_lastCursorChangeWasInteresting = false; } } else { this->saveCurrentCursorPositionForNavigation(); } //emit navigationStateChanged(saveState()); /* if (!m_contentsChanged && m_lastCursorChangeWasInteresting) { //navigate change emit navigationStateChanged(m_tempNavigationState); m_lastCursorChangeWasInteresting = false; } else if (m_contentsChanged) { this->saveCurrentCursorPositionForNavigation(); } */ highlightCurrentLine(); } void LiteEditorWidgetBase::slotSelectionChanged() { QString pattern; QTextCursor cur = this->textCursor(); if (cur.hasSelection()) { m_lastCursorChangeWasInteresting = false; QString text = cur.selectedText(); cur.setPosition(cur.selectionStart()); cur.select(QTextCursor::WordUnderCursor); if (text == cur.selectedText() && isIdentifierChar(*text.begin())) { pattern = text; } } if (m_selectionExpression.pattern() != pattern) { m_selectionExpression.setPattern(pattern); updateFindOrSelectionMark(LiteApi::EditorNavigateSelection); viewport()->update(); } if (m_inBlockSelectionMode && !textCursor().hasSelection()) { m_inBlockSelectionMode = false; m_blockSelection.clear(); viewport()->update(); } //clearLink(); } void LiteEditorWidgetBase::slotUpdateBlockNotify(const QTextBlock &) { } void LiteEditorWidgetBase::maybeSelectLine() { QTextCursor cursor = textCursor(); if (!cursor.hasSelection()) { const QTextBlock &block = cursor.block(); if (block.next().isValid()) { cursor.setPosition(block.position()); cursor.setPosition(block.next().position(), QTextCursor::KeepAnchor); } else { cursor.movePosition(QTextCursor::EndOfBlock); cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor); cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor); } setTextCursor(cursor); } } void LiteEditorWidgetBase::gotoLine(int blockNumber, int column, bool center, int selection) { m_lastCursorChangeWasInteresting = false; const QTextBlock &block = document()->findBlockByNumber(blockNumber); if (block.isValid()) { QTextCursor cursor(block); int length = block.text().length(); if (column <= length) { cursor.movePosition(QTextCursor::Right,QTextCursor::MoveAnchor,column); if ( (selection > 0) && ( (column+selection) <= length) ) { cursor.movePosition(QTextCursor::Right,QTextCursor::KeepAnchor,selection); } } // if (column) { // if (column <= length) { // cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, column > length ? length : column); // if (selection && ( (column+selection) <= length ) ) { // cursor.movePosition(QTextCursor::Right,QTextCursor::KeepAnchor, selection); // } // } else { // cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, length); // } // } else { // int pos = cursor.position(); // while (document()->characterAt(pos).category() == QChar::Separator_Space) { // ++pos; // } // cursor.setPosition(pos); // } setTextCursor(cursor); if (center) { centerCursor(); } else { ensureCursorVisible(); } } } QChar LiteEditorWidgetBase::characterAt(int pos) const { return document()->characterAt(pos); } void LiteEditorWidgetBase::handleHomeKey(bool anchor) { QTextCursor cursor = textCursor(); QTextCursor::MoveMode mode = QTextCursor::MoveAnchor; if (anchor) mode = QTextCursor::KeepAnchor; const int initpos = cursor.position(); int pos = cursor.block().position(); QChar character = characterAt(pos); const QLatin1Char tab = QLatin1Char('\t'); while (character == tab || character.category() == QChar::Separator_Space) { ++pos; if (pos == initpos) break; character = characterAt(pos); } // Go to the start of the block when we're already at the start of the text if (pos == initpos) pos = cursor.block().position(); cursor.setPosition(pos, mode); setTextCursor(cursor); } void LiteEditorWidgetBase::setFindOption(LiteApi::FindOption *opt) { if (!opt) { m_findExpression.setPattern(""); } else { m_findExpression.setPattern(opt->findText); if (opt->useRegexp) { m_findExpression.setPatternSyntax(QRegExp::RegExp); } else { m_findExpression.setPatternSyntax(QRegExp::FixedString); } m_findFlags = 0; if (opt->backWard) { m_findFlags |= QTextDocument::FindBackward; } if (opt->matchCase) { m_findFlags |= QTextDocument::FindCaseSensitively; m_findExpression.setCaseSensitivity(Qt::CaseSensitive); } else { m_findExpression.setCaseSensitivity(Qt::CaseInsensitive); } if (opt->matchWord) { m_findFlags |= QTextDocument::FindWholeWords; } if (!m_findExpression.isValid()) { m_findExpression.setPattern(""); } } updateFindOrSelectionMark(LiteApi::EditorNavigateFind); if (!m_selectionExpression.isEmpty()) { updateFindOrSelectionMark(LiteApi::EditorNavigateSelection); } viewport()->update(); } void LiteEditorWidgetBase::setLineWrap(bool wrap) { setLineWrapMode(wrap ? QPlainTextEdit::WidgetWidth : QPlainTextEdit::NoWrap); } bool LiteEditorWidgetBase::isLineWrap() const { return this->lineWrapMode() != QPlainTextEdit::NoWrap; } void LiteEditorWidgetBase::gotoLineStart() { handleHomeKey(false); } void LiteEditorWidgetBase::gotoLineStartWithSelection() { handleHomeKey(true); } void LiteEditorWidgetBase::gotoLineEnd() { moveCursor(QTextCursor::EndOfLine); } void LiteEditorWidgetBase::gotoLineEndWithSelection() { moveCursor(QTextCursor::EndOfLine, QTextCursor::KeepAnchor); } void LiteEditorWidgetBase::gotoNextLine() { moveCursor(QTextCursor::Down); } void LiteEditorWidgetBase::gotoNextLineWithSelection() { moveCursor(QTextCursor::Down, QTextCursor::KeepAnchor); } void LiteEditorWidgetBase::gotoPreviousLine() { moveCursor(QTextCursor::Up); } void LiteEditorWidgetBase::gotoPreviousLineWithSelection() { moveCursor(QTextCursor::Up, QTextCursor::KeepAnchor); } void LiteEditorWidgetBase::gotoPreviousCharacter() { moveCursor(QTextCursor::PreviousCharacter); } void LiteEditorWidgetBase::gotoPreviousCharacterWithSelection() { moveCursor(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor); } void LiteEditorWidgetBase::gotoNextCharacter() { moveCursor(QTextCursor::NextCharacter); } void LiteEditorWidgetBase::gotoNextCharacterWithSelection() { moveCursor(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); } void LiteEditorWidgetBase::gotoPreviousWord() { moveCursor(QTextCursor::PreviousWord); setTextCursor(textCursor()); } void LiteEditorWidgetBase::gotoPreviousWordWithSelection() { moveCursor(QTextCursor::PreviousWord, QTextCursor::KeepAnchor); setTextCursor(textCursor()); } void LiteEditorWidgetBase::gotoNextWord() { moveCursor(QTextCursor::NextWord); setTextCursor(textCursor()); } void LiteEditorWidgetBase::gotoNextWordWithSelection() { moveCursor(QTextCursor::NextWord, QTextCursor::KeepAnchor); setTextCursor(textCursor()); } void LiteEditorWidgetBase::gotoDocStart() { moveCursor(QTextCursor::Start); } void LiteEditorWidgetBase::gotoDocEnd() { moveCursor(QTextCursor::End); } void LiteEditorWidgetBase::duplicate() { QTextCursor cursor = textCursor(); cursor.beginEditBlock(); if (cursor.hasSelection()) { QString text = cursor.selectedText(); int start = cursor.selectionStart(); int end = cursor.selectionEnd(); cursor.setPosition(end); cursor.insertText(text); cursor.setPosition(start,QTextCursor::MoveAnchor); cursor.setPosition(end,QTextCursor::KeepAnchor); } else { int pos = cursor.positionInBlock(); cursor.movePosition(QTextCursor::StartOfBlock); cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); QString text = cursor.selectedText(); cursor.movePosition(QTextCursor::EndOfBlock); cursor.insertBlock(); int start = cursor.position(); cursor.insertText(text); cursor.setPosition(start); cursor.movePosition(QTextCursor::Right,QTextCursor::MoveAnchor,pos); } cursor.endEditBlock(); setTextCursor(cursor); } // shift+del void LiteEditorWidgetBase::cutLine() { maybeSelectLine(); QPlainTextEdit::cut(); } // ctrl+ins void LiteEditorWidgetBase::copyLine() { QTextCursor prevCursor = textCursor(); maybeSelectLine(); copy(); setTextCursor(prevCursor); } void LiteEditorWidgetBase::deleteLine() { maybeSelectLine(); textCursor().removeSelectedText(); } void LiteEditorWidgetBase::deleteEndOfWord() { moveCursor(QTextCursor::EndOfWord, QTextCursor::KeepAnchor); textCursor().removeSelectedText(); setTextCursor(textCursor()); } void LiteEditorWidgetBase::moveLineUpDown(bool up) { QTextCursor cursor = textCursor(); QTextCursor move = cursor; move.setVisualNavigation(false); // this opens folded items instead of destroying them if (m_moveLineUndoHack) move.joinPreviousEditBlock(); else move.beginEditBlock(); bool hasSelection = cursor.hasSelection(); if (hasSelection) { move.setPosition(cursor.selectionStart()); move.movePosition(QTextCursor::StartOfBlock); move.setPosition(cursor.selectionEnd(), QTextCursor::KeepAnchor); move.movePosition(move.atBlockStart() ? QTextCursor::Left: QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); } else { move.movePosition(QTextCursor::StartOfBlock); move.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); } QString text = move.selectedText(); move.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor); move.removeSelectedText(); if (up) { move.movePosition(QTextCursor::PreviousBlock); move.insertBlock(); move.movePosition(QTextCursor::Left); } else { move.movePosition(QTextCursor::EndOfBlock); if (move.atBlockStart()) { // empty block move.movePosition(QTextCursor::NextBlock); move.insertBlock(); move.movePosition(QTextCursor::Left); } else { move.insertBlock(); } } int start = move.position(); move.clearSelection(); move.insertText(text); int end = move.position(); if (hasSelection) { move.setPosition(end); move.setPosition(start, QTextCursor::KeepAnchor); } else { move.setPosition(start); } move.endEditBlock(); setTextCursor(move); m_moveLineUndoHack = true; } void LiteEditorWidgetBase::copyLineUpDown(bool up) { QTextCursor cursor = textCursor(); QTextCursor move = cursor; move.beginEditBlock(); bool hasSelection = cursor.hasSelection(); if (hasSelection) { move.setPosition(cursor.selectionStart()); move.movePosition(QTextCursor::StartOfBlock); move.setPosition(cursor.selectionEnd(), QTextCursor::KeepAnchor); move.movePosition(move.atBlockStart() ? QTextCursor::Left: QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); } else { move.movePosition(QTextCursor::StartOfBlock); move.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); } QString text = move.selectedText(); if (up) { move.setPosition(cursor.selectionStart()); move.movePosition(QTextCursor::StartOfBlock); move.insertBlock(); move.movePosition(QTextCursor::Left); } else { move.movePosition(QTextCursor::EndOfBlock); if (move.atBlockStart()) { move.movePosition(QTextCursor::NextBlock); move.insertBlock(); move.movePosition(QTextCursor::Left); } else { move.insertBlock(); } } int start = move.position(); move.clearSelection(); move.insertText(text); int end = move.position(); move.setPosition(start); move.setPosition(end, QTextCursor::KeepAnchor); move.endEditBlock(); setTextCursor(move); } void LiteEditorWidgetBase::joinLines() { QTextCursor cursor = textCursor(); QTextCursor start = cursor; QTextCursor end = cursor; start.setPosition(cursor.selectionStart()); end.setPosition(cursor.selectionEnd() - 1); int lineCount = qMax(1, end.blockNumber() - start.blockNumber()); cursor.beginEditBlock(); cursor.setPosition(cursor.selectionStart()); while (lineCount--) { cursor.movePosition(QTextCursor::NextBlock); cursor.movePosition(QTextCursor::StartOfBlock); cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); QString cutLine = cursor.selectedText(); // Collapse leading whitespaces to one or insert whitespace cutLine.replace(QRegExp(QLatin1String("^\\s*")), QLatin1String(" ")); cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor); cursor.removeSelectedText(); cursor.movePosition(QTextCursor::PreviousBlock); cursor.movePosition(QTextCursor::EndOfBlock); cursor.insertText(cutLine); } cursor.endEditBlock(); setTextCursor(cursor); } void LiteEditorWidgetBase::deleteStartOfWord() { moveCursor(QTextCursor::StartOfWord, QTextCursor::KeepAnchor); textCursor().removeSelectedText(); setTextCursor(textCursor()); } void LiteEditorWidgetBase::moveLineUp() { moveLineUpDown(true); } void LiteEditorWidgetBase::moveLineDown() { moveLineUpDown(false); } void LiteEditorWidgetBase::copyLineUp() { copyLineUpDown(true); } void LiteEditorWidgetBase::copyLineDown() { copyLineUpDown(false); } void LiteEditorWidgetBase::insertLineBefore() { QTextCursor cur = this->textCursor(); cur.movePosition(QTextCursor::PreviousBlock); cur.movePosition(QTextCursor::EndOfLine); if (m_autoIndent) { indentEnter(cur); } else { cur.insertText("\n"); } this->setTextCursor(cur); } void LiteEditorWidgetBase::insertLineAfter() { QTextCursor cur = this->textCursor(); cur.movePosition(QTextCursor::EndOfLine); if (m_autoIndent) { indentEnter(cur); } else { cur.insertText("\n"); } this->setTextCursor(cur); } bool LiteEditorWidgetBase::findPrevBlock(QTextCursor &cursor, int indent, const QString &skip) const { QTextBlock block = cursor.block().previous(); while(block.isValid()) { TextEditor::TextBlockUserData *data = TextEditor::BaseTextDocumentLayout::testUserData(block); if (data && data->foldingIndent() == indent) { QString text = block.text().trimmed(); if (text.isEmpty() || text.startsWith(skip)) { block = block.previous(); continue; } cursor.setPosition(block.position()); return true; } block = block.previous(); } return false; } bool LiteEditorWidgetBase::findStartBlock(QTextCursor &cursor, int indent) const { QTextBlock block = cursor.block(); while(block.isValid()) { TextEditor::TextBlockUserData *data = TextEditor::BaseTextDocumentLayout::testUserData(block); if (data && data->foldingIndent() == indent) { cursor.setPosition(block.position()); return true; } block = block.previous(); } return false; } bool LiteEditorWidgetBase::findEndBlock(QTextCursor &cursor, int indent) const { QTextBlock block = cursor.block().next(); while(block.isValid()) { TextEditor::TextBlockUserData *data = TextEditor::BaseTextDocumentLayout::testUserData(block); if (data && data->foldingIndent() == indent) { cursor.setPosition(block.previous().position()); return true; } block = block.next(); } return false; } bool LiteEditorWidgetBase::findNextBlock(QTextCursor &cursor, int indent, const QString &skip) const { QTextBlock block = cursor.block().next(); while(block.isValid()) { TextEditor::TextBlockUserData *data = TextEditor::BaseTextDocumentLayout::testUserData(block); if (data && data->foldingIndent() == indent) { QString text = block.text().trimmed(); if (text.isEmpty() || text.startsWith(skip)) { block = block.next(); continue; } cursor.setPosition(block.position()); return true; } block = block.next(); } return false; } void LiteEditorWidgetBase::gotoPrevBlock() { QTextCursor cursor = this->textCursor(); if (!findPrevBlock(cursor,0)) { cursor.movePosition(QTextCursor::Start); } this->setTextCursor(cursor); } void LiteEditorWidgetBase::gotoNextBlock() { QTextCursor cursor = this->textCursor(); if (!findNextBlock(cursor,0)) { cursor.movePosition(QTextCursor::End); } this->setTextCursor(cursor); } void LiteEditorWidgetBase::selectBlock() { QTextCursor cursor = this->textCursor(); if (!findStartBlock(cursor,0)) { return; } QTextCursor end = this->textCursor(); if (!findEndBlock(end,0)) { return; } cursor.setPosition(end.position()+end.block().length()-1,QTextCursor::KeepAnchor); this->setTextCursor(cursor); } bool LiteEditorWidgetBase::event(QEvent *e) { m_contentsChanged = false; return QPlainTextEdit::event(e); } QString LiteEditorWidgetBase::autoCompleteSurroundText(QTextCursor &cursor, const QString &textToInsert) const { if (textToInsert == QLatin1String("(")) return cursor.selectedText() + QLatin1Char(')'); if (textToInsert == QLatin1String("{")) { //If the text span multiple lines, insert on different lines QString str = cursor.selectedText(); if (str.contains(QChar::ParagraphSeparator)) { //Also, try to simulate auto-indent str = (str.startsWith(QChar::ParagraphSeparator) ? QString() : QString(QChar::ParagraphSeparator)) + str; if (str.endsWith(QChar::ParagraphSeparator)) str += QLatin1Char('}') + QString(QChar::ParagraphSeparator); else str += QString(QChar::ParagraphSeparator) + QLatin1Char('}'); } else { str += QLatin1Char('}'); } return str; } if (textToInsert == QLatin1String("[")) return cursor.selectedText() + QLatin1Char(']'); if (textToInsert == QLatin1String("\"")) return cursor.selectedText() + QLatin1Char('"'); if (textToInsert == QLatin1String("'")) return cursor.selectedText() + QLatin1Char('\''); return ""; } static void countBracket(QChar open, QChar close, QChar c, int *errors, int *stillopen) { if (c == open) ++*stillopen; else if (c == close) --*stillopen; if (*stillopen < 0) { *errors += -1 * (*stillopen); *stillopen = 0; } } static void countBrackets(QTextCursor cursor, int from, int end, QChar open, QChar close, int *errors, int *stillopen) { cursor.setPosition(from); QTextBlock block = cursor.block(); while (block.isValid() && block.position() < end) { TextEditor::Parentheses parenList = TextEditor::BaseTextDocumentLayout::parentheses(block); if (!parenList.isEmpty() && !TextEditor::BaseTextDocumentLayout::ifdefedOut(block)) { for (int i = 0; i < parenList.count(); ++i) { TextEditor::Parenthesis paren = parenList.at(i); int position = block.position() + paren.pos; if (position < from || position >= end) continue; countBracket(open, close, paren.chr, errors, stillopen); } } block = block.next(); } } bool LiteEditorWidgetBase::checkIsMatchBraces(QTextCursor &cursor, const QString &textToInsert) const { const QChar character = textToInsert.at(0); const QString parentheses1 = QLatin1String("()"); const QString parentheses2 = QLatin1String("[]"); const QString parentheses3 = QLatin1String("{}"); if (parentheses1.contains(character) || parentheses2.contains(character) || parentheses3.contains(character) ) { QTextCursor tmp= cursor; bool foundBlockStart = TextEditor::TextBlockUserData::findPreviousBlockOpenParenthesis(&tmp); int blockStart = foundBlockStart ? tmp.position() : 0; tmp = cursor; bool foundBlockEnd = TextEditor::TextBlockUserData::findNextBlockClosingParenthesis(&tmp); int blockEnd = foundBlockEnd ? tmp.position() : (cursor.document()->characterCount() - 1); QChar openChar; QChar closeChar; if (parentheses1.contains(character)) { openChar = QLatin1Char('('); closeChar = QLatin1Char(')'); } else { if (parentheses2.contains(character)) { openChar = QLatin1Char('['); closeChar = QLatin1Char(']'); } else if (parentheses3.contains(character)) { openChar = QLatin1Char('{'); closeChar = QLatin1Char('}'); } if (cursor.document()->blockCount() < 5000) { blockStart = 0; blockEnd = cursor.document()->characterCount()-1; } else { blockStart = cursor.block().position(); blockEnd = cursor.block().position()+cursor.block().length(); } } int errors = 0; int stillopen = 0; countBrackets(cursor, blockStart, blockEnd, openChar, closeChar, &errors, &stillopen); int errorsBeforeInsertion = errors + stillopen; errors = 0; stillopen = 0; countBrackets(cursor, blockStart, cursor.position(), openChar, closeChar, &errors, &stillopen); countBracket(openChar, closeChar, character, &errors, &stillopen); countBrackets(cursor, cursor.position(), blockEnd, openChar, closeChar, &errors, &stillopen); int errorsAfterInsertion = errors + stillopen; if (errorsAfterInsertion < errorsBeforeInsertion) return false; // insertion fixes parentheses or bracket errors, do not auto complete } return true; } bool LiteEditorWidgetBase::autoBackspace(QTextCursor &cursor) { int pos = cursor.position(); if (pos == 0) return false; if (this->m_textLexer->isInComment(cursor)) { return false; } // QTextCursor c = cursor; // c.setPosition(pos - 1); QTextDocument *doc = cursor.document(); const QChar lookAhead = doc->characterAt(pos); const QChar lookBehind = doc->characterAt(pos - 1); // const QChar lookFurtherBehind = doc->characterAt(pos - 2); if ( (lookBehind == QLatin1Char('(') && lookAhead == QLatin1Char(')')) || (lookBehind == QLatin1Char('[') && lookAhead == QLatin1Char(']')) || (lookBehind == QLatin1Char('{') && lookAhead == QLatin1Char('}')) ) { if (m_textLexer->isInString(cursor)) { return false; } } else if ( (lookBehind == QLatin1Char('\"') && lookAhead == QLatin1Char('\"')) || (lookBehind == QLatin1Char('\'') && lookAhead == QLatin1Char('\'')) || (lookBehind == QLatin1Char('`') && lookAhead == QLatin1Char('`'))) { if (!this->m_bLastBraces) { int bpos = cursor.positionInBlock(); if (bpos > 1) { if (bpos >= 2) { QChar ch = doc->characterAt(pos-2); if (ch.isLetterOrNumber()) { return false; } } } } if (!this->m_textLexer->isLangSupport()) { return false; } if (!this->m_textLexer->stringQuoteList().contains(lookAhead)) { return false; } if(!m_textLexer->isInEmptyString(cursor)) { return false; } } else { return false; } const QChar character = lookBehind; if (character == QLatin1Char('(') || character == QLatin1Char('[') || character == QLatin1Char('{') ) { QTextCursor tmp = cursor; TextEditor::TextBlockUserData::findPreviousBlockOpenParenthesis(&tmp); int blockStart = tmp.isNull() ? 0 : tmp.position(); tmp = cursor; TextEditor::TextBlockUserData::findNextBlockClosingParenthesis(&tmp); int blockEnd = tmp.isNull() ? (cursor.document()->characterCount()-1) : tmp.position(); QChar openChar = character; QChar closeChar; if (openChar == QLatin1Char('(')) { closeChar = ')'; } else { if (openChar == QLatin1Char('[')) { closeChar = ']'; } else { closeChar = '}'; } if (cursor.document()->blockCount() < 5000) { blockStart = 0; blockEnd = cursor.document()->characterCount()-1; } else { blockStart = cursor.block().position(); blockEnd = cursor.block().position()+cursor.block().length(); } } int errors = 0; int stillopen = 0; countBrackets(cursor, blockStart, blockEnd, openChar, closeChar, &errors, &stillopen); int errorsBeforeDeletion = errors + stillopen; errors = 0; stillopen = 0; countBrackets(cursor, blockStart, pos - 1, openChar, closeChar, &errors, &stillopen); countBrackets(cursor, pos, blockEnd, openChar, closeChar, &errors, &stillopen); int errorsAfterDeletion = errors + stillopen; if (errorsAfterDeletion < errorsBeforeDeletion) return false; // insertion fixes parentheses or bracket errors, do not auto complete } // if ((lookBehind == QLatin1Char('(') && lookAhead == QLatin1Char(')')) // || (lookBehind == QLatin1Char('[') && lookAhead == QLatin1Char(']')) // || (lookBehind == QLatin1Char('`') && lookAhead == QLatin1Char('`')) // || (lookBehind == QLatin1Char('"') && lookAhead == QLatin1Char('"') // && lookFurtherBehind != QLatin1Char('\\')) // || (lookBehind == QLatin1Char('\'') && lookAhead == QLatin1Char('\'') // && lookFurtherBehind != QLatin1Char('\\'))) { cursor.beginEditBlock(); cursor.deleteChar(); cursor.deletePreviousChar(); cursor.endEditBlock(); return true; // } // return false; } void LiteEditorWidgetBase::handleBackspaceKey() { } void LiteEditorWidgetBase::setVisualizeWhitespace(bool b) { m_visualizeWhitespace = b; } void LiteEditorWidgetBase::autoIndent() { QTextCursor cursor = textCursor(); cursor.beginEditBlock(); ::autoIndent(this->document(),cursor,this->tabSettings()); cursor.endEditBlock(); } static QString QString_toTitle(const QString &str) { QString r = str; for (int i = 0; i < r.length(); i++) { if (i == 0) { r[i] = r[i].toTitleCase(); } else { r[i] = r[i].toLower(); } } return r; } static QString QString_toUpper(const QString &str) { return str.toUpper(); } static QString QString_toLower(const QString &str) { return str.toLower(); } static QString QString_toSwapCase(const QString &str) { QString r = str; for (int i = 0; i < r.length(); i++) { if (r[i].isUpper()) { r[i] = r[i].toLower(); } else if (r[i].isLower()) { r[i] = r[i].toUpper(); } } return r; } void LiteEditorWidgetBase::convertCaseTitle() { this->transformSelection(QString_toTitle); } void LiteEditorWidgetBase::convertCaseUpper() { this->transformSelection(QString_toUpper); } void LiteEditorWidgetBase::convertCaseLower() { this->transformSelection(QString_toLower); } void LiteEditorWidgetBase::convertCaseSwap() { this->transformSelection(QString_toSwapCase); } void LiteEditorWidgetBase::convertTabToSpaces() { switchTabToSpace(true); } void LiteEditorWidgetBase::convertSpacesToTab() { switchTabToSpace(false); } void LiteEditorWidgetBase::switchTabToSpace(bool tabtospace) { if (hasBlockSelection()) { return; } QTextCursor cursor = this->textCursor(); if (!cursor.hasSelection()) { //TODO select tab or spaces return; } int pos = cursor.selectionStart(); QString text = cursor.selectedText(); QString transformedText = text; if (tabtospace) { transformedText.replace("\t",QString(m_nTabSize,' ')); } else { transformedText.replace(QString(m_nTabSize,' '),"\t"); } if (transformedText == text) { return; } cursor.insertText(transformedText); cursor.setPosition(pos); cursor.setPosition(pos+transformedText.length(), QTextCursor::KeepAnchor); this->setTextCursor(cursor); } static int trailingWhitespaces(const QString &text) { int i = 0; while (i < text.size()) { if (!text.at(text.size()-1-i).isSpace()) return i; ++i; } return i; } void LiteEditorWidgetBase::keyPressEvent(QKeyEvent *e) { if ((e->modifiers() & Qt::ControlModifier) && e->key() == Qt::Key_S) { return; } #ifdef Q_OS_MAC if ((e->modifiers() & Qt::ControlModifier) && e->key() == ',') { return; } #endif if (e->key() == Qt::Key_Insert ) { if (e->modifiers() == Qt::NoModifier) { this->setOverwriteMode(!this->overwriteMode()); emit overwriteModeChanged(this->overwriteMode()); return; } else if (e->modifiers() == Qt::ControlModifier) { this->copyLine(); return; } QPlainTextEdit::keyPressEvent(e); return; } hideTipText(); this->m_moveLineUndoHack = false; bool ro = isReadOnly(); if (e == QKeySequence::Cut) { if (!ro) { cut(); e->accept(); return; } } else if (e == QKeySequence::Delete || e->key() == Qt::Key_Backspace) { if (!ro) { if (m_inBlockSelectionMode) { removeBlockSelection(); e->accept(); return; } } } else if (e == QKeySequence::Paste) { if (!ro) { paste(); e->accept(); return; } } else if (e == QKeySequence::SelectAll) { selectAll(); e->accept(); return; } if ( e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return ) { if (e->modifiers() == Qt::NoModifier) { if (m_autoIndent) { indentEnter(textCursor()); return; } } else if (e->modifiers() & Qt::ControlModifier) { if (e->modifiers() & Qt::ShiftModifier) { insertLineBefore(); } else { insertLineAfter(); } return; } else if (e->modifiers() & Qt::ShiftModifier) { QTextCursor cur = this->textCursor(); if (m_autoIndent) { indentEnter(cur); } else { cur.insertText("\n"); } this->setTextCursor(cur); return; } } if (e == QKeySequence::MoveToStartOfBlock || e == QKeySequence::SelectStartOfBlock){ if ((e->modifiers() & (Qt::AltModifier | Qt::ShiftModifier)) == (Qt::AltModifier | Qt::ShiftModifier)) { e->accept(); return; } handleHomeKey(e == QKeySequence::SelectStartOfBlock); e->accept(); } else if (e == QKeySequence::MoveToStartOfLine || e == QKeySequence::SelectStartOfLine){ if ((e->modifiers() & (Qt::AltModifier | Qt::ShiftModifier)) == (Qt::AltModifier | Qt::ShiftModifier)) { e->accept(); return; } QTextCursor cursor = textCursor(); if (QTextLayout *layout = cursor.block().layout()) { if (layout->lineForTextPosition(cursor.position() - cursor.block().position()).lineNumber() == 0) { handleHomeKey(e == QKeySequence::SelectStartOfLine); e->accept(); return; } } } else if (!ro && e == QKeySequence::DeleteStartOfWord && !textCursor().hasSelection()) { e->accept(); QTextCursor c = textCursor(); c.movePosition(QTextCursor::PreviousWord, QTextCursor::KeepAnchor); QString text = c.selectedText(); int trail = trailingWhitespaces(text); if ( trail >= 1 ) { c = textCursor(); c.movePosition(QTextCursor::PreviousCharacter,QTextCursor::KeepAnchor,trail); } c.removeSelectedText(); return; } else if (!ro && e == QKeySequence::DeleteEndOfWord && !textCursor().hasSelection()) { e->accept(); QTextCursor c = textCursor(); c.movePosition(QTextCursor::NextWord, QTextCursor::KeepAnchor); c.removeSelectedText(); return; } else { switch (e->key()) { case Qt::Key_Tab: case Qt::Key_Backtab: { if (ro) break; QTextCursor cursor = textCursor(); indentText(cursor, e->key() == Qt::Key_Tab); e->accept(); return; } case Qt::Key_Backspace: { QTextCursor cursor = this->textCursor(); if ((e->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier | Qt::AltModifier | Qt::MetaModifier)) == Qt::NoModifier && !cursor.hasSelection()) { int pos = cursor.position(); if (pos >= 1) { QTextDocument *doc = cursor.document(); const QChar lookAhead = doc->characterAt(pos-1); if (lookAhead == ' ') { this->indentText(cursor,false); e->accept(); return; } } if (this->autoBackspace(cursor)) { this->setTextCursor(cursor); e->accept(); return; } } break; } case Qt::Key_Up: case Qt::Key_Down: if ((e->modifiers() & Qt::ControlModifier) && (e->modifiers()&Qt::ShiftModifier)) { this->moveLineUpDown(e->key() == Qt::Key_Up); return; } if (e->modifiers() & Qt::ControlModifier) { verticalScrollBar()->triggerAction( e->key() == Qt::Key_Up ? QAbstractSlider::SliderSingleStepSub : QAbstractSlider::SliderSingleStepAdd); e->accept(); return; } case Qt::Key_Right: case Qt::Key_Left: #ifdef Q_OS_MAC break; #endif if ((e->modifiers() & (Qt::AltModifier | Qt::ShiftModifier)) == (Qt::AltModifier | Qt::ShiftModifier)) { int diff_row = 0; int diff_col = 0; if (e->key() == Qt::Key_Up) diff_row = -1; else if (e->key() == Qt::Key_Down) diff_row = 1; else if (e->key() == Qt::Key_Left) diff_col = -1; else if (e->key() == Qt::Key_Right) diff_col = 1; handleBlockSelection(diff_row, diff_col); e->accept(); return; } else { // leave block selection mode if (m_inBlockSelectionMode) { m_inBlockSelectionMode = false; m_blockSelection.clear(); viewport()->update(); } } break; case Qt::Key_PageUp: case Qt::Key_PageDown: if (e->modifiers() == Qt::ControlModifier) { verticalScrollBar()->triggerAction( e->key() == Qt::Key_PageUp ? QAbstractSlider::SliderPageStepSub : QAbstractSlider::SliderPageStepAdd); e->accept(); return; } break; default: break; } } if (!ro && m_inBlockSelectionMode) { QString text = e->text(); if (!text.isEmpty() && (text.at(0).isPrint() || text.at(0) == QLatin1Char('\t'))) { removeBlockSelection(); } } if (((e->modifiers() & (Qt::ControlModifier|Qt::AltModifier)) != Qt::ControlModifier) && m_textLexer->isLangSupport() && m_textLexer->isEndOfString(this->textCursor())) { QString keyText = e->text(); // keyText == "\"" || keyText == "\'" || keyText == "`") if (m_textLexer->stringQuoteList().contains(keyText)) { QTextCursor cursor = textCursor(); if (m_textLexer->hasStringBackslash()) { int pos = cursor.position(); if (pos > 0) { QChar ch = document()->characterAt(pos-1); if (ch == '\\') { QPlainTextEdit::keyPressEvent(e); return; } } } if (!cursor.atBlockEnd()) { QString text = cursor.block().text(); if (text.mid(cursor.positionInBlock(),1) == keyText) { if (this->checkIsMatchBraces(cursor,keyText)) { cursor.movePosition(QTextCursor::Right); setTextCursor(cursor); return; } } } } } if (((e->modifiers() & (Qt::ControlModifier|Qt::AltModifier)) != Qt::ControlModifier) && (m_bLastBraces ||m_textLexer->isCanAutoCompleter(this->textCursor())) ) { if (m_bLastBraces) { if (e->text() == m_lastBraceText) { QTextCursor cursor = textCursor(); cursor.movePosition(QTextCursor::Right,QTextCursor::MoveAnchor); setTextCursor(cursor); m_bLastBraces = false; return; } } if (textCursor().hasSelection()) { QPlainTextEdit::keyPressEvent(e); return; } m_bLastBraces = false; QString keyText = e->text(); QString mr; if (m_autoBraces0 && keyText == "{") { mr = "}"; } else if (m_autoBraces1 && keyText == "(") { mr = ")"; } else if (m_autoBraces2 && keyText == "[") { mr = "]"; } else if (m_autoBraces3 && keyText == "\'") { mr = "\'"; } else if (m_autoBraces4 && keyText == "\"") { mr = "\""; } else if (m_autoBraces5 && keyText == "`") { if (m_mimeType == "text/x-gosrc") { mr = "`"; } } if (m_textLexer->isInStringOrComment(this->textCursor())) { QPlainTextEdit::keyPressEvent(e); return; } if (m_textLexer->stringQuoteList().contains(mr) && m_textLexer->hasStringBackslash()) { QTextCursor cursor = textCursor(); int pos = cursor.position(); if (pos > 0) { QChar ch = document()->characterAt(pos-1); if (ch == '\\') { QPlainTextEdit::keyPressEvent(e); return; } } } if (keyText == ")" || keyText == "]" || keyText == "}") { QTextCursor cursor = textCursor(); if (!cursor.atBlockEnd()) { QString text = cursor.block().text(); if (text.mid(cursor.positionInBlock(),1) == keyText) { if (this->checkIsMatchBraces(cursor,keyText)) { cursor.movePosition(QTextCursor::Right); setTextCursor(cursor); return; } } } } else if (keyText == "(" || keyText == "[" || keyText == "{") { QTextCursor cursor = textCursor(); if (!cursor.atBlockEnd()) { QString text = cursor.block().text(); if (text.mid(cursor.positionInBlock(),1) == keyText) { if (this->checkIsMatchBraces(cursor,keyText)) { cursor.movePosition(QTextCursor::Right); setTextCursor(cursor); return; } } else if (text.at(cursor.positionInBlock()).isLetterOrNumber()) { QPlainTextEdit::keyPressEvent(e); return; } } } else if (keyText == "\"" || keyText == "\'" || keyText == "`") { QTextCursor cursor = textCursor(); if (!cursor.atBlockEnd()) { QString text = cursor.block().text(); if (text.mid(cursor.positionInBlock(),1) == keyText) { if (this->checkIsMatchBraces(cursor,keyText)) { cursor.movePosition(QTextCursor::Right); setTextCursor(cursor); return; } } else { int pos = cursor.positionInBlock(); if (text.at(pos).isLetterOrNumber()) { QPlainTextEdit::keyPressEvent(e); return; } if (pos > 0) { if (text.at(pos-1).isLetterOrNumber()) { QPlainTextEdit::keyPressEvent(e); return; } } } } } if (!mr.isNull()) { QTextCursor cursor = textCursor(); if (this->checkIsMatchBraces(cursor,keyText)) { cursor.beginEditBlock(); int pos = cursor.position(); if (cursor.hasSelection()) { pos = cursor.selectionStart(); } cursor.insertText(keyText+mr); cursor.setPosition(pos+1); cursor.endEditBlock(); setTextCursor(cursor); m_bLastBraces = true; m_lastBraceText = mr; return; } } } QPlainTextEdit::keyPressEvent(e); } void LiteEditorWidgetBase::keyReleaseEvent(QKeyEvent *e) { if (e->key() == Qt::Key_Control) { clearLink(); } QPlainTextEdit::keyReleaseEvent(e); } void LiteEditorWidgetBase::leaveEvent(QEvent *e) { clearLink(); QPlainTextEdit::leaveEvent(e); } void LiteEditorWidgetBase::indentBlock(QTextBlock block, bool bIndent) { QTextCursor cursor(block); cursor.beginEditBlock(); cursor.movePosition(QTextCursor::StartOfBlock); cursor.removeSelectedText(); if (bIndent) { cursor.insertText(this->tabText()); } else { QString text = block.text(); if (!text.isEmpty()) { if (text.at(0) == '\t') { cursor.deleteChar(); } else if (m_bTabUseSpace && text.startsWith(QString(m_nTabSize,' '))) { int count = m_nTabSize; while (count--) { cursor.deleteChar(); } } else if (text.at(0) == ' ') { cursor.deleteChar(); } } } cursor.endEditBlock(); } void LiteEditorWidgetBase::indentCursor(QTextCursor cur, bool bIndent) { cur.beginEditBlock(); if (bIndent) { cur.insertText(this->tabText()); } else { QString text = cur.block().text(); int pos = cur.positionInBlock()-1; if (pos >= 0) { if (text.at(pos) == '\t') { cur.deletePreviousChar(); } else if (m_bTabUseSpace && (pos-m_nTabSize+1 >= 0) && (text.mid(pos-m_nTabSize+1,m_nTabSize) == QString(m_nTabSize,' '))) { int count = m_nTabSize; while (count--) { cur.deletePreviousChar(); } } else if (text.at(pos) == ' ') { cur.deletePreviousChar(); } } } cur.endEditBlock(); } void LiteEditorWidgetBase::indentText(QTextCursor cur,bool bIndent) { QTextDocument *doc = document(); cur.beginEditBlock(); if (!cur.hasSelection()) { indentCursor(cur,bIndent); } else { QTextBlock block = doc->findBlock(cur.selectionStart()); QTextBlock end = doc->findBlock(cur.selectionEnd()); if (end.position() == cur.selectionEnd()) { end = end.previous(); } if (block == end && cur.selectionStart() != block.position() ) { cur.removeSelectedText(); //indentCursor(cur,bIndent); if (bIndent) { cur.insertText(this->tabText()); } goto end; } bool bResetPos = bIndent && cur.selectionStart() == block.position(); bool bStart = cur.position() == cur.selectionStart(); int startPos = cur.selectionStart(); do { indentBlock(block,bIndent); block = block.next(); } while (block.isValid() && block.position() <= end.position()); int endPos = cur.selectionEnd(); if (bResetPos) { if (bStart) { cur.setPosition(endPos); cur.movePosition(QTextCursor::Left,QTextCursor::KeepAnchor,endPos-startPos); } else { cur.setPosition(startPos); cur.movePosition(QTextCursor::Right,QTextCursor::KeepAnchor,endPos-startPos); } } } end: cur.endEditBlock(); setTextCursor(cur); } QString LiteEditorWidgetBase::tabText(int n) const { if (m_bTabUseSpace) { return QString(m_nTabSize*n,' '); } return QString(n,'\t'); } void LiteEditorWidgetBase::indentEnter(QTextCursor cur) { QTextBlock block = cur.block(); if (block.isValid() && block.next().isValid() && !block.next().isVisible()) { unfold(); } 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 < pos) { if (!text.at(i).isSpace()) break; if (text.at(i) == ' ') { space++; } else if (text.at(i) == '\t') { tab++; } i++; } if (tab == 0) { tab += space/m_nTabSize; inText += QString(m_nTabSize*tab,' '); } else { tab += space/m_nTabSize; inText += this->tabText(tab); } if (!text.isEmpty()) { if (pos >= text.size()) { const QChar ch = text.at(text.size()-1); if (ch == '{' || ch == '(') { inText += this->tabText(); } } else if (pos >= 1 && pos < text.size()) { const QChar l = text.at(pos-1); const QChar r = text.at(pos); if ( (l == '{' && r == '}') || (l == '(' && r== ')') ) { cur.beginEditBlock(); cur.insertText(inText); int pos = cur.position(); cur.insertText(inText); cur.setPosition(pos); this->setTextCursor(cur); cur.insertText(this->tabText()); cur.endEditBlock(); return; } } } cur.beginEditBlock(); cur.insertText(inText); cur.endEditBlock(); ensureCursorVisible(); } static QString simpleInfo(const QString &info, int maxLine) { QStringList lines = info.split("\n"); if (lines.size() <= maxLine) { return info; } QStringList out; for (int i = 0; i < maxLine; i++) { out += lines[i]; } return out.join("\n")+"\n..."; } void LiteEditorWidgetBase::showToolTipInfo(const QPoint &pos, const QString &text) { showTipText(pos,simpleInfo(text,m_maxTipInfoLines),this); } void LiteEditorWidgetBase::showTipText(const QPoint &pos, const QString &text, QWidget *widget) { static QString last; static QPoint lastPos; if (last == text && lastPos == pos) { return; } last = text; lastPos = pos; QToolTip::showText(pos,text,widget); } void LiteEditorWidgetBase::hideTipText() { QToolTip::hideText(); } void LiteEditorWidgetBase::cleanWhitespace(bool wholeDocument) { QTextCursor cursor = this->textCursor(); bool hasSelection = cursor.hasSelection(); QTextCursor copyCursor = cursor; copyCursor.setVisualNavigation(false); if (wholeDocument) { copyCursor.select(QTextCursor::Document); } copyCursor.beginEditBlock(); cleanWhitespace(copyCursor, true); if (!hasSelection) ensureFinalNewLine(copyCursor); copyCursor.endEditBlock(); } void LiteEditorWidgetBase::cleanWhitespace(QTextCursor &cursor, bool inEntireDocument) { QTextDocument *document = this->document(); TextEditor::BaseTextDocumentLayout *documentLayout = qobject_cast<TextEditor::BaseTextDocumentLayout*>(document->documentLayout()); Q_ASSERT(cursor.visualNavigation() == false); QTextBlock block = document->findBlock(cursor.selectionStart()); QTextBlock end; if (cursor.hasSelection()) end = document->findBlock(cursor.selectionEnd()-1).next(); while (block.isValid() && block != end) { if (inEntireDocument || block.revision() != documentLayout->lastSaveRevision) { QString blockText = block.text(); if (int trailing = trailingWhitespaces(blockText)) { cursor.setPosition(block.position() + block.length() - 1); cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor, trailing); cursor.removeSelectedText(); } } block = block.next(); } } void LiteEditorWidgetBase::ensureFinalNewLine(QTextCursor &cursor) { cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor); bool emptyFile = !cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor); if (!emptyFile && cursor.selectedText().at(0) != QChar::ParagraphSeparator) { cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor); cursor.insertText(QLatin1String("\n")); } } void LiteEditorWidgetBase::setNavigateHead(LiteApi::EditorNaviagteType type, const QString &msg) { m_navigateManager->setType(type,msg); m_navigateArea->update(); } void LiteEditorWidgetBase::insertNavigateMark(int blockNumber, LiteApi::EditorNaviagteType type, const QString &msg, const QString &tag, int offset, int selection) { m_navigateManager->insertMark(blockNumber,msg,type,tag,offset,selection); m_navigateArea->update(); } void LiteEditorWidgetBase::clearAllNavigateMark(LiteApi::EditorNaviagteType types, const QString &tag) { m_navigateManager->clearAllNavigateMark(types, tag); m_navigateArea->update(); } void LiteEditorWidgetBase::clearAllNavigateMarks() { m_navigateManager->clearAll(); m_navigateArea->update(); } void LiteEditorWidgetBase::moveCursorVisible(bool ensureVisible) { QTextCursor cursor = this->textCursor(); if (!cursor.block().isVisible()) { cursor.setVisualNavigation(true); cursor.movePosition(QTextCursor::Up); this->setTextCursor(cursor); } if (ensureVisible) this->ensureCursorVisible(); } void LiteEditorWidgetBase::toggleBlockVisible(const QTextBlock &block) { TextEditor::BaseTextDocumentLayout *documentLayout = qobject_cast<TextEditor::BaseTextDocumentLayout*>(document()->documentLayout()); bool visible = block.next().isVisible(); TextEditor::BaseTextDocumentLayout::doFoldOrUnfold(block, !visible); documentLayout->requestUpdate(); documentLayout->emitDocumentSizeChanged(); } void LiteEditorWidgetBase::foldIndentChanged(QTextBlock block) { if (!block.isVisible()) { QTextDocument *doc = document(); TextEditor::BaseTextDocumentLayout *documentLayout = qobject_cast<TextEditor::BaseTextDocumentLayout*>(doc->documentLayout()); block.setVisible(true); documentLayout->requestUpdate(); } } void LiteEditorWidgetBase::updateBlock(const QTextBlock &/*block*/) { } void LiteEditorWidgetBase::documentSizeChanged(QSizeF) { } void LiteEditorWidgetBase::fold() { QTextDocument *doc = document(); TextEditor::BaseTextDocumentLayout *documentLayout = qobject_cast<TextEditor::BaseTextDocumentLayout*>(doc->documentLayout()); QTextBlock block = textCursor().block(); if (!(TextEditor::BaseTextDocumentLayout::canFold(block) && block.next().isVisible())) { // find the closest previous block which can fold int indent = TextEditor::BaseTextDocumentLayout::foldingIndent(block); while (block.isValid() && (TextEditor::BaseTextDocumentLayout::foldingIndent(block) >= indent || !block.isVisible())) block = block.previous(); } if (block.isValid()) { TextEditor::BaseTextDocumentLayout::doFoldOrUnfold(block, false); this->moveCursorVisible(true); documentLayout->requestUpdate(); documentLayout->emitDocumentSizeChanged(); } } void LiteEditorWidgetBase::unfold() { QTextDocument *doc = document(); TextEditor::BaseTextDocumentLayout *documentLayout = qobject_cast<TextEditor::BaseTextDocumentLayout*>(doc->documentLayout()); QTextBlock block = textCursor().block(); while (block.isValid() && !block.isVisible()) block = block.previous(); TextEditor::BaseTextDocumentLayout::doFoldOrUnfold(block, true); this->moveCursorVisible(true); documentLayout->requestUpdate(); documentLayout->emitDocumentSizeChanged(); } void LiteEditorWidgetBase::foldAll() { QTextDocument *doc = document(); TextEditor::BaseTextDocumentLayout *documentLayout = qobject_cast<TextEditor::BaseTextDocumentLayout*>(doc->documentLayout()); QTextBlock block = doc->firstBlock(); while (block.isValid()) { if (TextEditor::BaseTextDocumentLayout::canFold(block)) TextEditor::BaseTextDocumentLayout::doFoldOrUnfold(block, false); block = block.next(); } moveCursorVisible(true); documentLayout->requestUpdate(); documentLayout->emitDocumentSizeChanged(); centerCursor(); } void LiteEditorWidgetBase::unfoldAll() { QTextDocument *doc = document(); TextEditor::BaseTextDocumentLayout *documentLayout = qobject_cast<TextEditor::BaseTextDocumentLayout*>(doc->documentLayout()); QTextBlock block = doc->firstBlock(); while (block.isValid()) { if (TextEditor::BaseTextDocumentLayout::canFold(block)) TextEditor::BaseTextDocumentLayout::doFoldOrUnfold(block, true); block = block.next(); } moveCursorVisible(true); documentLayout->requestUpdate(); documentLayout->emitDocumentSizeChanged(); centerCursor(); } QTextBlock LiteEditorWidgetBase::foldedBlockAt(const QPoint &pos, QRect *box) const { QPointF offset(contentOffset()); QTextBlock block = firstVisibleBlock(); qreal top = blockBoundingGeometry(block).translated(offset).top(); qreal bottom = top + blockBoundingRect(block).height(); int viewportHeight = viewport()->height(); while (block.isValid() && top <= viewportHeight) { QTextBlock nextBlock = block.next(); if (block.isVisible() && bottom >= 0) { if (nextBlock.isValid() && !nextBlock.isVisible()) { QTextLayout *layout = block.layout(); QTextLine line = layout->lineAt(layout->lineCount()-1); QRectF lineRect = line.naturalTextRect().translated(offset.x(), top); lineRect.adjust(0, 0, -1, -1); QRectF collapseRect(lineRect.right() + 12, lineRect.top(), fontMetrics().width(QLatin1String(" {...}; ")), lineRect.height()); if (collapseRect.contains(pos)) { QTextBlock result = block; if (box) *box = collapseRect.toAlignedRect(); return result; } else { block = nextBlock; while (nextBlock.isValid() && !nextBlock.isVisible()) { block = nextBlock; nextBlock = block.next(); } } } } block = nextBlock; top = bottom; bottom = top + blockBoundingRect(block).height(); } return QTextBlock(); } void LiteEditorWidgetBase::uplinkDeployTimeout() { m_lastUpToolTipPos = m_upToolTipPos; m_upToolTipTimer->start(m_upToolTipTime+100); } void LiteEditorWidgetBase::uplinkInfoTimeout() { if (m_lastUpToolTipPos != m_upToolTipPos) { hideTipText(); return; } QTextCursor cursor = cursorForPosition(m_upToolTipPos); bool findLink = false; if (!cursor.isNull()) { int pos = cursor.position(); QRect rc = this->cursorRect(cursor); LiteApi::selectWordUnderCursor(cursor); if (cursor.hasSelection()) { rc.setLeft(rc.left()-(pos-cursor.selectionStart())*m_averageCharWidth); rc.setRight(rc.right()+(cursor.selectionEnd()-pos)*m_averageCharWidth); if (rc.contains(m_upToolTipPos)) { findLink = true; m_showLinkInfomation = true; hideTipText(); emit updateLink(cursor,m_upToolTipPos,false); } } } if (!findLink) { hideTipText(); } } void LiteEditorWidgetBase::stopUplinkTimer() { m_showLinkInfomation = false; hideTipText(); m_upToolTipTimer->stop(); m_upToolTipDeployTimer->stop(); } bool LiteEditorWidgetBase::isSpellCheckingAt(QTextCursor cur) const { QTextBlock block = cur.block(); if (!block.userData()) { return false; } TextEditor::TextBlockUserData *data = static_cast<TextEditor::TextBlockUserData*>(block.userData()); return data->shouldSpellCheck(cur.positionInBlock()); } void LiteEditorWidgetBase::showLink(const LiteApi::Link &link) { if (link.showNav && !link.sourceInfo.isEmpty()) { QPoint pt = this->mapToGlobal(link.cursorPos); this->showToolTipInfo(pt,link.sourceInfo); } else if (link.showTip && !link.targetInfo.isEmpty()) { QPoint pt = this->mapToGlobal(link.cursorPos); this->showToolTipInfo(pt,link.targetInfo); } if (!link.showNav) { return; } if (!m_showLinkNavigation) { return; } if (m_currentLink == link) { return; } if (link.targetFileName.isEmpty()) { clearLink(); return; } QTextEdit::ExtraSelection sel; sel.cursor = textCursor(); sel.cursor.setPosition(link.linkTextStart); sel.cursor.setPosition(link.linkTextEnd, QTextCursor::KeepAnchor); sel.format.setForeground(Qt::blue); sel.format.setFontUnderline(true); setExtraSelections(LiteApi::LinkSelection,QList<QTextEdit::ExtraSelection>() << sel); viewport()->setCursor(Qt::PointingHandCursor); m_currentLink = link; m_linkPressed = false; } void LiteEditorWidgetBase::clearLink() { m_showLinkNavigation = false; m_linkPressed = false; if (!m_currentLink.hasValidLinkText()) return; setExtraSelections(LiteApi::LinkSelection, QList<QTextEdit::ExtraSelection>()); viewport()->setCursor(Qt::IBeamCursor); m_currentLink = LiteApi::Link(); hideTipText(); } bool LiteEditorWidgetBase::openLink(const LiteApi::Link &link) { if (!link.hasValidTarget()) { return false; } if (!link.targetOpenDir.isEmpty()) { LiteApi::IQuickOpenManager *mgr = LiteApi::getQuickOpenManager(m_liteApp); if (mgr) { LiteApi::IQuickOpenFileSystem *fileSystem = LiteApi::getQuickOpenFileSystem(mgr); if (fileSystem) { fileSystem->setRootPath(link.targetOpenDir); fileSystem->setPlaceholderText(link.targetOpenDirInfo); mgr->setCurrentFilter(fileSystem); QPoint pt = this->mapToGlobal(link.cursorPos); mgr->showPopup(&pt); return true; } } } LiteApi::gotoLine(m_liteApp,link.targetFileName,link.targetLine,link.targetColumn,true,true); return true; } void LiteEditorWidgetBase::setExtraSelections(LiteApi::ExtraSelectionKind kind, const QList<QTextEdit::ExtraSelection> &selections) { m_extralSelectionMap[kind] = selections; QList<QTextEdit::ExtraSelection> all; QMapIterator<LiteApi::ExtraSelectionKind,QList<QTextEdit::ExtraSelection> > i(m_extralSelectionMap); while(i.hasNext()) { i.next(); all += i.value(); } QPlainTextEdit::setExtraSelections(all); } QRectF LiteEditorWidgetBase::selectionRect(const QTextCursor &cursor) { QRectF r; if (!cursor.hasSelection()) { r = this->cursorRect(cursor); } else { QTextDocument *doc = this->document(); const int position = cursor.selectionStart(); const int anchor = cursor.selectionEnd(); const QTextBlock posBlock = doc->findBlock(position); const QTextBlock anchorBlock = doc->findBlock(anchor); if (posBlock == anchorBlock && posBlock.isValid() && posBlock.layout()->lineCount()) { const QTextLine posLine = posBlock.layout()->lineForTextPosition(position - posBlock.position()); const QTextLine anchorLine = anchorBlock.layout()->lineForTextPosition(anchor - anchorBlock.position()); const int firstLine = qMin(posLine.lineNumber(), anchorLine.lineNumber()); const int lastLine = qMax(posLine.lineNumber(), anchorLine.lineNumber()); const QTextLayout *layout = posBlock.layout(); r = QRectF(); for (int i = firstLine; i <= lastLine; ++i) { r |= layout->lineAt(i).rect(); r |= layout->lineAt(i).naturalTextRect(); // might be bigger in the case of wrap not enabled } r.translate(blockBoundingRect(posBlock).topLeft()); } else { qDebug() << "error"; // QRectF anchorRect = rectForPosition(cursor.selectionEnd()); // r |= anchorRect; // r |= boundingRectOfFloatsInSelection(cursor); // QRectF frameRect(doc->documentLayout()->frameBoundingRect(cursor.currentFrame())); // r.setLeft(frameRect.left()); // r.setRight(frameRect.right()); } if (r.isValid()) r.adjust(-1, -1, 1, 1); } return r; } void LiteEditorWidgetBase::testUpdateLink(QMouseEvent *e) { if (!m_mouseNavigation) { return; } bool findLink = false; if (e->modifiers() & Qt::ControlModifier) { // Link emulation behaviour for 'go to definition' QTextCursor cursor = cursorForPosition(e->pos()); if (!cursor.isNull()) { int pos = cursor.position(); QRect rc = this->cursorRect(cursor); LiteApi::selectWordUnderCursor(cursor); if (cursor.hasSelection()) { rc.setLeft(rc.left()-(pos-cursor.selectionStart())*m_averageCharWidth); rc.setRight(rc.right()+(cursor.selectionEnd()-pos)*m_averageCharWidth); if (rc.contains(e->pos())) { findLink = true; m_showLinkNavigation = true; emit updateLink(cursor,e->pos(),true); } } } } if (!findLink) { clearLink(); } } void LiteEditorWidgetBase::mousePressEvent(QMouseEvent *e) { if (e->button() == Qt::LeftButton) { this->clearBlockSelection(); QTextBlock foldedBlock = foldedBlockAt(e->pos()); if (foldedBlock.isValid()) { toggleBlockVisible(foldedBlock); viewport()->setCursor(Qt::IBeamCursor); } if (m_mouseNavigation) { if (this->m_currentLink.hasValidTarget()) { this->m_linkPressed = true; } m_uplinkSkip = true; this->stopUplinkTimer(); } } else if (e->button() == Qt::RightButton) { int eventCursorPosition = cursorForPosition(e->pos()).position(); if (eventCursorPosition < textCursor().selectionStart() || eventCursorPosition > textCursor().selectionEnd()) { setTextCursor(cursorForPosition(e->pos())); } } QPlainTextEdit::mousePressEvent(e); } void LiteEditorWidgetBase::mouseReleaseEvent(QMouseEvent *e) { if (m_mouseNavigation && m_linkPressed && (e->modifiers() & Qt::ControlModifier) && !(e->modifiers() & Qt::ShiftModifier) && e->button() == Qt::LeftButton) { if (openLink(m_currentLink)) { clearLink(); return; } } QPlainTextEdit::mouseReleaseEvent(e); } const TextEditor::TabSettings &LiteEditorWidgetBase::tabSettings() const { TextEditor::BaseTextDocumentLayout *layout = (TextEditor::BaseTextDocumentLayout*)this->document()->documentLayout(); return layout->m_tabSettings; } void LiteEditorWidgetBase::clearBlockSelection() { if (m_inBlockSelectionMode) { m_inBlockSelectionMode = false; m_blockSelection.clear(); QTextCursor cursor = this->textCursor(); cursor.clearSelection(); setTextCursor(cursor); } } QString LiteEditorWidgetBase::copyBlockSelection() const { QString selection; QTextCursor cursor = this->textCursor(); if (!m_inBlockSelectionMode) return selection; const TextEditor::TabSettings &ts = this->tabSettings(); QTextBlock block = m_blockSelection.firstBlock.block(); QTextBlock lastBlock = m_blockSelection.lastBlock.block(); bool textInserted = false; for (;;) { if (this->selectionVisible(block.blockNumber())) { if (textInserted) selection += QLatin1Char('\n'); textInserted = true; QString text = block.text(); int startOffset = 0; int startPos = ts.positionAtColumn(text, m_blockSelection.firstVisualColumn, &startOffset); int endOffset = 0; int endPos = ts.positionAtColumn(text, m_blockSelection.lastVisualColumn, &endOffset); if (startPos == endPos) { selection += QString(endOffset - startOffset, QLatin1Char(' ')); } else { if (startOffset < 0) selection += QString(-startOffset, QLatin1Char(' ')); if (endOffset < 0) --endPos; selection += text.mid(startPos, endPos - startPos); if (endOffset < 0) selection += QString(ts.m_tabSize + endOffset, QLatin1Char(' ')); else if (endOffset > 0) selection += QString(endOffset, QLatin1Char(' ')); } } if (block == lastBlock) break; block = block.next(); } return selection; } void LiteEditorWidgetBase::removeBlockSelection(const QString &text) { QTextCursor cursor = this->textCursor(); if (!cursor.hasSelection() || !m_inBlockSelectionMode) return; int cursorPosition = cursor.selectionStart(); cursor.clearSelection(); cursor.beginEditBlock(); const TextEditor::TabSettings &ts = this->tabSettings(); QTextBlock block = m_blockSelection.firstBlock.block(); QTextBlock lastBlock = m_blockSelection.lastBlock.block(); for (;;) { QString text = block.text(); int startOffset = 0; int startPos = ts.positionAtColumn(text, m_blockSelection.firstVisualColumn, &startOffset); int endOffset = 0; int endPos = ts.positionAtColumn(text, m_blockSelection.lastVisualColumn, &endOffset); cursor.setPosition(block.position() + startPos); cursor.setPosition(block.position() + endPos, QTextCursor::KeepAnchor); cursor.removeSelectedText(); if (startOffset < 0) cursor.insertText(QString(ts.m_tabSize + startOffset, QLatin1Char(' '))); if (endOffset < 0) cursor.insertText(QString(-endOffset, QLatin1Char(' '))); if (block == lastBlock) break; block = block.next(); } cursor.setPosition(cursorPosition); if (!text.isEmpty()) cursor.insertText(text); cursor.endEditBlock(); this->setTextCursor(cursor); } bool LiteEditorWidgetBase::selectionVisible(int blockNumber) const { Q_UNUSED(blockNumber); return true; } void LiteEditorWidgetBase::handleBlockSelection(int diff_row, int diff_col) { if (!m_inBlockSelectionMode) { m_blockSelection.fromSelection(this->tabSettings(), textCursor()); m_inBlockSelectionMode = true; } m_blockSelection.moveAnchor(m_blockSelection.anchorBlockNumber() + diff_row, m_blockSelection.anchorColumnNumber() + diff_col); setTextCursor(m_blockSelection.selection(this->tabSettings())); viewport()->update(); } void LiteEditorWidgetBase::copy() { if (!textCursor().hasSelection()) return; QPlainTextEdit::copy(); } void LiteEditorWidgetBase::paste() { if (m_inBlockSelectionMode) removeBlockSelection(); QPlainTextEdit::paste(); } void LiteEditorWidgetBase::cut() { if (m_inBlockSelectionMode) { copy(); removeBlockSelection(); return; } QTextCursor cur = this->textCursor(); if (!cur.hasSelection()) { maybeSelectLine(); } QPlainTextEdit::cut(); } void LiteEditorWidgetBase::selectAll() { this->clearBlockSelection(); QPlainTextEdit::selectAll(); } void LiteEditorWidgetBase::mouseMoveEvent(QMouseEvent *e) { testUpdateLink(e); if (e->buttons() == Qt::NoButton) { const QTextBlock collapsedBlock = foldedBlockAt(e->pos()); if (collapsedBlock.isValid() && !m_mouseOnFoldedMarker) { m_mouseOnFoldedMarker = true; viewport()->setCursor(Qt::PointingHandCursor); } else if (!collapsedBlock.isValid() && m_mouseOnFoldedMarker) { m_mouseOnFoldedMarker = false; viewport()->setCursor(Qt::IBeamCursor); } } else { QPlainTextEdit::mouseMoveEvent(e); if (e->modifiers() & Qt::AltModifier) { if (!m_inBlockSelectionMode) { m_blockSelection.fromSelection(this->tabSettings(), textCursor()); m_inBlockSelectionMode = true; } else { QTextCursor cursor = textCursor(); // get visual column int column = this->tabSettings().columnAt( cursor.block().text(), cursor.positionInBlock()); if (cursor.positionInBlock() == cursor.block().length()-1) column += (e->pos().x() - cursorRect().center().x())/QFontMetricsF(font()).width(QLatin1Char(' ')); m_blockSelection.moveAnchor(cursor.blockNumber(), column); setTextCursor(m_blockSelection.selection(this->tabSettings())); viewport()->update(); } } } if (viewport()->cursor().shape() == Qt::BlankCursor) viewport()->setCursor(Qt::IBeamCursor); } bool LiteEditorWidgetBase::viewportEvent(QEvent *e) { if (e->type() == QEvent::ToolTip) { if (QApplication::keyboardModifiers() & Qt::ControlModifier) { return true; } const QHelpEvent *he = static_cast<QHelpEvent*>(e); m_upToolTipPos = he->pos(); m_upToolTipDeployTimer->start(m_upToolTipTime); return true; } return QPlainTextEdit::viewportEvent(e); } void LiteEditorWidgetBase::inputMethodEvent(QInputMethodEvent *e) { m_inputCursorOffset = e->preeditString().length(); QPlainTextEdit::inputMethodEvent(e); } static void fillBackground(QPainter *p, const QRectF &rect, QBrush brush, QRectF gradientRect = QRectF()) { p->save(); if (brush.style() >= Qt::LinearGradientPattern && brush.style() <= Qt::ConicalGradientPattern) { if (!gradientRect.isNull()) { QTransform m = QTransform::fromTranslate(gradientRect.left(), gradientRect.top()); m.scale(gradientRect.width(), gradientRect.height()); brush.setTransform(m); const_cast<QGradient *>(brush.gradient())->setCoordinateMode(QGradient::LogicalMode); } } else { p->setBrushOrigin(rect.topLeft()); } p->fillRect(rect, brush); p->restore(); } //copy of QTextDocument static bool findInBlock(const QTextBlock &block, const QRegExp &expression, int offset, QTextDocument::FindFlags options, QTextCursor &cursor) { const QRegExp expr(expression); QString text = block.text(); text.replace(QChar::Nbsp, QLatin1Char(' ')); int idx = -1; while (offset >=0 && offset <= text.length()) { idx = (options & QTextDocument::FindBackward) ? expr.lastIndexIn(text, offset) : expr.indexIn(text, offset); if (idx == -1 || expr.matchedLength() == 0) return false; if (options & QTextDocument::FindWholeWords) { const int start = idx; const int end = start + expr.matchedLength(); if ((start != 0 && isIdentifierChar(text.at(start - 1))) || (end != text.length() && isIdentifierChar(text.at(end)))) { //if this is not a whole word, continue the search in the string offset = (options & QTextDocument::FindBackward) ? idx-1 : end+1; idx = -1; continue; } } //we have a hit, return the cursor for that. break; } if (idx == -1) return false; cursor = QTextCursor(block.docHandle(), block.position() + idx); cursor.setPosition(cursor.position() + expr.matchedLength(), QTextCursor::KeepAnchor); return true; } void LiteEditorWidgetBase::paintEvent(QPaintEvent *e) { QPainter painter(viewport()); QTextDocument *doc = this->document(); QTextCursor cursor = textCursor(); const QFontMetricsF fm(this->font()); qreal averageCharWidth = fm.averageCharWidth(); int charOffsetX = this->document()->documentMargin()- this->horizontalScrollBar()->value(); bool hasSelection = cursor.hasSelection(); int selectionStart = cursor.selectionStart(); int selectionEnd = cursor.selectionEnd(); QTextBlock block = firstVisibleBlock(); QPointF offset = contentOffset(); qreal offsetX = offset.x(); //QPlainTextEdit::paintEvent QRect er = e->rect(); QRect viewportRect = viewport()->rect(); qreal viewportOffsetLeft = viewportRect.left()-offsetX; qreal viewportOffsetRight = viewportRect.right()-offsetX; painter.setPen(this->palette().color(QPalette::Text)); painter.fillRect(er,this->palette().brush(QPalette::Base)); bool editable = !isReadOnly(); qreal maximumWidth = document()->documentLayout()->documentSize().width(); // Set a brush origin so that the WaveUnderline knows where the wave started painter.setBrushOrigin(offset); // keep right margin clean from full-width selection int maxX = offset.x() + qMax((qreal)viewportRect.width(), maximumWidth) - document()->documentMargin(); er.setRight(qMin(er.right(), maxX)); painter.setClipRect(er); QAbstractTextDocumentLayout::PaintContext context = getPaintContext(); static bool bc = true; bc = !bc; context.cursorPosition = bc ? -1 : cursor.position(); if (!hasFocus()) { context.cursorPosition = -1; } int blockSelectionIndex = -1; if (m_inBlockSelectionMode && context.selections.count() && context.selections.last().cursor == textCursor()) { blockSelectionIndex = context.selections.size()-1; context.selections[blockSelectionIndex].format.clearBackground(); } while (block.isValid()) { QRectF r = blockBoundingRect(block).translated(offset); if (!block.isVisible()) { offset.ry() += r.height(); block = block.next(); continue; } QTextLayout *layout = block.layout(); if (!layout->cacheEnabled()) { layout->setCacheEnabled(true); } if (r.bottom() >= er.top() && r.top() <= er.bottom()) { QTextBlockFormat blockFormat = block.blockFormat(); QBrush bg = blockFormat.background(); if (bg != Qt::NoBrush) { QRectF contentsRect = r; contentsRect.setWidth(qMax(r.width(), maximumWidth)); fillBackground(&painter, contentsRect, bg); } QVector<QTextLayout::FormatRange> selections; QVector<QTextLayout::FormatRange> prioritySelections; int blpos = block.position(); int bllen = block.length(); for (int i = 0; i < context.selections.size(); ++i) { const QAbstractTextDocumentLayout::Selection &range = context.selections.at(i); const int selStart = range.cursor.selectionStart() - blpos; const int selEnd = range.cursor.selectionEnd() - blpos; if (selStart < bllen && selEnd >= 0 && selEnd >= selStart) { QTextLayout::FormatRange o; o.start = selStart; o.length = selEnd - selStart; o.format = range.format; if (i == blockSelectionIndex) { QString text = block.text(); const TextEditor::TabSettings &ts = this->tabSettings(); o.start = ts.positionAtColumn(text, m_blockSelection.firstVisualColumn); o.length = ts.positionAtColumn(text,m_blockSelection.lastVisualColumn) - o.start; } // if ((hasSelection && i == context.selections.size()-1) // || (o.format.foreground().style() == Qt::NoBrush // && o.format.underlineStyle() != QTextCharFormat::NoUnderline // && o.format.background() == Qt::NoBrush)) { // prioritySelections.append(o); // } else { selections.append(o); // } } else if (!range.cursor.hasSelection() && range.format.hasProperty(QTextFormat::FullWidthSelection) && block.contains(range.cursor.position())) { // for full width selections we don't require an actual selection, just // a position to specify the line. that's more convenience in usage. QTextLayout::FormatRange o; QTextLine l = layout->lineForTextPosition(range.cursor.position() - blpos); o.start = l.textStart(); o.length = l.textLength(); if (o.start + o.length == bllen - 1) ++o.length; // include newline o.format = range.format; selections.append(o); } } selections += prioritySelections; // for (int i = 0; i < context.selections.size(); ++i) { // const QAbstractTextDocumentLayout::Selection &range = context.selections.at(i); // const int selStart = range.cursor.selectionStart() - blpos; // const int selEnd = range.cursor.selectionEnd() - blpos; // if (!hasSelection && range.cursor.selectionEnd() == selectionEnd) { // continue; // } // if (selStart < bllen && selEnd > 0 // && selEnd > selStart) { // QTextLayout::FormatRange o; // o.start = selStart; // o.length = selEnd - selStart; // QTextCharFormat formatCopy(range.format); // formatCopy.clearForeground(); // o.format = formatCopy; // if (!o.format.hasProperty(LiteEditorWidgetBase::MatchBrace)) { // //o.format.setForeground(palette().highlightedText()); // o.format.setBackground(palette().highlight()); // } // selections.append(o); // } else if (!range.cursor.hasSelection() && range.format.hasProperty(QTextFormat::FullWidthSelection) // && block.contains(range.cursor.position())) { // // for full width selections we don't require an actual selection, just // // a position to specify the line. that's more convenience in usage. // QTextLayout::FormatRange o; // QTextLine l = layout->lineForTextPosition(range.cursor.position() - blpos); // o.start = l.textStart(); // o.length = l.textLength(); // if (o.start + o.length == bllen - 1) // ++o.length; // include newline // o.format = range.format; // selections.append(o); // } // } if (block == textCursor().block()) { QTextLine l = layout->lineForTextPosition(textCursor().positionInBlock()); QRectF rr = l.rect(); rr.moveTop(rr.top() + r.top()); rr.setLeft(offset.x()); rr.setRight(viewportRect.width() - offset.x()); painter.fillRect(rr, m_currentLineBackground); } bool findSelectionMark = false; if (!m_findExpression.isEmpty()) { painter.save(); QColor color(this->palette().color(QPalette::Text)); color.setAlpha(128); painter.setPen(color); int pos = 0; while (true) { QTextCursor cur; if (!findInBlock(block,m_findExpression,pos,m_findFlags,cur)) { break; } findSelectionMark = true; pos = cur.selectionEnd()-block.position(); QTextLine l = layout->lineForTextPosition(cur.selectionStart()-blpos); qreal left = l.cursorToX(cur.selectionStart()-blpos); qreal right = l.cursorToX(cur.selectionEnd()-blpos); if (right >= viewportOffsetLeft && left <= viewportOffsetRight) { painter.drawRoundedRect(offsetX+left,r.top()+l.y(),right-left,l.height(),3,3); } } painter.restore(); } else if (!m_selectionExpression.isEmpty()) { painter.save(); QColor color(this->palette().color(QPalette::Text)); color.setAlpha(128); painter.setPen(color); int pos = 0; while (true) { QTextCursor cur; if (!findInBlock(block,m_selectionExpression,pos,QTextDocument::FindWholeWords,cur)) { break; } findSelectionMark = true; pos = cur.selectionEnd()-block.position(); if (selectionStart == cur.selectionStart() && selectionEnd == cur.selectionEnd()) { continue; } QTextLine l = layout->lineForTextPosition(cur.selectionStart()-blpos); qreal left = l.cursorToX(cur.selectionStart()-blpos); qreal right = l.cursorToX(cur.selectionEnd()-blpos); if (right >= viewportOffsetLeft && left <= viewportOffsetRight) { painter.drawRoundedRect(offsetX+left,r.top()+l.y(),right-left,l.height(),3,3); } } painter.restore(); } TextEditor::BaseTextDocumentLayout::userData(block)->setFindExpressionMark(findSelectionMark); QRectF blockSelectionCursorRect; if (m_inBlockSelectionMode && block.position() >= m_blockSelection.firstBlock.block().position() && block.position() <= m_blockSelection.lastBlock.block().position()) { QString text = block.text(); const TextEditor::TabSettings &ts = this->tabSettings(); qreal spacew = QFontMetricsF(font()).width(QLatin1Char(' ')); int offset = 0; int relativePos = ts.positionAtColumn(text, m_blockSelection.firstVisualColumn, &offset); QTextLine line = layout->lineForTextPosition(relativePos); qreal x = line.cursorToX(relativePos) + offset * spacew; int eoffset = 0; int erelativePos = ts.positionAtColumn(text, m_blockSelection.lastVisualColumn, &eoffset); QTextLine eline = layout->lineForTextPosition(erelativePos); qreal ex = eline.cursorToX(erelativePos) + eoffset * spacew; QRectF rr = line.naturalTextRect(); rr.moveTop(rr.top() + r.top()); rr.setLeft(r.left() + x); if (line.lineNumber() == eline.lineNumber()) rr.setRight(r.left() + ex); painter.fillRect(rr, palette().highlight()); if ((m_blockSelection.anchor == TextEditor::BaseTextBlockSelection::TopLeft && block == m_blockSelection.firstBlock.block()) || (m_blockSelection.anchor == TextEditor::BaseTextBlockSelection::BottomLeft && block == m_blockSelection.lastBlock.block()) ) { rr.setRight(rr.left()+2); blockSelectionCursorRect = rr; } for (int i = line.lineNumber() + 1; i < eline.lineNumber(); ++i) { rr = layout->lineAt(i).naturalTextRect(); rr.moveTop(rr.top() + r.top()); rr.setLeft(r.left() + x); painter.fillRect(rr, palette().highlight()); } rr = eline.naturalTextRect(); rr.moveTop(rr.top() + r.top()); rr.setRight(r.left() + ex); if (line.lineNumber() != eline.lineNumber()) painter.fillRect(rr, palette().highlight()); if ((m_blockSelection.anchor == TextEditor::BaseTextBlockSelection::TopRight && block == m_blockSelection.firstBlock.block()) || (m_blockSelection.anchor == TextEditor::BaseTextBlockSelection::BottomRight && block == m_blockSelection.lastBlock.block())) { rr.setLeft(rr.right()-2); blockSelectionCursorRect = rr; } } bool drawCursor = ( editable && context.cursorPosition >= blpos && context.cursorPosition < blpos + bllen); bool drawCursorAsBlock = drawCursor && overwriteMode() ; if (drawCursorAsBlock) { if (context.cursorPosition == blpos + bllen - 1) { drawCursorAsBlock = false; } else { QTextLayout::FormatRange o; o.start = context.cursorPosition - blpos; o.length = 1; o.format.setForeground(palette().base()); o.format.setBackground(palette().text()); selections.append(o); } } QRect clip = er; clip.setTop(r.top()); clip.setBottom(r.bottom()); layout->draw(&painter, offset, selections, clip); if (!m_inBlockSelectionMode) { if ((drawCursor && !drawCursorAsBlock) || (editable && context.cursorPosition < -1 && !layout->preeditAreaText().isEmpty())) { int cpos = context.cursorPosition+m_inputCursorOffset; if (cpos < -1) cpos = layout->preeditAreaPosition() - (cpos + 2); else cpos -= blpos; layout->drawCursor(&painter, offset, cpos, cursorWidth()); } } #ifndef Q_OS_MAC if (blockSelectionCursorRect.isValid()) painter.fillRect(blockSelectionCursorRect, palette().text()); #endif } //draw indent line if (m_indentLineVisible) { QString text = block.text(); int pos = text.length(); for (int i = 0; i < pos; i++) { if (!text.at(i).isSpace()) { pos = i; break; } } QTextLine line = layout->lineForTextPosition(pos); int kt = r.top()+1; int kb = r.top()+line.height()-1; int k = line.cursorToX(pos)/averageCharWidth; painter.save(); painter.setPen(QPen(m_indentLineForeground,1,Qt::DotLine)); for (int i = 0; i < k; i+=m_nTabSize) { int xoff = charOffsetX+averageCharWidth*i; painter.drawLine(xoff,kt,xoff,kb); } painter.restore(); } if (m_visualizeWhitespace) { QString text = block.text(); painter.save(); for (int i = 0; i < text.length(); i++) { QTextLine line = layout->lineForTextPosition(i); if (line.cursorToX(i) > er.right()) { break; } if (text.at(i) == '\t') { painter.setPen(QPen(m_visualizeWhitespaceForeground,1)); QTextLine line = layout->lineForTextPosition(i); QRectF lineRect = line.naturalTextRect().translated(offset.x(), r.top()); qreal left = line.cursorToX(i)+offset.x()+2; qreal right = line.cursorToX(i+1)+offset.x()-4; qreal y = lineRect.top()+line.height()/2; painter.drawLine(left,y,right,y); painter.drawLine(right-4,y-4,right,y); painter.drawLine(right-4,y+4,right,y); } else if (text.at(i).isSpace()) { painter.setPen(QPen(m_visualizeWhitespaceForeground,2)); QTextLine line = layout->lineForTextPosition(i); QRectF lineRect = line.naturalTextRect().translated(offset.x(), r.top()); qreal left = line.cursorToX(i)+offset.x(); qreal right = line.cursorToX(i+1)+offset.x(); qreal y = lineRect.top()+line.height()/2; painter.drawPoint(left+(right-left)/2,y); } } painter.restore(); } QTextBlock nextBlock = block.next(); //draw wrap int lineCount = layout->lineCount(); if (lineCount >= 2 || !nextBlock.isValid()) { painter.save(); painter.setPen(Qt::lightGray); for (int i = 0; i < lineCount-1; ++i) { // paint line wrap indicator QTextLine line = layout->lineAt(i); QRectF lineRect = line.naturalTextRect().translated(offset.x(), r.top()); QChar visualArrow((ushort)0x21b5); painter.drawText(QPointF(lineRect.right(), lineRect.top() + line.ascent()), visualArrow); } if (m_eofVisible && !nextBlock.isValid()) { // paint EOF symbol QTextLine line = layout->lineAt(lineCount-1); QRectF lineRect = line.naturalTextRect().translated(offset.x(), r.top()); int h = 4; lineRect.adjust(0, 0, -1, -1); QPainterPath path; QPointF pos(lineRect.topRight() + QPointF(h+4, line.ascent())); path.moveTo(pos); path.lineTo(pos + QPointF(-h, -h)); path.lineTo(pos + QPointF(0, -2*h)); path.lineTo(pos + QPointF(h, -h)); path.closeSubpath(); painter.setBrush(painter.pen().color()); painter.drawPath(path); } painter.restore(); } //draw fold text ... QTextBlock nextVisibleBlock = nextBlock; if (!nextVisibleBlock.isVisible()) { // invisible blocks do have zero line count nextVisibleBlock = doc->findBlockByLineNumber(nextVisibleBlock.firstLineNumber()); // paranoia in case our code somewhere did not set the line count // of the invisible block to 0 while (nextVisibleBlock.isValid() && !nextVisibleBlock.isVisible()) nextVisibleBlock = nextVisibleBlock.next(); } if (nextBlock.isValid() && !nextBlock.isVisible()) { bool selectThis = (hasSelection && nextBlock.position() >= selectionStart && nextBlock.position() < selectionEnd); if (selectThis) { painter.save(); painter.setBrush(palette().highlight()); } QTextLayout *layout = block.layout(); QTextLine line = layout->lineAt(layout->lineCount()-1); QRectF lineRect = line.naturalTextRect().translated(offset.x(), r.top()); lineRect.adjust(0, 0, -1, -1); QRectF collapseRect(lineRect.right() + 12, lineRect.top(), fontMetrics().width(QLatin1String(" {...}; ")), lineRect.height()); painter.setRenderHint(QPainter::Antialiasing, true); painter.translate(.5, .5); painter.drawRoundedRect(collapseRect.adjusted(0, 0, 0, -1), 3, 3); painter.setRenderHint(QPainter::Antialiasing, false); painter.translate(-.5, -.5); QString replacement = QLatin1String("..."); if (TextEditor::TextBlockUserData *nextBlockUserData = TextEditor::BaseTextDocumentLayout::testUserData(nextBlock)) { if (nextBlockUserData->foldingStartIncluded()) replacement.prepend(nextBlock.text().trimmed().left(1)); } block = nextVisibleBlock.previous(); if (!block.isValid()) block = doc->lastBlock(); if (TextEditor::TextBlockUserData *blockUserData = TextEditor::BaseTextDocumentLayout::testUserData(block)) { if (blockUserData->foldingEndIncluded()) { QString right = block.text().trimmed(); if (right.endsWith(QLatin1Char(';'))) { right.chop(1); right = right.trimmed(); replacement.append(right.right(right.endsWith(QLatin1Char('/')) ? 2 : 1)); replacement.append(QLatin1Char(';')); } else { replacement.append(right.right(right.endsWith(QLatin1Char('/')) ? 2 : 1)); } } } if (selectThis) painter.setPen(palette().highlightedText().color()); painter.drawText(collapseRect, Qt::AlignCenter, replacement); if (selectThis) painter.restore(); } offset.ry() += r.height(); if (offset.y() > viewportRect.height()) break; block = block.next(); } if (backgroundVisible() && !block.isValid() && offset.y() <= er.bottom() && (centerOnScroll() || verticalScrollBar()->maximum() == verticalScrollBar()->minimum())) { painter.fillRect(QRect(QPoint((int)er.left(), (int)offset.y()), er.bottomRight()), palette().background()); } if (m_rightLineVisible) { int xoff = charOffsetX+averageCharWidth*m_rightLineWidth; painter.save(); painter.setPen(QPen(m_indentLineForeground,1,Qt::DotLine)); painter.drawLine(xoff,0,xoff,rect().height()); painter.restore(); } } bool LiteEditorWidgetBase::hasBlockSelection() const { return m_inBlockSelectionMode; } void LiteEditorWidgetBase::transformSelection(TransformationMethod method) { if (hasBlockSelection()) { transformBlockSelection(method); return; } QTextCursor cursor = this->textCursor(); int pos = cursor.position(); int anchor = cursor.anchor(); if (!cursor.hasSelection()) { // if nothing is selected, select the word over the cursor cursor.select(QTextCursor::WordUnderCursor); } QString text = cursor.selectedText(); QString transformedText = method(text); if (transformedText == text) { // if the transformation does not do anything to the selection, do no create an undo step return; } cursor.insertText(transformedText); // (re)select the changed text // Note: this assumes the transformation did not change the length, cursor.setPosition(anchor); cursor.setPosition(pos, QTextCursor::KeepAnchor); this->setTextCursor(cursor); } int LiteEditorWidgetBase::verticalBlockSelectionFirstColumn() const { if (m_inBlockSelectionMode) return m_blockSelection.firstVisualColumn; return -1; } int LiteEditorWidgetBase::verticalBlockSelectionLastColumn() const { if (m_inBlockSelectionMode) return m_blockSelection.lastVisualColumn; return -1; } void LiteEditorWidgetBase::transformBlockSelection(TransformationMethod method) { QTextCursor cursor = textCursor(); int minPos = cursor.anchor(); int maxPos = cursor.position(); if (minPos > maxPos) qSwap(minPos, maxPos); int leftBound = verticalBlockSelectionFirstColumn(); int rightBound = verticalBlockSelectionLastColumn(); TextEditor::BaseTextBlockSelection::Anchor anchorPosition = m_blockSelection.anchor; QString text = cursor.selectedText(); QString transformedText = text; QTextBlock currentLine = document()->findBlock(minPos); int lineStart = currentLine.position(); do { if (currentLine.contains(lineStart + leftBound)) { int currentBlockWidth = qBound(0, currentLine.text().length() - leftBound, rightBound - leftBound); cursor.setPosition(lineStart + leftBound); cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor, currentBlockWidth); transformedText.replace(lineStart + leftBound - minPos, currentBlockWidth, method(cursor.selectedText())); } currentLine = currentLine.next(); if (!currentLine.isValid()) break; lineStart = currentLine.position(); } while (lineStart < maxPos); if (transformedText == text) { // if the transformation does not do anything to the selection, do no create an undo step return; } cursor.setPosition(minPos); cursor.setPosition(maxPos, QTextCursor::KeepAnchor); cursor.insertText(transformedText); // restore former block selection if (anchorPosition <= TextEditor::BaseTextBlockSelection::TopRight) qSwap(minPos, maxPos); cursor.setPosition(minPos); cursor.setPosition(maxPos, QTextCursor::KeepAnchor); m_blockSelection.fromSelection(tabSettings(), cursor); m_blockSelection.anchor = anchorPosition; m_inBlockSelectionMode = true; m_blockSelection.firstVisualColumn = leftBound; m_blockSelection.lastVisualColumn = rightBound; setTextCursor(m_blockSelection.selection(tabSettings())); viewport()->update(); } // Update selections or find marks. void LiteEditorWidgetBase::updateFindOrSelectionMark(LiteApi::EditorNaviagteType type) { clearAllNavigateMark(type, ""); if (!checkFindOrSelectionMark(type)) return; QTextDocument *doc = this->document(); QTextCursor cur; for (QTextBlock it = doc->begin(); it != doc->end(); it = it.next()) { if (!checkFindOrSelectionMarkBlock(it, type,cur)) continue; int blockNumber = it.blockNumber(); int offset = cur.selectionStart()-it.position(); int selection = cur.selectionEnd()-cur.selectionStart(); insertNavigateMark(blockNumber, type, QString("%1: %2").arg(blockNumber+1).arg(it.text()), "",offset,selection); } } bool LiteEditorWidgetBase::checkFindOrSelectionMark(LiteApi::EditorNaviagteType type) const { if (LiteApi::EditorNavigateFind == type) { return !m_findExpression.isEmpty(); } if (LiteApi::EditorNavigateSelection == type) { return !m_selectionExpression.isEmpty() && m_findExpression.isEmpty(); } return false; } bool LiteEditorWidgetBase::checkFindOrSelectionMarkBlock( const QTextBlock &block, LiteApi::EditorNaviagteType type, QTextCursor &cur) const { int pos = 0; if (LiteApi::EditorNavigateFind == type) return findInBlock(block, m_findExpression, pos, m_findFlags, cur); if (LiteApi::EditorNavigateSelection == type) return findInBlock(block, m_selectionExpression, pos, QTextDocument::FindWholeWords, cur); return false; }
149,699
C++
.cpp
3,926
29.38054
221
0.59999
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,493
faketooltip.cpp
visualfc_liteide/liteidex/src/plugins/liteeditor/faketooltip.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: faketooltip.cpp // Creator: visualfc <visualfc@gmail.com> #include "faketooltip.h" #include <QStylePainter> #include <QStyleOptionFrame> //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 FakeToolTip::FakeToolTip(QWidget *parent) : QWidget(parent, Qt::ToolTip | Qt::WindowStaysOnTopHint) { setFocusPolicy(Qt::NoFocus); //setAttribute(Qt::WA_DeleteOnClose); QPalette p = palette(); const QColor toolTipTextColor = p.color(QPalette::Inactive, QPalette::ToolTipText); p.setColor(QPalette::Inactive, QPalette::WindowText, toolTipTextColor); p.setColor(QPalette::Inactive, QPalette::ButtonText, toolTipTextColor); setPalette(p); this->setForegroundRole(QPalette::ToolTipText); this->setBackgroundRole(QPalette::ToolTipBase); const int margin = 1 + style()->pixelMetric(QStyle::PM_ToolTipLabelFrameWidth, 0, this); setContentsMargins(margin + 1, margin, margin, margin); setWindowOpacity(style()->styleHint(QStyle::SH_ToolTipLabel_Opacity, 0, this) / 255.0); } void FakeToolTip::paintEvent(QPaintEvent *) { QStylePainter p(this); QStyleOptionFrame opt; opt.init(this); p.drawPrimitive(QStyle::PE_PanelTipLabel, opt); p.end(); } void FakeToolTip::resizeEvent(QResizeEvent *) { QStyleHintReturnMask frameMask; QStyleOption option; option.init(this); if (style()->styleHint(QStyle::SH_ToolTip_Mask, &option, this, &frameMask)) setMask(frameMask.region); }
2,706
C++
.cpp
66
38.060606
92
0.699962
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,494
katetextlexer.cpp
visualfc_liteide/liteidex/src/plugins/liteeditor/katetextlexer.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: katetextlexer.cpp // Creator: visualfc <visualfc@gmail.com> #include "katetextlexer.h" #include "qtc_texteditor/basetextdocumentlayout.h" #include "qtc_texteditor/syntaxhighlighter.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 KateTextLexer::KateTextLexer(QObject *parent) : LiteApi::ITextLexer(parent) { } bool KateTextLexer::isLangSupport() const { return true; } bool KateTextLexer::isInComment(const QTextCursor &cursor) const { int pos = cursor.positionInBlock(); TextEditor::TextBlockUserData *data = TextEditor::BaseTextDocumentLayout::userData(cursor.block()); int state = data->lexerState(); if (state != 0 && data->tokens().isEmpty()) { QTextBlock block = cursor.block().previous(); while(block.isValid()) { TextEditor::TextBlockUserData *data = TextEditor::BaseTextDocumentLayout::userData(block); if (data && !data->tokens().isEmpty()) { return data->tokens().last().id == TextEditor::SyntaxHighlighter::Comment; } block = block.previous(); } return false; } int offset = 0; if (cursor.positionInBlock() == cursor.block().length()-1) { offset = 1; } foreach(TextEditor::SyntaxToken token, data->tokens()) { if ((token.id == TextEditor::SyntaxHighlighter::Comment) && (pos >= token.offset) && (pos < (token.offset+token.count+offset))) { return true; } } return false; } bool KateTextLexer::isInString(const QTextCursor &cursor) const { int pos = cursor.positionInBlock(); TextEditor::TextBlockUserData *data = TextEditor::BaseTextDocumentLayout::userData(cursor.block()); foreach(TextEditor::SyntaxToken token, data->tokens()) { if ((token.id == TextEditor::SyntaxHighlighter::String) && (pos >= token.offset) && (pos < token.offset+token.count)) { return true; } } return false; } bool KateTextLexer::isInEmptyString(const QTextCursor &cursor) const { int pos = cursor.positionInBlock(); TextEditor::TextBlockUserData *data = TextEditor::BaseTextDocumentLayout::userData(cursor.block()); foreach(TextEditor::SyntaxToken token, data->tokens()) { if ((token.id == TextEditor::SyntaxHighlighter::String) && (pos >= token.offset) && (pos < token.offset+token.count) && (token.count == 2)) { return true; } } return false; } bool KateTextLexer::isEndOfString(const QTextCursor &cursor) const { int pos = cursor.positionInBlock(); TextEditor::TextBlockUserData *data = TextEditor::BaseTextDocumentLayout::userData(cursor.block()); foreach(TextEditor::SyntaxToken token, data->tokens()) { if ((token.id == TextEditor::SyntaxHighlighter::String) && (pos == (token.offset+token.count-1)) ) { return true; } } return false; } bool KateTextLexer::isInStringOrComment(const QTextCursor &cursor) const { return isInString(cursor) || isInComment(cursor); } bool KateTextLexer::isCanAutoCompleter(const QTextCursor &cursor) const { return !isInStringOrComment(cursor); } bool KateTextLexer::isInImport(const QTextCursor &/*cursor*/) const { return false; } int KateTextLexer::startOfFunctionCall(const QTextCursor &/*cursor*/) const { return -1; } QString KateTextLexer::fetchFunctionTip(const QString &/*func*/, const QString &/*kind*/, const QString &/*info*/) { return QString(); } bool KateTextLexer::fetchFunctionArgs(const QString &/*str*/, int &/*argnr*/, int &/*parcount*/) { return false; } QString KateTextLexer::stringQuoteList() const { return QString("\"\'"); } bool KateTextLexer::hasStringBackslash() const { return true; }
5,079
C++
.cpp
140
31.814286
114
0.668901
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,495
functiontooltip.cpp
visualfc_liteide/liteidex/src/plugins/liteeditor/functiontooltip.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: functiontooltip.cpp // Creator: visualfc <visualfc@gmail.com> #include "functiontooltip.h" #include "faketooltip.h" #include <QDesktopWidget> #include <QApplication> #include <QStylePainter> #include <QStyleOptionFrame> #include <QToolButton> #include <QHBoxLayout> #include <QToolTip> #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 FunctionTooltip::FunctionTooltip(LiteApi::IApplication *app, LiteApi::ITextEditor *editor, LiteApi::ITextLexer *lexer, int maxTipCount, QObject *parent) : QObject(parent), m_liteApp(app), m_editor(editor), m_lexer(lexer), m_maxTipCount(maxTipCount) { m_editWidget = LiteApi::getPlainTextEdit(editor); m_popup = new FakeToolTip(m_editWidget); QHBoxLayout *hbox = new QHBoxLayout; hbox->setMargin(0); hbox->setSpacing(0); m_label = new QLabel; hbox->addWidget(m_label); m_popup->setLayout(hbox); qApp->installEventFilter(this); } FunctionTooltip::~FunctionTooltip() { delete m_popup; } void FunctionTooltip::showFunctionHint(int startPosition, const QString &tip) { m_currentarg = -1; m_tip = tip; m_escapePressed = false; m_startpos = startPosition; saveTip(startPosition,tip); updateArgumentHighlight(); showPopup(m_startpos); } bool FunctionTooltip::eventFilter(QObject *obj, QEvent *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) { hide(); } break; case QEvent::KeyPress: if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape) { m_escapePressed = 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_Comma || ke->text() == "(") { if (m_lexer->isInStringOrComment(m_editor->textCursor())) { return false; } int pos = m_lexer->startOfFunctionCall(m_editor->textCursor()); if (pos != -1 && pos+1 != m_startpos) { m_startpos = pos+1; if (restoreTip(m_startpos)) { updateArgumentHighlight(); showPopup(m_startpos); } else { hide(); } return false; } } else if (m_popup->isVisible()) { updateArgumentHighlight(); } } 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: { QWidget *widget = qobject_cast<QWidget *>(obj); if (! (widget == m_label || m_popup->isAncestorOf(widget))) { hide(); } } break; default: break; } return false; } void FunctionTooltip::updateArgumentHighlight() { int curpos = m_editor->position(); if (curpos < m_startpos) { hide(); return; } QString str = m_editor->textAt(m_startpos, curpos - m_startpos); int argnr = 0; int parcount = 0; m_lexer->fetchFunctionArgs(str,argnr,parcount); if (m_currentarg != argnr) { m_currentarg = argnr; updateHintText(); } if (parcount < 0) hide(); } void FunctionTooltip::updateHintText() { QString hintText; hintText = m_tip; /* for (int i = 0; i < m_args.size(); i++) { if (i != 0) { hintText += ","; } if (i == m_currentarg) { hintText += "<b>"+Qt::escape(m_args[i])+"</b>"; } else { hintText += Qt::escape(m_args[i]); } } */ m_label->setText(hintText); } void FunctionTooltip::showPopup(int startpos) { QToolTip::hideText(); m_popup->setFixedWidth(m_popup->minimumSizeHint().width()); const QDesktopWidget *desktop = QApplication::desktop(); #ifdef Q_WS_MAC const QRect screen = desktop->availableGeometry(desktop->screenNumber(m_editor->widget())); #else const QRect screen = desktop->screenGeometry(desktop->screenNumber(m_editor->widget())); #endif const QSize sz = m_popup->sizeHint(); QPoint pos = m_editor->cursorRect(startpos).topLeft(); pos.setY(pos.y() - sz.height() - 1); if (pos.x() + sz.width() > screen.right()) pos.setX(screen.right() - sz.width()); m_popup->move(pos); if (!m_popup->isVisible()) { m_popup->show(); } } void FunctionTooltip::hide() { if (!m_popup->isVisible()) { return; } m_popup->hide(); m_startpos = -1; } void FunctionTooltip::saveTip(int startPos, const QString &text) { QMutableListIterator<TipInfo> it(m_infoList); while(it.hasNext()) { TipInfo &info = it.next(); if (info.startPos == startPos) { info.tip = text; return; } } m_infoList.append(TipInfo(startPos,text)); if (m_infoList.size() >= m_maxTipCount) { m_infoList.removeFirst(); } } bool FunctionTooltip::restoreTip(int startpos) { foreach(TipInfo info, m_infoList) { if (info.startPos == startpos) { m_tip = info.tip; return true; } } return false; }
7,137
C++
.cpp
225
25.213333
152
0.592361
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,496
liteeditoroption.cpp
visualfc_liteide/liteidex/src/plugins/liteeditor/liteeditoroption.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: liteeditoroption.cpp // Creator: visualfc <visualfc@gmail.com> #include "liteeditoroption.h" #include "ui_liteeditoroption.h" #include "liteeditor_global.h" #include "liteapi/liteutil.h" #include <QFontDatabase> #include <QDir> #include <QFileInfo> #include <QStandardItemModel> #include <QStandardItem> //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 QString defaultFontFamily() { #if defined(Q_OS_WIN) return "Courier"; #elif defined(Q_OS_LINUX) return "Monospace"; #elif defined(Q_OS_MAC) return "Menlo"; #else return "Monospace"; #endif } LiteEditorOption::LiteEditorOption(LiteApi::IApplication *app,QObject *parent) : LiteApi::IOption(parent), m_liteApp(app), m_widget(new QWidget), ui(new Ui::LiteEditorOption) { ui->setupUi(m_widget); // QFontDatabase db; // const QStringList families = db.families(); connect(ui->editPushButton,SIGNAL(clicked()),this,SLOT(editStyleFile())); connect(ui->rightLineVisibleCheckBox,SIGNAL(toggled(bool)),ui->rightLineWidthSpinBox,SLOT(setEnabled(bool))); connect(ui->restoreDefaultFontButton,SIGNAL(clicked()),this,SLOT(restoreDefaultFont())); connect(ui->monospaceFontCheckBox,SIGNAL(toggled(bool)),this,SLOT(filterMonospaceFont(bool))); m_mimeModel = new QStandardItemModel(0,5,this); m_mimeModel->setHeaderData(0,Qt::Horizontal,tr("MIME Type")); m_mimeModel->setHeaderData(1,Qt::Horizontal,tr("Tab Width")); m_mimeModel->setHeaderData(2,Qt::Horizontal,tr("Tab To Spaces")); m_mimeModel->setHeaderData(3,Qt::Horizontal,tr("Custom Extensions")); m_mimeModel->setHeaderData(4,Qt::Horizontal,tr("File Extensions")); connect(m_mimeModel,SIGNAL(itemChanged(QStandardItem*)),this,SLOT(mimeItemChanged(QStandardItem*))); ui->mimeTreeView->setModel(m_mimeModel); ui->mimeTreeView->setRootIsDecorated(false); #if QT_VERSION >= 0x050000 ui->mimeTreeView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); #else ui->mimeTreeView->header()->setResizeMode(QHeaderView::ResizeToContents); #endif } QWidget *LiteEditorOption::widget() { return m_widget; } QString LiteEditorOption::name() const { return "LiteEditor"; } QString LiteEditorOption::mimeType() const { return OPTION_LITEEDITOR; } void LiteEditorOption::save() { m_fontFamily = ui->fontComboBox->currentFont().family(); 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(EDITOR_FONTZOOM,fontZoom); QString style = ui->styleComboBox->currentText(); if (style != m_liteApp->settings()->value(EDITOR_STYLE,"default.xml").toString()) { m_liteApp->settings()->setValue(EDITOR_STYLE,style); QString styleFile = m_liteApp->resourcePath()+"/liteeditor/color/"+style; m_liteApp->editorManager()->loadColorStyleScheme(styleFile); } bool noprintCheck = ui->noprintCheckBox->isChecked(); bool autoIndent = ui->autoIndentCheckBox->isChecked(); bool autoBraces0 = ui->autoBraces0CheckBox->isChecked(); bool autoBraces1 = ui->autoBraces1CheckBox->isChecked(); bool autoBraces2 = ui->autoBraces2CheckBox->isChecked(); bool autoBraces3 = ui->autoBraces3CheckBox->isChecked(); bool autoBraces4 = ui->autoBraces4CheckBox->isChecked(); bool autoBraces5 = ui->autoBraces5CheckBox->isChecked(); bool lineNumberVisible = ui->lineNumberVisibleCheckBox->isChecked(); bool codeFoldVisible = ui->codeFoldVisibleCheckBox->isChecked(); bool caseSensitive = ui->completerCaseSensitiveCheckBox->isChecked(); bool fuzzyCompleter = ui->completerFuzzyCheckBox->isChecked(); bool cleanWhitespaceOnSave = ui->cleanWhitespaceOnSaveCheckBox->isChecked(); bool antialias = ui->antialiasCheckBox->isChecked(); bool rightLineVisible = ui->rightLineVisibleCheckBox->isChecked(); bool eofVisible = ui->eofVisibleCheckBox->isChecked(); bool defaultWordWrap = ui->defaultWordWrapCheckBox->isChecked(); bool indentLineVisible = ui->indentLineCheckBox->isChecked(); bool wheelZoom = ui->wheelZoomingCheckBox->isChecked(); bool visualizeWhitespace = ui->visualizeWhitespaceCheckBox->isChecked(); int rightLineWidth = ui->rightLineWidthSpinBox->value(); bool cleanCompleterCache = ui->cleanCompleterCacheCheckBox->isChecked(); bool copyToHtml = ui->enableCopyToHtmlCheckBox->isChecked(); int min = ui->preMinLineEdit->text().toInt(); if (min < 0 || min > 10) { min = 1; } bool offsetVisible = ui->offsetCheckBox->isChecked(); bool allowVscrollLastLine = ui->allowVscrollLastLineCheckBox->isChecked(); m_liteApp->settings()->setValue(EDITOR_NOPRINTCHECK,noprintCheck); m_liteApp->settings()->setValue(EDITOR_FAMILY,m_fontFamily); m_liteApp->settings()->setValue(EDITOR_FONTSIZE,m_fontSize); m_liteApp->settings()->setValue(EDITOR_ANTIALIAS,antialias); m_liteApp->settings()->setValue(EDITOR_AUTOINDENT,autoIndent); m_liteApp->settings()->setValue(EDITOR_AUTOBRACE0,autoBraces0); m_liteApp->settings()->setValue(EDITOR_AUTOBRACE1,autoBraces1); m_liteApp->settings()->setValue(EDITOR_AUTOBRACE2,autoBraces2); m_liteApp->settings()->setValue(EDITOR_AUTOBRACE3,autoBraces3); m_liteApp->settings()->setValue(EDITOR_AUTOBRACE4,autoBraces4); m_liteApp->settings()->setValue(EDITOR_AUTOBRACE5,autoBraces5); m_liteApp->settings()->setValue(EDITOR_LINENUMBERVISIBLE,lineNumberVisible); m_liteApp->settings()->setValue(EDITOR_CODEFOLDVISIBLE,codeFoldVisible); m_liteApp->settings()->setValue(EDITOR_EOFVISIBLE,eofVisible); m_liteApp->settings()->setValue(EDITOR_DEFAULTWORDWRAP,defaultWordWrap); m_liteApp->settings()->setValue(EDITOR_INDENTLINEVISIBLE,indentLineVisible); m_liteApp->settings()->setValue(EDITOR_COMPLETER_CASESENSITIVE,caseSensitive); m_liteApp->settings()->setValue(EDITOR_COMPLETER_FUZZY,fuzzyCompleter); m_liteApp->settings()->setValue(EDITOR_PREFIXLENGTH,min); m_liteApp->settings()->setValue(EDITOR_CLEANWHITESPACEONSAVE,cleanWhitespaceOnSave); m_liteApp->settings()->setValue(EDITOR_RIGHTLINEVISIBLE,rightLineVisible); m_liteApp->settings()->setValue(EDITOR_WHEEL_SCROLL,wheelZoom); m_liteApp->settings()->setValue(EDITOR_OFFSETVISIBLE,offsetVisible); m_liteApp->settings()->setValue(EDITOR_VISUALIZEWHITESPACE,visualizeWhitespace); m_liteApp->settings()->setValue(EDITOR_CLEAN_COMPLETERCACHE_SAVE,cleanCompleterCache); m_liteApp->settings()->setValue(EDITOR_ENABLE_COPYTOHTML,copyToHtml); m_liteApp->settings()->setValue(EDITOR_ALLOW_VSCROLL_LASTLINE,allowVscrollLastLine); if (rightLineVisible) { m_liteApp->settings()->setValue(EDITOR_RIGHTLINEWIDTH,rightLineWidth); } for (int i = 0; i < m_mimeModel->rowCount(); i++) { QString mime = m_mimeModel->item(i,0)->text(); QString tab = m_mimeModel->item(i,1)->text(); QString custom = m_mimeModel->item(i,3)->text(); bool ok; int n = tab.toInt(&ok); if (ok && n > 0 && n < 20) { //m_liteApp->settings()->setValue(MIMETYPE_TABWIDTH+mime,n); LiteApi::updateAppSetting(m_liteApp,MIMETYPE_TABWIDTH+mime,n,4); } bool b = m_mimeModel->item(i,2)->checkState() == Qt::Checked; //m_liteApp->settings()->setValue(MIMETYPE_TABTOSPACE+mime,b); LiteApi::updateAppSetting(m_liteApp,MIMETYPE_TABTOSPACE+mime,b,false); //m_liteApp->settings()->setValue(EDITOR_CUSTOMEXTENSION+mime,custom); LiteApi::updateAppSetting(m_liteApp,EDITOR_CUSTOMEXTENSION+mime,custom,""); LiteApi::IMimeType *imt = m_liteApp->mimeTypeManager()->findMimeType(mime); if (imt) { imt->setCustomPatterns(custom.split(";")); } } } void LiteEditorOption::load() { m_fontFamily = m_liteApp->settings()->value(EDITOR_FAMILY,defaultFontFamily()).toString(); ui->fontComboBox->setCurrentFont(QFont(m_fontFamily)); m_fontSize = m_liteApp->settings()->value(EDITOR_FONTSIZE,12).toInt(); int fontZoom = m_liteApp->settings()->value(EDITOR_FONTZOOM,100).toInt(); ui->fontZoomSpinBox->setValue(fontZoom); bool antialias = m_liteApp->settings()->value(EDITOR_ANTIALIAS,true).toBool(); ui->antialiasCheckBox->setChecked(antialias); updatePointSizes(); ui->fontZoomSpinBox->setValue(fontZoom); QString styleName = m_liteApp->settings()->value(EDITOR_STYLE,"default.xml").toString(); QString stylePath = m_liteApp->resourcePath()+"/liteeditor/color"; QDir dir(stylePath); int index = -1; if (!QFileInfo(stylePath,styleName).exists()) { styleName = "default.xml"; } ui->styleComboBox->clear(); foreach(QFileInfo info, dir.entryInfoList(QStringList() << "*.xml")) { ui->styleComboBox->addItem(info.fileName()); if (info.fileName() == styleName) { index = ui->styleComboBox->count()-1; } } if (index >= 0 && index < ui->styleComboBox->count()) { ui->styleComboBox->setCurrentIndex(index); } bool noprintCheck = m_liteApp->settings()->value(EDITOR_NOPRINTCHECK,true).toBool(); bool autoIndent = m_liteApp->settings()->value(EDITOR_AUTOINDENT,true).toBool(); bool autoBraces0 = m_liteApp->settings()->value(EDITOR_AUTOBRACE0,true).toBool(); bool autoBraces1 = m_liteApp->settings()->value(EDITOR_AUTOBRACE1,true).toBool(); bool autoBraces2 = m_liteApp->settings()->value(EDITOR_AUTOBRACE2,true).toBool(); bool autoBraces3 = m_liteApp->settings()->value(EDITOR_AUTOBRACE3,true).toBool(); bool autoBraces4 = m_liteApp->settings()->value(EDITOR_AUTOBRACE4,true).toBool(); bool autoBraces5 = m_liteApp->settings()->value(EDITOR_AUTOBRACE5,true).toBool(); bool caseSensitive = m_liteApp->settings()->value(EDITOR_COMPLETER_CASESENSITIVE,false).toBool(); bool fuzzyCompleter = m_liteApp->settings()->value(EDITOR_COMPLETER_FUZZY,true).toBool(); bool cleanWhitespaceOnSave = m_liteApp->settings()->value(EDITOR_CLEANWHITESPACEONSAVE,false).toBool(); bool lineNumberVisible = m_liteApp->settings()->value(EDITOR_LINENUMBERVISIBLE,true).toBool(); bool codeFoldVisible = m_liteApp->settings()->value(EDITOR_CODEFOLDVISIBLE,true).toBool(); bool rightLineVisible = m_liteApp->settings()->value(EDITOR_RIGHTLINEVISIBLE,true).toBool(); bool eofVisible = m_liteApp->settings()->value(EDITOR_EOFVISIBLE,false).toBool(); bool defaultWordWrap = m_liteApp->settings()->value(EDITOR_DEFAULTWORDWRAP,false).toBool(); bool indentLineVisible = m_liteApp->settings()->value(EDITOR_INDENTLINEVISIBLE,true).toBool(); bool wheelZoom = m_liteApp->settings()->value(EDITOR_WHEEL_SCROLL,true).toBool(); bool offsetVisible = m_liteApp->settings()->value(EDITOR_OFFSETVISIBLE,false).toBool(); bool visualizeWhitespace = m_liteApp->settings()->value(EDITOR_VISUALIZEWHITESPACE,false).toBool(); int rightLineWidth = m_liteApp->settings()->value(EDITOR_RIGHTLINEWIDTH,80).toInt(); bool cleanComplerCache = m_liteApp->settings()->value(EDITOR_CLEAN_COMPLETERCACHE_SAVE,false).toBool(); bool copyToHtml = m_liteApp->settings()->value(EDITOR_ENABLE_COPYTOHTML,true).toBool(); bool allowVscrollLastLine = m_liteApp->settings()->value(EDITOR_ALLOW_VSCROLL_LASTLINE,true).toBool(); int min = m_liteApp->settings()->value(EDITOR_PREFIXLENGTH,1).toInt(); ui->noprintCheckBox->setChecked(noprintCheck);; ui->autoIndentCheckBox->setChecked(autoIndent); ui->autoBraces0CheckBox->setChecked(autoBraces0); ui->autoBraces1CheckBox->setChecked(autoBraces1); ui->autoBraces2CheckBox->setChecked(autoBraces2); ui->autoBraces3CheckBox->setChecked(autoBraces3); ui->autoBraces4CheckBox->setChecked(autoBraces4); ui->autoBraces5CheckBox->setChecked(autoBraces5); ui->lineNumberVisibleCheckBox->setChecked(lineNumberVisible); ui->visualizeWhitespaceCheckBox->setChecked(visualizeWhitespace); ui->codeFoldVisibleCheckBox->setChecked(codeFoldVisible); ui->completerCaseSensitiveCheckBox->setChecked(caseSensitive); ui->completerFuzzyCheckBox->setChecked(fuzzyCompleter); ui->preMinLineEdit->setText(QString("%1").arg(min)); ui->cleanWhitespaceOnSaveCheckBox->setChecked(cleanWhitespaceOnSave); ui->rightLineVisibleCheckBox->setChecked(rightLineVisible); ui->rightLineWidthSpinBox->setValue(rightLineWidth); ui->eofVisibleCheckBox->setChecked(eofVisible); ui->defaultWordWrapCheckBox->setChecked(defaultWordWrap); ui->indentLineCheckBox->setChecked(indentLineVisible); ui->wheelZoomingCheckBox->setChecked(wheelZoom); ui->offsetCheckBox->setChecked(offsetVisible); ui->cleanCompleterCacheCheckBox->setChecked(cleanComplerCache); ui->enableCopyToHtmlCheckBox->setChecked(copyToHtml); ui->allowVscrollLastLineCheckBox->setChecked(allowVscrollLastLine); QStringList mimeTypes = m_liteApp->editorManager()->mimeTypeList(); qStableSort(mimeTypes); m_mimeModel->removeRows(0,m_mimeModel->rowCount()); foreach(QString mime, mimeTypes) { if (mime.startsWith("text/") || mime.startsWith("application/")) { QStandardItem *item = new QStandardItem(mime); item->setEditable(false); bool tabToSpace = false; int tabWidth = 4; LiteApi::IMimeType *im = m_liteApp->mimeTypeManager()->findMimeType(mime); if (im) { tabToSpace = im->tabToSpace(); tabWidth = im->tabWidth(); } tabToSpace = m_liteApp->settings()->value(MIMETYPE_TABTOSPACE+mime,tabToSpace).toBool(); tabWidth = m_liteApp->settings()->value(MIMETYPE_TABWIDTH+mime,tabWidth).toInt(); QStandardItem *tab = new QStandardItem(QString("%1").arg(tabWidth)); QStandardItem *useSpace = new QStandardItem(); useSpace->setCheckable(true); useSpace->setCheckState(tabToSpace?Qt::Checked:Qt::Unchecked); useSpace->setEditable(false); QStandardItem *ext = new QStandardItem; ext->setEditable(false); if (im) { ext->setText(im->globPatterns().join(";")); } QString custom = m_liteApp->settings()->value(EDITOR_CUSTOMEXTENSION+mime,"").toString(); QStandardItem *cus = new QStandardItem(custom); m_mimeModel->appendRow(QList<QStandardItem*>() << item << tab << useSpace << cus << ext); } } } LiteEditorOption::~LiteEditorOption() { delete m_widget; delete ui; } void LiteEditorOption::updatePointSizes() { // Update point sizes const int oldSize = m_fontSize; if (ui->sizeComboBox->count()) { //const QString curSize = ui->sizeComboBox->currentText(); 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> LiteEditorOption::pointSizesForSelectedFont() const { static QFontDatabase db; const QString familyName = ui->fontComboBox->currentFont().family(); 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; } void LiteEditorOption::editStyleFile() { QString fileName = ui->styleComboBox->currentText(); if (fileName.isEmpty()) { return; } QString filePath = m_liteApp->resourcePath()+"/liteeditor/color/"+fileName; m_liteApp->fileManager()->openEditor(filePath); } void LiteEditorOption::mimeItemChanged(QStandardItem *item) { if (item->column() == 1) { bool ok; int n = item->text().toInt(&ok); if (!ok || n <= 0 || n >= 20) { item->setText("4"); } } } void LiteEditorOption::restoreDefaultFont() { m_fontFamily = defaultFontFamily(); ui->fontComboBox->setCurrentFont(QFont(m_fontFamily)); m_fontSize = 12; ui->fontZoomSpinBox->setValue(100); ui->antialiasCheckBox->setChecked(true); updatePointSizes(); } void LiteEditorOption::filterMonospaceFont(bool b) { ui->fontComboBox->setFontFilters(b ?QFontComboBox::MonospacedFonts : QFontComboBox::AllFonts); ui->fontComboBox->updateGeometry(); }
18,768
C++
.cpp
380
42.471053
114
0.685375
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,497
liteeditoroptionfactory.cpp
visualfc_liteide/liteidex/src/plugins/liteeditor/liteeditoroptionfactory.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: liteeditoroptionfactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "liteeditoroptionfactory.h" #include "liteeditoroption.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 LiteEditorOptionFactory::LiteEditorOptionFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IOptionFactory(parent), m_liteApp(app) { } QStringList LiteEditorOptionFactory::mimeTypes() const { return QStringList() << "option/liteeditor"; } LiteApi::IOption *LiteEditorOptionFactory::create(const QString &mimeType) { if (mimeType == "option/liteeditor") { return new LiteEditorOption(m_liteApp,this); } return 0; }
1,910
C++
.cpp
49
36.673469
93
0.689116
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,498
profileprojectplugin.cpp
visualfc_liteide/liteidex/src/plugins/profileproject/profileprojectplugin.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: profileprojectplugin.cpp // Creator: visualfc <visualfc@gmail.com> #include "profileprojectplugin.h" #include "profilefilefactory.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 ProfileProjectPlugin::ProfileProjectPlugin() { m_info->setId("plugin/profileproject"); m_info->setName("ProfileProject"); m_info->setAuthor("visualfc"); m_info->setVer("x2"); m_info->setInfo("Project Profile Plugin"); } bool ProfileProjectPlugin::initWithApp(LiteApi::IApplication *app) { if (!LiteApi::IPlugin::initWithApp(app)) { return false; } ProfileFileFactory *factory = new ProfileFileFactory(app,this); app->projectManager()->addFactory(factory); return true; } Q_EXPORT_PLUGIN(ProfileProjectPlugin)
2,003
C++
.cpp
51
36.72549
82
0.684995
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,499
profileproject.cpp
visualfc_liteide/liteidex/src/plugins/profileproject/profileproject.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: profileproject.cpp // Creator: visualfc <visualfc@gmail.com> #include "profileproject.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 ProfileProject::ProfileProject(LiteApi::IApplication *app) : ModelProjectImpl(app) { }
1,490
C++
.cpp
36
39.5
82
0.670572
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,500
profilefilefactory.cpp
visualfc_liteide/liteidex/src/plugins/profileproject/profilefilefactory.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: profilefilefactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "profilefilefactory.h" #include "profilefile.h" #include "profileproject.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 ProfileFileFactory::ProfileFileFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IProjectFactory(parent), m_liteApp(app) { m_mimeTypes.append("text/x-profile"); m_mimeTypes.append("text/x-gopro"); } QStringList ProfileFileFactory::mimeTypes() const { return m_mimeTypes; } LiteApi::IProject *ProfileFileFactory::open(const QString &fileName, const QString &mimeType) { if (!m_mimeTypes.contains(mimeType)) { return 0; } ProfileProject *project = new ProfileProject(m_liteApp); project->setModelFile(new ProfileFile(m_liteApp,project)); if (!project->open(fileName,mimeType)) { delete project; return 0; } return project; } bool ProfileFileFactory::findTargetInfo(const QString &fileName, const QString &mimeType, QMap<QString,QString>& targetInfo) const { if (!m_mimeTypes.contains(mimeType)) { return false; } ProfileFile *file = new ProfileFile(m_liteApp,0); bool b = file->open(fileName,mimeType); if (b) { targetInfo = file->targetInfo(); } delete file; return b; }
2,569
C++
.cpp
71
33.028169
130
0.683387
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,501
profilefile.cpp
visualfc_liteide/liteidex/src/plugins/profileproject/profilefile.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: profilefile.cpp // Creator: visualfc <visualfc@gmail.com> #include "profilefile.h" #include <QStandardItem> #include <QFileInfo> #include <QFile> #include <QDir> #include <QDebug> #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 ProfileFile::ProfileFile(LiteApi::IApplication *app, QObject *parent) : ModelFileImpl(app,parent) { } bool ProfileFile::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-gopro"; } return true; } void ProfileFile::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 ProfileFile::target() const { QString target = QFileInfo(m_fileName).fileName(); QString val = value("TARG"); if (!val.isEmpty()) { target = val; } val = value("TARGET"); if (!val.isEmpty()) { target = val; } QString dest = value("DESTDIR"); if (!dest.isEmpty()) { target = QFileInfo(QDir(dest),target).filePath(); } return target; } QString ProfileFile::targetPath() const { QString target = QFileInfo(m_fileName).fileName(); QString val = value("TARG"); if (!val.isEmpty()) { target = val; } val = value("TARGET"); if (!val.isEmpty()) { target = val; } QString dest = value("DESTDIR"); if (!dest.isEmpty()) { target = QFileInfo(QDir(dest),target).filePath(); } QString workPath = QFileInfo(m_fileName).absolutePath(); if (!workPath.isEmpty()) { target = QFileInfo(QDir(workPath),target).filePath(); } return target; } QMap<QString,QString> ProfileFile::targetInfo() const { QMap<QString,QString> m; if (m_fileName.isEmpty()) { return m; } QFileInfo info(m_fileName); QString target = info.fileName(); QString val = value("TARG"); if (!val.isEmpty()) { target = val; } val = value("TARGET"); if (!val.isEmpty()) { target = val; } QString dest = value("DESTDIR"); if (!dest.isEmpty()) { target = QFileInfo(QDir(dest),target).filePath(); } 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; }
5,181
C++
.cpp
159
27.509434
82
0.631411
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,503
hellooptionfactory.cpp
visualfc_liteide/liteidex/src/tools/template/hello_option/hellooptionfactory.cpp
#include "hellooption.h" #include "hellooptionfactory.h" HelloOptionFactory::HelloOptionFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IOptionFactory(parent), m_liteApp(app) { } QStringList HelloOptionFactory::mimeTypes() const { return QStringList() << OPTION_HELLO; } LiteApi::IOption *HelloOptionFactory::create(const QString &mimeType) { if (mimeType == OPTION_HELLO) { return new HelloOption(m_liteApp,this); } return 0; }
482
C++
.cpp
18
23.722222
83
0.744035
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,504
hellooption.cpp
visualfc_liteide/liteidex/src/tools/template/hello_option/hellooption.cpp
#include "hellooption.h" #include "ui_hellooption.h" #include "hello_global.h" HelloOption::HelloOption(LiteApi::IApplication *app,QObject *parent) : LiteApi::IOption(parent), m_liteApp(app), m_widget(new QWidget), ui(new Ui::HelloOption) { ui->setupUi(m_widget); } HelloOption::~HelloOption() { delete m_widget; delete ui; } QWidget *HelloOption::widget() { return m_widget; } QString HelloOption::name() const { return "Hello"; } QString HelloOption::mimeType() const { return OPTION_HELLO; } void HelloOption::apply() { }
570
C++
.cpp
31
15.935484
70
0.719101
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,505
helloplugin.cpp
visualfc_liteide/liteidex/src/tools/template/hello_plugin/helloplugin.cpp
#include "helloplugin.h" #include <QtPlugin> HelloPlugin::HelloPlugin() { } bool HelloPlugin::load(LiteApi::IApplication *app) { return true; } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(PluginFactory,PluginFactory) #endif
230
C++
.cpp
12
17.583333
50
0.795349
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,506
textoutput.cpp
visualfc_liteide/liteidex/src/utils/textoutput/textoutput.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: textoutput.cpp // Creator: visualfc <visualfc@gmail.com> #include "textoutput.h" #include "colorstyle/colorstyle.h" #include "../liteapp/liteapp_global.h" #include <QTextCharFormat> #include <QMouseEvent> #include <QKeyEvent> #include <QTextCursor> #include <QTextBlock> #include <QElapsedTimer> #include <QTime> //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 fadeText(QTextCursor& cur) { QTextCharFormat f(cur.charFormat()); QColor color(f.foreground().color()); color.setAlpha(160); f.setForeground(color); cur.setCharFormat(f); } TextOutput::TextOutput(LiteApi::IApplication *app, bool readOnly, QWidget *parent) : TerminalEdit(parent), m_liteApp(app) { this->setReadOnly(readOnly); m_fmt = this->currentCharFormat(); m_defPalette = this->palette(); m_clrText = m_defPalette.foreground().color(); m_clrTag = Qt::darkBlue; m_clrError = Qt::red; m_existsTimer.start(); connect(m_liteApp->editorManager(),SIGNAL(colorStyleSchemeChanged()),this,SLOT(loadColorStyleScheme())); connect(m_liteApp->optionManager(),SIGNAL(applyOption(QString)),this,SLOT(applyOption(QString))); this->applyOption(OPTION_LITEOUTPUT); } void TextOutput::append(const QString &text) { append(text, m_clrText); } void TextOutput::append(const QString &text,const QBrush &foreground) { QTextCharFormat f = m_fmt; f.setForeground(foreground); appendAndReset(text, f); } void TextOutput::appendTag(const QString &text, bool error, bool time) { QTextCharFormat f = m_fmt; f.setFontWeight(QFont::Bold); if (error) { f.setForeground(m_clrError); } else { f.setForeground(m_clrTag); } if (time) { appendAndReset(QTime::currentTime().toString("hh:mm:ss: ")+text, f); } else { appendAndReset(text, f); } } void TextOutput::appendAndReset(const QString &text, QTextCharFormat& f) { TerminalEdit::append(text, &f); m_existsTimer.restart(); } void TextOutput::updateExistsTextColor(bool force) { if (!m_existsTimer.hasExpired(2500) && !force) return; QTextDocument* doc = document(); for (QTextBlock it = doc->begin(); it != doc->end(); it = it.next()) { QTextCursor cur(it); cur.select(QTextCursor::BlockUnderCursor); fadeText(cur); } } void TextOutput::setMaxLine(int max) { this->setMaximumBlockCount(max);; } void TextOutput::setLineWrap(bool b) { this->setLineWrapMode(b ? QPlainTextEdit::WidgetWidth : QPlainTextEdit::NoWrap); } bool TextOutput::isLineWrap() const { return this->lineWrapMode() != QPlainTextEdit::NoWrap; } void TextOutput::loadColorStyleScheme() { bool useColorShceme = m_liteApp->settings()->value(OUTPUT_USECOLORSCHEME,true).toBool(); const ColorStyleScheme *colorScheme = m_liteApp->editorManager()->colorStyleScheme(); const ColorStyle *text = colorScheme->findStyle("Text"); const ColorStyle *selection = colorScheme->findStyle("Selection"); const ColorStyle *keyword = colorScheme->findStyle("Keyword"); const ColorStyle *error = colorScheme->findStyle("Error"); QPalette p = this->m_defPalette; if (useColorShceme && text) { if (text->foregound().isValid()) { p.setColor(QPalette::Text,text->foregound()); p.setColor(QPalette::Foreground, text->foregound()); } if (text->background().isValid()) { p.setColor(QPalette::Base, text->background()); } } if (useColorShceme && selection) { if (selection->foregound().isValid()) { p.setColor(QPalette::HighlightedText, selection->foregound()); } if (selection->background().isValid()) { p.setColor(QPalette::Highlight, selection->background()); } p.setBrush(QPalette::Inactive, QPalette::Highlight, p.highlight()); p.setBrush(QPalette::Inactive, QPalette::HighlightedText, p.highlightedText()); } QString sheet = QString("QPlainTextEdit{color:%1;background-color:%2;selection-color:%3;selection-background-color:%4;}") .arg(p.text().color().name()) .arg(p.base().color().name()) .arg(p.highlightedText().color().name()) .arg(p.highlight().color().name()); this->setPalette(p); this->setStyleSheet(sheet); m_clrText = p.text().color(); m_fmt.setForeground(p.text().color()); m_fmt.setBackground(p.base().color()); if (useColorShceme && keyword && keyword->foregound().isValid()) { m_clrTag = keyword->foregound(); } else { m_clrTag = Qt::darkBlue; } if (useColorShceme && error && error->foregound().isValid()) { m_clrError = error->foregound(); } else { m_clrError = Qt::red; } QTextCursor cur(document()); cur.select(QTextCursor::Document); cur.setCharFormat(m_fmt); fadeText(cur); } void TextOutput::applyOption(QString opt) { if (opt != OPTION_LITEOUTPUT) { return; } QString fontFamily = m_liteApp->settings()->value(OUTPUT_FAMILY).toString(); int fontSize = m_liteApp->settings()->value(OUTPUT_FONTSIZE,12).toInt(); int fontZoom = m_liteApp->settings()->value(OUTPUT_FONTZOOM,100).toInt(); bool antialias = m_liteApp->settings()->value(OUTPUT_ANTIALIAS,true).toBool(); int maxLines = m_liteApp->settings()->value(OUTPUT_MAXLINES,5000).toInt(); QFont font = this->font(); if (!fontFamily.isEmpty()) { font.setFamily(fontFamily); } font.setPointSize(fontSize*fontZoom/100.0); if (antialias) { font.setStyleStrategy(QFont::PreferAntialias); } else { font.setStyleStrategy(QFont::NoAntialias); } this->setFont(font); this->setMaxLine(maxLines); this->loadColorStyleScheme(); }
7,301
C++
.cpp
193
31.958549
126
0.64973
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,507
terminaledit.cpp
visualfc_liteide/liteidex/src/utils/textoutput/terminaledit.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: terminaledit.cpp // Creator: visualfc <visualfc@gmail.com> #include "terminaledit.h" #include <QTextCursor> #include <QLineEdit> #include <QKeyEvent> #include <QMouseEvent> #include <QTextBlock> #include <QTextCharFormat> #include <QMenu> #include <QAction> #include <QClipboard> #include <QApplication> #include <QMimeData> #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 TerminalEdit::TerminalEdit(QWidget *parent) : QPlainTextEdit(parent) { this->setCursorWidth(4); this->setAcceptDrops(false); //this->setWordWrapMode(QTextOption::NoWrap); m_contextMenu = new QMenu(this); m_contextRoMenu = new QMenu(this); m_bAutoPosCursor = true; m_bFilterTermColor = false; m_bTerminalInput = false; m_lastInputPostion = 0; m_lastPosition = 0; m_lastKey = -1; this->setContextMenuPolicy(Qt::CustomContextMenu); m_cut = new QAction(tr("Cut"),this); m_cut->setShortcut(QKeySequence::Cut); m_cut->setShortcutContext(Qt::WidgetShortcut); m_copy = new QAction(tr("Copy"),this); m_copy->setShortcut(QKeySequence::Copy); m_copy->setShortcutContext(Qt::WidgetShortcut); m_paste = new QAction(tr("Paste"),this); m_paste->setShortcut(QKeySequence::Paste); m_paste->setShortcutContext(Qt::WidgetShortcut); m_selectAll = new QAction(tr("Select All"),this); m_selectAll->setShortcut(QKeySequence::SelectAll); m_selectAll->setShortcutContext(Qt::WidgetShortcut); m_clear = new QAction(tr("Clear All"),this); m_contextMenu->addAction(m_cut); m_contextMenu->addAction(m_copy); m_contextMenu->addAction(m_paste); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_selectAll); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_clear); m_contextRoMenu->addAction(m_copy); m_contextRoMenu->addSeparator(); m_contextRoMenu->addAction(m_selectAll); m_contextRoMenu->addSeparator(); m_contextRoMenu->addAction(m_clear); connect(this,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(contextMenuRequested(QPoint))); connect(this,SIGNAL(cursorPositionChanged()),this,SLOT(cursorPositionChanged())); connect(this,SIGNAL(selectionChanged()),this,SLOT(cursorPositionChanged())); connect(m_cut,SIGNAL(triggered()),this,SLOT(cut())); connect(m_copy,SIGNAL(triggered()),this,SLOT(copy())); connect(m_paste,SIGNAL(triggered()),this,SLOT(paste())); connect(m_selectAll,SIGNAL(triggered()),this,SLOT(selectAll())); connect(m_clear,SIGNAL(triggered()),this,SLOT(clear())); } void TerminalEdit::setFilterTermColor(bool filter) { m_bFilterTermColor = filter; } void TerminalEdit::setTerminalInput(bool term) { m_bTerminalInput = term; } void TerminalEdit::append(const QString &text, QTextCharFormat *fmt) { QString str = text; if (m_bFilterTermColor) { static QRegExp rx("\033\\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]"); str.remove(rx); } if (str.isEmpty()) { return; } setUndoRedoEnabled(false); QTextCursor cur = this->textCursor(); cur.movePosition(QTextCursor::End); if (m_bTerminalInput && m_lastKey != -1) { cur.setPosition(m_lastInputPostion,QTextCursor::KeepAnchor); } if (fmt) { cur.setCharFormat(*fmt); } cur.insertText(str); this->setTextCursor(cur); setUndoRedoEnabled(true); m_lastPosition = this->textCursor().position(); if (str.contains("\n") || m_lastKey == -1) { m_lastInputPostion = m_lastPosition; } m_lastKey = -1; } void TerminalEdit::clear() { m_lastPosition = 0; m_lastInputPostion = 0; m_lastKey = -1; QPlainTextEdit::clear(); } void TerminalEdit::keyPressEvent(QKeyEvent *ke) { QTextCursor cur = this->textCursor(); int pos = cur.position(); int end = cur.position(); if (cur.hasSelection()) { pos = cur.selectionStart(); end = cur.selectionEnd(); } bool bReadOnly = pos < m_lastInputPostion; if (bReadOnly && ( ke == QKeySequence::Paste || ke == QKeySequence::Cut || ke == QKeySequence::DeleteEndOfWord || ke == QKeySequence::DeleteStartOfWord)) { return; } if (ke == QKeySequence::DeleteStartOfWord) { if (!cur.hasSelection()) { cur.movePosition(QTextCursor::PreviousWord, QTextCursor::KeepAnchor); if (cur.selectionStart() < m_lastPosition) { cur.movePosition(QTextCursor::Right,QTextCursor::KeepAnchor,m_lastPosition-cur.selectionStart()); } } cur.removeSelectedText(); return; } m_lastKey = ke->key(); if (ke->modifiers() == Qt::NoModifier || ke->modifiers() == Qt::ShiftModifier || ke->modifiers() == Qt::KeypadModifier) { if (ke->key() < Qt::Key_Escape) { if (bReadOnly) { return; } } else { if (ke->key() == Qt::Key_Backspace) { if (cur.hasSelection()) { if (bReadOnly) { return; } } else if (pos <= m_lastInputPostion) { return; } } else if (bReadOnly && ( ke->key() == Qt::Key_Delete || ke->key() == Qt::Key_Tab || ke->key() == Qt::Key_Backtab || ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter)) { return; } if (ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter) { cur.setPosition(end,QTextCursor::MoveAnchor); cur.setPosition(m_lastPosition,QTextCursor::KeepAnchor); #ifdef Q_OS_WIN emit enterText(cur.selectedText()+"\r\n"); #else emit enterText(cur.selectedText()+"\n"); #endif QPlainTextEdit::keyPressEvent(ke); QTextCursor cur = this->textCursor(); cur.movePosition(QTextCursor::End); return; } else if (ke->key() == Qt::Key_Tab){ cur.setPosition(end,QTextCursor::MoveAnchor); cur.setPosition(m_lastPosition,QTextCursor::KeepAnchor); emit tabText(cur.selectedText()+"\t"); return; } else if (ke->key() == Qt::Key_Up || ke->key() == Qt::Key_Down) { emit keyUpdown(ke->key()); return; } } } QPlainTextEdit::keyPressEvent(ke); } void TerminalEdit::mouseDoubleClickEvent(QMouseEvent *e) { QPlainTextEdit::mouseDoubleClickEvent(e); QTextCursor cur = cursorForPosition(e->pos()); emit dbclickEvent(cur); } void TerminalEdit::mousePressEvent(QMouseEvent *e) { QPlainTextEdit::mousePressEvent(e); if (!m_bAutoPosCursor) { return; } if (!this->isReadOnly() && m_bFocusOut) { m_bFocusOut = false; QTextCursor cur = this->textCursor(); if (!cur.hasSelection()) { cur.movePosition(QTextCursor::End); this->setTextCursor(cur); } } } void TerminalEdit::focusOutEvent(QFocusEvent *e) { QPlainTextEdit::focusOutEvent(e); m_bFocusOut = true; } void TerminalEdit::focusInEvent(QFocusEvent *e) { QPlainTextEdit::focusInEvent(e); if (!this->isReadOnly()) { QTextCursor cur = this->textCursor(); if (!cur.hasSelection()) { cur.movePosition(QTextCursor::End); this->setTextCursor(cur); } } } void TerminalEdit::contextMenuRequested(const QPoint &pt) { QPoint globalPos = this->mapToGlobal(pt); if (isReadOnly()) { m_contextRoMenu->popup(globalPos); } else { m_contextMenu->popup(globalPos); } } void TerminalEdit::cursorPositionChanged() { QTextCursor cur = this->textCursor(); int pos = cur.position(); if (cur.hasSelection()) { pos = cur.selectionStart(); m_copy->setEnabled(true); if (pos < m_lastPosition) { m_cut->setEnabled(false); } else { m_cut->setEnabled(!this->isReadOnly()); } } else { m_copy->setEnabled(false); m_cut->setEnabled(false); } if (pos < m_lastPosition) { m_paste->setEnabled(false); } else { QClipboard *clipboard = QApplication::clipboard(); if (clipboard->mimeData()->hasText() || clipboard->mimeData()->hasHtml()){ m_paste->setEnabled(true); } else { m_paste->setEnabled(false); } } }
10,271
C++
.cpp
286
27.91958
114
0.593652
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,508
symboltreeview.cpp
visualfc_liteide/liteidex/src/utils/symboltreeview/symboltreeview.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: symboltreeview.cpp // Creator: visualfc <visualfc@gmail.com> #include "symboltreeview.h" #include <QHeaderView> #include <QFocusEvent> #include <QScrollBar> #include <QAbstractItemModel> //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 QStringList stringListFromIndex(const QModelIndex &index) { QStringList list; if (!index.isValid()) return list; list.append(stringListFromIndex(index.parent())); list.append(index.data().toString()); return list; } static QModelIndex indexFromStringList(QAbstractItemModel *model, QStringList &list, const QModelIndex & parent = QModelIndex()) { if (list.isEmpty()) return QModelIndex(); QString text = list.front(); for (int i = 0; i < model->rowCount(parent); i++) { QModelIndex child = model->index(i,0,parent); if (child.data().toString() == text) { list.pop_front(); if (list.isEmpty()) { return child; } else { QModelIndex next = indexFromStringList(model,list,child); if (next.isValid()) return next; else return child; } } } return QModelIndex(); } SymbolTreeView::SymbolTreeView(QWidget *parent) : QTreeView(parent) { init(true); } SymbolTreeView::SymbolTreeView(bool bResizeToContents, QWidget *parent) : QTreeView(parent) { init(bResizeToContents); } void SymbolTreeView::init(bool bResizeToContents) { m_bClickedItem = false; m_hsbPos = 0; setEditTriggers(QAbstractItemView::NoEditTriggers); // setFrameStyle(QFrame::NoFrame); setIndentation(indentation() * 9/10); { this->setHeaderHidden(true); if (bResizeToContents) { #if QT_VERSION >= 0x050000 this->header()->setSectionResizeMode(QHeaderView::ResizeToContents); #else this->header()->setResizeMode(QHeaderView::ResizeToContents); #endif this->header()->setStretchLastSection(false); } this->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); } setContextMenuPolicy(Qt::CustomContextMenu); setUniformRowHeights(true); setTextElideMode(Qt::ElideNone); // setExpandsOnDoubleClick(false); setAttribute(Qt::WA_MacShowFocusRect, false); connect(this,SIGNAL(clicked(QModelIndex)),this,SLOT(clickedItem(QModelIndex))); connect(this->horizontalScrollBar(),SIGNAL(valueChanged(int)),this,SLOT(hsbValueChanged(int))); } void SymbolTreeView::focusInEvent(QFocusEvent *event) { if (event->reason() != Qt::PopupFocusReason) QTreeView::focusInEvent(event); } void SymbolTreeView::focusOutEvent(QFocusEvent *event) { if (event->reason() != Qt::PopupFocusReason) QTreeView::focusOutEvent(event); } QModelIndex SymbolTreeView::topViewIndex() { return indexAt(QPoint(1,1)); } void SymbolTreeView::reset() { QTreeView::reset(); //setRootIndex(model()->index(0,0)); //this->setRootIndex(QModelIndex()); } void SymbolTreeView::getTreeExpands(const QModelIndex &parent, QList<QModelIndex> &list) const { for (int i = 0; i < this->model()->rowCount(parent); i++) { QModelIndex index = this->model()->index(i,0,parent); if (this->isExpanded(index)) { list.append(index); getTreeExpands(index,list); } } } void SymbolTreeView::clickedItem(QModelIndex) { this->m_bClickedItem = true; this->m_hsbPos = this->horizontalScrollBar()->sliderPosition(); } void SymbolTreeView::hsbValueChanged(int) { if (this->m_bClickedItem) { this->m_bClickedItem = false; this->horizontalScrollBar()->setValue(this->m_hsbPos); } } QList<QModelIndex> SymbolTreeView::expandIndexs() const { QList<QModelIndex> expands; getTreeExpands(QModelIndex(),expands); return expands; } void SymbolTreeView::currentChanged(const QModelIndex &current, const QModelIndex &previous) { QTreeView::currentChanged(current,previous); emit currentIndexChanged(current, previous); } void SymbolTreeView::saveState(SymbolTreeState *state) { if (!state) { return; } state->expands.clear(); foreach (QModelIndex index, this->expandIndexs()) { state->expands.append(stringListFromIndex(index)); } state->cur = stringListFromIndex(this->currentIndex()); state->vbar = verticalScrollBar()->value(); state->hbar = horizontalScrollBar()->value(); } void SymbolTreeView::loadState(QAbstractItemModel *model,SymbolTreeState *state) { //load state //this->expandToDepth(0) QListIterator<QStringList> ie(state->expands); while (ie.hasNext()) { QStringList expandPath = ie.next(); QModelIndex expandIndex = indexFromStringList(model,expandPath); if (expandIndex.isValid()) { this->setExpanded(expandIndex,true); } } QModelIndex curIndex = indexFromStringList(model,state->cur); if (curIndex.isValid()) { this->setCurrentIndex(curIndex); } if (state->vbar != -1) { verticalScrollBar()->setValue(state->vbar); } if (state->hbar != -1) { horizontalScrollBar()->setValue(state->hbar); } } void SymbolTreeView::keyPressEvent(QKeyEvent *event) { // Note: This always eats the event // whereas QAbstractItemView never eats it if ((event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) && event->modifiers() == 0 && QTreeView::currentIndex().isValid() && QTreeView::state() != QAbstractItemView::EditingState) { emit QTreeView::activated(QTreeView::currentIndex()); emit enterKeyPressed(QTreeView::currentIndex()); return; } QTreeView::keyPressEvent(event); }
7,053
C++
.cpp
208
28.971154
128
0.670918
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,509
multifolderview.cpp
visualfc_liteide/liteidex/src/utils/folderview/multifolderview.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: multifolderview.cpp // Creator: visualfc <visualfc@gmail.com> #include "multifolderview.h" #include <QMessageBox> #include <QHeaderView> #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 MultiFolderView::MultiFolderView(LiteApi::IApplication *app, QWidget *parent) : BaseFolderView(app,parent) { m_model = new MultiFolderModel(this); #ifdef Q_OS_MAC m_model->sort(0); m_model->setSorting(QDir::DirsFirst|QDir::Name|QDir::IgnoreCase); #endif this->setModel(m_model); this->setHeaderHidden(true); m_contextMenu = new QMenu(this); this->setSelectionMode(QAbstractItemView::ExtendedSelection); setContextMenuPolicy(Qt::CustomContextMenu); connect(this,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(customContextMenuRequested(QPoint))); connect(m_model,SIGNAL(directoryLoaded(QFileSystemModel*,QString)),this,SLOT(directoryLoaded(QFileSystemModel*,QString))); } MultiFolderView::~MultiFolderView() { } void MultiFolderView::setFilter(QDir::Filters filters) { m_model->setFilter(filters); } QDir::Filters MultiFolderView::filter() const { return m_model->filter(); } void MultiFolderView::setNameFilters(const QStringList &filters) { m_model->setNameFilters(filters); } QStringList MultiFolderView::nameFilters() const { return m_model->nameFilters(); } QFileInfo MultiFolderView::fileInfo(const QModelIndex &index) const { return m_model->fileInfo(index); } QString MultiFolderView::fileRootPath(const QModelIndex &index) const { return m_model->fileRootPath(index); } bool MultiFolderView::addRootPath(const QString &path) { if (m_model->isRootPath(path)) { return true; } QModelIndex index = m_model->addRootPath(path); return index.isValid(); } void MultiFolderView::setRootPathList(const QStringList &pathList) { m_model->clearAll(); foreach (QString path, pathList) { m_model->addRootPath(path); } } QStringList MultiFolderView::rootPathList() const { return m_model->rootPathList(); } void MultiFolderView::clear() { m_model->clearAll(); } void MultiFolderView::expandFolder(const QString &path, bool expand) { QList<QModelIndex> indexList = m_model->indexForPath(path); foreach (QModelIndex sourceIndex, indexList) { QModelIndex index = sourceIndex; if (expand) { this->expand(index); } else { this->collapse(index); } } } QList<QModelIndex> MultiFolderView::indexForPath(const QString &path) const { return m_model->indexForPath(path); } void MultiFolderView::setShowDetails(bool b) { m_model->setShowDetails(b); } bool MultiFolderView::isShowDetails() const { return m_model->isShowDetails(); } QModelIndex MultiFolderView::findIndexForContext(const QString &filePath) const { if (!m_contextIndex.isValid()) { return QModelIndex(); } QModelIndex si = m_model->mapToSource(m_contextIndex); QModelIndexList list = this->indexForPath(filePath); foreach (QModelIndex index, list) { if (m_model->mapToSource(index).model() == si.model()) { return index; } } return QModelIndex(); } void MultiFolderView::removeIndex(const QModelIndex &index) { m_model->remove(index); } void MultiFolderView::customContextMenuRequested(const QPoint &pos) { m_contextMenu->clear(); LiteApi::FILESYSTEM_CONTEXT_FLAG flag = LiteApi::FILESYSTEM_ROOT; QModelIndex index = this->indexAt(pos); if (index.isValid()) { m_contextIndex = index; QModelIndex sourceIndex = index; m_contextInfo = m_model->fileInfo(sourceIndex); if (m_model->isRootIndex(sourceIndex)) { flag = LiteApi::FILESYSTEM_ROOTFOLDER; } else if (m_model->isDir(sourceIndex)) { flag = LiteApi::FILESYSTEM_FOLDER; } else { flag = LiteApi::FILESYSTEM_FILES; } } else { m_contextIndex = this->rootIndex(); m_contextInfo = QFileInfo(); } //root folder if (flag == LiteApi::FILESYSTEM_ROOT) { m_contextMenu->addAction(m_openFolderAct); } else if (flag == LiteApi::FILESYSTEM_ROOTFOLDER) { #ifdef Q_OS_MAC if (m_contextInfo.isBundle()) { m_contextMenu->addAction(m_openBundleAct); m_contextMenu->addSeparator(); } #endif m_contextMenu->addAction(m_openInNewWindowAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_newFileAct); m_contextMenu->addAction(m_newFileWizardAct); m_contextMenu->addAction(m_newFolderAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_reloadFolderAct); m_contextMenu->addAction(m_closeFolderAct); m_contextMenu->addSeparator(); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_copyFileAct); m_contextMenu->addAction(m_pasteFileAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_copyFullPathToClipboardAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_openExplorerAct); m_contextMenu->addAction(m_openShellAct); m_contextMenu->addAction(m_openTerminalAct); } else if (flag == LiteApi::FILESYSTEM_FOLDER) { #ifdef Q_OS_MAC if (m_contextInfo.isBundle()) { m_contextMenu->addAction(m_openBundleAct); m_contextMenu->addSeparator(); } #endif m_contextMenu->addAction(m_openInNewWindowAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_newFileAct); m_contextMenu->addAction(m_newFileWizardAct); m_contextMenu->addAction(m_newFolderAct); m_contextMenu->addAction(m_renameFolderAct); if (this->canMoveToTrash()) { m_contextMenu->addAction(m_moveToTrashAct); } else { m_contextMenu->addAction(m_removeFolderAct); } m_contextMenu->addSeparator(); m_contextMenu->addAction(m_copyFileAct); m_contextMenu->addAction(m_pasteFileAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_copyFullPathToClipboardAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_openExplorerAct); m_contextMenu->addAction(m_openShellAct); m_contextMenu->addAction(m_openTerminalAct); } else if (flag == LiteApi::FILESYSTEM_FILES) { m_contextMenu->addAction(m_openEditorAct); m_contextMenu->addMenu(this->openWithMenu()); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_newFileAct); m_contextMenu->addAction(m_newFileWizardAct); m_contextMenu->addAction(m_newFolderAct); m_contextMenu->addAction(m_renameFileAct); if (this->canMoveToTrash()) { m_contextMenu->addAction(m_moveToTrashAct); } else { m_contextMenu->addAction(m_removeFileAct); } m_contextMenu->addSeparator(); m_contextMenu->addAction(m_copyFileAct); m_contextMenu->addAction(m_pasteFileAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_copyFullPathToClipboardAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_openExplorerAct); m_contextMenu->addAction(m_openShellAct); m_contextMenu->addAction(m_openTerminalAct); } m_pasteFileAct->setEnabled(this->canPasteFile()); bool check = this->selectionModel()->selectedRows(0).size() == 1; m_removeFileAct->setEnabled(check); m_removeFolderAct->setEnabled(check); m_renameFileAct->setEnabled(check); m_renameFolderAct->setEnabled(check); check = true; foreach (QModelIndex index, this->selectionCopyOrRemoveList()) { if (this->m_model->isRootIndex(index)) { check = false; break; } } this->m_moveToTrashAct->setEnabled(check && !this->selectionCopyOrRemoveList().isEmpty()); emit aboutToShowContextMenu(m_contextMenu,flag,m_contextInfo); m_contextMenu->exec(this->mapToGlobal(pos)); } void MultiFolderView::removeFolder() { QFileInfo info = m_contextInfo; 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?") +"\n"+info.filePath(), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::Yes) { QModelIndex index = this->currentIndex(); if (!m_model->remove(index)) { QMessageBox::information(m_liteApp->mainWindow(),tr("Delete Folder"), tr("Failed to delete the folder!")); } } } void MultiFolderView::removeFile() { QFileInfo info = m_contextInfo; 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?") +"\n"+info.filePath(), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::Yes) { QModelIndex index = this->currentIndex(); if (!m_model->remove(index)) { QMessageBox::information(m_liteApp->mainWindow(),tr("Delete File"), tr("Failed to delete the file!")); } } } void MultiFolderView::openFolder() { m_liteApp->fileManager()->openFolder(); } void MultiFolderView::closeFolder() { QModelIndex index = this->currentIndex(); m_model->removeRoot(index); } void MultiFolderView::reloadFolder() { m_model->reloadAll(); } void MultiFolderView::closeAllFolders() { m_model->clearAll(); } void MultiFolderView::directoryLoaded(QFileSystemModel *model, const QString &path) { QModelIndex index = m_model->indexForPath(model,path); if (!index.isValid()) { return; } } QModelIndexList MultiFolderView::selectionCopyOrRemoveList() const { QModelIndexList selection = this->selectionModel()->selectedRows(0); if (selection.size() <= 1) { return selection; } QStringList dirList; foreach (QModelIndex index, selection) { if (m_model->isDir(index)) { dirList << QDir::cleanPath(m_model->fileInfo(index).filePath()); } } QModelIndexList itemList; foreach (QModelIndex index, selection) { QString filePath = QDir::cleanPath(m_model->fileInfo(index).filePath()); QStringList chkList = dirList; chkList.removeAll(filePath); bool find = false; foreach (QString chk, chkList) { if (filePath.startsWith(chk+"/")) { find = true; break; } } if (!find) { itemList << index; } } return itemList; }
12,671
C++
.cpp
348
29.201149
127
0.643295
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,510
dirsortfilterproxymodel.cpp
visualfc_liteide/liteidex/src/utils/folderview/dirsortfilterproxymodel.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: dirsortfilterproxymodel.cpp // Creator: visualfc <visualfc@gmail.com> #include "dirsortfilterproxymodel.h" #include <QFileSystemModel> #include <QFileInfo> #include <QDirModel> #include <QDateTime> //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 /* For sorting */ struct QDirSortItem { mutable QString filename_cache; mutable QString suffix_cache; QFileInfo item; }; class QDirSortItemComparator { int qt_cmp_si_sort_flags; public: QDirSortItemComparator(int flags) : qt_cmp_si_sort_flags(flags) {} bool sort(const QDirSortItem &, const QDirSortItem &); }; bool QDirSortItemComparator::sort(const QDirSortItem &n1, const QDirSortItem &n2) { const QDirSortItem* f1 = &n1; const QDirSortItem* f2 = &n2; if ((qt_cmp_si_sort_flags & QDir::DirsFirst) && (f1->item.isDir() != f2->item.isDir())) return f1->item.isDir(); if ((qt_cmp_si_sort_flags & QDir::DirsLast) && (f1->item.isDir() != f2->item.isDir())) return !f1->item.isDir(); int r = 0; int sortBy = (qt_cmp_si_sort_flags & QDir::SortByMask) | (qt_cmp_si_sort_flags & QDir::Type); switch (sortBy) { case QDir::Time: r = f1->item.lastModified().secsTo(f2->item.lastModified()); break; case QDir::Size: r = int(qBound<qint64>(-1, f2->item.size() - f1->item.size(), 1)); break; case QDir::Type: { bool ic = qt_cmp_si_sort_flags & QDir::IgnoreCase; if (f1->suffix_cache.isNull()) f1->suffix_cache = ic ? f1->item.suffix().toLower() : f1->item.suffix(); if (f2->suffix_cache.isNull()) f2->suffix_cache = ic ? f2->item.suffix().toLower() : f2->item.suffix(); r = qt_cmp_si_sort_flags & QDir::LocaleAware ? f1->suffix_cache.localeAwareCompare(f2->suffix_cache) : f1->suffix_cache.compare(f2->suffix_cache); } break; default: ; } if (r == 0 && sortBy != QDir::Unsorted) { // Still not sorted - sort by name bool ic = qt_cmp_si_sort_flags & QDir::IgnoreCase; if (f1->filename_cache.isNull()) f1->filename_cache = ic ? f1->item.fileName().toLower() : f1->item.fileName(); if (f2->filename_cache.isNull()) f2->filename_cache = ic ? f2->item.fileName().toLower() : f2->item.fileName(); r = qt_cmp_si_sort_flags & QDir::LocaleAware ? f1->filename_cache.localeAwareCompare(f2->filename_cache) : f1->filename_cache.compare(f2->filename_cache); } if (r == 0) // Enforce an order - the order the items appear in the array r = (&n1) - (&n2); if (qt_cmp_si_sort_flags & QDir::Reversed) return r > 0; return r < 0; } DirSortFilterProxyModel::DirSortFilterProxyModel(QObject *parent) : QSortFilterProxyModel(parent), m_sorts(QDir::NoSort) { } void DirSortFilterProxyModel::setSorting(QDir::SortFlags sort) { m_sorts = sort; } QDir::SortFlags DirSortFilterProxyModel::sorting() const { return m_sorts; } bool DirSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { QFileSystemModel *model = dynamic_cast<QFileSystemModel*>(this->sourceModel()); if (!model) { return QSortFilterProxyModel::lessThan(left,right); } QDirSortItemComparator comp(m_sorts); QDirSortItem n1; QDirSortItem n2; n1.item = model->fileInfo(left); n2.item = model->fileInfo(right); return comp.sort(n1,n2); }
5,044
C++
.cpp
129
32.170543
96
0.610302
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,511
basefolderview.cpp
visualfc_liteide/liteidex/src/utils/folderview/basefolderview.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: basefolderview.cpp // Creator: visualfc <visualfc@gmail.com> #include "basefoldeview.h" #include "liteenvapi/liteenvapi.h" #include "terminalapi/terminalapi.h" #include "fileutil/fileutil.h" #include "folderdialog.h" #include <QTreeView> #include <QMenu> #include <QAction> #include <QMessageBox> #include <QProcess> #include <QInputDialog> #include <QLineEdit> #include <QUrl> #include <QToolBar> #include <QFileSystemWatcher> #include <QFileDialog> #include <QHeaderView> #include <QProcess> #include <QProcessEnvironment> #include <QDesktopServices> #include <QApplication> #include <QClipboard> #include <QMimeData> #include <QUrl> #include <QFile> #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 BaseFolderView::BaseFolderView(LiteApi::IApplication *app, QWidget *parent) : SymbolTreeView(parent), m_liteApp(app) { this->setHeaderHidden(true); #if QT_VERSION >= 0x050000 this->header()->setSectionResizeMode(QHeaderView::ResizeToContents); #else this->header()->setResizeMode(QHeaderView::ResizeToContents); #endif this->header()->setStretchLastSection(false); this->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); m_openBundleAct = new QAction(tr("Open Application"),this); m_openInNewWindowAct = new QAction(tr("Open In New Window"),this); m_openEditorAct = new QAction(tr("Open File"),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); #if defined(Q_OS_WIN) m_openExplorerAct = new QAction(tr("Show in Explorer"),this); #elif defined(Q_OS_MAC) m_openExplorerAct = new QAction(tr("Show in Finder"),this); #else m_openExplorerAct = new QAction(tr("Show Containing Folder"),this); #endif #ifdef Q_OS_WIN m_openShellAct = new QAction(tr("Open Command Prompt Here"),this); #else m_openShellAct = new QAction(tr("Open Terminal Here"),this); #endif m_openTerminalAct = new QAction(tr("Open in Integrated Terminal"),this); m_openFolderAct = new QAction(tr("Open Folder..."),this); m_reloadFolderAct = new QAction(tr("Reload Folder"),this); m_closeFolderAct = new QAction(tr("Close Folder"),this); m_closeAllFoldersAct = new QAction(tr("Close All Folders"),this); m_copyFileAct = new QAction(tr("Copy"),this); m_pasteFileAct = new QAction(tr("Paste"),this); m_copyFullPathToClipboardAct = new QAction(tr("Copy Path"),this); m_moveToTrashAct = new QAction(tr("Move To Trash"),this); connect(m_openBundleAct,SIGNAL(triggered()),this,SLOT(openBundle())); connect(m_openInNewWindowAct,SIGNAL(triggered()),this,SLOT(openInNewWindow())); 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_openTerminalAct,SIGNAL(triggered()),this,SLOT(openTerminal())); connect(m_openExplorerAct,SIGNAL(triggered()),this,SLOT(openExplorer())); connect(m_openFolderAct,SIGNAL(triggered()),this,SLOT(openFolder())); connect(m_closeFolderAct,SIGNAL(triggered()),this,SLOT(closeFolder())); connect(m_reloadFolderAct,SIGNAL(triggered()),this,SLOT(reloadFolder())); connect(m_closeAllFoldersAct,SIGNAL(triggered()),this,SLOT(closeAllFolders())); connect(m_copyFileAct,SIGNAL(triggered()),this,SLOT(copyFile())); connect(m_pasteFileAct,SIGNAL(triggered()),this,SLOT(pasteFile())); connect(m_copyFullPathToClipboardAct,SIGNAL(triggered()),this,SLOT(copyFullPathToClipboard())); connect(m_moveToTrashAct,SIGNAL(triggered()),this,SLOT(moveToTrash())); m_openWithMenu = 0; } QDir BaseFolderView::contextDir() const { if (m_contextInfo.isDir()) { return m_contextInfo.filePath(); } return m_contextInfo.dir(); } QFileInfo BaseFolderView::contextFileInfo() const { return m_contextInfo; } bool BaseFolderView::canMoveToTrash() const { return FileUtil::hasTrash(); } void BaseFolderView::openBundle() { if (m_contextInfo.isBundle()) { if (QFileInfo("/usr/bin/open").exists()) { QStringList args; args << m_contextInfo.filePath(); QProcess::execute(QLatin1String("/usr/bin/open"), args); } } } void BaseFolderView::openInNewWindow() { if (m_contextInfo.isDir()) { m_liteApp->fileManager()->openFolderInNewWindow(m_contextInfo.filePath()); } } void BaseFolderView::openEditor() { if (m_contextInfo.isFile()) { m_liteApp->fileManager()->openEditor(m_contextInfo.filePath()); } } void BaseFolderView::newFile() { QDir dir = contextDir(); CreateFileDialog dlg(m_liteApp->mainWindow()); 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 BaseFolderView::newFileWizard() { QString filePath; QString projPath; QFileInfo info = m_contextInfo; 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 BaseFolderView::renameFile() { QFileInfo info = m_contextInfo; 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(); #ifdef Q_OS_WIN if (!MoveFileW(info.filePath().toStdWString().c_str(),QFileInfo(dir,fileName).filePath().toStdWString().c_str())) { QMessageBox::information(m_liteApp->mainWindow(),tr("Rename File"), tr("Failed to rename the file!")); } #else if (!QFile::rename(info.filePath(),QFileInfo(dir,fileName).filePath())) { QMessageBox::information(m_liteApp->mainWindow(),tr("Rename File"), tr("Failed to rename the file!")); } #endif } } void BaseFolderView::removeFile() { // QFileInfo info = m_contextInfo; // 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?") // +"\n"+info.filePath(), // 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 BaseFolderView::newFolder() { QDir dir = contextDir(); CreateDirDialog dlg(m_liteApp->mainWindow()); dlg.setDirectory(dir.path()); if (dlg.exec() == QDialog::Rejected) { return; } QString folderName = dlg.getDirName(); 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 BaseFolderView::renameFolder() { QFileInfo info = m_contextInfo; 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(); #ifdef Q_OS_WIN QString _old = info.filePath(); QString _new = dir.path()+"/"+folderName; if (!MoveFileW(_old.toStdWString().c_str(),_new.toStdWString().c_str())) { QMessageBox::information(m_liteApp->mainWindow(),tr("Rename Folder"), tr("Failed to rename the folder!")); } #else if (!dir.rename(info.fileName(),folderName)) { QMessageBox::information(m_liteApp->mainWindow(),tr("Rename Folder"), tr("Failed to rename the folder!")); } #endif } } void BaseFolderView::removeFolder() { QFileInfo info = m_contextInfo; 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?") +"\n"+info.filePath(), 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 BaseFolderView::openExplorer() { FileUtil::openInExplorer(contextFileInfo().filePath()); } void BaseFolderView::openTerminal() { LiteApi::ITerminal *term = LiteApi::getTerminalManager(m_liteApp); if (term) { term->openDefaultTerminal(contextDir().path()); } } void BaseFolderView::openFolder() { } void BaseFolderView::closeFolder() { } void BaseFolderView::reloadFolder() { } void BaseFolderView::closeAllFolders() { } void BaseFolderView::copyFile() { QClipboard *clip = qApp->clipboard(); QMimeData *data = new QMimeData(); QList<QUrl> urls; QModelIndexList items = this->selectionCopyOrRemoveList(); if (!items.isEmpty()) { foreach (QModelIndex item, items) { urls << QUrl::fromLocalFile(this->fileInfo(item).filePath()); } } else { QFileInfo info = m_contextInfo; urls << QUrl::fromLocalFile(info.filePath()); } data->setUrls(urls); clip->setMimeData(data); } //static bool copy_dir(const QString &src, const QString &dest) //{ // QDir dir(src); // QDir destDir(dest); // foreach(QFileInfo info, dir.entryInfoList(QDir::Dirs|QDir::Files|QDir::NoDotAndDotDot)) { // if (info.isFile() && !info.isSymLink()) { // QFile::copy(info.filePath(), QFileInfo(destDir,info.fileName()).filePath()); // } else if (info.isDir()) { // destDir.mkdir(info.fileName()); // if (QFileInfo(destDir,info.fileName()).isDir()) { // copy_dir(info.filePath(),QFileInfo(destDir,info.fileName()).filePath()); // } // } // } // return true; //} bool BaseFolderView::copy_dir(const QString &src, const QString &dest_root, const QString &newName) { QDir dir(src); QDir destDir(dest_root); QString name = QFileInfo(src).fileName(); if (!newName.isEmpty()) { name = newName; } destDir.mkdir(name); if (!destDir.cd(name)) { m_liteApp->appendLog("FolderView",QString("copy dir %1 false!").arg(src),true); return false; } foreach(QFileInfo info, dir.entryInfoList(QDir::Dirs|QDir::Files|QDir::NoDotAndDotDot)) { if (info.isFile() && !info.isSymLink()) { bool b = QFile::copy(info.filePath(), QFileInfo(destDir,info.fileName()).filePath()); if (!b) { m_liteApp->appendLog("FolderView",QString("copy file %1=>%2 false!").arg(info.filePath()).arg(destDir.absolutePath()),true); } } else if (info.isDir()) { copy_dir(info.filePath(),destDir.absolutePath(),""); } } return true; } void BaseFolderView::pasteFile() { QClipboard *clip = qApp->clipboard(); const QMimeData *data = clip->mimeData(); if (!data) { return; } if (!data->hasUrls()) { return; } QDir dir = contextDir(); QString dstPath = QFileInfo(dir.absolutePath()).canonicalFilePath(); int allflag = 0; foreach (QUrl url, data->urls()) { if (!url.isLocalFile()) { continue; } QString fileName = url.toLocalFile(); QFileInfo orginfo(QDir::cleanPath(fileName)); if (!orginfo.exists()) { continue; } if(orginfo.isDir() && orginfo.canonicalPath() != dstPath) { QString chkPath = QDir::cleanPath(orginfo.canonicalFilePath()); if (chkPath == dstPath || dstPath.startsWith(chkPath+"/")) { m_liteApp->appendLog("FolderView",QString("You can't paste \"%1\" at this location because you can't paste an item into itselft.").arg(chkPath),true); continue; } if (QFileInfo(dir,orginfo.fileName()).exists()){ if (chkPath.startsWith(dstPath+"/"+orginfo.fileName()+"/")) { m_liteApp->appendLog("FolderView",QString("The folder \"%1\" can't be replaced by an item it contains.").arg(chkPath),true); continue; } } } QString dstName = orginfo.fileName(); QString dstFileName = orginfo.canonicalFilePath(); // check Duplicate if (orginfo.canonicalPath() == dstPath) { int num = 0; while (QFileInfo(dir,dstName).exists()) { dstName = orginfo.baseName()+" copy"; if (num > 0) { dstName += " "+QString::number(num); } if (!orginfo.completeSuffix().isEmpty()) { dstName += "."+orginfo.completeSuffix(); } num++; } //upadte filename dstFileName = QFileInfo(dir,dstName).filePath(); } // check over name int flag = 0; if (QFileInfo(dir,dstName).exists()) { if (allflag == 0) { QMessageBox msgbox; msgbox.setIcon(QMessageBox::Question); msgbox.setInformativeText(QString(tr("An item \"%1\" already exists in this location. Do you want to replace it and move old item to trash?")).arg(dstName)); QPushButton *stop = msgbox.addButton(tr("Stop"), QMessageBox::RejectRole); QPushButton *keepBoth = msgbox.addButton(tr("Keep Both"), QMessageBox::ActionRole); QPushButton *keepBothAll = msgbox.addButton(tr("Keep Both All"), QMessageBox::ActionRole); QPushButton *replace = msgbox.addButton(tr("Replace"), QMessageBox::ActionRole); QPushButton *replaceAll = msgbox.addButton(tr("Replace All"), QMessageBox::ActionRole); msgbox.setDefaultButton(stop); int ret = msgbox.exec(); //stop button if (ret == QMessageBox::Rejected) { break; } QPushButton *btn = (QPushButton*)msgbox.clickedButton(); if (btn == keepBoth) { flag = 1; } else if (btn == keepBothAll) { allflag = 1; flag = 1; } else if (btn == replace) { flag = 2; } else if (btn == replaceAll) { allflag = 2; flag = 2; } } else { flag = allflag; } } if (flag == 1) { int num = 0; while (QFileInfo(dir,dstName).exists()) { dstName = orginfo.baseName(); if (num > 0) { dstName += " "+QString::number(num); } if (!orginfo.completeSuffix().isEmpty()) { dstName += "."+orginfo.completeSuffix(); } num++; } //upadte filename dstFileName = QFileInfo(dir,dstName).filePath(); } else if (flag == 2) { FileUtil::moveToTrash(QFileInfo(dir,dstName).filePath()); } if (orginfo.isFile()) { bool b = QFile::copy(fileName,QFileInfo(dir,dstName).filePath()); if (!b) { m_liteApp->appendLog("FolderView",QString("cannot paste file %1").arg(fileName),true); } } else if(orginfo.isDir()) { copy_dir(orginfo.filePath(),dstPath,dstName); } qApp->processEvents(); } } bool BaseFolderView::canPasteFile() { QClipboard *clip = qApp->clipboard(); const QMimeData *data = clip->mimeData(); if (!data) { return false; } if (!data->hasUrls()) { return false; } foreach (QUrl url, data->urls()) { if (url.isLocalFile()) { return true; } } return false; } void BaseFolderView::copyFullPathToClipboard() { QModelIndexList indexs = this->selectionCopyOrRemoveList(); QStringList fileList; foreach (QModelIndex index, indexs) { QFileInfo info = this->fileInfo(index); fileList << info.filePath(); } if (fileList.isEmpty()) { return; } QClipboard *clip = qApp->clipboard(); clip->setText(fileList.join("\n")); } void BaseFolderView::moveToTrash() { QModelIndexList indexs = this->selectionCopyOrRemoveList(); QStringList fileList; foreach (QModelIndex index, indexs) { QFileInfo info = this->fileInfo(index); fileList << info.filePath(); } if (fileList.isEmpty()) { return; } QString info; int size = fileList.size(); if (size == 1) { info = QString(tr("Are you sure that you want move to trash this item?")) +"\n"+fileList.join("\n"); } else if (size < 6) { info = QString(tr("Are you sure that you want move to trash %1 items?")).arg(size) +"\n"+fileList.join("\n"); } else { info = QString(tr("Are you sure that you want move to trash %1 items?")).arg(size); } int ret = QMessageBox::question(m_liteApp->mainWindow(), tr("Move to Trash"),info, QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::Yes) { foreach (QString filename, fileList) { if (!FileUtil::moveToTrash(filename)) { m_liteApp->appendLog("FolderView",QString("cannot move file to trash \"%1\"").arg(filename),true); } } } } void BaseFolderView::openWithEditor() { QAction *act = (QAction*)sender(); if (!act) { return; } QString id = act->data().toString(); if (id.isEmpty()) { return; } if (!m_contextInfo.isFile()) { return; } m_liteApp->fileManager()->openEditorByFactory(m_contextInfo.filePath(),id); } void BaseFolderView::openWithSystemEditor() { if (!m_contextInfo.isFile()) { return; } QUrl url = QUrl::fromLocalFile(m_contextInfo.filePath()); if (!url.isValid()) { return; } QDesktopServices::openUrl(url); } QMenu *BaseFolderView::openWithMenu() { if (m_openWithMenu) { return m_openWithMenu; } m_openWithMenu = new QMenu(tr("Open With"),this); foreach(LiteApi::IEditorFactory *factory, m_liteApp->editorManager()->factoryList()) { QAction *act = new QAction(factory->displayName(),this); act->setData(factory->id()); m_openWithMenu->addAction(act); connect(act,SIGNAL(triggered()),this,SLOT(openWithEditor())); } QAction *act = new QAction(tr("System Editor"),this); m_openWithMenu->addAction(act); connect(act,SIGNAL(triggered()),this,SLOT(openWithSystemEditor())); return m_openWithMenu; } QModelIndex BaseFolderView::findIndexForContext(const QString &/*filePath*/) const { return QModelIndex(); } void BaseFolderView::removeIndex(const QModelIndex &index) { } QFileInfo BaseFolderView::fileInfo(const QModelIndex &index) const { return QFileInfo(); } QModelIndexList BaseFolderView::selectionCopyOrRemoveList() const { return QModelIndexList(); } void BaseFolderView::openShell() { QProcessEnvironment env = LiteApi::getCurrentEnvironment(m_liteApp); FileUtil::openInShell(env, contextDir().path()); }
23,600
C++
.cpp
633
30.127962
173
0.607703
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,512
folderlistview.cpp
visualfc_liteide/liteidex/src/utils/folderview/folderlistview.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: folderlistview.cpp // Creator: visualfc <visualfc@gmail.com> #include "folderlistview.h" #include <QTreeView> #include <QMenu> #include <QAction> #include <QMessageBox> #include <QDesktopServices> #include <QProcess> #include <QInputDialog> #include <QFileDialog> #include <QHeaderView> #include <QSortFilterProxyModel> //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 FolderListProxyModel : public QSortFilterProxyModel { public: FolderListProxyModel(QObject *parent) : QSortFilterProxyModel(parent) { } virtual bool lessThan( const QModelIndex & left, const QModelIndex & right ) const { FolderListModel *model = static_cast<FolderListModel*>(this->sourceModel()); if (model->isRootIndex(left) && model->isRootIndex(right)) { return false; } QFileInfo l = model->fileInfo(left); QFileInfo r = model->fileInfo(right); if (l.isDir() && r.isFile()) { return true; } else if (l.isFile() && r.isDir()) { return false; } #ifdef Q_OS_WIN if (l.filePath().length() <= 3 || r.filePath().length() <= 3) { return l.filePath().at(0) < r.filePath().at(0); } #endif return (l.fileName().compare(r.fileName(),Qt::CaseInsensitive) < 0); } }; FolderListView::FolderListView(bool proxyMode, LiteApi::IApplication *app, QWidget *parent) : BaseFolderView(app,parent) { m_model = new FolderListModel(this); if (proxyMode) { m_proxy = new FolderListProxyModel(this); m_proxy->setSourceModel(m_model); m_proxy->sort(0); this->setModel(m_proxy); } else { m_proxy = 0; this->setModel(m_model); } this->setHeaderHidden(true); setContextMenuPolicy(Qt::CustomContextMenu); connect(this,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(customContextMenuRequested(QPoint))); } void FolderListView::setFilter(QDir::Filters filters) { m_model->setFilter(filters); } QDir::Filters FolderListView::filter() const { return m_model->filter(); } QFileInfo FolderListView::fileInfo(const QModelIndex &index) const { if (m_proxy) { return m_model->fileInfo(m_proxy->mapToSource(index)); } else { return m_model->fileInfo(index); } } bool FolderListView::addRootPath(const QString &path) { if (m_model->isRootPath(path)) { return true; } if (!m_model->addRootPath(path).isValid()) { m_liteApp->appendLog("Add path false",path,true); return false; } if (m_proxy) { m_proxy->invalidate(); } return true; } void FolderListView::setRootPathList(const QStringList &pathList) { m_model->clear(); foreach(QString path, pathList) { m_model->addRootPath(path); } if (m_proxy) { m_proxy->invalidate(); } } QStringList FolderListView::rootPathList() const { return m_model->rootPathList(); } void FolderListView::clear() { m_model->clear(); } void FolderListView::expandFolder(const QString &path, bool expand) { QList<QModelIndex> indexList = m_model->indexForPath(path); foreach (QModelIndex sourceIndex, indexList) { QModelIndex index = sourceIndex; if (m_proxy) { index = m_proxy->mapFromSource(sourceIndex); } if (expand) { this->expand(index); } else { this->collapse(index); } } } QList<QModelIndex> FolderListView::indexForPath(const QString &path) const { QList<QModelIndex> indexList = m_model->indexForPath(path); if (!m_proxy) { return indexList; } QList<QModelIndex> indexs; foreach (QModelIndex sourceIndex, indexList) { indexs.push_back(m_proxy->mapFromSource(sourceIndex)); } return indexs; } void FolderListView::customContextMenuRequested(const QPoint &pos) { QMenu menu(this); LiteApi::FILESYSTEM_CONTEXT_FLAG flag = LiteApi::FILESYSTEM_ROOT; QModelIndex index = this->indexAt(pos); if (index.isValid()) { m_contextIndex = index; QModelIndex sourceIndex = index; if (m_proxy) { sourceIndex = m_proxy->mapToSource(index); } m_contextInfo = m_model->fileInfo(sourceIndex); if (m_model->isRootIndex(sourceIndex)) { flag = LiteApi::FILESYSTEM_ROOTFOLDER; } else if (m_model->isDir(sourceIndex)) { flag = LiteApi::FILESYSTEM_FOLDER; } else { flag = LiteApi::FILESYSTEM_FILES; } } else { m_contextIndex = this->rootIndex(); m_contextInfo = QFileInfo(); } //root folder if (flag == LiteApi::FILESYSTEM_ROOT) { menu.addAction(m_openFolderAct); } else if (flag == LiteApi::FILESYSTEM_ROOTFOLDER) { menu.addAction(m_newFileAct); menu.addAction(m_newFileWizardAct); menu.addAction(m_newFolderAct); menu.addSeparator(); menu.addAction(m_reloadFolderAct); menu.addAction(m_closeFolderAct); menu.addSeparator(); menu.addAction(m_openExplorerAct); menu.addAction(m_openShellAct); menu.addAction(m_openTerminalAct); } else if (flag == LiteApi::FILESYSTEM_FOLDER) { menu.addAction(m_newFileAct); menu.addAction(m_newFileWizardAct); menu.addAction(m_newFolderAct); menu.addAction(m_renameFolderAct); menu.addAction(m_removeFolderAct); menu.addSeparator(); menu.addAction(m_openExplorerAct); menu.addAction(m_openShellAct); menu.addAction(m_openTerminalAct); } else if (flag == LiteApi::FILESYSTEM_FILES) { menu.addAction(m_openEditorAct); menu.addMenu(this->openWithMenu()); menu.addSeparator(); menu.addAction(m_newFileAct); menu.addAction(m_newFileWizardAct); menu.addAction(m_newFolderAct); menu.addAction(m_renameFileAct); menu.addAction(m_removeFileAct); menu.addSeparator(); menu.addAction(m_openExplorerAct); menu.addAction(m_openShellAct); menu.addAction(m_openTerminalAct); } emit aboutToShowContextMenu(&menu,flag,m_contextInfo); menu.exec(this->mapToGlobal(pos)); } void FolderListView::removeFile() { QFileInfo info = m_contextInfo; 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?") +"\n"+info.filePath(), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::Yes) { QModelIndex index = this->currentIndex(); if (m_proxy) { index = m_proxy->mapToSource(index); } if (!m_model->remove(index)) { QMessageBox::information(m_liteApp->mainWindow(),tr("Delete File"), tr("Failed to delete the file!")); } } } void FolderListView::removeFolder() { QFileInfo info = m_contextInfo; 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?") +"\n"+info.filePath(), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::Yes) { QModelIndex index = this->currentIndex(); if (m_proxy) { index = m_proxy->mapToSource(index); } if (!m_model->remove(index)) { QMessageBox::information(m_liteApp->mainWindow(),tr("Delete Folder"), tr("Failed to delete the folder!")); } } } void FolderListView::openFolder() { m_liteApp->fileManager()->openFolder(); } void FolderListView::closeFolder() { QModelIndex index = this->currentIndex(); if (m_proxy) { index = m_proxy->mapToSource(index); } m_model->removeRoot(index); } void FolderListView::reloadFolder() { QModelIndex index = this->currentIndex(); this->collapse(index); if (m_proxy) { index = m_proxy->mapToSource(index); } m_model->reloadRoot(index); } void FolderListView::closeAllFolders() { m_model->clear(); }
9,674
C++
.cpp
293
26.860068
117
0.634352
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,514
folderlistmodel.cpp
visualfc_liteide/liteidex/src/utils/folderview/folderlistmodel.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: folderlistmodel.cpp // Creator: visualfc <visualfc@gmail.com> #include "folderlistmodel.h" #include "filesystemmodelex.h" #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 FolderListModel::FolderListModel(QObject *parent) : QAbstractItemModel(parent) { ignoreNextLayoutAboutToBeChanged = false; ignoreNextLayoutChanged = false; m_filters = QDir::AllEntries | QDir::NoDotAndDotDot | QDir::AllDirs; m_resolveSymlinks = false; m_nameFilterDisables = true; m_bWatcherRoot = false; } FolderListModel::~FolderListModel() { clear(); } void FolderListModel::clear() { if (m_modelList.isEmpty()) { return; } this->beginRemoveRows(QModelIndex(),0,m_modelList.size()); this->removeRows(0,m_modelList.size()); if (m_bWatcherRoot) { foreach (SourceModel s, m_modelList) { m_watcher->removePath(s.watchPath); delete s.model; } } m_modelList.clear(); m_indexMap.clear(); this->endRemoveRows(); } QModelIndex FolderListModel::addRootPath(const QString &path) { if (!QDir(path).exists()) { return QModelIndex(); } FileSystemModelEx *model = new FileSystemModelEx(this); model->setFilter(m_filters); if (!m_nameFilters.isEmpty()) { model->setNameFilters(m_nameFilters); } model->setNameFilterDisables(m_nameFilterDisables); model->setResolveSymlinks(m_resolveSymlinks); QModelIndex sourceIndex = model->setRootPath(path); if (!sourceIndex.isValid()) { return sourceIndex; } SourceModel m; m.model = model; m.rootPath = QDir::cleanPath(QDir::fromNativeSeparators(path)); m.watchPath = model->filePath(sourceIndex.parent()); if (m_bWatcherRoot) { if (!m_watcher->directories().contains(m.watchPath)) { m_watcher->addPath(m.watchPath); } } m.rootSourceIndex = sourceIndex; m.rootIndex = createIndex(m_modelList.size(),0,sourceIndex.internalPointer()); m_indexMap.insert(sourceIndex.internalId(),model); m_modelList.append(m); connect(model, SIGNAL(rowsAboutToBeInserted(const QModelIndex &, int, int)), SLOT(sourceRowsAboutToBeInserted(const QModelIndex &, int, int))); connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)), SLOT(sourceRowsInserted(const QModelIndex &, int, int))); connect(model, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)), SLOT(sourceRowsAboutToBeRemoved(const QModelIndex &, int, int))); connect(model, SIGNAL(rowsRemoved(const QModelIndex &, int, int)), SLOT(sourceRowsRemoved(const QModelIndex &, int, int))); connect(model, SIGNAL(rowsAboutToBeMoved(const QModelIndex &, int, int, const QModelIndex &, int)), SLOT(sourceRowsAboutToBeMoved(const QModelIndex &, int, int, const QModelIndex &, int))); connect(model, SIGNAL(rowsMoved(const QModelIndex &, int, int, const QModelIndex &, int)), SLOT(sourceRowsMoved(const QModelIndex &, int, int, const QModelIndex &, int))); connect(model, SIGNAL(columnsAboutToBeInserted(const QModelIndex &, int, int)), SLOT(sourceColumnsAboutToBeInserted(const QModelIndex &, int, int))); connect(model, SIGNAL(columnsInserted(const QModelIndex &, int, int)), SLOT(sourceColumnsInserted(const QModelIndex &, int, int))); connect(model, SIGNAL(columnsAboutToBeRemoved(const QModelIndex &, int, int)), SLOT(sourceColumnsAboutToBeRemoved(const QModelIndex &, int, int))); connect(model, SIGNAL(columnsRemoved(const QModelIndex &, int, int)), SLOT(sourceColumnsRemoved(const QModelIndex &, int, int))); connect(model, SIGNAL(columnsAboutToBeMoved(const QModelIndex &, int, int, const QModelIndex &, int)), SLOT(sourceColumnsAboutToBeMoved(const QModelIndex &, int, int, const QModelIndex &, int))); connect(model, SIGNAL(columnsMoved(const QModelIndex &, int, int, const QModelIndex &, int)), SLOT(sourceColumnsMoved(const QModelIndex &, int, int, const QModelIndex &, int))); connect(model, SIGNAL(modelAboutToBeReset()), SLOT(sourceModelAboutToBeReset())); connect(model, SIGNAL(modelReset()), SLOT(sourceModelReset())); connect(model, SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)), SLOT(sourceDataChanged(const QModelIndex &, const QModelIndex &))); connect(model, SIGNAL(headerDataChanged(Qt::Orientation,int,int)), SLOT(sourceHeaderDataChanged(Qt::Orientation,int,int))); connect(model, SIGNAL(layoutAboutToBeChanged()), SLOT(sourceLayoutAboutToBeChanged())); connect(model, SIGNAL(layoutChanged()), SLOT(sourceLayoutChanged())); return m.rootIndex; } void FolderListModel::removeRootPath(const QString &path) { QString rootPath = QDir::cleanPath(QDir::fromNativeSeparators(path)); QModelIndex index; foreach (SourceModel s, m_modelList) { if (s.rootPath == rootPath) { index = s.rootIndex; break; } } if (index.isValid()) { removeRoot(index); } } void FolderListModel::removeRoot(const QModelIndex &index) { QMutableListIterator<SourceModel> i(m_modelList); while (i.hasNext()) { SourceModel s = i.next(); if (s.rootIndex.internalId() == index.internalId()) { this->beginRemoveRows(QModelIndex(),index.row(),index.row()); if (m_bWatcherRoot) { int n = 0; foreach (SourceModel m, m_modelList) { if (m.watchPath == s.watchPath) { n++; } } if (n <= 1) { m_watcher->removePath(s.watchPath); } } this->removeRow(index.row()); i.remove(); this->endRemoveRows(); QMutableHashIterator<qint64,QAbstractItemModel*> i2(m_indexMap); while (i2.hasNext()) { i2.next(); if (i2.value() == s.model) { i2.remove(); } } delete s.model; break; } } } void FolderListModel::reloadRoot(const QModelIndex &index) { QMutableListIterator<SourceModel> i(m_modelList); int count = 0; while (i.hasNext()) { SourceModel s = i.next(); if (s.rootIndex.internalId() == index.internalId()) { QModelIndex sourceIndex = s.model->setRootPath(s.rootPath); s.rootSourceIndex = sourceIndex; s.rootIndex = createIndex(count,0,sourceIndex.internalPointer()); m_indexMap.insert(sourceIndex.internalId(),s.model); i.setValue(s); break; } count++; } } bool FolderListModel::isRootPath(const QString &path) { QString rootPath = QDir::cleanPath(QDir::fromNativeSeparators(path)); foreach (SourceModel s, m_modelList) { if (s.rootPath == rootPath) { return true; } } return false; } QList<QModelIndex> FolderListModel::rootIndexs() const { QList<QModelIndex> indexs; foreach (SourceModel s, m_modelList) { indexs.append(s.rootIndex); } return indexs; } QStringList FolderListModel::rootPathList() const { QStringList paths; foreach (SourceModel s, m_modelList) { paths.append(s.rootPath); } return paths; } QFileSystemModel *FolderListModel::findSource(const QModelIndex &proxyIndex) const { return (QFileSystemModel*)m_indexMap[proxyIndex.internalId()]; } QItemSelection FolderListModel::mapSelectionToSource(const QItemSelection &proxySelection) const { QModelIndexList proxyIndexes = proxySelection.indexes(); QItemSelection sourceSelection; for (int i = 0; i < proxyIndexes.size(); ++i) { const QModelIndex proxyIdx = mapToSource(proxyIndexes.at(i)); if (!proxyIdx.isValid()) continue; sourceSelection << QItemSelectionRange(proxyIdx); } return sourceSelection; } QItemSelection FolderListModel::mapSelectionFromSource(const QItemSelection &sourceSelection) const { QModelIndexList sourceIndexes = sourceSelection.indexes(); QItemSelection proxySelection; for (int i = 0; i < sourceIndexes.size(); ++i) { const QModelIndex srcIdx = mapFromSource(sourceIndexes.at(i)); if (!srcIdx.isValid()) continue; proxySelection << QItemSelectionRange(srcIdx); } return proxySelection; } QModelIndex FolderListModel::mapFromSource(const QModelIndex &sourceIndex) const { if (!sourceIndex.isValid()) return QModelIndex(); int row = sourceIndex.row(); for (int i = 0; i < m_modelList.size(); i++) { if (m_modelList[i].rootSourceIndex.internalId() == sourceIndex.internalId()) { row = i; break; } } QModelIndex index = createIndex(row, sourceIndex.column(), sourceIndex.internalPointer()); m_indexMap.insert(sourceIndex.internalId(),(QAbstractItemModel*)sourceIndex.model()); return index; } QModelIndex FolderListModel::mapToSource(const QModelIndex &proxyIndex) const { if (!proxyIndex.isValid()) { return QModelIndex(); } int row = proxyIndex.row(); for (int i = 0; i < m_modelList.size(); i++) { if (m_modelList[i].rootIndex.internalId() == proxyIndex.internalId()) { row = i; break; } } FileSystemModelEx *model = (FileSystemModelEx*)findSource(proxyIndex); return model->createIndex(row, proxyIndex.column(), proxyIndex.internalPointer()); } QString FolderListModel::filePath(const QModelIndex &index) const { if (!index.isValid()) { return QString(); } QModelIndex sourceIndex = mapToSource(index); return ((FileSystemModelEx*)sourceIndex.model())->filePath(sourceIndex); } QString FolderListModel::fileName(const QModelIndex &index) const { if (!index.isValid()) { return QString(); } QModelIndex sourceIndex = mapToSource(index); return ((FileSystemModelEx*)sourceIndex.model())->fileName(sourceIndex); } QFileInfo FolderListModel::fileInfo(const QModelIndex &index) const { if (!index.isValid()) { return QFileInfo(); } QModelIndex sourceIndex = mapToSource(index); return ((FileSystemModelEx*)sourceIndex.model())->fileInfo(sourceIndex); } bool FolderListModel::isDir(const QModelIndex &index) const { if (!index.isValid()) { return true; } QModelIndex sourceIndex = mapToSource(index); return ((FileSystemModelEx*)sourceIndex.model())->isDir(sourceIndex); } QModelIndex FolderListModel::mkdir(const QModelIndex &parent, const QString &name) { if (!parent.isValid()) { return QModelIndex(); } QModelIndex sourceIndex = mapToSource(parent); return ((FileSystemModelEx*)sourceIndex.model())->mkdir(sourceIndex,name); } bool FolderListModel::rmdir(const QModelIndex &index) { if (!index.isValid()) { return false; } QModelIndex sourceIndex = mapToSource(index); return ((FileSystemModelEx*)sourceIndex.model())->rmdir(sourceIndex); } bool FolderListModel::remove(const QModelIndex &index) { if (!index.isValid()) { return false; } QModelIndex sourceIndex = mapToSource(index); return ((FileSystemModelEx*)sourceIndex.model())->remove(sourceIndex); } void FolderListModel::setFilter(QDir::Filters filters) { m_filters = filters; foreach (SourceModel s, m_modelList) { s.model->setFilter(filters); } } QDir::Filters FolderListModel::filter() const { return m_filters; } void FolderListModel::setNameFilters(const QStringList &filters) { m_nameFilters = filters; foreach (SourceModel s, m_modelList) { s.model->setNameFilters(filters); } } QStringList FolderListModel::nameFilters() const { return m_nameFilters; } void FolderListModel::setNameFilterDisables(bool enable) { if (m_nameFilterDisables == enable) { return; } m_nameFilterDisables = enable; foreach (SourceModel s, m_modelList) { s.model->setNameFilterDisables(enable); } } bool FolderListModel::nameFilterDisables() const { return m_nameFilterDisables; } void FolderListModel::setResolveSymlinks(bool enable) { if (m_resolveSymlinks == enable) { return; } m_resolveSymlinks = enable; foreach (SourceModel s, m_modelList) { s.model->setResolveSymlinks(enable); } } bool FolderListModel::resolveSymlinks() const { return m_resolveSymlinks; } bool FolderListModel::isRootIndex(const QModelIndex &index) const { foreach (SourceModel s, m_modelList) { if (s.rootIndex.internalId() == index.internalId()) { return true; } } return false; } void FolderListModel::setWatcherRoot(bool b) { if (m_bWatcherRoot == b) { return; } if (m_bWatcherRoot) { if (!m_watcher) { m_watcher = new QFileSystemWatcher(this); } connect(m_watcher,SIGNAL(directoryChanged(QString)),this,SLOT(directoryChanged(QString))); QStringList paths; foreach (SourceModel s, m_modelList) { paths.append(s.watchPath); } paths.removeDuplicates(); m_watcher->addPaths(paths); } else { if (m_watcher) { delete m_watcher; } m_watcher = 0; } } bool FolderListModel::isWatcherRoot() const { return m_bWatcherRoot; } QList<QModelIndex> FolderListModel::indexForPath(const QString &path) const { QList<QModelIndex> indexs; QString findPath = QDir::cleanPath(QDir::fromNativeSeparators(path)); foreach (SourceModel s, m_modelList) { if (!findPath.startsWith(s.rootPath)) { continue; } QModelIndex sourceIndex = s.model->index(path); if (sourceIndex.isValid()) { indexs.append(this->mapFromSource(sourceIndex)); } } return indexs; } Qt::DropActions FolderListModel::supportedDragActions() const { return Qt::MoveAction | Qt::CopyAction; } bool FolderListModel::isRootSourceIndex(const QModelIndex &sourceIndex) const { foreach (SourceModel s, m_modelList) { if (s.rootSourceIndex.internalId() == sourceIndex.internalId()) { return true; } } return false; } int FolderListModel::columnCount(const QModelIndex &/*parent*/) const { return 1; // if (!parent.isValid()) { // if (!m_modelList.isEmpty()) { // return m_modelList[0].model->columnCount(m_modelList[0].rootSourceIndex); // } // return 1; // } // QModelIndex sourceIndex = mapToSource(parent); // return sourceIndex.model()->columnCount(sourceIndex); } QModelIndex FolderListModel::index(int row, int column, const QModelIndex &parent) const { if (!hasIndex(row, column, parent)) return QModelIndex(); if (!parent.isValid()) { QModelIndex sourceIndex = m_modelList[row].rootSourceIndex; if (sourceIndex.column() != column) { sourceIndex = sourceIndex.sibling(sourceIndex.row(),column); m_indexMap.insert(sourceIndex.internalId(),m_modelList[row].model); } return createIndex(row,column,sourceIndex.internalPointer()); } const QModelIndex sourceParent = mapToSource(parent); const QModelIndex sourceIndex = sourceParent.model()->index(row, column, sourceParent); Q_ASSERT(sourceIndex.isValid()); return mapFromSource(sourceIndex); } QModelIndex FolderListModel::parent(const QModelIndex &child) const { Q_ASSERT(child.isValid() ? child.model() == this : true); if (isRootIndex(child)) { return QModelIndex(); } const QModelIndex sourceIndex = mapToSource(child); const QModelIndex sourceParent = sourceIndex.parent(); return mapFromSource(sourceParent); } int FolderListModel::rowCount(const QModelIndex &parent) const { if (!parent.isValid()) { return m_modelList.size(); } Q_ASSERT(parent.isValid() ? parent.model() == this : true); QModelIndex sourceIndex = mapToSource(parent); return sourceIndex.model()->rowCount(sourceIndex); } QVariant FolderListModel::data(const QModelIndex &proxyIndex, int role) const { if (!proxyIndex.isValid()) { return QVariant(); } QModelIndex sourceIndex = mapToSource(proxyIndex); return sourceIndex.model()->data(sourceIndex,role); } QVariant FolderListModel::headerData(int section, Qt::Orientation orientation, int role) const { if (m_modelList.isEmpty()) { return QVariant(); } if (orientation == Qt::Horizontal) { const QModelIndex proxyIndex = index(0, section); QModelIndex sourceIndex = mapToSource(proxyIndex); int sourceSection = sourceIndex.column(); return sourceIndex.model()->headerData(sourceSection,orientation,role); } else { const QModelIndex proxyIndex = index(section, 0); QModelIndex sourceIndex = mapToSource(proxyIndex); int sourceSection = sourceIndex.row(); return sourceIndex.model()->headerData(sourceSection,orientation,role); } } QMap<int, QVariant> FolderListModel::itemData(const QModelIndex &proxyIndex) const { return QAbstractItemModel::itemData(proxyIndex); } Qt::ItemFlags FolderListModel::flags(const QModelIndex &index) const { QModelIndex sourceIndex = mapToSource(index); if (!sourceIndex.isValid()) { return Qt::NoItemFlags; } return sourceIndex.model()->flags(sourceIndex); } bool FolderListModel::setData(const QModelIndex &index, const QVariant &value, int role) { QModelIndex sourceIndex = mapToSource(index); return ((QAbstractItemModel*)sourceIndex.model())->setData(sourceIndex,value,role); } bool FolderListModel::setItemData(const QModelIndex &index, const QMap< int, QVariant >& roles) { return QAbstractItemModel::setItemData(index, roles); } bool FolderListModel::setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role) { if (orientation == Qt::Horizontal) { const QModelIndex proxyIndex = index(0, section); QModelIndex sourceIndex = mapToSource(proxyIndex); int sourceSection = sourceIndex.column(); return ((QAbstractItemModel*)sourceIndex.model())->setHeaderData(sourceSection,orientation,value,role); } else { const QModelIndex proxyIndex = index(section, 0); QModelIndex sourceIndex = mapToSource(proxyIndex); int sourceSection = sourceIndex.row(); return ((QAbstractItemModel*)sourceIndex.model())->setHeaderData(sourceSection,orientation,value,role); } } bool FolderListModel::insertColumns(int column, int count, const QModelIndex& parent) { Q_ASSERT(parent.isValid() ? parent.model() == this : true); QModelIndex sourceIndex = mapToSource(parent); return ((QAbstractItemModel*)sourceIndex.model())->insertColumns(column, count, sourceIndex); } /*! \reimp */ bool FolderListModel::insertRows(int row, int count, const QModelIndex& parent) { Q_ASSERT(parent.isValid() ? parent.model() == this : true); QModelIndex sourceIndex = mapToSource(parent); return ((QAbstractItemModel*)sourceIndex.model())->insertRows(row, count, sourceIndex); } bool FolderListModel::removeColumns(int column, int count, const QModelIndex &parent) { Q_ASSERT(parent.isValid() ? parent.model() == this : true); QModelIndex sourceIndex = mapToSource(parent); return ((QAbstractItemModel*)sourceIndex.model())->removeColumns(column, count, sourceIndex); } bool FolderListModel::removeRows(int row, int count, const QModelIndex &parent) { Q_ASSERT(parent.isValid() ? parent.model() == this : true); if (!parent.isValid()) { return QAbstractItemModel::removeRows(row,count); } QModelIndex sourceIndex = mapToSource(parent); return ((QAbstractItemModel*)sourceIndex.model())->removeRows(row, count, sourceIndex); } void FolderListModel::directoryChanged(const QString &path) { if (!m_bWatcherRoot) { return; } foreach(SourceModel s, m_modelList) { if (s.watchPath == path && !QDir(s.rootPath).exists()) { this->removeRoot(s.rootIndex); break; } } } bool FolderListModel::canFetchMore(const QModelIndex &parent) const { if (!parent.isValid()) { return false; } QModelIndex sourceIndex = mapToSource(parent); return sourceIndex.model()->canFetchMore(sourceIndex); } void FolderListModel::fetchMore(const QModelIndex &parent) { if (!parent.isValid()) { return; } QModelIndex sourceIndex = mapToSource(parent); QAbstractItemModel *model = (QAbstractItemModel*)sourceIndex.model(); model->fetchMore(sourceIndex); } void FolderListModel::sort(int column, Qt::SortOrder order) { foreach (SourceModel s, m_modelList) { s.model->sort(column,order); } } QSize FolderListModel::span(const QModelIndex &index) const { if (!index.isValid()) { return QAbstractItemModel::span(index); } QModelIndex sourceIndex = mapToSource(index); return sourceIndex.model()->span(sourceIndex); } bool FolderListModel::hasChildren(const QModelIndex &parent) const { if (!parent.isValid()) { return m_modelList.size() > 0; } QModelIndex sourceIndex = mapToSource(parent); return sourceIndex.model()->hasChildren(sourceIndex); } QModelIndex FolderListModel::buddy(const QModelIndex &index) const { return index; } void FolderListModel::sourceColumnsAboutToBeInserted(const QModelIndex &parent, int start, int end) { //Q_ASSERT(parent.isValid() ? parent.model() == m_model : true); this->beginInsertColumns(mapFromSource(parent), start, end); } void FolderListModel::sourceColumnsAboutToBeMoved(const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destParent, int dest) { //Q_ASSERT(sourceParent.isValid() ? sourceParent.model() == m_model : true); //Q_ASSERT(destParent.isValid() ? destParent.model() == m_model : true); this->beginMoveColumns(this->mapFromSource(sourceParent), sourceStart, sourceEnd, this->mapFromSource(destParent), dest); } void FolderListModel::sourceColumnsAboutToBeRemoved(const QModelIndex &parent, int start, int end) { //Q_ASSERT(parent.isValid() ? parent.model() == m_model : true); this->beginRemoveColumns(this->mapFromSource(parent), start, end); } void FolderListModel::sourceColumnsInserted(const QModelIndex &parent, int start, int end) { //Q_ASSERT(parent.isValid() ? parent.model() == m_model : true); Q_UNUSED(parent) Q_UNUSED(start) Q_UNUSED(end) this->endInsertColumns(); } void FolderListModel::sourceColumnsMoved(const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destParent, int dest) { //Q_ASSERT(sourceParent.isValid() ? sourceParent.model() == m_model : true); //Q_ASSERT(destParent.isValid() ? destParent.model() == m_model : true); Q_UNUSED(sourceParent) Q_UNUSED(sourceStart) Q_UNUSED(sourceEnd) Q_UNUSED(destParent) Q_UNUSED(dest) this->endMoveColumns(); } void FolderListModel::sourceColumnsRemoved(const QModelIndex &parent, int start, int end) { //Q_ASSERT(parent.isValid() ? parent.model() == m_model : true); Q_UNUSED(parent) Q_UNUSED(start) Q_UNUSED(end) this->endRemoveColumns(); } void FolderListModel::sourceDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) { //Q_ASSERT(topLeft.isValid() ? topLeft.model() == m_model : true); //Q_ASSERT(bottomRight.isValid() ? bottomRight.model() == m_model : true); this->dataChanged(this->mapFromSource(topLeft), this->mapFromSource(bottomRight)); } void FolderListModel::sourceHeaderDataChanged(Qt::Orientation orientation, int first, int last) { this->headerDataChanged(orientation, first, last); } void FolderListModel::sourceLayoutAboutToBeChanged() { if (ignoreNextLayoutAboutToBeChanged) return; foreach(const QPersistentModelIndex &proxyPersistentIndex, this->persistentIndexList()) { // qDebug() << proxyPersistentIndex << this->filePath(proxyPersistentIndex); proxyIndexes << proxyPersistentIndex; // Q_ASSERT(proxyPersistentIndex.isValid()); const QPersistentModelIndex srcPersistentIndex = this->mapToSource(proxyPersistentIndex); // Q_ASSERT(srcPersistentIndex.isValid()); layoutChangePersistentIndexes << srcPersistentIndex; } this->layoutAboutToBeChanged(); } void FolderListModel::sourceLayoutChanged() { if (ignoreNextLayoutChanged) return; for (int i = 0; i < proxyIndexes.size(); ++i) { this->changePersistentIndex(proxyIndexes.at(i), this->mapFromSource(layoutChangePersistentIndexes.at(i))); } layoutChangePersistentIndexes.clear(); proxyIndexes.clear(); this->layoutChanged(); } void FolderListModel::sourceModelAboutToBeReset() { this->beginResetModel(); } void FolderListModel::sourceModelReset() { this->endResetModel(); } void FolderListModel::sourceRowsAboutToBeInserted(const QModelIndex &/*parent*/, int /*start*/, int /*end*/) { //Q_ASSERT(parent.isValid() ? parent.model() == m_model : true); //this->beginInsertRows(this->mapFromSource(parent), start, end); } void FolderListModel::sourceRowsAboutToBeMoved(const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destParent, int dest) { //Q_ASSERT(sourceParent.isValid() ? sourceParent.model() == m_model : true); //Q_ASSERT(destParent.isValid() ? destParent.model() == m_model : true); this->beginMoveRows(this->mapFromSource(sourceParent), sourceStart, sourceEnd, this->mapFromSource(destParent), dest); } void FolderListModel::sourceRowsAboutToBeRemoved(const QModelIndex &parent, int start, int end) { //Q_ASSERT(parent.isValid() ? parent.model() == m_model : true); this->beginRemoveRows(this->mapFromSource(parent), start, end); } void FolderListModel::sourceRowsInserted(const QModelIndex &parent, int start, int end) { //Q_ASSERT(parent.isValid() ? parent.model() == m_model : true); Q_UNUSED(parent) Q_UNUSED(start) Q_UNUSED(end) //this->beginInsertRows(this->mapFromSource(parent), start, end); //this->endInsertRows(); for (int i = start; i <= end; i++) { this->beginInsertRows(this->mapFromSource(parent), i,i); this->endInsertRows(); } } void FolderListModel::sourceRowsMoved(const QModelIndex &sourceParent, int sourceStart, int sourceEnd, const QModelIndex &destParent, int dest) { //Q_ASSERT(sourceParent.isValid() ? sourceParent.model() == m_model : true); //Q_ASSERT(destParent.isValid() ? destParent.model() == m_model : true); Q_UNUSED(sourceParent) Q_UNUSED(sourceStart) Q_UNUSED(sourceEnd) Q_UNUSED(destParent) Q_UNUSED(dest) this->endMoveRows(); } void FolderListModel::sourceRowsRemoved(const QModelIndex &parent, int start, int end) { //Q_ASSERT(parent.isValid() ? parent.model() == m_model : true); Q_UNUSED(parent) Q_UNUSED(start) Q_UNUSED(end) this->endRemoveRows(); }
28,620
C++
.cpp
778
31.637532
155
0.691213
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,517
folderdialog.cpp
visualfc_liteide/liteidex/src/utils/folderview/folderdialog.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: folderdialog.cpp // Creator: visualfc <visualfc@gmail.com> #include "folderdialog.h" #include <QLineEdit> #include <QLabel> #include <QHBoxLayout> #include <QVBoxLayout> #include <QPushButton> #include <QGridLayout> //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 CreateFileDialog::CreateFileDialog(QWidget *parent) : QDialog(parent), m_bOpenEditor(false) { this->setWindowTitle(tr("Create File")); QGridLayout *grid = new QGridLayout; QLabel *label1 = new QLabel(tr("Directory:")); m_dirLabel = new QLabel(); QLabel *label2 = new QLabel(tr("File Name:")); m_fileNameEdit = new QLineEdit(); grid->addWidget(label1,0,0); grid->addWidget(m_dirLabel,0,1); grid->addWidget(label2,1,0); grid->addWidget(m_fileNameEdit,1,1); QHBoxLayout *hbox = new QHBoxLayout; QPushButton *btn1 = new QPushButton(tr("Create")); QPushButton *btn2 = new QPushButton(tr("Create and Edit")); QPushButton *btn3 = new QPushButton(tr("Cancel")); hbox->addStretch(); hbox->addWidget(btn1); hbox->addWidget(btn2); hbox->addWidget(btn3); QVBoxLayout *vbox = new QVBoxLayout; vbox->addLayout(grid); vbox->addStretch(0); vbox->addLayout(hbox); this->setLayout(vbox); connect(btn1,SIGNAL(clicked()),this,SLOT(accept())); connect(btn2,SIGNAL(clicked()),this,SLOT(createAndEdit())); connect(btn3,SIGNAL(clicked()),this,SLOT(reject())); } void CreateFileDialog::setDirectory(const QString &path) { m_dirLabel->setText(path); } QString CreateFileDialog::getFileName() const { return m_fileNameEdit->text(); } void CreateFileDialog::createAndEdit() { m_bOpenEditor = true; this->accept(); } CreateDirDialog::CreateDirDialog(QWidget *parent) : QDialog(parent) { this->setWindowTitle(tr("Create Folder")); QGridLayout *grid = new QGridLayout; QLabel *label1 = new QLabel(tr("Directory:")); m_dirLabel = new QLabel(); QLabel *label2 = new QLabel(tr("Dir Name:")); m_dirNameEdit = new QLineEdit(); grid->addWidget(label1,0,0); grid->addWidget(m_dirLabel,0,1); grid->addWidget(label2,1,0); grid->addWidget(m_dirNameEdit,1,1); QHBoxLayout *hbox = new QHBoxLayout; QPushButton *btn1 = new QPushButton(tr("Create")); QPushButton *btn2 = new QPushButton(tr("Cancel")); hbox->addStretch(); hbox->addWidget(btn1); hbox->addWidget(btn2); QVBoxLayout *vbox = new QVBoxLayout; vbox->addLayout(grid); vbox->addStretch(0); vbox->addLayout(hbox); this->setLayout(vbox); connect(btn1,SIGNAL(clicked()),this,SLOT(accept())); connect(btn2,SIGNAL(clicked()),this,SLOT(reject())); } void CreateDirDialog::setDirectory(const QString &path) { m_dirLabel->setText(path); } QString CreateDirDialog::getDirName() const { return m_dirNameEdit->text(); }
4,088
C++
.cpp
116
31.939655
82
0.6857
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,518
folderview.cpp
visualfc_liteide/liteidex/src/utils/folderview/folderview.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: folderview.cpp // Creator: visualfc <visualfc@gmail.com> #include "folderview.h" #include "filesystemmodelex.h" #include <QMessageBox> #include <QHeaderView> #include <QSortFilterProxyModel> #include <QDesktopServices> #if QT_VERSION >= 0x050000 #include <QStandardPaths> #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 FolderView::FolderView(bool proxyMode, LiteApi::IApplication *app, QWidget *parent) : BaseFolderView(app,parent) { m_model = new FileSystemModelEx(this); if (proxyMode) { m_proxy = new FileSystemProxyModel(this); m_proxy->setSourceModel(m_model); this->setModel(m_proxy); m_proxy->sort(0); } else { m_proxy = 0; this->setModel(m_model); } this->setHeaderHidden(true); this->setSelectionMode(QAbstractItemView::ExtendedSelection); m_contextMenu = new QMenu(this); setContextMenuPolicy(Qt::CustomContextMenu); connect(this,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(customContextMenuRequested(QPoint))); } FolderView::~FolderView() { delete m_contextMenu; } void FolderView::setRootPath(const QString &path) { QModelIndex index = m_model->setRootPath(path); if (!path.isEmpty() && !index.isValid()) { #if QT_VERSION >= 0x050000 QString home = QStandardPaths::writableLocation(QStandardPaths::HomeLocation); #else QString home = QDesktopServices::storageLocation(QDesktopServices::HomeLocation); #endif index = m_model->setRootPath(home); } if (m_proxy) this->setRootIndex(m_proxy->mapFromSource(index)); else this->setRootIndex(index); } QString FolderView::rootPath() const { return m_model->rootPath(); } void FolderView::setFilter(QDir::Filters filters) { m_model->setFilter(filters); } QDir::Filters FolderView::filter() const { return m_model->filter(); } void FolderView::setNameFilters(const QStringList &filters) { m_model->setNameFilters(filters); } QStringList FolderView::nameFilters() const { return m_model->nameFilters(); } QFileInfo FolderView::fileInfo(const QModelIndex &index) const { if (m_proxy) return m_model->fileInfo(m_proxy->mapToSource(index)); else return m_model->fileInfo(index); } QModelIndex FolderView::indexForPath(const QString &fileName) const { QString filePath = QDir::fromNativeSeparators(fileName); if (!filePath.startsWith(this->rootPath()+"/")) { return QModelIndex(); } QModelIndex index = m_model->index(filePath); if (!index.isValid()) { return QModelIndex(); } if (m_proxy) { return m_proxy->mapFromSource(index); } return index; } void FolderView::reload() { this->collapseAll(); this->setRootPath(this->rootPath()); } bool FolderView::isShowDetails() const { return m_model->isShowDetails(); } QModelIndex FolderView::findIndexForContext(const QString &filePath) const { return this->indexForPath(filePath); } void FolderView::removeIndex(const QModelIndex &index) { QModelIndex i = index; if (m_proxy) { i = m_proxy->mapToSource(index); } m_model->remove(i); } void FolderView::setShowDetails(bool b) { m_model->setShowDetails(b); } void FolderView::removeFile() { QFileInfo info = m_contextInfo; 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?") +"\n"+info.filePath(), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::Yes) { QModelIndex index = this->currentIndex(); if (m_proxy) { index = m_proxy->mapToSource(index); } if (!m_model->remove(index)) { QMessageBox::information(m_liteApp->mainWindow(),tr("Delete File"), tr("Failed to delete the file!")); } } } QModelIndexList FolderView::selectionCopyOrRemoveList() const { QModelIndexList selection = this->selectionModel()->selectedRows(0); if (selection.size() <= 1) { return selection; } QStringList dirList; foreach (QModelIndex index, selection) { if (m_proxy) { index = m_proxy->mapToSource(index); } if (m_model->isDir(index)) { dirList << QDir::cleanPath(m_model->fileInfo(index).filePath()); } } QModelIndexList itemList; foreach (QModelIndex index, selection) { QString filePath = QDir::cleanPath(this->fileInfo(index).filePath()); QStringList chkList = dirList; chkList.removeAll(filePath); bool find = false; foreach (QString chk, chkList) { if (filePath.startsWith(chk+"/")) { find = true; break; } } if (!find) { itemList << index; } } return itemList; } void FolderView::removeFolder() { QFileInfo info = m_contextInfo; 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?") +"\n"+info.filePath(), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::Yes) { QModelIndex index = this->currentIndex(); if (m_proxy) { index = m_proxy->mapToSource(index); } if (!m_model->remove(index)) { QMessageBox::information(m_liteApp->mainWindow(),tr("Delete Folder"), tr("Failed to delete the folder!")); } } } void FolderView::customContextMenuRequested(const QPoint &pos) { m_contextMenu->clear(); LiteApi::FILESYSTEM_CONTEXT_FLAG flag = LiteApi::FILESYSTEM_ROOT; QModelIndex index = this->indexAt(pos); if (index.isValid()) { bool isDir = false; if (m_proxy) { m_contextInfo = m_model->fileInfo(m_proxy->mapToSource(index)); isDir = m_model->isDir(m_proxy->mapToSource(index)); } else { m_contextInfo = m_model->fileInfo(index); isDir = m_model->isDir(index); } m_contextIndex = index; if (isDir) { flag = LiteApi::FILESYSTEM_FOLDER; } else { flag = LiteApi::FILESYSTEM_FILES; } } else { m_contextIndex = this->rootIndex(); if (m_proxy) { m_contextInfo = m_model->fileInfo(m_proxy->mapToSource(m_contextIndex)); } else { m_contextInfo = m_model->fileInfo(m_contextIndex); } flag = LiteApi::FILESYSTEM_ROOTFOLDER; } //root folder if (flag == LiteApi::FILESYSTEM_ROOT) { m_contextMenu->addAction(m_newFileAct); m_contextMenu->addAction(m_newFileWizardAct); m_contextMenu->addAction(m_newFolderAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_openExplorerAct); m_contextMenu->addAction(m_openShellAct); m_contextMenu->addAction(m_openTerminalAct); } else if (flag == LiteApi::FILESYSTEM_ROOTFOLDER) { #ifdef Q_OS_MAC if (m_contextInfo.isBundle()) { m_contextMenu->addAction(m_openBundleAct); m_contextMenu->addSeparator(); } #endif m_contextMenu->addAction(m_newFileAct); m_contextMenu->addAction(m_newFileWizardAct); m_contextMenu->addAction(m_newFolderAct); m_contextMenu->addAction(m_renameFolderAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_copyFileAct); m_contextMenu->addAction(m_pasteFileAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_copyFullPathToClipboardAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_openExplorerAct); m_contextMenu->addAction(m_openShellAct); m_contextMenu->addAction(m_openTerminalAct); } else if (flag == LiteApi::FILESYSTEM_FOLDER) { #ifdef Q_OS_MAC if (m_contextInfo.isBundle()) { m_contextMenu->addAction(m_openBundleAct); m_contextMenu->addSeparator(); } #endif m_contextMenu->addAction(m_newFileAct); m_contextMenu->addAction(m_newFileWizardAct); m_contextMenu->addAction(m_newFolderAct); m_contextMenu->addAction(m_renameFolderAct); if (this->canMoveToTrash()) { m_contextMenu->addAction(m_moveToTrashAct); } else { m_contextMenu->addAction(m_removeFolderAct); } m_contextMenu->addSeparator(); m_contextMenu->addAction(m_copyFileAct); m_contextMenu->addAction(m_pasteFileAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_copyFullPathToClipboardAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_openExplorerAct); m_contextMenu->addAction(m_openShellAct); m_contextMenu->addAction(m_openTerminalAct); } else if (flag == LiteApi::FILESYSTEM_FILES) { m_contextMenu->addAction(m_openEditorAct); m_contextMenu->addMenu(this->openWithMenu()); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_newFileAct); m_contextMenu->addAction(m_newFileWizardAct); m_contextMenu->addAction(m_newFolderAct); m_contextMenu->addAction(m_renameFileAct); if (this->canMoveToTrash()) { m_contextMenu->addAction(m_moveToTrashAct); } else { m_contextMenu->addAction(m_removeFileAct); } m_contextMenu->addSeparator(); m_contextMenu->addAction(m_copyFileAct); m_contextMenu->addAction(m_pasteFileAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_copyFullPathToClipboardAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_openExplorerAct); m_contextMenu->addAction(m_openShellAct); m_contextMenu->addAction(m_openTerminalAct); } m_pasteFileAct->setEnabled(this->canPasteFile()); bool check = this->selectionModel()->selectedRows(0).size() == 1; m_removeFileAct->setEnabled(check); m_removeFolderAct->setEnabled(check); m_renameFileAct->setEnabled(check); m_renameFolderAct->setEnabled(check); check = true; foreach (QModelIndex index, this->selectionCopyOrRemoveList()) { if (m_proxy) { index = m_proxy->mapToSource(index); } if (index == this->rootIndex()) { check = false; break; } } m_moveToTrashAct->setEnabled(check && !this->selectionCopyOrRemoveList().empty()); emit aboutToShowContextMenu(m_contextMenu,flag,m_contextInfo); m_contextMenu->exec(this->mapToGlobal(pos)); }
12,254
C++
.cpp
347
28.706052
117
0.642809
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,522
modelfileimpl.cpp
visualfc_liteide/liteidex/src/utils/modelproject/modelfileimpl.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: modelfileimpl.cpp // Creator: visualfc <visualfc@gmail.com> #include "modelfileimpl.h" #include "fileutil/fileutil.h" #include <QStandardItemModel> #include <QFile> #include <QFileInfo> #include <QDir> #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 ModelFileImpl::ModelFileImpl(LiteApi::IApplication *app, QObject *parent) : LiteApi::IFile(parent), m_liteApp(app) { m_model = new QStandardItemModel(this); m_bReadOnly = false; } bool ModelFileImpl::loadText(const QString &fileName, const QString &mimeType, QString &/*outText*/) { m_mimeType = mimeType; if (!loadFile(fileName)) { return false; } m_fileName = fileName; m_rootPath = QFileInfo(m_fileName).absolutePath(); return true; } bool ModelFileImpl::reloadText(QString &outText) { if (m_fileName.isEmpty()) { return false; } return loadText(m_fileName,m_mimeType,outText); } bool ModelFileImpl::isReadOnly() const { return m_bReadOnly; } bool ModelFileImpl::isBinary() const { return false; } bool ModelFileImpl::saveText(const QString &/*fileName*/, const QString &/*text*/) { return false; } QString ModelFileImpl::filePath() const { return m_fileName; } QString ModelFileImpl::mimeType() const { return m_mimeType; } QStandardItemModel *ModelFileImpl::model() const { return m_model; } QString ModelFileImpl::value(const QString &key) const { QStringList val = m_context.value(key); if (!val.isEmpty()) { return val.at(0); } return QString(); } QStringList ModelFileImpl::values(const QString &key) const { return m_context.value(key); } QStringList ModelFileImpl::fileNameList() const { return m_fileNameList; } QStringList ModelFileImpl::filePathList() const { return m_filePathList; } QString ModelFileImpl::fileNameToFullPath(const QString &fileName) { QString fullPath = m_rootPath; fullPath += QLatin1Char('/'); fullPath += fileName; return fullPath; } QString ModelFileImpl::workPath() const { return QFileInfo(m_fileName).absolutePath(); }
3,359
C++
.cpp
117
26.059829
100
0.700372
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,523
modelprojectimpl.cpp
visualfc_liteide/liteidex/src/utils/modelproject/modelprojectimpl.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: modelprojectimpl.cpp // Creator: visualfc <visualfc@gmail.com> #include "modelprojectimpl.h" #include "modelfileimpl.h" #include "fileutil/fileutil.h" #include <QVBoxLayout> #include <QFileInfo> #include <QStandardItem> #include <QStandardItemModel> #include <QTreeView> #include <QToolBar> #include <QFileInfo> #include <QDir> //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 ModelProjectImpl::ModelProjectImpl(LiteApi::IApplication *app) : m_liteApp(app) { m_widget = new QWidget(m_liteApp->mainWindow()); m_tree = new QTreeView; m_tree->setEditTriggers(QAbstractItemView::NoEditTriggers); m_tree->setHeaderHidden(true); m_tree->setContextMenuPolicy(Qt::CustomContextMenu); QVBoxLayout *layout = new QVBoxLayout; layout->setMargin(0); layout->addWidget(m_tree); m_widget->setLayout(layout); connect(m_tree,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(doubleClickedTree(QModelIndex))); connect(m_liteApp->editorManager(),SIGNAL(editorSaved(LiteApi::IEditor*)),this,SLOT(editorSaved(LiteApi::IEditor*))); } ModelProjectImpl::~ModelProjectImpl() { if (m_widget) { delete m_widget; } // m_liteApp->dockManager()->removeDock(m_widget); } void ModelProjectImpl::load() { //m_liteApp->dockManager()->addDock(m_widget,tr("Project - ")+displayName()); } QWidget *ModelProjectImpl::widget() { return m_widget; } QString ModelProjectImpl::name() const { return QFileInfo(m_file->filePath()).fileName(); } QIcon ModelProjectImpl::icon() const { return QIcon(); } LiteApi::IFile *ModelProjectImpl::file() { return m_file; } QString ModelProjectImpl::filePath() const { if (m_file) { return m_file->filePath(); } return QString(); } QString ModelProjectImpl::mimeType() const { if (m_file) { return m_file->mimeType(); } return QString(); } void ModelProjectImpl::setModelFile(ModelFileImpl *file) { if (m_file == file) { return; } m_file = file; m_tree->setModel(m_file->model()); } bool ModelProjectImpl::open(const QString &fileName, const QString &mimeType) { QString outText; bool success = m_file->loadText(fileName,mimeType,outText); if (success) { m_file->updateModel(); m_tree->expandAll(); } return success; } QStringList ModelProjectImpl::folderList() const { QFileInfo info(m_file->filePath()); return QStringList() << info.path(); } QStringList ModelProjectImpl::fileNameList() const { return m_file->fileNameList(); } QStringList ModelProjectImpl::filePathList() const { return m_file->filePathList(); } QString ModelProjectImpl::fileNameToFullPath(const QString &fileName) { return m_file->fileNameToFullPath(fileName); } QMap<QString,QString> ModelProjectImpl::targetInfo() const { return m_file->targetInfo(); } void ModelProjectImpl::editorSaved(LiteApi::IEditor *editor) { if (!editor) { return; } if (FileUtil::compareFile(editor->filePath(),m_file->filePath())) { QString outText; bool success = m_file->reloadText(outText); if (success) { m_file->updateModel(); m_tree->expandAll(); emit reloaded(); } } } void ModelProjectImpl::doubleClickedTree(QModelIndex index) { if (!index.isValid()) { return; } QStandardItem *item = m_file->model()->itemFromIndex(index); if (!item) { return; } bool ok; int itemType = item->data().toInt(&ok); if (ok && ( itemType == ModelFileImpl::ItemFile || itemType == ModelFileImpl::ItemProFile ) ) { QString fileName = m_file->fileNameToFullPath(item->text()); if (!fileName.isEmpty()) { m_liteApp->fileManager()->openEditor(fileName); } } }
5,073
C++
.cpp
171
26
121
0.677466
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,524
navigate.cpp
visualfc_liteide/liteidex/src/utils/navigate/navigate.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: navigate.cpp // Creator: visualfc <visualfc@gmail.com> #include "navigate.h" #include "quickopenapi/quickopenapi.h" #include <QDir> #include <QAction> #include <QLabel> #include <QTreeView> //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 QString escaped(const QString &text) { #if QT_VERSION >= 0x050000 return text.toHtmlEscaped(); #else return Qt::escape(text); #endif } NavigateBar::NavigateBar(LiteApi::IApplication *app, QObject *parent) : QObject(parent), m_liteApp(app), m_toolBar(0) { } NavigateBar::~NavigateBar() { } QToolBar *NavigateBar::createToolBar(const QString &title, QWidget *parent) { if (m_toolBar) { return m_toolBar; } m_toolBar = new QToolBar(title,parent); m_toolBar->setIconSize(LiteApi::getToolBarIconSize(m_liteApp)); return m_toolBar; } void NavigateBar::LoadPath(const QString &path) { m_filePath = path; QFileInfo info(path); if (!info.filePath().startsWith("//")) { QStringList paths = QDir::fromNativeSeparators(info.filePath()).split("/"); if (paths.size() >= 2) { QString head = "<style> a{text-decoration: none; color:darkgray;} </style>"; //m_editNavHeadAct = m_editNavBar->addSeparator(); QString last; #ifdef Q_OS_WIN last = paths[0]; #endif for (int i = 1; i < paths.size(); i++) { QString name = paths[i]; #ifdef Q_OS_WIN if (i == 1) { name = paths[0]+"\\"+paths[1]; } #endif QString path = last+"/"+paths[i]; last = path; if (i != paths.size()-1) { name += ">"; } QString text = QString("<a href=\"%1\">%2</a>").arg(escaped(path)).arg(escaped(name)); QLabel *lbl = new QLabel; lbl->setText(head+text); m_toolBar->addWidget(lbl); connect(lbl,SIGNAL(linkActivated(QString)),this,SLOT(pathLinkActivated(QString))); } m_navHeadAct = m_toolBar->actions().first(); } } QAction *emptyAct = new QAction(this); m_toolBar->addAction(emptyAct); } QToolBar *NavigateBar::createNavToolBar(QWidget *parent) { QFileInfo info(m_filePath); QStringList paths = QDir::fromNativeSeparators(info.filePath()).split("/"); if (paths.size() < 2) { return 0; } QString head = "<style> a{text-decoration: none; color:darkgray;} </style>"; QToolBar *toolBar = new QToolBar(parent); toolBar->setIconSize(LiteApi::getToolBarIconSize(m_liteApp)); QString last; #ifdef Q_OS_WIN last = paths[0]; #endif for (int i = 1; i < paths.size(); i++) { QString name = paths[i]; #ifdef Q_OS_WIN if (i == 1) { name = paths[0]+"\\"+paths[1]; } #endif QString path = last+"/"+paths[i]; last = path; if (i != paths.size()-1) { name += ">"; } QString text = QString("<a href=\"%1\">%2</a>").arg(escaped(path)).arg(escaped(name)); QLabel *lbl = new QLabel; lbl->setText(head+text); toolBar->addWidget(lbl); connect(lbl,SIGNAL(linkActivated(QString)),this,SLOT(quickPathLinkActivated(QString))); } QAction *empytAct = new QAction(toolBar); toolBar->addAction(empytAct); return toolBar; } void NavigateBar::pathLinkActivated(const QString &path) { QString dirpath = QFileInfo(path).absolutePath(); LiteApi::IQuickOpenManager *mgr = LiteApi::getQuickOpenManager(m_liteApp); if (mgr) { LiteApi::IQuickOpenFileSystem *fileSystem = LiteApi::getQuickOpenFileSystem(mgr); if (fileSystem) { fileSystem->setRootPath(dirpath); fileSystem->setPlaceholderText(QString(tr("Browser Files in %1").arg(QDir::toNativeSeparators(dirpath)))); mgr->setCurrentFilter(fileSystem); mgr->modelView()->setRootIndex(fileSystem->rootIndex()); QModelIndex index = fileSystem->indexForPath(path); mgr->modelView()->setCurrentIndex(index); mgr->setTempToolBar(this->createNavToolBar(mgr->widget())); QRect rc = m_toolBar->actionGeometry(m_navHeadAct); QPoint pt = m_toolBar->mapToGlobal(rc.topLeft()); mgr->showPopup(&pt); mgr->modelView()->scrollTo(index); return; } } } void NavigateBar::quickPathLinkActivated(const QString &path) { QString dirpath = QFileInfo(path).absolutePath(); LiteApi::IQuickOpenManager *mgr = LiteApi::getQuickOpenManager(m_liteApp); if (mgr) { LiteApi::IQuickOpenFileSystem *fileSystem = LiteApi::getQuickOpenFileSystem(mgr); if (fileSystem) { fileSystem->setRootPath(dirpath); fileSystem->setPlaceholderText(QString(tr("Browser Files in %1").arg(QDir::toNativeSeparators(dirpath)))); mgr->setCurrentFilter(fileSystem); mgr->modelView()->setRootIndex(fileSystem->rootIndex()); QModelIndex index = fileSystem->indexForPath(path); mgr->modelView()->setCurrentIndex(index); } } }
6,434
C++
.cpp
172
31.040698
118
0.622919
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,525
processex.cpp
visualfc_liteide/liteidex/src/utils/processex/processex.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: processex.cpp // Creator: visualfc <visualfc@gmail.com> #include "processex.h" #include <QMap> #ifndef Q_OS_WIN #include <signal.h> #endif #ifdef Q_OS_WIN #include <windows.h> #include <shellapi.h> #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 QString ProcessEx::exitStatusText(int code, QProcess::ExitStatus status) { static QString text; switch (status) { case QProcess::NormalExit: text = tr("process exited with code %1").arg(code); break; case QProcess::CrashExit: text = tr("process crashed or was terminated"); break; default: text = tr("process exited with an unknown status"); } return text; } QString ProcessEx::processErrorText(QProcess::ProcessError code) { static QString text; switch (code) { case QProcess::FailedToStart: text = tr("process failed to start"); break; case QProcess::Crashed: text = tr("process crashed or was terminated while running"); break; case QProcess::Timedout: text = tr("timed out waiting for process"); break; case QProcess::ReadError: text = tr("couldn't read from the process"); break; case QProcess::WriteError: text = tr("couldn't write to the process"); break; case QProcess::UnknownError: default: text = tr("an unknown error occurred"); } return text; } ProcessEx::ProcessEx(QObject *parent) : Process(parent), m_suppressFinish(false) { connect(this,SIGNAL(stateChanged(QProcess::ProcessState)),this,SLOT(slotStateChanged(QProcess::ProcessState))); connect(this,SIGNAL(readyReadStandardOutput()),this,SLOT(slotReadOutput())); connect(this,SIGNAL(readyReadStandardError()),this,SLOT(slotReadError())); connect(this,SIGNAL(error(QProcess::ProcessError)),this,SLOT(slotError(QProcess::ProcessError))); connect(this,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(slotFinished(int,QProcess::ExitStatus))); } void ProcessEx::slotStateChanged(QProcess::ProcessState newState) { if (newState == QProcess::Starting) { m_suppressFinish = false; } } void ProcessEx::slotError(QProcess::ProcessError error) { switch (error) { // Suppress only if the process has stopped default: case QProcess::UnknownError: if (this->isRunning()) break; // Fall through // Always suppress case QProcess::FailedToStart: case QProcess::Crashed: m_suppressFinish = true; emit extFinish(true,-1,this->processErrorText(error)); break; // Never suppress case QProcess::Timedout: case QProcess::WriteError: case QProcess::ReadError: break; } } void ProcessEx::slotFinished(int code,QProcess::ExitStatus status) { if (!m_suppressFinish) { emit extFinish(false,code,this->exitStatusText(code,status)); } } void ProcessEx::slotReadOutput() { emit extOutput(this->readAllStandardOutput(),false); } void ProcessEx::slotReadError() { emit extOutput(this->readAllStandardError(),true); } Process::Process(QObject *parent) : QProcess(parent) { } Process::~Process() { stop(1); } bool Process::isRunning() const { return this->state() == QProcess::Running; } bool Process::isStop() const { return this->state() == QProcess::NotRunning; } void Process::stop(int ms) { if (isStop()) { return; } terminate(); closeReadChannel(QProcess::StandardOutput); closeReadChannel(QProcess::StandardError); if (!waitForFinished(ms)) { kill(); } } void Process::stopAndWait(int termMs, int finishMs) { stop(termMs); waitForFinished(finishMs); } void Process::startEx(const QString &cmd, const QStringList &args) { this->startEx(cmd,args.join(" ")); } void Process::startEx(const QString &cmd, const QString &args) { #ifdef Q_OS_WIN this->setNativeArguments(args); if (cmd.contains(' ')) { this->start("\""+cmd+"\""); } else { this->start(cmd); } #else if (cmd.contains(' ')) { this->start("\""+cmd+"\" "+args); } else { this->start(cmd+" "+args); } #endif } bool Process::startDetachedExAndHide(const QString &cmd, const QStringList &args) { #ifdef Q_OS_WIN return (intptr_t)ShellExecuteW(NULL, NULL, (LPCWSTR)cmd.toStdWString().data(), (LPCWSTR)args.join(" ").toStdWString().data(), NULL, SW_HIDE) > 32; #else return QProcess::startDetached(cmd, args); #endif } bool Process::startDetachedEx(const QString &cmd, const QStringList &args, const QString &workDir) { #ifdef Q_OS_WIN return (intptr_t)ShellExecuteW(NULL, L"open", (LPCWSTR)cmd.toStdWString().data(), (LPCWSTR)args.join(" ").toStdWString().data(), (LPCWSTR)workDir.toStdWString().data(), SW_SHOW) > 32; #else return QProcess::startDetached(cmd, args, workDir); #endif } void Process::setUserData(int id, const QVariant &data) { m_idVarMap.insert(id,data); } QVariant Process::userData(int id) const { return m_idVarMap.value(id); } #ifdef Q_OS_WIN void SendProcessCtrlC(QProcess */*process*/) { } #else void SendProcessCtrlC(QProcess *process) { if (process->pid() <= 0) { return; } kill(process->pid(),SIGINT); } #endif LiteProcess::LiteProcess(LiteApi::IApplication *app, QObject *parent) : QProcess(parent), m_liteApp(app), m_useCtrlC(false) { } void LiteProcess::setUseCtrlC(bool use) { m_useCtrlC = use; } void LiteProcess::startEx(const QString &cmd, const QString &args) { #ifdef Q_OS_WIN if (m_useCtrlC) { QString stub = m_liteApp->applicationPath()+"/liteide_ctrlc_stub.exe"; QString stubArg = cmd+" "+args; this->setNativeArguments(stubArg); this->start("\""+stub+"\""); } else { this->setNativeArguments(args); this->start(cmd); } #else this->start(cmd+" "+args); #endif } #ifdef Q_OS_WIN static BOOL sendMessage(UINT message, HWND hwnd, LPARAM lParam) { DWORD dwProcessID; GetWindowThreadProcessId(hwnd, &dwProcessID); if ((DWORD)lParam == dwProcessID) { SendNotifyMessage(hwnd, message, 0, 0); return FALSE; } return TRUE; } BOOL CALLBACK sendShutDownMessageToAllWindowsOfProcess_enumWnd(HWND hwnd, LPARAM lParam) { static UINT uiShutDownMessage = RegisterWindowMessage(L"liteide_ctrlcstub_shutdown"); return sendMessage(uiShutDownMessage, hwnd, lParam); } BOOL CALLBACK sendInterruptMessageToAllWindowsOfProcess_enumWnd(HWND hwnd, LPARAM lParam) { static UINT uiInterruptMessage = RegisterWindowMessage(L"liteide_ctrlcstub_interrupt"); return sendMessage(uiInterruptMessage, hwnd, lParam); } #endif void LiteProcess::interrupt() { if (m_useCtrlC) { Q_PID processId = this->pid(); #ifdef Q_OS_WIN if (processId) { EnumWindows(sendInterruptMessageToAllWindowsOfProcess_enumWnd, processId->dwProcessId); } #else if (processId > 0) { ::kill(processId,SIGINT); } #endif } } void LiteProcess::terminate() { if (m_useCtrlC) { Q_PID processId = this->pid(); #ifdef Q_OS_WIN if (processId) { EnumWindows(sendShutDownMessageToAllWindowsOfProcess_enumWnd, processId->dwProcessId); } #else if (processId > 0) { ::kill(processId,SIGINT); } #endif } else { QProcess::terminate(); } } bool LiteProcess::isStop() const { return this->state() == QProcess::NotRunning; }
8,756
C++
.cpp
304
24.875
187
0.680418
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,526
htmlutil.cpp
visualfc_liteide/liteidex/src/utils/htmlutil/htmlutil.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: htmlutil.cpp // Creator: visualfc <visualfc@gmail.com> #include "htmlutil.h" #include <QStringList> #include <QDomDocument> #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 HtmlUtil::HtmlUtil() { } /* <!--{ "Title": "Getting Started", "Path": "/install/" }--> */ QString HtmlUtil::findTitle(const QString &data) { QRegExp reg("<!--([\\w\\s\\n{}\":/,]*)-->"); int n = reg.indexIn(data); if (n < 0) { return QString(); } QRegExp reg1("Title[\"\\s:]*([\\w\\s]*)[\\s\"]*"); n = reg1.indexIn(reg.cap(1)); if (n < 0) { return QString(); } return reg1.cap(1); } QString HtmlUtil::docToNavdoc(const QString &data, QString &header, QString &nav) { QDomDocument doc; QStringList srcLines = data.split("\n"); QStringList navLines; QStringList dstLines; navLines.append("<table class=\"unruled\"><tbody><tr><td class=\"first\"><dl>"); int index = 0; if (srcLines.length() >= 1) { header = findTitle(data); if (header.isEmpty()) { //<!-- How to Write Go Code --> QString line = srcLines.at(0); QRegExp reg("<!--([\\w\\s]*)-->"); if (reg.indexIn(line) >= 0) { header = reg.cap(1).trimmed(); } } } foreach(QString source, srcLines) { QString line = source.trimmed(); index++; if (line.length() >= 10) { if (line.left(3) == "<h2") { if (doc.setContent(line)) { QDomElement e = doc.firstChildElement("h2"); if (!e.isNull()) { QString text = e.text(); QString id = e.attribute("id"); if (id.isEmpty()) { id = QString("tmp_%1").arg(index); e.setAttribute("id",id); } //<span class="navtop"><a href="#top">[Top]</a></span> QDomElement span = doc.createElement("span"); span.setAttribute("class","navtop"); QDomElement a = doc.createElement("a"); a.setAttribute("href","#top"); QDomText top = doc.createTextNode("[Top]"); a.appendChild(top); span.appendChild(a); e.appendChild(span); source = doc.toString(); navLines << QString("<dt><a href=\"#%1\">%2</a></dt>").arg(id).arg(text); } } } else if (line.left(3) == "<h3") { if (doc.setContent(line)) { QDomElement e = doc.firstChildElement("h3"); if (!e.isNull()) { QString text = e.text(); QString id = e.attribute("id"); if (id.isEmpty()) { id = QString("tmp_%1").arg(index); e.setAttribute("id",id); } source = doc.toString(); navLines << QString("<dd><a href=\"#%1\">%2</a></dd>").arg(id).arg(text); } } } } dstLines.append(source); } navLines.append("</dl></td><td><dl></dl></td><tr></tbody></table>"); nav = navLines.join(""); return dstLines.join("\n"); }
4,772
C++
.cpp
127
27.685039
97
0.498491
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,528
varianthelper.cpp
visualfc_liteide/liteidex/src/utils/dlvclient/varianthelper.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: varianthelper.cpp // Creator: visualfc <visualfc@gmail.com> #include "varianthelper.h" #include <QString> #include <QVariant> #include <QMap> #include <QMetaProperty> #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 QMap<QString,QVariant> VariantHelper::ObjectToVariantMap( const QObject* object, const QStringList& ignoredProperties) { QMap<QString,QVariant> result; const QMetaObject *metaobject = object->metaObject(); int count = metaobject->propertyCount(); for (int i=0; i<count; ++i) { QMetaProperty metaproperty = metaobject->property(i); const char *name = metaproperty.name(); if (ignoredProperties.contains(QLatin1String(name)) || (!metaproperty.isReadable())) continue; QVariant value = object->property(name); result[QLatin1String(name)] = value; } return result; } void VariantHelper::VarintMapToObject(const QMap<QString, QVariant> &variantMap, QObject *object) { const QMetaObject *metaobject = object->metaObject(); QMap<QString,QVariant>::const_iterator iter; for (iter = variantMap.constBegin(); iter != variantMap.constEnd(); ++iter) { object->setProperty(iter.key().toLatin1(),iter.value()); int pIdx = metaobject->indexOfProperty( iter.key().toLatin1() ); if ( pIdx < 0 ) { qDebug() << "waring not find property key" << iter.key(); object->setProperty(iter.key().toLatin1(),iter.value()); continue; } QMetaProperty metaproperty = metaobject->property( pIdx ); QVariant::Type type = metaproperty.type(); QVariant v( iter.value() ); if ( v.canConvert( type ) ) { v.convert( type ); metaproperty.write( object, v ); } else if (QString(QLatin1String("QVariant")).compare(QLatin1String(metaproperty.typeName())) == 0) { metaproperty.write( object, v ); } } }
3,309
C++
.cpp
77
37.311688
110
0.643925
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,529
dlvclient.cpp
visualfc_liteide/liteidex/src/utils/dlvclient/dlvclient.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: dlvclient.cpp // Creator: visualfc <visualfc@gmail.com> #include "dlvclient.h" #include <QTcpSocket> #include <QHostAddress> #include <QUrl> #include <QDebug> #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) #include <qjsondocument.h> #else #include "qjsonrpc/src/json/qjson_export.h" #include "qjsonrpc/src/json/qjsondocument.h" #endif #include "qjsonrpc/src/qjsonrpcservicereply.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 DlvClient::DlvClient(QObject *parent) : QObject(parent) { m_isCommandBlock = false; m_callTimeout = 5000; } bool DlvClient::IsConnect() const { return !m_dlv.isNull(); } QString DlvClient::Address() const { return m_addr; } bool DlvClient::Connect(const QString &service) { QUrl serviceUrl = QUrl::fromUserInput(service); QHostAddress serviceAddress(serviceUrl.host()); QTcpSocket *tcpSocket = new QTcpSocket(this); int servicePort = serviceUrl.port() ? serviceUrl.port() : 5555; tcpSocket->connectToHost(serviceAddress, servicePort); if (!tcpSocket->waitForConnected(5000)) { qDebug("could not connect to host at %s:%d", serviceUrl.host().toLocal8Bit().data(), servicePort); return false; } m_addr = service; m_isCommandBlock = false; m_dlv.reset(new QJsonRpcSocket(tcpSocket,this)); return true; } void DlvClient::SetCallTimeout(int timeout) { m_callTimeout = timeout; } int DlvClient::CallTimeout() const { return m_callTimeout; } int DlvClient::ProcessPid() const { ProcessPidIn in; ProcessPidOut out; callBlocked("ProcessPid",&in,&out); return out.Pid; } QDateTime DlvClient::LastModified() const { LastModifiedIn in; LastModifiedOut out; callBlocked("LastModified",&in,&out); return out.Time; } bool DlvClient::Detach() const { DetachIn in; in.Kill = true; DetachOut out; return callBlocked("Detach",&in,&out); } QList<DiscardedBreakpoint> DlvClient::Restart() const { RestartIn in; RestartOut out; callBlocked("Restart",&in,&out); return out.DiscardedBreakpoints; } QList<DiscardedBreakpoint> DlvClient::RestartFrom(const QString &pos) const { RestartIn in; in.Position = pos; RestartOut out; callBlocked("Restart",&in,&out); return out.DiscardedBreakpoints; } DebuggerState DlvClient::Next() const { DebuggerCommand in("next"); CommandOut out; callBlocked("Command",&in,&out); return out.State; } DebuggerState DlvClient::Step() const { DebuggerCommand in("step"); CommandOut out; callBlocked("Command",&in,&out); return out.State; } DebuggerState DlvClient::StepOut() const { DebuggerCommand in("stepOut"); CommandOut out; callBlocked("Command",&in,&out); return out.State; } DebuggerState DlvClient::StepInstruction() const { DebuggerCommand in("stepInstruction"); CommandOut out; callBlocked("Command",&in,&out); return out.State; } DebuggerState DlvClient::SwitchThread(int threadID) const { DebuggerCommand in("switchThread"); in.ThreadID = threadID; CommandOut out; callBlocked("Command",&in,&out); return out.State; } DebuggerState DlvClient::SwitchGoroutine(int goroutineID) const { DebuggerCommand in("switchGoroutine"); in.GoroutineID = goroutineID; CommandOut out; callBlocked("Command",&in,&out); return out.State; } DebuggerState DlvClient::Halt() const { DebuggerCommand in("halt"); CommandOut out; callBlocked("Command",&in,&out); return out.State; } DebuggerState DlvClient::Continue() const { DebuggerCommand in("continue"); CommandOut out; callBlocked("Command",&in,&out); return out.State; } DebuggerState DlvClient::Rewind() const { DebuggerCommand in("rewind"); CommandOut out; callBlocked("Command",&in,&out); return out.State; } bool DlvClient::CallNext() { DebuggerCommand cmd("next"); return callDebuggerCommand(cmd); } bool DlvClient::CallStep() { DebuggerCommand cmd("step"); return callDebuggerCommand(cmd); } bool DlvClient::CallStepOut() { DebuggerCommand cmd("stepOut"); return callDebuggerCommand(cmd); } bool DlvClient::CallStepInstruction() { DebuggerCommand cmd("stepInstruction"); return callDebuggerCommand(cmd); } bool DlvClient::CallSwitchThread(int threadID) { DebuggerCommand cmd("switchThread"); cmd.ThreadID = threadID; return callDebuggerCommand(cmd); } bool DlvClient::CallSwitchGoroutine(int goroutineID) { DebuggerCommand cmd("switchGoroutine"); cmd.GoroutineID = goroutineID; return callDebuggerCommand(cmd); } bool DlvClient::CallHalt() { DebuggerCommand cmd("halt"); return callDebuggerCommand(cmd); } bool DlvClient::CallContinue() { DebuggerCommand cmd("continue"); return callDebuggerCommand(cmd); } bool DlvClient::CallRewind() { DebuggerCommand cmd("rewind"); return callDebuggerCommand(cmd); } BreakpointPointer DlvClient::CreateBreakpoint(const Breakpoint &bp) const { CreateBreakpointIn in; in.Breakpoint = bp; CreateBreakpointOut out; callBlocked("CreateBreakpoint",&in,&out); return out.pBreakpoint; } BreakpointPointer DlvClient::CreateBreakpointByFuncName(const QString &funcName) const { Breakpoint bp; bp.FunctionName = funcName; return CreateBreakpoint(bp); } BreakpointPointer DlvClient::GetBreakpoint(int id) const { GetBreakpointIn in; in.Id = id; GetBreakpointOut out; callBlocked("GetBreakpoint",&in,&out); return out.pBreakpoint; } BreakpointPointer DlvClient::GetBreakpointByName(const QString &name) const { GetBreakpointIn in; in.Name = name; GetBreakpointOut out; callBlocked("GetBreakpoint",&in,&out); return out.pBreakpoint; } QList<Breakpoint> DlvClient::ListBreakpoints() const { ListBreakpointsIn in; ListBreakpointsOut out; callBlocked("ListBreakpoints",&in,&out); return out.Breakpoints; } BreakpointPointer DlvClient::ClearBreakpoint(int id) const { CleartBreakpointIn in; in.Id = id; ClearBreakpointOut out; callBlocked("ClearBreakpoint",&in,&out); return out.pBreakpoint; } BreakpointPointer DlvClient::ClearBreakpointByName(const QString &name) const { CleartBreakpointIn in; in.Name = name; ClearBreakpointOut out; callBlocked("ClearBreakpoint",&in,&out); return out.pBreakpoint; } bool DlvClient::AmendBreakpoint(const Breakpoint &bp) const { AmendBreakpointIn in; in.Breakpoint = bp; AmendBreakpointOut out; return callBlocked("AmendBreakpoint",&in,&out); } bool DlvClient::CancelNext() const { CancelNextIn in; CancelNextOut out; return callBlocked("CancelNext",&in,&out); } QList<Thread> DlvClient::ListThreads() const { ListThreadsIn in; ListThreadsOut out; callBlocked("ListThreads",&in,&out); return out.Threads; } ThreadPointer DlvClient::GetThread(int id) const { GetThreadIn in; in.Id = id; GetThreadOut out; callBlocked("GetThread",&in,&out); return out.pThread; } VariablePointer DlvClient::EvalVariable(const EvalScope &scope, const QString &expr, const LoadConfig &cfg) const { EvalIn in; in.Scope = scope; in.Expr = expr; in.Cfg = cfg; EvalOut out; callBlocked("Eval",&in,&out); return out.pVariable; } bool DlvClient::SetVariable(const EvalScope &scope, const QString &symbol, const QString &value) { SetIn in; in.Scope = scope; in.Symbol = symbol; in.Value = value; SetOut out; return callBlocked("Set",&in,&out); } QStringList DlvClient::ListSources(const QString &filter) { ListSourcesIn in; in.Filter = filter; ListSourcesOut out; callBlocked("ListSources",&in,&out); return out.Sources; } QStringList DlvClient::ListFunctions(const QString &filter) { ListFunctionsIn in; in.Filter = filter; ListFunctionsOut out; callBlocked("ListFunctions",&in,&out); return out.Funcs; } DebuggerState DlvClient::GetState() const { StateIn in; StateOut out; callBlocked("State",&in,&out); return out.State; } QStringList DlvClient::ListTypes(const QString &filter) const { ListTypesIn in; in.Filter = filter; ListTypesOut out; callBlocked("ListTypes",&in,&out); return out.Types; } QList<Variable> DlvClient::ListPackageVariables(const QString &filter, const LoadConfig &cfg) const { ListPackageVarsIn in; in.Filter = filter; in.Cfg = cfg; ListPackageVarsOut out; callBlocked("ListPackageVars",&in,&out); return out.Variables; } QList<Variable> DlvClient::ListLocalVariables(const EvalScope &scope, const LoadConfig &cfg) const { ListLocalVarsIn in; in.Scope = scope; in.Cfg = cfg; ListLocalVarsOut out; callBlocked("ListLocalVars",&in,&out); return out.Variables; } QList<Register> DlvClient::ListRegisters(int threadID, bool includeFp) const { ListRegistersIn in; in.ThreadID = threadID; in.IncludeFp = includeFp; ListRegistersOut out; callBlocked("ListRegisters",&in,&out); return out.Regs; } QList<Variable> DlvClient::ListFunctionArgs(const EvalScope &scope, const LoadConfig &cfg) const { ListFunctionArgsIn in; in.Scope = scope; in.Cfg = cfg; ListFunctionArgsOut out; callBlocked("ListFunctionArgs",&in,&out); return out.Variables; } QList<Goroutine> DlvClient::ListGoroutines() const { ListGoroutinesIn in; ListGoroutinesOut out; callBlocked("ListGoroutines",&in,&out); return out.Goroutines; } QList<Stackframe> DlvClient::Stacktrace(int goroutineId, int depth, const LoadConfig &cfg) const { StacktraceIn in; in.Id = goroutineId; in.Depth = depth; in.Full = true; in.Cfg = cfg; StacktraceOut out; callBlocked("Stacktrace",&in,&out); return out.Locations; } bool DlvClient::AttachedToExistingProcess() const { AttachedToExistingProcessIn in; AttachedToExistingProcessOut out; callBlocked("AttachedToExistingProcess",&in,&out); return out.Answer; } QList<Location> DlvClient::FindLocation(const EvalScope &scope, const QString &loc) const { FindLocationIn in; in.Scope= scope; in.Loc = loc; FindLocationOut out; callBlocked("FindLocation",&in,&out); return out.Locations; } QList<AsmInstruction> DlvClient::DisassembleRange(const EvalScope &scope, quint64 startPC, quint64 endPC, AssemblyFlavour flavour) const { DisassembleIn in; in.Scope = scope; in.StartPC = startPC; in.EndPC = endPC; in.Flavour = flavour; DisassembleOut out; callBlocked("Disassemble",&in,&out); return out.Disassemble; } QList<AsmInstruction> DlvClient::DisassemblePC(const EvalScope &scope, quint64 pc, AssemblyFlavour flavour) const { DisassembleIn in; in.Scope = scope; in.StartPC = pc; in.EndPC = 0; in.Flavour = flavour; DisassembleOut out; callBlocked("Disassemble",&in,&out); return out.Disassemble; } bool DlvClient::Recorded() const { RecordedIn in; RecordedOut out; callBlocked("Recorded",&in,&out); return out.Recorded; } QString DlvClient::TraceDirectory() const { RecordedIn in; RecordedOut out; callBlocked("Recorded",&in,&out); return out.TraceDirectory; } int DlvClient::Checkpoint(const QString &where) const { CheckpointIn in; in.Where = where; CheckpointOut out; callBlocked("Checkpoint",&in,&out); return out.ID; } QList<struct Checkpoint> DlvClient::ListCheckpoints() const { ListCheckpointsIn in; ListCheckpointsOut out; callBlocked("ListCheckpoints",&in,&out); return out.Checkpoints; } bool DlvClient::ClearCheckpoint(int id) const { ClearCheckpointIn in; in.ID = id; ClearBreakpointOut out; return callBlocked("ClearCheckpoint",&in,&out); } int DlvClient::GetAPIVersion() const { GetVersionIn in; GetVersionOut out; callBlocked("GetVersion",&in,&out); return out.APIVersion; } QString DlvClient::GetDelveVersion() const { GetVersionIn in; GetVersionOut out; callBlocked("GetVersion",&in,&out); return out.DelveVersion; } bool DlvClient::SetAPIVersion(int version) const { SetAPIVersionIn in; in.APIVersion = version; SetAPIVersionOut out; return callBlocked("SetApiVersion",&in,&out); } QVariant DlvClient::LastJsonData() const { return m_lastJsonData; } bool DlvClient::callCommand(const QString &cmd) { DebuggerCommand dc(cmd); return callDebuggerCommand(dc); } bool DlvClient::callDebuggerCommand(const DebuggerCommand &cmd) { if (m_isCommandBlock) { return false; } m_isCommandBlock = true; m_lastCommand = cmd; QVariantMap param; cmd.toMap(param); QJsonRpcMessage request = QJsonRpcMessage::createRequest("RPCServer.Command", QJsonValue::fromVariant(param)); QJsonRpcServiceReply *reply = m_dlv->sendMessage(request); if (!reply) { m_isCommandBlock = false; return false; } connect(reply,SIGNAL(finished()),this,SLOT(finishedCommandReply())); m_lastReply.reset(reply); return true; } bool DlvClient::isCommandBlocked() const { return m_isCommandBlock; } void DlvClient::finishedCommandReply() { m_isCommandBlock = false; QJsonRpcServiceReply *reply = (QJsonRpcServiceReply*)(sender()); m_lastJsonData = reply->response().result().toVariant(); if (reply->response().type() == QJsonRpcMessage::Error) { int code = reply->response().errorCode(); QString msg = reply->response().errorMessage(); if (msg.isEmpty()) { ResponseError resp; resp.fromMap(reply->response().toObject().toVariantMap()); msg = resp.error; } emit commandError(code,msg); } else { CommandOut out; QVariant data = reply->response().result().toVariant(); out.fromMap(data.toMap()); emit commandSuccess(m_lastCommand.Name,out.State,data.toMap()); } } bool DlvClient::callBlocked(const QString &method, const JsonDataIn *in, JsonDataOut *out) const { QVariantMap param; in->toMap(param); QJsonRpcMessage request = QJsonRpcMessage::createRequest("RPCServer."+method, QJsonValue::fromVariant(param)); QJsonRpcMessage response = m_dlv->sendMessageBlocking(request,m_callTimeout); if (response.type() == QJsonRpcMessage::Error) { //qDebug("error(%d): %s", response.errorCode(), response.errorMessage().toLocal8Bit().data());// return false; } m_lastJsonData = response.result().toVariant(); out->fromMap(response.result().toVariant().toMap()); return true; }
16,527
C++
.cpp
576
23.980903
137
0.693349
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,532
golangapi.cpp
visualfc_liteide/liteidex/src/utils/golangapi/golangapi.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: golangapi.cpp // Creator: visualfc <visualfc@gmail.com> #include "golangapi.h" #include <QFile> #include <QSet> #include <QRegExp> #include <QTextStream> #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 GolangApi::GolangApi(QObject *parent) : LiteApi::IGolangApi(parent) { } bool GolangApi::load(const QString &fileName) { QFile file(fileName); if (!file.open(QFile::ReadOnly)) { return false; } QTextStream stream(&file); stream.setCodec("utf-8"); return loadStream(&stream); } bool GolangApi::loadStream(QTextStream *stream) { m_pkgs.clear(); //pkg syscall (darwin-386), const TIOCSBRK ideal-int //var //pkg archive/tar, var ErrFieldTooLong error //const //pkg archive/tar, const TypeBlock ideal-char //pkg crypto/sha512, const BlockSize ideal-int //pkg archive/zip, const Deflate uint16 //type-const //pkg go/ast, type ObjKind int //pkg syscall, type Errno uintptr //pkg syscall (windows-amd64), const ECOMM Errno // func //pkg archive/tar, func NewReader(io.Reader) *Reader //pkg bytes, func FieldsFunc([]byte, func(rune) bool) [][]byte //type-var,method //pkg archive/tar, type Header struct //pkg archive/tar, type Header struct, AccessTime time.Time //pkg archive/tar, method (*Reader) Next() (*Header, error) //pkg archive/zip, method (*File) Open() (io.ReadCloser, error) //pkg bufio, method (ReadWriter) Available() int //type-interface //pkg container/heap, type Interface interface { Len, Less, Pop, Push, Swap } //pkg container/heap, type Interface interface, Len() int QRegExp reg("^pkg\\s([\\w\\-\\.\\/]+)(\\s\\(([\\w\\-]+)\\))?,\\s(\\w+)"); QRegExp regm("\\(\\*?([\\w\\-]+)\\)\\s*(\\w+)"); Package *lastPkg = 0; Type *lastType = 0; while (!stream->atEnd()) { QString line = stream->readLine(); int pos = reg.indexIn(line); if (pos < 0) { continue; } // 1 pkgname // 2 ? (system) // 3 ? system // 4 const|func|method|var|type QString pkgName = reg.cap(1); // if (!reg.cap(3).isEmpty()) { // pkg = reg.cap(2)+"."+pkg; // } if (!lastPkg || lastPkg->name != pkgName) { lastPkg = m_pkgs.findPackage(pkgName); if (!lastPkg) { lastPkg = new Package(pkgName); m_pkgs.pkgList.append(lastPkg); lastType = 0; } } QString right = line.mid(reg.cap().length()).trimmed(); QString flag = reg.cap(4); if (flag == "var") { ///pkg archive/tar, var ErrFieldTooLong error int pos = right.indexOf(" "); QString name = right.left(pos); if (pos != -1 && lastPkg->findValue(name) == 0) { lastPkg->valueList.append(new Value(VarApi,name,right.mid(pos+1))); } } else if (flag == "const") { //pkg syscall (windows-amd64), const ECOMM Errno int pos = right.indexOf(" "); QString name = right.left(pos); if (pos != -1 && lastPkg->findValue(name) == 0) { lastPkg->valueList.append(new Value(ConstApi,name,right.mid(pos+1))); } } else if (flag == "func") { //pkg bytes, func FieldsFunc([]byte, func(rune) bool) [][]byte int pos = right.indexOf("("); QString name = right.left(pos); if (pos != -1 && lastPkg->findValue(name) == 0) { lastPkg->valueList.append(new Value(FuncApi,name,right.mid(pos))); } } else if (flag == "method") { //pkg archive/tar, method (*Reader) Next() (*Header, error) //pkg archive/zip, method (*File) Open() (io.ReadCloser, error) //pkg bufio, method (ReadWriter) Available() int int pos = regm.indexIn(right); if (pos != -1) { QString typeName = regm.cap(1); QString name = regm.cap(2); QString exp = right.mid(regm.cap().length()).trimmed(); if (lastType == 0 || lastType->name != typeName || lastType->typ == StructApi) { lastType = lastPkg->findType(typeName); if (!lastType) { lastType = new Type(StructApi,typeName,"struct"); lastPkg->typeList.append(lastType); } } if (lastType->findValue(name) == 0) { lastType->valueList.append(new Value(TypeMethodApi,name,exp)); } } } else if (flag == "type") { //pkg go/ast, type ObjKind int //pkg archive/tar, type Header struct //pkg archive/tar, type Header struct, AccessTime time.Time //pkg container/heap, type Interface interface { Len, Less, Pop, Push, Swap } //pkg container/heap, type Interface interface, Len() int int pos = right.indexOf(" "); if (pos != -1) { QString typeName = right.left(pos); QString exp = right.mid(pos+1); if (exp == "struct") { lastType = lastPkg->findType(typeName); if (!lastType) { lastType = new Type(StructApi,typeName,exp); lastPkg->typeList.append(lastType); } } else if (exp.startsWith("struct,")) { QString last = exp.mid(7).trimmed(); int pos2 = last.indexOf(" "); if (pos2 != -1) { if (lastType == 0 || lastType->name != typeName || lastType->typ == StructApi) { lastType = lastPkg->findType(typeName); if (!lastType) { lastType = new Type(StructApi,typeName,"struct"); lastPkg->typeList.append(lastType); } } QString name = last.left(pos2); if (name == "embedded") { QString emName = last.mid(pos2+1); if (!lastType->embeddedList.contains(emName)) { lastType->embeddedList.append(emName); } } else if (lastType->findValue(name) == 0){ lastType->valueList.append(new Value(TypeVarApi,name,last.mid(pos2+1))); } } } else if (exp.startsWith("interface {")) { lastType = lastPkg->findType(typeName); if (!lastType) { lastType = new Type(InterfaceApi,typeName,exp); lastPkg->typeList.append(lastType); } } else if (exp.startsWith("interface,")) { QString last = exp.mid(10).trimmed(); int pos2 = last.indexOf("("); if (pos2 != -1) { if (lastType == 0 || lastType->name != typeName || lastType->typ == StructApi) { lastType = lastPkg->findType(typeName); if (!lastType) { lastType = new Type(InterfaceApi,typeName,"struct"); lastPkg->typeList.append(lastType); } } QString name = last.left(pos2); if (lastType->findValue(name) == 0) { lastType->valueList.append(new Value(TypeMethodApi,name,last.mid(pos2))); } } } else { lastType = lastPkg->findType(typeName); if (!lastType) { lastType = new Type(TypeApi,typeName,exp); lastPkg->typeList.append(lastType); } } } } } // QRegExp reg("^pkg\\s([\\w\\/]+)(\\s\\(([\\w-]+)\\))?,\\s(\\w+)(\\s\\(\\*?([\\w\\-]+)\\))?\\s(\\w+)"); // QRegExp reg2("^(\\w+),\\s+(\\w+)"); // while (!stream->atEnd()) { // QString line = stream->readLine().trimmed(); // // 1 pkgname // // 2 ? (system) // // 3 ? system // // 4 const|func|method|var|type // // 5 ? (method-type) // // 6 ? method-type // // 7 value // int pos = reg.indexIn(line); // if (pos != -1) { // QString typeVar; // int next = reg2.indexIn(line.right(line.length()-reg.cap().length()).trimmed()); // if (next != -1) { // typeVar = reg2.cap(2); // } // //qDebug() << reg.cap() << reg.captureCount(); // QString pkg = reg.cap(1); // //QString sys = reg.cap(3); // QString flag = reg.cap(4); // QString method_type = reg.cap(6); // QString value = reg.cap(7); // QMap<QString,Package>::iterator it = pkgMap.find(pkg); // if (it == pkgMap.end()) { // it = pkgMap.insert(pkg,Package()); // } // if (flag == "const") { // it->appendConst(value); // //constList.append(tag); // } else if (flag == "func") { // //funcList.append(tag); // it->appendFunc(value); // } else if (flag == "method") { // //methodList.append(tag); // it->appendTypeMethod(method_type,value); // } else if (flag == "type") { // //typeList.append(tag); // if (!typeVar.isEmpty()) { // it->appendTypeVar(value,typeVar); // } else { // it->insertType(value); // } // } else if (flag == "var") { // //varList.append(tag); // it->appendVar(value); // } // } // } return true; } QStringList GolangApi::all(int flag) const { QStringList finds; foreach(Package *pkg, m_pkgs.pkgList) { finds.append(pkg->name); finds.append(pkg->name+"."); foreach(Value *value, pkg->valueList) { if (flag & value->typ) { finds.append(pkg->name+"."+value->name); } } foreach(Type *type, pkg->typeList) { if (flag & type->typ) { QString name = pkg->name+"."+type->name; finds.append(name); name += "."; foreach (Value *value, type->valueList) { if (flag & value->typ) { finds.append(name+value->name); } } } } } return finds; } static QStringList findType(Package *pkg, const QString &typeName, const QString &v) { Type *typ = pkg->findType(typeName); if (typ) { Value *value = typ->findValue(v); if (value) { if (value->typ == TypeVarApi) { return QStringList() << pkg->name+"#"+typ->name << value->name; } else if (value->typ == TypeMethodApi ){ return QStringList() << pkg->name+"#"+typ->name+"."+value->name << value->name; } } else { foreach(QString embedded, typ->embeddedList) { QStringList find = findType(pkg,embedded,v); if (!find.isEmpty()) { return find; } } } } return QStringList(); } /* NullApi = 0, PkgApi = 0x0001, ConstApi = 0x0002, VarApi = 0x0004, StructApi = 0x0008, InterfaceApi = 0x0010, TypeApi = 0x0020, FuncApi = 0x0040, TypeMethodApi = 0x0080, TypeVarApi = 0x0100, */ static QString typeName(LiteApi::PkgApiEnum api) { switch(api) { case LiteApi::NullApi: break; case LiteApi::PkgApi: return "package"; case LiteApi::ConstApi: return "const"; case LiteApi::VarApi: return "var"; case LiteApi::StructApi: return "struct"; case LiteApi::InterfaceApi: return "interface"; case LiteApi::TypeApi: return "type"; case LiteApi::FuncApi: return "func"; case LiteApi::TypeMethodApi: return "method"; case LiteApi::TypeVarApi: return "field"; default: break; } return QString(); } QString GolangApi::findDocInfo(const QString &tag) const { int pos = tag.lastIndexOf("/"); QString pkgName = tag.left(pos+1); QStringList all = tag.mid(pos+1).split(".",qtSkipEmptyParts); if (all.size() >= 1) { pkgName += all.at(0); Package *pkg = m_pkgs.findPackage(pkgName); if (pkg) { if (all.size() == 1) { return "package "+pkgName; } else { Type *typ = pkg->findType(all.at(1)); if (typ) { if (all.size() == 2) { return QString("type %1 %2").arg(typ->name).arg(typeName(typ->typ)); } else { Value *value = typ->findValue(all.at(2)); if (value) { if (value->typ == TypeVarApi) { return QString("field %1 %2").arg(value->name).arg(value->exp); } else if (value->typ == TypeMethodApi ){ return QString("method %1%2").arg(value->name).arg(value->exp); } } } } else { Value *value = pkg->findValue(all.at(1)); if (value) { if (value->typ == VarApi) { return QString("var %1 %2").arg(value->name).arg(value->exp); } else if (value->typ == ConstApi) { return QString("const %1 %2").arg(value->name).arg(value->exp); } else if (value->typ == FuncApi) { return QString("func %1%2").arg(value->name).arg(value->exp); } } } } } } return QString(); } QStringList GolangApi::findDocUrl(const QString &tag) const { int pos = tag.lastIndexOf("/"); QString pkgName = tag.left(pos+1); QStringList all = tag.mid(pos+1).split(".",qtSkipEmptyParts); if (all.size() >= 1) { pkgName += all.at(0); Package *pkg = m_pkgs.findPackage(pkgName); if (pkg) { if (all.size() == 1) { return QStringList() << pkgName << pkgName; } else { Type *typ = pkg->findType(all.at(1)); if (typ) { if (all.size() == 2) { return QStringList() << pkgName+"#"+typ->name << typ->name; } else { return findType(pkg,typ->name,all.at(2)); } } else { Value *value = pkg->findValue(all.at(1)); if (value) { if (value->typ == VarApi) { return QStringList() << pkgName+"#variables" << value->name; } else if (value->typ == ConstApi) { if (value->exp.startsWith("ideal-") || value->exp == "uint16") { return QStringList() << pkgName+"#constants" << value->name; } else { return QStringList() << pkgName+"#"+value->exp << value->name; } } else if (value->typ == FuncApi) { return QStringList() << pkgName+"#"+value->name << value->name; } } } } } } return QStringList(); } PkgApiEnum GolangApi::findExp(const QString &tag, QString &exp) const { QStringList all = tag.split("."); if (all.size() >= 1) { Package *pkg = m_pkgs.findPackage(all.at(0)); if (pkg) { if (all.size() == 1) { exp = "package"; return pkg->typ; } else { Type *typ = pkg->findType(all.at(1)); if (typ) { if (all.size() == 2) { exp = typ->exp; return typ->typ; } else { Value *value = typ->findValue(all.at(2)); if (value) { exp = value->exp; return value->typ; } } } else { Value *value = pkg->findValue(all.at(1)); if (value) { exp = value->exp; return value->typ; } } } } } return NullApi; } GolangApiThread::GolangApiThread(QObject *parent) :QThread(parent) { m_api = new GolangApi(this); } GolangApiThread::~GolangApiThread() { if (this->isRunning()) { this->terminate(); } } void GolangApiThread::loadData(const QByteArray &data) { m_data = data; m_file.clear(); QThread::start(); } void GolangApiThread::loadFile(const QString &fileName) { m_file = fileName; QThread::start(); } LiteApi::IGolangApi* GolangApiThread::api() const { return m_api; } QStringList GolangApiThread::all() const { return m_all; } QByteArray GolangApiThread::data() const { return m_data; } void GolangApiThread::run() { if (!m_file.isEmpty()) { QFile f(m_file); if (!f.open(QFile::ReadOnly)) { return; } QTextStream s(&f); if (m_api->loadStream(&s)) { m_all = m_api->all(LiteApi::AllGolangApi); } } else { QTextStream s(&m_data); if (m_api->loadStream(&s)) { m_all = m_api->all(LiteApi::AllGolangApi); } } }
19,773
C++
.cpp
525
26.775238
107
0.478302
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,533
litetabwidget.cpp
visualfc_liteide/liteidex/src/utils/tabwidget/litetabwidget.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: litetabwidget.cpp // Creator: visualfc <visualfc@gmail.com> #include "litetabwidget.h" #include "liteapi/liteapi.h" #include <QTabBar> #include <QHBoxLayout> #include <QVBoxLayout> #include <QStackedLayout> #include <QStackedWidget> #include <QToolButton> #include <QPushButton> #include <QToolBar> #include <QAction> #include <QActionGroup> #include <QMenu> #include <QKeyEvent> #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 LiteTabWidget::LiteTabWidget(QSize iconSize, QObject *parent) : QObject(parent) { m_tabBar = new TabBar; m_tabBar->setExpanding(false); m_tabBar->setDocumentMode(true); m_tabBar->setDrawBase(false); m_tabBar->setUsesScrollButtons(true); m_tabBar->setMovable(true); m_tabBar->setSelectionBehaviorOnRemove(QTabBar::SelectPreviousTab); m_tabBarWidget = new QWidget; m_addTabAct = new QAction(QIcon("icon:images/addpage.png"),tr("Open a new tab"),this); m_listButton = new QToolButton; m_listButton->setToolTip(tr("List All Tabs")); m_listButton->setIcon(QIcon("icon:images/listpage.png")); m_listButton->setPopupMode(QToolButton::InstantPopup); m_listButton->setStyleSheet( "QToolButton::menu-indicator{image:none;}"); m_closeTabAct = new QAction(QIcon("icon:images/closepage.png"),tr("Close Tab"),this); // m_closeButton = new QToolButton; // m_closeButton->setDefaultAction(m_closeTabAct); QHBoxLayout *layout = new QHBoxLayout; layout->setMargin(0); layout->setSpacing(0); m_tabBar->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); m_tabToolBar = new QToolBar; m_tabToolBar->setObjectName("toolbar.tabs"); m_tabToolBar->setIconSize(iconSize); m_tabToolBar->addWidget(m_tabBar); //QWidget *dump = new QWidget; //dump->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); // m_tabToolBar->addWidget(dump); m_tabToolBar->addWidget(m_listButton); m_tabToolBar->addAction(m_closeTabAct); layout->addWidget(m_tabToolBar); m_tabBarWidget->setLayout(layout); m_stackedWidget = new QStackedWidget; connect(m_tabBar,SIGNAL(currentChanged(int)),this,SLOT(tabCurrentChanged(int))); connect(m_tabBar,SIGNAL(tabCloseRequested(int)),this,SIGNAL(tabCloseRequested(int))); connect(m_tabBar,SIGNAL(tabMoved(int,int)),this,SLOT(tabMoved(int,int))); connect(m_closeTabAct,SIGNAL(triggered()),this,SLOT(closeCurrentTab())); connect(m_addTabAct,SIGNAL(triggered()),this,SIGNAL(tabAddRequest())); m_listButton->setEnabled(false); } LiteTabWidget::~LiteTabWidget() { delete m_tabBarWidget; } void LiteTabWidget::closeCurrentTab() { int index = m_tabBar->currentIndex(); if (index < 0) { return; } emit tabCloseRequested(index); } int LiteTabWidget::addTab(QWidget *w,const QString & label, const QString &tip) { return addTab(w,QIcon(),label,tip); } int LiteTabWidget::addTab(QWidget *w,const QIcon & icon, const QString & label, const QString &tip) { if (!w) { return -1; } if (m_widgetList.size() == 0) { m_listButton->setEnabled(true); } int index = m_tabBar->addTab(icon,label); if (!tip.isEmpty()) { m_tabBar->setTabToolTip(index,tip); } m_stackedWidget->addWidget(w); m_widgetList.append(w); return index; } void LiteTabWidget::removeTab(int index) { if (index < 0) return; QWidget *w = widget(index); if (w) { m_stackedWidget->removeWidget(w); m_widgetList.removeAt(index); } if (m_widgetList.size() == 0) { m_listButton->setEnabled(false); } m_tabBar->removeTab(index); } QWidget *LiteTabWidget::currentWidget() { return m_stackedWidget->currentWidget(); } TabBar *LiteTabWidget::tabBar() { return m_tabBar; } int LiteTabWidget::count() const { return m_tabBar->count(); } int LiteTabWidget::currentIndex() const { return m_tabBar->currentIndex(); } QList<QWidget*> LiteTabWidget::widgetList() const { return m_widgetList; } QWidget *LiteTabWidget::stackedWidget() { return m_stackedWidget; } QWidget *LiteTabWidget::tabBarWidget() { return m_tabBarWidget; } void LiteTabWidget::setListMenu(QMenu *menu) { m_listButton->setMenu(menu); } void LiteTabWidget::setTabText(int index, const QString & text) { m_tabBar->setTabText(index,text); } QString LiteTabWidget::tabText(int index) const { return m_tabBar->tabText(index); } void LiteTabWidget::setTabToolTip(int index, const QString &tip) { m_tabBar->setTabToolTip(index,tip); } void LiteTabWidget::setTabData(int index, const QVariant &data) { m_tabBar->setTabData(index,data); } QVariant LiteTabWidget::tabData(int index) const { return m_tabBar->tabData(index); } int LiteTabWidget::indexOf(QWidget *w) { return m_widgetList.indexOf(w); } QWidget *LiteTabWidget::widget(int index) { return m_widgetList.value(index); } void LiteTabWidget::setCurrentWidget(QWidget *w) { int index = indexOf(w); if (index < 0) return; setCurrentIndex(index); } void LiteTabWidget::tabCurrentChanged(int index) { QWidget *w = m_widgetList.value(index); if (w) { m_stackedWidget->setCurrentWidget(w); } emit currentChanged(index); } void LiteTabWidget::setCurrentIndex(int index) { m_tabBar->setCurrentIndex(index); } void LiteTabWidget::tabMoved(int from, int to) { m_widgetList.swap(from,to); }
6,735
C++
.cpp
219
27.438356
99
0.705437
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,534
vtermwidget.cpp
visualfc_liteide/liteidex/src/utils/vterm/vtermwidget.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: vtermwidget.cpp // Creator: visualfc <visualfc@gmail.com> #include "vtermwidget.h" #include <QProcess> #include <QResizeEvent> #include <QScrollBar> #include <QDebug> #include <signal.h> #include <QKeySequence> #include <QClipboard> #include <QApplication> #include <QMenu> #include <QAction> //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 #if defined(Q_OS_MAC) # define TermControlModifier Qt::MetaModifier #else # define TermControlModifier Qt::ControlModifier #endif VTermWidget::VTermWidget(LiteApi::IApplication *app, const QFont &font, QWidget *parent) : VTermWidgetBase(app,24,80,font,parent),m_liteApp(app) { this->setContextMenuPolicy(Qt::CustomContextMenu); m_process = PtyQt::createPtyProcess(IPtyProcess::AutoPty); m_contextMenu = new QMenu(this); m_bStarted = false; m_copy = new QAction(tr("Copy"),this); m_copy->setShortcut(QKeySequence::Copy); m_copy->setShortcutContext(Qt::WidgetShortcut); m_paste = new QAction(tr("Paste"),this); m_paste->setShortcut(QKeySequence::Paste); m_paste->setShortcutContext(Qt::WidgetShortcut); m_selectAll = new QAction(tr("Select All"),this); m_selectAll->setShortcut(QKeySequence::SelectAll); m_selectAll->setShortcutContext(Qt::WidgetShortcut); m_contextMenu->addAction(m_copy); m_contextMenu->addAction(m_paste); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_selectAll); connect(m_process,SIGNAL(started()),this,SIGNAL(started())); connect(m_process,SIGNAL(exited()),this,SIGNAL(exited())); connect(this,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(contextMenuRequested(QPoint))); connect(m_copy,SIGNAL(triggered()),this,SLOT(copy())); connect(m_paste,SIGNAL(triggered()),this,SLOT(paste())); connect(m_selectAll,SIGNAL(triggered()),this,SLOT(selectAll())); } VTermWidget::~VTermWidget() { delete m_process; } bool VTermWidget::isAvailable() const { return m_process->isAvailable(); } void VTermWidget::start(const QString &program, const QStringList &arguments, const QString &workingDirectory, QStringList env) { m_bStarted = false; if (!m_process->isAvailable()) { qDebug() << "pty process invalid"; return; } bool b = m_process->startProcess(program,arguments,workingDirectory,env,qint16(m_cols),qint16(m_rows)); if (!b) { qDebug() << m_process->lastError(); return; } m_bStarted = true; connect(m_process->notifier(),SIGNAL(readyRead()),this,SLOT(readyRead())); connect(this,SIGNAL(sizeChanged(int,int)),this,SLOT(resizePty(int,int))); } bool VTermWidget::isStarted() const { return m_bStarted; } IPtyProcess *VTermWidget::process() const { return m_process; } void VTermWidget::copy() { QString text = selectedText(); if (!text.isEmpty()) { qApp->clipboard()->setText(text); } } void VTermWidget::paste() { QString text = qApp->clipboard()->text(); if (!text.isEmpty()) { m_process->write(text.toUtf8()); } } void VTermWidget::readyRead() { QByteArray data = m_process->readAll(); if (data.isEmpty()) { return; } this->inputWrite(data); } void VTermWidget::resizeEvent(QResizeEvent *e) { VTermWidgetBase::resizeEvent(e); } void VTermWidget::keyPressEvent(QKeyEvent *e) { if (!m_bStarted) { return; } //#ifdef Q_OS_WIN // WINDOWS copy & clear selection if (hasSelection() && (e == QKeySequence::Copy || e->key() == Qt::Key_Return)) { QString text = selectedText(); if (!text.isEmpty()) { qApp->clipboard()->setText(text); clearSelection(); return; } } //#else // if (e == QKeySequence::Copy) { // QString text = selectedText(); // if (!text.isEmpty()) { // qApp->clipboard()->setText(text); // } // return; // } //#endif else if (e == QKeySequence::Paste) { QString text = qApp->clipboard()->text(); if (!text.isEmpty()) { m_process->write(text.toUtf8()); } return; } else if (e == QKeySequence::SelectAll) { selectAll(); return; } if ((e->modifiers() & TermControlModifier) ) { QChar c(e->key()); char asciiVal = c.toUpper().toLatin1(); QByteArray array; if (asciiVal >= 0x41 && asciiVal <= 0x5f) { array.push_back(asciiVal-0x40); m_process->write(array); return; } } VTermWidgetBase::keyPressEvent(e); } void VTermWidget::resizePty(int rows, int cols) { if (!m_bStarted) { return; } m_process->resize(cols,rows); } void VTermWidget::contextMenuRequested(const QPoint &pt) { m_copy->setEnabled(this->hasSelection()); m_paste->setEnabled(!qApp->clipboard()->text().isEmpty()); QPoint globalPos = this->mapToGlobal(pt); m_contextMenu->popup(globalPos); } void VTermWidget::write_data(const char *buf, int len) { if (!m_bStarted) { return; } m_process->write(QByteArray(buf,len)); }
6,336
C++
.cpp
198
27.974747
144
0.657292
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,535
vtermwidgetbase.cpp
visualfc_liteide/liteidex/src/utils/vterm/vtermwidgetbase.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: vtermwidgetbase.cpp // Creator: visualfc <visualfc@gmail.com> #include "vtermwidgetbase.h" #include <QFontMetrics> #include <QPainter> #include <QScrollBar> #include <QPaintEvent> #include <QKeyEvent> #include <QMouseEvent> #include <QTimerEvent> #include <QInputMethodEvent> #include <QResizeEvent> #include <QTextLayout> #include <QVector> #include <QTextFormat> #include <QTextCharFormat> #include <QApplication> #include <QDebug> #include <QImage> //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 QColor toQColor(VTermColor *c, int alpha = 255) { return QColor(c->rgb.red, c->rgb.green, c->rgb.blue,alpha); }; bool attrs_is_equal(VTermScreenCellAttrs *a, VTermScreenCellAttrs *b) { return a->bold == b->bold && a->italic == b->italic && a->strike == b->strike && a->underline == b->underline; } int vterm_damage(VTermRect rect, void *user) { return static_cast<VTermWidgetBase*>(user)->vterm_damage(rect); } int vterm_moverect(VTermRect dest, VTermRect src, void *user) { return static_cast<VTermWidgetBase*>(user)->vterm_moverect(dest,src); } int vterm_movecursor(VTermPos pos, VTermPos oldpos, int visible, void *user) { return static_cast<VTermWidgetBase*>(user)->vterm_movecursor(pos,oldpos,visible); } int vterm_settermprop(VTermProp prop, VTermValue *val, void *user) { return static_cast<VTermWidgetBase*>(user)->vterm_settermprop(prop,val); } int vterm_bell(void *user) { return static_cast<VTermWidgetBase*>(user)->vterm_bell(); } int vterm_resize(int rows, int cols, void *user) { return static_cast<VTermWidgetBase*>(user)->vterm_resize(rows,cols); } int vterm_sb_pushline(int cols, const VTermScreenCell *cells, void *user) { return static_cast<VTermWidgetBase*>(user)->vterm_sb_pushline(cols,cells); } int vterm_sb_popline(int cols, VTermScreenCell *cells, void *user) { return static_cast<VTermWidgetBase*>(user)->vterm_sb_popline(cols,cells); } static VTermScreenCallbacks vterm_screen_callbacks = { vterm_damage, vterm_moverect, vterm_movecursor, vterm_settermprop, vterm_bell, vterm_resize, vterm_sb_pushline, vterm_sb_popline, }; VTermWidgetBase::VTermWidgetBase(LiteApi::IApplication *app, int rows, int cols, const QFont &font, QWidget *parent) : QAbstractScrollArea(parent), m_liteApp(app) { this->setAttribute(Qt::WA_InputMethodEnabled,true); this->setFont(font); m_sbListCapacity = 10000; m_rows = rows; m_cols = cols; m_lineBuf.resize(m_cols); m_cursor.row = -1; m_cursor.col = -1; m_cursor.visible = false; m_ignoreScroll = false; m_darkMode = false; m_leftButtonPress = false; m_vt = vterm_new(rows,cols); m_screen = vterm_obtain_screen(m_vt); m_state = vterm_obtain_state(m_vt); vterm_screen_set_callbacks(m_screen,&vterm_screen_callbacks,this); vterm_set_utf8(m_vt,1); vterm_screen_set_damage_merge(m_screen, VTERM_DAMAGE_SCROLL); vterm_screen_enable_altscreen(m_screen,1); // static QColor colorTable[] = { // QColor(0x00,0x00,0x00), QColor(0xB2,0x18,0x18), // Black, Red // QColor(0x18,0xB2,0x18), QColor(0xB2,0x68,0x18), // Green, Yellow // QColor(0x18,0x18,0xB2), QColor(0xB2,0x18,0xB2), // Blue, Magenta // QColor(0x18,0xB2,0xB2), QColor(0xB2,0xB2,0xB2), // Cyan, White // QColor(0x68,0x68,0x68), QColor(0xFF,0x54,0x54), // QColor(0x54,0xFF,0x54), QColor(0xFF,0xFF,0x54), // QColor(0x54,0x54,0xFF), QColor(0xFF,0x54,0xFF), // QColor(0x54,0xFF,0xFF), QColor(0xFF,0xFF,0xFF), // }; // for (int i = 0; i < 16; i++) { // QColor c = colorTable[i]; // setPaletteColor(i,c.red(),c.green(),c.blue()); // } memset(&m_empytCell,0,sizeof (VTermScreenCell)); m_empytCell.chars[0] = '\0'; m_empytCell.width = 1; setDarkMode(false); vterm_screen_reset(m_screen, 1); this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); m_ptOffset = QPoint(4,2); connect(this,SIGNAL(selectionChanged()),viewport(),SLOT(update())); } void VTermWidgetBase::setPaletteColor(int index, uint8_t r, uint8_t g, uint8_t b) { VTermColor col; vterm_color_rgb(&col, r, g, b); vterm_state_set_palette_color(m_state, index, &col); } VTermWidgetBase::~VTermWidgetBase() { for (int i = 0; i < m_sbList.size(); ++i) { delete m_sbList[i]; } m_sbList.clear(); vterm_free(m_vt); } int VTermWidgetBase::vterm_damage(VTermRect rect) { // QRect rc = mapVTermRectToRect(rect); // qDebug() << "vterm_damage1"<< rect.start_row << rect.end_row << rect.start_col << rect.end_col; // rect = mapRectToVTermRect(rc); // qDebug() << "vterm_damage2"<< rect.start_row << rect.end_row << rect.start_col << rect.end_col; this->clearSelection(); viewport()->update(mapVTermRectToRect(rect)); return 1; } QRect VTermWidgetBase::mapVTermRectToRect(VTermRect rect) { QPoint topLeft = QPoint( rect.start_col * m_cellSize.width(), rect.start_row * m_cellSize.height()); QPoint bottomRight = QPoint( (rect.end_col+1) * m_cellSize.width(), (rect.end_row+1) * m_cellSize.height()); topLeft += m_ptOffset; bottomRight += m_ptOffset; return QRect(topLeft,bottomRight); } VTermRect VTermWidgetBase::mapRectToVTermRect(QRect rect) { VTermRect rc; rect.translate(-m_ptOffset); rc.start_row = rect.top() /m_cellSize.height(); rc.end_row = rect.bottom()/m_cellSize.height()-1; rc.start_col = rect.left()/m_cellSize.width(); rc.end_col = rect.right()/m_cellSize.width()-1; return rc; } QPoint VTermWidgetBase::mapPointToCell(QPoint pt) { int row = (pt.y()-m_ptOffset.y())/m_cellSize.height(); int col = (pt.x()-m_ptOffset.x())/m_cellSize.width(); return QPoint(col,row+topVisibleRow()); } int VTermWidgetBase::scrollbackRowSize() const { return m_sbList.size(); } int VTermWidgetBase::termRows() const { return m_rows; } int VTermWidgetBase::termCols() const { return m_cols; } int VTermWidgetBase::topVisibleRow() const { return this->verticalScrollBar()->value()-m_sbList.size(); } int VTermWidgetBase::allRowSize() const { return m_sbList.size()+m_rows; } int VTermWidgetBase::startRow() const { return -scrollbackRowSize(); } int VTermWidgetBase::endRow() const { return m_rows; } QString VTermWidgetBase::getLineText(int row, int start_col, int end_col) const { VTermRect rc; rc.start_row = row; rc.end_row = row+1; rc.start_col = start_col; rc.end_col = end_col; size_t len = end_col-start_col; size_t n = _get_chars(m_screen,0, (void*)(&m_lineBuf[0]),len,rc); return QString::fromUcs4(&m_lineBuf[0],n); } QString VTermWidgetBase::selectedText() const { if (m_selection.isNull()) { return QString(); } if (m_selection.height() == 1) { return getLineText(m_selection.top(),m_selection.left(),m_selection.right()); } int start_row = m_selection.top(); int end_row = m_selection.bottom(); QStringList lines; lines.append(getLineText(start_row,m_selection.left(),m_cols)); for (int row = start_row+1; row < end_row; row++) { lines.append(getLineText(row,0,m_cols)); } lines.append(getLineText(end_row,0,m_selection.right())); #ifdef Q_OS_WIN QString sep = "\r\n"; #else QString sep = "\n"; #endif return lines.join(sep); } QRect VTermWidgetBase::selectedRect() const { return m_selection; } int VTermWidgetBase::vterm_moverect(VTermRect dest, VTermRect src) { // qDebug() << "vterm_moverect" << dest.start_row << dest.end_row << src.start_row << src.end_row; //viewport()->update(); QRegion re; re += mapVTermRectToRect(dest); re += mapVTermRectToRect(src); viewport()->update(re); return 1; } int VTermWidgetBase::vterm_movecursor(VTermPos pos, VTermPos oldpos, int visible) { // qDebug() << "vterm_movecursor" << pos.row << pos.col << oldpos.row << oldpos.col+1; m_cursor.row = pos.row; m_cursor.col = pos.col; m_cursor.visible = visible; QRegion re; VTermRect rc1 = {pos.row,pos.row,pos.col,pos.col+1}; re += mapVTermRectToRect(rc1); VTermRect rc2 = {oldpos.row,oldpos.row,oldpos.col,oldpos.col+1}; re += mapVTermRectToRect(rc2); viewport()->update(re); return 1; } /* VTERM_PROP_CURSORVISIBLE = 1, // bool VTERM_PROP_CURSORBLINK, // bool VTERM_PROP_ALTSCREEN, // bool VTERM_PROP_TITLE, // string VTERM_PROP_ICONNAME, // string VTERM_PROP_REVERSE, // bool VTERM_PROP_CURSORSHAPE, // number VTERM_PROP_MOUSE, // number */ int VTermWidgetBase::vterm_settermprop(VTermProp prop, VTermValue *val) { //qDebug() << "vterm_settermprop" << prop << val->number; switch (prop) { case VTERM_PROP_CURSORVISIBLE: m_cursor.visible = val->boolean; break; case VTERM_PROP_CURSORBLINK: m_cursor.blink = val->boolean; break; case VTERM_PROP_ALTSCREEN: m_altScreen = val->boolean; this->verticalScrollBar()->setEnabled(!m_altScreen); //this->verticalScrollBar()->setRange(0,m_altScreen ? 0 : m_sbList.size()); break; case VTERM_PROP_TITLE: emit titleChanged(QString::fromUtf8(val->string)); break; case VTERM_PROP_ICONNAME: emit iconNameChanged(QString::fromUtf8(val->string)); break; case VTERM_PROP_REVERSE: // qDebug() << "VTERM_PROP_REVERSE" << val->number; break; case VTERM_PROP_CURSORSHAPE: m_cursor.shape = val->number; break; case VTERM_PROP_MOUSE: m_propMouse = val->number; break; default: break; } //this->viewport()->update(); return 1; } int VTermWidgetBase::vterm_bell() { return 1; } int VTermWidgetBase::vterm_resize(int rows, int cols) { m_rows = rows; m_cols = cols; m_lineBuf.resize(m_cols); //qDebug() << "vterm_resize" << rows << cols << m_cellWidth << m_cellHeight; emit sizeChanged(m_rows,m_cols); return 1; } int VTermWidgetBase::vterm_sb_pushline(int cols, const VTermScreenCell *cells) { // qDebug() << "vterm_sb_pushline" << cols; ScrollbackLine *sb = new ScrollbackLine; sb->cols = cols; sb->cells.resize(cols); memcpy(&sb->cells[0],cells,sizeof(cells[0])*size_t(cols)); m_sbList.push_front(sb); while (m_sbList.size() > m_sbListCapacity) { m_sbList.pop_back(); } this->verticalScrollBar()->setRange(0,m_sbList.size()); this->verticalScrollBar()->setValue(this->verticalScrollBar()->maximum()); return 1; } int VTermWidgetBase::vterm_sb_popline(int cols, VTermScreenCell *cells) { // qDebug() << "vterm_sb_popline" << cols; if (m_sbList.isEmpty()) { return 0; } ScrollbackLine *sb = m_sbList.front(); int ncells = sb->cols; if (ncells > cols) { ncells = cols; } memcpy(cells, &sb->cells[0], sizeof(cells[0]) * size_t(ncells)); if (cols > ncells) { memset(&cells[ncells],0,sizeof(cells[0])*size_t(cols-ncells)); } for (int i = ncells; i < cols; ++i) { cells[i].width = 1; cells[i].fg = m_defaultFg; cells[i].bg = m_defaultBg; } m_sbList.pop_front(); delete sb; this->verticalScrollBar()->setRange(0,m_sbList.size()); return 1; } bool VTermWidgetBase::fetchCell(int row, int col, VTermScreenCell *cell) const { if (row < 0) { if (m_sbList.isEmpty()) { *cell = m_empytCell; return false; } ScrollbackLine *sb = m_sbList.at(-row-1); if (col < sb->cols) { *cell = sb->cells[col]; } else { *cell = m_empytCell; return false; } } else { vterm_screen_get_cell(m_screen,VTermPos{row,col},cell); } vterm_screen_convert_color_to_rgb(m_screen, &cell->fg); vterm_screen_convert_color_to_rgb(m_screen, &cell->bg); return true; } bool VTermWidgetBase::event(QEvent *e) { if (e->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(e); if (ke->key() == Qt::Key_Tab) { keyPressEvent(ke); return true; } } return QAbstractScrollArea::event(e); } void VTermWidgetBase::setFont(const QFont &fnt) { QFontMetrics fm(fnt); #ifdef Q_OS_WIN m_cellSize.setWidth(fm.averageCharWidth()); #else m_cellSize.setWidth(fm.maxWidth()); #endif m_cellSize.setHeight(fm.height()); QAbstractScrollArea::setFont(fnt); } void VTermWidgetBase::setTermSize(int rows, int cols) { m_ignoreScroll = true; vterm_set_size(m_vt,rows,cols); vterm_screen_flush_damage(m_screen); m_ignoreScroll = false; int width = rows*m_cellSize.width(); int height = cols*m_cellSize.height(); this->viewport()->setMinimumSize(width,height); } void VTermWidgetBase::inputWrite(const QByteArray &data) { vterm_input_write(m_vt,data.data(),size_t(data.length())); vterm_screen_flush_damage(m_screen); //this->viewport()->update(); } void VTermWidgetBase::inputKey(Qt::Key _key, Qt::KeyboardModifier _mod) { VTermModifier mod = qt_to_vtermModifier(_mod); VTermKey key = qt_to_vtermKey(_key,_mod & Qt::KeypadModifier); if (key != VTERM_KEY_NONE) { if (key == VTERM_KEY_ESCAPE) mod = VTERM_MOD_NONE; vterm_keyboard_key(m_vt, key, mod); } flushOutput(); } void VTermWidgetBase::setDarkMode(bool b) { m_darkMode = b; if (m_darkMode) { vterm_color_rgb(&m_defaultBg,30,30,30); vterm_color_rgb(&m_defaultFg,200,200,200); m_clrSelect = QColor(86,86,84); } else { vterm_color_rgb(&m_defaultBg,255,255,255); vterm_color_rgb(&m_defaultFg,0,0,0); m_clrSelect = QColor(179,215,253); } m_clrCursor = toQColor(&m_defaultFg,128); vterm_state_set_default_colors(m_state,&m_defaultFg,&m_defaultBg); m_empytCell.bg = m_defaultBg; m_empytCell.fg = m_defaultFg; vterm_screen_reset(m_screen, 1); } bool VTermWidgetBase::isDarkMode() const { return m_darkMode; } void VTermWidgetBase::paintEvent(QPaintEvent *e) { QPainter p(viewport()); p.fillRect(this->rect(),toQColor(&m_defaultBg)); // qDebug() << e->region().rectCount(); // for (QRegion::const_iterator it=e->region().begin(); it != e->region().end(); it++) { // //p.fillRect(*it,toQColor(&m_defaultBg)); // //p.setClipRect(*it); // VTermRect rc = qrect_to_vtermrect(*it); // if (rc.end_row == rc.start_row) { // rc.end_row++; // } // qDebug() << "update" << rc.start_row << rc.end_row << rc.start_col << rc.end_col << "-" << m_rows << m_cols; // drawScreenCell(p,rc); // } // return; // //qDebug() << "check" << this->verticalScrollBar()->value()-m_sbList.size(); VTermRect rect; rect.start_row = topVisibleRow(); rect.end_row = rect.start_row+m_rows; rect.start_col = 0; rect.end_col = m_cols; //qDebug() << "drawScreenCell" << rect.start_row << rect.end_row << rect.start_col << rect.end_col; drawScreenCell(p,rect); } void VTermWidgetBase::drawScreenCell(QPainter &p, VTermRect rect) { QFont fnt = this->font(); QFontMetrics fm(fnt); p.setPen(toQColor(&m_defaultFg)); p.setBrush(toQColor(&m_defaultBg)); VTermScreenCell cell; int xoff = m_ptOffset.x();//(this->width()-this->verticalScrollBar()->sizeHint().width() -m_cellSize.width()*m_cols)/2; int yoff = 1-fm.descent()+m_ptOffset.y(); QRect cursorRect; QPen oldPen = p.pen(); QBrush oldBrush = p.brush(); for (int row = rect.start_row; row < rect.end_row; row++) { int x = xoff; int y = yoff+(row-rect.start_row)*m_cellSize.height(); QString text; VTermColor last_bg = m_defaultBg; VTermColor last_fg = m_defaultFg; VTermScreenCellAttrs last_attr = m_empytCell.attrs; QTextLayout::FormatRange lastFR; QFont lastFnt = this->font(); p.setPen(oldPen); p.setBrush(oldBrush); p.setFont(this->font()); for (int col = rect.start_col; col < rect.end_col; col++) { bool b = fetchCell(row,col,&cell); VTermColor *bg = &cell.bg; VTermColor *fg = &cell.fg; if (cell.attrs.reverse) { qSwap(bg,fg); } last_fg = *fg; last_bg = *bg; QString c; if (!b || !cell.chars[0]) { text += ' '; cell.width = 1; c = ' '; } else { c = QString::fromUcs4(cell.chars); text += c; } QRect rc(x+col*m_cellSize.width(),y+fm.descent(),m_cellSize.width()*cell.width,m_cellSize.height()); if (m_cursor.visible && m_cursor.row == row && m_cursor.col == col) { cursorRect = rc; } if (!attrs_is_equal(&last_attr,&cell.attrs)) { QFont fnt = this->font(); if (cell.attrs.bold) { fnt.setWeight(QFont::Bold); } if (cell.attrs.italic) { fnt.setItalic(true); } if (cell.attrs.strike) { fnt.setStrikeOut(true); } if (cell.attrs.underline) { fnt.setUnderline(true); } p.setFont(fnt); } last_attr = cell.attrs; if (!vterm_color_is_equal(&m_defaultBg,bg)) { p.fillRect(rc,toQColor(bg)); } if (!vterm_color_is_equal(&m_defaultFg,fg)) { p.setPen(toQColor(fg)); } else { p.setPen(oldPen); } if (isSelection(row,col)) { p.fillRect(rc,m_clrSelect); } p.drawText(x+col*m_cellSize.width(),y+m_cellSize.height(),c); if (cell.width > 1) { col += cell.width-1; } } } if (cursorRect.isEmpty()) { return; } // VTERM_PROP_CURSORSHAPE_BLOCK = 1, // VTERM_PROP_CURSORSHAPE_UNDERLINE, // VTERM_PROP_CURSORSHAPE_BAR_LEFT, switch (m_cursor.shape) { case VTERM_PROP_CURSORSHAPE_BLOCK: break; case VTERM_PROP_CURSORSHAPE_UNDERLINE: cursorRect.setTop(cursorRect.bottom()-2); break; case VTERM_PROP_CURSORSHAPE_BAR_LEFT: cursorRect.setRight(cursorRect.left()+2); break; } //p.fillRect(cursorRect,QColor(40,40,40,128)); if (this->hasFocus()) { p.fillRect(cursorRect,m_clrCursor); } else { p.setPen(m_clrCursor); p.drawRect(cursorRect); } } void VTermWidgetBase::keyPressEvent(QKeyEvent *e) { VTermModifier mod = qt_to_vtermModifier(e->modifiers()); VTermKey key = qt_to_vtermKey(e->key(),e->modifiers() & Qt::KeypadModifier); if (key != VTERM_KEY_NONE) { if (key == VTERM_KEY_ESCAPE) mod = VTERM_MOD_NONE; vterm_keyboard_key(m_vt, key, mod); } else if (e->text().length()) { vterm_keyboard_unichar( m_vt, e->text().toUcs4()[0], mod); } flushOutput(); } void VTermWidgetBase::mouseMoveEvent(QMouseEvent *e) { // vterm_mouse_move(m_vt,row,col,qt_to_vtermModifier(e->modifiers())); // this->viewport()->update(); if (m_leftButtonPress) { updateSelection(e->pos()); viewport()->update(); } } void VTermWidgetBase::mousePressEvent(QMouseEvent *e) { // vterm_mouse_button(m_vt,e->button(),true,qt_to_vtermModifier(e->modifiers())); // this->viewport()->update(); if (e->button() == Qt::LeftButton) { if (m_trippleClickTimer.isActive() && ( (e->pos() - m_trippleClickPoint).manhattanLength() < QApplication::startDragDistance())) { QPoint cell = mapPointToCell(e->pos()); setSelectionByRow(cell.y()); m_trippleClickTimer.stop(); } else { this->clearSelection(); } m_ptOrg = e->pos(); m_leftButtonPress = true; } } void VTermWidgetBase::updateSelection(QPoint scenePos) { QPoint start = mapPointToCell(m_ptOrg); QPoint end = mapPointToCell(scenePos); if (start != end) { setSelection(start, end); } } void VTermWidgetBase::mouseReleaseEvent(QMouseEvent *e) { // vterm_mouse_button(m_vt,e->button(),false,qt_to_vtermModifier(e->modifiers())); // this->viewport()->update(); if (e->button() == Qt::LeftButton) { this->updateSelection(e->pos()); m_leftButtonPress = false; } } void VTermWidgetBase::mouseDoubleClickEvent(QMouseEvent *e) { if (e->button() == Qt::LeftButton) { m_trippleClickPoint = e->pos(); m_trippleClickTimer.start(QApplication::doubleClickInterval(),this); QPoint cell = mapPointToCell(e->pos()); setSelectionUnderWord(cell.y(),cell.x()); } } void VTermWidgetBase::timerEvent(QTimerEvent *e) { if (e->timerId() == m_trippleClickTimer.timerId()) { m_trippleClickTimer.stop(); } } void VTermWidgetBase::inputMethodEvent(QInputMethodEvent *e) { QVector<uint> str = e->commitString().toUcs4(); foreach(uint c, str) { vterm_keyboard_unichar(m_vt,c,VTERM_MOD_NONE); } flushOutput(); viewport()->update(); } void VTermWidgetBase::resizeEvent(QResizeEvent *e) { e->accept(); // save scroll int rows = (e->size().height()-m_ptOffset.y()*2) /m_cellSize.height(); int cols = (e->size().width()-this->verticalScrollBar()->sizeHint().width() - m_ptOffset.x()*2) /m_cellSize.width(); int oldMax = this->verticalScrollBar()->maximum(); int oldValue = this->verticalScrollBar()->value(); m_ignoreScroll = true; vterm_set_size(m_vt,rows,cols); vterm_screen_flush_damage(m_screen); m_ignoreScroll = false; // restore scroll int newMax = this->verticalScrollBar()->maximum(); if (newMax!=0 && oldMax!=0) { int newValue = oldValue*newMax/oldMax; this->verticalScrollBar()->setValue(newValue); } QAbstractScrollArea::resizeEvent(e); } void VTermWidgetBase::focusInEvent(QFocusEvent *e) { e->accept(); viewport()->update(); } void VTermWidgetBase::focusOutEvent(QFocusEvent *e) { e->accept(); viewport()->update(); } void VTermWidgetBase::flushOutput() { size_t len = vterm_output_read(m_vt, textbuf, sizeof(textbuf)); if (len > 0) { this->write_data(textbuf,int(len)); } } void VTermWidgetBase::write_data(const char *buf, int len) { qDebug() << "output" << QString::fromUtf8(buf,int(len)); } void VTermWidgetBase::setSelection(QPoint cellStart, QPoint cellEnd) { if (cellStart.y() > cellEnd.y()) qSwap(cellStart, cellEnd); if (cellStart.y() == cellEnd.y() && cellStart.x() > cellEnd.x()) qSwap(cellStart, cellEnd); if (cellStart.x() < 0) cellStart.rx() = 0; if (cellStart.y() < startRow()) cellStart.ry() = startRow(); if (cellEnd.x() > m_cols) cellEnd.rx() = m_cols; if (cellEnd.y() > endRow()) cellEnd.ry() = endRow(); if (cellStart.y() >= m_rows) { m_selection = QRect(); } else { m_selection = QRect(cellStart, cellEnd); } m_selected.start_row = cellStart.y()+topVisibleRow(); m_selected.start_col = cellStart.x(); m_selected.end_col = cellStart.y(); m_selected.end_row = cellEnd.y()+topVisibleRow(); emit selectionChanged(); } void VTermWidgetBase::setSelectionByRow(int row) { if (row < startRow() || row >= endRow()) { clearSelection(); return; } m_selection = QRect(0,row,m_cols+1,1); emit selectionChanged(); } bool VTermWidgetBase::adjustFetchCell(int row, int *col, VTermScreenCell *cell) { bool b = this->fetchCell(row,*col,cell); if (!b) { return false; } if (cell->chars[0] == uint32_t(-1)) { bool b = this->fetchCell(row,*col-1,cell); if (b) { *col = *col-1; return true; } } return b; } void VTermWidgetBase::setSelectionUnderWord(int row, int col) { if (row < startRow() || row >= endRow() || col < 0 || col >= m_cols) { clearSelection(); return; } VTermScreenCell cell; this->adjustFetchCell(row,&col,&cell); if (!cell.chars[0]) { int ncol = col+1; for (; ncol < m_cols; ++ncol) { this->fetchCell(row,ncol,&cell); if (cell.chars[0]) { break; } } int pcol = col-1; for (;pcol >= 0;--pcol) { this->fetchCell(row,pcol,&cell); if (cell.chars[0]) { break; } } setSelection(QPoint(pcol+1,row),QPoint(ncol,row)); } else { bool isSpace = QString::fromUcs4(cell.chars)[0].isSpace(); int width = cell.width; int ncol = col+width; for (; ncol < m_cols;) { this->fetchCell(row,ncol,&cell); if (!cell.chars[0]) { break; } QChar c = QString::fromUcs4(cell.chars)[0]; if (isSpace && !c.isSpace()) { break; } else if (!isSpace && c.isSpace()) { break; } ncol += cell.width; } int pcol = col-1; for (; pcol >= 0;--pcol) { this->adjustFetchCell(row,&pcol,&cell); if (!cell.chars[0]) { break; } QChar c = QString::fromUcs4(cell.chars)[0]; if (isSpace && !c.isSpace()) { break; } else if (!isSpace && c.isSpace()) { break; } } setSelection(QPoint(pcol+cell.width,row),QPoint(ncol,row)); } } void VTermWidgetBase::selectAll() { m_selection = QRect(0,-scrollbackRowSize(),m_cols+1,allRowSize()); emit selectionChanged(); } void VTermWidgetBase::clearSelection() { if (m_selection.isNull()) return; m_selection = QRect(); emit selectionChanged(); } bool VTermWidgetBase::hasSelection() const { return !m_selection.isNull(); } bool VTermWidgetBase::isSelection(int row, int col) const { if (m_selection.isNull()) { return false; } if (m_selection.height() == 1) { if (row == m_selection.top() && col >= m_selection.left() && col < m_selection.right()) { return true; } } else { if (m_selection.top() == row) { if (col >= m_selection.left()) { return true; } } else if (m_selection.bottom() == row) { if (col < m_selection.right()) { return true; } } else if (row > m_selection.top() && row < m_selection.bottom()) { return true; } } return false; } VTermModifier qt_to_vtermModifier(Qt::KeyboardModifiers mod) { int ret = VTERM_MOD_NONE; if (mod & Qt::SHIFT) ret |= VTERM_MOD_SHIFT; if (mod & Qt::ALT) ret |= VTERM_MOD_ALT; if (mod & Qt::CTRL) ret |= VTERM_MOD_CTRL; return static_cast<VTermModifier>(ret); } VTermKey qt_to_vtermKey(int key, bool keypad) { if (key >= Qt::Key_F1 && key <= Qt::Key_F35) return static_cast<VTermKey>(VTERM_KEY_FUNCTION_0 + key - Qt::Key_F1 + 1); switch (key) { case Qt::Key_Return: return VTERM_KEY_ENTER; case Qt::Key_Tab: return VTERM_KEY_TAB; case Qt::Key_Backspace: return VTERM_KEY_BACKSPACE; case Qt::Key_Escape: return VTERM_KEY_ESCAPE; case Qt::Key_Up: return VTERM_KEY_UP; case Qt::Key_Down: return VTERM_KEY_DOWN; case Qt::Key_Left: return VTERM_KEY_LEFT; case Qt::Key_Right: return VTERM_KEY_RIGHT; case Qt::Key_Insert: return VTERM_KEY_INS; case Qt::Key_Delete: return VTERM_KEY_DEL; case Qt::Key_Home: return VTERM_KEY_HOME; case Qt::Key_End: return VTERM_KEY_END; case Qt::Key_PageUp: return VTERM_KEY_PAGEUP; case Qt::Key_PageDown: return VTERM_KEY_PAGEDOWN; case Qt::Key_multiply: return keypad ? VTERM_KEY_KP_MULT : VTERM_KEY_NONE; case Qt::Key_Plus: return keypad ? VTERM_KEY_KP_PLUS : VTERM_KEY_NONE; case Qt::Key_Comma: return keypad ? VTERM_KEY_KP_COMMA : VTERM_KEY_NONE; case Qt::Key_Minus: return keypad ? VTERM_KEY_KP_MINUS : VTERM_KEY_NONE; case Qt::Key_Period: return keypad ? VTERM_KEY_KP_PERIOD : VTERM_KEY_NONE; case Qt::Key_Slash: return keypad ? VTERM_KEY_KP_DIVIDE : VTERM_KEY_NONE; case Qt::Key_Enter: return keypad ? VTERM_KEY_KP_ENTER : VTERM_KEY_NONE; case Qt::Key_Equal: return keypad ? VTERM_KEY_KP_EQUAL : VTERM_KEY_NONE; default: return VTERM_KEY_NONE; } } #define UNICODE_TAB '\t' #define UNICODE_SPACE 0x20 #define UNICODE_LINEFEED 0x0a static inline unsigned int utf8_seqlen(long codepoint) { if(codepoint < 0x0000080) return 1; if(codepoint < 0x0000800) return 2; if(codepoint < 0x0010000) return 3; if(codepoint < 0x0200000) return 4; if(codepoint < 0x4000000) return 5; return 6; } /* Does NOT NUL-terminate the buffer */ static int fill_utf8(long codepoint, char *str) { int nbytes = utf8_seqlen(codepoint); // This is easier done backwards int b = nbytes; while(b > 1) { b--; str[b] = 0x80 | (codepoint & 0x3f); codepoint >>= 6; } switch(nbytes) { case 1: str[0] = (codepoint & 0x7f); break; case 2: str[0] = 0xc0 | (codepoint & 0x1f); break; case 3: str[0] = 0xe0 | (codepoint & 0x0f); break; case 4: str[0] = 0xf0 | (codepoint & 0x07); break; case 5: str[0] = 0xf8 | (codepoint & 0x03); break; case 6: str[0] = 0xfc | (codepoint & 0x01); break; } return nbytes; } size_t VTermWidgetBase::_get_chars(const VTermScreen *screen, const int utf8, void *buffer, size_t len, const VTermRect rect) const { size_t outpos = 0; int padding = 0; #define PUT(c) \ if(utf8) { \ size_t thislen = utf8_seqlen(c); \ if(buffer && outpos + thislen <= len) \ outpos += fill_utf8((c), (char *)buffer + outpos); \ else \ outpos += thislen; \ } \ else { \ if(buffer && outpos + 1 <= len) \ ((uint32_t*)buffer)[outpos++] = (c); \ else \ outpos++; \ } int row,col,i; for(row = rect.start_row; row < rect.end_row; row++) { for(col = rect.start_col; col < rect.end_col; col++) { VTermScreenCell cell; fetchCell(row, col,&cell); if(cell.chars[0] == 0) // Erased cell, might need a space padding++; else if(cell.chars[0] == (uint32_t)-1) // Gap behind a double-width char, do nothing ; else { while(padding > 0) { PUT(UNICODE_TAB); padding-=8; } padding = 0; for(i = 0; i < VTERM_MAX_CHARS_PER_CELL && cell.chars[i]; i++) { PUT(cell.chars[i]); } } } if(row < rect.end_row - 1) { PUT(UNICODE_LINEFEED); padding = 0; } } return outpos; }
33,312
C++
.cpp
1,020
26.829412
131
0.597594
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,537
iconutil.cpp
visualfc_liteide/liteidex/src/utils/iconutil/iconutil.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: iconutil.cpp // Creator: visualfc <visualfc@gmail.com> #include "iconutil.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
1,418
C++
.cpp
32
41.46875
83
0.644509
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,538
gotools.cpp
visualfc_liteide/liteidex/src/utils/gotools/gotools.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2018 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: gotools.cpp // Creator: visualfc <visualfc@gmail.com> #include "gotools.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> GopherLib::GopherLib(const QString &libname, QObject *parent) : QObject(parent) { lib.setFileName(libname); fnInvokeAsync = 0; fnInvoke = 0; fnSetenv = 0; fnSetBuildEnv = 0; fnClearBuildEnv = 0; if (lib.isLoaded()) { fnInvokeAsync = (InvokeAsyncFunc)lib.resolve("InvokeAsync"); fnInvoke = (InvokeFunc)lib.resolve("Invoke"); fnSetenv = (SetenvFunc)lib.resolve("Setenv"); fnSetBuildEnv = (SetBuildEnvFunc)lib.resolve("SetBuildEnv"); fnClearBuildEnv = (ClearBuildEnvFunc)lib.resolve("ClearBuildEnv"); } }
2,027
C++
.cpp
49
37.306122
83
0.649949
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,539
documentbrowser.cpp
visualfc_liteide/liteidex/src/utils/documentbrowser/documentbrowser.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: documentbrowser.cpp // Creator: visualfc <visualfc@gmail.com> #include "documentbrowser.h" #include "extension/extension.h" #include "cmark/libcmark.h" #include <QTextBrowser> #include <QVBoxLayout> #include <QHBoxLayout> #include <QScrollBar> #include <QStatusBar> #include <QComboBox> #include <QToolBar> #include <QToolButton> #include <QCheckBox> #include <QAction> #include <QRegExp> #include <QFile> #include <QFileInfo> #include <QTextCodec> #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 DocumentBrowser::DocumentBrowser(LiteApi::IApplication *app, QObject *parent) : LiteApi::IDocumentBrowser(parent), m_liteApp(app), m_extension(new Extension) { m_widget = new QWidget; m_htmlWidget = app->htmlWidgetManager()->createByName(this,"QTextBrowser"); m_toolBar = new QToolBar; m_toolBar->setIconSize(LiteApi::getToolBarIconSize(m_liteApp)); m_backwardAct = new QAction(QIcon("icon:images/backward.png"),tr("Back"),this); m_forwardAct = new QAction(QIcon("icon:images/forward.png"),tr("Forward"),this); m_reloadUrlAct = new QAction(QIcon("icon:images/reload.png"),tr("Reload"),this); m_toolBar->addAction(m_backwardAct); m_toolBar->addAction(m_forwardAct); LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(this,"Document"); m_increaseFontSize = new QAction(tr("Increase Font Size"),this); actionContext->regAction(m_increaseFontSize,"IncreaseFontSize","Ctrl++;Ctrl+="); m_decreaseFontSize = new QAction(tr("Decrease Font Size"),this); actionContext->regAction(m_decreaseFontSize,"DecreaseFontSize","Ctrl+-"); m_resetFontSize = new QAction(tr("Reset Font Size"),this); actionContext->regAction(m_resetFontSize,"ResizeFontSize","Ctrl+0"); m_urlComboBox = new QComboBox; m_urlComboBox->setEditable(true); m_urlComboBox->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred); m_toolBar->addSeparator(); m_toolBar->addWidget(m_urlComboBox); m_toolBar->addAction(m_reloadUrlAct); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->setMargin(0); mainLayout->setSpacing(0); mainLayout->addWidget(m_toolBar); mainLayout->addWidget(m_htmlWidget->widget()); m_widget->setLayout(mainLayout); m_widget->addAction(m_increaseFontSize); m_widget->addAction(m_decreaseFontSize); m_widget->addAction(m_resetFontSize); connect(m_increaseFontSize,SIGNAL(triggered()),this,SLOT(increaseFontSize())); connect(m_decreaseFontSize,SIGNAL(triggered()),this,SLOT(decreaseFontSize())); connect(m_resetFontSize,SIGNAL(triggered()),this,SLOT(resetFontSize())); connect(m_htmlWidget,SIGNAL(linkHovered(QUrl)),this,SIGNAL(linkHovered(QUrl))); connect(m_htmlWidget,SIGNAL(linkClicked(QUrl)),this,SLOT(linkClicked(QUrl))); connect(m_htmlWidget,SIGNAL(loadFinished(bool)),this,SIGNAL(documentLoaded())); connect(m_htmlWidget,SIGNAL(anchorChanged(QString)),this,SIGNAL(anchorChanged(QString))); connect(m_backwardAct,SIGNAL(triggered()),this,SLOT(backward())); connect(m_forwardAct,SIGNAL(triggered()),this,SLOT(forward())); connect(m_reloadUrlAct,SIGNAL(triggered()),this,SLOT(reloadUrl())); connect(m_urlComboBox,SIGNAL(activated(QString)),this,SLOT(activatedUrl(QString))); connect(this,SIGNAL(backwardAvailable(bool)),m_backwardAct,SLOT(setEnabled(bool))); connect(this,SIGNAL(forwardAvailable(bool)),m_forwardAct,SLOT(setEnabled(bool))); m_extension->addObject("LiteApi.IDocumentBrowser",this); m_extension->addObject("LiteApi.IHtmlWidget",m_htmlWidget); m_extension->addObject("LiteApi.QTextBrowser",m_htmlWidget->widget()); m_htmlWidget->installEventFilter(m_liteApp->editorManager()); requestFontZoom(0); QPalette p = m_htmlWidget->widget()->palette(); p.setBrush(QPalette::Highlight,Qt::yellow); p.setColor(QPalette::HighlightedText,Qt::black); m_htmlWidget->widget()->setPalette(p); emit backwardAvailable(false); emit forwardAvailable(false); } DocumentBrowser::~DocumentBrowser() { if (m_widget) { delete m_widget; } if (m_extension) { delete m_extension; } } LiteApi::IExtension *DocumentBrowser::extension() { return m_extension; } bool DocumentBrowser::open(const QString &fileName,const QString &mimeType) { QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { return false; } m_mimeType = mimeType; QFileInfo info(fileName); QString htmlType = m_liteApp->mimeTypeManager()->findMimeTypeByFile(fileName); m_name = info.fileName(); m_fileName = QDir::toNativeSeparators(fileName); m_htmlWidget->setSearchPaths(QStringList()<<info.absolutePath()); QByteArray ba = file.readAll(); if (htmlType == "text/html") { QTextCodec *codec = QTextCodec::codecForHtml(ba,QTextCodec::codecForName("utf-8")); setUrlHtml(QUrl::fromLocalFile(fileName),codec->toUnicode(ba)); } else if (htmlType == "text/x-markdown") { QTextCodec *codec = QTextCodec::codecForName("utf-8"); QByteArray out = md2html(ba); setUrlHtml(QUrl::fromLocalFile(fileName),codec->toUnicode(out)); } file.close(); return true; } QWidget *DocumentBrowser::widget() { return m_widget; } QString DocumentBrowser::name() const { return m_name; } QString DocumentBrowser::filePath() const { return m_fileName; } QString DocumentBrowser::mimeType() const { return m_mimeType; } void DocumentBrowser::onActive() { } void DocumentBrowser::setName(const QString &t) { m_name = t; } void DocumentBrowser::setSearchPaths(const QStringList &paths) { m_htmlWidget->setSearchPaths(paths); } QUrl DocumentBrowser::resolveUrl(const QUrl &url) const { if (!url.isRelative()) return url; // For the second case QUrl can merge "#someanchor" with "foo.html" // correctly to "foo.html#someanchor" if (!(m_url.isRelative() || (m_url.scheme() == QLatin1String("file") && !QFileInfo(m_url.toLocalFile()).isAbsolute())) || (url.hasFragment() && url.path().isEmpty())) { return m_url.resolved(url); } // this is our last resort when current url and new url are both relative // we try to resolve against the current working directory in the local // file system. QFileInfo fi(m_url.toLocalFile()); if (fi.exists()) { return QUrl::fromLocalFile(fi.absolutePath() + QDir::separator()).resolved(url); } return url; } QToolBar *DocumentBrowser::toolBar() { return m_toolBar; } QComboBox *DocumentBrowser::urlComboBox() { return m_urlComboBox; } LiteApi::IHtmlWidget *DocumentBrowser::htmlWidget() { return m_htmlWidget; } void DocumentBrowser::scrollToAnchor(const QString &text) { const HistoryEntry &historyEntry = createHistoryEntry(); m_url.setFragment(text); if (text.isEmpty()) { m_htmlWidget->setScrollBarValue(Qt::Horizontal,0); m_htmlWidget->setScrollBarValue(Qt::Vertical,0); } else { m_htmlWidget->scrollToAnchor(text); } m_urlComboBox->blockSignals(true); int index = m_urlComboBox->findText(m_url.toString()); if (index == -1) { m_urlComboBox->addItem(m_url.toString()); index = m_urlComboBox->count()-1; } m_urlComboBox->setCurrentIndex(index); m_urlComboBox->blockSignals(false); emit documentLoaded(); if (!m_backwardStack.isEmpty() && m_url == m_backwardStack.top().url) { //restoreHistoryEntry(m_backwardStack.top()); return; } if (!m_backwardStack.isEmpty()) { m_backwardStack.top() = historyEntry; } HistoryEntry entry; entry.url = m_url; m_backwardStack.push(entry); emit backwardAvailable(m_backwardStack.count() > 1); if (!m_forwardStack.isEmpty() && m_url == m_forwardStack.top().url) { m_forwardStack.pop(); emit forwardAvailable(m_forwardStack.count() > 0); } else { m_forwardStack.clear(); emit forwardAvailable(false); } } void DocumentBrowser::setUrlHtml(const QUrl &url,const QString &data) { const HistoryEntry &historyEntry = createHistoryEntry(); if (!data.isEmpty()) { m_htmlWidget->setHtml(data,url); } m_url = url; if (!url.fragment().isEmpty()) { m_htmlWidget->scrollToAnchor(url.fragment()); } else { m_htmlWidget->setScrollBarValue(Qt::Horizontal,0); m_htmlWidget->setScrollBarValue(Qt::Vertical,0); } m_urlComboBox->blockSignals(true); int index = m_urlComboBox->findText(m_url.toString()); if (index == -1) { m_urlComboBox->addItem(m_url.toString()); index = m_urlComboBox->count()-1; } m_urlComboBox->setCurrentIndex(index); m_urlComboBox->blockSignals(false); if (!m_backwardStack.isEmpty() && url == m_backwardStack.top().url) { // restoreHistoryEntry(m_backwardStack.top()); return; } if (!m_backwardStack.isEmpty()) { m_backwardStack.top() = historyEntry; } HistoryEntry entry; entry.url = url; m_backwardStack.push(entry); emit backwardAvailable(m_backwardStack.count() > 1); if (!m_forwardStack.isEmpty() && url == m_forwardStack.top().url) { m_forwardStack.pop(); emit forwardAvailable(m_forwardStack.count() > 0); } else { m_forwardStack.clear(); emit forwardAvailable(false); } } void DocumentBrowser::activatedUrl(QString text) { if (text.isEmpty()) { return; } QUrl url(text); requestUrl(url); } DocumentBrowser::HistoryEntry DocumentBrowser::createHistoryEntry() const { HistoryEntry entry; entry.url = m_url; entry.hpos = m_htmlWidget->scrollBarValue(Qt::Horizontal); entry.vpos = m_htmlWidget->scrollBarValue(Qt::Vertical); return entry; } void DocumentBrowser::restoreHistoryEntry(const HistoryEntry &entry) { m_url = entry.url; m_htmlWidget->setScrollBarValue(Qt::Horizontal,entry.hpos); m_htmlWidget->setScrollBarValue(Qt::Vertical,entry.vpos); } void DocumentBrowser::backward() { if (m_backwardStack.count() <= 1) { return; } m_forwardStack.push(createHistoryEntry()); m_backwardStack.pop(); emit requestUrl(m_backwardStack.top().url); emit backwardAvailable(m_backwardStack.count() > 1); emit forwardAvailable(true); } void DocumentBrowser::reloadUrl() { emit requestUrl(m_url); } void DocumentBrowser::increaseFontSize() { this->requestFontZoom(10); } void DocumentBrowser::decreaseFontSize() { this->requestFontZoom(-10); } void DocumentBrowser::resetFontSize() { int fontSize = m_liteApp->settings()->value(DOCUMENT_FONTSIZE,12).toInt(); m_liteApp->settings()->setValue(DOCUMENT_FONTZOOM,100); QWidget *widget = m_htmlWidget->widget(); QFont font = widget->font(); font.setPointSize(fontSize); widget->setFont(font); } void DocumentBrowser::requestFontZoom(int zoom) { int fontSize = m_liteApp->settings()->value(DOCUMENT_FONTSIZE,12).toInt(); int fontZoom = m_liteApp->settings()->value(DOCUMENT_FONTZOOM,100).toInt(); fontZoom += zoom; if (fontZoom <= 10) { return; } m_liteApp->settings()->setValue(DOCUMENT_FONTZOOM,fontZoom); QWidget *widget = m_htmlWidget->widget(); QFont font = widget->font(); font.setPointSize(fontSize*fontZoom/100.0); widget->setFont(font); } void DocumentBrowser::forward() { if (m_forwardStack.isEmpty()) { return; } if (!m_backwardStack.isEmpty()) { m_backwardStack.top() = createHistoryEntry(); } m_backwardStack.push(m_forwardStack.pop()); emit requestUrl(m_backwardStack.top().url); emit backwardAvailable(true); emit forwardAvailable(m_forwardStack.count() > 0); } void DocumentBrowser::linkClicked(QUrl url) { if (url.path().isEmpty() && !url.fragment().isEmpty()) { m_liteApp->mainWindow()->statusBar()->clearMessage(); //m_textBrowser->scrollToAnchor(url.fragment()); this->scrollToAnchor(url.fragment()); return; } emit requestUrl(url); }
13,455
C++
.cpp
379
31.131926
107
0.695448
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,540
documentbrowserfactory.cpp
visualfc_liteide/liteidex/src/utils/documentbrowser/documentbrowserfactory.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: documentbrowserfactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "documentbrowserfactory.h" #include "documentbrowser.h" #include <QFile> #include <QTextBrowser> #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 DocumentBrowserFactory::DocumentBrowserFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IEditorFactory(parent), m_liteApp(app) { m_mimeTypes << "liteide/x-browser"; } QStringList DocumentBrowserFactory::mimeTypes() const { return m_mimeTypes; } LiteApi::IEditor *DocumentBrowserFactory::open(const QString &fileName, const QString &mimeType) { DocumentBrowser *browser = new DocumentBrowser(m_liteApp,0); if (browser->open(fileName,mimeType)) { return browser; } return 0; } QString DocumentBrowserFactory::id() const { return "DocumentBrowser"; } QString DocumentBrowserFactory::displayName() const { return tr("DocumentBrowser"); } bool DocumentBrowserFactory::testMimeType(const QString &mimeType) { return true; }
2,297
C++
.cpp
66
32.530303
96
0.704137
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,541
filesystemmodel.cpp
visualfc_liteide/liteidex/src/utils/filesystem/filesystemmodel.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: filesystemmodel.cpp // Creator: visualfc <visualfc@gmail.com> #include "filesystemmodel.h" #include "liteapi/liteqt.h" #include <QFileInfo> #include <QDir> #include <QIcon> #include <QFont> #include <QFileIconProvider> #include <QFileSystemWatcher> #include <QMutexLocker> #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 FileNode::FileNode(FileSystemModel *model) : m_model(model), m_parent(0), m_children(0), m_bWatcher(false) { } FileNode::FileNode(FileSystemModel *model, const QString &path, FileNode *parent) : m_model(model), m_parent(parent), m_children(0), m_path(path), m_bWatcher(false) { QFileInfo info(path); if (m_model->isRootPathNodeFillPath() && parent && parent->parent() == 0) { m_text = QDir::toNativeSeparators(info.filePath()); } else { m_text = info.fileName(); } } FileNode::~FileNode() { clear(); if (m_children) { delete m_children; } if (m_bWatcher) { m_model->removeWatcher(m_path); } } QList<FileNode*>* FileNode::children() { if (m_children == 0) { m_children = new QList<FileNode*>(); //bool isRoot = false; if (!m_path.isEmpty()) { QFileInfo info(m_path); if (info.isDir()) { // isRoot = info.isRoot(); QDir dir(m_path); foreach(QFileInfo childInfo, dir.entryInfoList(this->m_model->filter(),this->m_model->dirSort())) { if (!this->m_model->isShowHideFiles() && childInfo.isDir() && childInfo.fileName().startsWith(".")) { continue; } m_children->append(new FileNode(this->m_model,childInfo.filePath(),this)); } } } if (!m_children->isEmpty() && !m_bWatcher) { m_bWatcher = true; m_model->addWatcher(m_path); } } return m_children; } FileNode* FileNode::parent() { return m_parent; } FileNode* FileNode::child(int row) { return children()->at(row); } int FileNode::childCount() { return children()->count(); } int FileNode::row() const { if (m_parent) { return m_parent->children()->indexOf(const_cast<FileNode*>(this)); } return 0; } QString FileNode::path() const { return m_path; } QString FileNode::text() const { return m_text; } bool FileNode::isDir() const { return QFileInfo(m_path).isDir(); } bool FileNode::isFile() const { return QFileInfo(m_path).isFile(); } QFileInfo FileNode::fileInfo() const { return QFileInfo(m_path); } bool FileNode::isExist() const { return QFileInfo(m_path).exists(); } void FileNode::clear() { if (m_children) { qDeleteAll(m_children->begin(),m_children->end()); m_children->clear(); } } void FileNode::reload() { clear(); if (m_children == 0) { m_children = new QList<FileNode*>(); } if (!m_path.isEmpty()) { QFileInfo info(m_path); if (info.isDir()) { QDir dir(m_path); foreach(QFileInfo childInfo, dir.entryInfoList(this->m_model->filter(),this->m_model->dirSort())) { if (!this->m_model->isShowHideFiles() && childInfo.isDir() && childInfo.fileName().startsWith(".")) { continue; } m_children->append(new FileNode(this->m_model,childInfo.filePath(),this)); } } } if (!m_children->isEmpty() && !m_bWatcher) { m_bWatcher = true; m_model->addWatcher(m_path); } } FileNode *FileNode::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("/",qtSkipEmptyParts); FileNode *parent = this; bool find = false; foreach (QString name,nameList) { find = false; QList<FileNode*>* chilren = parent->children(); for (int i = 0; i < chilren->count(); i++) { FileNode *node = chilren->at(i); if (!node->isDir()) { continue; } if (node->m_text == name) { parent = node; find = true; break; } } if (!find) { return 0; } } return parent; } FileSystemModel::FileSystemModel(QObject *parent) : QAbstractItemModel(parent), m_rootNode(new FileNode(this)), m_iconProvider(new QFileIconProvider), m_fileWatcher(0) { m_filters = QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot; m_sorts = QDir::DirsFirst | QDir::Name | QDir::IgnoreCase;// | QDir::Type; // connect(m_fileWatcher,SIGNAL(directoryChanged(QString)),this,SLOT(directoryChanged(QString))); } FileSystemModel::~FileSystemModel() { delete m_rootNode; delete m_iconProvider; if (m_fileWatcher) { delete m_fileWatcher; } } void FileSystemModel::reloadDirectory(const QString &path) { this->beginResetModel(); QDir dir(path); bool b = dir.exists(); if (!b) { m_fileWatcher->removePath(path); } foreach(QModelIndex index,this->findPaths(path)) { FileNode *node = nodeFromIndex(index); if (b) { node->reload(); } else { FileNode *parent = node->parent(); if (parent) { parent->reload(); } } } this->endResetModel(); } FileNode *FileSystemModel::nodeFromIndex(const QModelIndex &index) const { if (index.isValid()) { return static_cast<FileNode*>(index.internalPointer()); } return m_rootNode; } void FileSystemModel::setStartIndex(const QModelIndex &index) { m_startPath = filePath(index); } void FileSystemModel::setStartPath(const QString &path) { m_startPath = path; } QModelIndex FileSystemModel::startIndex() const { return findPath(m_startPath); } QString FileSystemModel::startPath() const { return m_startPath; } QString FileSystemModel::filePath(const QModelIndex &index) const { return nodeFromIndex(index)->path(); } void FileSystemModel::setFilter(QDir::Filters filters) { if (m_filters != filters) { m_filters = filters; this->reload(); } } void FileSystemModel::setDirSort(QDir::SortFlags flags) { if (m_sorts != flags) { m_sorts = flags; this->reload(); } } QDir::Filters FileSystemModel::filter() const { return m_filters; } bool FileSystemModel::isShowHideFiles() const { return m_filters & QDir::Hidden; } QDir::SortFlags FileSystemModel::dirSort() const { return m_sorts; } void FileSystemModel::clear() { this->beginResetModel(); m_rootNode->clear(); m_pathList.clear(); m_startPath.clear(); this->endResetModel(); } void FileSystemModel::reload() { this->setRootPathList(this->rootPathList()); } void FileSystemModel::setRootPath(const QString &path) { this->setRootPathList(QStringList() << path); } bool FileSystemModel::removeRootPath(const QString &path) { QString pathName = QDir::fromNativeSeparators(path); FileNode *node = 0; int index = -1; for (int i = 0; i < m_rootNode->childCount(); i++) { node = m_rootNode->children()->at(i); if (node && (node->path() == pathName)) { index = i; break; } } if (index == -1) { return false; } if (!m_pathList.removeAll(pathName)) { return false; } this->beginRemoveRows(QModelIndex(),index,index); m_rootNode->children()->removeAt(index); delete node; this->endRemoveRows(); return true; } bool FileSystemModel::addRootPath(const QString &path) { QString pathName = QDir::fromNativeSeparators(QDir::cleanPath(path)); if (m_pathList.contains(pathName)) { return false; } this->beginInsertRows(QModelIndex(),m_rootNode->childCount(),m_rootNode->childCount()); m_pathList.append(pathName); m_rootNode->children()->append(new FileNode(this,pathName,m_rootNode)); this->endInsertRows(); return true; } void FileSystemModel::setRootPathList(const QStringList &pathList) { this->beginResetModel(); m_rootNode->clear(); m_fileWatcherMap.clear(); m_pathList.clear(); if (m_fileWatcher) { disconnect(m_fileWatcher,0); delete m_fileWatcher; } m_fileWatcher = new QFileSystemWatcher; connect(m_fileWatcher,SIGNAL(directoryChanged(QString)),this,SIGNAL(direcotryChanged(QString))); foreach (QString path, pathList) { m_pathList.append(QDir::fromNativeSeparators(QDir::cleanPath(path))); } m_pathList.removeDuplicates(); foreach(QString path, m_pathList) { m_rootNode->children()->append(new FileNode(this,path,m_rootNode)); } if (m_startPath.isEmpty() && !pathList.isEmpty()) { m_startPath = pathList.first(); } this->endResetModel(); } QStringList FileSystemModel::rootPathList() const { return m_pathList; } QModelIndex FileSystemModel::findPathHelper(const QString &path, const QModelIndex &parentIndex) const { FileNode *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("/",qtSkipEmptyParts); 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); FileNode *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> FileSystemModel::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 FileSystemModel::findPath(const QString &path) const { QList<QModelIndex> list = this->findPaths(path); if (!list.isEmpty()) { return list.last(); } return QModelIndex(); } int FileSystemModel::rowCount(const QModelIndex &parent) const { FileNode *node = nodeFromIndex(parent); return node->childCount(); } int FileSystemModel::columnCount(const QModelIndex&) const { return 1; } QModelIndex FileSystemModel::parent(const QModelIndex &child) const { FileNode *node = nodeFromIndex(child); FileNode *parent = node->parent(); if (parent == m_rootNode) { return QModelIndex(); } return createIndex(parent->row(),0,parent); } QModelIndex FileSystemModel::index(int row, int column,const QModelIndex &parent) const { if (!hasIndex(row,column,parent)) return QModelIndex(); FileNode *node = nodeFromIndex(parent); return createIndex(row,column,node->child(row)); } QVariant FileSystemModel::data(const QModelIndex &index, int role) const { FileNode *node = nodeFromIndex(index); if (!node) { return QVariant(); } switch(role) { case Qt::DisplayRole: return node->text(); case Qt::ToolTipRole: return QDir::toNativeSeparators(node->path()); 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(); } bool FileSystemModel::isRootPathNode(FileNode *node) const { return node->parent() == m_rootNode; } bool FileSystemModel::isRootPathNodeFillPath() const { return false; } void FileSystemModel::addWatcher(const QString &path) { QMutexLocker _(&m_mutex); QString cpath = QDir::fromNativeSeparators(QDir::cleanPath(path)); int value = m_fileWatcherMap[cpath]; value++; m_fileWatcherMap[cpath] = value; if (value > 1) { return; } m_fileWatcher->addPath(path); } void FileSystemModel::removeWatcher(const QString &path) { QMutexLocker _(&m_mutex); QString cpath = QDir::fromNativeSeparators(QDir::cleanPath(path)); int value = m_fileWatcherMap[cpath]; value--; m_fileWatcherMap[cpath] = value; if (value == 0) { m_fileWatcher->removePath(cpath); } }
14,166
C++
.cpp
504
22.970238
121
0.630155
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,542
filesystemwidget.cpp
visualfc_liteide/liteidex/src/utils/filesystem/filesystemwidget.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: filesystemwidget.cpp // Creator: visualfc <visualfc@gmail.com> #include "filesystemwidget.h" #include "liteenvapi/liteenvapi.h" #include "litebuildapi/litebuildapi.h" #include "golangdocapi/golangdocapi.h" #include "fileutil/fileutil.h" #include "../folderview/folderdialog.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 <QFileSystemWatcher> #include <QFileDialog> #include <QHeaderView> #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 FileSystemWidget::FileSystemWidget(bool bMultiDirMode, LiteApi::IApplication *app, QWidget *parent) : QWidget(parent), m_liteApp(app), m_bMultiDirMode(bMultiDirMode), m_bHideRoot(false) { m_tree = new SymbolTreeView; m_model = new FileSystemModel(this); QDir::Filters filters = QDir::AllDirs | QDir::Files | QDir::Drives | QDir::Readable| QDir::Writable | QDir::Executable/* | QDir::Hidden*/ | QDir::NoDotAndDotDot; #ifdef Q_OS_WIN // Symlinked directories can cause file watcher warnings on Win32. filters |= QDir::NoSymLinks; #endif m_model->setFilter(filters); m_tree->setContextMenuPolicy(Qt::CustomContextMenu); m_tree->setModel(m_model); QVBoxLayout *layout = new QVBoxLayout; layout->setMargin(0); layout->addWidget(m_tree); this->setLayout(layout); connect(m_tree,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(openPathIndex(QModelIndex))); connect(m_liteApp->editorManager(),SIGNAL(currentEditorChanged(LiteApi::IEditor*)),this,SLOT(currentEditorChanged(LiteApi::IEditor*))); // m_fileMenu = new QMenu(this); // m_folderMenu = new QMenu(this); // m_rootMenu = new QMenu(this); m_openEditorAct = new QAction(tr("Open File"),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_viewGodocAct = new QAction(tr("View Godoc Here"),this); m_addFolderAct = new QAction(tr("Add Folder..."),this); m_closeFolerAct = new QAction(tr("Close Folder"),this); m_closeAllFoldersAct = new QAction(tr("Close All Folders"),this); // m_fileMenu->addAction(m_executeFileAct); // 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_viewGodocAct); // m_fileMenu->addSeparator(); // m_fileMenu->addAction(m_openShellAct); // m_fileMenu->addAction(m_openExplorerAct); // 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_closeFolerAct); // m_folderMenu->addSeparator(); // m_folderMenu->addAction(m_viewGodocAct); // m_folderMenu->addSeparator(); // m_folderMenu->addAction(m_openShellAct); // m_folderMenu->addAction(m_openExplorerAct); // m_rootMenu->addAction(m_addFolderAct); // m_rootMenu->addSeparator(); //m_rootMenu->addAction(m_closeAllFoldersAct); connect(m_model,SIGNAL(direcotryChanged(QString)),this,SLOT(reloadDirectory(QString))); 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_viewGodocAct,SIGNAL(triggered()),this,SLOT(viewGodoc())); connect(m_addFolderAct,SIGNAL(triggered()),this,SLOT(addFolder())); connect(m_closeFolerAct,SIGNAL(triggered()),this,SLOT(closeFolder())); connect(m_closeAllFoldersAct,SIGNAL(triggered()),this,SLOT(closeAllFolders())); connect(m_tree,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(treeViewContextMenuRequested(QPoint))); connect(m_model,SIGNAL(modelReset()),this,SLOT(modelReset())); } FileSystemWidget::~FileSystemWidget() { // 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); } void FileSystemWidget::setHideRoot(bool b) { if (m_bMultiDirMode) { return; } m_bHideRoot = b; } bool FileSystemWidget::isHideRoot() const { return m_bHideRoot; } void FileSystemWidget::clear() { m_model->clear(); } SymbolTreeView *FileSystemWidget::treeView() const { return m_tree; } FileSystemModel *FileSystemWidget::model() const { return m_model; } QModelIndex FileSystemWidget::rootIndex() const { if (m_model->rowCount() == 0) { return QModelIndex(); } return m_model->index(0,0); } void FileSystemWidget::modelReset() { if (m_bHideRoot && (m_model->rowCount() > 0)) { m_tree->setRootIndex(m_model->index(0,0)); } } void FileSystemWidget::showHideFiles(bool b) { if (isShowHideFiles() == b) { return; } QDir::Filters filters = m_model->filter(); if (b) { filters |= QDir::Hidden; } else { filters ^= QDir::Hidden; } m_model->setFilter(filters); if (m_bHideRoot) { m_tree->expand(this->rootIndex()); } else { m_tree->expandToDepth(0); } } bool FileSystemWidget::isShowHideFiles() const { return m_model->filter() & QDir::Hidden; } void FileSystemWidget::reloadDirectory(QString dir) { SymbolTreeState state; m_tree->saveState(&state); m_model->reloadDirectory(dir); m_tree->loadState(m_model,&state); } QDir FileSystemWidget::contextDir() const { if (m_contextInfo.isDir()) { return m_contextInfo.filePath(); } return m_contextInfo.dir(); } QFileInfo FileSystemWidget::contextFileInfo() const { return m_contextInfo; } void FileSystemWidget::openEditor() { if (m_contextInfo.isFile()) { m_liteApp->fileManager()->openEditor(m_contextInfo.filePath()); } } void FileSystemWidget::newFile() { QDir dir = contextDir(); CreateFileDialog dlg(m_liteApp->mainWindow()); 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 FileSystemWidget::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 FileSystemWidget::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(); #ifdef Q_OS_WIN if (!MoveFileW(info.filePath().toStdWString().c_str(),QFileInfo(dir,fileName).filePath().toStdWString().c_str())) { QMessageBox::information(m_liteApp->mainWindow(),tr("Rename File"), tr("Failed to rename the file!")); } #else if (!QFile::rename(info.filePath(),QFileInfo(dir,fileName).filePath())) { QMessageBox::information(m_liteApp->mainWindow(),tr("Rename File"), tr("Failed to rename the file!")); } #endif } } void FileSystemWidget::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 FileSystemWidget::newFolder() { QDir dir = contextDir(); CreateDirDialog dlg(m_liteApp->mainWindow()); dlg.setDirectory(dir.path()); if (dlg.exec() == QDialog::Rejected) { return; } QString folderName = dlg.getDirName(); 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 FileSystemWidget::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(); #ifdef Q_OS_WIN QString _old = info.filePath(); QString _new = dir.path()+"/"+folderName; if (!MoveFileW(_old.toStdWString().c_str(),_new.toStdWString().c_str())) { QMessageBox::information(m_liteApp->mainWindow(),tr("Rename Folder"), tr("Failed to rename the folder!")); } #else if (!dir.rename(info.fileName(),folderName)) { QMessageBox::information(m_liteApp->mainWindow(),tr("Rename Folder"), tr("Failed to rename the folder!")); } #endif } } void FileSystemWidget::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(); m_model->removeWatcher(info.filePath()); if (!dir.rmdir(info.fileName())) { QMessageBox::information(m_liteApp->mainWindow(),tr("Delete Folder"), tr("Failed to delete the folder!")); m_model->addWatcher(info.filePath()); } } } void FileSystemWidget::openExplorer() { QDir dir = contextDir(); QDesktopServices::openUrl(QUrl::fromLocalFile(dir.path())); } void FileSystemWidget::viewGodoc() { QDir dir = contextDir(); LiteApi::IGolangDoc *doc = LiteApi::findExtensionObject<LiteApi::IGolangDoc*>(m_liteApp,"LiteApi.IGolangDoc"); if (doc) { QUrl url; url.setScheme("pdoc"); url.setPath(dir.path()); doc->openUrl(url); doc->activeBrowser(); } } void FileSystemWidget::addFolder() { #if QT_VERSION >= 0x050000 static QString home = QStandardPaths::writableLocation(QStandardPaths::HomeLocation); #else static QString home = QDesktopServices::storageLocation(QDesktopServices::HomeLocation); #endif QString folder = QFileDialog::getExistingDirectory(this,tr("Add Folder"),home); if (folder.isEmpty()) { return; } this->addRootPath(folder); QDir dir(folder); if (dir.cdUp()) { home = dir.path(); } } void FileSystemWidget::closeFolder() { // if (m_contextInfo.exists() && !m_contextInfo.isDir()) { // return; // } this->m_model->removeRootPath(m_contextInfo.filePath()); } void FileSystemWidget::closeAllFolders() { this->m_model->clear(); } void FileSystemWidget::openShell() { QDir dir = contextDir(); QProcessEnvironment env = LiteApi::getCurrentEnvironment(m_liteApp); QString shell = env.value("LITEIDE_SHELL"); if (!shell.isEmpty()) { foreach (QString info, shell.split(";",qtSkipEmptyParts)) { QStringList ar = info.split(" ",qtSkipEmptyParts); if (ar.size() >= 1) { QString cmd = FileUtil::lookPath(ar[0],LiteApi::getCurrentEnvironment(m_liteApp),false); if (!cmd.isEmpty()) { QString path = dir.path(); ar.pop_front(); #ifdef Q_OS_MAC ar.push_back(path); #endif #ifdef Q_OS_WIN if (path.length() == 2 && path.right(1) == ":") { path += "/"; } #endif QProcess::startDetached(cmd,ar,path); return; } } } return; } QString cmd = env.value("LITEIDE_TERM"); QStringList args = env.value("LITEIDE_TERMARGS").split(" ",qtSkipEmptyParts); //qDebug() << cmd; QString path = dir.path(); #ifdef Q_OS_MAC args.append(path); #endif #ifdef Q_OS_WIN if (path.length() == 2 && path.right(1) == ":") { path += "/"; } #endif QProcess::startDetached(cmd,args,path); } void FileSystemWidget::treeViewContextMenuRequested(const QPoint &pos) { //QMenu *pop = new QMenu(this); //connect(pop,SIGNAL(destroyed()),this,SLOT(destroy2())); QMenu menu(m_tree); LiteApi::FILESYSTEM_CONTEXT_FLAG flag = LiteApi::FILESYSTEM_ROOT; QModelIndex index = m_tree->indexAt(pos); if (index.isValid()) { FileNode *node = m_model->nodeFromIndex(index); if (node) { m_contextInfo = node->fileInfo(); m_contextIndex = index; if (m_model->isRootPathNode(node)) { //contextMenu = m_folderMenu; flag = LiteApi::FILESYSTEM_ROOTFOLDER; //m_closeFolerAct->setVisible(true); //m_removeFolderAct->setVisible(false); } else if (node->isDir()) { //contextMenu = m_folderMenu; flag = LiteApi::FILESYSTEM_FOLDER; //m_closeFolerAct->setVisible(false); //m_removeFolderAct->setVisible(true); } else { //contextMenu = m_fileMenu; flag = LiteApi::FILESYSTEM_FILES; } } } else if (!m_bMultiDirMode) { m_contextIndex = this->rootIndex(); FileNode *node = m_model->nodeFromIndex(m_contextIndex); if (node) { m_contextInfo = node->fileInfo(); } flag = LiteApi::FILESYSTEM_ROOTFOLDER; } bool hasGo = false; if (!m_bMultiDirMode || (flag != LiteApi::FILESYSTEM_ROOT)) { foreach(QFileInfo info, contextDir().entryInfoList(QDir::Files)) { if (info.suffix() == "go") { hasGo = true; } } } //root folder if (flag == LiteApi::FILESYSTEM_ROOT) { if (m_bMultiDirMode) { menu.addAction(m_addFolderAct); } else { menu.addAction(m_newFileAct); menu.addAction(m_newFileWizardAct); menu.addAction(m_newFolderAct); menu.addSeparator(); if (hasGo) { menu.addAction(m_viewGodocAct); menu.addSeparator(); } menu.addAction(m_openShellAct); menu.addAction(m_openExplorerAct); } } else if (flag == LiteApi::FILESYSTEM_ROOTFOLDER) { menu.addAction(m_newFileAct); menu.addAction(m_newFileWizardAct); menu.addAction(m_newFolderAct); menu.addAction(m_renameFolderAct); menu.addAction(m_closeFolerAct); menu.addSeparator(); if (hasGo) { menu.addAction(m_viewGodocAct); menu.addSeparator(); } menu.addAction(m_openShellAct); menu.addAction(m_openExplorerAct); } else if (flag == LiteApi::FILESYSTEM_FOLDER) { menu.addAction(m_newFileAct); menu.addAction(m_newFileWizardAct); menu.addAction(m_newFolderAct); menu.addAction(m_renameFolderAct); menu.addAction(m_removeFolderAct); menu.addSeparator(); if (hasGo) { menu.addAction(m_viewGodocAct); menu.addSeparator(); } menu.addAction(m_openShellAct); menu.addAction(m_openExplorerAct); } else if (flag == LiteApi::FILESYSTEM_FILES) { menu.addAction(m_openEditorAct); menu.addSeparator(); menu.addAction(m_newFileAct); menu.addAction(m_newFileWizardAct); menu.addAction(m_renameFileAct); menu.addAction(m_removeFileAct); menu.addSeparator(); if (hasGo) { menu.addAction(m_viewGodocAct); menu.addSeparator(); } menu.addAction(m_openShellAct); menu.addAction(m_openExplorerAct); } emit aboutToShowContextMenu(&menu,flag,m_contextInfo); menu.exec(m_tree->mapToGlobal(pos)); } void FileSystemWidget::addRootPath(const QString &path) { if (m_model->addRootPath(path)) { m_liteApp->recentManager()->addRecent(path,"folder"); QModelIndex index = m_model->index(m_model->rowCount()-1,0,QModelIndex()); if (index.isValid()) { m_tree->expand(index); } } } void FileSystemWidget::setRootPathList(const QStringList &pathList) { m_model->setRootPathList(pathList); currentEditorChanged(m_liteApp->editorManager()->currentEditor()); } void FileSystemWidget::setRootPath(const QString &path) { m_model->setRootPath(path); if (m_bHideRoot) { m_tree->expand(this->rootIndex()); } else { m_tree->expandToDepth(0); } } QString FileSystemWidget::rootPath() const { QStringList paths = m_model->rootPathList(); if (!paths.isEmpty()) { return paths.first(); } return QString(); } QStringList FileSystemWidget::rootPathList() const { return m_model->rootPathList(); } void FileSystemWidget::setStartIndex(const QModelIndex &index) { QModelIndex oldIndex = m_model->startIndex(); if (oldIndex != index) { m_model->setStartIndex(index); m_tree->update(oldIndex); m_tree->update(index); emit startPathChanged(m_model->filePath(index)); } } QString FileSystemWidget::startPath() const { QModelIndex index = m_model->startIndex(); return m_model->filePath(index); } void FileSystemWidget::pathIndexChanged(const QModelIndex & index) { FileNode *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 FileSystemWidget::openPathIndex(const QModelIndex &index) { FileNode *node = m_model->nodeFromIndex(index); if (!node) { return; } if (node->isFile()) { //QFileInfo info(node->path()); QString mimeType = m_liteApp->mimeTypeManager()->findMimeTypeByFile(node->path()); if (mimeType.startsWith("text/") || mimeType.startsWith("application/")) { m_liteApp->fileManager()->openEditor(node->path()); return; } // QString cmd = FileUtil::lookPathInDir(info.fileName(),info.path()); // if (cmd == node->path()) { // LiteApi::ILiteBuild *build = LiteApi::getLiteBuild(m_liteApp); // if (build) { // build->executeCommand(info.fileName(),QString(),info.path()); // return; // } // } m_liteApp->fileManager()->openEditor(node->path(),true); } } void FileSystemWidget::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_tree->setCurrentIndex(index); m_tree->scrollTo(index,QAbstractItemView::EnsureVisible); if (m_syncProject->isChecked()) { setStartIndex(index.parent()); } } } */ } void FileSystemWidget::syncEditor(bool b) { if (!b) { // m_syncProject->setChecked(false); } } void FileSystemWidget::expandStartPath(QString) { m_tree->scrollTo(m_model->startIndex(),QAbstractItemView::EnsureVisible); }
24,404
C++
.cpp
687
28.965066
139
0.625566
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,544
editormanager.cpp
visualfc_liteide/liteidex/src/liteapp/editormanager.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: editormanager.cpp // Creator: visualfc <visualfc@gmail.com> #include "editormanager.h" #include "liteapp_global.h" #include "liteapi/liteids.h" #include "liteenvapi/liteenvapi.h" #include "terminalapi/terminalapi.h" #include <QFileInfo> #include <QTabWidget> #include <QMessageBox> #include <QMenu> #include <QAction> #include <QStackedWidget> #include <QToolBar> #include <QVBoxLayout> #include <QFileInfo> #include <QFileDialog> #include <QEvent> #include <QKeyEvent> #include <QTabBar> #include <QApplication> #include <QStatusBar> #include <QToolButton> #include <QComboBox> #include <QTextCodec> #include <QClipboard> #include <QLabel> #include <QStandardItemModel> #include <QHeaderView> #include <QDebug> #include "fileutil/fileutil.h" #include "liteapp.h" #include "openeditorswidget.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 EditorManager::~EditorManager() { delete m_tabContextFileMenu; delete m_tabContextNofileMenu; delete m_editorTabWidget; delete m_listMenu; delete m_openEditorWidget; m_browserActionMap.clear(); if (!m_nullMenu->parent()) { delete m_nullMenu; } } bool EditorManager::initWithApp(IApplication *app) { if (!IEditorManager::initWithApp(app)) { return false; } m_updateMenuInFocus = false; m_mouseExtNavigate = true; m_nullMenu = new QMenu; m_nullMenu->setEnabled(false); m_currentNavigationHistoryPosition = 0; m_colorStyleScheme = new ColorStyleScheme(this); m_maxEditorCount = m_liteApp->settings()->value(LITEAPP_MAXEDITORCOUNT,64).toInt(); m_widget = new QWidget; //create editor tab widget m_editorTabWidget = new LiteTabWidget(LiteApi::getToolBarIconSize(m_liteApp)); //create list menu m_listMenu = new QMenu; m_listGroup = new QActionGroup(this); m_editorTabWidget->setListMenu(m_listMenu); connect(m_listMenu,SIGNAL(aboutToShow()),this,SLOT(aboutToShowListMenu())); connect(m_listGroup,SIGNAL(triggered(QAction*)),this,SLOT(triggeredListAction(QAction*))); //create editor model m_editorModel = new QStandardItemModel(this); //create opne editor for model m_openEditorWidget = new OpenEditorsWidget(app); m_openEditorWidget->setEditorModel(m_editorModel); m_liteApp->toolWindowManager()->addToolWindow(Qt::LeftDockWidgetArea,m_openEditorWidget,"OpenEditor",tr("Open Editor"),true); m_editorTabWidget->tabBar()->setTabsClosable(m_liteApp->settings()->value(LITEAPP_EDITTABSCLOSABLE,true).toBool()); m_editorTabWidget->tabBar()->setEnableWheel(m_liteApp->settings()->value(LITEAPP_EDITTABSENABLEWHELL,true).toBool()); //m_editorTabWidget->tabBar()->setIconSize(LiteApi::getToolBarIconSize()); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->setMargin(0); mainLayout->setSpacing(0); // QToolBar *toolBar = m_editorTabWidget->headerToolBar(); // toolBar->setObjectName("toolbar/tabs"); // m_liteApp->actionManager()->insertToolBar(toolBar); // m_editorTabWidget->headerToolBar()->setAllowedAreas(Qt::TopToolBarArea|Qt::BottomToolBarArea); mainLayout->addWidget(m_editorTabWidget->tabBarWidget()); mainLayout->addWidget(m_editorTabWidget->stackedWidget()); m_widget->setLayout(mainLayout); connect(m_editorTabWidget,SIGNAL(currentChanged(int)),this,SLOT(editorTabChanged(int))); connect(m_editorTabWidget,SIGNAL(tabCloseRequested(int)),this,SLOT(editorTabCloseRequested(int))); connect(m_editorTabWidget,SIGNAL(tabAddRequest()),this,SIGNAL(tabAddRequest())); m_editorTabWidget->stackedWidget()->installEventFilter(this); m_editorTabWidget->tabBar()->installEventFilter(this); m_tabContextFileMenu = new QMenu; m_tabContextNofileMenu = new QMenu; m_tabContextIndex = -1; QAction *closeAct = new QAction(tr("Close"),this); closeAct->setShortcut(QKeySequence("Ctrl+W")); QAction *closeOthersAct = new QAction(tr("Close Others"),this); QAction *closeAllAct = new QAction(tr("Close All"),this); QAction *closeLeftAct = new QAction(tr("Close Left Tabs"),this); QAction *closeRightAct = new QAction(tr("Close Right Tabs"),this); QAction *closeSameFolderFiles = new QAction(tr("Close Files in Same Folder"),this); QAction *closeOtherFolderFiles = new QAction(tr("Close Files in Other Folders"),this); QAction *copyPathToClipboard = new QAction(tr("Copy Full Path to Clipboard"),this); #if defined(Q_OS_WIN) QAction *showInExplorer = new QAction(tr("Show in Explorer"),this); #elif defined(Q_OS_MAC) QAction *showInExplorer = new QAction(tr("Show in Finder"),this); #else QAction *showInExplorer = new QAction(tr("Show Containing Folder"),this); #endif #ifdef Q_OS_WIN QAction *openInShell = new QAction(tr("Open Command Prompt Here"),this); #else QAction *openInShell = new QAction(tr("Open Terminal Here"),this); #endif QAction *openTerminal = new QAction(tr("Open in Integrated Terminal"),this); QAction *moveToAct = new QAction(tr("Move to New Window"),this); m_tabContextFileMenu->addAction(closeAct); m_tabContextFileMenu->addAction(closeOthersAct); m_tabContextFileMenu->addAction(closeLeftAct); m_tabContextFileMenu->addAction(closeRightAct); m_tabContextFileMenu->addAction(closeAllAct); m_tabContextFileMenu->addSeparator(); m_tabContextFileMenu->addAction(closeSameFolderFiles); m_tabContextFileMenu->addAction(closeOtherFolderFiles); m_tabContextFileMenu->addSeparator(); m_tabContextFileMenu->addAction(copyPathToClipboard); m_tabContextFileMenu->addAction(showInExplorer); m_tabContextFileMenu->addAction(openInShell); m_tabContextFileMenu->addAction(openTerminal); m_tabContextFileMenu->addSeparator(); m_tabContextFileMenu->addAction(moveToAct); m_tabContextNofileMenu->addAction(closeAct); m_tabContextNofileMenu->addAction(closeOthersAct); m_tabContextNofileMenu->addAction(closeLeftAct); m_tabContextNofileMenu->addAction(closeRightAct); m_tabContextNofileMenu->addAction(closeAllAct); connect(closeAct,SIGNAL(triggered()),this,SLOT(tabContextClose())); connect(closeOthersAct,SIGNAL(triggered()),this,SLOT(tabContextCloseOthers())); connect(closeLeftAct,SIGNAL(triggered()),this,SLOT(tabContextCloseLefts())); connect(closeRightAct,SIGNAL(triggered()),this,SLOT(tabContextCloseRights())); connect(closeAllAct,SIGNAL(triggered()),this,SLOT(tabContextCloseAll())); connect(closeSameFolderFiles,SIGNAL(triggered()),this,SLOT(tabContextCloseSameFolderFiles())); connect(closeOtherFolderFiles,SIGNAL(triggered()),this,SLOT(tabContextCloseOtherFolderFiles())); connect(copyPathToClipboard,SIGNAL(triggered()),this,SLOT(tabContextCopyPathToClipboard())); connect(showInExplorer,SIGNAL(triggered()),this,SLOT(tabContextShowInExplorer())); connect(openInShell,SIGNAL(triggered()),this,SLOT(tabContextOpenInShell())); connect(openTerminal,SIGNAL(triggered()),this,SLOT(tabContextOpenInTerminal())); connect(moveToAct,SIGNAL(triggered()),this,SLOT(moveToNewWindow())); connect(qApp,SIGNAL(focusChanged(QWidget*,QWidget*)),this,SLOT(focusChanged(QWidget*,QWidget*))); QStatusBar *bar = m_liteApp->mainWindow()->statusBar(); m_lineInfo = new QLabel("000:000"); bar->addPermanentWidget(m_lineInfo); LiteApi::IAppIdleTimer *idleTimer = LiteApi::GetAppIdleTimer(m_liteApp); if (idleTimer) { connect(idleTimer,SIGNAL(appIdle(int)),this,SLOT(appIdle(int))); } m_editorTabWidget->tabBar()->setElideMode(Qt::ElideNone); applyOption(OPTION_LITEAPP); return true; } void EditorManager::createActions() { m_editMenu = m_liteApp->actionManager()->loadMenu(ID_MENU_EDIT); QToolBar *toolBar = m_liteApp->actionManager()->loadToolBar(ID_TOOLBAR_STD); m_goBackAct = new QAction(tr("Navigate Backward"),this); m_goBackAct->setIcon(QIcon("icon:images/backward.png")); m_goForwardAct = new QAction(tr("Navigate Forward"),this); m_goForwardAct->setIcon(QIcon("icon:images/forward.png")); m_gotoNextTab = new QAction(tr("Go to next tab"),this); m_gotoPrevTab = new QAction(tr("Go to previous tab"),this); IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(m_liteApp,"App"); #ifdef Q_OS_MAC actionContext->regAction(m_goBackAct,"Backward","Ctrl+Alt+Left"); actionContext->regAction(m_goForwardAct,"Forward","Ctrl+Alt+Right"); actionContext->regAction(m_gotoNextTab,"GotoNextTab","Alt+Tab"); actionContext->regAction(m_gotoPrevTab,"GotoPreviusTab","Alt+Shift+Tab"); #else actionContext->regAction(m_goBackAct,"Backward","Alt+Left"); actionContext->regAction(m_goForwardAct,"Forward","Alt+Right"); actionContext->regAction(m_gotoNextTab,"GotoNextTab","Ctrl+Tab"); actionContext->regAction(m_gotoPrevTab,"GotoPreviusTab","Ctrl+Shift+Tab"); #endif m_liteApp->actionManager()->setViewMenuSeparator("sep/nav",true); m_liteApp->actionManager()->insertViewMenuAction(m_goBackAct,"sep/nav"); m_liteApp->actionManager()->insertViewMenuAction(m_goForwardAct,"sep/nav"); updateNavigatorActions(); toolBar->addSeparator(); toolBar->addAction(m_goBackAct); toolBar->addAction(m_goForwardAct); m_widget->addAction(m_gotoNextTab); m_widget->addAction(m_gotoPrevTab); connect(m_goBackAct,SIGNAL(triggered()),this,SLOT(goBack())); connect(m_goForwardAct,SIGNAL(triggered()),this,SLOT(goForward())); connect(m_gotoNextTab,SIGNAL(triggered()),this,SLOT(gotoNextTab())); connect(m_gotoPrevTab,SIGNAL(triggered()),this,SLOT(gotoPrevTab())); } QWidget *EditorManager::widget() { return m_widget; } void EditorManager::editorTabChanged(int /*index*/) { QWidget *w = m_editorTabWidget->currentWidget(); if (w == 0) { this->setCurrentEditor(0); } else { IEditor *ed = m_widgetEditorMap.value(w,0); this->setCurrentEditor(ed); } } void EditorManager::editorTabCloseRequested(int index) { QWidget *w = m_editorTabWidget->widget(index); IEditor *ed = m_widgetEditorMap.value(w,0); closeEditor(ed); } QList<IEditor*> EditorManager::sortedEditorList() const { QList<IEditor*> editorList; foreach (QWidget *w,m_editorTabWidget->widgetList()) { IEditor *ed = m_widgetEditorMap.value(w); if (ed) { editorList << ed; } } return editorList; } class EditorItem : public QStandardItem { public: LiteApi::IEditor *editor; }; void EditorManager::addEditor(IEditor *editor) { QWidget *w = m_widgetEditorMap.key(editor,0); if (w == 0) { w = editor->widget(); if (w == 0) { return; } m_editorTabWidget->addTab(w,QIcon(),editor->name(),editor->filePath()); m_widgetEditorMap.insert(w,editor); emit editorCreated(editor); connect(editor,SIGNAL(modificationChanged(bool)),this,SLOT(modificationChanged(bool))); LiteApi::IEditContext *context = LiteApi::getEditContext(editor); if (context) { this->addEditContext(context); } if (!editor->filePath().isEmpty()) { QStandardItem *item = new QStandardItem(editor->name()); item->setToolTip(editor->filePath()); m_editorModel->appendRow(QList<QStandardItem*>() << item); } } } void EditorManager::gotoNextTab() { int index = m_editorTabWidget->tabBar()->currentIndex(); index++; if (index >= m_editorTabWidget->tabBar()->count()) { index = 0; } m_editorTabWidget->setCurrentIndex(index); // qDebug() << "Changing to next tab:" << index; } void EditorManager::gotoPrevTab() { int index = m_editorTabWidget->tabBar()->currentIndex(); index--; if (index < 0) { index = m_editorTabWidget->tabBar()->count()-1; } m_editorTabWidget->setCurrentIndex(index); // qDebug() << "Changing to previous tab:" << index; } bool EditorManager::eventFilter(QObject *target, QEvent *event) { if (event->type() == QEvent::MouseButtonDblClick && target == m_editorTabWidget->tabBar()) { QMouseEvent *ev = (QMouseEvent*)event; if (ev->button() == Qt::LeftButton) { emit doubleClickedTab(); } } else if (event->type() == QEvent::MouseButtonPress) { QMouseEvent *ev = (QMouseEvent*)event; if (m_mouseExtNavigate) { if ( ev->button() == 0x00000008/*Qt::BackButton*/) { this->goBack(); } else if (ev->button() == 0x00000010/*Qt::ForwardButton*/) { this->goForward(); } } if (target == m_editorTabWidget->tabBar()) { if (ev->button() == Qt::RightButton) { m_tabContextIndex = m_editorTabWidget->tabBar()->tabAt(ev->pos()); if (m_tabContextIndex >= 0) { QString filePath = tabContextFilePath(); if (filePath.isEmpty()) { m_tabContextNofileMenu->popup(ev->globalPos()); } else { m_tabContextFileMenu->popup(ev->globalPos()); } } } else if (ev->button() == Qt::MiddleButton) { int index = m_editorTabWidget->tabBar()->tabAt(ev->pos()); if (index >= 0) { editorTabCloseRequested(index); } } } } return IEditorManager::eventFilter(target,event); } QString EditorManager::tabContextFilePath() const { if (m_tabContextIndex < 0) { return QString(); } QWidget *w = m_editorTabWidget->widget(m_tabContextIndex); IEditor *ed = m_widgetEditorMap.value(w,0); if (!ed) { return QString(); } return ed->filePath(); } QAction *EditorManager::registerBrowser(IEditor *editor) { QAction *act = new QAction(editor->name(),this); act->setCheckable(true); act->setChecked(false); connect(act,SIGNAL(toggled(bool)),this,SLOT(toggleBrowserAction(bool))); m_browserActionMap.insert(editor,act); return act; } void EditorManager::activeBrowser(IEditor *editor) { QAction *act = m_browserActionMap.value(editor); if (!act) { return; } if (!act->isChecked()) { act->toggle(); } setCurrentEditor(editor); } bool EditorManager::closeEditor(IEditor *editor) { if (!editor) { editor = m_currentEditor; } if (editor == 0) { return false; } if (editor->isModified() && !editor->isReadOnly()) { QString text = QString(tr("Save changes to %1?")).arg(editor->filePath()); int ret = QMessageBox::question(m_widget,tr("Unsaved Modifications"),text,QMessageBox::Save | QMessageBox::No | QMessageBox::Cancel); if (ret == QMessageBox::Cancel) { return false; } else if (ret == QMessageBox::Save) { //cur->save(); saveEditor(editor); } } if (!editor->filePath().isEmpty()) { m_liteApp->settings()->setValue(QString("state_%1").arg(editor->filePath()),editor->saveState()); } int index = m_editorTabWidget->indexOf(editor->widget()); if (index < 0) { return false; } emit editorAboutToClose(editor); m_editorTabWidget->removeTab(index); m_widgetEditorMap.remove(editor->widget()); QString filePath = editor->filePath(); if (!filePath.isEmpty()) { for (int i = 0; i < m_editorModel->rowCount(); i++) { QStandardItem *item = m_editorModel->item(i,0); if (item->toolTip() == filePath) { m_editorModel->removeRow(i); break; } } } QMapIterator<IEditor*,QAction*> i(m_browserActionMap); while (i.hasNext()) { i.next(); if (i.key() == editor) { i.value()->blockSignals(true); i.value()->setChecked(false); i.value()->blockSignals(false); return true; } } LiteApi::IEditContext *context = LiteApi::getEditContext(editor); if (context) { this->removeEditContext(context); } editor->deleteLater(); return true; } bool EditorManager::saveEditor(IEditor *editor, bool emitAboutSave) { IEditor *cur = 0; if (editor) { cur = editor; } else { cur = m_currentEditor; } if (cur && cur->isModified()) { if (emitAboutSave) { emit editorAboutToSave(cur); } if (cur->save()) { emit editorSaved(cur); } else if (cur->isReadOnly()){ m_liteApp->appendLog("Editor",QString("File is read only %1").arg(cur->filePath()),false); } else { m_liteApp->appendLog("Editor",QString("Failed to save %1").arg(cur->filePath()),true); } return true; } return false; } bool EditorManager::saveEditorAs(IEditor *editor) { IEditor *cur = 0; if (editor) { cur = editor; } else { cur = m_currentEditor; } if (cur == 0) { return false; } QString fileName = cur->filePath(); if (fileName.isEmpty()) { return false; } QFileInfo info(fileName); QStringList filter; QString ext = info.suffix(); if (!ext.isEmpty()) { filter.append(QString("%1 (*.%1)").arg(ext).arg(ext)); } filter.append(tr("All Files (*)")); QString path = info.absolutePath(); QString saveFileName = QFileDialog::getSaveFileName(m_liteApp->mainWindow(),tr("Save As"),path,filter.join(";;")); if (FileUtil::compareFile(fileName,saveFileName,false)) { return false; } if (!cur->saveAs(saveFileName)) { return false; } QWidget *w = m_widgetEditorMap.key(cur,0); if(w) { int index = m_editorTabWidget->indexOf(w); m_editorTabWidget->setTabText(index,cur->name()); } emit currentEditorChanged(cur); return true; } bool EditorManager::saveAllEditors(bool emitAboutSave) { QList<IEditor*> editorList = m_widgetEditorMap.values(); foreach (IEditor *editor, editorList) { saveEditor(editor,emitAboutSave); } return true; } bool EditorManager::closeAllEditors() { bool bCloseAll = true; QMapIterator<QWidget *, IEditor *> i (m_widgetEditorMap); while (i.hasNext()) { i.next(); if (!closeEditor(i.value())) { bCloseAll = false; break; } } return bCloseAll; } IEditor *EditorManager::currentEditor() const { return m_currentEditor; } void EditorManager::updateEditorMenu(IEditContext *context) { if (context && context->focusMenu()) { #if defined(Q_OS_OSX) // dirty trick to show the correct edit menu at the first time on Mac OS X m_editMenu->setEnabled(false); #endif m_editMenu->menuAction()->setMenu(context->focusMenu()); m_editMenu->setEnabled(true); } else { m_editMenu->menuAction()->setMenu(m_nullMenu); m_editMenu->setEnabled(false); } if (context && context->focusToolBar()) { context->focusToolBar()->setEnabled(true); } } void EditorManager::setCurrentEditor(IEditor *editor, bool ignoreNavigationHistory) { if (m_currentEditor == editor) { return; } if (editor && !ignoreNavigationHistory) { this->addNavigationHistory(); } m_currentEditor = editor; this->updateEditInfo(""); if (editor != 0) { m_editorTabWidget->setCurrentWidget(editor->widget()); editor->onActive(); } if (!m_updateMenuInFocus) { IEditContext *context = LiteApi::getEditContext(editor); updateEditorMenu(context); } emit currentEditorChanged(editor); } IEditor *EditorManager::findEditor(const QString &fileName, bool canonical) const { QMapIterator<QWidget *, IEditor *> i(m_widgetEditorMap); while (i.hasNext()) { i.next(); if (FileUtil::compareFile(i.value()->filePath(),fileName,canonical)) { return i.value(); } } return 0; } QList<IEditor*> EditorManager::editorList() const { return m_widgetEditorMap.values(); } void EditorManager::addFactory(IEditorFactory *factory) { m_factoryList.append(factory); } void EditorManager::removeFactory(IEditorFactory *factory) { m_factoryList.removeOne(factory); } QList<IEditorFactory*> EditorManager::factoryList() const { return m_factoryList; } QStringList EditorManager::mimeTypeList() const { QStringList types; foreach(IEditorFactory *factory, m_factoryList) { types.append(factory->mimeTypes()); } return types; } IEditor *EditorManager::openEditor(const QString &fileName, const QString &mimeType) { IEditor *editor = findEditor(fileName,true); if (editor) { return editor; } bool matchFactory = false; foreach (IEditorFactory *factory, m_factoryList) { if (factory->mimeTypes().contains(mimeType)) { matchFactory = true; try { editor = factory->open(fileName,mimeType); } catch(std::bad_alloc &ba) { m_liteApp->appendLog("EditorManager",QString("exception %1! can not load file %2").arg(ba.what()).arg(fileName),true); return 0; } if (editor) { break; } } } if (editor == 0 && !matchFactory) { QString type = "liteide/default.editor"; foreach (IEditorFactory *factory, m_factoryList) { if (factory->mimeTypes().contains(type)) { try { editor = factory->open(fileName,type); } catch(std::bad_alloc &ba) { m_liteApp->appendLog("EditorManager",QString("exception %1! can not load file %2").arg(ba.what()).arg(fileName),true); return 0; } if (editor) { break; } } } } if (editor) { addEditor(editor); ITextEditor *textEditor = getTextEditor(editor); if (textEditor) { textEditor->restoreState(m_liteApp->settings()->value(QString("state_%1").arg(editor->filePath())).toByteArray()); } while (m_editorTabWidget->tabBar()->count() > m_maxEditorCount) { this->closeEditorForTab(0); } } return editor; } IEditor *EditorManager::openEditorByFactory(const QString &fileName, const QString &mimeType, const QString &factoryId) { IEditor *editor1 = findEditor(fileName,true); IEditor *editor = 0; foreach (IEditorFactory *factory, m_factoryList) { if (factory->id() == factoryId) { if (factory->testMimeType(mimeType)) { try { editor = factory->open(fileName,mimeType); } catch(std::bad_alloc &ba) { m_liteApp->appendLog("EditorManager",QString("exception %1! can not load file %2").arg(ba.what()).arg(fileName),true); return 0; } if (editor) { break; } } break; } } if (editor1) { if (editor) { this->closeEditor(editor1); } else { return editor1; } } if (editor) { addEditor(editor); ITextEditor *textEditor = getTextEditor(editor); if (textEditor) { textEditor->restoreState(m_liteApp->settings()->value(QString("state_%1").arg(editor->filePath())).toByteArray()); } while (m_editorTabWidget->tabBar()->count() > m_maxEditorCount) { this->closeEditorForTab(0); } } return editor; } void EditorManager::toggleBrowserAction(bool b) { QAction *act = (QAction*)sender(); if (act) { IEditor *editor = m_browserActionMap.key(act,0); if (editor) { if (b) { addEditor(editor); setCurrentEditor(editor); } else { closeEditor(editor); } } } } void EditorManager::modificationChanged(bool b) { IEditor *editor = static_cast<IEditor*>(sender()); if (editor) { QString text = editor->name(); QString filePath = editor->filePath(); if (b) { text += " *"; } int index = m_editorTabWidget->indexOf(editor->widget()); if (index >= 0) { m_editorTabWidget->setTabText(index,text); } for (int i = 0; i < m_editorModel->rowCount(); i++) { QStandardItem *item = m_editorModel->item(i,0); if (item->toolTip() == filePath) { item->setText(text); break; } } emit editorModifyChanged(editor,b); } } void EditorManager::addNavigationHistory(IEditor *editor,const QByteArray &saveState) { if (editor && editor != currentEditor()) { return; // we only save editor sate for the current editor, when the user interacts } if (!editor) editor = currentEditor(); if (!editor) return; QString filePath = editor->filePath(); if (filePath.isEmpty()) { return; } QByteArray state; if (saveState.isNull()) { state = editor->saveState(); } else { state = saveState; } m_currentNavigationHistoryPosition = qMin(m_currentNavigationHistoryPosition, m_navigationHistory.size()); // paranoia if (m_currentNavigationHistoryPosition > 0 && m_currentNavigationHistoryPosition <= m_navigationHistory.size()) { EditLocation &prev = m_navigationHistory[m_currentNavigationHistoryPosition-1]; if (prev.filePath == filePath && prev.state == state) { return; } } EditLocation location; location.filePath = filePath; location.state = state; m_navigationHistory.insert(m_currentNavigationHistoryPosition, location); ++m_currentNavigationHistoryPosition; while (m_navigationHistory.size() >= 100) { if (m_currentNavigationHistoryPosition > 50) { m_navigationHistory.removeFirst(); --m_currentNavigationHistoryPosition; } else { m_navigationHistory.removeLast(); } } updateNavigatorActions(); } void EditorManager::goBack() { updateCurrentPositionInNavigationHistory(); if (m_currentNavigationHistoryPosition > 0) { --m_currentNavigationHistoryPosition; EditLocation location = m_navigationHistory.at(m_currentNavigationHistoryPosition); IEditor *editor = m_liteApp->fileManager()->openEditor(location.filePath,true,true); if (editor) { editor->restoreState(location.state); } else { m_navigationHistory.removeAt(m_currentNavigationHistoryPosition); } } updateNavigatorActions(); } void EditorManager::goForward() { updateCurrentPositionInNavigationHistory(); if (m_currentNavigationHistoryPosition >= m_navigationHistory.size()-1) return; ++m_currentNavigationHistoryPosition; EditLocation location = m_navigationHistory.at(m_currentNavigationHistoryPosition); IEditor *editor = m_liteApp->fileManager()->openEditor(location.filePath,true,true); if (!editor) { return; } editor->restoreState(location.state); updateNavigatorActions(); } void EditorManager::updateNavigatorActions() { m_goBackAct->setEnabled(m_currentNavigationHistoryPosition > 0); m_goForwardAct->setEnabled(m_currentNavigationHistoryPosition < m_navigationHistory.size()-1); } void EditorManager::cutForwardNavigationHistory() { while (m_currentNavigationHistoryPosition < m_navigationHistory.size() - 1) m_navigationHistory.removeLast(); } void EditorManager::loadColorStyleScheme(const QString &fileName) { if (m_colorStyleScheme->load(fileName)) { emit colorStyleSchemeChanged(); } } const ColorStyleScheme *EditorManager::colorStyleScheme() const { return m_colorStyleScheme; } void EditorManager::addEditContext(IEditContext *context) { m_editContextMap.insert(context->focusWidget(),context); } void EditorManager::removeEditContext(IEditContext *context) { m_editContextMap.remove(context->focusWidget()); } void EditorManager::updateEditInfo(const QString &info) { m_lineInfo->setText(info); } void EditorManager::updateCurrentPositionInNavigationHistory() { IEditor *editor = currentEditor(); if (!editor) return; QString filePath = editor->filePath(); if(filePath.isEmpty()) { return; } EditLocation *location; if (m_currentNavigationHistoryPosition < m_navigationHistory.size()) { location = &m_navigationHistory[m_currentNavigationHistoryPosition]; } else { m_navigationHistory.append(EditLocation()); location = &m_navigationHistory[m_navigationHistory.size()-1]; } location->filePath = filePath; location->state = editor->saveState(); } void EditorManager::tabContextClose() { if (m_tabContextIndex < 0) { return; } editorTabCloseRequested(m_tabContextIndex); } void EditorManager::tabContextCloseOthers() { if (m_tabContextIndex < 0) { return; } QList<IEditor*> closeList; for (int i = 0; i < m_editorTabWidget->tabBar()->count(); i++) { if (i != m_tabContextIndex) { QWidget *w = m_editorTabWidget->widget(i); IEditor *ed = m_widgetEditorMap.value(w,0); closeList << ed; } } foreach(IEditor *ed, closeList ) { closeEditor(ed); } } void EditorManager::tabContextCloseLefts() { if (m_tabContextIndex < 0) { return; } QList<IEditor*> closeList; for (int i = 0; i < m_tabContextIndex; i++) { QWidget *w = m_editorTabWidget->widget(i); IEditor *ed = m_widgetEditorMap.value(w,0); closeList << ed; } foreach(IEditor *ed, closeList ) { closeEditor(ed); } } void EditorManager::tabContextCloseRights() { if (m_tabContextIndex < 0) { return; } QList<IEditor*> closeList; for (int i = m_tabContextIndex+1; i < m_editorTabWidget->tabBar()->count(); i++) { QWidget *w = m_editorTabWidget->widget(i); IEditor *ed = m_widgetEditorMap.value(w,0); closeList << ed; } foreach(IEditor *ed, closeList ) { closeEditor(ed); } } void EditorManager::tabContextCloseAll() { closeAllEditors(); } void EditorManager::tabContextCopyPathToClipboard() { QString filePath = tabContextFilePath(); if (filePath.isEmpty()) { return; } qApp->clipboard()->setText(QDir::toNativeSeparators(filePath)); } void EditorManager::tabContextShowInExplorer() { QString filePath = tabContextFilePath(); if (filePath.isEmpty()) { return; } FileUtil::openInExplorer(filePath); } void EditorManager::tabContextOpenInShell() { QString filePath = tabContextFilePath(); if (filePath.isEmpty()) { return; } QProcessEnvironment env = LiteApi::getCurrentEnvironment(m_liteApp); FileUtil::openInShell(env,filePath); } void EditorManager::tabContextOpenInTerminal() { QString filePath = tabContextFilePath(); if (filePath.isEmpty()) { return; } QFileInfo info(filePath); LiteApi::ITerminal *terminal = LiteApi::getTerminalManager(m_liteApp); if (terminal) { terminal->openDefaultTerminal(info.path()); } } void EditorManager::tabContextCloseOtherFolderFiles() { QString filePath = tabContextFilePath(); if (filePath.isEmpty()) { return; } QFileInfo info(filePath); QString path = info.path(); QList<IEditor*> closeList; for (int i = 0; i < m_editorTabWidget->tabBar()->count(); i++) { if (i != m_tabContextIndex) { QWidget *w = m_editorTabWidget->widget(i); IEditor *ed = m_widgetEditorMap.value(w,0); QString filePath = ed->filePath(); if (filePath.isEmpty()) { continue; } QFileInfo info(filePath); if (info.path() != path) { closeList << ed; } } } foreach(IEditor *ed, closeList ) { closeEditor(ed); } } void EditorManager::tabContextCloseSameFolderFiles() { if (m_tabContextIndex < 0) { return; } QWidget *w = m_editorTabWidget->widget(m_tabContextIndex); IEditor *ed = m_widgetEditorMap.value(w,0); if (!ed) { return; } QString filePath = ed->filePath(); if (filePath.isEmpty()) { return; } QFileInfo info(filePath); QString path = info.path(); QList<IEditor*> closeList; closeList << ed; for (int i = 0; i < m_editorTabWidget->tabBar()->count(); i++) { if (i != m_tabContextIndex) { QWidget *w = m_editorTabWidget->widget(i); IEditor *ed = m_widgetEditorMap.value(w,0); QString filePath = ed->filePath(); if (filePath.isEmpty()) { continue; } QFileInfo info(filePath); if (info.path() == path) { closeList << ed; } } } foreach(IEditor *ed, closeList ) { closeEditor(ed); } } void EditorManager::moveToNewWindow() { if (m_tabContextIndex < 0) { return; } QWidget *w = m_editorTabWidget->widget(m_tabContextIndex); IEditor *ed = m_widgetEditorMap.value(w,0); if (!ed) { return; } QString filePath = ed->filePath(); if (filePath.isEmpty()) { return; } QString sessionName = "dir:"+QFileInfo(filePath).dir().dirName(); IApplication *app = m_liteApp->newInstance(sessionName); QFileInfo info(filePath); if (app->fileManager()->openEditor(filePath)) { this->closeEditor(ed); app->fileManager()->addFolderList(info.path()); } } void EditorManager::focusChanged(QWidget *old, QWidget *now) { if (!m_updateMenuInFocus) { return; } IEditContext *context = m_editContextMap.value(now); updateEditorMenu(context); context = m_editContextMap.value(old); if (context && context->focusToolBar()) { context->focusToolBar()->setEnabled(false); } } void EditorManager::aboutToShowListMenu() { m_listMenu->clear(); QList<QAction*> actions = m_listGroup->actions(); qDeleteAll(actions); foreach (QWidget *widget, m_editorTabWidget->widgetList()) { LiteApi::IEditor *editor = m_widgetEditorMap.value(widget); if (!editor) { continue; } QAction *act = new QAction(editor->name()+"\t"+editor->filePath(),m_listGroup); act->setCheckable(true); act->setToolTip(editor->filePath()); m_listGroup->addAction(act); if (m_currentEditor == editor) { act->setChecked(true); } } m_listMenu->addActions(m_listGroup->actions()); } void EditorManager::triggeredListAction(QAction *act) { int index = m_listGroup->actions().indexOf(act); if (index < 0) { return; } m_editorTabWidget->setCurrentIndex(index); } void EditorManager::applyOption(QString id) { if (id != OPTION_LITEAPP) { return; } m_isAutoIdleSaveDocuments = m_liteApp->settings()->value(LITEAPP_AUTOIDLESAVEDOCUMENTS,false).toBool(); m_autoIdleSaveDocumentsTime = m_liteApp->settings()->value(LITEAPP_AUTOIDLESAVEDOCUMENTS_TIME,3).toInt(); if (m_autoIdleSaveDocumentsTime < 1) { m_autoIdleSaveDocumentsTime = 1; } m_maxEditorCount = m_liteApp->settings()->value(LITEAPP_MAXEDITORCOUNT,64).toInt(); m_editorTabWidget->tabBar()->setTabsClosable(m_liteApp->settings()->value(LITEAPP_EDITTABSCLOSABLE,true).toBool()); m_editorTabWidget->tabBar()->setEnableWheel(m_liteApp->settings()->value(LITEAPP_EDITTABSENABLEWHELL,true).toBool()); m_mouseExtNavigate = m_liteApp->settings()->value(LITEAPP_EDITORMOUSEEXTNAVIGATE,true).toBool(); #ifdef Q_OS_MAC #if QT_VERSION >= 0x050900 QString qss = m_liteApp->settings()->value(LITEAPP_QSS,"default.qss").toString(); if (qss == "default.qss") { m_editorTabWidget->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_editorTabWidget->tabBar()->setStyleSheet("QTabBar::close-button:hover,QTabBar::close-button:selected {margin: 0px; image: url(:/images/close.png); subcontrol-position: left; }"); } #endif #endif } void EditorManager::appIdle(int sec) { if (m_isAutoIdleSaveDocuments) { if (sec == m_autoIdleSaveDocumentsTime) { this->saveAllEditors(false); } } } void EditorManager::closeEditorForTab(int index) { QWidget *w = m_editorTabWidget->widget(index); IEditor *ed = m_widgetEditorMap.value(w,0); closeEditor(ed); }
39,369
C++
.cpp
1,116
28.870072
186
0.646982
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,545
textbrowserhtmlwidget.cpp
visualfc_liteide/liteidex/src/liteapp/textbrowserhtmlwidget.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: textbrowserhtmlwidget.cpp // Creator: visualfc <visualfc@gmail.com> #include "textbrowserhtmlwidget.h" #include <QTextBrowser> #include <QScrollBar> #include <QFileInfo> #include <QFile> #include <QTextCursor> #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 TextBrowserHtmlWidget::TextBrowserHtmlWidget(QObject *parent) : IHtmlWidget(parent) { m_widget = new QTextBrowser; m_widget->setOpenLinks(false); m_widget->setOpenExternalLinks(false); connect(m_widget,SIGNAL(anchorClicked(QUrl)),this,SIGNAL(linkClicked(QUrl))); connect(m_widget,SIGNAL(highlighted(QUrl)),this,SIGNAL(linkHovered(QUrl))); } QWidget *TextBrowserHtmlWidget::widget() const { return m_widget; } QString TextBrowserHtmlWidget::className() const { return QLatin1String("QTextBrowser"); } void TextBrowserHtmlWidget::setSearchPaths(const QStringList &paths) { m_widget->setSearchPaths(paths); } void TextBrowserHtmlWidget::setHtml(const QString &html, const QUrl &url) { m_widget->setHtml(html); m_url = url; if (!url.isEmpty()) { QString file = url.toLocalFile(); if (!file.isEmpty()) { QFileInfo info(file); QStringList paths = m_widget->searchPaths(); paths.append(info.path()); paths.removeDuplicates(); m_widget->setSearchPaths(paths); } } emit contentsSizeChanged(); emit loadFinished(true); } QUrl TextBrowserHtmlWidget::url() const { return m_url; } void TextBrowserHtmlWidget::clear() { m_widget->clear(); } void TextBrowserHtmlWidget::scrollToAnchor(const QString &anchor) { m_widget->scrollToAnchor(anchor); emit anchorChanged(anchor); } void TextBrowserHtmlWidget::setScrollBarValue(Qt::Orientation orientation, int value) { if (orientation == Qt::Horizontal) { m_widget->horizontalScrollBar()->setValue(value); } else { m_widget->verticalScrollBar()->setValue(value); } } int TextBrowserHtmlWidget::scrollBarValue(Qt::Orientation orientation) const { if (orientation == Qt::Horizontal) { return m_widget->horizontalScrollBar()->value(); } return m_widget->verticalScrollBar()->value(); } int TextBrowserHtmlWidget::scrollBarMinimum(Qt::Orientation orientation) const { if (orientation == Qt::Horizontal) { return m_widget->horizontalScrollBar()->minimum(); } return m_widget->verticalScrollBar()->minimum(); } int TextBrowserHtmlWidget::scrollBarMaximum(Qt::Orientation orientation) const { if (orientation == Qt::Horizontal) { return m_widget->horizontalScrollBar()->maximum(); } return m_widget->verticalScrollBar()->maximum(); } QString TextBrowserHtmlWidget::selectedText() const { return m_widget->textCursor().selectedText(); } bool TextBrowserHtmlWidget::findText(const QString &exp, QTextDocument::FindFlags options) { QTextDocument *doc = m_widget->document(); if (!doc) { return false; } QTextCursor cursor = m_widget->cursorForPosition(QPoint(0,0)); int from = cursor.position(); if (cursor.hasSelection()) { if (options & QTextDocument::FindBackward) { from = cursor.selectionStart(); } else { from = cursor.selectionEnd(); } } QTextCursor find; find = doc->find(exp,from,options); if (!find.isNull()) { m_widget->setTextCursor(find); m_widget->ensureCursorVisible(); return true; } return false; } #ifndef QT_NO_PRINTER void TextBrowserHtmlWidget::print(QPrinter *printer) { m_widget->print(printer); } #endif TextBrowserHtmlWidgetFactory::TextBrowserHtmlWidgetFactory(QObject *parent) : IHtmlWidgetFactory(parent) { } QString TextBrowserHtmlWidgetFactory::className() const { return "QTextBrowser"; } IHtmlWidget *TextBrowserHtmlWidgetFactory::create(QObject *parent) { return new TextBrowserHtmlWidget(parent); } IHtmlDocument *TextBrowserHtmlWidgetFactory::createDocument(QObject *parent) { return new TextBrowserHtmlDocument(parent); } TextBrowserHtmlDocument::TextBrowserHtmlDocument(QObject *parent) : IHtmlDocument(parent) { m_doc = new QTextBrowser; m_doc->setVisible(false); } TextBrowserHtmlDocument::~TextBrowserHtmlDocument() { delete m_doc; } void TextBrowserHtmlDocument::setHtml(const QString &html, const QUrl &url) { m_doc->setHtml(html); if (!url.isEmpty()) { QString file = url.toLocalFile(); if (!file.isEmpty()) { QFileInfo info(file); QStringList paths = m_doc->searchPaths(); paths.append(info.path()); paths.removeDuplicates(); m_doc->setSearchPaths(paths); } } emit loadFinished(true); } #ifndef QT_NO_PRINTER void TextBrowserHtmlDocument::print(QPrinter *printer) { m_doc->print(printer); } #endif QString TextBrowserHtmlDocument::toHtml() const { return m_doc->toHtml(); } QString TextBrowserHtmlDocument::toPlainText() const { return m_doc->toPlainText(); }
6,318
C++
.cpp
207
26.714976
90
0.699655
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,546
recentmanager.cpp
visualfc_liteide/liteidex/src/liteapp/recentmanager.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: recentmanager.cpp // Creator: visualfc <visualfc@gmail.com> #include "recentmanager.h" #include "liteapp_global.h" #include "liteapi/liteids.h" #include <QMenu> #include <QAction> //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 RecentManager::RecentManager(QObject *parent) : IRecentManager(parent) { m_maxRecentFiles = 32; } bool RecentManager::initWithApp(IApplication *app) { if (!IRecentManager::initWithApp(app)) { return false; } m_maxRecentFiles = m_liteApp->settings()->value(LITEAPP_MAXRECENTFILES,32).toInt(); m_recentMenu = m_liteApp->actionManager()->loadMenu(ID_MENU_RECENT); QAction *clearAllRecent = new QAction(tr("Clear All History"),this); m_recentSeparator = m_recentMenu->addSeparator(); m_recentMenu->addAction(clearAllRecent); connect(clearAllRecent,SIGNAL(triggered(bool)),this,SLOT(clearAllRecentMenu())); registerRecent(new FileRecent(app,this)); registerRecent(new FolderRecent(app,this)); registerRecent(new SessionRecent(app,this)); connect(m_liteApp->optionManager(),SIGNAL(applyOption(QString)),this,SLOT(applyOption(QString))); return true; } void RecentManager::registerRecent(IRecent *recent) { if (m_recentTypeList.contains(recent->type())) { return; } m_recentTypeList.append(recent->type()); m_recentList.append(recent); updateRecentMenu(recent->type()); } QList<IRecent *> RecentManager::recentList() const { return m_recentList; } IRecent *RecentManager::findRecent(const QString &type) const { foreach (IRecent *recent, m_recentList) { if (recent->type() == type) { return recent; } } return 0; } QStringList RecentManager::recentTypeList() const { return m_recentTypeList; } void RecentManager::addRecent(const QString &name, const QString &type) { IRecent *recent = findRecent(type); if (!recent) { return; } recent->addRecent(name,m_maxRecentFiles); updateAppListRecentMenu(type); } void RecentManager::removeRecent(const QString &name, const QString &type) { IRecent *recent = findRecent(type); if (!recent) { return; } recent->removeRecent(name); updateAppListRecentMenu(type); } QStringList RecentManager::recentNameList(const QString &type) { IRecent *recent = findRecent(type); if (!recent) { return QStringList(); } return recent->recentNameList(); } void RecentManager::clearRecentNameList(const QString &type) { IRecent *recent = findRecent(type); if (!recent) { return; } recent->clearRecentNameList(); updateAppListRecentMenu(type); } void RecentManager::openRecent(const QString &name, const QString &type) { IRecent *recent = findRecent(type); if (recent) { recent->openRecent(name); } } void RecentManager::updateRecentMenu(const QString &type) { IRecent *recent = findRecent(type); if (!recent) { return; } QMenu *menu = m_mapRecentTypeMenu.value(type,0); if (!menu) { QString name = recent->displyType(); QAction *act = new QAction(name,this); m_recentMenu->insertAction(m_recentSeparator,act); menu = new QMenu(type,m_recentMenu); act->setMenu(menu); m_mapRecentTypeMenu.insert(type,menu); } if (!menu) { return; } menu->clear(); QAction *sep = menu->addSeparator(); QAction *clear = menu->addAction(tr("Clear Menu")); clear->setData(type); connect(clear,SIGNAL(triggered(bool)),this,SLOT(clearRecentMenu())); int count = 0; foreach (QString name, this->recentNameList(type)) { if (count++ > m_maxRecentFiles) { return; } QAction *act = new QAction(name,menu); menu->insertAction(sep,act); act->setData(type); connect(act,SIGNAL(triggered()),this,SLOT(openRecentAction())); } } void RecentManager::updateAppListRecentMenu(const QString &type) { foreach (IApplication *app, m_liteApp->instanceList()) { app->recentManager()->updateRecentMenu(type); ((RecentManager*)app->recentManager())->emitRecentNameListChanged(type); } } void RecentManager::emitRecentNameListChanged(const QString &type) { emit recentNameListChanged(type); } void RecentManager::applyOption(const QString &opt) { if (opt != OPTION_LITEAPP) { return; } m_maxRecentFiles = m_liteApp->settings()->value(LITEAPP_MAXRECENTFILES,32).toInt(); } void RecentManager::openRecentAction() { QAction *act = (QAction*)sender(); if (!act) { return; } QString name = act->text(); QString type = act->data().toString(); IRecent *recent = findRecent(type); if (recent) { recent->openRecent(name); } } void RecentManager::clearRecentMenu() { QAction *act = (QAction*)sender(); if (!act) { return; } QString type = act->data().toString(); clearRecentNameList(type); } void RecentManager::clearAllRecentMenu() { foreach (IRecent *recent, m_recentList) { recent->clearRecentNameList(); updateAppListRecentMenu(recent->type()); } }
6,672
C++
.cpp
207
26.884058
102
0.655582
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,547
liteappoptionfactory.cpp
visualfc_liteide/liteidex/src/liteapp/liteappoptionfactory.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: liteappoptionfactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "liteappoption.h" #include "outputoption.h" #include "liteappoptionfactory.h" #include "liteapp_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 LiteAppOptionFactory::LiteAppOptionFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IOptionFactory(parent), m_liteApp(app) { } QStringList LiteAppOptionFactory::mimeTypes() const { return QStringList() << OPTION_LITEAPP << OPTION_LITEOUTPUT; } LiteApi::IOption *LiteAppOptionFactory::create(const QString &mimeType) { if (mimeType == OPTION_LITEAPP) { return new LiteAppOption(m_liteApp,this); } else if (mimeType == OPTION_LITEOUTPUT) { return new OutputOption(m_liteApp,this); } return 0; }
2,047
C++
.cpp
53
36.207547
87
0.68794
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,548
pluginsdialog.cpp
visualfc_liteide/liteidex/src/liteapp/pluginsdialog.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: pluginsdialog.cpp // Creator: visualfc <visualfc@gmail.com> #include "pluginsdialog.h" #include "ui_pluginsdialog.h" #include "pluginmanager.h" #include <QStandardItemModel> #include <QStandardItem> #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 PluginsDialog::PluginsDialog(LiteApi::IApplication *app, QWidget *parent) : QDialog(parent), m_liteApp(app), ui(new Ui::PluginsDialog) { ui->setupUi(this); this->setAttribute(Qt::WA_DeleteOnClose); m_model = new QStandardItemModel(0,6,this); m_model->setHeaderData(0, Qt::Horizontal, tr("Name")); m_model->setHeaderData(1, Qt::Horizontal, tr("Enabled")); m_model->setHeaderData(2, Qt::Horizontal, tr("Details")); m_model->setHeaderData(3, Qt::Horizontal, tr("Author")); m_model->setHeaderData(4, Qt::Horizontal, tr("Version")); m_model->setHeaderData(5, Qt::Horizontal, tr("File Name")); ui->treeView->setModel(m_model); ui->treeView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->treeView->setItemsExpandable(true); ui->treeView->setRootIsDecorated(false); #if QT_VERSION >= 0x050000 ui->treeView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); #else ui->treeView->header()->setResizeMode(QHeaderView::ResizeToContents); #endif connect(m_model,SIGNAL(itemChanged(QStandardItem*)),this,SLOT(itemChanged(QStandardItem*))); } PluginsDialog::~PluginsDialog() { delete ui; } void PluginsDialog::appendInfo(const LiteApi::PluginInfo *info) { if (!info) { return; } QList<QStandardItem*> items; items.append(new QStandardItem(info->name())); QStandardItem *load = new QStandardItem(); load->setCheckable(true); load->setData(info->id()); if (info->isMustLoad()) { load->setEnabled(false); } bool b = m_liteApp->settings()->value(QString("liteapp/%1_load").arg(info->id()),true).toBool(); if (b) { load->setCheckState(Qt::Checked); } else { load->setCheckState(Qt::Unchecked); } items.append(load); items.append(new QStandardItem(info->info())); items.append(new QStandardItem(info->author())); items.append(new QStandardItem(info->ver())); items.append(new QStandardItem(QFileInfo(info->filePath()).fileName())); items.at(5)->setToolTip(info->filePath()); m_model->appendRow(items); } void PluginsDialog::itemChanged(QStandardItem *item) { if (item && item->isCheckable()) { QString id = item->data(Qt::UserRole+1).toString(); if (!id.isEmpty()) { m_liteApp->settings()->setValue(QString("liteapp/%1_load").arg(id),item->checkState() == Qt::Checked); } } }
3,949
C++
.cpp
102
35.068627
114
0.677176
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,549
sidewindowstyle.cpp
visualfc_liteide/liteidex/src/liteapp/sidewindowstyle.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: sidewindowstyle.cpp // Creator: visualfc <visualfc@gmail.com> #include "sidewindowstyle.h" #include "tooldockwidget.h" #include "rotationtoolbutton.h" #include "liteapp_global.h" #include "liteapi/liteids.h" #include <QStatusBar> #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 SideDockWidget::SideDockWidget(QSize iconSize, QWidget *parent) : BaseDockWidget(iconSize,parent) { } void SideDockWidget::createMenu(Qt::DockWidgetArea area) { m_area = area; m_moveMenu = new QMenu(tr("Move To"),this); QAction *sideAct = new QAction(this); if (area == Qt::LeftDockWidgetArea) { sideAct->setText(tr("RightSideBar")); sideAct->setData(Qt::RightDockWidgetArea); m_areaInfo = tr("LeftDockWidgt"); } else { sideAct->setText(tr("LeftSideBar")); sideAct->setData(Qt::LeftDockWidgetArea); m_areaInfo = tr("RightDockWidget"); } m_moveMenu->addAction(sideAct); QAction *outAct = new QAction(tr("OutputBar"),this); outAct->setData(Qt::BottomDockWidgetArea); m_moveMenu->addAction(outAct); connect(sideAct,SIGNAL(triggered()),this,SLOT(moveAction())); connect(outAct,SIGNAL(triggered()),this,SLOT(moveAction())); m_menu = new QMenu(this); QToolButton *btn = new QToolButton(m_toolBar); btn->setPopupMode(QToolButton::InstantPopup); btn->setIcon(QIcon("icon:images/movemenu.png")); btn->setMenu(m_menu); btn->setText(tr("SideBar")); btn->setToolTip(tr("Show SideBar")); btn->setStyleSheet("QToolButton::menu-indicator {image: none;}"); m_toolBar->insertWidget(m_closeAct,btn); } void SideDockWidget::moveAction() { QAction *action = static_cast<QAction*>(sender()); if (!action) { return; } this->setFloatingWindow(false); Qt::DockWidgetArea area = (Qt::DockWidgetArea)action->data().toInt(); emit moveActionTo(m_area,area,current); } void SideDockWidget::actionChanged() { } void SideDockWidget::activeComboBoxIndex(int index) { if (index < 0 || index >= m_comboBox->count()) { return; } QString objName = m_comboBox->itemData(index).toString(); foreach(QAction *act, m_actions) { if (act->objectName() == objName) { QAction *org = current.data(); current = act; emit currenActionChanged(org,act); break; } } } void SideDockWidget::topLevelChanged(bool b) { BaseDockWidget::topLevelChanged(b); if (b) { m_comboBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); m_spacer->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Minimum); } else { m_comboBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); m_spacer->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Minimum); } } void SideDockWidget::setCheckedAction(QAction *action) { current = action; for (int i = 0; i < m_comboBox->count(); i++) { if (m_comboBox->itemData(i).toString() == action->objectName()) { m_comboBox->setCurrentIndex(i); //m_titleLabel->setText(m_comboBox->currentText()); break; } } } static bool actionThan(const QAction *s1, const QAction *s2) { return s1->text() < s2->text(); } void SideDockWidget::setActions(const QMap<QAction *, SideActionState *> &m) { m_actions = m.keys(); m_comboBox->clear(); int cur = 0; int index = 0; m_menu->clear(); // QMapIterator<QAction *, SideActionState *> i(m); QList<QAction*> keys = m.keys(); qSort(keys.begin(),keys.end(),actionThan); for (int i = 0; i < keys.size(); i++) { QAction *act = keys[i]; m_comboBox->addItem(m.value(act)->title,act->objectName()); m_menu->addAction(act); if (current && (current->objectName() == act->objectName())) { cur = index; } index++; } // while(i.hasNext()) { // i.next(); // QAction *act = i.key(); // m_comboBox->addItem(i.value()->title,act->objectName()); // m_menu->addAction(act); // if (current && (current->objectName() == act->objectName())) { // cur = index; // } // index++; // } m_menu->addSeparator(); m_menu->addAction(m_floatAct); m_menu->addMenu(m_moveMenu); m_comboBox->setCurrentIndex(cur); } void SideDockWidget::setWindowTitle(const QString &text) { BaseDockWidget::setWindowTitle(m_areaInfo+" - "+text); } SideActionBar::SideActionBar(QSize iconSize, QMainWindow *window, Qt::DockWidgetArea area) : BaseActionBar(window), m_iconSize(iconSize), m_window(window),m_area(area), m_bHideToolBar(false) { m_toolBar = new QToolBar; m_toolBar->hide(); m_toolBar->setObjectName(QString("side_tool_%1").arg(m_area)); m_toolBar->setMovable(false); // QWidget *spacer = new QWidget; // spacer->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); // spacerAct = toolBar->addWidget(spacer); // toolBar->addSeparator(); } SideActionBar::~SideActionBar() { qDeleteAll(m_actionStateMap); } void SideActionBar::addAction(QAction *action, QWidget *widget, const QString &id, const QString &title, QList<QAction *> widgetActions, QList<QWidget *> widgetList) { RotationToolButton *btn = new RotationToolButton; btn->setDefaultAction(action); if (m_area == Qt::LeftDockWidgetArea) { btn->setRotation(RotationToolButton::CounterClockwise); } else if (m_area == Qt::RightDockWidgetArea) { btn->setRotation(RotationToolButton::Clockwise); } SideDockWidget *dock = new SideDockWidget(m_iconSize, m_window); dock->setObjectName(dockWidgetObjName(id)); dock->setWindowTitle(title); dock->setAllowedAreas(m_area); dock->setFeatures(QDockWidget::DockWidgetClosable); dock->hide(); dock->createMenu(m_area); m_window->addDockWidget(m_area,dock); connect(dock,SIGNAL(visibilityChanged(bool)),this,SLOT(dockVisible(bool))); connect(dock,SIGNAL(moveActionTo(Qt::DockWidgetArea,Qt::DockWidgetArea,QAction*)),this,SIGNAL(moveActionTo(Qt::DockWidgetArea,Qt::DockWidgetArea,QAction*))); connect(dock,SIGNAL(currenActionChanged(QAction*,QAction*)),this,SLOT(currenActionChanged(QAction*,QAction*))); SideActionState *state = new SideActionState; state->toolBtn = btn; state->widget = widget; state->id = id; state->title = title; state->widgetActions = widgetActions; state->widgetList = widgetList; m_actionStateMap.insert(action,state); dock->setCheckedAction(action); //toolBar->insertWidget(spacerAct,btn); m_toolBar->addWidget(btn); if (m_toolBar->isHidden() && !m_bHideToolBar) { m_toolBar->show(); } m_dockList.append(dock); connect(action,SIGNAL(toggled(bool)),this,SLOT(toggledAction(bool))); //update actions foreach(SideDockWidget *dock, m_dockList) { dock->setActions(m_actionStateMap); } } void SideActionBar::removeAction(QAction *action) { for (int i = 0; i < m_dockList.size(); i++) { SideDockWidget *dock = m_dockList[i]; if (dock->checkedAction() == action) { dock->hide(); m_window->removeDockWidget(dock); m_dockList.removeAt(i); m_toolBar->removeAction(action); dock->deleteLater(); break; } } SideActionState *state = m_actionStateMap.value(action); if (state) { delete state->toolBtn; } m_actionStateMap.remove(action); delete state; foreach(SideDockWidget *dock, m_dockList) { dock->setActions(m_actionStateMap); } if (m_actionStateMap.isEmpty()) { m_toolBar->hide(); } } void SideActionBar::setHideToolBar(bool b) { m_bHideToolBar = b; if (m_bHideToolBar) { m_toolBar->hide(); } else { m_toolBar->show(); } } QAction *SideActionBar::findToolAction(QWidget *widget) const { QMapIterator<QAction*,SideActionState*> i(m_actionStateMap); while (i.hasNext()) { i.next(); if (i.value()->widget == widget) { return i.key(); } } return 0; } void SideActionBar::dockVisible(bool b) { SideDockWidget *dock = (SideDockWidget*)sender(); QAction *action = dock->checkedAction(); if (action) { action->setChecked(dock->isVisible()); } else if (b && !dock->actions().isEmpty()) { dock->actions().first()->setChecked(true); } } QString SideActionBar::dockWidgetObjName(const QString &id) const { return QString("side_dock_x_%1").arg(id); } void SideActionBar::updateAction(QAction *action) { SideActionState *state = m_actionStateMap.value(action); foreach (SideDockWidget *dock, m_dockList) { if (dock->checkedAction() == action) { if (action->isChecked()) { if (dock->isHidden()) { dock->show(); } dock->setWidget(state->widget); if (!state->widgetList.isEmpty()) { dock->setWidgetList(state->widgetList); } else { dock->setWidgetActions(state->widgetActions); } dock->setObjectName(dockWidgetObjName(state->id)); dock->setWindowTitle(state->title); state->widget->setVisible(true); } else { dock->hide(); state->widget->setVisible(false); } break; } } } void SideActionBar::setShowToolBar(bool visible) { if (!visible) { m_toolBar->hide(); } else if (!m_actionStateMap.isEmpty()) { m_toolBar->show(); } } void SideActionBar::toggledAction(bool) { QAction *action = (QAction*)sender(); updateAction(action); } void SideActionBar::currenActionChanged(QAction *org, QAction *act) { if (org == act) { return; } SideDockWidget *curDock = (SideDockWidget*)sender(); foreach (SideDockWidget *dock, m_dockList) { if ((dock->checkedAction() == act) && (dock != curDock)) { dock->setCheckedAction(org); org->setChecked(act->isChecked()); updateAction(org); break; } } curDock->setCheckedAction(act); act->setChecked(true); updateAction(act); } OutputActionBar::OutputActionBar(QSize iconSize, QMainWindow *window, Qt::DockWidgetArea _area) : BaseActionBar(window), m_area(_area), m_bHideToolBar(false) { m_toolBar = new QToolBar; m_toolBar->hide(); m_toolBar->setObjectName(QString("side_tool_%1").arg(m_area)); m_toolBar->setMovable(false); // QWidget *spacer = new QWidget; // spacer->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); // spacerAct = toolBar->addWidget(spacer); // toolBar->addSeparator(); m_dock = new OutputDockWidget(iconSize, window); m_dock->setObjectName(QString("side_dock_%1").arg(m_area)); m_dock->setWindowTitle(QString("side_dock_%1").arg(m_area)); m_dock->setFeatures(QDockWidget::DockWidgetClosable); m_dock->hide(); m_dock->createMenu(m_area); window->addDockWidget(m_area,m_dock); connect(m_dock,SIGNAL(visibilityChanged(bool)),this,SLOT(dockVisible(bool))); connect(m_dock,SIGNAL(moveActionTo(Qt::DockWidgetArea,Qt::DockWidgetArea,QAction*)),this,SIGNAL(moveActionTo(Qt::DockWidgetArea,Qt::DockWidgetArea,QAction*))); } OutputActionBar::~OutputActionBar() { qDeleteAll(m_actionStateMap); } OutputDockWidget *OutputActionBar::dockWidget() const { return m_dock; } void OutputActionBar::addAction(QAction *action, QWidget *widget, const QString &id, const QString &title, QList<QAction *> widgetActions, QList<QWidget *> widgetList) { RotationToolButton *btn = new RotationToolButton; btn->setDefaultAction(action); if (m_area == Qt::LeftDockWidgetArea) { btn->setRotation(RotationToolButton::CounterClockwise); } else if (m_area == Qt::RightDockWidgetArea) { btn->setRotation(RotationToolButton::Clockwise); } SideActionState *state = new SideActionState; state->toolBtn = btn; state->widget = widget; state->id = id; state->title = title; state->widgetActions = widgetActions; state->widgetList = widgetList; m_actionStateMap.insert(action,state); m_dock->addAction(action,title); //toolBar->insertWidget(spacerAct,btn); m_toolBar->addWidget(btn); if (m_toolBar->isHidden() && !m_bHideToolBar) { m_toolBar->show(); } connect(action,SIGNAL(toggled(bool)),this,SLOT(toggledAction(bool))); } void OutputActionBar::removeAction(QAction *action) { if (action->isChecked()) { action->setChecked(false); } SideActionState *state = m_actionStateMap.value(action); if (state) { delete state->toolBtn; } m_dock->removeAction(action); m_actionStateMap.remove(action); delete state; if (m_dock->actions().isEmpty()) { m_toolBar->hide(); } } void OutputActionBar::setHideToolBar(bool b) { m_bHideToolBar = b; if (m_bHideToolBar) { m_toolBar->hide(); } else { if (!m_dock->actions().isEmpty()){ m_toolBar->show(); } } } QAction *OutputActionBar::findToolAction(QWidget *widget) const { QMapIterator<QAction*,SideActionState*> i(m_actionStateMap); while (i.hasNext()) { i.next(); if (i.value()->widget == widget) { return i.key(); } } return 0; } void OutputActionBar::dockVisible(bool b) { QAction *action = m_dock->checkedAction(); if (action) { action->setChecked(m_dock->isVisible()); } else if (b && !m_dock->actions().isEmpty()) { // m_dock->actions().first()->setChecked(true) int index = m_dock->currentIndex(); if (index >= 0 && index < m_dock->actions().size()) { m_dock->actions()[index]->setChecked(true); } } } void OutputActionBar::toggledAction(bool) { QAction *action = (QAction*)sender(); SideActionState *state = m_actionStateMap.value(action); if (!state) { return; } if (action->isChecked()) { if (m_dock->isHidden()) { m_dock->show(); } m_dock->setWidget(state->widget); if (!state->widgetList.isEmpty()) { m_dock->setWidgetList(state->widgetList); } else { m_dock->setWidgetActions(state->widgetActions); } m_dock->setWindowTitle(state->title); state->widget->setVisible(true); } else { if (!m_dock->checkedAction()) { m_dock->hide(); state->widget->setVisible(false); } } } SideWindowStyle::SideWindowStyle(LiteApi::IApplication *app, QMainWindow *window, QObject *parent) : IWindowStyle(parent),m_liteApp(app),m_mainWindow(window) { QSize iconSize = LiteApi::getToolBarIconSize(app); m_leftSideBar = new SideActionBar(iconSize,window,Qt::LeftDockWidgetArea); m_rightSideBar = new SideActionBar(iconSize,window,Qt::RightDockWidgetArea); m_outputBar = new OutputActionBar(iconSize,window,Qt::BottomDockWidgetArea); connect(m_leftSideBar,SIGNAL(moveActionTo(Qt::DockWidgetArea,Qt::DockWidgetArea,QAction*)),this,SLOT(moveActionTo(Qt::DockWidgetArea,Qt::DockWidgetArea,QAction*))); connect(m_rightSideBar,SIGNAL(moveActionTo(Qt::DockWidgetArea,Qt::DockWidgetArea,QAction*)),this,SLOT(moveActionTo(Qt::DockWidgetArea,Qt::DockWidgetArea,QAction*))); connect(m_outputBar,SIGNAL(moveActionTo(Qt::DockWidgetArea,Qt::DockWidgetArea,QAction*)),this,SLOT(moveActionTo(Qt::DockWidgetArea,Qt::DockWidgetArea,QAction*))); m_actionBarMap[Qt::LeftDockWidgetArea] = m_leftSideBar; m_actionBarMap[Qt::RightDockWidgetArea] = m_rightSideBar; m_actionBarMap[Qt::BottomDockWidgetArea] = m_outputBar; m_mainWindow->addToolBar(Qt::LeftToolBarArea,m_leftSideBar->toolBar()); m_mainWindow->addToolBar(Qt::RightToolBarArea,m_rightSideBar->toolBar()); m_mainWindow->addDockWidget(Qt::BottomDockWidgetArea,m_outputBar->dockWidget()); m_mainWindow->setDockNestingEnabled(true); m_mainWindow->setDockOptions(QMainWindow::AllowNestedDocks); m_statusBar = new QStatusBar; m_hideSideAct = new QAction(tr("Hide SideBar"),this); m_hideSideAct->setIcon(QIcon("icon:images/hidesidebar.png")); m_hideSideAct->setCheckable(true); QToolButton *btn = new QToolButton; btn->setDefaultAction(m_hideSideAct); btn->setStyleSheet("QToolButton {border:0}" "QToolButton:checked {background : qlineargradient(spread:pad, x1:0, y1:1, x2:1, y2:0, stop:0 rgba(55, 57, 59, 255), stop:1 rgba(255, 255, 255, 255));}"); m_statusBar->addWidget(btn); m_statusBar->setContentsMargins(0,0,0,0); m_statusBar->addWidget(m_outputBar->toolBar(),1); m_mainWindow->setStatusBar(m_statusBar); //m_mainWindow->addToolBar(Qt::BottomToolBarArea,m_outputBar->toolBar); m_sideMenu = 0; m_outputMenu = 0; connect(m_hideSideAct,SIGNAL(toggled(bool)),this,SLOT(hideSideBar(bool))); m_useShortcuts = m_liteApp->settings()->value(LITEAPP_TOOLWINDOW_SHORTCUTS,true).toBool(); } SideWindowStyle::~SideWindowStyle() { delete m_sideMenu; delete m_outputMenu; delete m_leftSideBar; delete m_rightSideBar; } void SideWindowStyle::createToolWindowMenu() { QMenu *menu = m_liteApp->actionManager()->loadMenu(ID_MENU_VIEW); if (menu) { menu->addAction(m_hideSideAct); m_sideMenu = menu->addMenu(tr("SideBar Windows")); m_outputMenu = menu->addMenu(tr("Output Windows")); } LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(m_liteApp,"App"); actionContext->regAction(m_hideSideAct,"HideSideBar",LiteApi::UseMacShortcuts?"Ctrl+Alt+0":"Alt+0"); } void SideWindowStyle::restoreHideToolWindows() { foreach(QAction *action,m_hideActionList) { action->setChecked(true); } m_hideActionList.clear(); } void SideWindowStyle::restoreHideSideToolWindows() { foreach(QAction *action,m_hideSideActionList) { action->setChecked(true); } m_hideSideActionList.clear(); m_leftSideBar->setShowToolBar(true); m_rightSideBar->setShowToolBar(true); } void SideWindowStyle::hideSideToolWindows() { m_hideSideActionList.clear(); foreach(QAction *action, m_leftSideBar->actionMap().keys()) { if (action->isChecked()) { m_hideSideActionList.append(action); action->setChecked(false); } } foreach(QAction *action, m_rightSideBar->actionMap().keys()) { if (action->isChecked()) { m_hideSideActionList.append(action); action->setChecked(false); } } m_leftSideBar->setShowToolBar(false); m_rightSideBar->setShowToolBar(false); } void SideWindowStyle::hideAllToolWindows() { m_hideActionList.clear(); foreach(QAction *action, m_leftSideBar->actionMap().keys()) { if (action->isChecked()) { m_hideActionList.append(action); action->setChecked(false); } } foreach(QAction *action, m_rightSideBar->actionMap().keys()) { if (action->isChecked()) { m_hideActionList.append(action); action->setChecked(false); } } foreach(QAction *action, m_outputBar->actionMap().keys()) { if (action->isChecked()) { m_hideActionList.append(action); action->setChecked(false); } } } void SideWindowStyle::hideSideBar(bool b) { if (b) { hideSideToolWindows(); } else { restoreHideSideToolWindows(); } } void SideWindowStyle::toggledSideBar(bool b) { if (b) { m_hideSideAct->setChecked(false); } } void SideWindowStyle::showOrHideToolWindow() { bool hide = false; foreach(QAction *action, m_leftSideBar->actionMap().keys()) { if (action->isChecked()) { hide = true; break; } } foreach(QAction *action, m_rightSideBar->actionMap().keys()) { if (action->isChecked()) { hide = true; break; } } if (hide) { hideAllToolWindows(); } else { restoreHideToolWindows(); } } void SideWindowStyle::hideOutputWindow() { foreach(QAction *act, m_outputBar->actionMap().keys()) { if (act->isChecked()) { act->setChecked(false); } } } void SideWindowStyle::saveToolState() const { m_liteApp->settings()->setValue("side_side_hide",m_hideSideAct->isChecked()); } void SideWindowStyle::restoreToolsState() { m_hideSideAct->setChecked(m_liteApp->settings()->value("side_side_hide").toBool()); } void SideWindowStyle::updateConer() { m_mainWindow->setCorner(Qt::BottomLeftCorner,Qt::LeftDockWidgetArea); m_mainWindow->setCorner(Qt::BottomRightCorner,Qt::RightDockWidgetArea); } void SideWindowStyle::moveToolWindow(Qt::DockWidgetArea from, Qt::DockWidgetArea to, QAction *action, bool /*split*/) { if (from == to) { return; } BaseActionBar *fromBar = m_actionBarMap[from]; BaseActionBar *toBar = m_actionBarMap[to]; if (!fromBar || !toBar) { return; } SideActionState *state = fromBar->actionMap().value(action); QWidget *widget = state->widget; QString id = state->id; QString title = state->title; QList<QAction*> widgetActions = state->widgetActions; QWidgetList widgetList = state->widgetList; fromBar->removeAction(action); toBar->addAction(action,widget,id,title,widgetActions,widgetList); action->setChecked(true); //save m_liteApp->settings()->setValue("sidebar_area/"+action->objectName(),to); if (from == Qt::BottomDockWidgetArea && to != Qt::BottomDockWidgetArea) { m_outputMenu->removeAction(action); m_sideMenu->addAction(action); action->setText(title); if (m_useShortcuts) { int index = m_leftSideBar->actionMap().size()+m_rightSideBar->actionMap().size(); if (index <= 9) { action->setText(QString("%1: %2").arg(index).arg(title)); QKeySequence ks(QString("Ctrl+Alt+%1").arg(index)); LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(m_liteApp,"App"); actionContext->regAction(action,"ToolWindow_"+id,ks.toString()); } else { LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(m_liteApp,"App"); actionContext->regAction(action,"ToolWindow_"+id,""); } } } else if (from != Qt::BottomDockWidgetArea && to == Qt::BottomDockWidgetArea) { m_sideMenu->removeAction(action); m_outputMenu->addAction(action); action->setText(title); if (m_useShortcuts) { int index = m_outputBar->actionMap().size(); if (index <= 9) { action->setText(QString("%1: %2").arg(index).arg(title)); #ifdef Q_OS_MAC QKeySequence ks(QString("Ctrl+Meta+%1").arg(index)); #else QKeySequence ks(QString("Ctrl+Shift+%1").arg(index)); #endif LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(m_liteApp,"App"); actionContext->regAction(action,"ToolWindow_"+id,ks.toString()); } else { LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->getActionContext(m_liteApp,"App"); actionContext->regAction(action,"ToolWindow_"+id,""); } } } } void SideWindowStyle::moveActionTo(Qt::DockWidgetArea from, Qt::DockWidgetArea to, QAction *action) { this->moveToolWindow(from,to,action,false); } QAction *SideWindowStyle::findToolWindow(QWidget *widget) { QAction *act = m_leftSideBar->findToolAction(widget); if (act) { return act; } act = m_rightSideBar->findToolAction(widget); if (act) { return act; } return m_outputBar->findToolAction(widget); } void SideWindowStyle::removeToolWindow(QAction */*action*/) { } QAction *SideWindowStyle::addToolWindow(LiteApi::IApplication *app, Qt::DockWidgetArea area, QWidget *widget, const QString &id, const QString &title, bool /*split*/, QList<QAction *> widgetActions, QList<QWidget *> widgetList) { QAction *action = new QAction(this); action->setText(title); action->setCheckable(true); action->setObjectName(id); area = (Qt::DockWidgetArea)m_liteApp->settings()->value("sidebar_area/"+id,area).toInt(); if (area == Qt::TopDockWidgetArea || area == Qt::BottomDockWidgetArea) { m_outputBar->addAction(action,widget,id,title,widgetActions,widgetList); int index = m_outputBar->actionMap().size(); action->setText(title); if ((index <= 9) && m_useShortcuts) { action->setText(QString("%1: %2").arg(index).arg(title)); //QKeySequence ks(LiteApi::UseMacShortcuts?QString("Ctrl+Alt+%1").arg(index):QString("Alt+%1").arg(index)); #ifdef Q_OS_MAC QKeySequence ks(QString("Ctrl+Meta+%1").arg(index)); #else QKeySequence ks(QString("Ctrl+Shift+%1").arg(index)); #endif LiteApi::IActionContext *actionContext = app->actionManager()->getActionContext(app,"App"); actionContext->regAction(action,"ToolWindow_"+id,ks.toString()); } if (m_outputMenu) { m_outputMenu->addAction(action); } } else { SideActionBar *sideBar = (area == Qt::LeftDockWidgetArea) ? m_leftSideBar : m_rightSideBar; sideBar->addAction(action,widget,id,title,widgetActions,widgetList); int index = m_leftSideBar->actionMap().size()+m_rightSideBar->actionMap().size(); action->setText(title); if ((index <= 9) && m_useShortcuts) { action->setText(QString("%1: %2").arg(index).arg(title)); //QKeySequence ks(LiteApi::UseMacShortcuts?QString("Ctrl+Alt+%1").arg(index):QString("Ctrl+Alt+%1").arg(index)); QKeySequence ks(QString("Ctrl+Alt+%1").arg(index)); LiteApi::IActionContext *actionContext = app->actionManager()->getActionContext(app,"App"); actionContext->regAction(action,"ToolWindow_"+id,ks.toString()); } connect(action,SIGNAL(toggled(bool)),this,SLOT(toggledSideBar(bool))); if (m_sideMenu) { m_sideMenu->addAction(action); } } return action; }
27,883
C++
.cpp
757
30.940555
227
0.653808
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,550
splitfolderwindow.cpp
visualfc_liteide/liteidex/src/liteapp/splitfolderwindow.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2018 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: splitfolderwindow.cpp // Creator: visualfc <visualfc@gmail.com> #include "splitfolderwindow.h" #include "symboltreeview/symboltreeview.h" #include "liteapp_global.h" #include <QTreeView> #include <QStackedWidget> #include <QSplitter> #include <QDir> #include <QAction> #include <QStandardItem> #include <QStandardItemModel> #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 SplitFolderWindow::SplitFolderWindow(IApplication *app, QObject *parent) : IFolderWindow(parent), m_liteApp(app) { m_spliter = new QSplitter(Qt::Vertical); m_tree = new SplitFolderView(app); m_tree->setHeaderHidden(true); m_tree->setRootIsDecorated(false); m_stacked = new QStackedWidget(); m_spliter->addWidget(m_tree); m_spliter->addWidget(m_stacked); m_spliter->setStretchFactor(0,0); m_spliter->setStretchFactor(1,1); m_filters = QDir::AllDirs | QDir::Files | QDir::Drives | QDir::Readable| QDir::Writable | QDir::Executable /*| QDir::Hidden*/ | QDir::NoDotAndDotDot; m_bShowDetails = false; m_bSyncEditor = false; connect(m_tree,SIGNAL(currentIndexChanged(QModelIndex,QModelIndex)),this,SLOT(currentIndexChanged(QModelIndex,QModelIndex))); connect(m_tree,SIGNAL(aboutToShowContextMenu(QMenu*,LiteApi::FILESYSTEM_CONTEXT_FLAG,QFileInfo)),this,SLOT(aboutToShowFolderContextMenu(QMenu*,LiteApi::FILESYSTEM_CONTEXT_FLAG,QFileInfo))); connect(m_tree,SIGNAL(closeFolderIndex(QModelIndex)),this,SLOT(closeFolderIndex(QModelIndex))); connect(m_tree,SIGNAL(reloadFolderIndex(QModelIndex)),this,SLOT(reloadFolderIndex(QModelIndex))); connect(m_liteApp->editorManager(),SIGNAL(currentEditorChanged(LiteApi::IEditor*)),this,SLOT(currentEditorChanged(LiteApi::IEditor*))); QByteArray state = m_liteApp->settings()->value("LiteApp/BoxFolderSplitter").toByteArray(); m_spliter->restoreState(state); } SplitFolderWindow::~SplitFolderWindow() { m_liteApp->settings()->setValue("LiteApp/BoxFolderSplitter",m_spliter->saveState()); delete m_spliter; } QString SplitFolderWindow::id() const { return "folderwindow/splitfolder"; } QWidget *SplitFolderWindow::widget() const { return m_spliter; } QStringList SplitFolderWindow::folderList() const { return m_folderList; } void SplitFolderWindow::setFolderList(const QStringList &folders) { foreach (QString folder, folders) { addFolderImpl(folder); } } void SplitFolderWindow::addFolderList(const QString &folder) { addFolderImpl(folder); } void SplitFolderWindow::closeAllFolders() { m_folderList.clear(); m_tree->clear(); int count = m_stacked->count(); while (count) { count--; QWidget *widget = m_stacked->widget(count); m_stacked->removeWidget(widget); delete widget; } } void SplitFolderWindow::currentIndexChanged(const QModelIndex &index, const QModelIndex &/*prev*/) { int row = findInStacked(index); if (row == -1) { return; } QString folder = index.data(Qt::UserRole+1).toString(); if (!QFileInfo(folder).exists()) { m_tree->closeFolder(); return; } FolderView *widget = (FolderView*)m_stacked->widget(row); if (widget->filter() != m_filters) { widget->setFilter(m_filters); } if (widget->isShowDetails() != m_bShowDetails) { widget->setShowDetails(m_bShowDetails); } m_stacked->setCurrentIndex(row); } void SplitFolderWindow::closeFolderIndex(const QModelIndex &index) { int row = findInStacked(index); if (row == -1) { return; } QWidget *widget = m_stacked->widget(row); m_stacked->removeWidget(widget); delete widget; m_folderList.removeAt(row); } void SplitFolderWindow::reloadFolderIndex(const QModelIndex &index) { int row = findInStacked(index); if (row == -1) { return; } FolderView *widget = (FolderView*)m_stacked->widget(row); widget->reload(); } void SplitFolderWindow::setShowHideFiles(bool b) { if (b) { m_filters |= QDir::Hidden; } else if (m_filters.testFlag(QDir::Hidden)) { m_filters ^= QDir::Hidden; } FolderView *widget = (FolderView*)m_stacked->currentWidget(); if (!widget) { return; } if (widget->filter() != m_filters) { widget->setFilter(m_filters); } } void SplitFolderWindow::setShowDetails(bool b) { m_bShowDetails = b; FolderView *widget = (FolderView*)m_stacked->currentWidget(); if (!widget) { return; } if (widget->isShowDetails() != b) { widget->setShowDetails(b); } } void SplitFolderWindow::setSyncEditor(bool b) { m_bSyncEditor = b; if (b) { this->currentEditorChanged(m_liteApp->editorManager()->currentEditor()); } } void SplitFolderWindow::currentEditorChanged(IEditor *editor) { if (!editor || !m_bSyncEditor) { return; } QString filePath = editor->filePath(); if (filePath.isEmpty()) { return; } filePath = QDir::toNativeSeparators(filePath); FolderView *widget = (FolderView*)m_stacked->currentWidget(); if (widget) { QModelIndex index = widget->indexForPath(filePath); if (index.isValid()) { widget->scrollTo(index); widget->clearSelection(); widget->setCurrentIndex(index); return; } } int count = m_folderList.count(); for (int i = 0; i < count; i++) { QString folder = m_folderList.at(i); if (!QFileInfo(folder).exists()) { continue; } FolderView *widget = (FolderView*)m_stacked->widget(i); QModelIndex index = widget->indexForPath(filePath); if (index.isValid()) { widget->scrollTo(index); widget->clearSelection(); widget->setCurrentIndex(index); m_tree->setCurrentIndex(m_tree->model()->index(i,0)); m_stacked->setCurrentIndex(i); return; } } } void SplitFolderWindow::doubleClickedFolderView(const QModelIndex &index) { if (!index.isValid()) { return; } FolderView *view = (FolderView*)(sender()); QFileInfo info = view->fileInfo(index); if (info.isFile()) { m_liteApp->fileManager()->openEditor(info.filePath()); } } void SplitFolderWindow::enterKeyPressedFolderView(const QModelIndex &index) { if (!index.isValid()) { return; } FolderView *view = (FolderView*)(sender()); QFileInfo info = view->fileInfo(index); if (info.isFile()) { m_liteApp->fileManager()->openEditor(info.filePath()); } else { view->setExpanded(index,!view->isExpanded(index)); } } void SplitFolderWindow::addFolderImpl(const QString &_folder) { QString folder = QDir::toNativeSeparators(_folder); if (m_folderList.contains(folder)) { return; } if (!QDir(folder).exists()) { return; } FolderView *view = new FolderView(true,m_liteApp); view->setFilter(m_filters); view->setShowDetails(m_bShowDetails); view->setRootPath(folder); connect(view,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(doubleClickedFolderView(QModelIndex))); connect(view,SIGNAL(enterKeyPressed(QModelIndex)),this,SLOT(enterKeyPressedFolderView(QModelIndex))); connect(view,SIGNAL(aboutToShowContextMenu(QMenu*,LiteApi::FILESYSTEM_CONTEXT_FLAG,QFileInfo)),this,SLOT(aboutToShowFolderContextMenu(QMenu*,LiteApi::FILESYSTEM_CONTEXT_FLAG,QFileInfo))); m_stacked->addWidget(view); m_folderList.append(folder); m_tree->addRootPath(folder); m_liteApp->recentManager()->addRecent(folder,"folder"); } int SplitFolderWindow::findInStacked(const QModelIndex &index) { if (!index.isValid()) { return -1; } QString folder = index.data(Qt::UserRole+1).toString(); return m_folderList.indexOf(folder); } void SplitFolderWindow::aboutToShowFolderContextMenu(QMenu *menu, LiteApi::FILESYSTEM_CONTEXT_FLAG flag, const QFileInfo &info) { m_liteApp->fileManager()->emitAboutToShowFolderContextMenu(menu,flag,info,"liteapp/folder"); } SplitFolderView::SplitFolderView(IApplication *app, QWidget *parent) : BaseFolderView(app,parent) { m_model = new QStandardItemModel(this); this->setModel(m_model); m_contextMenu = new QMenu(); this->setContextMenuPolicy(Qt::CustomContextMenu); connect(this,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(customContextMenuRequested(QPoint))); } void SplitFolderView::addRootPath(const QString &folder) { QStandardItem *item = new QStandardItem(folder); item->setData(folder,Qt::UserRole+1); item->setToolTip(folder); m_model->appendRow(item); this->setCurrentIndex(m_model->indexFromItem(item)); } void SplitFolderView::clear() { m_model->clear(); } void SplitFolderView::openFolder() { m_liteApp->fileManager()->openFolder(); } void SplitFolderView::closeFolder() { QModelIndex index = this->currentIndex(); if (!index.isValid()) { return; } emit closeFolderIndex(index); m_model->removeRow(index.row()); } void SplitFolderView::reloadFolder() { QModelIndex index = this->currentIndex(); if (!index.isValid()) { return; } emit reloadFolderIndex(index); } void SplitFolderView::customContextMenuRequested(const QPoint &pos) { QModelIndex index = this->currentIndex(); if (!index.isValid()) { return; } QString dir = index.data(Qt::UserRole+1).toString(); QFileInfo fileInfo(dir); m_contextMenu->clear(); m_contextInfo = fileInfo; LiteApi::FILESYSTEM_CONTEXT_FLAG flag = LiteApi::FILESYSTEM_ROOTFOLDER; m_contextMenu->addAction(m_openInNewWindowAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_newFileAct); m_contextMenu->addAction(m_newFileWizardAct); m_contextMenu->addAction(m_newFolderAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_openFolderAct); m_contextMenu->addAction(m_reloadFolderAct); m_contextMenu->addAction(m_closeFolderAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_copyFullPathToClipboardAct); m_contextMenu->addSeparator(); m_contextMenu->addAction(m_openExplorerAct); m_contextMenu->addAction(m_openShellAct); m_contextMenu->addAction(m_openTerminalAct); emit aboutToShowContextMenu(m_contextMenu,flag,m_contextInfo); m_contextMenu->exec(this->mapToGlobal(pos)); }
12,205
C++
.cpp
347
29.342939
194
0.667771
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,551
idletimer.cpp
visualfc_liteide/liteidex/src/liteapp/idletimer.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: idletimer.cpp // Creator: visualfc <visualfc@gmail.com> #include "idletimer.h" #include <QApplication> #include <QTimer> //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 AppIdleTimer::AppIdleTimer() { m_timer = new QTimer(this); m_timer->setInterval(1000); connect(m_timer,SIGNAL(timeout()),this,SLOT(timeout())); qApp->installEventFilter(this); m_count = 0; m_timer->start(); } AppIdleTimer::~AppIdleTimer() { m_timer->stop(); } void AppIdleTimer::resetTimer() { m_count = 0; m_timer->stop(); m_timer->start(); } void AppIdleTimer::timeout() { m_count++; emit appIdle(m_count); } bool AppIdleTimer::eventFilter(QObject *obj, QEvent *event) { switch (event->type()) { case QEvent::KeyPress: case QEvent::KeyRelease: case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseButtonDblClick: case QEvent::MouseMove: resetTimer(); break; default: break; } return QObject::eventFilter(obj,event); }
2,375
C++
.cpp
74
28.081081
83
0.642639
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,552
optionsbrowser.cpp
visualfc_liteide/liteidex/src/liteapp/optionsbrowser.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: optionsbrowser.cpp // Creator: visualfc <visualfc@gmail.com> #include "optionsbrowser.h" #include "ui_optionswidget.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 OptionsBrowser::OptionsBrowser(LiteApi::IApplication *app, QWidget *parent) : QDialog(parent), m_liteApp(app), ui(new Ui::OptionsWidget) { ui->setupUi(this); connect(ui->listWidget,SIGNAL(itemSelectionChanged()),this,SLOT(itemSelectionChanged())); connect(ui->buttonBox,SIGNAL(clicked(QAbstractButton*)),this,SLOT(clicked(QAbstractButton*))); } OptionsBrowser::~OptionsBrowser() { delete ui; //delete m_widget; } QString OptionsBrowser::name() const { return tr("Options"); } QString OptionsBrowser::mimeType() const { return "browser/options"; } void OptionsBrowser::addOption(LiteApi::IOption *opt) { if (!opt || !opt->widget()) { return; } QListWidgetItem *item = new QListWidgetItem; item->setIcon(opt->icon()); item->setText(opt->name()); item->setTextAlignment(Qt::AlignLeft);// | Qt::AlignHCenter); item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); QLayout *layout = opt->widget()->layout(); if (layout) { layout->setMargin(0); } ui->listWidget->addItem(item); ui->stackedWidget->addWidget(opt->widget()); m_widgetOptionMap.insert(item,opt); } int OptionsBrowser::execute(const QString &mimeType) { if (ui->listWidget->count() == 0) { return exec(); } QListWidgetItem *item = ui->listWidget->item(0); QMapIterator<QListWidgetItem*,LiteApi::IOption*> i(m_widgetOptionMap); while (i.hasNext()) { i.next(); if (i.value()->mimeType() == mimeType) { item = i.key(); break; } } ui->listWidget->setCurrentItem(item); LiteApi::IOption *opt = m_widgetOptionMap.value(item); if (opt) { //ui->scrollArea->resize(opt->widget()->size()); opt->load(); } // this->setMinimumHeight(600); //#ifdef Q_OS_MAC // this->setMinimumWidth(900); //#else // this->setMinimumWidth(800); //#endif return exec(); } QString OptionsBrowser::currenMimeType() const { QListWidgetItem *item = ui->listWidget->currentItem(); if (item) { LiteApi::IOption *opt = m_widgetOptionMap.value(item); if (opt) { return opt->mimeType(); } } return QString(); } void OptionsBrowser::itemSelectionChanged() { QListWidgetItem *item = ui->listWidget->currentItem(); if (!item) { return; } LiteApi::IOption *opt = m_widgetOptionMap.value(item); if (opt) { opt->load(); ui->stackedWidget->setCurrentWidget(opt->widget()); ui->infoLabel->setText(QString("Name : %1 MimeType : %2").arg(opt->name()).arg(opt->mimeType())); opt->widget()->updateGeometry(); } } void OptionsBrowser::clicked(QAbstractButton *button) { QDialogButtonBox::ButtonRole role = ui->buttonBox->buttonRole(button); if (role == QDialogButtonBox::AcceptRole) { this->applay(); this->accept(); } else if (role == QDialogButtonBox::RejectRole) { this->reject(); } else if (role == QDialogButtonBox::ApplyRole) { this->applay(); } } void OptionsBrowser::applay() { QListWidgetItem *item = ui->listWidget->currentItem(); if (!item) { return; } LiteApi::IOption *opt = m_widgetOptionMap.value(item); if (opt) { opt->save(); emit applyOption(opt->mimeType()); } }
4,799
C++
.cpp
151
27.609272
108
0.646741
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,553
goproxy.cpp
visualfc_liteide/liteidex/src/liteapp/goproxy.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: goproxy.cpp // Creator: visualfc <visualfc@gmail.com> #include "goproxy.h" #include "cdrv.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 static GODRV_CALL godrv_call_fn = 0; static int godrv_call(const QByteArray &id, const QByteArray &args, DRV_CALLBACK cb, void *ctx) { if (godrv_call_fn == 0) { return -1; } return godrv_call_fn((char*)id.constData(),id.length(),(char*)args.constData(),args.length(),cb,ctx); } static void cdrv_callback(char *id, int id_size, char *reply, int len, int err, void *ctx) { ((GoProxy*)(ctx))->callback(id,id_size,reply,len,err); } GoProxy::GoProxy(QObject *parent) : LiteApi::IGoProxy(parent) { m_isRuning = false; } bool GoProxy::isValid() const { return godrv_call_fn != 0; } bool GoProxy::hasProxy() { return godrv_call_fn != 0; } bool GoProxy::isRunning() const { return m_isRuning; } QByteArray GoProxy::commandId() const { return m_id; } void GoProxy::writeStdin(const QByteArray &data) { godrv_call("stdin",data,&cdrv_callback,this); } void GoProxy::call(const QByteArray &id, const QByteArray &args) { m_id = id; m_isRuning = false; godrv_call(id,args,&cdrv_callback,this); } void GoProxy::callback(char *id, int id_size, char *reply, int reply_size, int flag) { if (m_id != QByteArray(id,id_size)) { return; } if (flag == 0) { m_isRuning = true; emit started(); } else if(flag == 1) { emit stdoutput(QByteArray(reply,reply_size)); } else if (flag == 2) { emit stderror(QByteArray(reply,reply_size)); } else if (flag == 3) { m_isRuning = false; emit finished(0,""); } else if (flag == 4) { m_isRuning = false; emit finished(2,QByteArray(reply,reply_size)); } } void cdrv_init(void *fn) { godrv_call_fn = (GODRV_CALL)fn; } void cdrv_cb(DRV_CALLBACK cb, char *id, int id_size, char *reply, int size, int err, void* ctx) { cb(id,id_size,reply,size,err,ctx); }
3,270
C++
.cpp
105
28.095238
105
0.652174
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,554
aboutdialog.cpp
visualfc_liteide/liteidex/src/liteapp/aboutdialog.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: aboutdialog.cpp // Creator: visualfc <visualfc@gmail.com> #include "aboutdialog.h" #include "ui_aboutdialog.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 AboutDialog::AboutDialog(LiteApi::IApplication *app,QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); ui->verLabel->setText(app->ideVersion()); ui->qtVerLabel->setText(QString(tr("Based on Qt %1 (%2 bit)")).arg(QLatin1String(qVersion())). arg(QString::number(QSysInfo::WordSize))); } AboutDialog::~AboutDialog() { delete ui; }
1,831
C++
.cpp
46
37.065217
98
0.661055
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,555
newfiledialog.cpp
visualfc_liteide/liteidex/src/liteapp/newfiledialog.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: newfiledialog.cpp // Creator: visualfc <visualfc@gmail.com> #include "newfiledialog.h" #include "ui_newfiledialog.h" #include "liteapi/liteqt.h" #include <QStandardItemModel> #include <QStandardItem> #include <QStringListModel> #include <QDir> #include <QFileInfo> #include <QSettings> #include <QTextCodec> #include <QFileDialog> #include <QMessageBox> #include <QDateTime> #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 NewFileDialog::NewFileDialog(QWidget *parent) : QDialog(parent), ui(new Ui::NewFileDialog) { ui->setupUi(this); m_templateModel = new QStandardItemModel(this); m_pathModel = new QStringListModel(this); ui->templateTreeView->setModel(m_templateModel); ui->pathTreeView->setModel(m_pathModel); ui->pathTreeView->setEditTriggers(0); ui->pathTreeView->setRootIsDecorated(false); ui->pathTreeView->setHeaderHidden(true); ui->templateTreeView->setEditTriggers(0); ui->templateTreeView->setRootIsDecorated(false); ui->templateTreeView->setHeaderHidden(true); connect(ui->templateTreeView,SIGNAL(clicked(QModelIndex)),this,SLOT(activeTemplate(QModelIndex))); connect(ui->nameLineEdit,SIGNAL(textChanged(QString)),this,SLOT(nameLineChanged(QString))); connect(ui->locationLineEdit,SIGNAL(textChanged(QString)),this,SLOT(locationLineChanged(QString))); connect(ui->pathTreeView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(activePath(QModelIndex))); } NewFileDialog::~NewFileDialog() { delete ui; } void NewFileDialog::setPathList(const QStringList &pathList) { m_pathModel->setStringList(pathList); if (m_gopath.isEmpty() && !pathList.isEmpty()) { m_gopath = pathList.first(); } } void NewFileDialog::setGopath(const QString &path) { m_gopath = path; } void NewFileDialog::setProjectLocation(const QString &path) { m_projectLocation = path; } void NewFileDialog::setFileLocation(const QString &path) { m_fileLocation = path; } void NewFileDialog::updateLocation() { ui->nameLineEdit->clear(); QModelIndex index = ui->templateTreeView->currentIndex(); if (index.isValid()) { activeTemplate(index); } } void NewFileDialog::accept() { if (!m_cur.isValid()) { return; } QString location = ui->locationLineEdit->text().trimmed(); QString name = ui->nameLineEdit->text().trimmed(); if (name.isEmpty() || location.isEmpty()) { return; } QDir dir(location); if (!dir.exists()) { if (!dir.mkpath(location)) { QMessageBox::warning(this,tr("Error"),tr("Could not create the target directory: %1").arg(location)); return; } } else { if (m_cur.type != "file" && !dir.entryList(QDir::Files).isEmpty()) { int ret = QMessageBox::warning(this,tr("Warning"),QString(tr("Location %1 is not empty.\nUse the target directory anyway?")).arg(location), QMessageBox::Yes|QMessageBox::No,QMessageBox::No); if (ret != QMessageBox::Yes) { return; } } } static const char * const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; m_stringMap.clear(); m_stringMap.insert("$ROOT$",QFileInfo(name).fileName()); QDate dt = QDate::currentDate(); QTime tm = QTime::currentTime(); m_stringMap.insert("$DATE$", QString("%1 %2 %3").arg(dt.day()).arg(shortMonthNames[dt.month()-1]).arg(dt.year())); m_stringMap.insert("$DATETIME$",QString("%1 %2 %3 %4").arg(tm.toString("hh:mm")).arg(dt.day()).arg(shortMonthNames[dt.month()-1]).arg(dt.year())); m_openFiles.clear(); m_openPath = location; QStringList ofiles; foreach (QString file, m_cur.files) { QString infile = QFileInfo(m_cur.dir,file).absoluteFilePath(); QString ofile = file; QFileInfo oi(name); QString base = oi.fileName(); if (!oi.suffix().isEmpty() && (oi.suffix() == QFileInfo(infile).suffix())) { ofile.replace("root",base.left(base.length()-oi.suffix().length()-1)); } else { ofile.replace("root",base); } QString outfile = QFileInfo(location,ofile).absoluteFilePath(); if (QFile::exists(outfile)) { int ret = QMessageBox::warning(this,tr("Overwrite File"),QString(tr("%1 already exists.\nDo you want to replace it?").arg(outfile)), QMessageBox::Yes|QMessageBox::No|QMessageBox::Abort,QMessageBox::Abort); if (ret == QMessageBox::Abort) { return; } else if (ret == QMessageBox::No) { continue; } } if (processFile(infile,outfile)) { ofiles.append(outfile); if (m_cur.open.contains(file)) { m_openFiles.append(QDir::toNativeSeparators(outfile)); } } } if (ofiles.isEmpty()) { QMessageBox::warning(this,tr("Error"),tr("No files could be created.")); return; } QDialog::accept(); } void NewFileDialog::activePath(QModelIndex index) { if (!index.isValid()) { return; } if (m_cur.type == "project") { m_projectLocation = index.data(Qt::DisplayRole).toString(); } else if (m_cur.type == "file"){ m_fileLocation = index.data(Qt::DisplayRole).toString(); } else if (m_cur.type == "gopath") { m_gopath = index.data(Qt::DisplayRole).toString(); } QModelIndex i = ui->templateTreeView->currentIndex(); if (i.isValid()) { activeTemplate(i); } } void NewFileDialog::loadTemplate(const QString &root) { m_templateModel->clear(); m_cur.clear(); ui->nameLineEdit->clear(); ui->locationLineEdit->clear(); QStringList files; files << "file.sub" << "project.sub"; foreach (QString file, files) { QFile f(root+"/"+file); if (!f.open(QIODevice::ReadOnly)) { continue; } while (!f.atEnd()) { QString line = f.readLine().trimmed(); QString setup = root+"/"+line+"/setup.inf"; QSettings set(setup,QSettings::IniFormat); if (set.status() != QSettings::NoError) { continue; } QString name = set.value("SETUP/NAME").toString(); QString type = set.value("SETUP/type").toString(); if (!name.isEmpty()) { QStandardItem *item = new QStandardItem(name); item->setData(setup); QFont font = item->font(); if (type == "file") { font.setItalic(true); } else { font.setBold(true); } item->setFont(font); m_templateModel->appendRow(item); } } f.close(); } if (m_templateModel->rowCount() > 0) { QModelIndex index = m_templateModel->index(0,0); ui->templateTreeView->setCurrentIndex(index); activeTemplate(index); } } void NewFileDialog::activeTemplate(QModelIndex index) { m_cur.clear(); if (index.isValid()) { QString fileName = index.data(Qt::UserRole+1).toString(); QSettings set(fileName,QSettings::IniFormat); if (set.status() != QSettings::NoError) { return; } m_cur.dir = QFileInfo(fileName).absolutePath(); m_cur.name = set.value("SETUP/NAME").toString(); m_cur.author = set.value("SETUP/AUTHOR").toString(); m_cur.info = set.value("SETUP/INFO").toString(); m_cur.type = set.value("SETUP/TYPE").toString().toLower(); m_cur.files = set.value("SETUP/FILES").toString().trimmed().split(" ",qtSkipEmptyParts); m_cur.open = set.value("SETUP/OPEN").toString().trimmed().split(" ",qtSkipEmptyParts); m_cur.scheme = set.value("SETUP/SCHEME").toString().toLower(); if (m_cur.open.isEmpty() && m_cur.files.count() > 0) { m_cur.open.append(m_cur.files.at(0)); } if (m_cur.type.isEmpty()) { m_cur.type = "file"; } } if (m_cur.type == "file") { ui->typeLabel->setText(tr("File template details:")); } else { ui->typeLabel->setText(tr("Project template details:")); } QStringList infos; if (!m_cur.name.isEmpty()) { infos.append("Name = "+m_cur.name); } if (!m_cur.author.isEmpty()) { infos.append("Author = "+m_cur.author); } if (!m_cur.info.isEmpty()) { infos.append("Info = "+m_cur.info); } ui->infoLabel->setText(infos.join("\n")); QString location; bool b = true; if (m_cur.type == "gopath") { location = QFileInfo(m_gopath,"src").filePath(); //b = false; } else if (m_cur.type == "project") { location = m_projectLocation; } else { location = m_fileLocation; } ui->locationLineEdit->setEnabled(b); ui->locationBrowseButton->setEnabled(b); ui->locationLineEdit->setText(QDir::toNativeSeparators(location)); //update nameLineChanged(ui->nameLineEdit->text()); } bool NewFileDialog::processFile(const QString &infile, const QString &outfile) { QFile in(infile); if (!in.open(QIODevice::ReadOnly|QIODevice::Text)) { return false; } QFile out(outfile); if (!out.open(QIODevice::WriteOnly|QIODevice::Text)) { return false; } QTextCodec *codec = QTextCodec::codecForName("UTF-8"); QString all = codec->toUnicode(in.readAll()); QMapIterator<QString,QString> i(m_stringMap); while (i.hasNext()) { i.next(); all.replace(i.key(),i.value()); } out.write(codec->fromUnicode(all)); in.close(); out.close(); return true; } QStringList NewFileDialog::openFiles() const { return m_openFiles; } QString NewFileDialog::type() const { return m_cur.type; } QString NewFileDialog::scheme() const { return m_cur.scheme; } QString NewFileDialog::openPath() const { return m_openPath; } void NewFileDialog::on_locationBrowseButton_clicked() { QString location = ui->locationLineEdit->text(); location = QFileDialog::getExistingDirectory(this,tr("Choose a directory for the new content:"),location); if (location.isEmpty()) { return; } ui->locationLineEdit->setText(location); if (m_cur.type == "project") { m_projectLocation = location; } else if (m_cur.type == "file"){ m_fileLocation = location; } } void NewFileDialog::locationLineChanged(QString) { QString location = ui->locationLineEdit->text(); if (location.isEmpty()) { return; } if (m_cur.type == "project") { m_projectLocation = location; } else if (m_cur.type == "file"){ m_fileLocation = location; } } void NewFileDialog::nameLineChanged(QString) { if (m_cur.type == "file") { return; } QString name = ui->nameLineEdit->text(); QString location; if (m_cur.type == "gopath") { location = QFileInfo(m_gopath,"src").filePath(); } else if (m_cur.type == "project") { location = m_projectLocation; } else { location = m_fileLocation; } location = QFileInfo(location,name).absoluteFilePath(); ui->locationLineEdit->blockSignals(true); ui->locationLineEdit->setText(QDir::toNativeSeparators(location)); ui->locationLineEdit->blockSignals(false); }
12,807
C++
.cpp
366
28.765027
151
0.620918
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,557
main.cpp
visualfc_liteide/liteidex/src/liteapp/main.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: main.cpp // Creator: visualfc <visualfc@gmail.com> #include <QApplication> #include <QTranslator> #include <QLocale> #include <QLibraryInfo> #include <QDir> #include <QSettings> #include <QSplashScreen> #include <QTextCodec> #if QT_VERSION >= 0x050000 #include <QStandardPaths> #endif #ifdef Q_OS_MACOS #include <QtConcurrent/QtConcurrent> #endif #include <QDebug> #include <QtGlobal> #include "mainwindow.h" #include "liteapp.h" #include "goproxy.h" #include "cdrv.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 #ifdef Q_OS_MACOS class LiteIDEApplication : public QApplication { public: IApplication *liteApp = nullptr; LiteIDEApplication(int &argc, char **argv) : QApplication(argc, argv) {} bool event(QEvent *event) override { if (event->type() == QEvent::FileOpen) { QString filePath = static_cast<QFileOpenEvent *>(event)->file(); if (liteApp == nullptr) { // Cold start, wait liteApp ready QFuture<void> future = QtConcurrent::run([this, filePath](){ while(this->liteApp == nullptr) QThread::sleep(1); QMetaObject::invokeMethod(this, [this, filePath]() { openFileOrFolder(filePath); }, Qt::QueuedConnection); }); } else { openFileOrFolder(filePath); } } return QApplication::event(event); } private: void openFileOrFolder(QString filePath) { QFileInfo f(filePath); if (!f.exists() || liteApp == nullptr) return; if (f.isFile()) { liteApp->fileManager()->openEditor(filePath); } else if (f.isDir()) { liteApp->fileManager()->addFolderList(filePath); } } }; #endif #ifdef LITEAPP_LIBRARY int liteapp_main(int argc, char *argv[]) #else int main(int argc, char *argv[]) #endif { #ifndef LITEAPP_LIBRARY #if defined(_MSC_VER) && defined(_DEBUG) _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF); #endif #endif #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0) QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif #ifdef Q_OS_MACOS LiteIDEApplication app(argc, argv); #else QApplication app(argc, argv); #endif QStringList arguments = app.arguments(); //init load file or folder list QStringList fileList; //liteide --select-env [system|win32|cross-linux64|...] select init environment id //liteide --reset-setting reset current setting //liteide --local-setting force user local setting //liteide --user-setting force use user setting QString flagSelectEnv = "--select-env"; QString argSelectEnv; QString flagResetSetting = "--reset-setting"; QString flagLocalSetting = "--local-setting"; QString flagUserSetting = "--user-setting"; bool argResetSetting = false; bool argLocalSetting = false; bool argUserSetting = false; for(int i = 1; i < arguments.size(); i++) { QString arg = arguments[i]; if (arg.startsWith("-")) { if (arg.indexOf(flagSelectEnv+"=") == 0) { argSelectEnv = arg.mid(flagSelectEnv.length()+1); } else if (arg == flagSelectEnv) { i++; if (i < arguments.size()) { argSelectEnv = arguments[i]; } } else if (arg == flagResetSetting) { argResetSetting = true; } else if (arg == flagLocalSetting) { argLocalSetting = true; } else if (arg == flagUserSetting) { argUserSetting = true; } continue; } fileList.append(arg); } //save to global if (!argSelectEnv.isEmpty()) { LiteApp::s_cookie.insert(flagSelectEnv,argSelectEnv); } if (argLocalSetting) { LiteApp::s_cookie.insert(flagLocalSetting,true); } if (argUserSetting) { LiteApp::s_cookie.insert(flagUserSetting,true); } #if QT_VERSION >= 0x050100 app.setAttribute(Qt::AA_UseHighDpiPixmaps); #endif //QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande"); QTranslator translator; QTranslator qtTranslator; QString resPath = LiteApp::getResoucePath(); QString locale = QLocale::system().name(); QString qss; QSettings global(resPath+"/liteapp/config/global.ini",QSettings::IniFormat); bool storeLocal = global.value(LITEIDE_STORELOCAL,false).toBool(); if (argUserSetting) { storeLocal = false; } else if (argLocalSetting) { storeLocal = true; } if (storeLocal) { QSettings settings(resPath+"/liteapp/config/liteide.ini", QSettings::IniFormat); if (argResetSetting) { settings.clear(); } locale = settings.value(LITEAPP_LANGUAGE,locale).toString(); qss = settings.value(LITEAPP_QSS,"default.qss").toString(); } else { QSettings settings(QSettings::IniFormat,QSettings::UserScope,"liteide","liteide"); if (argResetSetting) { settings.clear(); } locale = settings.value(LITEAPP_LANGUAGE,locale).toString(); qss = settings.value(LITEAPP_QSS,"default.qss").toString(); } if (!locale.isEmpty()) { const QString &liteideTrPath = resPath+"/translations"; if (translator.load(QLatin1String("liteide_") + locale, liteideTrPath)) { const QString &qtTrPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath); const QString &qtTrFile = QLatin1String("qt_") + locale; // Binary installer puts Qt tr files into creatorTrPath app.installTranslator(&translator); if (qtTranslator.load(qtTrFile, qtTrPath) || qtTranslator.load(qtTrFile, liteideTrPath)) { app.installTranslator(&qtTranslator); } app.setProperty("liteide_locale", locale); } } if (!qss.isEmpty()) { QFile f(resPath+"/liteapp/qss/"+qss); if (f.open(QFile::ReadOnly)) { QString styleSheet = QLatin1String(f.readAll()); app.setStyleSheet(styleSheet); } } IApplication *liteApp = LiteApp::NewApplication("default",0); #ifdef Q_OS_MACOS app.liteApp = liteApp; #endif foreach(QString file, fileList) { QFileInfo f(file); if (f.isFile()) { liteApp->fileManager()->openEditor(file); } else if (f.isDir()) { liteApp->fileManager()->addFolderList(file); } } int ret = app.exec(); return ret; } int cdrv_main(int argc, char **argv) { return liteapp_main(argc,argv); }
7,988
C++
.cpp
221
29.61086
102
0.628989
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,558
folderproject.cpp
visualfc_liteide/liteidex/src/liteapp/folderproject.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: folderproject.cpp // Creator: visualfc <visualfc@gmail.com> #include "folderproject.h" #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 FolderProject::FolderProject(IApplication *app) : m_liteApp(app), m_folderView(0) { #ifdef Q_OS_MAC m_folderView = new FolderListView(true,m_liteApp); #else m_folderView = new FolderListView(false,m_liteApp); #endif // m_folderView = new FolderListView(false,m_liteApp); m_folderView->setDragEnabled(true); m_folderView->setDragDropMode(QAbstractItemView::InternalMove); } FolderProject::~FolderProject() { if (m_folderView) { delete m_folderView; } } QWidget *FolderProject::widget() { return m_folderView; } QString FolderProject::name() const { return "FolderProject"; } QString FolderProject::filePath() const { QStringList paths = m_folderView->rootPathList(); if (!paths.isEmpty()) { return paths[0]; } return QString(); } QString FolderProject::mimeType() const { return "folder/x-path"; } void FolderProject::openFolder(const QString &folder) { m_folderView->setRootPathList(QStringList() << folder); } void FolderProject::appendFolder(const QString &folder) { m_folderView->addRootPath(folder); } void FolderProject::clear() { m_folderView->clear(); } QStringList FolderProject::folderList() const { return m_folderView->rootPathList(); } QStringList FolderProject::fileNameList() const { return QStringList(); } QStringList FolderProject::filePathList() const { return QStringList(); } QString FolderProject::fileNameToFullPath(const QString &filePath) { return filePath; } QMap<QString,QString> FolderProject::targetInfo() const { return QMap<QString,QString>(); } void FolderProject::load() { }
3,046
C++
.cpp
106
26.358491
82
0.706124
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,559
openeditorswidget.cpp
visualfc_liteide/liteidex/src/liteapp/openeditorswidget.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: openeditorswidget.cpp // Creator: visualfc <visualfc@gmail.com> #include "openeditorswidget.h" #include <QCoreApplication> #include <QSortFilterProxyModel> #include <QHeaderView> //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 OpenEditorsWidget::OpenEditorsWidget(LiteApi::IApplication *app) : m_liteApp(app) { //m_model = new Core::ProxyModel(this); setWindowTitle(tr("Open Documents")); setDragEnabled(true); setDragDropMode(QAbstractItemView::DragOnly); setCloseButtonVisible(true); m_model = new QSortFilterProxyModel(this); this->setModel(m_model); setContextMenuPolicy(Qt::CustomContextMenu); this->setEditTriggers(QTreeView::NoEditTriggers); this->header()->setCascadingSectionResizes( true ); connect(m_liteApp->editorManager(),SIGNAL(currentEditorChanged(LiteApi::IEditor*)),this,SLOT(updateCurrentItem(LiteApi::IEditor*))); connect(this,SIGNAL(activated(QModelIndex)),this,SLOT(handleActivated(QModelIndex))); connect(this,SIGNAL(closeActivated(QModelIndex)),this,SLOT(closeDocument(QModelIndex))); connect(this,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(contextMenuRequested(QPoint))); } void OpenEditorsWidget::setEditorModel(QAbstractItemModel *model) { m_model->setSourceModel(model); } void OpenEditorsWidget::handleActivated(const QModelIndex &index) { if (index.column() == 0) { activateEditor(index); } else if (index.column() == 1) { // the funky close button closeDocument(index); // work around a bug in itemviews where the delegate wouldn't get the QStyle::State_MouseOver QPoint cursorPos = QCursor::pos(); QWidget *vp = viewport(); QMouseEvent e(QEvent::MouseMove, vp->mapFromGlobal(cursorPos), cursorPos, Qt::NoButton, 0, 0); QCoreApplication::sendEvent(vp, &e); } } void OpenEditorsWidget::updateCurrentItem(LiteApi::IEditor *editor) { QModelIndex index = indexFromEditor(editor); if (!index.isValid()) { clearSelection(); return; } setCurrentIndex(index); selectionModel()->select(currentIndex(), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); scrollTo(currentIndex()); } void OpenEditorsWidget::contextMenuRequested(QPoint /*pos*/) { } void OpenEditorsWidget::activateEditor(const QModelIndex &index) { LiteApi::IEditor *editor = editorFormIndex(index); if (editor) { m_liteApp->editorManager()->setCurrentEditor(editor); } } void OpenEditorsWidget::closeDocument(const QModelIndex &index) { LiteApi::IEditor *editor = editorFormIndex(index); if (editor) { m_liteApp->editorManager()->closeEditor(editor); } updateCurrentItem(m_liteApp->editorManager()->currentEditor()); } LiteApi::IEditor *OpenEditorsWidget::editorFormIndex(const QModelIndex &index) { QString filePath = index.data(Qt::ToolTipRole).toString(); if (filePath.isEmpty()) { return 0; } return m_liteApp->editorManager()->findEditor(filePath,true); } QModelIndex OpenEditorsWidget::indexFromEditor(LiteApi::IEditor *editor) { QModelIndex r; if (!editor) { return r; } QString filePath = editor->filePath(); if (filePath.isEmpty()) { return r; } for (int i = 0; i < model()->rowCount(); i++) { QModelIndex index = model()->index(i,0); if (index.data(Qt::ToolTipRole).toString() == filePath) { return index; } } return r; }
4,890
C++
.cpp
125
34.024
137
0.680617
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,560
mainwindow.cpp
visualfc_liteide/liteidex/src/liteapp/mainwindow.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: mainwindow.cpp // Creator: visualfc <visualfc@gmail.com> #include "mainwindow.h" #include "aboutdialog.h" #include <QAction> #include <QActionGroup> #include <QIcon> #include <QMenuBar> #include <QToolBar> #include <QStatusBar> #include <QMessageBox> #include <QDockWidget> #include <QPushButton> #include <QFileDialog> #include <QCloseEvent> #include <QVBoxLayout> #include <QUrl> #include <QMimeData> #include <QTextBlock> #include <QRegExp> #include <QFileInfo> #include <QSplitter> #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 QMenu* MainWindow::s_macDocMenu = 0; QMap<QWidget*, QAction*> MainWindow::s_windowActions; MainWindow::MainWindow(IApplication *app, QWidget *parent) : ToolMainWindow(parent), m_liteApp(app), m_windowClosedCheck(false) { this->setAttribute(Qt::WA_DeleteOnClose); QIcon icon; icon.addFile("icon:images/liteide16.png"); icon.addFile("icon:images/liteide24.png"); icon.addFile("icon:images/liteide32.png"); icon.addFile("icon:images/liteide48.png"); icon.addFile("icon:images/liteide64.png"); icon.addFile("icon:images/liteide128.png"); this->setWindowIcon(icon); this->setContextMenuPolicy(Qt::CustomContextMenu); this->setAcceptDrops(true); m_mainSplitter = new QSplitter(Qt::Vertical,this); setCentralWidget(m_mainSplitter); #if QT_VERSION >= 0x050200 #ifdef Q_OS_OSX if (!s_macDocMenu) { s_macDocMenu = new QMenu; s_macDocMenu->setAsDockMenu(); } if (s_macDocMenu) { QAction *act = new QAction("macOS",this); act->setCheckable(true); s_macDocMenu->addAction(act); connect(act,SIGNAL(triggered(bool)),this,SLOT(triggeredWindowsAct())); s_windowActions.insert(this,act); } #endif #endif } QSplitter *MainWindow::splitter() { return m_mainSplitter; } void MainWindow::setWindowStyle(IWindowStyle *style) { ToolMainWindow::setWindowStyle(style); //loadInitToolState(m_liteApp->settings()->value("liteapp/toolState").toByteArray()); } MainWindow::~MainWindow() { s_windowActions.remove(this); delete m_liteApp; } void MainWindow::closeEvent(QCloseEvent *event) { if (this->m_windowClosedCheck) { return; } m_liteApp->saveSession(m_liteApp->currentSession()); m_liteApp->saveState(); m_liteApp->projectManager()->closeProject(); if (m_liteApp->editorManager()->closeAllEditors()) { this->m_windowClosedCheck = true; this->hideAllToolWindows(); event->accept(); } else { event->ignore(); } } void MainWindow::dragEnterEvent(QDragEnterEvent *event) { if (event->mimeData()->hasUrls()) event->acceptProposedAction(); } void MainWindow::changeEvent(QEvent *e) { if (e->type() == QEvent::WindowStateChange) { bool b = (windowState() & Qt::WindowFullScreen) != 0; emit fullScreenStateChanged(b); } } bool MainWindow::event(QEvent *event) { if (event->type() == QEvent::WindowActivate) { setActiveWindowAction(this); } return ToolMainWindow::event(event); } void MainWindow::setFullScreen(bool b) { if (bool(windowState() & Qt::WindowFullScreen) == b) return; if (b) { setWindowState(windowState() | Qt::WindowFullScreen); } else { setWindowState(windowState() & ~Qt::WindowFullScreen); } } void MainWindow::dropEvent(QDropEvent *event) { QList<QUrl> urls = event->mimeData()->urls(); if (urls.isEmpty()) return; QStringList folders; foreach (QUrl url, urls) { QString fileName = url.toLocalFile(); if (fileName.isEmpty()) { return; } QFileInfo info(fileName); if (info.isFile()) { m_liteApp->fileManager()->openFile(fileName); } else if(info.isDir()) { folders.append(info.filePath()); } } if (!folders.isEmpty()) { foreach (QString folder, folders) { m_liteApp->fileManager()->addFolderList(folder); } } } void MainWindow::setWindowTitle(const QString &name, const QString &filePath, bool isModify) { QAction *act = s_windowActions.value(this); if (act) { QString title = QString("(%1)").arg(m_liteApp->currentSession()); if (!name.isEmpty()) { title = name + " - "+title; } act->setText(title); } QString title = QString("LiteIDE (%1)").arg(m_liteApp->currentSession()); if (!filePath.isEmpty()) { QString path = QDir::toNativeSeparators(filePath); if (isModify) { path += "*"; } title = path + " - "+title; } else if (!name.isEmpty()) { title = name + " - "+title; } ToolMainWindow::setWindowTitle(title); } void MainWindow::currentEditorChanged(IEditor *editor) { QString name; QString filePath; bool isModified = false; if (editor) { name = editor->name(); filePath = editor->filePath(); isModified = editor->isModified(); } this->setWindowTitle(name,filePath,isModified); } void MainWindow::editorModifyChanged(IEditor *editor, bool b) { QString name; QString filePath; if (editor) { name = editor->name(); filePath = editor->filePath(); } this->setWindowTitle(name,filePath,b); } void MainWindow::about() { AboutDialog *dlg = new AboutDialog(m_liteApp,m_liteApp->mainWindow()); dlg->setAttribute(Qt::WA_DeleteOnClose); dlg->exec(); } void MainWindow::triggeredWindowsAct() { QAction *act = (QAction*)sender(); if (!act) { return; } QWidget *widget = s_windowActions.key(act,0); if (!widget) { return; } QWidget *window = widget->window(); if (window == this) { act->setChecked(true); this->setWindowState(windowState() & ~Qt::WindowMinimized); } window->raise(); window->activateWindow(); } void MainWindow::setActiveWindowAction(QWidget *window) { QMapIterator<QWidget*,QAction*> it(s_windowActions); while (it.hasNext()) { it.next(); it.value()->setChecked(it.key() == window); } }
7,427
C++
.cpp
247
25.582996
92
0.654975
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,561
toolwindowmanager.cpp
visualfc_liteide/liteidex/src/liteapp/toolwindowmanager.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: toolwindowmanager.cpp // Creator: visualfc <visualfc@gmail.com> #include "toolwindowmanager.h" #include "toolmainwindow.h" #include "liteapp_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 QAction *ToolWindowManager::addToolWindow(Qt::DockWidgetArea area, QWidget *widget, const QString &id, const QString &title, bool split, QList<QAction*> widgetActions, QList<QWidget *> widgetList) { return ((ToolMainWindow*)m_liteApp->mainWindow())->addToolWindow(m_liteApp,area,widget,id,title,split,widgetActions,widgetList); } void ToolWindowManager::moveToolWindow(Qt::DockWidgetArea from, Qt::DockWidgetArea to, QAction *action, bool split) { ((ToolMainWindow*)m_liteApp->mainWindow())->moveToolWindow(from,to,action,split); } QAction *ToolWindowManager::findToolWindow(QWidget *widget) { return ((ToolMainWindow*)m_liteApp->mainWindow())->findToolWindow(widget); } void ToolWindowManager::removeToolWindow(QAction *action) { ((ToolMainWindow*)m_liteApp->mainWindow())->removeToolWindow(action); } void ToolWindowManager::removeToolWindow(QWidget *widget) { QAction *act = this->findToolWindow(widget); if (act) { this->removeToolWindow(act); } }
2,452
C++
.cpp
57
40.842105
196
0.710339
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,562
filemanager.cpp
visualfc_liteide/liteidex/src/liteapp/filemanager.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: filemanager.cpp // Creator: visualfc <visualfc@gmail.com> #include "filemanager.h" #include "newfiledialog.h" #include "fileutil/fileutil.h" #include "liteenvapi/liteenvapi.h" #include "folderview/folderlistview.h" #include "folderview/multifolderview.h" #include "liteapp_global.h" #include "multifolderwindow.h" #include "splitfolderwindow.h" #include <QApplication> #include <QMenu> #include <QAction> #include <QFileDialog> #include <QFileInfo> #include <QRegExp> #include <QMenu> #include <QMessageBox> #include <QFileInfo> #include <QDateTime> #include <QFileSystemWatcher> #include <QMessageBox> #include <QTimer> #include <QDesktopServices> #include <QDir> #include <QVBoxLayout> #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 bool FileManager::initWithApp(IApplication *app) { if (!IFileManager::initWithApp(app)) { return false; } // m_folderWindow = new MultiFolderWindow(app); m_fileWatcher = new QFileSystemWatcher(this); connect(m_fileWatcher,SIGNAL(fileChanged(QString)),this,SLOT(fileChanged(QString))); m_newFileDialog = 0; m_initPath = m_liteApp->settings()->value("FileManager/initpath",QDir::homePath()).toString(); m_fileWatcherAutoReload = m_liteApp->settings()->value(LITEAPP_FILEWATCHERAUTORELOAD,false).toBool(); m_showHideFilesAct = new QAction(tr("Show Hidden Files"),this); m_showHideFilesAct->setCheckable(true); m_showDetailsAct = new QAction(tr("Show Details"),this); m_showDetailsAct->setCheckable(true); m_syncEditorAct = new QAction(QIcon("icon:images/sync.png"),tr("Synchronize with editor"),this); m_syncEditorAct->setCheckable(true); m_splitModeAct = new QAction(tr("Split Mode"),this); m_splitModeAct->setCheckable(true); bool bSplitMode = m_liteApp->settings()->value(LITEAPP_FOLDERSPLITMODE,false).toBool(); if (bSplitMode) { m_folderWindow = new SplitFolderWindow(app); } else { m_folderWindow = new MultiFolderWindow(app); } m_splitModeAct->setChecked(bSplitMode); bool bShowHiddenFiles = m_liteApp->settings()->value(LITEAPP_FOLDERSHOWHIDENFILES,false).toBool(); m_showHideFilesAct->setChecked(bShowHiddenFiles); m_folderWindow->setShowHideFiles(bShowHiddenFiles); bool bShowDetails = m_liteApp->settings()->value(LITEAPP_FOLDERSHOWDETAILS,false).toBool(); m_showDetailsAct->setChecked(bShowDetails); m_folderWindow->setShowDetails(bShowDetails); bool bSyncEditor = m_liteApp->settings()->value(LITEAPP_FOLDERSSYNCEDITOR,false).toBool(); m_syncEditorAct->setChecked(bSyncEditor); m_folderWindow->setSyncEditor(bSyncEditor); connect(m_showHideFilesAct,SIGNAL(triggered(bool)),this,SLOT(setShowHideFiles(bool))); connect(m_showDetailsAct,SIGNAL(triggered(bool)),this,SLOT(setShowDetails(bool))); connect(m_syncEditorAct,SIGNAL(triggered(bool)),this,SLOT(setSyncEditor(bool))); connect(m_splitModeAct,SIGNAL(triggered(bool)),this,SLOT(setSplitMode(bool))); 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); m_filterMenu->addSeparator(); m_filterMenu->addAction(m_splitModeAct); actions << m_filterMenu->menuAction() << m_syncEditorAct; m_folderWidget = new QWidget; m_layout = new QVBoxLayout; m_layout->setMargin(0); m_folderWidget->setLayout(m_layout); m_layout->addWidget(m_folderWindow->widget()); m_toolWindowAct = m_liteApp->toolWindowManager()->addToolWindow(Qt::LeftDockWidgetArea,m_folderWidget,"Folders",tr("Folders"),false,actions); return true; } FileManager::FileManager() : m_newFileDialog(0), m_folderWindow(0), m_checkBlockActivated(false), m_checkOnFocusChange(false) { connect(qApp, SIGNAL(focusChanged(QWidget*,QWidget*)), this, SLOT(onApplicationFocusChange())); } FileManager::~FileManager() { m_liteApp->settings()->setValue(LITEAPP_FOLDERSSYNCEDITOR,m_syncEditorAct->isChecked()); m_liteApp->settings()->setValue(LITEAPP_FOLDERSHOWHIDENFILES,m_showHideFilesAct->isChecked()); m_liteApp->settings()->setValue(LITEAPP_FOLDERSHOWDETAILS,m_showDetailsAct->isChecked()); m_liteApp->settings()->setValue(LITEAPP_FOLDERSPLITMODE,m_splitModeAct->isChecked()); delete m_filterMenu; delete m_fileWatcher; m_liteApp->settings()->setValue("FileManager/initpath",m_initPath); if (m_newFileDialog) { delete m_newFileDialog; } delete m_folderWindow; } bool FileManager::findProjectTargetInfo(const QString &fileName, QMap<QString,QString>& targetInfo) const { QString mimeType = m_liteApp->mimeTypeManager()->findMimeTypeByFile(fileName); if (m_liteApp->projectManager()->mimeTypeList().contains(mimeType)) { QList<IProjectFactory*> factoryList = m_liteApp->projectManager()->factoryList(); foreach(LiteApi::IProjectFactory *factory, factoryList) { if (factory->mimeTypes().contains(mimeType)) { bool ret = factory->findTargetInfo(fileName,mimeType,targetInfo); if (ret) { return true; } } } } return false; } QString FileManager::openAllTypeFilter() const { QStringList types; QStringList filter; foreach (IMimeType *mimeType, m_liteApp->mimeTypeManager()->mimeTypeList()) { QStringList patterns = mimeType->allPatterns(); types.append(patterns); filter.append(QString("%1 (%2)").arg(mimeType->comment()).arg(patterns.join(" "))); } types.removeDuplicates(); filter.removeDuplicates(); if (!types.isEmpty()) { QString all = QString(tr("All Support Files (%1)")).arg(types.join(" ")); filter.insert(0,all); } filter.append(tr("All Files (*)")); return filter.join(";;"); } QString FileManager::openProjectTypeFilter() const { QStringList types; QStringList filter; QStringList projectMimeTypes = m_liteApp->projectManager()->mimeTypeList(); foreach (IMimeType *mimeType, m_liteApp->mimeTypeManager()->mimeTypeList()) { QStringList patterns = mimeType->allPatterns(); if (projectMimeTypes.contains(mimeType->type())) { types.append(patterns); filter.append(QString("%1 (%2)").arg(mimeType->comment()).arg(patterns.join(" "))); } } types.removeDuplicates(); filter.removeDuplicates(); if (!types.isEmpty()) { QString all = QString(tr("All Support Files (%1)")).arg(types.join(" ")); filter.insert(0,all); } filter.append(tr("All Files (*)")); return filter.join(";;"); } QString FileManager::openEditorTypeFilter() const { QStringList types; QStringList filter; QStringList projectMimeTypes = m_liteApp->editorManager()->mimeTypeList(); foreach (IMimeType *mimeType, m_liteApp->mimeTypeManager()->mimeTypeList()) { if (projectMimeTypes.contains(mimeType->type())) { QStringList patterns = mimeType->allPatterns(); types.append(patterns); filter.append(QString("%1 (%2)").arg(mimeType->comment()).arg(patterns.join(" "))); } } types.removeDuplicates(); filter.removeDuplicates(); if (!types.isEmpty()) { QString all = QString(tr("All Support Files (%1)")).arg(types.join(" ")); filter.insert(0,all); } filter.append(tr("All Files (*)")); return filter.join(";;"); } QStringList FileManager::folderList() const { return m_folderWindow->folderList(); } void FileManager::setFolderList(const QStringList &folders) { m_folderWindow->setFolderList(folders); } void FileManager::addFolderList(const QString &folder) { m_folderWindow->addFolderList(folder); } IApplication* FileManager::openFolderInNewWindow(const QString &folder) { IApplication *app = m_liteApp->newInstance("dir:"+QDir(folder).dirName()); app->fileManager()->setFolderList(QStringList() << folder); return app; } void FileManager::emitAboutToShowFolderContextMenu(QMenu *menu, FILESYSTEM_CONTEXT_FLAG flag, const QFileInfo &info, const QString &context) { emit aboutToShowFolderContextMenu(menu,flag,info,context); } void FileManager::newFile() { QString projPath; QString filePath; IProject *project = m_liteApp->projectManager()->currentProject(); if (project) { QFileInfo info(project->filePath()); if (info.isDir()) { projPath = info.filePath(); } else { projPath = info.path(); } } IEditor *editor = m_liteApp->editorManager()->currentEditor(); if (editor && !editor->filePath().isEmpty()) { filePath = QFileInfo(editor->filePath()).absolutePath(); } if (filePath.isEmpty()) { #if QT_VERSION >= 0x050000 filePath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation); #else filePath = QDesktopServices::storageLocation(QDesktopServices::HomeLocation); #endif } if (projPath.isEmpty()) { #if QT_VERSION >= 0x050000 projPath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation); #else projPath = QDesktopServices::storageLocation(QDesktopServices::HomeLocation); #endif } execFileWizard(projPath,filePath); } void FileManager::openFiles() { QStringList fileNames = QFileDialog::getOpenFileNames(m_liteApp->mainWindow(), tr("Open Project or File"), m_initPath,openAllTypeFilter()); if (fileNames.isEmpty()) return; foreach (QString fileName, fileNames) { if (openFile(fileName)) { m_initPath = QFileInfo(fileName).canonicalPath(); } } } void FileManager::openFolder() { QString folder = QFileDialog::getExistingDirectory(m_liteApp->mainWindow(), tr("Select a folder:"), m_initPath); if (!folder.isEmpty()) { QDir dir(folder); if (dir.cdUp()) { m_initPath = dir.path(); } this->addFolderList(folder); } } void FileManager::newInstance() { m_liteApp->newInstance(""); } void FileManager::openFolderNewWindow() { QString folder = QFileDialog::getExistingDirectory(m_liteApp->mainWindow(), tr("Select a folder:"), m_initPath); if (!folder.isEmpty()) { QDir dir(folder); if (dir.cdUp()) { m_initPath = dir.path(); } this->openFolderInNewWindow(folder); } } void FileManager::closeAllFolders() { m_folderWindow->closeAllFolders(); } void FileManager::openEditors() { QStringList fileNames = QFileDialog::getOpenFileNames(m_liteApp->mainWindow(), tr("Open Files"), m_initPath,openEditorTypeFilter()); if (fileNames.isEmpty()) return; foreach (QString fileName, fileNames) { if (openEditor(fileName)) { m_initPath = QFileInfo(fileName).canonicalPath(); } } } void FileManager::openProjects() { QStringList fileNames = QFileDialog::getOpenFileNames(m_liteApp->mainWindow(), tr("Open Project"), m_initPath,openProjectTypeFilter()); if (fileNames.isEmpty()) return; foreach (QString fileName, fileNames) { if (openProject(fileName)) { m_initPath = QFileInfo(fileName).canonicalPath(); } } } void FileManager::execFileWizard(const QString &projPath, const QString &filePath, const QString &gopath) { if (!m_newFileDialog) { m_newFileDialog = new NewFileDialog(m_liteApp->mainWindow()); m_newFileDialog->loadTemplate(m_liteApp->resourcePath()+"/liteapp/template"); } QStringList pathList = LiteApi::getGOPATH(m_liteApp,false); //pathList.append(LiteApi::getGOROOT(m_liteApp)); pathList.removeDuplicates(); m_newFileDialog->setPathList(pathList); if (!gopath.isEmpty()) { m_newFileDialog->setGopath(gopath); } m_newFileDialog->setFileLocation(filePath); m_newFileDialog->setProjectLocation(projPath); m_newFileDialog->updateLocation(); if (pathList.isEmpty() && gopath.isEmpty()) { m_newFileDialog->setGopath(projPath); } if (m_newFileDialog->exec() == QDialog::Accepted) { //emit fileWizardFinished(m_newFileDialog->openPath(),m_newFileDialog->f) emit fileWizardFinished(m_newFileDialog->type(),m_newFileDialog->scheme(),m_newFileDialog->openPath()); QMessageBox::StandardButton ret; ret = QMessageBox::question(m_liteApp->mainWindow(), tr("LiteIDE"), tr("Project '%1' has been created.\n" "Do you want to open it now?") .arg(m_newFileDialog->openFiles().join(" ")), QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::Yes); if (ret == QMessageBox::Yes) { QString scheme = m_newFileDialog->scheme(); if (scheme == "folder") { this->addFolderList(m_newFileDialog->openPath()); } foreach(QString file, m_newFileDialog->openFiles()) { this->openFile(file); } } } } bool FileManager::openFile(const QString &fileName) { QString mimeType = m_liteApp->mimeTypeManager()->findMimeTypeByFile(fileName); if (m_liteApp->projectManager()->mimeTypeList().contains(mimeType)) { return openProject(fileName) != 0; } else { return openEditor(fileName) != 0; } return false; } IEditor *FileManager::createEditor(const QString &contents, const QString &mimeType) { foreach(LiteApi::IEditorFactory *factory, m_liteApp->editorManager()->factoryList()) { if (factory->mimeTypes().contains(mimeType)) { LiteApi::IEditor *editor = factory->create(contents,mimeType); if (editor) { return editor; } } } return NULL; } IEditor *FileManager::createEditor(const QString &_fileName) { QString fileName = QDir::fromNativeSeparators(_fileName); QString mimeType = m_liteApp->mimeTypeManager()->findMimeTypeByFile(fileName); foreach(LiteApi::IEditorFactory *factory, m_liteApp->editorManager()->factoryList()) { if (factory->mimeTypes().contains(mimeType)) { LiteApi::IEditor *editor = factory->open(fileName,mimeType); if (editor) { return editor; } } } return NULL; } IEditor *FileManager::openEditor(const QString &_fileName, bool bActive, bool ignoreNavigationHistory) { QString fileName = QDir::fromNativeSeparators(QDir::cleanPath(_fileName)); QString mimeType = m_liteApp->mimeTypeManager()->findMimeTypeByFile(fileName); IEditor *editor = m_liteApp->editorManager()->openEditor(fileName,mimeType); if (editor && bActive) { m_liteApp->editorManager()->setCurrentEditor(editor,ignoreNavigationHistory); } if (editor) { m_liteApp->recentManager()->addRecent(fileName,"file"); } else { m_liteApp->recentManager()->removeRecent(fileName,"file"); } return editor; } IEditor *FileManager::openEditorByFactory(const QString &_fileName, const QString &factoryId, bool bActive, bool ignoreNavigationHistory) { QString fileName = QDir::fromNativeSeparators(QDir::cleanPath(_fileName)); QString mimeType = m_liteApp->mimeTypeManager()->findMimeTypeByFile(fileName); IEditor *editor = m_liteApp->editorManager()->openEditorByFactory(fileName,mimeType,factoryId); if (editor && bActive) { m_liteApp->editorManager()->setCurrentEditor(editor,ignoreNavigationHistory); } if (editor) { m_liteApp->recentManager()->addRecent(fileName,"file"); } else { m_liteApp->recentManager()->removeRecent(fileName,"file"); } return editor; } IProject *FileManager::openProject(const QString &_fileName) { QString fileName = QDir::fromNativeSeparators(_fileName); QString mimeType = m_liteApp->mimeTypeManager()->findMimeTypeByFile(fileName); IProject *proj = m_liteApp->projectManager()->openProject(fileName,mimeType); if (proj) { m_liteApp->recentManager()->addRecent(fileName,"proj"); } else { m_liteApp->recentManager()->removeRecent(fileName,"proj"); } return proj; } //IApplication* FileManager::openFolderEx(const QString &folder) //{ // QDir dir(folder); // if (!dir.exists()) { // return m_liteApp; // } // if (m_folderWidget->rootPathList().isEmpty()) { // m_folderWidget->setRootPath(folder); // } else { // if (m_liteApp->settings()->value(LITEAPP_OPTNFOLDERINNEWWINDOW,true).toBool()) { // return this->openFolderInNewWindow(folder); // } else { // m_folderWidget->setRootPath(folder); // } // } // m_toolWindowAct->setChecked(true); // addRecentFile(folder,"folder"); // return m_liteApp; //} IProject *FileManager::openProjectScheme(const QString &_fileName, const QString &scheme) { QString fileName = QDir::fromNativeSeparators(_fileName); QString mimeType = m_liteApp->mimeTypeManager()->findMimeTypeByScheme(scheme); if (mimeType.isEmpty()) { return 0; } IProject *proj = m_liteApp->projectManager()->openProject(QDir::fromNativeSeparators(fileName),mimeType); if (proj) { m_liteApp->recentManager()->addRecent(fileName,scheme); } else { m_liteApp->recentManager()->removeRecent(fileName,scheme); } return proj; } void FileManager::applyOption(QString id) { if (id != OPTION_LITEAPP) { return; } m_fileWatcherAutoReload = m_liteApp->settings()->value(LITEAPP_FILEWATCHERAUTORELOAD,false).toBool(); } void FileManager::updateFileState(const QString &fileName) { if (fileName.isEmpty()) { return; } m_fileStateMap.insert(fileName,QFileInfo(fileName).lastModified()); if (!m_fileWatcher->files().contains(fileName)) { m_fileWatcher->addPath(fileName);; } } void FileManager::editorCreated(LiteApi::IEditor *editor) { if (!editor) { return; } QString fileName = editor->filePath(); if (!fileName.isEmpty()) { updateFileState(fileName); } } void FileManager::editorAboutToClose(LiteApi::IEditor *editor) { if (!editor) { return; } QString fileName = editor->filePath(); if (!fileName.isEmpty()) { m_fileStateMap.remove(fileName); m_changedFiles.remove(fileName); m_fileWatcher->removePath(fileName); } } void FileManager::editorSaved(LiteApi::IEditor *editor) { if (!editor) { return; } updateFileState(editor->filePath()); } void FileManager::fileChanged(QString fileName) { const bool wasempty = m_changedFiles.isEmpty(); if (m_fileStateMap.contains(fileName)) { m_changedFiles.insert(fileName); } if (wasempty && !m_changedFiles.isEmpty()) { QTimer::singleShot(200, this, SLOT(checkForReload())); } } void FileManager::onApplicationFocusChange() { if (!m_checkOnFocusChange) return; m_checkOnFocusChange = false; checkForReload(); } void FileManager::setShowHideFiles(bool b) { m_folderWindow->setShowHideFiles(b); } void FileManager::setShowDetails(bool b) { m_folderWindow->setShowDetails(b); } void FileManager::setSyncEditor(bool b) { m_folderWindow->setSyncEditor(b); } void FileManager::setSplitMode(bool b) { QStringList folderList = m_folderWindow->folderList(); delete m_folderWindow; if (b) { m_folderWindow = new SplitFolderWindow(m_liteApp); } else { m_folderWindow = new MultiFolderWindow(m_liteApp); } m_layout->addWidget(m_folderWindow->widget()); m_folderWindow->setFolderList(folderList); m_folderWindow->setShowHideFiles(m_showHideFilesAct->isChecked()); m_folderWindow->setShowDetails(m_showDetailsAct->isChecked()); m_folderWindow->setSyncEditor(m_syncEditorAct->isChecked()); } void FileManager::checkForReload() { if (m_changedFiles.isEmpty()) { return; } if (this->m_checkBlockActivated) return; if (QApplication::activeModalWidget()) { // We do not want to prompt for modified file if we currently have some modal dialog open. // There is no really sensible way to get notified globally if a window closed, // so just check on every focus change. m_checkOnFocusChange = true; return; } this->m_checkBlockActivated = true; int lastReloadRet = QMessageBox::Yes; int lastCloseRet = QMessageBox::Yes; QStringList files = m_changedFiles.toList(); m_changedFiles.clear(); foreach (QString fileName, files) { if (!QFile::exists(fileName)) { //remove if (m_fileStateMap.contains(fileName)) { if (!fileName.isEmpty()) { LiteApi::IEditor *editor = m_liteApp->editorManager()->findEditor(fileName,false); if (editor) { // The file has been deleted. // If the buffer is modified, ask the user what he wants to do. // Otherwise, apply the default action : close the editor. int ret = QMessageBox::Yes; if (lastCloseRet != QMessageBox::YesToAll) { if (m_fileWatcherAutoReload) { if (editor->isModified() ) { QString text = QString(tr("%1\nThis file has been deleted from the drive,\n" "but you have unsaved modifications in your LiteIDE editor.\n" "\nDo you want to close the editor?" "\nAnswering \"Yes\" will discard your unsaved changes.")).arg(fileName); ret = QMessageBox::question(m_liteApp->mainWindow(),tr("LiteIDE X"),text,QMessageBox::YesToAll|QMessageBox::Yes|QMessageBox::No,QMessageBox::No); } } else { QString text = QString(tr("%1\nThis file has been deleted from the drive.\n" "\nDo you want to close the editor?")).arg(fileName); ret = QMessageBox::question(m_liteApp->mainWindow(),tr("LiteIDE X"),text,QMessageBox::YesToAll|QMessageBox::Yes|QMessageBox::No,QMessageBox::No); } } if (ret == QMessageBox::Yes || ret == QMessageBox::YesToAll) { m_liteApp->editorManager()->closeEditor(editor); m_liteApp->appendLog("EditorManager",fileName+" remove",false); } if (ret == QMessageBox::YesToAll) { lastCloseRet = QMessageBox::YesToAll; } } } } } else { if (m_fileStateMap.contains(fileName)) { LiteApi::IEditor *editor = m_liteApp->editorManager()->findEditor(fileName,true); if (editor) { // The file has been modified. // If the buffer is modified, ask the user what he wants to do. // Otherwise, apply the default action : reload the new content in the editor. QDateTime lastModified = QFileInfo(fileName).lastModified(); QDateTime modified = m_fileStateMap.value(fileName); if (!m_fileWatcher->files().contains(fileName)) { m_fileWatcher->addPath(fileName);; } if (lastModified > modified) { int ret = QMessageBox::Yes; if (lastReloadRet != QMessageBox::YesToAll) { if (m_fileWatcherAutoReload) { if (editor->isModified()) { QString text = QString(tr("%1\nThis file has been modified on the drive,\n" "but you have unsaved modifications in your LiteIDE editor.\n" "\nDo you want to reload the file from disk?" "\nAnswering \"Yes\" will discard your unsaved changes.")).arg(fileName); ret = QMessageBox::question(m_liteApp->mainWindow(),tr("LiteIDE X"),text,QMessageBox::YesToAll|QMessageBox::Yes|QMessageBox::No,QMessageBox::YesToAll); } } else { QString text = QString(tr("%1\nThis file has been modified on the drive.\n" "\nDo you want to reload the file from disk?")).arg(fileName); ret = QMessageBox::question(m_liteApp->mainWindow(),tr("LiteIDE X"),text,QMessageBox::YesToAll|QMessageBox::Yes|QMessageBox::No,QMessageBox::YesToAll); } } if (ret == QMessageBox::YesToAll || ret == QMessageBox::Yes) { // If the file modification is the result of an internal Ctrl+S, do not reload QDateTime lastModified = QFileInfo(fileName).lastModified(); QDateTime modified = m_fileStateMap.value(fileName); if (lastModified != modified) { editor->reload(); m_fileStateMap.insert(fileName,lastModified); m_liteApp->appendLog("EditorManager",fileName+" reload",false); } } if (ret == QMessageBox::YesToAll) { lastReloadRet = QMessageBox::YesToAll; } } } } } } m_checkBlockActivated = false; QTimer::singleShot(200, this, SLOT(checkForReload())); }
27,687
C++
.cpp
680
32.770588
187
0.635689
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,563
liteapp.cpp
visualfc_liteide/liteidex/src/liteapp/liteapp.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: liteapp.cpp // Creator: visualfc <visualfc@gmail.com> #include "liteapp.h" #include "filemanager.h" #include "editormanager.h" #include "projectmanager.h" #include "pluginmanager.h" #include "actionmanager.h" #include "mimetypemanager.h" #include "optionmanager.h" #include "toolwindowmanager.h" #include "htmlwidgetmanager.h" #include "recentmanager.h" #include "mainwindow.h" #include "liteappoptionfactory.h" #include "folderprojectfactory.h" #include "textbrowserhtmlwidget.h" #include "pluginsdialog.h" #include "liteapp_global.h" #ifdef Q_OS_MAC #include "macsupport.h" #endif #include "splitwindowstyle.h" #include "sidewindowstyle.h" #include "idletimer.h" #include "iconutil/iconutil.h" #include "liteapi/liteutil.h" #include "liteapi/liteids.h" #include <QApplication> #include <QSplashScreen> #include <QMenuBar> #include <QDir> #include <QToolBar> #include <QAction> #include <QDateTime> #include <QSplitter> #include <QTextCursor> #include <QTextBlock> #include <QTimer> #include <QPainter> #include <QComboBox> #include <QProcessEnvironment> #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 LITEIDE_VERSION "X38.3" QString LiteApp::getRootPath() { QDir rootDir = QApplication::applicationDirPath(); rootDir.cdUp(); return rootDir.canonicalPath(); } QString LiteApp::getToolPath() { static QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); QString path = env.value("LITEIDE_TOOL_PATH"); if (!path.isEmpty()) { return path; } return QApplication::applicationDirPath(); } QString LiteApp::getPluginPath() { static QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); QString path = env.value("LITEIDE_PLUGIN_PATH"); if (!path.isEmpty()) { return path; } QString root = getRootPath(); #ifdef Q_OS_MAC return root+"/PlugIns"; #else return root+"/lib/liteide/plugins"; #endif } QString LiteApp::getResoucePath() { static QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); QString path = env.value("LITEIDE_RES_PATH"); if (!path.isEmpty()) { return path; } QString root = getRootPath(); #ifdef Q_OS_MAC return root+"/Resources"; #else return root+"/share/liteide"; #endif } QString LiteApp::getStoragePath() { #if QT_VERSION >= 0x050000 QString root = QStandardPaths::writableLocation(QStandardPaths::DataLocation); #else QString root = QDesktopServices::storageLocation(QDesktopServices::DataLocation); #endif return root+"/liteide"; } IApplication* LiteApp::NewApplication(const QString &sessionName, IApplication *baseApp) { LiteApp *app = new LiteApp; app->load(sessionName,baseApp); return app; } PluginManager *LiteApp::pluginManager() { static PluginManager manager; return &manager; } QList<IApplication *> LiteApp::appList() { return s_appList; } QMap<QString,QVariant> LiteApp::s_cookie; QList<IApplication*> LiteApp::s_appList; LiteApp::LiteApp() : m_rootPath(LiteApp::getRootPath()), m_applicationPath(QApplication::applicationDirPath()), m_toolPath(LiteApp::getToolPath()), m_pluginPath(LiteApp::getPluginPath()), m_resourcePath(LiteApp::getResoucePath()), m_storagePath(LiteApp::getStoragePath()) { s_appList.append(this); QSettings global(m_resourcePath+"/liteapp/config/global.ini",QSettings::IniFormat); bool storeLocal = global.value(LITEIDE_STORELOCAL,false).toBool(); QString flagLocalSetting = "--local-setting"; QString flagUserSetting = "--user-setting"; if (s_cookie.value(flagUserSetting).toBool()) { storeLocal = false; } else if (s_cookie.value(flagLocalSetting).toBool()) { storeLocal = true; } if (storeLocal) { m_settings = new QSettings(m_resourcePath+"/liteapp/config/liteide.ini", QSettings::IniFormat); } else { m_settings = new QSettings(QSettings::IniFormat,QSettings::UserScope,"liteide","liteide",this); } QStringList searchPathList; if (m_settings->value(LITEIDE_CUSTOMEICON,false).toBool()) { QString iconPath = m_settings->value(LITEIDE_CUSTOMEICONPATH,"default").toString(); if (!iconPath.isEmpty()) { searchPathList << m_resourcePath+"/liteapp/qrc/"+iconPath+"/liteapp"; searchPathList << m_resourcePath+"/liteapp/qrc/"+iconPath; } } searchPathList << ":/"; searchPathList << m_resourcePath+"/liteapp/qrc/default/liteapp"; searchPathList << m_resourcePath+"/liteapp/qrc/default"; QDir::setSearchPaths("icon",searchPathList); m_extension = new Extension; //install idle timer; m_idleTimer = new AppIdleTimer; m_extension->addObject("LiteApi.IAppIdleTimer",m_idleTimer); m_mainwindow = new MainWindow(this); QString style = this->settings()->value(LITEAPP_STYLE,"sidebar").toString(); if (style == "splitter") { SplitWindowStyle *style = new SplitWindowStyle(this,m_mainwindow); m_mainwindow->setWindowStyle(style); } else { SideWindowStyle *style = new SideWindowStyle(this,m_mainwindow); m_mainwindow->setWindowStyle(style); } m_toolWindowManager = new ToolWindowManager; m_htmlWidgetManager = new HtmlWidgetManager; m_actionManager = new ActionManager; m_projectManager = new ProjectManager; m_fileManager = new FileManager; m_editorManager = new EditorManager; m_mimeTypeManager = new MimeTypeManager; m_optionManager = new OptionManager; m_recentManager = new RecentManager; m_goProxy = new GoProxy(this); m_actionManager->initWithApp(this); m_mainwindow->createToolWindowMenu(); m_toolWindowManager->initWithApp(this); m_mimeTypeManager->initWithApp(this); m_recentManager->initWithApp(this); m_projectManager->initWithApp(this); m_fileManager->initWithApp(this); m_editorManager->initWithApp(this); m_optionManager->initWithApp(this); //m_mainwindow->setCentralWidget(m_editorManager->widget()); m_mainwindow->splitter()->addWidget(m_editorManager->widget()); //m_mainwindow->splitter()->addWidget(m_outputManager->widget()); m_mainwindow->splitter()->setStretchFactor(0,50); //m_mainwindow->setStatusBar(m_outputManager->statusBar()); m_htmlWidgetManager->addFactory(new TextBrowserHtmlWidgetFactory(this)); m_extension->addObject("LiteApi.IMimeTypeManager",m_mimeTypeManager); m_extension->addObject("LiteApi.IProjectManager",m_projectManager); m_extension->addObject("LiteApi.IEditManager",m_editorManager); m_extension->addObject("LiteApi.IOptoinManager",m_optionManager); m_extension->addObject("LiteApi.IToolWindowManager",m_toolWindowManager); m_extension->addObject("LiteApi.QMainWindow",m_mainwindow); m_extension->addObject("LiteApi.QMainWindow.QSplitter",m_mainwindow->splitter()); m_extension->addObject("LiteApi.IHtmlWidgetManager",m_htmlWidgetManager); //add actions connect(m_projectManager,SIGNAL(currentProjectChanged(LiteApi::IProject*)),this,SLOT(currentProjectChanged(LiteApi::IProject*))); connect(m_editorManager,SIGNAL(currentEditorChanged(LiteApi::IEditor*)),m_projectManager,SLOT(currentEditorChanged(LiteApi::IEditor*))); connect(m_editorManager,SIGNAL(currentEditorChanged(LiteApi::IEditor*)),m_mainwindow,SLOT(currentEditorChanged(LiteApi::IEditor*))); connect(m_editorManager,SIGNAL(editorModifyChanged(LiteApi::IEditor*,bool)),m_mainwindow,SLOT(editorModifyChanged(LiteApi::IEditor*,bool))); connect(m_editorManager,SIGNAL(currentEditorChanged(LiteApi::IEditor*)),this,SLOT(currentEditorChanged(LiteApi::IEditor*))); connect(m_editorManager,SIGNAL(tabAddRequest()),m_fileManager,SLOT(openEditors())); connect(m_editorManager,SIGNAL(editorSaved(LiteApi::IEditor*)),m_fileManager,SLOT(editorSaved(LiteApi::IEditor*))); connect(m_editorManager,SIGNAL(editorCreated(LiteApi::IEditor*)),m_fileManager,SLOT(editorCreated(LiteApi::IEditor*))); connect(m_editorManager,SIGNAL(editorAboutToClose(LiteApi::IEditor*)),m_fileManager,SLOT(editorAboutToClose(LiteApi::IEditor*))); connect(m_editorManager,SIGNAL(doubleClickedTab()),m_mainwindow,SLOT(showOrHideToolWindow())); connect(m_optionManager,SIGNAL(applyOption(QString)),m_fileManager,SLOT(applyOption(QString))); connect(m_optionManager,SIGNAL(applyOption(QString)),m_projectManager,SLOT(applyOption(QString))); connect(m_optionManager,SIGNAL(applyOption(QString)),m_editorManager,SLOT(applyOption(QString))); connect(m_optionManager,SIGNAL(applyOption(QString)),this,SLOT(applyOption(QString))); QAction *esc = new QAction(tr("Escape"),this); m_actionManager->getActionContext(this,"App")->regAction(esc,"Escape","ESC"); m_mainwindow->addAction(esc); connect(esc,SIGNAL(triggered()),this,SLOT(escape())); createActions(); createMenus(); createToolBars(); m_editorManager->createActions(); m_logOutput = new TextOutput(this); //m_outputManager->addOutuput(m_logOutput,tr("Console")); m_logAct = m_toolWindowManager->addToolWindow(Qt::BottomDockWidgetArea,m_logOutput,"EventLog",tr("Event Log"),true); connect(m_logOutput,SIGNAL(dbclickEvent(QTextCursor)),this,SLOT(dbclickLogOutput(QTextCursor))); m_optionAct = new QAction(loadIcon("icon:images/options.png"),tr("Options"),this); m_optionAct->setMenuRole(QAction::PreferencesRole); m_actionManager->setViewMenuSeparator("sep/option",true); m_actionManager->insertViewMenuAction(m_optionAct,"sep/option"); m_stdToolBar->addSeparator(); m_stdToolBar->addAction(m_optionAct); connect(m_optionAct,SIGNAL(triggered()),m_optionManager,SLOT(exec())); this->appendLog("LiteApp","Initializing"); this->appendLog("Load Setting",m_settings->fileName()); m_liteAppOptionFactory = new LiteAppOptionFactory(this,this); m_optionManager->addFactory(m_liteAppOptionFactory); connect(m_goProxy,SIGNAL(stdoutput(QByteArray)),this,SLOT(goproxyDone(QByteArray))); //connect(this,SIGNAL(key_escape()),m_mainwindow,SLOT(hideOutputWindow())); connect(m_mainwindow,SIGNAL(fullScreenStateChanged(bool)),m_fullScreent,SLOT(setChecked(bool))); } static QImage makeSplashImage(LiteApi::IApplication *app) { QRect r(0,0,400,280); QImage image(r.size(),QImage::Format_ARGB32_Premultiplied); QPainter painter(&image); painter.setRenderHint(QPainter::Antialiasing,true); QLinearGradient lg(0,0,r.width(),r.height()); lg.setColorAt(0.0,qRgb(0,125,127)); lg.setColorAt(1.0,qRgb(0,88,127)); QBrush bk(lg); painter.fillRect(r,bk); int th = r.height()*2/5; int bh = r.height()-th; painter.fillRect(1,th,r.width()-2,bh-1,Qt::white); QFont font("Timer",32); font.setPointSize(32); font.setItalic(true); painter.setPen(Qt::white); painter.setFont(font); painter.drawText(2,2,r.width()-2,th,Qt::AlignCenter,app->ideFullName()); font.setPointSize(9); font.setItalic(false); font.setBold(true); painter.setPen(Qt::black); painter.setFont(font); painter.drawText(10,th,r.width()-10,bh,Qt::AlignLeft|Qt::AlignVCenter,app->ideCopyright()); painter.drawImage(r.width()-145,r.height()-145,QImage("icon:/images/liteide-logo128.png")); return image; } void LiteApp::load(const QString &sessionName, IApplication *baseApp) { bool bLoadSession = true; if (baseApp == 0) { bLoadSession = m_settings->value(LITEAPP_AUTOLOADLASTSESSION,true).toBool(); } m_currentSession = sessionName; if (!bLoadSession) { m_currentSession = "emtpy"; } QSplashScreen *splash = 0; bool bSplash = m_settings->value(LITEAPP_SPLASHVISIBLE,true).toBool(); if (baseApp) { bSplash = false; } if (bSplash) { splash = new QSplashScreen(QPixmap::fromImage(makeSplashImage(this)),Qt::WindowStaysOnTopHint); } if (bSplash) { splash->show(); } if (bSplash) { splash->showMessage("Scanning plugins...",Qt::AlignLeft|Qt::AlignBottom); } qApp->processEvents(); loadMimeType(); loadPlugins(); if (bSplash) { splash->showMessage("Loading plugins...",Qt::AlignLeft|Qt::AlignBottom); } qApp->processEvents(); initPlugins(); if (bSplash) { splash->showMessage("Loading state...",Qt::AlignLeft|Qt::AlignBottom); } qApp->processEvents(); loadState(); if (baseApp) { if (baseApp->mainWindow()->isMaximized()) { m_mainwindow->resize(800,600); m_mainwindow->show(); } else { QRect rc = baseApp->mainWindow()->geometry(); rc.adjust(20,20,20,20); m_mainwindow->setGeometry(rc); m_mainwindow->show(); } } else { m_mainwindow->show(); } emit loaded(); m_projectManager->setCurrentProject(0); if (bSplash) { splash->showMessage("Loading session...",Qt::AlignLeft|Qt::AlignBottom); } qApp->processEvents(); if (bLoadSession && !sessionName.isEmpty()) { loadSession(sessionName); this->appendLog("Load session",sessionName); } if (bSplash) { m_mainwindow->raise(); splash->finish(m_mainwindow); splash->deleteLater(); } this->appendLog("HtmlWidgetFactory",m_htmlWidgetManager->classNameList().join(" ")); this->appendLog("DefaultHtmlWidgetFactory",m_htmlWidgetManager->defaultClassName()); m_goProxy->call("version"); appendLog("LiteApp","Finished loading"); } LiteApp::~LiteApp() { s_appList.removeAll(this); cleanup(); } IExtension *LiteApp::extension() { return m_extension; } void LiteApp::cleanup() { // emit aboutToQuit(); //delete plugin by reverse depend QListIterator<IPlugin*> it(m_pluginList); it.toBack(); while(it.hasPrevious()) { IPlugin *p = it.previous(); //qDebug() << "clean plugin" << p; delete p; } m_pluginList.clear(); delete m_idleTimer; delete m_projectManager; delete m_editorManager; delete m_htmlWidgetManager; delete m_liteAppOptionFactory; delete m_fileManager; delete m_mimeTypeManager; delete m_optionManager; delete m_logOutput; delete m_toolWindowManager; delete m_recentManager; delete m_actionManager; delete m_extension; delete m_settings; } void LiteApp::aboutPlugins() { PluginsDialog *dlg = new PluginsDialog(this,m_mainwindow); foreach (LiteApi::IPluginFactory *factory, pluginManager()->factoryList()) { dlg->appendInfo(factory->info()); } dlg->exec(); } void LiteApp::escape() { IEditor *editor = m_editorManager->currentEditor(); if (!editor) { return; } bool bFocus = editor->widget()->isAncestorOf(qApp->focusWidget()); if (!bFocus) { editor->onActive(); } else { emit key_escape(); m_mainwindow->hideOutputWindow(); } } void LiteApp::newWindow() { LiteApp::newInstance("default"); } void LiteApp::closeWindow() { m_mainwindow->close(); } void LiteApp::exit() { qApp->closeAllWindows(); } void LiteApp::applyOption(QString id) { if (id != OPTION_LITEAPP) { return; } //bool b = m_settings->value(LITEAPP_OPTNFOLDERINNEWWINDOW,true).toBool(); //m_openFolderNewWindowAct->setVisible(!b); } bool LiteApp::hasGoProxy() const { return GoProxy::hasProxy(); } IGoProxy *LiteApp::createGoProxy(QObject *parent) { return new GoProxy(parent); } IApplication *LiteApp::newInstance(const QString &sessionName) { return LiteApp::NewApplication(sessionName,this); } QList<IApplication *> LiteApp::instanceList() const { return s_appList; } IEditorManager *LiteApp::editorManager() { return m_editorManager; } IFileManager *LiteApp::fileManager() { return m_fileManager; } IProjectManager *LiteApp::projectManager() { return m_projectManager; } IActionManager *LiteApp::actionManager() { return m_actionManager; } IMimeTypeManager *LiteApp::mimeTypeManager() { return m_mimeTypeManager; } IOptionManager *LiteApp::optionManager() { return m_optionManager; } IToolWindowManager *LiteApp::toolWindowManager() { return m_toolWindowManager; } IHtmlWidgetManager *LiteApp::htmlWidgetManager() { return m_htmlWidgetManager; } IRecentManager *LiteApp::recentManager() { return m_recentManager; } QMainWindow *LiteApp::mainWindow() const { return m_mainwindow; } QSettings *LiteApp::settings() { return m_settings; } QMap<QString,QVariant> &LiteApp::globalCookie() { return s_cookie; } QString LiteApp::rootPath() const { return m_rootPath; } QString LiteApp::resourcePath() const { return m_resourcePath; } QString LiteApp::applicationPath() const { return m_applicationPath; } QString LiteApp::toolPath() const { return m_toolPath; } QString LiteApp::pluginPath() const { return m_pluginPath; } QString LiteApp::storagePath() const { return m_storagePath; } QString LiteApp::ideVersion() const { return LITEIDE_VERSION; } QString LiteApp::ideFullName() const { return this->ideName()+" "+this->ideVersion(); } QString LiteApp::ideName() const { return "LiteIDE"; } QString LiteApp::ideCopyright() const { static QString s_info = "2011-2023(c)\n" "visualfc@gmail.com\n" "\n" "https://github.com/visualfc/liteide\n"; return s_info; } void LiteApp::setPluginPath(const QString &path) { m_pluginPath = path; appendLog("LiteApp","Set plugin path to "+path); } void LiteApp::setResourcePath(const QString &path) { m_resourcePath = path; appendLog("LiteApp","Set resource path to "+path); } QList<IPlugin*> LiteApp::pluginList() const { return m_pluginList; } void LiteApp::appendLog(const QString &model, const QString &log, bool error) { QDateTime dt = QDateTime::currentDateTime(); QString text = dt.toString("hh:mm:ss"); text += QLatin1Char(' '); text += model; text += ": "; text += log; text += QLatin1Char('\n'); m_logOutput->updateExistsTextColor(); if (error) { m_logOutput->append(text,Qt::red); m_logAct->setChecked(true); } else { m_logOutput->append(text); } } void LiteApp::sendBroadcast(const QString &module, const QString &id, const QVariant &param) { emit broadcast(module,id,param); } void LiteApp::loadPlugins() { pluginManager()->loadPlugins(m_pluginPath); } void LiteApp::loadMimeType() { QDir dir(m_resourcePath+"/liteapp/mimetype"); if (dir.exists()) { m_mimeTypeManager->loadMimeTypes(dir.absolutePath()); } } void LiteApp::initPlugins() { foreach (IPluginFactory *factory,pluginManager()->factoryList()) { bool load = m_settings->value(QString("liteapp/%1_load").arg(factory->id()),true).toBool(); if (!load) { continue; } LiteApi::IPlugin *plugin = factory->createPlugin(); if (plugin) { bool ret = plugin->load(this); if (ret) { m_pluginList.append(plugin); } appendLog("LiteApp",QString("%1 %2").arg(ret?"Loaded":"ERROR while loading").arg(factory->id()),!ret); } } } void LiteApp::createActions() { IActionContext *actionContext = m_actionManager->getActionContext(this,"App"); m_newAct = new QAction(loadIcon("icon:images/new.png"),tr("New..."),m_mainwindow); actionContext->regAction(m_newAct,"New",QKeySequence::New); m_openFileAct = new QAction(loadIcon("icon:images/openfile.png"),tr("Open File..."),m_mainwindow); actionContext->regAction(m_openFileAct,"OpenFile",QKeySequence::Open); m_openFolderAct = new QAction(loadIcon("icon:images/openfolder.png"),tr("Open Folder..."),m_mainwindow); actionContext->regAction(m_openFolderAct,"OpenFolder",""); m_openFolderNewWindowAct = new QAction(loadIcon("icon:images/openfolder.png"),tr("Open Folder in New Window..."),m_mainwindow); //bool b = m_settings->value(LITEAPP_OPTNFOLDERINNEWWINDOW,true).toBool(); //m_openFolderNewWindowAct->setVisible(!b); actionContext->regAction(m_openFolderNewWindowAct,"OpenFolderNewWindow",""); m_closeAllFolderAct = new QAction(tr("Close All Folders"),m_mainwindow); actionContext->regAction(m_closeAllFolderAct,"CloseAllFolders",""); m_newWindow = new QAction(tr("New Window"),m_mainwindow); actionContext->regAction(m_newWindow,"NewWindow","Ctrl+Shift+N"); m_closeWindow = new QAction(tr("Close Window"),m_mainwindow); actionContext->regAction(m_closeWindow,"CloseWindow","Ctrl+Shift+W"); m_closeAct = new QAction(loadIcon("icon:images/closefile.png"),tr("Close File"),m_mainwindow); actionContext->regAction(m_closeAct,"CloseFile","Ctrl+W"); m_closeAllAct = new QAction(tr("Close All Files"),m_mainwindow); actionContext->regAction(m_closeAllAct,"CloseAllFiles",""); m_openProjectAct = new QAction(loadIcon("icon:images/openproject.png"),tr("Open Project"),m_mainwindow); m_saveProjectAct = new QAction(loadIcon("icon:images/saveproject.png"),tr("Save Project"),m_mainwindow); m_closeProjectAct = new QAction(loadIcon("icon:images/closeproject.png"),tr("Close Project"),m_mainwindow); actionContext->regAction(m_closeProjectAct,"CloseProject",""); m_saveAct = new QAction(loadIcon("icon:images/save.png"),tr("Save File"),m_mainwindow); actionContext->regAction(m_saveAct,"SaveFile",QKeySequence::Save); m_saveAsAct = new QAction(tr("Save File As..."),m_mainwindow); actionContext->regAction(m_saveAsAct,"SaveFileAs",QKeySequence::SaveAs); m_saveAllAct = new QAction(loadIcon("icon:images/saveall.png"),tr("Save All Files"),m_mainwindow); actionContext->regAction(m_saveAllAct,"SaveAllFiles",""); m_exitAct = new QAction(tr("Exit"),m_mainwindow); #ifdef Q_OS_WIN actionContext->regAction(m_exitAct,"Exit","Ctrl+Q"); #else actionContext->regAction(m_exitAct,"Exit",QKeySequence::Quit); #endif m_fullScreent = new QAction(tr("Full Screen"),m_mainwindow); m_fullScreent->setCheckable(true); actionContext->regAction(m_fullScreent,"FullScreen","Ctrl+Shift+F11"); m_aboutAct = new QAction(tr("About LiteIDE"),m_mainwindow); #if defined(Q_OS_OSX) m_aboutAct->setMenuRole(QAction::AboutRole); #endif actionContext->regAction(m_aboutAct,"About",""); m_aboutPluginsAct = new QAction(tr("About Plugins"),m_mainwindow); #if defined(Q_OS_OSX) m_aboutPluginsAct->setMenuRole(QAction::ApplicationSpecificRole); #endif actionContext->regAction(m_aboutPluginsAct,"AboutPlugins",""); connect(m_newAct,SIGNAL(triggered()),m_fileManager,SLOT(newFile())); connect(m_openFileAct,SIGNAL(triggered()),m_fileManager,SLOT(openFiles())); connect(m_openFolderAct,SIGNAL(triggered()),m_fileManager,SLOT(openFolder())); connect(m_openFolderNewWindowAct,SIGNAL(triggered()),m_fileManager,SLOT(openFolderNewWindow())); connect(m_closeAllFolderAct,SIGNAL(triggered()),m_fileManager,SLOT(closeAllFolders())); connect(m_newWindow,SIGNAL(triggered()),this,SLOT(newWindow())); connect(m_closeWindow,SIGNAL(triggered()),this,SLOT(closeWindow())); connect(m_closeAct,SIGNAL(triggered()),m_editorManager,SLOT(closeEditor())); connect(m_closeAllAct,SIGNAL(triggered()),m_editorManager,SLOT(closeAllEditors())); connect(m_openProjectAct,SIGNAL(triggered()),m_fileManager,SLOT(openProjects())); connect(m_saveProjectAct,SIGNAL(triggered()),m_projectManager,SLOT(saveProject())); connect(m_closeProjectAct,SIGNAL(triggered()),m_projectManager,SLOT(closeProject())); connect(m_saveAct,SIGNAL(triggered()),m_editorManager,SLOT(saveEditor())); connect(m_saveAsAct,SIGNAL(triggered()),m_editorManager,SLOT(saveEditorAs())); connect(m_saveAllAct,SIGNAL(triggered()),m_editorManager,SLOT(saveAllEditors())); connect(m_exitAct,SIGNAL(triggered()),this,SLOT(exit())); connect(m_aboutAct,SIGNAL(triggered()),m_mainwindow,SLOT(about())); connect(m_aboutPluginsAct,SIGNAL(triggered()),this,SLOT(aboutPlugins())); connect(m_fullScreent,SIGNAL(toggled(bool)),m_mainwindow,SLOT(setFullScreen(bool))); } void LiteApp::createMenus() { m_fileMenu = m_actionManager->loadMenu(ID_MENU_FILE); m_viewMenu = m_actionManager->loadMenu(ID_MENU_VIEW); m_helpMenu = m_actionManager->loadMenu(ID_MENU_HELP); m_fileMenu->addAction(m_newAct); m_fileMenu->addAction(m_openFileAct); m_fileMenu->addAction(m_openFolderAct); m_fileMenu->addAction(m_openFolderNewWindowAct); m_fileMenu->addSeparator(); m_fileMenu->addAction(m_saveAct); m_fileMenu->addAction(m_saveAsAct); m_fileMenu->addAction(m_saveAllAct); m_fileMenu->addSeparator(); m_fileMenu->addAction(m_newWindow); m_fileMenu->addAction(m_closeWindow); m_fileMenu->addSeparator(); m_fileMenu->addAction(m_closeAct); m_fileMenu->addAction(m_closeAllAct); m_fileMenu->addAction(m_closeAllFolderAct); //m_fileMenu->addAction(m_closeProjectAct); //m_fileMenu->addAction(m_openProjectAct); //m_fileMenu->addAction(m_saveProjectAct); m_fileMenu->addSeparator(); m_fileMenu->addAction(m_exitAct); #ifdef Q_OS_MAC if (MacSupport::isLionOrHigh()) { MacSupport::setFullScreen(m_mainwindow); } else { m_viewMenu->addAction(m_fullScreent); } #else m_viewMenu->addAction(m_fullScreent); #endif m_viewMenu->addSeparator(); m_helpMenu->addAction(m_aboutAct); m_helpMenu->addAction(m_aboutPluginsAct); } void LiteApp::createToolBars() { m_stdToolBar = m_actionManager->loadToolBar(ID_TOOLBAR_STD); m_stdToolBar->addAction(m_newAct); m_stdToolBar->addSeparator(); m_stdToolBar->addAction(m_openFileAct); m_stdToolBar->addAction(m_openFolderAct); m_stdToolBar->addAction(m_saveAct); m_stdToolBar->addAction(m_saveAllAct); //m_stdToolBar->addSeparator(); //m_stdToolBar->addAction(m_openProjectAct); //m_stdToolBar->addAction(m_saveProjectAct); //m_stdToolBar->addAction(m_closeProjectAct); } void LiteApp::projectReloaded() { LiteApi::IProject *project = (LiteApi::IProject*)sender(); if (project) { //m_outputManager->setProjectInfo(project->filePath()); } } void LiteApp::currentProjectChanged(IProject *project) { bool b = (project != 0); m_saveProjectAct->setEnabled(b); m_closeProjectAct->setEnabled(b); if (project) { //m_outputManager->setProjectInfo(project->filePath()); connect(project,SIGNAL(reloaded()),this,SLOT(projectReloaded())); } else { //m_outputManager->setProjectInfo(""); } } void LiteApp::currentEditorChanged(IEditor *editor) { bool b = (editor != 0); if (b) { connect(editor,SIGNAL(modificationChanged(bool)),this,SLOT(editorModifyChanged(bool))); } m_saveAct->setEnabled(b && editor->isModified() && !editor->isReadOnly()); m_saveAsAct->setEnabled(editor && !editor->filePath().isEmpty()); m_saveAllAct->setEnabled(b); m_closeAct->setEnabled(b); m_closeAllAct->setEnabled(b); } void LiteApp::editorModifyChanged(bool /*b*/) { IEditor *editor = (IEditor*)sender(); if (editor && editor->isModified() && !editor->isReadOnly()) { m_saveAct->setEnabled(true); } else { m_saveAct->setEnabled(false); } } void LiteApp::loadState() { QByteArray geometry = m_settings->value("liteapp/geometry").toByteArray(); if (!geometry.isEmpty()) { m_mainwindow->restoreGeometry(geometry); } else { m_mainwindow->resize(800,600); } m_mainwindow->updateConer(); //fix Qt 5.9.6 QDockWidget bug #if QT_VERSION == 0x050906 QList<QDockWidget *> docks = m_mainwindow->findChildren<QDockWidget *>(); QList<int> horz; QList<int> vert; QList<QDockWidget*> ds; foreach (QDockWidget *dock, docks) { bool b = m_settings->value("dock_visible/"+dock->objectName()).toBool(); if (!b) { continue; } dock->setVisible(b); QSize sz = m_settings->value("dock_size/"+dock->objectName()).toSize(); horz << sz.width(); vert << sz.height(); ds << dock; } m_mainwindow->resizeDocks(ds,horz,Qt::Horizontal); m_mainwindow->resizeDocks(ds,vert,Qt::Vertical); foreach (QString id, m_actionManager->toolBarList()) { QToolBar *tbar = m_actionManager->loadToolBar(id); bool b = m_settings->value("toolbar_visible/"+tbar->objectName(),true).toBool(); tbar->setVisible(b); } #else m_mainwindow->restoreState(m_settings->value("liteapp/state").toByteArray()); #endif } void LiteApp::saveState() { m_settings->setValue("liteapp/geometry",m_mainwindow->saveGeometry()); m_settings->setValue("liteapp/state",m_mainwindow->saveState()); //fix Qt 5.9.6 QDockWidget bug #if QT_VERSION == 0x050906 QList<QDockWidget *> docks = m_mainwindow->findChildren<QDockWidget *>(); foreach (QDockWidget *dock, docks) { m_settings->setValue("dock_size/"+dock->objectName(),dock->size()); m_settings->setValue("dock_visible/"+dock->objectName(),dock->isVisible()); } foreach (QString id, m_actionManager->toolBarList()) { QToolBar *tbar = m_actionManager->loadToolBar(id); m_settings->setValue("toolbar_visible/"+tbar->objectName(),tbar->isVisible()); } #endif } void LiteApp::loadSession(const QString &session) { if (session.isEmpty()) { return; } m_recentManager->addRecent(session,"session"); QString sessionKey = "session/"+session; QString projectName = m_settings->value(sessionKey+"_project").toString(); QString scheme = m_settings->value(sessionKey+"_scheme").toString(); QString editorName = m_settings->value(sessionKey+"_cureditor").toString(); QStringList fileList = m_settings->value(sessionKey+"_alleditor").toStringList(); QStringList folderList = m_settings->value(sessionKey+"_folderList").toStringList(); m_fileManager->setFolderList(folderList); if (!projectName.isEmpty()) { if (scheme.isEmpty()) { m_fileManager->openProject(projectName); } else { m_fileManager->openProjectScheme(projectName,scheme); } } else { m_projectManager->closeProject(); } if (m_settings->value(LITEAPP_STARTUPRELOADFILES,true).toBool()) { foreach(QString fileName, fileList) { m_fileManager->openEditor(fileName,false); } if (!editorName.isEmpty()) { m_fileManager->openEditor(editorName,true); } else if (!fileList.isEmpty()){ m_fileManager->openEditor(fileList.last(),true); } } emit sessionListChanged(); } void LiteApp::saveSession(const QString &session) { if (session.isEmpty() || session == "empty") { return; } QString projectName; QString editorName; QString scheme; IProject *project = m_projectManager->currentProject(); if (project) { projectName = project->filePath(); IMimeType *type = m_mimeTypeManager->findMimeType(project->mimeType()); if (type) { scheme = type->scheme(); } } QStringList fileList; foreach (IEditor* ed,m_editorManager->sortedEditorList()) { if (ed->filePath().isEmpty()) { continue; } if (ed == m_editorManager->currentEditor()) { editorName = ed->filePath(); } else { fileList.append(ed->filePath()); } } QString sessionKey = "session/"+session; LiteApi::updateSetting(m_settings,sessionKey+"_project",projectName,""); LiteApi::updateSetting(m_settings,sessionKey+"_scheme",scheme,""); LiteApi::updateSetting(m_settings,sessionKey+"_cureditor",editorName,""); LiteApi::updateSetting(m_settings,sessionKey+"_alleditor",fileList,QStringList()); LiteApi::updateSetting(m_settings,sessionKey+"_folderList",m_fileManager->folderList(),QStringList()); } QStringList LiteApp::sessionList() const { return m_recentManager->recentNameList("session"); } QString LiteApp::currentSession() const { return m_currentSession; } void LiteApp::dbclickLogOutput(QTextCursor cur) { //QRegExp rep("(\\w?:?[\\w\\d_@\\-\\\\/\\.]+):(\\d+):"); QString text = cur.block().text().trimmed(); //skip time 08:38:49 if (text.length() < 9) { return; } QRegExp rep("(\\w?\\:?[\\w\\d\\_\\-\\\\/\\.]+):(\\d+):"); int index = rep.indexIn(text.mid(8)); 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_fileManager->openEditor(fileName); if (editor) { LiteApi::ITextEditor *textEditor = LiteApi::getTextEditor(editor); if (textEditor) { textEditor->gotoLine(line-1,0,true); } } } void LiteApp::goproxyDone(const QByteArray &reply) { this->appendLog("GoProxy",QString("%1 = %2").arg(QString::fromUtf8(m_goProxy->commandId())).arg(QString::fromUtf8(reply).trimmed())); }
34,585
C++
.cpp
942
32.138004
144
0.699525
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,564
actionmanager.cpp
visualfc_liteide/liteidex/src/liteapp/actionmanager.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: actionmanager.cpp // Creator: visualfc <visualfc@gmail.com> #include "actionmanager.h" #include "liteapp_global.h" #include "liteapi/liteids.h" #include <QMenuBar> #include <QToolBar> #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 ActionManager::ActionManager(QObject *parent) : IActionManager(parent), m_viewMenu(0), m_baseToolBarAct(0), m_baseBrowserAct(0) { } ActionManager::~ActionManager() { QMapIterator<QObject*,IActionContext*> it(m_objContextMap); while(it.hasNext()) { it.next(); delete it.value(); } } bool ActionManager::initWithApp(IApplication *app) { if (!IActionManager::initWithApp(app)) { return false; } insertMenu(ID_MENU_FILE,tr("&File")); insertMenu(ID_MENU_RECENT,tr("&Recent")); insertMenu(ID_MENU_EDIT,tr("&Edit")); insertMenu(ID_MENU_FIND,tr("F&ind")); m_viewMenu = insertMenu(ID_MENU_VIEW,tr("&View")); m_viewMenu->addSeparator(); m_baseToolBarAct = m_viewMenu->addSeparator(); m_baseBrowserAct = m_viewMenu->addSeparator(); m_viewMenu->addSeparator(); insertMenu(ID_MENU_TOOLS,tr("&Tools")); insertMenu(ID_MENU_BUILD,tr("&Build")); insertMenu(ID_MENU_DEBUG,tr("&Debug")); insertMenu(ID_MENU_HELP,tr("&Help")); QToolBar *stdToolBar = insertToolBar(ID_TOOLBAR_STD,tr("Standard Toolbar")); insertViewMenu(LiteApi::ViewMenuToolBarPos,stdToolBar->toggleViewAction()); return true; } QMenu *ActionManager::insertMenu(const QString &id, const QString &title, const QString &idBefore) { QMenu *menu = m_idMenuMap.value(id); if (menu) { return menu; } menu = new QMenu(title,m_liteApp->mainWindow()); menu->setObjectName(id); QMenu *m = 0; if (!idBefore.isEmpty()) { m = m_idMenuMap.value(idBefore); } if (m) { m_liteApp->mainWindow()->menuBar()->insertMenu(m->menuAction(),menu); } else { m_liteApp->mainWindow()->menuBar()->addAction(menu->menuAction()); } m_idMenuMap.insert(id,menu); return menu; } void ActionManager::removeMenu(QMenu *menu) { if (!menu) { return; } QString id = m_idMenuMap.key(menu); if (!id.isEmpty()) { m_idMenuMap.remove(id); } m_liteApp->mainWindow()->menuBar()->removeAction(menu->menuAction()); } QList<QString> ActionManager::menuList() const { return m_idMenuMap.keys(); } QMenu *ActionManager::loadMenu(const QString &id) { return m_idMenuMap.value(id); } QToolBar *ActionManager::insertToolBar(const QString &id, const QString &title, const QString &idBefore) { QToolBar *toolBar = m_idToolBarMap.value(id); if (toolBar) { return toolBar; } toolBar = new QToolBar(title, m_liteApp->mainWindow()); toolBar->setObjectName(id); toolBar->setIconSize(LiteApi::getToolBarIconSize(m_liteApp)); QToolBar *m = 0; if (!idBefore.isEmpty()) { m = m_idToolBarMap.value(idBefore); } if (m) { m_liteApp->mainWindow()->insertToolBar(m,toolBar); } else { m_liteApp->mainWindow()->addToolBar(toolBar); } m_idToolBarMap.insert(id,toolBar); return toolBar; } void ActionManager::insertToolBar(QToolBar *toolBar, const QString &idBefore) { QString id = toolBar->objectName(); toolBar->setIconSize(LiteApi::getToolBarIconSize(m_liteApp)); QToolBar *m = 0; if (!idBefore.isEmpty()) { m = m_idToolBarMap.value(idBefore); } if (m) { m_liteApp->mainWindow()->insertToolBar(m,toolBar); } else { m_liteApp->mainWindow()->addToolBar(toolBar); } m_idToolBarMap.insert(id,toolBar); } QToolBar *ActionManager::loadToolBar(const QString &id) { return m_idToolBarMap.value(id); } QList<QString> ActionManager::toolBarList() const { return m_idToolBarMap.keys(); } void ActionManager::removeToolBar(QToolBar* toolBar) { if (!toolBar) { return; } QString id = m_idToolBarMap.key(toolBar); if (!id.isEmpty()) { m_idToolBarMap.remove(id); } m_liteApp->mainWindow()->removeToolBar(toolBar); } void ActionManager::insertViewMenu(VIEWMENU_ACTION_POS pos, QAction *act) { if (pos == ViewMenuToolBarPos) { m_viewMenu->insertAction(m_baseToolBarAct,act); } else if(pos == ViewMenuBrowserPos){ m_viewMenu->insertAction(m_baseBrowserAct,act); } else { m_viewMenu->addAction(act); } } void ActionManager::setViewMenuSeparator(const QString &sepid, bool group) { if (sepid.isEmpty()) { return; } if (m_idSeperatorMap.contains(sepid)) { return; } if (group) { m_viewMenu->addSeparator(); } QAction *sep = m_viewMenu->addSeparator(); m_idSeperatorMap.insert(sepid,sep); } bool ActionManager::insertMenuActions(const QString &idMenu, const QString &idBeforeSep, bool newGroup, QList<QAction*> &actions) { if (idMenu.isEmpty()) { return false; } QMenu *menu = loadMenu(idMenu); if (!menu) { return false; } if (newGroup) { QMenu *realMenu = menu->menuAction()->menu(); if (realMenu) { if (!realMenu->actions().isEmpty() && !realMenu->actions().last()->isSeparator()) { menu->addSeparator(); } } else { menu->addSeparator(); } } QAction *sep = 0; if (!idBeforeSep.isEmpty()) { sep = m_idMenuSepMap[idMenu][idBeforeSep]; if (!sep) { sep = menu->addSeparator(); m_idMenuSepMap[idMenu].insert(idBeforeSep,sep); } } foreach (QAction *act, actions) { menu->insertAction(sep,act); } return true; } void ActionManager::insertViewMenuAction(QAction *act, const QString &sepid) { QAction *sep = m_idSeperatorMap[sepid]; m_viewMenu->insertAction(sep,act); } IActionContext *ActionManager::getActionContext(QObject *obj, const QString &name) { IActionContext *context = m_objContextMap.value(obj); if (!context) { context = new ActionContext(m_liteApp,name); connect(obj,SIGNAL(destroyed(QObject*)),this,SLOT(removeActionContext(QObject*))); m_objContextMap.insert(obj,context); } return context; } QStringList ActionManager::actionKeys() const { QStringList keys; QMapIterator<QObject*,IActionContext*> it(m_objContextMap); while(it.hasNext()) { it.next(); keys.append(it.value()->actionKeys()); } keys.removeDuplicates(); return keys; } ActionInfo *ActionManager::actionInfo(const QString &id) const { QMapIterator<QObject*,IActionContext*> it(m_objContextMap); while (it.hasNext()) { it.next(); ActionInfo *info = it.value()->actionInfo(id); if (info) { return info; } } return 0; } QList<QKeySequence> ActionManager::toShortcuts(const QString &ks) { QString keyseq = ks; QString part; int p = 0, diff = 0; QList<QKeySequence> keys; while (keyseq.length()) { // We MUST use something to separate each sequence, and space // does not cut it, since some of the key names have space // in them.. (Let's hope no one translate with a comma in it:) p = keyseq.indexOf(QLatin1Char(';')); if (-1 != p) { if (p == keyseq.count() - 1) { // Last comma 'Ctrl+;' p = -1; } else { if (QLatin1Char(';') == keyseq.at(p+1)) // e.g. 'Ctrl+;; Shift+;;' p++; if (QLatin1Char(' ') == keyseq.at(p+1)) { // Space after comma diff = 1; p++; } else { diff = 0; } } } part = keyseq.left(-1 == p ? keyseq.length() : p - diff); keyseq = keyseq.right(-1 == p ? 0 : keyseq.length() - (p + 1)); QKeySequence key(part); if (!key.isEmpty()) { keys.append(key); } } return keys; } QString ActionManager::formatShortcutsString(const QString &ks) { QStringList ksList; foreach(QKeySequence k, toShortcuts(ks)) { ksList.append(k.toString()); } return ksList.join("; "); } QString ActionManager::formatShortcutsNativeString(const QString &ks) { QStringList ksList; foreach(QKeySequence k, toShortcuts(ks)) { ksList.append(k.toString(QKeySequence::NativeText)); } return ksList.join("; "); } void ActionManager::setActionShourtcuts(const QString &id, const QString &shortcuts) { QMapIterator<QObject*,IActionContext*> it(m_objContextMap); while(it.hasNext()) { it.next(); it.value()->setActionShortcuts(id,shortcuts); } } QStringList ActionManager::actionContextNameList() const { QStringList nameList; QMapIterator<QObject*,IActionContext*> it(m_objContextMap); while(it.hasNext()) { it.next(); nameList.append(it.value()->contextName()); } nameList.removeDuplicates(); return nameList; } IActionContext *ActionManager::actionContextForName(const QString &name) { QMapIterator<QObject*,IActionContext*> it(m_objContextMap); while(it.hasNext()) { it.next(); if (it.value()->contextName().compare(name,Qt::CaseInsensitive) == 0) { return it.value(); } } return 0; } void ActionManager::removeActionContext(QObject *obj) { QMutableMapIterator<QObject*,IActionContext*> it(m_objContextMap); while (it.hasNext()) { it.next(); if (it.key() == obj) { delete it.value(); it.remove(); break; } } } ActionContext::ActionContext(IApplication *app, const QString &name) : m_liteApp(app), m_name(name) { } QString ActionContext::contextName() const { return m_name; } ActionContext::~ActionContext() { QMapIterator<QString,ActionInfo*> it(m_actionInfoMap); while(it.hasNext()) { it.next(); ActionInfo* info = it.value(); delete info; } m_actionInfoMap.clear(); } void ActionContext::regAction(QAction *act, const QString &id, const QString &defks, bool standard) { ActionInfo *info = m_actionInfoMap.value(id); if (info == 0) { info = new ActionInfo; m_actionInfoMap.insert(id,info); } info->standard = standard; info->defks = ActionManager::formatShortcutsString(defks); info->ks = m_liteApp->settings()->value(LITEAPP_SHORTCUTS+id,info->defks).toString(); info->ks = ActionManager::formatShortcutsString(info->ks); info->keys = ActionManager::toShortcuts(info->ks); if (act) { info->label = act->text(); act->setShortcuts(info->keys); act->setData(id); if (!info->ks.isEmpty()) { act->setToolTip(QString("%1 (%2)").arg(act->text()).arg(ActionManager::formatShortcutsNativeString(info->ks))); } info->action = act; } else { info->action = 0; } } void ActionContext::regAction(QAction *act, const QString &id, const QKeySequence::StandardKey &def) { regAction(act,id,QKeySequence(def).toString(),true); } QStringList ActionContext::actionKeys() const { return m_actionInfoMap.keys(); } ActionInfo *ActionContext::actionInfo(const QString &id) const { return m_actionInfoMap.value(id); } void ActionContext::setActionShortcuts(const QString &id, const QString &shortcuts) { ActionInfo *info = m_actionInfoMap.value(id); if (!info) { return; } info->ks = ActionManager::formatShortcutsString(shortcuts); info->keys = ActionManager::toShortcuts(info->ks); if (info->action) { info->action->setShortcuts(info->keys); if (!info->ks.isEmpty()) { info->action->setToolTip(QString("%1 (%2)").arg(info->action->text()).arg(ActionManager::formatShortcutsNativeString(info->ks))); } } if (info->ks != info->defks) { m_liteApp->settings()->setValue(LITEAPP_SHORTCUTS+id,info->ks); } else { m_liteApp->settings()->remove(LITEAPP_SHORTCUTS+id); } }
13,380
C++
.cpp
429
25.920746
141
0.640682
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,565
projectmanager.cpp
visualfc_liteide/liteidex/src/liteapp/projectmanager.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: projectmanager.cpp // Creator: visualfc <visualfc@gmail.com> #include "projectmanager.h" #include "liteapp_global.h" #include <QFileInfo> #include <QComboBox> #include <QVBoxLayout> #include <QHBoxLayout> #include <QPushButton> #include <QStackedWidget> #include <QStandardItemModel> #include <QStandardItem> #include <QStackedLayout> #include <QMenu> #include <QActionGroup> #include <QFileDialog> #include <QDebug> #include <QScrollArea> #include <QTabWidget> #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 ProjectManager::ProjectManager() : m_widget(0), m_folderProject(0) { } ProjectManager::~ProjectManager() { if (m_folderProject) { delete m_folderProject; } if (m_widget) { m_liteApp->toolWindowManager()->removeToolWindow(m_widget); delete m_widget; } } bool ProjectManager::initWithApp(IApplication *app) { if (!IProjectManager::initWithApp(app)) { return false; } m_widget = new QScrollArea; m_widget->setFrameShape(QFrame::NoFrame); m_widget->setWidgetResizable(true); m_folderProject = new FolderProject(m_liteApp); //m_toolWindowAct = m_liteApp->toolWindowManager()->addToolWindow(Qt::LeftDockWidgetArea,m_widget,"projects",tr("Projects"),false); connect(m_liteApp,SIGNAL(loaded()),this,SLOT(appLoaded())); m_bAutoCloseProjectEditors = m_liteApp->settings()->value(LITEAPP_AUTOCLOSEPROEJCTFILES,true).toBool(); return true; } void ProjectManager::appLoaded() { foreach (IProjectFactory *factory, this->m_factoryList) { foreach(QString type, factory->mimeTypes()) { IMimeType *mimeType = m_liteApp->mimeTypeManager()->findMimeType(type); if (mimeType && !mimeType->scheme().isEmpty()) { QAction *act = new QAction(QString(tr("Project <%1>").arg(mimeType->scheme())),this); act->setData(mimeType->scheme()); connect(act,SIGNAL(triggered()),this,SLOT(openSchemeAct())); //m_importMenu->addAction(act); } } } } QWidget *ProjectManager::widget() { return m_widget; } void ProjectManager::triggeredProject(QAction* act) { QString fileName = act->text(); m_liteApp->fileManager()->openProject(fileName); } void ProjectManager::openSchemeDialog(const QString &scheme) { static QString last = QDir::homePath(); QString dir = QFileDialog::getExistingDirectory(m_liteApp->mainWindow(), QString(tr("Import Directory <%1>").arg(scheme)), last, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if (dir.isEmpty()) { return; } last = dir; m_liteApp->fileManager()->openProjectScheme(dir,scheme); } void ProjectManager::openSchemeAct() { QAction *act = (QAction*)sender(); if (!act) { return; } QString scheme = act->data().toString(); if (scheme.isEmpty()) { return; } openSchemeDialog(scheme); } void ProjectManager::currentEditorChanged(LiteApi::IEditor* editor) { if (!editor) { return; } // QString fileName = editor->fileName(); // IProject *project = 0; // foreach (IProjectFactory *factory , m_factoryList) { // project = factory->findByEditor(editor); // if (project) { // break; // } // } // if (project) { // QAction *act = m_mapNameToAction.value(fileName); // if (act == 0) { // act = m_projectActGroup->addAction(fileName); // act->setCheckable(true); // m_mapNameToAction.insert(fileName,act); // m_projectMenu->addAction(act); // } // setCurrentProject(project); // } } IFolderProject *ProjectManager::openFolder(const QString &folderPath) { m_folderProject->openFolder(folderPath); setCurrentProject(m_folderProject); return m_folderProject; } IProject *ProjectManager::openProject(const QString &fileName, const QString &mimeType) { if (m_currentProject && m_currentProject->filePath() == fileName) { return m_currentProject; } IProject *project = 0; foreach (IProjectFactory *factory , m_factoryList) { if (factory->mimeTypes().contains(mimeType)) { project = factory->open(fileName,mimeType); if (project) { break; } } } if (project) { setCurrentProject(project); } return project; } void ProjectManager::addFactory(IProjectFactory *factory) { m_factoryList.append(factory); } void ProjectManager::removeFactory(IProjectFactory *factory) { m_factoryList.removeOne(factory); } QList<IProjectFactory*> ProjectManager::factoryList() const { return m_factoryList; } QStringList ProjectManager::mimeTypeList() const { QStringList types; foreach(IProjectFactory *factory, m_factoryList) { types.append(factory->mimeTypes()); } return types; } void ProjectManager::setCurrentProject(IProject *project) { if (m_currentProject) { closeProjectHelper(m_currentProject); } m_currentProject = project; if (m_currentProject) { //m_toolWindowAct->setChecked(true); m_widget->setWidget(m_currentProject->widget()); m_currentProject->load(); m_liteApp->appendLog("ProjectManager","Loaded project "+m_currentProject->name()); } emit currentProjectChanged(project); } IProject *ProjectManager::currentProject() const { return m_currentProject; } QList<IEditor*> ProjectManager::editorList(IProject *project) const { QList<IEditor*> editors; if (project) { foreach (QString fileName, project->filePathList()) { foreach(IEditor *editor, m_liteApp->editorManager()->editorList()) { if (FileUtil::compareFile(editor->filePath(),fileName)) { editors << editor; break; } } } } return editors; } void ProjectManager::addImportAction(QAction*) { //m_importMenu->addAction(act); } void ProjectManager::saveProject(IProject *project) { IProject *cur = 0; if (project == 0) { cur = m_currentProject; } else { cur = project; } if (cur == 0) { return; } foreach (IEditor *editor, editorList(cur)) { if (editor->isModified()) { m_liteApp->editorManager()->saveEditor(editor); } } } void ProjectManager::closeProjectHelper(IProject *project) { IProject *cur = 0; if (project) { cur = project; } else { cur = m_currentProject; } if (cur == 0) { return; } //m_widget->clear(); emit projectAboutToClose(cur); m_widget->takeWidget(); if (m_bAutoCloseProjectEditors) { foreach (IEditor *editor, editorList(cur)) { m_liteApp->editorManager()->closeEditor(editor); } } m_liteApp->appendLog("ProjectManager","Closed project "+cur->name()); if (cur != m_folderProject) { delete cur; } else if (cur && (cur == m_currentProject) ){ m_currentProject = 0; } } void ProjectManager::closeProject(IProject *project) { //m_toolWindowAct->setChecked(false); closeProjectHelper(project); emit currentProjectChanged(0); } void ProjectManager::applyOption(QString id) { if (id != OPTION_LITEAPP) { return; } m_bAutoCloseProjectEditors = m_liteApp->settings()->value(LITEAPP_AUTOCLOSEPROEJCTFILES,true).toBool(); }
8,976
C++
.cpp
288
26.003472
135
0.641974
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,566
splitwindowstyle.cpp
visualfc_liteide/liteidex/src/liteapp/splitwindowstyle.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: splitwindowstyle.cpp // Creator: visualfc <visualfc@gmail.com> #include "splitwindowstyle.h" #include "rotationtoolbutton.h" #include "tooldockwidget.h" #include "liteapp_global.h" #include "liteapi/liteids.h" #include <QToolBar> #include <QAction> #include <QActionGroup> #include <QStatusBar> #include <QLabel> #include <QDockWidget> #include <QStatusBar> #include <QKeySequence> #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 ActionGroup::ActionGroup(QObject *parent) : QObject(parent) { current = 0; } QList<QAction *> ActionGroup::actions() const { return m_actions; } void ActionGroup::addAction(QAction *action) { if(!m_actions.contains(action)) { m_actions.append(action); QObject::connect(action, SIGNAL(changed()), this, SLOT(actionChanged())); } if (current && current->isChecked()) { current->setChecked(false); } if (action->isChecked()) { current = action; } } void ActionGroup::removeAction(QAction *action) { if (m_actions.removeAll(action)) { if (action == current) current = 0; QObject::disconnect(action, SIGNAL(changed()), this, SLOT(actionChanged())); } } QAction * ActionGroup::checkedAction () const { return current; } void ActionGroup::actionChanged() { QAction *action = qobject_cast<QAction*>(sender()); Q_ASSERT_X(action != 0, "ActionGroup::actionChanged", "internal error"); if (action->isChecked()) { if (action != current) { if(current) current->setChecked(false); current = action; } } else if (action == current) { current = 0; } } SplitActionToolBar::SplitActionToolBar(QSize iconSize, QWidget *parent, Qt::DockWidgetArea _area) : QObject(parent), area(_area), bHideToolBar(false) { toolBar = new QToolBar; toolBar->hide(); toolBar->setObjectName(QString("tool_%1").arg(area)); toolBar->setMovable(false); QWidget *spacer = new QWidget; spacer->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); spacerAct = toolBar->addWidget(spacer); toolBar->addSeparator(); QWidget *spacer2 = new QWidget; spacer2->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); toolBar->addWidget(spacer2); dock1 = new SplitDockWidget(iconSize, parent); dock1->setObjectName(QString("dock_%1").arg(area)); dock1->setWindowTitle(QString("dock_%1").arg(area)); dock1->setFeatures(QDockWidget::DockWidgetClosable); dock1->hide(); dock1->createMenu(area,false); dock2 = new SplitDockWidget(iconSize,parent); dock2->setObjectName(QString("dock_%1_split").arg(area)); dock2->setWindowTitle(QString("dock_%1_split").arg(area)); dock2->setFeatures(QDockWidget::DockWidgetClosable); dock2->hide(); dock2->createMenu(area,true); connect(dock1,SIGNAL(visibilityChanged(bool)),this,SLOT(dock1Visible(bool))); connect(dock2,SIGNAL(visibilityChanged(bool)),this,SLOT(dock2Visible(bool))); connect(dock1,SIGNAL(moveActionTo(Qt::DockWidgetArea,Qt::DockWidgetArea,QAction*,bool)),this,SIGNAL(moveActionTo(Qt::DockWidgetArea,Qt::DockWidgetArea,QAction*,bool))); connect(dock2,SIGNAL(moveActionTo(Qt::DockWidgetArea,Qt::DockWidgetArea,QAction*,bool)),this,SIGNAL(moveActionTo(Qt::DockWidgetArea,Qt::DockWidgetArea,QAction*,bool))); } SplitDockWidget *SplitActionToolBar::dock(bool split) const { return split?dock2:dock1; } void SplitActionToolBar::addAction(QAction *action, const QString &title, bool split) { RotationToolButton *btn = new RotationToolButton; btn->setDefaultAction(action); if (area == Qt::LeftDockWidgetArea) { btn->setRotation(RotationToolButton::CounterClockwise); } else if (area == Qt::RightDockWidgetArea) { btn->setRotation(RotationToolButton::Clockwise); } m_actionWidgetMap.insert(action,btn); if (split) { dock2->addAction(action,title); toolBar->addWidget(btn); } else { dock1->addAction(action,title); toolBar->insertWidget(spacerAct,btn); } if (toolBar->isHidden() && !bHideToolBar) { toolBar->show(); } } void SplitActionToolBar::removeAction(QAction *action, bool split) { QWidget *widget = m_actionWidgetMap.value(action); if (widget) { delete widget; } m_actionWidgetMap.remove(action); if (split) { dock2->removeAction(action); } else { dock1->removeAction(action); } if (dock1->actions().isEmpty() && dock2->actions().isEmpty()) { toolBar->hide(); } } void SplitActionToolBar::setHideToolBar(bool b) { bHideToolBar = b; if (bHideToolBar) { toolBar->hide(); } else { if (!dock1->actions().isEmpty() || !dock2->actions().isEmpty()){ toolBar->show(); } } } void SplitActionToolBar::dock1Visible(bool b) { QAction *action = dock1->checkedAction(); if (action) { action->setChecked(dock1->isVisible()); } else if (b && !dock1->actions().isEmpty()) { dock1->actions().first()->setChecked(true); } } void SplitActionToolBar::dock2Visible(bool b) { QAction *action = dock2->checkedAction(); if (action) { action->setChecked(dock2->isVisible()); } else if (b && !dock2->actions().isEmpty()) { dock2->actions().first()->setChecked(true); } } SplitWindowStyle::SplitWindowStyle(LiteApi::IApplication *app, QMainWindow *window, QObject *parent) : IWindowStyle(parent), m_liteApp(app), m_mainWindow(window) { QSize iconSize = LiteApi::getToolBarIconSize(app); m_areaToolBar.insert(Qt::TopDockWidgetArea,new SplitActionToolBar(iconSize, m_mainWindow,Qt::TopDockWidgetArea)); m_areaToolBar.insert(Qt::BottomDockWidgetArea,new SplitActionToolBar(iconSize, m_mainWindow,Qt::BottomDockWidgetArea)); m_areaToolBar.insert(Qt::LeftDockWidgetArea,new SplitActionToolBar(iconSize, m_mainWindow,Qt::LeftDockWidgetArea)); m_areaToolBar.insert(Qt::RightDockWidgetArea,new SplitActionToolBar(iconSize, m_mainWindow,Qt::RightDockWidgetArea)); QMapIterator<Qt::DockWidgetArea,SplitActionToolBar*> it(m_areaToolBar); while(it.hasNext()) { it.next(); Qt::DockWidgetArea area = it.key(); SplitActionToolBar *actionToolBar = it.value(); m_mainWindow->addToolBar((Qt::ToolBarArea)area,actionToolBar->toolBar); m_mainWindow->addDockWidget(area,actionToolBar->dock1); m_mainWindow->addDockWidget(area,actionToolBar->dock2); if (area == Qt::TopDockWidgetArea || area == Qt::BottomDockWidgetArea) m_mainWindow->splitDockWidget(actionToolBar->dock1,actionToolBar->dock2,Qt::Horizontal); else m_mainWindow->splitDockWidget(actionToolBar->dock1,actionToolBar->dock2,Qt::Vertical); connect(actionToolBar,SIGNAL(moveActionTo(Qt::DockWidgetArea, Qt::DockWidgetArea,QAction*,bool)),this,SLOT(moveToolWindow(Qt::DockWidgetArea, Qt::DockWidgetArea,QAction*,bool))); } m_mainWindow->setDockNestingEnabled(true); m_mainWindow->setDockOptions(QMainWindow::AllowNestedDocks); m_statusBar = new QStatusBar; m_hideSideAct = new QAction(tr("Hide Sidebars"),this); m_hideSideAct->setIcon(QIcon("icon:images/hidesidebar.png")); m_hideSideAct->setCheckable(true); QToolButton *btn = new QToolButton; btn->setDefaultAction(m_hideSideAct); btn->setStyleSheet("QToolButton {border:0}" "QToolButton:checked {background : qlineargradient(spread:pad, x1:0, y1:1, x2:1, y2:0, stop:0 rgba(55, 57, 59, 255), stop:1 rgba(255, 255, 255, 255));}"); m_statusBar->addWidget(btn); m_statusBar->setContentsMargins(0,0,0,0); SplitActionToolBar *bar = m_areaToolBar.value(Qt::BottomDockWidgetArea); if (bar) { m_statusBar->addWidget(bar->toolBar,1); } m_mainWindow->setStatusBar(m_statusBar); m_windowMenu = 0; connect(m_hideSideAct,SIGNAL(toggled(bool)),this,SLOT(hideSideBar(bool))); m_useShortcuts = m_liteApp->settings()->value(LITEAPP_TOOLWINDOW_SHORTCUTS,true).toBool(); } SplitWindowStyle::~SplitWindowStyle() { qDeleteAll(m_actStateMap); } void SplitWindowStyle::createToolWindowMenu() { QMenu *menu = m_liteApp->actionManager()->loadMenu(ID_MENU_VIEW); if (menu) { m_windowMenu = menu->addMenu(tr("Tool Windows")); } } void SplitWindowStyle::toggledAction(bool) { QAction *action = static_cast<QAction*>(sender()); if (!action) { return; } SplitActionState *state = m_actStateMap.value(action); if (!state) { return; } SplitDockWidget *dock = m_areaToolBar.value(state->area)->dock(state->split); if (action->isChecked()) { if (dock->isHidden()) { dock->show(); } dock->setWidget(state->widget); if (!state->widgetList.isEmpty()) { dock->setWidgetList(state->widgetList); } else { dock->setWidgetActions(state->widgetActions); } dock->setWindowTitle(state->title); state->widget->setVisible(true); } else { if (!dock->checkedAction()) { dock->hide(); state->widget->setVisible(false); } } } QAction *SplitWindowStyle::findToolWindow(QWidget *widget) { QMapIterator<QAction*,SplitActionState*> it(m_actStateMap); while (it.hasNext()) { it.next(); if (it.value()->widget == widget) { return it.key(); } } return NULL; } void SplitWindowStyle::removeToolWindow(QAction *action) { SplitActionState *state = m_actStateMap.value(action); if (!state) { return; } if (action->isChecked()) { action->setChecked(false); } SplitActionToolBar *actToolBar = m_areaToolBar.value(state->area); if (actToolBar) { actToolBar->removeAction(action,state->split); } } QAction *SplitWindowStyle::addToolWindow(LiteApi::IApplication *app,Qt::DockWidgetArea area, QWidget *widget, const QString &id, const QString &title, bool split, QList<QAction*> widgetActions, QList<QWidget*> widgetList) { // QMap<QString,SplitInitToolSate>::iterator it = m_initIdStateMap.find(id); // if (it != m_initIdStateMap.end()) { // area = it.value().area; // split = it.value().split; // } area = (Qt::DockWidgetArea)m_liteApp->settings()->value("split_area/"+id,area).toInt(); split = m_liteApp->settings()->value("split_split/"+id,split).toBool(); SplitActionToolBar *actToolBar = m_areaToolBar.value(area); QAction *action = new QAction(this); action->setText(title); action->setCheckable(true); action->setObjectName(id); SplitActionState *state = new SplitActionState; state->area = area; state->split = split; state->widget = widget; state->widgetList = widgetList; state->widgetActions = widgetActions; state->id = id; state->title = title; actToolBar->addAction(action,title,split); action->setText(title); int index = m_actStateMap.size(); if ((index <= 9) && m_useShortcuts) { action->setText(QString("%1: %2").arg(index).arg(title)); QKeySequence ks(LiteApi::UseMacShortcuts?QString("Ctrl+Alt+%1").arg(index):QString("Alt+%1").arg(index)); LiteApi::IActionContext *actionContext = app->actionManager()->getActionContext(app,"App"); actionContext->regAction(action,"ToolWindow_"+id,ks.toString()); } m_actStateMap.insert(action,state); connect(action,SIGNAL(toggled(bool)),this,SLOT(toggledAction(bool))); if (m_windowMenu) { m_windowMenu->addAction(action); } return action; } void SplitWindowStyle::moveToolWindow(Qt::DockWidgetArea from, Qt::DockWidgetArea to, QAction *action, bool split) { SplitActionState *state = m_actStateMap.value(action); if (!state) { return; } if (state->area == to && state->split == split) { return; } SplitActionToolBar *actionToolBar = m_areaToolBar.value(to); SplitActionToolBar *oldActToolBar = m_areaToolBar.value(from); if (action->isChecked()) { action->setChecked(false); } oldActToolBar->removeAction(action,state->split); actionToolBar->addAction(action,state->title,split); state->area = to; state->split = split; action->setChecked(true); } void SplitWindowStyle::restoreToolWindows() { foreach(QAction *action,m_hideActionList) { action->setChecked(true); } m_hideActionList.clear(); } void SplitWindowStyle::showOrHideToolWindow() { bool hide = false; foreach(QAction *action, m_actStateMap.keys()) { if (action->isChecked()) { hide = true; break; } } if (hide) { hideAllToolWindows(); } else { restoreToolWindows(); } } void SplitWindowStyle::hideAllToolWindows() { m_hideActionList.clear(); foreach(QAction *action, m_actStateMap.keys()) { if (action->isChecked()) { m_hideActionList.append(action); action->setChecked(false); } } } void SplitWindowStyle::hideOutputWindow() { this->hideToolWindow(Qt::TopDockWidgetArea); this->hideToolWindow(Qt::BottomDockWidgetArea); } void SplitWindowStyle::hideSideBar(bool b) { QMapIterator<Qt::DockWidgetArea,SplitActionToolBar*> it(m_areaToolBar); while (it.hasNext()) { it.next(); if (it.key() != Qt::BottomDockWidgetArea) { it.value()->setHideToolBar(b); } } } void SplitWindowStyle::saveToolState() const { QMapIterator<QAction*,SplitActionState*> i(m_actStateMap); while (i.hasNext()) { i.next(); SplitActionState *state = i.value(); m_liteApp->settings()->setValue("split_area/"+state->id,state->area); m_liteApp->settings()->setValue("split_split/"+state->id,state->split); m_liteApp->settings()->setValue("split_check/"+state->id,i.key()->isChecked()); } m_liteApp->settings()->setValue("split_side_hide",m_hideSideAct->isChecked()); } void SplitWindowStyle::restoreToolsState() { m_hideSideAct->setChecked(m_liteApp->settings()->value("split_side_hide").toBool()); } void SplitWindowStyle::updateConer() { m_mainWindow->setCorner(Qt::BottomLeftCorner,Qt::LeftDockWidgetArea); m_mainWindow->setCorner(Qt::BottomRightCorner,Qt::RightDockWidgetArea); } void SplitWindowStyle::hideToolWindow(Qt::DockWidgetArea area) { SplitActionToolBar *bar = m_areaToolBar.value(area); if (bar) { bar->dock1->close(); bar->dock2->close(); } }
15,927
C++
.cpp
437
31.421053
221
0.677875
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,567
folderprojectfactory.cpp
visualfc_liteide/liteidex/src/liteapp/folderprojectfactory.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: folderprojectfactory.cpp // Creator: visualfc <visualfc@gmail.com> #include "folderprojectfactory.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 FolderProjectFactory::FolderProjectFactory(LiteApi::IApplication *app, QObject *parent) : LiteApi::IProjectFactory(parent), m_liteApp(app) { m_mimeTypes.append("folder/x-path"); } QStringList FolderProjectFactory::mimeTypes() const { return m_mimeTypes; } LiteApi::IProject *FolderProjectFactory::open(const QString &fileName, const QString &mimeType) { if (!m_mimeTypes.contains(mimeType)) { return 0; } return m_liteApp->projectManager()->openFolder(fileName); } bool FolderProjectFactory::findTargetInfo(const QString&, const QString&, QMap<QString,QString>&) const { return false; }
2,040
C++
.cpp
53
36.169811
103
0.693239
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,568
multifolderwindow.cpp
visualfc_liteide/liteidex/src/liteapp/multifolderwindow.cpp
/************************************************************************** ** This file is part of LiteIDE ** ** Copyright (c) 2011-2018 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: multifolderwindow.cpp // Creator: visualfc <visualfc@gmail.com> #include "multifolderwindow.h" #include "liteapp_global.h" #include <QMenu> #include <QAction> //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 MultiFolderWindow::MultiFolderWindow(LiteApi::IApplication *app, QObject *parent) : IFolderWindow(parent) { m_liteApp = app; m_folderListView = new MultiFolderView(app); QDir::Filters filters = QDir::AllDirs | QDir::Files | QDir::Drives | QDir::Readable| QDir::Writable | QDir::Executable /*| QDir::Hidden*/ | QDir::NoDotAndDotDot; m_folderListView->setFilter(filters); m_bSyncEditor = false; connect(m_folderListView,SIGNAL(aboutToShowContextMenu(QMenu*,LiteApi::FILESYSTEM_CONTEXT_FLAG,QFileInfo)),this,SLOT(aboutToShowFolderContextMenu(QMenu*,LiteApi::FILESYSTEM_CONTEXT_FLAG,QFileInfo))); connect(m_folderListView,SIGNAL(doubleClicked(QModelIndex)),this,SLOT(doubleClickedFolderView(QModelIndex))); connect(m_folderListView,SIGNAL(enterKeyPressed(QModelIndex)),this,SLOT(enterKeyPressedFolderView(QModelIndex))); connect(m_liteApp->editorManager(),SIGNAL(currentEditorChanged(LiteApi::IEditor*)),this,SLOT(currentEditorChanged(LiteApi::IEditor*))); } MultiFolderWindow::~MultiFolderWindow() { delete m_folderListView; } QWidget *MultiFolderWindow::widget() const { return m_folderListView; } QString MultiFolderWindow::id() const { return "folderwindow/multifolder"; } void MultiFolderWindow::setShowHideFiles(bool b) { QDir::Filters filters = m_folderListView->filter(); if (b) { filters |= QDir::Hidden; } else if (filters.testFlag(QDir::Hidden)){ filters ^= QDir::Hidden; } m_folderListView->setFilter(filters); } void MultiFolderWindow::setShowDetails(bool b) { m_folderListView->setShowDetails(b); } void MultiFolderWindow::setSyncEditor(bool b) { m_bSyncEditor = b; if (b) { this->currentEditorChanged(m_liteApp->editorManager()->currentEditor()); } } void MultiFolderWindow::doubleClickedFolderView(const QModelIndex &index) { if (!index.isValid()) { return; } QFileInfo info = m_folderListView->fileInfo(index); if (info.isFile()) { m_liteApp->fileManager()->openEditor(info.filePath()); } } void MultiFolderWindow::enterKeyPressedFolderView(const QModelIndex &index) { if (!index.isValid()) { return; } QFileInfo info = m_folderListView->fileInfo(index); if (info.isFile()) { m_liteApp->fileManager()->openEditor(info.filePath()); } else { m_folderListView->setExpanded(index,!m_folderListView->isExpanded(index)); } } QStringList MultiFolderWindow::folderList() const { return m_folderListView->rootPathList(); } void MultiFolderWindow::setFolderList(const QStringList &folders) { QStringList all = folders; all.removeDuplicates(); m_folderListView->setRootPathList(all); foreach (QString folder, all) { m_liteApp->recentManager()->addRecent(folder,"folder"); } if (m_folderListView->rootPathList().size() == 1) { m_folderListView->expandFolder(m_folderListView->rootPathList().first(),true); } } void MultiFolderWindow::addFolderList(const QString &folder) { if (!m_folderListView->addRootPath(folder)) { return; } m_liteApp->recentManager()->addRecent(folder,"folder"); m_folderListView->expandFolder(folder,true); } void MultiFolderWindow::closeAllFolders() { m_folderListView->closeAllFolders(); } void MultiFolderWindow::currentEditorChanged(LiteApi::IEditor *editor) { if (!editor || !m_bSyncEditor) { return; } QString fileName = editor->filePath(); if (fileName.isEmpty()) { return; } QList<QModelIndex> indexList = m_folderListView->indexForPath(fileName); if (indexList.isEmpty()) { return; } QModelIndex index = indexList.first(); m_folderListView->scrollTo(index,QAbstractItemView::EnsureVisible); m_folderListView->clearSelection(); m_folderListView->setCurrentIndex(index); } void MultiFolderWindow::aboutToShowFolderContextMenu(QMenu *menu, LiteApi::FILESYSTEM_CONTEXT_FLAG flag, const QFileInfo &info) { m_liteApp->fileManager()->emitAboutToShowFolderContextMenu(menu,flag,info,"liteapp/folder"); }
5,815
C++
.cpp
155
32.354839
204
0.684632
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,569
liteappoption.cpp
visualfc_liteide/liteidex/src/liteapp/liteappoption.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: liteappoption.cpp // Creator: visualfc <visualfc@gmail.com> #include "liteappoption.h" #include "actionmanager.h" #include "liteapp_global.h" #include "ui_liteappoption.h" #include <QDir> #include <QFileInfo> #include <QLocale> #include <QStandardItemModel> #include <QStandardItem> #include <QFileDialog> #include <QMessageBox> #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 LiteAppOption::LiteAppOption(LiteApi::IApplication *app,QObject *parent) : LiteApi::IOption(parent), m_liteApp(app), m_widget(new QWidget), ui(new Ui::LiteAppOption) { ui->setupUi(m_widget); const QString &liteideTrPath = m_liteApp->resourcePath()+"/translations"; QLocale eng(QLocale::English); ui->langComboBox->addItem(QLocale::languageToString(QLocale::English),eng.name()); QDir dir(liteideTrPath); if (dir.exists()) { foreach (QFileInfo info,dir.entryInfoList(QStringList() << "liteide_*.qm")) { QString base = info.baseName(); QLocale lc(base.right(base.length()-8)); if (lc.name().isEmpty()) { continue; } QLocale::Language lang = lc.language(); QString text = QString("%1 (%2)").arg(QLocale::languageToString(lang)).arg(lc.name()); ui->langComboBox->addItem(text,lc.name()); } } connect(ui->customIconCheckBox,SIGNAL(toggled(bool)),ui->iconPathComboBox,SLOT(setEnabled(bool))); QDir iconDir(m_liteApp->resourcePath()+"/liteapp/qrc"); foreach (QFileInfo info, iconDir.entryInfoList(QDir::Dirs|QDir::NoDotAndDotDot)) { ui->iconPathComboBox->addItem(info.fileName()); } m_keysModel = new QStandardItemModel(0,5,this); m_keysModel->setHeaderData(0,Qt::Horizontal,tr("Command")); m_keysModel->setHeaderData(1,Qt::Horizontal,tr("Label")); m_keysModel->setHeaderData(2,Qt::Horizontal,tr("Shortcuts")); m_keysModel->setHeaderData(3,Qt::Horizontal,tr("NativeText")); m_keysModel->setHeaderData(4,Qt::Horizontal,tr("Standard")); ui->keysTreeView->setModel(m_keysModel); #if QT_VERSION >= 0x050000 ui->keysTreeView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); #else ui->keysTreeView->header()->setResizeMode(QHeaderView::ResizeToContents); #endif #ifndef Q_OS_MAC ui->keysTreeView->header()->hideSection(3); #endif ui->styleComboBox->addItem(tr("SideBarStyle"),"sidebar"); ui->styleComboBox->addItem(tr("SplitterStyle"),"splitter"); const QString &liteQssPath = m_liteApp->resourcePath()+"/liteapp/qss"; QDir qssDir(liteQssPath); if (qssDir.exists()) { foreach (QFileInfo info, qssDir.entryInfoList(QStringList() << "*.qss")) { ui->qssComboBox->addItem(info.fileName()); } } // if (libgopher.isValid()) { // ui->gopherInfoLabel->setText(tr("libgopher is valid")); // } else { // ui->gopherInfoLabel->setText(tr("libgopher is invalid!")); // } // bool useGopher = m_liteApp->settings()->value(LITEAPP_USE_LIBGOPHER,false).toBool(); // ui->useLibgopherCheckBox->setChecked(useGopher); connect(m_keysModel,SIGNAL(itemChanged(QStandardItem*)),this,SLOT(shortcutsChanaged(QStandardItem*))); connect(ui->resetAllButton,SIGNAL(clicked()),this,SLOT(resetAllShortcuts())); connect(ui->resetButton,SIGNAL(clicked()),this,SLOT(resetShortcuts())); connect(ui->importButton,SIGNAL(clicked()),this,SLOT(importShortcuts())); connect(ui->exportButton,SIGNAL(clicked()),this,SLOT(exportShortcuts())); connect(ui->standardCheckBox,SIGNAL(toggled(bool)),this,SLOT(reloadShortcuts())); connect(ui->autoLoadLastSessionCheckBox,SIGNAL(toggled(bool)),this,SLOT(autoLoadLastSessionToggled(bool))); connect(ui->autoIdleSaveDocumentsCheckBox,SIGNAL(toggled(bool)),this,SLOT(autoIdleSaveDocumentsToggled(bool))); connect(ui->autoIdleSaveDocumentsCheckBox,SIGNAL(toggled(bool)),ui->autoIdleSaveDocumentsTimeSpinBox,SLOT(setEnabled(bool))); } LiteAppOption::~LiteAppOption() { delete m_widget; delete ui; } QWidget *LiteAppOption::widget() { return m_widget; } QString LiteAppOption::name() const { return "LiteApp"; } QString LiteAppOption::mimeType() const { return OPTION_LITEAPP; } void LiteAppOption::save() { bool storeLocal = ui->storeLocalCheckBox->isChecked(); QSettings global(m_liteApp->resourcePath()+"/liteapp/config/global.ini",QSettings::IniFormat); global.setValue(LITEIDE_STORELOCAL,storeLocal); int index = ui->langComboBox->currentIndex(); if (index >= 0 && index < ui->langComboBox->count()) { QString lc = ui->langComboBox->itemData(index).toString(); m_liteApp->settings()->setValue(LITEAPP_LANGUAGE,lc); } index = ui->styleComboBox->currentIndex(); if (index >= 0 && index < ui->styleComboBox->count()) { QString style = ui->styleComboBox->itemData(index).toString(); m_liteApp->settings()->setValue(LITEAPP_STYLE,style); } //QString max = ui->maxRecentLineEdit->text(); int max = ui->maxRecentFilesSpinBox->value(); m_liteApp->settings()->setValue(LITEAPP_MAXRECENTFILES,max); max = ui->maxEditorCountSpinBox->value(); m_liteApp->settings()->setValue(LITEAPP_MAXEDITORCOUNT,max); //bool b = ui->autoCloseProjecEditorsCheckBox->isChecked(); // m_liteApp->settings()->setValue(LITEAPP_AUTOCLOSEPROEJCTFILES,b); bool b1 = ui->autoLoadLastSessionCheckBox->isChecked(); m_liteApp->settings()->setValue(LITEAPP_AUTOLOADLASTSESSION,b1); bool b2 = ui->splashVisibleCheckBox->isChecked(); m_liteApp->settings()->setValue(LITEAPP_SPLASHVISIBLE,b2); bool b3 = ui->welcomeVisibleCheckBox->isChecked(); m_liteApp->settings()->setValue(LITEAPP_WELCOMEPAGEVISIBLE,b3); bool b4 = ui->editorTabsClosableCheckBox->isChecked(); m_liteApp->settings()->setValue(LITEAPP_EDITTABSCLOSABLE,b4); bool b5 = ui->startupReloadFilesCheckBox->isChecked(); m_liteApp->settings()->setValue(LITEAPP_STARTUPRELOADFILES,b5); // bool b6 = ui->startupReloadFoldersCheckBox->isChecked(); // m_liteApp->settings()->setValue(LITEAPP_STARTUPRELOADFOLDERS,b6); bool b7 = ui->fileWatcherAutoReloadCheckBox->isChecked(); m_liteApp->settings()->setValue(LITEAPP_FILEWATCHERAUTORELOAD,b7); bool b8 = ui->editorTabsEnableWhellCheckBox->isChecked(); m_liteApp->settings()->setValue(LITEAPP_EDITTABSENABLEWHELL,b8); bool b9 = ui->autoIdleSaveDocumentsCheckBox->isChecked(); m_liteApp->settings()->setValue(LITEAPP_AUTOIDLESAVEDOCUMENTS,b9); int time = ui->autoIdleSaveDocumentsTimeSpinBox->value(); m_liteApp->settings()->setValue(LITEAPP_AUTOIDLESAVEDOCUMENTS_TIME,time); bool toolwindowshortcuts = ui->toolWindowShortcutsCheckBox->isChecked(); m_liteApp->settings()->setValue(LITEAPP_TOOLWINDOW_SHORTCUTS,toolwindowshortcuts); bool ext = ui->editorMouseExtNavigateCheckBox->isChecked(); m_liteApp->settings()->setValue(LITEAPP_EDITORMOUSEEXTNAVIGATE,ext); int size = ui->buttonGroup->buttons().size(); for (int i = 0; i < size; i++) { if (ui->buttonGroup->buttons().at(i)->isChecked()) { m_liteApp->settings()->setValue(LITEAPP_TOOLBARICONSIZE,i); break; } } // bool useGopher = ui->useLibgopherCheckBox->isChecked(); // bool oldUseGopher = m_liteApp->settings()->value(LITEAPP_USE_LIBGOPHER,false).toBool(); // if (useGopher != oldUseGopher) { // m_liteApp->settings()->setValue(LITEAPP_USE_LIBGOPHER,useGopher); // if (!libgopher.isValid()) { // m_liteApp->appendLog("LiteApp",QString("libgopher is invalid")); // } else { // m_liteApp->appendLog("LiteApp",useGopher ? QString("enable use libgopher"):QString("disable use libgopher")); // } // } QString qss = ui->qssComboBox->currentText(); if (!qss.isEmpty()) { QFile f(m_liteApp->resourcePath()+"/liteapp/qss/"+qss); if (f.open(QFile::ReadOnly)) { m_liteApp->settings()->setValue(LITEAPP_QSS,qss); QString styleSheet = QLatin1String(f.readAll()); qApp->setStyleSheet(styleSheet); } } bool customelIcon = ui->customIconCheckBox->isChecked(); m_liteApp->settings()->setValue(LITEIDE_CUSTOMEICON,customelIcon); QString iconPath = ui->iconPathComboBox->currentText(); m_liteApp->settings()->setValue(LITEIDE_CUSTOMEICONPATH,iconPath); for (int i = 0; i < m_keysModel->rowCount(); i++) { QStandardItem *root = m_keysModel->item(i,0); if (!root) { continue; } LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->actionContextForName(root->text()); if (!actionContext) { continue; } for (int j = 0; j < root->rowCount(); j++) { QStandardItem *id = root->child(j,0); if (!id) { continue; } QStandardItem *bind = root->child(j,2); if (!bind) { continue; } m_liteApp->actionManager()->setActionShourtcuts(id->text(),bind->text()); } } } void LiteAppOption::load() { QSettings global(m_liteApp->resourcePath()+"/liteapp/config/global.ini",QSettings::IniFormat); bool storeLocal = global.value(LITEIDE_STORELOCAL,false).toBool(); ui->storeLocalCheckBox->setChecked(storeLocal); QString locale = QLocale::system().name(); locale = m_liteApp->settings()->value(LITEAPP_LANGUAGE,locale).toString(); if (!locale.isEmpty()) { for (int i = 0; i < ui->langComboBox->count(); i++) { if (locale == ui->langComboBox->itemData(i).toString()) { ui->langComboBox->setCurrentIndex(i); break; } } } QString style = m_liteApp->settings()->value(LITEAPP_STYLE,"sidebar").toString(); for (int i = 0; i < ui->styleComboBox->count(); i++) { if (style == ui->styleComboBox->itemData(i).toString()) { ui->styleComboBox->setCurrentIndex(i); break; } } bool customeIcon = m_liteApp->settings()->value(LITEIDE_CUSTOMEICON,false).toBool(); ui->customIconCheckBox->setChecked(customeIcon); ui->iconPathComboBox->setEnabled(customeIcon); QString qss = m_liteApp->settings()->value(LITEAPP_QSS,"default.qss").toString(); int index = ui->qssComboBox->findText(qss,Qt::MatchFixedString); if (index >= 0 && index < ui->qssComboBox->count()) { ui->qssComboBox->setCurrentIndex(index); } int max = m_liteApp->settings()->value(LITEAPP_MAXRECENTFILES,32).toInt(); //ui->maxRecentLineEdit->setText(QString("%1").arg(max)); ui->maxRecentFilesSpinBox->setValue(max); max = m_liteApp->settings()->value(LITEAPP_MAXEDITORCOUNT,64).toInt(); ui->maxEditorCountSpinBox->setValue(max); //bool b = m_liteApp->settings()->value(LITEAPP_AUTOCLOSEPROEJCTFILES,true).toBool(); //ui->autoCloseProjecEditorsCheckBox->setChecked(b); bool b1 = m_liteApp->settings()->value(LITEAPP_AUTOLOADLASTSESSION,true).toBool(); ui->autoLoadLastSessionCheckBox->setChecked(b1); bool b2 = m_liteApp->settings()->value(LITEAPP_SPLASHVISIBLE,true).toBool(); ui->splashVisibleCheckBox->setChecked(b2); bool b3 = m_liteApp->settings()->value(LITEAPP_WELCOMEPAGEVISIBLE,true).toBool(); ui->welcomeVisibleCheckBox->setChecked(b3); bool b4 = m_liteApp->settings()->value(LITEAPP_EDITTABSCLOSABLE,true).toBool(); ui->editorTabsClosableCheckBox->setChecked(b4); // bool b5 = m_liteApp->settings()->value(LITEAPP_STARTUPRELOADFOLDERS,true).toBool(); // ui->startupReloadFoldersCheckBox->setChecked(b5); bool b6 = m_liteApp->settings()->value(LITEAPP_STARTUPRELOADFILES,true).toBool(); ui->startupReloadFilesCheckBox->setChecked(b6); bool b7 = m_liteApp->settings()->value(LITEAPP_FILEWATCHERAUTORELOAD,false).toBool(); ui->fileWatcherAutoReloadCheckBox->setChecked(b7); bool b8 = m_liteApp->settings()->value(LITEAPP_EDITTABSENABLEWHELL,true).toBool(); ui->editorTabsEnableWhellCheckBox->setChecked(b8); int id = m_liteApp->settings()->value(LITEAPP_TOOLBARICONSIZE,0).toInt(); if (id >= 0 && id < ui->buttonGroup->buttons().size()) { ui->buttonGroup->buttons().at(id)->setChecked(true); } bool b9 = m_liteApp->settings()->value(LITEAPP_AUTOIDLESAVEDOCUMENTS,false).toBool(); ui->autoIdleSaveDocumentsCheckBox->setChecked(b9); int time = m_liteApp->settings()->value(LITEAPP_AUTOIDLESAVEDOCUMENTS_TIME,3).toInt(); if (time < 1) { time = 1; } ui->autoIdleSaveDocumentsTimeSpinBox->setValue(time); bool toolwndshortcuts = m_liteApp->settings()->value(LITEAPP_TOOLWINDOW_SHORTCUTS,true).toBool(); ui->toolWindowShortcutsCheckBox->setChecked(toolwndshortcuts); bool ext = m_liteApp->settings()->value(LITEAPP_EDITORMOUSEEXTNAVIGATE,true).toBool(); ui->editorMouseExtNavigateCheckBox->setChecked(ext); QString iconPath = m_liteApp->settings()->value(LITEIDE_CUSTOMEICONPATH,"default").toString(); index = ui->iconPathComboBox->findText(iconPath,Qt::MatchFixedString); if (index >= 0 && index < ui->iconPathComboBox->count()) { ui->iconPathComboBox->setCurrentIndex(index); } ui->standardCheckBox->setChecked(true); autoLoadLastSessionToggled(ui->autoLoadLastSessionCheckBox->isChecked()); this->reloadShortcuts(); } void LiteAppOption::reloadShortcuts() { m_keysModel->removeRows(0,m_keysModel->rowCount()); bool bCheckStandard = ui->standardCheckBox->isChecked(); foreach(QString name, m_liteApp->actionManager()->actionContextNameList() ) { LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->actionContextForName(name); if (actionContext) { QStandardItem *root = new QStandardItem(name); root->setEditable(false); foreach(QString id, actionContext->actionKeys()) { LiteApi::ActionInfo *info = actionContext->actionInfo(id); if (!info) { continue; } if (bCheckStandard && info->standard && (info->ks == info->defks)) { continue; } QStandardItem *item = new QStandardItem(id); item->setEditable(false); QStandardItem *label = new QStandardItem(info->label); label->setEditable(false); QStandardItem *std = new QStandardItem; std->setCheckable(true); std->setEnabled(false); std->setCheckState(info->standard?Qt::Checked:Qt::Unchecked); QStandardItem *bind = new QStandardItem(info->ks); bind->setEditable(true); if (info->ks != info->defks) { QFont font = bind->font(); font.setBold(true); bind->setFont(font); } QStandardItem *native = new QStandardItem(ActionManager::formatShortcutsNativeString(info->ks)); native->setEditable(false); root->appendRow(QList<QStandardItem*>() << item << label << bind << native << std); } m_keysModel->appendRow(root); } } ui->keysTreeView->expandAll(); } void LiteAppOption::shortcutsChanaged(QStandardItem *bind) { if (!bind) { return; } QStandardItem *root = bind->parent(); if (!root) { return; } LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->actionContextForName(root->text()); if (!actionContext) { return; } QStandardItem *item = root->child(bind->row(),0); if (!item) { return; } QStandardItem *native = root->child(bind->row(),3); LiteApi::ActionInfo *info = actionContext->actionInfo(item->text()); if (!info) { return; } m_keysModel->blockSignals(true); bind->setText(ActionManager::formatShortcutsString(bind->text())); native->setText(ActionManager::formatShortcutsNativeString(bind->text())); m_keysModel->blockSignals(false); QFont font = bind->font(); if (info->defks != bind->text()) { font.setBold(true); } else { font.setBold(false); } bind->setFont(font); } void LiteAppOption::resetAllShortcuts() { for (int i = 0; i < m_keysModel->rowCount(); i++) { QStandardItem *root = m_keysModel->item(i,0); if (!root) { continue; } LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->actionContextForName(root->text()); if (!actionContext) { continue; } for (int j = 0; j < root->rowCount(); j++) { QStandardItem *id = root->child(j,0); if (!id) { continue; } QStandardItem *bind = root->child(j,2); if (!bind) { continue; } LiteApi::ActionInfo *info = actionContext->actionInfo(id->text()); if (!info) { continue; } bind->setText(info->defks); QFont font = bind->font(); font.setBold(false); bind->setFont(font); } } } void LiteAppOption::resetShortcuts() { QModelIndex index = ui->keysTreeView->currentIndex(); if (!index.isValid()) { return; } QModelIndex rootIndex = index.parent(); if (!rootIndex.isValid()) { return; } QStandardItem *root = m_keysModel->item(rootIndex.row()); if (!root) { return; } LiteApi::IActionContext *actionContext = m_liteApp->actionManager()->actionContextForName(root->text()); if (!actionContext) { return; } QStandardItem *id = root->child(index.row(),0); if (!id) { return; } QStandardItem *bind = root->child(index.row(),2); if (!bind) { return; } LiteApi::ActionInfo *info = actionContext->actionInfo(id->text()); if (!info) { return; } bind->setText(info->defks); QFont font = bind->font(); font.setBold(false); bind->setFont(font); } void LiteAppOption::importShortcuts() { QString dir = m_liteApp->resourcePath()+"/liteapp/kms"; QString filePath = QFileDialog::getOpenFileName(m_liteApp->mainWindow(),tr("Import Keyboard Mapping Scheme"),dir,QString(tr("Keyboard Mapping Scheme (%1)")).arg("*.kms")); if (filePath.isEmpty()) { return; } QSettings read(filePath,QSettings::IniFormat); int version = read.value("liteidex/version",0).toInt(); if (version < 1) { QMessageBox::critical(m_liteApp->mainWindow(),"Import Error",QString(tr("Could not read scheme from %1!")).arg(filePath)); return; } for (int i = 0; i < m_keysModel->rowCount(); i++) { QStandardItem *root = m_keysModel->item(i,0); for (int j = 0; j < root->rowCount(); j++) { QStandardItem *id = root->child(j,0); if (!id) { continue; } QStandardItem *bind = root->child(j,2); if (!bind) { continue; } QVariant val = read.value(root->text()+"/"+id->text()); if (!val.isValid()) { continue; } bind->setText(ActionManager::formatShortcutsString(val.toString())); } } } void LiteAppOption::exportShortcuts() { QString dir = m_liteApp->resourcePath()+"/liteapp/kms"; QString filePath = QFileDialog::getSaveFileName(m_liteApp->mainWindow(),tr("Export Keyboard Mapping Scheme"),dir,QString(tr("Keyboard Mapping Scheme (%1)")).arg("*.kms")); if (filePath.isEmpty()) { return; } QFileInfo info(filePath); if (info.suffix() != "kms") { filePath += ".kms"; } QSettings write(filePath,QSettings::IniFormat); if (!write.isWritable()) { QMessageBox::critical(m_liteApp->mainWindow(),"Export Error",QString(tr("Could not write scheme to %1!")).arg(filePath)); return; } write.clear(); write.setValue("liteidex/version",1); for (int i = 0; i < m_keysModel->rowCount(); i++) { QStandardItem *root = m_keysModel->item(i,0); for (int j = 0; j < root->rowCount(); j++) { QStandardItem *id = root->child(j,0); if (!id) { continue; } QStandardItem *bind = root->child(j,2); if (!bind) { continue; } write.setValue(root->text()+"/"+id->text(),bind->text()); } } } void LiteAppOption::autoLoadLastSessionToggled(bool b) { //ui->startupReloadFoldersCheckBox->setEnabled(b); ui->startupReloadFilesCheckBox->setEnabled(b); } void LiteAppOption::autoIdleSaveDocumentsToggled(bool /*b*/) { }
22,210
C++
.cpp
518
36.150579
175
0.646447
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,571
tooldockwidget.cpp
visualfc_liteide/liteidex/src/liteapp/tooldockwidget.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: tooldockwidget.cpp // Creator: visualfc <visualfc@gmail.com> #include "tooldockwidget.h" #include "liteapi/liteapi.h" #include <QAction> #include <QIcon> #include <QLabel> #include <QHBoxLayout> #include <QHBoxLayout> #include <QVariant> #include <QMenu> #include <QToolButton> #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 BaseDockWidget::BaseDockWidget(QSize iconSize, QWidget *parent) : QDockWidget(parent), current(0) { m_mainWidget = new QWidget; m_widget = 0; QDockWidget::setWidget(m_mainWidget); m_mainLayout = new QVBoxLayout; m_mainLayout->setMargin(0); m_mainLayout->setSpacing(1); m_mainWidget->setLayout(m_mainLayout); m_comboBox = new QComboBox; m_comboBox->setMinimumContentsLength(4); //m_comboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents); m_comboBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); //m_comboBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); m_toolBar = new QToolBar(this); m_toolBar->setContentsMargins(0, 0, 0, 0); m_toolBar->setIconSize(iconSize); //m_toolBar->setFixedHeight(24); // m_titleLabel = new QLabel; // m_titleLabel->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Minimum); m_comboBoxAct = m_toolBar->addWidget(m_comboBox); // m_titleLabelAct = m_toolBar->addWidget(m_titleLabel); // m_titleLabelAct->setChecked(false); m_spacer = new QWidget; m_spacer->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); m_toolBar->addSeparator(); m_spacerAct = m_toolBar->addWidget(m_spacer); m_closeAct = new QAction(tr("Hide"), m_toolBar); m_closeAct->setToolTip(tr("Hide Tool Window")); m_closeAct->setIcon(QIcon("icon:images/hidetool.png")); m_toolBar->addAction(m_closeAct); connect(m_closeAct,SIGNAL(triggered()),this,SLOT(close())); connect(m_comboBox,SIGNAL(activated(int)),this,SLOT(activeComboBoxIndex(int))); this->setTitleBarWidget(m_toolBar); m_floatAct = new QAction(tr("Floating Window"),this); m_floatAct->setCheckable(true); connect(m_floatAct,SIGNAL(triggered(bool)),this,SLOT(setFloatingWindow(bool))); connect(this,SIGNAL(topLevelChanged(bool)),this,SLOT(topLevelChanged(bool))); /* m_toolBar->setStyleSheet("QToolBar {border: 1px ; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #eeeeee, stop: 1 #ababab); }"\ "QToolBar QToolButton { border:1px ; border-radius: 1px; }"\ "QToolBar QToolButton::hover { background-color: #ababab;}"\ "QToolBar::separator {width:2px; margin-left:2px; margin-right:2px; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #dedede, stop: 1 #a0a0a0);}"); */ } void BaseDockWidget::setWindowTitle(const QString &text) { QDockWidget::setWindowTitle(text); } QAction *BaseDockWidget::addWidget(QWidget *widget) { return m_toolBar->insertWidget(m_closeAct,widget); } void BaseDockWidget::setToolMenu(QMenu *menu) { QToolButton *btn = new QToolButton; btn->setPopupMode(QToolButton::InstantPopup); btn->setMenu(menu); btn->setStyleSheet("QToolButton::menu-indicator{image:none;}"); m_toolBar->insertWidget(m_closeAct,btn); } void BaseDockWidget::setWidgetActions(QList<QAction*> actions) { foreach(QAction *action, m_widgetActions) { m_toolBar->removeAction(action); } m_widgetActions = actions; //m_spacerAct->setVisible(!m_widgetActions.isEmpty()); foreach(QAction *action, m_widgetActions) { m_toolBar->insertAction(m_spacerAct,action); if (action->menu()) { QWidget *w = m_toolBar->widgetForAction(action); QToolButton *btn = qobject_cast<QToolButton*>(w); if (btn) { btn->setPopupMode(QToolButton::InstantPopup); btn->setStyleSheet("QToolButton::menu-indicator{image:none;}"); } } } } void BaseDockWidget::setWidgetList(QList<QWidget *> widgets) { foreach(QAction *action, m_widgetActions) { m_toolBar->removeAction(action); } m_widgetActions.clear(); m_widgetList = widgets; //m_spacerAct->setVisible(!m_widgetActions.isEmpty()); foreach(QWidget *widget, m_widgetList) { QAction *action = m_toolBar->insertWidget(m_spacerAct,widget); m_widgetActions.push_back(action); if (action->menu()) { QWidget *w = m_toolBar->widgetForAction(action); QToolButton *btn = qobject_cast<QToolButton*>(w); if (btn) { btn->setPopupMode(QToolButton::InstantPopup); btn->setStyleSheet("QToolButton::menu-indicator{image:none;}"); } } } } QList<QAction *> BaseDockWidget::actions() const { return m_actions; } void BaseDockWidget::removeAction(QAction *action) { if (m_actions.removeAll(action)) { if (action == current) current = 0; int index = m_comboBox->findData(action->objectName()); if (index >= 0) { m_comboBox->removeItem(index); } QObject::disconnect(action, SIGNAL(changed()), this, SLOT(actionChanged())); } } void BaseDockWidget::setWidget(QWidget *widget) { if (m_widget) { m_mainLayout->removeWidget(m_widget); } m_widget = widget; if (m_widget) { m_mainLayout->addWidget(m_widget); } } QWidget *BaseDockWidget::widget() const { return m_widget; } QAction * BaseDockWidget::checkedAction () const { return current; } void BaseDockWidget::actionChanged() { QAction *action = qobject_cast<QAction*>(sender()); Q_ASSERT_X(action != 0, "ActionGroup::actionChanged", "internal error"); if (action->isChecked()) { if (action != current) { if(current) current->setChecked(false); current = action; int index = m_comboBox->findData(action->objectName()); if (index >= 0) { m_comboBox->setCurrentIndex(index); //m_titleLabel->setText(m_comboBox->currentText()); } } } else if (action == current) { current = 0; } } void BaseDockWidget::activeComboBoxIndex(int index) { if (index < 0 || index >= m_comboBox->count()) { return; } QString objName = m_comboBox->itemData(index).toString(); foreach(QAction *act, m_actions) { if (act->objectName() == objName) { if (!act->isChecked()) { act->setChecked(true); } break; } } } void BaseDockWidget::topLevelChanged(bool b) { // m_comboBoxAct->setVisible(!b); // m_titleLabel->setText(m_comboBox->currentText()); // m_titleLabelAct->setVisible(b); m_closeAct->setVisible(!b); DockWidgetFeatures flags = this->features(); if (b) { this->setTitleBarWidget(0); m_mainLayout->insertWidget(0,m_toolBar); m_mainLayout->setMargin(2); m_toolBar->setVisible(true); flags |= QDockWidget::DockWidgetFloatable; } else { m_mainLayout->setMargin(0); m_toolBar->setVisible(false); m_mainLayout->removeWidget(m_toolBar); this->setTitleBarWidget(m_toolBar); flags &= (~QDockWidget::DockWidgetFloatable); } this->setFeatures(flags); m_floatAct->setChecked(b); } void BaseDockWidget::setFloatingWindow(bool b) { if (this->isFloating() != b) { DockWidgetFeatures flags = this->features(); if (b) { flags |= QDockWidget::DockWidgetFloatable; } else { flags &= (~QDockWidget::DockWidgetFloatable); } this->setFeatures(flags); this->setFloating(b); } if (m_floatAct->isChecked() != b) { m_floatAct->setChecked(b); } } void BaseDockWidget::addAction(QAction *action, const QString &title) { if(!m_actions.contains(action)) { m_actions.append(action); m_comboBox->addItem(title,action->objectName()); QObject::connect(action, SIGNAL(changed()), this, SLOT(actionChanged())); } if (current && current->isChecked()) { current->setChecked(false); } if (action->isChecked()) { current = action; } } SplitDockWidget::SplitDockWidget(QSize iconSize, QWidget *parent) : BaseDockWidget(iconSize,parent) { } void SplitDockWidget::createMenu(Qt::DockWidgetArea area, bool split) { m_area = area; QMenu *moveMenu = new QMenu(tr("Move To"),this); if (area != Qt::TopDockWidgetArea) { QAction *act = new QAction(tr("Top"),this); act->setData(Qt::TopDockWidgetArea); moveMenu->addAction(act); connect(act,SIGNAL(triggered()),this,SLOT(moveAction())); QAction *act1 = new QAction(tr("Top (Split)"),this); act1->setData(Qt::TopDockWidgetArea); moveMenu->addAction(act1); connect(act1,SIGNAL(triggered()),this,SLOT(moveActionSplit())); } if (area != Qt::BottomDockWidgetArea) { QAction *act = new QAction(tr("Bottom"),this); act->setData(Qt::BottomDockWidgetArea); moveMenu->addAction(act); connect(act,SIGNAL(triggered()),this,SLOT(moveAction())); QAction *act1 = new QAction(tr("Bottom (Split)"),this); act1->setData(Qt::BottomDockWidgetArea); moveMenu->addAction(act1); connect(act1,SIGNAL(triggered()),this,SLOT(moveActionSplit())); } if (area != Qt::LeftDockWidgetArea) { QAction *act = new QAction(tr("Left"),this); act->setData(Qt::LeftDockWidgetArea); moveMenu->addAction(act); connect(act,SIGNAL(triggered()),this,SLOT(moveAction())); QAction *act1 = new QAction(tr("Left (Split)"),this); act1->setData(Qt::LeftDockWidgetArea); moveMenu->addAction(act1); connect(act1,SIGNAL(triggered()),this,SLOT(moveActionSplit())); } if (area != Qt::RightDockWidgetArea) { QAction *act = new QAction(tr("Right"),this); act->setData(Qt::RightDockWidgetArea); moveMenu->addAction(act); connect(act,SIGNAL(triggered()),this,SLOT(moveAction())); QAction *act1 = new QAction(tr("Right (Split)"),this); act1->setData(Qt::RightDockWidgetArea); moveMenu->addAction(act1); connect(act1,SIGNAL(triggered()),this,SLOT(moveActionSplit())); } if (area == Qt::TopDockWidgetArea) { m_areaInfo = split ? tr("TopDockWidget (Split)") : tr("TopDockWidget"); } else if (area == Qt::BottomDockWidgetArea) { m_areaInfo = split ? tr("BottomDockWidget (Split)") : tr("BottomDockWidget"); } else if (area == Qt::LeftDockWidgetArea) { m_areaInfo = split ? tr("LeftDockWidget (Split)") : tr("LeftDockWidget"); } else if (area == Qt::RightDockWidgetArea) { m_areaInfo = split ? tr("RightDockWidget (Split)") : tr("RightDockWidget"); } QMenu *menu = new QMenu(this); menu->addAction(m_floatAct); if (split) { QAction *unsplitAct = new QAction(tr("Unsplit"),this); unsplitAct->setData(area); connect(unsplitAct,SIGNAL(triggered()),this,SLOT(unsplitAction())); menu->addAction(unsplitAct); } else { QAction *splitAct = new QAction(tr("Split"),this); splitAct->setData(area); connect(splitAct,SIGNAL(triggered()),this,SLOT(splitAction())); menu->addAction(splitAct); } menu->addAction(moveMenu->menuAction()); if (area == Qt::BottomDockWidgetArea || area == Qt::TopDockWidgetArea) { m_comboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents); m_comboBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); QWidget *spacer = new QWidget; spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); m_toolBar->insertWidget(m_closeAct,spacer); } QToolButton *btn = new QToolButton(m_toolBar); btn->setPopupMode(QToolButton::InstantPopup); btn->setIcon(QIcon("icon:images/movemenu.png")); btn->setMenu(menu); btn->setText(tr("Move To")); btn->setToolTip(tr("Move To")); btn->setStyleSheet("QToolButton::menu-indicator {image: none;}"); m_toolBar->insertWidget(m_closeAct,btn); } void SplitDockWidget::setWindowTitle(const QString &text) { BaseDockWidget::setWindowTitle(m_areaInfo+" - "+text); } void SplitDockWidget::moveAction() { QAction *action = static_cast<QAction*>(sender()); if (!action) { return; } Qt::DockWidgetArea area = (Qt::DockWidgetArea)action->data().toInt(); emit moveActionTo(m_area,area,current,false); } void SplitDockWidget::moveActionSplit() { QAction *action = static_cast<QAction*>(sender()); if (!action) { return; } Qt::DockWidgetArea area = (Qt::DockWidgetArea)action->data().toInt(); emit moveActionTo(m_area,area,current,true); } void SplitDockWidget::splitAction() { QAction *action = static_cast<QAction*>(sender()); if (!action) { return; } Qt::DockWidgetArea area = (Qt::DockWidgetArea)action->data().toInt(); emit moveActionTo(m_area,area,current,true); } void SplitDockWidget::unsplitAction() { QAction *action = static_cast<QAction*>(sender()); if (!action) { return; } Qt::DockWidgetArea area = (Qt::DockWidgetArea)action->data().toInt(); emit moveActionTo(m_area,area,current,false); } OutputDockWidget::OutputDockWidget(QSize iconSize, QWidget *parent) : BaseDockWidget(iconSize,parent) { m_comboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents); m_comboBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); QWidget *spacer = new QWidget; spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); m_toolBar->insertWidget(m_closeAct,spacer); } void OutputDockWidget::createMenu(Qt::DockWidgetArea area) { this->setAllowedAreas(area); QMenu *moveMenu = new QMenu(tr("Move To"),this); QAction *leftAct = new QAction(tr("LeftSideBar"),this); QAction *rightAct = new QAction(tr("RightSideBar"),this); leftAct->setData(Qt::LeftDockWidgetArea); rightAct->setData(Qt::RightDockWidgetArea); moveMenu->addAction(leftAct); moveMenu->addAction(rightAct); connect(leftAct,SIGNAL(triggered()),this,SLOT(moveAction())); connect(rightAct,SIGNAL(triggered()),this,SLOT(moveAction())); QMenu *menu = new QMenu(this); menu->addAction(m_floatAct); menu->addAction(moveMenu->menuAction()); m_comboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents); m_comboBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); QWidget *spacer = new QWidget; spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); m_toolBar->insertWidget(m_closeAct,spacer); QToolButton *btn = new QToolButton(m_toolBar); btn->setPopupMode(QToolButton::InstantPopup); btn->setIcon(QIcon("icon:images/movemenu.png")); btn->setMenu(menu); btn->setText(tr("Move To")); btn->setToolTip(tr("Move To")); btn->setStyleSheet("QToolButton::menu-indicator {image: none;}"); m_toolBar->insertWidget(m_closeAct,btn); } void OutputDockWidget::setWindowTitle(const QString &text) { BaseDockWidget::setWindowTitle(QString(tr("BottomDockWidget"))+" - "+text); } void OutputDockWidget::setWidget(QWidget *widget) { if (m_widget) { m_mainLayout->removeWidget(m_widget); m_widget->setVisible(false); } m_widget = widget; if (m_widget) { m_mainLayout->addWidget(m_widget); m_widget->setVisible(true); } } void OutputDockWidget::moveAction() { QAction *action = static_cast<QAction*>(sender()); if (!action) { return; } this->setFloatingWindow(false); Qt::DockWidgetArea area = (Qt::DockWidgetArea)action->data().toInt(); emit moveActionTo(Qt::BottomDockWidgetArea,area,current); }
17,224
C++
.cpp
456
32.151316
196
0.662659
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,572
outputoption.cpp
visualfc_liteide/liteidex/src/liteapp/outputoption.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: outputoption.cpp // Creator: visualfc <visualfc@gmail.com> #include "outputoption.h" #include "ui_outputoption.h" #include "liteapp_global.h" #include <QFontDatabase> #include <QStandardItemModel> #include <QStandardItem> //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 OutputOption::OutputOption(LiteApi::IApplication *app,QObject *parent) : LiteApi::IOption(parent), m_liteApp(app), m_widget(new QWidget), ui(new Ui::OutputOption) { ui->setupUi(m_widget); QFontDatabase db; m_familyList = db.families(); ui->familyComboBox->addItems(m_familyList); } OutputOption::~OutputOption() { delete m_widget; delete ui; } QWidget *OutputOption::widget() { return m_widget; } QString OutputOption::name() const { return "LiteOutput"; } QString OutputOption::mimeType() const { return OPTION_LITEOUTPUT; } void OutputOption::save() { m_fontFamily = ui->familyComboBox->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(OUTPUT_FAMILY,m_fontFamily); m_liteApp->settings()->setValue(OUTPUT_FONTSIZE,m_fontSize); m_liteApp->settings()->setValue(OUTPUT_FONTZOOM,fontZoom); bool antialias = ui->antialiasCheckBox->isChecked(); m_liteApp->settings()->setValue(OUTPUT_ANTIALIAS,antialias); bool colorScheme = ui->useColorSchemeCheckBox->isChecked(); int maxLines = ui->spinBoxOutputMaxLines->value(); m_liteApp->settings()->setValue(OUTPUT_USECOLORSCHEME,colorScheme); m_liteApp->settings()->setValue(OUTPUT_MAXLINES,maxLines); } void OutputOption::load() { #if defined(Q_OS_WIN) m_fontFamily = m_liteApp->settings()->value(OUTPUT_FAMILY,"Courier").toString(); #elif defined(Q_OS_LINUX) m_fontFamily = m_liteApp->settings()->value(OUTPUT_FAMILY,"Monospace").toString(); #elif defined(Q_OS_MAC) m_fontFamily = m_liteApp->settings()->value(OUTPUT_FAMILY,"Menlo").toString(); #else m_fontFamily = m_liteApp->settings()->value(OUTPUT_FAMILY,"Monospace").toString(); #endif m_fontSize = m_liteApp->settings()->value(OUTPUT_FONTSIZE,12).toInt(); int fontZoom = m_liteApp->settings()->value(OUTPUT_FONTZOOM,100).toInt(); bool antialias = m_liteApp->settings()->value(OUTPUT_ANTIALIAS,true).toBool(); ui->antialiasCheckBox->setChecked(antialias); const int idx = m_familyList.indexOf(m_fontFamily); ui->familyComboBox->setCurrentIndex(idx); updatePointSizes(); ui->fontZoomSpinBox->setValue(fontZoom); bool useColorScheme = m_liteApp->settings()->value(OUTPUT_USECOLORSCHEME,true).toBool(); ui->useColorSchemeCheckBox->setChecked(useColorScheme); int maxLines = m_liteApp->settings()->value(OUTPUT_MAXLINES,5000).toInt(); ui->spinBoxOutputMaxLines->setValue(maxLines); } void OutputOption::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> OutputOption::pointSizesForSelectedFont() const { QFontDatabase db; const QString familyName = ui->familyComboBox->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; }
5,515
C++
.cpp
146
32.684932
93
0.665727
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,574
htmlwidgetmanager.cpp
visualfc_liteide/liteidex/src/liteapp/htmlwidgetmanager.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: htmlwidgetmanager.cpp // Creator: visualfc <visualfc@gmail.com> #include "htmlwidgetmanager.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 HtmlWidgetManager::HtmlWidgetManager(QObject *parent) : IHtmlWidgetManager(parent) { } QStringList HtmlWidgetManager::classNameList() const { QStringList names; foreach(IHtmlWidgetFactory *factory, m_factoryList) { names.append(factory->className()); } return names; } void HtmlWidgetManager::addFactory(IHtmlWidgetFactory *factory) { m_factoryList.append(factory); if (m_factoryList.size() == 1) { m_defaultClassName = factory->className(); } } QList<IHtmlWidgetFactory *> HtmlWidgetManager::factoryList() const { return m_factoryList; } IHtmlWidget *HtmlWidgetManager::create(QObject *parent) { return createByName(parent,m_defaultClassName); } IHtmlWidget *HtmlWidgetManager::createByName(QObject *parent, const QString &className) { foreach(IHtmlWidgetFactory *factory, m_factoryList) { if (factory->className() == className) { return factory->create(parent); } } return 0; } IHtmlDocument *HtmlWidgetManager::createDocument(QObject *parent) { return createDocumentByName(parent,m_defaultClassName); } IHtmlDocument *HtmlWidgetManager::createDocumentByName(QObject *parent, const QString &className) { foreach(IHtmlWidgetFactory *factory, m_factoryList) { if (factory->className() == className) { return factory->createDocument(parent); } } return 0; } bool HtmlWidgetManager::setDefaultClassName(const QString &className) { foreach(IHtmlWidgetFactory *factory, m_factoryList) { if (factory->className() == className) { m_defaultClassName = className; return true; } } return false; } QString HtmlWidgetManager::defaultClassName() const { return m_defaultClassName; }
3,180
C++
.cpp
95
30.042105
97
0.697788
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,575
optionmanager.cpp
visualfc_liteide/liteidex/src/liteapp/optionmanager.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: optionmanager.cpp // Creator: visualfc <visualfc@gmail.com> #include "optionmanager.h" #include "optionsbrowser.h" #include <QAction> #include <QApplication> #include <QDesktopWidget> //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 OptionManager::OptionManager() : m_browser(0) { } OptionManager::~OptionManager() { if (m_browser) { delete m_browser; } } bool OptionManager::initWithApp(IApplication *app) { if (!IManager::initWithApp(app)) { return false; } return true; } void OptionManager::addFactory(IOptionFactory *factory) { m_factoryList.append(factory); } void OptionManager::removeFactory(IOptionFactory *factory) { m_factoryList.removeOne(factory); } QList<IOptionFactory*> OptionManager::factoryList() const { return m_factoryList; } void OptionManager::emitApplyOption(const QString &mimetype) { emit applyOption(mimetype); } void OptionManager::exec(const QString &mimeType) { if (!m_browser) { m_browser = new OptionsBrowser(m_liteApp,m_liteApp->mainWindow()); QRect rc = qApp->desktop()->screenGeometry(m_browser); int width = rc.width(); if (width > 900) { width = 900; } int height = rc.height(); if (height > 600) { height = 600; } m_browser->resize(width,height); connect(m_browser,SIGNAL(applyOption(QString)),this,SIGNAL(applyOption(QString))); foreach (IOptionFactory *f, m_factoryList) { QStringList mimeTypes = f->mimeTypes(); foreach (QString mimeType, mimeTypes) { IOption *opt = f->create(mimeType); if (opt) { m_browser->addOption(opt); } } } } QString last = m_liteApp->globalCookie().value("optionmanager/current").toString(); if (!mimeType.isEmpty()) { last = mimeType; } m_browser->execute(last); m_liteApp->globalCookie().insert("optionmanager/current",m_browser->currenMimeType()); } void OptionManager::loadOption(const QString &opt) { foreach (IOptionFactory *f, m_factoryList) { QStringList mimeTypes = f->mimeTypes(); foreach (QString mimeType, mimeTypes) { if (opt == mimeType) { emit applyOption(mimeType); } } } }
3,615
C++
.cpp
112
27.482143
90
0.643369
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,576
toolmainwindow.cpp
visualfc_liteide/liteidex/src/liteapp/toolmainwindow.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: toolmainwindow.cpp // Creator: visualfc <visualfc@gmail.com> #include "toolmainwindow.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 ToolMainWindow::ToolMainWindow(QWidget *parent) : QMainWindow(parent), m_windowStyle(0) { } ToolMainWindow::~ToolMainWindow() { if (m_windowStyle) { delete m_windowStyle; } } void ToolMainWindow::setWindowStyle(IWindowStyle *style) { m_windowStyle = style; } void ToolMainWindow::createToolWindowMenu() { m_windowStyle->createToolWindowMenu(); } QAction *ToolMainWindow::findToolWindow(QWidget *widget) { return m_windowStyle->findToolWindow(widget); } QByteArray ToolMainWindow::saveState(int version) const { m_windowStyle->saveToolState(); return QMainWindow::saveState(version); } bool ToolMainWindow::restoreState(const QByteArray &state, int version) { bool b = QMainWindow::restoreState(state,version); m_windowStyle->restoreToolsState(); return b; } void ToolMainWindow::updateConer() { m_windowStyle->updateConer(); } void ToolMainWindow::removeToolWindow(QAction *action) { m_windowStyle->removeToolWindow(action); } QAction *ToolMainWindow::addToolWindow(LiteApi::IApplication *app, Qt::DockWidgetArea area, QWidget *widget, const QString &id, const QString &title, bool split, QList<QAction*> widgetActions, QList<QWidget *> widgetList) { return m_windowStyle->addToolWindow(app,area,widget,id,title,split,widgetActions,widgetList); } void ToolMainWindow::moveToolWindow(Qt::DockWidgetArea from, Qt::DockWidgetArea to, QAction *action, bool split) { m_windowStyle->moveToolWindow(from,to,action,split); } void ToolMainWindow::showOrHideToolWindow() { m_windowStyle->showOrHideToolWindow(); } void ToolMainWindow::hideOutputWindow() { m_windowStyle->hideOutputWindow(); } void ToolMainWindow::hideAllToolWindows() { m_windowStyle->hideAllToolWindows(); }
3,176
C++
.cpp
94
31.5
221
0.728311
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,579
winptyprocess.h
visualfc_liteide/liteidex/src/3rdparty/ptyqt/core/winptyprocess.h
#ifndef WINPTYPROCESS_H #define WINPTYPROCESS_H #include "iptyprocess.h" #define _WIN32_WINNT 0x0501 #include <windows.h> #include <QLocalSocket> #include "winpty.h" class WinPtyProcess : public IPtyProcess { Q_OBJECT public: WinPtyProcess(); virtual ~WinPtyProcess(); virtual bool startProcess(const QString &shellPath, const QStringList &arguments, const QString &workingDirectory, QStringList environment, qint16 cols, qint16 rows); virtual bool resize(qint16 cols, qint16 rows); virtual bool kill(); virtual PtyType type(); virtual QString dumpDebugInfo(); virtual QIODevice *notifier(); virtual QByteArray readAll(); virtual qint64 write(const QByteArray &byteArray); virtual bool isAvailable(); virtual void moveToThread(QThread *targetThread); virtual int processList() const; public slots: void disconnected(); private: winpty_t *m_ptyHandler; HANDLE m_innerHandle; QString m_conInName; QString m_conOutName; QLocalSocket *m_inSocket; QLocalSocket *m_outSocket; bool m_initPty; }; #endif // WINPTYPROCESS_H
1,108
C++
.h
36
27.222222
170
0.753745
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,582
iptyprocess.h
visualfc_liteide/liteidex/src/3rdparty/ptyqt/core/iptyprocess.h
#ifndef IPTYPROCESS_H #define IPTYPROCESS_H #include <QString> #include <QStringList> #include <QDebug> //#ifdef Q_OS_WIN //#include <QLocalSocket> //#endif #define CONPTY_MINIMAL_WINDOWS_VERSION 18309 class IPtyProcess : public QObject { Q_OBJECT public: enum PtyType { UnixPty = 0, WinPty = 1, ConPty = 2, AutoPty = 3 }; IPtyProcess() : m_pid(0) , m_trace(false) { } virtual ~IPtyProcess() { } virtual bool startProcess(const QString &shellPath, const QStringList &arguments, const QString &workingDirectory, QStringList environment, qint16 cols, qint16 rows) = 0; virtual bool resize(qint16 cols, qint16 rows) = 0; virtual bool kill() = 0; virtual PtyType type() = 0; virtual QString dumpDebugInfo() = 0; virtual QIODevice *notifier() = 0; virtual QByteArray readAll() = 0; virtual qint64 write(const QByteArray &byteArray) = 0; virtual bool isAvailable() = 0; virtual void moveToThread(QThread *targetThread) = 0; virtual int processList() const = 0; // 0 - unsupport, 1 - no process , 2 - run process qint64 pid() { return m_pid; } QPair<qint16, qint16> size() { return m_size; } const QString lastError() { return m_lastError; } bool toggleTrace() { m_trace = !m_trace; return m_trace; } signals: void started(); void exited(); protected: QString m_shellPath; QString m_lastError; qint64 m_pid; QPair<qint16, qint16> m_size; //cols / rows bool m_trace; }; #endif // IPTYPROCESS_H
1,558
C++
.h
51
26.196078
174
0.67
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,583
winpty.h
visualfc_liteide/liteidex/src/3rdparty/ptyqt/core/winpty.h
/* * Copyright (c) 2011-2016 Ryan Prichard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #ifndef WINPTY_H #define WINPTY_H #include <windows.h> #include "winpty_constants.h" /* On 32-bit Windows, winpty functions have the default __cdecl (not __stdcall) * calling convention. (64-bit Windows has only a single calling convention.) * When compiled with __declspec(dllexport), with either MinGW or MSVC, the * winpty functions are unadorned--no underscore prefix or '@nn' suffix--so * GetProcAddress can be used easily. */ #define WINPTY_API __cdecl #ifdef __cplusplus extern "C" { #endif /* The winpty API uses wide characters, instead of UTF-8, to avoid conversion * complications related to surrogates. Windows generally tolerates unpaired * surrogates in text, which makes conversion to and from UTF-8 ambiguous and * complicated. (There are different UTF-8 variants that deal with UTF-16 * surrogates differently.) */ /***************************************************************************** * Error handling. */ /* All the APIs have an optional winpty_error_t output parameter. If a * non-NULL argument is specified, then either the API writes NULL to the * value (on success) or writes a newly allocated winpty_error_t object. The * object must be freed using winpty_error_free. */ /* An error object. */ typedef struct winpty_error_s winpty_error_t; typedef winpty_error_t *winpty_error_ptr_t; /* An error code -- one of WINPTY_ERROR_xxx. */ typedef DWORD winpty_result_t; /* The winpty_config_t object is not thread-safe. */ typedef struct winpty_config_s winpty_config_t; /* The winpty_t object is thread-safe. */ typedef struct winpty_s winpty_t; /* The winpty_spawn_config_t object is not thread-safe. */ typedef struct winpty_spawn_config_s winpty_spawn_config_t; /****************************************************************************/ #ifdef __cplusplus } #endif #endif /* WINPTY_H */
3,059
C++
.h
61
47
80
0.710135
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,584
winpty_constants.h
visualfc_liteide/liteidex/src/3rdparty/ptyqt/core/winpty_constants.h
/* * Copyright (c) 2016 Ryan Prichard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #ifndef WINPTY_CONSTANTS_H #define WINPTY_CONSTANTS_H /* * You may want to include winpty.h instead, which includes this header. * * This file is split out from winpty.h so that the agent can access the * winpty flags without also declaring the libwinpty APIs. */ /***************************************************************************** * Error codes. */ #define WINPTY_ERROR_SUCCESS 0 #define WINPTY_ERROR_OUT_OF_MEMORY 1 #define WINPTY_ERROR_SPAWN_CREATE_PROCESS_FAILED 2 #define WINPTY_ERROR_LOST_CONNECTION 3 #define WINPTY_ERROR_AGENT_EXE_MISSING 4 #define WINPTY_ERROR_UNSPECIFIED 5 #define WINPTY_ERROR_AGENT_DIED 6 #define WINPTY_ERROR_AGENT_TIMEOUT 7 #define WINPTY_ERROR_AGENT_CREATION_FAILED 8 /***************************************************************************** * Configuration of a new agent. */ /* Create a new screen buffer (connected to the "conerr" terminal pipe) and * pass it to child processes as the STDERR handle. This flag also prevents * the agent from reopening CONOUT$ when it polls -- regardless of whether the * active screen buffer changes, winpty continues to monitor the original * primary screen buffer. */ #define WINPTY_FLAG_CONERR 0x1ull /* Don't output escape sequences. */ #define WINPTY_FLAG_PLAIN_OUTPUT 0x2ull /* Do output color escape sequences. These escapes are output by default, but * are suppressed with WINPTY_FLAG_PLAIN_OUTPUT. Use this flag to reenable * them. */ #define WINPTY_FLAG_COLOR_ESCAPES 0x4ull /* On XP and Vista, winpty needs to put the hidden console on a desktop in a * service window station so that its polling does not interfere with other * (visible) console windows. To create this desktop, it must change the * process' window station (i.e. SetProcessWindowStation) for the duration of * the winpty_open call. In theory, this change could interfere with the * winpty client (e.g. other threads, spawning children), so winpty by default * spawns a special agent process to create the hidden desktop. Spawning * processes on Windows is slow, though, so if * WINPTY_FLAG_ALLOW_CURPROC_DESKTOP_CREATION is set, winpty changes this * process' window station instead. * See https://github.com/rprichard/winpty/issues/58. */ #define WINPTY_FLAG_ALLOW_CURPROC_DESKTOP_CREATION 0x8ull #define WINPTY_FLAG_MASK (0ull \ | WINPTY_FLAG_CONERR \ | WINPTY_FLAG_PLAIN_OUTPUT \ | WINPTY_FLAG_COLOR_ESCAPES \ | WINPTY_FLAG_ALLOW_CURPROC_DESKTOP_CREATION \ ) /* QuickEdit mode is initially disabled, and the agent does not send mouse * mode sequences to the terminal. If it receives mouse input, though, it * still writes MOUSE_EVENT_RECORD values into CONIN. */ #define WINPTY_MOUSE_MODE_NONE 0 /* QuickEdit mode is initially enabled. As CONIN enters or leaves mouse * input mode (i.e. where ENABLE_MOUSE_INPUT is on and ENABLE_QUICK_EDIT_MODE * is off), the agent enables or disables mouse input on the terminal. * * This is the default mode. */ #define WINPTY_MOUSE_MODE_AUTO 1 /* QuickEdit mode is initially disabled, and the agent enables the terminal's * mouse input mode. It does not disable terminal mouse mode (until exit). */ #define WINPTY_MOUSE_MODE_FORCE 2 /***************************************************************************** * winpty agent RPC call: process creation. */ /* If the spawn is marked "auto-shutdown", then the agent shuts down console * output once the process exits. The agent stops polling for new console * output, and once all pending data has been written to the output pipe, the * agent closes the pipe. (At that point, the pipe may still have data in it, * which the client may read. Once all the data has been read, further reads * return EOF.) */ #define WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN 1ull /* After the agent shuts down output, and after all output has been written * into the pipe(s), exit the agent by closing the console. If there any * surviving processes still attached to the console, they are killed. * * Note: With this flag, an RPC call (e.g. winpty_set_size) issued after the * agent exits will fail with an I/O or dead-agent error. */ #define WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN 2ull /* All the spawn flags. */ #define WINPTY_SPAWN_FLAG_MASK (0ull \ | WINPTY_SPAWN_FLAG_AUTO_SHUTDOWN \ | WINPTY_SPAWN_FLAG_EXIT_AFTER_SHUTDOWN \ ) #endif /* WINPTY_CONSTANTS_H */
5,828
C++
.h
107
51.224299
80
0.695928
visualfc/liteide
7,563
970
395
LGPL-2.1
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
21,586
libucd.h
visualfc_liteide/liteidex/src/3rdparty/libucd/include/libucd.h
/** * @file libucd.h * @brief charset detection functions * @author Yunhui Fu (yhfudev@gmail.com) * @version 1.0 * @date 2015-01-13 * @license GPL 2.0/LGPL 2.1 */ #ifndef __LIBUCD_H #define __LIBUCD_H #define UCD_IMEXPORT //#ifdef _WIN32 //# ifdef DLL_EXPORTS //# define UCD_IMEXPORT extern _declspec(dllexport) //# else //# define UCD_IMEXPORT extern _declspec(dllimport) //# endif //#else //# define UCD_IMEXPORT extern __attribute__ ((visibility("default"))) //#endif #include <stddef.h> #define UCD_RESULT_OK 0 #define UCD_RESULT_NOMEMORY (-1) #define UCD_RESULT_INVALID_DETECTOR (-2) #define UCD_MAX_ENCODING_NAME 64 #ifdef __cplusplus extern "C" { #endif typedef void * ucd_t; /** * Create an encoding detector. * @param pdet [out] pointer to a ucd_t variable that receives * the encoding detector handle. * @return UCD_RESULT_OK if succeeded. UCD_RESULT_NOMEMORY otherwise. */ UCD_IMEXPORT int ucd_init (ucd_t * pdet); /** * Destroy an encoding detector. * @param det [in] the encoding detector handle to be destroyed. */ UCD_IMEXPORT void ucd_clear (ucd_t * det); /** * Feed data to an encoding detector. * @param det [in] the encoding detector handle * @param data [in] data * @param len [in] length of data in bytes. * @return UCD_RESULT_OK if succeeded. * UCD_RESULT_NOMEMORY if running out of memory. * UCD_RESULT_INVALID_DETECTOR if det was invalid. */ UCD_IMEXPORT int ucd_parse (ucd_t * det, const char* data, size_t len); /** * Notify an end of data to an encoding detctor. * @param det [in] the encoding detector handle * @return UCD_RESULT_OK if succeeded. * UCD_RESULT_INVALID_DETECTOR if det was invalid. */ UCD_IMEXPORT int ucd_end (ucd_t * det); /** * Reset an encoding detector. * @param det [in] the encoding detector handle * @return UCD_RESULT_OK if succeeded. * UCD_RESULT_INVALID_DETECTOR if det was invalid. */ UCD_IMEXPORT int ucd_reset (ucd_t * det); /** * Get the name of encoding that was detected. * @param det [in] the encoding detector handle * @param namebuf [in/out] pointer to a buffer that receives the name of * detected encoding. A valid encoding name or an empty string * will be written to namebuf. If an empty strng was written, * the detector could not detect any encoding. * Written strings will always be NULL-terminated. * @param buflen [in] length of namebuf * @return UCD_RESULT_OK if succeeded. * UCD_RESULT_NOMEMORY if namebuf was too small to store * the entire encoding name. * UCD_RESULT_INVALID_DETECTOR if det was invalid. */ UCD_IMEXPORT int ucd_results (ucd_t * det, char* namebuf, size_t buflen); #ifdef __cplusplus }; #endif #endif /* __LIBUCD_H */
2,848
C++
.h
84
32.166667
77
0.683406
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,592
nscore.h
visualfc_liteide/liteidex/src/3rdparty/libucd/src/nscore.h
/** * @file nscore.h * @brief fake nscore.h * @author Yunhui Fu (yhfudev@gmail.com) * @version 1.0 * @date 2015-01-13 * @license GPL 2.0/LGPL 2.1 */ #ifndef __NS_FAKE_CORE_H #define __NS_FAKE_CORE_H #include <stdint.h> #include <stddef.h> typedef bool PRBool; typedef int32_t PRInt32; typedef uint32_t PRUint32; typedef int16_t PRInt16; typedef uint16_t PRUint16; typedef int8_t PRInt8; typedef uint8_t PRUint8; enum nsresult { NS_OK, NS_ERROR_OUT_OF_MEMORY }; #define PR_FALSE false #define PR_TRUE true #define nsnull 0 #define NS_ARRAY_LENGTH(a) (sizeof(a)/sizeof((a)[0])) #endif /* __NS_FAKE_CORE_H */
649
C++
.h
28
21.392857
53
0.697068
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,594
nsDebug.h
visualfc_liteide/liteidex/src/3rdparty/libucd/src/nsDebug.h
/** * @file nsDebug.h * @brief fake nsDebug.h * @author Yunhui Fu (yhfudev@gmail.com) * @version 1.0 * @date 2015-01-13 * @license GPL 2.0/LGPL 2.1 */ #ifndef __NS_FAKE_DEBUG_H #define __NS_FAKE_DEBUG_H #include <assert.h> #define NS_ASSERTION(a,msg) assert(a) #endif /* __NS_FAKE_DEBUG_H */
310
C++
.h
13
22.153846
41
0.650847
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,595
prmem.h
visualfc_liteide/liteidex/src/3rdparty/libucd/src/prmem.h
/** * @file prmem.h * @brief fake prmem.h * @author Yunhui Fu (yhfudev@gmail.com) * @version 1.0 * @date 2015-01-13 * @license GPL 2.0/LGPL 2.1 */ #ifndef __NS_FAKE_PRMEM_H #define __NS_FAKE_PRMEM_H #include <stdlib.h> #define PR_Malloc(length) malloc(length) #define PR_FREEIF(p) do { if (p) free(p); } while(0) #endif /* __NS_FAKE_PRMEM_H */
363
C++
.h
14
24.214286
52
0.644509
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,611
utils_global.h
visualfc_liteide/liteidex/src/3rdparty/qtc_editutil/utils_global.h
#ifndef QTCREATOR_UTILS_GLOBAL_H #define QTCREATOR_UTILS_GLOBAL_H #include <QtCore/qglobal.h> #define QTCREATOR_UTILS_EXPORT /* #if defined(TEXTEDITOR_LIBRARY) # define TEXTEDITOR_EXPORT Q_DECL_EXPORT #else # define TEXTEDITOR_EXPORT Q_DECL_IMPORT #endif */ #endif // QTCREATOR_UTILS_GLOBAL_H
300
C++
.h
12
23.833333
41
0.797203
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,614
gdbmi.h
visualfc_liteide/liteidex/src/3rdparty/qtc_gdbmi/gdbmi.h
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (info@qt.nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at info@qt.nokia.com. ** **************************************************************************/ #ifndef GDBMI_H #define GDBMI_H #include <QByteArray> #include <QList> #include <QVariant> class GdbMiValue { public: GdbMiValue() : m_type(Invalid) {} QByteArray m_name; QByteArray m_data; QList<GdbMiValue> m_children; enum Type { Invalid, Const, Tuple, List }; Type m_type; inline Type type() const { return m_type; } inline QByteArray name() const { return m_name; } inline bool hasName(const char *name) const { return m_name == name; } inline bool isValid() const { return m_type != Invalid; } inline bool isConst() const { return m_type == Const; } inline bool isTuple() const { return m_type == Tuple; } inline bool isList() const { return m_type == List; } inline QByteArray data() const { return m_data; } inline const QList<GdbMiValue> &children() const { return m_children; } inline int childCount() const { return m_children.size(); } const GdbMiValue &childAt(int index) const { return m_children[index]; } GdbMiValue &childAt(int index) { return m_children[index]; } GdbMiValue findChild(const char *name) const; QByteArray toString(bool multiline = false, int indent = 0) const; qulonglong toAddress() const; void fromString(const QByteArray &str); void fromStringMultiple(const QByteArray &str); public: static QByteArray parseCString(const char *&from, const char *to); static QByteArray escapeCString(const QByteArray &ba); static QString escapeCString(const QString &ba); void parseResultOrValue(const char *&from, const char *to); void parseValue(const char *&from, const char *to); void parseTuple(const char *&from, const char *to); void parseTuple_helper(const char *&from, const char *to); void parseList(const char *&from, const char *to); void dumpChildren(QByteArray *str, bool multiline, int indent) const; }; enum GdbResultClass { // "done" | "running" | "connected" | "error" | "exit" GdbResultUnknown, GdbResultDone, GdbResultRunning, GdbResultConnected, GdbResultError, GdbResultExit }; class GdbResponse { public: GdbResponse() : token(-1), resultClass(GdbResultUnknown) {} QByteArray toString() const; static QByteArray stringFromResultClass(GdbResultClass resultClass); int token; GdbResultClass resultClass; GdbMiValue data; QVariant cookie; QByteArray logStreamOutput; QByteArray consoleStreamOutput; }; #endif // GDBMI_H
3,817
C++
.h
102
34
77
0.689394
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,616
interface.h
visualfc_liteide/liteidex/src/3rdparty/qjsonrpc/tests/manual/console/interface.h
/* * Copyright (C) 2012-2013 Matt Broadstone * Contact: http://bitbucket.org/devonit/qjsonrpc * * This file is part of the QJsonRpc Library. * * 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. */ #ifndef QJSONRPCSERVICESCRIPT_H #define QJSONRPCSERVICESCRIPT_H #include <QObject> #include <QVariant> #include <QScriptClass> #include <QScriptable> class QJsonRpcSocket; class QJsonRpcServiceSocketPrototype : public QObject, protected QScriptable { Q_OBJECT public: QJsonRpcServiceSocketPrototype(QObject *parent = 0); ~QJsonRpcServiceSocketPrototype(); public Q_SLOTS: void connectToLocalService(const QString &service); QVariant invokeRemoteMethod(const QString &method, const QVariant &arg1 = QVariant(), const QVariant &arg2 = QVariant(), const QVariant &arg3 = QVariant(), const QVariant &arg4 = QVariant(), const QVariant &arg5 = QVariant(), const QVariant &arg6 = QVariant(), const QVariant &arg7 = QVariant(), const QVariant &arg8 = QVariant(), const QVariant &arg9 = QVariant(), const QVariant &arg10 = QVariant()); private: QJsonRpcSocket *m_socket; }; #endif
1,771
C++
.h
42
35.333333
101
0.68525
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,618
localclient.h
visualfc_liteide/liteidex/src/3rdparty/qjsonrpc/tests/manual/localclient/localclient.h
/* * Copyright (C) 2012-2013 Matt Broadstone * Contact: http://bitbucket.org/devonit/qjsonrpc * * This file is part of the QJsonRpc Library. * * 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. */ #ifndef CLIENT_H #define CLIENT_H #include <QObject> #include "qjsonrpcmessage.h" class QJsonRpcSocket; class LocalClient : public QObject { Q_OBJECT public: LocalClient(QObject *parent = 0); void run(); private Q_SLOTS: void processResponse(); private: QJsonRpcSocket *m_client; }; #endif
985
C++
.h
33
27.606061
69
0.762156
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,620
tcpclient.h
visualfc_liteide/liteidex/src/3rdparty/qjsonrpc/tests/manual/tcpclient/tcpclient.h
/* * Copyright (C) 2012-2013 Matt Broadstone * Contact: http://bitbucket.org/devonit/qjsonrpc * * This file is part of the QJsonRpc Library. * * 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. */ #ifndef TCPCLIENT_H #define TCPCLIENT_H #include <QObject> #include "qjsonrpcmessage.h" class QJsonRpcSocket; class TcpClient : public QObject { Q_OBJECT public: TcpClient(QObject *parent = 0); void run(); private Q_SLOTS: void processResponse(); void processMessage(const QJsonRpcMessage &message); private: QJsonRpcSocket *m_client; }; #endif
1,044
C++
.h
34
28.382353
69
0.76494
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