void DocCHMPlugin::createTOC(DocumentationCatalogItem* item) { QStringList lines = QStringList::split("\n", getSpecialData("catalog", item->url()) ); if(lines.count() % 4 != 0) { kdDebug(9002) << "DocCHMPlugin::createTOC: wrong count of strings"; return;} QValueVector<DocumentationItem*> items; items.push_back(item); for(QStringList::Iterator it = lines.begin(); it != lines.end();) { bool ok1 = true, ok2 = true; int parent = (*it).toInt(&ok1); ++it; int current = (*it).toInt(&ok2); ++it; if(int(items.size()) != current || !ok1 || !ok2 || parent < 0 || parent >= int(items.size()) || current < 0 || current != int(items.size())) { kdDebug(9002) << "DocCHMPlugin::createTOC error while parsing output of ioslave" << endl; break; } QString& name(*it); ++it; KURL url(*it); ++it; items.push_back(new DocumentationItem( DocumentationItem::Document, items[parent], chainEnd(items[parent]), decodeHTML(name))); items[current]->setURL(url); if(parent != 0) items[parent]->setType(DocumentationItem::Book); } return; }
/* Parse a DN and return an array-ized one. This is not a validating parser and it does not support any old-stylish syntax; gpgme is expected to return only rfc2253 compatible strings. */ static Kleo::DN::Attribute::List parse_dn( const unsigned char * string ) { if ( !string ) return QValueVector<Kleo::DN::Attribute>(); QValueVector<Kleo::DN::Attribute> result; while (*string) { while (*string == ' ') string++; if (!*string) break; /* ready */ DnPair pair = { 0, 0 }; string = parse_dn_part (&pair, string); if (!string) goto failure; if ( pair.key && pair.value ) result.push_back( Kleo::DN::Attribute( QString::fromUtf8( pair.key ), QString::fromUtf8( pair.value ) ) ); free( pair.key ); free( pair.value ); while (*string == ' ') string++; if (*string && *string != ',' && *string != ';' && *string != '+') goto failure; /* invalid delimiter */ if (*string) string++; } return result; failure: return QValueVector<Kleo::DN::Attribute>(); }
/** * Does spike-reduction on the given point-array's stack-top. * * Spikes are path segments of which one goes forward, and the sucessor * goes backward on the predecessor's segment: * * 2 0 1 * x------x<-----x * (0 is stack-top in point-array) * * This will be reduced to * 1 0 * x------x * * Preconditions: * - No other spikes exist in the whole point-array except at most * one at the end * - No two succeeding points are ever equal * - For each two succeeding points either p1.x == p2.x or p1.y == p2.y holds * true * - No such spike exists where 2 is situated between 0 and 1. * * Postcondition: * - No spikes exist in the whole point-array * * If no spike is found, the point-array is left unchanged. * @return \c true if an actual reduction was done */ inline static bool reduceSpike(QValueVector< QPoint > &pointArray) { if(pointArray.size() < 3) return false; QValueVector< QPoint >::Iterator it = pointArray.end(); QPoint p0 = *--it; QPoint p1 = *--it; QPoint p2 = *--it; bool elide = false; if((p0.x() == p1.x() && p1.x() == p2.x() && ((p1.y() < p0.y() && p0.y() < p2.y()) || (p2.y() < p0.y() && p0.y() < p1.y()) || (p1.y() < p2.y() && p2.y() < p0.y()) || (p0.y() < p2.y() && p2.y() < p1.y()) || (elide = p2.y() == p0.y() && p0.y() < p1.y()) || (elide = p1.y() < p0.y() && p0.y() == p2.y()))) || (p0.y() == p1.y() && p1.y() == p2.y() && ((p1.x() < p0.x() && p0.x() < p2.x()) || (p2.x() < p0.x() && p0.x() < p1.x()) || (p1.x() < p2.x() && p2.x() < p0.x()) || (p0.x() < p2.x() && p2.x() < p1.x()) || (elide = p2.x() == p0.x() && p0.x() < p1.x()) || (elide = p1.x() < p0.x() && p0.x() == p2.x())))) { // kdDebug(6040) << "spikered p2" << (elide ? " (elide)" : "") << ": " << p2 << " p1: " << p1 << " p0: " << p0 << endl; pointArray.pop_back(); pointArray.pop_back(); if(!elide) pointArray.push_back(p0); return true; } return false; }
QValueVector<KInetInterface> KInetInterface::getAllInterfaces(bool includeLoopback) { struct kde_ifaddrs *ads; struct kde_ifaddrs *a; QValueVector<KInetInterface> r; if (kde_getifaddrs(&ads)) return r; a = ads; while (a) { if ((a->ifa_flags & IFF_LOOPBACK) && !includeLoopback) { a = a->ifa_next; continue; } r.push_back(KInetInterface(QString::fromUtf8(a->ifa_name), convertFlags(a->ifa_flags), createAddress(a->ifa_addr), createAddress(a->ifa_netmask), (a->ifa_flags & IFF_BROADCAST) ? createAddress(a->ifa_broadaddr) : 0, (a->ifa_flags & IFF_POINTOPOINT) ? createAddress(a->ifa_dstaddr) : 0)); a = a->ifa_next; } kde_freeifaddrs(ads); return r; }
void PolygonElement::generate(ReportInterp* interp, int offsetX, int offsetY, QValueVector<PageElement>& elements) { PageElement element; element.type = PageElement::POLYGON; setPageElement(element, interp, offsetX, offsetY); element.points = points; elements.clear(); elements.push_back(element); }
void KOEditorDetails::writeEvent(Incidence *event) { event->clearAttendees(); QValueVector<QListViewItem*> toBeDeleted; QListViewItem *item; AttendeeListItem *a; for (item = mListView->firstChild(); item; item = item->nextSibling()) { a = (AttendeeListItem *)item; Attendee *attendee = a->data(); Q_ASSERT( attendee ); /* Check if the attendee is a distribution list and expand it */ if ( attendee->email().isEmpty() ) { KPIM::DistributionList list = KPIM::DistributionList::findByName( KABC::StdAddressBook::self(), attendee->name() ); if ( !list.isEmpty() ) { toBeDeleted.push_back( item ); // remove it once we are done expanding KPIM::DistributionList::Entry::List entries = list.entries( KABC::StdAddressBook::self() ); KPIM::DistributionList::Entry::List::Iterator it( entries.begin() ); while ( it != entries.end() ) { KPIM::DistributionList::Entry &e = ( *it ); ++it; // this calls insertAttendee, which appends insertAttendeeFromAddressee( e.addressee, attendee ); // TODO: duplicate check, in case it was already added manually } } } else { bool skip = false; if ( attendee->email().endsWith( "example.net" ) ) { if ( KMessageBox::warningYesNo( this, i18n("%1 does not look like a valid email address. " "Are you sure you want to invite this participant?").arg( attendee->email() ), i18n("Invalid email address") ) != KMessageBox::Yes ) { skip = true; } } if ( !skip ) { event->addAttendee( new Attendee( *attendee ) ); } } } KOAttendeeEditor::writeEvent( event ); // cleanup QValueVector<QListViewItem*>::iterator it; for( it = toBeDeleted.begin(); it != toBeDeleted.end(); ++it ) { delete *it; } }
/** * Reduces segment separators. * * A segment separator separates a segment into two segments, thus causing * two adjacent segment with the same orientation. * * 2 1 0 * x-------x---->x * (0 means stack-top) * * Here, 1 is a segment separator. As segment separators not only make * the line drawing algorithm inefficient, but also make the spike-reduction * fail, they must be eliminated: * * 1 0 * x------------>x * * Preconditions: * - No other segment separators exist in the whole point-array except * at most one at the end * - No two succeeding points are ever equal * - For each two succeeding points either p1.x == p2.x or p1.y == p2.y holds * true * - No such spike exists where 2 is situated between 0 and 1. * * Postcondition: * - No segment separators exist in the whole point-array * * If no segment separator is found at the end of the point-array, it is * left unchanged. * @return \c true if a segment separator was actually reduced. */ inline static bool reduceSegmentSeparator(QValueVector< QPoint > &pointArray) { if(pointArray.size() < 3) return false; QValueVector< QPoint >::Iterator it = pointArray.end(); QPoint p0 = *--it; QPoint p1 = *--it; QPoint p2 = *--it; // kdDebug(6040) << "checking p2: " << p2 << " p1: " << p1 << " p0: " << p0 << endl; if((p0.x() == p1.x() && p1.x() == p2.x() && ((p2.y() < p1.y() && p1.y() < p0.y()) || (p0.y() < p1.y() && p1.y() < p2.y()))) || (p0.y() == p1.y() && p1.y() == p2.y() && ((p2.x() < p1.x() && p1.x() < p0.x()) || (p0.x() < p1.x() && p1.x() < p2.x())))) { // kdDebug(6040) << "segred p2: " << p2 << " p1: " << p1 << " p0: " << p0 << endl; pointArray.pop_back(); pointArray.pop_back(); pointArray.push_back(p0); return true; } return false; }
void load( const QString& filename ) { QFile file( filename ); if ( !file.open( IO_ReadOnly ) ) { Console::instance()->send( tr( "Unable to open %1!\n" ).arg( filename ) ); return; } filenames.push_back( filename ); QXmlInputSource input( &file ); QXmlSimpleReader reader; reader.setFeature( "http://trolltech.com/xml/features/report-whitespace-only-CharData", false ); reader.setContentHandler( this ); reader.setErrorHandler( this ); reader.parse( &input, false ); filenames.pop_back(); }
// Construct a list of keys to be connected, sorted highest priority first. void KAccelBase::createKeyList(QValueVector< struct X > &rgKeys) { // kdDebug(125) << "KAccelBase::createKeyList()" << endl; if(!isEnabledInternal()) return; // create the list // For each action for(uint iAction = 0; iAction < m_rgActions.count(); iAction++) { KAccelAction *pAction = m_rgActions.actionPtr(iAction); if(pAction && pAction->m_pObjSlot && pAction->m_psMethodSlot && pAction != mtemp_pActionRemoving) { // For each key sequence associated with action for(uint iSeq = 0; iSeq < pAction->shortcut().count(); iSeq++) { const KKeySequence &seq = pAction->shortcut().seq(iSeq); if(seq.count() > 0) { KKeyServer::Variations vars; vars.init(seq.key(0), !m_bNativeKeys); for(uint iVari = 0; iVari < vars.count(); iVari++) { if(vars.key(iVari).code() && vars.key(iVari).sym()) rgKeys.push_back(X(iAction, iSeq, iVari, vars.key(iVari))); // kdDebug(125) << "\t" << pAction->name() << ": " << vars.key(iVari).toStringInternal() << endl; } } // else // kdDebug(125) << "\t*" << pAction->name() << ":" << endl; } } } // sort by priority: iVariation[of first key], iSequence, iAction qHeapSort(rgKeys.begin(), rgKeys.end()); }
QString EQStr::formatMessage(uint32_t formatid, const char* arguments, size_t argsLen) const { QString* formatStringRes = m_messageStrings.find(formatid); QString tempStr; if (formatStringRes == NULL) { uint32_t arg_len; unsigned char *cp; tempStr.sprintf( "Unknown: %04x:", formatid); cp = (unsigned char *) arguments; while (cp < ((unsigned char *) &arguments[argsLen])) { arg_len = (cp[0] << 0) | (cp[1] << 8) | (cp[2] << 16) | (cp[3] << 24); cp += 4; if (arg_len == 0) break; tempStr += " "; tempStr += QString::fromUtf8((const char *) cp, arg_len); cp += arg_len; } return tempStr; } else { QValueVector<QString> argList; argList.reserve(5); // reserve space for 5 elements to handle most common sizes // size_t totalArgsLen = 0; const char* curArg; while (totalArgsLen < argsLen) { curArg = arguments + totalArgsLen; // insert argument into the argument list argList.push_back(QString::fromUtf8(curArg)); totalArgsLen += strlen(curArg) + 1; } bool ok; int curPos; size_t substArg; int substArgValue; QString* substFormatStringRes; QString substFormatString; //////////////////////////// // replace template (%T) arguments in formatted string QString formatString = *formatStringRes; QRegExp rxt("%T(\\d{1,3})", true, false); // find first template substitution curPos = rxt.search(formatString, 0); while (curPos != -1) { substFormatStringRes = NULL; substArg = rxt.cap(1).toInt(&ok); if (ok && (substArg <= argList.size())) { substArgValue = argList[substArg-1].toInt(&ok); if (ok) substFormatStringRes = m_messageStrings.find(substArgValue); } // replace template argument with subst string if (substFormatStringRes != NULL) formatString.replace(curPos, rxt.matchedLength(), *substFormatStringRes); else curPos += rxt.matchedLength(); // if no replacement string, skip over // find next substitution curPos = rxt.search(formatString, curPos); } //////////////////////////// // now replace substitution arguments in formatted string // NOTE: not using QString::arg() because not all arguments are always used // and it will do screwy stuff in this situation QRegExp rx("%(\\d{1,3})", true, false); // find first template substitution curPos = rx.search(formatString, 0); while (curPos != -1) { substArg = rx.cap(1).toInt(&ok); // replace substitution argument with argument from list if (ok && (substArg <= argList.size())) formatString.replace(curPos, rx.matchedLength(), argList[substArg-1]); else curPos += rx.matchedLength(); // if no such argument, skip over // find next substitution curPos = rx.search(formatString, curPos); } return formatString; } }
bool startDocument() { levels.push_back( 0 ); return true; }
// public void kpMainWindow::pasteText (const QString &text, bool forceNewTextSelection, const QPoint &newTextSelectionTopLeft) { #if DEBUG_KP_MAIN_WINDOW && 1 kdDebug () << "kpMainWindow::pasteText(" << text << ",forceNewTextSelection=" << forceNewTextSelection << ",newTextSelectionTopLeft=" << newTextSelectionTopLeft << ")" << endl; #endif if (text.isEmpty ()) return; // sync: restoreOverrideCursor() in all exit paths QApplication::setOverrideCursor (Qt::waitCursor); if (toolHasBegunShape ()) tool ()->endShapeInternal (); QValueVector <QString> textLines (1, QString::null); for (int i = 0; i < (int) text.length (); i++) { if (text [i] == '\n') textLines.push_back (QString::null); else textLines [textLines.size () - 1].append (text [i]); } if (!forceNewTextSelection && m_document && m_document->selection () && m_document->selection ()->isText () && m_commandHistory && m_viewManager) { #if DEBUG_KP_MAIN_WINDOW && 1 kdDebug () << "\treusing existing Text Selection" << endl; #endif kpMacroCommand *macroCmd = new kpMacroCommand (i18n ("Text: Paste"), this); for (int i = 0; i < (int) textLines.size (); i++) { if (i > 0) { macroCmd->addCommand ( new kpToolTextEnterCommand ( QString::null/*uninteresting child of macroCmd*/, m_viewManager->textCursorRow (), m_viewManager->textCursorCol (), this)); } macroCmd->addCommand ( new kpToolTextInsertCommand ( QString::null/*uninteresting child of macroCmd*/, m_viewManager->textCursorRow (), m_viewManager->textCursorCol (), textLines [i], this)); } m_commandHistory->addCommand (macroCmd, false/*no exec*/); } else { #if DEBUG_KP_MAIN_WINDOW && 1 kdDebug () << "\tcreating Text Selection" << endl; #endif const kpTextStyle ts = textStyle (); const QFontMetrics fontMetrics = ts.fontMetrics (); int height = textLines.size () * fontMetrics.height (); if (textLines.size () >= 1) height += (textLines.size () - 1) * fontMetrics.leading (); int width = 0; for (QValueVector <QString>::const_iterator it = textLines.begin (); it != textLines.end (); it++) { const int w = fontMetrics.width (*it); if (w > width) width = w; } const int selWidth = QMAX (kpSelection::minimumWidthForTextStyle (ts), width + kpSelection::textBorderSize () * 2); const int selHeight = QMAX (kpSelection::minimumHeightForTextStyle (ts), height + kpSelection::textBorderSize () * 2); kpSelection sel (QRect (0, 0, selWidth, selHeight), textLines, ts); if (newTextSelectionTopLeft != KP_INVALID_POINT) { sel.moveTo (newTextSelectionTopLeft); paste (sel, true/*force topLeft*/); } else { paste (sel); } } QApplication::restoreOverrideCursor (); }
/*! Parses and loads multi definitions */ void cMultiCache::load( const QString &basePath ) { QFile indexFile( basePath + "multi.idx" ); if( !indexFile.open( IO_ReadOnly ) ) throw wpException( QString( "Error opening file %1 for reading." ).arg( basePath + "multi.idx" ) ); QDataStream indexStream( &indexFile ); indexStream.setByteOrder( QDataStream::LittleEndian ); QFile multiFile( basePath + "multi.mul" ); if ( !multiFile.open( IO_ReadOnly ) ) throw wpException( QString( "Error opening file %1 for reading." ).arg( basePath + "multi.mul" ) ); struct { Q_INT32 start; Q_INT32 length; Q_INT32 unknown; } indexData; ushort currentID = 0; while ( !indexStream.atEnd() ) { indexFile.at( currentID * 12 ); indexStream >> indexData.start; indexStream >> indexData.length; indexStream >> indexData.unknown; if ( indexData.start == -1 ) // empty record? { ++currentID; continue; } QValueVector<multiItem_st> items; items.reserve( indexData.length / 12 ); uint i = 0; multiFile.at( indexData.start ); QDataStream multiStream( &multiFile ); multiStream.setByteOrder( QDataStream::LittleEndian ); for (; i < indexData.length / 12; ++i ) { multiItem_st item; multiStream >> item.tile; multiStream >> item.x; multiStream >> item.y; multiStream >> item.z; Q_UINT8 empty; multiStream >> empty; // ???? Q_UINT32 isVisible = 0; multiStream >> isVisible; item.visible = isVisible > 0 ? true : false; if ( item.visible ) // we ignore invisible items (?) items.push_back(item); } MultiDefinition* multi = new MultiDefinition; multi->setItems( items ); multis.insert( currentID++, multi ); } }
int main(int argc, char** argv) { if (argc < 2) return 0; QValueVector<KeramikEmbedImage> images; cout<<"#include <qintdict.h>\n\n"; cout<<"#include \"keramikimage.h\"\n\n"; QMap<QString, int> assignID; int nextID = 0; for (int c = 1; c<argc; c++) { QImage input(argv[c]); QFileInfo fi(argv[c]); QString s = fi.baseName(); KeramikEmbedImage image; int pos; QString id = s; int readJustID = 0; if ((pos = s.findRev("-")) != -1) { int suffix = evalSuffix(s.mid(pos)); if (suffix !=-1 ) { id = s.mid(0,pos); readJustID = suffix; } } if (!assignID.contains(id)) { assignID[id] = nextID; nextID += 256; } s.replace("-","_"); if (s.contains("button")) KImageEffect::contrastHSV(input); int fullID = assignID[id] + readJustID;//Subwidget.. bool highlights = true; bool shadows = true; float gamma = 1.0; int brightAdj = 0; if (s.contains("toolbar") || s.contains("tab-top-active") || s.contains("menubar") ) { // highlights = false; gamma = 1/1.25f; //brightAdj = 10; shadows = false; } if (s.contains("scrollbar") && s.contains("groove")) { //highlights = false; //gamma = 1.5; shadows = false; } //brightAdj = -10; if (s.contains("scrollbar") && s.contains("slider")) { //highlights = false; gamma =1/0.7f; //shadows = false; } if (s.contains("menuitem")) { //highlights = false; gamma =1/0.6f; //shadows = false; } image.width = input.width(); image.height = input.height(); image.id = fullID; image.data = reinterpret_cast<unsigned char*>(strdup(s.latin1())); bool reallySolid = true; int pixCount = 0; int pixSolid = 0; cout<<"static const unsigned char "<<s.latin1()<<"[]={\n"; Q_UINT32* read = reinterpret_cast< Q_UINT32* >(input.bits() ); int size = input.width()*input.height(); for (int pos=0; pos<size; pos++) { QRgb basePix = (QRgb)*read; if (qAlpha(basePix) != 255) reallySolid = false; else pixSolid++; pixCount++; read++; } image.haveAlpha = !reallySolid; images.push_back(image); read = reinterpret_cast< Q_UINT32* >(input.bits() ); for (int pos=0; pos<size; pos++) { QRgb basePix = (QRgb)*read; //cout<<(r*destAlpha.alphas[pos])<<"\n"; //cout<<(int)destAlpha.alphas[pos]<<"\n"; QColor clr(basePix); int h,s,v; clr.hsv(&h,&s,&v); v=qGray(basePix); int targetColorAlpha = 0 , greyAdd = 0; //int srcAlpha = qAlpha(basePix); if (s>0 || v > 128) { //Non-shadow float fv = v/255.0; fv = pow(fv, gamma); v = int(255.5*fv); if (s<17 && highlights) //A bit of a highligt.. { float effectPortion = (16 - s)/15.0; greyAdd = (int)(v/4.0 * effectPortion*1.2); targetColorAlpha = v - greyAdd; } else { targetColorAlpha = v;//(int)(fv*255); greyAdd = 0; } } else { if (shadows) { targetColorAlpha = 0; greyAdd = v; } else { targetColorAlpha = v;//(int)(fv*255); greyAdd = 0; } } greyAdd+=brightAdj; if (reallySolid) cout<<targetColorAlpha<<","<<greyAdd<<","; else cout<<targetColorAlpha<<","<<greyAdd<<","<<qAlpha(basePix)<<","; //cout<<qRed(basePix)<<","<<qGreen(basePix)<<","<<qBlue(basePix)<<","<<qAlpha(basePix)<<","; if (pos%8 == 7) cout<<"\n"; read++; } cerr<<s.latin1()<<":"<<pixSolid<<"/"<<pixCount<<"("<<reallySolid<<")\n"; cout<<!reallySolid<<"\n"; cout<<"};\n\n"; } cout<<"static const KeramikEmbedImage image_db[] = {\n"; for (unsigned int c=0; c<images.size(); c++) { cout<<"\t{ "<<(images[c].haveAlpha?"true":"false")<<","<<images[c].width<<", "<<images[c].height<<", "<<images[c].id<<", "<<(char *)images[c].data<<"},"; cout<<"\n"; } cout<<"\t{0, 0, 0, 0, 0}\n"; cout<<"};\n\n"; cout<<"class KeramikImageDb\n"; cout<<"{\n"; cout<<"public:\n"; cout<<"\tstatic KeramikImageDb* getInstance()\n"; cout<<"\t{\n"; cout<<"\t\tif (!instance) instance = new KeramikImageDb;\n"; cout<<"\t\treturn instance;\n"; cout<<"\t}\n\n"; cout<<"\tstatic void release()\n"; cout<<"\t{\n"; cout<<"\t\tdelete instance;\n"; cout<<"\t\tinstance=0;\n"; cout<<"\t}\n\n"; cout<<"\tKeramikEmbedImage* getImage(int id)\n"; cout<<"\t{\n"; cout<<"\t\treturn images[id];\n"; cout<<"\t}\n\n"; cout<<"private:\n"; cout<<"\tKeramikImageDb():images(503)\n"; cout<<"\t{\n"; cout<<"\t\tfor (int c=0; image_db[c].width; c++)\n"; cout<<"\t\t\timages.insert(image_db[c].id, &image_db[c]);\n"; cout<<"\t}\n"; cout<<"\tstatic KeramikImageDb* instance;\n"; cout<<"\tQIntDict<KeramikEmbedImage> images;\n"; cout<<"};\n\n"; cout<<"KeramikImageDb* KeramikImageDb::instance = 0;\n\n"; cout<<"KeramikEmbedImage* KeramikGetDbImage(int id)\n"; cout<<"{\n"; cout<<"\treturn KeramikImageDb::getInstance()->getImage(id);\n"; cout<<"}\n\n"; cout<<"void KeramikDbCleanup()\n"; cout<<"{\n"; cout<<"\t\tKeramikImageDb::release();\n"; cout<<"}\n"; QFile file("keramikrc.h"); file.open(IO_WriteOnly); QTextStream ts( &file); ts<<"#ifndef KERAMIK_RC_H\n"; ts<<"#define KERAMIK_RC_H\n"; ts<<"enum KeramikWidget {\n"; for (QMap<QString, int>::iterator i = assignID.begin(); i != assignID.end(); ++i) { QString name = "keramik_"+i.key(); name.replace("-","_"); ts<<"\t"<<name<<" = "<<i.data()<<",\n"; } ts<<"\tkeramik_last\n"; ts<<"};\n"; ts<<"#endif\n"; return 0; }
void UpdateScreen::slotUpdate() { QString from = _fromVersion->text(); QString to = _toVersion->currentText(); if (from == to) { qApp->beep(); QString message = tr("Versions must be different"); QMessageBox::critical(this, tr("Error"), message); return; } // Connect to company database Driver* driver = Driver::getDriver(_company.dbType()); if (driver == NULL) { qApp->beep(); QString message = tr("Get driver failed: %1").arg(driver->lastError()); QMessageBox::critical(this, tr("Error"), message); return; } _connection = driver->allocConnection(); if (!_connection->dbaConnect(_company.database())) { qApp->beep(); QString message = tr("Open company failed: %1") .arg(_connection->lastError()); QMessageBox::critical(this, tr("Error"), message); return; } ServerConfig config; config.load(); QString dataDir = parseDir(config.dataDir); QString version = to; QValueVector<DataModel> models; while (true) { QString filePath = dataDir + "/models/" + version + ".xml"; DataModel model; if (!model.load(filePath)) { qApp->beep(); QString message = tr("Failed loading model: %1").arg(filePath); QMessageBox::critical(this, tr("Error"), message); return; } if (model.fromVersion.isEmpty()) { qApp->beep(); QString message = tr("Didn't find version: " + from); QMessageBox::critical(this, tr("Error"), message); return; } models.push_back(model); version = model.fromVersion; if (version == from) break; } if (models.size() == 0) { qApp->beep(); QString message = tr("No models found for update use"); QMessageBox::critical(this, tr("Error"), message); return; } QString dbType = _company.dbType(); for (int i = models.size() - 1; i >= 0; --i) { DataModel& model = models[i]; bool good = true; QValueVector<UpdateDefn> completed; for (unsigned int j = 0; j < model.updates.size(); ++j) { UpdateDefn& update = model.updates[j]; // Only run update if its for All or the right type if (!update.databases.contains("All")) if (!update.databases.contains(dbType)) continue; // Run update commands catching errors for (unsigned int k = 0; k < update.updateCmds.size(); ++k) { QString cmd = update.updateCmds[k]; Stmt stmt(_connection, cmd); if (!stmt.execute()) { qWarning(stmt.lastError()); good = false; break; } } completed.push_back(update); } // If good then try to run cleanup commands if (good) { for (unsigned int j = 0; j < completed.size(); ++j) { UpdateDefn& update = completed[j]; for (unsigned int k = 0; k < update.cleanupCmds.size(); ++k) { QString cmd = update.cleanupCmds[k]; Stmt stmt(_connection, cmd); if (!stmt.execute()) { qWarning(stmt.lastError()); good = false; break; } } } } // If still good then update version in database if (good) { QString cmd = "update db_config set config_value='" + model.version + "' where config_key='version'"; Stmt stmt(_connection, cmd); if (!stmt.execute()) { qWarning(stmt.lastError()); good = false; } _connection->commit(); } // If failed then run restore commands and inform user if (!good) { for (unsigned int j = 0; j < completed.size(); ++j) { UpdateDefn& update = completed[j]; for (unsigned int k = 0; k < update.restoreCmds.size(); ++k) { QString cmd = update.restoreCmds[k]; Stmt stmt(_connection, cmd); if (!stmt.execute()) { qWarning(stmt.lastError()); } } } qApp->beep(); QString message = tr("Update failed on version: " + model.version); QMessageBox::critical(this, tr("Error"), message); close(); return; } // Set new version in CompanyDefn CompanyDefn company = _company; company.setVersion(model.version); company.save(company.filePath(), true); _company = company; } QMessageBox::information(this, tr("Finished"), tr("Update successful")); close(); }