MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); readSettings(); ui->actionSound->setChecked(settings.soundsenabled); irc = new QIrc(); if (!irc->createSession()) { QMessageBox::critical(this, tr("Error"), tr("Can't create session")); close(); return; } connect(irc, SIGNAL(sigConnected()), this, SLOT(sltConnected())); connect(irc, SIGNAL(sigMessage(QString,QString)), this, SLOT(sltMessage(QString,QString))); connect(irc, SIGNAL(sigChannelJoined(QString,QString)), this, SLOT(sltChannelJoined(QString,QString))); connect(irc, SIGNAL(sigChannelParted(QString,QString,QString)), this, SLOT(sltChannelParted(QString,QString,QString))); connect(irc, SIGNAL(sigChannelNames(QString,QString,QStringList)), this, SLOT(sltChannelNames(QString,QString,QStringList))); connect(irc, SIGNAL(sigChannelMessage(QString,QString,QString)), this, SLOT(sltChannelMessage(QString,QString,QString))); connect(irc, SIGNAL(sigPrivateMessage(QString,QString,QString)), this, SLOT(sltPrivateMessage(QString,QString,QString))); connect(irc, SIGNAL(sigNick(QString,QString)), this, SLOT(sltNick(QString,QString))); connect(irc, SIGNAL(sigNotice(QString,QString,QString)), this, SLOT(sltNotice(QString,QString,QString))); connect(irc, SIGNAL(sigTopic(QString,QString,QString)), this, SLOT(sltTopic(QString,QString,QString))); connect(irc, SIGNAL(sigTopicSet(QString,QString,QString,QString)), this, SLOT(sltTopicSet(QString,QString,QString,QString))); connect(irc, SIGNAL(sigKick(QString,QString,QString)), this, SLOT(sltKick(QString,QString,QString))); connect(irc, SIGNAL(sigQuit(QString,QString)), this, SLOT(sltQuit(QString,QString))); connect(irc, SIGNAL(sigChannelModeChanged(QString,QString,QStringList)), this, SLOT(sltChannelModeChanged(QString,QString,QStringList))); connect(irc, SIGNAL(sigUmode(QString,QString)), this, SLOT(sltUmode(QString,QString))); connect(irc, SIGNAL(sigInvite(QString,QString,QString)), this, SLOT(sltInvite(QString,QString,QString))); connect(irc, SIGNAL(sigCtcpAction(QString,QString,QString)), this, SLOT(sltCtcpAction(QString,QString,QString))); connect(irc, SIGNAL(sigErrorOccured(QString)), this, SLOT(sltErrorOccured(QString))); consolebrowser = new QTextEdit(); consolebrowser->setReadOnly(true); QFont consolefont; if (consolefont.fromString(settings.consolefont)) consolebrowser->setFont(consolefont); if (!settings.hideconsole) consoleindex =ui->tabWidget->insertTab(0, consolebrowser, tr("Console")); setsdlg = 0; usercontextmenu = new QMenu(this); usercontextmenu->addAction(ui->actionPrivateChat); usercontextmenu->addAction(ui->actionInsert_to_editor); QMenu *managementmenu = usercontextmenu->addMenu(tr("Management")); managementmenu->addAction(ui->actionKick); managementmenu->addAction(ui->actionBan); managementmenu->addAction(ui->actionKickBan); managementmenu->addSeparator(); managementmenu->addAction(ui->actionOp); managementmenu->addAction(ui->actionDeOp); managementmenu->addSeparator(); managementmenu->addAction(ui->actionVoice); managementmenu->addAction(ui->actiondeVoice); connect(ui->treeWidget, SIGNAL(userContextMenu(QPoint)), this, SLOT(userContextMenuRequested(QPoint))); channelcontextmenu = new QMenu(this); channelcontextmenu->addAction(ui->actionLeave_channel); channelcontextmenu->addAction(ui->actionChannel_settings); connect(ui->treeWidget, SIGNAL(channelContextMenu(QPoint)), this, SLOT(channelContextMenuRequested(QPoint))); channelsettingsdialog = 0; trayicon = 0; traymenu = 0; setTrayIcon(settings.trayicon); connect(ui->actionChannel_settings, SIGNAL(triggered()), this, SLOT(channelSettingsPressed())); //smile menu smilemenu = new QMenu(this); smilewidgetaction = new QWidgetAction(smilemenu); smilebar = new SmileBar(); smilewidgetaction->setDefaultWidget(smilebar); smilemenu->addAction(smilewidgetaction); connect(smilebar, SIGNAL(smileClicked(QString)), ui->plainTextEditMessage, SLOT(insertPlainText(QString))); connect(smilebar, SIGNAL(smileClicked(QString)), ui->plainTextEditMessage, SLOT(setFocus())); ui->actionEmoticons->setMenu(smilemenu); smilebutton = new QToolButton(); smilebutton->setDefaultAction(ui->actionEmoticons); smilebutton->setPopupMode(QToolButton::InstantPopup); ui->mainToolBar->addWidget(smilebutton); channellistdialog = new ChannelListDialog(); connect(irc, SIGNAL(sigChannelListStart()), channellistdialog, SLOT(showAndClear())); connect(irc, SIGNAL(sigChannelListAddItem(QString,QString,QString)), channellistdialog, SLOT(addListItem(QString,QString,QString))); connect(irc, SIGNAL(sigChannelListEnd()), channellistdialog, SLOT(endOfList())); connect(channellistdialog, SIGNAL(channelDoubleClicked(QString)), irc, SLOT(joinChannel(QString))); connect(ui->pushButtonSend, SIGNAL(clicked()), ui->plainTextEditMessage, SIGNAL(sendKeyPressed())); connect(ui->plainTextEditMessage, SIGNAL(sendKeyPressed()), this, SLOT(sendPressed())); connect(ui->actionConnect, SIGNAL(triggered()), this, SLOT(connectPressed())); connect(ui->actionDisconnect, SIGNAL(triggered()), this, SLOT(disconnectPressed())); connect(ui->actionSettings, SIGNAL(triggered()), this, SLOT(settingsPressed())); connect(ui->actionJoin, SIGNAL(triggered()), this, SLOT(joinPressed())); connect(ui->treeWidget, SIGNAL(userDoubleClicked(QString)), this, SLOT(userDoubleClicked(QString))); connect(ui->actionPrivateChat, SIGNAL(triggered()), this, SLOT(privateChatPressed())); connect(ui->actionLeave_channel, SIGNAL(triggered()), this, SLOT(leaveChannelPressed())); connect(ui->actionKick, SIGNAL(triggered()), this, SLOT(kickPressed())); connect(ui->actionBan, SIGNAL(triggered()), this, SLOT(BanPressed())); connect(ui->actionKickBan, SIGNAL(triggered()), this, SLOT(kickBanPressed())); connect(ui->actionOp, SIGNAL(triggered()), this, SLOT(opPressed())); connect(ui->actionDeOp, SIGNAL(triggered()), this, SLOT(deOpPressed())); connect(ui->actionVoice, SIGNAL(triggered()), this, SLOT(voicePressed())); connect(ui->actiondeVoice, SIGNAL(triggered()), this, SLOT(devoicePressed())); connect(ui->pushButtonNick, SIGNAL(clicked()), this, SLOT(nickButtonPressed())); connect(ui->actionList_of_channels, SIGNAL(triggered()), irc, SLOT(getChannelsList())); connect(ui->actionAbout_Qt, SIGNAL(triggered()), qApp, SLOT(aboutQt())); connect(ui->tabWidget, SIGNAL(tabCloseRequested(int)), this, SLOT(tabCloseRequested(int))); connect(ui->actionInsert_to_editor, SIGNAL(triggered()), this, SLOT(insertUserToEditorPressed())); connect(ui->actionShowHide, SIGNAL(triggered()), this, SLOT(trayIconActivated())); connect(ui->actionQuit_program, SIGNAL(triggered()), this, SLOT(quitProgram())); connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(aboutPressed())); connect(ui->actionSound, SIGNAL(toggled(bool)), this, SLOT(soundActionToogled(bool))); }
/** * @brief Returns html rendered markdown of the note text * @param notesPath for transforming relative local urls to absolute ones * @return */ QString Note::toMarkdownHtml(QString notesPath) { hoedown_renderer *renderer = hoedown_html_renderer_new(HOEDOWN_HTML_USE_XHTML, 16); hoedown_extensions extensions = (hoedown_extensions) (HOEDOWN_EXT_BLOCK | HOEDOWN_EXT_SPAN); hoedown_document *document = hoedown_document_new(renderer, extensions, 16); // get the decrypted note text (or the normal note text if there isn't any) QString str = getDecryptedNoteText(); QString windowsSlash = ""; #ifdef Q_OS_WIN32 // we need an other slash for Windows windowsSlash = "/"; #endif // parse for relative file urls and make them absolute // (for example to show images under the note path) str.replace( QRegularExpression("\\(file:\\/\\/([^\\/].+)\\)"), "(file://" + windowsSlash + notesPath + "/\\1)"); unsigned char *sequence = (unsigned char *) qstrdup( str.toUtf8().constData()); qint64 length = strlen((char *) sequence); // return an empty string if the note is empty if (length == 0) { return ""; } hoedown_buffer *html = hoedown_buffer_new(length); // render markdown html hoedown_document_render(document, html, sequence, length); // get markdown html QString result = QString::fromUtf8((char *) html->data, html->size); /* Cleanup */ free(sequence); hoedown_buffer_free(html); hoedown_document_free(document); hoedown_html_renderer_free(renderer); QSettings(settings); QString fontString = settings.value("MainWindow/noteTextView.code.font") .toString(); // set the stylesheet for the <code> blocks QString codeStyleSheet = ""; if (fontString != "") { // set the note text view font QFont font; font.fromString(fontString); codeStyleSheet = "pre, code {" + encodeCssFont(font) + "}"; } result = "<html><head>" "<style>h1, h2, h3 { margin: 5pt 0 10pt 0; }" "a { color: #FF9137; text-decoration: none; }" + codeStyleSheet + "</style></head><body>" + result + "</body></html>"; // check if width of embedded local images is too high QRegularExpression re("<img src=\"file:\\/\\/([^\"]+)\""); QRegularExpressionMatchIterator i = re.globalMatch(result); while (i.hasNext()) { QRegularExpressionMatch match = i.next(); QString fileName = match.captured(1); QImage image(fileName); // cap the image width at 980px if (image.width() > 980) { result.replace( QRegularExpression("<img src=\"file:\\/\\/" + QRegularExpression::escape(fileName) + "\""), "<img width=\"980\" src=\"file://" + fileName + "\""); } } return result; }
QVariant FunctionListModel::data (const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); TreeList *item_p = static_cast<TreeList*>(index.internalPointer()); { bool ok; item_p->data(ITEM_NB_UNTESTED).toInt(&ok); if (!ok) { generateStatistics(item_p); } } switch (role) { default: return QVariant(); case FilterRole: { bool ok=false; CSMes::modifications_t modif=CSMes::MODIFICATIONS_UNDEFINED; int diff=item_p->data(ITEM_DIFFERENCE).toInt(&ok); if (ok) modif=static_cast<CSMes::modifications_t >(diff); else item_p->setData(ITEM_DIFFERENCE,static_cast<int>(modif=compareCSMesFunction(item_p))); switch (modif) { case CSMes::DIFFERENT: if (!filter_different) return true; break; case CSMes::NOT_EXISTING: if (!filter_not_existing) return true; break; case CSMes::NEW: if (!filter_new) return true; break; case CSMes::SAME_EXCEPT_WHITE_SPACES: if (!filter_different_indentation) return true; break; case CSMes::SAME_EXCEPT_COMMENT: if (!filter_different_comment) return true; break; case CSMes::SAME: if (!filter_same) return true; break; case CSMes::NOTHING_TO_COMPARE: case CSMes::MODIFICATIONS_UNDEFINED: break; } } return false; case SearchTextRole: return functionName(item_p,true); case Qt::BackgroundColorRole: { if (CoverageSettings::object().getExecutionAnalysisMode()) return QVariant(); double medium,low; if (item_p->data(ITEM_FUNCTION).toBool()) { medium=function_medium_level; low=function_low_level; } else { medium=class_medium_level; low=class_low_level; } bool ok; int nb_untested=item_p->data(ITEM_NB_UNTESTED).toInt(&ok); if (!ok) return QVariant(); int nb_tested=item_p->data(ITEM_NB_TESTED).toInt(&ok); if (!ok) return QVariant(); if (nb_tested>=0 && nb_untested>=0 && nb_tested+nb_untested>0) { double stat=static_cast<double>(nb_tested)/static_cast<double>(nb_tested+nb_untested)*100.0; if (stat<low) return COL_RED; if (stat<medium) return COL_ORANGE; return COL_GREEN; } return QVariant(); } case Qt::ToolTipRole: { if (!Options::get_opt_bool(QString(),"TOOLTIP_METHOD_LIST",DEF_TOOLTIP_METHOD_LIST)) return QVariant(); QString tooltip="<body><html>"; tooltip+=tr("<u><I>Name:</I></U> <TT>%1</TT>").arg(Qt::escape(item_p->data(ITEM_NAME).toString())); if (item_p->data(ITEM_DESCRIPTION).toString()!=QString()) tooltip+=tr("<BR><u><I>Prototype:</I></U> <TT>%1</TT>").arg(Qt::escape(item_p->data(ITEM_DESCRIPTION).toString())); bool ok; int nb_untested=item_p->data(ITEM_NB_UNTESTED).toInt(&ok); if (!ok) return QVariant(); int nb_tested=item_p->data(ITEM_NB_TESTED).toInt(&ok); if (!ok) return QVariant(); if (nb_tested+nb_untested>0) tooltip+=tr("<BR><U><I>Coverage:</I></U> %1").arg(Qt::escape(CSMesUndoRedoFramework::printStat(nb_tested,nb_untested))); if (item_p->data(ITEM_FILE_NAME).toString()!=QString()) { tooltip+=tr("<BR><u><I>Relative File Name:</I></u> <TT>%1</TT>").arg(Qt::escape(csmes_p->relativeSourceName(item_p->data(ITEM_FILE_NAME).toString()))); tooltip+=tr("<BR><u><I>Absolute File Name:</u> <TT>%1</TT>").arg(Qt::escape(item_p->data(ITEM_FILE_NAME).toString())); tooltip+=tr("<BR><u><I>Lines:</u> <TT>%1-%2</TT>") .arg(Qt::escape(item_p->data(ITEM_START_LINE).toString())) .arg(Qt::escape(item_p->data(ITEM_END_LINE).toString())); } if (item_p->data(ITEM_FILE_NAME_REF).toString()!=QString()) { tooltip+=tr("<BR><u><I>Relative File Name (reference):</I></u> <TT>%1</TT>").arg(Qt::escape(csmes_p->relativeSourceName(item_p->data(ITEM_FILE_NAME_REF).toString()))); tooltip+=tr("<BR><u><I>Absolute File Name (reference):</u> <TT>%1</TT>").arg(Qt::escape(item_p->data(ITEM_FILE_NAME_REF).toString())); tooltip+=tr("<BR><u><I>Lines (reference):</u> <TT>%1-%2</TT>") .arg(Qt::escape(item_p->data(ITEM_START_LINE_REF).toString())) .arg(Qt::escape(item_p->data(ITEM_END_LINE_REF).toString())); } CSMes::modifications_t modif=CSMes::MODIFICATIONS_UNDEFINED; int diff=item_p->data(ITEM_DIFFERENCE).toInt(&ok); if (ok) modif=static_cast<CSMes::modifications_t >(diff); else item_p->setData(ITEM_DIFFERENCE,static_cast<int>(modif=compareCSMesFunction(item_p))); if (modif!=CSMes::MODIFICATIONS_UNDEFINED && modif!=CSMes::NOTHING_TO_COMPARE) tooltip+=tr("<BR><u><I>Comparaison:</u> <TT>%1</TT>").arg( Qt::escape(CSMes::modificationsToString(modif))); tooltip+="</body></html>"; return tooltip; } case Qt::FontRole: { QFont f; switch (index.column()) { case FUNCTION_LIST_COLUMN_STATISTIC: f.fromString(Options::get_opt_str(QString(),"FONT_SOURCE_CODE",DEF_FONT_SOURCE_CODE)); break; default: f=QApplication::font(); break; } bool ok=false; CSMes::modifications_t modif=CSMes::MODIFICATIONS_UNDEFINED; int diff=item_p->data(ITEM_DIFFERENCE).toInt(&ok); if (ok) modif=static_cast<CSMes::modifications_t >(diff); else item_p->setData(ITEM_DIFFERENCE,static_cast<int>(modif=compareCSMesFunction(item_p))); switch (modif) { case CSMes::DIFFERENT: f.setBold(true); break; case CSMes::NOT_EXISTING: f.setBold(true); f.setStrikeOut(true); break; case CSMes::NEW: f.setBold(true); f.setUnderline(true); break; case CSMes::SAME_EXCEPT_WHITE_SPACES: case CSMes::SAME_EXCEPT_COMMENT: case CSMes::SAME: case CSMes::NOTHING_TO_COMPARE: case CSMes::MODIFICATIONS_UNDEFINED: break; } return f; } case Qt::StatusTipRole: return item_p->data(ITEM_DESCRIPTION); case Qt::DisplayRole: switch (index.column()) { case FUNCTION_LIST_COLUMN_STATISTIC: { bool ok; int nb_untested=item_p->data(ITEM_NB_UNTESTED).toInt(&ok); if (!ok) return QVariant(); int nb_tested=item_p->data(ITEM_NB_TESTED).toInt(&ok); if (!ok) return QVariant(); return CSMesUndoRedoFramework::printStat(nb_tested,nb_untested); } case FUNCTION_LIST_COLUMN_NAME: return item_p->data(ITEM_NAME); case FUNCTION_LIST_COLUMN_ABSOLUTE_FILE_NAME: return item_p->data(ITEM_FILE_NAME); case FUNCTION_LIST_COLUMN_FILE_NAME: { QFileInfo fileInfo(item_p->data(ITEM_FILE_NAME).toString()); return fileInfo.fileName(); } case FUNCTION_LIST_COLUMN_POSITION: { int start_line, end_line; if (CoverageSettings::object().getSourceType()==CSMesUndoRedoFramework::CSMES) { start_line=item_p->data(ITEM_START_LINE).toInt(); end_line=item_p->data(ITEM_END_LINE).toInt(); } else { start_line=item_p->data(ITEM_START_LINE_ORIG).toInt(); end_line=item_p->data(ITEM_END_LINE_ORIG).toInt(); } if (start_line<0 || end_line<0) return QVariant(); QString position; if (start_line==end_line) position=QString::number(start_line); else position=QString::number(start_line)+"-"+QString::number(end_line); return position; } case FUNCTION_LIST_COLUMN_DESCRIPTION: return item_p->data(ITEM_DESCRIPTION); case FUNCTION_LIST_COLUMN_ABSOLUTE_FILE_NAME_REF: return item_p->data(ITEM_FILE_NAME_REF); case FUNCTION_LIST_COLUMN_FILE_NAME_REF: { QFileInfo fileInfo(item_p->data(ITEM_FILE_NAME_REF).toString()); return fileInfo.fileName(); } case FUNCTION_LIST_COLUMN_POSITION_REF: { int start_line=item_p->data(ITEM_START_LINE_REF).toInt(); int end_line=item_p->data(ITEM_END_LINE_REF).toInt(); if (start_line<0 || end_line<0) return QVariant(); QString position; if (start_line==end_line) position=QString::number(start_line); else position=QString::number(start_line)+"-"+QString::number(end_line); return position; } case FUNCTION_LIST_COLUMN_DIFFERENCE: { bool ok; CSMes::modifications_t modif=CSMes::MODIFICATIONS_UNDEFINED; int diff=item_p->data(ITEM_DIFFERENCE).toInt(&ok); if (ok) modif=static_cast<CSMes::modifications_t >(diff); else item_p->setData(ITEM_DIFFERENCE,static_cast<int>(modif=compareCSMesFunction(item_p))); return CSMes::modificationsToString(modif); } default: return QVariant(); } } return QVariant(); }
void VCButton::createContents(QPtrList <QString> &list) { QRect rect(30, 30, 30, 30); for (QString* s = list.next(); s != NULL; s = list.next()) { if (*s == QString("Entry")) { s = list.prev(); break; } else if (*s == QString("Name")) { setCaption(*(list.next())); } else if (*s == QString("Parent")) { VCFrame* parent = _app->virtualConsole()->getFrame(list.next()->toInt()); if (parent != NULL) { reparent((QWidget*)parent, 0, QPoint(0, 0), true); } } else if (*s == QString("X")) { rect.setX(list.next()->toInt()); } else if (*s == QString("Y")) { rect.setY(list.next()->toInt()); } else if (*s == QString("Width")) { rect.setWidth(list.next()->toInt()); } else if (*s == QString("Height")) { rect.setHeight(list.next()->toInt()); } else if (*s == QString("Textcolor")) { QColor qc; qc.setRgb(list.next()->toUInt()); setPaletteForegroundColor(qc); } else if (*s == QString("Backgroundcolor")) { QColor qc; qc.setRgb(list.next()->toUInt()); setPaletteBackgroundColor(qc); } else if (*s == QString("Color")) { // Backwards compatibility for button background color QString t = *(list.next()); int i = t.find(QString(",")); int r = t.left(i).toInt(); int j = t.find(QString(","), i + 1); int g = t.mid(i+1, j-i-1).toInt(); int b = t.mid(j+1).toInt(); QColor qc(r, g, b); setPaletteBackgroundColor(qc); } else if (*s == QString("Pixmap")) { QString t; t = *(list.next()); QPixmap pm(t); if (pm.isNull() == false) { setIconText(t); setPaletteBackgroundPixmap(pm); } } else if (*s == QString("Font")) { QFont f = font(); QString q = *(list.next()); f.fromString(q); setFont(f); } else if (*s == QString("Function")) { attachFunction(list.next()->toInt()); } else if (*s == QString("BindKey")) { assert(m_keyBind); QString t = *(list.next()); m_keyBind->setKey(t.toInt()); } else if (*s == QString("BindMod")) { assert(m_keyBind); QString t = *(list.next()); m_keyBind->setMod(t.toInt()); } else if (*s == QString("BindPress")) { assert(m_keyBind); QString t = *(list.next()); m_keyBind->setPressAction((KeyBind::PressAction) t.toInt()); } else if (*s == QString("BindRelease")) { assert(m_keyBind); QString t = *(list.next()); m_keyBind->setReleaseAction((KeyBind::ReleaseAction) t.toInt()); } else { // Unknown keyword, ignore *list.next(); } } setGeometry(rect); }
void TextRoom::readSettings() { QFile file( settings->fileName() ); if ( !file.exists() ) { toggleFullScreen(); writeSettings(); return; } if ( settings->value("WindowState/ShowFullScreen", true).toBool() ) { if ( !isFullScreen() ) showFullScreen(); } else { showNormal(); QPoint pos = settings->value("WindowState/TopLeftPosition", QPoint(100, 100)).toPoint(); QSize size = settings->value("WindowState/WindowSize", QSize(300, 200)).toSize(); resize(size); move(pos); } QString foregroundColor = settings->value("Colors/FontColor", "#808080" ).toString(); QString back = settings->value("Colors/Background", "#000000" ).toString(); QString status_c = settings->value("Colors/StatusColor", "#202020" ).toString(); // oxygen does weird stuff with the background QApplication::setStyle("plastique"); QFont font; font.fromString( settings->value("StatusFont").toString()); defaultFont.fromString( settings->value("DefaultFont").toString() ); statsLabel->setFont( font ); deadlineLabel->setFont ( font ) ; curDir = settings->value("RecentFiles/LastDir", curDir).toString(); lastSearch = settings->value("TextSearch/LastPhrase", lastSearch).toString(); QDateTime today = QDateTime::currentDateTime(); QString todaytext = today.toString("yyyyMMdd"); // Read all the settings-> isAutoSave = settings->value("AutoSave", false).toBool(); isFlowMode = settings->value("FlowMode", false).toBool(); isSound = settings->value("Sound", true).toBool(); isPageCount = settings->value("PageCount", false).toBool(); isCharacterCount = settings->value("CharacterCount", false).toBool(); deadlinetext = settings->value("Deadline", todaytext).toString(); deadline = QDate::fromString(deadlinetext, "yyyyMMdd"); wordcount = settings->value("WordCount", 0).toInt(); editorWidth = settings->value("EditorWidth", 800).toInt(); editorTopSpace = settings->value("EditorTopSpace", 0).toInt(); editorBottomSpace = settings->value("EditorBottomSpace", 0).toInt(); alarm = settings->value("TimedWriting", 0).toInt(); pageCountFormula = settings->value("PageCountFormula", 250).toInt(); dateFormat = settings->value("DateFormat", "d MMMM yyyy dddd").toString(); timeFormatBool = settings->value("24-Hour", true ).toBool(); defaultDir = settings->value("DefaultDirectory", QDir::homePath()).toString(); backgroundImage = settings->value("BackgroundImage", "").toString(); isPlainText = settings->value("PlainText", false).toBool(); language = settings->value("LanguageName", "en_US").toString(); indentValue = settings->value("Indent", 50).toInt(); paragraphSpacing = settings->value("ParagraphSpacing", 20).toInt(); tabStopWidth = settings->value("TabStopWidth", 80).toInt(); cursorWidth = settings->value("CursorWidth", 3).toInt(); textEdit->setLayoutDirection(Qt::LayoutDirectionAuto); textEdit->setTabStopWidth(tabStopWidth); textEdit->setCursorWidth(cursorWidth); loadStyleSheet(foregroundColor, back, status_c); textEdit->setMaximumWidth(editorWidth); textEdit->document()->blockSignals(true); bool modified = textEdit->document()->isModified(); if ( isPlainText ) { QString text( textEdit->document()->toPlainText() ); textEdit->document()->clear(); textEdit->insertPlainText(text); textEdit->setAcceptRichText( false ); } else { textEdit->setAcceptRichText( true ); } indentLines(indentValue); setWindowModified(modified); textEdit->document()->setModified(modified); textEdit->document()->blockSignals(false); if ( timeFormatBool ) { timeFormat = "h:mm"; } else { timeFormat = "h:mm AP"; } horizontalSlider->setVisible( settings->value("ScrollBar", true).toBool() ); isScrollBarVisible = horizontalSlider->isVisible(); vPositionChanged(); topSpacer->changeSize(20, editorTopSpace, QSizePolicy::Maximum, QSizePolicy::Maximum); bottomSpacer->changeSize(20, editorBottomSpace, QSizePolicy::Maximum, QSizePolicy::Maximum); timeOut = alarm * 60000; if (alarm != 0) { QTimer::singleShot(timeOut, this, SLOT(alarmTime())); } if ( (optOpenLastFile = settings->value("RecentFiles/OpenLastFile", true).toBool()) ) { curFile = settings->value("RecentFiles/LastFile", curFile).toString(); if ( (isSaveCursor = settings->value("RecentFiles/SavePosition", true).toBool() )) cPosition = settings->value("RecentFiles/AtPosition", cPosition).toInt(); } wordCountChanged = true; getFileStatus(); sCursor(); }
void ChangeProperties::on_buttonSet_clicked() { QTreeWidgetItem *item = listProperties->currentItem(); if (!item) return; QString prop = item->text(0); QVariant value = activex->property(prop.toLatin1()); QVariant::Type type = value.type(); if (!value.isValid()) { const QMetaObject *mo = activex->metaObject(); const QMetaProperty property = mo->property(mo->indexOfProperty(prop.toLatin1())); type = QVariant::nameToType(property.typeName()); } switch (type) { case QVariant::Color: { QColor col; col.setNamedColor(editValue->text()); if (col.isValid()) { value = QVariant::fromValue(col); } else { QMessageBox::warning(this, tr("Can't parse input"), tr("Failed to create a color from %1\n" "The string has to be a valid color name (e.g. 'red')\n" "or a RGB triple of format '#rrggbb'." ).arg(editValue->text())); } } break; case QVariant::Font: { QFont fnt; if (fnt.fromString(editValue->text())) { value = QVariant::fromValue(fnt); } else { QMessageBox::warning(this, tr("Can't parse input"), tr("Failed to create a font from %1\n" "The string has to have a format family,<point size> or\n" "family,pointsize,stylehint,weight,italic,underline,strikeout,fixedpitch,rawmode." ).arg(editValue->text())); } } break; case QVariant::Pixmap: { QString fileName = editValue->text(); if (fileName.isEmpty()) fileName = QFileDialog::getOpenFileName(this); QPixmap pm(fileName); if (pm.isNull()) return; value = QVariant::fromValue(pm); } break; case QVariant::Bool: { QString txt = editValue->text().toLower(); value = QVariant(txt != QLatin1String("0") && txt != QLatin1String("false")); } break; case QVariant::List: { QStringList txtList = editValue->text().split(QRegExp(QLatin1String("[,;]"))); QList<QVariant> varList; for (int i = 0; i < txtList.count(); ++i) { QVariant svar(txtList.at(i)); QString str = svar.toString(); str = str.trimmed(); bool ok; int n = str.toInt(&ok); if (ok) { varList << n; continue; } double d = str.toDouble(&ok); if (ok) { varList << d; continue; } varList << str; } value = varList; } break; default: value = editValue->text(); break; } Q_ASSERT(activex->setProperty(prop.toLatin1(), value)); updateProperties(); listProperties->setCurrentItem(listProperties->findItems(prop, Qt::MatchExactly).at(0)); }
QFont KConfigBase::readFontEntry(const char *pKey, const QFont *pDefault) const { QFont aRetFont; QString aValue = readEntry(pKey); if(!aValue.isNull()) { if(aValue.contains(',') > 5) { // KDE3 and upwards entry if(!aRetFont.fromString(aValue) && pDefault) aRetFont = *pDefault; } else { // backward compatibility with older font formats // ### remove KDE 3.1 ? // find first part (font family) int nIndex = aValue.find(','); if(nIndex == -1) { if(pDefault) aRetFont = *pDefault; return aRetFont; } aRetFont.setFamily(aValue.left(nIndex)); // find second part (point size) int nOldIndex = nIndex; nIndex = aValue.find(',', nOldIndex + 1); if(nIndex == -1) { if(pDefault) aRetFont = *pDefault; return aRetFont; } aRetFont.setPointSize(aValue.mid(nOldIndex + 1, nIndex - nOldIndex - 1).toInt()); // find third part (style hint) nOldIndex = nIndex; nIndex = aValue.find(',', nOldIndex + 1); if(nIndex == -1) { if(pDefault) aRetFont = *pDefault; return aRetFont; } aRetFont.setStyleHint((QFont::StyleHint)aValue.mid(nOldIndex + 1, nIndex - nOldIndex - 1).toUInt()); // find fourth part (char set) nOldIndex = nIndex; nIndex = aValue.find(',', nOldIndex + 1); if(nIndex == -1) { if(pDefault) aRetFont = *pDefault; return aRetFont; } QString chStr = aValue.mid(nOldIndex + 1, nIndex - nOldIndex - 1); // find fifth part (weight) nOldIndex = nIndex; nIndex = aValue.find(',', nOldIndex + 1); if(nIndex == -1) { if(pDefault) aRetFont = *pDefault; return aRetFont; } aRetFont.setWeight(aValue.mid(nOldIndex + 1, nIndex - nOldIndex - 1).toUInt()); // find sixth part (font bits) uint nFontBits = aValue.right(aValue.length() - nIndex - 1).toUInt(); aRetFont.setItalic(nFontBits & 0x01); aRetFont.setUnderline(nFontBits & 0x02); aRetFont.setStrikeOut(nFontBits & 0x04); aRetFont.setFixedPitch(nFontBits & 0x08); aRetFont.setRawMode(nFontBits & 0x20); } } else { if(pDefault) aRetFont = *pDefault; } return aRetFont; }
void UIOptions::loadOptions() { if ( Options::self()->value( "Options/FirstTimeSetting", true ).toBool() ) Options::setDefaultOptions(); // QFont myFont; QPalette myPalette; QColor myColor; QString myFontFamily = qApp->font().toString(); QStringList myList; // General // Project cbReloadLastProject->setChecked( Options::self()->value( "Options/General/ReloadLastProject" ).toBool() ); cbReloadLastProjectFiles->setChecked( Options::self()->value( "Options/General/ReloadLastProjectFiles" ).toBool() ); cbSaveBeforeBuilding->setChecked( Options::self()->value( "Options/General/SaveBeforeBuilding" ).toBool() ); cbShowHeaderInformations->setChecked( Options::self()->value( "Options/General/ShowHeaderInformations" ).toBool() ); cbCreateBackup->setChecked( Options::self()->value( "Options/General/CreateBackup" ).toBool() ); // Path cbPath->setItemData( 0, Options::self()->value( "Options/General/MingwPath" ).toString() ); cbPath->setItemData( 1, Options::self()->value( "Options/General/QtPath" ).toString() ); cbPath->setItemData( 2, Options::self()->value( "Options/General/TranslationsPath" ).toString() ); cbPath->setItemData( 3, Options::self()->value( "Options/General/DocumentationsPath" ).toString() ); cbPath->setItemData( 4, Options::self()->value( "Options/General/TemplatesPath" ).toString() ); cbPath->setItemData( 5, Options::self()->value( "Options/General/PdfViewer" ).toString() ); cbPath->setItemData( 6, Options::self()->value( "Options/General/WebBrowser" ).toString() ); on_cbPath_currentIndexChanged( 0 ); // Others cbShowQtWarnings->setChecked( Options::self()->value( "Options/General/ShowQtWarnings" ).toBool() ); // Editor // Editor if ( !myFont.fromString( Options::self()->value( "Options/Editor/TextFont" ).toString() ) ) myFont = qApp->font(); leTextFontPreview->setFont( myFont ); leTextFontPreview->setText( myFont.family() ); lTextForegroundColorPreview->setText( Options::self()->value( "Options/Editor/TextForegroundColor" ).toString() ); lTextBackgroundColorPreview->setText( Options::self()->value( "Options/Editor/TextBackgroundColor" ).toString() ); lTextSelectionColorPreview->setText( Options::self()->value( "Options/Editor/TextSelectionColor" ).toString() ); sbTextTabSpacing->setValue( Options::self()->value( "Options/Editor/TextTabSpacing" ).toInt() ); sbTextScrollLines->setValue( Options::self()->value( "Options/Editor/TextScrollLines" ).toInt() ); sbLimitLine->setValue( Options::self()->value( "Options/Editor/LimitLine" ).toInt() ); lLimitLineColorPreview->setText( Options::self()->value( "Options/Editor/LimitLineColor" ).toString() ); lCurrentLineColorPreview->setText( Options::self()->value( "Options/Editor/CurrentLineColor" ).toString() ); cbSourceShowingMethod->setCurrentIndex( Options::self()->value( "Options/Editor/SourceShowingMethod" ).toInt() ); cbSourceIndentationMethod->setCurrentIndex( Options::self()->value( "Options/Editor/SourceIndentationMethod" ).toInt() ); cbPrintingColor->setChecked( Options::self()->value( "Options/Editor/PrintingColor" ).toBool() ); cbPrintingLineNumbers->setChecked( Options::self()->value( "Options/Editor/PrintingLineNumbers" ).toBool() ); cbHighlightCurrentLine->setChecked( Options::self()->value( "Options/Editor/HighlightCurrentLine" ).toBool() ); cbActivateAutoCompletion->setChecked( Options::self()->value( "Options/Editor/activateAutoCompletion" ).toBool() ); cbActivateParentheseMatcher->setChecked( Options::self()->value( "Options/Editor/activateParentheseMatcher" ).toBool() ); // Color Scheme myFont = qApp->font(); // myList = Options::self()->value( "Options/Editor/Number" ).toStringList(); myFont.fromString( myList.at( 0 ) ); lColorSchemePreview1->setFont( myFont ); lColorSchemePreview1->setText( myFont.family() ); myPalette = lColorSchemePreview1->palette(); myColor = QColor( myList.at( 1 ) ); if ( myColor.isValid() ) myPalette.setColor( QPalette::Button, myColor ); myColor = QColor( myList.at( 2 ) ); if ( myColor.isValid() ) myPalette.setColor( QPalette::ButtonText, myColor ); lColorSchemePreview1->setPalette( myPalette ); // myList = Options::self()->value( "Options/Editor/String" ).toStringList(); myFont.fromString( myList.at( 0 ) ); lColorSchemePreview2->setFont( myFont ); lColorSchemePreview2->setText( myFont.family() ); myPalette = lColorSchemePreview2->palette(); myColor = QColor( myList.at( 1 ) ); if ( myColor.isValid() ) myPalette.setColor( QPalette::Button, myColor ); myColor = QColor( myList.at( 2 ) ); if ( myColor.isValid() ) myPalette.setColor( QPalette::ButtonText, myColor ); lColorSchemePreview2->setPalette( myPalette ); // myList = Options::self()->value( "Options/Editor/Type" ).toStringList(); myFont.fromString( myList.at( 0 ) ); lColorSchemePreview3->setFont( myFont ); lColorSchemePreview3->setText( myFont.family() ); myPalette = lColorSchemePreview3->palette(); myColor = QColor( myList.at( 1 ) ); if ( myColor.isValid() ) myPalette.setColor( QPalette::Button, myColor ); myColor = QColor( myList.at( 2 ) ); if ( myColor.isValid() ) myPalette.setColor( QPalette::ButtonText, myColor ); lColorSchemePreview3->setPalette( myPalette ); // myList = Options::self()->value( "Options/Editor/Keyword" ).toStringList(); myFont.fromString( myList.at( 0 ) ); lColorSchemePreview4->setFont( myFont ); lColorSchemePreview4->setText( myFont.family() ); myPalette = lColorSchemePreview4->palette(); myColor = QColor( myList.at( 1 ) ); if ( myColor.isValid() ) myPalette.setColor( QPalette::Button, myColor ); myColor = QColor( myList.at( 2 ) ); if ( myColor.isValid() ) myPalette.setColor( QPalette::ButtonText, myColor ); lColorSchemePreview4->setPalette( myPalette ); // myList = Options::self()->value( "Options/Editor/Label" ).toStringList(); myFont.fromString( myList.at( 0 ) ); lColorSchemePreview5->setFont( myFont ); lColorSchemePreview5->setText( myFont.family() ); myPalette = lColorSchemePreview5->palette(); myColor = QColor( myList.at( 1 ) ); if ( myColor.isValid() ) myPalette.setColor( QPalette::Button, myColor ); myColor = QColor( myList.at( 2 ) ); if ( myColor.isValid() ) myPalette.setColor( QPalette::ButtonText, myColor ); lColorSchemePreview5->setPalette( myPalette ); // myList = Options::self()->value( "Options/Editor/Comment" ).toStringList(); myFont.fromString( myList.at( 0 ) ); lColorSchemePreview6->setFont( myFont ); lColorSchemePreview6->setText( myFont.family() ); myPalette = lColorSchemePreview6->palette(); myColor = QColor( myList.at( 1 ) ); if ( myColor.isValid() ) myPalette.setColor( QPalette::Button, myColor ); myColor = QColor( myList.at( 2 ) ); if ( myColor.isValid() ) myPalette.setColor( QPalette::ButtonText, myColor ); lColorSchemePreview6->setPalette( myPalette ); // myList = Options::self()->value( "Options/Editor/Preprocessor" ).toStringList(); myFont.fromString( myList.at( 0 ) ); lColorSchemePreview7->setFont( myFont ); lColorSchemePreview7->setText( myFont.family() ); myPalette = lColorSchemePreview7->palette(); myColor = QColor( myList.at( 1 ) ); if ( myColor.isValid() ) myPalette.setColor( QPalette::Button, myColor ); myColor = QColor( myList.at( 2 ) ); if ( myColor.isValid() ) myPalette.setColor( QPalette::ButtonText, myColor ); lColorSchemePreview7->setPalette( myPalette ); // colorize(); }
/** * Get the font with the given name * */ GuiFont gui_mch_get_font(char_u *name, int giveErrorIfMissing) { QString family = VimWrapper::convertFrom(name); QFont font; font.setStyleHint(QFont::TypeWriter); font.setStyleStrategy(QFont::StyleStrategy(QFont::PreferDefault | QFont::ForceIntegerMetrics) ); if ( name == NULL ) { // Fallback font font.setFamily("Monospace"); font.setFixedPitch(true); font.setPointSize(10); font.setKerning(false); return new QFont(font); } bool ok; int size = family.section(' ', -1).trimmed().toInt(&ok); if ( ok ) { QString realname = family.section(' ', 0, -2).trimmed(); font.setFamily(realname); font.setPointSize(size); } else if ( !font.fromString(family) ) { font.setRawName(family); } font.setBold(false); font.setItalic(false); font.setKerning(false); // // When you ask for a font you may get a different font. This happens // when the font system does some form of substitution (such as as virtual fonts). // This bit of code checks if the font that is requested is the font that is returned. // // In a nutshell this is what is done: // - If the font exists and has fixed width, load it // - If the font does not exist or is not monospace, don't load the font // + If giveErrorIfMissing is true, throw an error message, otherwise fail silently // * We open an exception for the Monospace font, we ALWAYS load the monospace font // QFontInfo fi(font); if ( fi.family().compare(font.family(), Qt::CaseInsensitive) != 0 && font.family().compare("Monospace", Qt::CaseInsensitive) != 0) { if ( giveErrorIfMissing ) { EMSG2(e_font, name); } return NOFONT; } if ( !fi.fixedPitch() ) { if ( giveErrorIfMissing ) { EMSG2(e_font, name); } return NOFONT; } return new QFont(font); }
// Populate (setup) dialog controls from settings descriptors. void OptionsForm::setup ( Options *pOptions ) { // Set reference descriptor. m_pOptions = pOptions; // Start clean. m_iDirtyCount = 0; // Avoid nested changes. m_iDirtySetup++; // Load combo box history... m_pOptions->loadComboBoxHistory(m_ui.ServerHostComboBox); m_pOptions->loadComboBoxHistory(m_ui.ServerPortComboBox); m_pOptions->loadComboBoxHistory(m_ui.ServerCmdLineComboBox); m_pOptions->loadComboBoxHistory(m_ui.MessagesLogPathComboBox); // Load Server settings... m_ui.ServerHostComboBox->setEditText(m_pOptions->sServerHost); m_ui.ServerPortComboBox->setEditText(QString::number(m_pOptions->iServerPort)); m_ui.ServerTimeoutSpinBox->setValue(m_pOptions->iServerTimeout); m_ui.ServerStartCheckBox->setChecked(m_pOptions->bServerStart); m_ui.ServerCmdLineComboBox->setEditText(m_pOptions->sServerCmdLine); m_ui.StartDelaySpinBox->setValue(m_pOptions->iStartDelay); // Logging options... m_ui.MessagesLogCheckBox->setChecked(m_pOptions->bMessagesLog); m_ui.MessagesLogPathComboBox->setEditText(m_pOptions->sMessagesLogPath); // Load Display options... QFont font; QPalette pal; // Display font. if (m_pOptions->sDisplayFont.isEmpty() || !font.fromString(m_pOptions->sDisplayFont)) font = QFont("Sans Serif", 8); m_ui.DisplayFontTextLabel->setFont(font); m_ui.DisplayFontTextLabel->setText(font.family() + ' ' + QString::number(font.pointSize())); // Display effect. m_ui.DisplayEffectCheckBox->setChecked(m_pOptions->bDisplayEffect); toggleDisplayEffect(m_pOptions->bDisplayEffect); // Auto-refresh and maximum volume options. m_ui.AutoRefreshCheckBox->setChecked(m_pOptions->bAutoRefresh); m_ui.AutoRefreshTimeSpinBox->setValue(m_pOptions->iAutoRefreshTime); m_ui.MaxVolumeSpinBox->setValue(m_pOptions->iMaxVolume); // Messages font. if (m_pOptions->sMessagesFont.isEmpty() || !font.fromString(m_pOptions->sMessagesFont)) font = QFont("Monospace", 8); pal = m_ui.MessagesFontTextLabel->palette(); pal.setColor(QPalette::Background, pal.base().color()); m_ui.MessagesFontTextLabel->setPalette(pal); m_ui.MessagesFontTextLabel->setFont(font); m_ui.MessagesFontTextLabel->setText(font.family() + ' ' + QString::number(font.pointSize())); // Messages limit option. m_ui.MessagesLimitCheckBox->setChecked(m_pOptions->bMessagesLimit); m_ui.MessagesLimitLinesSpinBox->setValue(m_pOptions->iMessagesLimitLines); // Other options finally. m_ui.ConfirmRemoveCheckBox->setChecked(m_pOptions->bConfirmRemove); m_ui.ConfirmRestartCheckBox->setChecked(m_pOptions->bConfirmRestart); m_ui.ConfirmResetCheckBox->setChecked(m_pOptions->bConfirmReset); m_ui.ConfirmErrorCheckBox->setChecked(m_pOptions->bConfirmError); m_ui.KeepOnTopCheckBox->setChecked(m_pOptions->bKeepOnTop); m_ui.StdoutCaptureCheckBox->setChecked(m_pOptions->bStdoutCapture); m_ui.CompletePathCheckBox->setChecked(m_pOptions->bCompletePath); m_ui.InstrumentNamesCheckBox->setChecked(m_pOptions->bInstrumentNames); m_ui.MaxRecentFilesSpinBox->setValue(m_pOptions->iMaxRecentFiles); if (m_pOptions->iBaseFontSize > 0) m_ui.BaseFontSizeComboBox->setEditText(QString::number(m_pOptions->iBaseFontSize)); else m_ui.BaseFontSizeComboBox->setCurrentIndex(0); #ifndef CONFIG_LIBGIG m_ui.InstrumentNamesCheckBox->setEnabled(false); #endif bMaxVoicesModified = bMaxStreamsModified = false; #ifdef CONFIG_MAX_VOICES const bool bMaxVoicesSupported = m_pOptions->getEffectiveMaxVoices() >= 0; const bool bMaxStreamsSupported = m_pOptions->getEffectiveMaxStreams() >= 0; m_ui.MaxVoicesSpinBox->setEnabled(bMaxVoicesSupported); m_ui.MaxVoicesSpinBox->setValue(m_pOptions->getMaxVoices()); if (!bMaxVoicesSupported) m_ui.MaxVoicesSpinBox->setToolTip( tr("This parameter is not supported by the current sampler " "version in use.") ); else m_ui.MaxVoicesSpinBox->setToolTip( tr("The max. amount of voices the sampler shall process " "simultaniously.") ); m_ui.MaxStreamsSpinBox->setEnabled(bMaxStreamsSupported); m_ui.MaxStreamsSpinBox->setValue(m_pOptions->getMaxStreams()); if (!bMaxStreamsSupported) m_ui.MaxStreamsSpinBox->setToolTip( tr("This parameter is not supported by the current sampler " "version in use.") ); else m_ui.MaxStreamsSpinBox->setToolTip( tr("The max. amount of disk streams the sampler shall process " "simultaniously.") ); #else m_ui.MaxVoicesSpinBox->setEnabled(false); m_ui.MaxStreamsSpinBox->setEnabled(false); m_ui.MaxVoicesSpinBox->setToolTip( tr("QSampler was built without support for this parameter.") ); m_ui.MaxStreamsSpinBox->setToolTip( tr("QSampler was built without support for this parameter.") ); #endif // CONFIG_MAX_VOICES // Done. m_iDirtySetup--; stabilizeForm(); }
int main(int argc, char *argv[]) { #ifdef Q_OS_X11 XInitThreads(); #endif QApplication app(argc, argv); QFont font; font.fromString(appsettings->value(NULL, GC_FONT_DEFAULT, QFont().toString()).toString()); font.setPointSize(appsettings->value(NULL, GC_FONT_DEFAULT_SIZE, 12).toInt()); app.setFont(font); // set default font //this is the path within the current directory where GC will look for //files to allow USB stick support QString localLibraryPath="Library/GoldenCheetah"; //this is the path that used to be used for all platforms //now different platforms will use their own path //this path is checked first to make things easier for long-time users QString oldLibraryPath=QDir::home().path()+"/Library/GoldenCheetah"; //these are the new platform-dependent library paths #if defined(Q_OS_MACX) QString libraryPath="Library/GoldenCheetah"; #elif defined(Q_OS_WIN) QString libraryPath=QDesktopServices::storageLocation(QDesktopServices::DataLocation) + "/GoldenCheetah"; #else // Q_OS_LINUX et al QString libraryPath=".goldencheetah"; #endif //First check to see if the Library folder exists where the executable is (for USB sticks) QDir home = QDir(); //if it does, create an ini file for settings and cd into the library if(home.exists(localLibraryPath)) { home.cd(localLibraryPath); } //if it does not exist, let QSettings handle storing settings //also cd to the home directory and look for libraries else { home = QDir::home(); //check if this users previously stored files in the old library path //if they did, use the existing library if (home.exists(oldLibraryPath)) { home.cd(oldLibraryPath); } //otherwise use the new library path else { //first create the path if it does not exist if (!home.exists(libraryPath)) { if (!home.mkpath(libraryPath)) { qDebug()<<"Failed to create library path\n"; assert(false); } } home.cd(libraryPath); } } // install QT Translator to enable QT Dialogs translation QTranslator qtTranslator; qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); app.installTranslator(&qtTranslator); // Language setting (default to system locale) QVariant lang = appsettings->value(NULL, GC_LANG, QLocale::system().name()); // Load specific translation QTranslator gcTranslator; gcTranslator.load(":translations/gc_" + lang.toString() + ".qm"); app.installTranslator(&gcTranslator); // Initialize metrics once the translator is installed RideMetricFactory::instance().initialize(); // Initialize global registry once the translator is installed GcWindowRegistry::initialize(); // initialise the trainDB trainDB = new TrainDB(home); QStringList args( app.arguments() ); QVariant lastOpened; if( args.size() > 1 ){ lastOpened = args.at(1); } else { lastOpened = appsettings->value(NULL, GC_SETTINGS_LAST); } double crankLength = appsettings->value(NULL, GC_CRANKLENGTH).toDouble(); if(crankLength<=0) { appsettings->setValue(GC_CRANKLENGTH,172.5); } bool anyOpened = false; if (lastOpened != QVariant()) { QStringList list = lastOpened.toStringList(); QStringListIterator i(list); while (i.hasNext()) { QString cyclist = i.next(); if (home.cd(cyclist)) { MainWindow *mainWindow = new MainWindow(home); mainWindow->show(); home.cdUp(); anyOpened = true; } } } if (!anyOpened) { ChooseCyclistDialog d(home, true); d.setModal(true); if (d.exec() != QDialog::Accepted) return 0; home.cd(d.choice()); if (!home.exists()) assert(false); MainWindow *mainWindow = new MainWindow(home); mainWindow->show(); } return app.exec(); }
int main(int argc, char *argv[]) { int ret=2; // return code from qapplication, default to error // // PROCESS COMMAND LINE SWITCHES // // snaffle arguments into a stringlist we can play with into sargs // and only keep non-switch args in the args string list QStringList sargs, args; for (int i=0; i<argc; i++) sargs << argv[i]; #ifdef GC_DEBUG bool debug = true; #else bool debug = false; #endif bool help = false; // honour command line switches foreach (QString arg, sargs) { // help or version requested if (arg == "--help" || arg == "--version") { help = true; fprintf(stderr, "GoldenCheetah %s (%d)\nusage: GoldenCheetah [[directory] athlete]\n\n", VERSION_STRING, VERSION_LATEST); fprintf(stderr, "--help or --version to print this message and exit\n"); #ifdef GC_DEBUG fprintf(stderr, "--debug to turn on redirection of messages to goldencheetah.log [debug build]\n"); #else fprintf(stderr, "--debug to direct diagnostic messages to the terminal instead of goldencheetah.log\n"); #endif fprintf (stderr, "\nSpecify the folder and/or athlete to open on startup\n"); fprintf(stderr, "If no parameters are passed it will reopen the last athlete.\n\n"); } else if (arg == "--debug") { #ifdef GC_DEBUG // debug, so don't redirect stderr! debug = false; #else debug = true; #endif } else { // not switches ! args << arg; } } // help or version printed so just exit now if (help) { exit(0); } // // INITIALISE ONE TIME OBJECTS // #ifdef Q_OS_X11 XInitThreads(); #endif #ifdef Q_OS_MACX if ( QSysInfo::MacintoshVersion > QSysInfo::MV_10_8 ) { // fix Mac OS X 10.9 (mavericks) font issue // https://bugreports.qt-project.org/browse/QTBUG-32789 QFont::insertSubstitution("LucidaGrande", "Lucida Grande"); } #endif // create the application -- only ever ONE regardless of restarts application = new QApplication(argc, argv); #ifdef Q_OS_MAC // get an autorelease pool setup static CocoaInitializer cocoaInitializer; #endif // set defaultfont QFont font; font.fromString(appsettings->value(NULL, GC_FONT_DEFAULT, QFont().toString()).toString()); font.setPointSize(appsettings->value(NULL, GC_FONT_DEFAULT_SIZE, 12).toInt()); application->setFont(font); // set default font // // OPEN FIRST MAINWINDOW // do { // lets not restart endlessly restarting = false; //this is the path within the current directory where GC will look for //files to allow USB stick support QString localLibraryPath="Library/GoldenCheetah"; //this is the path that used to be used for all platforms //now different platforms will use their own path //this path is checked first to make things easier for long-time users QString oldLibraryPath=QDir::home().path()+"/Library/GoldenCheetah"; //these are the new platform-dependent library paths #if defined(Q_OS_MACX) QString libraryPath="Library/GoldenCheetah"; #elif defined(Q_OS_WIN) #if QT_VERSION > 0x050000 // windows and qt5 QStringList paths=QStandardPaths::standardLocations(QStandardPaths::DataLocation); QString libraryPath = paths.at(0) + "/GoldenCheetah"; #else // windows not qt5 QString libraryPath=QDesktopServices::storageLocation(QDesktopServices::DataLocation) + "/GoldenCheetah"; #endif // qt5 #else // not windows or osx (must be Linux or OpenBSD) // Q_OS_LINUX et al QString libraryPath=".goldencheetah"; #endif // // or did we override in settings? QString sh; if ((sh=appsettings->value(NULL, GC_HOMEDIR).toString()) != "") localLibraryPath = sh; // lets try the local library we've worked out... QDir home = QDir(); if(home.exists(localLibraryPath)) { home.cd(localLibraryPath); } else { // YIKES !! The directory we should be using doesn't exist! home = QDir::home(); if (home.exists(oldLibraryPath)) { // there is an old style path, lets fo there home.cd(oldLibraryPath); } else { if (!home.exists(libraryPath)) { if (!home.mkpath(libraryPath)) { qDebug()<<"Failed to create library path\n"; exit(0); } } home.cd(libraryPath); } } // set global root directory gcroot = home.absolutePath(); // now redirect stderr #ifndef WIN32 if (!debug) nostderr(home.absolutePath()); #endif // install QT Translator to enable QT Dialogs translation // we may have restarted JUST to get this! QTranslator qtTranslator; qtTranslator.load("qt_" + QLocale::system().name(), QLibraryInfo::location(QLibraryInfo::TranslationsPath)); application->installTranslator(&qtTranslator); // Language setting (default to system locale) QVariant lang = appsettings->value(NULL, GC_LANG, QLocale::system().name()); // Load specific translation QTranslator gcTranslator; gcTranslator.load(":translations/gc_" + lang.toString() + ".qm"); application->installTranslator(&gcTranslator); // Initialize metrics once the translator is installed RideMetricFactory::instance().initialize(); // Initialize global registry once the translator is installed GcWindowRegistry::initialize(); // initialise the trainDB trainDB = new TrainDB(home); // lets do what the command line says ... QVariant lastOpened; if(args.count() == 2) { // $ ./GoldenCheetah Mark // athlete lastOpened = args.at(1); } else if (args.count() == 3) { // $ ./GoldenCheetah ~/Athletes Mark // first parameter is a folder that exists? if (QFileInfo(args.at(1)).isDir()) { home.cd(args.at(1)); } // folder and athlete lastOpened = args.at(2); } else { // no parameters passed lets open the last athlete we worked with lastOpened = appsettings->value(NULL, GC_SETTINGS_LAST); } // lets attempt to open as asked/remembered bool anyOpened = false; if (lastOpened != QVariant()) { QStringList list = lastOpened.toStringList(); QStringListIterator i(list); while (i.hasNext()) { QString cyclist = i.next(); if (home.cd(cyclist)) { MainWindow *mainWindow = new MainWindow(home); mainWindow->show(); home.cdUp(); anyOpened = true; } } } // ack, didn't manage to open an athlete // lets ask the user which / create a new one if (!anyOpened) { ChooseCyclistDialog d(home, true); d.setModal(true); // choose cancel? if ((ret=d.exec()) != QDialog::Accepted) { delete trainDB; return ret; } // chosen, so lets get the choice.. home.cd(d.choice()); if (!home.exists()) { delete trainDB; exit(0); } // .. and open a mainwindow MainWindow *mainWindow = new MainWindow(home); mainWindow->show(); } ret=application->exec(); // close trainDB delete trainDB; } while (restarting); return ret; }
void OptionsDialog::reaSettings() { #ifdef Q_OS_WIN32 QSettings settings(QDir::homePath()+tr("/Application Data/")+qApp->applicationName()+".ini", QSettings::IniFormat); #else QSettings settings; #endif QDateTime today = QDateTime::currentDateTime(); QString todaytext = today.toString("yyyyMMdd"); QStringList fontS; QFont font; QFont defaultFont; fontS << settings.value("Font/FileName_Settings", ui.statusbarFontComboBox->currentFont() ).toString() << settings.value("Font/Statistics_Settings", ui.statusbarFontComboBox->currentFont() ).toString() << settings.value("Font/DefaultFont", ui.fontComboBox->currentFont() ).toString(); font.fromString(fontS.at(0)); ui.statusbarFontComboBox->setCurrentFont( font ); ui.statusbarBoldCheckBox->setChecked( font.bold() ); ui.statusbarItalicCheckBox->setChecked( font.italic() ); ui.statusbarSpinBox->setValue( font.pointSize() ); defaultFont.fromString(fontS.at(2)); ui.fontComboBox->setCurrentFont( defaultFont ); ui.fontSizeSpinBox->setValue( defaultFont.pointSize() ); ui.loadOnStartCheckBox->setChecked( settings.value( "RecentFiles/OpenLastFile", true ).toBool() ); ui.saveCursorCheckBox->setChecked( settings.value( "RecentFiles/SavePosition", true ).toBool() ); if ( !ui.loadOnStartCheckBox->isChecked() ) ui.saveCursorCheckBox->setEnabled( false ); ui.editorWidthSpinBox->setMaximum( settings.value("MaxEditorWidth", 1024).toInt()); ui.editorTopSpaceSpinBox->setMaximum(settings.value("MaxEditorTopSpace", 768).toInt()); ui.editorBottomSpaceSpinBox->setMaximum(settings.value("MaxEditorBottomSpace", 1000).toInt()); ui.wordCountSpinBox->setValue( settings.value("WordCount", 0).toInt()); ui.pageCountSpinBox->setValue( settings.value("PageCountFormula", 250).toInt()); ui.fullScreenCheckBox->setChecked( settings.value("WindowState/ShowFullScreen", true).toBool() ); ui.splashScreenCheckBox->setChecked( settings.value("WindowState/ShowSplashScreen", true).toBool() ); ui.autoSaveCheckBox->setChecked( settings.value("AutoSave", false).toBool() ); ui.flowModeCheckBox->setChecked( settings.value("FlowMode", false).toBool() ); ui.scrollBarCheckBox->setChecked( settings.value("ScrollBar", true).toBool() ); ui.pageCountCheckBox->setChecked( settings.value("PageCount", false).toBool() ); ui.soundCheckBox->setChecked( settings.value("Sound", true).toBool() ); QString datetext = settings.value("Deadline", todaytext).toString(); QDate date; QDate dateselected = date.fromString(datetext, "yyyyMMdd"); ui.calendarWidget->setSelectedDate(dateselected); ui.editorWidthSpinBox->setValue( settings.value ("EditorWidth", 800).toInt()); ui.editorTopSpaceSpinBox->setValue( settings.value("EditorTopSpace", 0).toInt()); ui.editorBottomSpaceSpinBox->setValue( settings.value("EditorBottomSpace", 0).toInt()); ui.spinBox->setValue( settings.value("TimedWriting", 0 ).toInt()); ui.dateFormat->setText( settings.value("DateFormat", "dd MMMM yyyy dddd").toString()); ui.timeFormat->setText( settings.value("TimeFormat", "HH:MM").toString()); QPalette palette; palette.setColor(ui.pbFontColor->backgroundRole(), fcolor = settings.value("Colors/FontColor", "#808080" ).toString()); ui.pbFontColor->setPalette(palette); palette.setColor(ui.pbStatusBarColor->backgroundRole(), scolor = settings.value("Colors/StatusColor", "#202020" ).toString()); ui.pbStatusBarColor->setPalette(palette); palette.setColor(ui.pbEditorBackColor->backgroundRole(), bgcolor = settings.value("Colors/Background", "black" ).toString()); ui.pbEditorBackColor->setPalette(palette); palette.setColor(ui.pbStatusBarBgColor->backgroundRole(), sbcolor = settings.value("Colors/StatusBg", "#808080").toString()); ui.pbStatusBarBgColor->setPalette(palette); }
bool VCWidget::loadXMLAppearance(QDomDocument*, QDomElement* root) { QDomNode node; QDomElement tag; QString str; Q_ASSERT(root != NULL); if (root->tagName() != KXMLQLCVCAppearance) { cout << "Appearance node not found!" << endl; return false; } /* Children */ node = root->firstChild(); while (node.isNull() == false) { tag = node.toElement(); if (tag.tagName() == KXMLQLCVCWidgetFrameStyle) { int style = 0; style = stringToFrameStyle(tag.text()); setFrameStyle(style); } else if (tag.tagName() == KXMLQLCVCWidgetForegroundColor) { if (tag.text() != KXMLQLCVCWidgetColorDefault) { QColor color(tag.text().toInt()); setForegroundColor(color); } } else if (tag.tagName() == KXMLQLCVCWidgetBackgroundColor) { if (tag.text() != KXMLQLCVCWidgetColorDefault) setBackgroundColor(QColor(tag.text().toInt())); } else if (tag.tagName() == KXMLQLCVCWidgetBackgroundImage) { if (tag.text() != KXMLQLCVCWidgetBackgroundImageNone) setBackgroundImage(tag.text()); } else if (tag.tagName() == KXMLQLCVCWidgetFont) { if (tag.text() != KXMLQLCVCWidgetFontDefault) { QFont font; font.fromString(tag.text()); setFont(font); } } else { cout << "Unknown appearance tag: " << tag.tagName().toStdString() << endl; } node = node.nextSibling(); } return true; }
void CurrentTrack::init() { DEBUG_BLOCK PERF_LOG( "Begin init" ); // Call the base implementation. Context::Applet::init(); setToolTip( i18n( "Right-click to configure" ) ); m_ratingWidget = new RatingWidget( this ); m_ratingWidget->setSpacing( 2 ); m_ratingWidget->setMinimumSize( m_albumWidth + 10, 30 ); m_ratingWidget->setMaximumSize( m_albumWidth + 10, 30 ); connect( m_ratingWidget, SIGNAL(ratingChanged(int)), SLOT(trackRatingChanged(int)) ); QLabel *collectionLabel = new QLabel( i18n( "Local Collection" ) ); collectionLabel->setAttribute( Qt::WA_NoSystemBackground ); collectionLabel->setAlignment( Qt::AlignCenter ); m_collectionLabel = new QGraphicsProxyWidget( this ); m_collectionLabel->setWidget( collectionLabel ); m_title = new TextScrollingWidget( this ); m_artist = new TextScrollingWidget( this ); m_album = new TextScrollingWidget( this ); m_byText = new QGraphicsSimpleTextItem( i18nc( "What artist is this track by", "By" ), this ); m_onText = new QGraphicsSimpleTextItem( i18nc( "What album is this track on", "On" ), this ); m_recentWidget = new RecentlyPlayedListWidget( this ); m_recentHeader = new TextScrollingWidget( this ); m_recentHeader->setDrawBackground( true ); m_recentHeader->setAlignment( Qt::AlignLeft ); QFont recentHeaderFont; recentHeaderFont.setPointSize( recentHeaderFont.pointSize() + 2 ); m_recentHeader->setFont( recentHeaderFont ); m_title->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ); m_artist->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ); m_album->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ); m_collectionLabel->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ); m_recentHeader->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Fixed ); m_recentWidget->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ); m_recentWidget->setMinimumHeight( 10 ); m_albumCover = new DropPixmapLayoutItem( this ); m_albumCover->setPreferredSize( QSizeF( m_albumWidth, m_albumWidth ) ); connect( m_albumCover, SIGNAL(imageDropped(QPixmap)), SLOT(coverDropped(QPixmap)) ); const QBrush brush = normalBrush(); m_title->setBrush( brush ); m_artist->setBrush( brush ); m_album->setBrush( brush ); m_byText->setBrush( brush ); m_onText->setBrush( brush ); const QFont tinyFont = KGlobalSettings::smallestReadableFont(); m_byText->setFont( tinyFont ); m_onText->setFont( tinyFont ); m_actionsLayout = new QGraphicsLinearLayout; m_actionsLayout->setMinimumWidth( 10 ); m_actionsLayout->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ); QGraphicsLinearLayout *titlesLayout = new QGraphicsLinearLayout( Qt::Vertical ); titlesLayout->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ); titlesLayout->setMinimumWidth( 10 ); titlesLayout->setSpacing( 2 ); titlesLayout->addItem( m_title ); titlesLayout->addItem( m_artist ); titlesLayout->addItem( m_album ); titlesLayout->addItem( m_actionsLayout ); titlesLayout->setItemSpacing( 2, 4 ); // a bit more spacing for the actions row const qreal pad = standardPadding(); QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout( this ); l->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding ); l->addCornerAnchors( m_ratingWidget, Qt::BottomLeftCorner, l, Qt::BottomLeftCorner ); l->addCornerAnchors( m_ratingWidget, Qt::BottomLeftCorner, m_collectionLabel, Qt::BottomLeftCorner ); l->addCornerAnchors( m_ratingWidget, Qt::TopRightCorner, m_collectionLabel, Qt::TopRightCorner ); l->addCornerAnchors( m_recentHeader, Qt::TopRightCorner, l, Qt::TopRightCorner ); l->addAnchor( m_albumCover, Qt::AnchorBottom, m_ratingWidget, Qt::AnchorTop )->setSpacing( 4 ); l->addAnchor( m_albumCover, Qt::AnchorHorizontalCenter, m_ratingWidget, Qt::AnchorHorizontalCenter ); l->addAnchor( titlesLayout, Qt::AnchorTop, l, Qt::AnchorTop )->setSpacing( 18 ); l->addAnchor( titlesLayout, Qt::AnchorRight, l, Qt::AnchorRight )->setSpacing( pad ); l->addAnchors( m_recentWidget, m_recentHeader, Qt::Horizontal ); l->addAnchor( m_recentWidget, Qt::AnchorTop, m_recentHeader, Qt::AnchorBottom ); l->addAnchor( m_recentWidget, Qt::AnchorRight, m_recentHeader, Qt::AnchorRight ); l->addAnchor( m_recentWidget, Qt::AnchorLeft, m_ratingWidget, Qt::AnchorRight )->setSpacing( pad * 2 ); l->addAnchor( m_recentWidget, Qt::AnchorBottom, m_albumCover, Qt::AnchorBottom )->setSpacing( 20 ); qreal midSpacing = qMax( m_byText->boundingRect().width(), m_onText->boundingRect().width() ) + pad; l->addAnchor( titlesLayout, Qt::AnchorLeft, m_ratingWidget, Qt::AnchorRight )->setSpacing( midSpacing ); l->anchor( m_recentHeader, Qt::AnchorTop, l, Qt::AnchorTop )->setSpacing( 2 ); // Read config KConfigGroup config = Amarok::config("Current Track Applet"); const QString fontDesc = config.readEntry( "Font", QString() ); QFont font; if( !fontDesc.isEmpty() ) font.fromString( fontDesc ); else font.setPointSize( font.pointSize() + 3 ); m_showEditTrackDetailsAction = config.readEntry( "ShowEditTrackAction", true ); m_title->setFont( font ); m_artist->setFont( font ); m_album->setFont( font ); m_title->setAlignment( Qt::AlignLeft ); m_artist->setAlignment( Qt::AlignLeft ); m_album->setAlignment( Qt::AlignLeft ); dataEngine( "amarok-current" )->setProperty( "coverWidth", m_albumWidth ); dataEngine( "amarok-current" )->connectSource( "current", this ); connect( The::paletteHandler(), SIGNAL(newPalette(QPalette)), SLOT(paletteChanged(QPalette)) ); connect( CollectionManager::instance(), SIGNAL(collectionDataChanged(Collections::Collection*)), this, SLOT(queryCollection()), Qt::QueuedConnection ); queryCollection(); setView( Stopped ); PERF_LOG( "Finished init" ); }
void Properties::serializeIn( QXmlStreamReader& stream ) { if ( !stream.isStartElement( ) || stream.name( ) != "properties" ) { qDebug( ) << "qan::Properties::serializeIn(): properties start element not found."; return; } while ( stream.readNextStartElement( ) ) // <properties> { if ( stream.isStartElement( ) && stream.name( ) == "property" ) { // <property> QString propertyName = QString( stream.attributes( ).value( "name" ).toString( ) ); QVariant::Type type = ( QVariant::Type )stream.attributes( ).value( "t" ).toInt( ); QVariant value; switch ( type ) { case QVariant::Type::String: value = QVariant( stream.attributes( ).value( "v" ).toString( ) ); break; case QVariant::Type::Bool: value = QVariant( stream.attributes( ).value( "v" ) == "true" ? true : false ); break; case QVariant::Type::Int: value = QVariant( stream.attributes( ).value( "v" ).toInt( ) ); break; case QVariant::Type::Double: value = QVariant( stream.attributes( ).value( "v" ).toDouble( ) ); break; case QVariant::Type::Color: { QColor c( stream.attributes( ).value( "v" ).toString( ) ); if ( c.isValid( ) ) value = QVariant::fromValue< QColor >( c ); } break; case QVariant::Type::Font: { QFont f; f.fromString( stream.attributes( ).value( "v" ).toString( ) ); value = QVariant::fromValue< QFont >( f ); } break; case QVariant::Type::SizeF: { QString s( stream.attributes( ).value( "v" ).toString( ) ); QTextStream ts( &s ); qreal w, h; ts >> w; QString separator; ts >> separator; ts >> h; value = QVariant::fromValue< QSizeF >( QSizeF( w, h ) ); } break; default: value = QVariant( ); break; } if ( value.isValid( ) ) { QString enumValues = stream.attributes( ).value( "isEnum" ).toString( ); if ( !enumValues.isEmpty( ) ) addEnumProperty( propertyName, value, enumValues.split( ',' ) ); else setProperty( propertyName, value ); } if ( stream.readNextStartElement( ) && stream.name( ) == "values" ) { // <values> serializeTimeValuesIn( propertyName, stream ); } // </values> } // </property> else {
void lmcChatRoomWindow::init(User* pLocalUser, bool connected, QString thread) { localId = pLocalUser->id; localName = pLocalUser->name; this->pLocalUser = pLocalUser; pMessageLog->localId = localId; // get the avatar image for the users from the cache folder QDir cacheDir(StdLocation::cacheDir()); QString fileName = "avt_" + localId + ".png"; QString filePath = cacheDir.absoluteFilePath(fileName); pMessageLog->participantAvatars.insert(localId, filePath); threadId = thread; groupMode = !threadId.isNull(); createUserMenu(); createSmileyMenu(); createToolBar(); bConnected = connected; if ( !bConnected ) showStatus( IT_Disconnected, true ); pSoundPlayer = new lmcSoundPlayer(); ui.tvUserList->setIconSize(QSize(16, 16)); ui.tvUserList->header()->setSectionsMovable(false); ui.tvUserList->header()->setStretchLastSection(false); ui.tvUserList->header()->setSectionResizeMode(0, QHeaderView::Stretch); lmcUserTreeWidgetGroupItem *pItem = new lmcUserTreeWidgetGroupItem(); pItem->setData(0, IdRole, GroupId); pItem->setData(0, TypeRole, "Group"); pItem->setText(0, "Participants"); pItem->setSizeHint(0, QSize(0, 22)); ui.tvUserList->addTopLevelItem(pItem); ui.tvUserList->expandAll(); pSettings = new lmcSettings(); showSmiley = pSettings->value(IDS_EMOTICON, IDS_EMOTICON_VAL).toBool(); pMessageLog->showSmiley = showSmiley; pMessageLog->autoFile = pSettings->value(IDS_AUTOFILE, IDS_AUTOFILE_VAL).toBool(); pMessageLog->fontSizeVal = pSettings->value(IDS_FONTSIZE, IDS_FONTSIZE_VAL).toInt(); pMessageLog->messageTime = pSettings->value(IDS_MESSAGETIME, IDS_MESSAGETIME_VAL).toBool(); pMessageLog->messageDate = pSettings->value(IDS_MESSAGEDATE, IDS_MESSAGEDATE_VAL).toBool(); pMessageLog->allowLinks = pSettings->value(IDS_ALLOWLINKS, IDS_ALLOWLINKS_VAL).toBool(); pMessageLog->pathToLink = pSettings->value(IDS_PATHTOLINK, IDS_PATHTOLINK_VAL).toBool(); pMessageLog->trimMessage = pSettings->value(IDS_TRIMMESSAGE, IDS_TRIMMESSAGE_VAL).toBool(); QFont font = QApplication::font(); font.fromString(pSettings->value(IDS_FONT, IDS_FONT_VAL).toString()); messageColor = QApplication::palette().text().color(); messageColor.setNamedColor(pSettings->value(IDS_COLOR, IDS_COLOR_VAL).toString()); sendKeyMod = pSettings->value(IDS_SENDKEYMOD, IDS_SENDKEYMOD_VAL).toBool(); if ( !groupMode ) { restoreGeometry(pSettings->value(IDS_WINDOWPUBLICCHAT).toByteArray()); ui.vSplitter->restoreState(pSettings->value(IDS_SPLITTERPUBLICCHATV).toByteArray()); ui.hSplitter->restoreState(pSettings->value(IDS_SPLITTERPUBLICCHATH).toByteArray()); } setUIText(); setMessageFont( font ); ui.txtMessage->setStyleSheet( "QTextEdit {color: " + messageColor.name() + ";}" ); ui.txtMessage->setFocus(); QString themePath = pSettings->value(IDS_THEME, IDS_THEME_VAL).toString(); pMessageLog->initMessageLog(themePath); int viewType = pSettings->value(IDS_USERLISTVIEW, IDS_USERLISTVIEW_VAL).toInt(); ui.tvUserList->setView((UserListView)viewType); // Destroy the window when it closes if in group mode setAttribute(Qt::WA_DeleteOnClose, groupMode); // Add the local user as a participant addUser(pLocalUser); }
bool QgsLayoutItemScaleBar::readPropertiesFromElement( const QDomElement &itemElem, const QDomDocument &, const QgsReadWriteContext &context ) { mSettings.setHeight( itemElem.attribute( QStringLiteral( "height" ), QStringLiteral( "5.0" ) ).toDouble() ); mSettings.setLabelBarSpace( itemElem.attribute( QStringLiteral( "labelBarSpace" ), QStringLiteral( "3.0" ) ).toDouble() ); mSettings.setBoxContentSpace( itemElem.attribute( QStringLiteral( "boxContentSpace" ), QStringLiteral( "1.0" ) ).toDouble() ); mSettings.setNumberOfSegments( itemElem.attribute( QStringLiteral( "numSegments" ), QStringLiteral( "2" ) ).toInt() ); mSettings.setNumberOfSegmentsLeft( itemElem.attribute( QStringLiteral( "numSegmentsLeft" ), QStringLiteral( "0" ) ).toInt() ); mSettings.setUnitsPerSegment( itemElem.attribute( QStringLiteral( "numUnitsPerSegment" ), QStringLiteral( "1.0" ) ).toDouble() ); mSettings.setSegmentSizeMode( static_cast<QgsScaleBarSettings::SegmentSizeMode>( itemElem.attribute( QStringLiteral( "segmentSizeMode" ), QStringLiteral( "0" ) ).toInt() ) ); mSettings.setMinimumBarWidth( itemElem.attribute( QStringLiteral( "minBarWidth" ), QStringLiteral( "50" ) ).toDouble() ); mSettings.setMaximumBarWidth( itemElem.attribute( QStringLiteral( "maxBarWidth" ), QStringLiteral( "150" ) ).toDouble() ); mSegmentMillimeters = itemElem.attribute( QStringLiteral( "segmentMillimeters" ), QStringLiteral( "0.0" ) ).toDouble(); mSettings.setMapUnitsPerScaleBarUnit( itemElem.attribute( QStringLiteral( "numMapUnitsPerScaleBarUnit" ), QStringLiteral( "1.0" ) ).toDouble() ); mSettings.setLineWidth( itemElem.attribute( QStringLiteral( "outlineWidth" ), QStringLiteral( "0.3" ) ).toDouble() ); mSettings.setUnitLabel( itemElem.attribute( QStringLiteral( "unitLabel" ) ) ); mSettings.setLineJoinStyle( QgsSymbolLayerUtils::decodePenJoinStyle( itemElem.attribute( QStringLiteral( "lineJoinStyle" ), QStringLiteral( "miter" ) ) ) ); mSettings.setLineCapStyle( QgsSymbolLayerUtils::decodePenCapStyle( itemElem.attribute( QStringLiteral( "lineCapStyle" ), QStringLiteral( "square" ) ) ) ); QDomNodeList textFormatNodeList = itemElem.elementsByTagName( QStringLiteral( "text-style" ) ); if ( !textFormatNodeList.isEmpty() ) { QDomElement textFormatElem = textFormatNodeList.at( 0 ).toElement(); mSettings.textFormat().readXml( textFormatElem, context ); } else { QFont f; if ( !QgsFontUtils::setFromXmlChildNode( f, itemElem, QStringLiteral( "scaleBarFont" ) ) ) { f.fromString( itemElem.attribute( QStringLiteral( "font" ), QLatin1String( "" ) ) ); } mSettings.textFormat().setFont( f ); if ( f.pointSizeF() > 0 ) { mSettings.textFormat().setSize( f.pointSizeF() ); mSettings.textFormat().setSizeUnit( QgsUnitTypes::RenderPoints ); } else if ( f.pixelSize() > 0 ) { mSettings.textFormat().setSize( f.pixelSize() ); mSettings.textFormat().setSizeUnit( QgsUnitTypes::RenderPixels ); } } //colors //fill color QDomNodeList fillColorList = itemElem.elementsByTagName( QStringLiteral( "fillColor" ) ); if ( !fillColorList.isEmpty() ) { QDomElement fillColorElem = fillColorList.at( 0 ).toElement(); bool redOk, greenOk, blueOk, alphaOk; int fillRed, fillGreen, fillBlue, fillAlpha; fillRed = fillColorElem.attribute( QStringLiteral( "red" ) ).toDouble( &redOk ); fillGreen = fillColorElem.attribute( QStringLiteral( "green" ) ).toDouble( &greenOk ); fillBlue = fillColorElem.attribute( QStringLiteral( "blue" ) ).toDouble( &blueOk ); fillAlpha = fillColorElem.attribute( QStringLiteral( "alpha" ) ).toDouble( &alphaOk ); if ( redOk && greenOk && blueOk && alphaOk ) { mSettings.setFillColor( QColor( fillRed, fillGreen, fillBlue, fillAlpha ) ); } } else { mSettings.setFillColor( QColor( itemElem.attribute( QStringLiteral( "brushColor" ), QStringLiteral( "#000000" ) ) ) ); } //fill color 2 QDomNodeList fillColor2List = itemElem.elementsByTagName( QStringLiteral( "fillColor2" ) ); if ( !fillColor2List.isEmpty() ) { QDomElement fillColor2Elem = fillColor2List.at( 0 ).toElement(); bool redOk, greenOk, blueOk, alphaOk; int fillRed, fillGreen, fillBlue, fillAlpha; fillRed = fillColor2Elem.attribute( QStringLiteral( "red" ) ).toDouble( &redOk ); fillGreen = fillColor2Elem.attribute( QStringLiteral( "green" ) ).toDouble( &greenOk ); fillBlue = fillColor2Elem.attribute( QStringLiteral( "blue" ) ).toDouble( &blueOk ); fillAlpha = fillColor2Elem.attribute( QStringLiteral( "alpha" ) ).toDouble( &alphaOk ); if ( redOk && greenOk && blueOk && alphaOk ) { mSettings.setFillColor2( QColor( fillRed, fillGreen, fillBlue, fillAlpha ) ); } } else { mSettings.setFillColor2( QColor( itemElem.attribute( QStringLiteral( "brush2Color" ), QStringLiteral( "#ffffff" ) ) ) ); } //stroke color QDomNodeList strokeColorList = itemElem.elementsByTagName( QStringLiteral( "strokeColor" ) ); if ( !strokeColorList.isEmpty() ) { QDomElement strokeColorElem = strokeColorList.at( 0 ).toElement(); bool redOk, greenOk, blueOk, alphaOk; int strokeRed, strokeGreen, strokeBlue, strokeAlpha; strokeRed = strokeColorElem.attribute( QStringLiteral( "red" ) ).toDouble( &redOk ); strokeGreen = strokeColorElem.attribute( QStringLiteral( "green" ) ).toDouble( &greenOk ); strokeBlue = strokeColorElem.attribute( QStringLiteral( "blue" ) ).toDouble( &blueOk ); strokeAlpha = strokeColorElem.attribute( QStringLiteral( "alpha" ) ).toDouble( &alphaOk ); if ( redOk && greenOk && blueOk && alphaOk ) { mSettings.setLineColor( QColor( strokeRed, strokeGreen, strokeBlue, strokeAlpha ) ); QPen p = mSettings.pen(); p.setColor( mSettings.lineColor() ); mSettings.setPen( p ); } } else { mSettings.setLineColor( QColor( itemElem.attribute( QStringLiteral( "penColor" ), QStringLiteral( "#000000" ) ) ) ); QPen p = mSettings.pen(); p.setColor( mSettings.lineColor() ); mSettings.setPen( p ); } //font color QDomNodeList textColorList = itemElem.elementsByTagName( QStringLiteral( "textColor" ) ); if ( !textColorList.isEmpty() ) { QDomElement textColorElem = textColorList.at( 0 ).toElement(); bool redOk, greenOk, blueOk, alphaOk; int textRed, textGreen, textBlue, textAlpha; textRed = textColorElem.attribute( QStringLiteral( "red" ) ).toDouble( &redOk ); textGreen = textColorElem.attribute( QStringLiteral( "green" ) ).toDouble( &greenOk ); textBlue = textColorElem.attribute( QStringLiteral( "blue" ) ).toDouble( &blueOk ); textAlpha = textColorElem.attribute( QStringLiteral( "alpha" ) ).toDouble( &alphaOk ); if ( redOk && greenOk && blueOk && alphaOk ) { mSettings.textFormat().setColor( QColor( textRed, textGreen, textBlue, textAlpha ) ); } } else if ( itemElem.hasAttribute( QStringLiteral( "fontColor" ) ) ) { QColor c; c.setNamedColor( itemElem.attribute( QStringLiteral( "fontColor" ), QStringLiteral( "#000000" ) ) ); mSettings.textFormat().setColor( c ); } //style QString styleString = itemElem.attribute( QStringLiteral( "style" ), QLatin1String( "" ) ); setStyle( styleString.toLocal8Bit().data() ); if ( itemElem.attribute( QStringLiteral( "unitType" ) ).isEmpty() ) { QgsUnitTypes::DistanceUnit u = QgsUnitTypes::DistanceUnknownUnit; switch ( itemElem.attribute( QStringLiteral( "units" ) ).toInt() ) { case 0: u = QgsUnitTypes::DistanceUnknownUnit; break; case 1: u = QgsUnitTypes::DistanceMeters; break; case 2: u = QgsUnitTypes::DistanceFeet; break; case 3: u = QgsUnitTypes::DistanceNauticalMiles; break; } mSettings.setUnits( u ); } else { mSettings.setUnits( QgsUnitTypes::decodeDistanceUnit( itemElem.attribute( QStringLiteral( "unitType" ) ) ) ); } mSettings.setAlignment( static_cast< QgsScaleBarSettings::Alignment >( itemElem.attribute( QStringLiteral( "alignment" ), QStringLiteral( "0" ) ).toInt() ) ); //map disconnectCurrentMap(); mMap = nullptr; mMapUuid = itemElem.attribute( QStringLiteral( "mapUuid" ) ); return true; }
void wavrMessageLog::appendMessageLog(MessageType type, QString *lpszUserId, QString *lpszUserName, wavrXmlMessage *pMessage, bool bReload) { if(!pMessage && type != MT_Error) return; QString message; QString html; QString caption; QDateTime time; QFont font; QColor color; QString fontStyle; QString id = QString::null; bool addToLog = true; removeMessageLog("_wavr_statediv"); switch(type) { case MT_Message: time.setMSecsSinceEpoch(pMessage->header(XML_TIME).toLongLong()); message = pMessage->data(XML_MESSAGE); font.fromString(pMessage->data(XML_FONT)); color.setNamedColor(pMessage->data(XML_COLOR)); qDebug() << "message received is " << message; appendMessage(lpszUserId, lpszUserName, &message, &time, &font, &color); lastId = *lpszUserId; break; case MT_Broadcast: time.setMSecsSinceEpoch(pMessage->header(XML_TIME).toLongLong()); message = pMessage->data(XML_BROADCAST); appendBroadcast(lpszUserId, lpszUserName, &message, &time); lastId = QString::null; break; case MT_ChatState: message = pMessage->data(XML_CHATSTATE); caption = getChatStateMessage((ChatState)wavrHelper::indexOf(ChatStateNames, CS_Max, message)); qDebug() << "chatstate message " << message << " caption: " << caption; if(!caption.isNull()) { html = themeData.stateMsg; html.replace("%iconpath%", "qrc"IDR_BLANK); html.replace("%sender%", caption.arg(*lpszUserName)); html.replace("%message%", ""); appendMessageLog(&html); } addToLog = false; break; case MT_Failed: message = pMessage->data(XML_MESSAGE); font.fromString(pMessage->data(XML_FONT)); color.setNamedColor(pMessage->data(XML_COLOR)); html = themeData.sysMsg; caption = tr("Message not delivered to %1:"); fontStyle = getFontStyle(&font, &color, true); decodeMessage(&message); html.replace("%iconpath%", "qrc"IDR_CRITICALMSG); html.replace("%sender%", caption.arg(*lpszUserName)); html.replace("%style%", fontStyle); html.replace("%message%", message); appendMessageLog(&html); lastId = QString::null; break; case MT_Error: html = themeData.sysMsg; html.replace("%iconpath%", "qrc"IDR_CRITICALMSG); html.replace("%sender%", tr("Your message was not sent.")); html.replace("%message%", ""); appendMessageLog(&html); lastId = QString::null; addToLog = false; break; case MT_File: case MT_Folder: appendFileMessage(type, lpszUserName, pMessage, bReload); id = pMessage->data(XML_TEMPID); pMessage->removeData(XML_TEMPID); lastId = QString::null; break; default: break; } if(!bReload && addToLog && pMessage) { wavrXmlMessage xmlMessage = pMessage->clone(); QString userId = lpszUserId ? *lpszUserId : QString::null; QString userName = lpszUserName ? *lpszUserName : QString::null; messageLog.append(SingleMessage(type, userId, userName, xmlMessage, id)); } }
void qmlPlotPaintedItem::appendGraph(QQmlListProperty<qmlGraph> *list, qmlGraph *pdt) { auto& info = Info(list); auto& m_CustomPlot = *info.plot; info.m_graphs.append(pdt); auto makeAxis = [&](QCPAxis* ref, QCPAxis::AxisType type, qmlAxis* qmlAx){ if (qmlAx) { if (!qmlAx->isDefault()) ref = m_CustomPlot.axisRect(0)->addAxis(type); ref->setVisible(qmlAx->isVisible()); if (auto label = qmlAx->getLabel()) { if (!label->getText().isEmpty()) ref->setLabel(label->getText()); if (label->getColor().isValid()) ref->setLabelColor(label->getColor()); if (!label->getFont().isEmpty()) { QFont axFont; axFont.fromString(label->getFont()); ref->setLabelFont(axFont); } } if (auto tick = qmlAx->getTick()) { if (!tick->getFont().isEmpty()) ref->setTickLabelFont(tick->getFont()); const auto& tickVec = tick->getTickVector(); if (!tickVec.empty()) { ref->setAutoTicks(false); ref->setTickVector(tickVec); } const auto& tickLab = tick->getTickLabels(); if (!tickLab.empty()) { ref->setAutoTickLabels(false); ref->setTickVectorLabels(tickLab); } } } return ref; }; auto graph = m_CustomPlot.addGraph( makeAxis(m_CustomPlot.xAxis, QCPAxis::atBottom, pdt->getXAxis()), makeAxis(m_CustomPlot.yAxis, QCPAxis::atLeft, pdt->getYAxis())); graph->setName(pdt->getName()); graph->setPen(pdt->getPen()->getPen()); graph->setLineStyle(pdt->getLineStyle()); if (auto scatterInfo = pdt->getScatter()) { graph->setScatterStyle(scatterInfo->getStyle()); } }
CamlDevWindow::CamlDevWindow(QString wd, QWidget *parent) : QMainWindow(parent) { this->camlProcess = new QProcess(this); this->camlStarted = false; this->currentFile = ""; this->cwd = wd; this->unsavedChanges = false; this->programTitle = "LemonCaml"; /* The window title and icon */ this->setWindowTitle(this->programTitle + " - " + "untitled"); this->setWindowIcon(QIcon(":/progicon.png")); this->settings = new QSettings("Cocodidou", "LemonCaml"); this->globalSettings = new QSettings(QSettings::SystemScope, "Cocodidou", "LemonCaml"); /* The main window elements : two text-areas and a splitter */ this->centralBox = new QVBoxLayout(); this->split = new QSplitter(Qt::Horizontal,this); this->inputZone = new InputZone(); this->inputZone->setTabStopWidth(20); this->inputZone->setAcceptRichText(false); this->resize(settings->value("Size/y",800).toInt(), settings->value("Size/x",600).toInt()); this->move(settings->value("Pos/x",0).toInt(), settings->value("Pos/y",0).toInt()); this->setWindowFlags( (windowFlags() | Qt::CustomizeWindowHint)); #ifndef WIN32 QString defaultFont = "Andale Mono,10,-1,5,50,0,0,0,0,0"; #else QString defaultFont = "Courier New,10,-1,5,50,0,0,0,0,0"; #endif QString iFont = settings->value("Input/Font", defaultFont).toString(); QFont inputFont; inputFont.fromString(iFont); this->inputZone->setFont(inputFont); this->outputZone = new QTextEdit(this); this->outputZone->setReadOnly(true); this->outputZone->setTabStopWidth(20); QString kwfileloc = settings->value("General/keywordspath", (globalSettings->value("General/keywordspath", "./keywords").toString())).toString(); QFile kwfile(kwfileloc); QStringList kwds; if(kwfile.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream kstream(&kwfile); QString st = kstream.readLine(256); while(st != "") { kwds << st; st = kstream.readLine(256); } kwfile.close(); } else { QMessageBox::warning(this, tr("Warning"), tr("Unable to open the keywords file. There will likely be no syntax highlighting.")); } this->hilit = new highlighter(inputZone->document(), &kwds, this->settings); bool isHighlighting = (settings->value("Input/syntaxHighlight",1).toInt() == 1); if(!isHighlighting) { this->hilit->setDocument(NULL); } QString oFont = settings->value("Output/Font", defaultFont).toString(); QFont outputFont; outputFont.fromString(oFont); this->outputZone->setFont(outputFont); /* Find/Replace */ this->find = new findReplace(inputZone, hilit); split->addWidget(this->inputZone); split->addWidget(this->outputZone); split->showMaximized(); centralBox->addWidget(split); centralBox->addWidget(find); if(!centralBox->setStretchFactor(split, 100)) qDebug() << "There will be a problem with Find/replace!"; centralBox->setContentsMargins(0,0,0,0); /* a wrapper widget */ QWidget *window = new QWidget(); window->setLayout(centralBox); window->setContentsMargins(0,0,0,0); this->setCentralWidget(window); find->setVisible(false); if(settings->value("Input/indentOnFly",0).toInt() == 1) inputZone->setHandleEnter(true); /* the printer*/ this->printer = new QPrinter(QPrinter::HighResolution); /* The actions */ this->actionNew = new QAction(tr("New"),this); this->actionNew->setIcon(QIcon(":/new.png")); this->actionNew->setShortcut(QKeySequence(QKeySequence::New)); this->actionOpen = new QAction(tr("Open"),this); this->actionOpen->setIcon(QIcon(":/open.png")); this->actionOpen->setShortcut(QKeySequence(QKeySequence::Open)); this->actionSaveAs = new QAction(tr("Save As"),this); this->actionSaveAs->setIcon(QIcon(":/saveas.png")); this->actionSaveAs->setShortcut(QKeySequence(QKeySequence::SaveAs)); this->actionSave = new QAction(tr("Save"),this); this->actionSave->setIcon(QIcon(":/save.png")); this->actionSave->setShortcut(QKeySequence(QKeySequence::Save)); this->actionAutoIndent = new QAction(tr("Indent code"),this); this->actionAutoIndent->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_W)); this->actionFollowCursor = new QAction(tr("Indent code while typing"),this); this->actionFollowCursor->setCheckable(true); this->actionFollowCursor->setChecked(inputZone->getHandleEnter()); this->actionFollowCursor->setIcon(QIcon(":/autoindent.png")); this->actionPrint = new QAction(tr("Print"),this); this->actionPrint->setIcon(QIcon(":/print.png")); this->actionPrint->setShortcut(QKeySequence(QKeySequence::Print)); this->actionClearOutput = new QAction(tr("Clear output"),this); this->actionQuit = new QAction(tr("Quit"),this); this->actionQuit->setIcon(QIcon(":/exit.png")); this->actionQuit->setShortcut(QKeySequence(QKeySequence::Quit)); this->actionUndo = new QAction(tr("Undo"),this); this->actionUndo->setIcon(QIcon(":/undo.png")); this->actionUndo->setShortcut(QKeySequence(QKeySequence::Undo)); this->actionRedo = new QAction(tr("Redo"),this); this->actionRedo->setIcon(QIcon(":/redo.png")); this->actionRedo->setShortcut(QKeySequence(QKeySequence::Redo)); this->actionDelete = new QAction(tr("Delete"),this); this->actionChangeInputFont = new QAction(tr("Change Input Font"),this); this->actionChangeOutputFont = new QAction(tr("Change Output Font"),this); this->actionSendCaml = new QAction(tr("Send Code to Caml"),this); this->actionSendCaml->setIcon(QIcon(":/sendcaml.png")); this->actionSendCaml->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Return)); this->actionInterruptCaml = new QAction(tr("Interrupt Caml"),this); this->actionInterruptCaml->setIcon(QIcon(":/interrupt.png")); this->actionStopCaml = new QAction(tr("Stop Caml"),this); this->actionStopCaml->setIcon(QIcon(":/stopcaml.png")); this->actionShowSettings = new QAction(tr("Settings"),this); this->actionShowSettings->setShortcut(QKeySequence(QKeySequence::Preferences)); this->actionAbout = new QAction(tr("About LemonCaml..."),this); this->actionAboutQt = new QAction(tr("About Qt..."),this); this->actionHighlightEnable = new QAction(tr("Enable syntax highlighting"), this); this->actionHighlightEnable->setIcon(QIcon(":/highlight.png")); this->actionHighlightEnable->setCheckable(true); this->actionHighlightEnable->setChecked(isHighlighting); this->actionZoomIn = new QAction(tr("Zoom in"), this); this->actionZoomIn->setShortcut(QKeySequence(QKeySequence::ZoomIn)); this->actionZoomOut = new QAction(tr("Zoom out"), this); this->actionZoomOut->setShortcut(QKeySequence(QKeySequence::ZoomOut)); this->actionFind = new QAction(tr("Find/Replace..."), this); this->actionFind->setShortcut(QKeySequence(QKeySequence::Find)); this->actionFind->setIcon(QIcon(":/find.png")); this->actionFind->setCheckable(true); this->actionFind->setChecked(false); /* The toolbar */ this->toolbar = new QToolBar(tr("Tools"),this); this->toolbar->addAction(actionNew); this->toolbar->addAction(actionOpen); this->toolbar->addAction(actionSave); this->toolbar->addAction(actionSaveAs); this->toolbar->addAction(actionPrint); this->toolbar->addSeparator(); this->toolbar->addAction(actionUndo); this->toolbar->addAction(actionRedo); this->toolbar->addSeparator(); this->toolbar->addAction(actionSendCaml); this->toolbar->addAction(actionInterruptCaml); this->toolbar->addAction(actionStopCaml); this->toolbar->addAction(actionHighlightEnable); this->toolbar->addAction(actionFollowCursor); this->addToolBar(this->toolbar); /* The menubar */ this->menuFile = this->menuBar()->addMenu(tr("File")); this->menuFile->addAction(actionNew); this->menuFile->addAction(actionOpen); this->menuRecent = this->menuFile->addMenu(tr("Recent files")); this->menuFile->addAction(actionSave); this->menuFile->addAction(actionSaveAs); this->menuFile->addAction(actionPrint); this->menuFile->addAction(actionQuit); this->menuEdit = this->menuBar()->addMenu(tr("Edit")); this->menuEdit->addAction(actionUndo); this->menuEdit->addAction(actionRedo); this->menuEdit->addAction(actionDelete); this->menuEdit->addSeparator(); this->menuEdit->addAction(actionAutoIndent); this->menuEdit->addAction(actionFollowCursor); this->menuEdit->addSeparator(); this->menuEdit->addAction(actionFind); this->menuEdit->addAction(actionClearOutput); this->menuEdit->addAction(actionHighlightEnable); this->menuEdit->addAction(actionChangeInputFont); this->menuEdit->addAction(actionChangeOutputFont); this->menuEdit->addAction(actionZoomIn); this->menuEdit->addAction(actionZoomOut); this->menuCaml = this->menuBar()->addMenu(tr("Caml")); this->menuCaml->addAction(actionSendCaml); this->menuCaml->addAction(actionInterruptCaml); this->menuCaml->addAction(actionStopCaml); this->menuCaml->addAction(actionShowSettings); this->menuHelp = this->menuBar()->addMenu(tr("Help")); this->menuHelp->addAction(actionAbout); this->menuHelp->addAction(actionAboutQt); /* Connections */ connect(inputZone,SIGNAL(returnPressed()),this,SLOT(handleLineBreak())); connect(actionSendCaml,SIGNAL(triggered()),this,SLOT(sendCaml())); connect(camlProcess,SIGNAL(readyReadStandardOutput()),this,SLOT(readCaml())); connect(camlProcess,SIGNAL(readyReadStandardError()),this,SLOT(readCamlErrors())); connect(camlProcess,SIGNAL(stateChanged(QProcess::ProcessState)),this,SLOT(updateCamlStatus(QProcess::ProcessState))); connect(actionStopCaml,SIGNAL(triggered()),this,SLOT(stopCaml())); connect(camlProcess,SIGNAL(started()),this,SLOT(camlOK())); connect(actionInterruptCaml,SIGNAL(triggered()),this,SLOT(interruptCaml())); connect(actionSave,SIGNAL(triggered()),this,SLOT(save())); connect(actionSaveAs,SIGNAL(triggered()),this,SLOT(saveAs())); connect(actionOpen,SIGNAL(triggered()),this,SLOT(open())); connect(inputZone,SIGNAL(textChanged()),this,SLOT(textChanged())); connect(actionNew,SIGNAL(triggered()),this,SLOT(newFile())); connect(actionClearOutput,SIGNAL(triggered()),this->outputZone,SLOT(clear())); connect(actionChangeInputFont,SIGNAL(triggered()),this,SLOT(changeInputFont())); connect(actionChangeOutputFont,SIGNAL(triggered()),this,SLOT(changeOutputFont())); connect(actionQuit,SIGNAL(triggered()),this,SLOT(close())); connect(actionPrint,SIGNAL(triggered()),this,SLOT(print())); connect(actionUndo,SIGNAL(triggered()),this->inputZone,SLOT(undo())); connect(actionRedo,SIGNAL(triggered()),this->inputZone,SLOT(redo())); connect(actionDelete,SIGNAL(triggered()),this->inputZone,SLOT(paste())); connect(actionShowSettings,SIGNAL(triggered()),this,SLOT(showSettings())); connect(actionHighlightEnable,SIGNAL(toggled(bool)),this,SLOT(toggleHighlightOn(bool))); connect(actionAutoIndent,SIGNAL(triggered()),this,SLOT(autoIndentCode())); connect(actionFollowCursor,SIGNAL(triggered(bool)),this,SLOT(toggleAutoIndentOn(bool))); connect(actionZoomIn,SIGNAL(triggered()),this,SLOT(zoomIn())); connect(actionZoomOut,SIGNAL(triggered()),this,SLOT(zoomOut())); connect(actionFind,SIGNAL(triggered(bool)),this,SLOT(triggerFindReplace(bool))); connect(find,SIGNAL(hideRequest(bool)),this,SLOT(triggerFindReplace(bool))); connect(inputZone, SIGNAL(unindentKeyStrokePressed()), this, SLOT(unindent())); connect(actionAbout,SIGNAL(triggered()),this,SLOT(about())); connect(actionAboutQt,SIGNAL(triggered()),this,SLOT(aboutQt())); this->generateRecentMenu(); this->populateRecent(); this->highlightTriggered = false; fillIndentWords(&indentWords); //Draw trees? this->drawTrees = (settings->value("General/drawTrees",0).toInt() == 1)?true:false; this->graphCount = 0; this->startCamlProcess(); }
static bool convert(const QVariant::Private *d, QVariant::Type t, void *result, bool *ok) { switch (t) { case QVariant::ByteArray: if (d->type == QVariant::Color) { *static_cast<QByteArray *>(result) = v_cast<QColor>(d)->name().toLatin1(); return true; } break; case QVariant::String: { QString *str = static_cast<QString *>(result); switch (d->type) { #ifndef QT_NO_SHORTCUT case QVariant::KeySequence: *str = QString(*v_cast<QKeySequence>(d)); return true; #endif case QVariant::Font: *str = v_cast<QFont>(d)->toString(); return true; case QVariant::Color: *str = v_cast<QColor>(d)->name(); return true; default: break; } break; } case QVariant::Pixmap: if (d->type == QVariant::Image) { *static_cast<QPixmap *>(result) = QPixmap::fromImage(*v_cast<QImage>(d)); return true; } else if (d->type == QVariant::Bitmap) { *static_cast<QPixmap *>(result) = *v_cast<QBitmap>(d); return true; } else if (d->type == QVariant::Brush) { if (v_cast<QBrush>(d)->style() == Qt::TexturePattern) { *static_cast<QPixmap *>(result) = v_cast<QBrush>(d)->texture(); return true; } } break; case QVariant::Image: if (d->type == QVariant::Pixmap) { *static_cast<QImage *>(result) = v_cast<QPixmap>(d)->toImage(); return true; } else if (d->type == QVariant::Bitmap) { *static_cast<QImage *>(result) = v_cast<QBitmap>(d)->toImage(); return true; } break; case QVariant::Bitmap: if (d->type == QVariant::Pixmap) { *static_cast<QBitmap *>(result) = *v_cast<QPixmap>(d); return true; } else if (d->type == QVariant::Image) { *static_cast<QBitmap *>(result) = QBitmap::fromImage(*v_cast<QImage>(d)); return true; } break; #ifndef QT_NO_SHORTCUT case QVariant::Int: if (d->type == QVariant::KeySequence) { *static_cast<int *>(result) = (int)(*(v_cast<QKeySequence>(d))); return true; } break; #endif case QVariant::Font: if (d->type == QVariant::String) { QFont *f = static_cast<QFont *>(result); f->fromString(*v_cast<QString>(d)); return true; } break; case QVariant::Color: if (d->type == QVariant::String) { static_cast<QColor *>(result)->setNamedColor(*v_cast<QString>(d)); return static_cast<QColor *>(result)->isValid(); } else if (d->type == QVariant::ByteArray) { static_cast<QColor *>(result)->setNamedColor(QString::fromLatin1( *v_cast<QByteArray>(d))); return true; } else if (d->type == QVariant::Brush) { if (v_cast<QBrush>(d)->style() == Qt::SolidPattern) { *static_cast<QColor *>(result) = v_cast<QBrush>(d)->color(); return true; } } break; case QVariant::Brush: if (d->type == QVariant::Color) { *static_cast<QBrush *>(result) = QBrush(*v_cast<QColor>(d)); return true; } else if (d->type == QVariant::Pixmap) { *static_cast<QBrush *>(result) = QBrush(*v_cast<QPixmap>(d)); return true; } break; #ifndef QT_NO_SHORTCUT case QVariant::KeySequence: { QKeySequence *seq = static_cast<QKeySequence *>(result); switch (d->type) { case QVariant::String: *seq = QKeySequence(*v_cast<QString>(d)); return true; case QVariant::Int: *seq = QKeySequence(d->data.i); return true; default: break; } } #endif default: break; } return qcoreVariantHandler()->convert(d, t, result, ok); }
bool RGBText::loadXML(const QDomElement& root) { if (root.tagName() != KXMLQLCRGBAlgorithm) { qWarning() << Q_FUNC_INFO << "RGB Algorithm node not found"; return false; } if (root.attribute(KXMLQLCRGBAlgorithmType) != KXMLQLCRGBText) { qWarning() << Q_FUNC_INFO << "RGB Algorithm is not Text"; return false; } QDomNode node = root.firstChild(); while (node.isNull() == false) { QDomElement tag = node.toElement(); if (tag.tagName() == KXMLQLCRGBTextContent) { setText(tag.text()); } else if (tag.tagName() == KXMLQLCRGBTextFont) { QFont font; if (font.fromString(tag.text()) == true) setFont(font); else qWarning() << Q_FUNC_INFO << "Invalid font:" << tag.text(); } else if (tag.tagName() == KXMLQLCRGBTextAnimationStyle) { setAnimationStyle(stringToAnimationStyle(tag.text())); } else if (tag.tagName() == KXMLQLCRGBTextOffset) { QString str; int value; bool ok; str = tag.attribute(KXMLQLCRGBTextOffsetX); ok = false; value = str.toInt(&ok); if (ok == true) setXOffset(value); else qWarning() << Q_FUNC_INFO << "Invalid X offset:" << str; str = tag.attribute(KXMLQLCRGBTextOffsetY); ok = false; value = str.toInt(&ok); if (ok == true) setYOffset(value); else qWarning() << Q_FUNC_INFO << "Invalid Y offset:" << str; } else { qWarning() << Q_FUNC_INFO << "Unknown RGBText tag:" << tag.tagName(); } node = node.nextSibling(); } return true; }
/** * @brief Returns html rendered markdown of the note text * @param notesPath for transforming relative local urls to absolute ones * @param maxImageWidth defined maximum image width (ignored if forExport is true) * @param forExport defines whether the export or preview stylesheet * @return */ QString Note::toMarkdownHtml(QString notesPath, int maxImageWidth, bool forExport) { hoedown_renderer *renderer = hoedown_html_renderer_new(HOEDOWN_HTML_USE_XHTML, 16); hoedown_extensions extensions = (hoedown_extensions) (HOEDOWN_EXT_BLOCK | HOEDOWN_EXT_SPAN); hoedown_document *document = hoedown_document_new(renderer, extensions, 16); // get the decrypted note text (or the normal note text if there isn't any) QString str = getDecryptedNoteText(); QString windowsSlash = ""; #ifdef Q_OS_WIN32 // we need an other slash for Windows windowsSlash = "/"; #endif // parse for relative file urls and make them absolute // (for example to show images under the note path) str.replace( QRegularExpression("\\(file:\\/\\/([^\\/].+)\\)"), "(file://" + windowsSlash + notesPath + "/\\1)"); unsigned char *sequence = (unsigned char *) qstrdup( str.toUtf8().constData()); qint64 length = strlen((char *) sequence); // return an empty string if the note is empty if (length == 0) { return ""; } hoedown_buffer *html = hoedown_buffer_new(length); // render markdown html hoedown_document_render(document, html, sequence, length); // get markdown html QString result = QString::fromUtf8((char *) html->data, html->size); /* Cleanup */ free(sequence); hoedown_buffer_free(html); hoedown_document_free(document); hoedown_html_renderer_free(renderer); QSettings(settings); QString fontString = settings.value("MainWindow/noteTextView.code.font") .toString(); // set the stylesheet for the <code> blocks QString codeStyleSheet = ""; if (fontString != "") { // set the note text view font QFont font; font.fromString(fontString); // add the font for the code block codeStyleSheet = QString( "pre, code { %1; }").arg(encodeCssFont(font)); } bool darkModeColors = settings.value("darkModeColors").toBool(); QString codeBackgroundColor = darkModeColors ? "#444444" : "#f1f1f1"; // do some more code formatting codeStyleSheet += QString( "pre, code { padding: 16px; overflow: auto;" " line-height: 1.45em; background-color: %1;" " border-radius: 3px; }").arg(codeBackgroundColor); // remove double code blocks result.replace("<pre><code>", "<pre>") .replace("</code></pre>", "</pre>"); if (forExport) { // get defined body font from settings QString bodyfontString = settings.value("MainWindow/noteTextView.font") .toString(); // create export stylesheet QString exportStyleSheet = ""; if (bodyfontString != "") { QFont bodyFont; bodyFont.fromString(bodyfontString); exportStyleSheet = QString( "body { %1; }").arg(encodeCssFont(bodyFont)); } result = QString("<html><head><meta charset=\"utf-8\"/><style>" "h1 { margin: 5px 0 20px 0; }" "h2, h3 { margin: 10px 0 15px 0; }" "img { max-width: 100%; }" "a { color: #FF9137; text-decoration: none; } %1 %2" "</style></head><body>%3</body></html>") .arg(codeStyleSheet, exportStyleSheet, result); } else { // for preview result = QString("<html><head><style>" "h1 { margin: 5px 0 20px 0; }" "h2, h3 { margin: 10px 0 15px 0; }" "a { color: #FF9137; text-decoration: none; } %1" "</style></head><body>%2</body></html>") .arg(codeStyleSheet, result); } // check if width of embedded local images is too high QRegularExpression re("<img src=\"file:\\/\\/([^\"]+)\""); QRegularExpressionMatchIterator i = re.globalMatch(result); while (i.hasNext()) { QRegularExpressionMatch match = i.next(); QString fileName = match.captured(1); #ifdef Q_OS_WIN // remove the leading slash under Windows to get a more correct filename QImage image(Utils::Misc::removeIfStartsWith(fileName, "/")); #else QImage image(fileName); #endif if (forExport) { result.replace( QRegularExpression("<img src=\"file:\\/\\/" + QRegularExpression::escape(fileName) + "\""), QString("<img src=\"file://%2\"").arg(fileName)); } else { // for preview // cap the image width at 980px or the note text view width if (image.width() > maxImageWidth) { result.replace( QRegularExpression("<img src=\"file:\\/\\/" + QRegularExpression::escape(fileName) + "\""), QString("<img width=\"%1\" src=\"file://%2\"").arg( QString::number(maxImageWidth), fileName)); } } } // check if there is a script that wants to modify the content QString scriptResult = ScriptingService::instance() ->callNoteToMarkdownHtmlHook(this, result); if (!scriptResult.isEmpty()) { result = scriptResult; } return result; }
QImage* MyTextEffect::drawImage() { QFont myFont; QPen myPen; myPen.setJoinStyle( Qt::RoundJoin ); QBrush myBrush( QColor(0,0,0,0) ); QColor backgroundColor(0,0,0,0); int outline = 0; int align = 1; int arrowType = 0, arrowSize = 0, arrowPos = 0; QStringList sl = currentText.split("\n"); while ( !sl.isEmpty() ) { if ( sl.last().trimmed().isEmpty() ) sl.takeLast(); else break; } if ( sl.count() ) { QStringList desc = sl[0].split("|"); if ( desc.count() >= 9 ) { myFont.fromString( desc[0] ); myFont.setPointSize( desc[1].toInt() ); myFont.setBold( desc[2].toInt() ); myFont.setItalic( desc[3].toInt() ); QStringList fc = desc[4].split( "." ); if ( fc.count() == 2 ) { QColor col; col.setNamedColor( fc[ 0 ] ); col.setAlpha( fc[ 1 ].toInt() ); myPen.setColor( col ); myBrush.setColor( col ); } QStringList bc = desc[5].split( "." ); if ( bc.count() == 2 ) { backgroundColor.setNamedColor( bc[ 0 ] ); backgroundColor.setAlpha( bc[ 1 ].toInt() ); } align = desc[6].toInt(); int osize = desc[7].toInt(); if ( osize > 0 ) { QStringList oc = desc[8].split( "." ); if ( oc.count() == 2 ) { outline = osize; myPen.setWidth( osize ); myFont.setStyleStrategy( QFont::ForceOutline ); QColor col; col.setNamedColor( oc[ 0 ] ); col.setAlpha( oc[ 1 ].toInt() ); myPen.setColor( col ); } } } if ( desc.count() >= 12 ) { arrowType = desc[9].toInt(); arrowSize = desc[10].toInt(); arrowPos = desc[11].toInt(); } sl.takeFirst(); } QImage *image = new QImage( 10, 10, QImage::Format_ARGB32_Premultiplied ); QPainter painter; painter.begin( image ); painter.setPen( myPen ); painter.setBrush( myBrush ); painter.setFont( myFont ); QList<QRectF> br; QFontMetrics metrics( myFont ); int h = sl.count() * metrics.lineSpacing(); int w = 0; for ( int i = 0; i < sl.count(); ++i ) { QRectF minrect( 0, 0, 1, 1 ); QRectF r = painter.boundingRect( minrect, Qt::AlignHCenter | Qt::AlignVCenter, sl[i] ); if ( r.width() > w ) w = r.width(); br.append( r ); } QRectF minrect( 0, 0, 1, 1 ); int margin = qMax( painter.boundingRect( minrect, Qt::AlignHCenter | Qt::AlignVCenter, "M" ).width() / 3.0, 3.0 ); painter.end(); double x = ((double)outline + margin * 2) / 2.0; double y = x; w += 2 * x; h += 2 * y; if ( w > iwidth ) { x -= (w - iwidth) / 2.0; w = iwidth; } if ( h > iheight ) { y -= (h - iheight) / 2.0; h = iheight; } QPointF polygon[7]; arrowSize = h * arrowSize / 100.0; int n = 0; int leftOffset = 0, topOffset = 0; int wMargin = 0, hMargin = 0; if (arrowType) { switch (arrowType) { case 1: { leftOffset = arrowSize; wMargin = arrowSize; polygon[n].setX(1 + arrowSize); polygon[n++].setY(1); polygon[n].setY(qMax(1.0, qMin(h - 1.0, h * arrowPos / 100.0 - arrowSize / 2.0) ) ); polygon[n++].setX(1 + arrowSize); polygon[n].setY(qMax(1.0, qMin(h - 1.0, h * arrowPos / 100.0) ) ); polygon[n++].setX(1); polygon[n].setY(qMax(1.0, qMin(h - 1.0, h * arrowPos / 100.0 + arrowSize / 2.0) ) ); polygon[n++].setX(1 + arrowSize); polygon[n].setX(1 + arrowSize); polygon[n++].setY(h - 1); polygon[n].setX(w - 1 + arrowSize); polygon[n++].setY(h - 1); polygon[n].setX(w - 1 + arrowSize); polygon[n++].setY(1); break; } case 2: { wMargin = arrowSize; polygon[n].setX(1); polygon[n++].setY(1); polygon[n].setX(1); polygon[n++].setY(h - 1); polygon[n].setX(w - 1); polygon[n++].setY(h - 1); polygon[n].setY(qMax(1.0, qMin(h - 1.0, h * arrowPos / 100.0 + arrowSize / 2.0) ) ); polygon[n++].setX(w - 1); polygon[n].setY(qMax(1.0, qMin(h - 1.0, h * arrowPos / 100.0) ) ); polygon[n++].setX(w - 1 + arrowSize); polygon[n].setY(qMax(1.0, qMin(h - 1.0, h * arrowPos / 100.0 - arrowSize / 2.0) ) ); polygon[n++].setX(w - 1); polygon[n].setX(w - 1); polygon[n++].setY(1); break; } case 3: { topOffset = arrowSize; hMargin = arrowSize; polygon[n].setX(1); polygon[n++].setY(1 + arrowSize); polygon[n].setX(1); polygon[n++].setY(h - 1 + arrowSize); polygon[n].setX(w - 1); polygon[n++].setY(h - 1 + arrowSize); polygon[n].setX(w - 1); polygon[n++].setY(1 + arrowSize); polygon[n].setX(qMax(1.0, qMin(w - 1.0, w * arrowPos / 100.0 + arrowSize / 2.0) ) ); polygon[n++].setY(1 + arrowSize); polygon[n].setX(qMax(1.0, qMin(w - 1.0, w * arrowPos / 100.0) ) ); polygon[n++].setY(1); polygon[n].setX(qMax(1.0, qMin(w - 1.0, w * arrowPos / 100.0 - arrowSize / 2.0) ) ); polygon[n++].setY(1 + arrowSize); break; } case 4: { hMargin = arrowSize; polygon[n].setX(1); polygon[n++].setY(1); polygon[n].setX(1); polygon[n++].setY(h - 1); polygon[n].setX(qMax(1.0, qMin(w - 1.0, w * arrowPos / 100.0 - arrowSize / 2.0) ) ); polygon[n++].setY(h - 1); polygon[n].setX(qMax(1.0, qMin(w - 1.0, w * arrowPos / 100.0) ) ); polygon[n++].setY(h - 1 + arrowSize); polygon[n].setX(qMax(1.0, qMin(w - 1.0, w * arrowPos / 100.0 + arrowSize / 2.0) ) ); polygon[n++].setY(h - 1); polygon[n].setX(w - 1); polygon[n++].setY(h - 1); polygon[n].setX(w - 1); polygon[n++].setY(1); break; } } } delete image; image = new QImage( w + wMargin, h + hMargin, QImage::Format_ARGB32_Premultiplied ); image->fill( QColor(0,0,0,0) ); painter.begin( image ); painter.setRenderHints( QPainter::Antialiasing | QPainter::TextAntialiasing ); if ( backgroundColor.alpha() > 0 ) { painter.setPen( QColor(0,0,0,0) ); painter.setBrush( backgroundColor ); if (arrowType) { painter.drawPolygon( polygon, 7 ); } else { painter.drawRect( 1, 1, w - 2, h - 2 ); } } painter.setPen( myPen ); painter.setBrush( myBrush ); painter.setFont( myFont ); for ( int i = 0; i < sl.count(); ++i ) { QPointF point( 0, y + topOffset + metrics.ascent() ); switch ( align ) { case 2: { point.setX( leftOffset + (double)w / 2.0 - br[i].width() / 2.0 ); break; } case 3: { point.setX( leftOffset + w - x - br[i].width() ); break; } default: { point.setX( leftOffset + x ); break; } } if ( outline ) { QPainterPath myPath; myPath.addText( point, myFont, sl[i] ); painter.drawPath( myPath ); } else painter.drawText( point, sl[i] ); y += metrics.lineSpacing(); } painter.end(); return image; }