TextEdit::TextEdit(QWidget *parent) : QMainWindow(parent) { setToolButtonStyle(Qt::ToolButtonFollowStyle); setupFileActions(); setupEditActions(); setupTextActions(); { // QMenu *helpMenu = new QMenu(tr("Help"), this); // menuBar()->addMenu(helpMenu); // helpMenu->addAction(tr("About"), this, SLOT(about())); // helpMenu->addAction(tr("About &Qt"), qApp, SLOT(aboutQt())); } textEdit = new QTextEdit(this); ////////////////////////////////////////////////// connect(textEdit, SIGNAL(currentCharFormatChanged(QTextCharFormat)), this, SLOT(currentCharFormatChanged(QTextCharFormat))); connect(textEdit, SIGNAL(cursorPositionChanged()), this, SLOT(cursorPositionChanged())); /////////// //setCentralWidget(textEdit); //blank=new Blank(this); //setCentralWidget(blank); //create a transparent canvas and put it on the top of textEdit image =new MyCanvas(900,800,this); textEdit->setFixedSize(QSize(800,800)); textEdit->setBackgroundRole(QPalette::Light); //scrollArea对象的背景色设为Dark image->setFixedSize(QSize(800,800)); image->setStyleSheet(QString::fromUtf8("border:1px solid #000000;")); QScrollArea* scrollArea = new QScrollArea; scrollArea->setFixedSize(QSize(1800,900)); //scrollArea->setWidget(image); //将画布添加到scrollArea中 scrollArea->setBackgroundRole(QPalette::Light); //scrollArea对象的背景色设为Dark //scrollArea->setBackgroundColor(QColor::white); // QStackedLayout *stackedLayout = new QStackedLayout; // stackedLayout->addWidget(image); // stackedLayout->addWidget(textEdit); // stackedLayout->setStackingMode(QStackedLayout::StackAll); QHBoxLayout* hLayout=new QHBoxLayout(); hLayout->addWidget(textEdit); hLayout->addWidget(image); // scrollArea->setLayout(stackedLayout); scrollArea->setLayout(hLayout); //scrollArea->setGeometry(QRect(50,50,800,800)); setCentralWidget(scrollArea); //将scrollArea加入到主窗口的中心区new QPainter(this); scrollArea->setAlignment(Qt::AlignHCenter); //after canvas handle the mouse-drag event, emit it to the edittext for farther handling connect(image,SIGNAL(mouseMoveSig(QMouseEvent*)),this,SLOT(onMouseMove(QMouseEvent*))); //connect(image,SIGNAL(mouseMoveSig(QMouseEvent*)),textEdit,SLOT(mouseMoveEvent(QMouseEvent*))); //connect(image,SIGNAL(mouseMoveSig(QMouseEvent*)),textEdit,SLOT(cursorPositionChanged(QMouseEvent*))); //connect(this,SIGNAL(mouseMoveSig(QMouseEvent*)),image,SLOT(mouseMoveSlot(QMouseEvent*))); //connect(textEdit,SIGNAL(mouseMoveEvent(QMouseEvent*)),image,SLOT(mouseMoveSlot(QMouseEvent*))); // textEdit->setFocus(); setCurrentFileName(QString()); fontChanged(textEdit->font()); colorChanged(textEdit->textColor()); alignmentChanged(textEdit->alignment()); connect(textEdit->document(), SIGNAL(modificationChanged(bool)), actionSave, SLOT(setEnabled(bool))); connect(textEdit->document(), SIGNAL(modificationChanged(bool)), this, SLOT(setWindowModified(bool))); connect(textEdit->document(), SIGNAL(undoAvailable(bool)), actionUndo, SLOT(setEnabled(bool))); connect(textEdit->document(), SIGNAL(redoAvailable(bool)), actionRedo, SLOT(setEnabled(bool))); setWindowModified(textEdit->document()->isModified()); actionSave->setEnabled(textEdit->document()->isModified()); actionUndo->setEnabled(textEdit->document()->isUndoAvailable()); actionRedo->setEnabled(textEdit->document()->isRedoAvailable()); connect(actionUndo, SIGNAL(triggered()), textEdit, SLOT(undo())); connect(actionRedo, SIGNAL(triggered()), textEdit, SLOT(redo())); actionCut->setEnabled(false); actionCopy->setEnabled(false); connect(actionCut, SIGNAL(triggered()), textEdit, SLOT(cut())); connect(actionCopy, SIGNAL(triggered()), textEdit, SLOT(copy())); connect(actionPaste, SIGNAL(triggered()), textEdit, SLOT(paste())); connect(textEdit, SIGNAL(copyAvailable(bool)), actionCut, SLOT(setEnabled(bool))); connect(textEdit, SIGNAL(copyAvailable(bool)), actionCopy, SLOT(setEnabled(bool))); #ifndef QT_NO_CLIPBOARD connect(QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(clipboardDataChanged())); #endif //QString initialFile = ":/data/example.html"; QString initialFile = ":/data/test.txt"; const QStringList args = QCoreApplication::arguments(); if (args.count() == 2) initialFile = args.at(1); if (!load(initialFile)) fileNew(); }
QT_USE_NAMESPACE int main(int argc, char **argv) { Q_INIT_RESOURCE(linguist); QApplication app(argc, argv); QApplication::setOverrideCursor(Qt::WaitCursor); QStringList files; QString resourceDir = QLibraryInfo::location(QLibraryInfo::TranslationsPath); QStringList args = app.arguments(); for (int i = 1; i < args.count(); ++i) { QString argument = args.at(i); if (argument == QLatin1String("-resourcedir")) { if (i + 1 < args.count()) { resourceDir = QFile::decodeName(args.at(++i).toLocal8Bit()); } else { // issue a warning } } else if (!files.contains(argument)) { files.append(argument); } } QTranslator translator; QTranslator qtTranslator; QString sysLocale = QLocale::system().name(); if (translator.load(QLatin1String("linguist_") + sysLocale, resourceDir)) { app.installTranslator(&translator); if (qtTranslator.load(QLatin1String("qt_") + sysLocale, resourceDir)) app.installTranslator(&qtTranslator); else app.removeTranslator(&translator); } app.setOrganizationName(QLatin1String("Trolltech")); app.setApplicationName(QLatin1String("Linguist")); QSettings config; QWidget tmp; tmp.restoreGeometry(config.value(settingPath("Geometry/WindowGeometry")).toByteArray()); QSplashScreen *splash = 0; int screenId = QApplication::desktop()->screenNumber(tmp.geometry().center()); splash = new QSplashScreen(QApplication::desktop()->screen(screenId), QPixmap(QLatin1String(":/images/splash.png"))); if (QApplication::desktop()->isVirtualDesktop()) { QRect srect(0, 0, splash->width(), splash->height()); splash->move(QApplication::desktop()->availableGeometry(screenId).center() - srect.center()); } splash->setAttribute(Qt::WA_DeleteOnClose); splash->show(); MainWindow mw; mw.show(); splash->finish(&mw); QApplication::restoreOverrideCursor(); mw.openFiles(files, true); return app.exec(); }
void sortByProtocol(QStringList &sortList) { // Карта для хранения ссылок по протоколу доступа // Ключ карты - имя , значения - список путь QMap<protocolType, QStringList> sortingMap; QStringList res; // Результирующий лист QString temp; // Буфер для текущей обрабатываемой строки QString buf; // Буфер для ключа - домена QString str; // Буфер для одного из значений ключа - имени адреса QString aIterKlein; // Буфер для строки из списка для каждой строки из списка // Заполнение карты путей for(int i=0; i<sortList.count(); i++) { // Загрузка в бущер текущей строки для сортировки temp=sortList[i]; // Условия для разных протоколов доступа if(temp.contains("DHCP")) { // Получение адреса str=temp.remove(QString("DHCP:")); // Заполнение значение карты sortingMap[dhcp]<<temp; } else if(temp.contains("DNS")) { // Получение адреса str=temp.remove(QString("DNS:")); // Заполнение значение карты sortingMap[dns]<<temp; } else if(temp.contains("ftp")) { // Получение адреса str=temp.remove(QString("ftp://")); // Заполнение значение карты sortingMap[ftp]<<temp; } else if(temp.contains("https")) { // Получение адреса str=temp.remove(QString("https://")); // Заполнение значение карты sortingMap[https]<<temp; } else if(temp.contains("http")) { // Получение адреса str=temp.remove(QString("http://")); // Заполнение значение карты sortingMap[http]<<temp; } else if(temp.contains("nntp")) { // Заполнение значение карты sortingMap[nntp]<<temp; } else if(temp.contains("ntp")) { // Заполнение значение карты sortingMap[ntp]<<temp; } else if(temp.contains("@") && temp.indexOf(":", temp.indexOf("@"))!=-1) { // Заполнение значение карты sortingMap[ssh]<<temp; } else if(temp.contains("telnet")) { // Получение адреса str=temp.remove(QString("telnet://")); // Заполнение значение карты sortingMap[telnet]<<temp; } else { // Заполнение значение карты sortingMap[otherProtocol]<<temp; } } // Сортировка значений для каждого ключа QMap<protocolType, QStringList>::iterator it=sortingMap.begin(); for(;it!=sortingMap.end(); it++) { if(it.value().count()>1) { sortByLexeme(it.value()); } } // Загрузка в выходной лист значений для определенного ключа for(int k=0; k<sortingMap[dhcp].count(); k++) { // Загрузка в буфер текущей строки для сортировки aIterKlein="DHCP:"+sortingMap[dhcp][k]; // Добавление строки в выходной лист res<<aIterKlein; } for(int k=0; k<sortingMap[dns].count(); k++) { // Загрузка в буфер текущей строки для сортировки aIterKlein="DNS:"+sortingMap[dns][k]; // Добавление строки в выходной лист res<<aIterKlein; } for(int k=0; k<sortingMap[ftp].count(); k++) { // Загрузка в буфер текущей строки для сортировки aIterKlein="ftp://"+sortingMap[ftp][k]; // Добавление строки в выходной лист res<<aIterKlein; } for(int k=0; k<sortingMap[http].count(); k++) { // Загрузка в буфер текущей строки для сортировки aIterKlein="http://"+sortingMap[http][k]; // Добавление строки в выходной лист res<<aIterKlein; } for(int k=0; k<sortingMap[https].count(); k++) { // Загрузка в буфер текущей строки для сортировки aIterKlein="https://"+sortingMap[https][k]; // Добавление строки в выходной лист res<<aIterKlein; } for(int k=0; k<sortingMap[ntp].count(); k++) { // Добавление строки в выходной лист res<<sortingMap[ntp][k]; } for(int k=0; k<sortingMap[nntp].count(); k++) { // Добавление строки в выходной лист res<<sortingMap[nntp][k]; } for(int k=0; k<sortingMap[ssh].count(); k++) { // Добавление строки в выходной лист res<<sortingMap[ssh][k]; } for(int k=0; k<sortingMap[telnet].count(); k++) { // Загрузка в буфер текущей строки для сортировки aIterKlein="telnet://"+sortingMap[telnet][k]; // Добавление строки в выходной лист res<<aIterKlein; } for(int k=0; k<sortingMap[otherProtocol].count(); k++) { // Добавление строки в выходной лист res<<sortingMap[otherProtocol][k]; } // Замена данного листа на возвращаемый sortList=res; }
bool KoStarShape::loadOdf( const KoXmlElement & element, KoShapeLoadingContext & context ) { bool loadAsCustomShape = false; if( element.localName() == "custom-shape" ) { QString drawEngine = element.attributeNS( KoXmlNS::draw, "engine", "" ); if( drawEngine != "koffice:star" ) return false; loadAsCustomShape = true; } else if( element.localName() != "regular-polygon" ) { return false; } QPointF loadedPosition = position(); m_radius[tip] = 50; m_center = QPointF(50,50); if( ! loadAsCustomShape ) { QString corners = element.attributeNS( KoXmlNS::draw, "corners", "" ); if( ! corners.isEmpty() ) { m_cornerCount = corners.toUInt(); // initialize default angles of tip and base m_angles[base] = m_angles[tip] = defaultAngleRadian(); } m_convex = (element.attributeNS( KoXmlNS::draw, "concave", "false" ) == "false" ); if( m_convex ) { m_radius[base] = m_radius[tip]; } else { // sharpness is radius of ellipse on which inner polygon points are located // 0% means all polygon points are on a single ellipse // 100% means inner points are located at polygon center point QString sharpness = element.attributeNS( KoXmlNS::draw, "sharpness", "" ); if( ! sharpness.isEmpty() && sharpness.right( 1 ) == "%" ) { float percent = sharpness.left( sharpness.length()-1 ).toFloat(); m_radius[base] = m_radius[tip] * (100-percent)/100; } } } else { QString drawData = element.attributeNS( KoXmlNS::draw, "data" ); if( drawData.isEmpty() ) return false; QStringList properties = drawData.split( ';' ); if( properties.count() == 0 ) return false; foreach( const QString &property, properties ) { QStringList pair = property.split( ':' ); if( pair.count() != 2 ) continue; if( pair[0] == "corners" ) { m_cornerCount = pair[1].toInt(); } else if( pair[0] == "concave" ) { m_convex = (pair[1] == "false"); } else if( pair[0] == "baseRoundness" ) { m_roundness[base] = pair[1].toDouble(); } else if( pair[0] == "tipRoundness" ) { m_roundness[tip] = pair[1].toDouble(); } else if( pair[0] == "baseAngle" ) { m_angles[base] = pair[1].toDouble(); } else if( pair[0] == "tipAngle" ) { m_angles[tip] = pair[1].toDouble(); } else if( pair[0] == "sharpness" ) { float percent = pair[1].left( pair[1].length()-1 ).toFloat(); m_radius[base] = m_radius[tip] * (100-percent)/100; } } if( m_convex ) { m_radius[base] = m_radius[tip]; } }
/* Message type "C2ACamion" "0-02:06:18.040" "EngSpeed 898,500 rpm" "Accel 0,0 %" "TCO 114,30 km/h MD:0 OS:0 DI:0 TP:0 HI:0 EV:0 D1:0/0/0 D2:0/0/0" "Speed 114,30 km/h CC:0 BR:0 CS:0 PB:0" "Distance 0,000 km" "EngHours 1,90 h" "FuelC 0,0 L" "EngTemp +61 degr" "FuelLev 36,8 %" "VehID azerty" "FMS 02.51 Diag:0 Requ:0" "Gear S:* C:*" "DoorCtr1 P:* R:* S:*" "DC2 loe 1:* 2:* 3:* 4:* 5:* 6:* 7:* 8:* 9:* 10:*" "BellowPr FAL:* kPa FAR:* kPa RAL:* kPa RAR:* kPa" "BrakePr 1:* kPa 2:* kPa" "Alternat 1:* 2:* 3:* 4:*" "DateTime *" "AmbTemp * degr" */ void CPluginCANGine::parseToMessage () { QStringList list = m_message.split('\n'); if (2 < list.count()) { QStringList list_engspeed = list[2].split(QRegExp("\\s+")); if (1 < list_engspeed.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_ENGSPEED" , list_engspeed[1]); } } if (3 < list.count()) { QStringList list_accel = list[3].split(QRegExp("\\s+")); if (1 < list_accel.count() ) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_ACCEL" , list_accel[1]); } } if (4 < list.count()) { QStringList list_tco = list[4].split(QRegExp("\\s+")); if (1 < list_tco.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_TCO" , list_tco[1]); } if (3 < list_tco.count()) { QStringList list_tco_md = list_tco[3].split(":"); if (1 < list_tco_md.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_TCO_MD" , list_tco_md [1]); } } if (4 < list_tco.count()) { QStringList list_tco_os = list_tco[4].split(":"); if (1 < list_tco_os.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_TCO_OS" ,list_tco_os[1]); } } if (5 < list_tco.count()) { QStringList list_tco_di = list_tco[5].split(":"); if (1 < list_tco_di.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_TCO_DI" , list_tco_di[1]); } } if (6 < list_tco.count()) { QStringList list_tco_tp = list_tco[6].split(":"); if (1 < list_tco_tp.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_TCO_TP" , list_tco_tp[1]); } } if (7 < list_tco.count()) { QStringList list_tco_hi = list_tco[7].split(":"); if (1 < list_tco_hi.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_TCO_HI" ,list_tco_hi[1]); } } if (8 < list_tco.count()) { QStringList list_tco_ev = list_tco[8].split(":"); if (1 < list_tco_ev.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_TCO_EV" , list_tco_ev[1]); } } if (9 < list_tco.count()) { QStringList list_tch_d1 = list_tco[9].split(":"); if (1 < list_tch_d1.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_TCO_D1" , list_tch_d1[1]); } } if (10 < list_tco.count()) { QStringList list_tch_d2 = list_tco[10].split(":"); if (1 < list_tch_d2.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_TCO_D2" , list_tch_d2[1]); } } } if (5 < list.count()) { QStringList list_speed = list[5].split(QRegExp("\\s+")); if (1 < list_speed.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_SPEED" , list_speed[1]); } if (3 < list_speed.count()) { QStringList list_speed_cc = list_speed[3].split(":"); if (1 < list_speed_cc.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_SPEED_CC" , list_speed_cc[1]); } } if (4 < list_speed.count()) { QStringList list_speed_br = list_speed[4].split(":"); if (1 < list_speed_br.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_SPEED_BR" , list_speed_br[1]); } } if (5 < list_speed.count()) { QStringList list_speed_cs = list_speed[5].split(":"); if (1 < list_speed_cs.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_SPEED_CS" , list_speed_cs[1]); } } if (6 < list_speed.count()) { QStringList list_speed_pb = list_speed[6].split(":"); if (1 < list_speed_pb.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_SPEED_PB" , list_speed_pb[1]); } } } if (6 < list.count()) { QStringList list_distance = list[6].split(QRegExp("\\s+")); if (1 < list_distance.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DISTANCE" , list_distance[1]); } } if (7 < list.count()) { QStringList list_enghours = list[7].split(QRegExp("\\s+")); if (1 < list_enghours.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_ENGHOURS" , list_enghours[1]); } } if (8 < list.count()) { QStringList list_fuelc = list[8].split(QRegExp("\\s+")); if (1 < list_fuelc.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_FUELC" , list_fuelc[1]); } } if (9 < list.count()) { QStringList list_engtemp = list[9].split(QRegExp("\\s+")); if (1 < list_engtemp.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_ENGTEMP" , list_engtemp[1]); } } if (10 < list.count()) { QStringList list_fuellev = list[10].split(QRegExp("\\s+")); if (1 < list_fuellev.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_FUELLEV" , list_fuellev[1]); } } if (11 < list.count()) { QStringList list_vehid = list[11].split(QRegExp("\\s+")); if (1 < list_vehid.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_VEHID" , list_vehid[1]); } } if (12 < list.count()) { QStringList list_fms = list[12].split(QRegExp("\\s+")); if (1 < list_fms.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_FMS" , list_fms[1]); } if (2 < list_fms.count()) { QStringList list_fms_diag = list_fms[2].split(":"); if (1 < list_fms_diag.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_FMS_DIAG" , list_fms_diag[1]); } } if (3 < list_fms.count()) { QStringList list_fms_requ = list_fms[3].split(":"); if (1 < list_fms_requ.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_FMS_REQU" , list_fms_requ[1]); } } } if (13 < list.count()) { QStringList list_gear = list[13].split(QRegExp("\\s+")); if (1 < list_gear.count()) { QStringList list_gear_s = list_gear[1].split(":"); if (1 < list_gear_s.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_GEAR_S" , list_gear_s[1]); } } if (2 < list_gear.count()) { QStringList list_gear_c = list_gear[2].split(":"); if (1 < list_gear_c.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_GEAR_C" , list_gear_c[1]); } } } if (14 < list.count()) { QStringList list_doorctrl = list[14].split(QRegExp("\\s+")); if (1 < list_doorctrl.count()) { QStringList list_doorctrl_p = list_doorctrl[1].split(":"); if (1 < list_doorctrl_p.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DOORCTRL_P",list_doorctrl_p[1]); } } if (2 < list_doorctrl.count()) { QStringList list_doorctrl_r = list_doorctrl[2].split(":"); if (1 < list_doorctrl_r.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DOORCTRL_R",list_doorctrl_r[1]); } } if (3 < list_doorctrl.count()) { QStringList list_doorctrl_s = list_doorctrl[3].split(":"); if (1 < list_doorctrl_s.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DOORCTRL_S",list_doorctrl_s[1]); } } } if (15 < list.count()) { QStringList list_dc2 = list[15].split(QRegExp("\\s+")); if (1 < list_dc2.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DC2" , list_dc2[1]); } if (2 < list_dc2.count()) { QStringList list_dc2_loe_1 = list_dc2[2].split(":"); if (1 < list_dc2_loe_1.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DC2_LOE_1" , list_dc2_loe_1[1]); } } if (3 < list_dc2.count()) { QStringList list_dc2_loe_2 = list_dc2[3].split(":"); if (1 < list_dc2_loe_2.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DC2_LOE_2" , list_dc2_loe_2[1]); } } if (4 < list_dc2.count()) { QStringList list_dc2_loe_3 = list_dc2[4].split(":"); if (1 < list_dc2_loe_3.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DC2_LOE_3" , list_dc2_loe_3[1]); } } if (5 < list_dc2.count()) { QStringList list_dc2_loe_4 = list_dc2[5].split(":"); if (1 < list_dc2_loe_4.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DC2_LOE_4" , list_dc2_loe_4[1]); } } if (6 < list_dc2.count()) { QStringList list_dc2_loe_5 = list_dc2[6].split(":"); if (1 < list_dc2_loe_5.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DC2_LOE_5" , list_dc2_loe_5[1]); } } if (7 < list_dc2.count()) { QStringList list_dc2_loe_6 = list_dc2[7].split(":"); if (1 < list_dc2_loe_6.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DC2_LOE_6" , list_dc2_loe_6[1]); } } if (8 < list_dc2.count()) { QStringList list_dc2_loe_7 = list_dc2[8].split(":"); if (1 < list_dc2_loe_7.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DC2_LOE_7" , list_dc2_loe_7[1]); } } if (9 < list_dc2.count()) { QStringList list_dc2_loe_8 = list_dc2[9].split(":"); if (1 < list_dc2_loe_8.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DC2_LOE_8" , list_dc2_loe_8[1]); } } if (10 < list_dc2.count()) { QStringList list_dc2_loe_9 = list_dc2[10].split(":"); if (1 < list_dc2_loe_9.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DC2_LOE_9" ,list_dc2_loe_9[1]); } } if (11 < list_dc2.count()) { QStringList list_dc2_loe_10 = list_dc2[11].split(":"); if (1 < list_dc2_loe_10.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DC2_LOE_10" , list_dc2_loe_10[1]); } } } if (16 < list.count()) { QStringList list_bollowpr = list[16].split(QRegExp("\\s+")); if (1 < list_bollowpr.count()) { QStringList list_bellowpr_fal = list_bollowpr[1].split(":"); if (1 < list_bellowpr_fal.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_BELLOWPR_FAL" , list_bellowpr_fal[1]); } } if (3 < list_bollowpr.count()) { QStringList list_bellowpr_far = list_bollowpr[3].split(":"); if (1 < list_bellowpr_far.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_BELLOWPR_FAR" , list_bellowpr_far[1]); } } if (5 < list_bollowpr.count()) { QStringList list_bellowpr_ral = list_bollowpr[5].split(":"); if (1 < list_bellowpr_ral.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_BELLOWPR_RAL" , list_bellowpr_ral[1]); } } if (7 < list_bollowpr.count()) { QStringList list_bellowpr_rar = list_bollowpr[7].split(":"); if (1 < list_bellowpr_rar.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_BELLOWPR_RAR" , list_bellowpr_rar[1]); } } } if (17 < list.count()) { QStringList list_breakprr = list[17].split(QRegExp("\\s+")); if (1 < list_breakprr.count()) { QStringList list_brakepr_1 = list_breakprr[1].split(":"); if (1 < list_brakepr_1.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_BRAKEPR_1" , list_brakepr_1[1]); } } if (3 < list_breakprr.count()) { QStringList list_brakepr_2 = list_breakprr[3].split(":"); if (1 < list_brakepr_2.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_BRAKEPR_2" , list_brakepr_2[1]); } } } if (18 < list.count()) { QStringList list_alternat = list[18].split(QRegExp("\\s+")); if (1 < list_alternat.count()) { QStringList list_alternat_1 = list_alternat[1].split(":"); if (1 < list_alternat_1.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_ALTERNAT_1" , list_alternat_1[1]); } } if (2 < list_alternat.count()) { QStringList list_alternat_2 = list_alternat[2].split(":"); if (1 < list_alternat_2.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_ALTERNAT_2" , list_alternat_2[1]); } } if (3 < list_alternat.count()) { QStringList list_alternat_3 = list_alternat[3].split(":"); if (1 < list_alternat_3.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_ALTERNAT_3" , list_alternat_3[1]); } } if (4 < list_alternat.count()) { QStringList list_alternat_4 = list_alternat[4].split(":"); if (1 < list_alternat_4.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_ALTERNAT_4" , list_alternat_4[1]); } } } if (19 < list.count()) { QStringList list_datetime = list[19].split(QRegExp("\\s+")); if (1 < list_datetime.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_DATETIME" , list_datetime[1]); } } if (20 < list.count()) { QStringList list_ambtemp = list[20].split(QRegExp("\\s+")); if (1 < list_ambtemp.count()) { m_list_data_plugin[INFORMATIONS_DATA].setValueData("PCAN_AMBTEMP" , list_ambtemp[1]); } } emit signalUpdateServices (); }
QStringList djvSystem::searchPath() { //DJV_DEBUG("djvSystem::searchPath"); QStringList out; // Add paths from environment variables. QString path = env(djvPathEnv()); if (! path.isEmpty()) { //DJV_DEBUG_PRINT("DJV_PATH = " << path); QString match; Q_FOREACH(QChar c, djvFileInfoUtil::listSeparators) match += c; out += path.split( QRegExp(QString("[%1]+").arg(match)), QString::SkipEmptyParts); } path = env(ldLibPathEnv()); if (! path.isEmpty()) { //DJV_DEBUG_PRINT("LD_LIBRARY_PATH = " << path); QString match; Q_FOREACH(QChar c, djvFileInfoUtil::listSeparators) match += c; //DJV_DEBUG_PRINT("match = " << match); out += path.split( QRegExp(QString("[%1]+").arg(match)), QString::SkipEmptyParts); } // Add the application path. //DJV_DEBUG_PRINT("qApp = " << qApp); const QString applicationPath = qApp->applicationDirPath(); //DJV_DEBUG_PRINT("application path = " << applicationPath); out += applicationPath; // Add library and translation paths. out += QDir(applicationPath + "/../lib").absolutePath(); out += QDir(applicationPath + "/../translations").absolutePath(); #if defined(DJV_WINDOWS) || defined(DJV_OSX) const QString dirName = QDir(qApp->applicationDirPath()).dirName(); out += QDir(applicationPath + "/../../lib/" + dirName).absolutePath(); out += QDir(applicationPath + "/../../translations/" + dirName).absolutePath(); #endif // Add the build directories. out += QDir("lib/djvCore").absolutePath(); out += QDir("lib/djvGui").absolutePath(); out += QDir("lib/djvViewLib").absolutePath(); out += QDir("bin/djv_ls").absolutePath(); out += QDir("bin/djv_info").absolutePath(); out += QDir("bin/djv_convert").absolutePath(); // Add the current directory. out += "."; //DJV_DEBUG_PRINT("out = " << out); QSet<QString> set; for (int i = 0; i < out.count(); ++i) set.insert(out[i]); QList<QString> list = set.toList(); out.clear(); Q_FOREACH(const QString & s, list) out += s; return out; }
void XMLSchemaWriter::writeAssociationRoleDecl( UMLClassifier *c, const QString &multi, QTextStream &XMLschema) { bool isAbstract = c->getAbstract(); bool isInterface = c->isInterface(); QString elementName = getElementName(c); QString doc = c->getDoc(); if (!doc.isEmpty()) writeComment(doc, XMLschema); // Min/Max Occurs is based on whether it is this a single element // or a List (maxoccurs>1). One day this will be done correctly with special // multiplicity object that we don't have to figure out what it means via regex. QString minOccurs = "0"; QString maxOccurs = "unbounded"; if (multi.isEmpty()) { // in this case, association will only specify ONE element can exist // as a child minOccurs = "1"; maxOccurs = "1"; } else { QStringList values = QStringList::split( QRegExp("[^\\d{1,}|\\*]"), multi); // could use some improvement here.. for sequences like "0..1,3..5,10" we // don't capture the whole "richness" of the multi. Instead we translate it // now to minOccurs="0" maxOccurs="10" if (values.count() > 0) { // populate both with the actual value as long as our value isnt an asterix // In that case, use special value (from above) if(values[0].contains(QRegExp("\\d{1,}"))) minOccurs = values[0]; // use first number in sequence if(values[values.count()-1].contains(QRegExp("\\d{1,}"))) maxOccurs = values[values.count()-1]; // use only last number in sequence } } // Now declare the class in the association as an element or group. // // In a semi-arbitrary way, we have decided to make abstract classes into // "groups" and concrete classes into "complexTypes". // // This is because about the only thing you can do with an abstract // class (err. node) is inherit from it with a "concrete" element. Therefore, // in this manner, we need a group node for abstract classes to lay out the child // element choices so that the child, concrete class may be plugged into whatever spot // it parent could go. The tradeoff is that "group" nodes may not be extended, so the // choices that you lay out here are it (e.g. no more nodes may inherit" from this group) // // The flipside for concrete classes is that we want to use them as elements in our document. // Unfortunately, about all you can do with complexTypes in terms of inheritance, is to // use these as the basis for a new node type. This is NOT full inheritence because the new // class (err. element node) wont be able to go into the document where it parent went without // you heavily editing the schema. // // Therefore, IF a group is abstract, but has no inheriting sub-classes, there are no choices, and its nigh // on pointless to declare it as a group, in this special case, abstract classes get declared // as complexTypes. // // Of course, in OO methodology, you should be able to inherit from // any class, but schema just don't allow use to have full inheritence using either groups // or complexTypes. Thus we have taken a middle rode. If someone wants to key me into a // better way to represent this, I'd be happy to listen. =b.t. // // UPDATE: partial solution to the above: as of 13-Mar-2003 we now write BOTH a complexType // AND a group declaration for interfaces AND classes which are inherited from. // if ((isAbstract || isInterface ) && c->findSubClassConcepts().count() > 0) XMLschema<<getIndent()<<"<"<<makeSchemaTag("group") <<" ref=\""<<makePackageTag(getElementGroupTypeName(c))<<"\""; else XMLschema<<getIndent()<<"<"<<makeSchemaTag("element") <<" name=\""<<getElementName(c)<<"\"" <<" type=\""<<makePackageTag(getElementTypeName(c))<<"\""; // min/max occurs if (minOccurs != "1") XMLschema<<" minOccurs=\""<<minOccurs<<"\""; if (maxOccurs != "1") XMLschema<<" maxOccurs=\""<<maxOccurs<<"\""; // tidy up the node XMLschema<<"/>"<<m_endl; }
void MacroManager::load() { QDir dir(savePath); if(!dir.exists()) return; //no need to bother trying to load QFile data(savePath + "/qtmacrocodes.cfg"); if(!data.exists()) return; if(data.open(QFile::ReadOnly)) { QTextStream in(&data); QString line; int i=0; QString curProg; int curMKey = 0; int curGKey = 0; Macro m; while((line = in.readLine()) != NULL) { if(i==0) //this is version line. Isn't needed in first version { i++; continue; } if(line.left(2) == "#p") { trySaveMacro(&m, curProg, curMKey, curGKey); //Prog line curProg = line.right(line.length()-2); setCurActiveId(&curProg); writeDbg(tr("mm> found program ") + curProg); } else if(line.left(2) == "#m") { trySaveMacro(&m, curProg, curMKey, curGKey); //Mkey line curMKey = line.right(1).toInt(NULL); writeDbg(tr("mm> found mkey ") + QString::number(curMKey)); } else if(line.left(2) == "#g") { trySaveMacro(&m, curProg, curMKey, curGKey); //GKey line if(line.length() == 3) curGKey = line.right(1).toInt(NULL); else curGKey = line.right(2).toInt(NULL); writeDbg(tr("mm> found gkey ") + QString::number(curGKey)); } else if(line.contains("=", Qt::CaseSensitive)) { //Event line QStringList eventInfo = line.split("="); if(eventInfo.count() != 2) continue; writeDbg(tr("mm> found key: ") + QString::number(eventInfo.at(0).toInt(NULL)) + tr(":") + QString::number(eventInfo.at(1).toInt(NULL))); m.addEvent(eventInfo.at(0).toInt(NULL), (bool)eventInfo.at(1).toInt(NULL)); } } trySaveMacro(&m, curProg, curMKey, curGKey); } }
void ConjunctionsTool::slotCompute (void) { KStarsDateTime dtStart = startDate -> dateTime(); // Start date KStarsDateTime dtStop = stopDate -> dateTime(); // Stop date long double startJD = dtStart.djd(); // Start julian day long double stopJD = dtStop.djd(); // Stop julian day bool opposition = false; // true=opposition, false=conjunction if( Opposition->currentIndex() ) opposition = true; QStringList objects; // List of sky object used as Object1 KStarsData *data = KStarsData::Instance(); int progress = 0; // Check if we have a valid angle in maxSeparationBox dms maxSeparation( 0.0 ); bool ok; maxSeparation = maxSeparationBox->createDms( true, &ok ); if( !ok ) { KMessageBox::sorry( 0, i18n("Maximum separation entered is not a valid angle. Use the What's this help feature for information on how to enter a valid angle") ); return; } // Check if Object1 and Object2 are set if( FilterTypeComboBox->currentIndex() == 0 && !Object1 ) { KMessageBox::sorry( 0, i18n("Please select an object to check conjunctions with, by clicking on the \'Find Object\' button.") ); return; } Object2 = KSPlanetBase::createPlanet( Obj2ComboBox->currentIndex() ); if( FilterTypeComboBox->currentIndex() == 0 && Object1->name() == Object2->name() ) { // FIXME: Must free the created Objects KMessageBox::sorry( 0 , i18n("Please select two different objects to check conjunctions with.") ); return; } // Init KSConjunct object KSConjunct ksc; connect( &ksc, SIGNAL(madeProgress(int)), this, SLOT(showProgress(int)) ); ksc.setGeoLocation( geoPlace ); switch ( FilterTypeComboBox->currentIndex() ) { case 1: // All object types foreach( int type, data->skyComposite()->objectNames().keys() ) objects += data->skyComposite()->objectNames( type ); break; case 2: // Stars objects += data->skyComposite()->objectNames( SkyObject::STAR ); objects += data->skyComposite()->objectNames( SkyObject::CATALOG_STAR ); break; case 3: // Solar system objects += data->skyComposite()->objectNames( SkyObject::PLANET ); objects += data->skyComposite()->objectNames( SkyObject::COMET ); objects += data->skyComposite()->objectNames( SkyObject::ASTEROID ); objects += data->skyComposite()->objectNames( SkyObject::MOON ); objects += i18n("Sun"); // Remove Object2 planet objects.removeAll( Object2->name() ); break; case 4: // Planet objects += data->skyComposite()->objectNames( SkyObject::PLANET ); // Remove Object2 planet objects.removeAll( Object2->name() ); break; case 5: // Comet objects += data->skyComposite()->objectNames( SkyObject::COMET ); break; case 6: // Ateroid objects += data->skyComposite()->objectNames( SkyObject::ASTEROID ); break; case 7: // Open Clusters objects = data->skyComposite()->objectNames( SkyObject::OPEN_CLUSTER ); break; case 8: // Open Clusters objects = data->skyComposite()->objectNames( SkyObject::GLOBULAR_CLUSTER ); break; case 9: // Gaseous nebulae objects = data->skyComposite()->objectNames( SkyObject::GASEOUS_NEBULA ); break; case 10: // Planetary nebula objects = data->skyComposite()->objectNames( SkyObject::PLANETARY_NEBULA ); break; case 11: // Galaxies objects = data->skyComposite()->objectNames( SkyObject::GALAXY ); break; } // Remove all Jupiter and Saturn moons // KStars crash if we compute a conjunction between a planet and one of this moon if ( FilterTypeComboBox->currentIndex() == 1 || FilterTypeComboBox->currentIndex() == 3 || FilterTypeComboBox->currentIndex() == 6 ) { objects.removeAll( "Io" ); objects.removeAll( "Europa" ); objects.removeAll( "Ganymede" ); objects.removeAll( "Callisto" ); objects.removeAll( "Mimas" ); objects.removeAll( "Enceladus" ); objects.removeAll( "Tethys" ); objects.removeAll( "Dione" ); objects.removeAll( "Rhea" ); objects.removeAll( "Titan" ); objects.removeAll( "Hyperion" ); objects.removeAll( "Iapetus" ); } if ( FilterTypeComboBox->currentIndex() != 0 ) { // Show a progress dialog while processing QProgressDialog progressDlg( i18n( "Compute conjunction..." ), i18n( "Abort" ), 0, objects.count(), this); progressDlg.setWindowModality( Qt::WindowModal ); progressDlg.setValue( 0 ); foreach( QString object, objects ) { // If the user click on the 'cancel' button if ( progressDlg.wasCanceled() ) break; // Update progress dialog ++progress; progressDlg.setValue( progress ); progressDlg.setLabelText( i18n( "Compute conjunction between %1 and %2", Object2->name(), object ) ); // Compute conjuction Object1 = data->skyComposite()->findByName( object ); showConjunctions( ksc.findClosestApproach(*Object1, *Object2, startJD, stopJD, maxSeparation, opposition), object, Object2->name() ); } progressDlg.setValue( objects.count() ); } else {
/** add the given key and value @param scope scope of key @param key key name @param rootProperty is the property from which to start adding @param value the value associated with the key */ static QgsProperty * addKey_( QString const & scope, QString const & key, QgsPropertyKey * rootProperty, QVariant value ) { QStringList keySequence = makeKeyTokens_( scope, key ); // cursor through property key/value hierarchy QgsPropertyKey * currentProperty = rootProperty; QgsProperty * newProperty; // link to next property down hiearchy while ( ! keySequence.isEmpty() ) { // if the current head of the sequence list matches the property name, // then traverse down the property hierarchy if ( keySequence.first() == currentProperty->name() ) { // remove front key since we're traversing down a level keySequence.pop_front(); // if key sequence has one last element, then we use that as the // name to store the value if ( 1 == keySequence.count() ) { currentProperty->setValue( keySequence.front(), value ); return currentProperty; } // we're at the top element if popping the keySequence element // will leave it empty; in that case, just add the key else if ( keySequence.isEmpty() ) { currentProperty->setValue( value ); return currentProperty; } else if (( newProperty = currentProperty->find( keySequence.first() ) ) ) { currentProperty = dynamic_cast<QgsPropertyKey*>( newProperty ); if ( currentProperty ) { continue; } else // QgsPropertyValue not Key, so return null { return 0x0; } } else // the next subkey doesn't exist, so add it { newProperty = currentProperty->addKey( keySequence.first() ); if ( newProperty ) { currentProperty = dynamic_cast<QgsPropertyKey*>( newProperty ); } continue; } } else { return 0x0; } } return 0x0; } // addKey_
/** return the property that matches the given key sequence, if any @param scope scope of key @param key keyname @param rootProperty is likely to be the top level QgsPropertyKey in QgsProject:e:Imp. @return null if not found, otherwise located Property */ static QgsProperty * findKey_( QString const & scope, QString const & key, QgsPropertyKey & rootProperty ) { QgsPropertyKey * currentProperty = &rootProperty; QgsProperty * nextProperty; // link to next property down hiearchy QStringList keySequence = makeKeyTokens_( scope, key ); while ( ! keySequence.isEmpty() ) { // if the current head of the sequence list matches the property name, // then traverse down the property hierarchy if ( keySequence.first() == currentProperty->name() ) { // remove front key since we're traversing down a level keySequence.pop_front(); // if we have only one key name left, then return the key found if ( 1 == keySequence.count() ) { return currentProperty->find( keySequence.front() ); } // if we're out of keys then the current property is the one we // want; i.e., we're in the rate case of being at the top-most // property node else if ( keySequence.isEmpty() ) { return currentProperty; } else if (( nextProperty = currentProperty->find( keySequence.first() ) ) ) { if ( nextProperty->isKey() ) { currentProperty = dynamic_cast<QgsPropertyKey*>( nextProperty ); } // it may be that this may be one of several property value // nodes keyed by QDict string; if this is the last remaining // key token and the next property is a value node, then // that's the situation, so return the currentProperty else if ( nextProperty->isValue() && ( 1 == keySequence.count() ) ) { return currentProperty; } else // QgsPropertyValue not Key, so return null { return 0x0; } } else // if the next key down isn't found { // then the overall key sequence doesn't exist return 0x0; } } else { return 0x0; } } return 0x0; } // findKey_
FrameworkInfo parseOtoolLibraryLine(const QString &line, bool useDebugLibs) { FrameworkInfo info; QString trimmed = line.trimmed(); if (trimmed.isEmpty()) return info; // Don't deploy system libraries. if (trimmed.startsWith("/System/Library/") || (trimmed.startsWith("/usr/lib/") && trimmed.contains("libQt") == false) // exception for libQtuitools and libQtlucene || trimmed.startsWith("@executable_path")) return info; enum State {QtPath, FrameworkName, DylibName, Version, End}; State state = QtPath; int part = 0; QString name; QString qtPath; QString suffix = useDebugLibs ? "_debug" : ""; // Split the line into [Qt-path]/lib/qt[Module].framework/Versions/[Version]/ QStringList parts = trimmed.split("/"); while (part < parts.count()) { const QString currentPart = parts.at(part).simplified() ; ++part; if (currentPart == "") continue; if (state == QtPath) { // Check for library name part if (part < parts.count() && parts.at(part).contains(".dylib ")) { state = DylibName; info.installName += "/" + (qtPath + "lib/").simplified(); info.frameworkDirectory = info.installName; state = DylibName; continue; } else if (part < parts.count() && parts.at(part).endsWith(".framework")) { info.installName += "/" + (qtPath + "lib/").simplified(); info.frameworkDirectory = info.installName; state = FrameworkName; continue; } else if (trimmed.startsWith("/") == false) { // If the line does not contain a full path, the app is using a binary Qt package. if (currentPart.contains(".framework")) { info.frameworkDirectory = "/Library/Frameworks/"; state = FrameworkName; } else { info.frameworkDirectory = "/usr/lib/"; state = DylibName; } --part; continue; } qtPath += (currentPart + "/"); } if (state == FrameworkName) { // remove ".framework" name = currentPart; name.chop(QString(".framework").length()); info.frameworkName = currentPart; state = Version; ++part; continue; } if (state == DylibName) { name = currentPart.split(" (compatibility").at(0); info.frameworkName = name; info.binaryName = name.left(name.indexOf('.')) + suffix + name.mid(name.indexOf('.')); info.installName += name; info.deployedInstallName = "@executable_path/../Frameworks/" + info.binaryName; info.frameworkPath = info.frameworkDirectory + info.binaryName; info.sourceFilePath = info.frameworkPath; info.destinationDirectory = bundleFrameworkDirectory + "/"; info.binaryDirectory = info.frameworkDirectory; info.binaryPath = info.frameworkPath; state = End; ++part; continue; } else if (state == Version) { info.version = currentPart; info.binaryDirectory = "Versions/" + info.version; info.binaryName = name + suffix; info.binaryPath = "/" + info.binaryDirectory + "/" + info.binaryName; info.installName += info.frameworkName + "/" + info.binaryDirectory + "/" + name; info.deployedInstallName = "@executable_path/../Frameworks/" + info.frameworkName + info.binaryPath; info.frameworkPath = info.frameworkDirectory + info.frameworkName; info.sourceFilePath = info.frameworkPath + info.binaryPath; info.destinationDirectory = bundleFrameworkDirectory + "/" + info.frameworkName + "/" + info.binaryDirectory; state = End; } else if (state == End) { break; } } return info; }
void SoundSettingsPage::themeBoxChanged(int index) { QStringList themeDirs = soundEngine->getAvailableThemes().keys(); if(index >= 0 && index < themeDirs.count()) settingsCache->setSoundThemeName(themeDirs.at(index)); }
void AppearanceSettingsPage::themeBoxChanged(int index) { QStringList themeDirs = themeManager->getAvailableThemes().keys(); if(index >= 0 && index < themeDirs.count()) settingsCache->setThemeName(themeDirs.at(index)); }
bool TScriptInternalFunctions::runFunction(QString function, QStringList param, QString &result) { QString fn = function.toUpper(); if (fn == "ACOS") { if (param.length() < 1) return false; bool ok = false; double v = param[0].toDouble(&ok); if (!ok) v = 0; result = QString::number(acos(v)); return true; } if (fn == "ASIN") { if (param.length() < 1) return false; bool ok = false; double v = param[0].toDouble(&ok); if (!ok) v = 0; result = QString::number(asin(v)); return true; } if (fn == "ATAN") { if (param.length() < 1) return false; bool ok = false; double v = param[0].toDouble(&ok); if (!ok) v = 0; result = QString::number(atan(v)); return true; } if (fn == "BUILDTYPE") { #ifdef STANDALONE result = "STANDALONE"; #endif #ifdef PACKAGED result = "PACKAGED"; #endif return true; } if (fn == "CALC") { // Calculate an expression (e.g. 5+5) if (param.length() == 0) return false; QString expr = param[0]; result = calc(expr); return true; } if (fn == "COS") { if (param.length() < 1) return false; bool ok = false; double v = param[0].toDouble(&ok); if (!ok) v = 0; result = QString::number(cos(v)); return true; } if (fn == "COLORAT") { // $ColorAt(@window, layer, x, y) if (param.length() < 3) return false; QString layer = "main"; if (param.length() > 3) { layer = param[1]; param.removeAt(1); } subwindow_t sw = getCustomWindow(param[0]); if (sw.type == WT_NOTHING) return false; int x = floor( param[1].toFloat() ); int y = floor( param[2].toFloat() ); result = sw.widget->picwinPtr()->colorAt(layer, x, y); return true; } if (fn == "CURWINTYPE") { // Returns the current target type (msg or channel) subwindow_t sw = winList->value(*activeWid); if (sw.type == WT_CHANNEL) result = "CHANNEL"; else if (sw.type == WT_GRAPHIC) result = "GRAPHIC"; else if (sw.type == WT_GWINPUT) result = "GRAPHICINPUT"; else if (sw.type == WT_NOTHING) result = "NOTHIG"; else if (sw.type == WT_PRIVMSG) result = "PRIVMSG"; else if (sw.type == WT_STATUS) result = "STATUS"; else if (sw.type == WT_TXTONLY) result = "TXTONLY"; else result = "UNKNOWN"; return true; } if (fn == "DLG") { // Returns information of a dialog or its objects // $dlg(dialog,object) if (param.count() == 2) { QString dlg = param[0]; QString object = param[1]; QHashIterator<QString,TCustomScriptDialog*> i(*dialogs); while (i.hasNext()) { i.next(); if (i.key().toUpper() == dlg.toUpper()) { result = i.value()->getLabel(object); return true; } } } // $dlg(dialog,object,index) if (param.count() == 3) { QString dlg = param[0]; QString object = param[1]; QString index = param[2]; QHashIterator<QString,TCustomScriptDialog*> i(*dialogs); while (i.hasNext()) { i.next(); if (i.key().toUpper() == dlg.toUpper()) { result = i.value()->getItem(object, index.toInt()); return true; } } } // Default return false; } if (fn == "FILE") { // Returns a file descriptor by opening a file for read and|or write // $file(file.name, rwb) // result: 0 cannot open, -1 not existing if (param.count() < 2) { result = "0"; return true; } QString mode = param[1]; bool read = false; bool write = false; bool binary = false; bool append = false; bool switchfail = false; for (int i = 0; i <= mode.length()-1; i++) { char c = mode[i].toLatin1(); switch (c) { case 'a': append = true; continue; case 'r': read = true; continue; case 'w': write = true; continue; case 'b': binary = true; continue; default: switchfail = true; break; } } if (switchfail == true) { result = "0"; return true; } if ((read || write) == false) read = true; QIODevice::OpenMode om = 0; if (read) om |= QIODevice::ReadOnly; if (write) om |= QIODevice::WriteOnly; if (! binary) om |= QIODevice::Text; if (append) om |= QIODevice::Append; if (om == 0) { result = "0"; return true; } QFile *f = new QFile(param[0]); if (! f->open(om)) { result = "0"; return true; } t_sfile ts; ts.binary = binary; ts.read = read; ts.write = write; ts.fd = fdc; ts.file = f; files->insert(fdc, ts); result = QString::number(fdc++); return true; } if (fn == "FNEXIST") { // Checks if an actual function exists; This will NOT work on "internal" functions (these in here) if (param.count() != 1) return false; int idx = fnindex->value(param[0].toUpper(), -1); if (idx > -1) result = "1"; else result = "0"; return true; } if (fn == "GLUE") { // "glue" texts together. // $glue(hello,big,world) will return hellobigworld QString r; for (int i = 0; i <= param.length()-1; i++) r += param[i]; result = r; return true; } if (fn == "HOSTMASK") { // Returns hostmask *!*@host.name of nickname if IAL got it. // Otherwise, if IAL doesn't, it returns nickname!*@* as hostmask. if (param.count() != 1) { result.clear(); return false; } QString nickname = param[0]; IConnection *con = conList->value(*activeConn); QString host = con->ial.getHost(nickname); if (host.isEmpty()) { host = nickname; host.append("!*@*"); } else host.prepend("*!*@"); result = host; return true; } if (fn == "IALHOSTMASK") { // Returns hostname of nickname if IAL got it, otherwise empty text. // Better off using $hostmask() instead. if (param.count() != 1) { result.clear(); return false; } QString nickname = param[0]; IConnection *con = conList->value(*activeConn); QString host = con->ial.getHost(nickname); if (! host.isEmpty()) host.prepend("*!*@"); result = host; return true; } if (fn == "LEN") { // Counts amount of letters in a given text if (param.count() == 0) { result = "0"; return true; } result = QString::number( param.at(0).length() ); return true; } if (fn == "NULL") { // Returns empty result.clear(); return true; } if (fn == "PATH") { // $path(type) // Returns a file path to the given type. if (param.count() != 1) return false; QString type = param[0].toUpper(); if (type == "CONFIG") result = CONF_PATH; if (type == "COMMON") result = COMMON_PATH; if (type == "EXEC") result = QApplication::applicationDirPath(); if (type == "SKEL") result = SKEL_PATH; return true; } if (fn == "RAND") { // Pseudo-random number generator if (param.length() < 2) return false; int lo = param[0].toInt(); int hi = param[1].toInt(); result = rand(lo, hi); return true; } if (fn == "SIN") { if (param.length() < 1) return false; bool ok = false; double v = param[0].toDouble(&ok); if (!ok) v = 0; result = QString::number(sin(v)); return true; } if (fn == "SOCKBUFLEN") { // Returns amount of bytes left in sockread buffer if (param.length() < 1) return false; result = sockfactory->sockBufLen(param[0]); return true; } if (fn == "SOCKLIST") { // Find socket names. // $socklist(patt_*, pos) // If pos is zero, that will return amount of socket names the pattern matches. // If pos > 0, this will return an actual socket name it matches. if (param.length() < 2) return false; result = sockfactory->socklist(param[0], param[1].toInt()); return true; } if (fn == "SSTR") { // Substring, returns text by given positions inside the text. // $SSTR(The text, start, end) end is optional. if (param.length() < 2) return false; int start = param[1].toInt(); int stop = -1; if (param.length() >= 3) stop = param[2].toInt(); QString text = param[0]; result = sstr(text, start, stop); return true; } if (fn == "TAN") { if (param.length() < 1) return false; bool ok = false; double v = param[0].toDouble(&ok); if (!ok) v = 0; result = QString::number(tan(v)); return true; } if (fn == "TARGET") { // Returns the current target to send messages to (msg or channel) subwindow_t sw = winList->value(*activeWid); result.clear(); if ((sw.type == WT_CHANNEL) || (sw.type == WT_PRIVMSG)) result = sw.widget->getTarget(); return true; } if (fn == "TEXTWIDTH") { // Return text width in pixles by given font name and size // $textwidth(font, size, text) if (param.count() != 3) return false; QFont font(param[0]); font.setPixelSize(param[1].toInt()); QFontMetrics fm(font); result = QString::number( fm.width(param[2]) ); return true; } if (fn == "TOKEN") { // Get a text by tokens // $token(text here, position, token) the token is in ascii number. // If the position is zero, this will count amount of text items separated by the given token if (param.length() < 3) return false; bool ok = false; QString tcnum = param[2]; // token character (ascii num) QChar tc = tcnum.toInt(&ok); // converted from string-number to actual number, into a character. if (ok == false) return false; int p = param[1].toInt(&ok); // Which position to use if (ok == false) return false; result = token(param[0], p, tc); return true; } if (fn == "VERSION") { // IIRC version. result = VERSION_STRING; return true; } // No functions were matching, return false as error. return false; }
bool ShaderFactory::loadShader(GLhandleARB &progObj, QString shaderString) { GLhandleARB fragObj = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB); glAttachObjectARB(progObj, fragObj); GLhandleARB vertObj = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB); glAttachObjectARB(progObj, vertObj); { // vertObj QString qstr; qstr = "varying vec3 pointpos;\n"; qstr += "void main(void)\n"; qstr += "{\n"; qstr += " // Transform vertex position into homogenous clip-space.\n"; qstr += " gl_FrontColor = gl_Color;\n"; qstr += " gl_BackColor = gl_Color;\n"; qstr += " gl_Position = ftransform();\n"; qstr += " gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0;\n"; qstr += " gl_TexCoord[1] = gl_TextureMatrix[1] * gl_MultiTexCoord1;\n"; qstr += " gl_TexCoord[2] = gl_TextureMatrix[2] * gl_MultiTexCoord2;\n"; qstr += " gl_ClipVertex = gl_ModelViewMatrix * gl_Vertex;\n"; qstr += " pointpos = gl_Vertex.xyz;\n"; qstr += "}\n"; int len = qstr.length(); char *tbuffer = new char[len+1]; sprintf(tbuffer, qstr.toLatin1().data()); const char *sstr = tbuffer; glShaderSourceARB(vertObj, 1, &sstr, NULL); delete [] tbuffer; GLint compiled = -1; glCompileShaderARB(vertObj); glGetObjectParameterivARB(vertObj, GL_OBJECT_COMPILE_STATUS_ARB, &compiled); if (!compiled) { GLcharARB str[1000]; GLsizei len; glGetInfoLogARB(vertObj, (GLsizei) 1000, &len, str); QMessageBox::information(0, "Error : Vertex Shader", str); return false; } } { // fragObj int len = shaderString.length(); char *tbuffer = new char[len+1]; sprintf(tbuffer, shaderString.toLatin1().data()); const char *sstr = tbuffer; glShaderSourceARB(fragObj, 1, &sstr, NULL); delete [] tbuffer; GLint compiled = -1; glCompileShaderARB(fragObj); glGetObjectParameterivARB(fragObj, GL_OBJECT_COMPILE_STATUS_ARB, &compiled); if (!compiled) { GLcharARB str[1000]; GLsizei len; glGetInfoLogARB(fragObj, (GLsizei) 1000, &len, str); //----------------------------------- // display error //qApp->beep(); QString estr; QStringList slist = shaderString.split("\n"); for(int i=0; i<slist.count(); i++) estr += QString("%1 : %2\n").arg(i+1).arg(slist[i]); QTextEdit *tedit = new QTextEdit(); tedit->insertPlainText("-------------Error----------------\n\n"); tedit->insertPlainText(str); tedit->insertPlainText("\n-----------Shader---------------\n\n"); tedit->insertPlainText(estr); QVBoxLayout *layout = new QVBoxLayout(); layout->addWidget(tedit); QDialog *showError = new QDialog(); showError->setWindowTitle("Error in Fragment Shader"); showError->setSizeGripEnabled(true); showError->setModal(true); showError->setLayout(layout); showError->exec(); //----------------------------------- return false; } } //----------- link program shader ---------------------- GLint linked = -1; glLinkProgramARB(progObj); glGetObjectParameterivARB(progObj, GL_OBJECT_LINK_STATUS_ARB, &linked); if (!linked) { GLcharARB str[1000]; GLsizei len; QMessageBox::information(0, "ProgObj", "error linking texProgObj"); glGetInfoLogARB(progObj, (GLsizei) 1000, &len, str); QMessageBox::information(0, "Error", QString("%1\n%2").arg(len).arg(str)); return false; } glDeleteObjectARB(fragObj); glDeleteObjectARB(vertObj); return true; }
BrowserApplication::BrowserApplication(int &argc, char **argv) : QApplication(argc, argv) , m_localServer(0) { QCoreApplication::setOrganizationName(QLatin1String("Qt")); QCoreApplication::setApplicationName(QLatin1String("demobrowser")); QCoreApplication::setApplicationVersion(QLatin1String("0.1")); #ifdef Q_WS_QWS // Use a different server name for QWS so we can run an X11 // browser and a QWS browser in parallel on the same machine for // debugging QString serverName = QCoreApplication::applicationName() + QLatin1String("_qws"); #else QString serverName = QCoreApplication::applicationName(); #endif QLocalSocket socket; socket.connectToServer(serverName); if (socket.waitForConnected(500)) { QTextStream stream(&socket); QStringList args = QCoreApplication::arguments(); if (args.count() > 1) stream << args.last(); else stream << QString(); stream.flush(); socket.waitForBytesWritten(); return; } #if defined(Q_WS_MAC) QApplication::setQuitOnLastWindowClosed(false); #else QApplication::setQuitOnLastWindowClosed(true); #endif m_localServer = new QLocalServer(this); connect(m_localServer, SIGNAL(newConnection()), this, SLOT(newLocalSocketConnection())); if (!m_localServer->listen(serverName)) { if (m_localServer->serverError() == QAbstractSocket::AddressInUseError && QFile::exists(m_localServer->serverName())) { QFile::remove(m_localServer->serverName()); m_localServer->listen(serverName); } } #ifndef QT_NO_OPENSSL if (!QSslSocket::supportsSsl()) { QMessageBox::information(0, "Demo Browser", "This system does not support OpenSSL. SSL websites will not be available."); } #endif QDesktopServices::setUrlHandler(QLatin1String("http"), this, "openUrl"); QString localSysName = QLocale::system().name(); installTranslator(QLatin1String("qt_") + localSysName); QSettings settings; settings.beginGroup(QLatin1String("sessions")); m_lastSession = settings.value(QLatin1String("lastSession")).toByteArray(); settings.endGroup(); #if defined(Q_WS_MAC) connect(this, SIGNAL(lastWindowClosed()), this, SLOT(lastWindowClosed())); #endif QTimer::singleShot(0, this, SLOT(postLaunch())); }
QList<QStringList> USB_WiFi::scan_wifi(int update) { QMutexLocker locker(&mutex); QElapsedTimer timer; timer.start(); if(update == 1) qDebug()<<"update_scan thread:"<<QThread::currentThread(); else if(update == 0) qDebug()<<"scan_wifi thread:"<<QThread::currentThread(); if(update != 2) emit errorMsg(QString("scan wifi ...").prepend(update ? "update ":"")); qApp->processEvents(); QStringList header; header<<"SSID"<<"Intensity"<<"state"; QList<QStringList> result; result.append(header); process = new QProcess(); process->start("scan-wifi"); QStringList line; if(process->waitForStarted()) { if(process->waitForReadyRead(8000)) { QByteArray ret; while (process->bytesAvailable() > 0) { ret = process->readLine(); line.append(ret); qDebug()<<ret; } if(process->state() != 0) process->kill(); } } else return result; QString info; QStringList list; if(line.count() > 1) for (int i=0;i<line.count()-1;i++) { info = line[i]; QString Intensity = "NULL"; QString SSID = "<hidden>"; QString state="open"; Intensity = info.mid(1,4).trimmed(); int len = 0; if(info.right(13).count("(Security)") == 1) { state="locked"; len = info.lastIndexOf('(')-7; if(len > 0) SSID = info.mid(6,len); } else len = info.lastIndexOf('\n')-6; if(len > 0) SSID = info.mid(6,len); if(SSID == connected_ssid && ! connected_ssid.isEmpty()) state = "connected"; list.clear(); list<<SSID<<Intensity<<state; result.append(list); } emit errorMsg(QString("scan wifi completed! %1s").arg(timer.elapsed()/1000.0, 0, 'f', 3)); return result; }
void XMLSchemaWriter::writeComplexTypeClassifierDecl (UMLClassifier *c, UMLAssociationList associations, UMLAssociationList aggregations, UMLAssociationList compositions, UMLClassifierList superclasses, QTextStream &XMLschema) { // Preparations // // sort attributes by Scope UMLAttributeList attribs = findAttributes(c); QStringList attribGroups = findAttributeGroups(c); // test for relevant associations bool hasAssociations = determineIfHasChildNodes(c); bool hasSuperclass = superclasses.count()> 0; bool hasAttributes = attribs.count() > 0 || attribGroups.count() > 0; // START WRITING // start body of element QString elementTypeName = getElementTypeName(c); XMLschema<<getIndent()<<"<"<<makeSchemaTag("complexType")<<" name=\""<<elementTypeName<<"\""; if(hasAssociations || hasAttributes || hasSuperclass) { XMLschema<<">"<<m_endl; m_indentLevel++; if(hasSuperclass) { QString superClassName = getElementTypeName(superclasses.first()); XMLschema<<getIndent()<<"<"<<makeSchemaTag("complexContent")<<">"<<m_endl; //PROBLEM: we only treat ONE superclass for inheritence.. bah. m_indentLevel++; XMLschema<<getIndent()<<"<"<<makeSchemaTag("extension")<<" base=\""<<makePackageTag(superClassName) <<"\""; if(hasAssociations || hasAttributes ) XMLschema<<">"<<m_endl; else XMLschema<<"/>"<<m_endl; m_indentLevel++; } if(hasAssociations) { // Child Elements (from most associations) // bool didFirstOne = false; didFirstOne = writeAssociationDecls(associations, true, didFirstOne, c->getID(), XMLschema); didFirstOne = writeAssociationDecls(aggregations, false, didFirstOne, c->getID(), XMLschema); didFirstOne = writeAssociationDecls(compositions, false, didFirstOne, c->getID(), XMLschema); if (didFirstOne) { m_indentLevel--; XMLschema<<getIndent()<<"</"<<makeSchemaTag("sequence")<<">"<<m_endl; } } // ATTRIBUTES // if(hasAttributes) { writeAttributeDecls(attribs, XMLschema); for(uint i= 0; i < attribGroups.count(); i++) XMLschema<<getIndent()<<"<"<<makeSchemaTag("attributeGroup")<<" ref=\"" <<makePackageTag(attribGroups[i])<<"\"/>"<<m_endl; } if(hasSuperclass) { m_indentLevel--; if(hasAssociations || hasAttributes ) XMLschema<<getIndent()<<"</"<<makeSchemaTag("extension")<<">"<<m_endl; m_indentLevel--; XMLschema<<getIndent()<<"</"<<makeSchemaTag("complexContent")<<">"<<m_endl; } // close this element decl m_indentLevel--; XMLschema<<getIndent()<<"</"<<makeSchemaTag("complexType")<<">"<<m_endl; } else XMLschema<<"/>"<<m_endl; // empty node. just close this element decl }
bool SourceManager::findScripts() { QString path = GetShareDir() + "mythweather/scripts/"; QDir dir(path); dir.setFilter(QDir::Executable | QDir::Files | QDir::Dirs); if (!dir.exists()) { VERBOSE(VB_IMPORTANT, "MythWeather: Scripts directory not found"); return false; } QString busymessage = tr("Searching for scripts"); MythScreenStack *popupStack = GetMythMainWindow()->GetStack("weather stack"); if (popupStack == NULL) popupStack = GetMythMainWindow()->GetStack("popup stack"); MythUIBusyDialog *busyPopup = new MythUIBusyDialog(busymessage, popupStack, "mythweatherbusydialog"); if (busyPopup->Create()) { popupStack->AddScreen(busyPopup, false); } else { delete busyPopup; busyPopup = NULL; } qApp->processEvents(); recurseDirs(dir); // run through and see if any scripts have been deleted MSqlQuery db(MSqlQuery::InitCon()); db.prepare("SELECT sourceid, path FROM weathersourcesettings " "WHERE hostname = :HOST;"); db.bindValue(":HOST", gCoreContext->GetHostName()); if (!db.exec()) MythDB::DBError("SourceManager::findScripts - select", db); QStringList toRemove; while (db.next()) { QFileInfo fi(db.value(1).toString()); if (!fi.isExecutable()) { toRemove << db.value(0).toString(); VERBOSE(VB_IMPORTANT, QString("'%1' no longer exists") .arg(fi.absoluteFilePath())); } } db.prepare("DELETE FROM weathersourcesettings WHERE sourceid = :ID;"); for (int i = 0; i < toRemove.count(); ++i) { db.bindValue(":ID", toRemove[i]); if (!db.exec()) { // MythDB::DBError("Deleting weather source settings", db); } } if (busyPopup) { busyPopup->Close(); busyPopup = NULL; } return m_scripts.count() > 0; }
static void parse( MetaTranslator *tor, const char *initialContext, const char *defaultContext ) { QMap<QCString, QCString> qualifiedContexts; QStringList namespaces; QCString context; QCString ext; QCString text; QCString comment; QCString functionContext = initialContext; QCString prefix; bool utf8 = FALSE; yyTok = getToken(); while ( yyTok != Tok_Eof ) { switch ( yyTok ) { case Tok_i18n: utf8 = FALSE; yyTok = getToken(); if ( match( Tok_LeftParen ) && ( matchString( &context ) || matchSString( &context ) ) && match( Tok_Comma ) && ( matchString( &text ) || matchSString( &text ) ) ) { if ( ( match( Tok_Comma ) && ( matchString( &comment ) || matchSString( &comment ) ) && match( Tok_RightParen ) ) == false ) { comment = ""; } tor->insert( MetaTranslatorMessage( context, text, comment, QString::null, utf8 ) ); } // else // qDebug( " --- token failed ------------" ); break; case Tok_x18n: utf8 = FALSE; yyTok = getToken(); if ( match( Tok_LeftParen ) && ( matchString( &ext ) || matchSString( &ext ) ) && match( Tok_Comma ) && ( matchString( &context ) || matchSString( &context ) ) && match( Tok_Comma ) && ( matchString( &text ) || matchSString( &text ) ) ) { if ( ( match( Tok_Comma ) && ( matchString( &comment ) || matchSString( &comment ) ) && match( Tok_RightParen ) ) == false ) { comment = ""; } tor->insert( MetaTranslatorMessage( context, text, comment, QString::null, utf8 ) ); } // else // qDebug( " --- token failed ------------" ); break; case Tok_Ident: if ( !prefix.isNull() ) prefix += "::"; prefix += yyIdent; yyTok = getToken(); if ( yyTok != Tok_Gulbrandsen ) prefix = (const char *) 0; break; case Tok_Comment: comment = yyComment; comment = comment.simplifyWhiteSpace(); yyTok = getToken(); break; case Tok_Gulbrandsen: // at top level? if ( yyBraceDepth == (int) namespaces.count() && yyParenDepth == 0 ) functionContext = prefix; yyTok = getToken(); break; case Tok_RightBrace: case Tok_Semicolon: if ( yyBraceDepth >= 0 && yyBraceDepth + 1 == (int) namespaces.count() ) namespaces.remove( namespaces.fromLast() ); if ( yyBraceDepth == (int) namespaces.count() ) { functionContext = defaultContext; } yyTok = getToken(); break; default: yyTok = getToken(); } } // if ( yyBraceDepth != 0 ) // qWarning( "%s: Unbalanced braces in PHP code", (const char *) yyFileName ); // if ( yyParenDepth != 0 ) // qWarning( "%s: Unbalanced parentheses in PHP code", (const char *) yyFileName ); }
int runRcc(int argc, char *argv[]) { QString outFilename; bool helpRequested = false; bool list = false; QStringList files; QStringList args = qCmdLineArgs(argc, argv); RCCBuilder builder; //parse options QString errorMsg; for (int i = 1; i < args.count() && errorMsg.isEmpty(); i++) { if (args[i].isEmpty()) continue; if (args[i][0] == QLatin1Char('-')) { // option QString opt = args[i]; if (opt == QLatin1String("-o")) { if (!(i < argc-1)) { errorMsg = QLatin1String("Missing output name"); break; } outFilename = args[++i]; } else if (opt == QLatin1String("-name")) { if (!(i < argc-1)) { errorMsg = QLatin1String("Missing target name"); break; } builder.initName = args[++i]; } else if (opt == QLatin1String("-root")) { if (!(i < argc-1)) { errorMsg = QLatin1String("Missing root path"); break; } builder.resourceRoot = QDir::cleanPath(args[++i]); if (builder.resourceRoot.isEmpty() || builder.resourceRoot.at(0) != QLatin1Char('/')) errorMsg = QLatin1String("Root must start with a /"); } else if (opt == QLatin1String("-compress")) { if (!(i < argc-1)) { errorMsg = QLatin1String("Missing compression level"); break; } builder.compressLevel = args[++i].toInt(); } else if (opt == QLatin1String("-threshold")) { if (!(i < argc-1)) { errorMsg = QLatin1String("Missing compression threshold"); break; } builder.compressThreshold = args[++i].toInt(); } else if (opt == QLatin1String("-binary")) { builder.writeBinary = true; } else if (opt == QLatin1String("-namespace")) { builder.useNameSpace = !builder.useNameSpace; } else if (opt == QLatin1String("-verbose")) { builder.verbose = true; } else if (opt == QLatin1String("-list")) { list = true; } else if (opt == QLatin1String("-version") || opt == QLatin1String("-v")) { fprintf(stderr, "Qt Resource Compiler version %s\n", QT_VERSION_STR); return 1; } else if (opt == QLatin1String("-help") || opt == QLatin1String("-h")) { helpRequested = true; } else if (opt == QLatin1String("-no-compress")) { builder.compressLevel = -2; } else { errorMsg = QString::fromLatin1("Unknown option: '%1'").arg(args[i]); } } else { if (!QFile::exists(args[i])) { qWarning("%s: File does not exist '%s'", qPrintable(args[0]), qPrintable(args[i])); return 1; } files.append(args[i]); } } if (!files.size() || !errorMsg.isEmpty() || helpRequested) return showHelp(args[0], errorMsg); return int(!builder.processResourceFile(files, outFilename, list)); }
void CBIR::buildDescriptorsMatrix(QString path){ QString rootG = "../img/keepcon2-g/"; //QString root = "../img/keepcon2/"; QString root = path; QStringList images; QStringList fileDirs; //Carga todas las imágenes. QDir dir(root); dir.setFilter(QDir::Files | QDir::NoDotAndDotDot); dir.setSorting(QDir::Name); images << dir.entryList(); //Carga las imágenes de los grupos indicados. /* fileDirs << "auto" << "converse" << "doki"; for(int i=0; i<fileDirs.count(); i++){ QDir dir(rootG + fileDirs[i] + "/"); dir.setFilter(QDir::Files | QDir::NoDotAndDotDot); dir.setSorting(QDir::Name | QDir::Reversed); images << dir.entryList(); } */ //Carga de imágenes específicas. //images << "auto.jpg" << "auto-f.jpg" << "converse.jpg"; cout << "Cantidad de imagenes: " << images.count() << endl; //int length = (int)(imgDescriptors->elem_size/sizeof(float)); //descriptorsMat = cv::Mat(1106, DESCRIPTOR_DIMS, CV_32F); //float* img_ptr = descriptorsMat.ptr<float>(0); //CvSeqReader img_reader; CvSeq* totalDescriptors = 0; CvSeq* nextSeq = 0; IplImage* img; CvSeq *imgKeypoints, *imgDescriptors; CvSURFParams params = cvSURFParams(500, 1); //Calcula features para cada imagen for(int i=0; i<images.count(); i++){ img = NULL; imgKeypoints = 0; imgDescriptors = 0; qDebug() << "Intento de carga de la imagen" << images[i] << "."; img = Utils::loadImage((root + images[i]).toAscii().data(), true); if(img != NULL){ CvMemStorage* storage = cvCreateMemStorage(0); cvExtractSURF(img, 0, &imgKeypoints, &imgDescriptors, storage, params); qDebug() << "Imagen" << images[i] << "cargada con exito. Features:" << imgKeypoints->total; featuresCount.append(QPair<QString, int>(images[i], imgDescriptors->total)); //Linkeo la nueva secuencia de descriptores a la lista. if(totalDescriptors == 0){ totalDescriptors = imgDescriptors; nextSeq = totalDescriptors; }else{ nextSeq->h_next = imgDescriptors; nextSeq = nextSeq->h_next; } //Copiar los descriptores a la matriz de features /* cvStartReadSeq(imgDescriptors, &img_reader); for(int j=0; j<imgDescriptors->total; j++){ // j<1 para cargar un solo descriptor por cada imagen (prueba). const float* descriptor = (const float*)img_reader.ptr; CV_NEXT_SEQ_ELEM(img_reader.seq->elem_size, img_reader); memcpy(img_ptr, descriptor, DESCRIPTOR_DIMS*sizeof(float)); img_ptr += DESCRIPTOR_DIMS; } */ //cvReleaseMemStorage(&storage); cvReleaseImage(&img); } } int descriptorsCount = 0; int sequencesCount = 0; CvSeq* iterateSeq = totalDescriptors; while(iterateSeq != nextSeq){ descriptorsCount += iterateSeq->total; iterateSeq = iterateSeq->h_next; sequencesCount++; } if(iterateSeq != 0){ descriptorsCount += iterateSeq->total; sequencesCount++; } qDebug() << "Total de secuencias:" << sequencesCount; qDebug() << "Total de descriptores:" << descriptorsCount; //Creo la matriz de descriptores ahora que se conoce la cantidad. descriptorsMat = cv::Mat(descriptorsCount, DESCRIPTOR_DIMS, CV_32F); float* img_ptr = descriptorsMat.ptr<float>(0); CvSeqReader img_reader; //Copia los descriptores de la lista de secuencias a la matriz. iterateSeq = totalDescriptors; CvSeq* deallocateSeq = 0; for(int i=0; i<sequencesCount; i++){ deallocateSeq = iterateSeq; cvStartReadSeq(iterateSeq, &img_reader); int j; for(j=0; j<iterateSeq->total; j++){ const float* descriptor = (const float*)img_reader.ptr; CV_NEXT_SEQ_ELEM(img_reader.seq->elem_size, img_reader); memcpy(img_ptr, descriptor, DESCRIPTOR_DIMS*sizeof(float)); img_ptr += DESCRIPTOR_DIMS; } iterateSeq = iterateSeq->h_next; //Probar que efectivamente se libera la memoria. cvReleaseMemStorage(&deallocateSeq->storage); } }
void Participant::handleSampleSelection(const QStringList &paths) { int count = paths.count(); QStringList errors; // Insert new zones at the index of the first selected zone, or at the end // if no zones are selected. int insertIndex = context->getSelectedZoneCount() ? context->getZoneIndex(context->getSelectedZone(0)) : context->getZoneCount(); for (int i = 0; i < count; i++) { QString path = paths[i]; try { // Make sure the object at the given path is a valid sample file. // If the object isn't valid, then one of these constructors will // raise a `synthclone::Error`. synthclone::Sample sample(path); synthclone::SampleInputStream stream(sample); // Check the total time consumed by the sample. If it isn't in the // acceptable range for `synthclone` dry samples, then raise a // `synthclone::Error`. synthclone::SampleRate sampleRate = stream.getSampleRate(); synthclone::SampleTime time = stream.getFrames() / static_cast<synthclone::SampleTime>(sampleRate); QString message; if (time > synthclone::SAMPLE_TIME_MAXIMUM) { message = tr("%1: sample time is %2, which is greater than %3 " "seconds"). arg(path).arg(time).arg(synthclone::SAMPLE_TIME_MAXIMUM); throw synthclone::Error(message); } if (time < synthclone::SAMPLE_TIME_MINIMUM) { message = tr("%1: sample time is %2, which is less than %3 " "seconds"). arg(path).arg(time).arg(synthclone::SAMPLE_TIME_MINIMUM); throw synthclone::Error(message); } // Create a new zone for this sample, and set the sample time and // dry sample properties approriately. Make sure to remove the // zone if an exception is thrown, and propagate the exception to // the outer catch. synthclone::Zone *zone = context->addZone(insertIndex); try { zone->setSampleTime(time); zone->setDrySample(&sample); } catch (...) { context->removeZone(zone); throw; } } catch (synthclone::Error &e) { // Record errors that occur. errors.append(e.getMessage()); continue; } // We've successfully added a zone with a sample from the hard drive. insertIndex++; } // Report any errors that occurred during the operation. if (errors.count()) { context->reportError(errors.join("\n")); } }
/* * This Event method is called whenever the user presses a key */ void MainWindow::keyPressEvent(QKeyEvent* ke) { if (ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter) { if (ui->tvPackages->hasFocus()) { execKeyActionOnPackage(ectn_INSTALL); } //We are searching for AUR foreign packages... else if (isAURGroupSelected() && m_leFilterPackage->hasFocus() && m_cic == NULL) { if (UnixCommand::getLinuxDistro() == ectn_KAOS) return; ui->twGroups->setEnabled(false); QFuture<QList<PackageListData> *> f; disconnect(&g_fwAUR, SIGNAL(finished()), this, SLOT(preBuildAURPackageList())); m_cic = new CPUIntensiveComputing(); f = QtConcurrent::run(searchAURPackages, m_leFilterPackage->text()); g_fwAUR.setFuture(f); connect(&g_fwAUR, SIGNAL(finished()), this, SLOT(preBuildAURPackageList())); } //We are searching for packages that own some file typed by user... else if (isSearchByFileSelected() && m_leFilterPackage->hasFocus() && m_cic == NULL) { ui->twGroups->setEnabled(false); QFuture<QString> f; disconnect(&g_fwPackageOwnsFile, SIGNAL(finished()), this, SLOT(positionInPkgListSearchByFile())); m_cic = new CPUIntensiveComputing(); f = QtConcurrent::run(searchPacmanPackagesByFile, m_leFilterPackage->text()); g_fwPackageOwnsFile.setFuture(f); connect(&g_fwPackageOwnsFile, SIGNAL(finished()), this, SLOT(positionInPkgListSearchByFile())); } //We are probably inside 'Files' tab... else { QTreeView *tvPkgFileList = ui->twProperties->widget(ctn_TABINDEX_FILES)->findChild<QTreeView*>("tvPkgFileList"); if(tvPkgFileList) { if(tvPkgFileList->hasFocus()) { openFile(); } } } } else if(ke->key() == Qt::Key_Escape) { if(m_leFilterPackage->hasFocus()) { m_leFilterPackage->clear(); } } else if(ke->key() == Qt::Key_Delete) { onPressDelete(); } else if(ke->key() == Qt::Key_1 && ke->modifiers() == Qt::AltModifier) { changeTabWidgetPropertiesIndex(ctn_TABINDEX_INFORMATION); } else if(ke->key() == Qt::Key_2 && ke->modifiers() == Qt::AltModifier) { ui->twProperties->setCurrentIndex(ctn_TABINDEX_FILES); refreshTabFiles(false, true); } else if(ke->key() == Qt::Key_3 && ke->modifiers() == Qt::AltModifier) { changeTabWidgetPropertiesIndex(ctn_TABINDEX_TRANSACTION); } else if(ke->key() == Qt::Key_4 && ke->modifiers() == Qt::AltModifier) { changeTabWidgetPropertiesIndex(ctn_TABINDEX_OUTPUT); } else if(ke->key() == Qt::Key_5 && ke->modifiers() == Qt::AltModifier) { changeTabWidgetPropertiesIndex(ctn_TABINDEX_NEWS); } else if(ke->key() == Qt::Key_6 && ke->modifiers() == Qt::AltModifier) { changeTabWidgetPropertiesIndex(ctn_TABINDEX_HELPUSAGE); } else if(ke->key() == Qt::Key_F2) { if (isPackageTreeViewVisible()) { if (!ui->tvPackages->hasFocus()) ui->tvPackages->setFocus(); } else { maximizePropertiesTabWidget(false); if (!ui->tvPackages->hasFocus()) ui->tvPackages->setFocus(); } } else if(ke->key() == Qt::Key_F4) { openTerminal(); } else if(ke->key() == Qt::Key_F6) { openDirectory(); } else if (ke->key() == Qt::Key_F10) { maximizePackagesTreeView(false); } else if (ke->key() == Qt::Key_F12) { maximizePropertiesTabWidget(false); } else if(ke->key() == Qt::Key_C && ke->modifiers() == Qt::ControlModifier) { copyFullPathToClipboard(); } else if(ke->key() == Qt::Key_L && ke->modifiers() == Qt::ControlModifier) { m_leFilterPackage->setFocus(); m_leFilterPackage->selectAll(); } else if(ke->key() == Qt::Key_F && ke->modifiers() == Qt::ControlModifier) { if (m_commandExecuting != ectn_NONE) return; if (isPropertiesTabWidgetVisible() && (ui->twProperties->currentIndex() == ctn_TABINDEX_INFORMATION || ui->twProperties->currentIndex() == ctn_TABINDEX_OUTPUT || ui->twProperties->currentIndex() == ctn_TABINDEX_NEWS || ui->twProperties->currentIndex() == ctn_TABINDEX_HELPUSAGE)) { QTextBrowser *tb = ui->twProperties->currentWidget()->findChild<QTextBrowser*>("textBrowser"); SearchBar *searchBar = ui->twProperties->currentWidget()->findChild<SearchBar*>("searchbar"); if (tb && tb->toPlainText().size() > 0 && searchBar) { if (searchBar) searchBar->show(); } } else if (isPropertiesTabWidgetVisible() && ui->twProperties->currentIndex() == ctn_TABINDEX_FILES) { QTreeView *tb = ui->twProperties->currentWidget()->findChild<QTreeView*>("tvPkgFileList"); SearchBar *searchBar = ui->twProperties->currentWidget()->findChild<SearchBar*>("searchbar"); if (tb && tb->model()->rowCount() > 0 && searchBar) { if (searchBar) searchBar->show(); } } } else if(ke->key() == Qt::Key_D && ke->modifiers() == (Qt::ShiftModifier|Qt::ControlModifier)) { //The user wants to know which packages have no description! showPackagesWithNoDescription(); } else if(ke->key() == Qt::Key_G && ke->modifiers() == (Qt::ShiftModifier|Qt::ControlModifier)) { //The user wants to go to "Display All groups" if (!isAllGroupsSelected()) { ui->twGroups->setCurrentItem(m_AllGroupsItem); } } else if(ke->key() == Qt::Key_Y && ke->modifiers() == (Qt::ShiftModifier|Qt::ControlModifier) && m_hasAURTool) { if (m_commandExecuting != ectn_NONE) return; //The user wants to use "AUR tool" to search for pkgs m_actionSwitchToAURTool->trigger(); if (m_actionSwitchToAURTool->isChecked() && UnixCommand::getLinuxDistro() != ectn_KAOS) { m_leFilterPackage->setFocus(); } else { ui->tvPackages->setFocus(); } } else if(ke->key() == Qt::Key_C && ke->modifiers() == (Qt::ShiftModifier|Qt::ControlModifier)) { if (m_commandExecuting == ectn_NONE) { doCleanCache(); //If we are not executing any command, let's clean the cache } } else if(ke->key() == Qt::Key_R && ke->modifiers() == (Qt::ShiftModifier|Qt::ControlModifier)) { if (m_commandExecuting == ectn_NONE) { doRemovePacmanLockFile(); //If we are not executing any command, let's remove Pacman's lock file } } else if(ke->key() == Qt::Key_S && ke->modifiers() == (Qt::ShiftModifier|Qt::ControlModifier)) { gistSysInfo(); } #if QT_VERSION >= 0x050300 else if(ke->key() == Qt::Key_T && ke->modifiers() == (Qt::ShiftModifier|Qt::ControlModifier) && m_initializationCompleted) { if (m_commandExecuting != ectn_NONE) return; QStringList terminals = Terminal::getListOfAvailableTerminals(); if (terminals.count() > 2) { int index = terminals.indexOf(SettingsManager::getTerminal()); int newIndex = selectTerminal(index); if (index != newIndex) { SettingsManager::setTerminal(terminals.at(newIndex)); } } } #endif else ke->ignore(); }
void Statistic::onReport() { ui.curOperationLabel->setText(trUtf8("Анализ отчета...")); setCursor(Qt::WaitCursor); CXSettings* settings = CXSettings::inst(); settings->setValue(E_StartDate, QDateTime(ui.mStartDateEdit->date(), ui.mStartTimeEdit->time())); settings->setValue(E_EndDate, QDateTime(ui.mEndDateEdit->date(), ui.mEndTimeEdit->time())); QStringList xmlFiles; #ifdef DEBUG_VER QString tmp = "D:/CNC_stat"; #else QString tmp = QApplication::applicationDirPath(); #endif QDir logsDir(tmp + "/" + LOG_PATH); //QDir logsDir(QApplication::applicationDirPath() + "/" + LOG_PATH); QString tempFileName; QStringList dirs = logsDir.entryList(QDir::Dirs); for (int i = 0; i < dirs.count(); ++i) { tempFileName = logsDir.path() + "/" + dirs.at(i) + "/report.xml"; if (QFile::exists(tempFileName)) xmlFiles.append(tempFileName); } QList <SXReportError> errorList = Engine::generateReport(xmlFiles, settings->value(E_StartDate).toDateTime(), settings->value(E_EndDate).toDateTime()); //#ifndef QT_NO_DEBUG // ui.mErrorTree->clear(); // // QTreeWidgetItem* newItem = NULL; // QTreeWidgetItem* childItem = NULL; // QString lastFilename = ""; // // for (int i = 0; i < errorList.count(); ++i) // { // const SXReportError& curErrorData = errorList.at(i); // // if ((newItem == NULL) || ((newItem != NULL) && (lastFilename != curErrorData.mFileName))) // { // newItem = new QTreeWidgetItem(ui.mErrorTree); // lastFilename = curErrorData.mFileName; // newItem->setText(0, lastFilename); // } // // childItem = new QTreeWidgetItem(newItem); // childItem->setForeground(0, Qt::red); // childItem->setText(0, curErrorData.mError); // // ui.mErrorTree->addTopLevelItem(newItem); // } //#else QFile errorLog("errors.log"); errorLog.open(QIODevice::WriteOnly); QTextStream textStream(&errorLog); textStream.setCodec(QTextCodec::codecForName("UTF-8")); for (int i = 0; i < errorList.count(); ++i) { const SXReportError& curErrorData = errorList.at(i); textStream << curErrorData.mFileName << "\t-\t"; textStream << curErrorData.mError << "\n"; } //#endif ui.mReportView->setHtml(Engine::getReportText()); ui.curOperationLabel->setText(trUtf8("Нет текущих операций")); setCursor(Qt::ArrowCursor); }
void SettingsJavaPluginForm::finished(QNetworkReply* reply) { reply->deleteLater(); m_reply = 0; disconnect(m_network, SIGNAL(finished(QNetworkReply*)), this, SLOT(finished(QNetworkReply*))); if (reply->error() != QNetworkReply::NoError) { setError(tr("Failed to download the plugin index file: %1").arg(reply->errorString())); return; } bool versionChecked = false; bool versionOK = false; while (!reply->atEnd()) { QString line = reply->readLine().trimmed(); if (line.isEmpty() && versionChecked) break; if (line.isEmpty() && !versionChecked) { if (!versionOK) { setError(tr("Your version of FatRat is no longer supported by the update site.")); return; } else versionChecked = true; } if (line.startsWith("Version: ")) { if (line.mid(9) == VERSION) versionOK = true; } else { QStringList parts = line.split('\t'); if (parts.count() < 3) continue; Plugin plugin; plugin.name = parts[0]; plugin.version = parts[1]; plugin.desc = parts[2]; m_availablePlugins << plugin; } } for (int i = 0; i < m_availablePlugins.size(); i++) { const Plugin& pl = m_availablePlugins[i]; QString fullName = pl.name + ".jar"; if (m_installedPlugins.contains(fullName)) { if (pl.version > m_installedPlugins[fullName]) { QTreeWidgetItem* i = new QTreeWidgetItem(treeUpdates, QStringList() << pl.name << pl.version); if (pl.name != "fatrat-jplugins") { i->setFlags(i->flags() | Qt::ItemIsUserCheckable); i->setCheckState(0, Qt::Unchecked); } else { i->setCheckState(0, Qt::Checked); i->setFlags( i->flags() & ~(Qt::ItemIsUserCheckable|Qt::ItemIsEnabled)); } treeUpdates->addTopLevelItem(i); } } else { QTreeWidgetItem* i = new QTreeWidgetItem(treeAvailable, QStringList() << pl.name << pl.desc); i->setFlags(i->flags() | Qt::ItemIsUserCheckable); i->setCheckState(0, Qt::Unchecked); treeAvailable->addTopLevelItem(i); } } toolBox->setItemText(0, tr("Available extensions (%1)").arg(treeAvailable->topLevelItemCount())); toolBox->setItemText(1, tr("Updates (%1)").arg(treeUpdates->topLevelItemCount())); }
void createTable(QString tableName,QList<QDomNode> fields,QTextStream &outstrm, QString tableDesc, bool isLookUp) { QStringList sfields; QStringList indexes; QStringList keys; QStringList rels; QString sql; QString keysql; QString field; QString index; QString constraint; int pos; QList <TrelatedTable> relTables; qDebug() << "Creating table: " + tableName; sfields << "CREATE TABLE IF NOT EXISTS " + tableName + "(" << "\n"; keys << "PRIMARY KEY ("; for (int fld = 0; fld < fields.count(); fld++) { QDomElement efield = fields[fld].toElement(); field = ""; if ((efield.attribute("type","") == "varchar") || (efield.attribute("type","") == "int")) field = efield.attribute("name","") + " " + efield.attribute("type","") + "(" + efield.attribute("size","") + ")"; else if (efield.attribute("type","") == "decimal") field = efield.attribute("name","") + " " + efield.attribute("type","") + "(" + efield.attribute("size","") + "," + efield.attribute("decsize","") + ")"; else field = efield.attribute("name","") + " " + efield.attribute("type",""); if (efield.attribute("key","false") == "true") { field = field + " NOT NULL COMMENT \"" + efield.attribute("desc","") + "\", "; keys << efield.attribute("name","") + " , "; } else field = field + " COMMENT \"" + efield.attribute("desc","") + "\", "; sfields << field << "\n"; if (efield.attribute("rtable","") != "") { if (efield.attribute("rlookup","") == "true") { idx++; index = "INDEX fk" + QString::number(idx) + "_" + tableName + "_" + efield.attribute("rtable","") ; indexes << index.left(64) + " (" + efield.attribute("name","") + ") , " << "\n"; constraint = "CONSTRAINT fk" + QString::number(idx) + "_" + tableName + "_" + efield.attribute("rtable",""); rels << constraint.left(64) << "\n"; rels << "FOREIGN KEY (" + efield.attribute("name","") + ")" << "\n"; rels << "REFERENCES " + efield.attribute("rtable","") + " (" + efield.attribute("rfield","") + ")" << "\n"; rels << "ON DELETE RESTRICT " << "\n"; rels << "ON UPDATE NO ACTION," << "\n"; } else { pos = relTableFound(relTables,efield.attribute("rtable","")); if (pos >= 0) { TrelatedField relfield; relfield.name = efield.attribute("name",""); relfield.rname = efield.attribute("rfield",""); relTables[pos].fields.append(relfield); } else { TrelatedTable relTable; relTable.name = efield.attribute("rtable",""); TrelatedField relfield; relfield.name = efield.attribute("name",""); relfield.rname = efield.attribute("rfield",""); relTable.fields.append(relfield); relTables.append(relTable); } } } } //Process combined foreign keys for (pos = 0; pos < relTables.count();pos++) { idx++; index = "INDEX fk" + QString::number(idx) + "_" + tableName + "_" + relTables[pos].name ; indexes << index.left(64) + " (" + getFields(relTables[pos]) + ") , " << "\n"; constraint = "CONSTRAINT fk" + QString::number(idx) + "_" + tableName + "_" + relTables[pos].name; rels << constraint.left(64) << "\n"; rels << "FOREIGN KEY (" + getFields(relTables[pos]) + ")" << "\n"; rels << "REFERENCES " + relTables[pos].name + " (" + getRelatedFields(relTables[pos]) + ")" << "\n"; rels << "ON DELETE CASCADE " << "\n"; rels << "ON UPDATE NO ACTION," << "\n"; } int clm; //Contatenate al different pieces of the create script into one SQL for (clm = 0; clm <= sfields.count() -1;clm++) { sql = sql + sfields[clm]; } for (clm = 0; clm <= keys.count() -1;clm++) { keysql = keysql + keys[clm]; } clm = keysql.lastIndexOf(","); keysql = keysql.left(clm) + ") , \n"; sql = sql + keysql; for (clm = 0; clm <= indexes.count() -1;clm++) { sql = sql + indexes[clm]; } for (clm = 0; clm <= rels.count() -1;clm++) { sql = sql + rels[clm]; } clm = sql.lastIndexOf(","); sql = sql.left(clm); sql = sql + ")" + "\n ENGINE = InnoDB CHARSET=utf8 COMMENT = \"" + tableDesc + "\"; \n"; idx++; sql = sql + "CREATE UNIQUE INDEX rowuuid" + QString::number(idx) + " ON " + tableName + "(rowuuid);\n"; if (isLookUp) sql = sql + "CREATE TRIGGER uudi_" + tableName + " BEFORE INSERT ON " + tableName + " FOR EACH ROW SET new.rowuuid = uuid();\n\n"; else sql = sql + "\n"; outstrm << sql; }
void sortByLexeme(QStringList &sortList) { // Карта для хранения строк с начальной текстовой строкой // Ключ карты - начальная строка, значения - остаток строки QMap<QString, QStringList> strMap; // Карта для хранения строк с начальной числовой строкой // Ключ карты - начальная строка, значения - остаток строки QMap<double, QStringList> numMap; QList<double> sortingKeyNum; // Лист для сортировки числовых ключей QStringList sortingKeyStr; // Лист для сортировки строковых ключей QStringList res; // Результирующий лист QString temp; // Буфер для текущей обрабатываемой строки QString buf; // Буфер для ключа - домена QString str; // Буфер для одного из значений ключа - имени адреса QString aIter; // Буфер для строкого ключа при формировании выходного списка QString aIterKlein; // Буфер для строки из списка для каждой строки из списка double num; // Буфер для хранения ключа для числовой карты double aIterNum; // Буфер для числового ключа при формировании выходного списка // Заполнение карты путей for(int i=0; i<sortList.count(); i++) { // Загрузка в бущер текущей строки для сортировки temp=sortList[i]; // Заполнение карты по числовому ключу if(temp[0].isNumber()) { // Получение ключа buf=temp.section(QRegExp("[A-z]"), 0, 0); // Перевод ключа из строки в число num=buf.toDouble(); // Получение значения str=temp.remove(buf); /*// Заполнение карты, если остаток строки не пустой if(!str.isEmpty()) {*/ if(numMap.contains(num)) { numMap[num]<<str; } else { numMap.insert(num, QStringList(str)); } //} } // Заполнение карты по нечисловому ключу else { // Получение ключа buf=temp.section(QRegExp("\\d"), 0, 0); // Получение значения str=temp.remove(buf); /*// Заполнение карты, если остаток строки не пустой if(!str.isEmpty()) {*/ if(strMap.contains(buf)) { strMap[buf]<<str; } else { strMap.insert(buf, QStringList(str)); } //} } } // Сортировка карты с числовым ключом // Сортировка значений для каждого ключа QMap<double, QStringList>::iterator itn=numMap.begin(); for(;itn!=numMap.end(); itn++) { if(itn.value().count()>1) { sortByLexeme(itn.value()); } } // Записей ключей в лист itn=numMap.begin(); for(;itn!=numMap.end(); itn++) { sortingKeyNum<<itn.key(); } // Сортировка ключей //sortingKeyNum.sort(); qStableSort(sortingKeyNum.begin(), sortingKeyNum.end()); // Сортировка карты со строковым ключом // Сортировка значений для каждого ключа QMap<QString, QStringList>::iterator its=strMap.begin(); for(;its!=strMap.end(); its++) { if(its.value().count()>1) { sortByLexeme(its.value()); } } // Записей ключей в лист its=strMap.begin(); for(;its!=strMap.end(); its++) { sortingKeyStr<<its.key(); } // Сортировка ключей //sortingKeyStr.sort(); qStableSort(sortingKeyStr.begin(), sortingKeyStr.end(), caseInsensitiveLessThan); // Заполнение выходного листа полями из числовой карты for(int j=0; j<sortingKeyNum.count(); j++) { // Загрузка в бущер текущей строки для ключа aIterNum=sortingKeyNum[j]; // Загрузка в выходной лист значений для определенного ключа for(int k=0; k<numMap[aIterNum].count(); k++) { // Загрузка в буфер текущей строки для сортировки aIterKlein=QString::number(aIterNum)+numMap[aIterNum][k]; // Добавление строки в выходной лист res<<aIterKlein; } } // Заполнение выходного листа полями из строковой карты for(int j=0; j<sortingKeyStr.count(); j++) { // Загрузка в бущер текущей строки для ключа aIter=sortingKeyStr[j]; // Загрузка в выходной лист значений для определенного ключа for(int k=0; k<strMap[aIter].count(); k++) { // Загрузка в буфер текущей строки для сортировки aIterKlein=aIter+strMap[aIter][k]; // Добавление строки в выходной лист res<<aIterKlein; } } // Замена данного листа на возвращаемый sortList=res; }
void compile(QString path,QStringList& import,QFile &out){ QFile fp(path); if(fp.open(QFile::ReadOnly)){ QDir dir(QFileInfo(fp).absoluteDir()); QString modName = QFileInfo(fp).baseName(); if(readLine(fp).trimmed()!=FILE_HEAD){ qDebug("Indicated file is not a algorithm file of Uranus2"); exit(0); } int pIndent,cIndent=0,functionIndent=0; Function* function=0; QRegExp keyWord("(\\s*)(\\w+)\\s",Qt::CaseInsensitive); QRegExp argHook("(<.+>)?(.+)?"); QLinkedList<StackItem*> stack; while(!fp.atEnd()){ QString line=QString::fromUtf8(fp.readLine()); keyWord.indexIn(line); QString key=keyWord.cap(2).toLower(); line=line.mid(keyWord.cap().length()).trimmed(); pIndent = cIndent; cIndent=keyWord.cap(1).length(); if(cIndent<functionIndent){ if(function!=0){ function->write(out); function=0; } }else if(cIndent<=pIndent){ while(pIndent>=cIndent){ pIndent--; if(!stack.isEmpty()){ stack.pop_back(); } } } StackItem* parent = (stack.isEmpty())?0:stack.back(), *self=new StackItem(key,line,cIndent); stack.push_back(self); if(key=="import"){ import.append(dir.absoluteFilePath(line)); }else if(key=="function"){ function=new Function(modName,line); functionIndent=cIndent+1; }else if(key=="hint"){ if(function!=0){ if(parent->key=="function") self->indent++; self->outBegin="#"+line; function->append(self); } }else if(key=="arg"){ if(parent->key=="function"&&function){ function->args()<<line; } }else if(key=="assign"){ self->outBegin=line+"="; function->append(self); }else if(key=="value"){ if(parent->key=="assign"){ argHook.indexIn(line); if(argHook.cap(1)=="<list>"){ }else if(argHook.cap(1)=="<function>"){ }else if(argHook.cap(1)=="<variable>"){ self->outBegin=argHook.cap(2).trimmed(); }else{ self->outBegin=line.trimmed(); } parent->addChild(self); } }else if(key=="branch"){ self->outBegin="if True:"; function->append(self); }else if(key=="call"){ QString fname; if(line.left(3)=="://"){ fname=Function::conv(modName,line.mid(3)); }else{ QStringList f = line.split("/"); if(f.count()==2){ fname=Function::conv(f.at(0),f.at(1)); } } self->outBegin=fname+"("; self->outSep=","; self->outEnd=")"; if(parent->key=="do"){ function->append(self); }else{ parent->addChild(self); } }else if(key=="conditional"){ self->outBegin="if True:"; function->append(self); }else if(key=="do"){ }else if(key=="list"){ self->outBegin="["; self->outSep=","; self->outEnd="]"; parent->addChild(self); }else if(key=="item"){ argHook.indexIn(line); if(argHook.cap(1)=="<list>"){ }else if(argHook.cap(1)=="<function>"){ }else if(argHook.cap(1)=="<variable>"){ self->outBegin=argHook.cap(2).trimmed(); }else{ self->outBegin=line.trimmed(); } parent->addChild(self); }else if(key=="loop"){ self->outBegin="if True:"; function->append(self); }else if(key=="traverseloop"){ self->outBegin="if True:"; function->append(self); }else if(key=="traverse"){ self->outBegin="for traverse in "; self->outEnd=":"; function->append(self); }else if(key=="condition"){ self->outEnd=":"; if(parent->key=="branch"){ if(parent->data==0){ self->outBegin="if "; }else{ self->outBegin="elif "; } parent->data=1; }else if(parent->key=="loop"){ self->outBegin="while "; } argHook.indexIn(line); if(argHook.cap(1)=="<list>"){ }else if(argHook.cap(1)=="<function>"){ }else if(argHook.cap(1)=="<variable>"){ self->outBegin+=argHook.cap(2).trimmed(); }else{ self->outBegin+=line.trimmed(); } function->append(self); }else if(key=="return"){ self->outBegin="return "; argHook.indexIn(line); if(argHook.cap(1)=="<list>"){ }else if(argHook.cap(1)=="<function>"){ }else if(argHook.cap(1)=="<variable>"){ self->outBegin+=argHook.cap(2).trimmed(); }else{ self->outBegin+=line.trimmed(); } function->append(self); }else if(key=="execute"){ self->outBegin="exec("; self->outEnd=")"; argHook.indexIn(line); if(argHook.cap(1)=="<list>"){ }else if(argHook.cap(1)=="<function>"){ }else if(argHook.cap(1)=="<variable>"){ self->outBegin+=argHook.cap(2).trimmed(); }else{ self->outBegin+=line.trimmed(); } function->append(self); }else if(key=="break"){ self->outBegin = "break"; function->append(self); }else if(key=="continue"){ self->outBegin = "continue"; function->append(self); }else{ if(parent->key=="call"){ argHook.indexIn(line); if(argHook.cap(1)=="<list>"){ }else if(argHook.cap(1)=="<function>"){ }else if(argHook.cap(1)=="<variable>"){ self->outBegin+=argHook.cap(2).trimmed(); }else{ self->outBegin+=line.trimmed(); } parent->addChild(self); } } } if(function!=0) function->write(out); }else{ qDebug()<<"Can not open file "+path; } }