From 958934ee4bb29d31924b938419c51f0fe18a4c4c Mon Sep 17 00:00:00 2001 From: Tofu Buzzard Date: Sat, 27 Nov 2010 13:24:19 +0000 Subject: Some BOOL->bool that was bugging me. --- indra/llmath/llmath.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'indra') diff --git a/indra/llmath/llmath.h b/indra/llmath/llmath.h index 798f1154d0..b86768456d 100644 --- a/indra/llmath/llmath.h +++ b/indra/llmath/llmath.h @@ -106,7 +106,7 @@ const F32 F_ALMOST_ONE = 1.0f - F_ALMOST_ZERO; const F32 FP_MAG_THRESHOLD = 0.0000001f; // TODO: Replace with logic like is_approx_equal -inline BOOL is_approx_zero( F32 f ) { return (-F_APPROXIMATELY_ZERO < f) && (f < F_APPROXIMATELY_ZERO); } +inline bool is_approx_zero( F32 f ) { return (-F_APPROXIMATELY_ZERO < f) && (f < F_APPROXIMATELY_ZERO); } // These functions work by interpreting sign+exp+mantissa as an unsigned // integer. @@ -132,13 +132,13 @@ inline BOOL is_approx_zero( F32 f ) { return (-F_APPROXIMATELY_ZERO < f) && (f < // WARNING: Infinity is comparable with F32_MAX and negative // infinity is comparable with F32_MIN -inline BOOL is_approx_equal(F32 x, F32 y) +inline bool is_approx_equal(F32 x, F32 y) { const S32 COMPARE_MANTISSA_UP_TO_BIT = 0x02; return (std::abs((S32) ((U32&)x - (U32&)y) ) < COMPARE_MANTISSA_UP_TO_BIT); } -inline BOOL is_approx_equal(F64 x, F64 y) +inline bool is_approx_equal(F64 x, F64 y) { const S64 COMPARE_MANTISSA_UP_TO_BIT = 0x02; return (std::abs((S32) ((U64&)x - (U64&)y) ) < COMPARE_MANTISSA_UP_TO_BIT); -- cgit v1.2.3 From 1cc154166fe504e17735669b7b9e366f93e34d64 Mon Sep 17 00:00:00 2001 From: Tank_Master Date: Tue, 20 Dec 2011 22:17:20 -0800 Subject: STORM-1738 - Add autocorrect functionality Ported with owner permission from Firestorm, inital work done by LordGregGreg Back --- indra/llui/lllineeditor.cpp | 57 + indra/llui/lllineeditor.h | 1 + indra/newview/CMakeLists.txt | 4 + indra/newview/app_settings/settings.xml | 33 + .../newview/app_settings/settings_autocorrect.xml | 8369 ++++++++++++++++++++ indra/newview/llautocorrect.cpp | 402 + indra/newview/llautocorrect.h | 60 + indra/newview/llautocorrectfloater.cpp | 384 + indra/newview/llautocorrectfloater.h | 67 + indra/newview/llfloaterpreference.cpp | 4 +- indra/newview/llviewerfloaterreg.cpp | 3 +- .../skins/default/xui/en/floater_autocorrect.xml | 83 + .../newview/skins/default/xui/en/notifications.xml | 7 + .../default/xui/en/panel_preferences_chat.xml | 15 +- 14 files changed, 9485 insertions(+), 4 deletions(-) create mode 100644 indra/newview/app_settings/settings_autocorrect.xml create mode 100644 indra/newview/llautocorrect.cpp create mode 100644 indra/newview/llautocorrect.h create mode 100644 indra/newview/llautocorrectfloater.cpp create mode 100644 indra/newview/llautocorrectfloater.h create mode 100644 indra/newview/skins/default/xui/en/floater_autocorrect.xml (limited to 'indra') diff --git a/indra/llui/lllineeditor.cpp b/indra/llui/lllineeditor.cpp index 06dfc90d83..cee84cc53f 100644 --- a/indra/llui/lllineeditor.cpp +++ b/indra/llui/lllineeditor.cpp @@ -51,6 +51,8 @@ #include "lluictrlfactory.h" #include "llclipboard.h" #include "llmenugl.h" +#include "../newview/llautocorrect.h" +#include "../newview/llviewercontrol.h" // // Imported globals @@ -194,7 +196,60 @@ LLLineEditor::~LLLineEditor() // calls onCommit() while LLLineEditor still valid gFocusMgr.releaseFocusIfNeeded( this ); } +void LLLineEditor::autoCorrectText() +{ + static LLCachedControl doAnything(gSavedSettings, "EnableAutoCorrect"); + if( (!mReadOnly) && (doAnything))// && (isDirty())) + { + S32 wordStart = 0; + S32 wordEnd = mCursorPos-1; + //llinfos <<"Checking Word, Cursor is at "< 0) && (' '!=text[wordEnd-1])) + { + wordEnd--; + } + + wordStart=wordEnd; + + while ((wordEnd < (S32)text.length()) && (' '!=text[wordEnd] ) ) + { + wordEnd++; + } + + std::string strLastWord = std::string(text.begin(), text.end()); + std::string lastTypedWord = strLastWord.substr( wordStart, wordEnd-wordStart); + std::string correctedWord( AutoCorrect::getInstance()->replaceWord(lastTypedWord)); + if(correctedWord!=lastTypedWord) + { + LLWString strNew = utf8str_to_wstring( correctedWord ); + LLWString strOld = utf8str_to_wstring( lastTypedWord ); + int nDiff = strNew.size() - strOld.size(); + + //int wordStart = regText.find(lastTypedWord); + text.replace(wordStart,lastTypedWord.length(),strNew); + mText = wstring_to_utf8str(text); + mCursorPos+=nDiff; + } + } + } +} void LLLineEditor::onFocusReceived() { @@ -866,6 +921,8 @@ void LLLineEditor::addChar(const llwchar uni_char) LLUI::reportBadKeystroke(); } + autoCorrectText(); + getWindow()->hideCursorUntilMouseMove(); } diff --git a/indra/llui/lllineeditor.h b/indra/llui/lllineeditor.h index 2518dbe3c7..8dcc801b62 100644 --- a/indra/llui/lllineeditor.h +++ b/indra/llui/lllineeditor.h @@ -169,6 +169,7 @@ public: virtual BOOL setTextArg( const std::string& key, const LLStringExplicit& text ); virtual BOOL setLabelArg( const std::string& key, const LLStringExplicit& text ); + void autoCorrectText(); void setLabel(const LLStringExplicit &new_label) { mLabel = new_label; } const std::string& getLabel() { return mLabel.getString(); } diff --git a/indra/newview/CMakeLists.txt b/indra/newview/CMakeLists.txt index 6b2fe1e45a..b43426ad9f 100644 --- a/indra/newview/CMakeLists.txt +++ b/indra/newview/CMakeLists.txt @@ -97,6 +97,8 @@ set(viewer_SOURCE_FILES llassetuploadresponders.cpp llattachmentsmgr.cpp llaudiosourcevo.cpp + llautocorrect.cpp + llautocorrectfloater.cpp llavataractions.cpp llavatariconctrl.cpp llavatarlist.cpp @@ -651,6 +653,8 @@ set(viewer_HEADER_FILES llassetuploadresponders.h llattachmentsmgr.h llaudiosourcevo.h + llautocorrect.h + llautocorrectfloater.h llavataractions.h llavatariconctrl.h llavatarlist.h diff --git a/indra/newview/app_settings/settings.xml b/indra/newview/app_settings/settings.xml index aa8ad53a3d..c132cc6ea2 100644 --- a/indra/newview/app_settings/settings.xml +++ b/indra/newview/app_settings/settings.xml @@ -346,6 +346,17 @@ Value 0 + AutoCorrectCount + + Comment + How many words have been auto replaced. + Persist + 1 + Type + S32 + Value + 0 + AutoAcceptNewInventory Comment @@ -1606,6 +1617,17 @@ Value 0 + CmdLineAutocorrect + + Comment + Command for adding new entries to autocorrect + Persist + 1 + Type + String + Value + /addac + CmdLineDisableVoice Comment @@ -2775,6 +2797,17 @@ Value 1 + EnableAutoCorrect + + Comment + Enables or disables the autocorrect function + Persist + 1 + Type + Boolean + Value + 0 + EnableGroupChatPopups Comment diff --git a/indra/newview/app_settings/settings_autocorrect.xml b/indra/newview/app_settings/settings_autocorrect.xml new file mode 100644 index 0000000000..4669ba5822 --- /dev/null +++ b/indra/newview/app_settings/settings_autocorrect.xml @@ -0,0 +1,8369 @@ + + + Custom + + announce + 0 + author + You + data + + enabled + 1 + priority + 10 + wordStyle + 1 + + Abbreviations + + announce + 0 + author + Wulf / TankMaster + data + + afaic + As far as I am concerned + afaik + As far as I know + afk + (Away from Keyboard) + atm + at the moment + bbiab + (Be back in a bit) + bbl + (Be back later) + brb + (Be Right Back) + btw + By the way + fyi + For your information + fwiw + For what its worth + gtg + (Got to go) + idk + I don't know + iirc + If I recall correctly + imho + in my humble opinion + imo + in my opinion + irl + in real life + lol + (Laughing out Loud) + nm + Not much + np + No problem + nsfw + not safe for work + nvm + Nevermind + rofl + (Rolling on Floor Laughing) + tc + Take care + thx + Thanks + ttfn + Ta Ta for now + ttyl + Talk to you later + ty + Thank you + tyvm + Thank you very much + wb + Welcome back + yw + You're Welcome + yvw + You're very welcome + + enabled + 1 + priority + 4 + wordStyle + 1 + + Spelling Corrections + + announce + 0 + author + LordGregGreg / Wikipedia + data + + Amercia + America + Bernouilli + Bernoulli + Blitzkreig + Blitzkrieg + Bonnano + Bonanno + Brasillian + Brazilian + Britian + Britain + Brittish + British + Buddah + Buddha + Buddist + Buddhist + Cambrige + Cambridge + Capetown + Cape Town + Carmalite + Carmelite + Carnagie + Carnegie + Carnagie-Mellon + Carnegie-Mellon + Carnigie + Carnegie + Carnigie-Mellon + Carnegie-Mellon + Carribbean + Caribbean + Carribean + Caribbean + Carthagian + Carthaginian + Cataline + Catiline + Ceasar + Caesar + Celcius + Celsius + Champange + Champagne + Cincinatti + Cincinnati + Cincinnatti + Cincinnati + Conneticut + Connecticut + Dardenelles + Dardanelles + Dravadian + Dravidian + Enlish + English + Europian + European + Europians + Europeans + Eurpean + European + Eurpoean + European + Farenheit + Fahrenheit + Febuary + February + Feburary + February + Flemmish + Flemish + Formalhaut + Fomalhaut + Foundland + Newfoundland + Fransiscan + Franciscan + Fransiscans + Franciscans + Galations + Galatians + Gameboy + Game Boy + Ghandi + Gandhi + Godounov + Godunov + Gothenberg + Gothenburg + Gottleib + Gottlieb + Guaduloupe + Guadalupe + Guadulupe + Guadalupe + Guatamala + Guatemala + Guatamalan + Guatemalan + Guilia + Giulia + Guilio + Giulio + Guiness + Guinness + Guiseppe + Giuseppe + Habsbourg + Habsburg + Hallowean + Halloween + Heidelburg + Heidelberg + Ihaca + Ithaca + Israelies + Israelis + Janurary + January + Januray + January + Japanes + Japanese + Johanine + Johannine + Jospeh + Joseph + Juadaism + Judaism + Juadism + Judaism + Lybia + Libya + Malcom + Malcolm + Massachussets + Massachusetts + Massachussetts + Massachusetts + Mediteranean + Mediterranean + Michagan + Michigan + Misouri + Missouri + Missisipi + Mississippi + Missisippi + Mississippi + Monserrat + Montserrat + Montnana + Montana + Morisette + Morissette + Morrisette + Morissette + Mythraic + Mithraic + Naploeon + Napoleon + Napolean + Napoleon + Napoleonian + Napoleonic + Nazereth + Nazareth + Newyorker + New Yorker + Novermber + November + Nullabour + Nullarbor + Nuremburg + Nuremberg + Palistian + Palestinian + Palistinian + Palestinian + Palistinians + Palestinians + Papanicalou + Papanicolaou + Peloponnes + Peloponnesus + Pennyslvania + Pennsylvania + Pharoah + Pharaoh + Philipines + Philippines + Phillipine + Philippine + Phillipines + Philippines + Phillippines + Philippines + Phonecian + Phoenecian + Portugese + Portuguese + Postdam + Potsdam + Premonasterians + Premonstratensians + Pucini + Puccini + Puertorrican + Puerto Rican + Puertorricans + Puerto Ricans + Queenland + Queensland + Rockerfeller + Rockefeller + Russion + Russian + Sanhedrim + Sanhedrin + Saterday + Saturday + Saterdays + Saturdays + Sionist + Zionist + Sionists + Zionists + Sixtin + Sistine + Skagerak + Skagerrak + Tolkein + Tolkien + Tuscon + Tucson + Ukranian + Ukrainian + UnitesStates + UnitedStates + Yementite + Yemenite + abandonned + abandoned + aberation + aberration + abilties + abilities + abilty + ability + abondon + abandon + abondoned + abandoned + abondoning + abandoning + abondons + abandons + aborigene + aborigine + abortificant + abortifacient + abreviate + abbreviate + abreviated + abbreviated + abreviation + abbreviation + abritrary + arbitrary + absail + abseil + absailing + abseiling + absense + absence + absolutly + absolutely + absorbsion + absorption + absorbtion + absorption + abundacies + abundances + abundancies + abundances + abundunt + abundant + abutts + abuts + acadamy + academy + acadmic + academic + accademic + academic + accademy + academy + acccused + accused + accelleration + acceleration + accension + ascension + acceptence + acceptance + acceptible + acceptable + accessable + accessible + accidentaly + accidentally + accidently + accidentally + acclimitization + acclimatization + accomadate + accommodate + accomadated + accommodated + accomadates + accommodates + accomadating + accommodating + accomadation + accommodation + accomadations + accommodations + accomdate + accommodate + accomodate + accommodate + accomodated + accommodated + accomodates + accommodates + accomodating + accommodating + accomodation + accommodation + accomodations + accommodations + accompanyed + accompanied + accordeon + accordion + accordian + accordion + accoring + according + accoustic + acoustic + accquainted + acquainted + accrediation + accreditation + accredidation + accreditation + accross + across + accussed + accused + acedemic + academic + acheive + achieve + acheived + achieved + acheivement + achievement + acheivements + achievements + acheives + achieves + acheiving + achieving + acheivment + achievement + acheivments + achievements + achievment + achievement + achievments + achievements + achivement + achievement + achivements + achievements + acknowldeged + acknowledged + acknowledgeing + acknowledging + ackward + awkward + acommodate + accommodate + acomplish + accomplish + acomplished + accomplished + acomplishment + accomplishment + acomplishments + accomplishments + acording + according + acordingly + accordingly + acquaintence + acquaintance + acquaintences + acquaintances + acquiantence + acquaintance + acquiantences + acquaintances + acquited + acquitted + activites + activities + activly + actively + actualy + actually + acuracy + accuracy + acused + accused + acustom + accustom + acustommed + accustomed + adavanced + advanced + adbandon + abandon + additinally + additionally + additionaly + additionally + additonal + additional + additonally + additionally + addmission + admission + addopt + adopt + addopted + adopted + addoptive + adoptive + addres + address + addresable + addressable + addresed + addressed + addresing + addressing + addressess + addresses + addtion + addition + addtional + additional + adecuate + adequate + adequit + adequate + adhearing + adhering + adherance + adherence + admendment + amendment + admininistrative + administrative + adminstered + administered + adminstrate + administrate + adminstration + administration + adminstrative + administrative + adminstrator + administrator + admissability + admissibility + admissable + admissible + admited + admitted + admitedly + admittedly + adn + and + adolecent + adolescent + adquire + acquire + adquired + acquired + adquires + acquires + adquiring + acquiring + adres + address + adresable + addressable + adresing + addressing + adress + address + adressable + addressable + adressed + addressed + adressing + addressing + adventrous + adventurous + advertisment + advertisement + advertisments + advertisements + advesary + adversary + adviced + advised + aeriel + aerial + aeriels + aerials + afair + affair + afficianados + aficionados + afficionado + aficionado + afficionados + aficionados + affilate + affiliate + affilliate + affiliate + affort + afford + aforememtioned + aforementioned + againnst + against + agains + against + agaisnt + against + aganist + against + aggaravates + aggravates + aggreed + agreed + aggreement + agreement + aggregious + egregious + aggresive + aggressive + agian + again + agianst + against + agin + again + agina + again + aginst + against + agravate + aggravate + agre + agree + agred + agreed + agreeement + agreement + agreemnt + agreement + agregate + aggregate + agregates + aggregates + agreing + agreeing + agression + aggression + agressive + aggressive + agressively + aggressively + agressor + aggressor + agricuture + agriculture + agrieved + aggrieved + ahev + have + ahppen + happen + ahve + have + aicraft + aircraft + aiport + airport + airbourne + airborne + aircaft + aircraft + aircrafts + aircraft + airporta + airports + airrcraft + aircraft + aisian + asian + albiet + albeit + alchohol + alcohol + alchoholic + alcoholic + alchol + alcohol + alcholic + alcoholic + alcohal + alcohol + alcoholical + alcoholic + aledge + allege + aledged + alleged + aledges + alleges + alege + allege + aleged + alleged + alegience + allegiance + algebraical + algebraic + algorhitms + algorithms + algoritm + algorithm + algoritms + algorithms + alientating + alienating + alledge + allege + alledged + alleged + alledgedly + allegedly + alledges + alleges + allegedely + allegedly + allegedy + allegedly + allegely + allegedly + allegence + allegiance + allegience + allegiance + allign + align + alligned + aligned + alliviate + alleviate + allopone + allophone + allopones + allophones + allready + already + allthough + although + alltime + all-time + alltogether + altogether + almsot + almost + alochol + alcohol + alomst + almost + alot + a lot + alotted + allotted + alowed + allowed + alowing + allowing + alreayd + already + alse + else + alsot + also + alternitives + alternatives + altho + although + althought + although + altough + although + alusion + allusion + alwasy + always + alwyas + always + amalgomated + amalgamated + amatuer + amateur + amature + armature + amendmant + amendment + amerliorate + ameliorate + amke + make + amking + making + ammend + amend + ammended + amended + ammendment + amendment + ammendments + amendments + ammount + amount + ammused + amused + amoung + among + amoungst + amongst + amung + among + amunition + ammunition + analagous + analogous + analitic + analytic + analogeous + analogous + anarchim + anarchism + anarchistm + anarchism + anbd + and + ancestory + ancestry + ancilliary + ancillary + androgenous + androgynous + androgeny + androgyny + anihilation + annihilation + aniversary + anniversary + annoint + anoint + annointed + anointed + annointing + anointing + annoints + anoints + annouced + announced + annualy + annually + annuled + annulled + anohter + another + anomolies + anomalies + anomolous + anomalous + anomoly + anomaly + anonimity + anonymity + anounced + announced + anouncement + announcement + ansalisation + nasalisation + ansalization + nasalization + ansestors + ancestors + antartic + antarctic + anthromorphization + anthropomorphization + anthropolgist + anthropologist + anthropolgy + anthropology + anual + annual + anulled + annulled + anwsered + answered + anyhwere + anywhere + anyother + any other + anytying + anything + aparent + apparent + aparment + apartment + apenines + apennines + aplication + application + aplied + applied + apolegetics + apologetics + apon + apron + apparant + apparent + apparantly + apparently + appart + apart + appartment + apartment + appartments + apartments + appealling + appealing + appeareance + appearance + appearence + appearance + appearences + appearances + apperance + appearance + apperances + appearances + appereance + appearance + appereances + appearances + applicaiton + application + applicaitons + applications + appologies + apologies + appology + apology + apprearance + appearance + apprieciate + appreciate + approachs + approaches + appropiate + appropriate + appropraite + appropriate + appropropiate + appropriate + approproximate + approximate + approxamately + approximately + approxiately + approximately + approximitely + approximately + aprehensive + apprehensive + apropriate + appropriate + aproximate + approximate + aproximately + approximately + aquaduct + aqueduct + aquaintance + acquaintance + aquainted + acquainted + aquiantance + acquaintance + aquire + acquire + aquired + acquired + aquiring + acquiring + aquisition + acquisition + aquitted + acquitted + aranged + arranged + arangement + arrangement + arbitarily + arbitrarily + arbitary + arbitrary + archaelogists + archaeologists + archaelogy + archaeology + archaoelogy + archaeology + archaology + archaeology + archeaologist + archaeologist + archeaologists + archaeologists + archetect + architect + archetects + architects + archetectural + architectural + archetecturally + architecturally + archetecture + architecture + archiac + archaic + archictect + architect + archimedian + archimedean + architecht + architect + architechturally + architecturally + architechture + architecture + architechtures + architectures + architectual + architectural + archtype + archetype + archtypes + archetypes + aready + already + areodynamics + aerodynamics + argubly + arguably + arguement + argument + arguements + arguments + arised + arose + arival + arrival + armamant + armament + armistace + armistice + arogant + arrogant + arogent + arrogant + aroud + around + arrangment + arrangement + arrangments + arrangements + arround + around + artical + article + artice + article + articel + article + artifical + artificial + artifically + artificially + artillary + artillery + arund + around + asetic + ascetic + asfar + as far + asign + assign + aslo + also + asociated + associated + asorbed + absorbed + asphyxation + asphyxiation + assasin + assassin + assasinate + assassinate + assasinated + assassinated + assasinates + assassinates + assasination + assassination + assasinations + assassinations + assasined + assassinated + assasins + assassins + assassintation + assassination + assemple + assemble + assertation + assertion + asside + aside + assisnate + assassinate + assit + assist + assitant + assistant + assocation + association + assoicate + associate + assoicated + associated + assoicates + associates + assosication + assassination + asssassans + assassins + assualt + assault + assualted + assaulted + assymetric + asymmetric + assymetrical + asymmetrical + asteriod + asteroid + asthetic + aesthetic + asthetical + aesthetical + asthetically + aesthetically + asume + assume + aswell + as well + atain + attain + atempting + attempting + atheistical + atheistic + athenean + athenian + atheneans + athenians + athiesm + atheism + athiest + atheist + atorney + attorney + atribute + attribute + atributed + attributed + atributes + attributes + attaindre + attainder + attemp + attempt + attemped + attempted + attemt + attempt + attemted + attempted + attemting + attempting + attemts + attempts + attendence + attendance + attendent + attendant + attendents + attendants + attened + attended + attension + attention + attitide + attitude + attributred + attributed + attrocities + atrocities + audeince + audience + auromated + automated + austrailia + Australia + austrailian + Australian + auther + author + authobiographic + autobiographic + authobiography + autobiography + authorative + authoritative + authorites + authorities + authorithy + authority + authoritiers + authorities + authoritive + authoritative + authrorities + authorities + autochtonous + autochthonous + autoctonous + autochthonous + automaticly + automatically + automibile + automobile + automonomous + autonomous + autor + author + autority + authority + auxilary + auxiliary + auxillaries + auxiliaries + auxillary + auxiliary + auxilliaries + auxiliaries + auxilliary + auxiliary + availabe + available + availablity + availability + availaible + available + availble + available + availiable + available + availible + available + avalable + available + avalance + avalanche + avaliable + available + avation + aviation + avengence + a vengeance + averageed + averaged + avilable + available + awared + awarded + awya + away + baceause + because + backgorund + background + backrounds + backgrounds + bakc + back + banannas + bananas + bandwith + bandwidth + bankrupcy + bankruptcy + banruptcy + bankruptcy + baout + about + basicaly + basically + basicly + basically + bcak + back + beachead + beachhead + beacuse + because + beastiality + bestiality + beatiful + beautiful + beaurocracy + bureaucracy + beaurocratic + bureaucratic + beautyfull + beautiful + becamae + became + becames + becomes + becasue + because + beccause + because + becomeing + becoming + becomming + becoming + becouse + because + becuase + because + bedore + before + befoer + before + beggin + begin + begginer + beginner + begginers + beginners + beggining + beginning + begginings + beginnings + beggins + begins + begining + beginning + beginnig + beginning + behavour + behavior + beleagured + beleaguered + beleif + belief + beleive + believe + beleived + believed + beleives + believes + beleiving + believing + beligum + belgium + belive + believe + belived + believed + belives + believes + belligerant + belligerent + bellweather + bellwether + bemusemnt + bemusement + beneficary + beneficiary + beng + being + benificial + beneficial + benifit + benefit + benifits + benefits + bergamont + bergamot + beseige + besiege + beseiged + besieged + beseiging + besieging + betwen + between + beween + between + bewteen + between + bilateraly + bilaterally + billingualism + bilingualism + binominal + binomial + bizzare + bizarre + blaim + blame + blaimed + blamed + blessure + blessing + bodydbuilder + bodybuilder + bombardement + bombardment + bombarment + bombardment + bondary + boundary + borke + broke + boundry + boundary + bouyancy + buoyancy + bouyant + buoyant + boyant + buoyant + breakthough + breakthrough + breakthroughts + breakthroughs + breif + brief + breifly + briefly + brethen + brethren + bretheren + brethren + briliant + brilliant + brillant + brilliant + brimestone + brimstone + broacasted + broadcast + broadacasting + broadcasting + broady + broadly + buisness + business + buisnessman + businessman + buoancy + buoyancy + burried + buried + busineses + businesses + busness + business + bussiness + business + caculater + calculator + cacuses + caucuses + cahracters + characters + calaber + caliber + calculater + calculator + calculs + calculus + calenders + calendars + caligraphy + calligraphy + caluclate + calculate + caluclated + calculated + caluculate + calculate + caluculated + calculated + calulate + calculate + calulated + calculated + calulater + calculator + camoflage + camouflage + campain + campaign + campains + campaigns + candadate + candidate + candiate + candidate + candidiate + candidate + cannister + canister + cannisters + canisters + cannnot + cannot + cannonical + canonical + cannotation + connotation + cannotations + connotations + cant + can't + caost + coast + caperbility + capability + capible + capable + captial + capital + captued + captured + capturd + captured + carachter + character + caracterized + characterized + carcas + carcass + carefull + careful + careing + caring + carismatic + charismatic + carnege + carnage + carnige + carnage + carniverous + carnivorous + carreer + career + carrers + careers + cartdridge + cartridge + carthographer + cartographer + cartilege + cartilage + cartilidge + cartilage + cartrige + cartridge + casette + cassette + casion + caisson + cassawory + cassowary + cassowarry + cassowary + casulaties + casualties + casulaty + casualty + catagories + categories + catagorized + categorized + catagory + category + catapillar + caterpillar + catapillars + caterpillars + catapiller + caterpillar + catapillers + caterpillars + catepillar + caterpillar + catepillars + caterpillars + catergorize + categorize + catergorized + categorized + caterpilar + caterpillar + caterpilars + caterpillars + caterpiller + caterpillar + caterpillers + caterpillars + cathlic + catholic + catholocism + catholicism + catterpilar + caterpillar + catterpilars + caterpillars + catterpillar + caterpillar + catterpillars + caterpillars + cattleship + battleship + causalities + casualties + cellpading + cellpadding + cementary + cemetery + cemetarey + cemetery + cemetaries + cemeteries + cemetary + cemetery + cencus + census + censur + censor + cententenial + centennial + centruies + centuries + centruy + century + ceratin + certain + cerimonial + ceremonial + cerimonies + ceremonies + cerimonious + ceremonious + cerimony + ceremony + ceromony + ceremony + certainity + certainty + certian + certain + chalenging + challenging + challange + challenge + challanged + challenged + challege + challenge + changable + changeable + charachter + character + charachters + characters + charactersistic + characteristic + charactor + character + charactors + characters + charasmatic + charismatic + charaterized + characterized + chariman + chairman + charistics + characteristics + cheif + chief + cheifs + chiefs + chemcial + chemical + chemcially + chemically + chemestry + chemistry + chemicaly + chemically + childbird + childbirth + childen + children + choosen + chosen + chracter + character + chuch + church + churchs + churches + circulaton + circulation + circumsicion + circumcision + circut + circuit + ciricuit + circuit + ciriculum + curriculum + civillian + civilian + claer + clear + claerer + clearer + claerly + clearly + claimes + claims + clas + class + clasic + classic + clasical + classical + clasically + classically + cleareance + clearance + clera + clear + clincial + clinical + clinicaly + clinically + cmo + com + cmoputer + computer + co-incided + coincided + coctail + cocktail + coform + conform + cognizent + cognizant + coincedentally + coincidentally + colaborations + collaborations + colateral + collateral + colelctive + collective + collaberative + collaborative + collecton + collection + collegue + colleague + collegues + colleagues + collonade + colonnade + collonies + colonies + collony + colony + collosal + colossal + colonizators + colonizers + comander + commander + comando + commando + comandos + commandos + comany + company + comapany + company + comback + comeback + combanations + combinations + combinatins + combinations + combusion + combustion + comdemnation + condemnation + comemmorates + commemorates + comemoretion + commemoration + comision + commission + comisioned + commissioned + comisioner + commissioner + comisioning + commissioning + comisions + commissions + comission + commission + comissioned + commissioned + comissioner + commissioner + comissioning + commissioning + comissions + commissions + comited + committed + comiting + committing + comitted + committed + comittee + committee + comitting + committing + commandoes + commandos + commedic + comedic + commemerative + commemorative + commemmorate + commemorate + commemmorating + commemorating + commerical + commercial + commerically + commercially + commericial + commercial + commericially + commercially + commerorative + commemorative + comming + coming + comminication + communication + commision + commission + commisioned + commissioned + commisioner + commissioner + commisioning + commissioning + commisions + commissions + commited + committed + commitee + committee + commiting + committing + committe + committee + committment + commitment + committments + commitments + commmemorated + commemorated + commongly + commonly + commonweath + commonwealth + commuications + communications + commuinications + communications + communciation + communication + communiation + communication + communites + communities + compability + compatibility + comparision + comparison + comparisions + comparisons + comparitive + comparative + comparitively + comparatively + compatabilities + compatibilities + compatability + compatibility + compatable + compatible + compatablities + compatibilities + compatablity + compatibility + compatiable + compatible + compatiblities + compatibilities + compatiblity + compatibility + compeitions + competitions + compensantion + compensation + competance + competence + competant + competent + competative + competitive + competion + competition + competitiion + competition + competive + competitive + competiveness + competitiveness + comphrehensive + comprehensive + compitent + competent + completedthe + completed the + completelyl + completely + completetion + completion + complier + compiler + componant + component + comprable + comparable + comprimise + compromise + compulsary + compulsory + compulsery + compulsory + computarized + computerized + concensus + consensus + concider + consider + concidered + considered + concidering + considering + conciders + considers + concieted + conceited + concieved + conceived + concious + conscious + conciously + consciously + conciousness + consciousness + condamned + condemned + condemmed + condemned + condidtion + condition + condidtions + conditions + conditionsof + conditions of + conected + connected + conection + connection + conesencus + consensus + confidental + confidential + confidentally + confidentially + confids + confides + configureable + configurable + confortable + comfortable + congradulations + congratulations + congresional + congressional + conived + connived + conjecutre + conjecture + conjuction + conjunction + conotations + connotations + conquerd + conquered + conquerer + conqueror + conquerers + conquerors + conqured + conquered + conscent + consent + consciouness + consciousness + consdider + consider + consdidered + considered + consdiered + considered + consectutive + consecutive + consenquently + consequently + consentrate + concentrate + consentrated + concentrated + consentrates + concentrates + consept + concept + consequentually + consequently + consequeseces + consequences + consern + concern + conserned + concerned + conserning + concerning + conservitive + conservative + consiciousness + consciousness + consicousness + consciousness + considerd + considered + consideres + considered + consious + conscious + consistant + consistent + consistantly + consistently + consituencies + constituencies + consituency + constituency + consituted + constituted + consitution + constitution + consitutional + constitutional + consolodate + consolidate + consolodated + consolidated + consonent + consonant + consonents + consonants + consorcium + consortium + conspiracys + conspiracies + conspiriator + conspirator + constaints + constraints + constanly + constantly + constarnation + consternation + constatn + constant + constinually + continually + constituant + constituent + constituants + constituents + constituion + constitution + constituional + constitutional + consttruction + construction + constuction + construction + consulant + consultant + consumate + consummate + consumated + consummated + contaiminate + contaminate + containes + contains + contamporaries + contemporaries + contamporary + contemporary + contempoary + contemporary + contemporaneus + contemporaneous + contempory + contemporary + contendor + contender + contibute + contribute + contibuted + contributed + contibutes + contributes + contigent + contingent + contined + continued + continous + continuous + continously + continuously + continueing + continuing + contravercial + controversial + contraversy + controversy + contributer + contributor + contributers + contributors + contritutions + contributions + controled + controlled + controling + controlling + controll + control + controlls + controls + controvercial + controversial + controvercy + controversy + controveries + controversies + controversal + controversial + controversey + controversy + controvertial + controversial + controvery + controversy + contruction + construction + conveinent + convenient + convenant + covenant + convential + conventional + convertables + convertibles + convertion + conversion + conveyer + conveyor + conviced + convinced + convienient + convenient + coordiantion + coordination + coorperations + corporations + copmetitors + competitors + coputer + computer + copywrite + copyright + coridal + cordial + cornmitted + committed + corosion + corrosion + corparate + corporate + corperations + corporations + correcters + correctors + correponding + corresponding + correposding + corresponding + correspondant + correspondent + correspondants + correspondents + corridoors + corridors + corrispond + correspond + corrispondant + correspondent + corrispondants + correspondents + corrisponded + corresponded + corrisponding + corresponding + corrisponds + corresponds + costitution + constitution + coucil + council + counries + countries + countains + contains + countires + countries + coururier + courier + coverted + converted + cpoy + copy + creaeted + created + creedence + credence + critereon + criterion + criterias + criteria + criticists + critics + critising + criticising + critisising + criticising + critisism + criticism + critisisms + criticisms + critisize + criticise + critisized + criticised + critisizes + criticises + critisizing + criticising + critized + criticized + critizing + criticizing + crockodiles + crocodiles + crowm + crown + crtical + critical + crticised + criticised + crucifiction + crucifixion + crusies + cruises + crystalisation + crystallisation + culiminating + culminating + cumulatative + cumulative + curch + church + curcuit + circuit + currenly + currently + curriculem + curriculum + cxan + cyan + cyclinder + cylinder + dacquiri + daiquiri + dael + deal + dalmation + dalmatian + damenor + demeanor + dammage + damage + daugher + daughter + debateable + debatable + decendant + descendant + decendants + descendants + decendent + descendant + decendents + descendants + decideable + decidable + decidely + decidedly + decieved + deceived + decison + decision + decomissioned + decommissioned + decomposit + decompose + decomposited + decomposed + decompositing + decomposing + decomposits + decomposes + decress + decrees + decribe + describe + decribed + described + decribes + describes + decribing + describing + dectect + detect + defendent + defendant + defendents + defendants + deffensively + defensively + deffine + define + deffined + defined + definance + defiance + definate + definite + definately + definitely + definatly + definitely + definetly + definitely + definining + defining + definit + definite + definitly + definitely + definiton + definition + defintion + definition + degrate + degrade + delagates + delegates + delapidated + dilapidated + delerious + delirious + delevopment + development + deliberatly + deliberately + delusionally + delusively + demenor + demeanor + demographical + demographic + demolision + demolition + demorcracy + democracy + demostration + demonstration + denegrating + denigrating + densly + densely + deparment + department + deparmental + departmental + deparments + departments + dependance + dependence + dependancy + dependency + dependant + dependent + deram + dream + deriviated + derived + derivitive + derivative + derogitory + derogatory + descendands + descendants + descibed + described + descision + decision + descisions + decisions + descriibes + describes + descripters + descriptors + descripton + description + desctruction + destruction + descuss + discuss + desgined + designed + deside + decide + desigining + designing + desinations + destinations + desintegrated + disintegrated + desintegration + disintegration + desireable + desirable + desitned + destined + desktiop + desktop + desorder + disorder + desoriented + disoriented + desparate + desperate + despict + depict + despiration + desperation + dessicated + desiccated + dessigned + designed + destablized + destabilized + destory + destroy + detailled + detailed + detatched + detached + deteoriated + deteriorated + deteriate + deteriorate + deterioriating + deteriorating + determinining + determining + detremental + detrimental + devasted + devastated + develope + develop + developement + development + developped + developed + develpment + development + devels + delves + devestated + devastated + devestating + devastating + devide + divide + devided + divided + devistating + devastating + devolopement + development + diablical + diabolical + diamons + diamonds + diaster + disaster + dichtomy + dichotomy + diconnects + disconnects + dicover + discover + dicovered + discovered + dicovering + discovering + dicovers + discovers + dicovery + discovery + dicussed + discussed + didnt + didn't + diea + idea + dieing + dying + dieties + deities + diety + deity + diferent + different + diferrent + different + differentiatiations + differentiations + differnt + different + difficulity + difficulty + diffrent + different + dificulties + difficulties + dificulty + difficulty + dimenions + dimensions + dimention + dimension + dimentional + dimensional + dimentions + dimensions + dimesnional + dimensional + diminuitive + diminutive + dimunitive + diminutive + diosese + diocese + diphtong + diphthong + diphtongs + diphthongs + diplomancy + diplomacy + dipthong + diphthong + dipthongs + diphthongs + dirived + derived + disagreeed + disagreed + disapeared + disappeared + disapointing + disappointing + disappearred + disappeared + disaproval + disapproval + disasterous + disastrous + disatisfaction + dissatisfaction + disatisfied + dissatisfied + disatrous + disastrous + discontentment + discontent + discribe + describe + discribed + described + discribes + describes + discribing + describing + disctinction + distinction + disctinctive + distinctive + disemination + dissemination + disenchanged + disenchanted + disiplined + disciplined + disobediance + disobedience + disobediant + disobedient + disolved + dissolved + disover + discover + dispair + despair + disparingly + disparagingly + dispence + dispense + dispenced + dispensed + dispencing + dispensing + dispicable + despicable + dispite + despite + dispostion + disposition + disproportiate + disproportionate + disputandem + disputandum + disricts + districts + dissagreement + disagreement + dissapear + disappear + dissapearance + disappearance + dissapeared + disappeared + dissapearing + disappearing + dissapears + disappears + dissappear + disappear + dissappears + disappears + dissappointed + disappointed + dissarray + disarray + dissobediance + disobedience + dissobediant + disobedient + dissobedience + disobedience + dissobedient + disobedient + distiction + distinction + distingish + distinguish + distingished + distinguished + distingishes + distinguishes + distingishing + distinguishing + distingquished + distinguished + distrubution + distribution + distruction + destruction + distructive + destructive + ditributed + distributed + diversed + diverged + divice + device + divison + division + divisons + divisions + doccument + document + doccumented + documented + doccuments + documents + docrines + doctrines + doctines + doctrines + documenatry + documentary + doens + does + doesnt + doesn't + doign + doing + dominaton + domination + dominent + dominant + dominiant + dominant + donig + doing + dont + don't + dosen't + doesn't + doub + doubt + doulbe + double + dowloads + downloads + dramtic + dramatic + draughtman + draughtsman + dreasm + dreams + driectly + directly + drnik + drink + druming + drumming + drummless + drumless + dupicate + duplicate + durig + during + durring + during + duting + during + dyas + dryas + eahc + each + ealier + earlier + earlies + earliest + earnt + earned + ecclectic + eclectic + eceonomy + economy + ecidious + deciduous + eclispe + eclipse + ecomonic + economic + ect + etc + eearly + early + efel + evil + effeciency + efficiency + effecient + efficient + effeciently + efficiently + efficency + efficiency + efficent + efficient + efficently + efficiently + efford + effort + effords + efforts + effulence + effluence + eigth + eight + eiter + either + elction + election + electic + electric + electon + electron + electrial + electrical + electricly + electrically + electricty + electricity + elementay + elementary + eleminated + eliminated + eleminating + eliminating + eles + eels + eletricity + electricity + elicided + elicited + eligable + eligible + elimentary + elementary + ellected + elected + elphant + elephant + embarass + embarrass + embarassed + embarrassed + embarassing + embarrassing + embarassment + embarrassment + embargos + embargoes + embarras + embarrass + embarrased + embarrassed + embarrasing + embarrassing + embarrasment + embarrassment + embezelled + embezzled + emblamatic + emblematic + eminate + emanate + eminated + emanated + emision + emission + emited + emitted + emiting + emitting + emition + emission + emmediately + immediately + emmigrated + immigrated + emminently + eminently + emmisaries + emissaries + emmisarries + emissaries + emmisarry + emissary + emmisary + emissary + emmision + emission + emmisions + emissions + emmited + emitted + emmiting + emitting + emmitted + emitted + emmitting + emitting + emnity + enmity + emperical + empirical + emphaised + emphasised + emphsis + emphasis + emphysyma + emphysema + emprisoned + imprisoned + enameld + enameled + enchancement + enhancement + encouraing + encouraging + encryptiion + encryption + encylopedia + encyclopedia + endevors + endeavors + endevour + endeavour + endig + ending + endolithes + endoliths + enduce + induce + ened + need + enflamed + inflamed + enforceing + enforcing + engagment + engagement + engeneer + engineer + engeneering + engineering + engieneer + engineer + engieneers + engineers + enlargment + enlargement + enlargments + enlargements + enourmous + enormous + enourmously + enormously + ensconsed + ensconced + entaglements + entanglements + enteratinment + entertainment + enthusiatic + enthusiastic + entitity + entity + entitlied + entitled + entrepeneur + entrepreneur + entrepeneurs + entrepreneurs + enviorment + environment + enviormental + environmental + enviormentally + environmentally + enviorments + environments + enviornment + environment + enviornmental + environmental + enviornmentalist + environmentalist + enviornmentally + environmentally + enviornments + environments + enviroment + environment + enviromental + environmental + enviromentalist + environmentalist + enviromentally + environmentally + enviroments + environments + envolutionary + evolutionary + envrionments + environments + enxt + next + epidsodes + episodes + epsiode + episode + equialent + equivalent + equilibium + equilibrium + equilibrum + equilibrium + equiped + equipped + equippment + equipment + equitorial + equatorial + equivelant + equivalent + equivelent + equivalent + equivilant + equivalent + equivilent + equivalent + equivlalent + equivalent + erally + really + eratic + erratic + eratically + erratically + eraticly + erratically + errupted + erupted + esential + essential + esitmated + estimated + esle + else + especialy + especially + essencial + essential + essense + essence + essentail + essential + essentialy + essentially + essentual + essential + essesital + essential + estabishes + establishes + establising + establishing + ethnocentricm + ethnocentrism + ethose + those + evenhtually + eventually + eventally + eventually + eventhough + even though + eventially + eventually + eventualy + eventually + everthing + everything + everytime + every time + everyting + everything + eveyr + every + evidentally + evidently + exagerate + exaggerate + exagerated + exaggerated + exagerates + exaggerates + exagerating + exaggerating + exagerrate + exaggerate + exagerrated + exaggerated + exagerrates + exaggerates + exagerrating + exaggerating + examinated + examined + exampt + exempt + exapansion + expansion + excact + exact + excange + exchange + excecute + execute + excecuted + executed + excecutes + executes + excecuting + executing + excecution + execution + excedded + exceeded + excelent + excellent + excell + excel + excellance + excellence + excellant + excellent + excells + excels + excercise + exercise + exchanching + exchanging + excisted + existed + exculsivly + exclusively + execising + exercising + exection + execution + exectued + executed + exeedingly + exceedingly + exelent + excellent + exellent + excellent + exemple + example + exept + except + exeptional + exceptional + exerbate + exacerbate + exerbated + exacerbated + exerciese + exercises + exerpt + excerpt + exerpts + excerpts + exersize + exercise + exerternal + external + exhalted + exalted + exhibtion + exhibition + exibition + exhibition + exibitions + exhibitions + exicting + exciting + exinct + extinct + existance + existence + existant + existent + existince + existence + exliled + exiled + exludes + excludes + exmaple + example + exonorate + exonerate + exoskelaton + exoskeleton + expalin + explain + expatriot + expatriate + expeced + expected + expecially + especially + expeditonary + expeditionary + expeiments + experiments + expell + expel + expells + expels + experiance + experience + experianced + experienced + expiditions + expeditions + expierence + experience + explaination + explanation + explaning + explaining + explictly + explicitly + exploititive + exploitative + explotation + exploitation + expropiated + expropriated + expropiation + expropriation + exressed + expressed + extemely + extremely + extention + extension + extentions + extensions + extered + exerted + extermist + extremist + extint + extinct + extradiction + extradition + extraterrestial + extraterrestrial + extraterrestials + extraterrestrials + extravagent + extravagant + extrememly + extremely + extremeophile + extremophile + extremly + extremely + extrordinarily + extraordinarily + extrordinary + extraordinary + eyar + year + eyars + years + eyasr + years + faciliate + facilitate + faciliated + facilitated + faciliates + facilitates + facilites + facilities + facillitate + facilitate + facinated + fascinated + facist + fascist + familes + families + familliar + familiar + famoust + famous + fanatism + fanaticism + fatc + fact + faught + fought + favoutrable + favourable + feasable + feasible + fedreally + federally + feromone + pheromone + fertily + fertility + fianite + finite + fianlly + finally + ficticious + fictitious + fictious + fictitious + fidn + find + fiercly + fiercely + fightings + fighting + filiament + filament + fimilies + families + finacial + financial + finaly + finally + financialy + financially + firends + friends + firts + first + fisionable + fissionable + flamable + flammable + flawess + flawless + fleed + fled + florescent + fluorescent + flourescent + fluorescent + flourine + fluorine + fluorish + flourish + follwoing + following + folowing + following + fomed + formed + fomr + from + fonetic + phonetic + fontrier + fontier + foootball + football + forbad + forbade + forbiden + forbidden + foreward + foreword + forfiet + forfeit + forhead + forehead + foriegn + foreign + formallize + formalize + formallized + formalized + formaly + formally + formelly + formerly + formidible + formidable + formost + foremost + forsaw + foresaw + forseeable + foreseeable + fortelling + foretelling + forunner + forerunner + foucs + focus + foudn + found + fougth + fought + foundaries + foundries + foundary + foundry + fourties + forties + fourty + forty + fouth + fourth + foward + forward + freind + friend + freindly + friendly + frequentily + frequently + frome + from + fromed + formed + froniter + frontier + fucntion + function + fucntioning + functioning + fufill + fulfill + fufilled + fulfilled + fulfiled + fulfilled + fullfill + fulfill + fullfilled + fulfilled + fundametal + fundamental + fundametals + fundamentals + funguses + fungi + funtion + function + furuther + further + futher + further + futhermore + furthermore + galatic + galactic + gallaxies + galaxies + galvinized + galvanized + ganerate + generate + ganes + games + ganster + gangster + garantee + guarantee + garanteed + guaranteed + garantees + guarantees + garnison + garrison + gaurantee + guarantee + gauranteed + guaranteed + gaurantees + guarantees + gaurd + guard + gaurentee + guarantee + gaurenteed + guaranteed + gaurentees + guarantees + geneological + genealogical + geneologies + genealogies + geneology + genealogy + generaly + generally + generatting + generating + genialia + genitalia + geographicial + geographical + geometrician + geometer + geometricians + geometers + gerat + great + glight + flight + gnawwed + gnawed + godess + goddess + godesses + goddesses + gogin + going + goign + going + gonig + going + gouvener + governor + govement + government + govenment + government + govenrment + government + goverance + governance + goverment + government + govermental + governmental + governer + governor + governmnet + government + govorment + government + govormental + governmental + govornment + government + gracefull + graceful + graet + great + grafitti + graffiti + gramatically + grammatically + grammaticaly + grammatically + grammer + grammar + grat + great + gratuitious + gratuitous + greatful + grateful + greatfully + gratefully + greif + grief + gridles + griddles + gropu + group + grwo + grow + guage + gauge + guarentee + guarantee + guarenteed + guaranteed + guarentees + guarantees + guerilla + guerrilla + guerillas + guerrillas + guerrila + guerrilla + guerrilas + guerrillas + guidence + guidance + gunanine + guanine + gurantee + guarantee + guranteed + guaranteed + gurantees + guarantees + guttaral + guttural + gutteral + guttural + habaeus + habeas + habeus + habeas + haemorrage + haemorrhage + haev + have + halp + help + hapen + happen + hapened + happened + hapening + happening + happend + happened + happended + happened + happenned + happened + harased + harassed + harases + harasses + harasment + harassment + harasments + harassments + harassement + harassment + harras + harass + harrased + harassed + harrases + harasses + harrasing + harassing + harrasment + harassment + harrasments + harassments + harrassed + harassed + harrasses + harassed + harrassing + harassing + harrassment + harassment + harrassments + harassments + hasnt + hasn't + haviest + heaviest + headquarer + headquarter + headquater + headquarter + headquatered + headquartered + headquaters + headquarters + healthercare + healthcare + heared + heard + heathy + healthy + heigher + higher + heirarchy + hierarchy + heiroglyphics + hieroglyphics + helment + helmet + helpfull + helpful + helpped + helped + hemmorhage + hemorrhage + herad + heard + heridity + heredity + heroe + hero + heros + heroes + hertiage + heritage + hertzs + hertz + hesistant + hesitant + heterogenous + heterogeneous + hieght + height + hierachical + hierarchical + hierachies + hierarchies + hierachy + hierarchy + hierarcical + hierarchical + hierarcy + hierarchy + hieroglph + hieroglyph + hieroglphs + hieroglyphs + higer + higher + higest + highest + higway + highway + hillarious + hilarious + himselv + himself + hinderance + hindrance + hinderence + hindrance + hindrence + hindrance + hipopotamus + hippopotamus + hismelf + himself + histocompatability + histocompatibility + historicians + historians + hitsingles + hit singles + holliday + holiday + homestate + home state + homogeneize + homogenize + homogeneized + homogenized + honory + honorary + horrifing + horrifying + hosited + hoisted + hospitible + hospitable + hounour + honour + housr + hours + howver + however + hsitorians + historians + hstory + history + hten + then + htere + there + htey + they + htikn + think + hting + thing + htink + think + htis + this + humer + humor + humerous + humorous + huminoid + humanoid + humoural + humoral + humurous + humorous + husban + husband + hvae + have + hvaing + having + hvea + have + hwihc + which + hwile + while + hwole + whole + hydogen + hydrogen + hydropile + hydrophile + hydropilic + hydrophilic + hydropobe + hydrophobe + hydropobic + hydrophobic + hygeine + hygiene + hypocracy + hypocrisy + hypocrasy + hypocrisy + hypocricy + hypocrisy + hypocrit + hypocrite + hypocrits + hypocrites + i + I + iconclastic + iconoclastic + idaeidae + idea + idaes + ideas + idealogies + ideologies + idealogy + ideology + identicial + identical + identifers + identifiers + ideosyncratic + idiosyncratic + idesa + ideas + idiosyncracy + idiosyncrasy + illegimacy + illegitimacy + illegitmate + illegitimate + illess + illness + illiegal + illegal + illution + illusion + ilness + illness + ilogical + illogical + imagenary + imaginary + imagin + imagine + imaginery + imaginary + imcomplete + incomplete + imediately + immediately + imense + immense + immediatley + immediately + immediatly + immediately + immidately + immediately + immidiately + immediately + immitate + imitate + immitated + imitated + immitating + imitating + immitator + imitator + immunosupressant + immunosuppressant + impecabbly + impeccably + impedence + impedance + implamenting + implementing + impliment + implement + implimented + implemented + imploys + employs + importamt + important + imprioned + imprisoned + imprisonned + imprisoned + improvision + improvisation + improvments + improvements + inablility + inability + inaccessable + inaccessible + inadiquate + inadequate + inadquate + inadequate + inadvertant + inadvertent + inadvertantly + inadvertently + inagurated + inaugurated + inaguration + inauguration + inappropiate + inappropriate + inaugures + inaugurates + inbalance + imbalance + inbalanced + imbalanced + inbetween + between + incarcirated + incarcerated + incidentially + incidentally + incidently + incidentally + inclreased + increased + includ + include + includng + including + incompatabilities + incompatibilities + incompatability + incompatibility + incompatable + incompatible + incompatablities + incompatibilities + incompatablity + incompatibility + incompatiblities + incompatibilities + incompatiblity + incompatibility + incompetance + incompetence + incompetant + incompetent + incomptable + incompatible + incomptetent + incompetent + inconsistant + inconsistent + incoroporated + incorporated + incorperation + incorporation + incorportaed + incorporated + incorprates + incorporates + incorruptable + incorruptible + incramentally + incrementally + increadible + incredible + incredable + incredible + inctroduce + introduce + inctroduced + introduced + incuding + including + incunabla + incunabula + indefinately + indefinitely + indefineable + undefinable + indefinitly + indefinitely + indentical + identical + indepedantly + independently + indepedence + independence + independance + independence + independant + independent + independantly + independently + independece + independence + independendet + independent + indespensable + indispensable + indespensible + indispensable + indictement + indictment + indigineous + indigenous + indipendence + independence + indipendent + independent + indipendently + independently + indispensible + indispensable + indisputible + indisputable + indisputibly + indisputably + indite + indict + individualy + individually + indpendent + independent + indpendently + independently + indulgue + indulge + indutrial + industrial + indviduals + individuals + inefficienty + inefficiently + inevatible + inevitable + inevitible + inevitable + inevititably + inevitably + infalability + infallibility + infallable + infallible + infectuous + infectious + infered + inferred + infilitrate + infiltrate + infilitrated + infiltrated + infilitration + infiltration + infinit + infinite + inflamation + inflammation + influencial + influential + influented + influenced + infomation + information + informtion + information + infrantryman + infantryman + infrigement + infringement + ingenius + ingenious + ingreediants + ingredients + inhabitans + inhabitants + inherantly + inherently + inheritence + inheritance + inital + initial + initally + initially + initation + initiation + initiaitive + initiative + inlcuding + including + inmigrant + immigrant + inmigrants + immigrants + innoculated + inoculated + inocence + innocence + inofficial + unofficial + inot + into + inpeach + impeach + inpolite + impolite + inprisonment + imprisonment + inproving + improving + insectiverous + insectivorous + insensative + insensitive + inseperable + inseparable + insistance + insistence + insitution + institution + insitutions + institutions + inspite + in spite + instade + instead + instatance + instance + institue + institute + instuction + instruction + instuments + instruments + instutionalized + institutionalized + instutions + intuitions + insurence + insurance + intelectual + intellectual + inteligence + intelligence + inteligent + intelligent + intenational + international + intented + intended + intepretation + interpretation + intepretator + interpretor + interational + international + interbread + interbreed + interchangable + interchangeable + interchangably + interchangeably + intercontinetal + intercontinental + intered + interred + interelated + interrelated + interferance + interference + interfereing + interfering + intergrated + integrated + intergration + integration + interm + interim + internation + international + interpet + interpret + interrim + interim + interrugum + interregnum + intertaining + entertaining + interupt + interrupt + intervines + intervenes + intevene + intervene + intial + initial + intially + initially + intrduced + introduced + intrest + interest + introdued + introduced + intruduced + introduced + intrument + instrument + intrumental + instrumental + intruments + instruments + intrusted + entrusted + intutive + intuitive + intutively + intuitively + inudstry + industry + inventer + inventor + invertibrates + invertebrates + investingate + investigate + involvment + involvement + irelevent + irrelevant + iresistable + irresistible + iresistably + irresistibly + iresistible + irresistible + iresistibly + irresistibly + iritable + irritable + iritated + irritated + ironicly + ironically + irregardless + regardless + irrelevent + irrelevant + irreplacable + irreplaceable + irresistable + irresistible + irresistably + irresistibly + isnt + isn't + issueing + issuing + itnroduced + introduced + iunior + junior + iwll + will + iwth + with + jaques + jacques + jeapardy + jeopardy + jewllery + jewellery + jouney + journey + journied + journeyed + journies + journeys + jstu + just + jsut + just + judical + judicial + judisuary + judiciary + juducial + judicial + juristiction + jurisdiction + juristictions + jurisdictions + kindergarden + kindergarten + klenex + kleenex + knifes + knives + knive + knife + knowlege + knowledge + knowlegeable + knowledgeable + knwo + know + knwos + knows + konw + know + konws + knows + kwno + know + labatory + laboratory + labratory + laboratory + laguage + language + laguages + languages + larg + large + largst + largest + larrry + larry + lastr + last + lattitude + latitude + launhed + launched + lavae + larvae + layed + laid + lazyness + laziness + leage + league + leanr + learn + leathal + lethal + lefted + left + legitamate + legitimate + legitmate + legitimate + leibnitz + leibniz + lenght + length + leran + learn + lerans + learns + leutenant + lieutenant + levetate + levitate + levetated + levitated + levetates + levitates + levetating + levitating + levle + level + liasion + liaison + liason + liaison + liasons + liaisons + libary + library + libell + libel + libguistic + linguistic + libguistics + linguistics + libitarianisn + libertarianism + lieing + lying + liek + like + liekd + liked + liesure + leisure + lieuenant + lieutenant + lieved + lived + liftime + lifetime + lightyear + light year + lightyears + light years + likelyhood + likelihood + linnaena + linnaean + lippizaner + lipizzaner + liquify + liquefy + liscense + license + lisence + license + lisense + license + listners + listeners + litature + literature + literaly + literally + literture + literature + littel + little + litterally + literally + liuke + like + livley + lively + lmits + limits + loev + love + lonelyness + loneliness + longitudonal + longitudinal + lonley + lonely + lonly + lonely + loosing + losing + lotharingen + lothringen + lsat + last + lukid + likud + lveo + love + lvoe + love + maching + machine + mackeral + mackerel + magasine + magazine + magincian + magician + magnificient + magnificent + magolia + magnolia + mailny + mainly + maintainance + maintenance + maintainence + maintenance + maintance + maintenance + maintenence + maintenance + maintinaing + maintaining + maintioned + mentioned + majoroty + majority + maked + marked + makse + makes + maltesian + Maltese + mamal + mammal + mamalian + mammalian + managable + manageable + managment + management + maneouvre + manoeuvre + maneouvred + manoeuvred + maneouvres + manoeuvres + maneouvring + manoeuvring + manisfestations + manifestations + manoeuverability + maneuverability + manouver + maneuver + manouverability + maneuverability + manouverable + maneuverable + manouvers + maneuvers + mantained + maintained + manuever + maneuver + manuevers + maneuvers + manufacturedd + manufactured + manufature + manufacture + manufatured + manufactured + manufaturing + manufacturing + manuver + maneuver + mariage + marriage + marjority + majority + markes + marks + marketting + marketing + marmelade + marmalade + marrage + marriage + marraige + marriage + marrtyred + martyred + marryied + married + massmedia + mass media + masterbation + masturbation + mataphysical + metaphysical + materalists + materialist + mathamatics + mathematics + mathematican + mathematician + mathematicas + mathematics + matheticians + mathematicians + mathmatically + mathematically + mathmatician + mathematician + mathmaticians + mathematicians + mccarthyst + mccarthyist + mchanics + mechanics + meaninng + meaning + mear + wear + mechandise + merchandise + medacine + medicine + medeival + medieval + medevial + medieval + mediciney + mediciny + medievel + medieval + mediterainnean + mediterranean + meerkrat + meerkat + melieux + milieux + membranaphone + membranophone + memeber + member + menally + mentally + meranda + Miranda + mercentile + mercantile + messanger + messenger + messenging + messaging + metalic + metallic + metalurgic + metallurgic + metalurgical + metallurgical + metalurgy + metallurgy + metamorphysis + metamorphosis + metaphoricial + metaphorical + meterologist + meteorologist + meterology + meteorology + methaphor + metaphor + methaphors + metaphors + micoscopy + microscopy + midwifes + midwives + mileau + milieu + milennia + millennia + milennium + millennium + mileu + milieu + miliary + military + milion + million + miliraty + military + millenia + millennia + millenial + millennial + millenialism + millennialism + millenium + millennium + millepede + millipede + millioniare + millionaire + millitary + military + millon + million + miltary + military + minature + miniature + minerial + mineral + miniscule + minuscule + ministery + ministry + minstries + ministries + minstry + ministry + minumum + minimum + mirrorred + mirrored + miscelaneous + miscellaneous + miscellanious + miscellaneous + miscellanous + miscellaneous + mischeivous + mischievous + mischevious + mischievous + mischievious + mischievous + misdameanor + misdemeanor + misdameanors + misdemeanors + misdemenor + misdemeanor + misdemenors + misdemeanors + misfourtunes + misfortunes + misile + missile + mispell + misspell + mispelled + misspelled + mispelling + misspelling + missen + mizzen + missle + missile + missonary + missionary + misterious + mysterious + mistery + mystery + misteryous + mysterious + mkae + make + mkaes + makes + mkaing + making + mkea + make + moderm + modem + modle + model + moent + moment + moeny + money + mohammedans + muslims + moil + soil + moleclues + molecules + momento + memento + monestaries + monasteries + monestary + monastery + monickers + monikers + monolite + monolithic + montains + mountains + montanous + mountainous + monts + months + montypic + monotypic + moreso + more so + morgage + mortgage + morroccan + moroccan + morrocco + morocco + morroco + morocco + mortage + mortgage + mosture + moisture + motiviated + motivated + mounth + month + movei + movie + movment + movement + mroe + more + mucuous + mucous + muder + murder + mudering + murdering + muhammadan + muslim + multicultralism + multiculturalism + multipled + multiplied + multiplers + multipliers + munbers + numbers + muncipalities + municipalities + muncipality + municipality + munnicipality + municipality + muscels + muscles + muscial + musical + muscician + musician + muscicians + musicians + mutiliated + mutilated + myraid + myriad + mysef + myself + mysogynist + misogynist + mysogyny + misogyny + mysterous + mysterious + naieve + naive + naturaly + naturally + naturely + naturally + naturual + natural + naturually + naturally + neccesarily + necessarily + neccesary + necessary + neccessarily + necessarily + neccessary + necessary + neccessities + necessities + necesarily + necessarily + necesary + necessary + necessiate + necessitate + neglible + negligible + negligable + negligible + negociate + negotiate + negociation + negotiation + negociations + negotiations + negotation + negotiation + neice + niece + neigborhood + neighborhood + neigbour + neighbour + neigbourhood + neighbourhood + neolitic + neolithic + nessasarily + necessarily + nessecary + necessary + nestin + nesting + neverthless + nevertheless + newletters + newsletters + nickle + nickel + nightfa;; + nightfall + nightime + nighttime + nineth + ninth + ninteenth + nineteenth + ninties + 1990s + ninty + ninety + nkow + know + nkwo + know + nmae + name + noncombatents + noncombatants + nonsence + nonsense + nontheless + nonetheless + noone + no one + norhern + northern + northen + northern + northereastern + northeastern + notabley + notably + noteable + notable + noteably + notably + noteriety + notoriety + noth + north + nothern + northern + noticable + noticeable + noticably + noticeably + noticeing + noticing + noticible + noticeable + notwhithstanding + notwithstanding + noveau + nouveau + nowdays + nowadays + nowe + now + nto + not + nucular + nuclear + nuculear + nuclear + nuisanse + nuisance + numberous + numerous + nusance + nuisance + nutritent + nutrient + nutritents + nutrients + nuturing + nurturing + obediance + obedience + obediant + obedient + obession + obsession + obssessed + obsessed + obstacal + obstacle + obstancles + obstacles + obstruced + obstructed + ocasion + occasion + ocasional + occasional + ocasionally + occasionally + ocasionaly + occasionally + ocasioned + occasioned + ocasions + occasions + ocassion + occasion + ocassional + occasional + ocassionally + occasionally + ocassionaly + occasionally + ocassioned + occasioned + ocassions + occasions + occaison + occasion + occassion + occasion + occassional + occasional + occassionally + occasionally + occassionaly + occasionally + occassioned + occasioned + occassions + occasions + occationally + occasionally + occour + occur + occurance + occurrence + occurances + occurrences + occured + occurred + occurence + occurrence + occurences + occurrences + occuring + occurring + occurr + occur + occurrance + occurrence + occurrances + occurrences + octohedra + octahedra + octohedral + octahedral + octohedron + octahedron + ocuntries + countries + ocuntry + country + ocurr + occur + ocurrance + occurrence + ocurred + occurred + ocurrence + occurrence + offcers + officers + offcially + officially + offereings + offerings + offical + official + offically + officially + officals + officials + officaly + officially + officialy + officially + offred + offered + oftenly + often + oging + going + omision + omission + omited + omitted + omiting + omitting + omlette + omelette + ommision + omission + ommited + omitted + ommiting + omitting + ommitted + omitted + ommitting + omitting + omniverous + omnivorous + omniverously + omnivorously + omre + more + onot + note + onxy + onyx + onyl + only + openess + openness + oponent + opponent + oportunity + opportunity + opose + oppose + oposite + opposite + oposition + opposition + oppenly + openly + oppinion + opinion + opponant + opponent + oppononent + opponent + oppositition + opposition + oppossed + opposed + opprotunity + opportunity + opression + oppression + opressive + oppressive + opthalmic + ophthalmic + opthalmologist + ophthalmologist + opthalmology + ophthalmology + opthamologist + ophthalmologist + optmizations + optimizations + optomism + optimism + orded + ordered + organim + organism + organistion + organisation + organiztion + organization + orgin + origin + orginal + original + orginally + originally + orginize + organise + oridinarily + ordinarily + origanaly + originally + originall + original + originaly + originally + originially + originally + originnally + originally + origional + original + orignally + originally + orignially + originally + otehr + other + oublisher + publisher + ouevre + oeuvre + oustanding + outstanding + overshaddowed + overshadowed + overthere + over there + overwelming + overwhelming + overwheliming + overwhelming + owrk + work + owudl + would + oxigen + oxygen + oximoron + oxymoron + p0enis + penis + paide + paid + paitience + patience + palce + place + paleolitic + paleolithic + paliamentarian + parliamentarian + pallete + palette + pamflet + pamphlet + pamplet + pamphlet + pantomine + pantomime + paralel + parallel + paralell + parallel + paralelly + parallelly + paralely + parallelly + parallely + parallelly + paranthesis + parenthesis + paraphenalia + paraphernalia + parellels + parallels + parituclar + particular + parliment + parliament + parrakeets + parakeets + parralel + parallel + parrallel + parallel + parrallell + parallel + parrallelly + parallelly + parrallely + parallelly + partialy + partially + particually + particularly + particualr + particular + particuarly + particularly + particularily + particularly + particulary + particularly + pary + party + pased + passed + pasengers + passengers + passerbys + passersby + pasttime + pastime + pastural + pastoral + paticular + particular + pattented + patented + pavillion + pavilion + payed + paid + pblisher + publisher + pbulisher + publisher + peacefuland + peaceful and + peageant + pageant + peculure + peculiar + pedestrain + pedestrian + peformed + performed + peice + piece + penatly + penalty + penerator + penetrator + penisula + peninsula + penisular + peninsular + penninsula + peninsula + penninsular + peninsular + pennisula + peninsula + pensinula + peninsula + peom + poem + peoms + poems + peopel + people + peotry + poetry + perade + parade + percepted + perceived + percieve + perceive + percieved + perceived + perenially + perennially + perfomance + performance + perfomers + performers + performence + performance + performes + performed + perhasp + perhaps + perheaps + perhaps + perhpas + perhaps + peripathetic + peripatetic + peristent + persistent + perjery + perjury + perjorative + pejorative + permanant + permanent + permenant + permanent + permenantly + permanently + permissable + permissible + perogative + prerogative + peronal + personal + perosnality + personality + perphas + perhaps + perpindicular + perpendicular + perseverence + perseverance + persistance + persistence + persistant + persistent + personel + personnel + personell + personnel + personnell + personnel + persuded + persuaded + persue + pursue + persued + pursued + persuing + pursuing + persuit + pursuit + persuits + pursuits + pertubation + perturbation + pertubations + perturbations + pessiary + pessary + petetion + petition + phenomenom + phenomenon + phenomenonal + phenomenal + phenomenonly + phenomenally + phenomonenon + phenomenon + phenomonon + phenomenon + phenonmena + phenomena + philisopher + philosopher + philisophical + philosophical + philisophy + philosophy + phillosophically + philosophically + philospher + philosopher + philosphies + philosophies + philosphy + philosophy + phongraph + phonograph + phylosophical + philosophical + physicaly + physically + piblisher + publisher + pich + pitch + pilgrimmage + pilgrimage + pilgrimmages + pilgrimages + pinapple + pineapple + pinnaple + pineapple + pinoneered + pioneered + plagarism + plagiarism + planation + plantation + planed + planned + plantiff + plaintiff + plateu + plateau + plausable + plausible + playright + playwright + playwrite + playwright + playwrites + playwrights + pleasent + pleasant + plebicite + plebiscite + plesant + pleasant + poenis + penis + poeoples + peoples + poety + poetry + poisin + poison + polical + political + polinator + pollinator + polinators + pollinators + politican + politician + politicans + politicians + poltical + political + polute + pollute + poluted + polluted + polutes + pollutes + poluting + polluting + polution + pollution + polyphonyic + polyphonic + polysaccaride + polysaccharide + polysaccharid + polysaccharide + pomegranite + pomegranate + pomotion + promotion + poportional + proportional + popoulation + population + popularaty + popularity + populare + popular + populer + popular + portait + portrait + portayed + portrayed + portraing + portraying + portuguease + portuguese + portugues + Portuguese + posess + possess + posessed + possessed + posesses + possesses + posessing + possessing + posession + possession + posessions + possessions + posion + poison + positon + position + possable + possible + possably + possibly + posseses + possesses + possesing + possessing + possesion + possession + possessess + possesses + possibile + possible + possibilty + possibility + possiblility + possibility + possiblilty + possibility + possiblities + possibilities + possiblity + possibility + possition + position + posthomous + posthumous + postion + position + postive + positive + potatos + potatoes + potrait + portrait + potrayed + portrayed + poulations + populations + poverful + powerful + poweful + powerful + powerfull + powerful + ppublisher + publisher + practial + practical + practially + practically + practicaly + practically + practicioner + practitioner + practicioners + practitioners + practicly + practically + practioner + practitioner + practioners + practitioners + prairy + prairie + prarie + prairie + praries + prairies + pratice + practice + preample + preamble + precedessor + predecessor + preceed + precede + preceeded + preceded + preceeding + preceding + preceeds + precedes + precentage + percentage + precice + precise + precisly + precisely + precurser + precursor + predecesors + predecessors + predicatble + predictable + predicitons + predictions + predomiantly + predominately + prefered + preferred + prefering + preferring + preferrably + preferably + pregancies + pregnancies + preiod + period + preliferation + proliferation + premeire + premiere + premeired + premiered + premillenial + premillennial + preminence + preeminence + premission + permission + preocupation + preoccupation + prepair + prepare + prepartion + preparation + prepatory + preparatory + preperation + preparation + preperations + preparations + preriod + period + presedential + presidential + presense + presence + presidenital + presidential + presidental + presidential + presitgious + prestigious + prespective + perspective + prestigeous + prestigious + prestigous + prestigious + presumabely + presumably + presumibly + presumably + pretection + protection + prevelant + prevalent + preverse + perverse + previvous + previous + pricipal + principal + priciple + principle + priestood + priesthood + primarly + primarily + primative + primitive + primatively + primitively + primatives + primitives + primordal + primordial + priveledges + privileges + privelege + privilege + priveleged + privileged + priveleges + privileges + privelige + privilege + priveliged + privileged + priveliges + privileges + privelleges + privileges + privilage + privilege + priviledge + privilege + priviledges + privileges + privledge + privilege + privte + private + probabilaty + probability + probablistic + probabilistic + probablly + probably + probalibity + probability + probaly + probably + probelm + problem + proccess + process + proccessing + processing + procede + proceed + proceded + proceeded + procedes + proceeds + procedger + procedure + proceding + proceeding + procedings + proceedings + proceedure + procedure + proces + process + processer + processor + proclaimation + proclamation + proclamed + proclaimed + proclaming + proclaiming + proclomation + proclamation + profesion + profession + profesor + professor + professer + professor + proffesed + professed + proffesion + profession + proffesional + professional + proffesor + professor + profilic + prolific + progessed + progressed + programable + programmable + progrom + program + progroms + programs + prohabition + prohibition + prologomena + prolegomena + prominance + prominence + prominant + prominent + prominantly + prominently + prominately + prominently + promiscous + promiscuous + promotted + promoted + pronomial + pronominal + pronouced + pronounced + pronounched + pronounced + pronounciation + pronunciation + proove + prove + prooved + proved + prophacy + prophecy + propietary + proprietary + propmted + prompted + propoganda + propaganda + propogate + propagate + propogates + propagates + propogation + propagation + propostion + proposition + propotions + proportions + propper + proper + propperly + properly + proprietory + proprietary + proseletyzing + proselytizing + protaganist + protagonist + protaganists + protagonists + protocal + protocol + protoganist + protagonist + protrayed + portrayed + protruberance + protuberance + protruberances + protuberances + prouncements + pronouncements + provacative + provocative + provded + provided + provicial + provincial + provinicial + provincial + provisiosn + provision + provisonal + provisional + proximty + proximity + pseudononymous + pseudonymous + pseudonyn + pseudonym + psuedo + pseudo + psycology + psychology + psyhic + psychic + pubilsher + publisher + pubisher + publisher + publiaher + publisher + publically + publicly + publicaly + publicly + publicher + publisher + publihser + publisher + publisehr + publisher + publiser + publisher + publisger + publisher + publisheed + published + publisherr + publisher + publishher + publisher + publishor + publisher + publishre + publisher + publissher + publisher + publlisher + publisher + publsiher + publisher + publusher + publisher + puchasing + purchasing + pulisher + publisher + pumkin + pumpkin + puplisher + publisher + puritannical + puritanical + purposedly + purposely + purpotedly + purportedly + pursuade + persuade + pursuaded + persuaded + pursuades + persuades + pususading + persuading + puting + putting + pwoer + power + pyscic + psychic + qtuie + quiet + quantaty + quantity + quantitiy + quantity + quarantaine + quarantine + questonable + questionable + quicklyu + quickly + quinessential + quintessential + quitted + quit + quizes + quizzes + qutie + quiet + rabinnical + rabbinical + racaus + raucous + radiactive + radioactive + radify + ratify + raelly + really + rarified + rarefied + reaccurring + recurring + reacing + reaching + reacll + recall + readmition + readmission + realitvely + relatively + realsitic + realistic + realtions + relations + realy + really + realyl + really + reasearch + research + rebiulding + rebuilding + rebllions + rebellions + rebounce + rebound + reccomend + recommend + reccomendations + recommendations + reccomended + recommended + reccomending + recommending + reccommend + recommend + reccommended + recommended + reccommending + recommending + reccuring + recurring + receeded + receded + receeding + receding + receivedfrom + received from + recepient + recipient + recepients + recipients + receving + receiving + rechargable + rechargeable + reched + reached + recide + reside + recided + resided + recident + resident + recidents + residents + reciding + residing + reciepents + recipients + reciept + receipt + recieve + receive + recieved + received + reciever + receiver + recievers + receivers + recieves + receives + recieving + receiving + recipiant + recipient + recipiants + recipients + recived + received + recivership + receivership + recogise + recognise + recogize + recognize + recomend + recommend + recomended + recommended + recomending + recommending + recomends + recommends + recommedations + recommendations + reconaissance + reconnaissance + reconcilation + reconciliation + reconized + recognized + reconnaisance + reconnaissance + reconnaissence + reconnaissance + recontructed + reconstructed + recordproducer + record producer + recquired + required + recrational + recreational + recrod + record + recuiting + recruiting + recuring + recurring + recurrance + recurrence + rediculous + ridiculous + reedeming + redeeming + reenforced + reinforced + refect + reflect + refedendum + referendum + referal + referral + referece + reference + refereces + references + refered + referred + referemce + reference + referemces + references + referencs + references + referenece + reference + refereneced + referenced + refereneces + references + referiang + referring + refering + referring + refernce + references + refernces + references + referrence + reference + referrences + references + referrs + refers + reffered + referred + refference + reference + reffering + referring + refrence + reference + refrences + references + refrers + refers + refridgeration + refrigeration + refridgerator + refrigerator + refromist + reformist + refusla + refusal + regardes + regards + regluar + regular + reguarly + regularly + regulaion + regulation + regulaotrs + regulators + regularily + regularly + rehersal + rehearsal + reicarnation + reincarnation + reigining + reigning + reknown + renown + reknowned + renowned + rela + real + relaly + really + relatiopnship + relationship + relativly + relatively + relected + reelected + releive + relieve + releived + relieved + releiver + reliever + releses + releases + relevence + relevance + relevent + relevant + reliablity + reliability + relient + reliant + religeous + religious + religous + religious + religously + religiously + relinqushment + relinquishment + relitavely + relatively + relized + realized + relpacement + replacement + remaing + remaining + remeber + remember + rememberable + memorable + rememberance + remembrance + remembrence + remembrance + remenant + remnant + remenicent + reminiscent + reminent + remnant + reminescent + reminiscent + reminscent + reminiscent + reminsicent + reminiscent + rendevous + rendezvous + rendezous + rendezvous + renedered + rende + renewl + renewal + rennovate + renovate + rennovated + renovated + rennovating + renovating + rennovation + renovation + rentors + renters + reoccurrence + recurrence + reorganision + reorganisation + repatition + repetition + repectively + respectively + repeition + repetition + repentence + repentance + repentent + repentant + repeteadly + repeatedly + repetion + repetition + repid + rapid + reponse + response + reponsible + responsible + reportadly + reportedly + represantative + representative + representive + representative + representives + representatives + reproducable + reproducible + reprtoire + repertoire + repsectively + respectively + reptition + repetition + requirment + requirement + requred + required + resaurant + restaurant + resembelance + resemblance + resembes + resembles + resemblence + resemblance + resevoir + reservoir + residental + residential + resignement + resignment + resistable + resistible + resistence + resistance + resistent + resistant + respectivly + respectively + responce + response + responibilities + responsibilities + responisble + responsible + responnsibilty + responsibility + responsability + responsibility + responsibile + responsible + responsibilites + responsibilities + responsiblities + responsibilities + responsiblity + responsibility + ressemblance + resemblance + ressemble + resemble + ressembled + resembled + ressemblence + resemblance + ressembling + resembling + resssurecting + resurrecting + ressurect + resurrect + ressurected + resurrected + ressurection + resurrection + ressurrection + resurrection + restarant + restaurant + restarants + restaurants + restaraunt + restaurant + restaraunteur + restaurateur + restaraunteurs + restaurateurs + restaraunts + restaurants + restauranteurs + restaurateurs + restauration + restoration + restauraunt + restaurant + resteraunt + restaurant + resteraunts + restaurants + resticted + restricted + restraunt + restraint + resturant + restaurant + resturants + restaurants + resturaunt + restaurant + resturaunts + restaurants + resurecting + resurrecting + retalitated + retaliated + retalitation + retaliation + retreive + retrieve + returnd + returned + revaluated + reevaluated + reveiw + review + reveral + reversal + reversable + reversible + revolutionar + revolutionary + rewitten + rewritten + rewriet + rewrite + rference + reference + rferences + references + rhymme + rhyme + rhythem + rhythm + rhythim + rhythm + rhytmic + rhythmic + rigourous + rigorous + rininging + ringing + rised + rose + rococco + rococo + rocord + record + roomate + roommate + rougly + roughly + rucuperate + recuperate + rudimentatry + rudimentary + rulle + rule + runing + running + runnung + running + russina + Russian + rwite + write + rythem + rhythm + rythim + rhythm + rythm + rhythm + rythmic + rhythmic + rythyms + rhythms + sacrafice + sacrifice + sacreligious + sacrilegious + sacrifical + sacrificial + saftey + safety + safty + safety + salery + salary + sanctionning + sanctioning + sandwhich + sandwich + santioned + sanctioned + sargant + sergeant + sargeant + sergeant + satelite + satellite + satelites + satellites + satisfactority + satisfactorily + satric + satiric + satrical + satirical + satrically + satirically + sattelite + satellite + sattelites + satellites + saught + sought + saveing + saving + saxaphone + saxophone + scaleable + scalable + scandanavia + Scandinavia + scaricity + scarcity + scavanged + scavenged + schedual + schedule + scholarhip + scholarship + scholarstic + scholastic + scientfic + scientific + scientifc + scientific + scientis + scientist + scince + science + scinece + science + scirpt + script + scoll + scroll + screenwrighter + screenwriter + scrutinity + scrutiny + scuptures + sculptures + seach + search + seached + searched + seaches + searches + secratary + secretary + secretery + secretary + sedereal + sidereal + seeked + sought + segementation + segmentation + seguoys + segues + seige + siege + seing + seeing + seinor + senior + seldomly + seldom + senarios + scenarios + senstive + sensitive + sensure + censure + seperate + separate + seperated + separated + seperately + separately + seperates + separates + seperating + separating + seperation + separation + seperatism + separatism + seperatist + separatist + sepina + subpoena + sergent + sergeant + settelement + settlement + settlment + settlement + severeal + several + severley + severely + severly + severely + sevice + service + shadasloo + shadaloo + shaddow + shadow + shadoloo + shadaloo + shamen + shaman + sheat + sheath + sheild + shield + sherif + sheriff + shineing + shining + shiped + shipped + shiping + shipping + shopkeeepers + shopkeepers + shorly + shortly + shortwhile + short while + shoudl + should + shoudln + shouldn't + shouldnt + shouldn't + shreak + shriek + shrinked + shrunk + sicne + since + sideral + sidereal + siezure + seizure + siezures + seizures + siginificant + significant + signficant + significant + signficiant + significant + signfies + signifies + signifantly + significantly + significently + significantly + signifigant + significant + signifigantly + significantly + signitories + signatories + signitory + signatory + similarily + similarly + similiar + similar + similiarity + similarity + similiarly + similarly + simmilar + similar + simpley + simply + simplier + simpler + simultanous + simultaneous + simultanously + simultaneously + sincerley + sincerely + singsog + singsong + sinse + since + skateing + skating + slaugterhouses + slaughterhouses + slighly + slightly + slowy + slowly + smae + same + smealting + smelting + smoe + some + sneeks + sneaks + snese + sneeze + socalism + socialism + socities + societies + soem + some + sofware + software + sohw + show + soilders + soldiers + solatary + solitary + soley + solely + soliders + soldiers + soliliquy + soliloquy + soluable + soluble + somene + someone + somtimes + sometimes + somwhere + somewhere + sophicated + sophisticated + sophmore + sophomore + sorceror + sorcerer + sorrounding + surrounding + sotry + story + sotyr + story + soudn + sound + soudns + sounds + sould + could + sountrack + soundtrack + sourth + south + sourthern + southern + souvenier + souvenir + souveniers + souvenirs + soveits + soviets + sovereignity + sovereignty + soverign + sovereign + soverignity + sovereignty + soverignty + sovereignty + spainish + Spanish + speach + speech + specfic + specific + speciallized + specialized + specifiying + specifying + speciman + specimen + spectauclar + spectacular + spectaulars + spectaculars + spectum + spectrum + speices + species + spendour + splendour + spermatozoan + spermatozoon + spoace + space + sponser + sponsor + sponsered + sponsored + spontanous + spontaneous + sponzored + sponsored + spoonfulls + spoonfuls + sppeches + speeches + spreaded + spread + sprech + speech + spred + spread + spriritual + spiritual + spritual + spiritual + sqaure + square + stablility + stability + stainlees + stainless + staion + station + standars + standards + stange + strange + startegic + strategic + startegies + strategies + startegy + strategy + stateman + statesman + statememts + statements + statment + statement + steriods + steroids + sterotypes + stereotypes + stilus + stylus + stingent + stringent + stiring + stirring + stirrs + stirs + stlye + style + stomache + stomach + stong + strong + stopry + story + storeis + stories + storise + stories + stornegst + strongest + stoyr + story + stpo + stop + stradegies + strategies + stradegy + strategy + strat + start + stratagically + strategically + streemlining + streamlining + stregth + strength + strenghen + strengthen + strenghened + strengthened + strenghening + strengthening + strenght + strength + strenghten + strengthen + strenghtened + strengthened + strenghtening + strengthening + strengtened + strengthened + strenous + strenuous + strictist + strictest + strikely + strikingly + strnad + strand + stroy + story + structual + structural + stubborness + stubbornness + stucture + structure + stuctured + structured + studdy + study + studing + studying + stuggling + struggling + sturcture + structure + subcatagories + subcategories + subcatagory + subcategory + subconsiously + subconsciously + subjudgation + subjugation + submachne + submachine + subpecies + subspecies + subsidary + subsidiary + subsiduary + subsidiary + subsquent + subsequent + subsquently + subsequently + substace + substance + substancial + substantial + substatial + substantial + substituded + substituted + substract + subtract + substracted + subtracted + substracting + subtracting + substraction + subtraction + substracts + subtracts + subtances + substances + subterranian + subterranean + suburburban + suburban + succceeded + succeeded + succcesses + successes + succedded + succeeded + succeded + succeeded + succeds + succeeds + succesful + successful + succesfully + successfully + succesfuly + successfully + succesion + succession + succesive + successive + successfull + successful + successully + successfully + succsess + success + succsessfull + successful + suceed + succeed + suceeded + succeeded + suceeding + succeeding + suceeds + succeeds + sucesful + successful + sucesfully + successfully + sucesfuly + successfully + sucesion + succession + sucess + success + sucesses + successes + sucessful + successful + sucessfull + successful + sucessfully + successfully + sucessfuly + successfully + sucession + succession + sucessive + successive + sucessor + successor + sucessot + successor + sucide + suicide + sucidial + suicidal + sufferage + suffrage + sufferred + suffered + sufferring + suffering + sufficent + sufficient + sufficently + sufficiently + sumary + summary + sunglases + sunglasses + suop + soup + superceeded + superseded + superintendant + superintendent + suphisticated + sophisticated + suplimented + supplemented + supose + suppose + suposed + supposed + suposedly + supposedly + suposes + supposes + suposing + supposing + supplamented + supplemented + suppliementing + supplementing + suppoed + supposed + supposingly + supposedly + suppy + supply + supress + suppress + supressed + suppressed + supresses + suppresses + supressing + suppressing + suprise + surprise + suprised + surprised + suprising + surprising + suprisingly + surprisingly + suprize + surprise + suprized + surprised + suprizing + surprising + suprizingly + surprisingly + surfce + surface + surley + surely + suround + surround + surounded + surrounded + surounding + surrounding + suroundings + surroundings + surounds + surrounds + surplanted + supplanted + surpress + suppress + surpressed + suppressed + surprize + surprise + surprized + surprised + surprizing + surprising + surprizingly + surprisingly + surrended + surrendered + surrepetitious + surreptitious + surrepetitiously + surreptitiously + surreptious + surreptitious + surreptiously + surreptitiously + surronded + surrounded + surrouded + surrounded + surrouding + surrounding + surrundering + surrendering + surveilence + surveillance + surveill + surveil + surveyer + surveyor + surviver + survivor + survivers + survivors + survivied + survived + suseptable + susceptible + suseptible + susceptible + suspention + suspension + swaer + swear + swaers + swears + swepth + swept + swiming + swimming + syas + says + symetrical + symmetrical + symetrically + symmetrically + symetry + symmetry + symettric + symmetric + symmetral + symmetric + symmetricaly + symmetrically + synagouge + synagogue + syncronization + synchronization + synonomous + synonymous + synonymns + synonyms + synphony + symphony + syphyllis + syphilis + sypmtoms + symptoms + syrap + syrup + sysmatically + systematically + sytem + system + sytle + style + tabacco + tobacco + tahn + than + taht + that + talekd + talked + targetted + targeted + targetting + targeting + tast + taste + tath + that + tattooes + tattoos + taxanomic + taxonomic + taxanomy + taxonomy + teached + taught + techician + technician + techicians + technicians + techiniques + techniques + technitian + technician + technnology + technology + technolgy + technology + teh + the + tehy + they + telelevision + television + televsion + television + telphony + telephony + temerature + temperature + tempalte + template + tempaltes + templates + temparate + temperate + temperarily + temporarily + temperment + temperament + tempertaure + temperature + temperture + temperature + temprary + temporary + tenacle + tentacle + tenacles + tentacles + tendacy + tendency + tendancies + tendencies + tendancy + tendency + tennisplayer + tennis player + tepmorarily + temporarily + terrestial + terrestrial + terriories + territories + terriory + territory + territorist + terrorist + territoy + territory + terroist + terrorist + testiclular + testicular + tghe + the + thast + that's + theather + theater + theese + these + theif + thief + theives + thieves + themselfs + themselves + themslves + themselves + ther + there + therafter + thereafter + therby + thereby + theri + their + theyre + they're + thgat + that + thge + the + thier + their + thign + thing + thigns + things + thigsn + things + thikn + think + thikning + thinking + thikns + thinks + thiunk + think + thn + then + thna + than + thne + then + thnig + thing + thnigs + things + thoughout + throughout + threatend + threatened + threatning + threatening + threee + three + threshhold + threshold + thrid + third + throrough + thorough + throughly + thoroughly + throught + throat + througout + throughout + thru + through + thsi + this + thsoe + those + thta + that + thyat + that + tiem + time + tihkn + think + tihs + this + timne + time + tiome + time + tje + the + tjhe + the + tjpanishad + upanishad + tkae + take + tkaes + takes + tkaing + taking + tlaking + talking + tobbaco + tobacco + todays + today's + todya + today + toghether + together + toke + took + tolerence + tolerance + tomatos + tomatoes + tommorow + tomorrow + tommorrow + tomorrow + tongiht + tonight + toriodal + toroidal + tormenters + tormentors + tornadoe + tornado + torpeados + torpedoes + torpedos + torpedoes + tothe + to the + toubles + troubles + tounge + tongue + tourch + torch + towords + towards + towrad + toward + tradionally + traditionally + traditionaly + traditionally + traditionnal + traditional + traditition + tradition + tradtionally + traditionally + trafficed + trafficked + trafficing + trafficking + trafic + traffic + trancendent + transcendent + trancending + transcending + tranform + transform + tranformed + transformed + transcendance + transcendence + transcendant + transcendent + transcendentational + transcendental + transcripting + transcribing + transending + transcending + transesxuals + transsexuals + transfered + transferred + transfering + transferring + transformaton + transformation + transistion + transition + translater + translator + translaters + translators + transmissable + transmissible + transporation + transportation + tremelo + tremolo + tremelos + tremolos + triguered + triggered + triology + trilogy + troling + trolling + troup + troupe + troups + troops + truely + truly + trustworthyness + trustworthiness + turnk + trunk + tust + trust + twelth + twelfth + twon + town + twpo + two + tyhat + that + tyhe + they + typcial + typical + typicaly + typically + tyranies + tyrannies + tyrany + tyranny + tyrranies + tyrannies + tyrrany + tyranny + ubiquitious + ubiquitous + ublisher + publisher + uise + use + ultimely + ultimately + unacompanied + unaccompanied + unahppy + unhappy + unanymous + unanimous + unathorised + unauthorised + unavailible + unavailable + unballance + unbalance + unbeknowst + unbeknownst + unbeleivable + unbelievable + uncertainity + uncertainty + unchallengable + unchallengeable + unchangable + unchangeable + uncompetive + uncompetitive + unconcious + unconscious + unconciousness + unconsciousness + unconfortability + discomfort + uncontitutional + unconstitutional + unconvential + unconventional + undecideable + undecidable + understoon + understood + undesireable + undesirable + undetecable + undetectable + undoubtely + undoubtedly + undreground + underground + uneccesary + unnecessary + unecessary + unnecessary + unequalities + inequalities + unforetunately + unfortunately + unforgetable + unforgettable + unforgiveable + unforgivable + unfortunatley + unfortunately + unfortunatly + unfortunately + unfourtunately + unfortunately + unihabited + uninhabited + unilateraly + unilaterally + unilatreal + unilateral + unilatreally + unilaterally + uninterruped + uninterrupted + uninterupted + uninterrupted + univeral + universal + univeristies + universities + univeristy + university + univerity + university + universtiy + university + univesities + universities + univesity + university + unkown + unknown + unlikey + unlikely + unmanouverable + unmaneuverable + unmistakeably + unmistakably + unneccesarily + unnecessarily + unneccesary + unnecessary + unneccessarily + unnecessarily + unneccessary + unnecessary + unnecesarily + unnecessarily + unnecesary + unnecessary + unoffical + unofficial + unoperational + nonoperational + unoticeable + unnoticeable + unplease + displease + unplesant + unpleasant + unprecendented + unprecedented + unprecidented + unprecedented + unrepentent + unrepentant + unrepetant + unrepentant + unrepetent + unrepentant + unsed + unused + unsubstanciated + unsubstantiated + unsuccesful + unsuccessful + unsuccesfully + unsuccessfully + unsuccessfull + unsuccessful + unsucesful + unsuccessful + unsucesfuly + unsuccessfully + unsucessful + unsuccessful + unsucessfull + unsuccessful + unsucessfully + unsuccessfully + unsuprised + unsurprised + unsuprising + unsurprising + unsuprisingly + unsurprisingly + unsuprized + unsurprised + unsuprizing + unsurprising + unsuprizingly + unsurprisingly + unsurprized + unsurprised + unsurprizing + unsurprising + unsurprizingly + unsurprisingly + untill + until + untranslateable + untranslatable + unuseable + unusable + unusuable + unusable + unviersity + university + unwarrented + unwarranted + unweildly + unwieldy + unwieldly + unwieldy + upcomming + upcoming + upgradded + upgraded + upto + up to + usally + usually + useage + usage + usefull + useful + usefuly + usefully + useing + using + usualy + usually + ususally + usually + vaccum + vacuum + vaccume + vacuum + vacinity + vicinity + vaguaries + vagaries + vaieties + varieties + vailidty + validity + valetta + valletta + valuble + valuable + valueable + valuable + varations + variations + varient + variant + variey + variety + varing + varying + varities + varieties + varity + variety + vasall + vassal + vasalls + vassals + vegatarian + vegetarian + vegitable + vegetable + vegitables + vegetables + vegtable + vegetable + vehicule + vehicle + vell + well + venemous + venomous + vengance + vengeance + vengence + vengeance + verfication + verification + verison + version + verisons + versions + vermillion + vermilion + versitilaty + versatility + versitlity + versatility + vetween + between + veyr + very + vigeur + vigor + vigilence + vigilance + vigourous + vigorous + villian + villain + villification + vilification + villify + vilify + villin + villain + vincinity + vicinity + violentce + violence + virtualy + virtually + virutal + virtual + virutally + virtually + visable + visible + visably + visibly + visting + visiting + vistors + visitors + vitories + victories + volcanoe + volcano + voleyball + volleyball + volontary + voluntary + volonteer + volunteer + volonteered + volunteered + volonteering + volunteering + volonteers + volunteers + volounteer + volunteer + volounteered + volunteered + volounteering + volunteering + volounteers + volunteers + volumne + volume + vreity + variety + vrey + very + vriety + variety + vulnerablility + vulnerability + vyer + very + vyre + very + waht + what + wanna + want to + warantee + warranty + wardobe + wardrobe + warrent + warrant + warrriors + warriors + wasnt + wasn't + wass + was + watn + want + wayword + wayward + weaponary + weaponry + weas + was + wehn + when + weild + wield + weilded + wielded + wendsay + Wednesday + wensday + Wednesday + wereabouts + whereabouts + whant + want + whants + wants + whcih + which + wheras + whereas + wherease + whereas + whereever + wherever + whic + which + whihc + which + whith + with + whlch + which + whn + when + wholey + wholly + wholy + holy + whta + what + whther + whether + wich + which + widesread + widespread + wief + wife + wierd + weird + wiew + view + wih + with + wiht + with + wille + will + willingless + willingness + wirting + writing + withdrawl + withdrawal + witheld + withheld + withh + with + withing + within + withold + withhold + witht + with + witn + with + wiull + will + wnat + want + wnated + wanted + wnats + wants + wohle + whole + wokr + work + wokring + working + wonderfull + wonderful + wont + won't + wordlwide + worldwide + workststion + workstation + worls + world + worstened + worsened + woudl + would + wresters + wrestlers + wriet + write + writen + written + wroet + wrote + wrok + work + wroking + working + wtih + with + wupport + support + xenophoby + xenophobia + yaching + yachting + yaer + year + yaerly + yearly + yaers + years + yatch + yacht + yearm + year + yeasr + years + yeild + yield + yeilding + yielding + yera + year + yeras + years + yersa + years + yotube + YouTube + youre + you're + youseff + yousef + youself + yourself + ytou + you + yuo + you + zeebra + zebra + + enabled + 1 + priority + 5 + wordStyle + 1 + + + diff --git a/indra/newview/llautocorrect.cpp b/indra/newview/llautocorrect.cpp new file mode 100644 index 0000000000..08643fea93 --- /dev/null +++ b/indra/newview/llautocorrect.cpp @@ -0,0 +1,402 @@ +/** + * @file llautocorrect.cpp + * @brief Auto Correct Manager + * @copyright Copyright (c) 2011 LordGregGreg Back + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "llviewerprecompiledheaders.h" +#include "llautocorrect.h" +#include "llsdserialize.h" +#include "llboost.h" +#include "llcontrol.h" +#include "llviewercontrol.h" +#include "llnotificationsutil.h" + +AutoCorrect* AutoCorrect::sInstance; + +AutoCorrect::AutoCorrect() +{ + sInstance = this; + sInstance->loadFromDisk(); +} + +AutoCorrect::~AutoCorrect() +{ + sInstance = NULL; +} + +AutoCorrect* AutoCorrect::getInstance() +{ + if(sInstance)return sInstance; + else + { + sInstance = new AutoCorrect(); + return sInstance; + } +} +void AutoCorrect::save() +{ + saveToDisk(mAutoCorrects); +} +std::string AutoCorrect::getFileName() +{ + std::string path=gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, ""); + + if (!path.empty()) + { + path = gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, "settings_autocorrect.xml"); + } + return path; +} +std::string AutoCorrect::getDefaultFileName() +{ + std::string path=gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, ""); + + if (!path.empty()) + { + path = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "settings_autocorrect.xml"); + } + return path; +} +LLSD AutoCorrect::exportList(std::string listName) +{ + LLSD toReturn; + if(mAutoCorrects.has(listName)) + { + toReturn["listName"]=listName; + toReturn["data"]=mAutoCorrects[listName]["data"]; + toReturn["author"]=mAutoCorrects[listName]["author"]; + toReturn["wordStyle"]=mAutoCorrects[listName]["wordStyle"]; + toReturn["priority"]=mAutoCorrects[listName]["priority"]; + } + return toReturn; +} +BOOL AutoCorrect::addCorrectionList(LLSD newList) +{ + if(newList.has("listName")) + { + std::string name = newList["listName"]; + //if(!mAutoCorrects.has(name)){ + LLSD newPart; + newPart["data"]=newList["data"]; + newPart["enabled"]=TRUE; + newPart["announce"]=FALSE; + newPart["author"]=newList["author"]; + newPart["wordStyle"]=newList["wordStyle"]; + newPart["priority"]=newList["priority"].asInteger(); + llinfos << "adding new list with settings priority "<fileExists(filename)) + { + std::string defaultName = getDefaultFileName(); + llinfos << " user settings file doesnt exist, going to try and read default one from "<fileExists(defaultName)) + { + LLSD blankllsd; + llifstream file; + file.open(defaultName.c_str()); + if (file.is_open()) + { + LLSDSerialize::fromXMLDocument(blankllsd, file); + } + file.close(); + saveToDisk(blankllsd); + }else + saveToDisk(getExampleLLSD()); + } + else + { + llifstream file; + file.open(filename.c_str()); + if (file.is_open()) + { + LLSDSerialize::fromXML(mAutoCorrects, file); + } + file.close(); + } +} +void AutoCorrect::saveToDisk(LLSD newSettings) +{ + mAutoCorrects=newSettings; + std::string filename=getFileName(); + llofstream file; + file.open(filename.c_str()); + LLSDSerialize::toPrettyXML(mAutoCorrects, file); + file.close(); +} +void AutoCorrect::runTest() +{ + std::string startS("He just abandonned all his abilties"); + std::string endS = replaceWords(startS); + llinfos << "!!! Test of autoreplace; start with "< doAnything(gSavedSettings, "EnableAutoCorrect"); + if(!(doAnything))return currentWord; + //loop through priorities + for(int currentPriority = 10;currentPriority>=0;currentPriority--) + { + LLSD::map_const_iterator loc_it = mAutoCorrects.beginMap(); + LLSD::map_const_iterator loc_end = mAutoCorrects.endMap(); + for ( ; loc_it != loc_end; ++loc_it) + { + const std::string& location = (*loc_it).first; + //llinfos << "location is "< " << replacement.c_str() << llendl; + return replacement; + } + } + } + } + return currentWord; +} +std::string AutoCorrect::replaceWords(std::string words) +{ + static LLCachedControl doAnything(gSavedSettings, "EnableAutoCorrect"); + if(!(doAnything))return words; + //TODO update this function to use the "wordStyle" thing, + //but so far this function is never used, so later + + boost_tokenizer tokens(words, boost::char_separator(" ")); + for (boost_tokenizer::iterator token_iter = tokens.begin(); token_iter != tokens.end(); ++token_iter) + { + std::string currentWord(*token_iter); + LLSD::map_const_iterator loc_it = mAutoCorrects.beginMap(); + LLSD::map_const_iterator loc_end = mAutoCorrects.endMap(); + for ( ; loc_it != loc_end; ++loc_it) + { + const std::string& location = (*loc_it).first; + //llinfos << "location is "< " << replacement.c_str() << llendl; + int wordStart = words.find(currentWord); + words.replace(wordStart,currentWord.length(),replacement); + return replaceWords(words);//lol recursion! + } + } + } + return words; +} +BOOL AutoCorrect::addEntryToList(std::string wrong, std::string right, std::string listName) +{ + // *HACK: Make sure the "Custom" list exists, because the design of this + // system prevents us from updating it by changing the original file... + if(mAutoCorrects.has(listName)) + { + mAutoCorrects[listName]["data"][wrong]=right; + return TRUE; + } + else if(listName == "Custom") + { + mAutoCorrects[listName]["announce"] = 0; + mAutoCorrects[listName]["author"] = "You"; + mAutoCorrects[listName]["data"][wrong] = right; + mAutoCorrects[listName]["enabled"] = 1; + mAutoCorrects[listName]["priority"] = 10; + mAutoCorrects[listName]["wordStyle"] = 1; + return TRUE; + } + + return FALSE; +} +BOOL AutoCorrect::removeEntryFromList(std::string wrong, std::string listName) +{ + if(mAutoCorrects.has(listName)) + { + if(mAutoCorrects[listName]["data"].has(wrong)) + { + mAutoCorrects[listName]["data"].erase(wrong); + return TRUE; + } + } + return FALSE; +} + +LLSD AutoCorrect::getExampleLLSD() +{ + LLSD toReturn; + + LLSD listone; + LLSD listtwo; + + LLSD itemOne; + itemOne["wrong"]="wrong1"; + itemOne["right"]="right1"; + listone[0]=itemOne; + + LLSD itemTwo; + itemTwo["wrong"]="wrong2"; + itemTwo["right"]="right2"; + listone[1]=itemTwo; + + toReturn["listOne"]=listone; + + + itemOne["wrong"]="secondwrong1"; + itemOne["right"]="secondright1"; + listone[0]=itemOne; + + itemTwo["wrong"]="secondwrong2"; + itemTwo["right"]="secondright2"; + listone[1]=itemTwo; + + toReturn["listTwo"]=listone; + + return toReturn; +} + diff --git a/indra/newview/llautocorrect.h b/indra/newview/llautocorrect.h new file mode 100644 index 0000000000..ed8e819ca1 --- /dev/null +++ b/indra/newview/llautocorrect.h @@ -0,0 +1,60 @@ +/** + * @file llautocorrect.h + * @brief Auto Correct Manager + * @copyright Copyright (c) 2011 LordGregGreg Back + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +#ifndef AUTO_CORRECT +#define AUTO_CORRECT +class AutoCorrect +{ + AutoCorrect(); + ~AutoCorrect(); + static AutoCorrect* sInstance; +public: + static AutoCorrect* getInstance(); + BOOL addCorrectionList(LLSD newList); + BOOL removeCorrectionList(std::string listName); + BOOL setListEnabled(std::string listName, BOOL enabled); + BOOL setListAnnounceeState(std::string listName, BOOL announce); + BOOL setListPriority(std::string listName, int priority); + BOOL setListStyle(std::string listName, BOOL announce); + std::string replaceWords(std::string words); + std::string replaceWord(std::string currentWord); + BOOL addEntryToList(std::string wrong, std::string right, std::string listName); + BOOL removeEntryFromList(std::string wrong, std::string listName); + BOOL saveListToDisk(std::string listName, std::string fileName); + LLSD exportList(std::string listName); + void runTest(); + LLSD getAutoCorrects(); + LLSD getAutoCorrectEntries(std::string listName); + void save(); + + void loadFromDisk(); + +private: + void saveToDisk(LLSD newSettings); + LLSD getExampleLLSD(); + std::string getFileName(); + std::string getDefaultFileName(); + + LLSD mAutoCorrects; + +}; + + + +#endif diff --git a/indra/newview/llautocorrectfloater.cpp b/indra/newview/llautocorrectfloater.cpp new file mode 100644 index 0000000000..6dca759b02 --- /dev/null +++ b/indra/newview/llautocorrectfloater.cpp @@ -0,0 +1,384 @@ +/** + * @file llautocorrectfloater.cpp + * @brief Auto Correct List floater + * @copyright Copyright (c) 2011 LordGregGreg Back + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "llviewerprecompiledheaders.h" + +#include "llautocorrectfloater.h" + +#include "llagentdata.h" +#include "llcommandhandler.h" +#include "llfloater.h" +#include "lluictrlfactory.h" +#include "llagent.h" +#include "llpanel.h" +#include "llbutton.h" +#include "llcolorswatch.h" +#include "llcombobox.h" +#include "llview.h" +#include "llhttpclient.h" +#include "llbufferstream.h" +#include "llcheckboxctrl.h" +#include "llviewercontrol.h" + +#include "llui.h" +#include "llcontrol.h" +#include "llscrollingpanellist.h" +#include "llautocorrect.h" +#include "llfilepicker.h" +#include "llfile.h" +#include "llsdserialize.h" +//#include "llfloaterchat.h" +#include "llchat.h" +#include "llinventorymodel.h" +#include "llhost.h" +#include "llassetstorage.h" +#include "roles_constants.h" +#include "llviewertexteditor.h" +#include + +#include +#include "llfloaterreg.h" +#include "llinspecttoast.h" +#include "llnotificationhandler.h" +#include "llnotificationmanager.h" + + +AutoCorrectFloater::AutoCorrectFloater(const LLSD& key) : +LLFloater(key) +{ +} +void AutoCorrectFloater::onClose(bool app_quitting) +{ + destroy(); +} + +BOOL AutoCorrectFloater::postBuild(void) +{ + + namesList = getChild("ac_list_name"); + entryList = getChild("ac_list_entry"); + + childSetCommitCallback("ac_enable",onBoxCommitEnabled,this); + + childSetCommitCallback("ac_list_enabled",onEntrySettingChange,this); + childSetCommitCallback("ac_list_show",onEntrySettingChange,this); + childSetCommitCallback("ac_list_style",onEntrySettingChange,this); + childSetCommitCallback("ac_priority",onEntrySettingChange,this); + + + + updateEnabledStuff(); + updateNamesList(); + + + namesList->setCommitOnSelectionChange(TRUE); + childSetCommitCallback("ac_list_name", onSelectName, this); + + childSetAction("ac_deletelist",removeList,this); + childSetAction("ac_rementry",deleteEntry,this); + childSetAction("ac_exportlist",exportList,this); + childSetAction("ac_addentry",addEntry,this); + childSetAction("ac_loadlist",loadList,this); + + return true; +} + +void AutoCorrectFloater::onSelectName(LLUICtrl* ctrl, void* user_data) +{ + if ( user_data ) + { + AutoCorrectFloater* self = ( AutoCorrectFloater* )user_data; + if ( self ) + self->updateItemsList(); + } + +} +void AutoCorrectFloater::updateItemsList() +{ + entryList->deleteAllItems(); + if((namesList->getAllSelected().size())<=0) + { + + updateListControlsEnabled(FALSE); + return; + } + + updateListControlsEnabled(TRUE); + std::string listName= namesList->getFirstSelected()->getColumn(0)->getValue().asString(); + + LLSD listData = AutoCorrect::getInstance()->getAutoCorrectEntries(listName); + childSetValue("ac_list_enabled",listData["enabled"].asBoolean()); + childSetValue("ac_list_style",listData["wordStyle"].asBoolean()); + childSetValue("ac_list_show",listData["announce"].asBoolean()); + childSetValue("ac_text_name",listName); + childSetValue("ac_text_author",listData["author"]); + childSetValue("ac_priority",listData["priority"]); + static LLCachedControl countAuto(gSavedSettings, "AutoCorrectCount"); + childSetValue("ac_stats",(S32)countAuto); + + LLSD autoCorrects = listData["data"]; + LLSD::map_const_iterator loc_it = autoCorrects.beginMap(); + LLSD::map_const_iterator loc_end = autoCorrects.endMap(); + for ( ; loc_it != loc_end; ++loc_it) + { + const std::string& wrong = (*loc_it).first; + const std::string& right = (*loc_it).second; + + //std::string lentry(wrong+"=>"+right); + + LLSD element; + element["id"] = wrong; + LLSD& s_column = element["columns"][0]; + s_column["column"] = "Search"; + s_column["value"] = wrong; + s_column["font"] = "SANSSERIF"; + LLSD& r_column = element["columns"][1]; + r_column["column"] = "Replace"; + r_column["value"] = right; + r_column["font"] = "SANSSERIF"; + + entryList->addElement(element, ADD_BOTTOM); + } + +} +void AutoCorrectFloater::updateNamesList() +{ + namesList->deleteAllItems(); + static LLCachedControl enabledd(gSavedSettings, "EnableAutoCorrect"); + if(!(enabledd)) + { + updateItemsList(); + return; + } + static LLCachedControl countAuto(gSavedSettings, "AutoCorrectCount"); + childSetValue("ac_stats",(S32)countAuto); + LLSD autoCorrects = AutoCorrect::getInstance()->getAutoCorrects(); + LLSD::map_const_iterator loc_it = autoCorrects.beginMap(); + LLSD::map_const_iterator loc_end = autoCorrects.endMap(); + for ( ; loc_it != loc_end; ++loc_it) + { + const std::string& listName = (*loc_it).first; + + LLSD element; + element["id"] = listName; + LLSD& friend_column = element["columns"][0]; + friend_column["column"] = "Entries"; + friend_column["value"] = listName; + //friend_column["font"] = "SANSSERIF"; + const LLSD& loc_map = (*loc_it).second; + if(loc_map["enabled"].asBoolean()) + friend_column["font"] = "SANSSERIF"; + //friend_column["style"] = "BOLD"; + else + friend_column["font"] = "SANSSERIF_SMALL"; + //friend_column["style"] = "NORMAL"; + if(namesList) + namesList->addElement(element, ADD_BOTTOM); + } + updateItemsList(); +} +void AutoCorrectFloater::updateListControlsEnabled(BOOL selected) +{ + + childSetEnabled("ac_text1",selected); + childSetEnabled("ac_text2",selected); + childSetEnabled("ac_text_name",selected); + childSetEnabled("ac_text_author",selected); + childSetEnabled("ac_list_enabled",selected); + childSetEnabled("ac_list_show",selected); + childSetEnabled("ac_list_style",selected); + childSetEnabled("ac_deletelist",selected); + childSetEnabled("ac_exportlist",selected); + childSetEnabled("ac_addentry",selected); + childSetEnabled("ac_rementry",selected); + childSetEnabled("ac_priority",selected); + +} +void AutoCorrectFloater::updateEnabledStuff() +{ + static LLCachedControl enabledd(gSavedSettings, "EnableAutoCorrect"); + if(!(enabledd)) + { + LLCheckBoxCtrl *enBox = getChild("ac_enable"); + enBox->setDisabledColor(LLColor4::red); + getChild("ac_enable")->setEnabledColor(LLColor4(1.0f,0.0f,0.0f,1.0f)); + }else + { + getChild("ac_enable")->setEnabledColor( + LLUIColorTable::instance().getColor( "LabelTextColor" )); + } + + childSetEnabled("ac_list_name",enabledd); + childSetEnabled("ac_list_entry",enabledd); + updateListControlsEnabled(enabledd); + updateNamesList(); + AutoCorrect::getInstance()->save(); + +} +void AutoCorrectFloater::setData(void * data) +{ + //empanel = (LLPanel*)data; +} +void AutoCorrectFloater::onBoxCommitEnabled(LLUICtrl* caller, void* user_data) +{ + if ( user_data ) + { + AutoCorrectFloater* self = ( AutoCorrectFloater* )user_data; + if ( self ) + { + self->updateEnabledStuff(); + } + } +} +void AutoCorrectFloater::onEntrySettingChange(LLUICtrl* caller, void* user_data) +{ + if ( user_data ) + { + AutoCorrectFloater* self = ( AutoCorrectFloater* )user_data; + if ( self ) + { + std::string listName= self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); + AutoCorrect::getInstance()->setListEnabled(listName,self->childGetValue("ac_list_enabled").asBoolean()); + AutoCorrect::getInstance()->setListAnnounceeState(listName,self->childGetValue("ac_list_show").asBoolean()); + AutoCorrect::getInstance()->setListStyle(listName,self->childGetValue("ac_list_style").asBoolean()); + AutoCorrect::getInstance()->setListPriority(listName,self->childGetValue("ac_priority").asInteger()); + + //sInstance->updateEnabledStuff(); + self->updateItemsList(); + AutoCorrect::getInstance()->save(); + } + } +} +void AutoCorrectFloater::deleteEntry(void* data) +{ + if ( data ) + { + AutoCorrectFloater* self = ( AutoCorrectFloater* )data; + if ( self ) + { + + std::string listName=self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); + + if((self->entryList->getAllSelected().size())>0) + { + std::string wrong= self->entryList->getFirstSelected()->getColumn(0)->getValue().asString(); + AutoCorrect::getInstance()->removeEntryFromList(wrong,listName); + self->updateItemsList(); + AutoCorrect::getInstance()->save(); + } + } + } +} +void AutoCorrectFloater::loadList(void* data) +{ + LLFilePicker& picker = LLFilePicker::instance(); + + if(!picker.getOpenFile( LLFilePicker::FFLOAD_XML) ) + {return; + } + llifstream file; + file.open(picker.getFirstFile().c_str()); + LLSD blankllsd; + if (file.is_open()) + { + LLSDSerialize::fromXMLDocument(blankllsd, file); + } + file.close(); + gSavedSettings.setBOOL("EnableAutoCorrect",true); + AutoCorrect::getInstance()->addCorrectionList(blankllsd); + if ( data ) + { + AutoCorrectFloater* self = ( AutoCorrectFloater* )data; + if ( self ) + self->updateEnabledStuff(); + } +} +void AutoCorrectFloater::removeList(void* data) +{ + if ( data ) + { + AutoCorrectFloater* self = ( AutoCorrectFloater* )data; + if ( self ) + { + std::string listName= self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); + AutoCorrect::getInstance()->removeCorrectionList(listName); + self->updateEnabledStuff(); + } + + } +} +void AutoCorrectFloater::exportList(void *data) +{ + if ( data ) + { + AutoCorrectFloater* self = ( AutoCorrectFloater* )data; + if ( self ) + { + std::string listName=self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); + + LLFilePicker& picker = LLFilePicker::instance(); + + if(!picker.getSaveFile( LLFilePicker::FFSAVE_XML) ) + {return; + } + llofstream file; + file.open(picker.getFirstFile().c_str()); + LLSDSerialize::toPrettyXML(AutoCorrect::getInstance()->exportList(listName), file); + file.close(); + } + + } +} +void AutoCorrectFloater::addEntry(void* data) +{ + if ( data ) + { + AutoCorrectFloater* self = ( AutoCorrectFloater* )data; + if ( self ) + { + std::string listName= self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); + LLChat chat; + chat.mText ="To add an entry, please type in chat \""+gSavedSettings.getString("CmdLineAutocorrect")+" "+listName+"|wrongWord|rightWord\""; + + chat.mSourceType = CHAT_SOURCE_SYSTEM; + LLSD args; + args["type"] = LLNotificationsUI::NT_NEARBYCHAT; + LLNotificationsUI::LLNotificationManager::instance().onChat(chat, args); + + } + } + +} +AutoCorrectFloater* AutoCorrectFloater::showFloater() +{ + AutoCorrectFloater *floater = dynamic_cast(LLFloaterReg::getInstance("autocorrect")); + if(floater) + { + floater->setVisible(true); + floater->setFrontmost(true); + floater->center(); + return floater; + } + else + { + LL_WARNS("AutoCorrect") << "Can't find floater!" << LL_ENDL; + return NULL; + } +} diff --git a/indra/newview/llautocorrectfloater.h b/indra/newview/llautocorrectfloater.h new file mode 100644 index 0000000000..bec7161d1a --- /dev/null +++ b/indra/newview/llautocorrectfloater.h @@ -0,0 +1,67 @@ +/** + * @file llautocorrectfloater.h + * @brief Auto Correct List floater + * @copyright Copyright (c) 2011 LordGregGreg Back + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef AUTOCORRECTFLOATER_H +#define AUTOCORRECTFLOATER_H + +#include "llfloater.h" +#include "llmediactrl.h" +#include "llscrolllistctrl.h" + +#include "llviewerinventory.h" +#include + +class AutoCorrectFloater : +public LLFloater +{ +public: + AutoCorrectFloater(const LLSD& key); + + /*virtual*/ BOOL postBuild(); + /*virtual*/ void onClose(bool app_quitting); + + static AutoCorrectFloater* showFloater(); + + void setData(void * data); + void updateEnabledStuff(); + void updateNamesList(); + void updateListControlsEnabled(BOOL selected); + void updateItemsList(); + + LLScrollListCtrl *namesList; + LLScrollListCtrl *entryList; + //LLPanel * empanel; +private: + //static JCInvDropTarget* mNotecardDropTarget; + static void onBoxCommitEnabled(LLUICtrl* caller, void* user_data); + static void onEntrySettingChange(LLUICtrl* caller, void* user_data); + static void onSelectName(LLUICtrl* caller, void* user_data); + //static void ResponseItemDrop(LLViewerInventoryItem* item); + //static void onNotecardLoadComplete(LLVFS *vfs,const LLUUID& asset_uuid,LLAssetType::EType type,void* user_data, S32 status, LLExtStat ext_status); + + + static void deleteEntry(void* data); + static void addEntry(void* data); + static void exportList(void* data); + static void removeList(void* data); + static void loadList(void* data); +}; + +#endif // AUTOCORRECTFLOATER_H diff --git a/indra/newview/llfloaterpreference.cpp b/indra/newview/llfloaterpreference.cpp index a333989e7e..368d8f1efe 100755 --- a/indra/newview/llfloaterpreference.cpp +++ b/indra/newview/llfloaterpreference.cpp @@ -35,7 +35,7 @@ #include "llfloaterpreference.h" #include "message.h" - +#include "llautocorrectfloater.h" #include "llagent.h" #include "llavatarconstants.h" #include "llcheckboxctrl.h" @@ -354,6 +354,8 @@ LLFloaterPreference::LLFloaterPreference(const LLSD& key) gSavedSettings.getControl("NameTagShowUsernames")->getCommitSignal()->connect(boost::bind(&handleNameTagOptionChanged, _2)); gSavedSettings.getControl("NameTagShowFriends")->getCommitSignal()->connect(boost::bind(&handleNameTagOptionChanged, _2)); gSavedSettings.getControl("UseDisplayNames")->getCommitSignal()->connect(boost::bind(&handleDisplayNamesOptionChanged, _2)); + + mCommitCallbackRegistrar.add("Pref.ShowAC", boost::bind(&AutoCorrectFloater::showFloater)); LLAvatarPropertiesProcessor::getInstance()->addObserver( gAgent.getID(), this ); } diff --git a/indra/newview/llviewerfloaterreg.cpp b/indra/newview/llviewerfloaterreg.cpp index 8406f639df..3d33125b6a 100644 --- a/indra/newview/llviewerfloaterreg.cpp +++ b/indra/newview/llviewerfloaterreg.cpp @@ -30,7 +30,7 @@ #include "llfloaterreg.h" #include "llviewerfloaterreg.h" - +#include "llautocorrectfloater.h" #include "llcompilequeue.h" #include "llcallfloater.h" #include "llfasttimerview.h" @@ -169,6 +169,7 @@ void LLViewerFloaterReg::registerFloaters() LLFloaterReg::add("about_land", "floater_about_land.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("appearance", "floater_my_appearance.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("auction", "floater_auction.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); + LLFloaterReg::add("autocorrect", "floater_autocorrect.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("avatar", "floater_avatar.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("avatar_picker", "floater_avatar_picker.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("avatar_textures", "floater_avatar_textures.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); diff --git a/indra/newview/skins/default/xui/en/floater_autocorrect.xml b/indra/newview/skins/default/xui/en/floater_autocorrect.xml new file mode 100644 index 0000000000..0b8ed1c067 --- /dev/null +++ b/indra/newview/skins/default/xui/en/floater_autocorrect.xml @@ -0,0 +1,83 @@ + + + + - \ No newline at end of file + + -- cgit v1.2.3 From 14c09c3ce597e47f5c41bb45246e89a1f31d89b0 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Wed, 21 Dec 2011 10:06:26 -0500 Subject: Add unit-test module for LLProcessLauncher. As always with llcommon, this is expressed as an "integration test" to sidestep a circular dependency: the llcommon build depends on its unit tests, but all our unit tests depend on llcommon. Initial test code is more for human verification than automated verification: does APR's child-process management in fact support nonblocking operations? --- indra/llcommon/CMakeLists.txt | 1 + indra/llcommon/tests/llprocesslauncher_test.cpp | 144 ++++++++++++++++++++++++ 2 files changed, 145 insertions(+) create mode 100644 indra/llcommon/tests/llprocesslauncher_test.cpp (limited to 'indra') diff --git a/indra/llcommon/CMakeLists.txt b/indra/llcommon/CMakeLists.txt index 0a3eaec5c5..c8e1827584 100644 --- a/indra/llcommon/CMakeLists.txt +++ b/indra/llcommon/CMakeLists.txt @@ -326,6 +326,7 @@ if (LL_TESTS) LL_ADD_INTEGRATION_TEST(reflection "" "${test_libs}") LL_ADD_INTEGRATION_TEST(stringize "" "${test_libs}") LL_ADD_INTEGRATION_TEST(lleventdispatcher "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(llprocesslauncher "" "${test_libs}") # *TODO - reenable these once tcmalloc libs no longer break the build. #ADD_BUILD_TEST(llallocator llcommon) diff --git a/indra/llcommon/tests/llprocesslauncher_test.cpp b/indra/llcommon/tests/llprocesslauncher_test.cpp new file mode 100644 index 0000000000..3b5602f620 --- /dev/null +++ b/indra/llcommon/tests/llprocesslauncher_test.cpp @@ -0,0 +1,144 @@ +/** + * @file llprocesslauncher_test.cpp + * @author Nat Goodspeed + * @date 2011-12-19 + * @brief Test for llprocesslauncher. + * + * $LicenseInfo:firstyear=2011&license=viewerlgpl$ + * Copyright (c) 2011, Linden Research, Inc. + * $/LicenseInfo$ + */ + +// Precompiled header +#include "linden_common.h" +// associated header +#include "llprocesslauncher.h" +// STL headers +#include +// std headers +// external library headers +#include "llapr.h" +#include "apr_thread_proc.h" +#include "apr_file_io.h" +// other Linden headers +#include "../test/lltut.h" + +class APR +{ +public: + APR(): + pool(NULL) + { + apr_initialize(); + apr_pool_create(&pool, NULL); + } + + ~APR() + { + apr_terminate(); + } + + std::string strerror(apr_status_t rv) + { + char errbuf[256]; + apr_strerror(rv, errbuf, sizeof(errbuf)); + return errbuf; + } + + apr_pool_t *pool; +}; + +/***************************************************************************** +* TUT +*****************************************************************************/ +namespace tut +{ + struct llprocesslauncher_data + { + void aprchk(apr_status_t rv) + { + ensure_equals(apr.strerror(rv), rv, APR_SUCCESS); + } + + APR apr; + }; + typedef test_group llprocesslauncher_group; + typedef llprocesslauncher_group::object object; + llprocesslauncher_group llprocesslaunchergrp("llprocesslauncher"); + + template<> template<> + void object::test<1>() + { + set_test_name("raw APR nonblocking I/O"); + + apr_procattr_t *procattr = NULL; + aprchk(apr_procattr_create(&procattr, apr.pool)); + aprchk(apr_procattr_io_set(procattr, APR_CHILD_BLOCK, APR_CHILD_BLOCK, APR_CHILD_BLOCK)); + aprchk(apr_procattr_cmdtype_set(procattr, APR_PROGRAM_PATH)); + + std::vector argv; + apr_proc_t child; + argv.push_back("python"); + argv.push_back("-c"); + argv.push_back("raise RuntimeError('Hello from Python!')"); + argv.push_back(NULL); + + aprchk(apr_proc_create(&child, argv[0], + static_cast(&argv[0]), + NULL, // if we wanted to pass explicit environment + procattr, + apr.pool)); + + typedef std::pair DescFile; + typedef std::vector DescFileVec; + DescFileVec outfiles; + outfiles.push_back(DescFile("out", child.out)); + outfiles.push_back(DescFile("err", child.err)); + + while (! outfiles.empty()) + { + DescFileVec iterfiles(outfiles); + for (size_t i = 0; i < iterfiles.size(); ++i) + { + char buf[4096]; + + apr_status_t rv = apr_file_gets(buf, sizeof(buf), iterfiles[i].second); + if (APR_STATUS_IS_EOF(rv)) + { + std::cout << "(EOF on " << iterfiles[i].first << ")\n"; + outfiles.erase(outfiles.begin() + i); + continue; + } + if (rv != APR_SUCCESS) + { + std::cout << "(waiting; apr_file_gets(" << iterfiles[i].first << ") => " << rv << ": " << apr.strerror(rv) << ")\n"; + continue; + } + // Is it even possible to get APR_SUCCESS but read 0 bytes? + // Hope not, but defend against that anyway. + if (buf[0]) + { + std::cout << iterfiles[i].first << ": " << buf; + // Just for pretty output... if we only read a partial + // line, terminate it. + if (buf[strlen(buf) - 1] != '\n') + std::cout << "...\n"; + } + } + sleep(1); + } + apr_file_close(child.in); + apr_file_close(child.out); + apr_file_close(child.err); + + int rc = 0; + apr_exit_why_e why; + apr_status_t rv; + while (! APR_STATUS_IS_CHILD_DONE(rv = apr_proc_wait(&child, &rc, &why, APR_NOWAIT))) + { + std::cout << "child not done (" << rv << "): " << apr.strerror(rv) << '\n'; + sleep(0.5); + } + std::cout << "child done: rv = " << rv << " (" << apr.strerror(rv) << "), why = " << why << ", rc = " << rc << '\n'; + } +} // namespace tut -- cgit v1.2.3 From 7832d8eccb00d32b6122e5851238e962f65af1e8 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Wed, 21 Dec 2011 11:12:48 -0500 Subject: Fix llprocesslauncher_test.cpp to work on Windows. --- indra/llcommon/tests/llprocesslauncher_test.cpp | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'indra') diff --git a/indra/llcommon/tests/llprocesslauncher_test.cpp b/indra/llcommon/tests/llprocesslauncher_test.cpp index 3b5602f620..4d14e1be53 100644 --- a/indra/llcommon/tests/llprocesslauncher_test.cpp +++ b/indra/llcommon/tests/llprocesslauncher_test.cpp @@ -12,6 +12,7 @@ // Precompiled header #include "linden_common.h" // associated header +#define WIN32_LEAN_AND_MEAN #include "llprocesslauncher.h" // STL headers #include @@ -23,6 +24,10 @@ // other Linden headers #include "../test/lltut.h" +#if defined(LL_WINDOWS) +#define sleep _sleep +#endif + class APR { public: -- cgit v1.2.3 From 2fd0bc8648e71aa2f141fde4b3a6a0165f7ef4d6 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Wed, 21 Dec 2011 17:00:43 -0500 Subject: Change llprocesslauncher_test.cpp eyeballing to program verification. That is, where before we just flung stuff to stdout with the expectation that a human user would verify, replace with assertions in the test code itself. Quiet previous noise on stdout. Introduce a temp script file that produces output on both stdout and stderr, with sleep() calls so we predictably have to wait for it. Track and then verify the history of our interaction with the child process, noting especially EWOULDBLOCK attempts. --- indra/llcommon/tests/llprocesslauncher_test.cpp | 97 ++++++++++++++++++++++--- 1 file changed, 85 insertions(+), 12 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/tests/llprocesslauncher_test.cpp b/indra/llcommon/tests/llprocesslauncher_test.cpp index 4d14e1be53..ca06b3164e 100644 --- a/indra/llcommon/tests/llprocesslauncher_test.cpp +++ b/indra/llcommon/tests/llprocesslauncher_test.cpp @@ -17,6 +17,7 @@ // STL headers #include // std headers +#include // external library headers #include "llapr.h" #include "apr_thread_proc.h" @@ -71,11 +72,53 @@ namespace tut typedef llprocesslauncher_group::object object; llprocesslauncher_group llprocesslaunchergrp("llprocesslauncher"); + struct Item + { + Item(): tries(0) {} + unsigned tries; + std::string which; + std::string what; + }; + template<> template<> void object::test<1>() { set_test_name("raw APR nonblocking I/O"); + // Create a script file in a temporary place. + const char* tempdir = NULL; + aprchk(apr_temp_dir_get(&tempdir, apr.pool)); + + // Construct a temp filename template in that directory. + char *tempname = NULL; + aprchk(apr_filepath_merge(&tempname, tempdir, "testXXXXXX", 0, apr.pool)); + + // Create a temp file from that template. + apr_file_t* fp = NULL; + aprchk(apr_file_mktemp(&fp, tempname, APR_CREATE | APR_WRITE | APR_EXCL, apr.pool)); + + // Write it. + const char script[] = + "import sys\n" + "import time\n" + "\n" + "time.sleep(2)\n" + "print >>sys.stdout, \"stdout after wait\"\n" + "sys.stdout.flush()\n" + "time.sleep(2)\n" + "print >>sys.stderr, \"stderr after wait\"\n" + "sys.stderr.flush()\n" + ; + apr_size_t len(sizeof(script)-1); + aprchk(apr_file_write(fp, script, &len)); + aprchk(apr_file_close(fp)); + + // Arrange to track the history of our interaction with child: what we + // fetched, which pipe it came from, how many tries it took before we + // got it. + std::vector history; + history.push_back(Item()); + apr_procattr_t *procattr = NULL; aprchk(apr_procattr_create(&procattr, apr.pool)); aprchk(apr_procattr_io_set(procattr, APR_CHILD_BLOCK, APR_CHILD_BLOCK, APR_CHILD_BLOCK)); @@ -84,8 +127,7 @@ namespace tut std::vector argv; apr_proc_t child; argv.push_back("python"); - argv.push_back("-c"); - argv.push_back("raise RuntimeError('Hello from Python!')"); + argv.push_back(tempname); argv.push_back(NULL); aprchk(apr_proc_create(&child, argv[0], @@ -110,24 +152,35 @@ namespace tut apr_status_t rv = apr_file_gets(buf, sizeof(buf), iterfiles[i].second); if (APR_STATUS_IS_EOF(rv)) { - std::cout << "(EOF on " << iterfiles[i].first << ")\n"; +// std::cout << "(EOF on " << iterfiles[i].first << ")\n"; + history.back().which = iterfiles[i].first; + history.back().what = "*eof*"; + history.push_back(Item()); outfiles.erase(outfiles.begin() + i); continue; } - if (rv != APR_SUCCESS) + if (rv == EWOULDBLOCK) { - std::cout << "(waiting; apr_file_gets(" << iterfiles[i].first << ") => " << rv << ": " << apr.strerror(rv) << ")\n"; +// std::cout << "(waiting; apr_file_gets(" << iterfiles[i].first << ") => " << rv << ": " << apr.strerror(rv) << ")\n"; + ++history.back().tries; continue; } + ensure_equals(rv, APR_SUCCESS); // Is it even possible to get APR_SUCCESS but read 0 bytes? // Hope not, but defend against that anyway. if (buf[0]) { - std::cout << iterfiles[i].first << ": " << buf; - // Just for pretty output... if we only read a partial - // line, terminate it. - if (buf[strlen(buf) - 1] != '\n') - std::cout << "...\n"; +// std::cout << iterfiles[i].first << ": " << buf; + history.back().which = iterfiles[i].first; + history.back().what.append(buf); + if (buf[strlen(buf) - 1] == '\n') + history.push_back(Item()); + else + { + // Just for pretty output... if we only read a partial + // line, terminate it. +// std::cout << "...\n"; + } } } sleep(1); @@ -141,9 +194,29 @@ namespace tut apr_status_t rv; while (! APR_STATUS_IS_CHILD_DONE(rv = apr_proc_wait(&child, &rc, &why, APR_NOWAIT))) { - std::cout << "child not done (" << rv << "): " << apr.strerror(rv) << '\n'; +// std::cout << "child not done (" << rv << "): " << apr.strerror(rv) << '\n'; sleep(0.5); } - std::cout << "child done: rv = " << rv << " (" << apr.strerror(rv) << "), why = " << why << ", rc = " << rc << '\n'; +// std::cout << "child done: rv = " << rv << " (" << apr.strerror(rv) << "), why = " << why << ", rc = " << rc << '\n'; + ensure_equals(rv, APR_CHILD_DONE); + ensure_equals(why, APR_PROC_EXIT); + ensure_equals(rc, 0); + + // Remove temp script file + aprchk(apr_file_remove(tempname, apr.pool)); + + // Beyond merely executing all the above successfully, verify that we + // obtained expected output -- and that we duly got control while + // waiting, proving the non-blocking nature of these pipes. + ensure("blocking I/O on child pipe (0)", history[0].tries); + ensure_equals(history[0].which, "out"); + ensure_equals(history[0].what, "stdout after wait\n"); + ensure("blocking I/O on child pipe (1)", history[1].tries); + ensure_equals(history[1].which, "out"); + ensure_equals(history[1].what, "*eof*"); + ensure_equals(history[2].which, "err"); + ensure_equals(history[2].what, "stderr after wait\n"); + ensure_equals(history[3].which, "err"); + ensure_equals(history[3].what, "*eof*"); } } // namespace tut -- cgit v1.2.3 From 25ef0cd2236aeb2d0047881e11a0022c4355cd48 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Wed, 21 Dec 2011 20:42:11 -0500 Subject: Tweak llprocesslauncher_test.cpp to run properly on Windows. Fix EOL issues: "\r\n" vs. "\n". On Windows, requesting a read in nonblocking mode can produce EAGAIN instead of EWOULDBLOCK. --- indra/llcommon/tests/llprocesslauncher_test.cpp | 27 ++++++++++++++----------- 1 file changed, 15 insertions(+), 12 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/tests/llprocesslauncher_test.cpp b/indra/llcommon/tests/llprocesslauncher_test.cpp index ca06b3164e..bdae81770f 100644 --- a/indra/llcommon/tests/llprocesslauncher_test.cpp +++ b/indra/llcommon/tests/llprocesslauncher_test.cpp @@ -27,6 +27,9 @@ #if defined(LL_WINDOWS) #define sleep _sleep +#define EOL "\r\n" +#else +#define EOL "\n" #endif class APR @@ -99,15 +102,15 @@ namespace tut // Write it. const char script[] = - "import sys\n" - "import time\n" - "\n" - "time.sleep(2)\n" - "print >>sys.stdout, \"stdout after wait\"\n" - "sys.stdout.flush()\n" - "time.sleep(2)\n" - "print >>sys.stderr, \"stderr after wait\"\n" - "sys.stderr.flush()\n" + "import sys" EOL + "import time" EOL + EOL + "time.sleep(2)" EOL + "print >>sys.stdout, \"stdout after wait\"" EOL + "sys.stdout.flush()" EOL + "time.sleep(2)" EOL + "print >>sys.stderr, \"stderr after wait\"" EOL + "sys.stderr.flush()" EOL ; apr_size_t len(sizeof(script)-1); aprchk(apr_file_write(fp, script, &len)); @@ -159,7 +162,7 @@ namespace tut outfiles.erase(outfiles.begin() + i); continue; } - if (rv == EWOULDBLOCK) + if (rv == EWOULDBLOCK || rv == EAGAIN) { // std::cout << "(waiting; apr_file_gets(" << iterfiles[i].first << ") => " << rv << ": " << apr.strerror(rv) << ")\n"; ++history.back().tries; @@ -210,12 +213,12 @@ namespace tut // waiting, proving the non-blocking nature of these pipes. ensure("blocking I/O on child pipe (0)", history[0].tries); ensure_equals(history[0].which, "out"); - ensure_equals(history[0].what, "stdout after wait\n"); + ensure_equals(history[0].what, "stdout after wait" EOL); ensure("blocking I/O on child pipe (1)", history[1].tries); ensure_equals(history[1].which, "out"); ensure_equals(history[1].what, "*eof*"); ensure_equals(history[2].which, "err"); - ensure_equals(history[2].what, "stderr after wait\n"); + ensure_equals(history[2].what, "stderr after wait" EOL); ensure_equals(history[3].which, "err"); ensure_equals(history[3].what, "*eof*"); } -- cgit v1.2.3 From 39c3efbda3bc4c7b415aa851ec4f42f05acda0cb Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Thu, 22 Dec 2011 16:20:19 -0500 Subject: Add child_status_callback() function and arrange to call periodically. At least on OS X 10.7, a call to apr_proc_wait(APR_NOWAIT) in fact seems to block the caller. So instead of polling apr_proc_wait(), use APR callback mechanism (apr_proc_other_child_register() et al.) and poll that using apr_proc_other_child_refresh_all(). Evidently this polls the underlying system waitpid(), but the internal call seems to better support nonblocking. On arrival in the child_status_callback(APR_OC_REASON_DEATH) call, though, apr_proc_wait() produces ECHILD: the child process in question has already been reaped. The OS-encoded wait() status does get passed to the callback, but then we have to use OS-dependent macros to tease apart voluntary termination vs. killed by signal... a bit of a hole in APR's abstraction layer. Wrap ensure_equals() calls with a macro to explain which comparison failed. --- indra/llcommon/tests/llprocesslauncher_test.cpp | 161 ++++++++++++++++++++---- 1 file changed, 138 insertions(+), 23 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/tests/llprocesslauncher_test.cpp b/indra/llcommon/tests/llprocesslauncher_test.cpp index bdae81770f..7d67d13960 100644 --- a/indra/llcommon/tests/llprocesslauncher_test.cpp +++ b/indra/llcommon/tests/llprocesslauncher_test.cpp @@ -22,14 +22,17 @@ #include "llapr.h" #include "apr_thread_proc.h" #include "apr_file_io.h" +#include // other Linden headers #include "../test/lltut.h" +#include "stringize.h" #if defined(LL_WINDOWS) #define sleep _sleep #define EOL "\r\n" #else #define EOL "\n" +#include #endif class APR @@ -57,6 +60,10 @@ public: apr_pool_t *pool; }; +#define ensure_equals_(left, right) \ + ensure_equals(STRINGIZE(#left << " != " << #right), (left), (right)) +#define aprchk(expr) aprchk_(#expr, (expr)) + /***************************************************************************** * TUT *****************************************************************************/ @@ -64,9 +71,10 @@ namespace tut { struct llprocesslauncher_data { - void aprchk(apr_status_t rv) + void aprchk_(const char* call, apr_status_t rv) { - ensure_equals(apr.strerror(rv), rv, APR_SUCCESS); + ensure_equals(STRINGIZE(call << " => " << rv << ": " << apr.strerror(rv)), + rv, APR_SUCCESS); } APR apr; @@ -83,6 +91,91 @@ namespace tut std::string what; }; +#define tabent(symbol) { symbol, #symbol } + static struct ReasonCode + { + int code; + const char* name; + } reasons[] = + { + tabent(APR_OC_REASON_DEATH), + tabent(APR_OC_REASON_UNWRITABLE), + tabent(APR_OC_REASON_RESTART), + tabent(APR_OC_REASON_UNREGISTER), + tabent(APR_OC_REASON_LOST), + tabent(APR_OC_REASON_RUNNING) + }; +#undef tabent + + struct WaitInfo + { + WaitInfo(apr_proc_t* child_): + child(child_), + rv(-1), // we haven't yet called apr_proc_wait() + rc(0), + why(apr_exit_why_e(0)) + {} + apr_proc_t* child; // which subprocess + apr_status_t rv; // return from apr_proc_wait() + int rc; // child's exit code + apr_exit_why_e why; // APR_PROC_EXIT, APR_PROC_SIGNAL, APR_PROC_SIGNAL_CORE + }; + + void child_status_callback(int reason, void* data, int status) + { + std::string reason_str; + BOOST_FOREACH(const ReasonCode& rcp, reasons) + { + if (reason == rcp.code) + { + reason_str = rcp.name; + break; + } + } + if (reason_str.empty()) + { + reason_str = STRINGIZE("unknown reason " << reason); + } + std::cout << "child_status_callback(" << reason_str << ")\n"; + + if (reason == APR_OC_REASON_DEATH || reason == APR_OC_REASON_LOST) + { + // Somewhat oddly, APR requires that you explicitly unregister + // even when it already knows the child has terminated. + apr_proc_other_child_unregister(data); + + WaitInfo* wi(static_cast(data)); + wi->rv = apr_proc_wait(wi->child, &wi->rc, &wi->why, APR_NOWAIT); + if (wi->rv == ECHILD) + { + std::cout << "apr_proc_wait() got ECHILD during child_status_callback(" + << reason_str << ")\n"; + // So -- is this why we have a 'status' param? + wi->rv = APR_CHILD_DONE; // pretend this call worked; fake results +#if defined(LL_WINDOWS) + wi->why = APR_PROC_EXIT; + wi->rc = status; // correct?? +#else // Posix + if (WIFEXITED(status)) + { + wi->why = APR_PROC_EXIT; + wi->rc = WEXITSTATUS(status); + } + else if (WIFSIGNALED(status)) + { + wi->why = APR_PROC_SIGNAL; + wi->rc = WTERMSIG(status); + } + else // uh, shouldn't happen? + { + wi->why = APR_PROC_EXIT; + wi->rc = status; // someone else will have to decode + } +#endif // Posix + } + } + } + template<> template<> void object::test<1>() { @@ -106,10 +199,10 @@ namespace tut "import time" EOL EOL "time.sleep(2)" EOL - "print >>sys.stdout, \"stdout after wait\"" EOL + "print >>sys.stdout, 'stdout after wait'" EOL "sys.stdout.flush()" EOL "time.sleep(2)" EOL - "print >>sys.stderr, \"stderr after wait\"" EOL + "print >>sys.stderr, 'stderr after wait'" EOL "sys.stderr.flush()" EOL ; apr_size_t len(sizeof(script)-1); @@ -122,6 +215,7 @@ namespace tut std::vector history; history.push_back(Item()); + // Run the child process. apr_procattr_t *procattr = NULL; aprchk(apr_procattr_create(&procattr, apr.pool)); aprchk(apr_procattr_io_set(procattr, APR_CHILD_BLOCK, APR_CHILD_BLOCK, APR_CHILD_BLOCK)); @@ -134,11 +228,23 @@ namespace tut argv.push_back(NULL); aprchk(apr_proc_create(&child, argv[0], - static_cast(&argv[0]), + &argv[0], NULL, // if we wanted to pass explicit environment procattr, apr.pool)); + // We do not want this child process to outlive our APR pool. On + // destruction of the pool, forcibly kill the process. Tell APR to try + // SIGTERM and wait 3 seconds. If that didn't work, use SIGKILL. + apr_pool_note_subprocess(apr.pool, &child, APR_KILL_AFTER_TIMEOUT); + + // arrange to call child_status_callback() + WaitInfo wi(&child); + apr_proc_other_child_register(&child, child_status_callback, &wi, child.in, apr.pool); + + // Monitor two different output pipes. Because one will be closed + // before the other, keep them in a vector so we can drop whichever of + // them is closed first. typedef std::pair DescFile; typedef std::vector DescFileVec; DescFileVec outfiles; @@ -168,7 +274,7 @@ namespace tut ++history.back().tries; continue; } - ensure_equals(rv, APR_SUCCESS); + aprchk_("apr_file_gets(buf, sizeof(buf), iterfiles[i].second)", rv); // Is it even possible to get APR_SUCCESS but read 0 bytes? // Hope not, but defend against that anyway. if (buf[0]) @@ -186,24 +292,33 @@ namespace tut } } } + // Do this once per tick, as we expect the viewer will + apr_proc_other_child_refresh_all(APR_OC_REASON_RUNNING); sleep(1); } apr_file_close(child.in); apr_file_close(child.out); apr_file_close(child.err); - int rc = 0; - apr_exit_why_e why; - apr_status_t rv; - while (! APR_STATUS_IS_CHILD_DONE(rv = apr_proc_wait(&child, &rc, &why, APR_NOWAIT))) + // Okay, we've broken the loop because our pipes are all closed. If we + // haven't yet called wait, give the callback one more chance. This + // models the fact that unlike this small test program, the viewer + // will still be running. + if (wi.rv == -1) + { + std::cout << "last gasp apr_proc_other_child_refresh_all()\n"; + apr_proc_other_child_refresh_all(APR_OC_REASON_RUNNING); + } + + if (wi.rv == -1) { -// std::cout << "child not done (" << rv << "): " << apr.strerror(rv) << '\n'; - sleep(0.5); + std::cout << "child_status_callback() wasn't called\n"; + wi.rv = apr_proc_wait(wi.child, &wi.rc, &wi.why, APR_NOWAIT); } // std::cout << "child done: rv = " << rv << " (" << apr.strerror(rv) << "), why = " << why << ", rc = " << rc << '\n'; - ensure_equals(rv, APR_CHILD_DONE); - ensure_equals(why, APR_PROC_EXIT); - ensure_equals(rc, 0); + ensure_equals_(wi.rv, APR_CHILD_DONE); + ensure_equals_(wi.why, APR_PROC_EXIT); + ensure_equals_(wi.rc, 0); // Remove temp script file aprchk(apr_file_remove(tempname, apr.pool)); @@ -212,14 +327,14 @@ namespace tut // obtained expected output -- and that we duly got control while // waiting, proving the non-blocking nature of these pipes. ensure("blocking I/O on child pipe (0)", history[0].tries); - ensure_equals(history[0].which, "out"); - ensure_equals(history[0].what, "stdout after wait" EOL); + ensure_equals_(history[0].which, "out"); + ensure_equals_(history[0].what, "stdout after wait" EOL); ensure("blocking I/O on child pipe (1)", history[1].tries); - ensure_equals(history[1].which, "out"); - ensure_equals(history[1].what, "*eof*"); - ensure_equals(history[2].which, "err"); - ensure_equals(history[2].what, "stderr after wait" EOL); - ensure_equals(history[3].which, "err"); - ensure_equals(history[3].what, "*eof*"); + ensure_equals_(history[1].which, "out"); + ensure_equals_(history[1].what, "*eof*"); + ensure_equals_(history[2].which, "err"); + ensure_equals_(history[2].what, "stderr after wait" EOL); + ensure_equals_(history[3].which, "err"); + ensure_equals_(history[3].what, "*eof*"); } } // namespace tut -- cgit v1.2.3 From 6ccba8810102cc13def8057a82463c9787b21e57 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Thu, 22 Dec 2011 17:18:02 -0500 Subject: Never call apr_proc_wait() inside child_status_callback(). Quiet the temporary child_status_callback() output. Add a bit of diagnostic info if apr_proc_wait() returns anything but APR_CHILD_DONE. --- indra/llcommon/tests/llprocesslauncher_test.cpp | 57 +++++++++++++------------ 1 file changed, 29 insertions(+), 28 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/tests/llprocesslauncher_test.cpp b/indra/llcommon/tests/llprocesslauncher_test.cpp index 7d67d13960..bd7666313e 100644 --- a/indra/llcommon/tests/llprocesslauncher_test.cpp +++ b/indra/llcommon/tests/llprocesslauncher_test.cpp @@ -71,10 +71,10 @@ namespace tut { struct llprocesslauncher_data { - void aprchk_(const char* call, apr_status_t rv) + void aprchk_(const char* call, apr_status_t rv, apr_status_t expected=APR_SUCCESS) { ensure_equals(STRINGIZE(call << " => " << rv << ": " << apr.strerror(rv)), - rv, APR_SUCCESS); + rv, expected); } APR apr; @@ -123,6 +123,7 @@ namespace tut void child_status_callback(int reason, void* data, int status) { +/*==========================================================================*| std::string reason_str; BOOST_FOREACH(const ReasonCode& rcp, reasons) { @@ -137,6 +138,7 @@ namespace tut reason_str = STRINGIZE("unknown reason " << reason); } std::cout << "child_status_callback(" << reason_str << ")\n"; +|*==========================================================================*/ if (reason == APR_OC_REASON_DEATH || reason == APR_OC_REASON_LOST) { @@ -145,34 +147,33 @@ namespace tut apr_proc_other_child_unregister(data); WaitInfo* wi(static_cast(data)); - wi->rv = apr_proc_wait(wi->child, &wi->rc, &wi->why, APR_NOWAIT); - if (wi->rv == ECHILD) - { - std::cout << "apr_proc_wait() got ECHILD during child_status_callback(" - << reason_str << ")\n"; - // So -- is this why we have a 'status' param? - wi->rv = APR_CHILD_DONE; // pretend this call worked; fake results + // It's just wrong to call apr_proc_wait() here. The only way APR + // knows to call us with APR_OC_REASON_DEATH is that it's already + // reaped this child process, so calling wait() will only produce + // "huh?" from the OS. We must rely on the status param passed in, + // which unfortunately comes straight from the OS wait() call. +// wi->rv = apr_proc_wait(wi->child, &wi->rc, &wi->why, APR_NOWAIT); + wi->rv = APR_CHILD_DONE; // fake apr_proc_wait() results #if defined(LL_WINDOWS) - wi->why = APR_PROC_EXIT; - wi->rc = status; // correct?? + wi->why = APR_PROC_EXIT; + wi->rc = status; // no encoding on Windows (no signals) #else // Posix - if (WIFEXITED(status)) - { - wi->why = APR_PROC_EXIT; - wi->rc = WEXITSTATUS(status); - } - else if (WIFSIGNALED(status)) - { - wi->why = APR_PROC_SIGNAL; - wi->rc = WTERMSIG(status); - } - else // uh, shouldn't happen? - { - wi->why = APR_PROC_EXIT; - wi->rc = status; // someone else will have to decode - } -#endif // Posix + if (WIFEXITED(status)) + { + wi->why = APR_PROC_EXIT; + wi->rc = WEXITSTATUS(status); + } + else if (WIFSIGNALED(status)) + { + wi->why = APR_PROC_SIGNAL; + wi->rc = WTERMSIG(status); } + else // uh, shouldn't happen? + { + wi->why = APR_PROC_EXIT; + wi->rc = status; // someone else will have to decode + } +#endif // Posix } } @@ -316,7 +317,7 @@ namespace tut wi.rv = apr_proc_wait(wi.child, &wi.rc, &wi.why, APR_NOWAIT); } // std::cout << "child done: rv = " << rv << " (" << apr.strerror(rv) << "), why = " << why << ", rc = " << rc << '\n'; - ensure_equals_(wi.rv, APR_CHILD_DONE); + aprchk_("apr_proc_wait(wi->child, &wi->rc, &wi->why, APR_NOWAIT)", wi.rv, APR_CHILD_DONE); ensure_equals_(wi.why, APR_PROC_EXIT); ensure_equals_(wi.rc, 0); -- cgit v1.2.3 From 29273ffba68d254ce3e6d9939a854c778a377721 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Thu, 22 Dec 2011 17:27:53 -0500 Subject: Comment out lookup table used only by commented-out code. Otherwise the unreferenced declaration causes a fatal warning. --- indra/llcommon/tests/llprocesslauncher_test.cpp | 2 ++ 1 file changed, 2 insertions(+) (limited to 'indra') diff --git a/indra/llcommon/tests/llprocesslauncher_test.cpp b/indra/llcommon/tests/llprocesslauncher_test.cpp index bd7666313e..b3e0796191 100644 --- a/indra/llcommon/tests/llprocesslauncher_test.cpp +++ b/indra/llcommon/tests/llprocesslauncher_test.cpp @@ -91,6 +91,7 @@ namespace tut std::string what; }; +/*==========================================================================*| #define tabent(symbol) { symbol, #symbol } static struct ReasonCode { @@ -106,6 +107,7 @@ namespace tut tabent(APR_OC_REASON_RUNNING) }; #undef tabent +|*==========================================================================*/ struct WaitInfo { -- cgit v1.2.3 From cf7c6f93f28534fee2c13e29501b6ab6e7b77d61 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Fri, 23 Dec 2011 15:23:03 -0500 Subject: Make pipe-management logic more robust. Previous logic was vulnerable to the case in which both pipes reached EOF in the same loop iteration. Now we use std::list instead of std::vector, allowing us to iterate and delete with a single pass. --- indra/llcommon/tests/llprocesslauncher_test.cpp | 43 ++++++++++++++++--------- 1 file changed, 27 insertions(+), 16 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/tests/llprocesslauncher_test.cpp b/indra/llcommon/tests/llprocesslauncher_test.cpp index bd7666313e..d6d05ed769 100644 --- a/indra/llcommon/tests/llprocesslauncher_test.cpp +++ b/indra/llcommon/tests/llprocesslauncher_test.cpp @@ -16,6 +16,7 @@ #include "llprocesslauncher.h" // STL headers #include +#include // std headers #include // external library headers @@ -28,7 +29,7 @@ #include "stringize.h" #if defined(LL_WINDOWS) -#define sleep _sleep +#define sleep(secs) _sleep((secs) * 1000) #define EOL "\r\n" #else #define EOL "\n" @@ -244,44 +245,54 @@ namespace tut apr_proc_other_child_register(&child, child_status_callback, &wi, child.in, apr.pool); // Monitor two different output pipes. Because one will be closed - // before the other, keep them in a vector so we can drop whichever of + // before the other, keep them in a list so we can drop whichever of // them is closed first. typedef std::pair DescFile; - typedef std::vector DescFileVec; - DescFileVec outfiles; + typedef std::list DescFileList; + DescFileList outfiles; outfiles.push_back(DescFile("out", child.out)); outfiles.push_back(DescFile("err", child.err)); while (! outfiles.empty()) { - DescFileVec iterfiles(outfiles); - for (size_t i = 0; i < iterfiles.size(); ++i) + // This peculiar for loop is designed to let us erase(dfli). With + // a list, that invalidates only dfli itself -- but even so, we + // lose the ability to increment it for the next item. So at the + // top of every loop, while dfli is still valid, increment + // dflnext. Then before the next iteration, set dfli to dflnext. + for (DescFileList::iterator + dfli(outfiles.begin()), dflnext(outfiles.begin()), dflend(outfiles.end()); + dfli != dflend; dfli = dflnext) { + // Only valid to increment dflnext once we're sure it's not + // already at dflend. + ++dflnext; + char buf[4096]; - apr_status_t rv = apr_file_gets(buf, sizeof(buf), iterfiles[i].second); + apr_status_t rv = apr_file_gets(buf, sizeof(buf), dfli->second); if (APR_STATUS_IS_EOF(rv)) { -// std::cout << "(EOF on " << iterfiles[i].first << ")\n"; - history.back().which = iterfiles[i].first; +// std::cout << "(EOF on " << dfli->first << ")\n"; + history.back().which = dfli->first; history.back().what = "*eof*"; history.push_back(Item()); - outfiles.erase(outfiles.begin() + i); + outfiles.erase(dfli); continue; } if (rv == EWOULDBLOCK || rv == EAGAIN) { -// std::cout << "(waiting; apr_file_gets(" << iterfiles[i].first << ") => " << rv << ": " << apr.strerror(rv) << ")\n"; +// std::cout << "(waiting; apr_file_gets(" << dfli->first << ") => " << rv << ": " << apr.strerror(rv) << ")\n"; ++history.back().tries; continue; } - aprchk_("apr_file_gets(buf, sizeof(buf), iterfiles[i].second)", rv); + aprchk_("apr_file_gets(buf, sizeof(buf), dfli->second)", rv); // Is it even possible to get APR_SUCCESS but read 0 bytes? // Hope not, but defend against that anyway. if (buf[0]) { -// std::cout << iterfiles[i].first << ": " << buf; - history.back().which = iterfiles[i].first; +// std::cout << dfli->first << ": " << buf; + history.back().which = dfli->first; history.back().what.append(buf); if (buf[strlen(buf) - 1] == '\n') history.push_back(Item()); @@ -295,7 +306,7 @@ namespace tut } // Do this once per tick, as we expect the viewer will apr_proc_other_child_refresh_all(APR_OC_REASON_RUNNING); - sleep(1); + sleep(0.5); } apr_file_close(child.in); apr_file_close(child.out); @@ -313,7 +324,7 @@ namespace tut if (wi.rv == -1) { - std::cout << "child_status_callback() wasn't called\n"; + std::cout << "child_status_callback(APR_OC_REASON_DEATH) wasn't called" << std::endl; wi.rv = apr_proc_wait(wi.child, &wi.rc, &wi.why, APR_NOWAIT); } // std::cout << "child done: rv = " << rv << " (" << apr.strerror(rv) << "), why = " << why << ", rc = " << rc << '\n'; -- cgit v1.2.3 From 8008d540e5177aa4fb0c802b157eec2695c8334a Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Fri, 23 Dec 2011 16:45:05 -0500 Subject: Should we expect EOF on one pipe before we finish reading the other? Defend test against the ambiguous answer to that question by not recording, or testing for, EOF history events. Enrich output for history-verification failures: display whole history array. --- indra/llcommon/tests/llprocesslauncher_test.cpp | 61 +++++++++++++++++++------ 1 file changed, 48 insertions(+), 13 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/tests/llprocesslauncher_test.cpp b/indra/llcommon/tests/llprocesslauncher_test.cpp index 895325c705..dbbe54e9fa 100644 --- a/indra/llcommon/tests/llprocesslauncher_test.cpp +++ b/indra/llcommon/tests/llprocesslauncher_test.cpp @@ -246,6 +246,11 @@ namespace tut WaitInfo wi(&child); apr_proc_other_child_register(&child, child_status_callback, &wi, child.in, apr.pool); + // TODO: + // Stuff child.in until it (would) block to verify EWOULDBLOCK/EAGAIN. + // Have child script clear it later, then write one more line to prove + // that it gets through. + // Monitor two different output pipes. Because one will be closed // before the other, keep them in a list so we can drop whichever of // them is closed first. @@ -276,9 +281,9 @@ namespace tut if (APR_STATUS_IS_EOF(rv)) { // std::cout << "(EOF on " << dfli->first << ")\n"; - history.back().which = dfli->first; - history.back().what = "*eof*"; - history.push_back(Item()); +// history.back().which = dfli->first; +// history.back().what = "*eof*"; +// history.push_back(Item()); outfiles.erase(dfli); continue; } @@ -340,15 +345,45 @@ namespace tut // Beyond merely executing all the above successfully, verify that we // obtained expected output -- and that we duly got control while // waiting, proving the non-blocking nature of these pipes. - ensure("blocking I/O on child pipe (0)", history[0].tries); - ensure_equals_(history[0].which, "out"); - ensure_equals_(history[0].what, "stdout after wait" EOL); - ensure("blocking I/O on child pipe (1)", history[1].tries); - ensure_equals_(history[1].which, "out"); - ensure_equals_(history[1].what, "*eof*"); - ensure_equals_(history[2].which, "err"); - ensure_equals_(history[2].what, "stderr after wait" EOL); - ensure_equals_(history[3].which, "err"); - ensure_equals_(history[3].what, "*eof*"); + try + { + unsigned i = 0; + ensure("blocking I/O on child pipe (0)", history[i].tries); + ensure_equals_(history[i].which, "out"); + ensure_equals_(history[i].what, "stdout after wait" EOL); +// ++i; +// ensure_equals_(history[i].which, "out"); +// ensure_equals_(history[i].what, "*eof*"); + ++i; + ensure("blocking I/O on child pipe (1)", history[i].tries); + ensure_equals_(history[i].which, "err"); + ensure_equals_(history[i].what, "stderr after wait" EOL); +// ++i; +// ensure_equals_(history[i].which, "err"); +// ensure_equals_(history[i].what, "*eof*"); + } + catch (const failure&) + { + std::cout << "History:\n"; + BOOST_FOREACH(const Item& item, history) + { + std::string what(item.what); + if ((! what.empty()) && what[what.length() - 1] == '\n') + { + what.erase(what.length() - 1); + if ((! what.empty()) && what[what.length() - 1] == '\r') + { + what.erase(what.length() - 1); + what.append("\\r"); + } + what.append("\\n"); + } + std::cout << " " << item.which << ": '" << what << "' (" + << item.tries << " tries)\n"; + } + std::cout << std::flush; + // re-raise same error; just want to enrich the output + throw; + } } } // namespace tut -- cgit v1.2.3 From 97876f6118eadf6a2669826d68412cc020975a64 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Fri, 23 Dec 2011 17:38:34 -0500 Subject: Fix sleep(0.5) to sleep(1) -- truncation to int makes that dubious. --- indra/llcommon/tests/llprocesslauncher_test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/llcommon/tests/llprocesslauncher_test.cpp b/indra/llcommon/tests/llprocesslauncher_test.cpp index dbbe54e9fa..4d8f850d92 100644 --- a/indra/llcommon/tests/llprocesslauncher_test.cpp +++ b/indra/llcommon/tests/llprocesslauncher_test.cpp @@ -313,7 +313,7 @@ namespace tut } // Do this once per tick, as we expect the viewer will apr_proc_other_child_refresh_all(APR_OC_REASON_RUNNING); - sleep(0.5); + sleep(1); } apr_file_close(child.in); apr_file_close(child.out); -- cgit v1.2.3 From 61b5f3143e4ea53c9f64e5a1a5ad19f2edf3e776 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Thu, 5 Jan 2012 15:43:23 -0500 Subject: Introduce LLStreamQueue to buffer nonblocking I/O. Add unit tests to verify basic functionality. --- indra/llcommon/CMakeLists.txt | 3 + indra/llcommon/llstreamqueue.cpp | 24 +++ indra/llcommon/llstreamqueue.h | 229 ++++++++++++++++++++++++++++ indra/llcommon/tests/llstreamqueue_test.cpp | 177 +++++++++++++++++++++ 4 files changed, 433 insertions(+) create mode 100644 indra/llcommon/llstreamqueue.cpp create mode 100644 indra/llcommon/llstreamqueue.h create mode 100644 indra/llcommon/tests/llstreamqueue_test.cpp (limited to 'indra') diff --git a/indra/llcommon/CMakeLists.txt b/indra/llcommon/CMakeLists.txt index c8e1827584..334f78cbff 100644 --- a/indra/llcommon/CMakeLists.txt +++ b/indra/llcommon/CMakeLists.txt @@ -88,6 +88,7 @@ set(llcommon_SOURCE_FILES llsingleton.cpp llstat.cpp llstacktrace.cpp + llstreamqueue.cpp llstreamtools.cpp llstring.cpp llstringtable.cpp @@ -221,6 +222,7 @@ set(llcommon_HEADER_FILES llstat.h llstatenums.h llstl.h + llstreamqueue.h llstreamtools.h llstrider.h llstring.h @@ -327,6 +329,7 @@ if (LL_TESTS) LL_ADD_INTEGRATION_TEST(stringize "" "${test_libs}") LL_ADD_INTEGRATION_TEST(lleventdispatcher "" "${test_libs}") LL_ADD_INTEGRATION_TEST(llprocesslauncher "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(llstreamqueue "" "${test_libs}") # *TODO - reenable these once tcmalloc libs no longer break the build. #ADD_BUILD_TEST(llallocator llcommon) diff --git a/indra/llcommon/llstreamqueue.cpp b/indra/llcommon/llstreamqueue.cpp new file mode 100644 index 0000000000..1116a2b6a2 --- /dev/null +++ b/indra/llcommon/llstreamqueue.cpp @@ -0,0 +1,24 @@ +/** + * @file llstreamqueue.cpp + * @author Nat Goodspeed + * @date 2012-01-05 + * @brief Implementation for llstreamqueue. + * + * $LicenseInfo:firstyear=2012&license=viewerlgpl$ + * Copyright (c) 2012, Linden Research, Inc. + * $/LicenseInfo$ + */ + +// Precompiled header +#include "linden_common.h" +// associated header +#include "llstreamqueue.h" +// STL headers +// std headers +// external library headers +// other Linden headers + +// As of this writing, llstreamqueue.h is entirely template-based, therefore +// we don't strictly need a corresponding .cpp file. However, our CMake test +// macro assumes one. Here it is. +bool llstreamqueue_cpp_ignored = true; diff --git a/indra/llcommon/llstreamqueue.h b/indra/llcommon/llstreamqueue.h new file mode 100644 index 0000000000..2fbc2067d2 --- /dev/null +++ b/indra/llcommon/llstreamqueue.h @@ -0,0 +1,229 @@ +/** + * @file llstreamqueue.h + * @author Nat Goodspeed + * @date 2012-01-04 + * @brief Definition of LLStreamQueue + * + * $LicenseInfo:firstyear=2012&license=viewerlgpl$ + * Copyright (c) 2012, Linden Research, Inc. + * $/LicenseInfo$ + */ + +#if ! defined(LL_LLSTREAMQUEUE_H) +#define LL_LLSTREAMQUEUE_H + +#include +#include +#include // std::streamsize +#include + +/** + * This class is a growable buffer between a producer and consumer. It serves + * as a queue usable with Boost.Iostreams -- hence, a "stream queue." + * + * This is especially useful for buffering nonblocking I/O. For instance, we + * want application logic to be able to serialize LLSD to a std::ostream. We + * may write more data than the destination pipe can handle all at once, but + * it's imperative NOT to block the application-level serialization call. So + * we buffer it instead. Successive frames can try nonblocking writes to the + * destination pipe until all buffered data has been sent. + * + * Similarly, we want application logic be able to deserialize LLSD from a + * std::istream. Again, we must not block that deserialize call waiting for + * more data to arrive from the input pipe! Instead we build up a buffer over + * a number of frames, using successive nonblocking reads, until we have + * "enough" data to be able to present it through a std::istream. + * + * @note The use cases for this class overlap somewhat with those for the + * LLIOPipe/LLPumpIO hierarchies, and indeed we considered using those. This + * class has two virtues over the older machinery: + * + * # It's vastly simpler -- way fewer concepts. It's not clear to me whether + * there were ever LLIOPipe/etc. use cases that demanded all the fanciness + * rolled in, or whether they were simply overdesigned. In any case, no + * remaining Lindens will admit to familiarity with those classes -- and + * they're sufficiently obtuse that it would take considerable learning + * curve to figure out how to use them properly. The bottom line is that + * current management is not keen on any more engineers climbing that curve. + * # This class is designed around available components such as std::string, + * std::list, Boost.Iostreams. There's less proprietary code. + */ +template +class LLGenericStreamQueue +{ +public: + LLGenericStreamQueue(): + mClosed(false) + {} + + /** + * Boost.Iostreams Source Device facade for use with other Boost.Iostreams + * functionality. LLGenericStreamQueue doesn't quite fit any of the Boost + * 1.48 Iostreams concepts; instead it behaves as both a Sink and a + * Source. This is its Source facade. + */ + struct Source + { + typedef Ch char_type; + typedef boost::iostreams::source_tag category; + + /// Bind the underlying LLGenericStreamQueue + Source(LLGenericStreamQueue& sq): + mStreamQueue(sq) + {} + + // Read up to n characters from the underlying data source into the + // buffer s, returning the number of characters read; return -1 to + // indicate EOF + std::streamsize read(Ch* s, std::streamsize n) + { + return mStreamQueue.read(s, n); + } + + LLGenericStreamQueue& mStreamQueue; + }; + + /** + * Boost.Iostreams Sink Device facade for use with other Boost.Iostreams + * functionality. LLGenericStreamQueue doesn't quite fit any of the Boost + * 1.48 Iostreams concepts; instead it behaves as both a Sink and a + * Source. This is its Sink facade. + */ + struct Sink + { + typedef Ch char_type; + typedef boost::iostreams::sink_tag category; + + /// Bind the underlying LLGenericStreamQueue + Sink(LLGenericStreamQueue& sq): + mStreamQueue(sq) + {} + + /// Write up to n characters from the buffer s to the output sequence, + /// returning the number of characters written + std::streamsize write(const Ch* s, std::streamsize n) + { + return mStreamQueue.write(s, n); + } + + /// Send EOF to consumer + void close() + { + mStreamQueue.close(); + } + + LLGenericStreamQueue& mStreamQueue; + }; + + /// Present Boost.Iostreams Source facade + Source asSource() { return Source(*this); } + /// Present Boost.Iostreams Sink facade + Sink asSink() { return Sink(*this); } + + /// append data to buffer + std::streamsize write(const Ch* s, std::streamsize n) + { + // Unclear how often we might be asked to write 0 bytes -- perhaps a + // naive caller responding to an unready nonblocking read. But if we + // do get such a call, don't add a completely empty BufferList entry. + if (n == 0) + return n; + // We could implement this using a single std::string object, a la + // ostringstream. But the trouble with appending to a string is that + // you might have to recopy all previous contents to grow its size. If + // we want this to scale to large data volumes, better to allocate + // individual pieces. + mBuffer.push_back(string(s, n)); + return n; + } + + /** + * Inform this LLGenericStreamQueue that no further data are forthcoming. + * For our purposes, close() is strictly a producer-side operation; + * there's little point in closing the consumer side. + */ + void close() + { + mClosed = true; + } + + /// consume data from buffer + std::streamsize read(Ch* s, std::streamsize n) + { + // read() is actually a convenience method for peek() followed by + // skip(). + std::streamsize got(peek(s, n)); + // We can only skip() as many characters as we can peek(); ignore + // skip() return here. + skip(n); + return got; + } + + /// Retrieve data from buffer without consuming. Like read(), return -1 on + /// EOF. + std::streamsize peek(Ch* s, std::streamsize n) const; + + /// Consume data from buffer without retrieving. Unlike read() and peek(), + /// at EOF we simply skip 0 characters. + std::streamsize skip(std::streamsize n); + +private: + typedef std::basic_string string; + typedef std::list BufferList; + BufferList mBuffer; + bool mClosed; +}; + +template +std::streamsize LLGenericStreamQueue::peek(Ch* s, std::streamsize n) const +{ + // Here we may have to build up 'n' characters from an arbitrary + // number of individual BufferList entries. + typename BufferList::const_iterator bli(mBuffer.begin()), blend(mBuffer.end()); + // Indicate EOF if producer has closed the pipe AND we've exhausted + // all previously-buffered data. + if (mClosed && bli == blend) + { + return -1; + } + // Here either producer hasn't yet closed, or we haven't yet exhausted + // remaining data. + std::streamsize needed(n), got(0); + // Loop until either we run out of BufferList entries or we've + // completely satisfied the request. + for ( ; bli != blend && needed; ++bli) + { + std::streamsize chunk(std::min(needed, std::streamsize(bli->length()))); + std::copy(bli->begin(), bli->begin() + chunk, s); + needed -= chunk; + s += chunk; + got += chunk; + } + return got; +} + +template +std::streamsize LLGenericStreamQueue::skip(std::streamsize n) +{ + typename BufferList::iterator bli(mBuffer.begin()), blend(mBuffer.end()); + std::streamsize toskip(n), skipped(0); + while (bli != blend && toskip >= bli->length()) + { + std::streamsize chunk(bli->length()); + typename BufferList::iterator zap(bli++); + mBuffer.erase(zap); + toskip -= chunk; + skipped += chunk; + } + if (bli != blend && toskip) + { + bli->erase(bli->begin(), bli->begin() + toskip); + skipped += toskip; + } + return skipped; +} + +typedef LLGenericStreamQueue LLStreamQueue; +typedef LLGenericStreamQueue LLWStreamQueue; + +#endif /* ! defined(LL_LLSTREAMQUEUE_H) */ diff --git a/indra/llcommon/tests/llstreamqueue_test.cpp b/indra/llcommon/tests/llstreamqueue_test.cpp new file mode 100644 index 0000000000..e88c37d5be --- /dev/null +++ b/indra/llcommon/tests/llstreamqueue_test.cpp @@ -0,0 +1,177 @@ +/** + * @file llstreamqueue_test.cpp + * @author Nat Goodspeed + * @date 2012-01-05 + * @brief Test for llstreamqueue. + * + * $LicenseInfo:firstyear=2012&license=viewerlgpl$ + * Copyright (c) 2012, Linden Research, Inc. + * $/LicenseInfo$ + */ + +// Precompiled header +#include "linden_common.h" +// associated header +#include "llstreamqueue.h" +// STL headers +#include +// std headers +// external library headers +#include +// other Linden headers +#include "../test/lltut.h" +#include "stringize.h" + +/***************************************************************************** +* TUT +*****************************************************************************/ +namespace tut +{ + struct llstreamqueue_data + { + llstreamqueue_data(): + // we want a buffer with actual bytes in it, not an empty vector + buffer(10) + {} + // As LLStreamQueue is merely a typedef for + // LLGenericStreamQueue, and no logic in LLGenericStreamQueue is + // specific to the instantiation, we're comfortable for now + // testing only the narrow-char version. + LLStreamQueue strq; + // buffer for use in multiple tests + std::vector buffer; + }; + typedef test_group llstreamqueue_group; + typedef llstreamqueue_group::object object; + llstreamqueue_group llstreamqueuegrp("llstreamqueue"); + + template<> template<> + void object::test<1>() + { + set_test_name("empty LLStreamQueue"); + ensure_equals("brand-new LLStreamQueue isn't empty", + strq.asSource().read(&buffer[0], buffer.size()), 0); + strq.asSink().close(); + ensure_equals("closed empty LLStreamQueue not at EOF", + strq.asSource().read(&buffer[0], buffer.size()), -1); + } + + template<> template<> + void object::test<2>() + { + set_test_name("one internal block, one buffer"); + LLStreamQueue::Sink sink(strq.asSink()); + ensure_equals("write(\"\")", sink.write("", 0), 0); + ensure_equals("0 write should leave LLStreamQueue empty", + strq.peek(&buffer[0], buffer.size()), 0); + // The meaning of "atomic" is that it must be smaller than our buffer. + std::string atomic("atomic"); + ensure("test data exceeds buffer", atomic.length() < buffer.size()); + ensure_equals(STRINGIZE("write(\"" << atomic << "\")"), + sink.write(&atomic[0], atomic.length()), atomic.length()); + size_t peeklen(strq.peek(&buffer[0], buffer.size())); + ensure_equals(STRINGIZE("peek(\"" << atomic << "\")"), + peeklen, atomic.length()); + ensure_equals(STRINGIZE("peek(\"" << atomic << "\") result"), + std::string(buffer.begin(), buffer.begin() + peeklen), atomic); + // peek() should not consume. Use a different buffer to prove it isn't + // just leftover data from the first peek(). + std::vector again(buffer.size()); + peeklen = size_t(strq.peek(&again[0], again.size())); + ensure_equals(STRINGIZE("peek(\"" << atomic << "\") again"), + peeklen, atomic.length()); + ensure_equals(STRINGIZE("peek(\"" << atomic << "\") again result"), + std::string(again.begin(), again.begin() + peeklen), atomic); + // now consume. + std::vector third(buffer.size()); + size_t readlen(strq.read(&third[0], third.size())); + ensure_equals(STRINGIZE("read(\"" << atomic << "\")"), + readlen, atomic.length()); + ensure_equals(STRINGIZE("read(\"" << atomic << "\") result"), + std::string(third.begin(), third.begin() + readlen), atomic); + ensure_equals("peek() after read()", strq.peek(&buffer[0], buffer.size()), 0); + } + + template<> template<> + void object::test<3>() + { + set_test_name("basic skip()"); + std::string lovecraft("lovecraft"); + ensure("test data exceeds buffer", lovecraft.length() < buffer.size()); + ensure_equals(STRINGIZE("write(\"" << lovecraft << "\")"), + strq.write(&lovecraft[0], lovecraft.length()), lovecraft.length()); + size_t peeklen(strq.peek(&buffer[0], buffer.size())); + ensure_equals(STRINGIZE("peek(\"" << lovecraft << "\")"), + peeklen, lovecraft.length()); + ensure_equals(STRINGIZE("peek(\"" << lovecraft << "\") result"), + std::string(buffer.begin(), buffer.begin() + peeklen), lovecraft); + std::streamsize skip1(4); + ensure_equals(STRINGIZE("skip(" << skip1 << ")"), strq.skip(skip1), skip1); + size_t readlen(strq.read(&buffer[0], buffer.size())); + ensure_equals(STRINGIZE("read(\"" << lovecraft.substr(skip1) << "\")"), + readlen, lovecraft.length() - skip1); + ensure_equals(STRINGIZE("read(\"" << lovecraft.substr(skip1) << "\") result"), + std::string(buffer.begin(), buffer.begin() + readlen), + lovecraft.substr(skip1)); + ensure_equals("unconsumed", strq.read(&buffer[0], buffer.size()), 0); + } + + template<> template<> + void object::test<4>() + { + set_test_name("skip() multiple blocks"); + std::string blocks[] = { "books of ", "H.P. ", "Lovecraft" }; + std::streamsize skip(blocks[0].length() + blocks[1].length() + 4); + BOOST_FOREACH(const std::string& block, blocks) + { + strq.write(&block[0], block.length()); + } + std::streamsize skiplen(strq.skip(skip)); + ensure_equals(STRINGIZE("skip(" << skip << ")"), skiplen, skip); + size_t readlen(strq.read(&buffer[0], buffer.size())); + ensure_equals("read(\"craft\")", readlen, 5); + ensure_equals("read(\"craft\") result", + std::string(buffer.begin(), buffer.begin() + readlen), "craft"); + } + + template<> template<> + void object::test<5>() + { + set_test_name("concatenate blocks"); + std::string blocks[] = { "abcd", "efghij", "klmnopqrs" }; + BOOST_FOREACH(const std::string& block, blocks) + { + strq.write(&block[0], block.length()); + } + std::vector longbuffer(30); + std::streamsize readlen(strq.read(&longbuffer[0], longbuffer.size())); + ensure_equals("read() multiple blocks", + readlen, blocks[0].length() + blocks[1].length() + blocks[2].length()); + ensure_equals("read() multiple blocks result", + std::string(longbuffer.begin(), longbuffer.begin() + readlen), + blocks[0] + blocks[1] + blocks[2]); + } + + template<> template<> + void object::test<6>() + { + set_test_name("split blocks"); + std::string blocks[] = { "abcdefghijklm", "nopqrstuvwxyz" }; + BOOST_FOREACH(const std::string& block, blocks) + { + strq.write(&block[0], block.length()); + } + strq.close(); + std::streamsize readlen(strq.read(&buffer[0], buffer.size())); + ensure_equals("read() 0", readlen, buffer.size()); + ensure_equals("read() 0 result", std::string(buffer.begin(), buffer.end()), "abcdefghij"); + readlen = strq.read(&buffer[0], buffer.size()); + ensure_equals("read() 1", readlen, buffer.size()); + ensure_equals("read() 1 result", std::string(buffer.begin(), buffer.end()), "klmnopqrst"); + readlen = strq.read(&buffer[0], buffer.size()); + ensure_equals("read() 2", readlen, 6); + ensure_equals("read() 2 result", + std::string(buffer.begin(), buffer.begin() + readlen), "uvwxyz"); + ensure_equals("read() 3", strq.read(&buffer[0], buffer.size()), -1); + } +} // namespace tut -- cgit v1.2.3 From 39a86eda8d6d810bd7f4dd6b96f022548a496ba1 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Thu, 12 Jan 2012 12:19:27 -0500 Subject: Add LLStreamQueue::size() and tests to exercise it. --- indra/llcommon/llstreamqueue.h | 11 +++++++++++ indra/llcommon/tests/llstreamqueue_test.cpp | 30 ++++++++++++++++++++++++----- 2 files changed, 36 insertions(+), 5 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/llstreamqueue.h b/indra/llcommon/llstreamqueue.h index 2fbc2067d2..0726bad175 100644 --- a/indra/llcommon/llstreamqueue.h +++ b/indra/llcommon/llstreamqueue.h @@ -53,6 +53,7 @@ class LLGenericStreamQueue { public: LLGenericStreamQueue(): + mSize(0), mClosed(false) {} @@ -134,6 +135,7 @@ public: // we want this to scale to large data volumes, better to allocate // individual pieces. mBuffer.push_back(string(s, n)); + mSize += n; return n; } @@ -167,10 +169,17 @@ public: /// at EOF we simply skip 0 characters. std::streamsize skip(std::streamsize n); + /// How many characters do we currently have buffered? + std::streamsize size() const + { + return mSize; + } + private: typedef std::basic_string string; typedef std::list BufferList; BufferList mBuffer; + std::streamsize mSize; bool mClosed; }; @@ -212,12 +221,14 @@ std::streamsize LLGenericStreamQueue::skip(std::streamsize n) std::streamsize chunk(bli->length()); typename BufferList::iterator zap(bli++); mBuffer.erase(zap); + mSize -= chunk; toskip -= chunk; skipped += chunk; } if (bli != blend && toskip) { bli->erase(bli->begin(), bli->begin() + toskip); + mSize -= toskip; skipped += toskip; } return skipped; diff --git a/indra/llcommon/tests/llstreamqueue_test.cpp b/indra/llcommon/tests/llstreamqueue_test.cpp index e88c37d5be..050ad5c5bf 100644 --- a/indra/llcommon/tests/llstreamqueue_test.cpp +++ b/indra/llcommon/tests/llstreamqueue_test.cpp @@ -50,6 +50,8 @@ namespace tut { set_test_name("empty LLStreamQueue"); ensure_equals("brand-new LLStreamQueue isn't empty", + strq.size(), 0); + ensure_equals("brand-new LLStreamQueue returns data", strq.asSource().read(&buffer[0], buffer.size()), 0); strq.asSink().close(); ensure_equals("closed empty LLStreamQueue not at EOF", @@ -62,18 +64,22 @@ namespace tut set_test_name("one internal block, one buffer"); LLStreamQueue::Sink sink(strq.asSink()); ensure_equals("write(\"\")", sink.write("", 0), 0); - ensure_equals("0 write should leave LLStreamQueue empty", + ensure_equals("0 write should leave LLStreamQueue empty (size())", + strq.size(), 0); + ensure_equals("0 write should leave LLStreamQueue empty (peek())", strq.peek(&buffer[0], buffer.size()), 0); // The meaning of "atomic" is that it must be smaller than our buffer. std::string atomic("atomic"); ensure("test data exceeds buffer", atomic.length() < buffer.size()); ensure_equals(STRINGIZE("write(\"" << atomic << "\")"), sink.write(&atomic[0], atomic.length()), atomic.length()); + ensure_equals("size() after write()", strq.size(), atomic.length()); size_t peeklen(strq.peek(&buffer[0], buffer.size())); ensure_equals(STRINGIZE("peek(\"" << atomic << "\")"), peeklen, atomic.length()); ensure_equals(STRINGIZE("peek(\"" << atomic << "\") result"), std::string(buffer.begin(), buffer.begin() + peeklen), atomic); + ensure_equals("size() after peek()", strq.size(), atomic.length()); // peek() should not consume. Use a different buffer to prove it isn't // just leftover data from the first peek(). std::vector again(buffer.size()); @@ -90,6 +96,7 @@ namespace tut ensure_equals(STRINGIZE("read(\"" << atomic << "\") result"), std::string(third.begin(), third.begin() + readlen), atomic); ensure_equals("peek() after read()", strq.peek(&buffer[0], buffer.size()), 0); + ensure_equals("size() after read()", strq.size(), 0); } template<> template<> @@ -107,6 +114,7 @@ namespace tut std::string(buffer.begin(), buffer.begin() + peeklen), lovecraft); std::streamsize skip1(4); ensure_equals(STRINGIZE("skip(" << skip1 << ")"), strq.skip(skip1), skip1); + ensure_equals("size() after skip()", strq.size(), lovecraft.length() - skip1); size_t readlen(strq.read(&buffer[0], buffer.size())); ensure_equals(STRINGIZE("read(\"" << lovecraft.substr(skip1) << "\")"), readlen, lovecraft.length() - skip1); @@ -121,15 +129,20 @@ namespace tut { set_test_name("skip() multiple blocks"); std::string blocks[] = { "books of ", "H.P. ", "Lovecraft" }; - std::streamsize skip(blocks[0].length() + blocks[1].length() + 4); + std::streamsize total(blocks[0].length() + blocks[1].length() + blocks[2].length()); + std::streamsize leave(5); // len("craft") above + std::streamsize skip(total - leave); + std::streamsize written(0); BOOST_FOREACH(const std::string& block, blocks) { - strq.write(&block[0], block.length()); + written += strq.write(&block[0], block.length()); + ensure_equals("size() after write()", strq.size(), written); } std::streamsize skiplen(strq.skip(skip)); ensure_equals(STRINGIZE("skip(" << skip << ")"), skiplen, skip); + ensure_equals("size() after skip()", strq.size(), leave); size_t readlen(strq.read(&buffer[0], buffer.size())); - ensure_equals("read(\"craft\")", readlen, 5); + ensure_equals("read(\"craft\")", readlen, leave); ensure_equals("read(\"craft\") result", std::string(buffer.begin(), buffer.begin() + readlen), "craft"); } @@ -162,14 +175,21 @@ namespace tut strq.write(&block[0], block.length()); } strq.close(); + // We've already verified what strq.size() should be at this point; + // see above test named "skip() multiple blocks" + std::streamsize chksize(strq.size()); std::streamsize readlen(strq.read(&buffer[0], buffer.size())); ensure_equals("read() 0", readlen, buffer.size()); ensure_equals("read() 0 result", std::string(buffer.begin(), buffer.end()), "abcdefghij"); + chksize -= readlen; + ensure_equals("size() after read() 0", strq.size(), chksize); readlen = strq.read(&buffer[0], buffer.size()); ensure_equals("read() 1", readlen, buffer.size()); ensure_equals("read() 1 result", std::string(buffer.begin(), buffer.end()), "klmnopqrst"); + chksize -= readlen; + ensure_equals("size() after read() 1", strq.size(), chksize); readlen = strq.read(&buffer[0], buffer.size()); - ensure_equals("read() 2", readlen, 6); + ensure_equals("read() 2", readlen, chksize); ensure_equals("read() 2 result", std::string(buffer.begin(), buffer.begin() + readlen), "uvwxyz"); ensure_equals("read() 3", strq.read(&buffer[0], buffer.size()), -1); -- cgit v1.2.3 From b6a08ad007deb855ce4d428654279206853a3b99 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Fri, 13 Jan 2012 12:41:54 -0500 Subject: Extract APR and temp-fixture-file helper code to indra/test. Specifically: Introduce ManageAPR class in indra/test/manageapr.h. This is useful for a simple test program without lots of static constructors. Extract NamedTempFile from llsdserialize_test.cpp to indra/test/ namedtempfile.h. Refactor to use APR file operations rather than platform- dependent APIs. Use NamedTempFile for llprocesslauncher_test.cpp. --- indra/llcommon/tests/llprocesslauncher_test.cpp | 73 ++----- indra/llcommon/tests/llsdserialize_test.cpp | 261 +----------------------- indra/test/manageapr.h | 45 ++++ indra/test/namedtempfile.h | 113 ++++++++++ 4 files changed, 184 insertions(+), 308 deletions(-) create mode 100644 indra/test/manageapr.h create mode 100644 indra/test/namedtempfile.h (limited to 'indra') diff --git a/indra/llcommon/tests/llprocesslauncher_test.cpp b/indra/llcommon/tests/llprocesslauncher_test.cpp index 4d8f850d92..3935c64a94 100644 --- a/indra/llcommon/tests/llprocesslauncher_test.cpp +++ b/indra/llcommon/tests/llprocesslauncher_test.cpp @@ -18,14 +18,14 @@ #include #include // std headers -#include // external library headers #include "llapr.h" #include "apr_thread_proc.h" -#include "apr_file_io.h" #include // other Linden headers #include "../test/lltut.h" +#include "../test/manageapr.h" +#include "../test/namedtempfile.h" #include "stringize.h" #if defined(LL_WINDOWS) @@ -36,30 +36,8 @@ #include #endif -class APR -{ -public: - APR(): - pool(NULL) - { - apr_initialize(); - apr_pool_create(&pool, NULL); - } - - ~APR() - { - apr_terminate(); - } - - std::string strerror(apr_status_t rv) - { - char errbuf[256]; - apr_strerror(rv, errbuf, sizeof(errbuf)); - return errbuf; - } - - apr_pool_t *pool; -}; +// static instance of this manages APR init/cleanup +static ManageAPR manager; #define ensure_equals_(left, right) \ ensure_equals(STRINGIZE(#left << " != " << #right), (left), (right)) @@ -74,11 +52,11 @@ namespace tut { void aprchk_(const char* call, apr_status_t rv, apr_status_t expected=APR_SUCCESS) { - ensure_equals(STRINGIZE(call << " => " << rv << ": " << apr.strerror(rv)), + ensure_equals(STRINGIZE(call << " => " << rv << ": " << manager.strerror(rv)), rv, expected); } - APR apr; + LLAPRPool pool; }; typedef test_group llprocesslauncher_group; typedef llprocesslauncher_group::object object; @@ -186,19 +164,7 @@ namespace tut set_test_name("raw APR nonblocking I/O"); // Create a script file in a temporary place. - const char* tempdir = NULL; - aprchk(apr_temp_dir_get(&tempdir, apr.pool)); - - // Construct a temp filename template in that directory. - char *tempname = NULL; - aprchk(apr_filepath_merge(&tempname, tempdir, "testXXXXXX", 0, apr.pool)); - - // Create a temp file from that template. - apr_file_t* fp = NULL; - aprchk(apr_file_mktemp(&fp, tempname, APR_CREATE | APR_WRITE | APR_EXCL, apr.pool)); - - // Write it. - const char script[] = + NamedTempFile script("py", "import sys" EOL "import time" EOL EOL @@ -208,10 +174,7 @@ namespace tut "time.sleep(2)" EOL "print >>sys.stderr, 'stderr after wait'" EOL "sys.stderr.flush()" EOL - ; - apr_size_t len(sizeof(script)-1); - aprchk(apr_file_write(fp, script, &len)); - aprchk(apr_file_close(fp)); + ); // Arrange to track the history of our interaction with child: what we // fetched, which pipe it came from, how many tries it took before we @@ -221,30 +184,33 @@ namespace tut // Run the child process. apr_procattr_t *procattr = NULL; - aprchk(apr_procattr_create(&procattr, apr.pool)); + aprchk(apr_procattr_create(&procattr, pool.getAPRPool())); aprchk(apr_procattr_io_set(procattr, APR_CHILD_BLOCK, APR_CHILD_BLOCK, APR_CHILD_BLOCK)); aprchk(apr_procattr_cmdtype_set(procattr, APR_PROGRAM_PATH)); std::vector argv; apr_proc_t child; argv.push_back("python"); - argv.push_back(tempname); + // Have to have a named copy of this std::string so its c_str() value + // will persist. + std::string scriptname(script.getName()); + argv.push_back(scriptname.c_str()); argv.push_back(NULL); aprchk(apr_proc_create(&child, argv[0], &argv[0], NULL, // if we wanted to pass explicit environment procattr, - apr.pool)); + pool.getAPRPool())); // We do not want this child process to outlive our APR pool. On // destruction of the pool, forcibly kill the process. Tell APR to try // SIGTERM and wait 3 seconds. If that didn't work, use SIGKILL. - apr_pool_note_subprocess(apr.pool, &child, APR_KILL_AFTER_TIMEOUT); + apr_pool_note_subprocess(pool.getAPRPool(), &child, APR_KILL_AFTER_TIMEOUT); // arrange to call child_status_callback() WaitInfo wi(&child); - apr_proc_other_child_register(&child, child_status_callback, &wi, child.in, apr.pool); + apr_proc_other_child_register(&child, child_status_callback, &wi, child.in, pool.getAPRPool()); // TODO: // Stuff child.in until it (would) block to verify EWOULDBLOCK/EAGAIN. @@ -289,7 +255,7 @@ namespace tut } if (rv == EWOULDBLOCK || rv == EAGAIN) { -// std::cout << "(waiting; apr_file_gets(" << dfli->first << ") => " << rv << ": " << apr.strerror(rv) << ")\n"; +// std::cout << "(waiting; apr_file_gets(" << dfli->first << ") => " << rv << ": " << manager.strerror(rv) << ")\n"; ++history.back().tries; continue; } @@ -334,14 +300,11 @@ namespace tut std::cout << "child_status_callback(APR_OC_REASON_DEATH) wasn't called" << std::endl; wi.rv = apr_proc_wait(wi.child, &wi.rc, &wi.why, APR_NOWAIT); } -// std::cout << "child done: rv = " << rv << " (" << apr.strerror(rv) << "), why = " << why << ", rc = " << rc << '\n'; +// std::cout << "child done: rv = " << rv << " (" << manager.strerror(rv) << "), why = " << why << ", rc = " << rc << '\n'; aprchk_("apr_proc_wait(wi->child, &wi->rc, &wi->why, APR_NOWAIT)", wi.rv, APR_CHILD_DONE); ensure_equals_(wi.why, APR_PROC_EXIT); ensure_equals_(wi.rc, 0); - // Remove temp script file - aprchk(apr_file_remove(tempname, apr.pool)); - // Beyond merely executing all the above successfully, verify that we // obtained expected output -- and that we duly got control while // waiting, proving the non-blocking nature of these pipes. diff --git a/indra/llcommon/tests/llsdserialize_test.cpp b/indra/llcommon/tests/llsdserialize_test.cpp index 72322c3b72..4359e9afb9 100644 --- a/indra/llcommon/tests/llsdserialize_test.cpp +++ b/indra/llcommon/tests/llsdserialize_test.cpp @@ -43,38 +43,12 @@ typedef U32 uint32_t; #include "llprocesslauncher.h" #endif -#include - -/*==========================================================================*| -// Whoops, seems Linden's Boost package and the viewer are built with -// different settings of VC's /Zc:wchar_t switch! Using Boost.Filesystem -// pathname operations produces Windows link errors: -// unresolved external symbol "private: static class std::codecvt const * & __cdecl boost::filesystem3::path::wchar_t_codecvt_facet()" -// unresolved external symbol "void __cdecl boost::filesystem3::path_traits::convert()" -// See: -// http://boost.2283326.n4.nabble.com/filesystem-v3-unicode-and-std-codecvt-linker-error-td3455549.html -// which points to: -// http://msdn.microsoft.com/en-us/library/dh8che7s%28v=VS.100%29.aspx - -// As we're not trying to preserve compatibility with old Boost.Filesystem -// code, but rather writing brand-new code, use the newest available -// Filesystem API. -#define BOOST_FILESYSTEM_VERSION 3 -#include "boost/filesystem.hpp" -#include "boost/filesystem/v3/fstream.hpp" -|*==========================================================================*/ #include "boost/range.hpp" #include "boost/foreach.hpp" #include "boost/function.hpp" #include "boost/lambda/lambda.hpp" #include "boost/lambda/bind.hpp" namespace lambda = boost::lambda; -/*==========================================================================*| -// Aaaarrgh, Linden's Boost package doesn't even include Boost.Iostreams! -#include "boost/iostreams/stream.hpp" -#include "boost/iostreams/device/file_descriptor.hpp" -|*==========================================================================*/ #include "../llsd.h" #include "../llsdserialize.h" @@ -82,236 +56,17 @@ namespace lambda = boost::lambda; #include "../llformat.h" #include "../test/lltut.h" +#include "../test/manageapr.h" +#include "../test/namedtempfile.h" #include "stringize.h" +static ManageAPR manager; + std::vector string_to_vector(const std::string& str) { return std::vector(str.begin(), str.end()); } -#if ! LL_WINDOWS -// We want to call strerror_r(), but alarmingly, there are two different -// variants. The one that returns int always populates the passed buffer -// (except in case of error), whereas the other one always returns a valid -// char* but might or might not populate the passed buffer. How do we know -// which one we're getting? Define adapters for each and let the compiler -// select the applicable adapter. - -// strerror_r() returns char* -std::string message_from(int /*orig_errno*/, const char* /*buffer*/, const char* strerror_ret) -{ - return strerror_ret; -} - -// strerror_r() returns int -std::string message_from(int orig_errno, const char* buffer, int strerror_ret) -{ - if (strerror_ret == 0) - { - return buffer; - } - // Here strerror_r() has set errno. Since strerror_r() has already failed, - // seems like a poor bet to call it again to diagnose its own error... - int stre_errno = errno; - if (stre_errno == ERANGE) - { - return STRINGIZE("strerror_r() can't explain errno " << orig_errno - << " (buffer too small)"); - } - if (stre_errno == EINVAL) - { - return STRINGIZE("unknown errno " << orig_errno); - } - // Here we don't even understand the errno from strerror_r()! - return STRINGIZE("strerror_r() can't explain errno " << orig_errno - << " (error " << stre_errno << ')'); -} -#endif // ! LL_WINDOWS - -// boost::filesystem::temp_directory_path() isn't yet in Boost 1.45! :-( -std::string temp_directory_path() -{ -#if LL_WINDOWS - char buffer[4096]; - GetTempPathA(sizeof(buffer), buffer); - return buffer; - -#else // LL_DARWIN, LL_LINUX - static const char* vars[] = { "TMPDIR", "TMP", "TEMP", "TEMPDIR" }; - BOOST_FOREACH(const char* var, vars) - { - const char* found = getenv(var); - if (found) - return found; - } - return "/tmp"; -#endif // LL_DARWIN, LL_LINUX -} - -// Windows presents a kinda sorta compatibility layer. Code to the yucky -// Windows names because they're less likely than the Posix names to collide -// with any other names in this source. -#if LL_WINDOWS -#define _remove DeleteFileA -#else // ! LL_WINDOWS -#define _open open -#define _write write -#define _close close -#define _remove remove -#endif // ! LL_WINDOWS - -// Create a text file with specified content "somewhere in the -// filesystem," cleaning up when it goes out of scope. -class NamedTempFile -{ -public: - // Function that accepts an ostream ref and (presumably) writes stuff to - // it, e.g.: - // (lambda::_1 << "the value is " << 17 << '\n') - typedef boost::function Streamer; - - NamedTempFile(const std::string& ext, const std::string& content): - mPath(temp_directory_path()) - { - createFile(ext, lambda::_1 << content); - } - - // Disambiguate when passing string literal - NamedTempFile(const std::string& ext, const char* content): - mPath(temp_directory_path()) - { - createFile(ext, lambda::_1 << content); - } - - NamedTempFile(const std::string& ext, const Streamer& func): - mPath(temp_directory_path()) - { - createFile(ext, func); - } - - ~NamedTempFile() - { - _remove(mPath.c_str()); - } - - std::string getName() const { return mPath; } - -private: - void createFile(const std::string& ext, const Streamer& func) - { - // Silly maybe, but use 'ext' as the name prefix. Strip off a leading - // '.' if present. - int pfx_offset = ((! ext.empty()) && ext[0] == '.')? 1 : 0; - -#if ! LL_WINDOWS - // Make sure mPath ends with a directory separator, if it doesn't already. - if (mPath.empty() || - ! (mPath[mPath.length() - 1] == '\\' || mPath[mPath.length() - 1] == '/')) - { - mPath.append("/"); - } - - // mkstemp() accepts and modifies a char* template string. Generate - // the template string, then copy to modifiable storage. - // mkstemp() requires its template string to end in six X's. - mPath += ext.substr(pfx_offset) + "XXXXXX"; - // Copy to vector - std::vector pathtemplate(mPath.begin(), mPath.end()); - // append a nul byte for classic-C semantics - pathtemplate.push_back('\0'); - // std::vector promises that a pointer to the 0th element is the same - // as a pointer to a contiguous classic-C array - int fd(mkstemp(&pathtemplate[0])); - if (fd == -1) - { - // The documented errno values (http://linux.die.net/man/3/mkstemp) - // are used in a somewhat unusual way, so provide context-specific - // errors. - if (errno == EEXIST) - { - LL_ERRS("NamedTempFile") << "mkstemp(\"" << mPath - << "\") could not create unique file " << LL_ENDL; - } - if (errno == EINVAL) - { - LL_ERRS("NamedTempFile") << "bad mkstemp() file path template '" - << mPath << "'" << LL_ENDL; - } - // Shrug, something else - int mkst_errno = errno; - char buffer[256]; - LL_ERRS("NamedTempFile") << "mkstemp(\"" << mPath << "\") failed: " - << message_from(mkst_errno, buffer, - strerror_r(mkst_errno, buffer, sizeof(buffer))) - << LL_ENDL; - } - // mkstemp() seems to have worked! Capture the modified filename. - // Avoid the nul byte we appended. - mPath.assign(pathtemplate.begin(), (pathtemplate.end()-1)); - -/*==========================================================================*| - // Define an ostream on the open fd. Tell it to close fd on destruction. - boost::iostreams::stream - out(fd, boost::iostreams::close_handle); -|*==========================================================================*/ - - // Write desired content. - std::ostringstream out; - // Stream stuff to it. - func(out); - - std::string data(out.str()); - int written(_write(fd, data.c_str(), data.length())); - int closed(_close(fd)); - llassert_always(written == data.length() && closed == 0); - -#else // LL_WINDOWS - // GetTempFileName() is documented to require a MAX_PATH buffer. - char tempname[MAX_PATH]; - // Use 'ext' as filename prefix, but skip leading '.' if any. - // The 0 param is very important: requests iterating until we get a - // unique name. - if (0 == GetTempFileNameA(mPath.c_str(), ext.c_str() + pfx_offset, 0, tempname)) - { - // I always have to look up this call... :-P - LPSTR msgptr; - FormatMessageA( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - LPSTR(&msgptr), // have to cast (char**) to (char*) - 0, NULL ); - LL_ERRS("NamedTempFile") << "GetTempFileName(\"" << mPath << "\", \"" - << (ext.c_str() + pfx_offset) << "\") failed: " - << msgptr << LL_ENDL; - LocalFree(msgptr); - } - // GetTempFileName() appears to have worked! Capture the actual - // filename. - mPath = tempname; - // Open the file and stream content to it. Destructor will close. - std::ofstream out(tempname); - func(out); - -#endif // LL_WINDOWS - } - - void peep() - { - std::cout << "File '" << mPath << "' contains:\n"; - std::ifstream reader(mPath.c_str()); - std::string line; - while (std::getline(reader, line)) - std::cout << line << '\n'; - std::cout << "---\n"; - } - - std::string mPath; -}; - namespace tut { struct sd_xml_data @@ -1783,7 +1538,7 @@ namespace tut const char* PYTHON(getenv("PYTHON")); ensure("Set $PYTHON to the Python interpreter", PYTHON); - NamedTempFile scriptfile(".py", script); + NamedTempFile scriptfile("py", script); #if LL_WINDOWS std::string q("\""); @@ -1888,12 +1643,12 @@ namespace tut " else:\n" " assert False, 'Too many data items'\n"; - // Create a something.llsd file containing 'data' serialized to + // Create an llsdXXXXXX file containing 'data' serialized to // notation. It's important to separate with newlines because Python's // llsd module doesn't support parsing from a file stream, only from a // string, so we have to know how much of the file to read into a // string. - NamedTempFile file(".llsd", + NamedTempFile file("llsd", // NamedTempFile's boost::function constructor // takes a callable. To this callable it passes the // std::ostream with which it's writing the @@ -1926,7 +1681,7 @@ namespace tut // Create an empty data file. This is just a placeholder for our // script to write into. Create it to establish a unique name that // we know. - NamedTempFile file(".llsd", ""); + NamedTempFile file("llsd", ""); python("write Python notation", lambda::_1 << diff --git a/indra/test/manageapr.h b/indra/test/manageapr.h new file mode 100644 index 0000000000..0c1ca7b7be --- /dev/null +++ b/indra/test/manageapr.h @@ -0,0 +1,45 @@ +/** + * @file manageapr.h + * @author Nat Goodspeed + * @date 2012-01-13 + * @brief ManageAPR class for simple test programs + * + * $LicenseInfo:firstyear=2012&license=viewerlgpl$ + * Copyright (c) 2012, Linden Research, Inc. + * $/LicenseInfo$ + */ + +#if ! defined(LL_MANAGEAPR_H) +#define LL_MANAGEAPR_H + +#include "llapr.h" + +/** + * Declare a static instance of this class for dead-simple ll_init_apr() at + * program startup, ll_cleanup_apr() at termination. This is recommended for + * use only with simple test programs. Once you start introducing static + * instances of other classes that depend on APR already being initialized, + * the indeterminate static-constructor-order problem rears its ugly head. + */ +class ManageAPR +{ +public: + ManageAPR() + { + ll_init_apr(); + } + + ~ManageAPR() + { + ll_cleanup_apr(); + } + + static std::string strerror(apr_status_t rv) + { + char errbuf[256]; + apr_strerror(rv, errbuf, sizeof(errbuf)); + return errbuf; + } +}; + +#endif /* ! defined(LL_MANAGEAPR_H) */ diff --git a/indra/test/namedtempfile.h b/indra/test/namedtempfile.h new file mode 100644 index 0000000000..9670d4db53 --- /dev/null +++ b/indra/test/namedtempfile.h @@ -0,0 +1,113 @@ +/** + * @file namedtempfile.h + * @author Nat Goodspeed + * @date 2012-01-13 + * @brief NamedTempFile class for tests that need disk files as fixtures. + * + * $LicenseInfo:firstyear=2012&license=viewerlgpl$ + * Copyright (c) 2012, Linden Research, Inc. + * $/LicenseInfo$ + */ + +#if ! defined(LL_NAMEDTEMPFILE_H) +#define LL_NAMEDTEMPFILE_H + +#include "llapr.h" +#include "apr_file_io.h" +#include +#include +#include "boost/lambda/lambda.hpp" +#include "boost/lambda/bind.hpp" +#include +#include + +/** + * Create a text file with specified content "somewhere in the + * filesystem," cleaning up when it goes out of scope. + */ +class NamedTempFile +{ +public: + NamedTempFile(const std::string& pfx, const std::string& content, apr_pool_t* pool=gAPRPoolp): + mPool(pool) + { + createFile(pfx, boost::lambda::_1 << content); + } + + // Disambiguate when passing string literal + NamedTempFile(const std::string& pfx, const char* content, apr_pool_t* pool=gAPRPoolp): + mPool(pool) + { + createFile(pfx, boost::lambda::_1 << content); + } + + // Function that accepts an ostream ref and (presumably) writes stuff to + // it, e.g.: + // (boost::lambda::_1 << "the value is " << 17 << '\n') + typedef boost::function Streamer; + + NamedTempFile(const std::string& pfx, const Streamer& func, apr_pool_t* pool=gAPRPoolp): + mPool(pool) + { + createFile(pfx, func); + } + + ~NamedTempFile() + { + ll_apr_assert_status(apr_file_remove(mPath.c_str(), mPool)); + } + + std::string getName() const { return mPath; } + +private: + void createFile(const std::string& pfx, const Streamer& func) + { + // Create file in a temporary place. + const char* tempdir = NULL; + ll_apr_assert_status(apr_temp_dir_get(&tempdir, mPool)); + + // Construct a temp filename template in that directory. + char *tempname = NULL; + ll_apr_assert_status(apr_filepath_merge(&tempname, + tempdir, + (pfx + "XXXXXX").c_str(), + 0, + mPool)); + + // Create a temp file from that template. + apr_file_t* fp = NULL; + ll_apr_assert_status(apr_file_mktemp(&fp, + tempname, + APR_CREATE | APR_WRITE | APR_EXCL, + mPool)); + // apr_file_mktemp() alters tempname with the actual name. Not until + // now is it valid to capture as our mPath. + mPath = tempname; + + // Write desired content. + std::ostringstream out; + // Stream stuff to it. + func(out); + + std::string data(out.str()); + apr_size_t writelen(data.length()); + ll_apr_assert_status(apr_file_write(fp, data.c_str(), &writelen)); + ll_apr_assert_status(apr_file_close(fp)); + llassert_always(writelen == data.length()); + } + + void peep() + { + std::cout << "File '" << mPath << "' contains:\n"; + std::ifstream reader(mPath.c_str()); + std::string line; + while (std::getline(reader, line)) + std::cout << line << '\n'; + std::cout << "---\n"; + } + + std::string mPath; + apr_pool_t* mPool; +}; + +#endif /* ! defined(LL_NAMEDTEMPFILE_H) */ -- cgit v1.2.3 From a01dd3549cca620de47fae824198473c51a12f49 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Tue, 17 Jan 2012 18:40:05 -0500 Subject: Make NamedTempFile::peep() a public member for debugging unit tests. --- indra/test/namedtempfile.h | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) (limited to 'indra') diff --git a/indra/test/namedtempfile.h b/indra/test/namedtempfile.h index 9670d4db53..7ffb2836cc 100644 --- a/indra/test/namedtempfile.h +++ b/indra/test/namedtempfile.h @@ -59,6 +59,16 @@ public: std::string getName() const { return mPath; } + void peep() + { + std::cout << "File '" << mPath << "' contains:\n"; + std::ifstream reader(mPath.c_str()); + std::string line; + while (std::getline(reader, line)) + std::cout << line << '\n'; + std::cout << "---\n"; + } + private: void createFile(const std::string& pfx, const Streamer& func) { @@ -96,16 +106,6 @@ private: llassert_always(writelen == data.length()); } - void peep() - { - std::cout << "File '" << mPath << "' contains:\n"; - std::ifstream reader(mPath.c_str()); - std::string line; - while (std::getline(reader, line)) - std::cout << line << '\n'; - std::cout << "---\n"; - } - std::string mPath; apr_pool_t* mPool; }; -- cgit v1.2.3 From c0731c1c05cafe508c91c5f583301234ba3b8403 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Tue, 17 Jan 2012 18:55:42 -0500 Subject: Add log message if LLProcessLauncher child fails to execv(). On a Posix platform (vfork()/execv() implementation), if for any reason the execv() failed (e.g. executable not on PATH), the viewer would never know, nor the user: the vfork() child produced no output, and terminated with rc 0! Add logging, make child terminate with nonzero rc. Remove pointless addArgument(const char*) overload: this does nothing for you that the compiler won't do implicitly. In llupdateinstaller.cpp, remove pointless c_str() call in addArgument() arg: we were starting with a std::string, then extracting its c_str(), only to construct a whole new std::string from it! --- indra/llcommon/llprocesslauncher.cpp | 20 +++++++++++--------- indra/llcommon/llprocesslauncher.h | 4 +++- .../viewer_components/updater/llupdateinstaller.cpp | 2 +- 3 files changed, 15 insertions(+), 11 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/llprocesslauncher.cpp b/indra/llcommon/llprocesslauncher.cpp index 10950181fd..25d64e9e28 100644 --- a/indra/llcommon/llprocesslauncher.cpp +++ b/indra/llcommon/llprocesslauncher.cpp @@ -73,11 +73,6 @@ void LLProcessLauncher::addArgument(const std::string &arg) mLaunchArguments.push_back(arg); } -void LLProcessLauncher::addArgument(const char *arg) -{ - mLaunchArguments.push_back(std::string(arg)); -} - #if LL_WINDOWS int LLProcessLauncher::launch(void) @@ -262,12 +257,19 @@ int LLProcessLauncher::launch(void) if(id == 0) { // child process - ::execv(mExecutable.c_str(), (char * const *)fake_argv); - + // If we reach this point, the exec failed. - // Use _exit() instead of exit() per the vfork man page. - _exit(0); + LL_WARNS("LLProcessLauncher") << "failed to launch: "; + for (const char * const * ai = fake_argv; *ai; ++ai) + { + LL_CONT << *ai << ' '; + } + LL_CONT << LL_ENDL; + // Use _exit() instead of exit() per the vfork man page. Exit with a + // distinctive rc: someday soon we'll be able to retrieve it, and it + // would be nice to be able to tell that the child process failed! + _exit(249); } // parent process diff --git a/indra/llcommon/llprocesslauncher.h b/indra/llcommon/llprocesslauncher.h index 954c249147..1daa980c58 100644 --- a/indra/llcommon/llprocesslauncher.h +++ b/indra/llcommon/llprocesslauncher.h @@ -28,6 +28,7 @@ #define LL_LLPROCESSLAUNCHER_H #if LL_WINDOWS +#define WIN32_LEAN_AND_MEAN #include #endif @@ -51,7 +52,6 @@ public: void clearArguments(); void addArgument(const std::string &arg); - void addArgument(const char *arg); int launch(void); bool isRunning(void); @@ -66,10 +66,12 @@ public: void orphan(void); // This needs to be called periodically on Mac/Linux to clean up zombie processes. + // (However, as of 2012-01-12 there are no such calls in the viewer code base. :-P ) static void reap(void); // Accessors for platform-specific process ID #if LL_WINDOWS + // (Windows flavor unused as of 2012-01-12) HANDLE getProcessHandle() { return mProcessHandle; }; #else pid_t getProcessID() { return mProcessID; }; diff --git a/indra/viewer_components/updater/llupdateinstaller.cpp b/indra/viewer_components/updater/llupdateinstaller.cpp index c7b70c2de8..84f23b3acc 100644 --- a/indra/viewer_components/updater/llupdateinstaller.cpp +++ b/indra/viewer_components/updater/llupdateinstaller.cpp @@ -81,7 +81,7 @@ int ll_install_update(std::string const & script, LLProcessLauncher launcher; launcher.setExecutable(actualScriptPath); launcher.addArgument(updatePath); - launcher.addArgument(ll_install_failed_marker_path().c_str()); + launcher.addArgument(ll_install_failed_marker_path()); launcher.addArgument(boost::lexical_cast(required)); int result = launcher.launch(); launcher.orphan(); -- cgit v1.2.3 From 74fbd31813494fe120211fbdad3ed6da9c2d5d8b Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Tue, 17 Jan 2012 19:03:17 -0500 Subject: Add first couple of LLProcessLauncher tests. Run INTEGRATION_TEST_llprocesslauncher using setpython.py so we can find the Python interpreter of interest. Introduce python() function to run a Python script specified using NamedTempFile conventions. Introduce a convention by which we can read output from a Python script using only the limited pre-January-2012 LLProcessLauncher API. Introduce python_out() function to leverage that convention. Exercise a couple of LLProcessLauncher methods using all the above. --- indra/llcommon/CMakeLists.txt | 3 +- indra/llcommon/tests/llprocesslauncher_test.cpp | 146 ++++++++++++++++++++++++ 2 files changed, 148 insertions(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/llcommon/CMakeLists.txt b/indra/llcommon/CMakeLists.txt index 334f78cbff..2c376bb016 100644 --- a/indra/llcommon/CMakeLists.txt +++ b/indra/llcommon/CMakeLists.txt @@ -328,7 +328,8 @@ if (LL_TESTS) LL_ADD_INTEGRATION_TEST(reflection "" "${test_libs}") LL_ADD_INTEGRATION_TEST(stringize "" "${test_libs}") LL_ADD_INTEGRATION_TEST(lleventdispatcher "" "${test_libs}") - LL_ADD_INTEGRATION_TEST(llprocesslauncher "" "${test_libs}") + LL_ADD_INTEGRATION_TEST(llprocesslauncher "" "${test_libs}" + "${PYTHON_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/setpython.py") LL_ADD_INTEGRATION_TEST(llstreamqueue "" "${test_libs}") # *TODO - reenable these once tcmalloc libs no longer break the build. diff --git a/indra/llcommon/tests/llprocesslauncher_test.cpp b/indra/llcommon/tests/llprocesslauncher_test.cpp index 3935c64a94..aebd280c2e 100644 --- a/indra/llcommon/tests/llprocesslauncher_test.cpp +++ b/indra/llcommon/tests/llprocesslauncher_test.cpp @@ -18,10 +18,14 @@ #include #include // std headers +#include // external library headers #include "llapr.h" #include "apr_thread_proc.h" #include +#include +#include +#include // other Linden headers #include "../test/lltut.h" #include "../test/manageapr.h" @@ -36,6 +40,8 @@ #include #endif +namespace lambda = boost::lambda; + // static instance of this manages APR init/cleanup static ManageAPR manager; @@ -56,6 +62,116 @@ namespace tut rv, expected); } + /** + * Run a Python script using LLProcessLauncher. + * @param desc Arbitrary description for error messages + * @param script Python script, any form acceptable to NamedTempFile, + * typically either a std::string or an expression of the form + * (lambda::_1 << "script content with " << variable_data) + * @param arg If specified, will be passed to script as its + * sys.argv[1] + * @param tweak "Do something" to LLProcessLauncher object before + * calling its launch() method. This program is to test + * LLProcessLauncher, but many such tests are "just like" this + * python() function but for one or two extra method calls before + * launch(). This avoids us having to clone & edit this function for + * such tests. + */ + template + void python(const std::string& desc, const CONTENT& script, const std::string& arg="", + const boost::function tweak=lambda::_1) + { + const char* PYTHON(getenv("PYTHON")); + ensure("Set $PYTHON to the Python interpreter", PYTHON); + + NamedTempFile scriptfile("py", script); + LLProcessLauncher py; + py.setExecutable(PYTHON); + py.addArgument(scriptfile.getName()); + if (! arg.empty()) + { + py.addArgument(arg); + } + tweak(py); + ensure_equals(STRINGIZE("Couldn't launch " << desc << " script"), py.launch(), 0); + // One of the irritating things about LLProcessLauncher is that + // there's no API to wait for the child to terminate -- but given + // its use in our graphics-intensive interactive viewer, it's + // understandable. + while (py.isRunning()) + { + sleep(1); + } + } + + /** + * Run a Python script using LLProcessLauncher, expecting that it will + * write to the file passed as its sys.argv[1]. Retrieve that output. + * + * Until January 2012, LLProcessLauncher provided distressingly few + * mechanisms for a child process to communicate back to its caller -- + * not even its return code. We've introduced a convention by which we + * create an empty temp file, pass the name of that file to our child + * as sys.argv[1] and expect the script to write its output to that + * file. This function implements the C++ (parent process) side of + * that convention. + * + * @param desc as for python() + * @param script as for python() + * @param tweak as for python() + */ + template + std::string python_out(const std::string& desc, const CONTENT& script, + const boost::function tweak=lambda::_1) + { + NamedTempFile out("out", ""); // placeholder + // pass name of this temporary file to the script + python(desc, script, out.getName(), tweak); + // assuming the script wrote a line to that file, read it + std::string output; + { + std::ifstream inf(out.getName().c_str()); + ensure(STRINGIZE("No output from " << desc << " script"), + std::getline(inf, output)); + std::string more; + while (std::getline(inf, more)) + { + output += '\n' + more; + } + } // important to close inf BEFORE removing NamedTempFile + return output; + } + + class NamedTempDir + { + public: + // Use python() function to create a temp directory: I've found + // nothing in either Boost.Filesystem or APR quite like Python's + // tempfile.mkdtemp(). + // Special extra bonus: on Mac, mkdtemp() reports a pathname + // starting with /var/folders/something, whereas that's really a + // symlink to /private/var/folders/something. Have to use + // realpath() to compare properly. + NamedTempDir(llprocesslauncher_data* ths): + mThis(ths), + mPath(ths->python_out("mkdtemp()", + "import os.path, sys, tempfile\n" + "with open(sys.argv[1], 'w') as f:\n" + " f.write(os.path.realpath(tempfile.mkdtemp()))\n")) + {} + + ~NamedTempDir() + { + mThis->aprchk(apr_dir_remove(mPath.c_str(), gAPRPoolp)); + } + + std::string getName() const { return mPath; } + + private: + llprocesslauncher_data* mThis; + std::string mPath; + }; + LLAPRPool pool; }; typedef test_group llprocesslauncher_group; @@ -349,4 +465,34 @@ namespace tut throw; } } + + template<> template<> + void object::test<2>() + { + set_test_name("set/getExecutable()"); + LLProcessLauncher child; + child.setExecutable("nonsense string"); + ensure_equals("setExecutable() 0", child.getExecutable(), "nonsense string"); + child.setExecutable("python"); + ensure_equals("setExecutable() 1", child.getExecutable(), "python"); + } + + template<> template<> + void object::test<3>() + { + set_test_name("setWorkingDirectory()"); + // We want to test setWorkingDirectory(). But what directory is + // guaranteed to exist on every machine, under every OS? Have to + // create one. + NamedTempDir tempdir(this); + std::string cwd(python_out("getcwd()", + "import os, sys\n" + "with open(sys.argv[1], 'w') as f:\n" + " f.write(os.getcwd())\n", + // Before LLProcessLauncher::launch(), call setWorkingDirectory() + lambda::bind(&LLProcessLauncher::setWorkingDirectory, + lambda::_1, + tempdir.getName()))); + ensure_equals("os.getcwd()", cwd, tempdir.getName()); + } } // namespace tut -- cgit v1.2.3 From 51b26cab9ad8dc54277c6158ad40afdf3ed0e6d0 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Tue, 17 Jan 2012 20:30:46 -0500 Subject: Any proper RAII class must either handle copying or be noncopyable. NamedTempFile makes no attempt to deal with copying, therefore make it noncopyable. --- indra/test/namedtempfile.h | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'indra') diff --git a/indra/test/namedtempfile.h b/indra/test/namedtempfile.h index 7ffb2836cc..aa7058b111 100644 --- a/indra/test/namedtempfile.h +++ b/indra/test/namedtempfile.h @@ -16,8 +16,9 @@ #include "apr_file_io.h" #include #include -#include "boost/lambda/lambda.hpp" -#include "boost/lambda/bind.hpp" +#include +#include +#include #include #include @@ -25,7 +26,7 @@ * Create a text file with specified content "somewhere in the * filesystem," cleaning up when it goes out of scope. */ -class NamedTempFile +class NamedTempFile: public boost::noncopyable { public: NamedTempFile(const std::string& pfx, const std::string& content, apr_pool_t* pool=gAPRPoolp): -- cgit v1.2.3 From 2ae9f921f2e1d6bd10e4c334a19312761a914046 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Tue, 17 Jan 2012 20:44:26 -0500 Subject: Refactor llprocesslauncher_test.cpp for better code reuse. Instead of free python() and python_out() functions containing a local temporary LLProcessLauncher instance, with a 'tweak' callback param to "do stuff" to that inaccessible object, change to a PythonProcessLauncher class that sets up a (public) LLProcessLauncher member, then allows you to run() or run() and then readfile() the output. Now you can construct an instance and tweak to your heart's content -- without funky callback syntax -- before running the script. Move all such helpers from TUT fixture struct to namespace scope. While fixture-struct methods can freely call one another, introducing a nested class gets awkward: constructor must explicitly require and bind a fixture-struct pointer or reference. Namespace scope solves this. (Truthfully, I only put them in the fixture struct originally because I thought it necessary for calling ensure() et al. But ensure() and friends are free functions; need only qualify them with tut:: namespace.) --- indra/llcommon/tests/llprocesslauncher_test.cpp | 282 +++++++++++++----------- 1 file changed, 155 insertions(+), 127 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/tests/llprocesslauncher_test.cpp b/indra/llcommon/tests/llprocesslauncher_test.cpp index aebd280c2e..310271e465 100644 --- a/indra/llcommon/tests/llprocesslauncher_test.cpp +++ b/indra/llcommon/tests/llprocesslauncher_test.cpp @@ -12,7 +12,6 @@ // Precompiled header #include "linden_common.h" // associated header -#define WIN32_LEAN_AND_MEAN #include "llprocesslauncher.h" // STL headers #include @@ -24,8 +23,8 @@ #include "apr_thread_proc.h" #include #include -#include -#include +//#include +//#include // other Linden headers #include "../test/lltut.h" #include "../test/manageapr.h" @@ -40,138 +39,169 @@ #include #endif -namespace lambda = boost::lambda; +//namespace lambda = boost::lambda; // static instance of this manages APR init/cleanup static ManageAPR manager; +/***************************************************************************** +* Helpers +*****************************************************************************/ + #define ensure_equals_(left, right) \ ensure_equals(STRINGIZE(#left << " != " << #right), (left), (right)) + #define aprchk(expr) aprchk_(#expr, (expr)) +static void aprchk_(const char* call, apr_status_t rv, apr_status_t expected=APR_SUCCESS) +{ + tut::ensure_equals(STRINGIZE(call << " => " << rv << ": " << manager.strerror(rv)), + rv, expected); +} -/***************************************************************************** -* TUT -*****************************************************************************/ -namespace tut +/** + * Read specified file using std::getline(). It is assumed to be an error if + * the file is empty: don't use this function if that's an acceptable case. + * Last line will not end with '\n'; this is to facilitate the usual case of + * string compares with a single line of output. + * @param pathname The file to read. + * @param desc Optional description of the file for error message; + * defaults to "in " + */ +static std::string readfile(const std::string& pathname, const std::string& desc="") { - struct llprocesslauncher_data + std::string use_desc(desc); + if (use_desc.empty()) { - void aprchk_(const char* call, apr_status_t rv, apr_status_t expected=APR_SUCCESS) - { - ensure_equals(STRINGIZE(call << " => " << rv << ": " << manager.strerror(rv)), - rv, expected); - } + use_desc = STRINGIZE("in " << pathname); + } + std::ifstream inf(pathname.c_str()); + std::string output; + tut::ensure(STRINGIZE("No output " << use_desc), std::getline(inf, output)); + std::string more; + while (std::getline(inf, more)) + { + output += '\n' + more; + } + return output; +} - /** - * Run a Python script using LLProcessLauncher. - * @param desc Arbitrary description for error messages - * @param script Python script, any form acceptable to NamedTempFile, - * typically either a std::string or an expression of the form - * (lambda::_1 << "script content with " << variable_data) - * @param arg If specified, will be passed to script as its - * sys.argv[1] - * @param tweak "Do something" to LLProcessLauncher object before - * calling its launch() method. This program is to test - * LLProcessLauncher, but many such tests are "just like" this - * python() function but for one or two extra method calls before - * launch(). This avoids us having to clone & edit this function for - * such tests. - */ - template - void python(const std::string& desc, const CONTENT& script, const std::string& arg="", - const boost::function tweak=lambda::_1) - { - const char* PYTHON(getenv("PYTHON")); - ensure("Set $PYTHON to the Python interpreter", PYTHON); - - NamedTempFile scriptfile("py", script); - LLProcessLauncher py; - py.setExecutable(PYTHON); - py.addArgument(scriptfile.getName()); - if (! arg.empty()) - { - py.addArgument(arg); - } - tweak(py); - ensure_equals(STRINGIZE("Couldn't launch " << desc << " script"), py.launch(), 0); - // One of the irritating things about LLProcessLauncher is that - // there's no API to wait for the child to terminate -- but given - // its use in our graphics-intensive interactive viewer, it's - // understandable. - while (py.isRunning()) - { - sleep(1); - } - } +/** + * Construct an LLProcessLauncher to run a Python script. + */ +struct PythonProcessLauncher +{ + /** + * @param desc Arbitrary description for error messages + * @param script Python script, any form acceptable to NamedTempFile, + * typically either a std::string or an expression of the form + * (lambda::_1 << "script content with " << variable_data) + */ + template + PythonProcessLauncher(const std::string& desc, const CONTENT& script): + mDesc(desc), + mScript("py", script) + { + const char* PYTHON(getenv("PYTHON")); + tut::ensure("Set $PYTHON to the Python interpreter", PYTHON); + + mPy.setExecutable(PYTHON); + mPy.addArgument(mScript.getName()); + } - /** - * Run a Python script using LLProcessLauncher, expecting that it will - * write to the file passed as its sys.argv[1]. Retrieve that output. - * - * Until January 2012, LLProcessLauncher provided distressingly few - * mechanisms for a child process to communicate back to its caller -- - * not even its return code. We've introduced a convention by which we - * create an empty temp file, pass the name of that file to our child - * as sys.argv[1] and expect the script to write its output to that - * file. This function implements the C++ (parent process) side of - * that convention. - * - * @param desc as for python() - * @param script as for python() - * @param tweak as for python() - */ - template - std::string python_out(const std::string& desc, const CONTENT& script, - const boost::function tweak=lambda::_1) + /// Run Python script and wait for it to complete. + void run() + { + tut::ensure_equals(STRINGIZE("Couldn't launch " << mDesc << " script"), + mPy.launch(), 0); + // One of the irritating things about LLProcessLauncher is that + // there's no API to wait for the child to terminate -- but given + // its use in our graphics-intensive interactive viewer, it's + // understandable. + while (mPy.isRunning()) { - NamedTempFile out("out", ""); // placeholder - // pass name of this temporary file to the script - python(desc, script, out.getName(), tweak); - // assuming the script wrote a line to that file, read it - std::string output; - { - std::ifstream inf(out.getName().c_str()); - ensure(STRINGIZE("No output from " << desc << " script"), - std::getline(inf, output)); - std::string more; - while (std::getline(inf, more)) - { - output += '\n' + more; - } - } // important to close inf BEFORE removing NamedTempFile - return output; + sleep(1); } + } - class NamedTempDir - { - public: - // Use python() function to create a temp directory: I've found - // nothing in either Boost.Filesystem or APR quite like Python's - // tempfile.mkdtemp(). - // Special extra bonus: on Mac, mkdtemp() reports a pathname - // starting with /var/folders/something, whereas that's really a - // symlink to /private/var/folders/something. Have to use - // realpath() to compare properly. - NamedTempDir(llprocesslauncher_data* ths): - mThis(ths), - mPath(ths->python_out("mkdtemp()", - "import os.path, sys, tempfile\n" - "with open(sys.argv[1], 'w') as f:\n" - " f.write(os.path.realpath(tempfile.mkdtemp()))\n")) - {} - - ~NamedTempDir() - { - mThis->aprchk(apr_dir_remove(mPath.c_str(), gAPRPoolp)); - } + /** + * Run a Python script using LLProcessLauncher, expecting that it will + * write to the file passed as its sys.argv[1]. Retrieve that output. + * + * Until January 2012, LLProcessLauncher provided distressingly few + * mechanisms for a child process to communicate back to its caller -- + * not even its return code. We've introduced a convention by which we + * create an empty temp file, pass the name of that file to our child + * as sys.argv[1] and expect the script to write its output to that + * file. This function implements the C++ (parent process) side of + * that convention. + */ + std::string run_read() + { + NamedTempFile out("out", ""); // placeholder + // pass name of this temporary file to the script + mPy.addArgument(out.getName()); + run(); + // assuming the script wrote to that file, read it + return readfile(out.getName(), STRINGIZE("from " << mDesc << " script")); + } + + LLProcessLauncher mPy; + std::string mDesc; + NamedTempFile mScript; +}; + +/// convenience function for PythonProcessLauncher::run() +template +static void python(const std::string& desc, const CONTENT& script) +{ + PythonProcessLauncher py(desc, script); + py.run(); +} + +/// convenience function for PythonProcessLauncher::run_read() +template +static std::string python_out(const std::string& desc, const CONTENT& script) +{ + PythonProcessLauncher py(desc, script); + return py.run_read(); +} + +/// Create a temporary directory and clean it up later. +class NamedTempDir: public boost::noncopyable +{ +public: + // Use python() function to create a temp directory: I've found + // nothing in either Boost.Filesystem or APR quite like Python's + // tempfile.mkdtemp(). + // Special extra bonus: on Mac, mkdtemp() reports a pathname + // starting with /var/folders/something, whereas that's really a + // symlink to /private/var/folders/something. Have to use + // realpath() to compare properly. + NamedTempDir(): + mPath(python_out("mkdtemp()", + "import os.path, sys, tempfile\n" + "with open(sys.argv[1], 'w') as f:\n" + " f.write(os.path.realpath(tempfile.mkdtemp()))\n")) + {} + + ~NamedTempDir() + { + aprchk(apr_dir_remove(mPath.c_str(), gAPRPoolp)); + } - std::string getName() const { return mPath; } + std::string getName() const { return mPath; } - private: - llprocesslauncher_data* mThis; - std::string mPath; - }; +private: + std::string mPath; +}; +/***************************************************************************** +* TUT +*****************************************************************************/ +namespace tut +{ + struct llprocesslauncher_data + { LLAPRPool pool; }; typedef test_group llprocesslauncher_group; @@ -484,15 +514,13 @@ namespace tut // We want to test setWorkingDirectory(). But what directory is // guaranteed to exist on every machine, under every OS? Have to // create one. - NamedTempDir tempdir(this); - std::string cwd(python_out("getcwd()", - "import os, sys\n" - "with open(sys.argv[1], 'w') as f:\n" - " f.write(os.getcwd())\n", - // Before LLProcessLauncher::launch(), call setWorkingDirectory() - lambda::bind(&LLProcessLauncher::setWorkingDirectory, - lambda::_1, - tempdir.getName()))); - ensure_equals("os.getcwd()", cwd, tempdir.getName()); + NamedTempDir tempdir; + PythonProcessLauncher py("getcwd()", + "import os, sys\n" + "with open(sys.argv[1], 'w') as f:\n" + " f.write(os.getcwd())\n"); + // Before running, call setWorkingDirectory() + py.mPy.setWorkingDirectory(tempdir.getName()); + ensure_equals("os.getcwd()", py.run_read(), tempdir.getName()); } } // namespace tut -- cgit v1.2.3 From 4bfd84d3be8d33bc6eb0dab22d2b3034de0800c9 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Tue, 17 Jan 2012 21:40:41 -0500 Subject: Add tests for child-process args management and for kill() method. --- indra/llcommon/tests/llprocesslauncher_test.cpp | 80 ++++++++++++++++++++++++- 1 file changed, 79 insertions(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/llcommon/tests/llprocesslauncher_test.cpp b/indra/llcommon/tests/llprocesslauncher_test.cpp index 310271e465..4f6a6ed922 100644 --- a/indra/llcommon/tests/llprocesslauncher_test.cpp +++ b/indra/llcommon/tests/llprocesslauncher_test.cpp @@ -23,6 +23,8 @@ #include "apr_thread_proc.h" #include #include +#include +#include //#include //#include // other Linden headers @@ -513,7 +515,7 @@ namespace tut set_test_name("setWorkingDirectory()"); // We want to test setWorkingDirectory(). But what directory is // guaranteed to exist on every machine, under every OS? Have to - // create one. + // create one. Naturally, ensure we clean it up when done. NamedTempDir tempdir; PythonProcessLauncher py("getcwd()", "import os, sys\n" @@ -523,4 +525,80 @@ namespace tut py.mPy.setWorkingDirectory(tempdir.getName()); ensure_equals("os.getcwd()", py.run_read(), tempdir.getName()); } + + template<> template<> + void object::test<4>() + { + set_test_name("clearArguments()"); + PythonProcessLauncher py("args", + "import sys\n" + // note nonstandard output-file arg! + "with open(sys.argv[3], 'w') as f:\n" + " for arg in sys.argv[1:]:\n" + " print >>f, arg\n"); + // We expect that PythonProcessLauncher has already called + // addArgument() with the name of its own NamedTempFile. But let's + // change it up. + py.mPy.clearArguments(); + // re-add script pathname + py.mPy.addArgument(py.mScript.getName()); // sys.argv[0] + py.mPy.addArgument("first arg"); // sys.argv[1] + py.mPy.addArgument("second arg"); // sys.argv[2] + // run_read() calls addArgument() one more time, hence [3] + std::string output(py.run_read()); + boost::split_iterator + li(output, boost::first_finder("\n")), lend; + ensure("didn't get first arg", li != lend); + std::string arg(li->begin(), li->end()); + ensure_equals(arg, "first arg"); + ++li; + ensure("didn't get second arg", li != lend); + arg.assign(li->begin(), li->end()); + ensure_equals(arg, "second arg"); + ++li; + ensure("didn't get output filename?!", li != lend); + arg.assign(li->begin(), li->end()); + ensure("output filename empty?!", ! arg.empty()); + ++li; + ensure("too many args", li == lend); + } + + template<> template<> + void object::test<5>() + { + set_test_name("kill()"); + PythonProcessLauncher py("kill()", + "import sys, time\n" + "with open(sys.argv[1], 'w') as f:\n" + " f.write('ok')\n" + "# now sleep; expect caller to kill\n" + "time.sleep(120)\n" + "# if caller hasn't managed to kill by now, bad\n" + "with open(sys.argv[1], 'w') as f:\n" + " f.write('bad')\n"); + NamedTempFile out("out", "not started"); + py.mPy.addArgument(out.getName()); + ensure_equals("couldn't launch kill() script", py.mPy.launch(), 0); + // Wait for the script to wake up and do its first write + int i = 0, timeout = 60; + for ( ; i < timeout; ++i) + { + sleep(1); + if (readfile(out.getName(), "from kill() script") == "ok") + break; + } + // If we broke this loop because of the counter, something's wrong + ensure("script never started", i < timeout); + // script has performed its first write and should now be sleeping. + py.mPy.kill(); + // wait for the script to terminate... one way or another. + while (py.mPy.isRunning()) + { + sleep(1); + } + // If kill() failed, the script would have woken up on its own and + // overwritten the file with 'bad'. But if kill() succeeded, it should + // not have had that chance. + ensure_equals("kill() script output", readfile(out.getName()), "ok"); + } } // namespace tut -- cgit v1.2.3 From 06f9dbd8db9895f81d7bd325d8cf616f68533396 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Wed, 18 Jan 2012 01:09:50 -0500 Subject: Introduce static LLProcessLauncher::isRunning(ll_pid_t) method. typedef LLProcessLauncher::ll_pid_t to be HANDLE on Windows, pid_t elsewhere. Then we can define getProcessID() returning ll_pid_t on all platforms, retaining getProcessHandle() for hypothetical existing consumers... of which there are none in practice. This lets us define isRunning(ll_pid_t) to encapsulate the platform-specific logic to actually check on a running child process, turning non-static isRunning() into a fairly trivial wrapper. --- indra/llcommon/llprocesslauncher.cpp | 49 +++++++++++++++++++++++------------- indra/llcommon/llprocesslauncher.h | 19 ++++++++++++-- 2 files changed, 48 insertions(+), 20 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/llprocesslauncher.cpp b/indra/llcommon/llprocesslauncher.cpp index 25d64e9e28..e1af49c2fb 100644 --- a/indra/llcommon/llprocesslauncher.cpp +++ b/indra/llcommon/llprocesslauncher.cpp @@ -143,18 +143,25 @@ int LLProcessLauncher::launch(void) bool LLProcessLauncher::isRunning(void) { - if(mProcessHandle != 0) + mProcessHandle = isRunning(mProcessHandle); + return (mProcessHandle != 0); +} + +LLProcessLauncher::ll_pid_t LLProcessLauncher::isRunning(ll_pid_t handle) +{ + if (! handle) + return 0; + + DWORD waitresult = WaitForSingleObject(handle, 0); + if(waitresult == WAIT_OBJECT_0) { - DWORD waitresult = WaitForSingleObject(mProcessHandle, 0); - if(waitresult == WAIT_OBJECT_0) - { - // the process has completed. - mProcessHandle = 0; - } + // the process has completed. + return 0; } - return (mProcessHandle != 0); + return handle; } + bool LLProcessLauncher::kill(void) { bool result = true; @@ -293,19 +300,25 @@ int LLProcessLauncher::launch(void) bool LLProcessLauncher::isRunning(void) { - if(mProcessID != 0) - { - // Check whether the process has exited, and reap it if it has. - if(reap_pid(mProcessID)) - { - // the process has exited. - mProcessID = 0; - } - } - + mProcessID = isRunning(mProcessID); return (mProcessID != 0); } +LLProcessLauncher::ll_pid_t LLProcessLauncher::isRunning(ll_pid_t pid) +{ + if (! pid) + return 0; + + // Check whether the process has exited, and reap it if it has. + if(reap_pid(pid)) + { + // the process has exited. + return 0; + } + + return pid; +} + bool LLProcessLauncher::kill(void) { bool result = true; diff --git a/indra/llcommon/llprocesslauncher.h b/indra/llcommon/llprocesslauncher.h index 1daa980c58..63193abd8f 100644 --- a/indra/llcommon/llprocesslauncher.h +++ b/indra/llcommon/llprocesslauncher.h @@ -54,6 +54,8 @@ public: void addArgument(const std::string &arg); int launch(void); + // isRunning isn't const because, if child isn't running, it clears stored + // process ID bool isRunning(void); // Attempt to kill the process -- returns true if the process is no longer running when it returns. @@ -72,10 +74,23 @@ public: // Accessors for platform-specific process ID #if LL_WINDOWS // (Windows flavor unused as of 2012-01-12) - HANDLE getProcessHandle() { return mProcessHandle; }; + typedef HANDLE ll_pid_t; + HANDLE getProcessHandle() const { return mProcessHandle; } + ll_pid_t getProcessID() const { return mProcessHandle; } #else - pid_t getProcessID() { return mProcessID; }; + typedef pid_t ll_pid_t; + ll_pid_t getProcessID() const { return mProcessID; }; #endif + /** + * Test if a process (ll_pid_t obtained from getProcessID()) is still + * running. Return is same nonzero ll_pid_t value if still running, else + * zero, so you can test it like a bool. But if you want to update a + * stored variable as a side effect, you can write code like this: + * @code + * childpid = LLProcessLauncher::isRunning(childpid); + * @endcode + */ + static ll_pid_t isRunning(ll_pid_t); private: std::string mExecutable; -- cgit v1.2.3 From ff4addd1b427344c6064734bdb59952e78f759fd Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Wed, 18 Jan 2012 01:10:52 -0500 Subject: Add tests for implicit-kill-on-destroy, also orphan() method. --- indra/llcommon/tests/llprocesslauncher_test.cpp | 110 +++++++++++++++++++++++- 1 file changed, 109 insertions(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/llcommon/tests/llprocesslauncher_test.cpp b/indra/llcommon/tests/llprocesslauncher_test.cpp index 4f6a6ed922..7c0f0eaa84 100644 --- a/indra/llcommon/tests/llprocesslauncher_test.cpp +++ b/indra/llcommon/tests/llprocesslauncher_test.cpp @@ -566,7 +566,7 @@ namespace tut template<> template<> void object::test<5>() { - set_test_name("kill()"); + set_test_name("explicit kill()"); PythonProcessLauncher py("kill()", "import sys, time\n" "with open(sys.argv[1], 'w') as f:\n" @@ -601,4 +601,112 @@ namespace tut // not have had that chance. ensure_equals("kill() script output", readfile(out.getName()), "ok"); } + + template<> template<> + void object::test<6>() + { + set_test_name("implicit kill()"); + NamedTempFile out("out", "not started"); + LLProcessLauncher::ll_pid_t pid(0); + { + PythonProcessLauncher py("kill()", + "import sys, time\n" + "with open(sys.argv[1], 'w') as f:\n" + " f.write('ok')\n" + "# now sleep; expect caller to kill\n" + "time.sleep(120)\n" + "# if caller hasn't managed to kill by now, bad\n" + "with open(sys.argv[1], 'w') as f:\n" + " f.write('bad')\n"); + py.mPy.addArgument(out.getName()); + ensure_equals("couldn't launch kill() script", py.mPy.launch(), 0); + // Capture ll_pid_t for later + pid = py.mPy.getProcessID(); + // Wait for the script to wake up and do its first write + int i = 0, timeout = 60; + for ( ; i < timeout; ++i) + { + sleep(1); + if (readfile(out.getName(), "from kill() script") == "ok") + break; + } + // If we broke this loop because of the counter, something's wrong + ensure("script never started", i < timeout); + // Script has performed its first write and should now be sleeping. + // Destroy the LLProcessLauncher, which should kill the child. + } + // wait for the script to terminate... one way or another. + while (LLProcessLauncher::isRunning(pid)) + { + sleep(1); + } + // If kill() failed, the script would have woken up on its own and + // overwritten the file with 'bad'. But if kill() succeeded, it should + // not have had that chance. + ensure_equals("kill() script output", readfile(out.getName()), "ok"); + } + + template<> template<> + void object::test<7>() + { + set_test_name("orphan()"); + NamedTempFile from("from", "not started"); + NamedTempFile to("to", ""); + LLProcessLauncher::ll_pid_t pid(0); + { + PythonProcessLauncher py("orphan()", + "import sys, time\n" + "with open(sys.argv[1], 'w') as f:\n" + " f.write('ok')\n" + "# wait for 'go' from test program\n" + "for i in xrange(60):\n" + " time.sleep(1)\n" + " with open(sys.argv[2]) as f:\n" + " go = f.read()\n" + " if go == 'go':\n" + " break\n" + "else:\n" + " with open(sys.argv[1], 'w') as f:\n" + " f.write('never saw go')\n" + " sys.exit(1)\n" + "# okay, saw 'go', write 'ack'\n" + "with open(sys.argv[1], 'w') as f:\n" + " f.write('ack')\n"); + py.mPy.addArgument(from.getName()); + py.mPy.addArgument(to.getName()); + ensure_equals("couldn't launch kill() script", py.mPy.launch(), 0); + // Capture ll_pid_t for later + pid = py.mPy.getProcessID(); + // Wait for the script to wake up and do its first write + int i = 0, timeout = 60; + for ( ; i < timeout; ++i) + { + sleep(1); + if (readfile(from.getName(), "from orphan() script") == "ok") + break; + } + // If we broke this loop because of the counter, something's wrong + ensure("script never started", i < timeout); + // Script has performed its first write and should now be waiting + // for us. Orphan it. + py.mPy.orphan(); + // Now destroy the LLProcessLauncher, which should NOT kill the child! + } + // If the destructor killed the child anyway, give it time to die + sleep(2); + // How do we know it's not terminated? By making it respond to + // a specific stimulus in a specific way. + { + std::ofstream outf(to.getName().c_str()); + outf << "go"; + } // flush and close. + // now wait for the script to terminate... one way or another. + while (LLProcessLauncher::isRunning(pid)) + { + sleep(1); + } + // If the LLProcessLauncher destructor implicitly called kill(), the + // script could not have written 'ack' as we expect. + ensure_equals("orphan() script output", readfile(from.getName()), "ack"); + } } // namespace tut -- cgit v1.2.3 From 1ed5bb3adaea0b4fee1e471575459039df8ced2f Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Wed, 18 Jan 2012 10:56:13 -0500 Subject: Make embedded Python scripts compatible with Python 2.5 *SIGH* Apparently our TeamCity build machines are still not up to Python 2.6. --- indra/llcommon/tests/llprocesslauncher_test.cpp | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'indra') diff --git a/indra/llcommon/tests/llprocesslauncher_test.cpp b/indra/llcommon/tests/llprocesslauncher_test.cpp index 7c0f0eaa84..057f83631e 100644 --- a/indra/llcommon/tests/llprocesslauncher_test.cpp +++ b/indra/llcommon/tests/llprocesslauncher_test.cpp @@ -181,6 +181,7 @@ public: // realpath() to compare properly. NamedTempDir(): mPath(python_out("mkdtemp()", + "from __future__ import with_statement\n" "import os.path, sys, tempfile\n" "with open(sys.argv[1], 'w') as f:\n" " f.write(os.path.realpath(tempfile.mkdtemp()))\n")) @@ -518,6 +519,7 @@ namespace tut // create one. Naturally, ensure we clean it up when done. NamedTempDir tempdir; PythonProcessLauncher py("getcwd()", + "from __future__ import with_statement\n" "import os, sys\n" "with open(sys.argv[1], 'w') as f:\n" " f.write(os.getcwd())\n"); @@ -531,6 +533,7 @@ namespace tut { set_test_name("clearArguments()"); PythonProcessLauncher py("args", + "from __future__ import with_statement\n" "import sys\n" // note nonstandard output-file arg! "with open(sys.argv[3], 'w') as f:\n" @@ -568,6 +571,7 @@ namespace tut { set_test_name("explicit kill()"); PythonProcessLauncher py("kill()", + "from __future__ import with_statement\n" "import sys, time\n" "with open(sys.argv[1], 'w') as f:\n" " f.write('ok')\n" @@ -610,6 +614,7 @@ namespace tut LLProcessLauncher::ll_pid_t pid(0); { PythonProcessLauncher py("kill()", + "from __future__ import with_statement\n" "import sys, time\n" "with open(sys.argv[1], 'w') as f:\n" " f.write('ok')\n" @@ -655,6 +660,7 @@ namespace tut LLProcessLauncher::ll_pid_t pid(0); { PythonProcessLauncher py("orphan()", + "from __future__ import with_statement\n" "import sys, time\n" "with open(sys.argv[1], 'w') as f:\n" " f.write('ok')\n" -- cgit v1.2.3 From 6fddfab6dd8e49dcbf4933bde23dbcdfe3e213db Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Thu, 19 Jan 2012 16:41:17 -0500 Subject: Try to fix argument quoting on Windows. Despite LLProcessLauncher's list-of-argument-strings API, on Windows it must ram them all into a single command-line string anyway. This means that if arguments contain spaces (or anything else that would confuse Windows command- line parsing), the target process won't receive the intended arguments. Introduce double quotes for any arguments not already double-quoted by caller. --- indra/llcommon/llprocesslauncher.cpp | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/llprocesslauncher.cpp b/indra/llcommon/llprocesslauncher.cpp index e1af49c2fb..adad3546fe 100644 --- a/indra/llcommon/llprocesslauncher.cpp +++ b/indra/llcommon/llprocesslauncher.cpp @@ -75,6 +75,28 @@ void LLProcessLauncher::addArgument(const std::string &arg) #if LL_WINDOWS +static std::string quote(const std::string& str) +{ + std::string::size_type len(str.length()); + // If the string is already quoted, assume user knows what s/he's doing. + if (len >= 2 && str[0] == '"' && str[len-1] == '"') + { + return str; + } + + // Not already quoted: do it. + std::string result("\""); + for (std::string::const_iterator ci(str.begin()), cend(str.end()); ci != cend; ++ci) + { + if (*ci == '"') + { + result.append("\\"); + } + result.append(*ci); + } + return result + "\""; +} + int LLProcessLauncher::launch(void) { // If there was already a process associated with this object, kill it. @@ -87,11 +109,11 @@ int LLProcessLauncher::launch(void) STARTUPINFOA sinfo; memset(&sinfo, 0, sizeof(sinfo)); - std::string args = mExecutable; + std::string args = quote(mExecutable); for(int i = 0; i < (int)mLaunchArguments.size(); i++) { args += " "; - args += mLaunchArguments[i]; + args += quote(mLaunchArguments[i]); } // So retarded. Windows requires that the second parameter to CreateProcessA be a writable (non-const) string... -- cgit v1.2.3 From 083a9e0927144a9e2f052bc8573da8a26259a257 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Thu, 19 Jan 2012 17:04:55 -0500 Subject: To grow std::string by a char, use push_back() instead of append(). --- indra/llcommon/llprocesslauncher.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/llcommon/llprocesslauncher.cpp b/indra/llcommon/llprocesslauncher.cpp index adad3546fe..5791d14ec0 100644 --- a/indra/llcommon/llprocesslauncher.cpp +++ b/indra/llcommon/llprocesslauncher.cpp @@ -92,7 +92,7 @@ static std::string quote(const std::string& str) { result.append("\\"); } - result.append(*ci); + result.push_back(*ci); } return result + "\""; } -- cgit v1.2.3 From 9c66ac87fd46db3987e60ae50989b2497099480b Mon Sep 17 00:00:00 2001 From: Kitty Barnett Date: Fri, 20 Jan 2012 18:06:32 +0100 Subject: STORM-276 Basic spellchecking framework --- indra/cmake/Copy3rdPartyLibs.cmake | 3 + indra/cmake/ViewerMiscLibs.cmake | 1 + indra/llui/CMakeLists.txt | 3 + indra/llui/llmenugl.cpp | 6 +- indra/llui/llmenugl.h | 6 +- indra/llui/llspellcheck.cpp | 345 ++++++++++++++++++++++++++++++++ indra/llui/llspellcheck.h | 77 +++++++ indra/llui/llspellcheckmenuhandler.h | 46 +++++ indra/newview/app_settings/settings.xml | 22 ++ indra/newview/llappviewer.cpp | 14 ++ indra/newview/llstartup.cpp | 1 + indra/newview/llviewercontrol.cpp | 24 +++ indra/newview/llviewermenu.cpp | 86 ++++++++ indra/newview/llviewermenu.h | 1 + indra/newview/viewer_manifest.py | 8 + 15 files changed, 641 insertions(+), 2 deletions(-) create mode 100644 indra/llui/llspellcheck.cpp create mode 100644 indra/llui/llspellcheck.h create mode 100644 indra/llui/llspellcheckmenuhandler.h (limited to 'indra') diff --git a/indra/cmake/Copy3rdPartyLibs.cmake b/indra/cmake/Copy3rdPartyLibs.cmake index 394db362b1..ebeae3e5be 100644 --- a/indra/cmake/Copy3rdPartyLibs.cmake +++ b/indra/cmake/Copy3rdPartyLibs.cmake @@ -41,6 +41,7 @@ if(WINDOWS) libeay32.dll libcollada14dom22-d.dll glod.dll + libhunspell.dll ) set(release_src_dir "${ARCH_PREBUILT_DIRS_RELEASE}") @@ -53,6 +54,7 @@ if(WINDOWS) libeay32.dll libcollada14dom22.dll glod.dll + libhunspell.dll ) if(USE_GOOGLE_PERFTOOLS) @@ -215,6 +217,7 @@ elseif(DARWIN) libllqtwebkit.dylib libminizip.a libndofdev.dylib + libhunspell-1.3.dylib libexception_handler.dylib libcollada14dom.dylib ) diff --git a/indra/cmake/ViewerMiscLibs.cmake b/indra/cmake/ViewerMiscLibs.cmake index df013b1665..f907181929 100644 --- a/indra/cmake/ViewerMiscLibs.cmake +++ b/indra/cmake/ViewerMiscLibs.cmake @@ -2,6 +2,7 @@ include(Prebuilt) if (NOT STANDALONE) + use_prebuilt_binary(libhunspell) use_prebuilt_binary(libuuid) use_prebuilt_binary(slvoice) use_prebuilt_binary(fontconfig) diff --git a/indra/llui/CMakeLists.txt b/indra/llui/CMakeLists.txt index 772f173f17..1377336bb4 100644 --- a/indra/llui/CMakeLists.txt +++ b/indra/llui/CMakeLists.txt @@ -87,6 +87,7 @@ set(llui_SOURCE_FILES llsearcheditor.cpp llslider.cpp llsliderctrl.cpp + llspellcheck.cpp llspinctrl.cpp llstatbar.cpp llstatgraph.cpp @@ -192,6 +193,8 @@ set(llui_HEADER_FILES llsdparam.h llsliderctrl.h llslider.h + llspellcheck.h + llspellcheckmenuhandler.h llspinctrl.h llstatbar.h llstatgraph.h diff --git a/indra/llui/llmenugl.cpp b/indra/llui/llmenugl.cpp index 95ecbb1c94..2a65262bbb 100644 --- a/indra/llui/llmenugl.cpp +++ b/indra/llui/llmenugl.cpp @@ -3854,7 +3854,7 @@ void LLContextMenu::setVisible(BOOL visible) } // Takes cursor position in screen space? -void LLContextMenu::show(S32 x, S32 y) +void LLContextMenu::show(S32 x, S32 y, LLView* spawning_view) { if (getChildList()->empty()) { @@ -3908,6 +3908,10 @@ void LLContextMenu::show(S32 x, S32 y) setRect(rect); arrange(); + if (spawning_view) + mSpawningViewHandle = spawning_view->getHandle(); + else + mSpawningViewHandle.markDead(); LLView::setVisible(TRUE); } diff --git a/indra/llui/llmenugl.h b/indra/llui/llmenugl.h index 36f3ba34b9..67b3e1fbe6 100644 --- a/indra/llui/llmenugl.h +++ b/indra/llui/llmenugl.h @@ -670,7 +670,7 @@ public: virtual void draw (); - virtual void show (S32 x, S32 y); + virtual void show (S32 x, S32 y, LLView* spawning_view = NULL); virtual void hide (); virtual BOOL handleHover ( S32 x, S32 y, MASK mask ); @@ -683,10 +683,14 @@ public: LLHandle getHandle() { return getDerivedHandle(); } + LLView* getSpawningView() const { return mSpawningViewHandle.get(); } + void setSpawningView(LLHandle spawning_view) { mSpawningViewHandle = spawning_view; } + protected: BOOL mHoveredAnyItem; LLMenuItemGL* mHoverItem; LLRootHandle mHandle; + LLHandle mSpawningViewHandle; }; diff --git a/indra/llui/llspellcheck.cpp b/indra/llui/llspellcheck.cpp new file mode 100644 index 0000000000..433ca02852 --- /dev/null +++ b/indra/llui/llspellcheck.cpp @@ -0,0 +1,345 @@ +/** + * @file llspellcheck.cpp + * @brief Spell checking functionality + * + * $LicenseInfo:firstyear=2001&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include "linden_common.h" + +#include "lldir.h" +#include "llsdserialize.h" + +#include "llspellcheck.h" +#if LL_WINDOWS + #include + #pragma comment(lib, "libhunspell.lib") +#else + #include +#endif + +static const std::string DICT_DIR = "dictionaries"; +static const std::string DICT_CUSTOM_SUFFIX = "_custom"; +static const std::string DICT_IGNORE_SUFFIX = "_ignore"; + +LLSpellChecker::settings_change_signal_t LLSpellChecker::sSettingsChangeSignal; + +LLSpellChecker::LLSpellChecker() + : mHunspell(NULL) +{ + // Load initial dictionary information + refreshDictionaryMap(); +} + +LLSpellChecker::~LLSpellChecker() +{ + delete mHunspell; +} + +bool LLSpellChecker::checkSpelling(const std::string& word) const +{ + if ( (!mHunspell) || (word.length() < 3) || (0 != mHunspell->spell(word.c_str())) ) + { + return true; + } + if (mIgnoreList.size() > 0) + { + std::string word_lower(word); + LLStringUtil::toLower(word_lower); + return (mIgnoreList.end() != std::find(mIgnoreList.begin(), mIgnoreList.end(), word_lower)); + } + return false; +} + +S32 LLSpellChecker::getSuggestions(const std::string& word, std::vector& suggestions) const +{ + suggestions.clear(); + if ( (!mHunspell) || (word.length() < 3) ) + return 0; + + char** suggestion_list; int suggestion_cnt = 0; + if ( (suggestion_cnt = mHunspell->suggest(&suggestion_list, word.c_str())) != 0 ) + { + for (int suggestion_index = 0; suggestion_index < suggestion_cnt; suggestion_index++) + suggestions.push_back(suggestion_list[suggestion_index]); + mHunspell->free_list(&suggestion_list, suggestion_cnt); + } + return suggestions.size(); +} + +const LLSD LLSpellChecker::getDictionaryData(const std::string& dict_name) const +{ + for (LLSD::array_const_iterator it = mDictMap.beginArray(); it != mDictMap.endArray(); ++it) + { + const LLSD& dict_entry = *it; + if (dict_name == dict_entry["language"].asString()) + return dict_entry; + } + return LLSD(); +} + +void LLSpellChecker::refreshDictionaryMap() +{ + const std::string app_path = getDictionaryAppPath(); + const std::string user_path = getDictionaryUserPath(); + + // Load dictionary information (file name, friendly name, ...) + llifstream user_map(user_path + "dictionaries.xml", std::ios::binary); + if ( (!user_map.is_open()) || (0 == LLSDSerialize::fromXMLDocument(mDictMap, user_map)) || (0 == mDictMap.size()) ) + { + llifstream app_map(app_path + "dictionaries.xml", std::ios::binary); + if ( (!app_map.is_open()) || (0 == LLSDSerialize::fromXMLDocument(mDictMap, app_map)) || (0 == mDictMap.size()) ) + return; + } + + // Look for installed dictionaries + std::string tmp_app_path, tmp_user_path; + for (LLSD::array_iterator it = mDictMap.beginArray(); it != mDictMap.endArray(); ++it) + { + LLSD& sdDict = *it; + tmp_app_path = (sdDict.has("name")) ? app_path + sdDict["name"].asString() : LLStringUtil::null; + tmp_user_path = (sdDict.has("name")) ? user_path + sdDict["name"].asString() : LLStringUtil::null; + sdDict["installed"] = + (!tmp_app_path.empty()) && + ( ((gDirUtilp->fileExists(tmp_user_path + ".aff")) && (gDirUtilp->fileExists(tmp_user_path + ".dic"))) || + ((gDirUtilp->fileExists(tmp_app_path + ".aff")) && (gDirUtilp->fileExists(tmp_app_path + ".dic"))) ); + sdDict["has_custom"] = (!tmp_user_path.empty()) && (gDirUtilp->fileExists(tmp_user_path + DICT_CUSTOM_SUFFIX + ".dic")); + sdDict["has_ignore"] = (!tmp_user_path.empty()) && (gDirUtilp->fileExists(tmp_user_path + DICT_IGNORE_SUFFIX + ".dic")); + } +} + +void LLSpellChecker::addToCustomDictionary(const std::string& word) +{ + if (mHunspell) + { + mHunspell->add(word.c_str()); + } + addToDictFile(getDictionaryUserPath() + mDictFile + DICT_CUSTOM_SUFFIX + ".dic", word); + sSettingsChangeSignal(); +} + +void LLSpellChecker::addToIgnoreList(const std::string& word) +{ + std::string word_lower(word); + LLStringUtil::toLower(word_lower); + if (mIgnoreList.end() != std::find(mIgnoreList.begin(), mIgnoreList.end(), word_lower)) + { + mIgnoreList.push_back(word_lower); + addToDictFile(getDictionaryUserPath() + mDictFile + DICT_IGNORE_SUFFIX + ".dic", word_lower); + sSettingsChangeSignal(); + } +} + +void LLSpellChecker::addToDictFile(const std::string& dict_path, const std::string& word) +{ + std::vector word_list; + + if (gDirUtilp->fileExists(dict_path)) + { + llifstream file_in(dict_path, std::ios::in); + if (file_in.is_open()) + { + std::string word; int line_num = 0; + while (getline(file_in, word)) + { + // Skip over the first line since that's just a line count + if (0 != line_num) + word_list.push_back(word); + line_num++; + } + } + else + { + // TODO: show error message? + return; + } + } + + word_list.push_back(word); + + llofstream file_out(dict_path, std::ios::out | std::ios::trunc); + if (file_out.is_open()) + { + file_out << word_list.size() << std::endl; + for (std::vector::const_iterator itWord = word_list.begin(); itWord != word_list.end(); ++itWord) + file_out << *itWord << std::endl; + file_out.close(); + } +} + +void LLSpellChecker::setSecondaryDictionaries(std::list dict_list) +{ + if (!getUseSpellCheck()) + { + return; + } + + // Check if we're only adding secondary dictionaries, or removing them + std::list dict_add(llmax(dict_list.size(), mDictSecondary.size())), dict_rem(llmax(dict_list.size(), mDictSecondary.size())); + dict_list.sort(); + mDictSecondary.sort(); + std::list::iterator end_added = std::set_difference(dict_list.begin(), dict_list.end(), mDictSecondary.begin(), mDictSecondary.end(), dict_add.begin()); + std::list::iterator end_removed = std::set_difference(mDictSecondary.begin(), mDictSecondary.end(), dict_list.begin(), dict_list.end(), dict_rem.begin()); + + if (end_removed != dict_rem.begin()) // We can't remove secondary dictionaries so we need to recreate the Hunspell instance + { + mDictSecondary = dict_list; + + std::string dict_name = mDictName; + initHunspell(dict_name); + } + else if (end_added != dict_add.begin()) // Add the new secondary dictionaries one by one + { + const std::string app_path = getDictionaryAppPath(); + const std::string user_path = getDictionaryUserPath(); + for (std::list::const_iterator it_added = dict_add.begin(); it_added != end_added; ++it_added) + { + const LLSD dict_entry = getDictionaryData(*it_added); + if ( (!dict_entry.isDefined()) || (!dict_entry["installed"].asBoolean()) ) + continue; + + const std::string strFileDic = dict_entry["name"].asString() + ".dic"; + if (gDirUtilp->fileExists(user_path + strFileDic)) + mHunspell->add_dic((user_path + strFileDic).c_str()); + else if (gDirUtilp->fileExists(app_path + strFileDic)) + mHunspell->add_dic((app_path + strFileDic).c_str()); + } + mDictSecondary = dict_list; + sSettingsChangeSignal(); + } +} + +void LLSpellChecker::initHunspell(const std::string& dict_name) +{ + if (mHunspell) + { + delete mHunspell; + mHunspell = NULL; + mDictName.clear(); + mDictFile.clear(); + mIgnoreList.clear(); + } + + const LLSD dict_entry = (!dict_name.empty()) ? getDictionaryData(dict_name) : LLSD(); + if ( (!dict_entry.isDefined()) || (!dict_entry["installed"].asBoolean()) ) + { + sSettingsChangeSignal(); + return; + } + + const std::string app_path = getDictionaryAppPath(); + const std::string user_path = getDictionaryUserPath(); + if (dict_entry.has("name")) + { + const std::string filename_aff = dict_entry["name"].asString() + ".aff"; + const std::string filename_dic = dict_entry["name"].asString() + ".dic"; + if ( (gDirUtilp->fileExists(user_path + filename_aff)) && (gDirUtilp->fileExists(user_path + filename_dic)) ) + mHunspell = new Hunspell((user_path + filename_aff).c_str(), (user_path + filename_dic).c_str()); + else if ( (gDirUtilp->fileExists(app_path + filename_aff)) && (gDirUtilp->fileExists(app_path + filename_dic)) ) + mHunspell = new Hunspell((app_path + filename_aff).c_str(), (app_path + filename_dic).c_str()); + if (!mHunspell) + return; + + mDictName = dict_name; + mDictFile = dict_entry["name"].asString(); + + if (dict_entry["has_custom"].asBoolean()) + { + const std::string filename_dic = user_path + mDictFile + DICT_CUSTOM_SUFFIX + ".dic"; + mHunspell->add_dic(filename_dic.c_str()); + } + + if (dict_entry["has_ignore"].asBoolean()) + { + llifstream file_in(user_path + mDictFile + DICT_IGNORE_SUFFIX + ".dic", std::ios::in); + if (file_in.is_open()) + { + std::string word; int idxLine = 0; + while (getline(file_in, word)) + { + // Skip over the first line since that's just a line count + if (0 != idxLine) + { + LLStringUtil::toLower(word); + mIgnoreList.push_back(word); + } + idxLine++; + } + } + } + + for (std::list::const_iterator it = mDictSecondary.begin(); it != mDictSecondary.end(); ++it) + { + const LLSD dict_entry = getDictionaryData(*it); + if ( (!dict_entry.isDefined()) || (!dict_entry["installed"].asBoolean()) ) + continue; + + const std::string filename_dic = dict_entry["name"].asString() + ".dic"; + if (gDirUtilp->fileExists(user_path + filename_dic)) + mHunspell->add_dic((user_path + filename_dic).c_str()); + else if (gDirUtilp->fileExists(app_path + filename_dic)) + mHunspell->add_dic((app_path + filename_dic).c_str()); + } + } + + sSettingsChangeSignal(); +} + +// static +const std::string LLSpellChecker::getDictionaryAppPath() +{ + std::string dict_path = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, DICT_DIR, ""); + return dict_path; +} + +// static +const std::string LLSpellChecker::getDictionaryUserPath() +{ + std::string dict_path = gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, DICT_DIR, ""); + if (!gDirUtilp->fileExists(dict_path)) + { + LLFile::mkdir(dict_path); + } + return dict_path; +} + +// static +bool LLSpellChecker::getUseSpellCheck() +{ + return (LLSpellChecker::instanceExists()) && (LLSpellChecker::instance().mHunspell); +} + +// static +boost::signals2::connection LLSpellChecker::setSettingsChangeCallback(const settings_change_signal_t::slot_type& cb) +{ + return sSettingsChangeSignal.connect(cb); +} + +// static +void LLSpellChecker::setUseSpellCheck(const std::string& dict_name) +{ + if ( (((dict_name.empty()) && (getUseSpellCheck())) || (!dict_name.empty())) && + (LLSpellChecker::instance().mDictName != dict_name) ) + { + LLSpellChecker::instance().initHunspell(dict_name); + } +} diff --git a/indra/llui/llspellcheck.h b/indra/llui/llspellcheck.h new file mode 100644 index 0000000000..affdac2907 --- /dev/null +++ b/indra/llui/llspellcheck.h @@ -0,0 +1,77 @@ +/** + * @file llspellcheck.h + * @brief Spell checking functionality + * + * $LicenseInfo:firstyear=2001&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#ifndef LLSPELLCHECK_H +#define LLSPELLCHECK_H + +#include "llsingleton.h" +#include + +class Hunspell; + +class LLSpellChecker : public LLSingleton +{ + friend class LLSingleton; +protected: + LLSpellChecker(); + ~LLSpellChecker(); + +public: + void addToCustomDictionary(const std::string& word); + void addToIgnoreList(const std::string& word); + bool checkSpelling(const std::string& word) const; + S32 getSuggestions(const std::string& word, std::vector& suggestions) const; + +public: + const LLSD getDictionaryData(const std::string& dict_name) const; + const LLSD& getDictionaryMap() const { return mDictMap; } + void refreshDictionaryMap(); + void setSecondaryDictionaries(std::list dictList); +protected: + void addToDictFile(const std::string& dict_path, const std::string& word); + void initHunspell(const std::string& dict_name); + +public: + static const std::string getDictionaryAppPath(); + static const std::string getDictionaryUserPath(); + static bool getUseSpellCheck(); + static void setUseSpellCheck(const std::string& dict_name); + + typedef boost::signals2::signal settings_change_signal_t; + static boost::signals2::connection setSettingsChangeCallback(const settings_change_signal_t::slot_type& cb); + +protected: + Hunspell* mHunspell; + std::string mDictName; + std::string mDictFile; + LLSD mDictMap; + std::list mDictSecondary; + std::vector mIgnoreList; + + static settings_change_signal_t sSettingsChangeSignal; +}; + +#endif // LLSPELLCHECK_H diff --git a/indra/llui/llspellcheckmenuhandler.h b/indra/llui/llspellcheckmenuhandler.h new file mode 100644 index 0000000000..d5c95bad39 --- /dev/null +++ b/indra/llui/llspellcheckmenuhandler.h @@ -0,0 +1,46 @@ +/** + * @file llspellcheckmenuhandler.h + * @brief Interface used by spell check menu handling + * + * $LicenseInfo:firstyear=2001&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#ifndef LLSPELLCHECKMENUHANDLER_H +#define LLSPELLCHECKMENUHANDLER_H + +class LLSpellCheckMenuHandler +{ +public: + virtual bool getSpellCheck() const { return false; } + + virtual const std::string& getSuggestion(U32 index) const { return LLStringUtil::null; } + virtual U32 getSuggestionCount() const { return 0; } + virtual void replaceWithSuggestion(U32 index){} + + virtual void addToDictionary() {} + virtual bool canAddToDictionary() const { return false; } + + virtual void addToIgnore() {} + virtual bool canAddToIgnore() const { return false; } +}; + +#endif // LLSPELLCHECKMENUHANDLER_H diff --git a/indra/newview/app_settings/settings.xml b/indra/newview/app_settings/settings.xml index 1ea623791d..1ad3ee1dd1 100644 --- a/indra/newview/app_settings/settings.xml +++ b/indra/newview/app_settings/settings.xml @@ -12082,6 +12082,28 @@ Value 10.0 + SpellCheck + + Comment + Enable spellchecking on line and text editors + Persist + 1 + Type + Boolean + Value + 1 + + SpellCheckDictionary + + Comment + Current primary and secondary dictionaries used for spell checking + Persist + 1 + Type + String + Value + English (United States) + UseNewWalkRun Comment diff --git a/indra/newview/llappviewer.cpp b/indra/newview/llappviewer.cpp index 0861fe85a8..698f2469a3 100644 --- a/indra/newview/llappviewer.cpp +++ b/indra/newview/llappviewer.cpp @@ -91,6 +91,7 @@ #include "llsecondlifeurls.h" #include "llupdaterservice.h" #include "llcallfloater.h" +#include "llspellcheck.h" // Linden library includes #include "llavatarnamecache.h" @@ -112,6 +113,7 @@ // Third party library includes #include #include +#include @@ -2488,6 +2490,18 @@ bool LLAppViewer::initConfiguration() //gDirUtilp->setSkinFolder("default"); } + if (gSavedSettings.getBOOL("SpellCheck")) + { + std::list dict_list; + boost::split(dict_list, gSavedSettings.getString("SpellCheckDictionary"), boost::is_any_of(std::string(","))); + if (!dict_list.empty()) + { + LLSpellChecker::setUseSpellCheck(dict_list.front()); + dict_list.pop_front(); + LLSpellChecker::instance().setSecondaryDictionaries(dict_list); + } + } + mYieldTime = gSavedSettings.getS32("YieldTime"); // Read skin/branding settings if specified. diff --git a/indra/newview/llstartup.cpp b/indra/newview/llstartup.cpp index 7e02a41e7e..89360778d1 100644 --- a/indra/newview/llstartup.cpp +++ b/indra/newview/llstartup.cpp @@ -739,6 +739,7 @@ bool idle_startup() { display_startup(); initialize_edit_menu(); + initialize_spellcheck_menu(); display_startup(); init_menus(); display_startup(); diff --git a/indra/newview/llviewercontrol.cpp b/indra/newview/llviewercontrol.cpp index 093b84413a..7b6dbfaa0b 100644 --- a/indra/newview/llviewercontrol.cpp +++ b/indra/newview/llviewercontrol.cpp @@ -71,8 +71,12 @@ #include "llpaneloutfitsinventory.h" #include "llpanellogin.h" #include "llpaneltopinfobar.h" +#include "llspellcheck.h" #include "llupdaterservice.h" +// Third party library includes +#include + #ifdef TOGGLE_HACKED_GODLIKE_VIEWER BOOL gHackGodmode = FALSE; #endif @@ -498,6 +502,24 @@ bool handleForceShowGrid(const LLSD& newvalue) return true; } +bool handleSpellCheckChanged() +{ + if (gSavedSettings.getBOOL("SpellCheck")) + { + std::list dict_list; + boost::split(dict_list, gSavedSettings.getString("SpellCheckDictionary"), boost::is_any_of(std::string(","))); + if (!dict_list.empty()) + { + LLSpellChecker::setUseSpellCheck(dict_list.front()); + dict_list.pop_front(); + LLSpellChecker::instance().setSecondaryDictionaries(dict_list); + return true; + } + } + LLSpellChecker::setUseSpellCheck(LLStringUtil::null); + return true; +} + bool toggle_agent_pause(const LLSD& newvalue) { if ( newvalue.asBoolean() ) @@ -704,6 +726,8 @@ void settings_setup_listeners() gSavedSettings.getControl("UpdaterServiceSetting")->getSignal()->connect(boost::bind(&toggle_updater_service_active, _2)); gSavedSettings.getControl("ForceShowGrid")->getSignal()->connect(boost::bind(&handleForceShowGrid, _2)); gSavedSettings.getControl("RenderTransparentWater")->getSignal()->connect(boost::bind(&handleRenderTransparentWaterChanged, _2)); + gSavedSettings.getControl("SpellCheck")->getSignal()->connect(boost::bind(&handleSpellCheckChanged)); + gSavedSettings.getControl("SpellCheckDictionary")->getSignal()->connect(boost::bind(&handleSpellCheckChanged)); } #if TEST_CACHED_CONTROL diff --git a/indra/newview/llviewermenu.cpp b/indra/newview/llviewermenu.cpp index 0104d35e53..2a11f3cc16 100644 --- a/indra/newview/llviewermenu.cpp +++ b/indra/newview/llviewermenu.cpp @@ -81,6 +81,7 @@ #include "llrootview.h" #include "llsceneview.h" #include "llselectmgr.h" +#include "llspellcheckmenuhandler.h" #include "llstatusbar.h" #include "lltextureview.h" #include "lltoolcomp.h" @@ -4984,6 +4985,78 @@ class LLEditDelete : public view_listener_t } }; +void handle_spellcheck_replace_with_suggestion(const LLUICtrl* ctrl, const LLSD& param) +{ + const LLContextMenu* menu = dynamic_cast(ctrl->getParent()); + LLSpellCheckMenuHandler* spellcheck_handler = (menu) ? dynamic_cast(menu->getSpawningView()) : NULL; + if ( (!spellcheck_handler) || (!spellcheck_handler->getSpellCheck()) ) + { + return; + } + + U32 index = 0; + if ( (!LLStringUtil::convertToU32(param.asString(), index)) || (index >= spellcheck_handler->getSuggestionCount()) ) + { + return; + } + + spellcheck_handler->replaceWithSuggestion(index); +} + +bool visible_spellcheck_suggestion(LLUICtrl* ctrl, const LLSD& param) +{ + LLMenuItemGL* item = dynamic_cast(ctrl); + const LLContextMenu* menu = (item) ? dynamic_cast(item->getParent()) : NULL; + const LLSpellCheckMenuHandler* spellcheck_handler = (menu) ? dynamic_cast(menu->getSpawningView()) : NULL; + if ( (!spellcheck_handler) || (!spellcheck_handler->getSpellCheck()) ) + { + return false; + } + + U32 index = 0; + if ( (!LLStringUtil::convertToU32(param.asString(), index)) || (index >= spellcheck_handler->getSuggestionCount()) ) + { + return false; + } + + item->setLabel(spellcheck_handler->getSuggestion(index)); + return true; +} + +void handle_spellcheck_add_to_dictionary(const LLUICtrl* ctrl) +{ + const LLContextMenu* menu = dynamic_cast(ctrl->getParent()); + LLSpellCheckMenuHandler* spellcheck_handler = (menu) ? dynamic_cast(menu->getSpawningView()) : NULL; + if ( (spellcheck_handler) && (spellcheck_handler->canAddToDictionary()) ) + { + spellcheck_handler->addToDictionary(); + } +} + +bool enable_spellcheck_add_to_dictionary(const LLUICtrl* ctrl) +{ + const LLContextMenu* menu = dynamic_cast(ctrl->getParent()); + const LLSpellCheckMenuHandler* spellcheck_handler = (menu) ? dynamic_cast(menu->getSpawningView()) : NULL; + return (spellcheck_handler) && (spellcheck_handler->canAddToDictionary()); +} + +void handle_spellcheck_add_to_ignore(const LLUICtrl* ctrl) +{ + const LLContextMenu* menu = dynamic_cast(ctrl->getParent()); + LLSpellCheckMenuHandler* spellcheck_handler = (menu) ? dynamic_cast(menu->getSpawningView()) : NULL; + if ( (spellcheck_handler) && (spellcheck_handler->canAddToIgnore()) ) + { + spellcheck_handler->addToIgnore(); + } +} + +bool enable_spellcheck_add_to_ignore(const LLUICtrl* ctrl) +{ + const LLContextMenu* menu = dynamic_cast(ctrl->getParent()); + const LLSpellCheckMenuHandler* spellcheck_handler = (menu) ? dynamic_cast(menu->getSpawningView()) : NULL; + return (spellcheck_handler) && (spellcheck_handler->canAddToIgnore()); +} + bool enable_object_delete() { bool new_value = @@ -7933,6 +8006,19 @@ void initialize_edit_menu() } +void initialize_spellcheck_menu() +{ + LLUICtrl::CommitCallbackRegistry::Registrar& commit = LLUICtrl::CommitCallbackRegistry::currentRegistrar(); + LLUICtrl::EnableCallbackRegistry::Registrar& enable = LLUICtrl::EnableCallbackRegistry::currentRegistrar(); + + commit.add("SpellCheck.ReplaceWithSuggestion", boost::bind(&handle_spellcheck_replace_with_suggestion, _1, _2)); + enable.add("SpellCheck.VisibleSuggestion", boost::bind(&visible_spellcheck_suggestion, _1, _2)); + commit.add("SpellCheck.AddToDictionary", boost::bind(&handle_spellcheck_add_to_dictionary, _1)); + enable.add("SpellCheck.EnableAddToDictionary", boost::bind(&enable_spellcheck_add_to_dictionary, _1)); + commit.add("SpellCheck.AddToIgnore", boost::bind(&handle_spellcheck_add_to_ignore, _1)); + enable.add("SpellCheck.EnableAddToIgnore", boost::bind(&enable_spellcheck_add_to_ignore, _1)); +} + void initialize_menus() { // A parameterized event handler used as ctrl-8/9/0 zoom controls below. diff --git a/indra/newview/llviewermenu.h b/indra/newview/llviewermenu.h index 87cb4efbc4..8c40762865 100644 --- a/indra/newview/llviewermenu.h +++ b/indra/newview/llviewermenu.h @@ -39,6 +39,7 @@ class LLObjectSelection; class LLSelectNode; void initialize_edit_menu(); +void initialize_spellcheck_menu(); void init_menus(); void cleanup_menus(); diff --git a/indra/newview/viewer_manifest.py b/indra/newview/viewer_manifest.py index 0931c4ec9b..1b732676e4 100644 --- a/indra/newview/viewer_manifest.py +++ b/indra/newview/viewer_manifest.py @@ -91,6 +91,8 @@ class ViewerManifest(LLManifest): # ... and the entire windlight directory self.path("windlight") + # ... and the pre-installed spell checking dictionaries + self.path("dictionaries") self.end_prefix("app_settings") if self.prefix(src="character"): @@ -393,6 +395,9 @@ class WindowsManifest(ViewerManifest): self.path("ssleay32.dll") self.path("libeay32.dll") + # Hunspell + self.path("libhunspell.dll") + # For google-perftools tcmalloc allocator. try: if self.args['configuration'].lower() == 'debug': @@ -659,6 +664,7 @@ class DarwinManifest(ViewerManifest): # copy additional libs in /Contents/MacOS/ self.path("../packages/lib/release/libndofdev.dylib", dst="Resources/libndofdev.dylib") + self.path("../packages/lib/release/libhunspell-1.3.dylib", dst="Resources/libhunspell-1.3.dylib") self.path("../viewer_components/updater/scripts/darwin/update_install", "MacOS/update_install") @@ -1053,6 +1059,8 @@ class Linux_i686Manifest(LinuxManifest): self.path("libopenjpeg.so.1.4.0") self.path("libopenjpeg.so.1") self.path("libopenjpeg.so") + self.path("libhunspell-1.3.so") + self.path("libhunspell-1.3.so.0") self.path("libalut.so") self.path("libopenal.so", "libopenal.so.1") self.path("libopenal.so", "libvivoxoal.so.1") # vivox's sdk expects this soname -- cgit v1.2.3 From f0d1afc2266e13b4f36f750ba5e721e427caf7b8 Mon Sep 17 00:00:00 2001 From: Kitty Barnett Date: Fri, 20 Jan 2012 18:07:35 +0100 Subject: STORM-276 Added spellcheck functionality to the LLLineEditor control --- indra/llcommon/llstring.h | 3 + indra/llui/lllineeditor.cpp | 217 ++++++++++++++++++++- indra/llui/lllineeditor.h | 29 ++- .../skins/default/xui/en/menu_text_editor.xml | 79 ++++++++ 4 files changed, 324 insertions(+), 4 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/llstring.h b/indra/llcommon/llstring.h index 7e41e787b5..3a27badb5a 100644 --- a/indra/llcommon/llstring.h +++ b/indra/llcommon/llstring.h @@ -182,6 +182,9 @@ public: static bool isPunct(char a) { return ispunct((unsigned char)a) != 0; } static bool isPunct(llwchar a) { return iswpunct(a) != 0; } + static bool isAlpha(char a) { return isalpha((unsigned char)a) != 0; } + static bool isAlpha(llwchar a) { return iswalpha(a) != 0; } + static bool isAlnum(char a) { return isalnum((unsigned char)a) != 0; } static bool isAlnum(llwchar a) { return iswalnum(a) != 0; } diff --git a/indra/llui/lllineeditor.cpp b/indra/llui/lllineeditor.cpp index 06dfc90d83..5479c080bd 100644 --- a/indra/llui/lllineeditor.cpp +++ b/indra/llui/lllineeditor.cpp @@ -45,6 +45,7 @@ #include "llkeyboard.h" #include "llrect.h" #include "llresmgr.h" +#include "llspellcheck.h" #include "llstring.h" #include "llwindow.h" #include "llui.h" @@ -65,6 +66,7 @@ const S32 SCROLL_INCREMENT_ADD = 0; // make space for typing const S32 SCROLL_INCREMENT_DEL = 4; // make space for baskspacing const F32 AUTO_SCROLL_TIME = 0.05f; const F32 TRIPLE_CLICK_INTERVAL = 0.3f; // delay between double and triple click. *TODO: make this equal to the double click interval? +const F32 SPELLCHECK_DELAY = 0.5f; // delay between the last keypress and showing spell checking feedback for the word the cursor is on const std::string PASSWORD_ASTERISK( "\xE2\x80\xA2" ); // U+2022 BULLET @@ -88,6 +90,7 @@ LLLineEditor::Params::Params() background_image_focused("background_image_focused"), select_on_focus("select_on_focus", false), revert_on_esc("revert_on_esc", true), + spellcheck("spellcheck", false), commit_on_focus_lost("commit_on_focus_lost", true), ignore_tab("ignore_tab", true), is_password("is_password", false), @@ -134,6 +137,9 @@ LLLineEditor::LLLineEditor(const LLLineEditor::Params& p) mIgnoreArrowKeys( FALSE ), mIgnoreTab( p.ignore_tab ), mDrawAsterixes( p.is_password ), + mSpellCheck( p.spellcheck ), + mSpellCheckStart(-1), + mSpellCheckEnd(-1), mSelectAllonFocusReceived( p.select_on_focus ), mSelectAllonCommit( TRUE ), mPassDelete(FALSE), @@ -177,6 +183,12 @@ LLLineEditor::LLLineEditor(const LLLineEditor::Params& p) updateTextPadding(); setCursor(mText.length()); + if (mSpellCheck) + { + LLSpellChecker::setSettingsChangeCallback(boost::bind(&LLLineEditor::onSpellCheckSettingsChange, this)); + } + mSpellCheckTimer.reset(); + setPrevalidateInput(p.prevalidate_input_callback()); setPrevalidate(p.prevalidate_callback()); @@ -519,6 +531,94 @@ void LLLineEditor::selectAll() updatePrimary(); } +bool LLLineEditor::getSpellCheck() const +{ + return (LLSpellChecker::getUseSpellCheck()) && (!mReadOnly) && (mSpellCheck); +} + +const std::string& LLLineEditor::getSuggestion(U32 index) const +{ + return (index < mSuggestionList.size()) ? mSuggestionList[index] : LLStringUtil::null; +} + +U32 LLLineEditor::getSuggestionCount() const +{ + return mSuggestionList.size(); +} + +void LLLineEditor::replaceWithSuggestion(U32 index) +{ + for (std::list >::const_iterator it = mMisspellRanges.begin(); it != mMisspellRanges.end(); ++it) + { + if ( (it->first <= (U32)mCursorPos) && (it->second >= (U32)mCursorPos) ) + { + deselect(); + + // Delete the misspelled word + mText.erase(it->first, it->second - it->first); + + // Insert the suggestion in its place + LLWString suggestion = utf8str_to_wstring(mSuggestionList[index]); + mText.insert(it->first, suggestion); + setCursor(it->first + (S32)suggestion.length()); + + break; + } + } + mSpellCheckStart = mSpellCheckEnd = -1; +} + +void LLLineEditor::addToDictionary() +{ + if (canAddToDictionary()) + { + LLSpellChecker::instance().addToCustomDictionary(getMisspelledWord(mCursorPos)); + } +} + +bool LLLineEditor::canAddToDictionary() const +{ + return (getSpellCheck()) && (isMisspelledWord(mCursorPos)); +} + +void LLLineEditor::addToIgnore() +{ + if (canAddToIgnore()) + { + LLSpellChecker::instance().addToIgnoreList(getMisspelledWord(mCursorPos)); + } +} + +bool LLLineEditor::canAddToIgnore() const +{ + return (getSpellCheck()) && (isMisspelledWord(mCursorPos)); +} + +std::string LLLineEditor::getMisspelledWord(U32 pos) const +{ + for (std::list >::const_iterator it = mMisspellRanges.begin(); it != mMisspellRanges.end(); ++it) + { + if ( (it->first <= pos) && (it->second >= pos) ) + return wstring_to_utf8str(mText.getWString().substr(it->first, it->second - it->first)); + } + return LLStringUtil::null; +} + +bool LLLineEditor::isMisspelledWord(U32 pos) const +{ + for (std::list >::const_iterator it = mMisspellRanges.begin(); it != mMisspellRanges.end(); ++it) + { + if ( (it->first <= pos) && (it->second >= pos) ) + return true; + } + return false; +} + +void LLLineEditor::onSpellCheckSettingsChange() +{ + // Recheck the spelling on every change + mSpellCheckStart = mSpellCheckEnd = -1; +} BOOL LLLineEditor::handleDoubleClick(S32 x, S32 y, MASK mask) { @@ -1453,6 +1553,10 @@ BOOL LLLineEditor::handleKeyHere(KEY key, MASK mask ) { mKeystrokeCallback(this); } + if ( (!selection_modified) && (KEY_BACKSPACE == key) ) + { + mSpellCheckTimer.setTimerExpirySec(SPELLCHECK_DELAY); + } } } } @@ -1510,6 +1614,7 @@ BOOL LLLineEditor::handleUnicodeCharHere(llwchar uni_char) // We'll have to do something about this if something ever changes! - Doug mKeystrokeCallback( this ); } + mSpellCheckTimer.setTimerExpirySec(SPELLCHECK_DELAY); } } return handled; @@ -1560,6 +1665,7 @@ void LLLineEditor::doDelete() { mKeystrokeCallback( this ); } + mSpellCheckTimer.setTimerExpirySec(SPELLCHECK_DELAY); } } } @@ -1756,7 +1862,7 @@ void LLLineEditor::draw() if( (rendered_pixels_right < (F32)mTextRightEdge) && (rendered_text < text_len) ) { // unselected, right side - mGLFont->render( + rendered_text += mGLFont->render( mText, mScrollHPos + rendered_text, rendered_pixels_right, text_bottom, text_color, @@ -1770,7 +1876,7 @@ void LLLineEditor::draw() } else { - mGLFont->render( + rendered_text = mGLFont->render( mText, mScrollHPos, rendered_pixels_right, text_bottom, text_color, @@ -1785,6 +1891,80 @@ void LLLineEditor::draw() mBorder->setVisible(FALSE); // no more programmatic art. #endif + if ( (getSpellCheck()) && (mText.length() > 2) ) + { + // Calculate start and end indices for the first and last visible word + U32 start = prevWordPos(mScrollHPos), end = nextWordPos(mScrollHPos + rendered_text); + + if ( (mSpellCheckStart != start) || (mSpellCheckEnd = end) ) + { + const LLWString& text = mText.getWString().substr(start, end); + + // Find the start of the first word + U32 word_start = 0, word_end = 0; + while ( (word_start < text.length()) && (!LLStringOps::isAlpha(text[word_start])) ) + word_start++; + + // Iterate over all words in the text block and check them one by one + mMisspellRanges.clear(); + while (word_start < text.length()) + { + // Find the end of the current word (special case handling for "'" when it's used as a contraction) + word_end = word_start + 1; + while ( (word_end < text.length()) && + ((LLWStringUtil::isPartOfWord(text[word_end])) || + ((L'\'' == text[word_end]) && (word_end + 1 < text.length()) && + (LLStringOps::isAlnum(text[word_end - 1])) && (LLStringOps::isAlnum(text[word_end + 1])))) ) + { + word_end++; + } + if (word_end >= text.length()) + break; + + // Don't process words shorter than 3 characters + std::string word = wstring_to_utf8str(text.substr(word_start, word_end - word_start)); + if ( (word.length() >= 3) && (!LLSpellChecker::instance().checkSpelling(word)) ) + mMisspellRanges.push_back(std::pair(start + word_start, start + word_end)); + + // Find the start of the next word + word_start = word_end + 1; + while ( (word_start < text.length()) && (!LLWStringUtil::isPartOfWord(text[word_start])) ) + word_start++; + } + + mSpellCheckStart = start; + mSpellCheckEnd = end; + } + + // Draw squiggly lines under any (visible) misspelled words + for (std::list >::const_iterator it = mMisspellRanges.begin(); it != mMisspellRanges.end(); ++it) + { + // Skip over words that aren't (partially) visible + if ( ((it->first < start) && (it->second < start)) || (it->first > end) ) + continue; + + // Skip the current word if the user is still busy editing it + if ( (!mSpellCheckTimer.hasExpired()) && (it->first <= (U32)mCursorPos) && (it->second >= (U32)mCursorPos) ) + continue; + + S32 pxWidth = getRect().getWidth(); + S32 pxStart = findPixelNearestPos(it->first - getCursor()); + if (pxStart > pxWidth) + continue; + S32 pxEnd = findPixelNearestPos(it->second - getCursor()); + if (pxEnd > pxWidth) + pxEnd = pxWidth; + + gGL.color4ub(255, 0, 0, 200); + while (pxStart < pxEnd) + { + gl_line_2d(pxStart, text_bottom - 2, pxStart + 3, text_bottom + 1); + gl_line_2d(pxStart + 3, text_bottom + 1, pxStart + 6, text_bottom - 2); + pxStart += 6; + } + } + } + // If we're editing... if( hasFocus()) { @@ -2242,6 +2422,7 @@ void LLLineEditor::updatePreedit(const LLWString &preedit_string, { mKeystrokeCallback( this ); } + mSpellCheckTimer.setTimerExpirySec(SPELLCHECK_DELAY); } BOOL LLLineEditor::getPreeditLocation(S32 query_offset, LLCoordGL *coord, LLRect *bounds, LLRect *control) const @@ -2393,7 +2574,37 @@ void LLLineEditor::showContextMenu(S32 x, S32 y) S32 screen_x, screen_y; localPointToScreen(x, y, &screen_x, &screen_y); - menu->show(screen_x, screen_y); + + if (hasSelection()) + { + if ( (mCursorPos < llmin(mSelectionStart, mSelectionEnd)) || (mCursorPos > llmax(mSelectionStart, mSelectionEnd)) ) + deselect(); + else + setCursor(llmax(mSelectionStart, mSelectionEnd)); + } + else + { + setCursorAtLocalPos(x); + } + + bool use_spellcheck = getSpellCheck(), is_misspelled = false; + if (use_spellcheck) + { + mSuggestionList.clear(); + + // If the cursor is on a misspelled word, retrieve suggestions for it + std::string misspelled_word = getMisspelledWord(mCursorPos); + if ((is_misspelled = !misspelled_word.empty()) == true) + { + LLSpellChecker::instance().getSuggestions(misspelled_word, mSuggestionList); + } + } + + menu->setItemVisible("Suggestion Separator", (use_spellcheck) && (!mSuggestionList.empty())); + menu->setItemVisible("Add to Dictionary", (use_spellcheck) && (is_misspelled)); + menu->setItemVisible("Add to Ignore", (use_spellcheck) && (is_misspelled)); + menu->setItemVisible("Spellcheck Separator", (use_spellcheck) && (is_misspelled)); + menu->show(screen_x, screen_y, this); } } diff --git a/indra/llui/lllineeditor.h b/indra/llui/lllineeditor.h index 2518dbe3c7..9513274f21 100644 --- a/indra/llui/lllineeditor.h +++ b/indra/llui/lllineeditor.h @@ -40,6 +40,7 @@ #include "llframetimer.h" #include "lleditmenuhandler.h" +#include "llspellcheckmenuhandler.h" #include "lluictrl.h" #include "lluiimage.h" #include "lluistring.h" @@ -54,7 +55,7 @@ class LLButton; class LLContextMenu; class LLLineEditor -: public LLUICtrl, public LLEditMenuHandler, protected LLPreeditor +: public LLUICtrl, public LLEditMenuHandler, protected LLPreeditor, public LLSpellCheckMenuHandler { public: @@ -86,6 +87,7 @@ public: Optional select_on_focus, revert_on_esc, + spellcheck, commit_on_focus_lost, ignore_tab, is_password; @@ -146,6 +148,24 @@ public: virtual void deselect(); virtual BOOL canDeselect() const; + // LLSpellCheckMenuHandler overrides + /*virtual*/ bool getSpellCheck() const; + + /*virtual*/ const std::string& getSuggestion(U32 index) const; + /*virtual*/ U32 getSuggestionCount() const; + /*virtual*/ void replaceWithSuggestion(U32 index); + + /*virtual*/ void addToDictionary(); + /*virtual*/ bool canAddToDictionary() const; + + /*virtual*/ void addToIgnore(); + /*virtual*/ bool canAddToIgnore() const; + + // Spell checking helper functions + std::string getMisspelledWord(U32 pos) const; + bool isMisspelledWord(U32 pos) const; + void onSpellCheckSettingsChange(); + // view overrides virtual void draw(); virtual void reshape(S32 width,S32 height,BOOL called_from_parent=TRUE); @@ -322,6 +342,13 @@ protected: S32 mLastSelectionStart; S32 mLastSelectionEnd; + bool mSpellCheck; + S32 mSpellCheckStart; + S32 mSpellCheckEnd; + LLTimer mSpellCheckTimer; + std::list > mMisspellRanges; + std::vector mSuggestionList; + LLTextValidate::validate_func_t mPrevalidateFunc; LLTextValidate::validate_func_t mPrevalidateInputFunc; diff --git a/indra/newview/skins/default/xui/en/menu_text_editor.xml b/indra/newview/skins/default/xui/en/menu_text_editor.xml index fe8489166b..70b40dd89b 100644 --- a/indra/newview/skins/default/xui/en/menu_text_editor.xml +++ b/indra/newview/skins/default/xui/en/menu_text_editor.xml @@ -1,6 +1,85 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Date: Fri, 20 Jan 2012 13:51:46 -0800 Subject: removed LLXUIXML library moved LLInitParam, and LLRegistry to llcommon moved LLUIColor, LLTrans, and LLXUIParser to llui reviewed by Nat --- indra/CMakeLists.txt | 1 - .../integration_tests/llui_libtest/CMakeLists.txt | 2 - indra/llcommon/CMakeLists.txt | 3 + indra/llcommon/llinitparam.cpp | 469 ++++ indra/llcommon/llinitparam.h | 2294 ++++++++++++++++++++ indra/llcommon/llregistry.h | 351 +++ indra/llui/CMakeLists.txt | 8 +- indra/llui/lltrans.cpp | 295 +++ indra/llui/lltrans.h | 133 ++ indra/llui/lluicolor.cpp | 87 + indra/llui/lluicolor.h | 71 + indra/llui/llxuiparser.cpp | 1756 +++++++++++++++ indra/llui/llxuiparser.h | 242 +++ indra/llui/tests/llurlentry_stub.cpp | 22 - indra/llui/tests/llurlentry_test.cpp | 15 - indra/llui/tests/llurlmatch_test.cpp | 34 - indra/llxuixml/CMakeLists.txt | 45 - indra/llxuixml/llinitparam.cpp | 469 ---- indra/llxuixml/llinitparam.h | 2294 -------------------- indra/llxuixml/llregistry.h | 351 --- indra/llxuixml/lltrans.cpp | 295 --- indra/llxuixml/lltrans.h | 133 -- indra/llxuixml/lluicolor.cpp | 87 - indra/llxuixml/lluicolor.h | 71 - indra/llxuixml/llxuiparser.cpp | 1756 --------------- indra/llxuixml/llxuiparser.h | 242 --- indra/newview/CMakeLists.txt | 3 - indra/newview/llviewerprecompiledheaders.h | 4 +- 28 files changed, 5709 insertions(+), 5824 deletions(-) create mode 100644 indra/llcommon/llinitparam.cpp create mode 100644 indra/llcommon/llinitparam.h create mode 100644 indra/llcommon/llregistry.h create mode 100644 indra/llui/lltrans.cpp create mode 100644 indra/llui/lltrans.h create mode 100644 indra/llui/lluicolor.cpp create mode 100644 indra/llui/lluicolor.h create mode 100644 indra/llui/llxuiparser.cpp create mode 100644 indra/llui/llxuiparser.h delete mode 100644 indra/llxuixml/CMakeLists.txt delete mode 100644 indra/llxuixml/llinitparam.cpp delete mode 100644 indra/llxuixml/llinitparam.h delete mode 100644 indra/llxuixml/llregistry.h delete mode 100644 indra/llxuixml/lltrans.cpp delete mode 100644 indra/llxuixml/lltrans.h delete mode 100644 indra/llxuixml/lluicolor.cpp delete mode 100644 indra/llxuixml/lluicolor.h delete mode 100644 indra/llxuixml/llxuiparser.cpp delete mode 100644 indra/llxuixml/llxuiparser.h (limited to 'indra') diff --git a/indra/CMakeLists.txt b/indra/CMakeLists.txt index 4b1bf49d07..1cebb53a07 100644 --- a/indra/CMakeLists.txt +++ b/indra/CMakeLists.txt @@ -66,7 +66,6 @@ if (VIEWER) add_subdirectory(${LIBS_OPEN_PREFIX}llcrashlogger) add_subdirectory(${LIBS_OPEN_PREFIX}llplugin) add_subdirectory(${LIBS_OPEN_PREFIX}llui) - add_subdirectory(${LIBS_OPEN_PREFIX}llxuixml) add_subdirectory(${LIBS_OPEN_PREFIX}viewer_components) # Legacy C++ tests. Build always, run if LL_TESTS is true. diff --git a/indra/integration_tests/llui_libtest/CMakeLists.txt b/indra/integration_tests/llui_libtest/CMakeLists.txt index 1180460f4b..633ad84159 100644 --- a/indra/integration_tests/llui_libtest/CMakeLists.txt +++ b/indra/integration_tests/llui_libtest/CMakeLists.txt @@ -18,7 +18,6 @@ include(LLWindow) include(LLUI) include(LLVFS) # ugh, needed for LLDir include(LLXML) -include(LLXUIXML) include(Linking) # include(Tut) @@ -32,7 +31,6 @@ include_directories( ${LLVFS_INCLUDE_DIRS} ${LLWINDOW_INCLUDE_DIRS} ${LLXML_INCLUDE_DIRS} - ${LLXUIXML_INCLUDE_DIRS} ) set(llui_libtest_SOURCE_FILES diff --git a/indra/llcommon/CMakeLists.txt b/indra/llcommon/CMakeLists.txt index 0a3eaec5c5..72b1d363b0 100644 --- a/indra/llcommon/CMakeLists.txt +++ b/indra/llcommon/CMakeLists.txt @@ -61,6 +61,7 @@ set(llcommon_SOURCE_FILES llformat.cpp llframetimer.cpp llheartbeat.cpp + llinitparam.cpp llinstancetracker.cpp llliveappconfig.cpp lllivefile.cpp @@ -173,6 +174,7 @@ set(llcommon_HEADER_FILES llheartbeat.h llhttpstatuscodes.h llindexedqueue.h + llinitparam.h llinstancetracker.h llkeythrottle.h lllazy.h @@ -204,6 +206,7 @@ set(llcommon_HEADER_FILES llqueuedthread.h llrand.h llrefcount.h + llregistry.h llrun.h llrefcount.h llsafehandle.h diff --git a/indra/llcommon/llinitparam.cpp b/indra/llcommon/llinitparam.cpp new file mode 100644 index 0000000000..db72aa19b9 --- /dev/null +++ b/indra/llcommon/llinitparam.cpp @@ -0,0 +1,469 @@ +/** + * @file llinitparam.cpp + * @brief parameter block abstraction for creating complex objects and + * parsing construction parameters from xml and LLSD + * + * $LicenseInfo:firstyear=2008&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include "linden_common.h" + +#include "llinitparam.h" + + +namespace LLInitParam +{ + // + // Param + // + Param::Param(BaseBlock* enclosing_block) + : mIsProvided(false) + { + const U8* my_addr = reinterpret_cast(this); + const U8* block_addr = reinterpret_cast(enclosing_block); + mEnclosingBlockOffset = 0x7FFFffff & (U32)(my_addr - block_addr); + } + + // + // ParamDescriptor + // + ParamDescriptor::ParamDescriptor(param_handle_t p, + merge_func_t merge_func, + deserialize_func_t deserialize_func, + serialize_func_t serialize_func, + validation_func_t validation_func, + inspect_func_t inspect_func, + S32 min_count, + S32 max_count) + : mParamHandle(p), + mMergeFunc(merge_func), + mDeserializeFunc(deserialize_func), + mSerializeFunc(serialize_func), + mValidationFunc(validation_func), + mInspectFunc(inspect_func), + mMinCount(min_count), + mMaxCount(max_count), + mUserData(NULL) + {} + + ParamDescriptor::ParamDescriptor() + : mParamHandle(0), + mMergeFunc(NULL), + mDeserializeFunc(NULL), + mSerializeFunc(NULL), + mValidationFunc(NULL), + mInspectFunc(NULL), + mMinCount(0), + mMaxCount(0), + mUserData(NULL) + {} + + ParamDescriptor::~ParamDescriptor() + { + delete mUserData; + } + + // + // Parser + // + Parser::~Parser() + {} + + void Parser::parserWarning(const std::string& message) + { + if (mParseSilently) return; + llwarns << message << llendl; + } + + void Parser::parserError(const std::string& message) + { + if (mParseSilently) return; + llerrs << message << llendl; + } + + + // + // BlockDescriptor + // + void BlockDescriptor::aggregateBlockData(BlockDescriptor& src_block_data) + { + mNamedParams.insert(src_block_data.mNamedParams.begin(), src_block_data.mNamedParams.end()); + std::copy(src_block_data.mUnnamedParams.begin(), src_block_data.mUnnamedParams.end(), std::back_inserter(mUnnamedParams)); + std::copy(src_block_data.mValidationList.begin(), src_block_data.mValidationList.end(), std::back_inserter(mValidationList)); + std::copy(src_block_data.mAllParams.begin(), src_block_data.mAllParams.end(), std::back_inserter(mAllParams)); + } + + BlockDescriptor::BlockDescriptor() + : mMaxParamOffset(0), + mInitializationState(UNINITIALIZED), + mCurrentBlockPtr(NULL) + {} + + // called by each derived class in least to most derived order + void BaseBlock::init(BlockDescriptor& descriptor, BlockDescriptor& base_descriptor, size_t block_size) + { + descriptor.mCurrentBlockPtr = this; + descriptor.mMaxParamOffset = block_size; + + switch(descriptor.mInitializationState) + { + case BlockDescriptor::UNINITIALIZED: + // copy params from base class here + descriptor.aggregateBlockData(base_descriptor); + + descriptor.mInitializationState = BlockDescriptor::INITIALIZING; + break; + case BlockDescriptor::INITIALIZING: + descriptor.mInitializationState = BlockDescriptor::INITIALIZED; + break; + case BlockDescriptor::INITIALIZED: + // nothing to do + break; + } + } + + param_handle_t BaseBlock::getHandleFromParam(const Param* param) const + { + const U8* param_address = reinterpret_cast(param); + const U8* baseblock_address = reinterpret_cast(this); + return (param_address - baseblock_address); + } + + bool BaseBlock::submitValue(Parser::name_stack_t& name_stack, Parser& p, bool silent) + { + if (!deserializeBlock(p, std::make_pair(name_stack.begin(), name_stack.end()), true)) + { + if (!silent) + { + p.parserWarning(llformat("Failed to parse parameter \"%s\"", p.getCurrentElementName().c_str())); + } + return false; + } + return true; + } + + + bool BaseBlock::validateBlock(bool emit_errors) const + { + const BlockDescriptor& block_data = mostDerivedBlockDescriptor(); + for (BlockDescriptor::param_validation_list_t::const_iterator it = block_data.mValidationList.begin(); it != block_data.mValidationList.end(); ++it) + { + const Param* param = getParamFromHandle(it->first); + if (!it->second(param)) + { + if (emit_errors) + { + llwarns << "Invalid param \"" << getParamName(block_data, param) << "\"" << llendl; + } + return false; + } + } + return true; + } + + void BaseBlock::serializeBlock(Parser& parser, Parser::name_stack_t& name_stack, const LLInitParam::BaseBlock* diff_block) const + { + // named param is one like LLView::Params::follows + // unnamed param is like LLView::Params::rect - implicit + const BlockDescriptor& block_data = mostDerivedBlockDescriptor(); + + for (BlockDescriptor::param_list_t::const_iterator it = block_data.mUnnamedParams.begin(); + it != block_data.mUnnamedParams.end(); + ++it) + { + param_handle_t param_handle = (*it)->mParamHandle; + const Param* param = getParamFromHandle(param_handle); + ParamDescriptor::serialize_func_t serialize_func = (*it)->mSerializeFunc; + if (serialize_func) + { + const Param* diff_param = diff_block ? diff_block->getParamFromHandle(param_handle) : NULL; + // each param descriptor remembers its serial number + // so we can inspect the same param under different names + // and see that it has the same number + name_stack.push_back(std::make_pair("", true)); + serialize_func(*param, parser, name_stack, diff_param); + name_stack.pop_back(); + } + } + + for(BlockDescriptor::param_map_t::const_iterator it = block_data.mNamedParams.begin(); + it != block_data.mNamedParams.end(); + ++it) + { + param_handle_t param_handle = it->second->mParamHandle; + const Param* param = getParamFromHandle(param_handle); + ParamDescriptor::serialize_func_t serialize_func = it->second->mSerializeFunc; + if (serialize_func && param->anyProvided()) + { + // Ensure this param has not already been serialized + // Prevents from being serialized as its own tag. + bool duplicate = false; + for (BlockDescriptor::param_list_t::const_iterator it2 = block_data.mUnnamedParams.begin(); + it2 != block_data.mUnnamedParams.end(); + ++it2) + { + if (param_handle == (*it2)->mParamHandle) + { + duplicate = true; + break; + } + } + + //FIXME: for now, don't attempt to serialize values under synonyms, as current parsers + // don't know how to detect them + if (duplicate) + { + continue; + } + + name_stack.push_back(std::make_pair(it->first, !duplicate)); + const Param* diff_param = diff_block ? diff_block->getParamFromHandle(param_handle) : NULL; + serialize_func(*param, parser, name_stack, diff_param); + name_stack.pop_back(); + } + } + } + + bool BaseBlock::inspectBlock(Parser& parser, Parser::name_stack_t name_stack, S32 min_count, S32 max_count) const + { + // named param is one like LLView::Params::follows + // unnamed param is like LLView::Params::rect - implicit + const BlockDescriptor& block_data = mostDerivedBlockDescriptor(); + + for (BlockDescriptor::param_list_t::const_iterator it = block_data.mUnnamedParams.begin(); + it != block_data.mUnnamedParams.end(); + ++it) + { + param_handle_t param_handle = (*it)->mParamHandle; + const Param* param = getParamFromHandle(param_handle); + ParamDescriptor::inspect_func_t inspect_func = (*it)->mInspectFunc; + if (inspect_func) + { + name_stack.push_back(std::make_pair("", true)); + inspect_func(*param, parser, name_stack, (*it)->mMinCount, (*it)->mMaxCount); + name_stack.pop_back(); + } + } + + for(BlockDescriptor::param_map_t::const_iterator it = block_data.mNamedParams.begin(); + it != block_data.mNamedParams.end(); + ++it) + { + param_handle_t param_handle = it->second->mParamHandle; + const Param* param = getParamFromHandle(param_handle); + ParamDescriptor::inspect_func_t inspect_func = it->second->mInspectFunc; + if (inspect_func) + { + // Ensure this param has not already been inspected + bool duplicate = false; + for (BlockDescriptor::param_list_t::const_iterator it2 = block_data.mUnnamedParams.begin(); + it2 != block_data.mUnnamedParams.end(); + ++it2) + { + if (param_handle == (*it2)->mParamHandle) + { + duplicate = true; + break; + } + } + + name_stack.push_back(std::make_pair(it->first, !duplicate)); + inspect_func(*param, parser, name_stack, it->second->mMinCount, it->second->mMaxCount); + name_stack.pop_back(); + } + } + + return true; + } + + bool BaseBlock::deserializeBlock(Parser& p, Parser::name_stack_range_t name_stack_range, bool ignored) + { + BlockDescriptor& block_data = mostDerivedBlockDescriptor(); + bool names_left = name_stack_range.first != name_stack_range.second; + + bool new_name = names_left + ? name_stack_range.first->second + : true; + + if (names_left) + { + const std::string& top_name = name_stack_range.first->first; + + ParamDescriptor::deserialize_func_t deserialize_func = NULL; + Param* paramp = NULL; + + BlockDescriptor::param_map_t::iterator found_it = block_data.mNamedParams.find(top_name); + if (found_it != block_data.mNamedParams.end()) + { + // find pointer to member parameter from offset table + paramp = getParamFromHandle(found_it->second->mParamHandle); + deserialize_func = found_it->second->mDeserializeFunc; + + Parser::name_stack_range_t new_name_stack(name_stack_range.first, name_stack_range.second); + ++new_name_stack.first; + if (deserialize_func(*paramp, p, new_name_stack, new_name)) + { + // value is no longer new, we know about it now + name_stack_range.first->second = false; + return true; + } + else + { + return false; + } + } + } + + // try to parse unnamed parameters, in declaration order + for ( BlockDescriptor::param_list_t::iterator it = block_data.mUnnamedParams.begin(); + it != block_data.mUnnamedParams.end(); + ++it) + { + Param* paramp = getParamFromHandle((*it)->mParamHandle); + ParamDescriptor::deserialize_func_t deserialize_func = (*it)->mDeserializeFunc; + + if (deserialize_func && deserialize_func(*paramp, p, name_stack_range, new_name)) + { + return true; + } + } + + // if no match, and no names left on stack, this is just an existence assertion of this block + // verify by calling readValue with NoParamValue type, an inherently unparseable type + if (!names_left) + { + Flag no_value; + return p.readValue(no_value); + } + + return false; + } + + //static + void BaseBlock::addParam(BlockDescriptor& block_data, const ParamDescriptorPtr in_param, const char* char_name) + { + // create a copy of the param descriptor in mAllParams + // so other data structures can store a pointer to it + block_data.mAllParams.push_back(in_param); + ParamDescriptorPtr param(block_data.mAllParams.back()); + + std::string name(char_name); + if ((size_t)param->mParamHandle > block_data.mMaxParamOffset) + { + llerrs << "Attempted to register param with block defined for parent class, make sure to derive from LLInitParam::Block" << llendl; + } + + if (name.empty()) + { + block_data.mUnnamedParams.push_back(param); + } + else + { + // don't use insert, since we want to overwrite existing entries + block_data.mNamedParams[name] = param; + } + + if (param->mValidationFunc) + { + block_data.mValidationList.push_back(std::make_pair(param->mParamHandle, param->mValidationFunc)); + } + } + + void BaseBlock::addSynonym(Param& param, const std::string& synonym) + { + BlockDescriptor& block_data = mostDerivedBlockDescriptor(); + if (block_data.mInitializationState == BlockDescriptor::INITIALIZING) + { + param_handle_t handle = getHandleFromParam(¶m); + + // check for invalid derivation from a paramblock (i.e. without using + // Block + if ((size_t)handle > block_data.mMaxParamOffset) + { + llerrs << "Attempted to register param with block defined for parent class, make sure to derive from LLInitParam::Block" << llendl; + } + + ParamDescriptorPtr param_descriptor = findParamDescriptor(param); + if (param_descriptor) + { + if (synonym.empty()) + { + block_data.mUnnamedParams.push_back(param_descriptor); + } + else + { + block_data.mNamedParams[synonym] = param_descriptor; + } + } + } + } + + const std::string& BaseBlock::getParamName(const BlockDescriptor& block_data, const Param* paramp) const + { + param_handle_t handle = getHandleFromParam(paramp); + for (BlockDescriptor::param_map_t::const_iterator it = block_data.mNamedParams.begin(); it != block_data.mNamedParams.end(); ++it) + { + if (it->second->mParamHandle == handle) + { + return it->first; + } + } + + return LLStringUtil::null; + } + + ParamDescriptorPtr BaseBlock::findParamDescriptor(const Param& param) + { + param_handle_t handle = getHandleFromParam(¶m); + BlockDescriptor& descriptor = mostDerivedBlockDescriptor(); + BlockDescriptor::all_params_list_t::iterator end_it = descriptor.mAllParams.end(); + for (BlockDescriptor::all_params_list_t::iterator it = descriptor.mAllParams.begin(); + it != end_it; + ++it) + { + if ((*it)->mParamHandle == handle) return *it; + } + return ParamDescriptorPtr(); + } + + // take all provided params from other and apply to self + // NOTE: this requires that "other" is of the same derived type as this + bool BaseBlock::mergeBlock(BlockDescriptor& block_data, const BaseBlock& other, bool overwrite) + { + bool some_param_changed = false; + BlockDescriptor::all_params_list_t::const_iterator end_it = block_data.mAllParams.end(); + for (BlockDescriptor::all_params_list_t::const_iterator it = block_data.mAllParams.begin(); + it != end_it; + ++it) + { + const Param* other_paramp = other.getParamFromHandle((*it)->mParamHandle); + ParamDescriptor::merge_func_t merge_func = (*it)->mMergeFunc; + if (merge_func) + { + Param* paramp = getParamFromHandle((*it)->mParamHandle); + llassert(paramp->mEnclosingBlockOffset == (*it)->mParamHandle); + some_param_changed |= merge_func(*paramp, *other_paramp, overwrite); + } + } + return some_param_changed; + } +} diff --git a/indra/llcommon/llinitparam.h b/indra/llcommon/llinitparam.h new file mode 100644 index 0000000000..550e1608cc --- /dev/null +++ b/indra/llcommon/llinitparam.h @@ -0,0 +1,2294 @@ +/** + * @file llinitparam.h + * @brief parameter block abstraction for creating complex objects and + * parsing construction parameters from xml and LLSD + * + * $LicenseInfo:firstyear=2008&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#ifndef LL_LLPARAM_H +#define LL_LLPARAM_H + +#include +#include +#include +#include +#include + +#include "llerror.h" + +namespace LLInitParam +{ + // used to indicate no matching value to a given name when parsing + struct Flag{}; + + template const T& defaultValue() { static T value; return value; } + + template ::value > + struct ParamCompare + { + static bool equals(const T &a, const T &b) + { + return a == b; + } + }; + + // boost function types are not comparable + template + struct ParamCompare + { + static bool equals(const T&a, const T &b) + { + return false; + } + }; + + template<> + struct ParamCompare + { + static bool equals(const LLSD &a, const LLSD &b) { return false; } + }; + + template<> + struct ParamCompare + { + static bool equals(const Flag& a, const Flag& b) { return false; } + }; + + + // helper functions and classes + typedef ptrdiff_t param_handle_t; + + // empty default implementation of key cache + // leverages empty base class optimization + template + class TypeValues + { + private: + struct Inaccessable{}; + public: + typedef std::map value_name_map_t; + typedef Inaccessable name_t; + + void setValueName(const std::string& key) {} + std::string getValueName() const { return ""; } + std::string calcValueName(const T& value) const { return ""; } + void clearValueName() const {} + + static bool getValueFromName(const std::string& name, T& value) + { + return false; + } + + static bool valueNamesExist() + { + return false; + } + + static std::vector* getPossibleValues() + { + return NULL; + } + + static value_name_map_t* getValueNames() {return NULL;} + }; + + template > + class TypeValuesHelper + { + public: + typedef typename std::map value_name_map_t; + typedef std::string name_t; + + //TODO: cache key by index to save on param block size + void setValueName(const std::string& value_name) + { + mValueName = value_name; + } + + std::string getValueName() const + { + return mValueName; + } + + std::string calcValueName(const T& value) const + { + value_name_map_t* map = getValueNames(); + for (typename value_name_map_t::iterator it = map->begin(), end_it = map->end(); + it != end_it; + ++it) + { + if (ParamCompare::equals(it->second, value)) + { + return it->first; + } + } + + return ""; + } + + void clearValueName() const + { + mValueName.clear(); + } + + static bool getValueFromName(const std::string& name, T& value) + { + value_name_map_t* map = getValueNames(); + typename value_name_map_t::iterator found_it = map->find(name); + if (found_it == map->end()) return false; + + value = found_it->second; + return true; + } + + static bool valueNamesExist() + { + return !getValueNames()->empty(); + } + + static value_name_map_t* getValueNames() + { + static value_name_map_t sMap; + static bool sInitialized = false; + + if (!sInitialized) + { + sInitialized = true; + DERIVED_TYPE::declareValues(); + } + return &sMap; + } + + static std::vector* getPossibleValues() + { + static std::vector sValues; + + value_name_map_t* map = getValueNames(); + for (typename value_name_map_t::iterator it = map->begin(), end_it = map->end(); + it != end_it; + ++it) + { + sValues.push_back(it->first); + } + return &sValues; + } + + static void declare(const std::string& name, const T& value) + { + (*getValueNames())[name] = value; + } + + protected: + static void getName(const std::string& name, const T& value) + {} + + mutable std::string mValueName; + }; + + class LL_COMMON_API Parser + { + LOG_CLASS(Parser); + + public: + + struct CompareTypeID + { + bool operator()(const std::type_info* lhs, const std::type_info* rhs) const + { + return lhs->before(*rhs); + } + }; + + typedef std::vector > name_stack_t; + typedef std::pair name_stack_range_t; + typedef std::vector possible_values_t; + + typedef bool (*parser_read_func_t)(Parser& parser, void* output); + typedef bool (*parser_write_func_t)(Parser& parser, const void*, name_stack_t&); + typedef boost::function parser_inspect_func_t; + + typedef std::map parser_read_func_map_t; + typedef std::map parser_write_func_map_t; + typedef std::map parser_inspect_func_map_t; + + Parser(parser_read_func_map_t& read_map, parser_write_func_map_t& write_map, parser_inspect_func_map_t& inspect_map) + : mParseSilently(false), + mParserReadFuncs(&read_map), + mParserWriteFuncs(&write_map), + mParserInspectFuncs(&inspect_map) + {} + virtual ~Parser(); + + template bool readValue(T& param) + { + parser_read_func_map_t::iterator found_it = mParserReadFuncs->find(&typeid(T)); + if (found_it != mParserReadFuncs->end()) + { + return found_it->second(*this, (void*)¶m); + } + return false; + } + + template bool writeValue(const T& param, name_stack_t& name_stack) + { + parser_write_func_map_t::iterator found_it = mParserWriteFuncs->find(&typeid(T)); + if (found_it != mParserWriteFuncs->end()) + { + return found_it->second(*this, (const void*)¶m, name_stack); + } + return false; + } + + // dispatch inspection to registered inspection functions, for each parameter in a param block + template bool inspectValue(name_stack_t& name_stack, S32 min_count, S32 max_count, const possible_values_t* possible_values) + { + parser_inspect_func_map_t::iterator found_it = mParserInspectFuncs->find(&typeid(T)); + if (found_it != mParserInspectFuncs->end()) + { + found_it->second(name_stack, min_count, max_count, possible_values); + return true; + } + return false; + } + + virtual std::string getCurrentElementName() = 0; + virtual void parserWarning(const std::string& message); + virtual void parserError(const std::string& message); + void setParseSilently(bool silent) { mParseSilently = silent; } + + protected: + template + void registerParserFuncs(parser_read_func_t read_func, parser_write_func_t write_func = NULL) + { + mParserReadFuncs->insert(std::make_pair(&typeid(T), read_func)); + mParserWriteFuncs->insert(std::make_pair(&typeid(T), write_func)); + } + + template + void registerInspectFunc(parser_inspect_func_t inspect_func) + { + mParserInspectFuncs->insert(std::make_pair(&typeid(T), inspect_func)); + } + + bool mParseSilently; + + private: + parser_read_func_map_t* mParserReadFuncs; + parser_write_func_map_t* mParserWriteFuncs; + parser_inspect_func_map_t* mParserInspectFuncs; + }; + + class Param; + + // various callbacks and constraints associated with an individual param + struct LL_COMMON_API ParamDescriptor + { + struct UserData + { + virtual ~UserData() {} + }; + + typedef bool(*merge_func_t)(Param&, const Param&, bool); + typedef bool(*deserialize_func_t)(Param&, Parser&, const Parser::name_stack_range_t&, bool); + typedef void(*serialize_func_t)(const Param&, Parser&, Parser::name_stack_t&, const Param* diff_param); + typedef void(*inspect_func_t)(const Param&, Parser&, Parser::name_stack_t&, S32 min_count, S32 max_count); + typedef bool(*validation_func_t)(const Param*); + + ParamDescriptor(param_handle_t p, + merge_func_t merge_func, + deserialize_func_t deserialize_func, + serialize_func_t serialize_func, + validation_func_t validation_func, + inspect_func_t inspect_func, + S32 min_count, + S32 max_count); + + ParamDescriptor(); + ~ParamDescriptor(); + + param_handle_t mParamHandle; + merge_func_t mMergeFunc; + deserialize_func_t mDeserializeFunc; + serialize_func_t mSerializeFunc; + inspect_func_t mInspectFunc; + validation_func_t mValidationFunc; + S32 mMinCount; + S32 mMaxCount; + S32 mNumRefs; + UserData* mUserData; + }; + + typedef boost::shared_ptr ParamDescriptorPtr; + + // each derived Block class keeps a static data structure maintaining offsets to various params + class LL_COMMON_API BlockDescriptor + { + public: + BlockDescriptor(); + + typedef enum e_initialization_state + { + UNINITIALIZED, + INITIALIZING, + INITIALIZED + } EInitializationState; + + void aggregateBlockData(BlockDescriptor& src_block_data); + + typedef boost::unordered_map param_map_t; + typedef std::vector param_list_t; + typedef std::list all_params_list_t; + typedef std::vector > param_validation_list_t; + + param_map_t mNamedParams; // parameters with associated names + param_list_t mUnnamedParams; // parameters with_out_ associated names + param_validation_list_t mValidationList; // parameters that must be validated + all_params_list_t mAllParams; // all parameters, owns descriptors + size_t mMaxParamOffset; + EInitializationState mInitializationState; // whether or not static block data has been initialized + class BaseBlock* mCurrentBlockPtr; // pointer to block currently being constructed + }; + + class LL_COMMON_API BaseBlock + { + public: + //TODO: implement in terms of owned_ptr + template + class Lazy + { + public: + Lazy() + : mPtr(NULL) + {} + + ~Lazy() + { + delete mPtr; + } + + Lazy(const Lazy& other) + { + if (other.mPtr) + { + mPtr = new T(*other.mPtr); + } + else + { + mPtr = NULL; + } + } + + Lazy& operator = (const Lazy& other) + { + if (other.mPtr) + { + mPtr = new T(*other.mPtr); + } + else + { + mPtr = NULL; + } + return *this; + } + + bool empty() const + { + return mPtr == NULL; + } + + void set(const T& other) + { + delete mPtr; + mPtr = new T(other); + } + + const T& get() const + { + return ensureInstance(); + } + + T& get() + { + return ensureInstance(); + } + + private: + // lazily allocate an instance of T + T* ensureInstance() const + { + if (mPtr == NULL) + { + mPtr = new T(); + } + return mPtr; + } + + private: + // if you get a compilation error with this, that means you are using a forward declared struct for T + // unfortunately, the type traits we rely on don't work with forward declared typed + //static const int dummy = sizeof(T); + + mutable T* mPtr; + }; + + // "Multiple" constraint types, put here in root class to avoid ambiguity during use + struct AnyAmount + { + enum { minCount = 0 }; + enum { maxCount = U32_MAX }; + }; + + template + struct AtLeast + { + enum { minCount = MIN_AMOUNT }; + enum { maxCount = U32_MAX }; + }; + + template + struct AtMost + { + enum { minCount = 0 }; + enum { maxCount = MAX_AMOUNT }; + }; + + template + struct Between + { + enum { minCount = MIN_AMOUNT }; + enum { maxCount = MAX_AMOUNT }; + }; + + template + struct Exactly + { + enum { minCount = EXACT_COUNT }; + enum { maxCount = EXACT_COUNT }; + }; + + // this typedef identifies derived classes as being blocks + typedef void baseblock_base_class_t; + LOG_CLASS(BaseBlock); + friend class Param; + + virtual ~BaseBlock() {} + bool submitValue(Parser::name_stack_t& name_stack, Parser& p, bool silent=false); + + param_handle_t getHandleFromParam(const Param* param) const; + bool validateBlock(bool emit_errors = true) const; + + Param* getParamFromHandle(const param_handle_t param_handle) + { + if (param_handle == 0) return NULL; + + U8* baseblock_address = reinterpret_cast(this); + return reinterpret_cast(baseblock_address + param_handle); + } + + const Param* getParamFromHandle(const param_handle_t param_handle) const + { + const U8* baseblock_address = reinterpret_cast(this); + return reinterpret_cast(baseblock_address + param_handle); + } + + void addSynonym(Param& param, const std::string& synonym); + + // Blocks can override this to do custom tracking of changes + virtual void paramChanged(const Param& changed_param, bool user_provided) {} + + bool deserializeBlock(Parser& p, Parser::name_stack_range_t name_stack_range, bool new_name); + void serializeBlock(Parser& p, Parser::name_stack_t& name_stack, const BaseBlock* diff_block = NULL) const; + bool inspectBlock(Parser& p, Parser::name_stack_t name_stack = Parser::name_stack_t(), S32 min_count = 0, S32 max_count = S32_MAX) const; + + virtual const BlockDescriptor& mostDerivedBlockDescriptor() const { return selfBlockDescriptor(); } + virtual BlockDescriptor& mostDerivedBlockDescriptor() { return selfBlockDescriptor(); } + + // take all provided params from other and apply to self + bool overwriteFrom(const BaseBlock& other) + { + return false; + } + + // take all provided params that are not already provided, and apply to self + bool fillFrom(const BaseBlock& other) + { + return false; + } + + static void addParam(BlockDescriptor& block_data, ParamDescriptorPtr param, const char* name); + + ParamDescriptorPtr findParamDescriptor(const Param& param); + + protected: + void init(BlockDescriptor& descriptor, BlockDescriptor& base_descriptor, size_t block_size); + + + bool mergeBlockParam(bool source_provided, bool dst_provided, BlockDescriptor& block_data, const BaseBlock& source, bool overwrite) + { + return mergeBlock(block_data, source, overwrite); + } + // take all provided params from other and apply to self + bool mergeBlock(BlockDescriptor& block_data, const BaseBlock& other, bool overwrite); + + static BlockDescriptor& selfBlockDescriptor() + { + static BlockDescriptor sBlockDescriptor; + return sBlockDescriptor; + } + + private: + const std::string& getParamName(const BlockDescriptor& block_data, const Param* paramp) const; + }; + + template + struct ParamCompare, false > + { + static bool equals(const BaseBlock::Lazy& a, const BaseBlock::Lazy& b) { return !a.empty() || !b.empty(); } + }; + + class LL_COMMON_API Param + { + public: + void setProvided(bool is_provided = true) + { + mIsProvided = is_provided; + enclosingBlock().paramChanged(*this, is_provided); + } + + Param& operator =(const Param& other) + { + mIsProvided = other.mIsProvided; + // don't change mEnclosingblockoffset + return *this; + } + protected: + + bool anyProvided() const { return mIsProvided; } + + Param(BaseBlock* enclosing_block); + + // store pointer to enclosing block as offset to reduce space and allow for quick copying + BaseBlock& enclosingBlock() const + { + const U8* my_addr = reinterpret_cast(this); + // get address of enclosing BLOCK class using stored offset to enclosing BaseBlock class + return *const_cast + (reinterpret_cast + (my_addr - (ptrdiff_t)(S32)mEnclosingBlockOffset)); + } + + private: + friend class BaseBlock; + + U32 mEnclosingBlockOffset:31; + U32 mIsProvided:1; + + }; + + // these templates allow us to distinguish between template parameters + // that derive from BaseBlock and those that don't + template + struct IsBlock + { + static const bool value = false; + struct EmptyBase {}; + typedef EmptyBase base_class_t; + }; + + template + struct IsBlock + { + static const bool value = true; + typedef BaseBlock base_class_t; + }; + + template + struct IsBlock, typename T::baseblock_base_class_t > + { + static const bool value = true; + typedef BaseBlock base_class_t; + }; + + template::value> + class ParamValue : public NAME_VALUE_LOOKUP + { + public: + typedef const T& value_assignment_t; + typedef T value_t; + typedef ParamValue self_t; + + ParamValue(): mValue() {} + ParamValue(value_assignment_t other) : mValue(other) {} + + void setValue(value_assignment_t val) + { + mValue = val; + } + + value_assignment_t getValue() const + { + return mValue; + } + + T& getValue() + { + return mValue; + } + + operator value_assignment_t() const + { + return mValue; + } + + value_assignment_t operator()() const + { + return mValue; + } + + void operator ()(const typename NAME_VALUE_LOOKUP::name_t& name) + { + *this = name; + } + + self_t& operator =(const typename NAME_VALUE_LOOKUP::name_t& name) + { + if (NAME_VALUE_LOOKUP::getValueFromName(name, mValue)) + { + setValueName(name); + } + + return *this; + } + + protected: + T mValue; + }; + + template + class ParamValue + : public T, + public NAME_VALUE_LOOKUP + { + public: + typedef const T& value_assignment_t; + typedef T value_t; + typedef ParamValue self_t; + + ParamValue() + : T(), + mValidated(false) + {} + + ParamValue(value_assignment_t other) + : T(other), + mValidated(false) + {} + + void setValue(value_assignment_t val) + { + *this = val; + } + + value_assignment_t getValue() const + { + return *this; + } + + T& getValue() + { + return *this; + } + + operator value_assignment_t() const + { + return *this; + } + + value_assignment_t operator()() const + { + return *this; + } + + void operator ()(const typename NAME_VALUE_LOOKUP::name_t& name) + { + *this = name; + } + + self_t& operator =(const typename NAME_VALUE_LOOKUP::name_t& name) + { + if (NAME_VALUE_LOOKUP::getValueFromName(name, *this)) + { + setValueName(name); + } + + return *this; + } + + protected: + mutable bool mValidated; // lazy validation flag + }; + + template + class ParamValue + : public NAME_VALUE_LOOKUP + { + public: + typedef const std::string& value_assignment_t; + typedef std::string value_t; + typedef ParamValue self_t; + + ParamValue(): mValue() {} + ParamValue(value_assignment_t other) : mValue(other) {} + + void setValue(value_assignment_t val) + { + if (NAME_VALUE_LOOKUP::getValueFromName(val, mValue)) + { + NAME_VALUE_LOOKUP::setValueName(val); + } + else + { + mValue = val; + } + } + + value_assignment_t getValue() const + { + return mValue; + } + + std::string& getValue() + { + return mValue; + } + + operator value_assignment_t() const + { + return mValue; + } + + value_assignment_t operator()() const + { + return mValue; + } + + protected: + std::string mValue; + }; + + + template > + struct ParamIterator + { + typedef typename std::vector >::const_iterator const_iterator; + typedef typename std::vector >::iterator iterator; + }; + + // specialize for custom parsing/decomposition of specific classes + // e.g. TypedParam has left, top, right, bottom, etc... + template, + bool HAS_MULTIPLE_VALUES = false, + bool VALUE_IS_BLOCK = IsBlock >::value> + class TypedParam + : public Param, + public ParamValue + { + public: + typedef TypedParam self_t; + typedef ParamValue param_value_t; + typedef typename param_value_t::value_assignment_t value_assignment_t; + typedef NAME_VALUE_LOOKUP name_value_lookup_t; + + using param_value_t::operator(); + + TypedParam(BlockDescriptor& block_descriptor, const char* name, value_assignment_t value, ParamDescriptor::validation_func_t validate_func, S32 min_count, S32 max_count) + : Param(block_descriptor.mCurrentBlockPtr) + { + if (LL_UNLIKELY(block_descriptor.mInitializationState == BlockDescriptor::INITIALIZING)) + { + ParamDescriptorPtr param_descriptor = ParamDescriptorPtr(new ParamDescriptor( + block_descriptor.mCurrentBlockPtr->getHandleFromParam(this), + &mergeWith, + &deserializeParam, + &serializeParam, + validate_func, + &inspectParam, + min_count, max_count)); + BaseBlock::addParam(block_descriptor, param_descriptor, name); + } + + setValue(value); + } + + bool isProvided() const { return Param::anyProvided(); } + + static bool deserializeParam(Param& param, Parser& parser, const Parser::name_stack_range_t& name_stack_range, bool new_name) + { + self_t& typed_param = static_cast(param); + // no further names in stack, attempt to parse value now + if (name_stack_range.first == name_stack_range.second) + { + if (parser.readValue(typed_param.getValue())) + { + typed_param.clearValueName(); + typed_param.setProvided(); + return true; + } + + // try to parse a known named value + if(name_value_lookup_t::valueNamesExist()) + { + // try to parse a known named value + std::string name; + if (parser.readValue(name)) + { + // try to parse a per type named value + if (name_value_lookup_t::getValueFromName(name, typed_param.getValue())) + { + typed_param.setValueName(name); + typed_param.setProvided(); + return true; + } + + } + } + } + return false; + } + + static void serializeParam(const Param& param, Parser& parser, Parser::name_stack_t& name_stack, const Param* diff_param) + { + const self_t& typed_param = static_cast(param); + if (!typed_param.isProvided()) return; + + if (!name_stack.empty()) + { + name_stack.back().second = true; + } + + std::string key = typed_param.getValueName(); + + // first try to write out name of name/value pair + + if (!key.empty()) + { + if (!diff_param || !ParamCompare::equals(static_cast(diff_param)->getValueName(), key)) + { + parser.writeValue(key, name_stack); + } + } + // then try to serialize value directly + else if (!diff_param || !ParamCompare::equals(typed_param.getValue(), static_cast(diff_param)->getValue())) + { + if (!parser.writeValue(typed_param.getValue(), name_stack)) + { + std::string calculated_key = typed_param.calcValueName(typed_param.getValue()); + if (!diff_param || !ParamCompare::equals(static_cast(diff_param)->getValueName(), calculated_key)) + { + parser.writeValue(calculated_key, name_stack); + } + } + } + } + + static void inspectParam(const Param& param, Parser& parser, Parser::name_stack_t& name_stack, S32 min_count, S32 max_count) + { + // tell parser about our actual type + parser.inspectValue(name_stack, min_count, max_count, NULL); + // then tell it about string-based alternatives ("red", "blue", etc. for LLColor4) + if (name_value_lookup_t::getPossibleValues()) + { + parser.inspectValue(name_stack, min_count, max_count, name_value_lookup_t::getPossibleValues()); + } + } + + void set(value_assignment_t val, bool flag_as_provided = true) + { + param_value_t::clearValueName(); + setValue(val); + setProvided(flag_as_provided); + } + + self_t& operator =(const typename NAME_VALUE_LOOKUP::name_t& name) + { + return static_cast(param_value_t::operator =(name)); + } + + protected: + + self_t& operator =(const self_t& other) + { + param_value_t::operator =(other); + Param::operator =(other); + return *this; + } + + static bool mergeWith(Param& dst, const Param& src, bool overwrite) + { + const self_t& src_typed_param = static_cast(src); + self_t& dst_typed_param = static_cast(dst); + + if (src_typed_param.isProvided() + && (overwrite || !dst_typed_param.isProvided())) + { + dst_typed_param.set(src_typed_param.getValue()); + return true; + } + return false; + } + }; + + // parameter that is a block + template + class TypedParam + : public Param, + public ParamValue + { + public: + typedef ParamValue param_value_t; + typedef typename param_value_t::value_assignment_t value_assignment_t; + typedef TypedParam self_t; + typedef NAME_VALUE_LOOKUP name_value_lookup_t; + + using param_value_t::operator(); + + TypedParam(BlockDescriptor& block_descriptor, const char* name, value_assignment_t value, ParamDescriptor::validation_func_t validate_func, S32 min_count, S32 max_count) + : Param(block_descriptor.mCurrentBlockPtr), + param_value_t(value) + { + if (LL_UNLIKELY(block_descriptor.mInitializationState == BlockDescriptor::INITIALIZING)) + { + ParamDescriptorPtr param_descriptor = ParamDescriptorPtr(new ParamDescriptor( + block_descriptor.mCurrentBlockPtr->getHandleFromParam(this), + &mergeWith, + &deserializeParam, + &serializeParam, + validate_func, + &inspectParam, + min_count, max_count)); + BaseBlock::addParam(block_descriptor, param_descriptor, name); + } + } + + static bool deserializeParam(Param& param, Parser& parser, const Parser::name_stack_range_t& name_stack_range, bool new_name) + { + self_t& typed_param = static_cast(param); + // attempt to parse block... + if(typed_param.deserializeBlock(parser, name_stack_range, new_name)) + { + typed_param.clearValueName(); + typed_param.setProvided(); + return true; + } + + if(name_value_lookup_t::valueNamesExist()) + { + // try to parse a known named value + std::string name; + if (parser.readValue(name)) + { + // try to parse a per type named value + if (name_value_lookup_t::getValueFromName(name, typed_param.getValue())) + { + typed_param.setValueName(name); + typed_param.setProvided(); + return true; + } + + } + } + return false; + } + + static void serializeParam(const Param& param, Parser& parser, Parser::name_stack_t& name_stack, const Param* diff_param) + { + const self_t& typed_param = static_cast(param); + if (!typed_param.isProvided()) return; + + if (!name_stack.empty()) + { + name_stack.back().second = true; + } + + std::string key = typed_param.getValueName(); + if (!key.empty()) + { + if (!parser.writeValue(key, name_stack)) + { + return; + } + } + else + { + typed_param.serializeBlock(parser, name_stack, static_cast(diff_param)); + } + } + + static void inspectParam(const Param& param, Parser& parser, Parser::name_stack_t& name_stack, S32 min_count, S32 max_count) + { + // I am a param that is also a block, so just recurse into my contents + const self_t& typed_param = static_cast(param); + typed_param.inspectBlock(parser, name_stack, min_count, max_count); + } + + // a param-that-is-a-block is provided when the user has set one of its child params + // *and* the block as a whole validates + bool isProvided() const + { + // only validate block when it hasn't already passed validation with current data + if (Param::anyProvided() && !param_value_t::mValidated) + { + // a sub-block is "provided" when it has been filled in enough to be valid + param_value_t::mValidated = param_value_t::validateBlock(false); + } + return Param::anyProvided() && param_value_t::mValidated; + } + + // assign block contents to this param-that-is-a-block + void set(value_assignment_t val, bool flag_as_provided = true) + { + setValue(val); + param_value_t::clearValueName(); + // force revalidation of block + // next call to isProvided() will update provision status based on validity + param_value_t::mValidated = false; + setProvided(flag_as_provided); + } + + self_t& operator =(const typename NAME_VALUE_LOOKUP::name_t& name) + { + return static_cast(param_value_t::operator =(name)); + } + + // propagate changed status up to enclosing block + /*virtual*/ void paramChanged(const Param& changed_param, bool user_provided) + { + param_value_t::paramChanged(changed_param, user_provided); + if (user_provided) + { + // a child param has been explicitly changed + // so *some* aspect of this block is now provided + param_value_t::mValidated = false; + setProvided(); + param_value_t::clearValueName(); + } + else + { + Param::enclosingBlock().paramChanged(*this, user_provided); + } + } + + protected: + + self_t& operator =(const self_t& other) + { + param_value_t::operator =(other); + Param::operator =(other); + return *this; + } + + static bool mergeWith(Param& dst, const Param& src, bool overwrite) + { + const self_t& src_typed_param = static_cast(src); + self_t& dst_typed_param = static_cast(dst); + + if (src_typed_param.anyProvided()) + { + if (dst_typed_param.mergeBlockParam(src_typed_param.isProvided(), dst_typed_param.isProvided(), param_value_t::selfBlockDescriptor(), src_typed_param, overwrite)) + { + dst_typed_param.clearValueName(); + dst_typed_param.setProvided(true); + return true; + } + } + return false; + } + }; + + // container of non-block parameters + template + class TypedParam + : public Param + { + public: + typedef TypedParam self_t; + typedef ParamValue param_value_t; + typedef typename std::vector container_t; + typedef const container_t& value_assignment_t; + + typedef typename param_value_t::value_t value_t; + typedef NAME_VALUE_LOOKUP name_value_lookup_t; + + TypedParam(BlockDescriptor& block_descriptor, const char* name, value_assignment_t value, ParamDescriptor::validation_func_t validate_func, S32 min_count, S32 max_count) + : Param(block_descriptor.mCurrentBlockPtr) + { + std::copy(value.begin(), value.end(), std::back_inserter(mValues)); + + if (LL_UNLIKELY(block_descriptor.mInitializationState == BlockDescriptor::INITIALIZING)) + { + ParamDescriptorPtr param_descriptor = ParamDescriptorPtr(new ParamDescriptor( + block_descriptor.mCurrentBlockPtr->getHandleFromParam(this), + &mergeWith, + &deserializeParam, + &serializeParam, + validate_func, + &inspectParam, + min_count, max_count)); + BaseBlock::addParam(block_descriptor, param_descriptor, name); + } + } + + bool isProvided() const { return Param::anyProvided(); } + + static bool deserializeParam(Param& param, Parser& parser, const Parser::name_stack_range_t& name_stack_range, bool new_name) + { + self_t& typed_param = static_cast(param); + value_t value; + // no further names in stack, attempt to parse value now + if (name_stack_range.first == name_stack_range.second) + { + // attempt to read value directly + if (parser.readValue(value)) + { + typed_param.add(value); + return true; + } + + // try to parse a known named value + if(name_value_lookup_t::valueNamesExist()) + { + // try to parse a known named value + std::string name; + if (parser.readValue(name)) + { + // try to parse a per type named value + if (name_value_lookup_t::getValueFromName(name, value)) + { + typed_param.add(value); + typed_param.mValues.back().setValueName(name); + return true; + } + + } + } + } + return false; + } + + static void serializeParam(const Param& param, Parser& parser, Parser::name_stack_t& name_stack, const Param* diff_param) + { + const self_t& typed_param = static_cast(param); + if (!typed_param.isProvided() || name_stack.empty()) return; + + for (const_iterator it = typed_param.mValues.begin(), end_it = typed_param.mValues.end(); + it != end_it; + ++it) + { + std::string key = it->getValueName(); + name_stack.back().second = true; + + if(key.empty()) + // not parsed via name values, write out value directly + { + bool value_written = parser.writeValue(*it, name_stack); + if (!value_written) + { + std::string calculated_key = it->calcValueName(it->getValue()); + if (!parser.writeValue(calculated_key, name_stack)) + { + break; + } + } + } + else + { + if(!parser.writeValue(key, name_stack)) + { + break; + } + } + } + } + + static void inspectParam(const Param& param, Parser& parser, Parser::name_stack_t& name_stack, S32 min_count, S32 max_count) + { + parser.inspectValue(name_stack, min_count, max_count, NULL); + if (name_value_lookup_t::getPossibleValues()) + { + parser.inspectValue(name_stack, min_count, max_count, name_value_lookup_t::getPossibleValues()); + } + } + + void set(value_assignment_t val, bool flag_as_provided = true) + { + mValues = val; + setProvided(flag_as_provided); + } + + param_value_t& add() + { + mValues.push_back(param_value_t(value_t())); + Param::setProvided(); + return mValues.back(); + } + + void add(const value_t& item) + { + param_value_t param_value; + param_value.setValue(item); + mValues.push_back(param_value); + setProvided(); + } + + void add(const typename name_value_lookup_t::name_t& name) + { + value_t value; + + // try to parse a per type named value + if (name_value_lookup_t::getValueFromName(name, value)) + { + add(value); + mValues.back().setValueName(name); + } + } + + // implicit conversion + operator value_assignment_t() const { return mValues; } + // explicit conversion + value_assignment_t operator()() const { return mValues; } + + typedef typename container_t::iterator iterator; + typedef typename container_t::const_iterator const_iterator; + iterator begin() { return mValues.begin(); } + iterator end() { return mValues.end(); } + const_iterator begin() const { return mValues.begin(); } + const_iterator end() const { return mValues.end(); } + bool empty() const { return mValues.empty(); } + size_t size() const { return mValues.size(); } + + U32 numValidElements() const + { + return mValues.size(); + } + + protected: + static bool mergeWith(Param& dst, const Param& src, bool overwrite) + { + const self_t& src_typed_param = static_cast(src); + self_t& dst_typed_param = static_cast(dst); + + if (overwrite) + { + std::copy(src_typed_param.begin(), src_typed_param.end(), std::back_inserter(dst_typed_param.mValues)); + } + else + { + container_t new_values(src_typed_param.mValues); + std::copy(dst_typed_param.begin(), dst_typed_param.end(), std::back_inserter(new_values)); + std::swap(dst_typed_param.mValues, new_values); + } + + if (src_typed_param.begin() != src_typed_param.end()) + { + dst_typed_param.setProvided(); + } + return true; + } + + container_t mValues; + }; + + // container of block parameters + template + class TypedParam + : public Param + { + public: + typedef TypedParam self_t; + typedef ParamValue param_value_t; + typedef typename std::vector container_t; + typedef const container_t& value_assignment_t; + typedef typename param_value_t::value_t value_t; + typedef NAME_VALUE_LOOKUP name_value_lookup_t; + + TypedParam(BlockDescriptor& block_descriptor, const char* name, value_assignment_t value, ParamDescriptor::validation_func_t validate_func, S32 min_count, S32 max_count) + : Param(block_descriptor.mCurrentBlockPtr) + { + std::copy(value.begin(), value.end(), back_inserter(mValues)); + + if (LL_UNLIKELY(block_descriptor.mInitializationState == BlockDescriptor::INITIALIZING)) + { + ParamDescriptorPtr param_descriptor = ParamDescriptorPtr(new ParamDescriptor( + block_descriptor.mCurrentBlockPtr->getHandleFromParam(this), + &mergeWith, + &deserializeParam, + &serializeParam, + validate_func, + &inspectParam, + min_count, max_count)); + BaseBlock::addParam(block_descriptor, param_descriptor, name); + } + } + + bool isProvided() const { return Param::anyProvided(); } + + static bool deserializeParam(Param& param, Parser& parser, const Parser::name_stack_range_t& name_stack_range, bool new_name) + { + self_t& typed_param = static_cast(param); + bool new_value = false; + + if (new_name || typed_param.mValues.empty()) + { + new_value = true; + typed_param.mValues.push_back(value_t()); + } + + param_value_t& value = typed_param.mValues.back(); + + // attempt to parse block... + if(value.deserializeBlock(parser, name_stack_range, new_name)) + { + typed_param.setProvided(); + return true; + } + else if(name_value_lookup_t::valueNamesExist()) + { + // try to parse a known named value + std::string name; + if (parser.readValue(name)) + { + // try to parse a per type named value + if (name_value_lookup_t::getValueFromName(name, value.getValue())) + { + typed_param.mValues.back().setValueName(name); + typed_param.setProvided(); + return true; + } + + } + } + + if (new_value) + { // failed to parse new value, pop it off + typed_param.mValues.pop_back(); + } + + return false; + } + + static void serializeParam(const Param& param, Parser& parser, Parser::name_stack_t& name_stack, const Param* diff_param) + { + const self_t& typed_param = static_cast(param); + if (!typed_param.isProvided() || name_stack.empty()) return; + + for (const_iterator it = typed_param.mValues.begin(), end_it = typed_param.mValues.end(); + it != end_it; + ++it) + { + name_stack.back().second = true; + + std::string key = it->getValueName(); + if (!key.empty()) + { + parser.writeValue(key, name_stack); + } + // Not parsed via named values, write out value directly + // NOTE: currently we don't worry about removing default values in Multiple + else + { + it->serializeBlock(parser, name_stack, NULL); + } + } + } + + static void inspectParam(const Param& param, Parser& parser, Parser::name_stack_t& name_stack, S32 min_count, S32 max_count) + { + // I am a vector of blocks, so describe my contents recursively + param_value_t(value_t()).inspectBlock(parser, name_stack, min_count, max_count); + } + + void set(value_assignment_t val, bool flag_as_provided = true) + { + mValues = val; + setProvided(flag_as_provided); + } + + param_value_t& add() + { + mValues.push_back(value_t()); + setProvided(); + return mValues.back(); + } + + void add(const value_t& item) + { + mValues.push_back(item); + setProvided(); + } + + void add(const typename name_value_lookup_t::name_t& name) + { + value_t value; + + // try to parse a per type named value + if (name_value_lookup_t::getValueFromName(name, value)) + { + add(value); + mValues.back().setValueName(name); + } + } + + // implicit conversion + operator value_assignment_t() const { return mValues; } + // explicit conversion + value_assignment_t operator()() const { return mValues; } + + typedef typename container_t::iterator iterator; + typedef typename container_t::const_iterator const_iterator; + iterator begin() { return mValues.begin(); } + iterator end() { return mValues.end(); } + const_iterator begin() const { return mValues.begin(); } + const_iterator end() const { return mValues.end(); } + bool empty() const { return mValues.empty(); } + size_t size() const { return mValues.size(); } + + U32 numValidElements() const + { + U32 count = 0; + for (const_iterator it = mValues.begin(), end_it = mValues.end(); + it != end_it; + ++it) + { + if(it->validateBlock(false)) count++; + } + return count; + } + + protected: + + static bool mergeWith(Param& dst, const Param& src, bool overwrite) + { + const self_t& src_typed_param = static_cast(src); + self_t& dst_typed_param = static_cast(dst); + + if (overwrite) + { + std::copy(src_typed_param.begin(), src_typed_param.end(), std::back_inserter(dst_typed_param.mValues)); + } + else + { + container_t new_values(src_typed_param.mValues); + std::copy(dst_typed_param.begin(), dst_typed_param.end(), std::back_inserter(new_values)); + std::swap(dst_typed_param.mValues, new_values); + } + + if (src_typed_param.begin() != src_typed_param.end()) + { + dst_typed_param.setProvided(); + } + + return true; + } + + container_t mValues; + }; + + template + class ChoiceBlock : public BASE_BLOCK + { + typedef ChoiceBlock self_t; + typedef ChoiceBlock enclosing_block_t; + typedef BASE_BLOCK base_block_t; + + LOG_CLASS(self_t); + public: + // take all provided params from other and apply to self + bool overwriteFrom(const self_t& other) + { + return static_cast(this)->mergeBlock(selfBlockDescriptor(), other, true); + } + + // take all provided params that are not already provided, and apply to self + bool fillFrom(const self_t& other) + { + return static_cast(this)->mergeBlock(selfBlockDescriptor(), other, false); + } + + bool mergeBlockParam(bool source_provided, bool dest_provided, BlockDescriptor& block_data, const self_t& source, bool overwrite) + { + bool source_override = source_provided && (overwrite || !dest_provided); + + if (source_override || source.mCurChoice == mCurChoice) + { + return mergeBlock(block_data, source, overwrite); + } + return false; + } + + // merge with other block + bool mergeBlock(BlockDescriptor& block_data, const self_t& other, bool overwrite) + { + mCurChoice = other.mCurChoice; + return base_block_t::mergeBlock(selfBlockDescriptor(), other, overwrite); + } + + // clear out old choice when param has changed + /*virtual*/ void paramChanged(const Param& changed_param, bool user_provided) + { + param_handle_t changed_param_handle = base_block_t::getHandleFromParam(&changed_param); + // if we have a new choice... + if (changed_param_handle != mCurChoice) + { + // clear provided flag on previous choice + Param* previous_choice = base_block_t::getParamFromHandle(mCurChoice); + if (previous_choice) + { + previous_choice->setProvided(false); + } + mCurChoice = changed_param_handle; + } + base_block_t::paramChanged(changed_param, user_provided); + } + + virtual const BlockDescriptor& mostDerivedBlockDescriptor() const { return selfBlockDescriptor(); } + virtual BlockDescriptor& mostDerivedBlockDescriptor() { return selfBlockDescriptor(); } + + protected: + ChoiceBlock() + : mCurChoice(0) + { + BaseBlock::init(selfBlockDescriptor(), base_block_t::selfBlockDescriptor(), sizeof(DERIVED_BLOCK)); + } + + // Alternatives are mutually exclusive wrt other Alternatives in the same block. + // One alternative in a block will always have isChosen() == true. + // At most one alternative in a block will have isProvided() == true. + template > + class Alternative : public TypedParam + { + public: + friend class ChoiceBlock; + + typedef Alternative self_t; + typedef TypedParam >::value> super_t; + typedef typename super_t::value_assignment_t value_assignment_t; + + using super_t::operator =; + + explicit Alternative(const char* name = "", value_assignment_t val = defaultValue()) + : super_t(DERIVED_BLOCK::selfBlockDescriptor(), name, val, NULL, 0, 1), + mOriginalValue(val) + { + // assign initial choice to first declared option + DERIVED_BLOCK* blockp = ((DERIVED_BLOCK*)DERIVED_BLOCK::selfBlockDescriptor().mCurrentBlockPtr); + if (LL_UNLIKELY(DERIVED_BLOCK::selfBlockDescriptor().mInitializationState == BlockDescriptor::INITIALIZING)) + { + if(blockp->mCurChoice == 0) + { + blockp->mCurChoice = Param::enclosingBlock().getHandleFromParam(this); + } + } + } + + void choose() + { + static_cast(Param::enclosingBlock()).paramChanged(*this, true); + } + + void chooseAs(value_assignment_t val) + { + super_t::set(val); + } + + void operator =(value_assignment_t val) + { + super_t::set(val); + } + + void operator()(typename super_t::value_assignment_t val) + { + super_t::set(val); + } + + operator value_assignment_t() const + { + return (*this)(); + } + + value_assignment_t operator()() const + { + if (static_cast(Param::enclosingBlock()).getCurrentChoice() == this) + { + return super_t::getValue(); + } + return mOriginalValue; + } + + bool isChosen() const + { + return static_cast(Param::enclosingBlock()).getCurrentChoice() == this; + } + + private: + T mOriginalValue; + }; + + protected: + static BlockDescriptor& selfBlockDescriptor() + { + static BlockDescriptor sBlockDescriptor; + return sBlockDescriptor; + } + + private: + param_handle_t mCurChoice; + + const Param* getCurrentChoice() const + { + return base_block_t::getParamFromHandle(mCurChoice); + } + }; + + template + class Block + : public BASE_BLOCK + { + typedef Block self_t; + typedef Block block_t; + + public: + typedef BASE_BLOCK base_block_t; + + // take all provided params from other and apply to self + bool overwriteFrom(const self_t& other) + { + return static_cast(this)->mergeBlock(selfBlockDescriptor(), other, true); + } + + // take all provided params that are not already provided, and apply to self + bool fillFrom(const self_t& other) + { + return static_cast(this)->mergeBlock(selfBlockDescriptor(), other, false); + } + + virtual const BlockDescriptor& mostDerivedBlockDescriptor() const { return selfBlockDescriptor(); } + virtual BlockDescriptor& mostDerivedBlockDescriptor() { return selfBlockDescriptor(); } + + protected: + Block() + { + //#pragma message("Parsing LLInitParam::Block") + BaseBlock::init(selfBlockDescriptor(), BASE_BLOCK::selfBlockDescriptor(), sizeof(DERIVED_BLOCK)); + } + + // + // Nested classes for declaring parameters + // + template > + class Optional : public TypedParam + { + public: + typedef TypedParam >::value> super_t; + typedef typename super_t::value_assignment_t value_assignment_t; + + using super_t::operator(); + using super_t::operator =; + + explicit Optional(const char* name = "", value_assignment_t val = defaultValue()) + : super_t(DERIVED_BLOCK::selfBlockDescriptor(), name, val, NULL, 0, 1) + { + //#pragma message("Parsing LLInitParam::Block::Optional") + } + + Optional& operator =(value_assignment_t val) + { + set(val); + return *this; + } + + DERIVED_BLOCK& operator()(value_assignment_t val) + { + super_t::set(val); + return static_cast(Param::enclosingBlock()); + } + }; + + template > + class Mandatory : public TypedParam + { + public: + typedef TypedParam >::value> super_t; + typedef Mandatory self_t; + typedef typename super_t::value_assignment_t value_assignment_t; + + using super_t::operator(); + using super_t::operator =; + + // mandatory parameters require a name to be parseable + explicit Mandatory(const char* name = "", value_assignment_t val = defaultValue()) + : super_t(DERIVED_BLOCK::selfBlockDescriptor(), name, val, &validate, 1, 1) + {} + + Mandatory& operator =(value_assignment_t val) + { + set(val); + return *this; + } + + DERIVED_BLOCK& operator()(typename super_t::value_assignment_t val) + { + super_t::set(val); + return static_cast(Param::enclosingBlock()); + } + + static bool validate(const Param* p) + { + // valid only if provided + return static_cast(p)->isProvided(); + } + + }; + + template > + class Multiple : public TypedParam + { + public: + typedef TypedParam >::value> super_t; + typedef Multiple self_t; + typedef typename super_t::container_t container_t; + typedef typename super_t::value_assignment_t value_assignment_t; + typedef typename super_t::iterator iterator; + typedef typename super_t::const_iterator const_iterator; + + explicit Multiple(const char* name = "") + : super_t(DERIVED_BLOCK::selfBlockDescriptor(), name, container_t(), &validate, RANGE::minCount, RANGE::maxCount) + {} + + Multiple& operator =(value_assignment_t val) + { + set(val); + return *this; + } + + DERIVED_BLOCK& operator()(typename super_t::value_assignment_t val) + { + super_t::set(val); + return static_cast(Param::enclosingBlock()); + } + + static bool validate(const Param* paramp) + { + U32 num_valid = ((super_t*)paramp)->numValidElements(); + return RANGE::minCount <= num_valid && num_valid <= RANGE::maxCount; + } + }; + + class Deprecated : public Param + { + public: + explicit Deprecated(const char* name) + : Param(DERIVED_BLOCK::selfBlockDescriptor().mCurrentBlockPtr) + { + BlockDescriptor& block_descriptor = DERIVED_BLOCK::selfBlockDescriptor(); + if (LL_UNLIKELY(block_descriptor.mInitializationState == BlockDescriptor::INITIALIZING)) + { + ParamDescriptorPtr param_descriptor = ParamDescriptorPtr(new ParamDescriptor( + block_descriptor.mCurrentBlockPtr->getHandleFromParam(this), + NULL, + &deserializeParam, + NULL, + NULL, + NULL, + 0, S32_MAX)); + BaseBlock::addParam(block_descriptor, param_descriptor, name); + } + } + + static bool deserializeParam(Param& param, Parser& parser, const Parser::name_stack_range_t& name_stack_range, bool new_name) + { + if (name_stack_range.first == name_stack_range.second) + { + //std::string message = llformat("Deprecated value %s ignored", getName().c_str()); + //parser.parserWarning(message); + return true; + } + + return false; + } + }; + + // different semantics for documentation purposes, but functionally identical + typedef Deprecated Ignored; + + protected: + static BlockDescriptor& selfBlockDescriptor() + { + static BlockDescriptor sBlockDescriptor; + return sBlockDescriptor; + } + + template + void changeDefault(TypedParam& param, + typename TypedParam::value_assignment_t value) + { + if (!param.isProvided()) + { + param.set(value, false); + } + } + + }; + + template + class BatchBlock + : public Block + { + public: + typedef BatchBlock self_t; + typedef Block super_t; + + BatchBlock() + {} + + bool deserializeBlock(Parser& p, Parser::name_stack_range_t name_stack_range, bool new_name) + { + if (new_name) + { + // reset block + *static_cast(this) = defaultBatchValue(); + } + return super_t::deserializeBlock(p, name_stack_range, new_name); + } + + bool mergeBlock(BlockDescriptor& block_data, const BaseBlock& other, bool overwrite) + { + if (overwrite) + { + *static_cast(this) = defaultBatchValue(); + // merge individual parameters into destination + return super_t::mergeBlock(super_t::selfBlockDescriptor(), other, overwrite); + } + return false; + } + protected: + static const DERIVED_BLOCK& defaultBatchValue() + { + static DERIVED_BLOCK default_value; + return default_value; + } + }; + + // FIXME: this specialization is not currently used, as it only matches against the BatchBlock base class + // and not the derived class with the actual params + template + class ParamValue , + NAME_VALUE_LOOKUP, + true> + : public NAME_VALUE_LOOKUP, + protected BatchBlock + { + public: + typedef BatchBlock block_t; + typedef const BatchBlock& value_assignment_t; + typedef block_t value_t; + + ParamValue() + : block_t(), + mValidated(false) + {} + + ParamValue(value_assignment_t other) + : block_t(other), + mValidated(false) + { + } + + void setValue(value_assignment_t val) + { + *this = val; + } + + value_assignment_t getValue() const + { + return *this; + } + + BatchBlock& getValue() + { + return *this; + } + + operator value_assignment_t() const + { + return *this; + } + + value_assignment_t operator()() const + { + return *this; + } + + protected: + mutable bool mValidated; // lazy validation flag + }; + + template + class ParamValue , + TypeValues, + IS_BLOCK> + : public IsBlock::base_class_t + { + public: + typedef ParamValue , TypeValues, false> self_t; + typedef const T& value_assignment_t; + typedef T value_t; + + ParamValue() + : mValue(), + mValidated(false) + {} + + ParamValue(value_assignment_t other) + : mValue(other), + mValidated(false) + {} + + void setValue(value_assignment_t val) + { + mValue.set(val); + } + + value_assignment_t getValue() const + { + return mValue.get(); + } + + T& getValue() + { + return mValue.get(); + } + + operator value_assignment_t() const + { + return mValue.get(); + } + + value_assignment_t operator()() const + { + return mValue.get(); + } + + bool deserializeBlock(Parser& p, Parser::name_stack_range_t name_stack_range, bool new_name) + { + return mValue.get().deserializeBlock(p, name_stack_range, new_name); + } + + void serializeBlock(Parser& p, Parser::name_stack_t& name_stack, const BaseBlock* diff_block = NULL) const + { + if (mValue.empty()) return; + + mValue.get().serializeBlock(p, name_stack, diff_block); + } + + bool inspectBlock(Parser& p, Parser::name_stack_t name_stack = Parser::name_stack_t(), S32 min_count = 0, S32 max_count = S32_MAX) const + { + if (mValue.empty()) return false; + + return mValue.get().inspectBlock(p, name_stack, min_count, max_count); + } + + protected: + mutable bool mValidated; // lazy validation flag + + private: + BaseBlock::Lazy mValue; + }; + + template <> + class ParamValue , + false> + : public TypeValues, + public BaseBlock + { + public: + typedef ParamValue, false> self_t; + typedef const LLSD& value_assignment_t; + + ParamValue() + : mValidated(false) + {} + + ParamValue(value_assignment_t other) + : mValue(other), + mValidated(false) + {} + + void setValue(value_assignment_t val) { mValue = val; } + + value_assignment_t getValue() const { return mValue; } + LLSD& getValue() { return mValue; } + + operator value_assignment_t() const { return mValue; } + value_assignment_t operator()() const { return mValue; } + + + // block param interface + bool deserializeBlock(Parser& p, Parser::name_stack_range_t name_stack_range, bool new_name); + void serializeBlock(Parser& p, Parser::name_stack_t& name_stack, const BaseBlock* diff_block = NULL) const; + bool inspectBlock(Parser& p, Parser::name_stack_t name_stack = Parser::name_stack_t(), S32 min_count = 0, S32 max_count = S32_MAX) const + { + //TODO: implement LLSD params as schema type Any + return true; + } + + protected: + mutable bool mValidated; // lazy validation flag + + private: + static void serializeElement(Parser& p, const LLSD& sd, Parser::name_stack_t& name_stack); + + LLSD mValue; + }; + + template + class CustomParamValue + : public Block > >, + public TypeValues + { + public: + typedef enum e_value_age + { + VALUE_NEEDS_UPDATE, // mValue needs to be refreshed from the block parameters + VALUE_AUTHORITATIVE, // mValue holds the authoritative value (which has been replicated to the block parameters via updateBlockFromValue) + BLOCK_AUTHORITATIVE // mValue is derived from the block parameters, which are authoritative + } EValueAge; + + typedef ParamValue > derived_t; + typedef CustomParamValue self_t; + typedef Block block_t; + typedef const T& value_assignment_t; + typedef T value_t; + + + CustomParamValue(const T& value = T()) + : mValue(value), + mValueAge(VALUE_AUTHORITATIVE), + mValidated(false) + {} + + bool deserializeBlock(Parser& parser, Parser::name_stack_range_t name_stack_range, bool new_name) + { + derived_t& typed_param = static_cast(*this); + // try to parse direct value T + if (name_stack_range.first == name_stack_range.second) + { + if(parser.readValue(typed_param.mValue)) + { + typed_param.mValueAge = VALUE_AUTHORITATIVE; + typed_param.updateBlockFromValue(false); + + typed_param.clearValueName(); + + return true; + } + } + + // fall back on parsing block components for T + return typed_param.BaseBlock::deserializeBlock(parser, name_stack_range, new_name); + } + + void serializeBlock(Parser& parser, Parser::name_stack_t& name_stack, const BaseBlock* diff_block = NULL) const + { + const derived_t& typed_param = static_cast(*this); + const derived_t* diff_param = static_cast(diff_block); + + std::string key = typed_param.getValueName(); + + // first try to write out name of name/value pair + if (!key.empty()) + { + if (!diff_param || !ParamCompare::equals(diff_param->getValueName(), key)) + { + parser.writeValue(key, name_stack); + } + } + // then try to serialize value directly + else if (!diff_param || !ParamCompare::equals(typed_param.getValue(), diff_param->getValue())) + { + + if (!parser.writeValue(typed_param.getValue(), name_stack)) + { + //RN: *always* serialize provided components of BlockValue (don't pass diff_param on), + // since these tend to be viewed as the constructor arguments for the value T. It seems + // cleaner to treat the uniqueness of a BlockValue according to the generated value, and + // not the individual components. This way will not + // be exported as , since it was probably the intent of the user to + // be specific about the RGB color values. This also fixes an issue where we distinguish + // between rect.left not being provided and rect.left being explicitly set to 0 (same as default) + + if (typed_param.mValueAge == VALUE_AUTHORITATIVE) + { + // if the value is authoritative but the parser doesn't accept the value type + // go ahead and make a copy, and splat the value out to its component params + // and serialize those params + derived_t copy(typed_param); + copy.updateBlockFromValue(true); + copy.block_t::serializeBlock(parser, name_stack, NULL); + } + else + { + block_t::serializeBlock(parser, name_stack, NULL); + } + } + } + } + + bool inspectBlock(Parser& parser, Parser::name_stack_t name_stack = Parser::name_stack_t(), S32 min_count = 0, S32 max_count = S32_MAX) const + { + // first, inspect with actual type... + parser.inspectValue(name_stack, min_count, max_count, NULL); + if (TypeValues::getPossibleValues()) + { + //...then inspect with possible string values... + parser.inspectValue(name_stack, min_count, max_count, TypeValues::getPossibleValues()); + } + // then recursively inspect contents... + return block_t::inspectBlock(parser, name_stack, min_count, max_count); + } + + bool validateBlock(bool emit_errors = true) const + { + if (mValueAge == VALUE_NEEDS_UPDATE) + { + if (block_t::validateBlock(emit_errors)) + { + // clear stale keyword associated with old value + TypeValues::clearValueName(); + mValueAge = BLOCK_AUTHORITATIVE; + static_cast(const_cast(this))->updateValueFromBlock(); + return true; + } + else + { + //block value incomplete, so not considered provided + // will attempt to revalidate on next call to isProvided() + return false; + } + } + else + { + // we have a valid value in hand + return true; + } + } + + // propagate change status up to enclosing block + /*virtual*/ void paramChanged(const Param& changed_param, bool user_provided) + { + BaseBlock::paramChanged(changed_param, user_provided); + if (user_provided) + { + // a parameter changed, so our value is out of date + mValueAge = VALUE_NEEDS_UPDATE; + } + } + + void setValue(value_assignment_t val) + { + derived_t& typed_param = static_cast(*this); + // set param version number to be up to date, so we ignore block contents + mValueAge = VALUE_AUTHORITATIVE; + mValue = val; + typed_param.clearValueName(); + static_cast(this)->updateBlockFromValue(false); + } + + value_assignment_t getValue() const + { + validateBlock(true); + return mValue; + } + + T& getValue() + { + validateBlock(true); + return mValue; + } + + operator value_assignment_t() const + { + return getValue(); + } + + value_assignment_t operator()() const + { + return getValue(); + } + + protected: + + // use this from within updateValueFromBlock() to set the value without making it authoritative + void updateValue(value_assignment_t value) + { + mValue = value; + } + + bool mergeBlockParam(bool source_provided, bool dst_provided, BlockDescriptor& block_data, const BaseBlock& source, bool overwrite) + { + bool source_override = source_provided && (overwrite || !dst_provided); + + const derived_t& src_typed_param = static_cast(source); + + if (source_override && src_typed_param.mValueAge == VALUE_AUTHORITATIVE) + { + // copy value over + setValue(src_typed_param.getValue()); + return true; + } + // merge individual parameters into destination + if (mValueAge == VALUE_AUTHORITATIVE) + { + static_cast(this)->updateBlockFromValue(dst_provided); + } + return mergeBlock(block_data, source, overwrite); + } + + bool mergeBlock(BlockDescriptor& block_data, const BaseBlock& source, bool overwrite) + { + return block_t::mergeBlock(block_data, source, overwrite); + } + + mutable bool mValidated; // lazy validation flag + + private: + mutable T mValue; + mutable EValueAge mValueAge; + }; +} + + +#endif // LL_LLPARAM_H diff --git a/indra/llcommon/llregistry.h b/indra/llcommon/llregistry.h new file mode 100644 index 0000000000..36ce6a97b7 --- /dev/null +++ b/indra/llcommon/llregistry.h @@ -0,0 +1,351 @@ +/** + * @file llregistry.h + * @brief template classes for registering name, value pairs in nested scopes, statically, etc. + * + * $LicenseInfo:firstyear=2001&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#ifndef LL_LLREGISTRY_H +#define LL_LLREGISTRY_H + +#include + +#include +#include "llsingleton.h" + +template +class LLRegistryDefaultComparator +{ + bool operator()(const T& lhs, const T& rhs) { return lhs < rhs; } +}; + +template > +class LLRegistry +{ +public: + typedef LLRegistry registry_t; + typedef typename boost::add_reference::type>::type ref_const_key_t; + typedef typename boost::add_reference::type>::type ref_const_value_t; + typedef typename boost::add_reference::type ref_value_t; + typedef typename boost::add_pointer::type>::type ptr_const_value_t; + typedef typename boost::add_pointer::type ptr_value_t; + + class Registrar + { + friend class LLRegistry; + public: + typedef typename std::map registry_map_t; + + bool add(ref_const_key_t key, ref_const_value_t value) + { + if (mMap.insert(std::make_pair(key, value)).second == false) + { + llwarns << "Tried to register " << key << " but it was already registered!" << llendl; + return false; + } + return true; + } + + void remove(ref_const_key_t key) + { + mMap.erase(key); + } + + void replace(ref_const_key_t key, ref_const_value_t value) + { + mMap[key] = value; + } + + typename registry_map_t::const_iterator beginItems() const + { + return mMap.begin(); + } + + typename registry_map_t::const_iterator endItems() const + { + return mMap.end(); + } + + protected: + ptr_value_t getValue(ref_const_key_t key) + { + typename registry_map_t::iterator found_it = mMap.find(key); + if (found_it != mMap.end()) + { + return &(found_it->second); + } + return NULL; + } + + ptr_const_value_t getValue(ref_const_key_t key) const + { + typename registry_map_t::const_iterator found_it = mMap.find(key); + if (found_it != mMap.end()) + { + return &(found_it->second); + } + return NULL; + } + + // if the registry is used to store pointers, and null values are valid entries + // then use this function to check the existence of an entry + bool exists(ref_const_key_t key) const + { + return mMap.find(key) != mMap.end(); + } + + bool empty() const + { + return mMap.empty(); + } + + protected: + // use currentRegistrar() or defaultRegistrar() + Registrar() {} + ~Registrar() {} + + private: + registry_map_t mMap; + }; + + typedef typename std::list scope_list_t; + typedef typename std::list::iterator scope_list_iterator_t; + typedef typename std::list::const_iterator scope_list_const_iterator_t; + + LLRegistry() + {} + + ~LLRegistry() {} + + ptr_value_t getValue(ref_const_key_t key) + { + for(scope_list_iterator_t it = mActiveScopes.begin(); + it != mActiveScopes.end(); + ++it) + { + ptr_value_t valuep = (*it)->getValue(key); + if (valuep != NULL) return valuep; + } + return mDefaultRegistrar.getValue(key); + } + + ptr_const_value_t getValue(ref_const_key_t key) const + { + for(scope_list_const_iterator_t it = mActiveScopes.begin(); + it != mActiveScopes.end(); + ++it) + { + ptr_value_t valuep = (*it)->getValue(key); + if (valuep != NULL) return valuep; + } + return mDefaultRegistrar.getValue(key); + } + + bool exists(ref_const_key_t key) const + { + for(scope_list_const_iterator_t it = mActiveScopes.begin(); + it != mActiveScopes.end(); + ++it) + { + if ((*it)->exists(key)) return true; + } + + return mDefaultRegistrar.exists(key); + } + + bool empty() const + { + for(scope_list_const_iterator_t it = mActiveScopes.begin(); + it != mActiveScopes.end(); + ++it) + { + if (!(*it)->empty()) return false; + } + + return mDefaultRegistrar.empty(); + } + + + Registrar& defaultRegistrar() + { + return mDefaultRegistrar; + } + + const Registrar& defaultRegistrar() const + { + return mDefaultRegistrar; + } + + + Registrar& currentRegistrar() + { + if (!mActiveScopes.empty()) + { + return *mActiveScopes.front(); + } + + return mDefaultRegistrar; + } + + const Registrar& currentRegistrar() const + { + if (!mActiveScopes.empty()) + { + return *mActiveScopes.front(); + } + + return mDefaultRegistrar; + } + + +protected: + void addScope(Registrar* scope) + { + // newer scopes go up front + mActiveScopes.insert(mActiveScopes.begin(), scope); + } + + void removeScope(Registrar* scope) + { + // O(N) but should be near the beggining and N should be small and this is safer than storing iterators + scope_list_iterator_t iter = std::find(mActiveScopes.begin(), mActiveScopes.end(), scope); + if (iter != mActiveScopes.end()) + { + mActiveScopes.erase(iter); + } + } + +private: + scope_list_t mActiveScopes; + Registrar mDefaultRegistrar; +}; + +template > +class LLRegistrySingleton + : public LLRegistry, + public LLSingleton +{ + friend class LLSingleton; +public: + typedef LLRegistry registry_t; + typedef const KEY& ref_const_key_t; + typedef const VALUE& ref_const_value_t; + typedef VALUE* ptr_value_t; + typedef const VALUE* ptr_const_value_t; + typedef LLSingleton singleton_t; + + class ScopedRegistrar : public registry_t::Registrar + { + public: + ScopedRegistrar(bool push_scope = true) + { + if (push_scope) + { + pushScope(); + } + } + + ~ScopedRegistrar() + { + if (!singleton_t::destroyed()) + { + popScope(); + } + } + + void pushScope() + { + singleton_t::instance().addScope(this); + } + + void popScope() + { + singleton_t::instance().removeScope(this); + } + + ptr_value_t getValueFromScope(ref_const_key_t key) + { + return getValue(key); + } + + ptr_const_value_t getValueFromScope(ref_const_key_t key) const + { + return getValue(key); + } + + private: + typename std::list::iterator mListIt; + }; + + class StaticRegistrar : public registry_t::Registrar + { + public: + virtual ~StaticRegistrar() {} + StaticRegistrar(ref_const_key_t key, ref_const_value_t value) + { + singleton_t::instance().mStaticScope->add(key, value); + } + }; + + // convenience functions + typedef typename LLRegistry::Registrar& ref_registrar_t; + static ref_registrar_t currentRegistrar() + { + return singleton_t::instance().registry_t::currentRegistrar(); + } + + static ref_registrar_t defaultRegistrar() + { + return singleton_t::instance().registry_t::defaultRegistrar(); + } + + static ptr_value_t getValue(ref_const_key_t key) + { + return singleton_t::instance().registry_t::getValue(key); + } + +protected: + // DERIVED_TYPE needs to derive from LLRegistrySingleton + LLRegistrySingleton() + : mStaticScope(NULL) + {} + + virtual void initSingleton() + { + mStaticScope = new ScopedRegistrar(); + } + + virtual ~LLRegistrySingleton() + { + delete mStaticScope; + } + +private: + ScopedRegistrar* mStaticScope; +}; + +// helper macro for doing static registration +#define GLUED_TOKEN(x, y) x ## y +#define GLUE_TOKENS(x, y) GLUED_TOKEN(x, y) +#define LLREGISTER_STATIC(REGISTRY, KEY, VALUE) static REGISTRY::StaticRegistrar GLUE_TOKENS(reg, __LINE__)(KEY, VALUE); + +#endif diff --git a/indra/llui/CMakeLists.txt b/indra/llui/CMakeLists.txt index 772f173f17..9226f36e73 100644 --- a/indra/llui/CMakeLists.txt +++ b/indra/llui/CMakeLists.txt @@ -12,7 +12,6 @@ include(LLRender) include(LLWindow) include(LLVFS) include(LLXML) -include(LLXUIXML) include_directories( ${LLCOMMON_INCLUDE_DIRS} @@ -24,7 +23,6 @@ include_directories( ${LLWINDOW_INCLUDE_DIRS} ${LLVFS_INCLUDE_DIRS} ${LLXML_INCLUDE_DIRS} - ${LLXUIXML_INCLUDE_DIRS} ) set(llui_SOURCE_FILES @@ -100,11 +98,13 @@ set(llui_SOURCE_FILES lltextutil.cpp lltextvalidate.cpp lltimectrl.cpp + lltrans.cpp lltransutil.cpp lltoggleablemenu.cpp lltoolbar.cpp lltooltip.cpp llui.cpp + lluicolor.cpp lluicolortable.cpp lluictrl.cpp lluictrlfactory.cpp @@ -121,6 +121,7 @@ set(llui_SOURCE_FILES llview.cpp llviewquery.cpp llwindowshade.cpp + llxuiparser.cpp ) set(llui_HEADER_FILES @@ -208,6 +209,7 @@ set(llui_HEADER_FILES lltoggleablemenu.h lltoolbar.h lltooltip.h + lltrans.h lltransutil.h lluicolortable.h lluiconstants.h @@ -215,6 +217,7 @@ set(llui_HEADER_FILES lluictrl.h lluifwd.h llui.h + lluicolor.h lluiimage.h lluistring.h llundo.h @@ -228,6 +231,7 @@ set(llui_HEADER_FILES llview.h llviewquery.h llwindowshade.h + llxuiparser.h ) set_source_files_properties(${llui_HEADER_FILES} diff --git a/indra/llui/lltrans.cpp b/indra/llui/lltrans.cpp new file mode 100644 index 0000000000..5388069c24 --- /dev/null +++ b/indra/llui/lltrans.cpp @@ -0,0 +1,295 @@ +/** + * @file lltrans.cpp + * @brief LLTrans implementation + * + * $LicenseInfo:firstyear=2000&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include "linden_common.h" + +#include "lltrans.h" + +#include "llfasttimer.h" // for call count statistics +#include "llxuiparser.h" +#include "llsd.h" +#include "llxmlnode.h" + +#include + +LLTrans::template_map_t LLTrans::sStringTemplates; +LLStringUtil::format_map_t LLTrans::sDefaultArgs; + +struct StringDef : public LLInitParam::Block +{ + Mandatory name; + Mandatory value; + + StringDef() + : name("name"), + value("value") + {} +}; + +struct StringTable : public LLInitParam::Block +{ + Multiple strings; + StringTable() + : strings("string") + {} +}; + +//static +bool LLTrans::parseStrings(LLXMLNodePtr &root, const std::set& default_args) +{ + std::string xml_filename = "(strings file)"; + if (!root->hasName("strings")) + { + llerrs << "Invalid root node name in " << xml_filename + << ": was " << root->getName() << ", expected \"strings\"" << llendl; + } + + StringTable string_table; + LLXUIParser parser; + parser.readXUI(root, string_table, xml_filename); + + if (!string_table.validateBlock()) + { + llerrs << "Problem reading strings: " << xml_filename << llendl; + return false; + } + + sStringTemplates.clear(); + sDefaultArgs.clear(); + + for(LLInitParam::ParamIterator::const_iterator it = string_table.strings.begin(); + it != string_table.strings.end(); + ++it) + { + LLTransTemplate xml_template(it->name, it->value); + sStringTemplates[xml_template.mName] = xml_template; + + std::set::const_iterator iter = default_args.find(xml_template.mName); + if (iter != default_args.end()) + { + std::string name = *iter; + if (name[0] != '[') + name = llformat("[%s]",name.c_str()); + sDefaultArgs[name] = xml_template.mText; + } + } + + return true; +} + + +//static +bool LLTrans::parseLanguageStrings(LLXMLNodePtr &root) +{ + std::string xml_filename = "(language strings file)"; + if (!root->hasName("strings")) + { + llerrs << "Invalid root node name in " << xml_filename + << ": was " << root->getName() << ", expected \"strings\"" << llendl; + } + + StringTable string_table; + LLXUIParser parser; + parser.readXUI(root, string_table, xml_filename); + + if (!string_table.validateBlock()) + { + llerrs << "Problem reading strings: " << xml_filename << llendl; + return false; + } + + for(LLInitParam::ParamIterator::const_iterator it = string_table.strings.begin(); + it != string_table.strings.end(); + ++it) + { + // share the same map with parseStrings() so we can search the strings using the same getString() function.- angela + LLTransTemplate xml_template(it->name, it->value); + sStringTemplates[xml_template.mName] = xml_template; + } + + return true; +} + + + +static LLFastTimer::DeclareTimer FTM_GET_TRANS("Translate string"); + +//static +std::string LLTrans::getString(const std::string &xml_desc, const LLStringUtil::format_map_t& msg_args) +{ + // Don't care about time as much as call count. Make sure we're not + // calling LLTrans::getString() in an inner loop. JC + LLFastTimer timer(FTM_GET_TRANS); + + template_map_t::iterator iter = sStringTemplates.find(xml_desc); + if (iter != sStringTemplates.end()) + { + std::string text = iter->second.mText; + LLStringUtil::format_map_t args = sDefaultArgs; + args.insert(msg_args.begin(), msg_args.end()); + LLStringUtil::format(text, args); + + return text; + } + else + { + LL_WARNS_ONCE("configuration") << "Missing String in strings.xml: [" << xml_desc << "]" << LL_ENDL; + return "MissingString("+xml_desc+")"; + } +} + +//static +std::string LLTrans::getString(const std::string &xml_desc, const LLSD& msg_args) +{ + // Don't care about time as much as call count. Make sure we're not + // calling LLTrans::getString() in an inner loop. JC + LLFastTimer timer(FTM_GET_TRANS); + + template_map_t::iterator iter = sStringTemplates.find(xml_desc); + if (iter != sStringTemplates.end()) + { + std::string text = iter->second.mText; + LLStringUtil::format(text, msg_args); + return text; + } + else + { + LL_WARNS_ONCE("configuration") << "Missing String in strings.xml: [" << xml_desc << "]" << LL_ENDL; + return "MissingString("+xml_desc+")"; + } +} + +//static +bool LLTrans::findString(std::string &result, const std::string &xml_desc, const LLStringUtil::format_map_t& msg_args) +{ + LLFastTimer timer(FTM_GET_TRANS); + + template_map_t::iterator iter = sStringTemplates.find(xml_desc); + if (iter != sStringTemplates.end()) + { + std::string text = iter->second.mText; + LLStringUtil::format_map_t args = sDefaultArgs; + args.insert(msg_args.begin(), msg_args.end()); + LLStringUtil::format(text, args); + result = text; + return true; + } + else + { + LL_WARNS_ONCE("configuration") << "Missing String in strings.xml: [" << xml_desc << "]" << LL_ENDL; + return false; + } +} + +//static +bool LLTrans::findString(std::string &result, const std::string &xml_desc, const LLSD& msg_args) +{ + LLFastTimer timer(FTM_GET_TRANS); + + template_map_t::iterator iter = sStringTemplates.find(xml_desc); + if (iter != sStringTemplates.end()) + { + std::string text = iter->second.mText; + LLStringUtil::format(text, msg_args); + result = text; + return true; + } + else + { + LL_WARNS_ONCE("configuration") << "Missing String in strings.xml: [" << xml_desc << "]" << LL_ENDL; + return false; + } +} + +//static +std::string LLTrans::getCountString(const std::string& language, const std::string& xml_desc, S32 count) +{ + // Compute which string identifier to use + const char* form = ""; + if (language == "ru") // Russian + { + // From GNU ngettext() + // Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2; + if (count % 10 == 1 + && count % 100 != 11) + { + // singular, "1 item" + form = "A"; + } + else if (count % 10 >= 2 + && count % 10 <= 4 + && (count % 100 < 10 || count % 100 >= 20) ) + { + // special case "2 items", "23 items", but not "13 items" + form = "B"; + } + else + { + // English-style plural, "5 items" + form = "C"; + } + } + else if (language == "fr" || language == "pt") // French, Brazilian Portuguese + { + // French and Portuguese treat zero as a singular "0 item" not "0 items" + if (count == 0 || count == 1) + { + form = "A"; + } + else + { + // English-style plural + form = "B"; + } + } + else // default + { + // languages like English with 2 forms, singular and plural + if (count == 1) + { + // "1 item" + form = "A"; + } + else + { + // "2 items", also use plural for "0 items" + form = "B"; + } + } + + // Translate that string + LLStringUtil::format_map_t args; + args["[COUNT]"] = llformat("%d", count); + + // Look up "AgeYearsB" or "AgeWeeksC" including the "form" + std::string key = llformat("%s%s", xml_desc.c_str(), form); + return getString(key, args); +} + +void LLTrans::setDefaultArg(const std::string& name, const std::string& value) +{ + sDefaultArgs[name] = value; +} diff --git a/indra/llui/lltrans.h b/indra/llui/lltrans.h new file mode 100644 index 0000000000..128b51d383 --- /dev/null +++ b/indra/llui/lltrans.h @@ -0,0 +1,133 @@ +/** + * @file lltrans.h + * @brief LLTrans definition + * + * $LicenseInfo:firstyear=2000&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#ifndef LL_TRANS_H +#define LL_TRANS_H + +#include + +#include "llpointer.h" +#include "llstring.h" + +class LLXMLNode; + +class LLSD; + +/** + * @brief String template loaded from strings.xml + */ +class LLTransTemplate +{ +public: + LLTransTemplate(const std::string& name = LLStringUtil::null, const std::string& text = LLStringUtil::null) : mName(name), mText(text) {} + + std::string mName; + std::string mText; +}; + +/** + * @brief Localized strings class + * This class is used to retrieve translations of strings used to build larger ones, as well as + * strings with a general usage that don't belong to any specific floater. For example, + * "Owner:", "Retrieving..." used in the place of a not yet known name, etc. + */ +class LLTrans +{ +public: + LLTrans(); + + /** + * @brief Parses the xml root that holds the strings. Used once on startup +// *FIXME * @param xml_filename Filename to parse + * @param default_args Set of strings (expected to be in the file) to use as default replacement args, e.g. "SECOND_LIFE" + * @returns true if the file was parsed successfully, true if something went wrong + */ + static bool parseStrings(LLPointer & root, const std::set& default_args); + + static bool parseLanguageStrings(LLPointer & root); + + /** + * @brief Returns a translated string + * @param xml_desc String's description + * @param args A list of substrings to replace in the string + * @returns Translated string + */ + static std::string getString(const std::string &xml_desc, const LLStringUtil::format_map_t& args); + static std::string getString(const std::string &xml_desc, const LLSD& args); + static bool findString(std::string &result, const std::string &xml_desc, const LLStringUtil::format_map_t& args); + static bool findString(std::string &result, const std::string &xml_desc, const LLSD& args); + + // Returns translated string with [COUNT] replaced with a number, following + // special per-language logic for plural nouns. For example, some languages + // may have different plurals for 0, 1, 2 and > 2. + // See "AgeWeeksA", "AgeWeeksB", etc. in strings.xml for examples. + static std::string getCountString(const std::string& language, const std::string& xml_desc, S32 count); + + /** + * @brief Returns a translated string + * @param xml_desc String's description + * @returns Translated string + */ + static std::string getString(const std::string &xml_desc) + { + LLStringUtil::format_map_t empty; + return getString(xml_desc, empty); + } + + static bool findString(std::string &result, const std::string &xml_desc) + { + LLStringUtil::format_map_t empty; + return findString(result, xml_desc, empty); + } + + static std::string getKeyboardString(const char* keystring) + { + std::string key_str(keystring); + std::string trans_str; + return findString(trans_str, key_str) ? trans_str : key_str; + } + + // get the default args + static const LLStringUtil::format_map_t& getDefaultArgs() + { + return sDefaultArgs; + } + + static void setDefaultArg(const std::string& name, const std::string& value); + + // insert default args into an arg list + static void getArgs(LLStringUtil::format_map_t& args) + { + args.insert(sDefaultArgs.begin(), sDefaultArgs.end()); + } + +private: + typedef std::map template_map_t; + static template_map_t sStringTemplates; + static LLStringUtil::format_map_t sDefaultArgs; +}; + +#endif diff --git a/indra/llui/lluicolor.cpp b/indra/llui/lluicolor.cpp new file mode 100644 index 0000000000..f9bb80f8c5 --- /dev/null +++ b/indra/llui/lluicolor.cpp @@ -0,0 +1,87 @@ +/** + * @file lluicolor.cpp + * @brief brief LLUIColor class implementation file + * + * $LicenseInfo:firstyear=2009&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include "linden_common.h" + +#include "lluicolor.h" + +LLUIColor::LLUIColor() + :mColorPtr(NULL) +{ +} + + +LLUIColor::LLUIColor(const LLColor4& color) +: mColor(color), + mColorPtr(NULL) +{ +} + +LLUIColor::LLUIColor(const LLUIColor* color) +: mColorPtr(color) +{ +} + +void LLUIColor::set(const LLColor4& color) +{ + mColor = color; + mColorPtr = NULL; +} + +void LLUIColor::set(const LLUIColor* color) +{ + mColorPtr = color; +} + +const LLColor4& LLUIColor::get() const +{ + return (mColorPtr == NULL ? mColor : mColorPtr->get()); +} + +LLUIColor::operator const LLColor4& () const +{ + return get(); +} + +const LLColor4& LLUIColor::operator()() const +{ + return get(); +} + +bool LLUIColor::isReference() const +{ + return mColorPtr != NULL; +} + +namespace LLInitParam +{ + // used to detect equivalence with default values on export + bool ParamCompare::equals(const LLUIColor &a, const LLUIColor &b) + { + // do not detect value equivalence, treat pointers to colors as distinct from color values + return (a.mColorPtr == NULL && b.mColorPtr == NULL ? a.mColor == b.mColor : a.mColorPtr == b.mColorPtr); + } +} diff --git a/indra/llui/lluicolor.h b/indra/llui/lluicolor.h new file mode 100644 index 0000000000..97ebea854a --- /dev/null +++ b/indra/llui/lluicolor.h @@ -0,0 +1,71 @@ +/** + * @file lluicolor.h + * @brief brief LLUIColor class header file + * + * $LicenseInfo:firstyear=2009&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#ifndef LL_LLUICOLOR_H_ +#define LL_LLUICOLOR_H_ + +#include "v4color.h" + +namespace LLInitParam +{ + template + struct ParamCompare; +} + +class LLUIColor +{ +public: + LLUIColor(); + LLUIColor(const LLColor4& color); + LLUIColor(const LLUIColor* color); + + void set(const LLColor4& color); + void set(const LLUIColor* color); + + const LLColor4& get() const; + + operator const LLColor4& () const; + const LLColor4& operator()() const; + + bool isReference() const; + +private: + friend struct LLInitParam::ParamCompare; + + const LLUIColor* mColorPtr; + LLColor4 mColor; +}; + +namespace LLInitParam +{ + template<> + struct ParamCompare + { + static bool equals(const LLUIColor& a, const LLUIColor& b); + }; +} + +#endif diff --git a/indra/llui/llxuiparser.cpp b/indra/llui/llxuiparser.cpp new file mode 100644 index 0000000000..afc76024d1 --- /dev/null +++ b/indra/llui/llxuiparser.cpp @@ -0,0 +1,1756 @@ +/** + * @file llxuiparser.cpp + * @brief Utility functions for handling XUI structures in XML + * + * $LicenseInfo:firstyear=2003&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include "linden_common.h" + +#include "llxuiparser.h" + +#include "llxmlnode.h" + +#ifdef LL_STANDALONE +#include +#else +#include "expat/expat.h" +#endif + +#include +#include +//#include +#include + +#include "lluicolor.h" + +using namespace BOOST_SPIRIT_CLASSIC_NS; + +const S32 MAX_STRING_ATTRIBUTE_SIZE = 40; + +static LLInitParam::Parser::parser_read_func_map_t sXSDReadFuncs; +static LLInitParam::Parser::parser_write_func_map_t sXSDWriteFuncs; +static LLInitParam::Parser::parser_inspect_func_map_t sXSDInspectFuncs; + +static LLInitParam::Parser::parser_read_func_map_t sSimpleXUIReadFuncs; +static LLInitParam::Parser::parser_write_func_map_t sSimpleXUIWriteFuncs; +static LLInitParam::Parser::parser_inspect_func_map_t sSimpleXUIInspectFuncs; + +const char* NO_VALUE_MARKER = "no_value"; + +const S32 LINE_NUMBER_HERE = 0; + +struct MaxOccursValues : public LLInitParam::TypeValuesHelper +{ + static void declareValues() + { + declare("unbounded", U32_MAX); + } +}; + +struct Occurs : public LLInitParam::Block +{ + Optional minOccurs; + Optional maxOccurs; + + Occurs() + : minOccurs("minOccurs", 0), + maxOccurs("maxOccurs", U32_MAX) + + {} +}; + + +typedef enum +{ + USE_REQUIRED, + USE_OPTIONAL +} EUse; + +namespace LLInitParam +{ + template<> + struct TypeValues : public TypeValuesHelper + { + static void declareValues() + { + declare("required", USE_REQUIRED); + declare("optional", USE_OPTIONAL); + } + }; +} + +struct Element; +struct Group; +struct Choice; +struct Sequence; +struct Any; + +struct Attribute : public LLInitParam::Block +{ + Mandatory name; + Mandatory type; + Mandatory use; + + Attribute() + : name("name"), + type("type"), + use("use") + {} +}; + +struct Any : public LLInitParam::Block +{ + Optional _namespace; + + Any() + : _namespace("namespace") + {} +}; + +struct All : public LLInitParam::Block +{ + Multiple< Lazy > elements; + + All() + : elements("element") + { + maxOccurs = 1; + } +}; + +struct Choice : public LLInitParam::ChoiceBlock +{ + Alternative< Lazy > element; + Alternative< Lazy > group; + Alternative< Lazy > choice; + Alternative< Lazy > sequence; + Alternative< Lazy > any; + + Choice() + : element("element"), + group("group"), + choice("choice"), + sequence("sequence"), + any("any") + {} + +}; + +struct Sequence : public LLInitParam::ChoiceBlock +{ + Alternative< Lazy > element; + Alternative< Lazy > group; + Alternative< Lazy > choice; + Alternative< Lazy > sequence; + Alternative< Lazy > any; +}; + +struct GroupContents : public LLInitParam::ChoiceBlock +{ + Alternative all; + Alternative choice; + Alternative sequence; + + GroupContents() + : all("all"), + choice("choice"), + sequence("sequence") + {} +}; + +struct Group : public LLInitParam::Block +{ + Optional name, + ref; + + Group() + : name("name"), + ref("ref") + {} +}; + +struct Restriction : public LLInitParam::Block +{ +}; + +struct Extension : public LLInitParam::Block +{ +}; + +struct SimpleContent : public LLInitParam::ChoiceBlock +{ + Alternative restriction; + Alternative extension; + + SimpleContent() + : restriction("restriction"), + extension("extension") + {} +}; + +struct SimpleType : public LLInitParam::Block +{ + // TODO +}; + +struct ComplexContent : public LLInitParam::Block +{ + Optional mixed; + + ComplexContent() + : mixed("mixed", true) + {} +}; + +struct ComplexTypeContents : public LLInitParam::ChoiceBlock +{ + Alternative simple_content; + Alternative complex_content; + Alternative group; + Alternative all; + Alternative choice; + Alternative sequence; + + ComplexTypeContents() + : simple_content("simpleContent"), + complex_content("complexContent"), + group("group"), + all("all"), + choice("choice"), + sequence("sequence") + {} +}; + +struct ComplexType : public LLInitParam::Block +{ + Optional name; + Optional mixed; + + Multiple attribute; + Multiple< Lazy > elements; + + ComplexType() + : name("name"), + attribute("xs:attribute"), + elements("xs:element"), + mixed("mixed") + { + } +}; + +struct ElementContents : public LLInitParam::ChoiceBlock +{ + Alternative simpleType; + Alternative complexType; + + ElementContents() + : simpleType("simpleType"), + complexType("complexType") + {} +}; + +struct Element : public LLInitParam::Block +{ + Optional name, + ref, + type; + + Element() + : name("xs:name"), + ref("xs:ref"), + type("xs:type") + {} +}; + +struct Schema : public LLInitParam::Block +{ +private: + Mandatory targetNamespace, + xmlns, + xs; + +public: + Optional attributeFormDefault, + elementFormDefault; + + Mandatory root_element; + + void setNameSpace(const std::string& ns) {targetNamespace = ns; xmlns = ns;} + + Schema(const std::string& ns = LLStringUtil::null) + : attributeFormDefault("attributeFormDefault"), + elementFormDefault("elementFormDefault"), + xs("xmlns:xs"), + targetNamespace("targetNamespace"), + xmlns("xmlns"), + root_element("xs:element") + { + attributeFormDefault = "unqualified"; + elementFormDefault = "qualified"; + xs = "http://www.w3.org/2001/XMLSchema"; + if (!ns.empty()) + { + setNameSpace(ns); + }; + } + +}; + +// +// LLXSDWriter +// +LLXSDWriter::LLXSDWriter() +: Parser(sXSDReadFuncs, sXSDWriteFuncs, sXSDInspectFuncs) +{ + registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:boolean", _1, _2, _3, _4)); + registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:string", _1, _2, _3, _4)); + registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:unsignedByte", _1, _2, _3, _4)); + registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:signedByte", _1, _2, _3, _4)); + registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:unsignedShort", _1, _2, _3, _4)); + registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:signedShort", _1, _2, _3, _4)); + registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:unsignedInt", _1, _2, _3, _4)); + registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:integer", _1, _2, _3, _4)); + registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:float", _1, _2, _3, _4)); + registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:double", _1, _2, _3, _4)); + registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:string", _1, _2, _3, _4)); + registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:string", _1, _2, _3, _4)); + registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:string", _1, _2, _3, _4)); + registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:string", _1, _2, _3, _4)); +} + +void LLXSDWriter::writeXSD(const std::string& type_name, LLXMLNodePtr node, const LLInitParam::BaseBlock& block, const std::string& xml_namespace) +{ + Schema schema(xml_namespace); + + schema.root_element.name = type_name; + Choice& choice = schema.root_element.complexType.choice; + + choice.minOccurs = 0; + choice.maxOccurs = "unbounded"; + + mSchemaNode = node; + //node->setName("xs:schema"); + //node->createChild("attributeFormDefault", true)->setStringValue("unqualified"); + //node->createChild("elementFormDefault", true)->setStringValue("qualified"); + //node->createChild("targetNamespace", true)->setStringValue(xml_namespace); + //node->createChild("xmlns:xs", true)->setStringValue("http://www.w3.org/2001/XMLSchema"); + //node->createChild("xmlns", true)->setStringValue(xml_namespace); + + //node = node->createChild("xs:complexType", false); + //node->createChild("name", true)->setStringValue(type_name); + //node->createChild("mixed", true)->setStringValue("true"); + + //mAttributeNode = node; + //mElementNode = node->createChild("xs:choice", false); + //mElementNode->createChild("minOccurs", true)->setStringValue("0"); + //mElementNode->createChild("maxOccurs", true)->setStringValue("unbounded"); + block.inspectBlock(*this); + + // duplicate element choices + LLXMLNodeList children; + mElementNode->getChildren("xs:element", children, FALSE); + for (LLXMLNodeList::iterator child_it = children.begin(); child_it != children.end(); ++child_it) + { + LLXMLNodePtr child_copy = child_it->second->deepCopy(); + std::string child_name; + child_copy->getAttributeString("name", child_name); + child_copy->setAttributeString("name", type_name + "." + child_name); + mElementNode->addChild(child_copy); + } + + LLXMLNodePtr element_declaration_node = mSchemaNode->createChild("xs:element", false); + element_declaration_node->createChild("name", true)->setStringValue(type_name); + element_declaration_node->createChild("type", true)->setStringValue(type_name); +} + +void LLXSDWriter::writeAttribute(const std::string& type, const Parser::name_stack_t& stack, S32 min_count, S32 max_count, const std::vector* possible_values) +{ + name_stack_t non_empty_names; + std::string attribute_name; + for (name_stack_t::const_iterator it = stack.begin(); + it != stack.end(); + ++it) + { + const std::string& name = it->first; + if (!name.empty()) + { + non_empty_names.push_back(*it); + } + } + + for (name_stack_t::const_iterator it = non_empty_names.begin(); + it != non_empty_names.end(); + ++it) + { + if (!attribute_name.empty()) + { + attribute_name += "."; + } + attribute_name += it->first; + } + + // only flag non-nested attributes as mandatory, nested attributes have variant syntax + // that can't be properly constrained in XSD + // e.g. vs + bool attribute_mandatory = min_count == 1 && max_count == 1 && non_empty_names.size() == 1; + + // don't bother supporting "Multiple" params as xml attributes + if (max_count <= 1) + { + // add compound attribute to root node + addAttributeToSchema(mAttributeNode, attribute_name, type, attribute_mandatory, possible_values); + } + + // now generated nested elements for compound attributes + if (non_empty_names.size() > 1 && !attribute_mandatory) + { + std::string element_name; + + // traverse all but last element, leaving that as an attribute name + name_stack_t::const_iterator end_it = non_empty_names.end(); + end_it--; + + for (name_stack_t::const_iterator it = non_empty_names.begin(); + it != end_it; + ++it) + { + if (it != non_empty_names.begin()) + { + element_name += "."; + } + element_name += it->first; + } + + std::string short_attribute_name = non_empty_names.back().first; + + LLXMLNodePtr complex_type_node; + + // find existing element node here, starting at tail of child list + if (mElementNode->mChildren.notNull()) + { + for(LLXMLNodePtr element = mElementNode->mChildren->tail; + element.notNull(); + element = element->mPrev) + { + std::string name; + if(element->getAttributeString("name", name) && name == element_name) + { + complex_type_node = element->mChildren->head; + break; + } + } + } + //create complex_type node + // + // + // + // + // + if(complex_type_node.isNull()) + { + complex_type_node = mElementNode->createChild("xs:element", false); + + complex_type_node->createChild("minOccurs", true)->setIntValue(min_count); + complex_type_node->createChild("maxOccurs", true)->setIntValue(max_count); + complex_type_node->createChild("name", true)->setStringValue(element_name); + complex_type_node = complex_type_node->createChild("xs:complexType", false); + } + + addAttributeToSchema(complex_type_node, short_attribute_name, type, false, possible_values); + } +} + +void LLXSDWriter::addAttributeToSchema(LLXMLNodePtr type_declaration_node, const std::string& attribute_name, const std::string& type, bool mandatory, const std::vector* possible_values) +{ + if (!attribute_name.empty()) + { + LLXMLNodePtr new_enum_type_node; + if (possible_values != NULL) + { + // custom attribute type, for example + // + // + // + // + // + // + new_enum_type_node = new LLXMLNode("xs:simpleType", false); + + LLXMLNodePtr restriction_node = new_enum_type_node->createChild("xs:restriction", false); + restriction_node->createChild("base", true)->setStringValue("xs:string"); + + for (std::vector::const_iterator it = possible_values->begin(); + it != possible_values->end(); + ++it) + { + LLXMLNodePtr enum_node = restriction_node->createChild("xs:enumeration", false); + enum_node->createChild("value", true)->setStringValue(*it); + } + } + + string_set_t& attributes_written = mAttributesWritten[type_declaration_node]; + + string_set_t::iterator found_it = attributes_written.lower_bound(attribute_name); + + // attribute not yet declared + if (found_it == attributes_written.end() || attributes_written.key_comp()(attribute_name, *found_it)) + { + attributes_written.insert(found_it, attribute_name); + + LLXMLNodePtr attribute_node = type_declaration_node->createChild("xs:attribute", false); + + // attribute name + attribute_node->createChild("name", true)->setStringValue(attribute_name); + + if (new_enum_type_node.notNull()) + { + attribute_node->addChild(new_enum_type_node); + } + else + { + // simple attribute type + attribute_node->createChild("type", true)->setStringValue(type); + } + + // required or optional + attribute_node->createChild("use", true)->setStringValue(mandatory ? "required" : "optional"); + } + // attribute exists...handle collision of same name attributes with potentially different types + else + { + LLXMLNodePtr attribute_declaration; + if (type_declaration_node.notNull()) + { + for(LLXMLNodePtr node = type_declaration_node->mChildren->tail; + node.notNull(); + node = node->mPrev) + { + std::string name; + if (node->getAttributeString("name", name) && name == attribute_name) + { + attribute_declaration = node; + break; + } + } + } + + bool new_type_is_enum = new_enum_type_node.notNull(); + bool existing_type_is_enum = !attribute_declaration->hasAttribute("type"); + + // either type is enum, revert to string in collision + // don't bother to check for enum equivalence + if (new_type_is_enum || existing_type_is_enum) + { + if (attribute_declaration->hasAttribute("type")) + { + attribute_declaration->setAttributeString("type", "xs:string"); + } + else + { + attribute_declaration->createChild("type", true)->setStringValue("xs:string"); + } + attribute_declaration->deleteChildren("xs:simpleType"); + } + else + { + // check for collision of different standard types + std::string existing_type; + attribute_declaration->getAttributeString("type", existing_type); + // if current type is not the same as the new type, revert to strnig + if (existing_type != type) + { + // ...than use most general type, string + attribute_declaration->setAttributeString("type", "string"); + } + } + } + } +} + +// +// LLXUIXSDWriter +// +void LLXUIXSDWriter::writeXSD(const std::string& type_name, const std::string& path, const LLInitParam::BaseBlock& block) +{ + std::string file_name(path); + file_name += type_name + ".xsd"; + LLXMLNodePtr root_nodep = new LLXMLNode(); + + LLXSDWriter::writeXSD(type_name, root_nodep, block, "http://www.lindenlab.com/xui"); + + // add includes for all possible children + const std::type_info* type = *LLWidgetTypeRegistry::instance().getValue(type_name); + const widget_registry_t* widget_registryp = LLChildRegistryRegistry::instance().getValue(type); + + // add choices for valid children + if (widget_registryp) + { + // add include declarations for all valid children + for (widget_registry_t::Registrar::registry_map_t::const_iterator it = widget_registryp->currentRegistrar().beginItems(); + it != widget_registryp->currentRegistrar().endItems(); + ++it) + { + std::string widget_name = it->first; + if (widget_name == type_name) + { + continue; + } + LLXMLNodePtr nodep = new LLXMLNode("xs:include", false); + nodep->createChild("schemaLocation", true)->setStringValue(widget_name + ".xsd"); + + // add to front of schema + mSchemaNode->addChild(nodep, mSchemaNode); + } + + for (widget_registry_t::Registrar::registry_map_t::const_iterator it = widget_registryp->currentRegistrar().beginItems(); + it != widget_registryp->currentRegistrar().endItems(); + ++it) + { + std::string widget_name = it->first; + // + LLXMLNodePtr widget_node = mElementNode->createChild("xs:element", false); + widget_node->createChild("name", true)->setStringValue(widget_name); + widget_node->createChild("type", true)->setStringValue(widget_name); + } + } + + LLFILE* xsd_file = LLFile::fopen(file_name.c_str(), "w"); + LLXMLNode::writeHeaderToFile(xsd_file); + root_nodep->writeToFile(xsd_file); + fclose(xsd_file); +} + +static LLInitParam::Parser::parser_read_func_map_t sXUIReadFuncs; +static LLInitParam::Parser::parser_write_func_map_t sXUIWriteFuncs; +static LLInitParam::Parser::parser_inspect_func_map_t sXUIInspectFuncs; + +// +// LLXUIParser +// +LLXUIParser::LLXUIParser() +: Parser(sXUIReadFuncs, sXUIWriteFuncs, sXUIInspectFuncs), + mCurReadDepth(0) +{ + if (sXUIReadFuncs.empty()) + { + registerParserFuncs(readFlag, writeFlag); + registerParserFuncs(readBoolValue, writeBoolValue); + registerParserFuncs(readStringValue, writeStringValue); + registerParserFuncs(readU8Value, writeU8Value); + registerParserFuncs(readS8Value, writeS8Value); + registerParserFuncs(readU16Value, writeU16Value); + registerParserFuncs(readS16Value, writeS16Value); + registerParserFuncs(readU32Value, writeU32Value); + registerParserFuncs(readS32Value, writeS32Value); + registerParserFuncs(readF32Value, writeF32Value); + registerParserFuncs(readF64Value, writeF64Value); + registerParserFuncs(readColor4Value, writeColor4Value); + registerParserFuncs(readUIColorValue, writeUIColorValue); + registerParserFuncs(readUUIDValue, writeUUIDValue); + registerParserFuncs(readSDValue, writeSDValue); + } +} + +static LLFastTimer::DeclareTimer FTM_PARSE_XUI("XUI Parsing"); +const LLXMLNodePtr DUMMY_NODE = new LLXMLNode(); + +void LLXUIParser::readXUI(LLXMLNodePtr node, LLInitParam::BaseBlock& block, const std::string& filename, bool silent) +{ + LLFastTimer timer(FTM_PARSE_XUI); + mNameStack.clear(); + mRootNodeName = node->getName()->mString; + mCurFileName = filename; + mCurReadDepth = 0; + setParseSilently(silent); + + if (node.isNull()) + { + parserWarning("Invalid node"); + } + else + { + readXUIImpl(node, block); + } +} + +bool LLXUIParser::readXUIImpl(LLXMLNodePtr nodep, LLInitParam::BaseBlock& block) +{ + typedef boost::tokenizer > tokenizer; + boost::char_separator sep("."); + + bool values_parsed = false; + bool silent = mCurReadDepth > 0; + + if (nodep->getFirstChild().isNull() + && nodep->mAttributes.empty() + && nodep->getSanitizedValue().empty()) + { + // empty node, just parse as flag + mCurReadNode = DUMMY_NODE; + return block.submitValue(mNameStack, *this, silent); + } + + // submit attributes for current node + values_parsed |= readAttributes(nodep, block); + + // treat text contents of xml node as "value" parameter + std::string text_contents = nodep->getSanitizedValue(); + if (!text_contents.empty()) + { + mCurReadNode = nodep; + mNameStack.push_back(std::make_pair(std::string("value"), true)); + // child nodes are not necessarily valid parameters (could be a child widget) + // so don't complain once we've recursed + if (!block.submitValue(mNameStack, *this, true)) + { + mNameStack.pop_back(); + block.submitValue(mNameStack, *this, silent); + } + else + { + mNameStack.pop_back(); + } + } + + // then traverse children + // child node must start with last name of parent node (our "scope") + // for example: "" + // which equates to the following nesting: + // button + // param + // nested_param1 + // nested_param2 + // nested_param3 + mCurReadDepth++; + for(LLXMLNodePtr childp = nodep->getFirstChild(); childp.notNull();) + { + std::string child_name(childp->getName()->mString); + S32 num_tokens_pushed = 0; + + // for non "dotted" child nodes check to see if child node maps to another widget type + // and if not, treat as a child element of the current node + // e.g. will interpret as "button.rect" + // since there is no widget named "rect" + if (child_name.find(".") == std::string::npos) + { + mNameStack.push_back(std::make_pair(child_name, true)); + num_tokens_pushed++; + } + else + { + // parse out "dotted" name into individual tokens + tokenizer name_tokens(child_name, sep); + + tokenizer::iterator name_token_it = name_tokens.begin(); + if(name_token_it == name_tokens.end()) + { + childp = childp->getNextSibling(); + continue; + } + + // check for proper nesting + if (mNameStack.empty()) + { + if (*name_token_it != mRootNodeName) + { + childp = childp->getNextSibling(); + continue; + } + } + else if(mNameStack.back().first != *name_token_it) + { + childp = childp->getNextSibling(); + continue; + } + + // now ignore first token + ++name_token_it; + + // copy remaining tokens on to our running token list + for(tokenizer::iterator token_to_push = name_token_it; token_to_push != name_tokens.end(); ++token_to_push) + { + mNameStack.push_back(std::make_pair(*token_to_push, true)); + num_tokens_pushed++; + } + } + + // recurse and visit children XML nodes + if(readXUIImpl(childp, block)) + { + // child node successfully parsed, remove from DOM + + values_parsed = true; + LLXMLNodePtr node_to_remove = childp; + childp = childp->getNextSibling(); + + nodep->deleteChild(node_to_remove); + } + else + { + childp = childp->getNextSibling(); + } + + while(num_tokens_pushed-- > 0) + { + mNameStack.pop_back(); + } + } + mCurReadDepth--; + return values_parsed; +} + +bool LLXUIParser::readAttributes(LLXMLNodePtr nodep, LLInitParam::BaseBlock& block) +{ + typedef boost::tokenizer > tokenizer; + boost::char_separator sep("."); + + bool any_parsed = false; + bool silent = mCurReadDepth > 0; + + for(LLXMLAttribList::const_iterator attribute_it = nodep->mAttributes.begin(); + attribute_it != nodep->mAttributes.end(); + ++attribute_it) + { + S32 num_tokens_pushed = 0; + std::string attribute_name(attribute_it->first->mString); + mCurReadNode = attribute_it->second; + + tokenizer name_tokens(attribute_name, sep); + // copy remaining tokens on to our running token list + for(tokenizer::iterator token_to_push = name_tokens.begin(); token_to_push != name_tokens.end(); ++token_to_push) + { + mNameStack.push_back(std::make_pair(*token_to_push, true)); + num_tokens_pushed++; + } + + // child nodes are not necessarily valid attributes, so don't complain once we've recursed + any_parsed |= block.submitValue(mNameStack, *this, silent); + + while(num_tokens_pushed-- > 0) + { + mNameStack.pop_back(); + } + } + + return any_parsed; +} + +void LLXUIParser::writeXUI(LLXMLNodePtr node, const LLInitParam::BaseBlock &block, const LLInitParam::BaseBlock* diff_block) +{ + mWriteRootNode = node; + name_stack_t name_stack = Parser::name_stack_t(); + block.serializeBlock(*this, name_stack, diff_block); + mOutNodes.clear(); +} + +// go from a stack of names to a specific XML node +LLXMLNodePtr LLXUIParser::getNode(name_stack_t& stack) +{ + LLXMLNodePtr out_node = mWriteRootNode; + + name_stack_t::iterator next_it = stack.begin(); + for (name_stack_t::iterator it = stack.begin(); + it != stack.end(); + it = next_it) + { + ++next_it; + if (it->first.empty()) + { + it->second = false; + continue; + } + + out_nodes_t::iterator found_it = mOutNodes.find(it->first); + + // node with this name not yet written + if (found_it == mOutNodes.end() || it->second) + { + // make an attribute if we are the last element on the name stack + bool is_attribute = next_it == stack.end(); + LLXMLNodePtr new_node = new LLXMLNode(it->first.c_str(), is_attribute); + out_node->addChild(new_node); + mOutNodes[it->first] = new_node; + out_node = new_node; + it->second = false; + } + else + { + out_node = found_it->second; + } + } + + return (out_node == mWriteRootNode ? LLXMLNodePtr(NULL) : out_node); +} + +bool LLXUIParser::readFlag(Parser& parser, void* val_ptr) +{ + LLXUIParser& self = static_cast(parser); + return self.mCurReadNode == DUMMY_NODE; +} + +bool LLXUIParser::writeFlag(Parser& parser, const void* val_ptr, name_stack_t& stack) +{ + // just create node + LLXUIParser& self = static_cast(parser); + LLXMLNodePtr node = self.getNode(stack); + return node.notNull(); +} + +bool LLXUIParser::readBoolValue(Parser& parser, void* val_ptr) +{ + S32 value; + LLXUIParser& self = static_cast(parser); + bool success = self.mCurReadNode->getBoolValue(1, &value); + *((bool*)val_ptr) = (value != FALSE); + return success; +} + +bool LLXUIParser::writeBoolValue(Parser& parser, const void* val_ptr, name_stack_t& stack) +{ + LLXUIParser& self = static_cast(parser); + LLXMLNodePtr node = self.getNode(stack); + if (node.notNull()) + { + node->setBoolValue(*((bool*)val_ptr)); + return true; + } + return false; +} + +bool LLXUIParser::readStringValue(Parser& parser, void* val_ptr) +{ + LLXUIParser& self = static_cast(parser); + *((std::string*)val_ptr) = self.mCurReadNode->getSanitizedValue(); + return true; +} + +bool LLXUIParser::writeStringValue(Parser& parser, const void* val_ptr, name_stack_t& stack) +{ + LLXUIParser& self = static_cast(parser); + LLXMLNodePtr node = self.getNode(stack); + if (node.notNull()) + { + const std::string* string_val = reinterpret_cast(val_ptr); + if (string_val->find('\n') != std::string::npos + || string_val->size() > MAX_STRING_ATTRIBUTE_SIZE) + { + // don't write strings with newlines into attributes + std::string attribute_name = node->getName()->mString; + LLXMLNodePtr parent_node = node->mParent; + parent_node->deleteChild(node); + // write results in text contents of node + if (attribute_name == "value") + { + // "value" is implicit, just write to parent + node = parent_node; + } + else + { + // create a child that is not an attribute, but with same name + node = parent_node->createChild(attribute_name.c_str(), false); + } + } + node->setStringValue(*string_val); + return true; + } + return false; +} + +bool LLXUIParser::readU8Value(Parser& parser, void* val_ptr) +{ + LLXUIParser& self = static_cast(parser); + return self.mCurReadNode->getByteValue(1, (U8*)val_ptr); +} + +bool LLXUIParser::writeU8Value(Parser& parser, const void* val_ptr, name_stack_t& stack) +{ + LLXUIParser& self = static_cast(parser); + LLXMLNodePtr node = self.getNode(stack); + if (node.notNull()) + { + node->setUnsignedValue(*((U8*)val_ptr)); + return true; + } + return false; +} + +bool LLXUIParser::readS8Value(Parser& parser, void* val_ptr) +{ + LLXUIParser& self = static_cast(parser); + S32 value; + if(self.mCurReadNode->getIntValue(1, &value)) + { + *((S8*)val_ptr) = value; + return true; + } + return false; +} + +bool LLXUIParser::writeS8Value(Parser& parser, const void* val_ptr, name_stack_t& stack) +{ + LLXUIParser& self = static_cast(parser); + LLXMLNodePtr node = self.getNode(stack); + if (node.notNull()) + { + node->setIntValue(*((S8*)val_ptr)); + return true; + } + return false; +} + +bool LLXUIParser::readU16Value(Parser& parser, void* val_ptr) +{ + LLXUIParser& self = static_cast(parser); + U32 value; + if(self.mCurReadNode->getUnsignedValue(1, &value)) + { + *((U16*)val_ptr) = value; + return true; + } + return false; +} + +bool LLXUIParser::writeU16Value(Parser& parser, const void* val_ptr, name_stack_t& stack) +{ + LLXUIParser& self = static_cast(parser); + LLXMLNodePtr node = self.getNode(stack); + if (node.notNull()) + { + node->setUnsignedValue(*((U16*)val_ptr)); + return true; + } + return false; +} + +bool LLXUIParser::readS16Value(Parser& parser, void* val_ptr) +{ + LLXUIParser& self = static_cast(parser); + S32 value; + if(self.mCurReadNode->getIntValue(1, &value)) + { + *((S16*)val_ptr) = value; + return true; + } + return false; +} + +bool LLXUIParser::writeS16Value(Parser& parser, const void* val_ptr, name_stack_t& stack) +{ + LLXUIParser& self = static_cast(parser); + LLXMLNodePtr node = self.getNode(stack); + if (node.notNull()) + { + node->setIntValue(*((S16*)val_ptr)); + return true; + } + return false; +} + +bool LLXUIParser::readU32Value(Parser& parser, void* val_ptr) +{ + LLXUIParser& self = static_cast(parser); + return self.mCurReadNode->getUnsignedValue(1, (U32*)val_ptr); +} + +bool LLXUIParser::writeU32Value(Parser& parser, const void* val_ptr, name_stack_t& stack) +{ + LLXUIParser& self = static_cast(parser); + LLXMLNodePtr node = self.getNode(stack); + if (node.notNull()) + { + node->setUnsignedValue(*((U32*)val_ptr)); + return true; + } + return false; +} + +bool LLXUIParser::readS32Value(Parser& parser, void* val_ptr) +{ + LLXUIParser& self = static_cast(parser); + return self.mCurReadNode->getIntValue(1, (S32*)val_ptr); +} + +bool LLXUIParser::writeS32Value(Parser& parser, const void* val_ptr, name_stack_t& stack) +{ + LLXUIParser& self = static_cast(parser); + LLXMLNodePtr node = self.getNode(stack); + if (node.notNull()) + { + node->setIntValue(*((S32*)val_ptr)); + return true; + } + return false; +} + +bool LLXUIParser::readF32Value(Parser& parser, void* val_ptr) +{ + LLXUIParser& self = static_cast(parser); + return self.mCurReadNode->getFloatValue(1, (F32*)val_ptr); +} + +bool LLXUIParser::writeF32Value(Parser& parser, const void* val_ptr, name_stack_t& stack) +{ + LLXUIParser& self = static_cast(parser); + LLXMLNodePtr node = self.getNode(stack); + if (node.notNull()) + { + node->setFloatValue(*((F32*)val_ptr)); + return true; + } + return false; +} + +bool LLXUIParser::readF64Value(Parser& parser, void* val_ptr) +{ + LLXUIParser& self = static_cast(parser); + return self.mCurReadNode->getDoubleValue(1, (F64*)val_ptr); +} + +bool LLXUIParser::writeF64Value(Parser& parser, const void* val_ptr, name_stack_t& stack) +{ + LLXUIParser& self = static_cast(parser); + LLXMLNodePtr node = self.getNode(stack); + if (node.notNull()) + { + node->setDoubleValue(*((F64*)val_ptr)); + return true; + } + return false; +} + +bool LLXUIParser::readColor4Value(Parser& parser, void* val_ptr) +{ + LLXUIParser& self = static_cast(parser); + LLColor4* colorp = (LLColor4*)val_ptr; + if(self.mCurReadNode->getFloatValue(4, colorp->mV) >= 3) + { + return true; + } + + return false; +} + +bool LLXUIParser::writeColor4Value(Parser& parser, const void* val_ptr, name_stack_t& stack) +{ + LLXUIParser& self = static_cast(parser); + LLXMLNodePtr node = self.getNode(stack); + if (node.notNull()) + { + LLColor4 color = *((LLColor4*)val_ptr); + node->setFloatValue(4, color.mV); + return true; + } + return false; +} + +bool LLXUIParser::readUIColorValue(Parser& parser, void* val_ptr) +{ + LLXUIParser& self = static_cast(parser); + LLUIColor* param = (LLUIColor*)val_ptr; + LLColor4 color; + bool success = self.mCurReadNode->getFloatValue(4, color.mV) >= 3; + if (success) + { + param->set(color); + return true; + } + return false; +} + +bool LLXUIParser::writeUIColorValue(Parser& parser, const void* val_ptr, name_stack_t& stack) +{ + LLXUIParser& self = static_cast(parser); + LLXMLNodePtr node = self.getNode(stack); + if (node.notNull()) + { + LLUIColor color = *((LLUIColor*)val_ptr); + //RN: don't write out the color that is represented by a function + // rely on param block exporting to get the reference to the color settings + if (color.isReference()) return false; + node->setFloatValue(4, color.get().mV); + return true; + } + return false; +} + +bool LLXUIParser::readUUIDValue(Parser& parser, void* val_ptr) +{ + LLXUIParser& self = static_cast(parser); + LLUUID temp_id; + // LLUUID::set is destructive, so use temporary value + if (temp_id.set(self.mCurReadNode->getSanitizedValue())) + { + *(LLUUID*)(val_ptr) = temp_id; + return true; + } + return false; +} + +bool LLXUIParser::writeUUIDValue(Parser& parser, const void* val_ptr, name_stack_t& stack) +{ + LLXUIParser& self = static_cast(parser); + LLXMLNodePtr node = self.getNode(stack); + if (node.notNull()) + { + node->setStringValue(((LLUUID*)val_ptr)->asString()); + return true; + } + return false; +} + +bool LLXUIParser::readSDValue(Parser& parser, void* val_ptr) +{ + LLXUIParser& self = static_cast(parser); + *((LLSD*)val_ptr) = LLSD(self.mCurReadNode->getSanitizedValue()); + return true; +} + +bool LLXUIParser::writeSDValue(Parser& parser, const void* val_ptr, name_stack_t& stack) +{ + LLXUIParser& self = static_cast(parser); + + LLXMLNodePtr node = self.getNode(stack); + if (node.notNull()) + { + std::string string_val = ((LLSD*)val_ptr)->asString(); + if (string_val.find('\n') != std::string::npos || string_val.size() > MAX_STRING_ATTRIBUTE_SIZE) + { + // don't write strings with newlines into attributes + std::string attribute_name = node->getName()->mString; + LLXMLNodePtr parent_node = node->mParent; + parent_node->deleteChild(node); + // write results in text contents of node + if (attribute_name == "value") + { + // "value" is implicit, just write to parent + node = parent_node; + } + else + { + node = parent_node->createChild(attribute_name.c_str(), false); + } + } + + node->setStringValue(string_val); + return true; + } + return false; +} + +/*virtual*/ std::string LLXUIParser::getCurrentElementName() +{ + std::string full_name; + for (name_stack_t::iterator it = mNameStack.begin(); + it != mNameStack.end(); + ++it) + { + full_name += it->first + "."; // build up dotted names: "button.param.nestedparam." + } + + return full_name; +} + +void LLXUIParser::parserWarning(const std::string& message) +{ +#ifdef LL_WINDOWS + // use Visual Studo friendly formatting of output message for easy access to originating xml + llutf16string utf16str = utf8str_to_utf16str(llformat("%s(%d):\t%s", mCurFileName.c_str(), mCurReadNode->getLineNumber(), message.c_str()).c_str()); + utf16str += '\n'; + OutputDebugString(utf16str.c_str()); +#else + Parser::parserWarning(message); +#endif +} + +void LLXUIParser::parserError(const std::string& message) +{ +#ifdef LL_WINDOWS + llutf16string utf16str = utf8str_to_utf16str(llformat("%s(%d):\t%s", mCurFileName.c_str(), mCurReadNode->getLineNumber(), message.c_str()).c_str()); + utf16str += '\n'; + OutputDebugString(utf16str.c_str()); +#else + Parser::parserError(message); +#endif +} + + +// +// LLSimpleXUIParser +// + +struct ScopedFile +{ + ScopedFile( const std::string& filename, const char* accessmode ) + { + mFile = LLFile::fopen(filename, accessmode); + } + + ~ScopedFile() + { + fclose(mFile); + mFile = NULL; + } + + S32 getRemainingBytes() + { + if (!isOpen()) return 0; + + S32 cur_pos = ftell(mFile); + fseek(mFile, 0L, SEEK_END); + S32 file_size = ftell(mFile); + fseek(mFile, cur_pos, SEEK_SET); + return file_size - cur_pos; + } + + bool isOpen() { return mFile != NULL; } + + LLFILE* mFile; +}; +LLSimpleXUIParser::LLSimpleXUIParser(LLSimpleXUIParser::element_start_callback_t element_cb) +: Parser(sSimpleXUIReadFuncs, sSimpleXUIWriteFuncs, sSimpleXUIInspectFuncs), + mCurReadDepth(0), + mElementCB(element_cb) +{ + if (sSimpleXUIReadFuncs.empty()) + { + registerParserFuncs(readFlag); + registerParserFuncs(readBoolValue); + registerParserFuncs(readStringValue); + registerParserFuncs(readU8Value); + registerParserFuncs(readS8Value); + registerParserFuncs(readU16Value); + registerParserFuncs(readS16Value); + registerParserFuncs(readU32Value); + registerParserFuncs(readS32Value); + registerParserFuncs(readF32Value); + registerParserFuncs(readF64Value); + registerParserFuncs(readColor4Value); + registerParserFuncs(readUIColorValue); + registerParserFuncs(readUUIDValue); + registerParserFuncs(readSDValue); + } +} + +LLSimpleXUIParser::~LLSimpleXUIParser() +{ +} + + +bool LLSimpleXUIParser::readXUI(const std::string& filename, LLInitParam::BaseBlock& block, bool silent) +{ + LLFastTimer timer(FTM_PARSE_XUI); + + mParser = XML_ParserCreate(NULL); + XML_SetUserData(mParser, this); + XML_SetElementHandler( mParser, startElementHandler, endElementHandler); + XML_SetCharacterDataHandler( mParser, characterDataHandler); + + mOutputStack.push_back(std::make_pair(&block, 0)); + mNameStack.clear(); + mCurFileName = filename; + mCurReadDepth = 0; + setParseSilently(silent); + + ScopedFile file(filename, "rb"); + if( !file.isOpen() ) + { + LL_WARNS("ReadXUI") << "Unable to open file " << filename << LL_ENDL; + XML_ParserFree( mParser ); + return false; + } + + S32 bytes_read = 0; + + S32 buffer_size = file.getRemainingBytes(); + void* buffer = XML_GetBuffer(mParser, buffer_size); + if( !buffer ) + { + LL_WARNS("ReadXUI") << "Unable to allocate XML buffer while reading file " << filename << LL_ENDL; + XML_ParserFree( mParser ); + return false; + } + + bytes_read = (S32)fread(buffer, 1, buffer_size, file.mFile); + if( bytes_read <= 0 ) + { + LL_WARNS("ReadXUI") << "Error while reading file " << filename << LL_ENDL; + XML_ParserFree( mParser ); + return false; + } + + mEmptyLeafNode.push_back(false); + + if( !XML_ParseBuffer(mParser, bytes_read, TRUE ) ) + { + LL_WARNS("ReadXUI") << "Error while parsing file " << filename << LL_ENDL; + XML_ParserFree( mParser ); + return false; + } + + mEmptyLeafNode.pop_back(); + + XML_ParserFree( mParser ); + return true; +} + +void LLSimpleXUIParser::startElementHandler(void *userData, const char *name, const char **atts) +{ + LLSimpleXUIParser* self = reinterpret_cast(userData); + self->startElement(name, atts); +} + +void LLSimpleXUIParser::endElementHandler(void *userData, const char *name) +{ + LLSimpleXUIParser* self = reinterpret_cast(userData); + self->endElement(name); +} + +void LLSimpleXUIParser::characterDataHandler(void *userData, const char *s, int len) +{ + LLSimpleXUIParser* self = reinterpret_cast(userData); + self->characterData(s, len); +} + +void LLSimpleXUIParser::characterData(const char *s, int len) +{ + mTextContents += std::string(s, len); +} + +void LLSimpleXUIParser::startElement(const char *name, const char **atts) +{ + processText(); + + typedef boost::tokenizer > tokenizer; + boost::char_separator sep("."); + + if (mElementCB) + { + LLInitParam::BaseBlock* blockp = mElementCB(*this, name); + if (blockp) + { + mOutputStack.push_back(std::make_pair(blockp, 0)); + } + } + + mOutputStack.back().second++; + S32 num_tokens_pushed = 0; + std::string child_name(name); + + if (mOutputStack.back().second == 1) + { // root node for this block + mScope.push_back(child_name); + } + else + { // compound attribute + if (child_name.find(".") == std::string::npos) + { + mNameStack.push_back(std::make_pair(child_name, true)); + num_tokens_pushed++; + mScope.push_back(child_name); + } + else + { + // parse out "dotted" name into individual tokens + tokenizer name_tokens(child_name, sep); + + tokenizer::iterator name_token_it = name_tokens.begin(); + if(name_token_it == name_tokens.end()) + { + return; + } + + // check for proper nesting + if(!mScope.empty() && *name_token_it != mScope.back()) + { + return; + } + + // now ignore first token + ++name_token_it; + + // copy remaining tokens on to our running token list + for(tokenizer::iterator token_to_push = name_token_it; token_to_push != name_tokens.end(); ++token_to_push) + { + mNameStack.push_back(std::make_pair(*token_to_push, true)); + num_tokens_pushed++; + } + mScope.push_back(mNameStack.back().first); + } + } + + // parent node is not empty + mEmptyLeafNode.back() = false; + // we are empty if we have no attributes + mEmptyLeafNode.push_back(atts[0] == NULL); + + mTokenSizeStack.push_back(num_tokens_pushed); + readAttributes(atts); + +} + +void LLSimpleXUIParser::endElement(const char *name) +{ + bool has_text = processText(); + + // no text, attributes, or children + if (!has_text && mEmptyLeafNode.back()) + { + // submit this as a valueless name (even though there might be text contents we haven't seen yet) + mCurAttributeValueBegin = NO_VALUE_MARKER; + mOutputStack.back().first->submitValue(mNameStack, *this, mParseSilently); + } + + if (--mOutputStack.back().second == 0) + { + if (mOutputStack.empty()) + { + LL_ERRS("ReadXUI") << "Parameter block output stack popped while empty." << LL_ENDL; + } + mOutputStack.pop_back(); + } + + S32 num_tokens_to_pop = mTokenSizeStack.back(); + mTokenSizeStack.pop_back(); + while(num_tokens_to_pop-- > 0) + { + mNameStack.pop_back(); + } + mScope.pop_back(); + mEmptyLeafNode.pop_back(); +} + +bool LLSimpleXUIParser::readAttributes(const char **atts) +{ + typedef boost::tokenizer > tokenizer; + boost::char_separator sep("."); + + bool any_parsed = false; + for(S32 i = 0; atts[i] && atts[i+1]; i += 2 ) + { + std::string attribute_name(atts[i]); + mCurAttributeValueBegin = atts[i+1]; + + S32 num_tokens_pushed = 0; + tokenizer name_tokens(attribute_name, sep); + // copy remaining tokens on to our running token list + for(tokenizer::iterator token_to_push = name_tokens.begin(); token_to_push != name_tokens.end(); ++token_to_push) + { + mNameStack.push_back(std::make_pair(*token_to_push, true)); + num_tokens_pushed++; + } + + // child nodes are not necessarily valid attributes, so don't complain once we've recursed + any_parsed |= mOutputStack.back().first->submitValue(mNameStack, *this, mParseSilently); + + while(num_tokens_pushed-- > 0) + { + mNameStack.pop_back(); + } + } + return any_parsed; +} + +bool LLSimpleXUIParser::processText() +{ + if (!mTextContents.empty()) + { + LLStringUtil::trim(mTextContents); + if (!mTextContents.empty()) + { + mNameStack.push_back(std::make_pair(std::string("value"), true)); + mCurAttributeValueBegin = mTextContents.c_str(); + mOutputStack.back().first->submitValue(mNameStack, *this, mParseSilently); + mNameStack.pop_back(); + } + mTextContents.clear(); + return true; + } + return false; +} + +/*virtual*/ std::string LLSimpleXUIParser::getCurrentElementName() +{ + std::string full_name; + for (name_stack_t::iterator it = mNameStack.begin(); + it != mNameStack.end(); + ++it) + { + full_name += it->first + "."; // build up dotted names: "button.param.nestedparam." + } + + return full_name; +} + +void LLSimpleXUIParser::parserWarning(const std::string& message) +{ +#ifdef LL_WINDOWS + // use Visual Studo friendly formatting of output message for easy access to originating xml + llutf16string utf16str = utf8str_to_utf16str(llformat("%s(%d):\t%s", mCurFileName.c_str(), LINE_NUMBER_HERE, message.c_str()).c_str()); + utf16str += '\n'; + OutputDebugString(utf16str.c_str()); +#else + Parser::parserWarning(message); +#endif +} + +void LLSimpleXUIParser::parserError(const std::string& message) +{ +#ifdef LL_WINDOWS + llutf16string utf16str = utf8str_to_utf16str(llformat("%s(%d):\t%s", mCurFileName.c_str(), LINE_NUMBER_HERE, message.c_str()).c_str()); + utf16str += '\n'; + OutputDebugString(utf16str.c_str()); +#else + Parser::parserError(message); +#endif +} + +bool LLSimpleXUIParser::readFlag(Parser& parser, void* val_ptr) +{ + LLSimpleXUIParser& self = static_cast(parser); + return self.mCurAttributeValueBegin == NO_VALUE_MARKER; +} + +bool LLSimpleXUIParser::readBoolValue(Parser& parser, void* val_ptr) +{ + LLSimpleXUIParser& self = static_cast(parser); + if (!strcmp(self.mCurAttributeValueBegin, "true")) + { + *((bool*)val_ptr) = true; + return true; + } + else if (!strcmp(self.mCurAttributeValueBegin, "false")) + { + *((bool*)val_ptr) = false; + return true; + } + + return false; +} + +bool LLSimpleXUIParser::readStringValue(Parser& parser, void* val_ptr) +{ + LLSimpleXUIParser& self = static_cast(parser); + *((std::string*)val_ptr) = self.mCurAttributeValueBegin; + return true; +} + +bool LLSimpleXUIParser::readU8Value(Parser& parser, void* val_ptr) +{ + LLSimpleXUIParser& self = static_cast(parser); + return parse(self.mCurAttributeValueBegin, uint_p[assign_a(*(U8*)val_ptr)]).full; +} + +bool LLSimpleXUIParser::readS8Value(Parser& parser, void* val_ptr) +{ + LLSimpleXUIParser& self = static_cast(parser); + return parse(self.mCurAttributeValueBegin, int_p[assign_a(*(S8*)val_ptr)]).full; +} + +bool LLSimpleXUIParser::readU16Value(Parser& parser, void* val_ptr) +{ + LLSimpleXUIParser& self = static_cast(parser); + return parse(self.mCurAttributeValueBegin, uint_p[assign_a(*(U16*)val_ptr)]).full; +} + +bool LLSimpleXUIParser::readS16Value(Parser& parser, void* val_ptr) +{ + LLSimpleXUIParser& self = static_cast(parser); + return parse(self.mCurAttributeValueBegin, int_p[assign_a(*(S16*)val_ptr)]).full; +} + +bool LLSimpleXUIParser::readU32Value(Parser& parser, void* val_ptr) +{ + LLSimpleXUIParser& self = static_cast(parser); + return parse(self.mCurAttributeValueBegin, uint_p[assign_a(*(U32*)val_ptr)]).full; +} + +bool LLSimpleXUIParser::readS32Value(Parser& parser, void* val_ptr) +{ + LLSimpleXUIParser& self = static_cast(parser); + return parse(self.mCurAttributeValueBegin, int_p[assign_a(*(S32*)val_ptr)]).full; +} + +bool LLSimpleXUIParser::readF32Value(Parser& parser, void* val_ptr) +{ + LLSimpleXUIParser& self = static_cast(parser); + return parse(self.mCurAttributeValueBegin, real_p[assign_a(*(F32*)val_ptr)]).full; +} + +bool LLSimpleXUIParser::readF64Value(Parser& parser, void* val_ptr) +{ + LLSimpleXUIParser& self = static_cast(parser); + return parse(self.mCurAttributeValueBegin, real_p[assign_a(*(F64*)val_ptr)]).full; +} + +bool LLSimpleXUIParser::readColor4Value(Parser& parser, void* val_ptr) +{ + LLSimpleXUIParser& self = static_cast(parser); + LLColor4 value; + + if (parse(self.mCurAttributeValueBegin, real_p[assign_a(value.mV[0])] >> real_p[assign_a(value.mV[1])] >> real_p[assign_a(value.mV[2])] >> real_p[assign_a(value.mV[3])], space_p).full) + { + *(LLColor4*)(val_ptr) = value; + return true; + } + return false; +} + +bool LLSimpleXUIParser::readUIColorValue(Parser& parser, void* val_ptr) +{ + LLSimpleXUIParser& self = static_cast(parser); + LLColor4 value; + LLUIColor* colorp = (LLUIColor*)val_ptr; + + if (parse(self.mCurAttributeValueBegin, real_p[assign_a(value.mV[0])] >> real_p[assign_a(value.mV[1])] >> real_p[assign_a(value.mV[2])] >> real_p[assign_a(value.mV[3])], space_p).full) + { + colorp->set(value); + return true; + } + return false; +} + +bool LLSimpleXUIParser::readUUIDValue(Parser& parser, void* val_ptr) +{ + LLSimpleXUIParser& self = static_cast(parser); + LLUUID temp_id; + // LLUUID::set is destructive, so use temporary value + if (temp_id.set(std::string(self.mCurAttributeValueBegin))) + { + *(LLUUID*)(val_ptr) = temp_id; + return true; + } + return false; +} + +bool LLSimpleXUIParser::readSDValue(Parser& parser, void* val_ptr) +{ + LLSimpleXUIParser& self = static_cast(parser); + *((LLSD*)val_ptr) = LLSD(self.mCurAttributeValueBegin); + return true; +} diff --git a/indra/llui/llxuiparser.h b/indra/llui/llxuiparser.h new file mode 100644 index 0000000000..d7cd256967 --- /dev/null +++ b/indra/llui/llxuiparser.h @@ -0,0 +1,242 @@ +/** + * @file llxuiparser.h + * @brief Utility functions for handling XUI structures in XML + * + * $LicenseInfo:firstyear=2003&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#ifndef LLXUIPARSER_H +#define LLXUIPARSER_H + +#include "llinitparam.h" +#include "llregistry.h" +#include "llpointer.h" + +#include +#include +#include +#include + + + +class LLView; + + +typedef LLPointer LLXMLNodePtr; + + +// lookup widget type by name +class LLWidgetTypeRegistry +: public LLRegistrySingleton +{}; + + +// global static instance for registering all widget types +typedef boost::function LLWidgetCreatorFunc; + +typedef LLRegistry widget_registry_t; + +class LLChildRegistryRegistry +: public LLRegistrySingleton +{}; + + + +class LLXSDWriter : public LLInitParam::Parser +{ + LOG_CLASS(LLXSDWriter); +public: + void writeXSD(const std::string& name, LLXMLNodePtr node, const LLInitParam::BaseBlock& block, const std::string& xml_namespace); + + /*virtual*/ std::string getCurrentElementName() { return LLStringUtil::null; } + + LLXSDWriter(); + +protected: + void writeAttribute(const std::string& type, const Parser::name_stack_t&, S32 min_count, S32 max_count, const std::vector* possible_values); + void addAttributeToSchema(LLXMLNodePtr nodep, const std::string& attribute_name, const std::string& type, bool mandatory, const std::vector* possible_values); + LLXMLNodePtr mAttributeNode; + LLXMLNodePtr mElementNode; + LLXMLNodePtr mSchemaNode; + + typedef std::set string_set_t; + typedef std::map attributes_map_t; + attributes_map_t mAttributesWritten; +}; + + + +// NOTE: DOES NOT WORK YET +// should support child widgets for XUI +class LLXUIXSDWriter : public LLXSDWriter +{ +public: + void writeXSD(const std::string& name, const std::string& path, const LLInitParam::BaseBlock& block); +}; + + +class LLXUIParserImpl; + +class LLXUIParser : public LLInitParam::Parser +{ +LOG_CLASS(LLXUIParser); + +public: + LLXUIParser(); + typedef LLInitParam::Parser::name_stack_t name_stack_t; + + /*virtual*/ std::string getCurrentElementName(); + /*virtual*/ void parserWarning(const std::string& message); + /*virtual*/ void parserError(const std::string& message); + + void readXUI(LLXMLNodePtr node, LLInitParam::BaseBlock& block, const std::string& filename = LLStringUtil::null, bool silent=false); + void writeXUI(LLXMLNodePtr node, const LLInitParam::BaseBlock& block, const LLInitParam::BaseBlock* diff_block = NULL); + +private: + bool readXUIImpl(LLXMLNodePtr node, LLInitParam::BaseBlock& block); + bool readAttributes(LLXMLNodePtr nodep, LLInitParam::BaseBlock& block); + + //reader helper functions + static bool readFlag(Parser& parser, void* val_ptr); + static bool readBoolValue(Parser& parser, void* val_ptr); + static bool readStringValue(Parser& parser, void* val_ptr); + static bool readU8Value(Parser& parser, void* val_ptr); + static bool readS8Value(Parser& parser, void* val_ptr); + static bool readU16Value(Parser& parser, void* val_ptr); + static bool readS16Value(Parser& parser, void* val_ptr); + static bool readU32Value(Parser& parser, void* val_ptr); + static bool readS32Value(Parser& parser, void* val_ptr); + static bool readF32Value(Parser& parser, void* val_ptr); + static bool readF64Value(Parser& parser, void* val_ptr); + static bool readColor4Value(Parser& parser, void* val_ptr); + static bool readUIColorValue(Parser& parser, void* val_ptr); + static bool readUUIDValue(Parser& parser, void* val_ptr); + static bool readSDValue(Parser& parser, void* val_ptr); + + //writer helper functions + static bool writeFlag(Parser& parser, const void* val_ptr, name_stack_t&); + static bool writeBoolValue(Parser& parser, const void* val_ptr, name_stack_t&); + static bool writeStringValue(Parser& parser, const void* val_ptr, name_stack_t&); + static bool writeU8Value(Parser& parser, const void* val_ptr, name_stack_t&); + static bool writeS8Value(Parser& parser, const void* val_ptr, name_stack_t&); + static bool writeU16Value(Parser& parser, const void* val_ptr, name_stack_t&); + static bool writeS16Value(Parser& parser, const void* val_ptr, name_stack_t&); + static bool writeU32Value(Parser& parser, const void* val_ptr, name_stack_t&); + static bool writeS32Value(Parser& parser, const void* val_ptr, name_stack_t&); + static bool writeF32Value(Parser& parser, const void* val_ptr, name_stack_t&); + static bool writeF64Value(Parser& parser, const void* val_ptr, name_stack_t&); + static bool writeColor4Value(Parser& parser, const void* val_ptr, name_stack_t&); + static bool writeUIColorValue(Parser& parser, const void* val_ptr, name_stack_t&); + static bool writeUUIDValue(Parser& parser, const void* val_ptr, name_stack_t&); + static bool writeSDValue(Parser& parser, const void* val_ptr, name_stack_t&); + + LLXMLNodePtr getNode(name_stack_t& stack); + +private: + Parser::name_stack_t mNameStack; + LLXMLNodePtr mCurReadNode; + // Root of the widget XML sub-tree, for example, "line_editor" + LLXMLNodePtr mWriteRootNode; + + typedef std::map out_nodes_t; + out_nodes_t mOutNodes; + LLXMLNodePtr mLastWrittenChild; + S32 mCurReadDepth; + std::string mCurFileName; + std::string mRootNodeName; +}; + +// LLSimpleXUIParser is a streamlined SAX-based XUI parser that does not support localization +// or parsing of a tree of independent param blocks, such as child widgets. +// Use this for reading non-localized files that only need a single param block as a result. +// +// NOTE: In order to support nested block parsing, we need callbacks for start element that +// push new blocks contexts on the mScope stack. +// NOTE: To support localization without building a DOM, we need to enforce consistent +// ordering of child elements from base file to localized diff file. Then we can use a pair +// of coroutines to perform matching of xml nodes during parsing. Not sure if the overhead +// of coroutines would offset the gain from SAX parsing +class LLSimpleXUIParserImpl; + +class LLSimpleXUIParser : public LLInitParam::Parser +{ +LOG_CLASS(LLSimpleXUIParser); +public: + typedef LLInitParam::Parser::name_stack_t name_stack_t; + typedef LLInitParam::BaseBlock* (*element_start_callback_t)(LLSimpleXUIParser&, const char* block_name); + + LLSimpleXUIParser(element_start_callback_t element_cb = NULL); + virtual ~LLSimpleXUIParser(); + + /*virtual*/ std::string getCurrentElementName(); + /*virtual*/ void parserWarning(const std::string& message); + /*virtual*/ void parserError(const std::string& message); + + bool readXUI(const std::string& filename, LLInitParam::BaseBlock& block, bool silent=false); + + +private: + //reader helper functions + static bool readFlag(Parser&, void* val_ptr); + static bool readBoolValue(Parser&, void* val_ptr); + static bool readStringValue(Parser&, void* val_ptr); + static bool readU8Value(Parser&, void* val_ptr); + static bool readS8Value(Parser&, void* val_ptr); + static bool readU16Value(Parser&, void* val_ptr); + static bool readS16Value(Parser&, void* val_ptr); + static bool readU32Value(Parser&, void* val_ptr); + static bool readS32Value(Parser&, void* val_ptr); + static bool readF32Value(Parser&, void* val_ptr); + static bool readF64Value(Parser&, void* val_ptr); + static bool readColor4Value(Parser&, void* val_ptr); + static bool readUIColorValue(Parser&, void* val_ptr); + static bool readUUIDValue(Parser&, void* val_ptr); + static bool readSDValue(Parser&, void* val_ptr); + +private: + static void startElementHandler(void *userData, const char *name, const char **atts); + static void endElementHandler(void *userData, const char *name); + static void characterDataHandler(void *userData, const char *s, int len); + + void startElement(const char *name, const char **atts); + void endElement(const char *name); + void characterData(const char *s, int len); + bool readAttributes(const char **atts); + bool processText(); + + Parser::name_stack_t mNameStack; + struct XML_ParserStruct* mParser; + LLXMLNodePtr mLastWrittenChild; + S32 mCurReadDepth; + std::string mCurFileName; + std::string mTextContents; + const char* mCurAttributeValueBegin; + std::vector mTokenSizeStack; + std::vector mScope; + std::vector mEmptyLeafNode; + element_start_callback_t mElementCB; + + std::vector > mOutputStack; +}; + + +#endif //LLXUIPARSER_H diff --git a/indra/llui/tests/llurlentry_stub.cpp b/indra/llui/tests/llurlentry_stub.cpp index c75df86891..cb3b7abb14 100644 --- a/indra/llui/tests/llurlentry_stub.cpp +++ b/indra/llui/tests/llurlentry_stub.cpp @@ -105,28 +105,6 @@ LLStyle::Params::Params() namespace LLInitParam { - Param::Param(BaseBlock* enclosing_block) - : mIsProvided(false) - { - const U8* my_addr = reinterpret_cast(this); - const U8* block_addr = reinterpret_cast(enclosing_block); - mEnclosingBlockOffset = (U16)(my_addr - block_addr); - } - - void BaseBlock::addParam(BlockDescriptor& block_data, const ParamDescriptorPtr in_param, const char* char_name){} - void BaseBlock::addSynonym(Param& param, const std::string& synonym) {} - param_handle_t BaseBlock::getHandleFromParam(const Param* param) const {return 0;} - - void BaseBlock::init(BlockDescriptor& descriptor, BlockDescriptor& base_descriptor, size_t block_size) - { - descriptor.mCurrentBlockPtr = this; - } - bool BaseBlock::deserializeBlock(Parser& p, Parser::name_stack_range_t name_stack, bool new_name){ return true; } - void BaseBlock::serializeBlock(Parser& parser, Parser::name_stack_t& name_stack, const LLInitParam::BaseBlock* diff_block) const {} - bool BaseBlock::inspectBlock(Parser& parser, Parser::name_stack_t name_stack, S32 min_value, S32 max_value) const { return true; } - bool BaseBlock::mergeBlock(BlockDescriptor& block_data, const BaseBlock& other, bool overwrite) { return true; } - bool BaseBlock::validateBlock(bool emit_errors) const { return true; } - ParamValue >::ParamValue(const LLUIColor& color) : super_t(color) {} diff --git a/indra/llui/tests/llurlentry_test.cpp b/indra/llui/tests/llurlentry_test.cpp index c1fb050206..8f0a48018f 100644 --- a/indra/llui/tests/llurlentry_test.cpp +++ b/indra/llui/tests/llurlentry_test.cpp @@ -70,21 +70,6 @@ S32 LLUIImage::getHeight() const return 0; } -namespace LLInitParam -{ - BlockDescriptor::BlockDescriptor() {} - ParamDescriptor::ParamDescriptor(param_handle_t p, - merge_func_t merge_func, - deserialize_func_t deserialize_func, - serialize_func_t serialize_func, - validation_func_t validation_func, - inspect_func_t inspect_func, - S32 min_count, - S32 max_count){} - ParamDescriptor::~ParamDescriptor() {} - -} - namespace tut { struct LLUrlEntryData diff --git a/indra/llui/tests/llurlmatch_test.cpp b/indra/llui/tests/llurlmatch_test.cpp index 7183413463..963473c92a 100644 --- a/indra/llui/tests/llurlmatch_test.cpp +++ b/indra/llui/tests/llurlmatch_test.cpp @@ -63,40 +63,6 @@ S32 LLUIImage::getHeight() const namespace LLInitParam { - BlockDescriptor::BlockDescriptor() {} - ParamDescriptor::ParamDescriptor(param_handle_t p, - merge_func_t merge_func, - deserialize_func_t deserialize_func, - serialize_func_t serialize_func, - validation_func_t validation_func, - inspect_func_t inspect_func, - S32 min_count, - S32 max_count){} - ParamDescriptor::~ParamDescriptor() {} - - void BaseBlock::addParam(BlockDescriptor& block_data, const ParamDescriptorPtr in_param, const char* char_name){} - param_handle_t BaseBlock::getHandleFromParam(const Param* param) const {return 0;} - void BaseBlock::addSynonym(Param& param, const std::string& synonym) {} - - void BaseBlock::init(BlockDescriptor& descriptor, BlockDescriptor& base_descriptor, size_t block_size) - { - descriptor.mCurrentBlockPtr = this; - } - - Param::Param(BaseBlock* enclosing_block) - : mIsProvided(false) - { - const U8* my_addr = reinterpret_cast(this); - const U8* block_addr = reinterpret_cast(enclosing_block); - mEnclosingBlockOffset = 0x7FFFffff & ((U32)(my_addr - block_addr)); - } - - bool BaseBlock::deserializeBlock(Parser& p, Parser::name_stack_range_t name_stack, bool new_name){ return true; } - void BaseBlock::serializeBlock(Parser& parser, Parser::name_stack_t& name_stack, const LLInitParam::BaseBlock* diff_block) const {} - bool BaseBlock::inspectBlock(Parser& parser, Parser::name_stack_t name_stack, S32 min_count, S32 max_count) const { return true; } - bool BaseBlock::mergeBlock(BlockDescriptor& block_data, const BaseBlock& other, bool overwrite) { return true; } - bool BaseBlock::validateBlock(bool emit_errors) const { return true; } - ParamValue >::ParamValue(const LLUIColor& color) : super_t(color) {} diff --git a/indra/llxuixml/CMakeLists.txt b/indra/llxuixml/CMakeLists.txt deleted file mode 100644 index daed4de6ce..0000000000 --- a/indra/llxuixml/CMakeLists.txt +++ /dev/null @@ -1,45 +0,0 @@ -# -*- cmake -*- - -project(llxuixml) - -include(00-Common) -include(LLCommon) -include(LLMath) -include(LLXML) - -include_directories( - ${LLCOMMON_INCLUDE_DIRS} - ${LLMATH_INCLUDE_DIRS} - ${LLXML_INCLUDE_DIRS} - ) - -set(llxuixml_SOURCE_FILES - llinitparam.cpp - lltrans.cpp - lluicolor.cpp - llxuiparser.cpp - ) - -set(llxuixml_HEADER_FILES - CMakeLists.txt - - llinitparam.h - lltrans.h - llregistry.h - lluicolor.h - llxuiparser.h - ) - -set_source_files_properties(${llxuixml_HEADER_FILES} - PROPERTIES HEADER_FILE_ONLY TRUE) - -list(APPEND llxuixml_SOURCE_FILES ${llxuixml_HEADER_FILES}) - -add_library (llxuixml ${llxuixml_SOURCE_FILES}) -# Libraries on which this library depends, needed for Linux builds -# Sort by high-level to low-level -target_link_libraries(llxuixml - llxml - llcommon - llmath - ) diff --git a/indra/llxuixml/llinitparam.cpp b/indra/llxuixml/llinitparam.cpp deleted file mode 100644 index db72aa19b9..0000000000 --- a/indra/llxuixml/llinitparam.cpp +++ /dev/null @@ -1,469 +0,0 @@ -/** - * @file llinitparam.cpp - * @brief parameter block abstraction for creating complex objects and - * parsing construction parameters from xml and LLSD - * - * $LicenseInfo:firstyear=2008&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include "linden_common.h" - -#include "llinitparam.h" - - -namespace LLInitParam -{ - // - // Param - // - Param::Param(BaseBlock* enclosing_block) - : mIsProvided(false) - { - const U8* my_addr = reinterpret_cast(this); - const U8* block_addr = reinterpret_cast(enclosing_block); - mEnclosingBlockOffset = 0x7FFFffff & (U32)(my_addr - block_addr); - } - - // - // ParamDescriptor - // - ParamDescriptor::ParamDescriptor(param_handle_t p, - merge_func_t merge_func, - deserialize_func_t deserialize_func, - serialize_func_t serialize_func, - validation_func_t validation_func, - inspect_func_t inspect_func, - S32 min_count, - S32 max_count) - : mParamHandle(p), - mMergeFunc(merge_func), - mDeserializeFunc(deserialize_func), - mSerializeFunc(serialize_func), - mValidationFunc(validation_func), - mInspectFunc(inspect_func), - mMinCount(min_count), - mMaxCount(max_count), - mUserData(NULL) - {} - - ParamDescriptor::ParamDescriptor() - : mParamHandle(0), - mMergeFunc(NULL), - mDeserializeFunc(NULL), - mSerializeFunc(NULL), - mValidationFunc(NULL), - mInspectFunc(NULL), - mMinCount(0), - mMaxCount(0), - mUserData(NULL) - {} - - ParamDescriptor::~ParamDescriptor() - { - delete mUserData; - } - - // - // Parser - // - Parser::~Parser() - {} - - void Parser::parserWarning(const std::string& message) - { - if (mParseSilently) return; - llwarns << message << llendl; - } - - void Parser::parserError(const std::string& message) - { - if (mParseSilently) return; - llerrs << message << llendl; - } - - - // - // BlockDescriptor - // - void BlockDescriptor::aggregateBlockData(BlockDescriptor& src_block_data) - { - mNamedParams.insert(src_block_data.mNamedParams.begin(), src_block_data.mNamedParams.end()); - std::copy(src_block_data.mUnnamedParams.begin(), src_block_data.mUnnamedParams.end(), std::back_inserter(mUnnamedParams)); - std::copy(src_block_data.mValidationList.begin(), src_block_data.mValidationList.end(), std::back_inserter(mValidationList)); - std::copy(src_block_data.mAllParams.begin(), src_block_data.mAllParams.end(), std::back_inserter(mAllParams)); - } - - BlockDescriptor::BlockDescriptor() - : mMaxParamOffset(0), - mInitializationState(UNINITIALIZED), - mCurrentBlockPtr(NULL) - {} - - // called by each derived class in least to most derived order - void BaseBlock::init(BlockDescriptor& descriptor, BlockDescriptor& base_descriptor, size_t block_size) - { - descriptor.mCurrentBlockPtr = this; - descriptor.mMaxParamOffset = block_size; - - switch(descriptor.mInitializationState) - { - case BlockDescriptor::UNINITIALIZED: - // copy params from base class here - descriptor.aggregateBlockData(base_descriptor); - - descriptor.mInitializationState = BlockDescriptor::INITIALIZING; - break; - case BlockDescriptor::INITIALIZING: - descriptor.mInitializationState = BlockDescriptor::INITIALIZED; - break; - case BlockDescriptor::INITIALIZED: - // nothing to do - break; - } - } - - param_handle_t BaseBlock::getHandleFromParam(const Param* param) const - { - const U8* param_address = reinterpret_cast(param); - const U8* baseblock_address = reinterpret_cast(this); - return (param_address - baseblock_address); - } - - bool BaseBlock::submitValue(Parser::name_stack_t& name_stack, Parser& p, bool silent) - { - if (!deserializeBlock(p, std::make_pair(name_stack.begin(), name_stack.end()), true)) - { - if (!silent) - { - p.parserWarning(llformat("Failed to parse parameter \"%s\"", p.getCurrentElementName().c_str())); - } - return false; - } - return true; - } - - - bool BaseBlock::validateBlock(bool emit_errors) const - { - const BlockDescriptor& block_data = mostDerivedBlockDescriptor(); - for (BlockDescriptor::param_validation_list_t::const_iterator it = block_data.mValidationList.begin(); it != block_data.mValidationList.end(); ++it) - { - const Param* param = getParamFromHandle(it->first); - if (!it->second(param)) - { - if (emit_errors) - { - llwarns << "Invalid param \"" << getParamName(block_data, param) << "\"" << llendl; - } - return false; - } - } - return true; - } - - void BaseBlock::serializeBlock(Parser& parser, Parser::name_stack_t& name_stack, const LLInitParam::BaseBlock* diff_block) const - { - // named param is one like LLView::Params::follows - // unnamed param is like LLView::Params::rect - implicit - const BlockDescriptor& block_data = mostDerivedBlockDescriptor(); - - for (BlockDescriptor::param_list_t::const_iterator it = block_data.mUnnamedParams.begin(); - it != block_data.mUnnamedParams.end(); - ++it) - { - param_handle_t param_handle = (*it)->mParamHandle; - const Param* param = getParamFromHandle(param_handle); - ParamDescriptor::serialize_func_t serialize_func = (*it)->mSerializeFunc; - if (serialize_func) - { - const Param* diff_param = diff_block ? diff_block->getParamFromHandle(param_handle) : NULL; - // each param descriptor remembers its serial number - // so we can inspect the same param under different names - // and see that it has the same number - name_stack.push_back(std::make_pair("", true)); - serialize_func(*param, parser, name_stack, diff_param); - name_stack.pop_back(); - } - } - - for(BlockDescriptor::param_map_t::const_iterator it = block_data.mNamedParams.begin(); - it != block_data.mNamedParams.end(); - ++it) - { - param_handle_t param_handle = it->second->mParamHandle; - const Param* param = getParamFromHandle(param_handle); - ParamDescriptor::serialize_func_t serialize_func = it->second->mSerializeFunc; - if (serialize_func && param->anyProvided()) - { - // Ensure this param has not already been serialized - // Prevents from being serialized as its own tag. - bool duplicate = false; - for (BlockDescriptor::param_list_t::const_iterator it2 = block_data.mUnnamedParams.begin(); - it2 != block_data.mUnnamedParams.end(); - ++it2) - { - if (param_handle == (*it2)->mParamHandle) - { - duplicate = true; - break; - } - } - - //FIXME: for now, don't attempt to serialize values under synonyms, as current parsers - // don't know how to detect them - if (duplicate) - { - continue; - } - - name_stack.push_back(std::make_pair(it->first, !duplicate)); - const Param* diff_param = diff_block ? diff_block->getParamFromHandle(param_handle) : NULL; - serialize_func(*param, parser, name_stack, diff_param); - name_stack.pop_back(); - } - } - } - - bool BaseBlock::inspectBlock(Parser& parser, Parser::name_stack_t name_stack, S32 min_count, S32 max_count) const - { - // named param is one like LLView::Params::follows - // unnamed param is like LLView::Params::rect - implicit - const BlockDescriptor& block_data = mostDerivedBlockDescriptor(); - - for (BlockDescriptor::param_list_t::const_iterator it = block_data.mUnnamedParams.begin(); - it != block_data.mUnnamedParams.end(); - ++it) - { - param_handle_t param_handle = (*it)->mParamHandle; - const Param* param = getParamFromHandle(param_handle); - ParamDescriptor::inspect_func_t inspect_func = (*it)->mInspectFunc; - if (inspect_func) - { - name_stack.push_back(std::make_pair("", true)); - inspect_func(*param, parser, name_stack, (*it)->mMinCount, (*it)->mMaxCount); - name_stack.pop_back(); - } - } - - for(BlockDescriptor::param_map_t::const_iterator it = block_data.mNamedParams.begin(); - it != block_data.mNamedParams.end(); - ++it) - { - param_handle_t param_handle = it->second->mParamHandle; - const Param* param = getParamFromHandle(param_handle); - ParamDescriptor::inspect_func_t inspect_func = it->second->mInspectFunc; - if (inspect_func) - { - // Ensure this param has not already been inspected - bool duplicate = false; - for (BlockDescriptor::param_list_t::const_iterator it2 = block_data.mUnnamedParams.begin(); - it2 != block_data.mUnnamedParams.end(); - ++it2) - { - if (param_handle == (*it2)->mParamHandle) - { - duplicate = true; - break; - } - } - - name_stack.push_back(std::make_pair(it->first, !duplicate)); - inspect_func(*param, parser, name_stack, it->second->mMinCount, it->second->mMaxCount); - name_stack.pop_back(); - } - } - - return true; - } - - bool BaseBlock::deserializeBlock(Parser& p, Parser::name_stack_range_t name_stack_range, bool ignored) - { - BlockDescriptor& block_data = mostDerivedBlockDescriptor(); - bool names_left = name_stack_range.first != name_stack_range.second; - - bool new_name = names_left - ? name_stack_range.first->second - : true; - - if (names_left) - { - const std::string& top_name = name_stack_range.first->first; - - ParamDescriptor::deserialize_func_t deserialize_func = NULL; - Param* paramp = NULL; - - BlockDescriptor::param_map_t::iterator found_it = block_data.mNamedParams.find(top_name); - if (found_it != block_data.mNamedParams.end()) - { - // find pointer to member parameter from offset table - paramp = getParamFromHandle(found_it->second->mParamHandle); - deserialize_func = found_it->second->mDeserializeFunc; - - Parser::name_stack_range_t new_name_stack(name_stack_range.first, name_stack_range.second); - ++new_name_stack.first; - if (deserialize_func(*paramp, p, new_name_stack, new_name)) - { - // value is no longer new, we know about it now - name_stack_range.first->second = false; - return true; - } - else - { - return false; - } - } - } - - // try to parse unnamed parameters, in declaration order - for ( BlockDescriptor::param_list_t::iterator it = block_data.mUnnamedParams.begin(); - it != block_data.mUnnamedParams.end(); - ++it) - { - Param* paramp = getParamFromHandle((*it)->mParamHandle); - ParamDescriptor::deserialize_func_t deserialize_func = (*it)->mDeserializeFunc; - - if (deserialize_func && deserialize_func(*paramp, p, name_stack_range, new_name)) - { - return true; - } - } - - // if no match, and no names left on stack, this is just an existence assertion of this block - // verify by calling readValue with NoParamValue type, an inherently unparseable type - if (!names_left) - { - Flag no_value; - return p.readValue(no_value); - } - - return false; - } - - //static - void BaseBlock::addParam(BlockDescriptor& block_data, const ParamDescriptorPtr in_param, const char* char_name) - { - // create a copy of the param descriptor in mAllParams - // so other data structures can store a pointer to it - block_data.mAllParams.push_back(in_param); - ParamDescriptorPtr param(block_data.mAllParams.back()); - - std::string name(char_name); - if ((size_t)param->mParamHandle > block_data.mMaxParamOffset) - { - llerrs << "Attempted to register param with block defined for parent class, make sure to derive from LLInitParam::Block" << llendl; - } - - if (name.empty()) - { - block_data.mUnnamedParams.push_back(param); - } - else - { - // don't use insert, since we want to overwrite existing entries - block_data.mNamedParams[name] = param; - } - - if (param->mValidationFunc) - { - block_data.mValidationList.push_back(std::make_pair(param->mParamHandle, param->mValidationFunc)); - } - } - - void BaseBlock::addSynonym(Param& param, const std::string& synonym) - { - BlockDescriptor& block_data = mostDerivedBlockDescriptor(); - if (block_data.mInitializationState == BlockDescriptor::INITIALIZING) - { - param_handle_t handle = getHandleFromParam(¶m); - - // check for invalid derivation from a paramblock (i.e. without using - // Block - if ((size_t)handle > block_data.mMaxParamOffset) - { - llerrs << "Attempted to register param with block defined for parent class, make sure to derive from LLInitParam::Block" << llendl; - } - - ParamDescriptorPtr param_descriptor = findParamDescriptor(param); - if (param_descriptor) - { - if (synonym.empty()) - { - block_data.mUnnamedParams.push_back(param_descriptor); - } - else - { - block_data.mNamedParams[synonym] = param_descriptor; - } - } - } - } - - const std::string& BaseBlock::getParamName(const BlockDescriptor& block_data, const Param* paramp) const - { - param_handle_t handle = getHandleFromParam(paramp); - for (BlockDescriptor::param_map_t::const_iterator it = block_data.mNamedParams.begin(); it != block_data.mNamedParams.end(); ++it) - { - if (it->second->mParamHandle == handle) - { - return it->first; - } - } - - return LLStringUtil::null; - } - - ParamDescriptorPtr BaseBlock::findParamDescriptor(const Param& param) - { - param_handle_t handle = getHandleFromParam(¶m); - BlockDescriptor& descriptor = mostDerivedBlockDescriptor(); - BlockDescriptor::all_params_list_t::iterator end_it = descriptor.mAllParams.end(); - for (BlockDescriptor::all_params_list_t::iterator it = descriptor.mAllParams.begin(); - it != end_it; - ++it) - { - if ((*it)->mParamHandle == handle) return *it; - } - return ParamDescriptorPtr(); - } - - // take all provided params from other and apply to self - // NOTE: this requires that "other" is of the same derived type as this - bool BaseBlock::mergeBlock(BlockDescriptor& block_data, const BaseBlock& other, bool overwrite) - { - bool some_param_changed = false; - BlockDescriptor::all_params_list_t::const_iterator end_it = block_data.mAllParams.end(); - for (BlockDescriptor::all_params_list_t::const_iterator it = block_data.mAllParams.begin(); - it != end_it; - ++it) - { - const Param* other_paramp = other.getParamFromHandle((*it)->mParamHandle); - ParamDescriptor::merge_func_t merge_func = (*it)->mMergeFunc; - if (merge_func) - { - Param* paramp = getParamFromHandle((*it)->mParamHandle); - llassert(paramp->mEnclosingBlockOffset == (*it)->mParamHandle); - some_param_changed |= merge_func(*paramp, *other_paramp, overwrite); - } - } - return some_param_changed; - } -} diff --git a/indra/llxuixml/llinitparam.h b/indra/llxuixml/llinitparam.h deleted file mode 100644 index ab20957760..0000000000 --- a/indra/llxuixml/llinitparam.h +++ /dev/null @@ -1,2294 +0,0 @@ -/** - * @file llinitparam.h - * @brief parameter block abstraction for creating complex objects and - * parsing construction parameters from xml and LLSD - * - * $LicenseInfo:firstyear=2008&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#ifndef LL_LLPARAM_H -#define LL_LLPARAM_H - -#include -#include -#include -#include -#include - -#include "llerror.h" - -namespace LLInitParam -{ - // used to indicate no matching value to a given name when parsing - struct Flag{}; - - template const T& defaultValue() { static T value; return value; } - - template ::value > - struct ParamCompare - { - static bool equals(const T &a, const T &b) - { - return a == b; - } - }; - - // boost function types are not comparable - template - struct ParamCompare - { - static bool equals(const T&a, const T &b) - { - return false; - } - }; - - template<> - struct ParamCompare - { - static bool equals(const LLSD &a, const LLSD &b) { return false; } - }; - - template<> - struct ParamCompare - { - static bool equals(const Flag& a, const Flag& b) { return false; } - }; - - - // helper functions and classes - typedef ptrdiff_t param_handle_t; - - // empty default implementation of key cache - // leverages empty base class optimization - template - class TypeValues - { - private: - struct Inaccessable{}; - public: - typedef std::map value_name_map_t; - typedef Inaccessable name_t; - - void setValueName(const std::string& key) {} - std::string getValueName() const { return ""; } - std::string calcValueName(const T& value) const { return ""; } - void clearValueName() const {} - - static bool getValueFromName(const std::string& name, T& value) - { - return false; - } - - static bool valueNamesExist() - { - return false; - } - - static std::vector* getPossibleValues() - { - return NULL; - } - - static value_name_map_t* getValueNames() {return NULL;} - }; - - template > - class TypeValuesHelper - { - public: - typedef typename std::map value_name_map_t; - typedef std::string name_t; - - //TODO: cache key by index to save on param block size - void setValueName(const std::string& value_name) - { - mValueName = value_name; - } - - std::string getValueName() const - { - return mValueName; - } - - std::string calcValueName(const T& value) const - { - value_name_map_t* map = getValueNames(); - for (typename value_name_map_t::iterator it = map->begin(), end_it = map->end(); - it != end_it; - ++it) - { - if (ParamCompare::equals(it->second, value)) - { - return it->first; - } - } - - return ""; - } - - void clearValueName() const - { - mValueName.clear(); - } - - static bool getValueFromName(const std::string& name, T& value) - { - value_name_map_t* map = getValueNames(); - typename value_name_map_t::iterator found_it = map->find(name); - if (found_it == map->end()) return false; - - value = found_it->second; - return true; - } - - static bool valueNamesExist() - { - return !getValueNames()->empty(); - } - - static value_name_map_t* getValueNames() - { - static value_name_map_t sMap; - static bool sInitialized = false; - - if (!sInitialized) - { - sInitialized = true; - DERIVED_TYPE::declareValues(); - } - return &sMap; - } - - static std::vector* getPossibleValues() - { - static std::vector sValues; - - value_name_map_t* map = getValueNames(); - for (typename value_name_map_t::iterator it = map->begin(), end_it = map->end(); - it != end_it; - ++it) - { - sValues.push_back(it->first); - } - return &sValues; - } - - static void declare(const std::string& name, const T& value) - { - (*getValueNames())[name] = value; - } - - protected: - static void getName(const std::string& name, const T& value) - {} - - mutable std::string mValueName; - }; - - class Parser - { - LOG_CLASS(Parser); - - public: - - struct CompareTypeID - { - bool operator()(const std::type_info* lhs, const std::type_info* rhs) const - { - return lhs->before(*rhs); - } - }; - - typedef std::vector > name_stack_t; - typedef std::pair name_stack_range_t; - typedef std::vector possible_values_t; - - typedef bool (*parser_read_func_t)(Parser& parser, void* output); - typedef bool (*parser_write_func_t)(Parser& parser, const void*, name_stack_t&); - typedef boost::function parser_inspect_func_t; - - typedef std::map parser_read_func_map_t; - typedef std::map parser_write_func_map_t; - typedef std::map parser_inspect_func_map_t; - - Parser(parser_read_func_map_t& read_map, parser_write_func_map_t& write_map, parser_inspect_func_map_t& inspect_map) - : mParseSilently(false), - mParserReadFuncs(&read_map), - mParserWriteFuncs(&write_map), - mParserInspectFuncs(&inspect_map) - {} - virtual ~Parser(); - - template bool readValue(T& param) - { - parser_read_func_map_t::iterator found_it = mParserReadFuncs->find(&typeid(T)); - if (found_it != mParserReadFuncs->end()) - { - return found_it->second(*this, (void*)¶m); - } - return false; - } - - template bool writeValue(const T& param, name_stack_t& name_stack) - { - parser_write_func_map_t::iterator found_it = mParserWriteFuncs->find(&typeid(T)); - if (found_it != mParserWriteFuncs->end()) - { - return found_it->second(*this, (const void*)¶m, name_stack); - } - return false; - } - - // dispatch inspection to registered inspection functions, for each parameter in a param block - template bool inspectValue(name_stack_t& name_stack, S32 min_count, S32 max_count, const possible_values_t* possible_values) - { - parser_inspect_func_map_t::iterator found_it = mParserInspectFuncs->find(&typeid(T)); - if (found_it != mParserInspectFuncs->end()) - { - found_it->second(name_stack, min_count, max_count, possible_values); - return true; - } - return false; - } - - virtual std::string getCurrentElementName() = 0; - virtual void parserWarning(const std::string& message); - virtual void parserError(const std::string& message); - void setParseSilently(bool silent) { mParseSilently = silent; } - - protected: - template - void registerParserFuncs(parser_read_func_t read_func, parser_write_func_t write_func = NULL) - { - mParserReadFuncs->insert(std::make_pair(&typeid(T), read_func)); - mParserWriteFuncs->insert(std::make_pair(&typeid(T), write_func)); - } - - template - void registerInspectFunc(parser_inspect_func_t inspect_func) - { - mParserInspectFuncs->insert(std::make_pair(&typeid(T), inspect_func)); - } - - bool mParseSilently; - - private: - parser_read_func_map_t* mParserReadFuncs; - parser_write_func_map_t* mParserWriteFuncs; - parser_inspect_func_map_t* mParserInspectFuncs; - }; - - class Param; - - // various callbacks and constraints associated with an individual param - struct ParamDescriptor - { - struct UserData - { - virtual ~UserData() {} - }; - - typedef bool(*merge_func_t)(Param&, const Param&, bool); - typedef bool(*deserialize_func_t)(Param&, Parser&, const Parser::name_stack_range_t&, bool); - typedef void(*serialize_func_t)(const Param&, Parser&, Parser::name_stack_t&, const Param* diff_param); - typedef void(*inspect_func_t)(const Param&, Parser&, Parser::name_stack_t&, S32 min_count, S32 max_count); - typedef bool(*validation_func_t)(const Param*); - - ParamDescriptor(param_handle_t p, - merge_func_t merge_func, - deserialize_func_t deserialize_func, - serialize_func_t serialize_func, - validation_func_t validation_func, - inspect_func_t inspect_func, - S32 min_count, - S32 max_count); - - ParamDescriptor(); - ~ParamDescriptor(); - - param_handle_t mParamHandle; - merge_func_t mMergeFunc; - deserialize_func_t mDeserializeFunc; - serialize_func_t mSerializeFunc; - inspect_func_t mInspectFunc; - validation_func_t mValidationFunc; - S32 mMinCount; - S32 mMaxCount; - S32 mNumRefs; - UserData* mUserData; - }; - - typedef boost::shared_ptr ParamDescriptorPtr; - - // each derived Block class keeps a static data structure maintaining offsets to various params - class BlockDescriptor - { - public: - BlockDescriptor(); - - typedef enum e_initialization_state - { - UNINITIALIZED, - INITIALIZING, - INITIALIZED - } EInitializationState; - - void aggregateBlockData(BlockDescriptor& src_block_data); - - typedef boost::unordered_map param_map_t; - typedef std::vector param_list_t; - typedef std::list all_params_list_t; - typedef std::vector > param_validation_list_t; - - param_map_t mNamedParams; // parameters with associated names - param_list_t mUnnamedParams; // parameters with_out_ associated names - param_validation_list_t mValidationList; // parameters that must be validated - all_params_list_t mAllParams; // all parameters, owns descriptors - size_t mMaxParamOffset; - EInitializationState mInitializationState; // whether or not static block data has been initialized - class BaseBlock* mCurrentBlockPtr; // pointer to block currently being constructed - }; - - class BaseBlock - { - public: - //TODO: implement in terms of owned_ptr - template - class Lazy - { - public: - Lazy() - : mPtr(NULL) - {} - - ~Lazy() - { - delete mPtr; - } - - Lazy(const Lazy& other) - { - if (other.mPtr) - { - mPtr = new T(*other.mPtr); - } - else - { - mPtr = NULL; - } - } - - Lazy& operator = (const Lazy& other) - { - if (other.mPtr) - { - mPtr = new T(*other.mPtr); - } - else - { - mPtr = NULL; - } - return *this; - } - - bool empty() const - { - return mPtr == NULL; - } - - void set(const T& other) - { - delete mPtr; - mPtr = new T(other); - } - - const T& get() const - { - return ensureInstance(); - } - - T& get() - { - return ensureInstance(); - } - - private: - // lazily allocate an instance of T - T* ensureInstance() const - { - if (mPtr == NULL) - { - mPtr = new T(); - } - return mPtr; - } - - private: - // if you get a compilation error with this, that means you are using a forward declared struct for T - // unfortunately, the type traits we rely on don't work with forward declared typed - //static const int dummy = sizeof(T); - - mutable T* mPtr; - }; - - // "Multiple" constraint types, put here in root class to avoid ambiguity during use - struct AnyAmount - { - enum { minCount = 0 }; - enum { maxCount = U32_MAX }; - }; - - template - struct AtLeast - { - enum { minCount = MIN_AMOUNT }; - enum { maxCount = U32_MAX }; - }; - - template - struct AtMost - { - enum { minCount = 0 }; - enum { maxCount = MAX_AMOUNT }; - }; - - template - struct Between - { - enum { minCount = MIN_AMOUNT }; - enum { maxCount = MAX_AMOUNT }; - }; - - template - struct Exactly - { - enum { minCount = EXACT_COUNT }; - enum { maxCount = EXACT_COUNT }; - }; - - // this typedef identifies derived classes as being blocks - typedef void baseblock_base_class_t; - LOG_CLASS(BaseBlock); - friend class Param; - - virtual ~BaseBlock() {} - bool submitValue(Parser::name_stack_t& name_stack, Parser& p, bool silent=false); - - param_handle_t getHandleFromParam(const Param* param) const; - bool validateBlock(bool emit_errors = true) const; - - Param* getParamFromHandle(const param_handle_t param_handle) - { - if (param_handle == 0) return NULL; - - U8* baseblock_address = reinterpret_cast(this); - return reinterpret_cast(baseblock_address + param_handle); - } - - const Param* getParamFromHandle(const param_handle_t param_handle) const - { - const U8* baseblock_address = reinterpret_cast(this); - return reinterpret_cast(baseblock_address + param_handle); - } - - void addSynonym(Param& param, const std::string& synonym); - - // Blocks can override this to do custom tracking of changes - virtual void paramChanged(const Param& changed_param, bool user_provided) {} - - bool deserializeBlock(Parser& p, Parser::name_stack_range_t name_stack_range, bool new_name); - void serializeBlock(Parser& p, Parser::name_stack_t& name_stack, const BaseBlock* diff_block = NULL) const; - bool inspectBlock(Parser& p, Parser::name_stack_t name_stack = Parser::name_stack_t(), S32 min_count = 0, S32 max_count = S32_MAX) const; - - virtual const BlockDescriptor& mostDerivedBlockDescriptor() const { return selfBlockDescriptor(); } - virtual BlockDescriptor& mostDerivedBlockDescriptor() { return selfBlockDescriptor(); } - - // take all provided params from other and apply to self - bool overwriteFrom(const BaseBlock& other) - { - return false; - } - - // take all provided params that are not already provided, and apply to self - bool fillFrom(const BaseBlock& other) - { - return false; - } - - static void addParam(BlockDescriptor& block_data, ParamDescriptorPtr param, const char* name); - - ParamDescriptorPtr findParamDescriptor(const Param& param); - - protected: - void init(BlockDescriptor& descriptor, BlockDescriptor& base_descriptor, size_t block_size); - - - bool mergeBlockParam(bool source_provided, bool dst_provided, BlockDescriptor& block_data, const BaseBlock& source, bool overwrite) - { - return mergeBlock(block_data, source, overwrite); - } - // take all provided params from other and apply to self - bool mergeBlock(BlockDescriptor& block_data, const BaseBlock& other, bool overwrite); - - static BlockDescriptor& selfBlockDescriptor() - { - static BlockDescriptor sBlockDescriptor; - return sBlockDescriptor; - } - - private: - const std::string& getParamName(const BlockDescriptor& block_data, const Param* paramp) const; - }; - - template - struct ParamCompare, false > - { - static bool equals(const BaseBlock::Lazy& a, const BaseBlock::Lazy& b) { return !a.empty() || !b.empty(); } - }; - - class Param - { - public: - void setProvided(bool is_provided = true) - { - mIsProvided = is_provided; - enclosingBlock().paramChanged(*this, is_provided); - } - - Param& operator =(const Param& other) - { - mIsProvided = other.mIsProvided; - // don't change mEnclosingblockoffset - return *this; - } - protected: - - bool anyProvided() const { return mIsProvided; } - - Param(BaseBlock* enclosing_block); - - // store pointer to enclosing block as offset to reduce space and allow for quick copying - BaseBlock& enclosingBlock() const - { - const U8* my_addr = reinterpret_cast(this); - // get address of enclosing BLOCK class using stored offset to enclosing BaseBlock class - return *const_cast - (reinterpret_cast - (my_addr - (ptrdiff_t)(S32)mEnclosingBlockOffset)); - } - - private: - friend class BaseBlock; - - U32 mEnclosingBlockOffset:31; - U32 mIsProvided:1; - - }; - - // these templates allow us to distinguish between template parameters - // that derive from BaseBlock and those that don't - template - struct IsBlock - { - static const bool value = false; - struct EmptyBase {}; - typedef EmptyBase base_class_t; - }; - - template - struct IsBlock - { - static const bool value = true; - typedef BaseBlock base_class_t; - }; - - template - struct IsBlock, typename T::baseblock_base_class_t > - { - static const bool value = true; - typedef BaseBlock base_class_t; - }; - - template::value> - class ParamValue : public NAME_VALUE_LOOKUP - { - public: - typedef const T& value_assignment_t; - typedef T value_t; - typedef ParamValue self_t; - - ParamValue(): mValue() {} - ParamValue(value_assignment_t other) : mValue(other) {} - - void setValue(value_assignment_t val) - { - mValue = val; - } - - value_assignment_t getValue() const - { - return mValue; - } - - T& getValue() - { - return mValue; - } - - operator value_assignment_t() const - { - return mValue; - } - - value_assignment_t operator()() const - { - return mValue; - } - - void operator ()(const typename NAME_VALUE_LOOKUP::name_t& name) - { - *this = name; - } - - self_t& operator =(const typename NAME_VALUE_LOOKUP::name_t& name) - { - if (NAME_VALUE_LOOKUP::getValueFromName(name, mValue)) - { - setValueName(name); - } - - return *this; - } - - protected: - T mValue; - }; - - template - class ParamValue - : public T, - public NAME_VALUE_LOOKUP - { - public: - typedef const T& value_assignment_t; - typedef T value_t; - typedef ParamValue self_t; - - ParamValue() - : T(), - mValidated(false) - {} - - ParamValue(value_assignment_t other) - : T(other), - mValidated(false) - {} - - void setValue(value_assignment_t val) - { - *this = val; - } - - value_assignment_t getValue() const - { - return *this; - } - - T& getValue() - { - return *this; - } - - operator value_assignment_t() const - { - return *this; - } - - value_assignment_t operator()() const - { - return *this; - } - - void operator ()(const typename NAME_VALUE_LOOKUP::name_t& name) - { - *this = name; - } - - self_t& operator =(const typename NAME_VALUE_LOOKUP::name_t& name) - { - if (NAME_VALUE_LOOKUP::getValueFromName(name, *this)) - { - setValueName(name); - } - - return *this; - } - - protected: - mutable bool mValidated; // lazy validation flag - }; - - template - class ParamValue - : public NAME_VALUE_LOOKUP - { - public: - typedef const std::string& value_assignment_t; - typedef std::string value_t; - typedef ParamValue self_t; - - ParamValue(): mValue() {} - ParamValue(value_assignment_t other) : mValue(other) {} - - void setValue(value_assignment_t val) - { - if (NAME_VALUE_LOOKUP::getValueFromName(val, mValue)) - { - NAME_VALUE_LOOKUP::setValueName(val); - } - else - { - mValue = val; - } - } - - value_assignment_t getValue() const - { - return mValue; - } - - std::string& getValue() - { - return mValue; - } - - operator value_assignment_t() const - { - return mValue; - } - - value_assignment_t operator()() const - { - return mValue; - } - - protected: - std::string mValue; - }; - - - template > - struct ParamIterator - { - typedef typename std::vector >::const_iterator const_iterator; - typedef typename std::vector >::iterator iterator; - }; - - // specialize for custom parsing/decomposition of specific classes - // e.g. TypedParam has left, top, right, bottom, etc... - template, - bool HAS_MULTIPLE_VALUES = false, - bool VALUE_IS_BLOCK = IsBlock >::value> - class TypedParam - : public Param, - public ParamValue - { - public: - typedef TypedParam self_t; - typedef ParamValue param_value_t; - typedef typename param_value_t::value_assignment_t value_assignment_t; - typedef NAME_VALUE_LOOKUP name_value_lookup_t; - - using param_value_t::operator(); - - TypedParam(BlockDescriptor& block_descriptor, const char* name, value_assignment_t value, ParamDescriptor::validation_func_t validate_func, S32 min_count, S32 max_count) - : Param(block_descriptor.mCurrentBlockPtr) - { - if (LL_UNLIKELY(block_descriptor.mInitializationState == BlockDescriptor::INITIALIZING)) - { - ParamDescriptorPtr param_descriptor = ParamDescriptorPtr(new ParamDescriptor( - block_descriptor.mCurrentBlockPtr->getHandleFromParam(this), - &mergeWith, - &deserializeParam, - &serializeParam, - validate_func, - &inspectParam, - min_count, max_count)); - BaseBlock::addParam(block_descriptor, param_descriptor, name); - } - - setValue(value); - } - - bool isProvided() const { return Param::anyProvided(); } - - static bool deserializeParam(Param& param, Parser& parser, const Parser::name_stack_range_t& name_stack_range, bool new_name) - { - self_t& typed_param = static_cast(param); - // no further names in stack, attempt to parse value now - if (name_stack_range.first == name_stack_range.second) - { - if (parser.readValue(typed_param.getValue())) - { - typed_param.clearValueName(); - typed_param.setProvided(); - return true; - } - - // try to parse a known named value - if(name_value_lookup_t::valueNamesExist()) - { - // try to parse a known named value - std::string name; - if (parser.readValue(name)) - { - // try to parse a per type named value - if (name_value_lookup_t::getValueFromName(name, typed_param.getValue())) - { - typed_param.setValueName(name); - typed_param.setProvided(); - return true; - } - - } - } - } - return false; - } - - static void serializeParam(const Param& param, Parser& parser, Parser::name_stack_t& name_stack, const Param* diff_param) - { - const self_t& typed_param = static_cast(param); - if (!typed_param.isProvided()) return; - - if (!name_stack.empty()) - { - name_stack.back().second = true; - } - - std::string key = typed_param.getValueName(); - - // first try to write out name of name/value pair - - if (!key.empty()) - { - if (!diff_param || !ParamCompare::equals(static_cast(diff_param)->getValueName(), key)) - { - parser.writeValue(key, name_stack); - } - } - // then try to serialize value directly - else if (!diff_param || !ParamCompare::equals(typed_param.getValue(), static_cast(diff_param)->getValue())) - { - if (!parser.writeValue(typed_param.getValue(), name_stack)) - { - std::string calculated_key = typed_param.calcValueName(typed_param.getValue()); - if (!diff_param || !ParamCompare::equals(static_cast(diff_param)->getValueName(), calculated_key)) - { - parser.writeValue(calculated_key, name_stack); - } - } - } - } - - static void inspectParam(const Param& param, Parser& parser, Parser::name_stack_t& name_stack, S32 min_count, S32 max_count) - { - // tell parser about our actual type - parser.inspectValue(name_stack, min_count, max_count, NULL); - // then tell it about string-based alternatives ("red", "blue", etc. for LLColor4) - if (name_value_lookup_t::getPossibleValues()) - { - parser.inspectValue(name_stack, min_count, max_count, name_value_lookup_t::getPossibleValues()); - } - } - - void set(value_assignment_t val, bool flag_as_provided = true) - { - param_value_t::clearValueName(); - setValue(val); - setProvided(flag_as_provided); - } - - self_t& operator =(const typename NAME_VALUE_LOOKUP::name_t& name) - { - return static_cast(param_value_t::operator =(name)); - } - - protected: - - self_t& operator =(const self_t& other) - { - param_value_t::operator =(other); - Param::operator =(other); - return *this; - } - - static bool mergeWith(Param& dst, const Param& src, bool overwrite) - { - const self_t& src_typed_param = static_cast(src); - self_t& dst_typed_param = static_cast(dst); - - if (src_typed_param.isProvided() - && (overwrite || !dst_typed_param.isProvided())) - { - dst_typed_param.set(src_typed_param.getValue()); - return true; - } - return false; - } - }; - - // parameter that is a block - template - class TypedParam - : public Param, - public ParamValue - { - public: - typedef ParamValue param_value_t; - typedef typename param_value_t::value_assignment_t value_assignment_t; - typedef TypedParam self_t; - typedef NAME_VALUE_LOOKUP name_value_lookup_t; - - using param_value_t::operator(); - - TypedParam(BlockDescriptor& block_descriptor, const char* name, value_assignment_t value, ParamDescriptor::validation_func_t validate_func, S32 min_count, S32 max_count) - : Param(block_descriptor.mCurrentBlockPtr), - param_value_t(value) - { - if (LL_UNLIKELY(block_descriptor.mInitializationState == BlockDescriptor::INITIALIZING)) - { - ParamDescriptorPtr param_descriptor = ParamDescriptorPtr(new ParamDescriptor( - block_descriptor.mCurrentBlockPtr->getHandleFromParam(this), - &mergeWith, - &deserializeParam, - &serializeParam, - validate_func, - &inspectParam, - min_count, max_count)); - BaseBlock::addParam(block_descriptor, param_descriptor, name); - } - } - - static bool deserializeParam(Param& param, Parser& parser, const Parser::name_stack_range_t& name_stack_range, bool new_name) - { - self_t& typed_param = static_cast(param); - // attempt to parse block... - if(typed_param.deserializeBlock(parser, name_stack_range, new_name)) - { - typed_param.clearValueName(); - typed_param.setProvided(); - return true; - } - - if(name_value_lookup_t::valueNamesExist()) - { - // try to parse a known named value - std::string name; - if (parser.readValue(name)) - { - // try to parse a per type named value - if (name_value_lookup_t::getValueFromName(name, typed_param.getValue())) - { - typed_param.setValueName(name); - typed_param.setProvided(); - return true; - } - - } - } - return false; - } - - static void serializeParam(const Param& param, Parser& parser, Parser::name_stack_t& name_stack, const Param* diff_param) - { - const self_t& typed_param = static_cast(param); - if (!typed_param.isProvided()) return; - - if (!name_stack.empty()) - { - name_stack.back().second = true; - } - - std::string key = typed_param.getValueName(); - if (!key.empty()) - { - if (!parser.writeValue(key, name_stack)) - { - return; - } - } - else - { - typed_param.serializeBlock(parser, name_stack, static_cast(diff_param)); - } - } - - static void inspectParam(const Param& param, Parser& parser, Parser::name_stack_t& name_stack, S32 min_count, S32 max_count) - { - // I am a param that is also a block, so just recurse into my contents - const self_t& typed_param = static_cast(param); - typed_param.inspectBlock(parser, name_stack, min_count, max_count); - } - - // a param-that-is-a-block is provided when the user has set one of its child params - // *and* the block as a whole validates - bool isProvided() const - { - // only validate block when it hasn't already passed validation with current data - if (Param::anyProvided() && !param_value_t::mValidated) - { - // a sub-block is "provided" when it has been filled in enough to be valid - param_value_t::mValidated = param_value_t::validateBlock(false); - } - return Param::anyProvided() && param_value_t::mValidated; - } - - // assign block contents to this param-that-is-a-block - void set(value_assignment_t val, bool flag_as_provided = true) - { - setValue(val); - param_value_t::clearValueName(); - // force revalidation of block - // next call to isProvided() will update provision status based on validity - param_value_t::mValidated = false; - setProvided(flag_as_provided); - } - - self_t& operator =(const typename NAME_VALUE_LOOKUP::name_t& name) - { - return static_cast(param_value_t::operator =(name)); - } - - // propagate changed status up to enclosing block - /*virtual*/ void paramChanged(const Param& changed_param, bool user_provided) - { - param_value_t::paramChanged(changed_param, user_provided); - if (user_provided) - { - // a child param has been explicitly changed - // so *some* aspect of this block is now provided - param_value_t::mValidated = false; - setProvided(); - param_value_t::clearValueName(); - } - else - { - Param::enclosingBlock().paramChanged(*this, user_provided); - } - } - - protected: - - self_t& operator =(const self_t& other) - { - param_value_t::operator =(other); - Param::operator =(other); - return *this; - } - - static bool mergeWith(Param& dst, const Param& src, bool overwrite) - { - const self_t& src_typed_param = static_cast(src); - self_t& dst_typed_param = static_cast(dst); - - if (src_typed_param.anyProvided()) - { - if (dst_typed_param.mergeBlockParam(src_typed_param.isProvided(), dst_typed_param.isProvided(), param_value_t::selfBlockDescriptor(), src_typed_param, overwrite)) - { - dst_typed_param.clearValueName(); - dst_typed_param.setProvided(true); - return true; - } - } - return false; - } - }; - - // container of non-block parameters - template - class TypedParam - : public Param - { - public: - typedef TypedParam self_t; - typedef ParamValue param_value_t; - typedef typename std::vector container_t; - typedef const container_t& value_assignment_t; - - typedef typename param_value_t::value_t value_t; - typedef NAME_VALUE_LOOKUP name_value_lookup_t; - - TypedParam(BlockDescriptor& block_descriptor, const char* name, value_assignment_t value, ParamDescriptor::validation_func_t validate_func, S32 min_count, S32 max_count) - : Param(block_descriptor.mCurrentBlockPtr) - { - std::copy(value.begin(), value.end(), std::back_inserter(mValues)); - - if (LL_UNLIKELY(block_descriptor.mInitializationState == BlockDescriptor::INITIALIZING)) - { - ParamDescriptorPtr param_descriptor = ParamDescriptorPtr(new ParamDescriptor( - block_descriptor.mCurrentBlockPtr->getHandleFromParam(this), - &mergeWith, - &deserializeParam, - &serializeParam, - validate_func, - &inspectParam, - min_count, max_count)); - BaseBlock::addParam(block_descriptor, param_descriptor, name); - } - } - - bool isProvided() const { return Param::anyProvided(); } - - static bool deserializeParam(Param& param, Parser& parser, const Parser::name_stack_range_t& name_stack_range, bool new_name) - { - self_t& typed_param = static_cast(param); - value_t value; - // no further names in stack, attempt to parse value now - if (name_stack_range.first == name_stack_range.second) - { - // attempt to read value directly - if (parser.readValue(value)) - { - typed_param.add(value); - return true; - } - - // try to parse a known named value - if(name_value_lookup_t::valueNamesExist()) - { - // try to parse a known named value - std::string name; - if (parser.readValue(name)) - { - // try to parse a per type named value - if (name_value_lookup_t::getValueFromName(name, value)) - { - typed_param.add(value); - typed_param.mValues.back().setValueName(name); - return true; - } - - } - } - } - return false; - } - - static void serializeParam(const Param& param, Parser& parser, Parser::name_stack_t& name_stack, const Param* diff_param) - { - const self_t& typed_param = static_cast(param); - if (!typed_param.isProvided() || name_stack.empty()) return; - - for (const_iterator it = typed_param.mValues.begin(), end_it = typed_param.mValues.end(); - it != end_it; - ++it) - { - std::string key = it->getValueName(); - name_stack.back().second = true; - - if(key.empty()) - // not parsed via name values, write out value directly - { - bool value_written = parser.writeValue(*it, name_stack); - if (!value_written) - { - std::string calculated_key = it->calcValueName(it->getValue()); - if (!parser.writeValue(calculated_key, name_stack)) - { - break; - } - } - } - else - { - if(!parser.writeValue(key, name_stack)) - { - break; - } - } - } - } - - static void inspectParam(const Param& param, Parser& parser, Parser::name_stack_t& name_stack, S32 min_count, S32 max_count) - { - parser.inspectValue(name_stack, min_count, max_count, NULL); - if (name_value_lookup_t::getPossibleValues()) - { - parser.inspectValue(name_stack, min_count, max_count, name_value_lookup_t::getPossibleValues()); - } - } - - void set(value_assignment_t val, bool flag_as_provided = true) - { - mValues = val; - setProvided(flag_as_provided); - } - - param_value_t& add() - { - mValues.push_back(param_value_t(value_t())); - Param::setProvided(); - return mValues.back(); - } - - void add(const value_t& item) - { - param_value_t param_value; - param_value.setValue(item); - mValues.push_back(param_value); - setProvided(); - } - - void add(const typename name_value_lookup_t::name_t& name) - { - value_t value; - - // try to parse a per type named value - if (name_value_lookup_t::getValueFromName(name, value)) - { - add(value); - mValues.back().setValueName(name); - } - } - - // implicit conversion - operator value_assignment_t() const { return mValues; } - // explicit conversion - value_assignment_t operator()() const { return mValues; } - - typedef typename container_t::iterator iterator; - typedef typename container_t::const_iterator const_iterator; - iterator begin() { return mValues.begin(); } - iterator end() { return mValues.end(); } - const_iterator begin() const { return mValues.begin(); } - const_iterator end() const { return mValues.end(); } - bool empty() const { return mValues.empty(); } - size_t size() const { return mValues.size(); } - - U32 numValidElements() const - { - return mValues.size(); - } - - protected: - static bool mergeWith(Param& dst, const Param& src, bool overwrite) - { - const self_t& src_typed_param = static_cast(src); - self_t& dst_typed_param = static_cast(dst); - - if (overwrite) - { - std::copy(src_typed_param.begin(), src_typed_param.end(), std::back_inserter(dst_typed_param.mValues)); - } - else - { - container_t new_values(src_typed_param.mValues); - std::copy(dst_typed_param.begin(), dst_typed_param.end(), std::back_inserter(new_values)); - std::swap(dst_typed_param.mValues, new_values); - } - - if (src_typed_param.begin() != src_typed_param.end()) - { - dst_typed_param.setProvided(); - } - return true; - } - - container_t mValues; - }; - - // container of block parameters - template - class TypedParam - : public Param - { - public: - typedef TypedParam self_t; - typedef ParamValue param_value_t; - typedef typename std::vector container_t; - typedef const container_t& value_assignment_t; - typedef typename param_value_t::value_t value_t; - typedef NAME_VALUE_LOOKUP name_value_lookup_t; - - TypedParam(BlockDescriptor& block_descriptor, const char* name, value_assignment_t value, ParamDescriptor::validation_func_t validate_func, S32 min_count, S32 max_count) - : Param(block_descriptor.mCurrentBlockPtr) - { - std::copy(value.begin(), value.end(), back_inserter(mValues)); - - if (LL_UNLIKELY(block_descriptor.mInitializationState == BlockDescriptor::INITIALIZING)) - { - ParamDescriptorPtr param_descriptor = ParamDescriptorPtr(new ParamDescriptor( - block_descriptor.mCurrentBlockPtr->getHandleFromParam(this), - &mergeWith, - &deserializeParam, - &serializeParam, - validate_func, - &inspectParam, - min_count, max_count)); - BaseBlock::addParam(block_descriptor, param_descriptor, name); - } - } - - bool isProvided() const { return Param::anyProvided(); } - - static bool deserializeParam(Param& param, Parser& parser, const Parser::name_stack_range_t& name_stack_range, bool new_name) - { - self_t& typed_param = static_cast(param); - bool new_value = false; - - if (new_name || typed_param.mValues.empty()) - { - new_value = true; - typed_param.mValues.push_back(value_t()); - } - - param_value_t& value = typed_param.mValues.back(); - - // attempt to parse block... - if(value.deserializeBlock(parser, name_stack_range, new_name)) - { - typed_param.setProvided(); - return true; - } - else if(name_value_lookup_t::valueNamesExist()) - { - // try to parse a known named value - std::string name; - if (parser.readValue(name)) - { - // try to parse a per type named value - if (name_value_lookup_t::getValueFromName(name, value.getValue())) - { - typed_param.mValues.back().setValueName(name); - typed_param.setProvided(); - return true; - } - - } - } - - if (new_value) - { // failed to parse new value, pop it off - typed_param.mValues.pop_back(); - } - - return false; - } - - static void serializeParam(const Param& param, Parser& parser, Parser::name_stack_t& name_stack, const Param* diff_param) - { - const self_t& typed_param = static_cast(param); - if (!typed_param.isProvided() || name_stack.empty()) return; - - for (const_iterator it = typed_param.mValues.begin(), end_it = typed_param.mValues.end(); - it != end_it; - ++it) - { - name_stack.back().second = true; - - std::string key = it->getValueName(); - if (!key.empty()) - { - parser.writeValue(key, name_stack); - } - // Not parsed via named values, write out value directly - // NOTE: currently we don't worry about removing default values in Multiple - else - { - it->serializeBlock(parser, name_stack, NULL); - } - } - } - - static void inspectParam(const Param& param, Parser& parser, Parser::name_stack_t& name_stack, S32 min_count, S32 max_count) - { - // I am a vector of blocks, so describe my contents recursively - param_value_t(value_t()).inspectBlock(parser, name_stack, min_count, max_count); - } - - void set(value_assignment_t val, bool flag_as_provided = true) - { - mValues = val; - setProvided(flag_as_provided); - } - - param_value_t& add() - { - mValues.push_back(value_t()); - setProvided(); - return mValues.back(); - } - - void add(const value_t& item) - { - mValues.push_back(item); - setProvided(); - } - - void add(const typename name_value_lookup_t::name_t& name) - { - value_t value; - - // try to parse a per type named value - if (name_value_lookup_t::getValueFromName(name, value)) - { - add(value); - mValues.back().setValueName(name); - } - } - - // implicit conversion - operator value_assignment_t() const { return mValues; } - // explicit conversion - value_assignment_t operator()() const { return mValues; } - - typedef typename container_t::iterator iterator; - typedef typename container_t::const_iterator const_iterator; - iterator begin() { return mValues.begin(); } - iterator end() { return mValues.end(); } - const_iterator begin() const { return mValues.begin(); } - const_iterator end() const { return mValues.end(); } - bool empty() const { return mValues.empty(); } - size_t size() const { return mValues.size(); } - - U32 numValidElements() const - { - U32 count = 0; - for (const_iterator it = mValues.begin(), end_it = mValues.end(); - it != end_it; - ++it) - { - if(it->validateBlock(false)) count++; - } - return count; - } - - protected: - - static bool mergeWith(Param& dst, const Param& src, bool overwrite) - { - const self_t& src_typed_param = static_cast(src); - self_t& dst_typed_param = static_cast(dst); - - if (overwrite) - { - std::copy(src_typed_param.begin(), src_typed_param.end(), std::back_inserter(dst_typed_param.mValues)); - } - else - { - container_t new_values(src_typed_param.mValues); - std::copy(dst_typed_param.begin(), dst_typed_param.end(), std::back_inserter(new_values)); - std::swap(dst_typed_param.mValues, new_values); - } - - if (src_typed_param.begin() != src_typed_param.end()) - { - dst_typed_param.setProvided(); - } - - return true; - } - - container_t mValues; - }; - - template - class ChoiceBlock : public BASE_BLOCK - { - typedef ChoiceBlock self_t; - typedef ChoiceBlock enclosing_block_t; - typedef BASE_BLOCK base_block_t; - - LOG_CLASS(self_t); - public: - // take all provided params from other and apply to self - bool overwriteFrom(const self_t& other) - { - return static_cast(this)->mergeBlock(selfBlockDescriptor(), other, true); - } - - // take all provided params that are not already provided, and apply to self - bool fillFrom(const self_t& other) - { - return static_cast(this)->mergeBlock(selfBlockDescriptor(), other, false); - } - - bool mergeBlockParam(bool source_provided, bool dest_provided, BlockDescriptor& block_data, const self_t& source, bool overwrite) - { - bool source_override = source_provided && (overwrite || !dest_provided); - - if (source_override || source.mCurChoice == mCurChoice) - { - return mergeBlock(block_data, source, overwrite); - } - return false; - } - - // merge with other block - bool mergeBlock(BlockDescriptor& block_data, const self_t& other, bool overwrite) - { - mCurChoice = other.mCurChoice; - return base_block_t::mergeBlock(selfBlockDescriptor(), other, overwrite); - } - - // clear out old choice when param has changed - /*virtual*/ void paramChanged(const Param& changed_param, bool user_provided) - { - param_handle_t changed_param_handle = base_block_t::getHandleFromParam(&changed_param); - // if we have a new choice... - if (changed_param_handle != mCurChoice) - { - // clear provided flag on previous choice - Param* previous_choice = base_block_t::getParamFromHandle(mCurChoice); - if (previous_choice) - { - previous_choice->setProvided(false); - } - mCurChoice = changed_param_handle; - } - base_block_t::paramChanged(changed_param, user_provided); - } - - virtual const BlockDescriptor& mostDerivedBlockDescriptor() const { return selfBlockDescriptor(); } - virtual BlockDescriptor& mostDerivedBlockDescriptor() { return selfBlockDescriptor(); } - - protected: - ChoiceBlock() - : mCurChoice(0) - { - BaseBlock::init(selfBlockDescriptor(), base_block_t::selfBlockDescriptor(), sizeof(DERIVED_BLOCK)); - } - - // Alternatives are mutually exclusive wrt other Alternatives in the same block. - // One alternative in a block will always have isChosen() == true. - // At most one alternative in a block will have isProvided() == true. - template > - class Alternative : public TypedParam - { - public: - friend class ChoiceBlock; - - typedef Alternative self_t; - typedef TypedParam >::value> super_t; - typedef typename super_t::value_assignment_t value_assignment_t; - - using super_t::operator =; - - explicit Alternative(const char* name = "", value_assignment_t val = defaultValue()) - : super_t(DERIVED_BLOCK::selfBlockDescriptor(), name, val, NULL, 0, 1), - mOriginalValue(val) - { - // assign initial choice to first declared option - DERIVED_BLOCK* blockp = ((DERIVED_BLOCK*)DERIVED_BLOCK::selfBlockDescriptor().mCurrentBlockPtr); - if (LL_UNLIKELY(DERIVED_BLOCK::selfBlockDescriptor().mInitializationState == BlockDescriptor::INITIALIZING)) - { - if(blockp->mCurChoice == 0) - { - blockp->mCurChoice = Param::enclosingBlock().getHandleFromParam(this); - } - } - } - - void choose() - { - static_cast(Param::enclosingBlock()).paramChanged(*this, true); - } - - void chooseAs(value_assignment_t val) - { - super_t::set(val); - } - - void operator =(value_assignment_t val) - { - super_t::set(val); - } - - void operator()(typename super_t::value_assignment_t val) - { - super_t::set(val); - } - - operator value_assignment_t() const - { - return (*this)(); - } - - value_assignment_t operator()() const - { - if (static_cast(Param::enclosingBlock()).getCurrentChoice() == this) - { - return super_t::getValue(); - } - return mOriginalValue; - } - - bool isChosen() const - { - return static_cast(Param::enclosingBlock()).getCurrentChoice() == this; - } - - private: - T mOriginalValue; - }; - - protected: - static BlockDescriptor& selfBlockDescriptor() - { - static BlockDescriptor sBlockDescriptor; - return sBlockDescriptor; - } - - private: - param_handle_t mCurChoice; - - const Param* getCurrentChoice() const - { - return base_block_t::getParamFromHandle(mCurChoice); - } - }; - - template - class Block - : public BASE_BLOCK - { - typedef Block self_t; - typedef Block block_t; - - public: - typedef BASE_BLOCK base_block_t; - - // take all provided params from other and apply to self - bool overwriteFrom(const self_t& other) - { - return static_cast(this)->mergeBlock(selfBlockDescriptor(), other, true); - } - - // take all provided params that are not already provided, and apply to self - bool fillFrom(const self_t& other) - { - return static_cast(this)->mergeBlock(selfBlockDescriptor(), other, false); - } - - virtual const BlockDescriptor& mostDerivedBlockDescriptor() const { return selfBlockDescriptor(); } - virtual BlockDescriptor& mostDerivedBlockDescriptor() { return selfBlockDescriptor(); } - - protected: - Block() - { - //#pragma message("Parsing LLInitParam::Block") - BaseBlock::init(selfBlockDescriptor(), BASE_BLOCK::selfBlockDescriptor(), sizeof(DERIVED_BLOCK)); - } - - // - // Nested classes for declaring parameters - // - template > - class Optional : public TypedParam - { - public: - typedef TypedParam >::value> super_t; - typedef typename super_t::value_assignment_t value_assignment_t; - - using super_t::operator(); - using super_t::operator =; - - explicit Optional(const char* name = "", value_assignment_t val = defaultValue()) - : super_t(DERIVED_BLOCK::selfBlockDescriptor(), name, val, NULL, 0, 1) - { - //#pragma message("Parsing LLInitParam::Block::Optional") - } - - Optional& operator =(value_assignment_t val) - { - set(val); - return *this; - } - - DERIVED_BLOCK& operator()(value_assignment_t val) - { - super_t::set(val); - return static_cast(Param::enclosingBlock()); - } - }; - - template > - class Mandatory : public TypedParam - { - public: - typedef TypedParam >::value> super_t; - typedef Mandatory self_t; - typedef typename super_t::value_assignment_t value_assignment_t; - - using super_t::operator(); - using super_t::operator =; - - // mandatory parameters require a name to be parseable - explicit Mandatory(const char* name = "", value_assignment_t val = defaultValue()) - : super_t(DERIVED_BLOCK::selfBlockDescriptor(), name, val, &validate, 1, 1) - {} - - Mandatory& operator =(value_assignment_t val) - { - set(val); - return *this; - } - - DERIVED_BLOCK& operator()(typename super_t::value_assignment_t val) - { - super_t::set(val); - return static_cast(Param::enclosingBlock()); - } - - static bool validate(const Param* p) - { - // valid only if provided - return static_cast(p)->isProvided(); - } - - }; - - template > - class Multiple : public TypedParam - { - public: - typedef TypedParam >::value> super_t; - typedef Multiple self_t; - typedef typename super_t::container_t container_t; - typedef typename super_t::value_assignment_t value_assignment_t; - typedef typename super_t::iterator iterator; - typedef typename super_t::const_iterator const_iterator; - - explicit Multiple(const char* name = "") - : super_t(DERIVED_BLOCK::selfBlockDescriptor(), name, container_t(), &validate, RANGE::minCount, RANGE::maxCount) - {} - - Multiple& operator =(value_assignment_t val) - { - set(val); - return *this; - } - - DERIVED_BLOCK& operator()(typename super_t::value_assignment_t val) - { - super_t::set(val); - return static_cast(Param::enclosingBlock()); - } - - static bool validate(const Param* paramp) - { - U32 num_valid = ((super_t*)paramp)->numValidElements(); - return RANGE::minCount <= num_valid && num_valid <= RANGE::maxCount; - } - }; - - class Deprecated : public Param - { - public: - explicit Deprecated(const char* name) - : Param(DERIVED_BLOCK::selfBlockDescriptor().mCurrentBlockPtr) - { - BlockDescriptor& block_descriptor = DERIVED_BLOCK::selfBlockDescriptor(); - if (LL_UNLIKELY(block_descriptor.mInitializationState == BlockDescriptor::INITIALIZING)) - { - ParamDescriptorPtr param_descriptor = ParamDescriptorPtr(new ParamDescriptor( - block_descriptor.mCurrentBlockPtr->getHandleFromParam(this), - NULL, - &deserializeParam, - NULL, - NULL, - NULL, - 0, S32_MAX)); - BaseBlock::addParam(block_descriptor, param_descriptor, name); - } - } - - static bool deserializeParam(Param& param, Parser& parser, const Parser::name_stack_range_t& name_stack_range, bool new_name) - { - if (name_stack_range.first == name_stack_range.second) - { - //std::string message = llformat("Deprecated value %s ignored", getName().c_str()); - //parser.parserWarning(message); - return true; - } - - return false; - } - }; - - // different semantics for documentation purposes, but functionally identical - typedef Deprecated Ignored; - - protected: - static BlockDescriptor& selfBlockDescriptor() - { - static BlockDescriptor sBlockDescriptor; - return sBlockDescriptor; - } - - template - void changeDefault(TypedParam& param, - typename TypedParam::value_assignment_t value) - { - if (!param.isProvided()) - { - param.set(value, false); - } - } - - }; - - template - class BatchBlock - : public Block - { - public: - typedef BatchBlock self_t; - typedef Block super_t; - - BatchBlock() - {} - - bool deserializeBlock(Parser& p, Parser::name_stack_range_t name_stack_range, bool new_name) - { - if (new_name) - { - // reset block - *static_cast(this) = defaultBatchValue(); - } - return super_t::deserializeBlock(p, name_stack_range, new_name); - } - - bool mergeBlock(BlockDescriptor& block_data, const BaseBlock& other, bool overwrite) - { - if (overwrite) - { - *static_cast(this) = defaultBatchValue(); - // merge individual parameters into destination - return super_t::mergeBlock(super_t::selfBlockDescriptor(), other, overwrite); - } - return false; - } - protected: - static const DERIVED_BLOCK& defaultBatchValue() - { - static DERIVED_BLOCK default_value; - return default_value; - } - }; - - // FIXME: this specialization is not currently used, as it only matches against the BatchBlock base class - // and not the derived class with the actual params - template - class ParamValue , - NAME_VALUE_LOOKUP, - true> - : public NAME_VALUE_LOOKUP, - protected BatchBlock - { - public: - typedef BatchBlock block_t; - typedef const BatchBlock& value_assignment_t; - typedef block_t value_t; - - ParamValue() - : block_t(), - mValidated(false) - {} - - ParamValue(value_assignment_t other) - : block_t(other), - mValidated(false) - { - } - - void setValue(value_assignment_t val) - { - *this = val; - } - - value_assignment_t getValue() const - { - return *this; - } - - BatchBlock& getValue() - { - return *this; - } - - operator value_assignment_t() const - { - return *this; - } - - value_assignment_t operator()() const - { - return *this; - } - - protected: - mutable bool mValidated; // lazy validation flag - }; - - template - class ParamValue , - TypeValues, - IS_BLOCK> - : public IsBlock::base_class_t - { - public: - typedef ParamValue , TypeValues, false> self_t; - typedef const T& value_assignment_t; - typedef T value_t; - - ParamValue() - : mValue(), - mValidated(false) - {} - - ParamValue(value_assignment_t other) - : mValue(other), - mValidated(false) - {} - - void setValue(value_assignment_t val) - { - mValue.set(val); - } - - value_assignment_t getValue() const - { - return mValue.get(); - } - - T& getValue() - { - return mValue.get(); - } - - operator value_assignment_t() const - { - return mValue.get(); - } - - value_assignment_t operator()() const - { - return mValue.get(); - } - - bool deserializeBlock(Parser& p, Parser::name_stack_range_t name_stack_range, bool new_name) - { - return mValue.get().deserializeBlock(p, name_stack_range, new_name); - } - - void serializeBlock(Parser& p, Parser::name_stack_t& name_stack, const BaseBlock* diff_block = NULL) const - { - if (mValue.empty()) return; - - mValue.get().serializeBlock(p, name_stack, diff_block); - } - - bool inspectBlock(Parser& p, Parser::name_stack_t name_stack = Parser::name_stack_t(), S32 min_count = 0, S32 max_count = S32_MAX) const - { - if (mValue.empty()) return false; - - return mValue.get().inspectBlock(p, name_stack, min_count, max_count); - } - - protected: - mutable bool mValidated; // lazy validation flag - - private: - BaseBlock::Lazy mValue; - }; - - template <> - class ParamValue , - false> - : public TypeValues, - public BaseBlock - { - public: - typedef ParamValue, false> self_t; - typedef const LLSD& value_assignment_t; - - ParamValue() - : mValidated(false) - {} - - ParamValue(value_assignment_t other) - : mValue(other), - mValidated(false) - {} - - void setValue(value_assignment_t val) { mValue = val; } - - value_assignment_t getValue() const { return mValue; } - LLSD& getValue() { return mValue; } - - operator value_assignment_t() const { return mValue; } - value_assignment_t operator()() const { return mValue; } - - - // block param interface - bool deserializeBlock(Parser& p, Parser::name_stack_range_t name_stack_range, bool new_name); - void serializeBlock(Parser& p, Parser::name_stack_t& name_stack, const BaseBlock* diff_block = NULL) const; - bool inspectBlock(Parser& p, Parser::name_stack_t name_stack = Parser::name_stack_t(), S32 min_count = 0, S32 max_count = S32_MAX) const - { - //TODO: implement LLSD params as schema type Any - return true; - } - - protected: - mutable bool mValidated; // lazy validation flag - - private: - static void serializeElement(Parser& p, const LLSD& sd, Parser::name_stack_t& name_stack); - - LLSD mValue; - }; - - template - class CustomParamValue - : public Block > >, - public TypeValues - { - public: - typedef enum e_value_age - { - VALUE_NEEDS_UPDATE, // mValue needs to be refreshed from the block parameters - VALUE_AUTHORITATIVE, // mValue holds the authoritative value (which has been replicated to the block parameters via updateBlockFromValue) - BLOCK_AUTHORITATIVE // mValue is derived from the block parameters, which are authoritative - } EValueAge; - - typedef ParamValue > derived_t; - typedef CustomParamValue self_t; - typedef Block block_t; - typedef const T& value_assignment_t; - typedef T value_t; - - - CustomParamValue(const T& value = T()) - : mValue(value), - mValueAge(VALUE_AUTHORITATIVE), - mValidated(false) - {} - - bool deserializeBlock(Parser& parser, Parser::name_stack_range_t name_stack_range, bool new_name) - { - derived_t& typed_param = static_cast(*this); - // try to parse direct value T - if (name_stack_range.first == name_stack_range.second) - { - if(parser.readValue(typed_param.mValue)) - { - typed_param.mValueAge = VALUE_AUTHORITATIVE; - typed_param.updateBlockFromValue(false); - - typed_param.clearValueName(); - - return true; - } - } - - // fall back on parsing block components for T - return typed_param.BaseBlock::deserializeBlock(parser, name_stack_range, new_name); - } - - void serializeBlock(Parser& parser, Parser::name_stack_t& name_stack, const BaseBlock* diff_block = NULL) const - { - const derived_t& typed_param = static_cast(*this); - const derived_t* diff_param = static_cast(diff_block); - - std::string key = typed_param.getValueName(); - - // first try to write out name of name/value pair - if (!key.empty()) - { - if (!diff_param || !ParamCompare::equals(diff_param->getValueName(), key)) - { - parser.writeValue(key, name_stack); - } - } - // then try to serialize value directly - else if (!diff_param || !ParamCompare::equals(typed_param.getValue(), diff_param->getValue())) - { - - if (!parser.writeValue(typed_param.getValue(), name_stack)) - { - //RN: *always* serialize provided components of BlockValue (don't pass diff_param on), - // since these tend to be viewed as the constructor arguments for the value T. It seems - // cleaner to treat the uniqueness of a BlockValue according to the generated value, and - // not the individual components. This way will not - // be exported as , since it was probably the intent of the user to - // be specific about the RGB color values. This also fixes an issue where we distinguish - // between rect.left not being provided and rect.left being explicitly set to 0 (same as default) - - if (typed_param.mValueAge == VALUE_AUTHORITATIVE) - { - // if the value is authoritative but the parser doesn't accept the value type - // go ahead and make a copy, and splat the value out to its component params - // and serialize those params - derived_t copy(typed_param); - copy.updateBlockFromValue(true); - copy.block_t::serializeBlock(parser, name_stack, NULL); - } - else - { - block_t::serializeBlock(parser, name_stack, NULL); - } - } - } - } - - bool inspectBlock(Parser& parser, Parser::name_stack_t name_stack = Parser::name_stack_t(), S32 min_count = 0, S32 max_count = S32_MAX) const - { - // first, inspect with actual type... - parser.inspectValue(name_stack, min_count, max_count, NULL); - if (TypeValues::getPossibleValues()) - { - //...then inspect with possible string values... - parser.inspectValue(name_stack, min_count, max_count, TypeValues::getPossibleValues()); - } - // then recursively inspect contents... - return block_t::inspectBlock(parser, name_stack, min_count, max_count); - } - - bool validateBlock(bool emit_errors = true) const - { - if (mValueAge == VALUE_NEEDS_UPDATE) - { - if (block_t::validateBlock(emit_errors)) - { - // clear stale keyword associated with old value - TypeValues::clearValueName(); - mValueAge = BLOCK_AUTHORITATIVE; - static_cast(const_cast(this))->updateValueFromBlock(); - return true; - } - else - { - //block value incomplete, so not considered provided - // will attempt to revalidate on next call to isProvided() - return false; - } - } - else - { - // we have a valid value in hand - return true; - } - } - - // propagate change status up to enclosing block - /*virtual*/ void paramChanged(const Param& changed_param, bool user_provided) - { - BaseBlock::paramChanged(changed_param, user_provided); - if (user_provided) - { - // a parameter changed, so our value is out of date - mValueAge = VALUE_NEEDS_UPDATE; - } - } - - void setValue(value_assignment_t val) - { - derived_t& typed_param = static_cast(*this); - // set param version number to be up to date, so we ignore block contents - mValueAge = VALUE_AUTHORITATIVE; - mValue = val; - typed_param.clearValueName(); - static_cast(this)->updateBlockFromValue(false); - } - - value_assignment_t getValue() const - { - validateBlock(true); - return mValue; - } - - T& getValue() - { - validateBlock(true); - return mValue; - } - - operator value_assignment_t() const - { - return getValue(); - } - - value_assignment_t operator()() const - { - return getValue(); - } - - protected: - - // use this from within updateValueFromBlock() to set the value without making it authoritative - void updateValue(value_assignment_t value) - { - mValue = value; - } - - bool mergeBlockParam(bool source_provided, bool dst_provided, BlockDescriptor& block_data, const BaseBlock& source, bool overwrite) - { - bool source_override = source_provided && (overwrite || !dst_provided); - - const derived_t& src_typed_param = static_cast(source); - - if (source_override && src_typed_param.mValueAge == VALUE_AUTHORITATIVE) - { - // copy value over - setValue(src_typed_param.getValue()); - return true; - } - // merge individual parameters into destination - if (mValueAge == VALUE_AUTHORITATIVE) - { - static_cast(this)->updateBlockFromValue(dst_provided); - } - return mergeBlock(block_data, source, overwrite); - } - - bool mergeBlock(BlockDescriptor& block_data, const BaseBlock& source, bool overwrite) - { - return block_t::mergeBlock(block_data, source, overwrite); - } - - mutable bool mValidated; // lazy validation flag - - private: - mutable T mValue; - mutable EValueAge mValueAge; - }; -} - - -#endif // LL_LLPARAM_H diff --git a/indra/llxuixml/llregistry.h b/indra/llxuixml/llregistry.h deleted file mode 100644 index 36ce6a97b7..0000000000 --- a/indra/llxuixml/llregistry.h +++ /dev/null @@ -1,351 +0,0 @@ -/** - * @file llregistry.h - * @brief template classes for registering name, value pairs in nested scopes, statically, etc. - * - * $LicenseInfo:firstyear=2001&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#ifndef LL_LLREGISTRY_H -#define LL_LLREGISTRY_H - -#include - -#include -#include "llsingleton.h" - -template -class LLRegistryDefaultComparator -{ - bool operator()(const T& lhs, const T& rhs) { return lhs < rhs; } -}; - -template > -class LLRegistry -{ -public: - typedef LLRegistry registry_t; - typedef typename boost::add_reference::type>::type ref_const_key_t; - typedef typename boost::add_reference::type>::type ref_const_value_t; - typedef typename boost::add_reference::type ref_value_t; - typedef typename boost::add_pointer::type>::type ptr_const_value_t; - typedef typename boost::add_pointer::type ptr_value_t; - - class Registrar - { - friend class LLRegistry; - public: - typedef typename std::map registry_map_t; - - bool add(ref_const_key_t key, ref_const_value_t value) - { - if (mMap.insert(std::make_pair(key, value)).second == false) - { - llwarns << "Tried to register " << key << " but it was already registered!" << llendl; - return false; - } - return true; - } - - void remove(ref_const_key_t key) - { - mMap.erase(key); - } - - void replace(ref_const_key_t key, ref_const_value_t value) - { - mMap[key] = value; - } - - typename registry_map_t::const_iterator beginItems() const - { - return mMap.begin(); - } - - typename registry_map_t::const_iterator endItems() const - { - return mMap.end(); - } - - protected: - ptr_value_t getValue(ref_const_key_t key) - { - typename registry_map_t::iterator found_it = mMap.find(key); - if (found_it != mMap.end()) - { - return &(found_it->second); - } - return NULL; - } - - ptr_const_value_t getValue(ref_const_key_t key) const - { - typename registry_map_t::const_iterator found_it = mMap.find(key); - if (found_it != mMap.end()) - { - return &(found_it->second); - } - return NULL; - } - - // if the registry is used to store pointers, and null values are valid entries - // then use this function to check the existence of an entry - bool exists(ref_const_key_t key) const - { - return mMap.find(key) != mMap.end(); - } - - bool empty() const - { - return mMap.empty(); - } - - protected: - // use currentRegistrar() or defaultRegistrar() - Registrar() {} - ~Registrar() {} - - private: - registry_map_t mMap; - }; - - typedef typename std::list scope_list_t; - typedef typename std::list::iterator scope_list_iterator_t; - typedef typename std::list::const_iterator scope_list_const_iterator_t; - - LLRegistry() - {} - - ~LLRegistry() {} - - ptr_value_t getValue(ref_const_key_t key) - { - for(scope_list_iterator_t it = mActiveScopes.begin(); - it != mActiveScopes.end(); - ++it) - { - ptr_value_t valuep = (*it)->getValue(key); - if (valuep != NULL) return valuep; - } - return mDefaultRegistrar.getValue(key); - } - - ptr_const_value_t getValue(ref_const_key_t key) const - { - for(scope_list_const_iterator_t it = mActiveScopes.begin(); - it != mActiveScopes.end(); - ++it) - { - ptr_value_t valuep = (*it)->getValue(key); - if (valuep != NULL) return valuep; - } - return mDefaultRegistrar.getValue(key); - } - - bool exists(ref_const_key_t key) const - { - for(scope_list_const_iterator_t it = mActiveScopes.begin(); - it != mActiveScopes.end(); - ++it) - { - if ((*it)->exists(key)) return true; - } - - return mDefaultRegistrar.exists(key); - } - - bool empty() const - { - for(scope_list_const_iterator_t it = mActiveScopes.begin(); - it != mActiveScopes.end(); - ++it) - { - if (!(*it)->empty()) return false; - } - - return mDefaultRegistrar.empty(); - } - - - Registrar& defaultRegistrar() - { - return mDefaultRegistrar; - } - - const Registrar& defaultRegistrar() const - { - return mDefaultRegistrar; - } - - - Registrar& currentRegistrar() - { - if (!mActiveScopes.empty()) - { - return *mActiveScopes.front(); - } - - return mDefaultRegistrar; - } - - const Registrar& currentRegistrar() const - { - if (!mActiveScopes.empty()) - { - return *mActiveScopes.front(); - } - - return mDefaultRegistrar; - } - - -protected: - void addScope(Registrar* scope) - { - // newer scopes go up front - mActiveScopes.insert(mActiveScopes.begin(), scope); - } - - void removeScope(Registrar* scope) - { - // O(N) but should be near the beggining and N should be small and this is safer than storing iterators - scope_list_iterator_t iter = std::find(mActiveScopes.begin(), mActiveScopes.end(), scope); - if (iter != mActiveScopes.end()) - { - mActiveScopes.erase(iter); - } - } - -private: - scope_list_t mActiveScopes; - Registrar mDefaultRegistrar; -}; - -template > -class LLRegistrySingleton - : public LLRegistry, - public LLSingleton -{ - friend class LLSingleton; -public: - typedef LLRegistry registry_t; - typedef const KEY& ref_const_key_t; - typedef const VALUE& ref_const_value_t; - typedef VALUE* ptr_value_t; - typedef const VALUE* ptr_const_value_t; - typedef LLSingleton singleton_t; - - class ScopedRegistrar : public registry_t::Registrar - { - public: - ScopedRegistrar(bool push_scope = true) - { - if (push_scope) - { - pushScope(); - } - } - - ~ScopedRegistrar() - { - if (!singleton_t::destroyed()) - { - popScope(); - } - } - - void pushScope() - { - singleton_t::instance().addScope(this); - } - - void popScope() - { - singleton_t::instance().removeScope(this); - } - - ptr_value_t getValueFromScope(ref_const_key_t key) - { - return getValue(key); - } - - ptr_const_value_t getValueFromScope(ref_const_key_t key) const - { - return getValue(key); - } - - private: - typename std::list::iterator mListIt; - }; - - class StaticRegistrar : public registry_t::Registrar - { - public: - virtual ~StaticRegistrar() {} - StaticRegistrar(ref_const_key_t key, ref_const_value_t value) - { - singleton_t::instance().mStaticScope->add(key, value); - } - }; - - // convenience functions - typedef typename LLRegistry::Registrar& ref_registrar_t; - static ref_registrar_t currentRegistrar() - { - return singleton_t::instance().registry_t::currentRegistrar(); - } - - static ref_registrar_t defaultRegistrar() - { - return singleton_t::instance().registry_t::defaultRegistrar(); - } - - static ptr_value_t getValue(ref_const_key_t key) - { - return singleton_t::instance().registry_t::getValue(key); - } - -protected: - // DERIVED_TYPE needs to derive from LLRegistrySingleton - LLRegistrySingleton() - : mStaticScope(NULL) - {} - - virtual void initSingleton() - { - mStaticScope = new ScopedRegistrar(); - } - - virtual ~LLRegistrySingleton() - { - delete mStaticScope; - } - -private: - ScopedRegistrar* mStaticScope; -}; - -// helper macro for doing static registration -#define GLUED_TOKEN(x, y) x ## y -#define GLUE_TOKENS(x, y) GLUED_TOKEN(x, y) -#define LLREGISTER_STATIC(REGISTRY, KEY, VALUE) static REGISTRY::StaticRegistrar GLUE_TOKENS(reg, __LINE__)(KEY, VALUE); - -#endif diff --git a/indra/llxuixml/lltrans.cpp b/indra/llxuixml/lltrans.cpp deleted file mode 100644 index 5388069c24..0000000000 --- a/indra/llxuixml/lltrans.cpp +++ /dev/null @@ -1,295 +0,0 @@ -/** - * @file lltrans.cpp - * @brief LLTrans implementation - * - * $LicenseInfo:firstyear=2000&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include "linden_common.h" - -#include "lltrans.h" - -#include "llfasttimer.h" // for call count statistics -#include "llxuiparser.h" -#include "llsd.h" -#include "llxmlnode.h" - -#include - -LLTrans::template_map_t LLTrans::sStringTemplates; -LLStringUtil::format_map_t LLTrans::sDefaultArgs; - -struct StringDef : public LLInitParam::Block -{ - Mandatory name; - Mandatory value; - - StringDef() - : name("name"), - value("value") - {} -}; - -struct StringTable : public LLInitParam::Block -{ - Multiple strings; - StringTable() - : strings("string") - {} -}; - -//static -bool LLTrans::parseStrings(LLXMLNodePtr &root, const std::set& default_args) -{ - std::string xml_filename = "(strings file)"; - if (!root->hasName("strings")) - { - llerrs << "Invalid root node name in " << xml_filename - << ": was " << root->getName() << ", expected \"strings\"" << llendl; - } - - StringTable string_table; - LLXUIParser parser; - parser.readXUI(root, string_table, xml_filename); - - if (!string_table.validateBlock()) - { - llerrs << "Problem reading strings: " << xml_filename << llendl; - return false; - } - - sStringTemplates.clear(); - sDefaultArgs.clear(); - - for(LLInitParam::ParamIterator::const_iterator it = string_table.strings.begin(); - it != string_table.strings.end(); - ++it) - { - LLTransTemplate xml_template(it->name, it->value); - sStringTemplates[xml_template.mName] = xml_template; - - std::set::const_iterator iter = default_args.find(xml_template.mName); - if (iter != default_args.end()) - { - std::string name = *iter; - if (name[0] != '[') - name = llformat("[%s]",name.c_str()); - sDefaultArgs[name] = xml_template.mText; - } - } - - return true; -} - - -//static -bool LLTrans::parseLanguageStrings(LLXMLNodePtr &root) -{ - std::string xml_filename = "(language strings file)"; - if (!root->hasName("strings")) - { - llerrs << "Invalid root node name in " << xml_filename - << ": was " << root->getName() << ", expected \"strings\"" << llendl; - } - - StringTable string_table; - LLXUIParser parser; - parser.readXUI(root, string_table, xml_filename); - - if (!string_table.validateBlock()) - { - llerrs << "Problem reading strings: " << xml_filename << llendl; - return false; - } - - for(LLInitParam::ParamIterator::const_iterator it = string_table.strings.begin(); - it != string_table.strings.end(); - ++it) - { - // share the same map with parseStrings() so we can search the strings using the same getString() function.- angela - LLTransTemplate xml_template(it->name, it->value); - sStringTemplates[xml_template.mName] = xml_template; - } - - return true; -} - - - -static LLFastTimer::DeclareTimer FTM_GET_TRANS("Translate string"); - -//static -std::string LLTrans::getString(const std::string &xml_desc, const LLStringUtil::format_map_t& msg_args) -{ - // Don't care about time as much as call count. Make sure we're not - // calling LLTrans::getString() in an inner loop. JC - LLFastTimer timer(FTM_GET_TRANS); - - template_map_t::iterator iter = sStringTemplates.find(xml_desc); - if (iter != sStringTemplates.end()) - { - std::string text = iter->second.mText; - LLStringUtil::format_map_t args = sDefaultArgs; - args.insert(msg_args.begin(), msg_args.end()); - LLStringUtil::format(text, args); - - return text; - } - else - { - LL_WARNS_ONCE("configuration") << "Missing String in strings.xml: [" << xml_desc << "]" << LL_ENDL; - return "MissingString("+xml_desc+")"; - } -} - -//static -std::string LLTrans::getString(const std::string &xml_desc, const LLSD& msg_args) -{ - // Don't care about time as much as call count. Make sure we're not - // calling LLTrans::getString() in an inner loop. JC - LLFastTimer timer(FTM_GET_TRANS); - - template_map_t::iterator iter = sStringTemplates.find(xml_desc); - if (iter != sStringTemplates.end()) - { - std::string text = iter->second.mText; - LLStringUtil::format(text, msg_args); - return text; - } - else - { - LL_WARNS_ONCE("configuration") << "Missing String in strings.xml: [" << xml_desc << "]" << LL_ENDL; - return "MissingString("+xml_desc+")"; - } -} - -//static -bool LLTrans::findString(std::string &result, const std::string &xml_desc, const LLStringUtil::format_map_t& msg_args) -{ - LLFastTimer timer(FTM_GET_TRANS); - - template_map_t::iterator iter = sStringTemplates.find(xml_desc); - if (iter != sStringTemplates.end()) - { - std::string text = iter->second.mText; - LLStringUtil::format_map_t args = sDefaultArgs; - args.insert(msg_args.begin(), msg_args.end()); - LLStringUtil::format(text, args); - result = text; - return true; - } - else - { - LL_WARNS_ONCE("configuration") << "Missing String in strings.xml: [" << xml_desc << "]" << LL_ENDL; - return false; - } -} - -//static -bool LLTrans::findString(std::string &result, const std::string &xml_desc, const LLSD& msg_args) -{ - LLFastTimer timer(FTM_GET_TRANS); - - template_map_t::iterator iter = sStringTemplates.find(xml_desc); - if (iter != sStringTemplates.end()) - { - std::string text = iter->second.mText; - LLStringUtil::format(text, msg_args); - result = text; - return true; - } - else - { - LL_WARNS_ONCE("configuration") << "Missing String in strings.xml: [" << xml_desc << "]" << LL_ENDL; - return false; - } -} - -//static -std::string LLTrans::getCountString(const std::string& language, const std::string& xml_desc, S32 count) -{ - // Compute which string identifier to use - const char* form = ""; - if (language == "ru") // Russian - { - // From GNU ngettext() - // Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2; - if (count % 10 == 1 - && count % 100 != 11) - { - // singular, "1 item" - form = "A"; - } - else if (count % 10 >= 2 - && count % 10 <= 4 - && (count % 100 < 10 || count % 100 >= 20) ) - { - // special case "2 items", "23 items", but not "13 items" - form = "B"; - } - else - { - // English-style plural, "5 items" - form = "C"; - } - } - else if (language == "fr" || language == "pt") // French, Brazilian Portuguese - { - // French and Portuguese treat zero as a singular "0 item" not "0 items" - if (count == 0 || count == 1) - { - form = "A"; - } - else - { - // English-style plural - form = "B"; - } - } - else // default - { - // languages like English with 2 forms, singular and plural - if (count == 1) - { - // "1 item" - form = "A"; - } - else - { - // "2 items", also use plural for "0 items" - form = "B"; - } - } - - // Translate that string - LLStringUtil::format_map_t args; - args["[COUNT]"] = llformat("%d", count); - - // Look up "AgeYearsB" or "AgeWeeksC" including the "form" - std::string key = llformat("%s%s", xml_desc.c_str(), form); - return getString(key, args); -} - -void LLTrans::setDefaultArg(const std::string& name, const std::string& value) -{ - sDefaultArgs[name] = value; -} diff --git a/indra/llxuixml/lltrans.h b/indra/llxuixml/lltrans.h deleted file mode 100644 index 128b51d383..0000000000 --- a/indra/llxuixml/lltrans.h +++ /dev/null @@ -1,133 +0,0 @@ -/** - * @file lltrans.h - * @brief LLTrans definition - * - * $LicenseInfo:firstyear=2000&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#ifndef LL_TRANS_H -#define LL_TRANS_H - -#include - -#include "llpointer.h" -#include "llstring.h" - -class LLXMLNode; - -class LLSD; - -/** - * @brief String template loaded from strings.xml - */ -class LLTransTemplate -{ -public: - LLTransTemplate(const std::string& name = LLStringUtil::null, const std::string& text = LLStringUtil::null) : mName(name), mText(text) {} - - std::string mName; - std::string mText; -}; - -/** - * @brief Localized strings class - * This class is used to retrieve translations of strings used to build larger ones, as well as - * strings with a general usage that don't belong to any specific floater. For example, - * "Owner:", "Retrieving..." used in the place of a not yet known name, etc. - */ -class LLTrans -{ -public: - LLTrans(); - - /** - * @brief Parses the xml root that holds the strings. Used once on startup -// *FIXME * @param xml_filename Filename to parse - * @param default_args Set of strings (expected to be in the file) to use as default replacement args, e.g. "SECOND_LIFE" - * @returns true if the file was parsed successfully, true if something went wrong - */ - static bool parseStrings(LLPointer & root, const std::set& default_args); - - static bool parseLanguageStrings(LLPointer & root); - - /** - * @brief Returns a translated string - * @param xml_desc String's description - * @param args A list of substrings to replace in the string - * @returns Translated string - */ - static std::string getString(const std::string &xml_desc, const LLStringUtil::format_map_t& args); - static std::string getString(const std::string &xml_desc, const LLSD& args); - static bool findString(std::string &result, const std::string &xml_desc, const LLStringUtil::format_map_t& args); - static bool findString(std::string &result, const std::string &xml_desc, const LLSD& args); - - // Returns translated string with [COUNT] replaced with a number, following - // special per-language logic for plural nouns. For example, some languages - // may have different plurals for 0, 1, 2 and > 2. - // See "AgeWeeksA", "AgeWeeksB", etc. in strings.xml for examples. - static std::string getCountString(const std::string& language, const std::string& xml_desc, S32 count); - - /** - * @brief Returns a translated string - * @param xml_desc String's description - * @returns Translated string - */ - static std::string getString(const std::string &xml_desc) - { - LLStringUtil::format_map_t empty; - return getString(xml_desc, empty); - } - - static bool findString(std::string &result, const std::string &xml_desc) - { - LLStringUtil::format_map_t empty; - return findString(result, xml_desc, empty); - } - - static std::string getKeyboardString(const char* keystring) - { - std::string key_str(keystring); - std::string trans_str; - return findString(trans_str, key_str) ? trans_str : key_str; - } - - // get the default args - static const LLStringUtil::format_map_t& getDefaultArgs() - { - return sDefaultArgs; - } - - static void setDefaultArg(const std::string& name, const std::string& value); - - // insert default args into an arg list - static void getArgs(LLStringUtil::format_map_t& args) - { - args.insert(sDefaultArgs.begin(), sDefaultArgs.end()); - } - -private: - typedef std::map template_map_t; - static template_map_t sStringTemplates; - static LLStringUtil::format_map_t sDefaultArgs; -}; - -#endif diff --git a/indra/llxuixml/lluicolor.cpp b/indra/llxuixml/lluicolor.cpp deleted file mode 100644 index f9bb80f8c5..0000000000 --- a/indra/llxuixml/lluicolor.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/** - * @file lluicolor.cpp - * @brief brief LLUIColor class implementation file - * - * $LicenseInfo:firstyear=2009&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include "linden_common.h" - -#include "lluicolor.h" - -LLUIColor::LLUIColor() - :mColorPtr(NULL) -{ -} - - -LLUIColor::LLUIColor(const LLColor4& color) -: mColor(color), - mColorPtr(NULL) -{ -} - -LLUIColor::LLUIColor(const LLUIColor* color) -: mColorPtr(color) -{ -} - -void LLUIColor::set(const LLColor4& color) -{ - mColor = color; - mColorPtr = NULL; -} - -void LLUIColor::set(const LLUIColor* color) -{ - mColorPtr = color; -} - -const LLColor4& LLUIColor::get() const -{ - return (mColorPtr == NULL ? mColor : mColorPtr->get()); -} - -LLUIColor::operator const LLColor4& () const -{ - return get(); -} - -const LLColor4& LLUIColor::operator()() const -{ - return get(); -} - -bool LLUIColor::isReference() const -{ - return mColorPtr != NULL; -} - -namespace LLInitParam -{ - // used to detect equivalence with default values on export - bool ParamCompare::equals(const LLUIColor &a, const LLUIColor &b) - { - // do not detect value equivalence, treat pointers to colors as distinct from color values - return (a.mColorPtr == NULL && b.mColorPtr == NULL ? a.mColor == b.mColor : a.mColorPtr == b.mColorPtr); - } -} diff --git a/indra/llxuixml/lluicolor.h b/indra/llxuixml/lluicolor.h deleted file mode 100644 index 97ebea854a..0000000000 --- a/indra/llxuixml/lluicolor.h +++ /dev/null @@ -1,71 +0,0 @@ -/** - * @file lluicolor.h - * @brief brief LLUIColor class header file - * - * $LicenseInfo:firstyear=2009&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#ifndef LL_LLUICOLOR_H_ -#define LL_LLUICOLOR_H_ - -#include "v4color.h" - -namespace LLInitParam -{ - template - struct ParamCompare; -} - -class LLUIColor -{ -public: - LLUIColor(); - LLUIColor(const LLColor4& color); - LLUIColor(const LLUIColor* color); - - void set(const LLColor4& color); - void set(const LLUIColor* color); - - const LLColor4& get() const; - - operator const LLColor4& () const; - const LLColor4& operator()() const; - - bool isReference() const; - -private: - friend struct LLInitParam::ParamCompare; - - const LLUIColor* mColorPtr; - LLColor4 mColor; -}; - -namespace LLInitParam -{ - template<> - struct ParamCompare - { - static bool equals(const LLUIColor& a, const LLUIColor& b); - }; -} - -#endif diff --git a/indra/llxuixml/llxuiparser.cpp b/indra/llxuixml/llxuiparser.cpp deleted file mode 100644 index afc76024d1..0000000000 --- a/indra/llxuixml/llxuiparser.cpp +++ /dev/null @@ -1,1756 +0,0 @@ -/** - * @file llxuiparser.cpp - * @brief Utility functions for handling XUI structures in XML - * - * $LicenseInfo:firstyear=2003&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include "linden_common.h" - -#include "llxuiparser.h" - -#include "llxmlnode.h" - -#ifdef LL_STANDALONE -#include -#else -#include "expat/expat.h" -#endif - -#include -#include -//#include -#include - -#include "lluicolor.h" - -using namespace BOOST_SPIRIT_CLASSIC_NS; - -const S32 MAX_STRING_ATTRIBUTE_SIZE = 40; - -static LLInitParam::Parser::parser_read_func_map_t sXSDReadFuncs; -static LLInitParam::Parser::parser_write_func_map_t sXSDWriteFuncs; -static LLInitParam::Parser::parser_inspect_func_map_t sXSDInspectFuncs; - -static LLInitParam::Parser::parser_read_func_map_t sSimpleXUIReadFuncs; -static LLInitParam::Parser::parser_write_func_map_t sSimpleXUIWriteFuncs; -static LLInitParam::Parser::parser_inspect_func_map_t sSimpleXUIInspectFuncs; - -const char* NO_VALUE_MARKER = "no_value"; - -const S32 LINE_NUMBER_HERE = 0; - -struct MaxOccursValues : public LLInitParam::TypeValuesHelper -{ - static void declareValues() - { - declare("unbounded", U32_MAX); - } -}; - -struct Occurs : public LLInitParam::Block -{ - Optional minOccurs; - Optional maxOccurs; - - Occurs() - : minOccurs("minOccurs", 0), - maxOccurs("maxOccurs", U32_MAX) - - {} -}; - - -typedef enum -{ - USE_REQUIRED, - USE_OPTIONAL -} EUse; - -namespace LLInitParam -{ - template<> - struct TypeValues : public TypeValuesHelper - { - static void declareValues() - { - declare("required", USE_REQUIRED); - declare("optional", USE_OPTIONAL); - } - }; -} - -struct Element; -struct Group; -struct Choice; -struct Sequence; -struct Any; - -struct Attribute : public LLInitParam::Block -{ - Mandatory name; - Mandatory type; - Mandatory use; - - Attribute() - : name("name"), - type("type"), - use("use") - {} -}; - -struct Any : public LLInitParam::Block -{ - Optional _namespace; - - Any() - : _namespace("namespace") - {} -}; - -struct All : public LLInitParam::Block -{ - Multiple< Lazy > elements; - - All() - : elements("element") - { - maxOccurs = 1; - } -}; - -struct Choice : public LLInitParam::ChoiceBlock -{ - Alternative< Lazy > element; - Alternative< Lazy > group; - Alternative< Lazy > choice; - Alternative< Lazy > sequence; - Alternative< Lazy > any; - - Choice() - : element("element"), - group("group"), - choice("choice"), - sequence("sequence"), - any("any") - {} - -}; - -struct Sequence : public LLInitParam::ChoiceBlock -{ - Alternative< Lazy > element; - Alternative< Lazy > group; - Alternative< Lazy > choice; - Alternative< Lazy > sequence; - Alternative< Lazy > any; -}; - -struct GroupContents : public LLInitParam::ChoiceBlock -{ - Alternative all; - Alternative choice; - Alternative sequence; - - GroupContents() - : all("all"), - choice("choice"), - sequence("sequence") - {} -}; - -struct Group : public LLInitParam::Block -{ - Optional name, - ref; - - Group() - : name("name"), - ref("ref") - {} -}; - -struct Restriction : public LLInitParam::Block -{ -}; - -struct Extension : public LLInitParam::Block -{ -}; - -struct SimpleContent : public LLInitParam::ChoiceBlock -{ - Alternative restriction; - Alternative extension; - - SimpleContent() - : restriction("restriction"), - extension("extension") - {} -}; - -struct SimpleType : public LLInitParam::Block -{ - // TODO -}; - -struct ComplexContent : public LLInitParam::Block -{ - Optional mixed; - - ComplexContent() - : mixed("mixed", true) - {} -}; - -struct ComplexTypeContents : public LLInitParam::ChoiceBlock -{ - Alternative simple_content; - Alternative complex_content; - Alternative group; - Alternative all; - Alternative choice; - Alternative sequence; - - ComplexTypeContents() - : simple_content("simpleContent"), - complex_content("complexContent"), - group("group"), - all("all"), - choice("choice"), - sequence("sequence") - {} -}; - -struct ComplexType : public LLInitParam::Block -{ - Optional name; - Optional mixed; - - Multiple attribute; - Multiple< Lazy > elements; - - ComplexType() - : name("name"), - attribute("xs:attribute"), - elements("xs:element"), - mixed("mixed") - { - } -}; - -struct ElementContents : public LLInitParam::ChoiceBlock -{ - Alternative simpleType; - Alternative complexType; - - ElementContents() - : simpleType("simpleType"), - complexType("complexType") - {} -}; - -struct Element : public LLInitParam::Block -{ - Optional name, - ref, - type; - - Element() - : name("xs:name"), - ref("xs:ref"), - type("xs:type") - {} -}; - -struct Schema : public LLInitParam::Block -{ -private: - Mandatory targetNamespace, - xmlns, - xs; - -public: - Optional attributeFormDefault, - elementFormDefault; - - Mandatory root_element; - - void setNameSpace(const std::string& ns) {targetNamespace = ns; xmlns = ns;} - - Schema(const std::string& ns = LLStringUtil::null) - : attributeFormDefault("attributeFormDefault"), - elementFormDefault("elementFormDefault"), - xs("xmlns:xs"), - targetNamespace("targetNamespace"), - xmlns("xmlns"), - root_element("xs:element") - { - attributeFormDefault = "unqualified"; - elementFormDefault = "qualified"; - xs = "http://www.w3.org/2001/XMLSchema"; - if (!ns.empty()) - { - setNameSpace(ns); - }; - } - -}; - -// -// LLXSDWriter -// -LLXSDWriter::LLXSDWriter() -: Parser(sXSDReadFuncs, sXSDWriteFuncs, sXSDInspectFuncs) -{ - registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:boolean", _1, _2, _3, _4)); - registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:string", _1, _2, _3, _4)); - registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:unsignedByte", _1, _2, _3, _4)); - registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:signedByte", _1, _2, _3, _4)); - registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:unsignedShort", _1, _2, _3, _4)); - registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:signedShort", _1, _2, _3, _4)); - registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:unsignedInt", _1, _2, _3, _4)); - registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:integer", _1, _2, _3, _4)); - registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:float", _1, _2, _3, _4)); - registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:double", _1, _2, _3, _4)); - registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:string", _1, _2, _3, _4)); - registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:string", _1, _2, _3, _4)); - registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:string", _1, _2, _3, _4)); - registerInspectFunc(boost::bind(&LLXSDWriter::writeAttribute, this, "xs:string", _1, _2, _3, _4)); -} - -void LLXSDWriter::writeXSD(const std::string& type_name, LLXMLNodePtr node, const LLInitParam::BaseBlock& block, const std::string& xml_namespace) -{ - Schema schema(xml_namespace); - - schema.root_element.name = type_name; - Choice& choice = schema.root_element.complexType.choice; - - choice.minOccurs = 0; - choice.maxOccurs = "unbounded"; - - mSchemaNode = node; - //node->setName("xs:schema"); - //node->createChild("attributeFormDefault", true)->setStringValue("unqualified"); - //node->createChild("elementFormDefault", true)->setStringValue("qualified"); - //node->createChild("targetNamespace", true)->setStringValue(xml_namespace); - //node->createChild("xmlns:xs", true)->setStringValue("http://www.w3.org/2001/XMLSchema"); - //node->createChild("xmlns", true)->setStringValue(xml_namespace); - - //node = node->createChild("xs:complexType", false); - //node->createChild("name", true)->setStringValue(type_name); - //node->createChild("mixed", true)->setStringValue("true"); - - //mAttributeNode = node; - //mElementNode = node->createChild("xs:choice", false); - //mElementNode->createChild("minOccurs", true)->setStringValue("0"); - //mElementNode->createChild("maxOccurs", true)->setStringValue("unbounded"); - block.inspectBlock(*this); - - // duplicate element choices - LLXMLNodeList children; - mElementNode->getChildren("xs:element", children, FALSE); - for (LLXMLNodeList::iterator child_it = children.begin(); child_it != children.end(); ++child_it) - { - LLXMLNodePtr child_copy = child_it->second->deepCopy(); - std::string child_name; - child_copy->getAttributeString("name", child_name); - child_copy->setAttributeString("name", type_name + "." + child_name); - mElementNode->addChild(child_copy); - } - - LLXMLNodePtr element_declaration_node = mSchemaNode->createChild("xs:element", false); - element_declaration_node->createChild("name", true)->setStringValue(type_name); - element_declaration_node->createChild("type", true)->setStringValue(type_name); -} - -void LLXSDWriter::writeAttribute(const std::string& type, const Parser::name_stack_t& stack, S32 min_count, S32 max_count, const std::vector* possible_values) -{ - name_stack_t non_empty_names; - std::string attribute_name; - for (name_stack_t::const_iterator it = stack.begin(); - it != stack.end(); - ++it) - { - const std::string& name = it->first; - if (!name.empty()) - { - non_empty_names.push_back(*it); - } - } - - for (name_stack_t::const_iterator it = non_empty_names.begin(); - it != non_empty_names.end(); - ++it) - { - if (!attribute_name.empty()) - { - attribute_name += "."; - } - attribute_name += it->first; - } - - // only flag non-nested attributes as mandatory, nested attributes have variant syntax - // that can't be properly constrained in XSD - // e.g. vs - bool attribute_mandatory = min_count == 1 && max_count == 1 && non_empty_names.size() == 1; - - // don't bother supporting "Multiple" params as xml attributes - if (max_count <= 1) - { - // add compound attribute to root node - addAttributeToSchema(mAttributeNode, attribute_name, type, attribute_mandatory, possible_values); - } - - // now generated nested elements for compound attributes - if (non_empty_names.size() > 1 && !attribute_mandatory) - { - std::string element_name; - - // traverse all but last element, leaving that as an attribute name - name_stack_t::const_iterator end_it = non_empty_names.end(); - end_it--; - - for (name_stack_t::const_iterator it = non_empty_names.begin(); - it != end_it; - ++it) - { - if (it != non_empty_names.begin()) - { - element_name += "."; - } - element_name += it->first; - } - - std::string short_attribute_name = non_empty_names.back().first; - - LLXMLNodePtr complex_type_node; - - // find existing element node here, starting at tail of child list - if (mElementNode->mChildren.notNull()) - { - for(LLXMLNodePtr element = mElementNode->mChildren->tail; - element.notNull(); - element = element->mPrev) - { - std::string name; - if(element->getAttributeString("name", name) && name == element_name) - { - complex_type_node = element->mChildren->head; - break; - } - } - } - //create complex_type node - // - // - // - // - // - if(complex_type_node.isNull()) - { - complex_type_node = mElementNode->createChild("xs:element", false); - - complex_type_node->createChild("minOccurs", true)->setIntValue(min_count); - complex_type_node->createChild("maxOccurs", true)->setIntValue(max_count); - complex_type_node->createChild("name", true)->setStringValue(element_name); - complex_type_node = complex_type_node->createChild("xs:complexType", false); - } - - addAttributeToSchema(complex_type_node, short_attribute_name, type, false, possible_values); - } -} - -void LLXSDWriter::addAttributeToSchema(LLXMLNodePtr type_declaration_node, const std::string& attribute_name, const std::string& type, bool mandatory, const std::vector* possible_values) -{ - if (!attribute_name.empty()) - { - LLXMLNodePtr new_enum_type_node; - if (possible_values != NULL) - { - // custom attribute type, for example - // - // - // - // - // - // - new_enum_type_node = new LLXMLNode("xs:simpleType", false); - - LLXMLNodePtr restriction_node = new_enum_type_node->createChild("xs:restriction", false); - restriction_node->createChild("base", true)->setStringValue("xs:string"); - - for (std::vector::const_iterator it = possible_values->begin(); - it != possible_values->end(); - ++it) - { - LLXMLNodePtr enum_node = restriction_node->createChild("xs:enumeration", false); - enum_node->createChild("value", true)->setStringValue(*it); - } - } - - string_set_t& attributes_written = mAttributesWritten[type_declaration_node]; - - string_set_t::iterator found_it = attributes_written.lower_bound(attribute_name); - - // attribute not yet declared - if (found_it == attributes_written.end() || attributes_written.key_comp()(attribute_name, *found_it)) - { - attributes_written.insert(found_it, attribute_name); - - LLXMLNodePtr attribute_node = type_declaration_node->createChild("xs:attribute", false); - - // attribute name - attribute_node->createChild("name", true)->setStringValue(attribute_name); - - if (new_enum_type_node.notNull()) - { - attribute_node->addChild(new_enum_type_node); - } - else - { - // simple attribute type - attribute_node->createChild("type", true)->setStringValue(type); - } - - // required or optional - attribute_node->createChild("use", true)->setStringValue(mandatory ? "required" : "optional"); - } - // attribute exists...handle collision of same name attributes with potentially different types - else - { - LLXMLNodePtr attribute_declaration; - if (type_declaration_node.notNull()) - { - for(LLXMLNodePtr node = type_declaration_node->mChildren->tail; - node.notNull(); - node = node->mPrev) - { - std::string name; - if (node->getAttributeString("name", name) && name == attribute_name) - { - attribute_declaration = node; - break; - } - } - } - - bool new_type_is_enum = new_enum_type_node.notNull(); - bool existing_type_is_enum = !attribute_declaration->hasAttribute("type"); - - // either type is enum, revert to string in collision - // don't bother to check for enum equivalence - if (new_type_is_enum || existing_type_is_enum) - { - if (attribute_declaration->hasAttribute("type")) - { - attribute_declaration->setAttributeString("type", "xs:string"); - } - else - { - attribute_declaration->createChild("type", true)->setStringValue("xs:string"); - } - attribute_declaration->deleteChildren("xs:simpleType"); - } - else - { - // check for collision of different standard types - std::string existing_type; - attribute_declaration->getAttributeString("type", existing_type); - // if current type is not the same as the new type, revert to strnig - if (existing_type != type) - { - // ...than use most general type, string - attribute_declaration->setAttributeString("type", "string"); - } - } - } - } -} - -// -// LLXUIXSDWriter -// -void LLXUIXSDWriter::writeXSD(const std::string& type_name, const std::string& path, const LLInitParam::BaseBlock& block) -{ - std::string file_name(path); - file_name += type_name + ".xsd"; - LLXMLNodePtr root_nodep = new LLXMLNode(); - - LLXSDWriter::writeXSD(type_name, root_nodep, block, "http://www.lindenlab.com/xui"); - - // add includes for all possible children - const std::type_info* type = *LLWidgetTypeRegistry::instance().getValue(type_name); - const widget_registry_t* widget_registryp = LLChildRegistryRegistry::instance().getValue(type); - - // add choices for valid children - if (widget_registryp) - { - // add include declarations for all valid children - for (widget_registry_t::Registrar::registry_map_t::const_iterator it = widget_registryp->currentRegistrar().beginItems(); - it != widget_registryp->currentRegistrar().endItems(); - ++it) - { - std::string widget_name = it->first; - if (widget_name == type_name) - { - continue; - } - LLXMLNodePtr nodep = new LLXMLNode("xs:include", false); - nodep->createChild("schemaLocation", true)->setStringValue(widget_name + ".xsd"); - - // add to front of schema - mSchemaNode->addChild(nodep, mSchemaNode); - } - - for (widget_registry_t::Registrar::registry_map_t::const_iterator it = widget_registryp->currentRegistrar().beginItems(); - it != widget_registryp->currentRegistrar().endItems(); - ++it) - { - std::string widget_name = it->first; - // - LLXMLNodePtr widget_node = mElementNode->createChild("xs:element", false); - widget_node->createChild("name", true)->setStringValue(widget_name); - widget_node->createChild("type", true)->setStringValue(widget_name); - } - } - - LLFILE* xsd_file = LLFile::fopen(file_name.c_str(), "w"); - LLXMLNode::writeHeaderToFile(xsd_file); - root_nodep->writeToFile(xsd_file); - fclose(xsd_file); -} - -static LLInitParam::Parser::parser_read_func_map_t sXUIReadFuncs; -static LLInitParam::Parser::parser_write_func_map_t sXUIWriteFuncs; -static LLInitParam::Parser::parser_inspect_func_map_t sXUIInspectFuncs; - -// -// LLXUIParser -// -LLXUIParser::LLXUIParser() -: Parser(sXUIReadFuncs, sXUIWriteFuncs, sXUIInspectFuncs), - mCurReadDepth(0) -{ - if (sXUIReadFuncs.empty()) - { - registerParserFuncs(readFlag, writeFlag); - registerParserFuncs(readBoolValue, writeBoolValue); - registerParserFuncs(readStringValue, writeStringValue); - registerParserFuncs(readU8Value, writeU8Value); - registerParserFuncs(readS8Value, writeS8Value); - registerParserFuncs(readU16Value, writeU16Value); - registerParserFuncs(readS16Value, writeS16Value); - registerParserFuncs(readU32Value, writeU32Value); - registerParserFuncs(readS32Value, writeS32Value); - registerParserFuncs(readF32Value, writeF32Value); - registerParserFuncs(readF64Value, writeF64Value); - registerParserFuncs(readColor4Value, writeColor4Value); - registerParserFuncs(readUIColorValue, writeUIColorValue); - registerParserFuncs(readUUIDValue, writeUUIDValue); - registerParserFuncs(readSDValue, writeSDValue); - } -} - -static LLFastTimer::DeclareTimer FTM_PARSE_XUI("XUI Parsing"); -const LLXMLNodePtr DUMMY_NODE = new LLXMLNode(); - -void LLXUIParser::readXUI(LLXMLNodePtr node, LLInitParam::BaseBlock& block, const std::string& filename, bool silent) -{ - LLFastTimer timer(FTM_PARSE_XUI); - mNameStack.clear(); - mRootNodeName = node->getName()->mString; - mCurFileName = filename; - mCurReadDepth = 0; - setParseSilently(silent); - - if (node.isNull()) - { - parserWarning("Invalid node"); - } - else - { - readXUIImpl(node, block); - } -} - -bool LLXUIParser::readXUIImpl(LLXMLNodePtr nodep, LLInitParam::BaseBlock& block) -{ - typedef boost::tokenizer > tokenizer; - boost::char_separator sep("."); - - bool values_parsed = false; - bool silent = mCurReadDepth > 0; - - if (nodep->getFirstChild().isNull() - && nodep->mAttributes.empty() - && nodep->getSanitizedValue().empty()) - { - // empty node, just parse as flag - mCurReadNode = DUMMY_NODE; - return block.submitValue(mNameStack, *this, silent); - } - - // submit attributes for current node - values_parsed |= readAttributes(nodep, block); - - // treat text contents of xml node as "value" parameter - std::string text_contents = nodep->getSanitizedValue(); - if (!text_contents.empty()) - { - mCurReadNode = nodep; - mNameStack.push_back(std::make_pair(std::string("value"), true)); - // child nodes are not necessarily valid parameters (could be a child widget) - // so don't complain once we've recursed - if (!block.submitValue(mNameStack, *this, true)) - { - mNameStack.pop_back(); - block.submitValue(mNameStack, *this, silent); - } - else - { - mNameStack.pop_back(); - } - } - - // then traverse children - // child node must start with last name of parent node (our "scope") - // for example: "" - // which equates to the following nesting: - // button - // param - // nested_param1 - // nested_param2 - // nested_param3 - mCurReadDepth++; - for(LLXMLNodePtr childp = nodep->getFirstChild(); childp.notNull();) - { - std::string child_name(childp->getName()->mString); - S32 num_tokens_pushed = 0; - - // for non "dotted" child nodes check to see if child node maps to another widget type - // and if not, treat as a child element of the current node - // e.g. will interpret as "button.rect" - // since there is no widget named "rect" - if (child_name.find(".") == std::string::npos) - { - mNameStack.push_back(std::make_pair(child_name, true)); - num_tokens_pushed++; - } - else - { - // parse out "dotted" name into individual tokens - tokenizer name_tokens(child_name, sep); - - tokenizer::iterator name_token_it = name_tokens.begin(); - if(name_token_it == name_tokens.end()) - { - childp = childp->getNextSibling(); - continue; - } - - // check for proper nesting - if (mNameStack.empty()) - { - if (*name_token_it != mRootNodeName) - { - childp = childp->getNextSibling(); - continue; - } - } - else if(mNameStack.back().first != *name_token_it) - { - childp = childp->getNextSibling(); - continue; - } - - // now ignore first token - ++name_token_it; - - // copy remaining tokens on to our running token list - for(tokenizer::iterator token_to_push = name_token_it; token_to_push != name_tokens.end(); ++token_to_push) - { - mNameStack.push_back(std::make_pair(*token_to_push, true)); - num_tokens_pushed++; - } - } - - // recurse and visit children XML nodes - if(readXUIImpl(childp, block)) - { - // child node successfully parsed, remove from DOM - - values_parsed = true; - LLXMLNodePtr node_to_remove = childp; - childp = childp->getNextSibling(); - - nodep->deleteChild(node_to_remove); - } - else - { - childp = childp->getNextSibling(); - } - - while(num_tokens_pushed-- > 0) - { - mNameStack.pop_back(); - } - } - mCurReadDepth--; - return values_parsed; -} - -bool LLXUIParser::readAttributes(LLXMLNodePtr nodep, LLInitParam::BaseBlock& block) -{ - typedef boost::tokenizer > tokenizer; - boost::char_separator sep("."); - - bool any_parsed = false; - bool silent = mCurReadDepth > 0; - - for(LLXMLAttribList::const_iterator attribute_it = nodep->mAttributes.begin(); - attribute_it != nodep->mAttributes.end(); - ++attribute_it) - { - S32 num_tokens_pushed = 0; - std::string attribute_name(attribute_it->first->mString); - mCurReadNode = attribute_it->second; - - tokenizer name_tokens(attribute_name, sep); - // copy remaining tokens on to our running token list - for(tokenizer::iterator token_to_push = name_tokens.begin(); token_to_push != name_tokens.end(); ++token_to_push) - { - mNameStack.push_back(std::make_pair(*token_to_push, true)); - num_tokens_pushed++; - } - - // child nodes are not necessarily valid attributes, so don't complain once we've recursed - any_parsed |= block.submitValue(mNameStack, *this, silent); - - while(num_tokens_pushed-- > 0) - { - mNameStack.pop_back(); - } - } - - return any_parsed; -} - -void LLXUIParser::writeXUI(LLXMLNodePtr node, const LLInitParam::BaseBlock &block, const LLInitParam::BaseBlock* diff_block) -{ - mWriteRootNode = node; - name_stack_t name_stack = Parser::name_stack_t(); - block.serializeBlock(*this, name_stack, diff_block); - mOutNodes.clear(); -} - -// go from a stack of names to a specific XML node -LLXMLNodePtr LLXUIParser::getNode(name_stack_t& stack) -{ - LLXMLNodePtr out_node = mWriteRootNode; - - name_stack_t::iterator next_it = stack.begin(); - for (name_stack_t::iterator it = stack.begin(); - it != stack.end(); - it = next_it) - { - ++next_it; - if (it->first.empty()) - { - it->second = false; - continue; - } - - out_nodes_t::iterator found_it = mOutNodes.find(it->first); - - // node with this name not yet written - if (found_it == mOutNodes.end() || it->second) - { - // make an attribute if we are the last element on the name stack - bool is_attribute = next_it == stack.end(); - LLXMLNodePtr new_node = new LLXMLNode(it->first.c_str(), is_attribute); - out_node->addChild(new_node); - mOutNodes[it->first] = new_node; - out_node = new_node; - it->second = false; - } - else - { - out_node = found_it->second; - } - } - - return (out_node == mWriteRootNode ? LLXMLNodePtr(NULL) : out_node); -} - -bool LLXUIParser::readFlag(Parser& parser, void* val_ptr) -{ - LLXUIParser& self = static_cast(parser); - return self.mCurReadNode == DUMMY_NODE; -} - -bool LLXUIParser::writeFlag(Parser& parser, const void* val_ptr, name_stack_t& stack) -{ - // just create node - LLXUIParser& self = static_cast(parser); - LLXMLNodePtr node = self.getNode(stack); - return node.notNull(); -} - -bool LLXUIParser::readBoolValue(Parser& parser, void* val_ptr) -{ - S32 value; - LLXUIParser& self = static_cast(parser); - bool success = self.mCurReadNode->getBoolValue(1, &value); - *((bool*)val_ptr) = (value != FALSE); - return success; -} - -bool LLXUIParser::writeBoolValue(Parser& parser, const void* val_ptr, name_stack_t& stack) -{ - LLXUIParser& self = static_cast(parser); - LLXMLNodePtr node = self.getNode(stack); - if (node.notNull()) - { - node->setBoolValue(*((bool*)val_ptr)); - return true; - } - return false; -} - -bool LLXUIParser::readStringValue(Parser& parser, void* val_ptr) -{ - LLXUIParser& self = static_cast(parser); - *((std::string*)val_ptr) = self.mCurReadNode->getSanitizedValue(); - return true; -} - -bool LLXUIParser::writeStringValue(Parser& parser, const void* val_ptr, name_stack_t& stack) -{ - LLXUIParser& self = static_cast(parser); - LLXMLNodePtr node = self.getNode(stack); - if (node.notNull()) - { - const std::string* string_val = reinterpret_cast(val_ptr); - if (string_val->find('\n') != std::string::npos - || string_val->size() > MAX_STRING_ATTRIBUTE_SIZE) - { - // don't write strings with newlines into attributes - std::string attribute_name = node->getName()->mString; - LLXMLNodePtr parent_node = node->mParent; - parent_node->deleteChild(node); - // write results in text contents of node - if (attribute_name == "value") - { - // "value" is implicit, just write to parent - node = parent_node; - } - else - { - // create a child that is not an attribute, but with same name - node = parent_node->createChild(attribute_name.c_str(), false); - } - } - node->setStringValue(*string_val); - return true; - } - return false; -} - -bool LLXUIParser::readU8Value(Parser& parser, void* val_ptr) -{ - LLXUIParser& self = static_cast(parser); - return self.mCurReadNode->getByteValue(1, (U8*)val_ptr); -} - -bool LLXUIParser::writeU8Value(Parser& parser, const void* val_ptr, name_stack_t& stack) -{ - LLXUIParser& self = static_cast(parser); - LLXMLNodePtr node = self.getNode(stack); - if (node.notNull()) - { - node->setUnsignedValue(*((U8*)val_ptr)); - return true; - } - return false; -} - -bool LLXUIParser::readS8Value(Parser& parser, void* val_ptr) -{ - LLXUIParser& self = static_cast(parser); - S32 value; - if(self.mCurReadNode->getIntValue(1, &value)) - { - *((S8*)val_ptr) = value; - return true; - } - return false; -} - -bool LLXUIParser::writeS8Value(Parser& parser, const void* val_ptr, name_stack_t& stack) -{ - LLXUIParser& self = static_cast(parser); - LLXMLNodePtr node = self.getNode(stack); - if (node.notNull()) - { - node->setIntValue(*((S8*)val_ptr)); - return true; - } - return false; -} - -bool LLXUIParser::readU16Value(Parser& parser, void* val_ptr) -{ - LLXUIParser& self = static_cast(parser); - U32 value; - if(self.mCurReadNode->getUnsignedValue(1, &value)) - { - *((U16*)val_ptr) = value; - return true; - } - return false; -} - -bool LLXUIParser::writeU16Value(Parser& parser, const void* val_ptr, name_stack_t& stack) -{ - LLXUIParser& self = static_cast(parser); - LLXMLNodePtr node = self.getNode(stack); - if (node.notNull()) - { - node->setUnsignedValue(*((U16*)val_ptr)); - return true; - } - return false; -} - -bool LLXUIParser::readS16Value(Parser& parser, void* val_ptr) -{ - LLXUIParser& self = static_cast(parser); - S32 value; - if(self.mCurReadNode->getIntValue(1, &value)) - { - *((S16*)val_ptr) = value; - return true; - } - return false; -} - -bool LLXUIParser::writeS16Value(Parser& parser, const void* val_ptr, name_stack_t& stack) -{ - LLXUIParser& self = static_cast(parser); - LLXMLNodePtr node = self.getNode(stack); - if (node.notNull()) - { - node->setIntValue(*((S16*)val_ptr)); - return true; - } - return false; -} - -bool LLXUIParser::readU32Value(Parser& parser, void* val_ptr) -{ - LLXUIParser& self = static_cast(parser); - return self.mCurReadNode->getUnsignedValue(1, (U32*)val_ptr); -} - -bool LLXUIParser::writeU32Value(Parser& parser, const void* val_ptr, name_stack_t& stack) -{ - LLXUIParser& self = static_cast(parser); - LLXMLNodePtr node = self.getNode(stack); - if (node.notNull()) - { - node->setUnsignedValue(*((U32*)val_ptr)); - return true; - } - return false; -} - -bool LLXUIParser::readS32Value(Parser& parser, void* val_ptr) -{ - LLXUIParser& self = static_cast(parser); - return self.mCurReadNode->getIntValue(1, (S32*)val_ptr); -} - -bool LLXUIParser::writeS32Value(Parser& parser, const void* val_ptr, name_stack_t& stack) -{ - LLXUIParser& self = static_cast(parser); - LLXMLNodePtr node = self.getNode(stack); - if (node.notNull()) - { - node->setIntValue(*((S32*)val_ptr)); - return true; - } - return false; -} - -bool LLXUIParser::readF32Value(Parser& parser, void* val_ptr) -{ - LLXUIParser& self = static_cast(parser); - return self.mCurReadNode->getFloatValue(1, (F32*)val_ptr); -} - -bool LLXUIParser::writeF32Value(Parser& parser, const void* val_ptr, name_stack_t& stack) -{ - LLXUIParser& self = static_cast(parser); - LLXMLNodePtr node = self.getNode(stack); - if (node.notNull()) - { - node->setFloatValue(*((F32*)val_ptr)); - return true; - } - return false; -} - -bool LLXUIParser::readF64Value(Parser& parser, void* val_ptr) -{ - LLXUIParser& self = static_cast(parser); - return self.mCurReadNode->getDoubleValue(1, (F64*)val_ptr); -} - -bool LLXUIParser::writeF64Value(Parser& parser, const void* val_ptr, name_stack_t& stack) -{ - LLXUIParser& self = static_cast(parser); - LLXMLNodePtr node = self.getNode(stack); - if (node.notNull()) - { - node->setDoubleValue(*((F64*)val_ptr)); - return true; - } - return false; -} - -bool LLXUIParser::readColor4Value(Parser& parser, void* val_ptr) -{ - LLXUIParser& self = static_cast(parser); - LLColor4* colorp = (LLColor4*)val_ptr; - if(self.mCurReadNode->getFloatValue(4, colorp->mV) >= 3) - { - return true; - } - - return false; -} - -bool LLXUIParser::writeColor4Value(Parser& parser, const void* val_ptr, name_stack_t& stack) -{ - LLXUIParser& self = static_cast(parser); - LLXMLNodePtr node = self.getNode(stack); - if (node.notNull()) - { - LLColor4 color = *((LLColor4*)val_ptr); - node->setFloatValue(4, color.mV); - return true; - } - return false; -} - -bool LLXUIParser::readUIColorValue(Parser& parser, void* val_ptr) -{ - LLXUIParser& self = static_cast(parser); - LLUIColor* param = (LLUIColor*)val_ptr; - LLColor4 color; - bool success = self.mCurReadNode->getFloatValue(4, color.mV) >= 3; - if (success) - { - param->set(color); - return true; - } - return false; -} - -bool LLXUIParser::writeUIColorValue(Parser& parser, const void* val_ptr, name_stack_t& stack) -{ - LLXUIParser& self = static_cast(parser); - LLXMLNodePtr node = self.getNode(stack); - if (node.notNull()) - { - LLUIColor color = *((LLUIColor*)val_ptr); - //RN: don't write out the color that is represented by a function - // rely on param block exporting to get the reference to the color settings - if (color.isReference()) return false; - node->setFloatValue(4, color.get().mV); - return true; - } - return false; -} - -bool LLXUIParser::readUUIDValue(Parser& parser, void* val_ptr) -{ - LLXUIParser& self = static_cast(parser); - LLUUID temp_id; - // LLUUID::set is destructive, so use temporary value - if (temp_id.set(self.mCurReadNode->getSanitizedValue())) - { - *(LLUUID*)(val_ptr) = temp_id; - return true; - } - return false; -} - -bool LLXUIParser::writeUUIDValue(Parser& parser, const void* val_ptr, name_stack_t& stack) -{ - LLXUIParser& self = static_cast(parser); - LLXMLNodePtr node = self.getNode(stack); - if (node.notNull()) - { - node->setStringValue(((LLUUID*)val_ptr)->asString()); - return true; - } - return false; -} - -bool LLXUIParser::readSDValue(Parser& parser, void* val_ptr) -{ - LLXUIParser& self = static_cast(parser); - *((LLSD*)val_ptr) = LLSD(self.mCurReadNode->getSanitizedValue()); - return true; -} - -bool LLXUIParser::writeSDValue(Parser& parser, const void* val_ptr, name_stack_t& stack) -{ - LLXUIParser& self = static_cast(parser); - - LLXMLNodePtr node = self.getNode(stack); - if (node.notNull()) - { - std::string string_val = ((LLSD*)val_ptr)->asString(); - if (string_val.find('\n') != std::string::npos || string_val.size() > MAX_STRING_ATTRIBUTE_SIZE) - { - // don't write strings with newlines into attributes - std::string attribute_name = node->getName()->mString; - LLXMLNodePtr parent_node = node->mParent; - parent_node->deleteChild(node); - // write results in text contents of node - if (attribute_name == "value") - { - // "value" is implicit, just write to parent - node = parent_node; - } - else - { - node = parent_node->createChild(attribute_name.c_str(), false); - } - } - - node->setStringValue(string_val); - return true; - } - return false; -} - -/*virtual*/ std::string LLXUIParser::getCurrentElementName() -{ - std::string full_name; - for (name_stack_t::iterator it = mNameStack.begin(); - it != mNameStack.end(); - ++it) - { - full_name += it->first + "."; // build up dotted names: "button.param.nestedparam." - } - - return full_name; -} - -void LLXUIParser::parserWarning(const std::string& message) -{ -#ifdef LL_WINDOWS - // use Visual Studo friendly formatting of output message for easy access to originating xml - llutf16string utf16str = utf8str_to_utf16str(llformat("%s(%d):\t%s", mCurFileName.c_str(), mCurReadNode->getLineNumber(), message.c_str()).c_str()); - utf16str += '\n'; - OutputDebugString(utf16str.c_str()); -#else - Parser::parserWarning(message); -#endif -} - -void LLXUIParser::parserError(const std::string& message) -{ -#ifdef LL_WINDOWS - llutf16string utf16str = utf8str_to_utf16str(llformat("%s(%d):\t%s", mCurFileName.c_str(), mCurReadNode->getLineNumber(), message.c_str()).c_str()); - utf16str += '\n'; - OutputDebugString(utf16str.c_str()); -#else - Parser::parserError(message); -#endif -} - - -// -// LLSimpleXUIParser -// - -struct ScopedFile -{ - ScopedFile( const std::string& filename, const char* accessmode ) - { - mFile = LLFile::fopen(filename, accessmode); - } - - ~ScopedFile() - { - fclose(mFile); - mFile = NULL; - } - - S32 getRemainingBytes() - { - if (!isOpen()) return 0; - - S32 cur_pos = ftell(mFile); - fseek(mFile, 0L, SEEK_END); - S32 file_size = ftell(mFile); - fseek(mFile, cur_pos, SEEK_SET); - return file_size - cur_pos; - } - - bool isOpen() { return mFile != NULL; } - - LLFILE* mFile; -}; -LLSimpleXUIParser::LLSimpleXUIParser(LLSimpleXUIParser::element_start_callback_t element_cb) -: Parser(sSimpleXUIReadFuncs, sSimpleXUIWriteFuncs, sSimpleXUIInspectFuncs), - mCurReadDepth(0), - mElementCB(element_cb) -{ - if (sSimpleXUIReadFuncs.empty()) - { - registerParserFuncs(readFlag); - registerParserFuncs(readBoolValue); - registerParserFuncs(readStringValue); - registerParserFuncs(readU8Value); - registerParserFuncs(readS8Value); - registerParserFuncs(readU16Value); - registerParserFuncs(readS16Value); - registerParserFuncs(readU32Value); - registerParserFuncs(readS32Value); - registerParserFuncs(readF32Value); - registerParserFuncs(readF64Value); - registerParserFuncs(readColor4Value); - registerParserFuncs(readUIColorValue); - registerParserFuncs(readUUIDValue); - registerParserFuncs(readSDValue); - } -} - -LLSimpleXUIParser::~LLSimpleXUIParser() -{ -} - - -bool LLSimpleXUIParser::readXUI(const std::string& filename, LLInitParam::BaseBlock& block, bool silent) -{ - LLFastTimer timer(FTM_PARSE_XUI); - - mParser = XML_ParserCreate(NULL); - XML_SetUserData(mParser, this); - XML_SetElementHandler( mParser, startElementHandler, endElementHandler); - XML_SetCharacterDataHandler( mParser, characterDataHandler); - - mOutputStack.push_back(std::make_pair(&block, 0)); - mNameStack.clear(); - mCurFileName = filename; - mCurReadDepth = 0; - setParseSilently(silent); - - ScopedFile file(filename, "rb"); - if( !file.isOpen() ) - { - LL_WARNS("ReadXUI") << "Unable to open file " << filename << LL_ENDL; - XML_ParserFree( mParser ); - return false; - } - - S32 bytes_read = 0; - - S32 buffer_size = file.getRemainingBytes(); - void* buffer = XML_GetBuffer(mParser, buffer_size); - if( !buffer ) - { - LL_WARNS("ReadXUI") << "Unable to allocate XML buffer while reading file " << filename << LL_ENDL; - XML_ParserFree( mParser ); - return false; - } - - bytes_read = (S32)fread(buffer, 1, buffer_size, file.mFile); - if( bytes_read <= 0 ) - { - LL_WARNS("ReadXUI") << "Error while reading file " << filename << LL_ENDL; - XML_ParserFree( mParser ); - return false; - } - - mEmptyLeafNode.push_back(false); - - if( !XML_ParseBuffer(mParser, bytes_read, TRUE ) ) - { - LL_WARNS("ReadXUI") << "Error while parsing file " << filename << LL_ENDL; - XML_ParserFree( mParser ); - return false; - } - - mEmptyLeafNode.pop_back(); - - XML_ParserFree( mParser ); - return true; -} - -void LLSimpleXUIParser::startElementHandler(void *userData, const char *name, const char **atts) -{ - LLSimpleXUIParser* self = reinterpret_cast(userData); - self->startElement(name, atts); -} - -void LLSimpleXUIParser::endElementHandler(void *userData, const char *name) -{ - LLSimpleXUIParser* self = reinterpret_cast(userData); - self->endElement(name); -} - -void LLSimpleXUIParser::characterDataHandler(void *userData, const char *s, int len) -{ - LLSimpleXUIParser* self = reinterpret_cast(userData); - self->characterData(s, len); -} - -void LLSimpleXUIParser::characterData(const char *s, int len) -{ - mTextContents += std::string(s, len); -} - -void LLSimpleXUIParser::startElement(const char *name, const char **atts) -{ - processText(); - - typedef boost::tokenizer > tokenizer; - boost::char_separator sep("."); - - if (mElementCB) - { - LLInitParam::BaseBlock* blockp = mElementCB(*this, name); - if (blockp) - { - mOutputStack.push_back(std::make_pair(blockp, 0)); - } - } - - mOutputStack.back().second++; - S32 num_tokens_pushed = 0; - std::string child_name(name); - - if (mOutputStack.back().second == 1) - { // root node for this block - mScope.push_back(child_name); - } - else - { // compound attribute - if (child_name.find(".") == std::string::npos) - { - mNameStack.push_back(std::make_pair(child_name, true)); - num_tokens_pushed++; - mScope.push_back(child_name); - } - else - { - // parse out "dotted" name into individual tokens - tokenizer name_tokens(child_name, sep); - - tokenizer::iterator name_token_it = name_tokens.begin(); - if(name_token_it == name_tokens.end()) - { - return; - } - - // check for proper nesting - if(!mScope.empty() && *name_token_it != mScope.back()) - { - return; - } - - // now ignore first token - ++name_token_it; - - // copy remaining tokens on to our running token list - for(tokenizer::iterator token_to_push = name_token_it; token_to_push != name_tokens.end(); ++token_to_push) - { - mNameStack.push_back(std::make_pair(*token_to_push, true)); - num_tokens_pushed++; - } - mScope.push_back(mNameStack.back().first); - } - } - - // parent node is not empty - mEmptyLeafNode.back() = false; - // we are empty if we have no attributes - mEmptyLeafNode.push_back(atts[0] == NULL); - - mTokenSizeStack.push_back(num_tokens_pushed); - readAttributes(atts); - -} - -void LLSimpleXUIParser::endElement(const char *name) -{ - bool has_text = processText(); - - // no text, attributes, or children - if (!has_text && mEmptyLeafNode.back()) - { - // submit this as a valueless name (even though there might be text contents we haven't seen yet) - mCurAttributeValueBegin = NO_VALUE_MARKER; - mOutputStack.back().first->submitValue(mNameStack, *this, mParseSilently); - } - - if (--mOutputStack.back().second == 0) - { - if (mOutputStack.empty()) - { - LL_ERRS("ReadXUI") << "Parameter block output stack popped while empty." << LL_ENDL; - } - mOutputStack.pop_back(); - } - - S32 num_tokens_to_pop = mTokenSizeStack.back(); - mTokenSizeStack.pop_back(); - while(num_tokens_to_pop-- > 0) - { - mNameStack.pop_back(); - } - mScope.pop_back(); - mEmptyLeafNode.pop_back(); -} - -bool LLSimpleXUIParser::readAttributes(const char **atts) -{ - typedef boost::tokenizer > tokenizer; - boost::char_separator sep("."); - - bool any_parsed = false; - for(S32 i = 0; atts[i] && atts[i+1]; i += 2 ) - { - std::string attribute_name(atts[i]); - mCurAttributeValueBegin = atts[i+1]; - - S32 num_tokens_pushed = 0; - tokenizer name_tokens(attribute_name, sep); - // copy remaining tokens on to our running token list - for(tokenizer::iterator token_to_push = name_tokens.begin(); token_to_push != name_tokens.end(); ++token_to_push) - { - mNameStack.push_back(std::make_pair(*token_to_push, true)); - num_tokens_pushed++; - } - - // child nodes are not necessarily valid attributes, so don't complain once we've recursed - any_parsed |= mOutputStack.back().first->submitValue(mNameStack, *this, mParseSilently); - - while(num_tokens_pushed-- > 0) - { - mNameStack.pop_back(); - } - } - return any_parsed; -} - -bool LLSimpleXUIParser::processText() -{ - if (!mTextContents.empty()) - { - LLStringUtil::trim(mTextContents); - if (!mTextContents.empty()) - { - mNameStack.push_back(std::make_pair(std::string("value"), true)); - mCurAttributeValueBegin = mTextContents.c_str(); - mOutputStack.back().first->submitValue(mNameStack, *this, mParseSilently); - mNameStack.pop_back(); - } - mTextContents.clear(); - return true; - } - return false; -} - -/*virtual*/ std::string LLSimpleXUIParser::getCurrentElementName() -{ - std::string full_name; - for (name_stack_t::iterator it = mNameStack.begin(); - it != mNameStack.end(); - ++it) - { - full_name += it->first + "."; // build up dotted names: "button.param.nestedparam." - } - - return full_name; -} - -void LLSimpleXUIParser::parserWarning(const std::string& message) -{ -#ifdef LL_WINDOWS - // use Visual Studo friendly formatting of output message for easy access to originating xml - llutf16string utf16str = utf8str_to_utf16str(llformat("%s(%d):\t%s", mCurFileName.c_str(), LINE_NUMBER_HERE, message.c_str()).c_str()); - utf16str += '\n'; - OutputDebugString(utf16str.c_str()); -#else - Parser::parserWarning(message); -#endif -} - -void LLSimpleXUIParser::parserError(const std::string& message) -{ -#ifdef LL_WINDOWS - llutf16string utf16str = utf8str_to_utf16str(llformat("%s(%d):\t%s", mCurFileName.c_str(), LINE_NUMBER_HERE, message.c_str()).c_str()); - utf16str += '\n'; - OutputDebugString(utf16str.c_str()); -#else - Parser::parserError(message); -#endif -} - -bool LLSimpleXUIParser::readFlag(Parser& parser, void* val_ptr) -{ - LLSimpleXUIParser& self = static_cast(parser); - return self.mCurAttributeValueBegin == NO_VALUE_MARKER; -} - -bool LLSimpleXUIParser::readBoolValue(Parser& parser, void* val_ptr) -{ - LLSimpleXUIParser& self = static_cast(parser); - if (!strcmp(self.mCurAttributeValueBegin, "true")) - { - *((bool*)val_ptr) = true; - return true; - } - else if (!strcmp(self.mCurAttributeValueBegin, "false")) - { - *((bool*)val_ptr) = false; - return true; - } - - return false; -} - -bool LLSimpleXUIParser::readStringValue(Parser& parser, void* val_ptr) -{ - LLSimpleXUIParser& self = static_cast(parser); - *((std::string*)val_ptr) = self.mCurAttributeValueBegin; - return true; -} - -bool LLSimpleXUIParser::readU8Value(Parser& parser, void* val_ptr) -{ - LLSimpleXUIParser& self = static_cast(parser); - return parse(self.mCurAttributeValueBegin, uint_p[assign_a(*(U8*)val_ptr)]).full; -} - -bool LLSimpleXUIParser::readS8Value(Parser& parser, void* val_ptr) -{ - LLSimpleXUIParser& self = static_cast(parser); - return parse(self.mCurAttributeValueBegin, int_p[assign_a(*(S8*)val_ptr)]).full; -} - -bool LLSimpleXUIParser::readU16Value(Parser& parser, void* val_ptr) -{ - LLSimpleXUIParser& self = static_cast(parser); - return parse(self.mCurAttributeValueBegin, uint_p[assign_a(*(U16*)val_ptr)]).full; -} - -bool LLSimpleXUIParser::readS16Value(Parser& parser, void* val_ptr) -{ - LLSimpleXUIParser& self = static_cast(parser); - return parse(self.mCurAttributeValueBegin, int_p[assign_a(*(S16*)val_ptr)]).full; -} - -bool LLSimpleXUIParser::readU32Value(Parser& parser, void* val_ptr) -{ - LLSimpleXUIParser& self = static_cast(parser); - return parse(self.mCurAttributeValueBegin, uint_p[assign_a(*(U32*)val_ptr)]).full; -} - -bool LLSimpleXUIParser::readS32Value(Parser& parser, void* val_ptr) -{ - LLSimpleXUIParser& self = static_cast(parser); - return parse(self.mCurAttributeValueBegin, int_p[assign_a(*(S32*)val_ptr)]).full; -} - -bool LLSimpleXUIParser::readF32Value(Parser& parser, void* val_ptr) -{ - LLSimpleXUIParser& self = static_cast(parser); - return parse(self.mCurAttributeValueBegin, real_p[assign_a(*(F32*)val_ptr)]).full; -} - -bool LLSimpleXUIParser::readF64Value(Parser& parser, void* val_ptr) -{ - LLSimpleXUIParser& self = static_cast(parser); - return parse(self.mCurAttributeValueBegin, real_p[assign_a(*(F64*)val_ptr)]).full; -} - -bool LLSimpleXUIParser::readColor4Value(Parser& parser, void* val_ptr) -{ - LLSimpleXUIParser& self = static_cast(parser); - LLColor4 value; - - if (parse(self.mCurAttributeValueBegin, real_p[assign_a(value.mV[0])] >> real_p[assign_a(value.mV[1])] >> real_p[assign_a(value.mV[2])] >> real_p[assign_a(value.mV[3])], space_p).full) - { - *(LLColor4*)(val_ptr) = value; - return true; - } - return false; -} - -bool LLSimpleXUIParser::readUIColorValue(Parser& parser, void* val_ptr) -{ - LLSimpleXUIParser& self = static_cast(parser); - LLColor4 value; - LLUIColor* colorp = (LLUIColor*)val_ptr; - - if (parse(self.mCurAttributeValueBegin, real_p[assign_a(value.mV[0])] >> real_p[assign_a(value.mV[1])] >> real_p[assign_a(value.mV[2])] >> real_p[assign_a(value.mV[3])], space_p).full) - { - colorp->set(value); - return true; - } - return false; -} - -bool LLSimpleXUIParser::readUUIDValue(Parser& parser, void* val_ptr) -{ - LLSimpleXUIParser& self = static_cast(parser); - LLUUID temp_id; - // LLUUID::set is destructive, so use temporary value - if (temp_id.set(std::string(self.mCurAttributeValueBegin))) - { - *(LLUUID*)(val_ptr) = temp_id; - return true; - } - return false; -} - -bool LLSimpleXUIParser::readSDValue(Parser& parser, void* val_ptr) -{ - LLSimpleXUIParser& self = static_cast(parser); - *((LLSD*)val_ptr) = LLSD(self.mCurAttributeValueBegin); - return true; -} diff --git a/indra/llxuixml/llxuiparser.h b/indra/llxuixml/llxuiparser.h deleted file mode 100644 index d7cd256967..0000000000 --- a/indra/llxuixml/llxuiparser.h +++ /dev/null @@ -1,242 +0,0 @@ -/** - * @file llxuiparser.h - * @brief Utility functions for handling XUI structures in XML - * - * $LicenseInfo:firstyear=2003&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#ifndef LLXUIPARSER_H -#define LLXUIPARSER_H - -#include "llinitparam.h" -#include "llregistry.h" -#include "llpointer.h" - -#include -#include -#include -#include - - - -class LLView; - - -typedef LLPointer LLXMLNodePtr; - - -// lookup widget type by name -class LLWidgetTypeRegistry -: public LLRegistrySingleton -{}; - - -// global static instance for registering all widget types -typedef boost::function LLWidgetCreatorFunc; - -typedef LLRegistry widget_registry_t; - -class LLChildRegistryRegistry -: public LLRegistrySingleton -{}; - - - -class LLXSDWriter : public LLInitParam::Parser -{ - LOG_CLASS(LLXSDWriter); -public: - void writeXSD(const std::string& name, LLXMLNodePtr node, const LLInitParam::BaseBlock& block, const std::string& xml_namespace); - - /*virtual*/ std::string getCurrentElementName() { return LLStringUtil::null; } - - LLXSDWriter(); - -protected: - void writeAttribute(const std::string& type, const Parser::name_stack_t&, S32 min_count, S32 max_count, const std::vector* possible_values); - void addAttributeToSchema(LLXMLNodePtr nodep, const std::string& attribute_name, const std::string& type, bool mandatory, const std::vector* possible_values); - LLXMLNodePtr mAttributeNode; - LLXMLNodePtr mElementNode; - LLXMLNodePtr mSchemaNode; - - typedef std::set string_set_t; - typedef std::map attributes_map_t; - attributes_map_t mAttributesWritten; -}; - - - -// NOTE: DOES NOT WORK YET -// should support child widgets for XUI -class LLXUIXSDWriter : public LLXSDWriter -{ -public: - void writeXSD(const std::string& name, const std::string& path, const LLInitParam::BaseBlock& block); -}; - - -class LLXUIParserImpl; - -class LLXUIParser : public LLInitParam::Parser -{ -LOG_CLASS(LLXUIParser); - -public: - LLXUIParser(); - typedef LLInitParam::Parser::name_stack_t name_stack_t; - - /*virtual*/ std::string getCurrentElementName(); - /*virtual*/ void parserWarning(const std::string& message); - /*virtual*/ void parserError(const std::string& message); - - void readXUI(LLXMLNodePtr node, LLInitParam::BaseBlock& block, const std::string& filename = LLStringUtil::null, bool silent=false); - void writeXUI(LLXMLNodePtr node, const LLInitParam::BaseBlock& block, const LLInitParam::BaseBlock* diff_block = NULL); - -private: - bool readXUIImpl(LLXMLNodePtr node, LLInitParam::BaseBlock& block); - bool readAttributes(LLXMLNodePtr nodep, LLInitParam::BaseBlock& block); - - //reader helper functions - static bool readFlag(Parser& parser, void* val_ptr); - static bool readBoolValue(Parser& parser, void* val_ptr); - static bool readStringValue(Parser& parser, void* val_ptr); - static bool readU8Value(Parser& parser, void* val_ptr); - static bool readS8Value(Parser& parser, void* val_ptr); - static bool readU16Value(Parser& parser, void* val_ptr); - static bool readS16Value(Parser& parser, void* val_ptr); - static bool readU32Value(Parser& parser, void* val_ptr); - static bool readS32Value(Parser& parser, void* val_ptr); - static bool readF32Value(Parser& parser, void* val_ptr); - static bool readF64Value(Parser& parser, void* val_ptr); - static bool readColor4Value(Parser& parser, void* val_ptr); - static bool readUIColorValue(Parser& parser, void* val_ptr); - static bool readUUIDValue(Parser& parser, void* val_ptr); - static bool readSDValue(Parser& parser, void* val_ptr); - - //writer helper functions - static bool writeFlag(Parser& parser, const void* val_ptr, name_stack_t&); - static bool writeBoolValue(Parser& parser, const void* val_ptr, name_stack_t&); - static bool writeStringValue(Parser& parser, const void* val_ptr, name_stack_t&); - static bool writeU8Value(Parser& parser, const void* val_ptr, name_stack_t&); - static bool writeS8Value(Parser& parser, const void* val_ptr, name_stack_t&); - static bool writeU16Value(Parser& parser, const void* val_ptr, name_stack_t&); - static bool writeS16Value(Parser& parser, const void* val_ptr, name_stack_t&); - static bool writeU32Value(Parser& parser, const void* val_ptr, name_stack_t&); - static bool writeS32Value(Parser& parser, const void* val_ptr, name_stack_t&); - static bool writeF32Value(Parser& parser, const void* val_ptr, name_stack_t&); - static bool writeF64Value(Parser& parser, const void* val_ptr, name_stack_t&); - static bool writeColor4Value(Parser& parser, const void* val_ptr, name_stack_t&); - static bool writeUIColorValue(Parser& parser, const void* val_ptr, name_stack_t&); - static bool writeUUIDValue(Parser& parser, const void* val_ptr, name_stack_t&); - static bool writeSDValue(Parser& parser, const void* val_ptr, name_stack_t&); - - LLXMLNodePtr getNode(name_stack_t& stack); - -private: - Parser::name_stack_t mNameStack; - LLXMLNodePtr mCurReadNode; - // Root of the widget XML sub-tree, for example, "line_editor" - LLXMLNodePtr mWriteRootNode; - - typedef std::map out_nodes_t; - out_nodes_t mOutNodes; - LLXMLNodePtr mLastWrittenChild; - S32 mCurReadDepth; - std::string mCurFileName; - std::string mRootNodeName; -}; - -// LLSimpleXUIParser is a streamlined SAX-based XUI parser that does not support localization -// or parsing of a tree of independent param blocks, such as child widgets. -// Use this for reading non-localized files that only need a single param block as a result. -// -// NOTE: In order to support nested block parsing, we need callbacks for start element that -// push new blocks contexts on the mScope stack. -// NOTE: To support localization without building a DOM, we need to enforce consistent -// ordering of child elements from base file to localized diff file. Then we can use a pair -// of coroutines to perform matching of xml nodes during parsing. Not sure if the overhead -// of coroutines would offset the gain from SAX parsing -class LLSimpleXUIParserImpl; - -class LLSimpleXUIParser : public LLInitParam::Parser -{ -LOG_CLASS(LLSimpleXUIParser); -public: - typedef LLInitParam::Parser::name_stack_t name_stack_t; - typedef LLInitParam::BaseBlock* (*element_start_callback_t)(LLSimpleXUIParser&, const char* block_name); - - LLSimpleXUIParser(element_start_callback_t element_cb = NULL); - virtual ~LLSimpleXUIParser(); - - /*virtual*/ std::string getCurrentElementName(); - /*virtual*/ void parserWarning(const std::string& message); - /*virtual*/ void parserError(const std::string& message); - - bool readXUI(const std::string& filename, LLInitParam::BaseBlock& block, bool silent=false); - - -private: - //reader helper functions - static bool readFlag(Parser&, void* val_ptr); - static bool readBoolValue(Parser&, void* val_ptr); - static bool readStringValue(Parser&, void* val_ptr); - static bool readU8Value(Parser&, void* val_ptr); - static bool readS8Value(Parser&, void* val_ptr); - static bool readU16Value(Parser&, void* val_ptr); - static bool readS16Value(Parser&, void* val_ptr); - static bool readU32Value(Parser&, void* val_ptr); - static bool readS32Value(Parser&, void* val_ptr); - static bool readF32Value(Parser&, void* val_ptr); - static bool readF64Value(Parser&, void* val_ptr); - static bool readColor4Value(Parser&, void* val_ptr); - static bool readUIColorValue(Parser&, void* val_ptr); - static bool readUUIDValue(Parser&, void* val_ptr); - static bool readSDValue(Parser&, void* val_ptr); - -private: - static void startElementHandler(void *userData, const char *name, const char **atts); - static void endElementHandler(void *userData, const char *name); - static void characterDataHandler(void *userData, const char *s, int len); - - void startElement(const char *name, const char **atts); - void endElement(const char *name); - void characterData(const char *s, int len); - bool readAttributes(const char **atts); - bool processText(); - - Parser::name_stack_t mNameStack; - struct XML_ParserStruct* mParser; - LLXMLNodePtr mLastWrittenChild; - S32 mCurReadDepth; - std::string mCurFileName; - std::string mTextContents; - const char* mCurAttributeValueBegin; - std::vector mTokenSizeStack; - std::vector mScope; - std::vector mEmptyLeafNode; - element_start_callback_t mElementCB; - - std::vector > mOutputStack; -}; - - -#endif //LLXUIPARSER_H diff --git a/indra/newview/CMakeLists.txt b/indra/newview/CMakeLists.txt index 6b2fe1e45a..baf7627f06 100644 --- a/indra/newview/CMakeLists.txt +++ b/indra/newview/CMakeLists.txt @@ -30,7 +30,6 @@ include(LLUI) include(LLVFS) include(LLWindow) include(LLXML) -include(LLXUIXML) include(LScript) include(Linking) include(NDOF) @@ -65,7 +64,6 @@ include_directories( ${LLVFS_INCLUDE_DIRS} ${LLWINDOW_INCLUDE_DIRS} ${LLXML_INCLUDE_DIRS} - ${LLXUIXML_INCLUDE_DIRS} ${LSCRIPT_INCLUDE_DIRS} ${LSCRIPT_INCLUDE_DIRS}/lscript_compile ${LLLOGIN_INCLUDE_DIRS} @@ -1740,7 +1738,6 @@ target_link_libraries(${VIEWER_BINARY_NAME} ${LLVFS_LIBRARIES} ${LLWINDOW_LIBRARIES} ${LLXML_LIBRARIES} - ${LLXUIXML_LIBRARIES} ${LSCRIPT_LIBRARIES} ${LLMATH_LIBRARIES} ${LLCOMMON_LIBRARIES} diff --git a/indra/newview/llviewerprecompiledheaders.h b/indra/newview/llviewerprecompiledheaders.h index f738b84bb9..6c8a827ba3 100644 --- a/indra/newview/llviewerprecompiledheaders.h +++ b/indra/newview/llviewerprecompiledheaders.h @@ -57,6 +57,8 @@ #include "lldeleteutils.h" #include "imageids.h" #include "indra_constants.h" +#include "llinitparam.h" + //#include "linden_common.h" //#include "llpreprocessor.h" #include "llallocator.h" @@ -124,7 +126,5 @@ // Library includes from llmessage project #include "llcachename.h" -// Library includes from llxuixml -#include "llinitparam.h" #endif -- cgit v1.2.3 From 4287dcaacf0804a5a73dbf37c629471e2855733c Mon Sep 17 00:00:00 2001 From: Richard Linden Date: Fri, 20 Jan 2012 14:55:39 -0800 Subject: moved LLSDParam to llcommon so that LLSD<->Param Block conversion are usable by everyone --- indra/llcommon/CMakeLists.txt | 2 + indra/llcommon/llinitparam.h | 4 +- indra/llcommon/llsdparam.cpp | 342 ++++++++++++++++++++++++++++++++++++++++++ indra/llcommon/llsdparam.h | 126 ++++++++++++++++ indra/llui/CMakeLists.txt | 2 - indra/llui/llsdparam.cpp | 342 ------------------------------------------ indra/llui/llsdparam.h | 126 ---------------- 7 files changed, 472 insertions(+), 472 deletions(-) create mode 100644 indra/llcommon/llsdparam.cpp create mode 100644 indra/llcommon/llsdparam.h delete mode 100644 indra/llui/llsdparam.cpp delete mode 100644 indra/llui/llsdparam.h (limited to 'indra') diff --git a/indra/llcommon/CMakeLists.txt b/indra/llcommon/CMakeLists.txt index 72b1d363b0..a1aa887d3a 100644 --- a/indra/llcommon/CMakeLists.txt +++ b/indra/llcommon/CMakeLists.txt @@ -82,6 +82,7 @@ set(llcommon_SOURCE_FILES llrefcount.cpp llrun.cpp llsd.cpp + llsdparam.cpp llsdserialize.cpp llsdserialize_xml.cpp llsdutil.cpp @@ -211,6 +212,7 @@ set(llcommon_HEADER_FILES llrefcount.h llsafehandle.h llsd.h + llsdparam.h llsdserialize.h llsdserialize_xml.h llsdutil.h diff --git a/indra/llcommon/llinitparam.h b/indra/llcommon/llinitparam.h index 550e1608cc..beaf07e56b 100644 --- a/indra/llcommon/llinitparam.h +++ b/indra/llcommon/llinitparam.h @@ -2057,8 +2057,8 @@ namespace LLInitParam // block param interface - bool deserializeBlock(Parser& p, Parser::name_stack_range_t name_stack_range, bool new_name); - void serializeBlock(Parser& p, Parser::name_stack_t& name_stack, const BaseBlock* diff_block = NULL) const; + LL_COMMON_API bool deserializeBlock(Parser& p, Parser::name_stack_range_t name_stack_range, bool new_name); + LL_COMMON_API void serializeBlock(Parser& p, Parser::name_stack_t& name_stack, const BaseBlock* diff_block = NULL) const; bool inspectBlock(Parser& p, Parser::name_stack_t name_stack = Parser::name_stack_t(), S32 min_count = 0, S32 max_count = S32_MAX) const { //TODO: implement LLSD params as schema type Any diff --git a/indra/llcommon/llsdparam.cpp b/indra/llcommon/llsdparam.cpp new file mode 100644 index 0000000000..0e29873bb0 --- /dev/null +++ b/indra/llcommon/llsdparam.cpp @@ -0,0 +1,342 @@ +/** + * @file llsdparam.cpp + * @brief parameter block abstraction for creating complex objects and + * parsing construction parameters from xml and LLSD + * + * $LicenseInfo:firstyear=2008&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include "linden_common.h" + +// Project includes +#include "llsdparam.h" +#include "llsdutil.h" + +static LLInitParam::Parser::parser_read_func_map_t sReadFuncs; +static LLInitParam::Parser::parser_write_func_map_t sWriteFuncs; +static LLInitParam::Parser::parser_inspect_func_map_t sInspectFuncs; +static const LLSD NO_VALUE_MARKER; + +LLFastTimer::DeclareTimer FTM_SD_PARAM_ADAPTOR("LLSD to LLInitParam conversion"); + +// +// LLParamSDParser +// +LLParamSDParser::LLParamSDParser() +: Parser(sReadFuncs, sWriteFuncs, sInspectFuncs) +{ + using boost::bind; + + if (sReadFuncs.empty()) + { + registerParserFuncs(readFlag, &LLParamSDParser::writeFlag); + registerParserFuncs(readS32, &LLParamSDParser::writeTypedValue); + registerParserFuncs(readU32, &LLParamSDParser::writeU32Param); + registerParserFuncs(readF32, &LLParamSDParser::writeTypedValue); + registerParserFuncs(readF64, &LLParamSDParser::writeTypedValue); + registerParserFuncs(readBool, &LLParamSDParser::writeTypedValue); + registerParserFuncs(readString, &LLParamSDParser::writeTypedValue); + registerParserFuncs(readUUID, &LLParamSDParser::writeTypedValue); + registerParserFuncs(readDate, &LLParamSDParser::writeTypedValue); + registerParserFuncs(readURI, &LLParamSDParser::writeTypedValue); + registerParserFuncs(readSD, &LLParamSDParser::writeTypedValue); + } +} + +// special case handling of U32 due to ambiguous LLSD::assign overload +bool LLParamSDParser::writeU32Param(LLParamSDParser::parser_t& parser, const void* val_ptr, parser_t::name_stack_t& name_stack) +{ + LLParamSDParser& sdparser = static_cast(parser); + if (!sdparser.mWriteRootSD) return false; + + parser_t::name_stack_range_t range(name_stack.begin(), name_stack.end()); + LLSD& sd_to_write = LLParamSDParserUtilities::getSDWriteNode(*sdparser.mWriteRootSD, range); + sd_to_write.assign((S32)*((const U32*)val_ptr)); + + return true; +} + +bool LLParamSDParser::writeFlag(LLParamSDParser::parser_t& parser, const void* val_ptr, parser_t::name_stack_t& name_stack) +{ + LLParamSDParser& sdparser = static_cast(parser); + if (!sdparser.mWriteRootSD) return false; + + parser_t::name_stack_range_t range(name_stack.begin(), name_stack.end()); + LLParamSDParserUtilities::getSDWriteNode(*sdparser.mWriteRootSD, range); + + return true; +} + +void LLParamSDParser::submit(LLInitParam::BaseBlock& block, const LLSD& sd, LLInitParam::Parser::name_stack_t& name_stack) +{ + mCurReadSD = &sd; + block.submitValue(name_stack, *this); +} + +void LLParamSDParser::readSD(const LLSD& sd, LLInitParam::BaseBlock& block, bool silent) +{ + mCurReadSD = NULL; + mNameStack.clear(); + setParseSilently(silent); + + LLParamSDParserUtilities::readSDValues(boost::bind(&LLParamSDParser::submit, this, boost::ref(block), _1, _2), sd, mNameStack); + //readSDValues(sd, block); +} + +void LLParamSDParser::writeSD(LLSD& sd, const LLInitParam::BaseBlock& block) +{ + mNameStack.clear(); + mWriteRootSD = &sd; + + name_stack_t name_stack; + block.serializeBlock(*this, name_stack); +} + +/*virtual*/ std::string LLParamSDParser::getCurrentElementName() +{ + std::string full_name = "sd"; + for (name_stack_t::iterator it = mNameStack.begin(); + it != mNameStack.end(); + ++it) + { + full_name += llformat("[%s]", it->first.c_str()); + } + + return full_name; +} + + +bool LLParamSDParser::readFlag(Parser& parser, void* val_ptr) +{ + LLParamSDParser& self = static_cast(parser); + return self.mCurReadSD == &NO_VALUE_MARKER; +} + + +bool LLParamSDParser::readS32(Parser& parser, void* val_ptr) +{ + LLParamSDParser& self = static_cast(parser); + + *((S32*)val_ptr) = self.mCurReadSD->asInteger(); + return true; +} + +bool LLParamSDParser::readU32(Parser& parser, void* val_ptr) +{ + LLParamSDParser& self = static_cast(parser); + + *((U32*)val_ptr) = self.mCurReadSD->asInteger(); + return true; +} + +bool LLParamSDParser::readF32(Parser& parser, void* val_ptr) +{ + LLParamSDParser& self = static_cast(parser); + + *((F32*)val_ptr) = self.mCurReadSD->asReal(); + return true; +} + +bool LLParamSDParser::readF64(Parser& parser, void* val_ptr) +{ + LLParamSDParser& self = static_cast(parser); + + *((F64*)val_ptr) = self.mCurReadSD->asReal(); + return true; +} + +bool LLParamSDParser::readBool(Parser& parser, void* val_ptr) +{ + LLParamSDParser& self = static_cast(parser); + + *((bool*)val_ptr) = self.mCurReadSD->asBoolean(); + return true; +} + +bool LLParamSDParser::readString(Parser& parser, void* val_ptr) +{ + LLParamSDParser& self = static_cast(parser); + + *((std::string*)val_ptr) = self.mCurReadSD->asString(); + return true; +} + +bool LLParamSDParser::readUUID(Parser& parser, void* val_ptr) +{ + LLParamSDParser& self = static_cast(parser); + + *((LLUUID*)val_ptr) = self.mCurReadSD->asUUID(); + return true; +} + +bool LLParamSDParser::readDate(Parser& parser, void* val_ptr) +{ + LLParamSDParser& self = static_cast(parser); + + *((LLDate*)val_ptr) = self.mCurReadSD->asDate(); + return true; +} + +bool LLParamSDParser::readURI(Parser& parser, void* val_ptr) +{ + LLParamSDParser& self = static_cast(parser); + + *((LLURI*)val_ptr) = self.mCurReadSD->asURI(); + return true; +} + +bool LLParamSDParser::readSD(Parser& parser, void* val_ptr) +{ + LLParamSDParser& self = static_cast(parser); + + *((LLSD*)val_ptr) = *self.mCurReadSD; + return true; +} + +// static +LLSD& LLParamSDParserUtilities::getSDWriteNode(LLSD& input, LLInitParam::Parser::name_stack_range_t& name_stack_range) +{ + LLSD* sd_to_write = &input; + + for (LLInitParam::Parser::name_stack_t::iterator it = name_stack_range.first; + it != name_stack_range.second; + ++it) + { + bool new_traversal = it->second; + + LLSD* child_sd = it->first.empty() ? sd_to_write : &(*sd_to_write)[it->first]; + + if (child_sd->isArray()) + { + if (new_traversal) + { + // write to new element at end + sd_to_write = &(*child_sd)[child_sd->size()]; + } + else + { + // write to last of existing elements, or first element if empty + sd_to_write = &(*child_sd)[llmax(0, child_sd->size() - 1)]; + } + } + else + { + if (new_traversal + && child_sd->isDefined() + && !child_sd->isArray()) + { + // copy child contents into first element of an array + LLSD new_array = LLSD::emptyArray(); + new_array.append(*child_sd); + // assign array to slot that previously held the single value + *child_sd = new_array; + // return next element in that array + sd_to_write = &((*child_sd)[1]); + } + else + { + sd_to_write = child_sd; + } + } + it->second = false; + } + + return *sd_to_write; +} + +//static +void LLParamSDParserUtilities::readSDValues(read_sd_cb_t cb, const LLSD& sd, LLInitParam::Parser::name_stack_t& stack) +{ + if (sd.isMap()) + { + for (LLSD::map_const_iterator it = sd.beginMap(); + it != sd.endMap(); + ++it) + { + stack.push_back(make_pair(it->first, true)); + readSDValues(cb, it->second, stack); + stack.pop_back(); + } + } + else if (sd.isArray()) + { + for (LLSD::array_const_iterator it = sd.beginArray(); + it != sd.endArray(); + ++it) + { + stack.back().second = true; + readSDValues(cb, *it, stack); + } + } + else if (sd.isUndefined()) + { + if (!cb.empty()) + { + cb(NO_VALUE_MARKER, stack); + } + } + else + { + if (!cb.empty()) + { + cb(sd, stack); + } + } +} + +//static +void LLParamSDParserUtilities::readSDValues(read_sd_cb_t cb, const LLSD& sd) +{ + LLInitParam::Parser::name_stack_t stack = LLInitParam::Parser::name_stack_t(); + readSDValues(cb, sd, stack); +} +namespace LLInitParam +{ + // LLSD specialization + // block param interface + bool ParamValue, false>::deserializeBlock(Parser& p, Parser::name_stack_range_t name_stack, bool new_name) + { + LLSD& sd = LLParamSDParserUtilities::getSDWriteNode(mValue, name_stack); + + LLSD::String string; + + if (p.readValue(string)) + { + sd = string; + return true; + } + return false; + } + + //static + void ParamValue, false>::serializeElement(Parser& p, const LLSD& sd, Parser::name_stack_t& name_stack) + { + p.writeValue(sd.asString(), name_stack); + } + + void ParamValue, false>::serializeBlock(Parser& p, Parser::name_stack_t& name_stack, const BaseBlock* diff_block) const + { + // read from LLSD value and serialize out to parser (which could be LLSD, XUI, etc) + Parser::name_stack_t stack; + LLParamSDParserUtilities::readSDValues(boost::bind(&serializeElement, boost::ref(p), _1, _2), mValue, stack); + } +} diff --git a/indra/llcommon/llsdparam.h b/indra/llcommon/llsdparam.h new file mode 100644 index 0000000000..6ef5debd7b --- /dev/null +++ b/indra/llcommon/llsdparam.h @@ -0,0 +1,126 @@ +/** + * @file llsdparam.h + * @brief parameter block abstraction for creating complex objects and + * parsing construction parameters from xml and LLSD + * + * $LicenseInfo:firstyear=2008&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#ifndef LL_LLSDPARAM_H +#define LL_LLSDPARAM_H + +#include "llinitparam.h" +#include "boost/function.hpp" + +struct LL_COMMON_API LLParamSDParserUtilities +{ + static LLSD& getSDWriteNode(LLSD& input, LLInitParam::Parser::name_stack_range_t& name_stack_range); + + typedef boost::function read_sd_cb_t; + static void readSDValues(read_sd_cb_t cb, const LLSD& sd, LLInitParam::Parser::name_stack_t& stack); + static void readSDValues(read_sd_cb_t cb, const LLSD& sd); +}; + +class LL_COMMON_API LLParamSDParser +: public LLInitParam::Parser +{ +LOG_CLASS(LLParamSDParser); + +typedef LLInitParam::Parser parser_t; + +public: + LLParamSDParser(); + void readSD(const LLSD& sd, LLInitParam::BaseBlock& block, bool silent = false); + void writeSD(LLSD& sd, const LLInitParam::BaseBlock& block); + + /*virtual*/ std::string getCurrentElementName(); + +private: + void submit(LLInitParam::BaseBlock& block, const LLSD& sd, LLInitParam::Parser::name_stack_t& name_stack); + + template + static bool writeTypedValue(Parser& parser, const void* val_ptr, parser_t::name_stack_t& name_stack) + { + LLParamSDParser& sdparser = static_cast(parser); + if (!sdparser.mWriteRootSD) return false; + + LLInitParam::Parser::name_stack_range_t range(name_stack.begin(), name_stack.end()); + LLSD& sd_to_write = LLParamSDParserUtilities::getSDWriteNode(*sdparser.mWriteRootSD, range); + + sd_to_write.assign(*((const T*)val_ptr)); + return true; + } + + static bool writeU32Param(Parser& parser, const void* value_ptr, parser_t::name_stack_t& name_stack); + static bool writeFlag(Parser& parser, const void* value_ptr, parser_t::name_stack_t& name_stack); + + static bool readFlag(Parser& parser, void* val_ptr); + static bool readS32(Parser& parser, void* val_ptr); + static bool readU32(Parser& parser, void* val_ptr); + static bool readF32(Parser& parser, void* val_ptr); + static bool readF64(Parser& parser, void* val_ptr); + static bool readBool(Parser& parser, void* val_ptr); + static bool readString(Parser& parser, void* val_ptr); + static bool readUUID(Parser& parser, void* val_ptr); + static bool readDate(Parser& parser, void* val_ptr); + static bool readURI(Parser& parser, void* val_ptr); + static bool readSD(Parser& parser, void* val_ptr); + + Parser::name_stack_t mNameStack; + const LLSD* mCurReadSD; + LLSD* mWriteRootSD; + LLSD* mCurWriteSD; +}; + + +extern LL_COMMON_API LLFastTimer::DeclareTimer FTM_SD_PARAM_ADAPTOR; +template +class LLSDParamAdapter : public T +{ +public: + LLSDParamAdapter() {} + LLSDParamAdapter(const LLSD& sd) + { + LLFastTimer _(FTM_SD_PARAM_ADAPTOR); + LLParamSDParser parser; + // don't spam for implicit parsing of LLSD, as we want to allow arbitrary freeform data and ignore most of it + bool parse_silently = true; + parser.readSD(sd, *this, parse_silently); + } + + operator LLSD() const + { + LLParamSDParser parser; + LLSD sd; + parser.writeSD(sd, *this); + return sd; + } + + LLSDParamAdapter(const T& val) + : T(val) + { + T::operator=(val); + } +}; + +#endif // LL_LLSDPARAM_H + diff --git a/indra/llui/CMakeLists.txt b/indra/llui/CMakeLists.txt index 9226f36e73..20c3456a56 100644 --- a/indra/llui/CMakeLists.txt +++ b/indra/llui/CMakeLists.txt @@ -81,7 +81,6 @@ set(llui_SOURCE_FILES llscrolllistcolumn.cpp llscrolllistctrl.cpp llscrolllistitem.cpp - llsdparam.cpp llsearcheditor.cpp llslider.cpp llsliderctrl.cpp @@ -190,7 +189,6 @@ set(llui_HEADER_FILES llscrolllistcolumn.h llscrolllistctrl.h llscrolllistitem.h - llsdparam.h llsliderctrl.h llslider.h llspinctrl.h diff --git a/indra/llui/llsdparam.cpp b/indra/llui/llsdparam.cpp deleted file mode 100644 index 0e29873bb0..0000000000 --- a/indra/llui/llsdparam.cpp +++ /dev/null @@ -1,342 +0,0 @@ -/** - * @file llsdparam.cpp - * @brief parameter block abstraction for creating complex objects and - * parsing construction parameters from xml and LLSD - * - * $LicenseInfo:firstyear=2008&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include "linden_common.h" - -// Project includes -#include "llsdparam.h" -#include "llsdutil.h" - -static LLInitParam::Parser::parser_read_func_map_t sReadFuncs; -static LLInitParam::Parser::parser_write_func_map_t sWriteFuncs; -static LLInitParam::Parser::parser_inspect_func_map_t sInspectFuncs; -static const LLSD NO_VALUE_MARKER; - -LLFastTimer::DeclareTimer FTM_SD_PARAM_ADAPTOR("LLSD to LLInitParam conversion"); - -// -// LLParamSDParser -// -LLParamSDParser::LLParamSDParser() -: Parser(sReadFuncs, sWriteFuncs, sInspectFuncs) -{ - using boost::bind; - - if (sReadFuncs.empty()) - { - registerParserFuncs(readFlag, &LLParamSDParser::writeFlag); - registerParserFuncs(readS32, &LLParamSDParser::writeTypedValue); - registerParserFuncs(readU32, &LLParamSDParser::writeU32Param); - registerParserFuncs(readF32, &LLParamSDParser::writeTypedValue); - registerParserFuncs(readF64, &LLParamSDParser::writeTypedValue); - registerParserFuncs(readBool, &LLParamSDParser::writeTypedValue); - registerParserFuncs(readString, &LLParamSDParser::writeTypedValue); - registerParserFuncs(readUUID, &LLParamSDParser::writeTypedValue); - registerParserFuncs(readDate, &LLParamSDParser::writeTypedValue); - registerParserFuncs(readURI, &LLParamSDParser::writeTypedValue); - registerParserFuncs(readSD, &LLParamSDParser::writeTypedValue); - } -} - -// special case handling of U32 due to ambiguous LLSD::assign overload -bool LLParamSDParser::writeU32Param(LLParamSDParser::parser_t& parser, const void* val_ptr, parser_t::name_stack_t& name_stack) -{ - LLParamSDParser& sdparser = static_cast(parser); - if (!sdparser.mWriteRootSD) return false; - - parser_t::name_stack_range_t range(name_stack.begin(), name_stack.end()); - LLSD& sd_to_write = LLParamSDParserUtilities::getSDWriteNode(*sdparser.mWriteRootSD, range); - sd_to_write.assign((S32)*((const U32*)val_ptr)); - - return true; -} - -bool LLParamSDParser::writeFlag(LLParamSDParser::parser_t& parser, const void* val_ptr, parser_t::name_stack_t& name_stack) -{ - LLParamSDParser& sdparser = static_cast(parser); - if (!sdparser.mWriteRootSD) return false; - - parser_t::name_stack_range_t range(name_stack.begin(), name_stack.end()); - LLParamSDParserUtilities::getSDWriteNode(*sdparser.mWriteRootSD, range); - - return true; -} - -void LLParamSDParser::submit(LLInitParam::BaseBlock& block, const LLSD& sd, LLInitParam::Parser::name_stack_t& name_stack) -{ - mCurReadSD = &sd; - block.submitValue(name_stack, *this); -} - -void LLParamSDParser::readSD(const LLSD& sd, LLInitParam::BaseBlock& block, bool silent) -{ - mCurReadSD = NULL; - mNameStack.clear(); - setParseSilently(silent); - - LLParamSDParserUtilities::readSDValues(boost::bind(&LLParamSDParser::submit, this, boost::ref(block), _1, _2), sd, mNameStack); - //readSDValues(sd, block); -} - -void LLParamSDParser::writeSD(LLSD& sd, const LLInitParam::BaseBlock& block) -{ - mNameStack.clear(); - mWriteRootSD = &sd; - - name_stack_t name_stack; - block.serializeBlock(*this, name_stack); -} - -/*virtual*/ std::string LLParamSDParser::getCurrentElementName() -{ - std::string full_name = "sd"; - for (name_stack_t::iterator it = mNameStack.begin(); - it != mNameStack.end(); - ++it) - { - full_name += llformat("[%s]", it->first.c_str()); - } - - return full_name; -} - - -bool LLParamSDParser::readFlag(Parser& parser, void* val_ptr) -{ - LLParamSDParser& self = static_cast(parser); - return self.mCurReadSD == &NO_VALUE_MARKER; -} - - -bool LLParamSDParser::readS32(Parser& parser, void* val_ptr) -{ - LLParamSDParser& self = static_cast(parser); - - *((S32*)val_ptr) = self.mCurReadSD->asInteger(); - return true; -} - -bool LLParamSDParser::readU32(Parser& parser, void* val_ptr) -{ - LLParamSDParser& self = static_cast(parser); - - *((U32*)val_ptr) = self.mCurReadSD->asInteger(); - return true; -} - -bool LLParamSDParser::readF32(Parser& parser, void* val_ptr) -{ - LLParamSDParser& self = static_cast(parser); - - *((F32*)val_ptr) = self.mCurReadSD->asReal(); - return true; -} - -bool LLParamSDParser::readF64(Parser& parser, void* val_ptr) -{ - LLParamSDParser& self = static_cast(parser); - - *((F64*)val_ptr) = self.mCurReadSD->asReal(); - return true; -} - -bool LLParamSDParser::readBool(Parser& parser, void* val_ptr) -{ - LLParamSDParser& self = static_cast(parser); - - *((bool*)val_ptr) = self.mCurReadSD->asBoolean(); - return true; -} - -bool LLParamSDParser::readString(Parser& parser, void* val_ptr) -{ - LLParamSDParser& self = static_cast(parser); - - *((std::string*)val_ptr) = self.mCurReadSD->asString(); - return true; -} - -bool LLParamSDParser::readUUID(Parser& parser, void* val_ptr) -{ - LLParamSDParser& self = static_cast(parser); - - *((LLUUID*)val_ptr) = self.mCurReadSD->asUUID(); - return true; -} - -bool LLParamSDParser::readDate(Parser& parser, void* val_ptr) -{ - LLParamSDParser& self = static_cast(parser); - - *((LLDate*)val_ptr) = self.mCurReadSD->asDate(); - return true; -} - -bool LLParamSDParser::readURI(Parser& parser, void* val_ptr) -{ - LLParamSDParser& self = static_cast(parser); - - *((LLURI*)val_ptr) = self.mCurReadSD->asURI(); - return true; -} - -bool LLParamSDParser::readSD(Parser& parser, void* val_ptr) -{ - LLParamSDParser& self = static_cast(parser); - - *((LLSD*)val_ptr) = *self.mCurReadSD; - return true; -} - -// static -LLSD& LLParamSDParserUtilities::getSDWriteNode(LLSD& input, LLInitParam::Parser::name_stack_range_t& name_stack_range) -{ - LLSD* sd_to_write = &input; - - for (LLInitParam::Parser::name_stack_t::iterator it = name_stack_range.first; - it != name_stack_range.second; - ++it) - { - bool new_traversal = it->second; - - LLSD* child_sd = it->first.empty() ? sd_to_write : &(*sd_to_write)[it->first]; - - if (child_sd->isArray()) - { - if (new_traversal) - { - // write to new element at end - sd_to_write = &(*child_sd)[child_sd->size()]; - } - else - { - // write to last of existing elements, or first element if empty - sd_to_write = &(*child_sd)[llmax(0, child_sd->size() - 1)]; - } - } - else - { - if (new_traversal - && child_sd->isDefined() - && !child_sd->isArray()) - { - // copy child contents into first element of an array - LLSD new_array = LLSD::emptyArray(); - new_array.append(*child_sd); - // assign array to slot that previously held the single value - *child_sd = new_array; - // return next element in that array - sd_to_write = &((*child_sd)[1]); - } - else - { - sd_to_write = child_sd; - } - } - it->second = false; - } - - return *sd_to_write; -} - -//static -void LLParamSDParserUtilities::readSDValues(read_sd_cb_t cb, const LLSD& sd, LLInitParam::Parser::name_stack_t& stack) -{ - if (sd.isMap()) - { - for (LLSD::map_const_iterator it = sd.beginMap(); - it != sd.endMap(); - ++it) - { - stack.push_back(make_pair(it->first, true)); - readSDValues(cb, it->second, stack); - stack.pop_back(); - } - } - else if (sd.isArray()) - { - for (LLSD::array_const_iterator it = sd.beginArray(); - it != sd.endArray(); - ++it) - { - stack.back().second = true; - readSDValues(cb, *it, stack); - } - } - else if (sd.isUndefined()) - { - if (!cb.empty()) - { - cb(NO_VALUE_MARKER, stack); - } - } - else - { - if (!cb.empty()) - { - cb(sd, stack); - } - } -} - -//static -void LLParamSDParserUtilities::readSDValues(read_sd_cb_t cb, const LLSD& sd) -{ - LLInitParam::Parser::name_stack_t stack = LLInitParam::Parser::name_stack_t(); - readSDValues(cb, sd, stack); -} -namespace LLInitParam -{ - // LLSD specialization - // block param interface - bool ParamValue, false>::deserializeBlock(Parser& p, Parser::name_stack_range_t name_stack, bool new_name) - { - LLSD& sd = LLParamSDParserUtilities::getSDWriteNode(mValue, name_stack); - - LLSD::String string; - - if (p.readValue(string)) - { - sd = string; - return true; - } - return false; - } - - //static - void ParamValue, false>::serializeElement(Parser& p, const LLSD& sd, Parser::name_stack_t& name_stack) - { - p.writeValue(sd.asString(), name_stack); - } - - void ParamValue, false>::serializeBlock(Parser& p, Parser::name_stack_t& name_stack, const BaseBlock* diff_block) const - { - // read from LLSD value and serialize out to parser (which could be LLSD, XUI, etc) - Parser::name_stack_t stack; - LLParamSDParserUtilities::readSDValues(boost::bind(&serializeElement, boost::ref(p), _1, _2), mValue, stack); - } -} diff --git a/indra/llui/llsdparam.h b/indra/llui/llsdparam.h deleted file mode 100644 index 3dfc6d020e..0000000000 --- a/indra/llui/llsdparam.h +++ /dev/null @@ -1,126 +0,0 @@ -/** - * @file llsdparam.h - * @brief parameter block abstraction for creating complex objects and - * parsing construction parameters from xml and LLSD - * - * $LicenseInfo:firstyear=2008&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#ifndef LL_LLSDPARAM_H -#define LL_LLSDPARAM_H - -#include "llinitparam.h" -#include "boost/function.hpp" - -struct LLParamSDParserUtilities -{ - static LLSD& getSDWriteNode(LLSD& input, LLInitParam::Parser::name_stack_range_t& name_stack_range); - - typedef boost::function read_sd_cb_t; - static void readSDValues(read_sd_cb_t cb, const LLSD& sd, LLInitParam::Parser::name_stack_t& stack); - static void readSDValues(read_sd_cb_t cb, const LLSD& sd); -}; - -class LLParamSDParser -: public LLInitParam::Parser -{ -LOG_CLASS(LLParamSDParser); - -typedef LLInitParam::Parser parser_t; - -public: - LLParamSDParser(); - void readSD(const LLSD& sd, LLInitParam::BaseBlock& block, bool silent = false); - void writeSD(LLSD& sd, const LLInitParam::BaseBlock& block); - - /*virtual*/ std::string getCurrentElementName(); - -private: - void submit(LLInitParam::BaseBlock& block, const LLSD& sd, LLInitParam::Parser::name_stack_t& name_stack); - - template - static bool writeTypedValue(Parser& parser, const void* val_ptr, parser_t::name_stack_t& name_stack) - { - LLParamSDParser& sdparser = static_cast(parser); - if (!sdparser.mWriteRootSD) return false; - - LLInitParam::Parser::name_stack_range_t range(name_stack.begin(), name_stack.end()); - LLSD& sd_to_write = LLParamSDParserUtilities::getSDWriteNode(*sdparser.mWriteRootSD, range); - - sd_to_write.assign(*((const T*)val_ptr)); - return true; - } - - static bool writeU32Param(Parser& parser, const void* value_ptr, parser_t::name_stack_t& name_stack); - static bool writeFlag(Parser& parser, const void* value_ptr, parser_t::name_stack_t& name_stack); - - static bool readFlag(Parser& parser, void* val_ptr); - static bool readS32(Parser& parser, void* val_ptr); - static bool readU32(Parser& parser, void* val_ptr); - static bool readF32(Parser& parser, void* val_ptr); - static bool readF64(Parser& parser, void* val_ptr); - static bool readBool(Parser& parser, void* val_ptr); - static bool readString(Parser& parser, void* val_ptr); - static bool readUUID(Parser& parser, void* val_ptr); - static bool readDate(Parser& parser, void* val_ptr); - static bool readURI(Parser& parser, void* val_ptr); - static bool readSD(Parser& parser, void* val_ptr); - - Parser::name_stack_t mNameStack; - const LLSD* mCurReadSD; - LLSD* mWriteRootSD; - LLSD* mCurWriteSD; -}; - - -extern LLFastTimer::DeclareTimer FTM_SD_PARAM_ADAPTOR; -template -class LLSDParamAdapter : public T -{ -public: - LLSDParamAdapter() {} - LLSDParamAdapter(const LLSD& sd) - { - LLFastTimer _(FTM_SD_PARAM_ADAPTOR); - LLParamSDParser parser; - // don't spam for implicit parsing of LLSD, as we want to allow arbitrary freeform data and ignore most of it - bool parse_silently = true; - parser.readSD(sd, *this, parse_silently); - } - - operator LLSD() const - { - LLParamSDParser parser; - LLSD sd; - parser.writeSD(sd, *this); - return sd; - } - - LLSDParamAdapter(const T& val) - : T(val) - { - T::operator=(val); - } -}; - -#endif // LL_LLSDPARAM_H - -- cgit v1.2.3 From f0dbb878337082d3f581874c12e6df2f4659a464 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Fri, 20 Jan 2012 18:10:40 -0500 Subject: Per Richard, replace LLProcessLauncher with LLProcess. LLProcessLauncher had the somewhat fuzzy mandate of (1) accumulating parameters with which to launch a child process and (2) sometimes tracking the lifespan of the ensuing child process. But a valid LLProcessLauncher object might or might not have ever been associated with an actual child process. LLProcess specifically tracks a child process. In effect, it's a fairly thin wrapper around a process HANDLE (on Windows) or pid_t (elsewhere), with lifespan management thrown in. A static LLProcess::create() method launches a new child; create() accepts an LLSD bundle with child parameters. So building up a parameter bundle is deferred to LLSD rather than conflated with the process management object. Reconcile all known LLProcessLauncher consumers in the viewer code base, notably the class unit tests. --- indra/llcommon/CMakeLists.txt | 6 +- indra/llcommon/llprocess.cpp | 338 ++++++++++ indra/llcommon/llprocess.h | 106 +++ indra/llcommon/llprocesslauncher.cpp | 394 ----------- indra/llcommon/llprocesslauncher.h | 107 --- indra/llcommon/tests/llprocess_test.cpp | 706 ++++++++++++++++++++ indra/llcommon/tests/llprocesslauncher_test.cpp | 718 --------------------- indra/llcommon/tests/llsdserialize_test.cpp | 13 +- indra/llplugin/llpluginprocessparent.cpp | 47 +- indra/llplugin/llpluginprocessparent.h | 10 +- indra/newview/llexternaleditor.cpp | 73 +-- indra/newview/llexternaleditor.h | 5 +- .../updater/llupdateinstaller.cpp | 20 +- 13 files changed, 1238 insertions(+), 1305 deletions(-) create mode 100644 indra/llcommon/llprocess.cpp create mode 100644 indra/llcommon/llprocess.h delete mode 100644 indra/llcommon/llprocesslauncher.cpp delete mode 100644 indra/llcommon/llprocesslauncher.h create mode 100644 indra/llcommon/tests/llprocess_test.cpp delete mode 100644 indra/llcommon/tests/llprocesslauncher_test.cpp (limited to 'indra') diff --git a/indra/llcommon/CMakeLists.txt b/indra/llcommon/CMakeLists.txt index 2c376bb016..e2af7265aa 100644 --- a/indra/llcommon/CMakeLists.txt +++ b/indra/llcommon/CMakeLists.txt @@ -74,7 +74,7 @@ set(llcommon_SOURCE_FILES llmortician.cpp lloptioninterface.cpp llptrto.cpp - llprocesslauncher.cpp + llprocess.cpp llprocessor.cpp llqueuedthread.cpp llrand.cpp @@ -197,7 +197,7 @@ set(llcommon_HEADER_FILES llpointer.h llpreprocessor.h llpriqueuemap.h - llprocesslauncher.h + llprocess.h llprocessor.h llptrskiplist.h llptrskipmap.h @@ -328,7 +328,7 @@ if (LL_TESTS) LL_ADD_INTEGRATION_TEST(reflection "" "${test_libs}") LL_ADD_INTEGRATION_TEST(stringize "" "${test_libs}") LL_ADD_INTEGRATION_TEST(lleventdispatcher "" "${test_libs}") - LL_ADD_INTEGRATION_TEST(llprocesslauncher "" "${test_libs}" + LL_ADD_INTEGRATION_TEST(llprocess "" "${test_libs}" "${PYTHON_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/setpython.py") LL_ADD_INTEGRATION_TEST(llstreamqueue "" "${test_libs}") diff --git a/indra/llcommon/llprocess.cpp b/indra/llcommon/llprocess.cpp new file mode 100644 index 0000000000..8c0caca680 --- /dev/null +++ b/indra/llcommon/llprocess.cpp @@ -0,0 +1,338 @@ +/** + * @file llprocess.cpp + * @brief Utility class for launching, terminating, and tracking the state of processes. + * + * $LicenseInfo:firstyear=2008&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#include "linden_common.h" +#include "llprocess.h" +#include "llsd.h" +#include "llsdserialize.h" +#include "stringize.h" + +#include +#include +#include + +/// Need an exception to avoid constructing an invalid LLProcess object, but +/// internal use only +struct LLProcessError: public std::runtime_error +{ + LLProcessError(const std::string& msg): std::runtime_error(msg) {} +}; + +LLProcessPtr LLProcess::create(const LLSD& params) +{ + try + { + return LLProcessPtr(new LLProcess(params)); + } + catch (const LLProcessError& e) + { + LL_WARNS("LLProcess") << e.what() << LL_ENDL; + return LLProcessPtr(); + } +} + +LLProcess::LLProcess(const LLSD& params): + mProcessID(0), + mAutokill(params["autokill"].asBoolean()) +{ + // nonstandard default bool value + if (! params.has("autokill")) + mAutokill = true; + if (! params.has("executable")) + { + throw LLProcessError(STRINGIZE("not launched: missing 'executable'\n" + << LLSDNotationStreamer(params))); + } + + launch(params); +} + +LLProcess::~LLProcess() +{ + if (mAutokill) + { + kill(); + } +} + +bool LLProcess::isRunning(void) +{ + mProcessID = isRunning(mProcessID); + return (mProcessID != 0); +} + +#if LL_WINDOWS + +static std::string quote(const std::string& str) +{ + std::string::size_type len(str.length()); + // If the string is already quoted, assume user knows what s/he's doing. + if (len >= 2 && str[0] == '"' && str[len-1] == '"') + { + return str; + } + + // Not already quoted: do it. + std::string result("\""); + for (std::string::const_iterator ci(str.begin()), cend(str.end()); ci != cend; ++ci) + { + if (*ci == '"') + { + result.append("\\"); + } + result.push_back(*ci); + } + return result + "\""; +} + +void LLProcess::launch(const LLSD& params) +{ + PROCESS_INFORMATION pinfo; + STARTUPINFOA sinfo; + memset(&sinfo, 0, sizeof(sinfo)); + + std::string args = quote(params["executable"]); + BOOST_FOREACH(const std::string& arg, llsd::inArray(params["args"])) + { + args += " "; + args += quote(arg); + } + + // So retarded. Windows requires that the second parameter to + // CreateProcessA be a writable (non-const) string... + std::vector args2(args.begin(), args.end()); + args2.push_back('\0'); + + // Convert wrapper to a real std::string so we can use c_str(); but use a + // named variable instead of a temporary so c_str() pointer remains valid. + std::string cwd(params["cwd"]); + const char * working_directory = 0; + if (! cwd.empty()) + working_directory = cwd.c_str(); + if( ! CreateProcessA( NULL, &args2[0], NULL, NULL, FALSE, 0, NULL, working_directory, &sinfo, &pinfo ) ) + { + int result = GetLastError(); + + LPTSTR error_str = 0; + if( + FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + result, + 0, + (LPTSTR)&error_str, + 0, + NULL) + != 0) + { + char message[256]; + wcstombs(message, error_str, sizeof(message)); + message[sizeof(message)-1] = 0; + LocalFree(error_str); + throw LLProcessError(STRINGIZE("CreateProcessA failed (" << result << "): " + << message)); + } + throw LLProcessError(STRINGIZE("CreateProcessA failed (" << result + << "), but FormatMessage() did not explain")); + } + + // foo = pinfo.dwProcessId; // get your pid here if you want to use it later on + // CloseHandle(pinfo.hProcess); // stops leaks - nothing else + mProcessID = pinfo.hProcess; + CloseHandle(pinfo.hThread); // stops leaks - nothing else +} + +LLProcess::id LLProcess::isRunning(id handle) +{ + if (! handle) + return 0; + + DWORD waitresult = WaitForSingleObject(handle, 0); + if(waitresult == WAIT_OBJECT_0) + { + // the process has completed. + return 0; + } + + return handle; +} + +bool LLProcess::kill(void) +{ + if (! mProcessID) + return false; + + TerminateProcess(mProcessID, 0); + return ! isRunning(); +} + +#else // Mac and linux + +#include +#include +#include +#include + +// Attempt to reap a process ID -- returns true if the process has exited and been reaped, false otherwise. +static bool reap_pid(pid_t pid) +{ + pid_t wait_result = ::waitpid(pid, NULL, WNOHANG); + if (wait_result == pid) + { + return true; + } + if (wait_result == -1 && errno == ECHILD) + { + // No such process -- this may mean we're ignoring SIGCHILD. + return true; + } + + return false; +} + +void LLProcess::launch(const LLSD& params) +{ + // flush all buffers before the child inherits them + ::fflush(NULL); + + pid_t child = vfork(); + if (child == 0) + { + // child process + + std::string cwd(params["cwd"]); + if (! cwd.empty()) + { + // change to the desired child working directory + if (::chdir(cwd.c_str())) + { + // chdir failed + LL_WARNS("LLProcess") << "could not chdir(\"" << cwd << "\")" << LL_ENDL; + // pointless to throw; this is child process... + _exit(248); + } + } + + // create an argv vector for the child process + std::vector fake_argv; + + // add the executable path + std::string executable(params["executable"]); + fake_argv.push_back(executable.c_str()); + + // and any arguments + const LLSD& params_args(params["args"]); + std::vector args(params_args.beginArray(), params_args.endArray()); + BOOST_FOREACH(const std::string& arg, args) + { + fake_argv.push_back(arg.c_str()); + } + + // terminate with a null pointer + fake_argv.push_back(NULL); + + ::execv(executable.c_str(), const_cast(&fake_argv[0])); + + // If we reach this point, the exec failed. + LL_WARNS("LLProcess") << "failed to launch: "; + BOOST_FOREACH(const char* arg, fake_argv) + { + LL_CONT << arg << ' '; + } + LL_CONT << LL_ENDL; + // Use _exit() instead of exit() per the vfork man page. Exit with a + // distinctive rc: someday soon we'll be able to retrieve it, and it + // would be nice to be able to tell that the child process failed! + _exit(249); + } + + // parent process + mProcessID = child; +} + +LLProcess::id LLProcess::isRunning(id pid) +{ + if (! pid) + return 0; + + // Check whether the process has exited, and reap it if it has. + if(reap_pid(pid)) + { + // the process has exited. + return 0; + } + + return pid; +} + +bool LLProcess::kill(void) +{ + if (! mProcessID) + return false; + + // Try to kill the process. We'll do approximately the same thing whether + // the kill returns an error or not, so we ignore the result. + (void)::kill(mProcessID, SIGTERM); + + // This will have the side-effect of reaping the zombie if the process has exited. + return ! isRunning(); +} + +/*==========================================================================*| +static std::list sZombies; + +void LLProcess::orphan(void) +{ + // Disassociate the process from this object + if(mProcessID != 0) + { + // We may still need to reap the process's zombie eventually + sZombies.push_back(mProcessID); + + mProcessID = 0; + } +} + +// static +void LLProcess::reap(void) +{ + // Attempt to real all saved process ID's. + + std::list::iterator iter = sZombies.begin(); + while(iter != sZombies.end()) + { + if(reap_pid(*iter)) + { + iter = sZombies.erase(iter); + } + else + { + iter++; + } + } +} +|*==========================================================================*/ + +#endif diff --git a/indra/llcommon/llprocess.h b/indra/llcommon/llprocess.h new file mode 100644 index 0000000000..9a74cfe829 --- /dev/null +++ b/indra/llcommon/llprocess.h @@ -0,0 +1,106 @@ +/** + * @file llprocess.h + * @brief Utility class for launching, terminating, and tracking child processes. + * + * $LicenseInfo:firstyear=2008&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2010, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; + * version 2.1 of the License only. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA + * $/LicenseInfo$ + */ + +#ifndef LL_LLPROCESS_H +#define LL_LLPROCESS_H + +#include +#include + +#if LL_WINDOWS +#define WIN32_LEAN_AND_MEAN +#include +#endif + +class LLSD; + +class LLProcess; +/// LLProcess instances are created on the heap by static factory methods and +/// managed by ref-counted pointers. +typedef boost::shared_ptr LLProcessPtr; + +/** + * LLProcess handles launching external processes with specified command line arguments. + * It also keeps track of whether the process is still running, and can kill it if required. +*/ +class LL_COMMON_API LLProcess: public boost::noncopyable +{ + LOG_CLASS(LLProcess); +public: + + /** + * Factory accepting LLSD::Map. + * MAY RETURN DEFAULT-CONSTRUCTED LLProcessPtr if params invalid! + * + * executable (required, string): executable pathname + * args (optional, string array): extra command-line arguments + * cwd (optional, string, dft no chdir): change to this directory before executing + * autokill (optional, bool, dft true): implicit kill() on ~LLProcess + */ + static LLProcessPtr create(const LLSD& params); + virtual ~LLProcess(); + + // isRunning isn't const because, if child isn't running, it clears stored + // process ID + bool isRunning(void); + + // Attempt to kill the process -- returns true if the process is no longer running when it returns. + // Note that even if this returns false, the process may exit some time after it's called. + bool kill(void); + +#if LL_WINDOWS + typedef HANDLE id; +#else + typedef pid_t id; +#endif + /// Get platform-specific process ID + id getProcessID() const { return mProcessID; }; + + /** + * Test if a process (id obtained from getProcessID()) is still + * running. Return is same nonzero id value if still running, else + * zero, so you can test it like a bool. But if you want to update a + * stored variable as a side effect, you can write code like this: + * @code + * childpid = LLProcess::isRunning(childpid); + * @endcode + * @note This method is intended as a unit-test hook, not as the first of + * a whole set of operations supported on freestanding @c id values. New + * functionality should be added as nonstatic members operating on + * mProcessID. + */ + static id isRunning(id); + +private: + /// constructor is private: use create() instead + LLProcess(const LLSD& params); + void launch(const LLSD& params); + + id mProcessID; + bool mAutokill; +}; + +#endif // LL_LLPROCESS_H diff --git a/indra/llcommon/llprocesslauncher.cpp b/indra/llcommon/llprocesslauncher.cpp deleted file mode 100644 index 5791d14ec0..0000000000 --- a/indra/llcommon/llprocesslauncher.cpp +++ /dev/null @@ -1,394 +0,0 @@ -/** - * @file llprocesslauncher.cpp - * @brief Utility class for launching, terminating, and tracking the state of processes. - * - * $LicenseInfo:firstyear=2008&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#include "linden_common.h" - -#include "llprocesslauncher.h" - -#include -#if LL_DARWIN || LL_LINUX -// not required or present on Win32 -#include -#endif - -LLProcessLauncher::LLProcessLauncher() -{ -#if LL_WINDOWS - mProcessHandle = 0; -#else - mProcessID = 0; -#endif -} - -LLProcessLauncher::~LLProcessLauncher() -{ - kill(); -} - -void LLProcessLauncher::setExecutable(const std::string &executable) -{ - mExecutable = executable; -} - -void LLProcessLauncher::setWorkingDirectory(const std::string &dir) -{ - mWorkingDir = dir; -} - -const std::string& LLProcessLauncher::getExecutable() const -{ - return mExecutable; -} - -void LLProcessLauncher::clearArguments() -{ - mLaunchArguments.clear(); -} - -void LLProcessLauncher::addArgument(const std::string &arg) -{ - mLaunchArguments.push_back(arg); -} - -#if LL_WINDOWS - -static std::string quote(const std::string& str) -{ - std::string::size_type len(str.length()); - // If the string is already quoted, assume user knows what s/he's doing. - if (len >= 2 && str[0] == '"' && str[len-1] == '"') - { - return str; - } - - // Not already quoted: do it. - std::string result("\""); - for (std::string::const_iterator ci(str.begin()), cend(str.end()); ci != cend; ++ci) - { - if (*ci == '"') - { - result.append("\\"); - } - result.push_back(*ci); - } - return result + "\""; -} - -int LLProcessLauncher::launch(void) -{ - // If there was already a process associated with this object, kill it. - kill(); - orphan(); - - int result = 0; - - PROCESS_INFORMATION pinfo; - STARTUPINFOA sinfo; - memset(&sinfo, 0, sizeof(sinfo)); - - std::string args = quote(mExecutable); - for(int i = 0; i < (int)mLaunchArguments.size(); i++) - { - args += " "; - args += quote(mLaunchArguments[i]); - } - - // So retarded. Windows requires that the second parameter to CreateProcessA be a writable (non-const) string... - char *args2 = new char[args.size() + 1]; - strcpy(args2, args.c_str()); - - const char * working_directory = 0; - if(!mWorkingDir.empty()) working_directory = mWorkingDir.c_str(); - if( ! CreateProcessA( NULL, args2, NULL, NULL, FALSE, 0, NULL, working_directory, &sinfo, &pinfo ) ) - { - result = GetLastError(); - - LPTSTR error_str = 0; - if( - FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, - NULL, - result, - 0, - (LPTSTR)&error_str, - 0, - NULL) - != 0) - { - char message[256]; - wcstombs(message, error_str, 256); - message[255] = 0; - llwarns << "CreateProcessA failed: " << message << llendl; - LocalFree(error_str); - } - - if(result == 0) - { - // Make absolutely certain we return a non-zero value on failure. - result = -1; - } - } - else - { - // foo = pinfo.dwProcessId; // get your pid here if you want to use it later on - // CloseHandle(pinfo.hProcess); // stops leaks - nothing else - mProcessHandle = pinfo.hProcess; - CloseHandle(pinfo.hThread); // stops leaks - nothing else - } - - delete[] args2; - - return result; -} - -bool LLProcessLauncher::isRunning(void) -{ - mProcessHandle = isRunning(mProcessHandle); - return (mProcessHandle != 0); -} - -LLProcessLauncher::ll_pid_t LLProcessLauncher::isRunning(ll_pid_t handle) -{ - if (! handle) - return 0; - - DWORD waitresult = WaitForSingleObject(handle, 0); - if(waitresult == WAIT_OBJECT_0) - { - // the process has completed. - return 0; - } - - return handle; -} - -bool LLProcessLauncher::kill(void) -{ - bool result = true; - - if(mProcessHandle != 0) - { - TerminateProcess(mProcessHandle,0); - - if(isRunning()) - { - result = false; - } - } - - return result; -} - -void LLProcessLauncher::orphan(void) -{ - // Forget about the process - mProcessHandle = 0; -} - -// static -void LLProcessLauncher::reap(void) -{ - // No actions necessary on Windows. -} - -#else // Mac and linux - -#include -#include -#include - -static std::list sZombies; - -// Attempt to reap a process ID -- returns true if the process has exited and been reaped, false otherwise. -static bool reap_pid(pid_t pid) -{ - bool result = false; - - pid_t wait_result = ::waitpid(pid, NULL, WNOHANG); - if(wait_result == pid) - { - result = true; - } - else if(wait_result == -1) - { - if(errno == ECHILD) - { - // No such process -- this may mean we're ignoring SIGCHILD. - result = true; - } - } - - return result; -} - -int LLProcessLauncher::launch(void) -{ - // If there was already a process associated with this object, kill it. - kill(); - orphan(); - - int result = 0; - int current_wd = -1; - - // create an argv vector for the child process - const char ** fake_argv = new const char *[mLaunchArguments.size() + 2]; // 1 for the executable path, 1 for the NULL terminator - - int i = 0; - - // add the executable path - fake_argv[i++] = mExecutable.c_str(); - - // and any arguments - for(int j=0; j < mLaunchArguments.size(); j++) - fake_argv[i++] = mLaunchArguments[j].c_str(); - - // terminate with a null pointer - fake_argv[i] = NULL; - - if(!mWorkingDir.empty()) - { - // save the current working directory - current_wd = ::open(".", O_RDONLY); - - // and change to the one the child will be executed in - if (::chdir(mWorkingDir.c_str())) - { - // chdir failed - } - } - - // flush all buffers before the child inherits them - ::fflush(NULL); - - pid_t id = vfork(); - if(id == 0) - { - // child process - ::execv(mExecutable.c_str(), (char * const *)fake_argv); - - // If we reach this point, the exec failed. - LL_WARNS("LLProcessLauncher") << "failed to launch: "; - for (const char * const * ai = fake_argv; *ai; ++ai) - { - LL_CONT << *ai << ' '; - } - LL_CONT << LL_ENDL; - // Use _exit() instead of exit() per the vfork man page. Exit with a - // distinctive rc: someday soon we'll be able to retrieve it, and it - // would be nice to be able to tell that the child process failed! - _exit(249); - } - - // parent process - - if(current_wd >= 0) - { - // restore the previous working directory - if (::fchdir(current_wd)) - { - // chdir failed - } - ::close(current_wd); - } - - delete[] fake_argv; - - mProcessID = id; - - return result; -} - -bool LLProcessLauncher::isRunning(void) -{ - mProcessID = isRunning(mProcessID); - return (mProcessID != 0); -} - -LLProcessLauncher::ll_pid_t LLProcessLauncher::isRunning(ll_pid_t pid) -{ - if (! pid) - return 0; - - // Check whether the process has exited, and reap it if it has. - if(reap_pid(pid)) - { - // the process has exited. - return 0; - } - - return pid; -} - -bool LLProcessLauncher::kill(void) -{ - bool result = true; - - if(mProcessID != 0) - { - // Try to kill the process. We'll do approximately the same thing whether the kill returns an error or not, so we ignore the result. - (void)::kill(mProcessID, SIGTERM); - - // This will have the side-effect of reaping the zombie if the process has exited. - if(isRunning()) - { - result = false; - } - } - - return result; -} - -void LLProcessLauncher::orphan(void) -{ - // Disassociate the process from this object - if(mProcessID != 0) - { - // We may still need to reap the process's zombie eventually - sZombies.push_back(mProcessID); - - mProcessID = 0; - } -} - -// static -void LLProcessLauncher::reap(void) -{ - // Attempt to real all saved process ID's. - - std::list::iterator iter = sZombies.begin(); - while(iter != sZombies.end()) - { - if(reap_pid(*iter)) - { - iter = sZombies.erase(iter); - } - else - { - iter++; - } - } -} - -#endif diff --git a/indra/llcommon/llprocesslauncher.h b/indra/llcommon/llprocesslauncher.h deleted file mode 100644 index 63193abd8f..0000000000 --- a/indra/llcommon/llprocesslauncher.h +++ /dev/null @@ -1,107 +0,0 @@ -/** - * @file llprocesslauncher.h - * @brief Utility class for launching, terminating, and tracking the state of processes. - * - * $LicenseInfo:firstyear=2008&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2010, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; - * version 2.1 of the License only. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA - * $/LicenseInfo$ - */ - -#ifndef LL_LLPROCESSLAUNCHER_H -#define LL_LLPROCESSLAUNCHER_H - -#if LL_WINDOWS -#define WIN32_LEAN_AND_MEAN -#include -#endif - - -/* - LLProcessLauncher handles launching external processes with specified command line arguments. - It also keeps track of whether the process is still running, and can kill it if required. -*/ - -class LL_COMMON_API LLProcessLauncher -{ - LOG_CLASS(LLProcessLauncher); -public: - LLProcessLauncher(); - virtual ~LLProcessLauncher(); - - void setExecutable(const std::string &executable); - void setWorkingDirectory(const std::string &dir); - - const std::string& getExecutable() const; - - void clearArguments(); - void addArgument(const std::string &arg); - - int launch(void); - // isRunning isn't const because, if child isn't running, it clears stored - // process ID - bool isRunning(void); - - // Attempt to kill the process -- returns true if the process is no longer running when it returns. - // Note that even if this returns false, the process may exit some time after it's called. - bool kill(void); - - // Use this if you want the external process to continue execution after the LLProcessLauncher instance controlling it is deleted. - // Normally, the destructor will attempt to kill the process and wait for termination. - // This should only be used if the viewer is about to exit -- otherwise, the child process will become a zombie after it exits. - void orphan(void); - - // This needs to be called periodically on Mac/Linux to clean up zombie processes. - // (However, as of 2012-01-12 there are no such calls in the viewer code base. :-P ) - static void reap(void); - - // Accessors for platform-specific process ID -#if LL_WINDOWS - // (Windows flavor unused as of 2012-01-12) - typedef HANDLE ll_pid_t; - HANDLE getProcessHandle() const { return mProcessHandle; } - ll_pid_t getProcessID() const { return mProcessHandle; } -#else - typedef pid_t ll_pid_t; - ll_pid_t getProcessID() const { return mProcessID; }; -#endif - /** - * Test if a process (ll_pid_t obtained from getProcessID()) is still - * running. Return is same nonzero ll_pid_t value if still running, else - * zero, so you can test it like a bool. But if you want to update a - * stored variable as a side effect, you can write code like this: - * @code - * childpid = LLProcessLauncher::isRunning(childpid); - * @endcode - */ - static ll_pid_t isRunning(ll_pid_t); - -private: - std::string mExecutable; - std::string mWorkingDir; - std::vector mLaunchArguments; - -#if LL_WINDOWS - HANDLE mProcessHandle; -#else - pid_t mProcessID; -#endif -}; - -#endif // LL_LLPROCESSLAUNCHER_H diff --git a/indra/llcommon/tests/llprocess_test.cpp b/indra/llcommon/tests/llprocess_test.cpp new file mode 100644 index 0000000000..55e22abd81 --- /dev/null +++ b/indra/llcommon/tests/llprocess_test.cpp @@ -0,0 +1,706 @@ +/** + * @file llprocess_test.cpp + * @author Nat Goodspeed + * @date 2011-12-19 + * @brief Test for llprocess. + * + * $LicenseInfo:firstyear=2011&license=viewerlgpl$ + * Copyright (c) 2011, Linden Research, Inc. + * $/LicenseInfo$ + */ + +// Precompiled header +#include "linden_common.h" +// associated header +#include "llprocess.h" +// STL headers +#include +#include +// std headers +#include +// external library headers +#include "llapr.h" +#include "apr_thread_proc.h" +#include +#include +#include +#include +//#include +//#include +// other Linden headers +#include "../test/lltut.h" +#include "../test/manageapr.h" +#include "../test/namedtempfile.h" +#include "stringize.h" +#include "llsdutil.h" + +#if defined(LL_WINDOWS) +#define sleep(secs) _sleep((secs) * 1000) +#define EOL "\r\n" +#else +#define EOL "\n" +#include +#endif + +//namespace lambda = boost::lambda; + +// static instance of this manages APR init/cleanup +static ManageAPR manager; + +/***************************************************************************** +* Helpers +*****************************************************************************/ + +#define ensure_equals_(left, right) \ + ensure_equals(STRINGIZE(#left << " != " << #right), (left), (right)) + +#define aprchk(expr) aprchk_(#expr, (expr)) +static void aprchk_(const char* call, apr_status_t rv, apr_status_t expected=APR_SUCCESS) +{ + tut::ensure_equals(STRINGIZE(call << " => " << rv << ": " << manager.strerror(rv)), + rv, expected); +} + +/** + * Read specified file using std::getline(). It is assumed to be an error if + * the file is empty: don't use this function if that's an acceptable case. + * Last line will not end with '\n'; this is to facilitate the usual case of + * string compares with a single line of output. + * @param pathname The file to read. + * @param desc Optional description of the file for error message; + * defaults to "in " + */ +static std::string readfile(const std::string& pathname, const std::string& desc="") +{ + std::string use_desc(desc); + if (use_desc.empty()) + { + use_desc = STRINGIZE("in " << pathname); + } + std::ifstream inf(pathname.c_str()); + std::string output; + tut::ensure(STRINGIZE("No output " << use_desc), std::getline(inf, output)); + std::string more; + while (std::getline(inf, more)) + { + output += '\n' + more; + } + return output; +} + +/** + * Construct an LLProcess to run a Python script. + */ +struct PythonProcessLauncher +{ + /** + * @param desc Arbitrary description for error messages + * @param script Python script, any form acceptable to NamedTempFile, + * typically either a std::string or an expression of the form + * (lambda::_1 << "script content with " << variable_data) + */ + template + PythonProcessLauncher(const std::string& desc, const CONTENT& script): + mDesc(desc), + mScript("py", script) + { + const char* PYTHON(getenv("PYTHON")); + tut::ensure("Set $PYTHON to the Python interpreter", PYTHON); + + mParams["executable"] = PYTHON; + mParams["args"].append(mScript.getName()); + } + + /// Run Python script and wait for it to complete. + void run() + { + mPy = LLProcess::create(mParams); + tut::ensure(STRINGIZE("Couldn't launch " << mDesc << " script"), mPy); + // One of the irritating things about LLProcess is that + // there's no API to wait for the child to terminate -- but given + // its use in our graphics-intensive interactive viewer, it's + // understandable. + while (mPy->isRunning()) + { + sleep(1); + } + } + + /** + * Run a Python script using LLProcess, expecting that it will + * write to the file passed as its sys.argv[1]. Retrieve that output. + * + * Until January 2012, LLProcess provided distressingly few + * mechanisms for a child process to communicate back to its caller -- + * not even its return code. We've introduced a convention by which we + * create an empty temp file, pass the name of that file to our child + * as sys.argv[1] and expect the script to write its output to that + * file. This function implements the C++ (parent process) side of + * that convention. + */ + std::string run_read() + { + NamedTempFile out("out", ""); // placeholder + // pass name of this temporary file to the script + mParams["args"].append(out.getName()); + run(); + // assuming the script wrote to that file, read it + return readfile(out.getName(), STRINGIZE("from " << mDesc << " script")); + } + + LLSD mParams; + LLProcessPtr mPy; + std::string mDesc; + NamedTempFile mScript; +}; + +/// convenience function for PythonProcessLauncher::run() +template +static void python(const std::string& desc, const CONTENT& script) +{ + PythonProcessLauncher py(desc, script); + py.run(); +} + +/// convenience function for PythonProcessLauncher::run_read() +template +static std::string python_out(const std::string& desc, const CONTENT& script) +{ + PythonProcessLauncher py(desc, script); + return py.run_read(); +} + +/// Create a temporary directory and clean it up later. +class NamedTempDir: public boost::noncopyable +{ +public: + // Use python() function to create a temp directory: I've found + // nothing in either Boost.Filesystem or APR quite like Python's + // tempfile.mkdtemp(). + // Special extra bonus: on Mac, mkdtemp() reports a pathname + // starting with /var/folders/something, whereas that's really a + // symlink to /private/var/folders/something. Have to use + // realpath() to compare properly. + NamedTempDir(): + mPath(python_out("mkdtemp()", + "from __future__ import with_statement\n" + "import os.path, sys, tempfile\n" + "with open(sys.argv[1], 'w') as f:\n" + " f.write(os.path.realpath(tempfile.mkdtemp()))\n")) + {} + + ~NamedTempDir() + { + aprchk(apr_dir_remove(mPath.c_str(), gAPRPoolp)); + } + + std::string getName() const { return mPath; } + +private: + std::string mPath; +}; + +/***************************************************************************** +* TUT +*****************************************************************************/ +namespace tut +{ + struct llprocess_data + { + LLAPRPool pool; + }; + typedef test_group llprocess_group; + typedef llprocess_group::object object; + llprocess_group llprocessgrp("llprocess"); + + struct Item + { + Item(): tries(0) {} + unsigned tries; + std::string which; + std::string what; + }; + +/*==========================================================================*| +#define tabent(symbol) { symbol, #symbol } + static struct ReasonCode + { + int code; + const char* name; + } reasons[] = + { + tabent(APR_OC_REASON_DEATH), + tabent(APR_OC_REASON_UNWRITABLE), + tabent(APR_OC_REASON_RESTART), + tabent(APR_OC_REASON_UNREGISTER), + tabent(APR_OC_REASON_LOST), + tabent(APR_OC_REASON_RUNNING) + }; +#undef tabent +|*==========================================================================*/ + + struct WaitInfo + { + WaitInfo(apr_proc_t* child_): + child(child_), + rv(-1), // we haven't yet called apr_proc_wait() + rc(0), + why(apr_exit_why_e(0)) + {} + apr_proc_t* child; // which subprocess + apr_status_t rv; // return from apr_proc_wait() + int rc; // child's exit code + apr_exit_why_e why; // APR_PROC_EXIT, APR_PROC_SIGNAL, APR_PROC_SIGNAL_CORE + }; + + void child_status_callback(int reason, void* data, int status) + { +/*==========================================================================*| + std::string reason_str; + BOOST_FOREACH(const ReasonCode& rcp, reasons) + { + if (reason == rcp.code) + { + reason_str = rcp.name; + break; + } + } + if (reason_str.empty()) + { + reason_str = STRINGIZE("unknown reason " << reason); + } + std::cout << "child_status_callback(" << reason_str << ")\n"; +|*==========================================================================*/ + + if (reason == APR_OC_REASON_DEATH || reason == APR_OC_REASON_LOST) + { + // Somewhat oddly, APR requires that you explicitly unregister + // even when it already knows the child has terminated. + apr_proc_other_child_unregister(data); + + WaitInfo* wi(static_cast(data)); + // It's just wrong to call apr_proc_wait() here. The only way APR + // knows to call us with APR_OC_REASON_DEATH is that it's already + // reaped this child process, so calling wait() will only produce + // "huh?" from the OS. We must rely on the status param passed in, + // which unfortunately comes straight from the OS wait() call. +// wi->rv = apr_proc_wait(wi->child, &wi->rc, &wi->why, APR_NOWAIT); + wi->rv = APR_CHILD_DONE; // fake apr_proc_wait() results +#if defined(LL_WINDOWS) + wi->why = APR_PROC_EXIT; + wi->rc = status; // no encoding on Windows (no signals) +#else // Posix + if (WIFEXITED(status)) + { + wi->why = APR_PROC_EXIT; + wi->rc = WEXITSTATUS(status); + } + else if (WIFSIGNALED(status)) + { + wi->why = APR_PROC_SIGNAL; + wi->rc = WTERMSIG(status); + } + else // uh, shouldn't happen? + { + wi->why = APR_PROC_EXIT; + wi->rc = status; // someone else will have to decode + } +#endif // Posix + } + } + + template<> template<> + void object::test<1>() + { + set_test_name("raw APR nonblocking I/O"); + + // Create a script file in a temporary place. + NamedTempFile script("py", + "import sys" EOL + "import time" EOL + EOL + "time.sleep(2)" EOL + "print >>sys.stdout, 'stdout after wait'" EOL + "sys.stdout.flush()" EOL + "time.sleep(2)" EOL + "print >>sys.stderr, 'stderr after wait'" EOL + "sys.stderr.flush()" EOL + ); + + // Arrange to track the history of our interaction with child: what we + // fetched, which pipe it came from, how many tries it took before we + // got it. + std::vector history; + history.push_back(Item()); + + // Run the child process. + apr_procattr_t *procattr = NULL; + aprchk(apr_procattr_create(&procattr, pool.getAPRPool())); + aprchk(apr_procattr_io_set(procattr, APR_CHILD_BLOCK, APR_CHILD_BLOCK, APR_CHILD_BLOCK)); + aprchk(apr_procattr_cmdtype_set(procattr, APR_PROGRAM_PATH)); + + std::vector argv; + apr_proc_t child; + argv.push_back("python"); + // Have to have a named copy of this std::string so its c_str() value + // will persist. + std::string scriptname(script.getName()); + argv.push_back(scriptname.c_str()); + argv.push_back(NULL); + + aprchk(apr_proc_create(&child, argv[0], + &argv[0], + NULL, // if we wanted to pass explicit environment + procattr, + pool.getAPRPool())); + + // We do not want this child process to outlive our APR pool. On + // destruction of the pool, forcibly kill the process. Tell APR to try + // SIGTERM and wait 3 seconds. If that didn't work, use SIGKILL. + apr_pool_note_subprocess(pool.getAPRPool(), &child, APR_KILL_AFTER_TIMEOUT); + + // arrange to call child_status_callback() + WaitInfo wi(&child); + apr_proc_other_child_register(&child, child_status_callback, &wi, child.in, pool.getAPRPool()); + + // TODO: + // Stuff child.in until it (would) block to verify EWOULDBLOCK/EAGAIN. + // Have child script clear it later, then write one more line to prove + // that it gets through. + + // Monitor two different output pipes. Because one will be closed + // before the other, keep them in a list so we can drop whichever of + // them is closed first. + typedef std::pair DescFile; + typedef std::list DescFileList; + DescFileList outfiles; + outfiles.push_back(DescFile("out", child.out)); + outfiles.push_back(DescFile("err", child.err)); + + while (! outfiles.empty()) + { + // This peculiar for loop is designed to let us erase(dfli). With + // a list, that invalidates only dfli itself -- but even so, we + // lose the ability to increment it for the next item. So at the + // top of every loop, while dfli is still valid, increment + // dflnext. Then before the next iteration, set dfli to dflnext. + for (DescFileList::iterator + dfli(outfiles.begin()), dflnext(outfiles.begin()), dflend(outfiles.end()); + dfli != dflend; dfli = dflnext) + { + // Only valid to increment dflnext once we're sure it's not + // already at dflend. + ++dflnext; + + char buf[4096]; + + apr_status_t rv = apr_file_gets(buf, sizeof(buf), dfli->second); + if (APR_STATUS_IS_EOF(rv)) + { +// std::cout << "(EOF on " << dfli->first << ")\n"; +// history.back().which = dfli->first; +// history.back().what = "*eof*"; +// history.push_back(Item()); + outfiles.erase(dfli); + continue; + } + if (rv == EWOULDBLOCK || rv == EAGAIN) + { +// std::cout << "(waiting; apr_file_gets(" << dfli->first << ") => " << rv << ": " << manager.strerror(rv) << ")\n"; + ++history.back().tries; + continue; + } + aprchk_("apr_file_gets(buf, sizeof(buf), dfli->second)", rv); + // Is it even possible to get APR_SUCCESS but read 0 bytes? + // Hope not, but defend against that anyway. + if (buf[0]) + { +// std::cout << dfli->first << ": " << buf; + history.back().which = dfli->first; + history.back().what.append(buf); + if (buf[strlen(buf) - 1] == '\n') + history.push_back(Item()); + else + { + // Just for pretty output... if we only read a partial + // line, terminate it. +// std::cout << "...\n"; + } + } + } + // Do this once per tick, as we expect the viewer will + apr_proc_other_child_refresh_all(APR_OC_REASON_RUNNING); + sleep(1); + } + apr_file_close(child.in); + apr_file_close(child.out); + apr_file_close(child.err); + + // Okay, we've broken the loop because our pipes are all closed. If we + // haven't yet called wait, give the callback one more chance. This + // models the fact that unlike this small test program, the viewer + // will still be running. + if (wi.rv == -1) + { + std::cout << "last gasp apr_proc_other_child_refresh_all()\n"; + apr_proc_other_child_refresh_all(APR_OC_REASON_RUNNING); + } + + if (wi.rv == -1) + { + std::cout << "child_status_callback(APR_OC_REASON_DEATH) wasn't called" << std::endl; + wi.rv = apr_proc_wait(wi.child, &wi.rc, &wi.why, APR_NOWAIT); + } +// std::cout << "child done: rv = " << rv << " (" << manager.strerror(rv) << "), why = " << why << ", rc = " << rc << '\n'; + aprchk_("apr_proc_wait(wi->child, &wi->rc, &wi->why, APR_NOWAIT)", wi.rv, APR_CHILD_DONE); + ensure_equals_(wi.why, APR_PROC_EXIT); + ensure_equals_(wi.rc, 0); + + // Beyond merely executing all the above successfully, verify that we + // obtained expected output -- and that we duly got control while + // waiting, proving the non-blocking nature of these pipes. + try + { + unsigned i = 0; + ensure("blocking I/O on child pipe (0)", history[i].tries); + ensure_equals_(history[i].which, "out"); + ensure_equals_(history[i].what, "stdout after wait" EOL); +// ++i; +// ensure_equals_(history[i].which, "out"); +// ensure_equals_(history[i].what, "*eof*"); + ++i; + ensure("blocking I/O on child pipe (1)", history[i].tries); + ensure_equals_(history[i].which, "err"); + ensure_equals_(history[i].what, "stderr after wait" EOL); +// ++i; +// ensure_equals_(history[i].which, "err"); +// ensure_equals_(history[i].what, "*eof*"); + } + catch (const failure&) + { + std::cout << "History:\n"; + BOOST_FOREACH(const Item& item, history) + { + std::string what(item.what); + if ((! what.empty()) && what[what.length() - 1] == '\n') + { + what.erase(what.length() - 1); + if ((! what.empty()) && what[what.length() - 1] == '\r') + { + what.erase(what.length() - 1); + what.append("\\r"); + } + what.append("\\n"); + } + std::cout << " " << item.which << ": '" << what << "' (" + << item.tries << " tries)\n"; + } + std::cout << std::flush; + // re-raise same error; just want to enrich the output + throw; + } + } + + template<> template<> + void object::test<2>() + { + set_test_name("setWorkingDirectory()"); + // We want to test setWorkingDirectory(). But what directory is + // guaranteed to exist on every machine, under every OS? Have to + // create one. Naturally, ensure we clean it up when done. + NamedTempDir tempdir; + PythonProcessLauncher py("getcwd()", + "from __future__ import with_statement\n" + "import os, sys\n" + "with open(sys.argv[1], 'w') as f:\n" + " f.write(os.getcwd())\n"); + // Before running, call setWorkingDirectory() + py.mParams["cwd"] = tempdir.getName(); + ensure_equals("os.getcwd()", py.run_read(), tempdir.getName()); + } + + template<> template<> + void object::test<3>() + { + set_test_name("arguments"); + PythonProcessLauncher py("args", + "from __future__ import with_statement\n" + "import sys\n" + // note nonstandard output-file arg! + "with open(sys.argv[3], 'w') as f:\n" + " for arg in sys.argv[1:]:\n" + " print >>f, arg\n"); + // We expect that PythonProcessLauncher has already appended + // its own NamedTempFile to mParams["args"] (sys.argv[0]). + py.mParams["args"].append("first arg"); // sys.argv[1] + py.mParams["args"].append("second arg"); // sys.argv[2] + // run_read() appends() one more argument, hence [3] + std::string output(py.run_read()); + boost::split_iterator + li(output, boost::first_finder("\n")), lend; + ensure("didn't get first arg", li != lend); + std::string arg(li->begin(), li->end()); + ensure_equals(arg, "first arg"); + ++li; + ensure("didn't get second arg", li != lend); + arg.assign(li->begin(), li->end()); + ensure_equals(arg, "second arg"); + ++li; + ensure("didn't get output filename?!", li != lend); + arg.assign(li->begin(), li->end()); + ensure("output filename empty?!", ! arg.empty()); + ++li; + ensure("too many args", li == lend); + } + + template<> template<> + void object::test<4>() + { + set_test_name("explicit kill()"); + PythonProcessLauncher py("kill()", + "from __future__ import with_statement\n" + "import sys, time\n" + "with open(sys.argv[1], 'w') as f:\n" + " f.write('ok')\n" + "# now sleep; expect caller to kill\n" + "time.sleep(120)\n" + "# if caller hasn't managed to kill by now, bad\n" + "with open(sys.argv[1], 'w') as f:\n" + " f.write('bad')\n"); + NamedTempFile out("out", "not started"); + py.mParams["args"].append(out.getName()); + py.mPy = LLProcess::create(py.mParams); + ensure("couldn't launch kill() script", py.mPy); + // Wait for the script to wake up and do its first write + int i = 0, timeout = 60; + for ( ; i < timeout; ++i) + { + sleep(1); + if (readfile(out.getName(), "from kill() script") == "ok") + break; + } + // If we broke this loop because of the counter, something's wrong + ensure("script never started", i < timeout); + // script has performed its first write and should now be sleeping. + py.mPy->kill(); + // wait for the script to terminate... one way or another. + while (py.mPy->isRunning()) + { + sleep(1); + } + // If kill() failed, the script would have woken up on its own and + // overwritten the file with 'bad'. But if kill() succeeded, it should + // not have had that chance. + ensure_equals("kill() script output", readfile(out.getName()), "ok"); + } + + template<> template<> + void object::test<5>() + { + set_test_name("implicit kill()"); + NamedTempFile out("out", "not started"); + LLProcess::id pid(0); + { + PythonProcessLauncher py("kill()", + "from __future__ import with_statement\n" + "import sys, time\n" + "with open(sys.argv[1], 'w') as f:\n" + " f.write('ok')\n" + "# now sleep; expect caller to kill\n" + "time.sleep(120)\n" + "# if caller hasn't managed to kill by now, bad\n" + "with open(sys.argv[1], 'w') as f:\n" + " f.write('bad')\n"); + py.mParams["args"].append(out.getName()); + py.mPy = LLProcess::create(py.mParams); + ensure("couldn't launch kill() script", py.mPy); + // Capture id for later + pid = py.mPy->getProcessID(); + // Wait for the script to wake up and do its first write + int i = 0, timeout = 60; + for ( ; i < timeout; ++i) + { + sleep(1); + if (readfile(out.getName(), "from kill() script") == "ok") + break; + } + // If we broke this loop because of the counter, something's wrong + ensure("script never started", i < timeout); + // Script has performed its first write and should now be sleeping. + // Destroy the LLProcess, which should kill the child. + } + // wait for the script to terminate... one way or another. + while (LLProcess::isRunning(pid)) + { + sleep(1); + } + // If kill() failed, the script would have woken up on its own and + // overwritten the file with 'bad'. But if kill() succeeded, it should + // not have had that chance. + ensure_equals("kill() script output", readfile(out.getName()), "ok"); + } + + template<> template<> + void object::test<6>() + { + set_test_name("autokill"); + NamedTempFile from("from", "not started"); + NamedTempFile to("to", ""); + LLProcess::id pid(0); + { + PythonProcessLauncher py("autokill", + "from __future__ import with_statement\n" + "import sys, time\n" + "with open(sys.argv[1], 'w') as f:\n" + " f.write('ok')\n" + "# wait for 'go' from test program\n" + "for i in xrange(60):\n" + " time.sleep(1)\n" + " with open(sys.argv[2]) as f:\n" + " go = f.read()\n" + " if go == 'go':\n" + " break\n" + "else:\n" + " with open(sys.argv[1], 'w') as f:\n" + " f.write('never saw go')\n" + " sys.exit(1)\n" + "# okay, saw 'go', write 'ack'\n" + "with open(sys.argv[1], 'w') as f:\n" + " f.write('ack')\n"); + py.mParams["args"].append(from.getName()); + py.mParams["args"].append(to.getName()); + py.mParams["autokill"] = false; + py.mPy = LLProcess::create(py.mParams); + ensure("couldn't launch kill() script", py.mPy); + // Capture id for later + pid = py.mPy->getProcessID(); + // Wait for the script to wake up and do its first write + int i = 0, timeout = 60; + for ( ; i < timeout; ++i) + { + sleep(1); + if (readfile(from.getName(), "from autokill script") == "ok") + break; + } + // If we broke this loop because of the counter, something's wrong + ensure("script never started", i < timeout); + // Now destroy the LLProcess, which should NOT kill the child! + } + // If the destructor killed the child anyway, give it time to die + sleep(2); + // How do we know it's not terminated? By making it respond to + // a specific stimulus in a specific way. + { + std::ofstream outf(to.getName().c_str()); + outf << "go"; + } // flush and close. + // now wait for the script to terminate... one way or another. + while (LLProcess::isRunning(pid)) + { + sleep(1); + } + // If the LLProcess destructor implicitly called kill(), the + // script could not have written 'ack' as we expect. + ensure_equals("autokill script output", readfile(from.getName()), "ack"); + } +} // namespace tut diff --git a/indra/llcommon/tests/llprocesslauncher_test.cpp b/indra/llcommon/tests/llprocesslauncher_test.cpp deleted file mode 100644 index 057f83631e..0000000000 --- a/indra/llcommon/tests/llprocesslauncher_test.cpp +++ /dev/null @@ -1,718 +0,0 @@ -/** - * @file llprocesslauncher_test.cpp - * @author Nat Goodspeed - * @date 2011-12-19 - * @brief Test for llprocesslauncher. - * - * $LicenseInfo:firstyear=2011&license=viewerlgpl$ - * Copyright (c) 2011, Linden Research, Inc. - * $/LicenseInfo$ - */ - -// Precompiled header -#include "linden_common.h" -// associated header -#include "llprocesslauncher.h" -// STL headers -#include -#include -// std headers -#include -// external library headers -#include "llapr.h" -#include "apr_thread_proc.h" -#include -#include -#include -#include -//#include -//#include -// other Linden headers -#include "../test/lltut.h" -#include "../test/manageapr.h" -#include "../test/namedtempfile.h" -#include "stringize.h" - -#if defined(LL_WINDOWS) -#define sleep(secs) _sleep((secs) * 1000) -#define EOL "\r\n" -#else -#define EOL "\n" -#include -#endif - -//namespace lambda = boost::lambda; - -// static instance of this manages APR init/cleanup -static ManageAPR manager; - -/***************************************************************************** -* Helpers -*****************************************************************************/ - -#define ensure_equals_(left, right) \ - ensure_equals(STRINGIZE(#left << " != " << #right), (left), (right)) - -#define aprchk(expr) aprchk_(#expr, (expr)) -static void aprchk_(const char* call, apr_status_t rv, apr_status_t expected=APR_SUCCESS) -{ - tut::ensure_equals(STRINGIZE(call << " => " << rv << ": " << manager.strerror(rv)), - rv, expected); -} - -/** - * Read specified file using std::getline(). It is assumed to be an error if - * the file is empty: don't use this function if that's an acceptable case. - * Last line will not end with '\n'; this is to facilitate the usual case of - * string compares with a single line of output. - * @param pathname The file to read. - * @param desc Optional description of the file for error message; - * defaults to "in " - */ -static std::string readfile(const std::string& pathname, const std::string& desc="") -{ - std::string use_desc(desc); - if (use_desc.empty()) - { - use_desc = STRINGIZE("in " << pathname); - } - std::ifstream inf(pathname.c_str()); - std::string output; - tut::ensure(STRINGIZE("No output " << use_desc), std::getline(inf, output)); - std::string more; - while (std::getline(inf, more)) - { - output += '\n' + more; - } - return output; -} - -/** - * Construct an LLProcessLauncher to run a Python script. - */ -struct PythonProcessLauncher -{ - /** - * @param desc Arbitrary description for error messages - * @param script Python script, any form acceptable to NamedTempFile, - * typically either a std::string or an expression of the form - * (lambda::_1 << "script content with " << variable_data) - */ - template - PythonProcessLauncher(const std::string& desc, const CONTENT& script): - mDesc(desc), - mScript("py", script) - { - const char* PYTHON(getenv("PYTHON")); - tut::ensure("Set $PYTHON to the Python interpreter", PYTHON); - - mPy.setExecutable(PYTHON); - mPy.addArgument(mScript.getName()); - } - - /// Run Python script and wait for it to complete. - void run() - { - tut::ensure_equals(STRINGIZE("Couldn't launch " << mDesc << " script"), - mPy.launch(), 0); - // One of the irritating things about LLProcessLauncher is that - // there's no API to wait for the child to terminate -- but given - // its use in our graphics-intensive interactive viewer, it's - // understandable. - while (mPy.isRunning()) - { - sleep(1); - } - } - - /** - * Run a Python script using LLProcessLauncher, expecting that it will - * write to the file passed as its sys.argv[1]. Retrieve that output. - * - * Until January 2012, LLProcessLauncher provided distressingly few - * mechanisms for a child process to communicate back to its caller -- - * not even its return code. We've introduced a convention by which we - * create an empty temp file, pass the name of that file to our child - * as sys.argv[1] and expect the script to write its output to that - * file. This function implements the C++ (parent process) side of - * that convention. - */ - std::string run_read() - { - NamedTempFile out("out", ""); // placeholder - // pass name of this temporary file to the script - mPy.addArgument(out.getName()); - run(); - // assuming the script wrote to that file, read it - return readfile(out.getName(), STRINGIZE("from " << mDesc << " script")); - } - - LLProcessLauncher mPy; - std::string mDesc; - NamedTempFile mScript; -}; - -/// convenience function for PythonProcessLauncher::run() -template -static void python(const std::string& desc, const CONTENT& script) -{ - PythonProcessLauncher py(desc, script); - py.run(); -} - -/// convenience function for PythonProcessLauncher::run_read() -template -static std::string python_out(const std::string& desc, const CONTENT& script) -{ - PythonProcessLauncher py(desc, script); - return py.run_read(); -} - -/// Create a temporary directory and clean it up later. -class NamedTempDir: public boost::noncopyable -{ -public: - // Use python() function to create a temp directory: I've found - // nothing in either Boost.Filesystem or APR quite like Python's - // tempfile.mkdtemp(). - // Special extra bonus: on Mac, mkdtemp() reports a pathname - // starting with /var/folders/something, whereas that's really a - // symlink to /private/var/folders/something. Have to use - // realpath() to compare properly. - NamedTempDir(): - mPath(python_out("mkdtemp()", - "from __future__ import with_statement\n" - "import os.path, sys, tempfile\n" - "with open(sys.argv[1], 'w') as f:\n" - " f.write(os.path.realpath(tempfile.mkdtemp()))\n")) - {} - - ~NamedTempDir() - { - aprchk(apr_dir_remove(mPath.c_str(), gAPRPoolp)); - } - - std::string getName() const { return mPath; } - -private: - std::string mPath; -}; - -/***************************************************************************** -* TUT -*****************************************************************************/ -namespace tut -{ - struct llprocesslauncher_data - { - LLAPRPool pool; - }; - typedef test_group llprocesslauncher_group; - typedef llprocesslauncher_group::object object; - llprocesslauncher_group llprocesslaunchergrp("llprocesslauncher"); - - struct Item - { - Item(): tries(0) {} - unsigned tries; - std::string which; - std::string what; - }; - -/*==========================================================================*| -#define tabent(symbol) { symbol, #symbol } - static struct ReasonCode - { - int code; - const char* name; - } reasons[] = - { - tabent(APR_OC_REASON_DEATH), - tabent(APR_OC_REASON_UNWRITABLE), - tabent(APR_OC_REASON_RESTART), - tabent(APR_OC_REASON_UNREGISTER), - tabent(APR_OC_REASON_LOST), - tabent(APR_OC_REASON_RUNNING) - }; -#undef tabent -|*==========================================================================*/ - - struct WaitInfo - { - WaitInfo(apr_proc_t* child_): - child(child_), - rv(-1), // we haven't yet called apr_proc_wait() - rc(0), - why(apr_exit_why_e(0)) - {} - apr_proc_t* child; // which subprocess - apr_status_t rv; // return from apr_proc_wait() - int rc; // child's exit code - apr_exit_why_e why; // APR_PROC_EXIT, APR_PROC_SIGNAL, APR_PROC_SIGNAL_CORE - }; - - void child_status_callback(int reason, void* data, int status) - { -/*==========================================================================*| - std::string reason_str; - BOOST_FOREACH(const ReasonCode& rcp, reasons) - { - if (reason == rcp.code) - { - reason_str = rcp.name; - break; - } - } - if (reason_str.empty()) - { - reason_str = STRINGIZE("unknown reason " << reason); - } - std::cout << "child_status_callback(" << reason_str << ")\n"; -|*==========================================================================*/ - - if (reason == APR_OC_REASON_DEATH || reason == APR_OC_REASON_LOST) - { - // Somewhat oddly, APR requires that you explicitly unregister - // even when it already knows the child has terminated. - apr_proc_other_child_unregister(data); - - WaitInfo* wi(static_cast(data)); - // It's just wrong to call apr_proc_wait() here. The only way APR - // knows to call us with APR_OC_REASON_DEATH is that it's already - // reaped this child process, so calling wait() will only produce - // "huh?" from the OS. We must rely on the status param passed in, - // which unfortunately comes straight from the OS wait() call. -// wi->rv = apr_proc_wait(wi->child, &wi->rc, &wi->why, APR_NOWAIT); - wi->rv = APR_CHILD_DONE; // fake apr_proc_wait() results -#if defined(LL_WINDOWS) - wi->why = APR_PROC_EXIT; - wi->rc = status; // no encoding on Windows (no signals) -#else // Posix - if (WIFEXITED(status)) - { - wi->why = APR_PROC_EXIT; - wi->rc = WEXITSTATUS(status); - } - else if (WIFSIGNALED(status)) - { - wi->why = APR_PROC_SIGNAL; - wi->rc = WTERMSIG(status); - } - else // uh, shouldn't happen? - { - wi->why = APR_PROC_EXIT; - wi->rc = status; // someone else will have to decode - } -#endif // Posix - } - } - - template<> template<> - void object::test<1>() - { - set_test_name("raw APR nonblocking I/O"); - - // Create a script file in a temporary place. - NamedTempFile script("py", - "import sys" EOL - "import time" EOL - EOL - "time.sleep(2)" EOL - "print >>sys.stdout, 'stdout after wait'" EOL - "sys.stdout.flush()" EOL - "time.sleep(2)" EOL - "print >>sys.stderr, 'stderr after wait'" EOL - "sys.stderr.flush()" EOL - ); - - // Arrange to track the history of our interaction with child: what we - // fetched, which pipe it came from, how many tries it took before we - // got it. - std::vector history; - history.push_back(Item()); - - // Run the child process. - apr_procattr_t *procattr = NULL; - aprchk(apr_procattr_create(&procattr, pool.getAPRPool())); - aprchk(apr_procattr_io_set(procattr, APR_CHILD_BLOCK, APR_CHILD_BLOCK, APR_CHILD_BLOCK)); - aprchk(apr_procattr_cmdtype_set(procattr, APR_PROGRAM_PATH)); - - std::vector argv; - apr_proc_t child; - argv.push_back("python"); - // Have to have a named copy of this std::string so its c_str() value - // will persist. - std::string scriptname(script.getName()); - argv.push_back(scriptname.c_str()); - argv.push_back(NULL); - - aprchk(apr_proc_create(&child, argv[0], - &argv[0], - NULL, // if we wanted to pass explicit environment - procattr, - pool.getAPRPool())); - - // We do not want this child process to outlive our APR pool. On - // destruction of the pool, forcibly kill the process. Tell APR to try - // SIGTERM and wait 3 seconds. If that didn't work, use SIGKILL. - apr_pool_note_subprocess(pool.getAPRPool(), &child, APR_KILL_AFTER_TIMEOUT); - - // arrange to call child_status_callback() - WaitInfo wi(&child); - apr_proc_other_child_register(&child, child_status_callback, &wi, child.in, pool.getAPRPool()); - - // TODO: - // Stuff child.in until it (would) block to verify EWOULDBLOCK/EAGAIN. - // Have child script clear it later, then write one more line to prove - // that it gets through. - - // Monitor two different output pipes. Because one will be closed - // before the other, keep them in a list so we can drop whichever of - // them is closed first. - typedef std::pair DescFile; - typedef std::list DescFileList; - DescFileList outfiles; - outfiles.push_back(DescFile("out", child.out)); - outfiles.push_back(DescFile("err", child.err)); - - while (! outfiles.empty()) - { - // This peculiar for loop is designed to let us erase(dfli). With - // a list, that invalidates only dfli itself -- but even so, we - // lose the ability to increment it for the next item. So at the - // top of every loop, while dfli is still valid, increment - // dflnext. Then before the next iteration, set dfli to dflnext. - for (DescFileList::iterator - dfli(outfiles.begin()), dflnext(outfiles.begin()), dflend(outfiles.end()); - dfli != dflend; dfli = dflnext) - { - // Only valid to increment dflnext once we're sure it's not - // already at dflend. - ++dflnext; - - char buf[4096]; - - apr_status_t rv = apr_file_gets(buf, sizeof(buf), dfli->second); - if (APR_STATUS_IS_EOF(rv)) - { -// std::cout << "(EOF on " << dfli->first << ")\n"; -// history.back().which = dfli->first; -// history.back().what = "*eof*"; -// history.push_back(Item()); - outfiles.erase(dfli); - continue; - } - if (rv == EWOULDBLOCK || rv == EAGAIN) - { -// std::cout << "(waiting; apr_file_gets(" << dfli->first << ") => " << rv << ": " << manager.strerror(rv) << ")\n"; - ++history.back().tries; - continue; - } - aprchk_("apr_file_gets(buf, sizeof(buf), dfli->second)", rv); - // Is it even possible to get APR_SUCCESS but read 0 bytes? - // Hope not, but defend against that anyway. - if (buf[0]) - { -// std::cout << dfli->first << ": " << buf; - history.back().which = dfli->first; - history.back().what.append(buf); - if (buf[strlen(buf) - 1] == '\n') - history.push_back(Item()); - else - { - // Just for pretty output... if we only read a partial - // line, terminate it. -// std::cout << "...\n"; - } - } - } - // Do this once per tick, as we expect the viewer will - apr_proc_other_child_refresh_all(APR_OC_REASON_RUNNING); - sleep(1); - } - apr_file_close(child.in); - apr_file_close(child.out); - apr_file_close(child.err); - - // Okay, we've broken the loop because our pipes are all closed. If we - // haven't yet called wait, give the callback one more chance. This - // models the fact that unlike this small test program, the viewer - // will still be running. - if (wi.rv == -1) - { - std::cout << "last gasp apr_proc_other_child_refresh_all()\n"; - apr_proc_other_child_refresh_all(APR_OC_REASON_RUNNING); - } - - if (wi.rv == -1) - { - std::cout << "child_status_callback(APR_OC_REASON_DEATH) wasn't called" << std::endl; - wi.rv = apr_proc_wait(wi.child, &wi.rc, &wi.why, APR_NOWAIT); - } -// std::cout << "child done: rv = " << rv << " (" << manager.strerror(rv) << "), why = " << why << ", rc = " << rc << '\n'; - aprchk_("apr_proc_wait(wi->child, &wi->rc, &wi->why, APR_NOWAIT)", wi.rv, APR_CHILD_DONE); - ensure_equals_(wi.why, APR_PROC_EXIT); - ensure_equals_(wi.rc, 0); - - // Beyond merely executing all the above successfully, verify that we - // obtained expected output -- and that we duly got control while - // waiting, proving the non-blocking nature of these pipes. - try - { - unsigned i = 0; - ensure("blocking I/O on child pipe (0)", history[i].tries); - ensure_equals_(history[i].which, "out"); - ensure_equals_(history[i].what, "stdout after wait" EOL); -// ++i; -// ensure_equals_(history[i].which, "out"); -// ensure_equals_(history[i].what, "*eof*"); - ++i; - ensure("blocking I/O on child pipe (1)", history[i].tries); - ensure_equals_(history[i].which, "err"); - ensure_equals_(history[i].what, "stderr after wait" EOL); -// ++i; -// ensure_equals_(history[i].which, "err"); -// ensure_equals_(history[i].what, "*eof*"); - } - catch (const failure&) - { - std::cout << "History:\n"; - BOOST_FOREACH(const Item& item, history) - { - std::string what(item.what); - if ((! what.empty()) && what[what.length() - 1] == '\n') - { - what.erase(what.length() - 1); - if ((! what.empty()) && what[what.length() - 1] == '\r') - { - what.erase(what.length() - 1); - what.append("\\r"); - } - what.append("\\n"); - } - std::cout << " " << item.which << ": '" << what << "' (" - << item.tries << " tries)\n"; - } - std::cout << std::flush; - // re-raise same error; just want to enrich the output - throw; - } - } - - template<> template<> - void object::test<2>() - { - set_test_name("set/getExecutable()"); - LLProcessLauncher child; - child.setExecutable("nonsense string"); - ensure_equals("setExecutable() 0", child.getExecutable(), "nonsense string"); - child.setExecutable("python"); - ensure_equals("setExecutable() 1", child.getExecutable(), "python"); - } - - template<> template<> - void object::test<3>() - { - set_test_name("setWorkingDirectory()"); - // We want to test setWorkingDirectory(). But what directory is - // guaranteed to exist on every machine, under every OS? Have to - // create one. Naturally, ensure we clean it up when done. - NamedTempDir tempdir; - PythonProcessLauncher py("getcwd()", - "from __future__ import with_statement\n" - "import os, sys\n" - "with open(sys.argv[1], 'w') as f:\n" - " f.write(os.getcwd())\n"); - // Before running, call setWorkingDirectory() - py.mPy.setWorkingDirectory(tempdir.getName()); - ensure_equals("os.getcwd()", py.run_read(), tempdir.getName()); - } - - template<> template<> - void object::test<4>() - { - set_test_name("clearArguments()"); - PythonProcessLauncher py("args", - "from __future__ import with_statement\n" - "import sys\n" - // note nonstandard output-file arg! - "with open(sys.argv[3], 'w') as f:\n" - " for arg in sys.argv[1:]:\n" - " print >>f, arg\n"); - // We expect that PythonProcessLauncher has already called - // addArgument() with the name of its own NamedTempFile. But let's - // change it up. - py.mPy.clearArguments(); - // re-add script pathname - py.mPy.addArgument(py.mScript.getName()); // sys.argv[0] - py.mPy.addArgument("first arg"); // sys.argv[1] - py.mPy.addArgument("second arg"); // sys.argv[2] - // run_read() calls addArgument() one more time, hence [3] - std::string output(py.run_read()); - boost::split_iterator - li(output, boost::first_finder("\n")), lend; - ensure("didn't get first arg", li != lend); - std::string arg(li->begin(), li->end()); - ensure_equals(arg, "first arg"); - ++li; - ensure("didn't get second arg", li != lend); - arg.assign(li->begin(), li->end()); - ensure_equals(arg, "second arg"); - ++li; - ensure("didn't get output filename?!", li != lend); - arg.assign(li->begin(), li->end()); - ensure("output filename empty?!", ! arg.empty()); - ++li; - ensure("too many args", li == lend); - } - - template<> template<> - void object::test<5>() - { - set_test_name("explicit kill()"); - PythonProcessLauncher py("kill()", - "from __future__ import with_statement\n" - "import sys, time\n" - "with open(sys.argv[1], 'w') as f:\n" - " f.write('ok')\n" - "# now sleep; expect caller to kill\n" - "time.sleep(120)\n" - "# if caller hasn't managed to kill by now, bad\n" - "with open(sys.argv[1], 'w') as f:\n" - " f.write('bad')\n"); - NamedTempFile out("out", "not started"); - py.mPy.addArgument(out.getName()); - ensure_equals("couldn't launch kill() script", py.mPy.launch(), 0); - // Wait for the script to wake up and do its first write - int i = 0, timeout = 60; - for ( ; i < timeout; ++i) - { - sleep(1); - if (readfile(out.getName(), "from kill() script") == "ok") - break; - } - // If we broke this loop because of the counter, something's wrong - ensure("script never started", i < timeout); - // script has performed its first write and should now be sleeping. - py.mPy.kill(); - // wait for the script to terminate... one way or another. - while (py.mPy.isRunning()) - { - sleep(1); - } - // If kill() failed, the script would have woken up on its own and - // overwritten the file with 'bad'. But if kill() succeeded, it should - // not have had that chance. - ensure_equals("kill() script output", readfile(out.getName()), "ok"); - } - - template<> template<> - void object::test<6>() - { - set_test_name("implicit kill()"); - NamedTempFile out("out", "not started"); - LLProcessLauncher::ll_pid_t pid(0); - { - PythonProcessLauncher py("kill()", - "from __future__ import with_statement\n" - "import sys, time\n" - "with open(sys.argv[1], 'w') as f:\n" - " f.write('ok')\n" - "# now sleep; expect caller to kill\n" - "time.sleep(120)\n" - "# if caller hasn't managed to kill by now, bad\n" - "with open(sys.argv[1], 'w') as f:\n" - " f.write('bad')\n"); - py.mPy.addArgument(out.getName()); - ensure_equals("couldn't launch kill() script", py.mPy.launch(), 0); - // Capture ll_pid_t for later - pid = py.mPy.getProcessID(); - // Wait for the script to wake up and do its first write - int i = 0, timeout = 60; - for ( ; i < timeout; ++i) - { - sleep(1); - if (readfile(out.getName(), "from kill() script") == "ok") - break; - } - // If we broke this loop because of the counter, something's wrong - ensure("script never started", i < timeout); - // Script has performed its first write and should now be sleeping. - // Destroy the LLProcessLauncher, which should kill the child. - } - // wait for the script to terminate... one way or another. - while (LLProcessLauncher::isRunning(pid)) - { - sleep(1); - } - // If kill() failed, the script would have woken up on its own and - // overwritten the file with 'bad'. But if kill() succeeded, it should - // not have had that chance. - ensure_equals("kill() script output", readfile(out.getName()), "ok"); - } - - template<> template<> - void object::test<7>() - { - set_test_name("orphan()"); - NamedTempFile from("from", "not started"); - NamedTempFile to("to", ""); - LLProcessLauncher::ll_pid_t pid(0); - { - PythonProcessLauncher py("orphan()", - "from __future__ import with_statement\n" - "import sys, time\n" - "with open(sys.argv[1], 'w') as f:\n" - " f.write('ok')\n" - "# wait for 'go' from test program\n" - "for i in xrange(60):\n" - " time.sleep(1)\n" - " with open(sys.argv[2]) as f:\n" - " go = f.read()\n" - " if go == 'go':\n" - " break\n" - "else:\n" - " with open(sys.argv[1], 'w') as f:\n" - " f.write('never saw go')\n" - " sys.exit(1)\n" - "# okay, saw 'go', write 'ack'\n" - "with open(sys.argv[1], 'w') as f:\n" - " f.write('ack')\n"); - py.mPy.addArgument(from.getName()); - py.mPy.addArgument(to.getName()); - ensure_equals("couldn't launch kill() script", py.mPy.launch(), 0); - // Capture ll_pid_t for later - pid = py.mPy.getProcessID(); - // Wait for the script to wake up and do its first write - int i = 0, timeout = 60; - for ( ; i < timeout; ++i) - { - sleep(1); - if (readfile(from.getName(), "from orphan() script") == "ok") - break; - } - // If we broke this loop because of the counter, something's wrong - ensure("script never started", i < timeout); - // Script has performed its first write and should now be waiting - // for us. Orphan it. - py.mPy.orphan(); - // Now destroy the LLProcessLauncher, which should NOT kill the child! - } - // If the destructor killed the child anyway, give it time to die - sleep(2); - // How do we know it's not terminated? By making it respond to - // a specific stimulus in a specific way. - { - std::ofstream outf(to.getName().c_str()); - outf << "go"; - } // flush and close. - // now wait for the script to terminate... one way or another. - while (LLProcessLauncher::isRunning(pid)) - { - sleep(1); - } - // If the LLProcessLauncher destructor implicitly called kill(), the - // script could not have written 'ack' as we expect. - ensure_equals("orphan() script output", readfile(from.getName()), "ack"); - } -} // namespace tut diff --git a/indra/llcommon/tests/llsdserialize_test.cpp b/indra/llcommon/tests/llsdserialize_test.cpp index 4359e9afb9..7756ba6226 100644 --- a/indra/llcommon/tests/llsdserialize_test.cpp +++ b/indra/llcommon/tests/llsdserialize_test.cpp @@ -40,7 +40,7 @@ typedef U32 uint32_t; #include #include #include -#include "llprocesslauncher.h" +#include "llprocess.h" #endif #include "boost/range.hpp" @@ -1557,14 +1557,15 @@ namespace tut } #else // LL_DARWIN, LL_LINUX - LLProcessLauncher py; - py.setExecutable(PYTHON); - py.addArgument(scriptfile.getName()); - ensure_equals(STRINGIZE("Couldn't launch " << desc << " script"), py.launch(), 0); + LLSD params; + params["executable"] = PYTHON; + params["args"].append(scriptfile.getName()); + LLProcessPtr py(LLProcess::create(params)); + ensure(STRINGIZE("Couldn't launch " << desc << " script"), py); // Implementing timeout would mean messing with alarm() and // catching SIGALRM... later maybe... int status(0); - if (waitpid(py.getProcessID(), &status, 0) == -1) + if (waitpid(py->getProcessID(), &status, 0) == -1) { int waitpid_errno(errno); ensure_equals(STRINGIZE("Couldn't retrieve rc from " << desc << " script: " diff --git a/indra/llplugin/llpluginprocessparent.cpp b/indra/llplugin/llpluginprocessparent.cpp index 110fac0f23..9b225cabb8 100644 --- a/indra/llplugin/llpluginprocessparent.cpp +++ b/indra/llplugin/llpluginprocessparent.cpp @@ -31,6 +31,7 @@ #include "llpluginprocessparent.h" #include "llpluginmessagepipe.h" #include "llpluginmessageclasses.h" +#include "stringize.h" #include "llapr.h" @@ -134,7 +135,10 @@ LLPluginProcessParent::~LLPluginProcessParent() mSharedMemoryRegions.erase(iter); } - mProcess.kill(); + if (mProcess) + { + mProcess->kill(); + } killSockets(); } @@ -159,8 +163,8 @@ void LLPluginProcessParent::errorState(void) void LLPluginProcessParent::init(const std::string &launcher_filename, const std::string &plugin_dir, const std::string &plugin_filename, bool debug) { - mProcess.setExecutable(launcher_filename); - mProcess.setWorkingDirectory(plugin_dir); + mProcessParams["executable"] = launcher_filename; + mProcessParams["cwd"] = plugin_dir; mPluginFile = plugin_filename; mPluginDir = plugin_dir; mCPUUsage = 0.0f; @@ -371,10 +375,8 @@ void LLPluginProcessParent::idle(void) // Launch the plugin process. // Only argument to the launcher is the port number we're listening on - std::stringstream stream; - stream << mBoundPort; - mProcess.addArgument(stream.str()); - if(mProcess.launch() != 0) + mProcessParams["args"].append(stringize(mBoundPort)); + if (! (mProcess = LLProcess::create(mProcessParams))) { errorState(); } @@ -388,19 +390,18 @@ void LLPluginProcessParent::idle(void) // The command we're constructing would look like this on the command line: // osascript -e 'tell application "Terminal"' -e 'set win to do script "gdb -pid 12345"' -e 'do script "continue" in win' -e 'end tell' - std::stringstream cmd; - - mDebugger.setExecutable("/usr/bin/osascript"); - mDebugger.addArgument("-e"); - mDebugger.addArgument("tell application \"Terminal\""); - mDebugger.addArgument("-e"); - cmd << "set win to do script \"gdb -pid " << mProcess.getProcessID() << "\""; - mDebugger.addArgument(cmd.str()); - mDebugger.addArgument("-e"); - mDebugger.addArgument("do script \"continue\" in win"); - mDebugger.addArgument("-e"); - mDebugger.addArgument("end tell"); - mDebugger.launch(); + LLSD params; + params["executable"] = "/usr/bin/osascript"; + params["args"].append("-e"); + params["args"].append("tell application \"Terminal\""); + params["args"].append("-e"); + params["args"].append(STRINGIZE("set win to do script \"gdb -pid " + << mProcess->getProcessID() << "\"")); + params["args"].append("-e"); + params["args"].append("do script \"continue\" in win"); + params["args"].append("-e"); + params["args"].append("end tell"); + mDebugger = LLProcess::create(params); #endif } @@ -470,7 +471,7 @@ void LLPluginProcessParent::idle(void) break; case STATE_EXITING: - if(!mProcess.isRunning()) + if (! mProcess->isRunning()) { setState(STATE_CLEANUP); } @@ -498,7 +499,7 @@ void LLPluginProcessParent::idle(void) break; case STATE_CLEANUP: - mProcess.kill(); + mProcess->kill(); killSockets(); setState(STATE_DONE); break; @@ -1077,7 +1078,7 @@ bool LLPluginProcessParent::pluginLockedUpOrQuit() { bool result = false; - if(!mProcess.isRunning()) + if (! mProcess->isRunning()) { LL_WARNS("Plugin") << "child exited" << LL_ENDL; result = true; diff --git a/indra/llplugin/llpluginprocessparent.h b/indra/llplugin/llpluginprocessparent.h index c66723f175..e8bcba75e0 100644 --- a/indra/llplugin/llpluginprocessparent.h +++ b/indra/llplugin/llpluginprocessparent.h @@ -30,13 +30,14 @@ #define LL_LLPLUGINPROCESSPARENT_H #include "llapr.h" -#include "llprocesslauncher.h" +#include "llprocess.h" #include "llpluginmessage.h" #include "llpluginmessagepipe.h" #include "llpluginsharedmemory.h" #include "lliosocket.h" #include "llthread.h" +#include "llsd.h" class LLPluginProcessParentOwner { @@ -148,8 +149,9 @@ private: LLSocket::ptr_t mListenSocket; LLSocket::ptr_t mSocket; U32 mBoundPort; - - LLProcessLauncher mProcess; + + LLSD mProcessParams; + LLProcessPtr mProcess; std::string mPluginFile; std::string mPluginDir; @@ -171,7 +173,7 @@ private: bool mBlocked; bool mPolledInput; - LLProcessLauncher mDebugger; + LLProcessPtr mDebugger; F32 mPluginLaunchTimeout; // Somewhat longer timeout for initial launch. F32 mPluginLockupTimeout; // If we don't receive a heartbeat in this many seconds, we declare the plugin locked up. diff --git a/indra/newview/llexternaleditor.cpp b/indra/newview/llexternaleditor.cpp index ed1d7e860a..ba58cd8067 100644 --- a/indra/newview/llexternaleditor.cpp +++ b/indra/newview/llexternaleditor.cpp @@ -29,6 +29,9 @@ #include "lltrans.h" #include "llui.h" +#include "llprocess.h" +#include "llsdutil.h" +#include // static const std::string LLExternalEditor::sFilenameMarker = "%s"; @@ -45,19 +48,8 @@ LLExternalEditor::EErrorCode LLExternalEditor::setCommand(const std::string& env return EC_NOT_SPECIFIED; } - // Add the filename marker if missing. - if (cmd.find(sFilenameMarker) == std::string::npos) - { - cmd += " \"" + sFilenameMarker + "\""; - llinfos << "Adding the filename marker (" << sFilenameMarker << ")" << llendl; - } - string_vec_t tokens; - if (tokenize(tokens, cmd) < 2) // 2 = bin + at least one arg (%s) - { - llwarns << "Error parsing editor command" << llendl; - return EC_PARSE_ERROR; - } + tokenize(tokens, cmd); // Check executable for existence. std::string bin_path = tokens[0]; @@ -68,51 +60,60 @@ LLExternalEditor::EErrorCode LLExternalEditor::setCommand(const std::string& env } // Save command. - mProcess.setExecutable(bin_path); - mArgs.clear(); + mProcessParams["executable"] = bin_path; + mProcessParams["args"].clear(); for (size_t i = 1; i < tokens.size(); ++i) { - if (i > 1) mArgs += " "; - mArgs += "\"" + tokens[i] + "\""; + mProcessParams["args"].append(tokens[i]); + } + + // Add the filename marker if missing. + if (cmd.find(sFilenameMarker) == std::string::npos) + { + mProcessParams["args"].append(sFilenameMarker); + llinfos << "Adding the filename marker (" << sFilenameMarker << ")" << llendl; + } + + llinfos << "Setting command [" << bin_path; + BOOST_FOREACH(const std::string& arg, llsd::inArray(mProcessParams["args"])) + { + llcont << " \"" << arg << "\""; } - llinfos << "Setting command [" << bin_path << " " << mArgs << "]" << llendl; + llcont << "]" << llendl; return EC_SUCCESS; } LLExternalEditor::EErrorCode LLExternalEditor::run(const std::string& file_path) { - std::string args = mArgs; - if (mProcess.getExecutable().empty() || args.empty()) + if (mProcessParams["executable"].asString().empty() || ! mProcessParams["args"].size()) { llwarns << "Editor command not set" << llendl; return EC_NOT_SPECIFIED; } - // Substitute the filename marker in the command with the actual passed file name. - LLStringUtil::replaceString(args, sFilenameMarker, file_path); - - // Split command into separate tokens. - string_vec_t tokens; - tokenize(tokens, args); + // Copy params block so we can replace sFilenameMarker + LLSD params(mProcessParams); - // Set process arguments taken from the command. - mProcess.clearArguments(); - for (string_vec_t::const_iterator arg_it = tokens.begin(); arg_it != tokens.end(); ++arg_it) + // Substitute the filename marker in the command with the actual passed file name. + LLSD& args(params["args"]); + for (LLSD::array_iterator ai(args.beginArray()), aend(args.endArray()); ai != aend; ++ai) { - mProcess.addArgument(*arg_it); + std::string sarg(*ai); + LLStringUtil::replaceString(sarg, sFilenameMarker, file_path); + *ai = sarg; } // Run the editor. - llinfos << "Running editor command [" << mProcess.getExecutable() + " " + args << "]" << llendl; - int result = mProcess.launch(); - if (result == 0) + llinfos << "Running editor command [" << params["executable"]; + BOOST_FOREACH(const std::string& arg, llsd::inArray(params["args"])) { - // Prevent killing the process in destructor (will add it to the zombies list). - mProcess.orphan(); + llcont << " \"" << arg << "\""; } - - return result == 0 ? EC_SUCCESS : EC_FAILED_TO_RUN; + llcont << "]" << llendl; + // Prevent killing the process in destructor. + params["autokill"] = false; + return LLProcess::create(params) ? EC_SUCCESS : EC_FAILED_TO_RUN; } // static diff --git a/indra/newview/llexternaleditor.h b/indra/newview/llexternaleditor.h index ef5db56c6e..e81c360c24 100644 --- a/indra/newview/llexternaleditor.h +++ b/indra/newview/llexternaleditor.h @@ -27,7 +27,7 @@ #ifndef LL_LLEXTERNALEDITOR_H #define LL_LLEXTERNALEDITOR_H -#include +#include "llsd.h" /** * Usage: @@ -98,8 +98,7 @@ private: static const std::string sSetting; - std::string mArgs; - LLProcessLauncher mProcess; + LLSD mProcessParams; }; #endif // LL_LLEXTERNALEDITOR_H diff --git a/indra/viewer_components/updater/llupdateinstaller.cpp b/indra/viewer_components/updater/llupdateinstaller.cpp index 84f23b3acc..e99fd0af7e 100644 --- a/indra/viewer_components/updater/llupdateinstaller.cpp +++ b/indra/viewer_components/updater/llupdateinstaller.cpp @@ -26,10 +26,10 @@ #include "linden_common.h" #include #include "llapr.h" -#include "llprocesslauncher.h" +#include "llprocess.h" #include "llupdateinstaller.h" #include "lldir.h" - +#include "llsd.h" #if defined(LL_WINDOWS) #pragma warning(disable: 4702) // disable 'unreachable code' so we can use lexical_cast (really!). @@ -78,15 +78,13 @@ int ll_install_update(std::string const & script, llinfos << "UpdateInstaller: installing " << updatePath << " using " << actualScriptPath << LL_ENDL; - LLProcessLauncher launcher; - launcher.setExecutable(actualScriptPath); - launcher.addArgument(updatePath); - launcher.addArgument(ll_install_failed_marker_path()); - launcher.addArgument(boost::lexical_cast(required)); - int result = launcher.launch(); - launcher.orphan(); - - return result; + LLSD params; + params["executable"] = actualScriptPath; + params["args"].append(updatePath); + params["args"].append(ll_install_failed_marker_path()); + params["args"].append(boost::lexical_cast(required)); + params["autokill"] = false; + return LLProcess::create(params)? 0 : -1; } -- cgit v1.2.3 From 6e214960ce203d1d50d7bd6bd04eedee3afd0fa3 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Fri, 20 Jan 2012 20:19:50 -0500 Subject: Define LLProcess::Params; accept create(const LLSDParamAdapter&). This allows callers to pass either LLSD formatted as before -- which all callers still do -- or an actual LLProcess::Params block. --- indra/llcommon/llprocess.cpp | 31 +++++++++++++------------------ indra/llcommon/llprocess.h | 33 +++++++++++++++++++++++++++------ 2 files changed, 40 insertions(+), 24 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/llprocess.cpp b/indra/llcommon/llprocess.cpp index 8c0caca680..dfb2ed69e9 100644 --- a/indra/llcommon/llprocess.cpp +++ b/indra/llcommon/llprocess.cpp @@ -26,7 +26,6 @@ #include "linden_common.h" #include "llprocess.h" -#include "llsd.h" #include "llsdserialize.h" #include "stringize.h" @@ -41,7 +40,7 @@ struct LLProcessError: public std::runtime_error LLProcessError(const std::string& msg): std::runtime_error(msg) {} }; -LLProcessPtr LLProcess::create(const LLSD& params) +LLProcessPtr LLProcess::create(const LLSDParamAdapter& params) { try { @@ -54,16 +53,13 @@ LLProcessPtr LLProcess::create(const LLSD& params) } } -LLProcess::LLProcess(const LLSD& params): +LLProcess::LLProcess(const LLSDParamAdapter& params): mProcessID(0), - mAutokill(params["autokill"].asBoolean()) + mAutokill(params.autokill) { - // nonstandard default bool value - if (! params.has("autokill")) - mAutokill = true; - if (! params.has("executable")) + if (! params.validateBlock(true)) { - throw LLProcessError(STRINGIZE("not launched: missing 'executable'\n" + throw LLProcessError(STRINGIZE("not launched: failed parameter validation\n" << LLSDNotationStreamer(params))); } @@ -108,14 +104,14 @@ static std::string quote(const std::string& str) return result + "\""; } -void LLProcess::launch(const LLSD& params) +void LLProcess::launch(const LLSDParamAdapter& params) { PROCESS_INFORMATION pinfo; STARTUPINFOA sinfo; memset(&sinfo, 0, sizeof(sinfo)); - std::string args = quote(params["executable"]); - BOOST_FOREACH(const std::string& arg, llsd::inArray(params["args"])) + std::string args = quote(params.executable); + BOOST_FOREACH(const std::string& arg, params.args) { args += " "; args += quote(arg); @@ -128,7 +124,7 @@ void LLProcess::launch(const LLSD& params) // Convert wrapper to a real std::string so we can use c_str(); but use a // named variable instead of a temporary so c_str() pointer remains valid. - std::string cwd(params["cwd"]); + std::string cwd(params.cwd); const char * working_directory = 0; if (! cwd.empty()) working_directory = cwd.c_str(); @@ -212,7 +208,7 @@ static bool reap_pid(pid_t pid) return false; } -void LLProcess::launch(const LLSD& params) +void LLProcess::launch(const LLSDParamAdapter& params) { // flush all buffers before the child inherits them ::fflush(NULL); @@ -222,7 +218,7 @@ void LLProcess::launch(const LLSD& params) { // child process - std::string cwd(params["cwd"]); + std::string cwd(params.cwd); if (! cwd.empty()) { // change to the desired child working directory @@ -239,12 +235,11 @@ void LLProcess::launch(const LLSD& params) std::vector fake_argv; // add the executable path - std::string executable(params["executable"]); + std::string executable(params.executable); fake_argv.push_back(executable.c_str()); // and any arguments - const LLSD& params_args(params["args"]); - std::vector args(params_args.beginArray(), params_args.endArray()); + std::vector args(params.args.begin(), params.args.end()); BOOST_FOREACH(const std::string& arg, args) { fake_argv.push_back(arg.c_str()); diff --git a/indra/llcommon/llprocess.h b/indra/llcommon/llprocess.h index 9a74cfe829..9ea129baf2 100644 --- a/indra/llcommon/llprocess.h +++ b/indra/llcommon/llprocess.h @@ -27,6 +27,8 @@ #ifndef LL_LLPROCESS_H #define LL_LLPROCESS_H +#include "llinitparam.h" +#include "llsdparam.h" #include #include @@ -35,8 +37,6 @@ #include #endif -class LLSD; - class LLProcess; /// LLProcess instances are created on the heap by static factory methods and /// managed by ref-counted pointers. @@ -50,17 +50,38 @@ class LL_COMMON_API LLProcess: public boost::noncopyable { LOG_CLASS(LLProcess); public: + /// Param block definition + struct Params: public LLInitParam::Block + { + Params(): + executable("executable"), + args("args"), + cwd("cwd"), + autokill("autokill", true) + {} + + /// pathname of executable + Mandatory executable; + /// zero or more additional command-line arguments + Multiple args; + /// current working directory, if need it changed + Optional cwd; + /// implicitly kill process on destruction of LLProcess object + Optional autokill; + }; /** - * Factory accepting LLSD::Map. + * Factory accepting either plain LLSD::Map or Params block. * MAY RETURN DEFAULT-CONSTRUCTED LLProcessPtr if params invalid! * + * Redundant with Params definition above? + * * executable (required, string): executable pathname * args (optional, string array): extra command-line arguments * cwd (optional, string, dft no chdir): change to this directory before executing * autokill (optional, bool, dft true): implicit kill() on ~LLProcess */ - static LLProcessPtr create(const LLSD& params); + static LLProcessPtr create(const LLSDParamAdapter& params); virtual ~LLProcess(); // isRunning isn't const because, if child isn't running, it clears stored @@ -96,8 +117,8 @@ public: private: /// constructor is private: use create() instead - LLProcess(const LLSD& params); - void launch(const LLSD& params); + LLProcess(const LLSDParamAdapter& params); + void launch(const LLSDParamAdapter& params); id mProcessID; bool mAutokill; -- cgit v1.2.3 From 47d94757075e338c480ba4d7d24948242a85a9bb Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Sat, 21 Jan 2012 11:45:15 -0500 Subject: Convert LLProcess consumers from LLSD to LLProcess::Params block. Using a Params block gives compile-time checking against attribute typos. One might inadvertently set myLLSD["autofill"] = false and only discover it when things behave strangely at runtime; but trying to set myParams.autofill will produce a compile error. However, it's excellent that the same LLProcess::create() method can accept either LLProcess::Params or a properly-constructed LLSD block. --- indra/llcommon/tests/llprocess_test.cpp | 26 ++++++++--------- indra/llcommon/tests/llsdserialize_test.cpp | 6 ++-- indra/llplugin/llpluginprocessparent.cpp | 28 +++++++++--------- indra/llplugin/llpluginprocessparent.h | 12 ++++---- indra/newview/llexternaleditor.cpp | 33 ++++++++++++---------- indra/newview/llexternaleditor.h | 5 ++-- .../updater/llupdateinstaller.cpp | 12 ++++---- 7 files changed, 62 insertions(+), 60 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/tests/llprocess_test.cpp b/indra/llcommon/tests/llprocess_test.cpp index 55e22abd81..405540e436 100644 --- a/indra/llcommon/tests/llprocess_test.cpp +++ b/indra/llcommon/tests/llprocess_test.cpp @@ -107,8 +107,8 @@ struct PythonProcessLauncher const char* PYTHON(getenv("PYTHON")); tut::ensure("Set $PYTHON to the Python interpreter", PYTHON); - mParams["executable"] = PYTHON; - mParams["args"].append(mScript.getName()); + mParams.executable = PYTHON; + mParams.args.add(mScript.getName()); } /// Run Python script and wait for it to complete. @@ -142,13 +142,13 @@ struct PythonProcessLauncher { NamedTempFile out("out", ""); // placeholder // pass name of this temporary file to the script - mParams["args"].append(out.getName()); + mParams.args.add(out.getName()); run(); // assuming the script wrote to that file, read it return readfile(out.getName(), STRINGIZE("from " << mDesc << " script")); } - LLSD mParams; + LLProcess::Params mParams; LLProcessPtr mPy; std::string mDesc; NamedTempFile mScript; @@ -515,7 +515,7 @@ namespace tut "with open(sys.argv[1], 'w') as f:\n" " f.write(os.getcwd())\n"); // Before running, call setWorkingDirectory() - py.mParams["cwd"] = tempdir.getName(); + py.mParams.cwd = tempdir.getName(); ensure_equals("os.getcwd()", py.run_read(), tempdir.getName()); } @@ -531,9 +531,9 @@ namespace tut " for arg in sys.argv[1:]:\n" " print >>f, arg\n"); // We expect that PythonProcessLauncher has already appended - // its own NamedTempFile to mParams["args"] (sys.argv[0]). - py.mParams["args"].append("first arg"); // sys.argv[1] - py.mParams["args"].append("second arg"); // sys.argv[2] + // its own NamedTempFile to mParams.args (sys.argv[0]). + py.mParams.args.add("first arg"); // sys.argv[1] + py.mParams.args.add("second arg"); // sys.argv[2] // run_read() appends() one more argument, hence [3] std::string output(py.run_read()); boost::split_iterator @@ -568,7 +568,7 @@ namespace tut "with open(sys.argv[1], 'w') as f:\n" " f.write('bad')\n"); NamedTempFile out("out", "not started"); - py.mParams["args"].append(out.getName()); + py.mParams.args.add(out.getName()); py.mPy = LLProcess::create(py.mParams); ensure("couldn't launch kill() script", py.mPy); // Wait for the script to wake up and do its first write @@ -611,7 +611,7 @@ namespace tut "# if caller hasn't managed to kill by now, bad\n" "with open(sys.argv[1], 'w') as f:\n" " f.write('bad')\n"); - py.mParams["args"].append(out.getName()); + py.mParams.args.add(out.getName()); py.mPy = LLProcess::create(py.mParams); ensure("couldn't launch kill() script", py.mPy); // Capture id for later @@ -667,9 +667,9 @@ namespace tut "# okay, saw 'go', write 'ack'\n" "with open(sys.argv[1], 'w') as f:\n" " f.write('ack')\n"); - py.mParams["args"].append(from.getName()); - py.mParams["args"].append(to.getName()); - py.mParams["autokill"] = false; + py.mParams.args.add(from.getName()); + py.mParams.args.add(to.getName()); + py.mParams.autokill = false; py.mPy = LLProcess::create(py.mParams); ensure("couldn't launch kill() script", py.mPy); // Capture id for later diff --git a/indra/llcommon/tests/llsdserialize_test.cpp b/indra/llcommon/tests/llsdserialize_test.cpp index 7756ba6226..e625545763 100644 --- a/indra/llcommon/tests/llsdserialize_test.cpp +++ b/indra/llcommon/tests/llsdserialize_test.cpp @@ -1557,9 +1557,9 @@ namespace tut } #else // LL_DARWIN, LL_LINUX - LLSD params; - params["executable"] = PYTHON; - params["args"].append(scriptfile.getName()); + LLProcess::Params params; + params.executable = PYTHON; + params.args.add(scriptfile.getName()); LLProcessPtr py(LLProcess::create(params)); ensure(STRINGIZE("Couldn't launch " << desc << " script"), py); // Implementing timeout would mean messing with alarm() and diff --git a/indra/llplugin/llpluginprocessparent.cpp b/indra/llplugin/llpluginprocessparent.cpp index 9b225cabb8..f10eaee5b4 100644 --- a/indra/llplugin/llpluginprocessparent.cpp +++ b/indra/llplugin/llpluginprocessparent.cpp @@ -163,8 +163,8 @@ void LLPluginProcessParent::errorState(void) void LLPluginProcessParent::init(const std::string &launcher_filename, const std::string &plugin_dir, const std::string &plugin_filename, bool debug) { - mProcessParams["executable"] = launcher_filename; - mProcessParams["cwd"] = plugin_dir; + mProcessParams.executable = launcher_filename; + mProcessParams.cwd = plugin_dir; mPluginFile = plugin_filename; mPluginDir = plugin_dir; mCPUUsage = 0.0f; @@ -375,7 +375,7 @@ void LLPluginProcessParent::idle(void) // Launch the plugin process. // Only argument to the launcher is the port number we're listening on - mProcessParams["args"].append(stringize(mBoundPort)); + mProcessParams.args.add(stringize(mBoundPort)); if (! (mProcess = LLProcess::create(mProcessParams))) { errorState(); @@ -390,17 +390,17 @@ void LLPluginProcessParent::idle(void) // The command we're constructing would look like this on the command line: // osascript -e 'tell application "Terminal"' -e 'set win to do script "gdb -pid 12345"' -e 'do script "continue" in win' -e 'end tell' - LLSD params; - params["executable"] = "/usr/bin/osascript"; - params["args"].append("-e"); - params["args"].append("tell application \"Terminal\""); - params["args"].append("-e"); - params["args"].append(STRINGIZE("set win to do script \"gdb -pid " - << mProcess->getProcessID() << "\"")); - params["args"].append("-e"); - params["args"].append("do script \"continue\" in win"); - params["args"].append("-e"); - params["args"].append("end tell"); + LLProcess::Params params; + params.executable = "/usr/bin/osascript"; + params.args.add("-e"); + params.args.add("tell application \"Terminal\""); + params.args.add("-e"); + params.args.add(STRINGIZE("set win to do script \"gdb -pid " + << mProcess->getProcessID() << "\"")); + params.args.add("-e"); + params.args.add("do script \"continue\" in win"); + params.args.add("-e"); + params.args.add("end tell"); mDebugger = LLProcess::create(params); #endif diff --git a/indra/llplugin/llpluginprocessparent.h b/indra/llplugin/llpluginprocessparent.h index e8bcba75e0..990fc5cbae 100644 --- a/indra/llplugin/llpluginprocessparent.h +++ b/indra/llplugin/llpluginprocessparent.h @@ -140,27 +140,27 @@ private: }; EState mState; void setState(EState state); - + bool pluginLockedUp(); bool pluginLockedUpOrQuit(); bool accept(); - + LLSocket::ptr_t mListenSocket; LLSocket::ptr_t mSocket; U32 mBoundPort; - LLSD mProcessParams; + LLProcess::Params mProcessParams; LLProcessPtr mProcess; - + std::string mPluginFile; std::string mPluginDir; LLPluginProcessParentOwner *mOwner; - + typedef std::map sharedMemoryRegionsType; sharedMemoryRegionsType mSharedMemoryRegions; - + LLSD mMessageClassVersions; std::string mPluginVersionString; diff --git a/indra/newview/llexternaleditor.cpp b/indra/newview/llexternaleditor.cpp index ba58cd8067..3dfebad958 100644 --- a/indra/newview/llexternaleditor.cpp +++ b/indra/newview/llexternaleditor.cpp @@ -60,22 +60,22 @@ LLExternalEditor::EErrorCode LLExternalEditor::setCommand(const std::string& env } // Save command. - mProcessParams["executable"] = bin_path; - mProcessParams["args"].clear(); + mProcessParams = LLProcess::Params(); + mProcessParams.executable = bin_path; for (size_t i = 1; i < tokens.size(); ++i) { - mProcessParams["args"].append(tokens[i]); + mProcessParams.args.add(tokens[i]); } // Add the filename marker if missing. if (cmd.find(sFilenameMarker) == std::string::npos) { - mProcessParams["args"].append(sFilenameMarker); + mProcessParams.args.add(sFilenameMarker); llinfos << "Adding the filename marker (" << sFilenameMarker << ")" << llendl; } llinfos << "Setting command [" << bin_path; - BOOST_FOREACH(const std::string& arg, llsd::inArray(mProcessParams["args"])) + BOOST_FOREACH(const std::string& arg, mProcessParams.args) { llcont << " \"" << arg << "\""; } @@ -86,33 +86,36 @@ LLExternalEditor::EErrorCode LLExternalEditor::setCommand(const std::string& env LLExternalEditor::EErrorCode LLExternalEditor::run(const std::string& file_path) { - if (mProcessParams["executable"].asString().empty() || ! mProcessParams["args"].size()) + // LLInitParams type wrappers don't seem to have empty() or size() + // methods; try determining emptiness by comparing begin/end iterators. + if (std::string(mProcessParams.executable).empty() || + (mProcessParams.args.begin() == mProcessParams.args.end())) { llwarns << "Editor command not set" << llendl; return EC_NOT_SPECIFIED; } // Copy params block so we can replace sFilenameMarker - LLSD params(mProcessParams); + LLProcess::Params params; + params.executable = mProcessParams.executable; // Substitute the filename marker in the command with the actual passed file name. - LLSD& args(params["args"]); - for (LLSD::array_iterator ai(args.beginArray()), aend(args.endArray()); ai != aend; ++ai) + BOOST_FOREACH(const std::string& arg, mProcessParams.args) { - std::string sarg(*ai); - LLStringUtil::replaceString(sarg, sFilenameMarker, file_path); - *ai = sarg; + std::string fixed(arg); + LLStringUtil::replaceString(fixed, sFilenameMarker, file_path); + params.args.add(fixed); } // Run the editor. - llinfos << "Running editor command [" << params["executable"]; - BOOST_FOREACH(const std::string& arg, llsd::inArray(params["args"])) + llinfos << "Running editor command [" << std::string(params.executable); + BOOST_FOREACH(const std::string& arg, params.args) { llcont << " \"" << arg << "\""; } llcont << "]" << llendl; // Prevent killing the process in destructor. - params["autokill"] = false; + params.autokill = false; return LLProcess::create(params) ? EC_SUCCESS : EC_FAILED_TO_RUN; } diff --git a/indra/newview/llexternaleditor.h b/indra/newview/llexternaleditor.h index e81c360c24..fd2c25020c 100644 --- a/indra/newview/llexternaleditor.h +++ b/indra/newview/llexternaleditor.h @@ -27,7 +27,7 @@ #ifndef LL_LLEXTERNALEDITOR_H #define LL_LLEXTERNALEDITOR_H -#include "llsd.h" +#include "llprocess.h" /** * Usage: @@ -97,8 +97,7 @@ private: */ static const std::string sSetting; - - LLSD mProcessParams; + LLProcess::Params mProcessParams; }; #endif // LL_LLEXTERNALEDITOR_H diff --git a/indra/viewer_components/updater/llupdateinstaller.cpp b/indra/viewer_components/updater/llupdateinstaller.cpp index e99fd0af7e..2f87d59373 100644 --- a/indra/viewer_components/updater/llupdateinstaller.cpp +++ b/indra/viewer_components/updater/llupdateinstaller.cpp @@ -78,12 +78,12 @@ int ll_install_update(std::string const & script, llinfos << "UpdateInstaller: installing " << updatePath << " using " << actualScriptPath << LL_ENDL; - LLSD params; - params["executable"] = actualScriptPath; - params["args"].append(updatePath); - params["args"].append(ll_install_failed_marker_path()); - params["args"].append(boost::lexical_cast(required)); - params["autokill"] = false; + LLProcess::Params params; + params.executable = actualScriptPath; + params.args.add(updatePath); + params.args.add(ll_install_failed_marker_path()); + params.args.add(boost::lexical_cast(required)); + params.autokill = false; return LLProcess::create(params)? 0 : -1; } -- cgit v1.2.3 From e690373b059117e316f7704309321aaca2839668 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Sat, 21 Jan 2012 19:46:46 -0500 Subject: Since lltrans.h moved to llui, fix linux_updater/CMakeLists.txt. --- indra/linux_updater/CMakeLists.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'indra') diff --git a/indra/linux_updater/CMakeLists.txt b/indra/linux_updater/CMakeLists.txt index 00a78b2a8f..4377a6333c 100644 --- a/indra/linux_updater/CMakeLists.txt +++ b/indra/linux_updater/CMakeLists.txt @@ -10,14 +10,14 @@ include(UI) include(LLCommon) include(LLVFS) include(LLXML) -include(LLXUIXML) +include(LLUI) include(Linking) include_directories( ${LLCOMMON_INCLUDE_DIRS} ${LLVFS_INCLUDE_DIRS} ${LLXML_INCLUDE_DIRS} - ${LLXUIXML_INCLUDE_DIRS} + ${LLUI_INCLUDE_DIRS} ${CURL_INCLUDE_DIRS} ${CARES_INCLUDE_DIRS} ${OPENSSL_INCLUDE_DIRS} @@ -42,7 +42,7 @@ target_link_libraries(linux-updater ${CRYPTO_LIBRARIES} ${UI_LIBRARIES} ${LLXML_LIBRARIES} - ${LLXUIXML_LIBRARIES} + ${LLUI_LIBRARIES} ${LLVFS_LIBRARIES} ${LLCOMMON_LIBRARIES} ) -- cgit v1.2.3 From b9a03b95aafb07eb32a8f99a671f2216acce96d4 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Sun, 22 Jan 2012 09:16:11 -0500 Subject: On Windows, introduce viewer Job Object and assign children to it. The idea is that, with the right flag settings, this will cause the OS to terminate remaining viewer child processes when the viewer terminates -- whether or not it terminates intentionally. Of course, if LLProcess's caller specifies autokill=false, e.g. to run the viewer updater, that asserts that we WANT the child to persist beyond the viewer session itself. --- indra/llcommon/llprocess.cpp | 167 +++++++++++++++++++++++++++++++++---------- 1 file changed, 128 insertions(+), 39 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/llprocess.cpp b/indra/llcommon/llprocess.cpp index dfb2ed69e9..d30d87411d 100644 --- a/indra/llcommon/llprocess.cpp +++ b/indra/llcommon/llprocess.cpp @@ -27,6 +27,7 @@ #include "linden_common.h" #include "llprocess.h" #include "llsdserialize.h" +#include "llsingleton.h" #include "stringize.h" #include @@ -80,43 +81,84 @@ bool LLProcess::isRunning(void) return (mProcessID != 0); } +/***************************************************************************** +* Windows specific +*****************************************************************************/ #if LL_WINDOWS -static std::string quote(const std::string& str) +static std::string WindowsErrorString(const std::string& operation); +static std::string quote(const std::string&); + +/** + * Wrap a Windows Job Object for use in managing child-process lifespan. + * + * On Windows, we use a Job Object to constrain the lifespan of any + * autokill=true child process to the viewer's own lifespan: + * http://stackoverflow.com/questions/53208/how-do-i-automatically-destroy-child-processes-in-windows + * (thanks Richard!). + * + * We manage it using an LLSingleton for a couple of reasons: + * + * # Lazy initialization: if some viewer session never launches a child + * process, we should never have to create a Job Object. + * # Cross-DLL support: be wary of C++ statics when multiple DLLs are + * involved. + */ +class LLJob: public LLSingleton { - std::string::size_type len(str.length()); - // If the string is already quoted, assume user knows what s/he's doing. - if (len >= 2 && str[0] == '"' && str[len-1] == '"') +public: + void assignProcess(const std::string& prog, HANDLE hProcess) { - return str; + // If we never managed to initialize this Job Object, can't use it -- + // but don't keep spamming the log, we already emitted warnings when + // we first tried to create. + if (! mJob) + return; + + if (! AssignProcessToJobObject(mJob, hProcess)) + { + LL_WARNS("LLProcess") << WindowsErrorString(STRINGIZE("AssignProcessToJobObject(\"" + << prog << "\")")) << LL_ENDL; + } } - // Not already quoted: do it. - std::string result("\""); - for (std::string::const_iterator ci(str.begin()), cend(str.end()); ci != cend; ++ci) +private: + LLJob(): + mJob(0) { - if (*ci == '"') + mJob = CreateJobObject(NULL, NULL); + if (! mJob) { - result.append("\\"); + LL_WARNS("LLProcess") << WindowsErrorString("CreateJobObject()") << LL_ENDL; + return; + } + + JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 }; + + // Configure all child processes associated with this new job object + // to terminate when the calling process (us!) terminates. + jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + if (! SetInformationJobObject(mJob, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli))) + { + LL_WARNS("LLProcess") << WindowsErrorString("SetInformationJobObject()") << LL_ENDL; } - result.push_back(*ci); } - return result + "\""; -} + + HANDLE mJob; +}; void LLProcess::launch(const LLSDParamAdapter& params) { PROCESS_INFORMATION pinfo; - STARTUPINFOA sinfo; - memset(&sinfo, 0, sizeof(sinfo)); - + STARTUPINFOA sinfo = { sizeof(sinfo) }; + std::string args = quote(params.executable); BOOST_FOREACH(const std::string& arg, params.args) { args += " "; args += quote(arg); } - + // So retarded. Windows requires that the second parameter to // CreateProcessA be a writable (non-const) string... std::vector args2(args.begin(), args.end()); @@ -130,28 +172,14 @@ void LLProcess::launch(const LLSDParamAdapter& params) working_directory = cwd.c_str(); if( ! CreateProcessA( NULL, &args2[0], NULL, NULL, FALSE, 0, NULL, working_directory, &sinfo, &pinfo ) ) { - int result = GetLastError(); - - LPTSTR error_str = 0; - if( - FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, - NULL, - result, - 0, - (LPTSTR)&error_str, - 0, - NULL) - != 0) - { - char message[256]; - wcstombs(message, error_str, sizeof(message)); - message[sizeof(message)-1] = 0; - LocalFree(error_str); - throw LLProcessError(STRINGIZE("CreateProcessA failed (" << result << "): " - << message)); - } - throw LLProcessError(STRINGIZE("CreateProcessA failed (" << result - << "), but FormatMessage() did not explain")); + throw LLProcessError(WindowsErrorString("CreateProcessA")); + } + + // Now associate the new child process with our Job Object -- unless + // autokill is false, i.e. caller asserts the child should persist. + if (params.autokill) + { + LLJob::instance().assignProcess(params.executable, pinfo.hProcess); } // foo = pinfo.dwProcessId; // get your pid here if you want to use it later on @@ -184,6 +212,67 @@ bool LLProcess::kill(void) return ! isRunning(); } +/** + * Double-quote an argument string, unless it's already double-quoted. If we + * quote it, escape any embedded double-quote with backslash. + * + * LLProcess::create()'s caller passes a Unix-style array of strings for + * command-line arguments. Our caller can and should expect that these will be + * passed to the child process as individual arguments, regardless of content + * (e.g. embedded spaces). But because Windows invokes any child process with + * a single command-line string, this means we must quote each argument behind + * the scenes. + */ +static std::string quote(const std::string& str) +{ + std::string::size_type len(str.length()); + // If the string is already quoted, assume user knows what s/he's doing. + if (len >= 2 && str[0] == '"' && str[len-1] == '"') + { + return str; + } + + // Not already quoted: do it. + std::string result("\""); + for (std::string::const_iterator ci(str.begin()), cend(str.end()); ci != cend; ++ci) + { + if (*ci == '"') + { + result.append("\\"); + } + result.push_back(*ci); + } + return result + "\""; +} + +/// GetLastError()/FormatMessage() boilerplate +static std::string WindowsErrorString(const std::string& operation) +{ + int result = GetLastError(); + + LPTSTR error_str = 0; + if (FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + result, + 0, + (LPTSTR)&error_str, + 0, + NULL) + != 0) + { + char message[256]; + wcstombs(message, error_str, sizeof(message)); + message[sizeof(message)-1] = 0; + LocalFree(error_str); + return STRINGIZE(operation << " failed (" << result << "): " << message); + } + return STRINGIZE(operation << " failed (" << result + << "), but FormatMessage() did not explain"); +} + +/***************************************************************************** +* Non-Windows specific +*****************************************************************************/ #else // Mac and linux #include -- cgit v1.2.3 From aa1bbe3277842a9a6e7db5227b35f1fbea50b7a6 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Sun, 22 Jan 2012 10:58:16 -0500 Subject: Make LLProcess::Params streamable; use that in LLExternalEditor. --- indra/llcommon/llprocess.cpp | 15 +++++++++++++++ indra/llcommon/llprocess.h | 4 ++++ indra/newview/llexternaleditor.cpp | 14 ++------------ 3 files changed, 21 insertions(+), 12 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/llprocess.cpp b/indra/llcommon/llprocess.cpp index d30d87411d..9d6c19f1dd 100644 --- a/indra/llcommon/llprocess.cpp +++ b/indra/llcommon/llprocess.cpp @@ -81,6 +81,21 @@ bool LLProcess::isRunning(void) return (mProcessID != 0); } +std::ostream& operator<<(std::ostream& out, const LLProcess::Params& params) +{ + std::string cwd(params.cwd); + if (! cwd.empty()) + { + out << "cd '" << cwd << "': "; + } + out << '"' << std::string(params.executable) << '"'; + BOOST_FOREACH(const std::string& arg, params.args) + { + out << " \"" << arg << '"'; + } + return out; +} + /***************************************************************************** * Windows specific *****************************************************************************/ diff --git a/indra/llcommon/llprocess.h b/indra/llcommon/llprocess.h index 9ea129baf2..7dbdf23679 100644 --- a/indra/llcommon/llprocess.h +++ b/indra/llcommon/llprocess.h @@ -31,6 +31,7 @@ #include "llsdparam.h" #include #include +#include // std::ostream #if LL_WINDOWS #define WIN32_LEAN_AND_MEAN @@ -124,4 +125,7 @@ private: bool mAutokill; }; +/// for logging +LL_COMMON_API std::ostream& operator<<(std::ostream&, const LLProcess::Params&); + #endif // LL_LLPROCESS_H diff --git a/indra/newview/llexternaleditor.cpp b/indra/newview/llexternaleditor.cpp index 3dfebad958..0d3ed0ba35 100644 --- a/indra/newview/llexternaleditor.cpp +++ b/indra/newview/llexternaleditor.cpp @@ -74,12 +74,7 @@ LLExternalEditor::EErrorCode LLExternalEditor::setCommand(const std::string& env llinfos << "Adding the filename marker (" << sFilenameMarker << ")" << llendl; } - llinfos << "Setting command [" << bin_path; - BOOST_FOREACH(const std::string& arg, mProcessParams.args) - { - llcont << " \"" << arg << "\""; - } - llcont << "]" << llendl; + llinfos << "Setting command [" << mProcessParams << "]" << llendl; return EC_SUCCESS; } @@ -108,12 +103,7 @@ LLExternalEditor::EErrorCode LLExternalEditor::run(const std::string& file_path) } // Run the editor. - llinfos << "Running editor command [" << std::string(params.executable); - BOOST_FOREACH(const std::string& arg, params.args) - { - llcont << " \"" << arg << "\""; - } - llcont << "]" << llendl; + llinfos << "Running editor command [" << params << "]" << llendl; // Prevent killing the process in destructor. params.autokill = false; return LLProcess::create(params) ? EC_SUCCESS : EC_FAILED_TO_RUN; -- cgit v1.2.3 From 748d1b311fdecf123df40bd7d22dd7e19afaca84 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Sun, 22 Jan 2012 11:56:38 -0500 Subject: Add LLProcess logging on launch(), kill(), isRunning(). Much as I dislike viewer log spam, seems to me starting a child process, killing it and observing its termination are noteworthy events. New logging makes LLExternalEditor launch message redundant; removed. --- indra/llcommon/llprocess.cpp | 34 +++++++++++++++++++++++++--------- indra/llcommon/llprocess.h | 7 ++++--- indra/newview/llexternaleditor.cpp | 4 +--- 3 files changed, 30 insertions(+), 15 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/llprocess.cpp b/indra/llcommon/llprocess.cpp index 9d6c19f1dd..6d329a3fa1 100644 --- a/indra/llcommon/llprocess.cpp +++ b/indra/llcommon/llprocess.cpp @@ -77,7 +77,7 @@ LLProcess::~LLProcess() bool LLProcess::isRunning(void) { - mProcessID = isRunning(mProcessID); + mProcessID = isRunning(mProcessID, mDesc); return (mProcessID != 0); } @@ -190,20 +190,23 @@ void LLProcess::launch(const LLSDParamAdapter& params) throw LLProcessError(WindowsErrorString("CreateProcessA")); } + // foo = pinfo.dwProcessId; // get your pid here if you want to use it later on + // CloseHandle(pinfo.hProcess); // stops leaks - nothing else + mProcessID = pinfo.hProcess; + CloseHandle(pinfo.hThread); // stops leaks - nothing else + + mDesc = STRINGIZE('"' << std::string(params.executable) << "\" (" << pinfo.dwProcessId << ')'); + LL_INFOS("LLProcess") << "Launched " << params << " (" << pinfo.dwProcessId << ")" << LL_ENDL; + // Now associate the new child process with our Job Object -- unless // autokill is false, i.e. caller asserts the child should persist. if (params.autokill) { - LLJob::instance().assignProcess(params.executable, pinfo.hProcess); + LLJob::instance().assignProcess(mDesc, mProcessID); } - - // foo = pinfo.dwProcessId; // get your pid here if you want to use it later on - // CloseHandle(pinfo.hProcess); // stops leaks - nothing else - mProcessID = pinfo.hProcess; - CloseHandle(pinfo.hThread); // stops leaks - nothing else } -LLProcess::id LLProcess::isRunning(id handle) +LLProcess::id LLProcess::isRunning(id handle, const std::string& desc) { if (! handle) return 0; @@ -212,6 +215,10 @@ LLProcess::id LLProcess::isRunning(id handle) if(waitresult == WAIT_OBJECT_0) { // the process has completed. + if (! desc.empty()) + { + LL_INFOS("LLProcess") << desc << " terminated" << LL_ENDL; + } return 0; } @@ -223,6 +230,7 @@ bool LLProcess::kill(void) if (! mProcessID) return false; + LL_INFOS("LLProcess") << "killing " << mDesc << LL_ENDL; TerminateProcess(mProcessID, 0); return ! isRunning(); } @@ -369,9 +377,12 @@ void LLProcess::launch(const LLSDParamAdapter& params) // parent process mProcessID = child; + + mDesc = STRINGIZE('"' << std::string(params.executable) << "\" (" << mProcessID << ')'); + LL_INFOS("LLProcess") << "Launched " << params << " (" << mProcessID << ")" << LL_ENDL; } -LLProcess::id LLProcess::isRunning(id pid) +LLProcess::id LLProcess::isRunning(id pid, const std::string& desc) { if (! pid) return 0; @@ -380,6 +391,10 @@ LLProcess::id LLProcess::isRunning(id pid) if(reap_pid(pid)) { // the process has exited. + if (! desc.empty()) + { + LL_INFOS("LLProcess") << desc << " terminated" << LL_ENDL; + } return 0; } @@ -393,6 +408,7 @@ bool LLProcess::kill(void) // Try to kill the process. We'll do approximately the same thing whether // the kill returns an error or not, so we ignore the result. + LL_INFOS("LLProcess") << "killing " << mDesc << LL_ENDL; (void)::kill(mProcessID, SIGTERM); // This will have the side-effect of reaping the zombie if the process has exited. diff --git a/indra/llcommon/llprocess.h b/indra/llcommon/llprocess.h index 7dbdf23679..019c33592c 100644 --- a/indra/llcommon/llprocess.h +++ b/indra/llcommon/llprocess.h @@ -97,7 +97,7 @@ public: typedef HANDLE id; #else typedef pid_t id; -#endif +#endif /// Get platform-specific process ID id getProcessID() const { return mProcessID; }; @@ -114,13 +114,14 @@ public: * functionality should be added as nonstatic members operating on * mProcessID. */ - static id isRunning(id); - + static id isRunning(id, const std::string& desc=""); + private: /// constructor is private: use create() instead LLProcess(const LLSDParamAdapter& params); void launch(const LLSDParamAdapter& params); + std::string mDesc; id mProcessID; bool mAutokill; }; diff --git a/indra/newview/llexternaleditor.cpp b/indra/newview/llexternaleditor.cpp index 0d3ed0ba35..561b87618c 100644 --- a/indra/newview/llexternaleditor.cpp +++ b/indra/newview/llexternaleditor.cpp @@ -102,9 +102,7 @@ LLExternalEditor::EErrorCode LLExternalEditor::run(const std::string& file_path) params.args.add(fixed); } - // Run the editor. - llinfos << "Running editor command [" << params << "]" << llendl; - // Prevent killing the process in destructor. + // Run the editor. Prevent killing the process in destructor. params.autokill = false; return LLProcess::create(params) ? EC_SUCCESS : EC_FAILED_TO_RUN; } -- cgit v1.2.3 From 323c0ef64ee02d64c983c35eee4f7ac09851e116 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Sun, 22 Jan 2012 12:06:26 -0500 Subject: Use LLProcess::create() to launch SLVoice, rather than inline code. This appears to close a long-pending action item, as it seems the original LLProcessLauncher implementation was in fact cloned-and-edited from this logic in LLVivoxVoiceClient::stateMachine(). In any case, leveraging LLProcess buys us: - reduced redundancy; fewer maintenance points - logging for both success and errors - (possibly) better SLVoice.exe lifespan management. --- indra/newview/llvoicevivox.cpp | 140 +++++------------------------------------ 1 file changed, 16 insertions(+), 124 deletions(-) (limited to 'indra') diff --git a/indra/newview/llvoicevivox.cpp b/indra/newview/llvoicevivox.cpp index df1d3f2955..820d1d73e1 100644 --- a/indra/newview/llvoicevivox.cpp +++ b/indra/newview/llvoicevivox.cpp @@ -27,8 +27,6 @@ #include "llviewerprecompiledheaders.h" #include "llvoicevivox.h" -#include - #include "llsdutil.h" // Linden library includes @@ -47,6 +45,7 @@ #include "llbase64.h" #include "llviewercontrol.h" #include "llappviewer.h" // for gDisconnected, gDisableVoice +#include "llprocess.h" // Viewer includes #include "llmutelist.h" // to check for muted avatars @@ -242,59 +241,21 @@ void LLVivoxVoiceClientCapResponder::result(const LLSD& content) } } - - -#if LL_WINDOWS -static HANDLE sGatewayHandle = 0; +static LLProcessPtr sGatewayPtr; static bool isGatewayRunning() { - bool result = false; - if(sGatewayHandle != 0) - { - DWORD waitresult = WaitForSingleObject(sGatewayHandle, 0); - if(waitresult != WAIT_OBJECT_0) - { - result = true; - } - } - return result; -} -static void killGateway() -{ - if(sGatewayHandle != 0) - { - TerminateProcess(sGatewayHandle,0); - } -} - -#else // Mac and linux - -static pid_t sGatewayPID = 0; -static bool isGatewayRunning() -{ - bool result = false; - if(sGatewayPID != 0) - { - // A kill with signal number 0 has no effect, just does error checking. It should return an error if the process no longer exists. - if(kill(sGatewayPID, 0) == 0) - { - result = true; - } - } - return result; + return sGatewayPtr && sGatewayPtr->isRunning(); } static void killGateway() { - if(sGatewayPID != 0) + if (sGatewayPtr) { - kill(sGatewayPID, SIGTERM); + sGatewayPtr->kill(); } } -#endif - /////////////////////////////////////////////////////////////////////////////////////////////// LLVivoxVoiceClient::LLVivoxVoiceClient() : @@ -790,7 +751,7 @@ void LLVivoxVoiceClient::stateMachine() } else if(!isGatewayRunning()) { - if(true) + if (true) // production build, not test { // Launch the voice daemon @@ -809,102 +770,33 @@ void LLVivoxVoiceClient::stateMachine() #endif // See if the vivox executable exists llstat s; - if(!LLFile::stat(exe_path, &s)) + if (!LLFile::stat(exe_path, &s)) { // vivox executable exists. Build the command line and launch the daemon. + LLProcess::Params params; + params.executable = exe_path; // SLIM SDK: these arguments are no longer necessary. // std::string args = " -p tcp -h -c"; - std::string args; - std::string cmd; std::string loglevel = gSavedSettings.getString("VivoxDebugLevel"); - if(loglevel.empty()) { loglevel = "-1"; // turn logging off completely } - - args += " -ll "; - args += loglevel; - - LL_DEBUGS("Voice") << "Args for SLVoice: " << args << LL_ENDL; - -#if LL_WINDOWS - PROCESS_INFORMATION pinfo; - STARTUPINFOA sinfo; - - memset(&sinfo, 0, sizeof(sinfo)); - - std::string exe_dir = gDirUtilp->getAppRODataDir(); - cmd = "SLVoice.exe"; - cmd += args; - - // So retarded. Windows requires that the second parameter to CreateProcessA be writable (non-const) string... - char *args2 = new char[args.size() + 1]; - strcpy(args2, args.c_str()); - if(!CreateProcessA(exe_path.c_str(), args2, NULL, NULL, FALSE, 0, NULL, exe_dir.c_str(), &sinfo, &pinfo)) - { -// DWORD dwErr = GetLastError(); - } - else - { - // foo = pinfo.dwProcessId; // get your pid here if you want to use it later on - // CloseHandle(pinfo.hProcess); // stops leaks - nothing else - sGatewayHandle = pinfo.hProcess; - CloseHandle(pinfo.hThread); // stops leaks - nothing else - } - - delete[] args2; -#else // LL_WINDOWS - // This should be the same for mac and linux - { - std::vector arglist; - arglist.push_back(exe_path); - - // Split the argument string into separate strings for each argument - typedef boost::tokenizer > tokenizer; - boost::char_separator sep(" "); - tokenizer tokens(args, sep); - tokenizer::iterator token_iter; - for(token_iter = tokens.begin(); token_iter != tokens.end(); ++token_iter) - { - arglist.push_back(*token_iter); - } - - // create an argv vector for the child process - char **fakeargv = new char*[arglist.size() + 1]; - int i; - for(i=0; i < arglist.size(); i++) - fakeargv[i] = const_cast(arglist[i].c_str()); + params.args.add("-ll"); + params.args.add(loglevel); + params.cwd = gDirUtilp->getAppRODataDir(); + sGatewayPtr = LLProcess::create(params); - fakeargv[i] = NULL; - - fflush(NULL); // flush all buffers before the child inherits them - pid_t id = vfork(); - if(id == 0) - { - // child - execv(exe_path.c_str(), fakeargv); - - // If we reach this point, the exec failed. - // Use _exit() instead of exit() per the vfork man page. - _exit(0); - } - - // parent - delete[] fakeargv; - sGatewayPID = id; - } -#endif // LL_WINDOWS mDaemonHost = LLHost(gSavedSettings.getString("VivoxVoiceHost").c_str(), gSavedSettings.getU32("VivoxVoicePort")); - } + } else { LL_INFOS("Voice") << exe_path << " not found." << LL_ENDL; - } + } } else - { + { // SLIM SDK: port changed from 44124 to 44125. // We can connect to a client gateway running on another host. This is useful for testing. // To do this, launch the gateway on a nearby host like this: -- cgit v1.2.3 From 738483e6302af5a9ad00fa3df17efe5336a03a41 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Sun, 22 Jan 2012 13:05:34 -0500 Subject: Every singleton needs a friend... --- indra/llcommon/llprocess.cpp | 1 + 1 file changed, 1 insertion(+) (limited to 'indra') diff --git a/indra/llcommon/llprocess.cpp b/indra/llcommon/llprocess.cpp index 6d329a3fa1..eb7ce4129b 100644 --- a/indra/llcommon/llprocess.cpp +++ b/indra/llcommon/llprocess.cpp @@ -138,6 +138,7 @@ public: } private: + friend class LLSingleton; LLJob(): mJob(0) { -- cgit v1.2.3 From 8fa6add8c3e7f6adf23aa0217d4471c9d56bc35a Mon Sep 17 00:00:00 2001 From: Kitty Barnett Date: Mon, 23 Jan 2012 19:22:47 +0100 Subject: STORM-276 Added missing library includes --- indra/newview/CMakeLists.txt | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'indra') diff --git a/indra/newview/CMakeLists.txt b/indra/newview/CMakeLists.txt index 6b2fe1e45a..bb0c4a9979 100644 --- a/indra/newview/CMakeLists.txt +++ b/indra/newview/CMakeLists.txt @@ -71,6 +71,7 @@ include_directories( ${LLLOGIN_INCLUDE_DIRS} ${UPDATER_INCLUDE_DIRS} ${LIBS_PREBUILT_DIR}/include/collada + ${LIBS_PREBUILD_DIR}/include/hunspell ${OPENAL_LIB_INCLUDE_DIRS} ${LIBS_PREBUILT_DIR}/include/collada/1.4 ) @@ -1566,6 +1567,9 @@ if (WINDOWS) ${SHARED_LIB_STAGING_DIR}/RelWithDebInfo/msvcp100.dll ${SHARED_LIB_STAGING_DIR}/Debug/msvcr100d.dll ${SHARED_LIB_STAGING_DIR}/Debug/msvcp100d.dll + ${SHARED_LIB_STAGING_DIR}/Release/libhunspell.dll + ${SHARED_LIB_STAGING_DIR}/RelWithDebInfo/libhunspell.dll + ${SHARED_LIB_STAGING_DIR}/Debug/libhunspell.dll ${SHARED_LIB_STAGING_DIR}/${CMAKE_CFG_INTDIR}/SLVoice.exe ${SHARED_LIB_STAGING_DIR}/${CMAKE_CFG_INTDIR}/vivoxsdk.dll ${SHARED_LIB_STAGING_DIR}/${CMAKE_CFG_INTDIR}/ortp.dll @@ -1745,6 +1749,7 @@ target_link_libraries(${VIEWER_BINARY_NAME} ${LLMATH_LIBRARIES} ${LLCOMMON_LIBRARIES} ${NDOF_LIBRARY} + ${HUNSPELL_LIBRARY} ${viewer_LIBRARIES} ${BOOST_PROGRAM_OPTIONS_LIBRARY} ${BOOST_REGEX_LIBRARY} -- cgit v1.2.3 From b81bf4f6f182e6345889d70140b34b15cbfb8d27 Mon Sep 17 00:00:00 2001 From: Kitty Barnett Date: Mon, 23 Jan 2012 19:31:47 +0100 Subject: STORM-276 Enabled spellchecking on selective line editors --- indra/newview/skins/default/xui/en/floater_chat_bar.xml | 1 + indra/newview/skins/default/xui/en/floater_im_session.xml | 1 + indra/newview/skins/default/xui/en/panel_nearby_chat_bar.xml | 1 + 3 files changed, 3 insertions(+) (limited to 'indra') diff --git a/indra/newview/skins/default/xui/en/floater_chat_bar.xml b/indra/newview/skins/default/xui/en/floater_chat_bar.xml index 63992462b3..32a2c26cf0 100644 --- a/indra/newview/skins/default/xui/en/floater_chat_bar.xml +++ b/indra/newview/skins/default/xui/en/floater_chat_bar.xml @@ -46,6 +46,7 @@ left="0" max_length_bytes="1023" name="chat_box" + spellcheck="true" text_pad_left="5" text_pad_right="25" tool_tip="Press Enter to say, Ctrl+Enter to shout" diff --git a/indra/newview/skins/default/xui/en/floater_im_session.xml b/indra/newview/skins/default/xui/en/floater_im_session.xml index a2739a8339..2f3788ec3d 100644 --- a/indra/newview/skins/default/xui/en/floater_im_session.xml +++ b/indra/newview/skins/default/xui/en/floater_im_session.xml @@ -84,6 +84,7 @@ label="To" layout="bottomleft" name="chat_editor" + spellcheck="true" tab_group="3" width="249"> diff --git a/indra/newview/skins/default/xui/en/panel_nearby_chat_bar.xml b/indra/newview/skins/default/xui/en/panel_nearby_chat_bar.xml index 21c627cdfb..6bc9c48729 100644 --- a/indra/newview/skins/default/xui/en/panel_nearby_chat_bar.xml +++ b/indra/newview/skins/default/xui/en/panel_nearby_chat_bar.xml @@ -19,6 +19,7 @@ left="0" max_length_bytes="1023" name="chat_box" + spellcheck="true" text_pad_left="5" text_pad_right="25" tool_tip="Press Enter to say, Ctrl+Enter to shout" -- cgit v1.2.3 From 507e136f9a25179992b2093e10ade1093cc71698 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Mon, 23 Jan 2012 16:24:33 -0500 Subject: Per Richard: close unusable Job Object; move quote() to LLStringUtil. If LLProcess can't set the right flag on a Windows Job Object, the object isn't useful to us, so we might as well discard it. quote() is sufficiently general that it belongs in LLStringUtil instead of buried as a static helper function in llprocess.cpp. --- indra/llcommon/llprocess.cpp | 49 +++------- indra/llcommon/llstring.h | 223 +++++++++++++++++++++++++------------------ 2 files changed, 141 insertions(+), 131 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/llprocess.cpp b/indra/llcommon/llprocess.cpp index eb7ce4129b..2c7512419d 100644 --- a/indra/llcommon/llprocess.cpp +++ b/indra/llcommon/llprocess.cpp @@ -28,6 +28,7 @@ #include "llprocess.h" #include "llsdserialize.h" #include "llsingleton.h" +#include "llstring.h" #include "stringize.h" #include @@ -102,7 +103,6 @@ std::ostream& operator<<(std::ostream& out, const LLProcess::Params& params) #if LL_WINDOWS static std::string WindowsErrorString(const std::string& operation); -static std::string quote(const std::string&); /** * Wrap a Windows Job Object for use in managing child-process lifespan. @@ -157,6 +157,10 @@ private: if (! SetInformationJobObject(mJob, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli))) { LL_WARNS("LLProcess") << WindowsErrorString("SetInformationJobObject()") << LL_ENDL; + // This Job Object is useless to us + CloseHandle(mJob); + // prevent assignProcess() from trying to use it + mJob = 0; } } @@ -168,11 +172,17 @@ void LLProcess::launch(const LLSDParamAdapter& params) PROCESS_INFORMATION pinfo; STARTUPINFOA sinfo = { sizeof(sinfo) }; - std::string args = quote(params.executable); + // LLProcess::create()'s caller passes a Unix-style array of strings for + // command-line arguments. Our caller can and should expect that these will be + // passed to the child process as individual arguments, regardless of content + // (e.g. embedded spaces). But because Windows invokes any child process with + // a single command-line string, this means we must quote each argument behind + // the scenes. + std::string args = LLStringUtil::quote(params.executable); BOOST_FOREACH(const std::string& arg, params.args) { args += " "; - args += quote(arg); + args += LLStringUtil::quote(arg); } // So retarded. Windows requires that the second parameter to @@ -236,39 +246,6 @@ bool LLProcess::kill(void) return ! isRunning(); } -/** - * Double-quote an argument string, unless it's already double-quoted. If we - * quote it, escape any embedded double-quote with backslash. - * - * LLProcess::create()'s caller passes a Unix-style array of strings for - * command-line arguments. Our caller can and should expect that these will be - * passed to the child process as individual arguments, regardless of content - * (e.g. embedded spaces). But because Windows invokes any child process with - * a single command-line string, this means we must quote each argument behind - * the scenes. - */ -static std::string quote(const std::string& str) -{ - std::string::size_type len(str.length()); - // If the string is already quoted, assume user knows what s/he's doing. - if (len >= 2 && str[0] == '"' && str[len-1] == '"') - { - return str; - } - - // Not already quoted: do it. - std::string result("\""); - for (std::string::const_iterator ci(str.begin()), cend(str.end()); ci != cend; ++ci) - { - if (*ci == '"') - { - result.append("\\"); - } - result.push_back(*ci); - } - return result + "\""; -} - /// GetLastError()/FormatMessage() boilerplate static std::string WindowsErrorString(const std::string& operation) { diff --git a/indra/llcommon/llstring.h b/indra/llcommon/llstring.h index 7e41e787b5..d3f1d01aa2 100644 --- a/indra/llcommon/llstring.h +++ b/indra/llcommon/llstring.h @@ -237,40 +237,41 @@ private: static std::string sLocale; public: - typedef typename std::basic_string::size_type size_type; + typedef std::basic_string string_type; + typedef typename string_type::size_type size_type; public: ///////////////////////////////////////////////////////////////////////////////////////// // Static Utility functions that operate on std::strings - static const std::basic_string null; + static const string_type null; typedef std::map format_map_t; - LL_COMMON_API static void getTokens(const std::basic_string& instr, std::vector >& tokens, const std::basic_string& delims); - LL_COMMON_API static void formatNumber(std::basic_string& numStr, std::basic_string decimals); - LL_COMMON_API static bool formatDatetime(std::basic_string& replacement, std::basic_string token, std::basic_string param, S32 secFromEpoch); - LL_COMMON_API static S32 format(std::basic_string& s, const format_map_t& substitutions); - LL_COMMON_API static S32 format(std::basic_string& s, const LLSD& substitutions); - LL_COMMON_API static bool simpleReplacement(std::basic_string& replacement, std::basic_string token, const format_map_t& substitutions); - LL_COMMON_API static bool simpleReplacement(std::basic_string& replacement, std::basic_string token, const LLSD& substitutions); + LL_COMMON_API static void getTokens(const string_type& instr, std::vector& tokens, const string_type& delims); + LL_COMMON_API static void formatNumber(string_type& numStr, string_type decimals); + LL_COMMON_API static bool formatDatetime(string_type& replacement, string_type token, string_type param, S32 secFromEpoch); + LL_COMMON_API static S32 format(string_type& s, const format_map_t& substitutions); + LL_COMMON_API static S32 format(string_type& s, const LLSD& substitutions); + LL_COMMON_API static bool simpleReplacement(string_type& replacement, string_type token, const format_map_t& substitutions); + LL_COMMON_API static bool simpleReplacement(string_type& replacement, string_type token, const LLSD& substitutions); LL_COMMON_API static void setLocale (std::string inLocale); LL_COMMON_API static std::string getLocale (void); - static bool isValidIndex(const std::basic_string& string, size_type i) + static bool isValidIndex(const string_type& string, size_type i) { return !string.empty() && (0 <= i) && (i <= string.size()); } - static void trimHead(std::basic_string& string); - static void trimTail(std::basic_string& string); - static void trim(std::basic_string& string) { trimHead(string); trimTail(string); } - static void truncate(std::basic_string& string, size_type count); + static void trimHead(string_type& string); + static void trimTail(string_type& string); + static void trim(string_type& string) { trimHead(string); trimTail(string); } + static void truncate(string_type& string, size_type count); - static void toUpper(std::basic_string& string); - static void toLower(std::basic_string& string); + static void toUpper(string_type& string); + static void toLower(string_type& string); // True if this is the head of s. - static BOOL isHead( const std::basic_string& string, const T* s ); + static BOOL isHead( const string_type& string, const T* s ); /** * @brief Returns true if string starts with substr @@ -278,8 +279,8 @@ public: * If etither string or substr are empty, this method returns false. */ static bool startsWith( - const std::basic_string& string, - const std::basic_string& substr); + const string_type& string, + const string_type& substr); /** * @brief Returns true if string ends in substr @@ -287,19 +288,26 @@ public: * If etither string or substr are empty, this method returns false. */ static bool endsWith( - const std::basic_string& string, - const std::basic_string& substr); + const string_type& string, + const string_type& substr); - static void addCRLF(std::basic_string& string); - static void removeCRLF(std::basic_string& string); + static void addCRLF(string_type& string); + static void removeCRLF(string_type& string); - static void replaceTabsWithSpaces( std::basic_string& string, size_type spaces_per_tab ); - static void replaceNonstandardASCII( std::basic_string& string, T replacement ); - static void replaceChar( std::basic_string& string, T target, T replacement ); - static void replaceString( std::basic_string& string, std::basic_string target, std::basic_string replacement ); + static void replaceTabsWithSpaces( string_type& string, size_type spaces_per_tab ); + static void replaceNonstandardASCII( string_type& string, T replacement ); + static void replaceChar( string_type& string, T target, T replacement ); + static void replaceString( string_type& string, string_type target, string_type replacement ); - static BOOL containsNonprintable(const std::basic_string& string); - static void stripNonprintable(std::basic_string& string); + static BOOL containsNonprintable(const string_type& string); + static void stripNonprintable(string_type& string); + + /** + * Double-quote an argument string, unless it's already double-quoted. If we + * quote it, escape any embedded double-quote with the escape string (default + * backslash). + */ + string_type quote(const string_type& str, const string_type& escape="\\"); /** * @brief Unsafe way to make ascii characters. You should probably @@ -308,18 +316,18 @@ public: * The 2 and 4 byte std::string probably work, so LLWStringUtil::_makeASCII * should work. */ - static void _makeASCII(std::basic_string& string); + static void _makeASCII(string_type& string); // Conversion to other data types - static BOOL convertToBOOL(const std::basic_string& string, BOOL& value); - static BOOL convertToU8(const std::basic_string& string, U8& value); - static BOOL convertToS8(const std::basic_string& string, S8& value); - static BOOL convertToS16(const std::basic_string& string, S16& value); - static BOOL convertToU16(const std::basic_string& string, U16& value); - static BOOL convertToU32(const std::basic_string& string, U32& value); - static BOOL convertToS32(const std::basic_string& string, S32& value); - static BOOL convertToF32(const std::basic_string& string, F32& value); - static BOOL convertToF64(const std::basic_string& string, F64& value); + static BOOL convertToBOOL(const string_type& string, BOOL& value); + static BOOL convertToU8(const string_type& string, U8& value); + static BOOL convertToS8(const string_type& string, S8& value); + static BOOL convertToS16(const string_type& string, S16& value); + static BOOL convertToU16(const string_type& string, U16& value); + static BOOL convertToU32(const string_type& string, U32& value); + static BOOL convertToS32(const string_type& string, S32& value); + static BOOL convertToF32(const string_type& string, F32& value); + static BOOL convertToF64(const string_type& string, F64& value); ///////////////////////////////////////////////////////////////////////////////////////// // Utility functions for working with char*'s and strings @@ -327,24 +335,24 @@ public: // Like strcmp but also handles empty strings. Uses // current locale. static S32 compareStrings(const T* lhs, const T* rhs); - static S32 compareStrings(const std::basic_string& lhs, const std::basic_string& rhs); + static S32 compareStrings(const string_type& lhs, const string_type& rhs); // case insensitive version of above. Uses current locale on // Win32, and falls back to a non-locale aware comparison on // Linux. static S32 compareInsensitive(const T* lhs, const T* rhs); - static S32 compareInsensitive(const std::basic_string& lhs, const std::basic_string& rhs); + static S32 compareInsensitive(const string_type& lhs, const string_type& rhs); // Case sensitive comparison with good handling of numbers. Does not use current locale. // a.k.a. strdictcmp() - static S32 compareDict(const std::basic_string& a, const std::basic_string& b); + static S32 compareDict(const string_type& a, const string_type& b); // Case *in*sensitive comparison with good handling of numbers. Does not use current locale. // a.k.a. strdictcmp() - static S32 compareDictInsensitive(const std::basic_string& a, const std::basic_string& b); + static S32 compareDictInsensitive(const string_type& a, const string_type& b); // Puts compareDict() in a form appropriate for LL container classes to use for sorting. - static BOOL precedesDict( const std::basic_string& a, const std::basic_string& b ); + static BOOL precedesDict( const string_type& a, const string_type& b ); // A replacement for strncpy. // If the dst buffer is dst_size bytes long or more, ensures that dst is null terminated and holds @@ -352,7 +360,7 @@ public: static void copy(T* dst, const T* src, size_type dst_size); // Copies src into dst at a given offset. - static void copyInto(std::basic_string& dst, const std::basic_string& src, size_type offset); + static void copyInto(string_type& dst, const string_type& src, size_type offset); static bool isPartOfWord(T c) { return (c == (T)'_') || LLStringOps::isAlnum(c); } @@ -362,7 +370,7 @@ public: #endif private: - LL_COMMON_API static size_type getSubstitution(const std::basic_string& instr, size_type& start, std::vector >& tokens); + LL_COMMON_API static size_type getSubstitution(const string_type& instr, size_type& start, std::vector& tokens); }; template const std::basic_string LLStringUtilBase::null; @@ -669,7 +677,7 @@ S32 LLStringUtilBase::compareStrings(const T* lhs, const T* rhs) //static template -S32 LLStringUtilBase::compareStrings(const std::basic_string& lhs, const std::basic_string& rhs) +S32 LLStringUtilBase::compareStrings(const string_type& lhs, const string_type& rhs) { return LLStringOps::collate(lhs.c_str(), rhs.c_str()); } @@ -695,8 +703,8 @@ S32 LLStringUtilBase::compareInsensitive(const T* lhs, const T* rhs ) } else { - std::basic_string lhs_string(lhs); - std::basic_string rhs_string(rhs); + string_type lhs_string(lhs); + string_type rhs_string(rhs); LLStringUtilBase::toUpper(lhs_string); LLStringUtilBase::toUpper(rhs_string); result = LLStringOps::collate(lhs_string.c_str(), rhs_string.c_str()); @@ -706,10 +714,10 @@ S32 LLStringUtilBase::compareInsensitive(const T* lhs, const T* rhs ) //static template -S32 LLStringUtilBase::compareInsensitive(const std::basic_string& lhs, const std::basic_string& rhs) +S32 LLStringUtilBase::compareInsensitive(const string_type& lhs, const string_type& rhs) { - std::basic_string lhs_string(lhs); - std::basic_string rhs_string(rhs); + string_type lhs_string(lhs); + string_type rhs_string(rhs); LLStringUtilBase::toUpper(lhs_string); LLStringUtilBase::toUpper(rhs_string); return LLStringOps::collate(lhs_string.c_str(), rhs_string.c_str()); @@ -720,7 +728,7 @@ S32 LLStringUtilBase::compareInsensitive(const std::basic_string& lhs, con //static template -S32 LLStringUtilBase::compareDict(const std::basic_string& astr, const std::basic_string& bstr) +S32 LLStringUtilBase::compareDict(const string_type& astr, const string_type& bstr) { const T* a = astr.c_str(); const T* b = bstr.c_str(); @@ -761,7 +769,7 @@ S32 LLStringUtilBase::compareDict(const std::basic_string& astr, const std // static template -S32 LLStringUtilBase::compareDictInsensitive(const std::basic_string& astr, const std::basic_string& bstr) +S32 LLStringUtilBase::compareDictInsensitive(const string_type& astr, const string_type& bstr) { const T* a = astr.c_str(); const T* b = bstr.c_str(); @@ -796,7 +804,7 @@ S32 LLStringUtilBase::compareDictInsensitive(const std::basic_string& astr // Puts compareDict() in a form appropriate for LL container classes to use for sorting. // static template -BOOL LLStringUtilBase::precedesDict( const std::basic_string& a, const std::basic_string& b ) +BOOL LLStringUtilBase::precedesDict( const string_type& a, const string_type& b ) { if( a.size() && b.size() ) { @@ -810,7 +818,7 @@ BOOL LLStringUtilBase::precedesDict( const std::basic_string& a, const std //static template -void LLStringUtilBase::toUpper(std::basic_string& string) +void LLStringUtilBase::toUpper(string_type& string) { if( !string.empty() ) { @@ -824,7 +832,7 @@ void LLStringUtilBase::toUpper(std::basic_string& string) //static template -void LLStringUtilBase::toLower(std::basic_string& string) +void LLStringUtilBase::toLower(string_type& string) { if( !string.empty() ) { @@ -838,7 +846,7 @@ void LLStringUtilBase::toLower(std::basic_string& string) //static template -void LLStringUtilBase::trimHead(std::basic_string& string) +void LLStringUtilBase::trimHead(string_type& string) { if( !string.empty() ) { @@ -853,7 +861,7 @@ void LLStringUtilBase::trimHead(std::basic_string& string) //static template -void LLStringUtilBase::trimTail(std::basic_string& string) +void LLStringUtilBase::trimTail(string_type& string) { if( string.size() ) { @@ -872,7 +880,7 @@ void LLStringUtilBase::trimTail(std::basic_string& string) // Replace line feeds with carriage return-line feed pairs. //static template -void LLStringUtilBase::addCRLF(std::basic_string& string) +void LLStringUtilBase::addCRLF(string_type& string) { const T LF = 10; const T CR = 13; @@ -914,7 +922,7 @@ void LLStringUtilBase::addCRLF(std::basic_string& string) // Remove all carriage returns //static template -void LLStringUtilBase::removeCRLF(std::basic_string& string) +void LLStringUtilBase::removeCRLF(string_type& string) { const T CR = 13; @@ -935,10 +943,10 @@ void LLStringUtilBase::removeCRLF(std::basic_string& string) //static template -void LLStringUtilBase::replaceChar( std::basic_string& string, T target, T replacement ) +void LLStringUtilBase::replaceChar( string_type& string, T target, T replacement ) { size_type found_pos = 0; - while( (found_pos = string.find(target, found_pos)) != std::basic_string::npos ) + while( (found_pos = string.find(target, found_pos)) != string_type::npos ) { string[found_pos] = replacement; found_pos++; // avoid infinite defeat if target == replacement @@ -947,10 +955,10 @@ void LLStringUtilBase::replaceChar( std::basic_string& string, T target, T //static template -void LLStringUtilBase::replaceString( std::basic_string& string, std::basic_string target, std::basic_string replacement ) +void LLStringUtilBase::replaceString( string_type& string, string_type target, string_type replacement ) { size_type found_pos = 0; - while( (found_pos = string.find(target, found_pos)) != std::basic_string::npos ) + while( (found_pos = string.find(target, found_pos)) != string_type::npos ) { string.replace( found_pos, target.length(), replacement ); found_pos += replacement.length(); // avoid infinite defeat if replacement contains target @@ -959,7 +967,7 @@ void LLStringUtilBase::replaceString( std::basic_string& string, std::basi //static template -void LLStringUtilBase::replaceNonstandardASCII( std::basic_string& string, T replacement ) +void LLStringUtilBase::replaceNonstandardASCII( string_type& string, T replacement ) { const char LF = 10; const S8 MIN = 32; @@ -979,12 +987,12 @@ void LLStringUtilBase::replaceNonstandardASCII( std::basic_string& string, //static template -void LLStringUtilBase::replaceTabsWithSpaces( std::basic_string& str, size_type spaces_per_tab ) +void LLStringUtilBase::replaceTabsWithSpaces( string_type& str, size_type spaces_per_tab ) { const T TAB = '\t'; const T SPACE = ' '; - std::basic_string out_str; + string_type out_str; // Replace tabs with spaces for (size_type i = 0; i < str.length(); i++) { @@ -1003,7 +1011,7 @@ void LLStringUtilBase::replaceTabsWithSpaces( std::basic_string& str, size //static template -BOOL LLStringUtilBase::containsNonprintable(const std::basic_string& string) +BOOL LLStringUtilBase::containsNonprintable(const string_type& string) { const char MIN = 32; BOOL rv = FALSE; @@ -1020,7 +1028,7 @@ BOOL LLStringUtilBase::containsNonprintable(const std::basic_string& strin //static template -void LLStringUtilBase::stripNonprintable(std::basic_string& string) +void LLStringUtilBase::stripNonprintable(string_type& string) { const char MIN = 32; size_type j = 0; @@ -1051,8 +1059,33 @@ void LLStringUtilBase::stripNonprintable(std::basic_string& string) delete []c_string; } +template +std::basic_string LLStringUtilBase::quote(const string_type& str, const string_type& escape) +{ + size_type len(str.length()); + // If the string is already quoted, assume user knows what s/he's doing. + if (len >= 2 && str[0] == '"' && str[len-1] == '"') + { + return str; + } + + // Not already quoted: do it. + string_type result; + result.push_back('"'); + for (typename string_type::const_iterator ci(str.begin()), cend(str.end()); ci != cend; ++ci) + { + if (*ci == '"') + { + result.append(escape); + } + result.push_back(*ci); + } + result.push_back('"'); + return result; +} + template -void LLStringUtilBase::_makeASCII(std::basic_string& string) +void LLStringUtilBase::_makeASCII(string_type& string) { // Replace non-ASCII chars with LL_UNKNOWN_CHAR for (size_type i = 0; i < string.length(); i++) @@ -1082,7 +1115,7 @@ void LLStringUtilBase::copy( T* dst, const T* src, size_type dst_size ) // static template -void LLStringUtilBase::copyInto(std::basic_string& dst, const std::basic_string& src, size_type offset) +void LLStringUtilBase::copyInto(string_type& dst, const string_type& src, size_type offset) { if ( offset == dst.length() ) { @@ -1092,7 +1125,7 @@ void LLStringUtilBase::copyInto(std::basic_string& dst, const std::basic_s } else { - std::basic_string tail = dst.substr(offset); + string_type tail = dst.substr(offset); dst = dst.substr(0, offset); dst += src; @@ -1103,7 +1136,7 @@ void LLStringUtilBase::copyInto(std::basic_string& dst, const std::basic_s // True if this is the head of s. //static template -BOOL LLStringUtilBase::isHead( const std::basic_string& string, const T* s ) +BOOL LLStringUtilBase::isHead( const string_type& string, const T* s ) { if( string.empty() ) { @@ -1119,8 +1152,8 @@ BOOL LLStringUtilBase::isHead( const std::basic_string& string, const T* s // static template bool LLStringUtilBase::startsWith( - const std::basic_string& string, - const std::basic_string& substr) + const string_type& string, + const string_type& substr) { if(string.empty() || (substr.empty())) return false; if(0 == string.find(substr)) return true; @@ -1130,8 +1163,8 @@ bool LLStringUtilBase::startsWith( // static template bool LLStringUtilBase::endsWith( - const std::basic_string& string, - const std::basic_string& substr) + const string_type& string, + const string_type& substr) { if(string.empty() || (substr.empty())) return false; std::string::size_type idx = string.rfind(substr); @@ -1141,14 +1174,14 @@ bool LLStringUtilBase::endsWith( template -BOOL LLStringUtilBase::convertToBOOL(const std::basic_string& string, BOOL& value) +BOOL LLStringUtilBase::convertToBOOL(const string_type& string, BOOL& value) { if( string.empty() ) { return FALSE; } - std::basic_string temp( string ); + string_type temp( string ); trim(temp); if( (temp == "1") || @@ -1178,7 +1211,7 @@ BOOL LLStringUtilBase::convertToBOOL(const std::basic_string& string, BOOL } template -BOOL LLStringUtilBase::convertToU8(const std::basic_string& string, U8& value) +BOOL LLStringUtilBase::convertToU8(const string_type& string, U8& value) { S32 value32 = 0; BOOL success = convertToS32(string, value32); @@ -1191,7 +1224,7 @@ BOOL LLStringUtilBase::convertToU8(const std::basic_string& string, U8& va } template -BOOL LLStringUtilBase::convertToS8(const std::basic_string& string, S8& value) +BOOL LLStringUtilBase::convertToS8(const string_type& string, S8& value) { S32 value32 = 0; BOOL success = convertToS32(string, value32); @@ -1204,7 +1237,7 @@ BOOL LLStringUtilBase::convertToS8(const std::basic_string& string, S8& va } template -BOOL LLStringUtilBase::convertToS16(const std::basic_string& string, S16& value) +BOOL LLStringUtilBase::convertToS16(const string_type& string, S16& value) { S32 value32 = 0; BOOL success = convertToS32(string, value32); @@ -1217,7 +1250,7 @@ BOOL LLStringUtilBase::convertToS16(const std::basic_string& string, S16& } template -BOOL LLStringUtilBase::convertToU16(const std::basic_string& string, U16& value) +BOOL LLStringUtilBase::convertToU16(const string_type& string, U16& value) { S32 value32 = 0; BOOL success = convertToS32(string, value32); @@ -1230,17 +1263,17 @@ BOOL LLStringUtilBase::convertToU16(const std::basic_string& string, U16& } template -BOOL LLStringUtilBase::convertToU32(const std::basic_string& string, U32& value) +BOOL LLStringUtilBase::convertToU32(const string_type& string, U32& value) { if( string.empty() ) { return FALSE; } - std::basic_string temp( string ); + string_type temp( string ); trim(temp); U32 v; - std::basic_istringstream i_stream((std::basic_string)temp); + std::basic_istringstream i_stream((string_type)temp); if(i_stream >> v) { value = v; @@ -1250,17 +1283,17 @@ BOOL LLStringUtilBase::convertToU32(const std::basic_string& string, U32& } template -BOOL LLStringUtilBase::convertToS32(const std::basic_string& string, S32& value) +BOOL LLStringUtilBase::convertToS32(const string_type& string, S32& value) { if( string.empty() ) { return FALSE; } - std::basic_string temp( string ); + string_type temp( string ); trim(temp); S32 v; - std::basic_istringstream i_stream((std::basic_string)temp); + std::basic_istringstream i_stream((string_type)temp); if(i_stream >> v) { //TODO: figure out overflow and underflow reporting here @@ -1277,7 +1310,7 @@ BOOL LLStringUtilBase::convertToS32(const std::basic_string& string, S32& } template -BOOL LLStringUtilBase::convertToF32(const std::basic_string& string, F32& value) +BOOL LLStringUtilBase::convertToF32(const string_type& string, F32& value) { F64 value64 = 0.0; BOOL success = convertToF64(string, value64); @@ -1290,17 +1323,17 @@ BOOL LLStringUtilBase::convertToF32(const std::basic_string& string, F32& } template -BOOL LLStringUtilBase::convertToF64(const std::basic_string& string, F64& value) +BOOL LLStringUtilBase::convertToF64(const string_type& string, F64& value) { if( string.empty() ) { return FALSE; } - std::basic_string temp( string ); + string_type temp( string ); trim(temp); F64 v; - std::basic_istringstream i_stream((std::basic_string)temp); + std::basic_istringstream i_stream((string_type)temp); if(i_stream >> v) { //TODO: figure out overflow and underflow reporting here @@ -1317,7 +1350,7 @@ BOOL LLStringUtilBase::convertToF64(const std::basic_string& string, F64& } template -void LLStringUtilBase::truncate(std::basic_string& string, size_type count) +void LLStringUtilBase::truncate(string_type& string, size_type count) { size_type cur_size = string.size(); string.resize(count < cur_size ? count : cur_size); -- cgit v1.2.3 From 199e875210435cbc914e80bf3eb6be6c985fce1c Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Mon, 23 Jan 2012 17:04:18 -0500 Subject: Use LLProcess::Params::args::empty() instead of comparing iterators. --- indra/newview/llexternaleditor.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) (limited to 'indra') diff --git a/indra/newview/llexternaleditor.cpp b/indra/newview/llexternaleditor.cpp index 561b87618c..db482f023e 100644 --- a/indra/newview/llexternaleditor.cpp +++ b/indra/newview/llexternaleditor.cpp @@ -81,10 +81,7 @@ LLExternalEditor::EErrorCode LLExternalEditor::setCommand(const std::string& env LLExternalEditor::EErrorCode LLExternalEditor::run(const std::string& file_path) { - // LLInitParams type wrappers don't seem to have empty() or size() - // methods; try determining emptiness by comparing begin/end iterators. - if (std::string(mProcessParams.executable).empty() || - (mProcessParams.args.begin() == mProcessParams.args.end())) + if (std::string(mProcessParams.executable).empty() || mProcessParams.args.empty()) { llwarns << "Editor command not set" << llendl; return EC_NOT_SPECIFIED; -- cgit v1.2.3 From da5d243c8f76f43a6bb4000402fade76eee0be33 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Mon, 23 Jan 2012 17:29:42 -0500 Subject: LLStringUtil methods are conventionally static. --- indra/llcommon/llstring.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/llcommon/llstring.h b/indra/llcommon/llstring.h index d3f1d01aa2..4c3936f9ab 100644 --- a/indra/llcommon/llstring.h +++ b/indra/llcommon/llstring.h @@ -307,7 +307,7 @@ public: * quote it, escape any embedded double-quote with the escape string (default * backslash). */ - string_type quote(const string_type& str, const string_type& escape="\\"); + static string_type quote(const string_type& str, const string_type& escape="\\"); /** * @brief Unsafe way to make ascii characters. You should probably -- cgit v1.2.3 From 61e98256df80822f9504a2037d5cbb029c39506d Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Mon, 23 Jan 2012 17:38:06 -0500 Subject: Clarify that items in LLProcess::Params::args are implicitly quoted. That is, we try to pass through each args entry as a separate child-process arvg[] entry, whitespace and all. --- indra/llcommon/llprocess.h | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/llcommon/llprocess.h b/indra/llcommon/llprocess.h index 019c33592c..51c42582ea 100644 --- a/indra/llcommon/llprocess.h +++ b/indra/llcommon/llprocess.h @@ -63,7 +63,16 @@ public: /// pathname of executable Mandatory executable; - /// zero or more additional command-line arguments + /** + * zero or more additional command-line arguments. Arguments are + * passed through as exactly as we can manage, whitespace and all. + * @note On Windows we manage this by implicitly double-quoting each + * argument while assembling the command line. BUT if a given argument + * is already double-quoted, we don't double-quote it again. Try to + * avoid making use of this, though, as on Mac and Linux explicitly + * double-quoted args will be passed to the child process including + * the double quotes. + */ Multiple args; /// current working directory, if need it changed Optional cwd; -- cgit v1.2.3 From 8758c7b8415a1cb67c504f142f96b5a7fec296d2 Mon Sep 17 00:00:00 2001 From: Oz Linden Date: Wed, 25 Jan 2012 11:34:22 -0500 Subject: storm-1738: mock autocorrect to allow building the llui_libtest integration test --- indra/integration_tests/llui_libtest/llui_libtest.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'indra') diff --git a/indra/integration_tests/llui_libtest/llui_libtest.cpp b/indra/integration_tests/llui_libtest/llui_libtest.cpp index 217e26c3ca..af0cb7c301 100644 --- a/indra/integration_tests/llui_libtest/llui_libtest.cpp +++ b/indra/integration_tests/llui_libtest/llui_libtest.cpp @@ -31,6 +31,7 @@ #include "llwidgetreg.h" // linden library includes +#include "llautocorrect.h" #include "llcontrol.h" // LLControlGroup #include "lldir.h" #include "lldiriterator.h" @@ -107,6 +108,16 @@ public: }; TestImageProvider gTestImageProvider; +// Mock Autocorrect +AutoCorrect* AutoCorrect::getInstance() +{ + return NULL; +} +std::string AutoCorrect::replaceWord(std::string currentWord) +{ + return currentWord; +} + static std::string get_xui_dir() { std::string delim = gDirUtilp->getDirDelimiter(); -- cgit v1.2.3 From 27df0a84564d3a886661aae0faae74c2157cd31b Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Fri, 27 Jan 2012 23:46:00 -0500 Subject: On Windows, only quote LLProcess arguments if they seem to need it. On Posix platforms, the OS argument mechanism makes quoting/reparsing unnecessary anyway, so this only affects Windows. Add optional 'triggers' parameter to LLStringUtils::quote() (default: space and double-quote). Only if the passed string contains a character in 'triggers' will it be double-quoted. This is observed to fix a Windows-specific problem in which plugin child process would fail to start because it wasn't expecting a quoted number. Use LLStringUtils::quote() more consistently in LLProcess implementation for logging. --- indra/llcommon/llprocess.cpp | 14 +++++++------- indra/llcommon/llstring.h | 26 +++++++++++++++++++++----- 2 files changed, 28 insertions(+), 12 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/llprocess.cpp b/indra/llcommon/llprocess.cpp index 2c7512419d..2b7a534fb3 100644 --- a/indra/llcommon/llprocess.cpp +++ b/indra/llcommon/llprocess.cpp @@ -87,12 +87,12 @@ std::ostream& operator<<(std::ostream& out, const LLProcess::Params& params) std::string cwd(params.cwd); if (! cwd.empty()) { - out << "cd '" << cwd << "': "; + out << "cd " << LLStringUtil::quote(cwd) << ": "; } - out << '"' << std::string(params.executable) << '"'; + out << LLStringUtil::quote(params.executable); BOOST_FOREACH(const std::string& arg, params.args) { - out << " \"" << arg << '"'; + out << ' ' << LLStringUtil::quote(arg); } return out; } @@ -132,8 +132,8 @@ public: if (! AssignProcessToJobObject(mJob, hProcess)) { - LL_WARNS("LLProcess") << WindowsErrorString(STRINGIZE("AssignProcessToJobObject(\"" - << prog << "\")")) << LL_ENDL; + LL_WARNS("LLProcess") << WindowsErrorString(STRINGIZE("AssignProcessToJobObject(" + << prog << ")")) << LL_ENDL; } } @@ -206,7 +206,7 @@ void LLProcess::launch(const LLSDParamAdapter& params) mProcessID = pinfo.hProcess; CloseHandle(pinfo.hThread); // stops leaks - nothing else - mDesc = STRINGIZE('"' << std::string(params.executable) << "\" (" << pinfo.dwProcessId << ')'); + mDesc = STRINGIZE(LLStringUtil::quote(params.executable) << " (" << pinfo.dwProcessId << ')'); LL_INFOS("LLProcess") << "Launched " << params << " (" << pinfo.dwProcessId << ")" << LL_ENDL; // Now associate the new child process with our Job Object -- unless @@ -356,7 +356,7 @@ void LLProcess::launch(const LLSDParamAdapter& params) // parent process mProcessID = child; - mDesc = STRINGIZE('"' << std::string(params.executable) << "\" (" << mProcessID << ')'); + mDesc = STRINGIZE(LLStringUtil::quote(params.executable) << " (" << mProcessID << ')'); LL_INFOS("LLProcess") << "Launched " << params << " (" << mProcessID << ")" << LL_ENDL; } diff --git a/indra/llcommon/llstring.h b/indra/llcommon/llstring.h index 4c3936f9ab..7b24b5e279 100644 --- a/indra/llcommon/llstring.h +++ b/indra/llcommon/llstring.h @@ -303,11 +303,17 @@ public: static void stripNonprintable(string_type& string); /** - * Double-quote an argument string, unless it's already double-quoted. If we - * quote it, escape any embedded double-quote with the escape string (default + * Double-quote an argument string if needed, unless it's already + * double-quoted. Decide whether it's needed based on the presence of any + * character in @a triggers (default space or double-quote). If we quote + * it, escape any embedded double-quote with the @a escape string (default * backslash). + * + * Passing triggers="" means always quote, unless it's already double-quoted. */ - static string_type quote(const string_type& str, const string_type& escape="\\"); + static string_type quote(const string_type& str, + const string_type& triggers=" \"", + const string_type& escape="\\"); /** * @brief Unsafe way to make ascii characters. You should probably @@ -1060,7 +1066,9 @@ void LLStringUtilBase::stripNonprintable(string_type& string) } template -std::basic_string LLStringUtilBase::quote(const string_type& str, const string_type& escape) +std::basic_string LLStringUtilBase::quote(const string_type& str, + const string_type& triggers, + const string_type& escape) { size_type len(str.length()); // If the string is already quoted, assume user knows what s/he's doing. @@ -1069,7 +1077,15 @@ std::basic_string LLStringUtilBase::quote(const string_type& str, const st return str; } - // Not already quoted: do it. + // Not already quoted: do we need to? triggers.empty() is a special case + // meaning "always quote." + if ((! triggers.empty()) && str.find_first_of(triggers) == string_type::npos) + { + // no trigger characters, don't bother quoting + return str; + } + + // For whatever reason, we must quote this string. string_type result; result.push_back('"'); for (typename string_type::const_iterator ci(str.begin()), cend(str.end()); ci != cend; ++ci) -- cgit v1.2.3 From 803acbc5efde19c0acacfc7fe4990841dbf31a3e Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Mon, 30 Jan 2012 10:14:10 -0500 Subject: Trim trailing "\r\n" from Windows FormatMessage() string for logging. --- indra/llcommon/llprocess.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/llcommon/llprocess.cpp b/indra/llcommon/llprocess.cpp index 2b7a534fb3..8c0e8fe65e 100644 --- a/indra/llcommon/llprocess.cpp +++ b/indra/llcommon/llprocess.cpp @@ -261,11 +261,15 @@ static std::string WindowsErrorString(const std::string& operation) NULL) != 0) { + // convert from wide-char string to multi-byte string char message[256]; wcstombs(message, error_str, sizeof(message)); message[sizeof(message)-1] = 0; LocalFree(error_str); - return STRINGIZE(operation << " failed (" << result << "): " << message); + // convert to std::string to trim trailing whitespace + std::string mbsstr(message); + mbsstr.erase(mbsstr.find_last_not_of(" \t\r\n")); + return STRINGIZE(operation << " failed (" << result << "): " << mbsstr); } return STRINGIZE(operation << " failed (" << result << "), but FormatMessage() did not explain"); -- cgit v1.2.3 From 85581eefa63d8f8e8c5132c4cd7e137f6cb88869 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Mon, 30 Jan 2012 12:11:44 -0500 Subject: Expose 'handle' as well as 'id' on LLProcess objects. On Posix, these and the corresponding getProcessID()/getProcessHandle() accessors produce the same pid_t value; but on Windows, it's useful to distinguish an int-like 'id' useful to human log readers versus an opaque 'handle' for passing to platform-specific API functions. So make the distinction in a platform-independent way. --- indra/llcommon/llprocess.cpp | 50 ++++++++++++++++++++------------- indra/llcommon/llprocess.h | 42 +++++++++++++++++---------- indra/llcommon/tests/llprocess_test.cpp | 16 +++++------ 3 files changed, 66 insertions(+), 42 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/llprocess.cpp b/indra/llcommon/llprocess.cpp index 8c0e8fe65e..a7bafb8cb0 100644 --- a/indra/llcommon/llprocess.cpp +++ b/indra/llcommon/llprocess.cpp @@ -42,7 +42,7 @@ struct LLProcessError: public std::runtime_error LLProcessError(const std::string& msg): std::runtime_error(msg) {} }; -LLProcessPtr LLProcess::create(const LLSDParamAdapter& params) +LLProcessPtr LLProcess::create(const LLSDOrParams& params) { try { @@ -55,8 +55,9 @@ LLProcessPtr LLProcess::create(const LLSDParamAdapter& params) } } -LLProcess::LLProcess(const LLSDParamAdapter& params): +LLProcess::LLProcess(const LLSDOrParams& params): mProcessID(0), + mProcessHandle(0), mAutokill(params.autokill) { if (! params.validateBlock(true)) @@ -78,8 +79,18 @@ LLProcess::~LLProcess() bool LLProcess::isRunning(void) { - mProcessID = isRunning(mProcessID, mDesc); - return (mProcessID != 0); + mProcessHandle = isRunning(mProcessHandle, mDesc); + return (mProcessHandle != 0); +} + +LLProcess::id LLProcess::getProcessID() const +{ + return mProcessID; +} + +LLProcess::handle LLProcess::getProcessHandle() const +{ + return mProcessHandle; } std::ostream& operator<<(std::ostream& out, const LLProcess::Params& params) @@ -122,7 +133,7 @@ static std::string WindowsErrorString(const std::string& operation); class LLJob: public LLSingleton { public: - void assignProcess(const std::string& prog, HANDLE hProcess) + void assignProcess(const std::string& prog, handle hProcess) { // If we never managed to initialize this Job Object, can't use it -- // but don't keep spamming the log, we already emitted warnings when @@ -164,10 +175,10 @@ private: } } - HANDLE mJob; + handle mJob; }; -void LLProcess::launch(const LLSDParamAdapter& params) +void LLProcess::launch(const LLSDOrParams& params) { PROCESS_INFORMATION pinfo; STARTUPINFOA sinfo = { sizeof(sinfo) }; @@ -201,28 +212,28 @@ void LLProcess::launch(const LLSDParamAdapter& params) throw LLProcessError(WindowsErrorString("CreateProcessA")); } - // foo = pinfo.dwProcessId; // get your pid here if you want to use it later on // CloseHandle(pinfo.hProcess); // stops leaks - nothing else - mProcessID = pinfo.hProcess; + mProcessID = pinfo.dwProcessId; + mProcessHandle = pinfo.hProcess; CloseHandle(pinfo.hThread); // stops leaks - nothing else - mDesc = STRINGIZE(LLStringUtil::quote(params.executable) << " (" << pinfo.dwProcessId << ')'); - LL_INFOS("LLProcess") << "Launched " << params << " (" << pinfo.dwProcessId << ")" << LL_ENDL; + mDesc = STRINGIZE(LLStringUtil::quote(params.executable) << " (" << mProcessID << ')'); + LL_INFOS("LLProcess") << "Launched " << params << " (" << mProcessID << ")" << LL_ENDL; // Now associate the new child process with our Job Object -- unless // autokill is false, i.e. caller asserts the child should persist. if (params.autokill) { - LLJob::instance().assignProcess(mDesc, mProcessID); + LLJob::instance().assignProcess(mDesc, mProcessHandle); } } -LLProcess::id LLProcess::isRunning(id handle, const std::string& desc) +LLProcess::handle LLProcess::isRunning(handle h, const std::string& desc) { - if (! handle) + if (! h) return 0; - DWORD waitresult = WaitForSingleObject(handle, 0); + DWORD waitresult = WaitForSingleObject(h, 0); if(waitresult == WAIT_OBJECT_0) { // the process has completed. @@ -233,16 +244,16 @@ LLProcess::id LLProcess::isRunning(id handle, const std::string& desc) return 0; } - return handle; + return h; } bool LLProcess::kill(void) { - if (! mProcessID) + if (! mProcessHandle) return false; LL_INFOS("LLProcess") << "killing " << mDesc << LL_ENDL; - TerminateProcess(mProcessID, 0); + TerminateProcess(mProcessHandle, 0); return ! isRunning(); } @@ -302,7 +313,7 @@ static bool reap_pid(pid_t pid) return false; } -void LLProcess::launch(const LLSDParamAdapter& params) +void LLProcess::launch(const LLSDOrParams& params) { // flush all buffers before the child inherits them ::fflush(NULL); @@ -359,6 +370,7 @@ void LLProcess::launch(const LLSDParamAdapter& params) // parent process mProcessID = child; + mProcessHandle = child; mDesc = STRINGIZE(LLStringUtil::quote(params.executable) << " (" << mProcessID << ')'); LL_INFOS("LLProcess") << "Launched " << params << " (" << mProcessID << ")" << LL_ENDL; diff --git a/indra/llcommon/llprocess.h b/indra/llcommon/llprocess.h index 51c42582ea..8a842589ec 100644 --- a/indra/llcommon/llprocess.h +++ b/indra/llcommon/llprocess.h @@ -35,7 +35,7 @@ #if LL_WINDOWS #define WIN32_LEAN_AND_MEAN -#include +#include // HANDLE (eye roll) #endif class LLProcess; @@ -79,6 +79,7 @@ public: /// implicitly kill process on destruction of LLProcess object Optional autokill; }; + typedef LLSDParamAdapter LLSDOrParams; /** * Factory accepting either plain LLSD::Map or Params block. @@ -91,7 +92,7 @@ public: * cwd (optional, string, dft no chdir): change to this directory before executing * autokill (optional, bool, dft true): implicit kill() on ~LLProcess */ - static LLProcessPtr create(const LLSDParamAdapter& params); + static LLProcessPtr create(const LLSDOrParams& params); virtual ~LLProcess(); // isRunning isn't const because, if child isn't running, it clears stored @@ -103,35 +104,46 @@ public: bool kill(void); #if LL_WINDOWS - typedef HANDLE id; + typedef int id; ///< as returned by getProcessID() + typedef HANDLE handle; ///< as returned by getProcessHandle() #else - typedef pid_t id; + typedef pid_t id; + typedef pid_t handle; #endif - /// Get platform-specific process ID - id getProcessID() const { return mProcessID; }; + /** + * Get an int-like id value. This is primarily intended for a human reader + * to differentiate processes. + */ + id getProcessID() const; + /** + * Get a "handle" of a kind that you might pass to platform-specific API + * functions to engage features not directly supported by LLProcess. + */ + handle getProcessHandle() const; /** - * Test if a process (id obtained from getProcessID()) is still - * running. Return is same nonzero id value if still running, else + * Test if a process (@c handle obtained from getProcessHandle()) is still + * running. Return same nonzero @c handle value if still running, else * zero, so you can test it like a bool. But if you want to update a * stored variable as a side effect, you can write code like this: * @code - * childpid = LLProcess::isRunning(childpid); + * hchild = LLProcess::isRunning(hchild); * @endcode * @note This method is intended as a unit-test hook, not as the first of - * a whole set of operations supported on freestanding @c id values. New - * functionality should be added as nonstatic members operating on - * mProcessID. + * a whole set of operations supported on freestanding @c handle values. + * New functionality should be added as nonstatic members operating on + * the same data as getProcessHandle(). */ - static id isRunning(id, const std::string& desc=""); + static handle isRunning(handle, const std::string& desc=""); private: /// constructor is private: use create() instead - LLProcess(const LLSDParamAdapter& params); - void launch(const LLSDParamAdapter& params); + LLProcess(const LLSDOrParams& params); + void launch(const LLSDOrParams& params); std::string mDesc; id mProcessID; + handle mProcessHandle; bool mAutokill; }; diff --git a/indra/llcommon/tests/llprocess_test.cpp b/indra/llcommon/tests/llprocess_test.cpp index 405540e436..4ad45bdf27 100644 --- a/indra/llcommon/tests/llprocess_test.cpp +++ b/indra/llcommon/tests/llprocess_test.cpp @@ -599,7 +599,7 @@ namespace tut { set_test_name("implicit kill()"); NamedTempFile out("out", "not started"); - LLProcess::id pid(0); + LLProcess::handle phandle(0); { PythonProcessLauncher py("kill()", "from __future__ import with_statement\n" @@ -614,8 +614,8 @@ namespace tut py.mParams.args.add(out.getName()); py.mPy = LLProcess::create(py.mParams); ensure("couldn't launch kill() script", py.mPy); - // Capture id for later - pid = py.mPy->getProcessID(); + // Capture handle for later + phandle = py.mPy->getProcessHandle(); // Wait for the script to wake up and do its first write int i = 0, timeout = 60; for ( ; i < timeout; ++i) @@ -630,7 +630,7 @@ namespace tut // Destroy the LLProcess, which should kill the child. } // wait for the script to terminate... one way or another. - while (LLProcess::isRunning(pid)) + while (LLProcess::isRunning(phandle)) { sleep(1); } @@ -646,7 +646,7 @@ namespace tut set_test_name("autokill"); NamedTempFile from("from", "not started"); NamedTempFile to("to", ""); - LLProcess::id pid(0); + LLProcess::handle phandle(0); { PythonProcessLauncher py("autokill", "from __future__ import with_statement\n" @@ -672,8 +672,8 @@ namespace tut py.mParams.autokill = false; py.mPy = LLProcess::create(py.mParams); ensure("couldn't launch kill() script", py.mPy); - // Capture id for later - pid = py.mPy->getProcessID(); + // Capture handle for later + phandle = py.mPy->getProcessHandle(); // Wait for the script to wake up and do its first write int i = 0, timeout = 60; for ( ; i < timeout; ++i) @@ -695,7 +695,7 @@ namespace tut outf << "go"; } // flush and close. // now wait for the script to terminate... one way or another. - while (LLProcess::isRunning(pid)) + while (LLProcess::isRunning(phandle)) { sleep(1); } -- cgit v1.2.3 From 60a777d2e3f9bec7a20e5de2df7cb3ecd2455b98 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Mon, 30 Jan 2012 12:32:05 -0500 Subject: LLProcess::handle must be qualified when used in LLJob class. --- indra/llcommon/llprocess.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/llprocess.cpp b/indra/llcommon/llprocess.cpp index a7bafb8cb0..1e27f8ce1d 100644 --- a/indra/llcommon/llprocess.cpp +++ b/indra/llcommon/llprocess.cpp @@ -133,7 +133,7 @@ static std::string WindowsErrorString(const std::string& operation); class LLJob: public LLSingleton { public: - void assignProcess(const std::string& prog, handle hProcess) + void assignProcess(const std::string& prog, LLProcess::handle hProcess) { // If we never managed to initialize this Job Object, can't use it -- // but don't keep spamming the log, we already emitted warnings when @@ -175,7 +175,7 @@ private: } } - handle mJob; + LLProcess::handle mJob; }; void LLProcess::launch(const LLSDOrParams& params) -- cgit v1.2.3 From 491cd825561be1cf4a6f428a535811cbe0e3f179 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Mon, 30 Jan 2012 17:47:57 -0500 Subject: Set bit flag on CreateProcess() to allow AssignProcessToJobObject(). Windows 7 and friends tend to create a process already implicitly allocated to a job object, and a process can only belong to a single job object. Passing CREATE_BREAKAWAY_FROM_JOB in CreateProcessA()'s dwCreationFlags seems to bypass the access-denied error observed with AssignProcessToJobObject() otherwise. This change should (!) enable OS lifespan management for SLVoice.exe et al. --- indra/llcommon/llprocess.cpp | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/llprocess.cpp b/indra/llcommon/llprocess.cpp index 1e27f8ce1d..8611d67f25 100644 --- a/indra/llcommon/llprocess.cpp +++ b/indra/llcommon/llprocess.cpp @@ -207,7 +207,26 @@ void LLProcess::launch(const LLSDOrParams& params) const char * working_directory = 0; if (! cwd.empty()) working_directory = cwd.c_str(); - if( ! CreateProcessA( NULL, &args2[0], NULL, NULL, FALSE, 0, NULL, working_directory, &sinfo, &pinfo ) ) + + // It's important to pass CREATE_BREAKAWAY_FROM_JOB because Windows 7 et + // al. tend to implicitly launch new processes already bound to a job. From + // http://msdn.microsoft.com/en-us/library/windows/desktop/ms681949%28v=vs.85%29.aspx : + // "The process must not already be assigned to a job; if it is, the + // function fails with ERROR_ACCESS_DENIED." ... + // "If the process is being monitored by the Program Compatibility + // Assistant (PCA), it is placed into a compatibility job. Therefore, the + // process must be created using CREATE_BREAKAWAY_FROM_JOB before it can + // be placed in another job." + if( ! CreateProcessA(NULL, // lpApplicationName + &args2[0], // lpCommandLine + NULL, // lpProcessAttributes + NULL, // lpThreadAttributes + FALSE, // bInheritHandles + CREATE_BREAKAWAY_FROM_JOB, // dwCreationFlags + NULL, // lpEnvironment + working_directory, // lpCurrentDirectory + &sinfo, // lpStartupInfo + &pinfo ) ) // lpProcessInformation { throw LLProcessError(WindowsErrorString("CreateProcessA")); } @@ -225,7 +244,7 @@ void LLProcess::launch(const LLSDOrParams& params) if (params.autokill) { LLJob::instance().assignProcess(mDesc, mProcessHandle); - } +} } LLProcess::handle LLProcess::isRunning(handle h, const std::string& desc) @@ -287,7 +306,7 @@ static std::string WindowsErrorString(const std::string& operation) } /***************************************************************************** -* Non-Windows specific +* Posix specific *****************************************************************************/ #else // Mac and linux @@ -444,4 +463,4 @@ void LLProcess::reap(void) } |*==========================================================================*/ -#endif +#endif // Posix -- cgit v1.2.3 From 59dfcba33de76bfc998b9aa2121c53dff75024f7 Mon Sep 17 00:00:00 2001 From: Jonathan Yap Date: Wed, 1 Feb 2012 10:28:45 -0500 Subject: STORM-1738 Slight adjustment to callback --- indra/llui/lllineeditor.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'indra') diff --git a/indra/llui/lllineeditor.cpp b/indra/llui/lllineeditor.cpp index ba50728e89..de951d3b56 100644 --- a/indra/llui/lllineeditor.cpp +++ b/indra/llui/lllineeditor.cpp @@ -151,7 +151,8 @@ LLLineEditor::LLLineEditor(const LLLineEditor::Params& p) mHighlightColor(p.highlight_color()), mPreeditBgColor(p.preedit_bg_color()), mGLFont(p.font), - mContextMenuHandle() + mContextMenuHandle(), + mAutocorrectCallback() { llassert( mMaxLengthBytes > 0 ); @@ -866,10 +867,10 @@ void LLLineEditor::addChar(const llwchar uni_char) } // *TODO implement callback routine - if (!mReadOnly /*&& autocorrectCallbackRoutine != NULL */) + if (!mReadOnly && mAutocorrectCallback != NULL) { // call callback - // autotocorrectCallbackRoutine(mText&, mCursorPos&); + // mAutotocorrectCallback(mText&, mCursorPos&); } getWindow()->hideCursorUntilMouseMove(); -- cgit v1.2.3 From 19ad674b107f121c02b3a353517b535ce170feb4 Mon Sep 17 00:00:00 2001 From: Jonathan Yap Date: Wed, 1 Feb 2012 11:23:59 -0500 Subject: STORM-1738 Make autocorrect into a proper singleton warn-on-failure:open-license --- indra/newview/llautocorrect.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/newview/llautocorrect.h b/indra/newview/llautocorrect.h index a5e8c5396e..82cf75f3cf 100644 --- a/indra/newview/llautocorrect.h +++ b/indra/newview/llautocorrect.h @@ -22,7 +22,7 @@ #include "lllineeditor.h" -class AutoCorrect +class AutoCorrect : public LLSingleton { AutoCorrect(); ~AutoCorrect(); @@ -50,6 +50,7 @@ public: void loadFromDisk(); private: + friend class LLSingleton; void saveToDisk(LLSD newSettings); LLSD getExampleLLSD(); std::string getFileName(); -- cgit v1.2.3 From d3a7a7ad4bd3d2c921f6e829aa283fece0a9da6a Mon Sep 17 00:00:00 2001 From: Jonathan Yap Date: Thu, 2 Feb 2012 11:00:11 -0500 Subject: STORM-1738 Settings cleanup warn-on-failure:open-license --- indra/newview/app_settings/settings.xml | 33 ++++++++-------------- indra/newview/llautocorrect.cpp | 13 ++++----- indra/newview/llautocorrectfloater.cpp | 13 ++------- .../skins/default/xui/en/floater_autocorrect.xml | 4 --- 4 files changed, 20 insertions(+), 43 deletions(-) (limited to 'indra') diff --git a/indra/newview/app_settings/settings.xml b/indra/newview/app_settings/settings.xml index 060ec8bd5a..16fa3a1cb2 100644 --- a/indra/newview/app_settings/settings.xml +++ b/indra/newview/app_settings/settings.xml @@ -346,17 +346,17 @@ Value 0 - AutoCorrectCount - - Comment - How many words have been auto replaced. - Persist - 1 - Type - S32 - Value - 0 - + AutoCorrect + + Comment + Replaces common spelling mistakes with correct word + Persist + 1 + Type + Boolean + Value + 0 + AutoAcceptNewInventory Comment @@ -2808,17 +2808,6 @@ Value 1 - EnableAutoCorrect - - Comment - Enables or disables the autocorrect function - Persist - 1 - Type - Boolean - Value - 0 - EnableGroupChatPopups Comment diff --git a/indra/newview/llautocorrect.cpp b/indra/newview/llautocorrect.cpp index d1aa2384b7..cca5c6913f 100644 --- a/indra/newview/llautocorrect.cpp +++ b/indra/newview/llautocorrect.cpp @@ -41,8 +41,8 @@ AutoCorrect::~AutoCorrect() void AutoCorrect::autocorrectCallback(LLUIString& inputText, S32& cursorPos) { - static LLCachedControl doAnything(gSavedSettings, "EnableAutoCorrect"); - if(doAnything) + static LLCachedControl perform_autocorrect(gSavedSettings, "AutoCorrect"); + if(perform_autocorrect) { S32 wordStart = 0; S32 wordEnd = cursorPos-1; @@ -290,8 +290,8 @@ LLSD AutoCorrect::getAutoCorrectEntries(std::string listName) } std::string AutoCorrect::replaceWord(std::string currentWord) { - static LLCachedControl doAnything(gSavedSettings, "EnableAutoCorrect"); - if(!(doAnything))return currentWord; + static LLCachedControl perform_autocorrect(gSavedSettings, "AutoCorrect"); + if(!(perform_autocorrect))return currentWord; //loop through priorities for(int currentPriority = 10;currentPriority>=0;currentPriority--) { @@ -337,7 +337,6 @@ std::string AutoCorrect::replaceWord(std::string currentWord) args["REPLACEMENT"]=replacement; LLNotificationsUtil::add("AutoReplace",args); } - gSavedSettings.setS32("AutoCorrectCount",gSavedSettings.getS32("AutoCorrectCount")+1); llinfos << "found a word in list " << location.c_str() << " and it will replace " << currentWord.c_str() << " => " << replacement.c_str() << llendl; return replacement; } @@ -348,8 +347,8 @@ std::string AutoCorrect::replaceWord(std::string currentWord) } std::string AutoCorrect::replaceWords(std::string words) { - static LLCachedControl doAnything(gSavedSettings, "EnableAutoCorrect"); - if(!(doAnything))return words; + static LLCachedControl perform_autocorrect(gSavedSettings, "AutoCorrect"); + if(!(perform_autocorrect))return words; //TODO update this function to use the "wordStyle" thing, //but so far this function is never used, so later diff --git a/indra/newview/llautocorrectfloater.cpp b/indra/newview/llautocorrectfloater.cpp index 6dca759b02..74762a876f 100644 --- a/indra/newview/llautocorrectfloater.cpp +++ b/indra/newview/llautocorrectfloater.cpp @@ -130,8 +130,6 @@ void AutoCorrectFloater::updateItemsList() childSetValue("ac_text_name",listName); childSetValue("ac_text_author",listData["author"]); childSetValue("ac_priority",listData["priority"]); - static LLCachedControl countAuto(gSavedSettings, "AutoCorrectCount"); - childSetValue("ac_stats",(S32)countAuto); LLSD autoCorrects = listData["data"]; LLSD::map_const_iterator loc_it = autoCorrects.beginMap(); @@ -161,14 +159,11 @@ void AutoCorrectFloater::updateItemsList() void AutoCorrectFloater::updateNamesList() { namesList->deleteAllItems(); - static LLCachedControl enabledd(gSavedSettings, "EnableAutoCorrect"); - if(!(enabledd)) + if(!gSavedSettings, "AutoCorrect") { updateItemsList(); return; } - static LLCachedControl countAuto(gSavedSettings, "AutoCorrectCount"); - childSetValue("ac_stats",(S32)countAuto); LLSD autoCorrects = AutoCorrect::getInstance()->getAutoCorrects(); LLSD::map_const_iterator loc_it = autoCorrects.beginMap(); LLSD::map_const_iterator loc_end = autoCorrects.endMap(); @@ -213,8 +208,7 @@ void AutoCorrectFloater::updateListControlsEnabled(BOOL selected) } void AutoCorrectFloater::updateEnabledStuff() { - static LLCachedControl enabledd(gSavedSettings, "EnableAutoCorrect"); - if(!(enabledd)) + if(!gSavedSettings, "AutoCorrect") { LLCheckBoxCtrl *enBox = getChild("ac_enable"); enBox->setDisabledColor(LLColor4::red); @@ -234,7 +228,6 @@ void AutoCorrectFloater::updateEnabledStuff() } void AutoCorrectFloater::setData(void * data) { - //empanel = (LLPanel*)data; } void AutoCorrectFloater::onBoxCommitEnabled(LLUICtrl* caller, void* user_data) { @@ -301,7 +294,7 @@ void AutoCorrectFloater::loadList(void* data) LLSDSerialize::fromXMLDocument(blankllsd, file); } file.close(); - gSavedSettings.setBOOL("EnableAutoCorrect",true); + gSavedSettings.setBOOL("AutoCorrect",true); AutoCorrect::getInstance()->addCorrectionList(blankllsd); if ( data ) { diff --git a/indra/newview/skins/default/xui/en/floater_autocorrect.xml b/indra/newview/skins/default/xui/en/floater_autocorrect.xml index 0b8ed1c067..b67b2e7ec0 100644 --- a/indra/newview/skins/default/xui/en/floater_autocorrect.xml +++ b/indra/newview/skins/default/xui/en/floater_autocorrect.xml @@ -75,9 +75,5 @@ >Words automatically corrected: - Count - \ No newline at end of file -- cgit v1.2.3 From 6443701a3fc41eff2c48f6e57a79010cdb8339e2 Mon Sep 17 00:00:00 2001 From: Jonathan Yap Date: Thu, 2 Feb 2012 12:59:41 -0500 Subject: STORM-1738 Change a few llwarns to lldebugs warn-on-failure:open-license --- indra/newview/llautocorrect.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'indra') diff --git a/indra/newview/llautocorrect.cpp b/indra/newview/llautocorrect.cpp index cca5c6913f..c16787d637 100644 --- a/indra/newview/llautocorrect.cpp +++ b/indra/newview/llautocorrect.cpp @@ -337,7 +337,7 @@ std::string AutoCorrect::replaceWord(std::string currentWord) args["REPLACEMENT"]=replacement; LLNotificationsUtil::add("AutoReplace",args); } - llinfos << "found a word in list " << location.c_str() << " and it will replace " << currentWord.c_str() << " => " << replacement.c_str() << llendl; + lldebugs << "found a word in list " << location.c_str() << " and it will replace " << currentWord.c_str() << " => " << replacement.c_str() << llendl; return replacement; } } @@ -361,7 +361,6 @@ std::string AutoCorrect::replaceWords(std::string words) for (; loc_it != loc_end; ++loc_it) { const std::string& location = (*loc_it).first; - //llinfos << "location is "< " << replacement.c_str() << llendl; + ldebugs << "found a word in list " << location.c_str() << " and it will replace " << currentWord.c_str() << " => " << replacement.c_str() << llendl; int wordStart = words.find(currentWord); words.replace(wordStart,currentWord.length(),replacement); return replaceWords(words);//lol recursion! -- cgit v1.2.3 From a9d11219779473c7d0c06bd0e56b0f068a487ad0 Mon Sep 17 00:00:00 2001 From: Kitty Barnett Date: Fri, 3 Feb 2012 15:20:34 +0100 Subject: STORM-276 Added spellcheck functionality to the LLTextEditor control --- indra/llui/lltextbase.cpp | 209 +++++++++++++++++++++++++++++++++++++++++++- indra/llui/lltextbase.h | 31 ++++++- indra/llui/lltexteditor.cpp | 34 ++++++- 3 files changed, 271 insertions(+), 3 deletions(-) (limited to 'indra') diff --git a/indra/llui/lltextbase.cpp b/indra/llui/lltextbase.cpp index 0040be45c7..7eee1d39c4 100644 --- a/indra/llui/lltextbase.cpp +++ b/indra/llui/lltextbase.cpp @@ -32,6 +32,7 @@ #include "lllocalcliprect.h" #include "llmenugl.h" #include "llscrollcontainer.h" +#include "llspellcheck.h" #include "llstl.h" #include "lltextparser.h" #include "lltextutil.h" @@ -155,6 +156,7 @@ LLTextBase::Params::Params() plain_text("plain_text",false), track_end("track_end", false), read_only("read_only", false), + spellcheck("spellcheck", false), v_pad("v_pad", 0), h_pad("h_pad", 0), clip("clip", true), @@ -181,6 +183,9 @@ LLTextBase::LLTextBase(const LLTextBase::Params &p) mFontShadow(p.font_shadow), mPopupMenu(NULL), mReadOnly(p.read_only), + mSpellCheck(p.spellcheck), + mSpellCheckStart(-1), + mSpellCheckEnd(-1), mCursorColor(p.cursor_color), mFgColor(p.text_color), mBorderVisible( p.border_visible ), @@ -246,6 +251,12 @@ LLTextBase::LLTextBase(const LLTextBase::Params &p) addChild(mDocumentView); } + if (mSpellCheck) + { + LLSpellChecker::setSettingsChangeCallback(boost::bind(&LLTextBase::onSpellCheckSettingsChange, this)); + } + mSpellCheckTimer.reset(); + createDefaultSegment(); updateRects(); @@ -530,8 +541,86 @@ void LLTextBase::drawText() return; } + // Perform spell check if needed + if ( (getSpellCheck()) && (getWText().length() > 2) ) + { + // Calculate start and end indices for the spell checking range + S32 start = line_start, end = getLineEnd(last_line); + + if ( (mSpellCheckStart != start) || (mSpellCheckEnd != end) ) + { + const LLWString& wstrText = getWText(); + mMisspellRanges.clear(); + + segment_set_t::iterator seg_it = getSegIterContaining(start); + while (mSegments.end() != seg_it) + { + LLTextSegmentPtr text_segment = *seg_it; + if ( (text_segment.isNull()) || (text_segment->getStart() >= end) ) + { + break; + } + + if (!text_segment->canEdit()) + { + ++seg_it; + continue; + } + + // Combine adjoining text segments into one + U32 seg_start = text_segment->getStart(), seg_end = llmin(text_segment->getEnd(), end); + while (mSegments.end() != ++seg_it) + { + text_segment = *seg_it; + if ( (text_segment.isNull()) || (!text_segment->canEdit()) || (text_segment->getStart() >= end) ) + { + break; + } + seg_end = llmin(text_segment->getEnd(), end); + } + + // Find the start of the first word + U32 word_start = seg_start, word_end = -1; + while ( (word_start < wstrText.length()) && (!LLStringOps::isAlpha(wstrText[word_start])) ) + word_start++; + + // Iterate over all words in the text block and check them one by one + while (word_start < seg_end) + { + // Find the end of the current word (special case handling for "'" when it's used as a contraction) + word_end = word_start + 1; + while ( (word_end < seg_end) && + ((LLWStringUtil::isPartOfWord(wstrText[word_end])) || + ((L'\'' == wstrText[word_end]) && + (LLStringOps::isAlnum(wstrText[word_end - 1])) && (LLStringOps::isAlnum(wstrText[word_end + 1])))) ) + { + word_end++; + } + if (word_end > seg_end) + break; + + // Don't process words shorter than 3 characters + std::string word = wstring_to_utf8str(wstrText.substr(word_start, word_end - word_start)); + if ( (word.length() >= 3) && (!LLSpellChecker::instance().checkSpelling(word)) ) + { + mMisspellRanges.push_back(std::pair(word_start, word_end)); + } + + // Find the start of the next word + word_start = word_end + 1; + while ( (word_start < seg_end) && (!LLWStringUtil::isPartOfWord(wstrText[word_start])) ) + word_start++; + } + } + + mSpellCheckStart = start; + mSpellCheckEnd = end; + } + } + LLTextSegmentPtr cur_segment = *seg_iter; + std::list >::const_iterator misspell_it = std::lower_bound(mMisspellRanges.begin(), mMisspellRanges.end(), std::pair(line_start, 0)); for (S32 cur_line = first_line; cur_line < last_line; cur_line++) { S32 next_line = cur_line + 1; @@ -566,7 +655,8 @@ void LLTextBase::drawText() cur_segment = *seg_iter; } - S32 clipped_end = llmin( line_end, cur_segment->getEnd() ) - cur_segment->getStart(); + S32 seg_end = llmin(line_end, cur_segment->getEnd()); + S32 clipped_end = seg_end - cur_segment->getStart(); if (mUseEllipses // using ellipses && clipped_end == line_end // last segment on line @@ -578,6 +668,35 @@ void LLTextBase::drawText() text_rect.mRight -= 2; } + // Draw squiggly lines under any visible misspelled words + while ( (mMisspellRanges.end() != misspell_it) && (misspell_it->first < seg_end) && (misspell_it->second > seg_start) ) + { + // Skip the current word if the user is still busy editing it + if ( (!mSpellCheckTimer.hasExpired()) && (misspell_it->first <= (U32)mCursorPos) && (misspell_it->second >= (U32)mCursorPos) ) + continue; + + S32 squiggle_start = 0, squiggle_end = 0, pony = 0; + cur_segment->getDimensions(seg_start - cur_segment->getStart(), misspell_it->first - seg_start, squiggle_start, pony); + cur_segment->getDimensions(misspell_it->first - cur_segment->getStart(), misspell_it->second - misspell_it->first, squiggle_end, pony); + squiggle_start += text_rect.mLeft; + + pony = (squiggle_end + 3) / 6; + squiggle_start += squiggle_end / 2 - pony * 3; + squiggle_end = squiggle_start + pony * 6; + + gGL.color4ub(255, 0, 0, 200); + while (squiggle_start < squiggle_end) + { + gl_line_2d(squiggle_start, text_rect.mBottom - 2, squiggle_start + 3, text_rect.mBottom + 1); + gl_line_2d(squiggle_start + 3, text_rect.mBottom + 1, squiggle_start + 6, text_rect.mBottom - 2); + squiggle_start += 6; + } + + if (misspell_it->second > seg_end) + break; + ++misspell_it; + } + text_rect.mLeft = (S32)(cur_segment->draw(seg_start - cur_segment->getStart(), clipped_end, selection_left, selection_right, text_rect)); seg_start = clipped_end + cur_segment->getStart(); @@ -1103,6 +1222,94 @@ void LLTextBase::deselect() mIsSelecting = FALSE; } +bool LLTextBase::getSpellCheck() const +{ + return (LLSpellChecker::getUseSpellCheck()) && (!mReadOnly) && (mSpellCheck); +} + +const std::string& LLTextBase::getSuggestion(U32 index) const +{ + return (index < mSuggestionList.size()) ? mSuggestionList[index] : LLStringUtil::null; +} + +U32 LLTextBase::getSuggestionCount() const +{ + return mSuggestionList.size(); +} + +void LLTextBase::replaceWithSuggestion(U32 index) +{ + for (std::list >::const_iterator it = mMisspellRanges.begin(); it != mMisspellRanges.end(); ++it) + { + if ( (it->first <= (U32)mCursorPos) && (it->second >= (U32)mCursorPos) ) + { + deselect(); + + // Delete the misspelled word + removeStringNoUndo(it->first, it->second - it->first); + + // Insert the suggestion in its place + LLWString suggestion = utf8str_to_wstring(mSuggestionList[index]); + insertStringNoUndo(it->first, utf8str_to_wstring(mSuggestionList[index])); + setCursorPos(it->first + (S32)suggestion.length()); + + break; + } + } + mSpellCheckStart = mSpellCheckEnd = -1; +} + +void LLTextBase::addToDictionary() +{ + if (canAddToDictionary()) + { + LLSpellChecker::instance().addToCustomDictionary(getMisspelledWord(mCursorPos)); + } +} + +bool LLTextBase::canAddToDictionary() const +{ + return (getSpellCheck()) && (isMisspelledWord(mCursorPos)); +} + +void LLTextBase::addToIgnore() +{ + if (canAddToIgnore()) + { + LLSpellChecker::instance().addToIgnoreList(getMisspelledWord(mCursorPos)); + } +} + +bool LLTextBase::canAddToIgnore() const +{ + return (getSpellCheck()) && (isMisspelledWord(mCursorPos)); +} + +std::string LLTextBase::getMisspelledWord(U32 pos) const +{ + for (std::list >::const_iterator it = mMisspellRanges.begin(); it != mMisspellRanges.end(); ++it) + { + if ( (it->first <= pos) && (it->second >= pos) ) + return wstring_to_utf8str(getWText().substr(it->first, it->second - it->first)); + } + return LLStringUtil::null; +} + +bool LLTextBase::isMisspelledWord(U32 pos) const +{ + for (std::list >::const_iterator it = mMisspellRanges.begin(); it != mMisspellRanges.end(); ++it) + { + if ( (it->first <= pos) && (it->second >= pos) ) + return true; + } + return false; +} + +void LLTextBase::onSpellCheckSettingsChange() +{ + // Recheck the spelling on every change + mSpellCheckStart = mSpellCheckEnd = -1; +} // Sets the scrollbar from the cursor position void LLTextBase::updateScrollFromCursor() diff --git a/indra/llui/lltextbase.h b/indra/llui/lltextbase.h index 0549141b72..90b147cee1 100644 --- a/indra/llui/lltextbase.h +++ b/indra/llui/lltextbase.h @@ -30,6 +30,7 @@ #include "v4color.h" #include "lleditmenuhandler.h" +#include "llspellcheckmenuhandler.h" #include "llstyle.h" #include "llkeywords.h" #include "llpanel.h" @@ -230,7 +231,8 @@ typedef LLPointer LLTextSegmentPtr; /// class LLTextBase : public LLUICtrl, - protected LLEditMenuHandler + protected LLEditMenuHandler, + public LLSpellCheckMenuHandler { public: friend class LLTextSegment; @@ -259,6 +261,7 @@ public: border_visible, track_end, read_only, + spellcheck, allow_scroll, plain_text, wrap, @@ -311,6 +314,24 @@ public: /*virtual*/ BOOL canDeselect() const; /*virtual*/ void deselect(); + // LLSpellCheckMenuHandler overrides + /*virtual*/ bool getSpellCheck() const; + + /*virtual*/ const std::string& getSuggestion(U32 index) const; + /*virtual*/ U32 getSuggestionCount() const; + /*virtual*/ void replaceWithSuggestion(U32 index); + + /*virtual*/ void addToDictionary(); + /*virtual*/ bool canAddToDictionary() const; + + /*virtual*/ void addToIgnore(); + /*virtual*/ bool canAddToIgnore() const; + + // Spell checking helper functions + std::string getMisspelledWord(U32 pos) const; + bool isMisspelledWord(U32 pos) const; + void onSpellCheckSettingsChange(); + // used by LLTextSegment layout code bool getWordWrap() { return mWordWrap; } bool getUseEllipses() { return mUseEllipses; } @@ -540,6 +561,14 @@ protected: BOOL mIsSelecting; // Are we in the middle of a drag-select? + // spell checking + bool mSpellCheck; + S32 mSpellCheckStart; + S32 mSpellCheckEnd; + LLTimer mSpellCheckTimer; + std::list > mMisspellRanges; + std::vector mSuggestionList; + // configuration S32 mHPad; // padding on left of text S32 mVPad; // padding above text diff --git a/indra/llui/lltexteditor.cpp b/indra/llui/lltexteditor.cpp index 3a23ce1cac..c5957838ba 100644 --- a/indra/llui/lltexteditor.cpp +++ b/indra/llui/lltexteditor.cpp @@ -54,6 +54,7 @@ #include "llwindow.h" #include "lltextparser.h" #include "llscrollcontainer.h" +#include "llspellcheck.h" #include "llpanel.h" #include "llurlregistry.h" #include "lltooltip.h" @@ -77,6 +78,7 @@ template class LLTextEditor* LLView::getChild( const S32 UI_TEXTEDITOR_LINE_NUMBER_MARGIN = 32; const S32 UI_TEXTEDITOR_LINE_NUMBER_DIGITS = 4; const S32 SPACES_PER_TAB = 4; +const F32 SPELLCHECK_DELAY = 0.5f; // delay between the last keypress and spell checking the word the cursor is on /////////////////////////////////////////////////////////////////// @@ -1961,7 +1963,34 @@ void LLTextEditor::showContextMenu(S32 x, S32 y) S32 screen_x, screen_y; localPointToScreen(x, y, &screen_x, &screen_y); - mContextMenu->show(screen_x, screen_y); + + setCursorAtLocalPos(x, y, false); + if (hasSelection()) + { + if ( (mCursorPos < llmin(mSelectionStart, mSelectionEnd)) || (mCursorPos > llmax(mSelectionStart, mSelectionEnd)) ) + deselect(); + else + setCursorPos(llmax(mSelectionStart, mSelectionEnd)); + } + + bool use_spellcheck = getSpellCheck(), is_misspelled = false; + if (use_spellcheck) + { + mSuggestionList.clear(); + + // If the cursor is on a misspelled word, retrieve suggestions for it + std::string misspelled_word = getMisspelledWord(mCursorPos); + if ((is_misspelled = !misspelled_word.empty()) == true) + { + LLSpellChecker::instance().getSuggestions(misspelled_word, mSuggestionList); + } + } + + mContextMenu->setItemVisible("Suggestion Separator", (use_spellcheck) && (!mSuggestionList.empty())); + mContextMenu->setItemVisible("Add to Dictionary", (use_spellcheck) && (is_misspelled)); + mContextMenu->setItemVisible("Add to Ignore", (use_spellcheck) && (is_misspelled)); + mContextMenu->setItemVisible("Spellcheck Separator", (use_spellcheck) && (is_misspelled)); + mContextMenu->show(screen_x, screen_y, this); } @@ -2846,6 +2875,9 @@ void LLTextEditor::setKeystrokeCallback(const keystroke_signal_t::slot_type& cal void LLTextEditor::onKeyStroke() { mKeystrokeSignal(this); + + mSpellCheckStart = mSpellCheckEnd = -1; + mSpellCheckTimer.setTimerExpirySec(SPELLCHECK_DELAY); } //virtual -- cgit v1.2.3 From 41e11a508379d8f6d2b95f835d2df9f4e2bbea01 Mon Sep 17 00:00:00 2001 From: Kitty Barnett Date: Fri, 3 Feb 2012 15:34:52 +0100 Subject: STORM-276 FIXED Selecting a character in a line editor and replacing it doesn't trigger a spell check --- indra/llui/lllineeditor.cpp | 53 ++++++++++++++++++++------------------------- indra/llui/lllineeditor.h | 1 + 2 files changed, 24 insertions(+), 30 deletions(-) (limited to 'indra') diff --git a/indra/llui/lllineeditor.cpp b/indra/llui/lllineeditor.cpp index 5479c080bd..e67753292e 100644 --- a/indra/llui/lllineeditor.cpp +++ b/indra/llui/lllineeditor.cpp @@ -66,7 +66,7 @@ const S32 SCROLL_INCREMENT_ADD = 0; // make space for typing const S32 SCROLL_INCREMENT_DEL = 4; // make space for baskspacing const F32 AUTO_SCROLL_TIME = 0.05f; const F32 TRIPLE_CLICK_INTERVAL = 0.3f; // delay between double and triple click. *TODO: make this equal to the double click interval? -const F32 SPELLCHECK_DELAY = 0.5f; // delay between the last keypress and showing spell checking feedback for the word the cursor is on +const F32 SPELLCHECK_DELAY = 0.5f; // delay between the last keypress and spell checking the word the cursor is on const std::string PASSWORD_ASTERISK( "\xE2\x80\xA2" ); // U+2022 BULLET @@ -1158,9 +1158,8 @@ void LLLineEditor::cut() LLUI::reportBadKeystroke(); } else - if( mKeystrokeCallback ) { - mKeystrokeCallback( this ); + onKeystroke(); } } } @@ -1294,9 +1293,8 @@ void LLLineEditor::pasteHelper(bool is_primary) LLUI::reportBadKeystroke(); } else - if( mKeystrokeCallback ) { - mKeystrokeCallback( this ); + onKeystroke(); } } } @@ -1549,10 +1547,7 @@ BOOL LLLineEditor::handleKeyHere(KEY key, MASK mask ) // Notify owner if requested if (!need_to_rollback && handled) { - if (mKeystrokeCallback) - { - mKeystrokeCallback(this); - } + onKeystroke(); if ( (!selection_modified) && (KEY_BACKSPACE == key) ) { mSpellCheckTimer.setTimerExpirySec(SPELLCHECK_DELAY); @@ -1608,12 +1603,10 @@ BOOL LLLineEditor::handleUnicodeCharHere(llwchar uni_char) // Notify owner if requested if( !need_to_rollback && handled ) { - if( mKeystrokeCallback ) - { - // HACK! The only usage of this callback doesn't do anything with the character. - // We'll have to do something about this if something ever changes! - Doug - mKeystrokeCallback( this ); - } + // HACK! The only usage of this callback doesn't do anything with the character. + // We'll have to do something about this if something ever changes! - Doug + onKeystroke(); + mSpellCheckTimer.setTimerExpirySec(SPELLCHECK_DELAY); } } @@ -1643,9 +1636,7 @@ void LLLineEditor::doDelete() if (!prevalidateInput(text_to_delete)) { - if( mKeystrokeCallback ) - mKeystrokeCallback( this ); - + onKeystroke(); return; } setCursor(getCursor() + 1); @@ -1661,10 +1652,8 @@ void LLLineEditor::doDelete() } else { - if( mKeystrokeCallback ) - { - mKeystrokeCallback( this ); - } + onKeystroke(); + mSpellCheckTimer.setTimerExpirySec(SPELLCHECK_DELAY); } } @@ -2296,6 +2285,15 @@ void LLLineEditor::setSelectAllonFocusReceived(BOOL b) mSelectAllonFocusReceived = b; } +void LLLineEditor::onKeystroke() +{ + if (mKeystrokeCallback) + { + mKeystrokeCallback(this); + } + + mSpellCheckStart = mSpellCheckEnd = -1; +} void LLLineEditor::setKeystrokeCallback(callback_t callback, void* user_data) { @@ -2418,10 +2416,8 @@ void LLLineEditor::updatePreedit(const LLWString &preedit_string, // Update of the preedit should be caused by some key strokes. mKeystrokeTimer.reset(); - if( mKeystrokeCallback ) - { - mKeystrokeCallback( this ); - } + onKeystroke(); + mSpellCheckTimer.setTimerExpirySec(SPELLCHECK_DELAY); } @@ -2575,6 +2571,7 @@ void LLLineEditor::showContextMenu(S32 x, S32 y) S32 screen_x, screen_y; localPointToScreen(x, y, &screen_x, &screen_y); + setCursorAtLocalPos(x); if (hasSelection()) { if ( (mCursorPos < llmin(mSelectionStart, mSelectionEnd)) || (mCursorPos > llmax(mSelectionStart, mSelectionEnd)) ) @@ -2582,10 +2579,6 @@ void LLLineEditor::showContextMenu(S32 x, S32 y) else setCursor(llmax(mSelectionStart, mSelectionEnd)); } - else - { - setCursorAtLocalPos(x); - } bool use_spellcheck = getSpellCheck(), is_misspelled = false; if (use_spellcheck) diff --git a/indra/llui/lllineeditor.h b/indra/llui/lllineeditor.h index 9513274f21..40f931ecc1 100644 --- a/indra/llui/lllineeditor.h +++ b/indra/llui/lllineeditor.h @@ -243,6 +243,7 @@ public: void setSelectAllonFocusReceived(BOOL b); void setSelectAllonCommit(BOOL b) { mSelectAllonCommit = b; } + void onKeystroke(); typedef boost::function callback_t; void setKeystrokeCallback(callback_t callback, void* user_data); -- cgit v1.2.3 From 49e0c38ee85214eb7d0e7e995d1a380ee2f60720 Mon Sep 17 00:00:00 2001 From: Kitty Barnett Date: Fri, 3 Feb 2012 19:45:00 +0100 Subject: STORM-276 Added preferences panel --- indra/llui/lllineeditor.cpp | 1 + indra/llui/llspellcheck.cpp | 12 +- indra/llui/llspellcheck.h | 29 +++-- indra/llui/lltextbase.cpp | 1 + indra/newview/llfloaterpreference.cpp | 95 +++++++++++++++ indra/newview/llfloaterpreference.h | 2 + indra/newview/skins/default/textures/textures.xml | 2 + .../skins/default/textures/widgets/Arrow_Left.png | Bin 0 -> 311 bytes .../skins/default/textures/widgets/Arrow_Right.png | Bin 0 -> 313 bytes .../skins/default/xui/en/floater_preferences.xml | 6 + .../xui/en/panel_preferences_spellcheck.xml | 132 +++++++++++++++++++++ 11 files changed, 261 insertions(+), 19 deletions(-) create mode 100644 indra/newview/skins/default/textures/widgets/Arrow_Left.png create mode 100644 indra/newview/skins/default/textures/widgets/Arrow_Right.png create mode 100644 indra/newview/skins/default/xui/en/panel_preferences_spellcheck.xml (limited to 'indra') diff --git a/indra/llui/lllineeditor.cpp b/indra/llui/lllineeditor.cpp index e67753292e..42cfc4cae9 100644 --- a/indra/llui/lllineeditor.cpp +++ b/indra/llui/lllineeditor.cpp @@ -617,6 +617,7 @@ bool LLLineEditor::isMisspelledWord(U32 pos) const void LLLineEditor::onSpellCheckSettingsChange() { // Recheck the spelling on every change + mMisspellRanges.clear(); mSpellCheckStart = mSpellCheckEnd = -1; } diff --git a/indra/llui/llspellcheck.cpp b/indra/llui/llspellcheck.cpp index 433ca02852..65207144f8 100644 --- a/indra/llui/llspellcheck.cpp +++ b/indra/llui/llspellcheck.cpp @@ -186,7 +186,7 @@ void LLSpellChecker::addToDictFile(const std::string& dict_path, const std::stri } } -void LLSpellChecker::setSecondaryDictionaries(std::list dict_list) +void LLSpellChecker::setSecondaryDictionaries(dict_list_t dict_list) { if (!getUseSpellCheck()) { @@ -194,11 +194,11 @@ void LLSpellChecker::setSecondaryDictionaries(std::list dict_list) } // Check if we're only adding secondary dictionaries, or removing them - std::list dict_add(llmax(dict_list.size(), mDictSecondary.size())), dict_rem(llmax(dict_list.size(), mDictSecondary.size())); + dict_list_t dict_add(llmax(dict_list.size(), mDictSecondary.size())), dict_rem(llmax(dict_list.size(), mDictSecondary.size())); dict_list.sort(); mDictSecondary.sort(); - std::list::iterator end_added = std::set_difference(dict_list.begin(), dict_list.end(), mDictSecondary.begin(), mDictSecondary.end(), dict_add.begin()); - std::list::iterator end_removed = std::set_difference(mDictSecondary.begin(), mDictSecondary.end(), dict_list.begin(), dict_list.end(), dict_rem.begin()); + dict_list_t::iterator end_added = std::set_difference(dict_list.begin(), dict_list.end(), mDictSecondary.begin(), mDictSecondary.end(), dict_add.begin()); + dict_list_t::iterator end_removed = std::set_difference(mDictSecondary.begin(), mDictSecondary.end(), dict_list.begin(), dict_list.end(), dict_rem.begin()); if (end_removed != dict_rem.begin()) // We can't remove secondary dictionaries so we need to recreate the Hunspell instance { @@ -211,7 +211,7 @@ void LLSpellChecker::setSecondaryDictionaries(std::list dict_list) { const std::string app_path = getDictionaryAppPath(); const std::string user_path = getDictionaryUserPath(); - for (std::list::const_iterator it_added = dict_add.begin(); it_added != end_added; ++it_added) + for (dict_list_t::const_iterator it_added = dict_add.begin(); it_added != end_added; ++it_added) { const LLSD dict_entry = getDictionaryData(*it_added); if ( (!dict_entry.isDefined()) || (!dict_entry["installed"].asBoolean()) ) @@ -287,7 +287,7 @@ void LLSpellChecker::initHunspell(const std::string& dict_name) } } - for (std::list::const_iterator it = mDictSecondary.begin(); it != mDictSecondary.end(); ++it) + for (dict_list_t::const_iterator it = mDictSecondary.begin(); it != mDictSecondary.end(); ++it) { const LLSD dict_entry = getDictionaryData(*it); if ( (!dict_entry.isDefined()) || (!dict_entry["installed"].asBoolean()) ) diff --git a/indra/llui/llspellcheck.h b/indra/llui/llspellcheck.h index affdac2907..8351655b49 100644 --- a/indra/llui/llspellcheck.h +++ b/indra/llui/llspellcheck.h @@ -44,17 +44,20 @@ public: void addToIgnoreList(const std::string& word); bool checkSpelling(const std::string& word) const; S32 getSuggestions(const std::string& word, std::vector& suggestions) const; - -public: - const LLSD getDictionaryData(const std::string& dict_name) const; - const LLSD& getDictionaryMap() const { return mDictMap; } - void refreshDictionaryMap(); - void setSecondaryDictionaries(std::list dictList); protected: - void addToDictFile(const std::string& dict_path, const std::string& word); - void initHunspell(const std::string& dict_name); + void addToDictFile(const std::string& dict_path, const std::string& word); + void initHunspell(const std::string& dict_name); public: + typedef std::list dict_list_t; + + const std::string& getActiveDictionary() const { return mDictName; } + const LLSD getDictionaryData(const std::string& dict_name) const; + const LLSD& getDictionaryMap() const { return mDictMap; } + const dict_list_t& getSecondaryDictionaries() const { return mDictSecondary; } + void refreshDictionaryMap(); + void setSecondaryDictionaries(dict_list_t dict_list); + static const std::string getDictionaryAppPath(); static const std::string getDictionaryUserPath(); static bool getUseSpellCheck(); @@ -64,11 +67,11 @@ public: static boost::signals2::connection setSettingsChangeCallback(const settings_change_signal_t::slot_type& cb); protected: - Hunspell* mHunspell; - std::string mDictName; - std::string mDictFile; - LLSD mDictMap; - std::list mDictSecondary; + Hunspell* mHunspell; + std::string mDictName; + std::string mDictFile; + LLSD mDictMap; + dict_list_t mDictSecondary; std::vector mIgnoreList; static settings_change_signal_t sSettingsChangeSignal; diff --git a/indra/llui/lltextbase.cpp b/indra/llui/lltextbase.cpp index 7eee1d39c4..2231d9b983 100644 --- a/indra/llui/lltextbase.cpp +++ b/indra/llui/lltextbase.cpp @@ -1308,6 +1308,7 @@ bool LLTextBase::isMisspelledWord(U32 pos) const void LLTextBase::onSpellCheckSettingsChange() { // Recheck the spelling on every change + mMisspellRanges.clear(); mSpellCheckStart = mSpellCheckEnd = -1; } diff --git a/indra/newview/llfloaterpreference.cpp b/indra/newview/llfloaterpreference.cpp index a333989e7e..29b07d2479 100755 --- a/indra/newview/llfloaterpreference.cpp +++ b/indra/newview/llfloaterpreference.cpp @@ -66,6 +66,7 @@ #include "llsky.h" #include "llscrolllistctrl.h" #include "llscrolllistitem.h" +#include "llspellcheck.h" #include "llsliderctrl.h" #include "lltabcontainer.h" #include "lltrans.h" @@ -110,6 +111,8 @@ #include "lllogininstance.h" // to check if logged in yet #include "llsdserialize.h" +#include + const F32 MAX_USER_FAR_CLIP = 512.f; const F32 MIN_USER_FAR_CLIP = 64.f; const F32 BANDWIDTH_UPDATER_TIMEOUT = 0.5f; @@ -445,6 +448,9 @@ BOOL LLFloaterPreference::postBuild() getChild("language_combobox")->setCommitCallback(boost::bind(&LLFloaterPreference::onLanguageChange, this)); + getChild("btn_spellcheck_moveleft")->setCommitCallback(boost::bind(&LLFloaterPreference::onClickDictMove, this, "list_spellcheck_active", "list_spellcheck_available")); + getChild("btn_spellcheck_moveright")->setCommitCallback(boost::bind(&LLFloaterPreference::onClickDictMove, this, "list_spellcheck_available", "list_spellcheck_active")); + // if floater is opened before login set default localized busy message if (LLStartUp::getStartupState() < STATE_STARTED) { @@ -577,6 +583,19 @@ void LLFloaterPreference::apply() } } + if (hasChild("check_spellcheck"), TRUE) + { + LLScrollListCtrl* list_ctrl = findChild("list_spellcheck_active"); + std::vector list_items = list_ctrl->getAllData(); + + std::list list_dict; + list_dict.push_back(LLSpellChecker::instance().getActiveDictionary()); + for (std::vector::const_iterator item_it = list_items.begin(); item_it != list_items.end(); ++item_it) + list_dict.push_back((*item_it)->getColumn(0)->getValue().asString()); + + gSavedSettings.setString("SpellCheckDictionary", boost::join(list_dict, ",")); + } + saveAvatarProperties(); if (mClickActionDirty) @@ -687,6 +706,8 @@ void LLFloaterPreference::onOpen(const LLSD& key) // Load (double-)click to walk/teleport settings. updateClickActionControls(); + buildDictLists(); + // Enabled/disabled popups, might have been changed by user actions // while preferences floater was closed. buildPopupLists(); @@ -865,6 +886,25 @@ void LLFloaterPreference::onNameTagOpacityChange(const LLSD& newvalue) } } +void LLFloaterPreference::onClickDictMove(const std::string& from, const std::string& to) +{ + LLScrollListCtrl* from_ctrl = findChild(from); + LLScrollListCtrl* to_ctrl = findChild(to); + + LLSD row; + row["columns"][0]["column"] = "name"; + row["columns"][0]["font"]["name"] = "SANSSERIF_SMALL"; + row["columns"][0]["font"]["style"] = "NORMAL"; + + std::vector sel_items = from_ctrl->getAllSelected(); + for (std::vector::const_iterator sel_it = sel_items.begin(); sel_it != sel_items.end(); ++sel_it) + { + row["columns"][0]["value"] = (*sel_it)->getColumn(0)->getValue(); + to_ctrl->addElement(row); + } + from_ctrl->deleteSelectedItems(); +} + void LLFloaterPreference::onClickSetCache() { std::string cur_name(gSavedSettings.getString("CacheLocation")); @@ -930,6 +970,61 @@ void LLFloaterPreference::refreshSkin(void* data) self->getChild("skin_selection", true)->setValue(sSkin); } +void LLFloaterPreference::buildDictLists() +{ + LLComboBox* dict_combo = findChild("combo_spellcheck_dict"); + dict_combo->clearRows(); + + LLScrollListCtrl* active_ctrl = findChild("list_spellcheck_active"); + active_ctrl->clearRows(); + + LLScrollListCtrl* avail_ctrl = findChild("list_spellcheck_available"); + avail_ctrl->clearRows(); + + if (LLSpellChecker::getUseSpellCheck()) + { + // Populate the main dictionary combobox + const LLSD& dict_map = LLSpellChecker::instance().getDictionaryMap(); + if (dict_map.size()) + { + for (LLSD::array_const_iterator dict_it = dict_map.beginArray(); dict_it != dict_map.endArray(); ++dict_it) + { + const LLSD& dict = *dict_it; + if ( (dict["installed"].asBoolean()) && (dict.has("language")) ) + dict_combo->add(dict["language"].asString()); + } + dict_combo->selectByValue(LLSpellChecker::instance().getActiveDictionary()); + } + + LLSD row; + row["columns"][0]["column"] = "name"; + row["columns"][0]["font"]["name"] = "SANSSERIF_SMALL"; + row["columns"][0]["font"]["style"] = "NORMAL"; + + // Populate the active dictionary list + LLSpellChecker::dict_list_t active_list = LLSpellChecker::instance().getSecondaryDictionaries(); + active_ctrl->sortByColumnIndex(0, true); + for (LLSpellChecker::dict_list_t::const_iterator it = active_list.begin(); it != active_list.end(); ++it) + { + row["columns"][0]["value"] = *it; + active_ctrl->addElement(row); + } + active_list.push_back(LLSpellChecker::instance().getActiveDictionary()); + + // Populate the available dictionary list + avail_ctrl->sortByColumnIndex(0, true); + for (LLSD::array_const_iterator dict_it = dict_map.beginArray(); dict_it != dict_map.endArray(); ++dict_it) + { + const LLSD& dict = *dict_it; + if ( (dict["installed"].asBoolean()) && (dict.has("language")) && + (active_list.end() == std::find(active_list.begin(), active_list.end(), dict["language"].asString())) ) + { + row["columns"][0]["value"] = dict["language"].asString(); + avail_ctrl->addElement(row); + } + } + } +} void LLFloaterPreference::buildPopupLists() { diff --git a/indra/newview/llfloaterpreference.h b/indra/newview/llfloaterpreference.h index 7ee3294478..cd258b5614 100644 --- a/indra/newview/llfloaterpreference.h +++ b/indra/newview/llfloaterpreference.h @@ -121,6 +121,7 @@ public: void setCacheLocation(const LLStringExplicit& location); + void onClickDictMove(const std::string& from, const std::string& to); void onClickSetCache(); void onClickResetCache(); void onClickSkin(LLUICtrl* ctrl,const LLSD& userdata); @@ -160,6 +161,7 @@ public: void applyUIColor(LLUICtrl* ctrl, const LLSD& param); void getUIColor(LLUICtrl* ctrl, const LLSD& param); + void buildDictLists(); void buildPopupLists(); static void refreshSkin(void* data); private: diff --git a/indra/newview/skins/default/textures/textures.xml b/indra/newview/skins/default/textures/textures.xml index 8702ebde2a..bc0363014a 100644 --- a/indra/newview/skins/default/textures/textures.xml +++ b/indra/newview/skins/default/textures/textures.xml @@ -54,6 +54,8 @@ with the same filename but different name + + diff --git a/indra/newview/skins/default/textures/widgets/Arrow_Left.png b/indra/newview/skins/default/textures/widgets/Arrow_Left.png new file mode 100644 index 0000000000..a424282839 Binary files /dev/null and b/indra/newview/skins/default/textures/widgets/Arrow_Left.png differ diff --git a/indra/newview/skins/default/textures/widgets/Arrow_Right.png b/indra/newview/skins/default/textures/widgets/Arrow_Right.png new file mode 100644 index 0000000000..e32bee8f34 Binary files /dev/null and b/indra/newview/skins/default/textures/widgets/Arrow_Right.png differ diff --git a/indra/newview/skins/default/xui/en/floater_preferences.xml b/indra/newview/skins/default/xui/en/floater_preferences.xml index 402868bb97..eebc3a9cca 100644 --- a/indra/newview/skins/default/xui/en/floater_preferences.xml +++ b/indra/newview/skins/default/xui/en/floater_preferences.xml @@ -120,6 +120,12 @@ layout="topleft" help_topic="preferences_advanced1_tab" name="advanced1" /> + diff --git a/indra/newview/skins/default/xui/en/panel_preferences_spellcheck.xml b/indra/newview/skins/default/xui/en/panel_preferences_spellcheck.xml new file mode 100644 index 0000000000..9b5d429846 --- /dev/null +++ b/indra/newview/skins/default/xui/en/panel_preferences_spellcheck.xml @@ -0,0 +1,132 @@ + + + + + Main dictionary : + + + + + Additional dictionaries : + + + Available + + + Active + + + + + + + -- cgit v1.2.3 From 2114e88cd1291ef1dba4b79bcdcca4b2d134262f Mon Sep 17 00:00:00 2001 From: Kitty Barnett Date: Fri, 3 Feb 2012 19:51:18 +0100 Subject: STORM-276 Enabled spell checking on notecards, picks and group notices --- indra/newview/skins/default/xui/en/floater_preview_notecard.xml | 1 + indra/newview/skins/default/xui/en/panel_edit_pick.xml | 1 + indra/newview/skins/default/xui/en/panel_group_notices.xml | 4 ++++ 3 files changed, 6 insertions(+) (limited to 'indra') diff --git a/indra/newview/skins/default/xui/en/floater_preview_notecard.xml b/indra/newview/skins/default/xui/en/floater_preview_notecard.xml index be3b2d179d..2e1c8ce670 100644 --- a/indra/newview/skins/default/xui/en/floater_preview_notecard.xml +++ b/indra/newview/skins/default/xui/en/floater_preview_notecard.xml @@ -70,6 +70,7 @@ max_length="65536" name="Notecard Editor" parse_urls="false" + spellcheck="true" tab_group="1" top="46" width="392" diff --git a/indra/newview/skins/default/xui/en/panel_edit_pick.xml b/indra/newview/skins/default/xui/en/panel_edit_pick.xml index 2ec2e03e8c..6d0be7fdec 100644 --- a/indra/newview/skins/default/xui/en/panel_edit_pick.xml +++ b/indra/newview/skins/default/xui/en/panel_edit_pick.xml @@ -134,6 +134,7 @@ top_pad="2" max_length="1023" name="pick_desc" + spellcheck="true" text_color="black" word_wrap="true" /> @@ -309,6 +311,7 @@ Maximum 200 per group daily left_pad="3" max_length_bytes="63" name="view_subject" + spellcheck="true" top_delta="-1" visible="false" width="200" /> @@ -333,6 +336,7 @@ Maximum 200 per group daily right="-1" max_length="511" name="view_message" + spellcheck="true" top_delta="-40" width="313" word_wrap="true" /> -- cgit v1.2.3 From 5e74293b0cfe562e8e3184217f27b3e86afe5277 Mon Sep 17 00:00:00 2001 From: Xiaohong Bao Date: Fri, 3 Feb 2012 22:01:46 -0700 Subject: fix for SH-2941: crash at LLCurl::Easy::~Easy() --- indra/llmessage/llcurl.cpp | 9 +++++++-- indra/llmessage/llcurl.h | 2 +- 2 files changed, 8 insertions(+), 3 deletions(-) (limited to 'indra') diff --git a/indra/llmessage/llcurl.cpp b/indra/llmessage/llcurl.cpp index 3bcaffc275..2ef43d9c00 100644 --- a/indra/llmessage/llcurl.cpp +++ b/indra/llmessage/llcurl.cpp @@ -583,10 +583,10 @@ LLCurl::Multi::Multi(F32 idle_time_out) LLCurl::Multi::~Multi() { - cleanup() ; + cleanup(true) ; } -void LLCurl::Multi::cleanup() +void LLCurl::Multi::cleanup(bool deleted) { if(!mCurlMultiHandle) { @@ -599,6 +599,11 @@ void LLCurl::Multi::cleanup() { Easy* easy = *iter; check_curl_multi_code(curl_multi_remove_handle(mCurlMultiHandle, easy->getCurlHandle())); + + if(deleted) + { + easy->mResponder = NULL ; //avoid triggering mResponder. + } delete easy; } mEasyActiveList.clear(); diff --git a/indra/llmessage/llcurl.h b/indra/llmessage/llcurl.h index fd664c0fa1..579ba0b1ab 100644 --- a/indra/llmessage/llcurl.h +++ b/indra/llmessage/llcurl.h @@ -318,7 +318,7 @@ public: private: void easyFree(LLCurl::Easy*); - void cleanup() ; + void cleanup(bool deleted = false) ; CURLM* mCurlMultiHandle; -- cgit v1.2.3 From 39ffad760b7abd09c8a7af6871fcabbf2da9c1e6 Mon Sep 17 00:00:00 2001 From: Jonathan Yap Date: Sun, 5 Feb 2012 15:48:07 -0500 Subject: STORM-1738 Fix some syntax errors warn-on-failure:open-license --- indra/newview/llautocorrect.cpp | 2 +- indra/newview/llautocorrectfloater.cpp | 11 ++++++----- indra/newview/llnearbychatbar.cpp | 2 +- 3 files changed, 8 insertions(+), 7 deletions(-) (limited to 'indra') diff --git a/indra/newview/llautocorrect.cpp b/indra/newview/llautocorrect.cpp index c16787d637..9162b35f45 100644 --- a/indra/newview/llautocorrect.cpp +++ b/indra/newview/llautocorrect.cpp @@ -375,7 +375,7 @@ std::string AutoCorrect::replaceWords(std::string words) args["REPLACEMENT"]=replacement; LLNotificationsUtil::add("AutoReplace",args); } - ldebugs << "found a word in list " << location.c_str() << " and it will replace " << currentWord.c_str() << " => " << replacement.c_str() << llendl; + lldebugs << "found a word in list " << location.c_str() << " and it will replace " << currentWord.c_str() << " => " << replacement.c_str() << llendl; int wordStart = words.find(currentWord); words.replace(wordStart,currentWord.length(),replacement); return replaceWords(words);//lol recursion! diff --git a/indra/newview/llautocorrectfloater.cpp b/indra/newview/llautocorrectfloater.cpp index 74762a876f..97170fc65c 100644 --- a/indra/newview/llautocorrectfloater.cpp +++ b/indra/newview/llautocorrectfloater.cpp @@ -159,7 +159,7 @@ void AutoCorrectFloater::updateItemsList() void AutoCorrectFloater::updateNamesList() { namesList->deleteAllItems(); - if(!gSavedSettings, "AutoCorrect") + if(!gSavedSettings.getBOOL("AutoCorrect")) { updateItemsList(); return; @@ -208,7 +208,8 @@ void AutoCorrectFloater::updateListControlsEnabled(BOOL selected) } void AutoCorrectFloater::updateEnabledStuff() { - if(!gSavedSettings, "AutoCorrect") + BOOL autocorrect = gSavedSettings.getBOOL("AutoCorrect"); + if(autocorrect) { LLCheckBoxCtrl *enBox = getChild("ac_enable"); enBox->setDisabledColor(LLColor4::red); @@ -219,9 +220,9 @@ void AutoCorrectFloater::updateEnabledStuff() LLUIColorTable::instance().getColor( "LabelTextColor" )); } - childSetEnabled("ac_list_name",enabledd); - childSetEnabled("ac_list_entry",enabledd); - updateListControlsEnabled(enabledd); + childSetEnabled("ac_list_name", autocorrect); + childSetEnabled("ac_list_entry", autocorrect); + updateListControlsEnabled(autocorrect); updateNamesList(); AutoCorrect::getInstance()->save(); diff --git a/indra/newview/llnearbychatbar.cpp b/indra/newview/llnearbychatbar.cpp index 8c8707e16c..86244cbaa6 100644 --- a/indra/newview/llnearbychatbar.cpp +++ b/indra/newview/llnearbychatbar.cpp @@ -89,7 +89,7 @@ BOOL LLNearbyChatBar::postBuild() mChatBox = getChild("chat_box"); // *TODO Establish LineEditor with autocorrect callback -// mChatBox->setAutocorrectCallback(boost::bind(&AutoCorrect::autocorrectCallback)); +// mChatBox->setAutocorrectCallback(boost::bind(&AutoCorrect::autocorrectCallback, _1, _2)); mChatBox->setCommitCallback(boost::bind(&LLNearbyChatBar::onChatBoxCommit, this)); mChatBox->setKeystrokeCallback(&onChatBoxKeystroke, this); mChatBox->setFocusLostCallback(boost::bind(&onChatBoxFocusLost, _1, this)); -- cgit v1.2.3 From d99acd56cdc41d72a073a4419e3e51c356e675bb Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Mon, 6 Feb 2012 17:06:55 -0500 Subject: ManageAPR should be noncopyable. Make that explicit. Any RAII class should either be noncopyable or should deal appropriately with a copy operation. ManageAPR is intended only for extremely simple cases, and hence should be noncopyable. --- indra/test/manageapr.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/test/manageapr.h b/indra/test/manageapr.h index 0c1ca7b7be..2452fb6ae4 100644 --- a/indra/test/manageapr.h +++ b/indra/test/manageapr.h @@ -13,6 +13,7 @@ #define LL_MANAGEAPR_H #include "llapr.h" +#include /** * Declare a static instance of this class for dead-simple ll_init_apr() at @@ -21,7 +22,7 @@ * instances of other classes that depend on APR already being initialized, * the indeterminate static-constructor-order problem rears its ugly head. */ -class ManageAPR +class ManageAPR: public boost::noncopyable { public: ManageAPR() -- cgit v1.2.3 From aafb03b29f5166e8978931ad8b717be32d942836 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Tue, 7 Feb 2012 10:53:23 -0500 Subject: Convert LLProcess implementation from platform-specific to using APR. Include logic to engage Linden apr_procattr_autokill_set() extension: on Windows, magic CreateProcess() flag must be pushed down into apr_proc_create() level. When using an APR package without that extension, present implementation should lock (e.g.) SLVoice.exe lifespan to viewer's on Windows XP but probably won't on Windows 7: need magic flag on CreateProcess(). Using APR child-termination callback requires us to define state (e.g. LLProcess::RUNNING). Take the opportunity to present Status, capturing state and (if terminated) rc or signal number; but since most of the time all caller really wants is to log the outcome, also present status string, encapsulating logic to examine state and describe exited-with-rc vs. killed-by-signal. New Status logic may report clearer results in the case of a Windows child process killed by exception. Clarify that static LLProcess::isRunning(handle) overload is only for use when the original LLProcess object has been destroyed: really only for unit tests. We necessarily retain our original platform-specific implementations for just that one method. (Nonstatic isRunning() no longer calls static method.) Clarify log output from llprocess_test.cpp in a couple places. --- indra/llcommon/llprocess.cpp | 552 +++++++++++++++++++++++--------- indra/llcommon/llprocess.h | 64 +++- indra/llcommon/tests/llprocess_test.cpp | 6 +- 3 files changed, 455 insertions(+), 167 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/llprocess.cpp b/indra/llcommon/llprocess.cpp index 8611d67f25..bc27002701 100644 --- a/indra/llcommon/llprocess.cpp +++ b/indra/llcommon/llprocess.cpp @@ -30,11 +30,15 @@ #include "llsingleton.h" #include "llstring.h" #include "stringize.h" +#include "llapr.h" #include #include #include +static std::string empty; +static LLProcess::Status interpret_status(int status); + /// Need an exception to avoid constructing an invalid LLProcess object, but /// internal use only struct LLProcessError: public std::runtime_error @@ -55,9 +59,14 @@ LLProcessPtr LLProcess::create(const LLSDOrParams& params) } } +/// Call an apr function returning apr_status_t. On failure, log warning and +/// throw LLProcessError mentioning the function call that produced that +/// result. +#define chkapr(func) \ + if (ll_apr_warn_status(func)) \ + throw LLProcessError(#func " failed") + LLProcess::LLProcess(const LLSDOrParams& params): - mProcessID(0), - mProcessHandle(0), mAutokill(params.autokill) { if (! params.validateBlock(true)) @@ -66,31 +75,298 @@ LLProcess::LLProcess(const LLSDOrParams& params): << LLSDNotationStreamer(params))); } - launch(params); + apr_procattr_t *procattr = NULL; + chkapr(apr_procattr_create(&procattr, gAPRPoolp)); + + // For which of stdin, stdout, stderr should we create a pipe to the + // child? In the viewer, there are only a couple viable + // apr_procattr_io_set() alternatives: inherit the viewer's own stdxxx + // handle (APR_NO_PIPE, e.g. for stdout, stderr), or create a pipe that's + // blocking on the child end but nonblocking at the viewer end + // (APR_CHILD_BLOCK). The viewer can't block for anything: the parent end + // MUST be nonblocking. As the APR documentation itself points out, it + // makes very little sense to set nonblocking I/O for the child end of a + // pipe: only a specially-written child could deal with that. + // Other major options could include explicitly creating a single APR pipe + // and passing it as both stdout and stderr (apr_procattr_child_out_set(), + // apr_procattr_child_err_set()), or accepting a filename, opening it and + // passing that apr_file_t (simple <, >, 2> redirect emulation). +// chkapr(apr_procattr_io_set(procattr, APR_CHILD_BLOCK, APR_CHILD_BLOCK, APR_CHILD_BLOCK)); + chkapr(apr_procattr_io_set(procattr, APR_NO_PIPE, APR_NO_PIPE, APR_NO_PIPE)); + + // Thumbs down on implicitly invoking the shell to invoke the child. From + // our point of view, the other major alternative to APR_PROGRAM_PATH + // would be APR_PROGRAM_ENV: still copy environment, but require full + // executable pathname. I don't see a downside to searching the PATH, + // though: if our caller wants (e.g.) a specific Python interpreter, s/he + // can still pass the full pathname. + chkapr(apr_procattr_cmdtype_set(procattr, APR_PROGRAM_PATH)); + // YES, do extra work if necessary to report child exec() failures back to + // parent process. + chkapr(apr_procattr_error_check_set(procattr, 1)); + // Do not start a non-autokill child in detached state. On Posix + // platforms, this setting attempts to daemonize the new child, closing + // std handles and the like, and that's a bit more detachment than we + // want. autokill=false just means not to implicitly kill the child when + // the parent terminates! +// chkapr(apr_procattr_detach_set(procattr, params.autokill? 0 : 1)); + + if (params.autokill) + { +#if defined(APR_HAS_PROCATTR_AUTOKILL_SET) + apr_status_t ok = apr_procattr_autokill_set(procattr, 1); +# if LL_WINDOWS + // As of 2012-02-02, we only expect this to be implemented on Windows. + // Avoid spamming the log with warnings we fully expect. + ll_apr_warn_status(ok); +# endif // LL_WINDOWS +#else + LL_WARNS("LLProcess") << "This version of APR lacks Linden apr_procattr_autokill_set() extension" << LL_ENDL; +#endif + } + + // Have to instantiate named std::strings for string params items so their + // c_str() values persist. + std::string cwd(params.cwd); + if (! cwd.empty()) + { + chkapr(apr_procattr_dir_set(procattr, cwd.c_str())); + } + + // create an argv vector for the child process + std::vector argv; + + // add the executable path + std::string executable(params.executable); + argv.push_back(executable.c_str()); + + // and any arguments + std::vector args(params.args.begin(), params.args.end()); + BOOST_FOREACH(const std::string& arg, args) + { + argv.push_back(arg.c_str()); + } + + // terminate with a null pointer + argv.push_back(NULL); + + // Launch! The NULL would be the environment block, if we were passing one. + chkapr(apr_proc_create(&mProcess, argv[0], &argv[0], NULL, procattr, gAPRPoolp)); + + // arrange to call status_callback() + apr_proc_other_child_register(&mProcess, &LLProcess::status_callback, this, mProcess.in, + gAPRPoolp); + mStatus.mState = RUNNING; + + mDesc = STRINGIZE(LLStringUtil::quote(params.executable) << " (" << mProcess.pid << ')'); + LL_INFOS("LLProcess") << "Launched " << params << " (" << mProcess.pid << ")" << LL_ENDL; + + // Unless caller explicitly turned off autokill (child should persist), + // take steps to terminate the child. This is all suspenders-and-belt: in + // theory our destructor should kill an autokill child, but in practice + // that doesn't always work (e.g. VWR-21538). + if (params.autokill) + { + // Tie the lifespan of this child process to the lifespan of our APR + // pool: on destruction of the pool, forcibly kill the process. Tell + // APR to try SIGTERM and wait 3 seconds. If that didn't work, use + // SIGKILL. + apr_pool_note_subprocess(gAPRPoolp, &mProcess, APR_KILL_AFTER_TIMEOUT); + + // On Windows, associate the new child process with our Job Object. + autokill(); + } } LLProcess::~LLProcess() { + // Only in state RUNNING are we registered for callback. In UNSTARTED we + // haven't yet registered. And since receiving the callback is the only + // way we detect child termination, we only change from state RUNNING at + // the same time we unregister. + if (mStatus.mState == RUNNING) + { + // We're still registered for a callback: unregister. Do it before + // we even issue the kill(): even if kill() somehow prompted an + // instantaneous callback (unlikely), this object is going away! Any + // information updated in this object by such a callback is no longer + // available to any consumer anyway. + apr_proc_other_child_unregister(this); + } + if (mAutokill) { - kill(); + kill("destructor"); + } +} + +bool LLProcess::kill(const std::string& who) +{ + if (isRunning()) + { + LL_INFOS("LLProcess") << who << " killing " << mDesc << LL_ENDL; + +#if LL_WINDOWS + int sig = -1; +#else // Posix + int sig = SIGTERM; +#endif + + ll_apr_warn_status(apr_proc_kill(&mProcess, sig)); } + + return ! isRunning(); } bool LLProcess::isRunning(void) { - mProcessHandle = isRunning(mProcessHandle, mDesc); - return (mProcessHandle != 0); + return getStatus().mState == RUNNING; +} + +LLProcess::Status LLProcess::getStatus() +{ + // Only when mState is RUNNING might the status change dynamically. For + // any other value, pointless to attempt to update status: it won't + // change. + if (mStatus.mState == RUNNING) + { + // Tell APR to sense whether the child is still running and call + // handle_status() appropriately. We should be able to get the same + // info from an apr_proc_wait(APR_NOWAIT) call; but at least in APR + // 1.4.2, testing suggests that even with APR_NOWAIT, apr_proc_wait() + // blocks the caller. We can't have that in the viewer. Hence the + // callback rigmarole. Once we update APR, it's probably worth testing + // again. Also -- although there's an apr_proc_other_child_refresh() + // call, i.e. get that information for one specific child, it accepts + // an 'apr_other_child_rec_t*' that's mentioned NOWHERE else in the + // documentation or header files! I would use the specific call if I + // knew how. As it is, each call to this method will call callbacks + // for ALL still-running child processes. Sigh... + apr_proc_other_child_refresh_all(APR_OC_REASON_RUNNING); + } + + return mStatus; +} + +std::string LLProcess::getStatusString() +{ + return getStatusString(getStatus()); +} + +std::string LLProcess::getStatusString(const Status& status) +{ + return getStatusString(mDesc, status); +} + +//static +std::string LLProcess::getStatusString(const std::string& desc, const Status& status) +{ + if (status.mState == UNSTARTED) + return desc + " was never launched"; + + if (status.mState == RUNNING) + return desc + " running"; + + if (status.mState == EXITED) + return STRINGIZE(desc << " exited with code " << status.mData); + + if (status.mState == KILLED) +#if LL_WINDOWS + return STRINGIZE(desc << " killed with exception " << std::hex << status.mData); +#else + return STRINGIZE(desc << " killed by signal " << status.mData); +#endif + + + return STRINGIZE(desc << " in unknown state " << status.mState << " (" << status.mData << ")"); +} + +// Classic-C-style APR callback +void LLProcess::status_callback(int reason, void* data, int status) +{ + // Our only role is to bounce this static method call back into object + // space. + static_cast(data)->handle_status(reason, status); +} + +#define tabent(symbol) { symbol, #symbol } +static struct ReasonCode +{ + int code; + const char* name; +} reasons[] = +{ + tabent(APR_OC_REASON_DEATH), + tabent(APR_OC_REASON_UNWRITABLE), + tabent(APR_OC_REASON_RESTART), + tabent(APR_OC_REASON_UNREGISTER), + tabent(APR_OC_REASON_LOST), + tabent(APR_OC_REASON_RUNNING) +}; +#undef tabent + +// Object-oriented callback +void LLProcess::handle_status(int reason, int status) +{ + { + // This odd appearance of LL_DEBUGS is just to bracket a lookup that will + // only be performed if in fact we're going to produce the log message. + LL_DEBUGS("LLProcess") << empty; + std::string reason_str; + BOOST_FOREACH(const ReasonCode& rcp, reasons) + { + if (reason == rcp.code) + { + reason_str = rcp.name; + break; + } + } + if (reason_str.empty()) + { + reason_str = STRINGIZE("unknown reason " << reason); + } + LL_CONT << mDesc << ": handle_status(" << reason_str << ", " << status << ")" << LL_ENDL; + } + + if (! (reason == APR_OC_REASON_DEATH || reason == APR_OC_REASON_LOST)) + { + // We're only interested in the call when the child terminates. + return; + } + + // Somewhat oddly, APR requires that you explicitly unregister even when + // it already knows the child has terminated. We must pass the same 'data' + // pointer as for the register() call, which was our 'this'. + apr_proc_other_child_unregister(this); + // We overload mStatus.mState to indicate whether the child is registered + // for APR callback: only RUNNING means registered. Track that we've + // unregistered. We know the child has terminated; might be EXITED or + // KILLED; refine below. + mStatus.mState = EXITED; + +// wi->rv = apr_proc_wait(wi->child, &wi->rc, &wi->why, APR_NOWAIT); + // It's just wrong to call apr_proc_wait() here. The only way APR knows to + // call us with APR_OC_REASON_DEATH is that it's already reaped this child + // process, so calling wait() will only produce "huh?" from the OS. We + // must rely on the status param passed in, which unfortunately comes + // straight from the OS wait() call, which means we have to decode it by + // hand. + mStatus = interpret_status(status); + LL_INFOS("LLProcess") << getStatusString() << LL_ENDL; } LLProcess::id LLProcess::getProcessID() const { - return mProcessID; + return mProcess.pid; } LLProcess::handle LLProcess::getProcessHandle() const { - return mProcessHandle; +#if LL_WINDOWS + return mProcess.hproc; +#else + return mProcess.pid; +#endif } std::ostream& operator<<(std::ostream& out, const LLProcess::Params& params) @@ -178,77 +454,15 @@ private: LLProcess::handle mJob; }; -void LLProcess::launch(const LLSDOrParams& params) +void LLProcess::autokill() { - PROCESS_INFORMATION pinfo; - STARTUPINFOA sinfo = { sizeof(sinfo) }; - - // LLProcess::create()'s caller passes a Unix-style array of strings for - // command-line arguments. Our caller can and should expect that these will be - // passed to the child process as individual arguments, regardless of content - // (e.g. embedded spaces). But because Windows invokes any child process with - // a single command-line string, this means we must quote each argument behind - // the scenes. - std::string args = LLStringUtil::quote(params.executable); - BOOST_FOREACH(const std::string& arg, params.args) - { - args += " "; - args += LLStringUtil::quote(arg); - } - - // So retarded. Windows requires that the second parameter to - // CreateProcessA be a writable (non-const) string... - std::vector args2(args.begin(), args.end()); - args2.push_back('\0'); - - // Convert wrapper to a real std::string so we can use c_str(); but use a - // named variable instead of a temporary so c_str() pointer remains valid. - std::string cwd(params.cwd); - const char * working_directory = 0; - if (! cwd.empty()) - working_directory = cwd.c_str(); - - // It's important to pass CREATE_BREAKAWAY_FROM_JOB because Windows 7 et - // al. tend to implicitly launch new processes already bound to a job. From - // http://msdn.microsoft.com/en-us/library/windows/desktop/ms681949%28v=vs.85%29.aspx : - // "The process must not already be assigned to a job; if it is, the - // function fails with ERROR_ACCESS_DENIED." ... - // "If the process is being monitored by the Program Compatibility - // Assistant (PCA), it is placed into a compatibility job. Therefore, the - // process must be created using CREATE_BREAKAWAY_FROM_JOB before it can - // be placed in another job." - if( ! CreateProcessA(NULL, // lpApplicationName - &args2[0], // lpCommandLine - NULL, // lpProcessAttributes - NULL, // lpThreadAttributes - FALSE, // bInheritHandles - CREATE_BREAKAWAY_FROM_JOB, // dwCreationFlags - NULL, // lpEnvironment - working_directory, // lpCurrentDirectory - &sinfo, // lpStartupInfo - &pinfo ) ) // lpProcessInformation - { - throw LLProcessError(WindowsErrorString("CreateProcessA")); - } - - // CloseHandle(pinfo.hProcess); // stops leaks - nothing else - mProcessID = pinfo.dwProcessId; - mProcessHandle = pinfo.hProcess; - CloseHandle(pinfo.hThread); // stops leaks - nothing else - - mDesc = STRINGIZE(LLStringUtil::quote(params.executable) << " (" << mProcessID << ')'); - LL_INFOS("LLProcess") << "Launched " << params << " (" << mProcessID << ")" << LL_ENDL; - - // Now associate the new child process with our Job Object -- unless - // autokill is false, i.e. caller asserts the child should persist. - if (params.autokill) - { - LLJob::instance().assignProcess(mDesc, mProcessHandle); -} + LLJob::instance().assignProcess(mDesc, mProcess.hproc); } LLProcess::handle LLProcess::isRunning(handle h, const std::string& desc) { + // This direct Windows implementation is because we have no access to the + // apr_proc_t struct: we expect it's been destroyed. if (! h) return 0; @@ -258,22 +472,44 @@ LLProcess::handle LLProcess::isRunning(handle h, const std::string& desc) // the process has completed. if (! desc.empty()) { - LL_INFOS("LLProcess") << desc << " terminated" << LL_ENDL; + DWORD status = 0; + if (! GetExitCodeProcess(h, &status)) + { + LL_WARNS("LLProcess") << desc << " terminated, but " + << WindowsErrorString("GetExitCodeProcess()") << LL_ENDL; + } + { + LL_INFOS("LLProcess") << getStatusString(desc, interpret_status(status)) + << LL_ENDL; + } } + CloseHandle(h); return 0; } return h; } -bool LLProcess::kill(void) +static LLProcess::Status interpret_status(int status) { - if (! mProcessHandle) - return false; + LLProcess::Status result; + + // This bit of code is cribbed from apr/threadproc/win32/proc.c, a + // function (unfortunately static) called why_from_exit_code(): + /* See WinNT.h STATUS_ACCESS_VIOLATION and family for how + * this class of failures was determined + */ + if ((status & 0xFFFF0000) == 0xC0000000) + { + result.mState = KILLED; + } + else + { + result.mState = EXITED; + } + result.mData = status; - LL_INFOS("LLProcess") << "killing " << mDesc << LL_ENDL; - TerminateProcess(mProcessHandle, 0); - return ! isRunning(); + return result; } /// GetLastError()/FormatMessage() boilerplate @@ -315,98 +551,91 @@ static std::string WindowsErrorString(const std::string& operation) #include #include +void LLProcess::autokill() +{ + // What we ought to do here is to: + // 1. create a unique process group and run all autokill children in that + // group (see https://jira.secondlife.com/browse/SWAT-563); + // 2. figure out a way to intercept control when the viewer exits -- + // gracefully or not; + // 3. when the viewer exits, kill off the aforementioned process group. + + // It's point 2 that's troublesome. Although I've seen some signal- + // handling logic in the Posix viewer code, I haven't yet found any bit of + // code that's run no matter how the viewer exits (a try/finally for the + // whole process, as it were). +} + // Attempt to reap a process ID -- returns true if the process has exited and been reaped, false otherwise. -static bool reap_pid(pid_t pid) +static bool reap_pid(pid_t pid, LLProcess::Status* pstatus=NULL) { - pid_t wait_result = ::waitpid(pid, NULL, WNOHANG); + LLProcess::Status dummy; + if (! pstatus) + { + // If caller doesn't want to see Status, give us a target anyway so we + // don't have to have a bunch of conditionals. + pstatus = &dummy; + } + + int status = 0; + pid_t wait_result = ::waitpid(pid, &status, WNOHANG); if (wait_result == pid) { + *pstatus = interpret_status(status); return true; } - if (wait_result == -1 && errno == ECHILD) + if (wait_result == 0) { - // No such process -- this may mean we're ignoring SIGCHILD. - return true; + pstatus->mState = LLProcess::RUNNING; + pstatus->mData = 0; + return false; } - - return false; -} -void LLProcess::launch(const LLSDOrParams& params) -{ - // flush all buffers before the child inherits them - ::fflush(NULL); + // Clear caller's Status block; caller must interpret UNSTARTED to mean + // "if this PID was ever valid, it no longer is." + *pstatus = LLProcess::Status(); - pid_t child = vfork(); - if (child == 0) + // We've dealt with the success cases: we were able to reap the child + // (wait_result == pid) or it's still running (wait_result == 0). It may + // be that the child terminated but didn't hang around long enough for us + // to reap. In that case we still have no Status to report, but we can at + // least state that it's not running. + if (wait_result == -1 && errno == ECHILD) { - // child process - - std::string cwd(params.cwd); - if (! cwd.empty()) - { - // change to the desired child working directory - if (::chdir(cwd.c_str())) - { - // chdir failed - LL_WARNS("LLProcess") << "could not chdir(\"" << cwd << "\")" << LL_ENDL; - // pointless to throw; this is child process... - _exit(248); - } - } - - // create an argv vector for the child process - std::vector fake_argv; - - // add the executable path - std::string executable(params.executable); - fake_argv.push_back(executable.c_str()); - - // and any arguments - std::vector args(params.args.begin(), params.args.end()); - BOOST_FOREACH(const std::string& arg, args) - { - fake_argv.push_back(arg.c_str()); - } - - // terminate with a null pointer - fake_argv.push_back(NULL); - - ::execv(executable.c_str(), const_cast(&fake_argv[0])); - - // If we reach this point, the exec failed. - LL_WARNS("LLProcess") << "failed to launch: "; - BOOST_FOREACH(const char* arg, fake_argv) - { - LL_CONT << arg << ' '; - } - LL_CONT << LL_ENDL; - // Use _exit() instead of exit() per the vfork man page. Exit with a - // distinctive rc: someday soon we'll be able to retrieve it, and it - // would be nice to be able to tell that the child process failed! - _exit(249); + // No such process -- this may mean we're ignoring SIGCHILD. + return true; } - // parent process - mProcessID = child; - mProcessHandle = child; - - mDesc = STRINGIZE(LLStringUtil::quote(params.executable) << " (" << mProcessID << ')'); - LL_INFOS("LLProcess") << "Launched " << params << " (" << mProcessID << ")" << LL_ENDL; + // Uh, should never happen?! + LL_WARNS("LLProcess") << "LLProcess::reap_pid(): waitpid(" << pid << ") returned " + << wait_result << "; not meaningful?" << LL_ENDL; + // If caller is looping until this pid terminates, and if we can't find + // out, better to break the loop than to claim it's still running. + return true; } LLProcess::id LLProcess::isRunning(id pid, const std::string& desc) { + // This direct Posix implementation is because we have no access to the + // apr_proc_t struct: we expect it's been destroyed. if (! pid) return 0; // Check whether the process has exited, and reap it if it has. - if(reap_pid(pid)) + LLProcess::Status status; + if(reap_pid(pid, &status)) { // the process has exited. if (! desc.empty()) { - LL_INFOS("LLProcess") << desc << " terminated" << LL_ENDL; + std::string statstr(desc + " apparently terminated: no status available"); + // We don't just pass UNSTARTED to getStatusString() because, in + // the context of reap_pid(), that state has special meaning. + if (status.mState != UNSTARTED) + { + statstr = getStatusString(desc, status); + } + LL_INFOS("LLProcess") << statstr << LL_ENDL; } return 0; } @@ -414,18 +643,27 @@ LLProcess::id LLProcess::isRunning(id pid, const std::string& desc) return pid; } -bool LLProcess::kill(void) +static LLProcess::Status interpret_status(int status) { - if (! mProcessID) - return false; + LLProcess::Status result; - // Try to kill the process. We'll do approximately the same thing whether - // the kill returns an error or not, so we ignore the result. - LL_INFOS("LLProcess") << "killing " << mDesc << LL_ENDL; - (void)::kill(mProcessID, SIGTERM); + if (WIFEXITED(status)) + { + result.mState = LLProcess::EXITED; + result.mData = WEXITSTATUS(status); + } + else if (WIFSIGNALED(status)) + { + result.mState = LLProcess::KILLED; + result.mData = WTERMSIG(status); + } + else // uh, shouldn't happen? + { + result.mState = LLProcess::EXITED; + result.mData = status; // someone else will have to decode + } - // This will have the side-effect of reaping the zombie if the process has exited. - return ! isRunning(); + return result; } /*==========================================================================*| diff --git a/indra/llcommon/llprocess.h b/indra/llcommon/llprocess.h index 8a842589ec..689f8aedab 100644 --- a/indra/llcommon/llprocess.h +++ b/indra/llcommon/llprocess.h @@ -29,6 +29,7 @@ #include "llinitparam.h" #include "llsdparam.h" +#include "apr_thread_proc.h" #include #include #include // std::ostream @@ -95,13 +96,52 @@ public: static LLProcessPtr create(const LLSDOrParams& params); virtual ~LLProcess(); - // isRunning isn't const because, if child isn't running, it clears stored - // process ID + // isRunning() isn't const because, when child terminates, it sets stored + // Status bool isRunning(void); - + + /** + * State of child process + */ + enum state + { + UNSTARTED, ///< initial value, invisible to consumer + RUNNING, ///< child process launched + EXITED, ///< child process terminated voluntarily + KILLED ///< child process terminated involuntarily + }; + + /** + * Status info + */ + struct Status + { + Status(): + mState(UNSTARTED), + mData(0) + {} + + state mState; ///< @see state + /** + * - for mState == EXITED: mData is exit() code + * - for mState == KILLED: mData is signal number (Posix) + * - otherwise: mData is undefined + */ + int mData; + }; + + /// Status query + Status getStatus(); + /// English Status string query, for logging etc. + std::string getStatusString(); + /// English Status string query for previously-captured Status + std::string getStatusString(const Status& status); + /// static English Status string query + static std::string getStatusString(const std::string& desc, const Status& status); + // Attempt to kill the process -- returns true if the process is no longer running when it returns. // Note that even if this returns false, the process may exit some time after it's called. - bool kill(void); + bool kill(const std::string& who=""); #if LL_WINDOWS typedef int id; ///< as returned by getProcessID() @@ -133,18 +173,28 @@ public: * a whole set of operations supported on freestanding @c handle values. * New functionality should be added as nonstatic members operating on * the same data as getProcessHandle(). + * + * In particular, if child termination is detected by static isRunning() + * rather than by nonstatic isRunning(), the LLProcess object won't be + * aware of the child's changed status and may encounter OS errors trying + * to obtain it. static isRunning() is only intended for after the + * launching LLProcess object has been destroyed. */ static handle isRunning(handle, const std::string& desc=""); private: /// constructor is private: use create() instead LLProcess(const LLSDOrParams& params); - void launch(const LLSDOrParams& params); + void autokill(); + // Classic-C-style APR callback + static void status_callback(int reason, void* data, int status); + // Object-oriented callback + void handle_status(int reason, int status); std::string mDesc; - id mProcessID; - handle mProcessHandle; + apr_proc_t mProcess; bool mAutokill; + Status mStatus; }; /// for logging diff --git a/indra/llcommon/tests/llprocess_test.cpp b/indra/llcommon/tests/llprocess_test.cpp index 4ad45bdf27..60ed12ad6a 100644 --- a/indra/llcommon/tests/llprocess_test.cpp +++ b/indra/llcommon/tests/llprocess_test.cpp @@ -630,7 +630,7 @@ namespace tut // Destroy the LLProcess, which should kill the child. } // wait for the script to terminate... one way or another. - while (LLProcess::isRunning(phandle)) + while (LLProcess::isRunning(phandle, "kill() script")) { sleep(1); } @@ -643,7 +643,7 @@ namespace tut template<> template<> void object::test<6>() { - set_test_name("autokill"); + set_test_name("autokill=false"); NamedTempFile from("from", "not started"); NamedTempFile to("to", ""); LLProcess::handle phandle(0); @@ -695,7 +695,7 @@ namespace tut outf << "go"; } // flush and close. // now wait for the script to terminate... one way or another. - while (LLProcess::isRunning(phandle)) + while (LLProcess::isRunning(phandle, "autokill script")) { sleep(1); } -- cgit v1.2.3 From 219a010aaf4891fc2ab8480a2121b1244191c24d Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Tue, 7 Feb 2012 11:17:04 -0500 Subject: LLProcess::Status enum values need qualification in helper function. --- indra/llcommon/llprocess.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/llprocess.cpp b/indra/llcommon/llprocess.cpp index bc27002701..1305c1d764 100644 --- a/indra/llcommon/llprocess.cpp +++ b/indra/llcommon/llprocess.cpp @@ -501,11 +501,11 @@ static LLProcess::Status interpret_status(int status) */ if ((status & 0xFFFF0000) == 0xC0000000) { - result.mState = KILLED; + result.mState = LLProcess::KILLED; } else { - result.mState = EXITED; + result.mState = LLProcess::EXITED; } result.mData = status; -- cgit v1.2.3 From 5d2bb536324a906078b224bdc9697b368e96a6b6 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Tue, 7 Feb 2012 12:06:03 -0500 Subject: On Linux, #undef Status: we use that name for nested LLProcess struct. Apparently something in the Linux system header chain #defines a macro Status as 'int'. That's just Bad in C++ land. It should at the very least be a typedef! #undefining it in llprocess.h permits the viewer to build. --- indra/llcommon/llprocess.h | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'indra') diff --git a/indra/llcommon/llprocess.h b/indra/llcommon/llprocess.h index 689f8aedab..0de033c15b 100644 --- a/indra/llcommon/llprocess.h +++ b/indra/llcommon/llprocess.h @@ -37,6 +37,10 @@ #if LL_WINDOWS #define WIN32_LEAN_AND_MEAN #include // HANDLE (eye roll) +#elif LL_LINUX +#if defined(Status) +#undef Status +#endif #endif class LLProcess; -- cgit v1.2.3 From 32e11494ffde368b2ac166e16dc294d66a18492f Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Tue, 7 Feb 2012 12:28:57 -0500 Subject: Use os.path.normcase(os.path.normpath()) when comparing directories. Once again we've been bitten by comparison failure between "c:\somepath" and "C:\somepath". Normalize paths in both Python helper scripts to make that comparison more robust. --- indra/llcommon/tests/llprocess_test.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/tests/llprocess_test.cpp b/indra/llcommon/tests/llprocess_test.cpp index 60ed12ad6a..6d2292fb88 100644 --- a/indra/llcommon/tests/llprocess_test.cpp +++ b/indra/llcommon/tests/llprocess_test.cpp @@ -186,7 +186,7 @@ public: "from __future__ import with_statement\n" "import os.path, sys, tempfile\n" "with open(sys.argv[1], 'w') as f:\n" - " f.write(os.path.realpath(tempfile.mkdtemp()))\n")) + " f.write(os.path.normcase(os.path.normpath(os.path.realpath(tempfile.mkdtemp()))))\n")) {} ~NamedTempDir() @@ -513,7 +513,7 @@ namespace tut "from __future__ import with_statement\n" "import os, sys\n" "with open(sys.argv[1], 'w') as f:\n" - " f.write(os.getcwd())\n"); + " f.write(os.path.normcase(os.path.normpath(os.getcwd())))\n"); // Before running, call setWorkingDirectory() py.mParams.cwd = tempdir.getName(); ensure_equals("os.getcwd()", py.run_read(), tempdir.getName()); -- cgit v1.2.3 From 90a1b67cc43792e1ca0047eaca51530aa14e134c Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Thu, 9 Feb 2012 15:22:24 -0500 Subject: Remove LLJob class: apr_procattr_autokill_set() should now handle. LLJob was vestigial code from before migrating Job Object support into APR. Also add APR signal-name string to getStatusString() output. --- indra/llcommon/llprocess.cpp | 70 +++----------------------------------------- 1 file changed, 4 insertions(+), 66 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/llprocess.cpp b/indra/llcommon/llprocess.cpp index 1305c1d764..7ccbdeed01 100644 --- a/indra/llcommon/llprocess.cpp +++ b/indra/llcommon/llprocess.cpp @@ -31,6 +31,7 @@ #include "llstring.h" #include "stringize.h" #include "llapr.h" +#include "apr_signal.h" #include #include @@ -274,10 +275,10 @@ std::string LLProcess::getStatusString(const std::string& desc, const Status& st #if LL_WINDOWS return STRINGIZE(desc << " killed with exception " << std::hex << status.mData); #else - return STRINGIZE(desc << " killed by signal " << status.mData); + return STRINGIZE(desc << " killed by signal " << status.mData + << " (" << apr_signal_description_get(status.mData) << ")"); #endif - return STRINGIZE(desc << " in unknown state " << status.mState << " (" << status.mData << ")"); } @@ -391,72 +392,9 @@ std::ostream& operator<<(std::ostream& out, const LLProcess::Params& params) static std::string WindowsErrorString(const std::string& operation); -/** - * Wrap a Windows Job Object for use in managing child-process lifespan. - * - * On Windows, we use a Job Object to constrain the lifespan of any - * autokill=true child process to the viewer's own lifespan: - * http://stackoverflow.com/questions/53208/how-do-i-automatically-destroy-child-processes-in-windows - * (thanks Richard!). - * - * We manage it using an LLSingleton for a couple of reasons: - * - * # Lazy initialization: if some viewer session never launches a child - * process, we should never have to create a Job Object. - * # Cross-DLL support: be wary of C++ statics when multiple DLLs are - * involved. - */ -class LLJob: public LLSingleton -{ -public: - void assignProcess(const std::string& prog, LLProcess::handle hProcess) - { - // If we never managed to initialize this Job Object, can't use it -- - // but don't keep spamming the log, we already emitted warnings when - // we first tried to create. - if (! mJob) - return; - - if (! AssignProcessToJobObject(mJob, hProcess)) - { - LL_WARNS("LLProcess") << WindowsErrorString(STRINGIZE("AssignProcessToJobObject(" - << prog << ")")) << LL_ENDL; - } - } - -private: - friend class LLSingleton; - LLJob(): - mJob(0) - { - mJob = CreateJobObject(NULL, NULL); - if (! mJob) - { - LL_WARNS("LLProcess") << WindowsErrorString("CreateJobObject()") << LL_ENDL; - return; - } - - JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 }; - - // Configure all child processes associated with this new job object - // to terminate when the calling process (us!) terminates. - jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; - if (! SetInformationJobObject(mJob, JobObjectExtendedLimitInformation, &jeli, sizeof(jeli))) - { - LL_WARNS("LLProcess") << WindowsErrorString("SetInformationJobObject()") << LL_ENDL; - // This Job Object is useless to us - CloseHandle(mJob); - // prevent assignProcess() from trying to use it - mJob = 0; - } - } - - LLProcess::handle mJob; -}; - void LLProcess::autokill() { - LLJob::instance().assignProcess(mDesc, mProcess.hproc); + // hopefully now handled by apr_procattr_autokill_set() } LLProcess::handle LLProcess::isRunning(handle h, const std::string& desc) -- cgit v1.2.3 From 60e39343b17f29c65e8a60a415f7ed83ff069a12 Mon Sep 17 00:00:00 2001 From: Kitty Barnett Date: Tue, 14 Feb 2012 21:48:22 +0100 Subject: STORM-276 Reworked the spell check preferences to be more robust and less error-prone --- indra/llui/llspellcheck.cpp | 20 +++- indra/llui/llspellcheck.h | 14 ++- indra/newview/llfloaterpreference.cpp | 121 +++++++++++++-------- indra/newview/llfloaterpreference.h | 2 +- .../xui/en/panel_preferences_spellcheck.xml | 4 + 5 files changed, 104 insertions(+), 57 deletions(-) (limited to 'indra') diff --git a/indra/llui/llspellcheck.cpp b/indra/llui/llspellcheck.cpp index 65207144f8..46df44cdba 100644 --- a/indra/llui/llspellcheck.cpp +++ b/indra/llui/llspellcheck.cpp @@ -41,6 +41,7 @@ static const std::string DICT_DIR = "dictionaries"; static const std::string DICT_CUSTOM_SUFFIX = "_custom"; static const std::string DICT_IGNORE_SUFFIX = "_ignore"; +LLSD LLSpellChecker::sDictMap; LLSpellChecker::settings_change_signal_t LLSpellChecker::sSettingsChangeSignal; LLSpellChecker::LLSpellChecker() @@ -86,9 +87,10 @@ S32 LLSpellChecker::getSuggestions(const std::string& word, std::vector class Hunspell; -class LLSpellChecker : public LLSingleton +class LLSpellChecker : public LLSingleton, public LLInitClass { friend class LLSingleton; + friend class LLInitClass; protected: LLSpellChecker(); ~LLSpellChecker(); @@ -52,28 +54,30 @@ public: typedef std::list dict_list_t; const std::string& getActiveDictionary() const { return mDictName; } - const LLSD getDictionaryData(const std::string& dict_name) const; - const LLSD& getDictionaryMap() const { return mDictMap; } const dict_list_t& getSecondaryDictionaries() const { return mDictSecondary; } - void refreshDictionaryMap(); void setSecondaryDictionaries(dict_list_t dict_list); static const std::string getDictionaryAppPath(); static const std::string getDictionaryUserPath(); + static const LLSD getDictionaryData(const std::string& dict_name); + static const LLSD& getDictionaryMap() { return sDictMap; } static bool getUseSpellCheck(); + static void refreshDictionaryMap(); static void setUseSpellCheck(const std::string& dict_name); typedef boost::signals2::signal settings_change_signal_t; static boost::signals2::connection setSettingsChangeCallback(const settings_change_signal_t::slot_type& cb); +protected: + static void initClass(); protected: Hunspell* mHunspell; std::string mDictName; std::string mDictFile; - LLSD mDictMap; dict_list_t mDictSecondary; std::vector mIgnoreList; + static LLSD sDictMap; static settings_change_signal_t sSettingsChangeSignal; }; diff --git a/indra/newview/llfloaterpreference.cpp b/indra/newview/llfloaterpreference.cpp index 29b07d2479..c41488ce91 100755 --- a/indra/newview/llfloaterpreference.cpp +++ b/indra/newview/llfloaterpreference.cpp @@ -448,6 +448,8 @@ BOOL LLFloaterPreference::postBuild() getChild("language_combobox")->setCommitCallback(boost::bind(&LLFloaterPreference::onLanguageChange, this)); + gSavedSettings.getControl("SpellCheck")->getSignal()->connect(boost::bind(&LLFloaterPreference::refreshDictLists, this, false)); + getChild("combo_spellcheck_dict")->setCommitCallback(boost::bind(&LLFloaterPreference::refreshDictLists, this, false)); getChild("btn_spellcheck_moveleft")->setCommitCallback(boost::bind(&LLFloaterPreference::onClickDictMove, this, "list_spellcheck_active", "list_spellcheck_available")); getChild("btn_spellcheck_moveright")->setCommitCallback(boost::bind(&LLFloaterPreference::onClickDictMove, this, "list_spellcheck_available", "list_spellcheck_active")); @@ -585,14 +587,19 @@ void LLFloaterPreference::apply() if (hasChild("check_spellcheck"), TRUE) { - LLScrollListCtrl* list_ctrl = findChild("list_spellcheck_active"); - std::vector list_items = list_ctrl->getAllData(); - std::list list_dict; - list_dict.push_back(LLSpellChecker::instance().getActiveDictionary()); - for (std::vector::const_iterator item_it = list_items.begin(); item_it != list_items.end(); ++item_it) - list_dict.push_back((*item_it)->getColumn(0)->getValue().asString()); + LLComboBox* dict_combo = findChild("combo_spellcheck_dict"); + const std::string dict_name = dict_combo->getSelectedItemLabel(); + if (!dict_name.empty()) + { + list_dict.push_back(dict_name); + + LLScrollListCtrl* list_ctrl = findChild("list_spellcheck_active"); + std::vector list_items = list_ctrl->getAllData(); + for (std::vector::const_iterator item_it = list_items.begin(); item_it != list_items.end(); ++item_it) + list_dict.push_back((*item_it)->getColumn(0)->getValue().asString()); + } gSavedSettings.setString("SpellCheckDictionary", boost::join(list_dict, ",")); } @@ -706,7 +713,7 @@ void LLFloaterPreference::onOpen(const LLSD& key) // Load (double-)click to walk/teleport settings. updateClickActionControls(); - buildDictLists(); + refreshDictLists(true); // Enabled/disabled popups, might have been changed by user actions // while preferences floater was closed. @@ -970,58 +977,80 @@ void LLFloaterPreference::refreshSkin(void* data) self->getChild("skin_selection", true)->setValue(sSkin); } -void LLFloaterPreference::buildDictLists() +void LLFloaterPreference::refreshDictLists(bool from_settings) { + bool enabled = gSavedSettings.getBOOL("SpellCheck"); + getChild("btn_spellcheck_moveleft")->setEnabled(enabled); + getChild("btn_spellcheck_moveright")->setEnabled(enabled); + + // Populate the dictionary combobox LLComboBox* dict_combo = findChild("combo_spellcheck_dict"); + std::string dict_cur = dict_combo->getSelectedItemLabel(); + if ((dict_cur.empty() || from_settings) && (LLSpellChecker::getUseSpellCheck())) + dict_cur = LLSpellChecker::instance().getActiveDictionary(); dict_combo->clearRows(); + dict_combo->setEnabled(enabled); - LLScrollListCtrl* active_ctrl = findChild("list_spellcheck_active"); - active_ctrl->clearRows(); + const LLSD& dict_map = LLSpellChecker::getDictionaryMap(); + if (dict_map.size()) + { + for (LLSD::array_const_iterator dict_it = dict_map.beginArray(); dict_it != dict_map.endArray(); ++dict_it) + { + const LLSD& dict = *dict_it; + if ( (dict["installed"].asBoolean()) && (dict.has("language")) ) + dict_combo->add(dict["language"].asString()); + } + if (!dict_combo->selectByValue(dict_cur)) + dict_combo->clear(); + } + // Populate the available and active dictionary list LLScrollListCtrl* avail_ctrl = findChild("list_spellcheck_available"); - avail_ctrl->clearRows(); + LLScrollListCtrl* active_ctrl = findChild("list_spellcheck_active"); - if (LLSpellChecker::getUseSpellCheck()) + LLSpellChecker::dict_list_t active_list; + if ( ((!avail_ctrl->getItemCount()) && (!active_ctrl->getItemCount())) || (from_settings) ) { - // Populate the main dictionary combobox - const LLSD& dict_map = LLSpellChecker::instance().getDictionaryMap(); - if (dict_map.size()) + if (LLSpellChecker::getUseSpellCheck()) + active_list = LLSpellChecker::instance().getSecondaryDictionaries(); + } + else + { + std::vector active_items = active_ctrl->getAllData(); + for (std::vector::const_iterator item_it = active_items.begin(); item_it != active_items.end(); ++item_it) { - for (LLSD::array_const_iterator dict_it = dict_map.beginArray(); dict_it != dict_map.endArray(); ++dict_it) - { - const LLSD& dict = *dict_it; - if ( (dict["installed"].asBoolean()) && (dict.has("language")) ) - dict_combo->add(dict["language"].asString()); - } - dict_combo->selectByValue(LLSpellChecker::instance().getActiveDictionary()); + std::string dict = (*item_it)->getColumn(0)->getValue().asString(); + if (dict_cur != dict) + active_list.push_back(dict); } + } - LLSD row; - row["columns"][0]["column"] = "name"; - row["columns"][0]["font"]["name"] = "SANSSERIF_SMALL"; - row["columns"][0]["font"]["style"] = "NORMAL"; - - // Populate the active dictionary list - LLSpellChecker::dict_list_t active_list = LLSpellChecker::instance().getSecondaryDictionaries(); - active_ctrl->sortByColumnIndex(0, true); - for (LLSpellChecker::dict_list_t::const_iterator it = active_list.begin(); it != active_list.end(); ++it) - { - row["columns"][0]["value"] = *it; - active_ctrl->addElement(row); - } - active_list.push_back(LLSpellChecker::instance().getActiveDictionary()); + LLSD row; + row["columns"][0]["column"] = "name"; + row["columns"][0]["font"]["name"] = "SANSSERIF_SMALL"; + row["columns"][0]["font"]["style"] = "NORMAL"; - // Populate the available dictionary list - avail_ctrl->sortByColumnIndex(0, true); - for (LLSD::array_const_iterator dict_it = dict_map.beginArray(); dict_it != dict_map.endArray(); ++dict_it) + active_ctrl->clearRows(); + active_ctrl->setEnabled(enabled); + active_ctrl->sortByColumnIndex(0, true); + for (LLSpellChecker::dict_list_t::const_iterator it = active_list.begin(); it != active_list.end(); ++it) + { + row["columns"][0]["value"] = *it; + active_ctrl->addElement(row); + } + active_list.push_back(dict_cur); + + avail_ctrl->clearRows(); + avail_ctrl->setEnabled(enabled); + avail_ctrl->sortByColumnIndex(0, true); + for (LLSD::array_const_iterator dict_it = dict_map.beginArray(); dict_it != dict_map.endArray(); ++dict_it) + { + const LLSD& dict = *dict_it; + if ( (dict["installed"].asBoolean()) && (dict.has("language")) && + (active_list.end() == std::find(active_list.begin(), active_list.end(), dict["language"].asString())) ) { - const LLSD& dict = *dict_it; - if ( (dict["installed"].asBoolean()) && (dict.has("language")) && - (active_list.end() == std::find(active_list.begin(), active_list.end(), dict["language"].asString())) ) - { - row["columns"][0]["value"] = dict["language"].asString(); - avail_ctrl->addElement(row); - } + row["columns"][0]["value"] = dict["language"].asString(); + avail_ctrl->addElement(row); } } } diff --git a/indra/newview/llfloaterpreference.h b/indra/newview/llfloaterpreference.h index cd258b5614..f75f71cc3d 100644 --- a/indra/newview/llfloaterpreference.h +++ b/indra/newview/llfloaterpreference.h @@ -161,8 +161,8 @@ public: void applyUIColor(LLUICtrl* ctrl, const LLSD& param); void getUIColor(LLUICtrl* ctrl, const LLSD& param); - void buildDictLists(); void buildPopupLists(); + void refreshDictLists(bool from_settings); static void refreshSkin(void* data); private: static std::string sSkin; diff --git a/indra/newview/skins/default/xui/en/panel_preferences_spellcheck.xml b/indra/newview/skins/default/xui/en/panel_preferences_spellcheck.xml index 9b5d429846..f1b16c5d0d 100644 --- a/indra/newview/skins/default/xui/en/panel_preferences_spellcheck.xml +++ b/indra/newview/skins/default/xui/en/panel_preferences_spellcheck.xml @@ -86,6 +86,7 @@ Active Date: Tue, 14 Feb 2012 21:57:58 +0100 Subject: STORM-276 FIXED Typing in an LLTextEditor freezes the viewer --- indra/llui/lltextbase.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/llui/lltextbase.cpp b/indra/llui/lltextbase.cpp index 2231d9b983..2d7516a1cd 100644 --- a/indra/llui/lltextbase.cpp +++ b/indra/llui/lltextbase.cpp @@ -552,7 +552,7 @@ void LLTextBase::drawText() const LLWString& wstrText = getWText(); mMisspellRanges.clear(); - segment_set_t::iterator seg_it = getSegIterContaining(start); + segment_set_t::const_iterator seg_it = getSegIterContaining(start); while (mSegments.end() != seg_it) { LLTextSegmentPtr text_segment = *seg_it; @@ -673,7 +673,10 @@ void LLTextBase::drawText() { // Skip the current word if the user is still busy editing it if ( (!mSpellCheckTimer.hasExpired()) && (misspell_it->first <= (U32)mCursorPos) && (misspell_it->second >= (U32)mCursorPos) ) + { + ++misspell_it; continue; + } S32 squiggle_start = 0, squiggle_end = 0, pony = 0; cur_segment->getDimensions(seg_start - cur_segment->getStart(), misspell_it->first - seg_start, squiggle_start, pony); -- cgit v1.2.3 From 9c792e337695b904e4f52fce83b293a2e97fdeaf Mon Sep 17 00:00:00 2001 From: Kitty Barnett Date: Tue, 14 Feb 2012 22:33:28 +0100 Subject: STORM-276 FIXED Misspellings that span multiple lines don't have their squiggly lines drawn correctly --- indra/llui/lltextbase.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'indra') diff --git a/indra/llui/lltextbase.cpp b/indra/llui/lltextbase.cpp index 2d7516a1cd..ce405cd4a4 100644 --- a/indra/llui/lltextbase.cpp +++ b/indra/llui/lltextbase.cpp @@ -678,9 +678,10 @@ void LLTextBase::drawText() continue; } + U32 misspell_start = llmax(misspell_it->first, seg_start), misspell_end = llmin(misspell_it->second, seg_end); S32 squiggle_start = 0, squiggle_end = 0, pony = 0; - cur_segment->getDimensions(seg_start - cur_segment->getStart(), misspell_it->first - seg_start, squiggle_start, pony); - cur_segment->getDimensions(misspell_it->first - cur_segment->getStart(), misspell_it->second - misspell_it->first, squiggle_end, pony); + cur_segment->getDimensions(seg_start - cur_segment->getStart(), misspell_start - seg_start, squiggle_start, pony); + cur_segment->getDimensions(misspell_start - cur_segment->getStart(), misspell_end - misspell_start, squiggle_end, pony); squiggle_start += text_rect.mLeft; pony = (squiggle_end + 3) / 6; -- cgit v1.2.3 From e615660823e680e824d2db0f1a59917597e64a13 Mon Sep 17 00:00:00 2001 From: Kitty Barnett Date: Thu, 9 Feb 2012 22:02:32 +0100 Subject: STORM-276 Differentiate between primary and secondary dictionaries --- indra/llui/llspellcheck.cpp | 6 ++---- indra/newview/llfloaterpreference.cpp | 2 +- 2 files changed, 3 insertions(+), 5 deletions(-) (limited to 'indra') diff --git a/indra/llui/llspellcheck.cpp b/indra/llui/llspellcheck.cpp index 46df44cdba..aa39e21a96 100644 --- a/indra/llui/llspellcheck.cpp +++ b/indra/llui/llspellcheck.cpp @@ -122,9 +122,7 @@ void LLSpellChecker::refreshDictionaryMap() tmp_app_path = (sdDict.has("name")) ? app_path + sdDict["name"].asString() : LLStringUtil::null; tmp_user_path = (sdDict.has("name")) ? user_path + sdDict["name"].asString() : LLStringUtil::null; sdDict["installed"] = - (!tmp_app_path.empty()) && - ( ((gDirUtilp->fileExists(tmp_user_path + ".aff")) && (gDirUtilp->fileExists(tmp_user_path + ".dic"))) || - ((gDirUtilp->fileExists(tmp_app_path + ".aff")) && (gDirUtilp->fileExists(tmp_app_path + ".dic"))) ); + (!tmp_app_path.empty()) && ((gDirUtilp->fileExists(tmp_user_path + ".dic")) || (gDirUtilp->fileExists(tmp_app_path + ".dic"))); sdDict["has_custom"] = (!tmp_user_path.empty()) && (gDirUtilp->fileExists(tmp_user_path + DICT_CUSTOM_SUFFIX + ".dic")); sdDict["has_ignore"] = (!tmp_user_path.empty()) && (gDirUtilp->fileExists(tmp_user_path + DICT_IGNORE_SUFFIX + ".dic")); } @@ -243,7 +241,7 @@ void LLSpellChecker::initHunspell(const std::string& dict_name) } const LLSD dict_entry = (!dict_name.empty()) ? getDictionaryData(dict_name) : LLSD(); - if ( (!dict_entry.isDefined()) || (!dict_entry["installed"].asBoolean()) ) + if ( (!dict_entry.isDefined()) || (!dict_entry["installed"].asBoolean()) || (!dict_entry["is_primary"].asBoolean())) { sSettingsChangeSignal(); return; diff --git a/indra/newview/llfloaterpreference.cpp b/indra/newview/llfloaterpreference.cpp index c41488ce91..c444d2bb6f 100755 --- a/indra/newview/llfloaterpreference.cpp +++ b/indra/newview/llfloaterpreference.cpp @@ -997,7 +997,7 @@ void LLFloaterPreference::refreshDictLists(bool from_settings) for (LLSD::array_const_iterator dict_it = dict_map.beginArray(); dict_it != dict_map.endArray(); ++dict_it) { const LLSD& dict = *dict_it; - if ( (dict["installed"].asBoolean()) && (dict.has("language")) ) + if ( (dict["installed"].asBoolean()) && (dict["is_primary"].asBoolean()) && (dict.has("language")) ) dict_combo->add(dict["language"].asString()); } if (!dict_combo->selectByValue(dict_cur)) -- cgit v1.2.3 From b47994601bfd2bc240434eab4e3a255c38d535d1 Mon Sep 17 00:00:00 2001 From: Seth ProductEngine Date: Fri, 10 Feb 2012 01:52:08 +0200 Subject: MAINT-784 FIXED the inventory filter to be restarted when switching from 'Since Logoff' to 'Hours Ago' or 'Days Ago'. Fix: checking for !isSinceLogoff() ensures that the time filter increases from zero and becomes more restrictive. This happens because setting 'Since Logoff' resets the 'Hours Ago' and 'Days Ago' to zero. --- indra/newview/llinventoryfilter.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/newview/llinventoryfilter.cpp b/indra/newview/llinventoryfilter.cpp index d54bce4619..0485b04895 100644 --- a/indra/newview/llinventoryfilter.cpp +++ b/indra/newview/llinventoryfilter.cpp @@ -502,7 +502,7 @@ void LLInventoryFilter::setHoursAgo(U32 hours) bool are_date_limits_valid = mFilterOps.mMinDate == time_min() && mFilterOps.mMaxDate == time_max(); bool is_increasing = hours > mFilterOps.mHoursAgo; - bool is_increasing_from_zero = is_increasing && !mFilterOps.mHoursAgo; + bool is_increasing_from_zero = is_increasing && !mFilterOps.mHoursAgo && !isSinceLogoff(); // *NOTE: need to cache last filter time, in case filter goes stale BOOL less_restrictive = (are_date_limits_valid && ((is_increasing && mFilterOps.mHoursAgo)) || !hours); -- cgit v1.2.3 From 59bfc3f608bed806e03898b833a0fda9f95d42b9 Mon Sep 17 00:00:00 2001 From: Kitty Barnett Date: Sun, 25 Mar 2012 19:50:46 +0200 Subject: Minor fix for GCC --- indra/llui/lllineeditor.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'indra') diff --git a/indra/llui/lllineeditor.cpp b/indra/llui/lllineeditor.cpp index 42cfc4cae9..0dc381231d 100644 --- a/indra/llui/lllineeditor.cpp +++ b/indra/llui/lllineeditor.cpp @@ -1948,8 +1948,8 @@ void LLLineEditor::draw() gGL.color4ub(255, 0, 0, 200); while (pxStart < pxEnd) { - gl_line_2d(pxStart, text_bottom - 2, pxStart + 3, text_bottom + 1); - gl_line_2d(pxStart + 3, text_bottom + 1, pxStart + 6, text_bottom - 2); + gl_line_2d(pxStart, (S32)text_bottom - 2, pxStart + 3, (S32)text_bottom + 1); + gl_line_2d(pxStart + 3, (S32)text_bottom + 1, pxStart + 6, (S32)text_bottom - 2); pxStart += 6; } } -- cgit v1.2.3 From 2587f6d9d8167bb29491ff681dcd133eb28aba67 Mon Sep 17 00:00:00 2001 From: Kitty Barnett Date: Thu, 29 Mar 2012 18:25:48 +0200 Subject: Minor fix for GCC --- indra/newview/llappviewer.cpp | 3 ++- indra/newview/llviewercontrol.cpp | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) (limited to 'indra') diff --git a/indra/newview/llappviewer.cpp b/indra/newview/llappviewer.cpp index 5a68cd531e..fac5416aab 100644 --- a/indra/newview/llappviewer.cpp +++ b/indra/newview/llappviewer.cpp @@ -2502,7 +2502,8 @@ bool LLAppViewer::initConfiguration() if (gSavedSettings.getBOOL("SpellCheck")) { std::list dict_list; - boost::split(dict_list, gSavedSettings.getString("SpellCheckDictionary"), boost::is_any_of(std::string(","))); + std::string dict_setting = gSavedSettings.getString("SpellCheckDictionary"); + boost::split(dict_list, dict_setting, boost::is_any_of(std::string(","))); if (!dict_list.empty()) { LLSpellChecker::setUseSpellCheck(dict_list.front()); diff --git a/indra/newview/llviewercontrol.cpp b/indra/newview/llviewercontrol.cpp index 7b6dbfaa0b..d7168a401c 100644 --- a/indra/newview/llviewercontrol.cpp +++ b/indra/newview/llviewercontrol.cpp @@ -507,7 +507,8 @@ bool handleSpellCheckChanged() if (gSavedSettings.getBOOL("SpellCheck")) { std::list dict_list; - boost::split(dict_list, gSavedSettings.getString("SpellCheckDictionary"), boost::is_any_of(std::string(","))); + std::string dict_setting = gSavedSettings.getString("SpellCheckDictionary"); + boost::split(dict_list, dict_setting, boost::is_any_of(std::string(","))); if (!dict_list.empty()) { LLSpellChecker::setUseSpellCheck(dict_list.front()); -- cgit v1.2.3 From e60dac5ce486f55fe69949a6a3a2949d4f868193 Mon Sep 17 00:00:00 2001 From: Kitty Barnett Date: Thu, 29 Mar 2012 21:07:09 +0200 Subject: STORM-276 Added dictionaries.xml and the Second Life glossary dictionary (enabled by default) --- .../app_settings/dictionaries/dictionaries.xml | 45 ++++ indra/newview/app_settings/dictionaries/sl.dic | 226 +++++++++++++++++++++ indra/newview/app_settings/settings.xml | 2 +- 3 files changed, 272 insertions(+), 1 deletion(-) create mode 100644 indra/newview/app_settings/dictionaries/dictionaries.xml create mode 100644 indra/newview/app_settings/dictionaries/sl.dic (limited to 'indra') diff --git a/indra/newview/app_settings/dictionaries/dictionaries.xml b/indra/newview/app_settings/dictionaries/dictionaries.xml new file mode 100644 index 0000000000..0ba959766b --- /dev/null +++ b/indra/newview/app_settings/dictionaries/dictionaries.xml @@ -0,0 +1,45 @@ + + + + + name + en_gb + is_primary + 1 + language + English (United Kingdom) + + + name + en_us + is_primary + 1 + language + English (United States) + + + name + es_es + is_primary + 1 + language + Español (España) + + + name + pt_br + is_primary + 1 + language + Português (Brasil) + + + name + sl + is_primary + 0 + language + Second Life Glossary + + + diff --git a/indra/newview/app_settings/dictionaries/sl.dic b/indra/newview/app_settings/dictionaries/sl.dic new file mode 100644 index 0000000000..06decad74b --- /dev/null +++ b/indra/newview/app_settings/dictionaries/sl.dic @@ -0,0 +1,226 @@ +225 +account +aditi +adult +agent +agni +alpha +alt +animation +AR +asset +attachment +autoreturn +avatar +avie +baked +ban +banlines +banlist +BDSM +beacon +bling +block +blog +blogger +bodyparts +bot +box +build +busy +cache +cage +camp +campie +Catznip +chim +classified +client +coalesced +collar +collision +combat +community +concierge +conference +continent +contribution +coordinate +copy +covenant +CS +damage +damage-enabled +death +deed +detach +displayname +Dolphin +drama +drop +estate +event +face +facelight +favorites +FIC +Firestorm +flexible +flexiprim +floater +fly +flycam +FMOD +follower +forums +freebie +freeze +friendship +fullperm +furry +gadget +general +gesture +goo +grid +gridnaut +griefer +griefing +ground +group +GSLR +GUI +Havok +hippo +hippotropolis +home +homestead +host +HUD +IM +impostors +Imprudence +indra +infohub +inspector +inventory +invisiprim +inworld +island +item +JIRA +JPEG2000 +Kakadu +KDU +kick +L$ +lag +land +landmark +LDPW +liaison +library +limits +linden +LindeX +link +linkset +live +lock +log +machinima +mainland +mainlanders +map +marketplace +mature +media +mega +megaprim +mentor +mesh +minimap +mini-map +moderate +modify +mono +morph +MOTD +mouselook +mouseview +move +mute +neko +newbie +non-physical +notecard +NPIOF +object +occlusion +off-world +officer +offline +ogg +online +ONSR +openspace +orbiter +orientation +parcel +particles +partner +permission +PG +phantom +Phoenix +physics +pick +poofer +position +premium +prim +primitar +primitive +profile +quaternion +Radegast +region +relog +resi +resident +return +rez +rezday +RLV +RLVa +roleplay +run +ruth +script +sculpted +sculptie +sculpty +shout +sim +simulator +Singularity +skin +SLEX +SLurl +snapshot +stipend +telehub +teleport +terraform +texture +tier +TOS +transfer +unlink +username +UUID +vendor +viewer +walk +whisper +windlight diff --git a/indra/newview/app_settings/settings.xml b/indra/newview/app_settings/settings.xml index e15822ed1f..7dc06cda0e 100644 --- a/indra/newview/app_settings/settings.xml +++ b/indra/newview/app_settings/settings.xml @@ -12168,7 +12168,7 @@ Type String Value - English (United States) + English (United States),Second Life Glossary UseNewWalkRun -- cgit v1.2.3 From 5f32e6493ed4f8b9b480da857f487fa21f32bd64 Mon Sep 17 00:00:00 2001 From: Oz Linden Date: Fri, 30 Mar 2012 14:09:39 -0400 Subject: convert line endings on sl.dic for coding standards compliance --- indra/newview/app_settings/dictionaries/sl.dic | 452 ++++++++++++------------- 1 file changed, 226 insertions(+), 226 deletions(-) (limited to 'indra') diff --git a/indra/newview/app_settings/dictionaries/sl.dic b/indra/newview/app_settings/dictionaries/sl.dic index 06decad74b..57e9dd06cd 100644 --- a/indra/newview/app_settings/dictionaries/sl.dic +++ b/indra/newview/app_settings/dictionaries/sl.dic @@ -1,226 +1,226 @@ -225 -account -aditi -adult -agent -agni -alpha -alt -animation -AR -asset -attachment -autoreturn -avatar -avie -baked -ban -banlines -banlist -BDSM -beacon -bling -block -blog -blogger -bodyparts -bot -box -build -busy -cache -cage -camp -campie -Catznip -chim -classified -client -coalesced -collar -collision -combat -community -concierge -conference -continent -contribution -coordinate -copy -covenant -CS -damage -damage-enabled -death -deed -detach -displayname -Dolphin -drama -drop -estate -event -face -facelight -favorites -FIC -Firestorm -flexible -flexiprim -floater -fly -flycam -FMOD -follower -forums -freebie -freeze -friendship -fullperm -furry -gadget -general -gesture -goo -grid -gridnaut -griefer -griefing -ground -group -GSLR -GUI -Havok -hippo -hippotropolis -home -homestead -host -HUD -IM -impostors -Imprudence -indra -infohub -inspector -inventory -invisiprim -inworld -island -item -JIRA -JPEG2000 -Kakadu -KDU -kick -L$ -lag -land -landmark -LDPW -liaison -library -limits -linden -LindeX -link -linkset -live -lock -log -machinima -mainland -mainlanders -map -marketplace -mature -media -mega -megaprim -mentor -mesh -minimap -mini-map -moderate -modify -mono -morph -MOTD -mouselook -mouseview -move -mute -neko -newbie -non-physical -notecard -NPIOF -object -occlusion -off-world -officer -offline -ogg -online -ONSR -openspace -orbiter -orientation -parcel -particles -partner -permission -PG -phantom -Phoenix -physics -pick -poofer -position -premium -prim -primitar -primitive -profile -quaternion -Radegast -region -relog -resi -resident -return -rez -rezday -RLV -RLVa -roleplay -run -ruth -script -sculpted -sculptie -sculpty -shout -sim -simulator -Singularity -skin -SLEX -SLurl -snapshot -stipend -telehub -teleport -terraform -texture -tier -TOS -transfer -unlink -username -UUID -vendor -viewer -walk -whisper -windlight +225 +account +aditi +adult +agent +agni +alpha +alt +animation +AR +asset +attachment +autoreturn +avatar +avie +baked +ban +banlines +banlist +BDSM +beacon +bling +block +blog +blogger +bodyparts +bot +box +build +busy +cache +cage +camp +campie +Catznip +chim +classified +client +coalesced +collar +collision +combat +community +concierge +conference +continent +contribution +coordinate +copy +covenant +CS +damage +damage-enabled +death +deed +detach +displayname +Dolphin +drama +drop +estate +event +face +facelight +favorites +FIC +Firestorm +flexible +flexiprim +floater +fly +flycam +FMOD +follower +forums +freebie +freeze +friendship +fullperm +furry +gadget +general +gesture +goo +grid +gridnaut +griefer +griefing +ground +group +GSLR +GUI +Havok +hippo +hippotropolis +home +homestead +host +HUD +IM +impostors +Imprudence +indra +infohub +inspector +inventory +invisiprim +inworld +island +item +JIRA +JPEG2000 +Kakadu +KDU +kick +L$ +lag +land +landmark +LDPW +liaison +library +limits +linden +LindeX +link +linkset +live +lock +log +machinima +mainland +mainlanders +map +marketplace +mature +media +mega +megaprim +mentor +mesh +minimap +mini-map +moderate +modify +mono +morph +MOTD +mouselook +mouseview +move +mute +neko +newbie +non-physical +notecard +NPIOF +object +occlusion +off-world +officer +offline +ogg +online +ONSR +openspace +orbiter +orientation +parcel +particles +partner +permission +PG +phantom +Phoenix +physics +pick +poofer +position +premium +prim +primitar +primitive +profile +quaternion +Radegast +region +relog +resi +resident +return +rez +rezday +RLV +RLVa +roleplay +run +ruth +script +sculpted +sculptie +sculpty +shout +sim +simulator +Singularity +skin +SLEX +SLurl +snapshot +stipend +telehub +teleport +terraform +texture +tier +TOS +transfer +unlink +username +UUID +vendor +viewer +walk +whisper +windlight -- cgit v1.2.3 From 3af3d5e83c81ecfa77735e6811470d1aa0f705da Mon Sep 17 00:00:00 2001 From: Oz Linden Date: Fri, 30 Mar 2012 15:07:46 -0400 Subject: move all dictionaries to the prebuilt package, and install from there --- .../app_settings/dictionaries/dictionaries.xml | 45 ---- indra/newview/app_settings/dictionaries/sl.dic | 226 --------------------- indra/newview/viewer_manifest.py | 2 +- 3 files changed, 1 insertion(+), 272 deletions(-) delete mode 100644 indra/newview/app_settings/dictionaries/dictionaries.xml delete mode 100644 indra/newview/app_settings/dictionaries/sl.dic (limited to 'indra') diff --git a/indra/newview/app_settings/dictionaries/dictionaries.xml b/indra/newview/app_settings/dictionaries/dictionaries.xml deleted file mode 100644 index 0ba959766b..0000000000 --- a/indra/newview/app_settings/dictionaries/dictionaries.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - name - en_gb - is_primary - 1 - language - English (United Kingdom) - - - name - en_us - is_primary - 1 - language - English (United States) - - - name - es_es - is_primary - 1 - language - Español (España) - - - name - pt_br - is_primary - 1 - language - Português (Brasil) - - - name - sl - is_primary - 0 - language - Second Life Glossary - - - diff --git a/indra/newview/app_settings/dictionaries/sl.dic b/indra/newview/app_settings/dictionaries/sl.dic deleted file mode 100644 index 57e9dd06cd..0000000000 --- a/indra/newview/app_settings/dictionaries/sl.dic +++ /dev/null @@ -1,226 +0,0 @@ -225 -account -aditi -adult -agent -agni -alpha -alt -animation -AR -asset -attachment -autoreturn -avatar -avie -baked -ban -banlines -banlist -BDSM -beacon -bling -block -blog -blogger -bodyparts -bot -box -build -busy -cache -cage -camp -campie -Catznip -chim -classified -client -coalesced -collar -collision -combat -community -concierge -conference -continent -contribution -coordinate -copy -covenant -CS -damage -damage-enabled -death -deed -detach -displayname -Dolphin -drama -drop -estate -event -face -facelight -favorites -FIC -Firestorm -flexible -flexiprim -floater -fly -flycam -FMOD -follower -forums -freebie -freeze -friendship -fullperm -furry -gadget -general -gesture -goo -grid -gridnaut -griefer -griefing -ground -group -GSLR -GUI -Havok -hippo -hippotropolis -home -homestead -host -HUD -IM -impostors -Imprudence -indra -infohub -inspector -inventory -invisiprim -inworld -island -item -JIRA -JPEG2000 -Kakadu -KDU -kick -L$ -lag -land -landmark -LDPW -liaison -library -limits -linden -LindeX -link -linkset -live -lock -log -machinima -mainland -mainlanders -map -marketplace -mature -media -mega -megaprim -mentor -mesh -minimap -mini-map -moderate -modify -mono -morph -MOTD -mouselook -mouseview -move -mute -neko -newbie -non-physical -notecard -NPIOF -object -occlusion -off-world -officer -offline -ogg -online -ONSR -openspace -orbiter -orientation -parcel -particles -partner -permission -PG -phantom -Phoenix -physics -pick -poofer -position -premium -prim -primitar -primitive -profile -quaternion -Radegast -region -relog -resi -resident -return -rez -rezday -RLV -RLVa -roleplay -run -ruth -script -sculpted -sculptie -sculpty -shout -sim -simulator -Singularity -skin -SLEX -SLurl -snapshot -stipend -telehub -teleport -terraform -texture -tier -TOS -transfer -unlink -username -UUID -vendor -viewer -walk -whisper -windlight diff --git a/indra/newview/viewer_manifest.py b/indra/newview/viewer_manifest.py index 1b732676e4..a59b763910 100644 --- a/indra/newview/viewer_manifest.py +++ b/indra/newview/viewer_manifest.py @@ -92,7 +92,7 @@ class ViewerManifest(LLManifest): # ... and the entire windlight directory self.path("windlight") # ... and the pre-installed spell checking dictionaries - self.path("dictionaries") + self.path("../../packages/dictionaries", dst="dictionaries") self.end_prefix("app_settings") if self.prefix(src="character"): -- cgit v1.2.3 From 63196a9c08c94ced5bb9ff5b9e623564d956bcd8 Mon Sep 17 00:00:00 2001 From: Oz Linden Date: Tue, 10 Apr 2012 15:57:39 -0400 Subject: add hunspell libs --- indra/llui/CMakeLists.txt | 2 ++ 1 file changed, 2 insertions(+) (limited to 'indra') diff --git a/indra/llui/CMakeLists.txt b/indra/llui/CMakeLists.txt index 1377336bb4..2208a2f327 100644 --- a/indra/llui/CMakeLists.txt +++ b/indra/llui/CMakeLists.txt @@ -25,6 +25,7 @@ include_directories( ${LLVFS_INCLUDE_DIRS} ${LLXML_INCLUDE_DIRS} ${LLXUIXML_INCLUDE_DIRS} + ${LIBS_PREBUILD_DIR}/include/hunspell ) set(llui_SOURCE_FILES @@ -252,6 +253,7 @@ add_library (llui ${llui_SOURCE_FILES}) # Libraries on which this library depends, needed for Linux builds # Sort by high-level to low-level target_link_libraries(llui + ${HUNSPELL_LIBRARY} ${LLMESSAGE_LIBRARIES} ${LLRENDER_LIBRARIES} ${LLWINDOW_LIBRARIES} -- cgit v1.2.3 From 51ceacbb45802209c36c555c03eeeb2f5fd1d3b4 Mon Sep 17 00:00:00 2001 From: Oz Linden Date: Wed, 11 Apr 2012 12:14:35 -0400 Subject: fix ordering problem in libraries? --- indra/llui/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/llui/CMakeLists.txt b/indra/llui/CMakeLists.txt index 2208a2f327..d0fd37a5b4 100644 --- a/indra/llui/CMakeLists.txt +++ b/indra/llui/CMakeLists.txt @@ -253,7 +253,6 @@ add_library (llui ${llui_SOURCE_FILES}) # Libraries on which this library depends, needed for Linux builds # Sort by high-level to low-level target_link_libraries(llui - ${HUNSPELL_LIBRARY} ${LLMESSAGE_LIBRARIES} ${LLRENDER_LIBRARIES} ${LLWINDOW_LIBRARIES} @@ -263,6 +262,7 @@ target_link_libraries(llui ${LLXUIXML_LIBRARIES} ${LLXML_LIBRARIES} ${LLMATH_LIBRARIES} + ${HUNSPELL_LIBRARY} ${LLCOMMON_LIBRARIES} # must be after llimage, llwindow, llrender ) -- cgit v1.2.3 From cf370a8dcde5ae77c27aa4fdd105d399c60c3d53 Mon Sep 17 00:00:00 2001 From: Oz Linden Date: Wed, 11 Apr 2012 13:31:06 -0400 Subject: add hunspell libraries in unit test build --- indra/integration_tests/llui_libtest/CMakeLists.txt | 2 ++ 1 file changed, 2 insertions(+) (limited to 'indra') diff --git a/indra/integration_tests/llui_libtest/CMakeLists.txt b/indra/integration_tests/llui_libtest/CMakeLists.txt index 1180460f4b..ba6b318cb8 100644 --- a/indra/integration_tests/llui_libtest/CMakeLists.txt +++ b/indra/integration_tests/llui_libtest/CMakeLists.txt @@ -33,6 +33,7 @@ include_directories( ${LLWINDOW_INCLUDE_DIRS} ${LLXML_INCLUDE_DIRS} ${LLXUIXML_INCLUDE_DIRS} + ${LIBS_PREBUILD_DIR}/include/hunspell ) set(llui_libtest_SOURCE_FILES @@ -80,6 +81,7 @@ target_link_libraries(llui_libtest ${LLIMAGEJ2COJ_LIBRARIES} ${OS_LIBRARIES} ${GOOGLE_PERFTOOLS_LIBRARIES} + ${HUNSPELL_LIBRARY} ) if (WINDOWS) -- cgit v1.2.3 From 6d050cad618493b7881ea6d0073e64ba732b6352 Mon Sep 17 00:00:00 2001 From: Kitty Barnett Date: Fri, 10 Feb 2012 16:25:55 +0100 Subject: - fixed : Hunspell linking issues --- indra/cmake/CMakeLists.txt | 1 + indra/cmake/FindHUNSPELL.cmake | 38 ++++++++++++++++++++++++++++++++++++++ indra/cmake/Hunspell.cmake | 21 +++++++++++++++++++++ indra/newview/CMakeLists.txt | 1 + 4 files changed, 61 insertions(+) create mode 100644 indra/cmake/FindHUNSPELL.cmake create mode 100644 indra/cmake/Hunspell.cmake (limited to 'indra') diff --git a/indra/cmake/CMakeLists.txt b/indra/cmake/CMakeLists.txt index 279d577a27..9b836aac5f 100644 --- a/indra/cmake/CMakeLists.txt +++ b/indra/cmake/CMakeLists.txt @@ -37,6 +37,7 @@ set(cmake_SOURCE_FILES GLOD.cmake GStreamer010Plugin.cmake GooglePerfTools.cmake + Hunspell.cmake JPEG.cmake LLAddBuildTest.cmake LLAudio.cmake diff --git a/indra/cmake/FindHUNSPELL.cmake b/indra/cmake/FindHUNSPELL.cmake new file mode 100644 index 0000000000..d411bdb9e5 --- /dev/null +++ b/indra/cmake/FindHUNSPELL.cmake @@ -0,0 +1,38 @@ +# -*- cmake -*- + +# - Find HUNSPELL +# This module defines +# HUNSPELL_INCLUDE_DIR, where to find libhunspell.h, etc. +# HUNSPELL_LIBRARY, the library needed to use HUNSPELL. +# HUNSPELL_FOUND, If false, do not try to use HUNSPELL. + +find_path(HUNSPELL_INCLUDE_DIR hunspell.h + PATH_SUFFIXES hunspell + ) + +set(HUNSPELL_NAMES ${HUNSPELL_NAMES} libhunspell-1.3 libhunspell) +find_library(HUNSPELL_LIBRARY + NAMES ${HUNSPELL_NAMES} + ) + +if (HUNSPELL_LIBRARY AND HUNSPELL_INCLUDE_DIR) + set(HUNSPELL_FOUND "YES") +else (HUNSPELL_LIBRARY AND HUNSPELL_INCLUDE_DIR) + set(HUNSPELL_FOUND "NO") +endif (HUNSPELL_LIBRARY AND HUNSPELL_INCLUDE_DIR) + + +if (HUNSPELL_FOUND) + if (NOT HUNSPELL_FIND_QUIETLY) + message(STATUS "Found Hunspell: Library in '${HUNSPELL_LIBRARY}' and header in '${HUNSPELL_INCLUDE_DIR}' ") + endif (NOT HUNSPELL_FIND_QUIETLY) +else (HUNSPELL_FOUND) + if (HUNSPELL_FIND_REQUIRED) + message(FATAL_ERROR " * * *\nCould not find HUNSPELL library! * * *") + endif (HUNSPELL_FIND_REQUIRED) +endif (HUNSPELL_FOUND) + +mark_as_advanced( + HUNSPELL_LIBRARY + HUNSPELL_INCLUDE_DIR + ) diff --git a/indra/cmake/Hunspell.cmake b/indra/cmake/Hunspell.cmake new file mode 100644 index 0000000000..def2198c93 --- /dev/null +++ b/indra/cmake/Hunspell.cmake @@ -0,0 +1,21 @@ +# -*- cmake -*- +include(Prebuilt) + +set(HUNSPELL_FIND_QUIETLY ON) +set(HUNSPELL_FIND_REQUIRED ON) + +if (STANDALONE) + include(FindHUNSPELL) +else (STANDALONE) + use_prebuilt_binary(libhunspell) + if (WINDOWS) + set(HUNSPELL_LIBRARY libhunspell) + set(HUNSPELL_INCLUDE_DIRS ${LIBS_PREBUILT_DIR}/include/hunspell) + elseif(DARWIN) + set(HUNSPELL_LIBRARY hunspell-1.3) + set(HUNSPELL_INCLUDE_DIRS ${LIBS_PREBUILT_DIR}/include/hunspell) + else() + set(HUNSPELL_LIBRARY hunspell-1.3) + set(HUNSPELL_INCLUDE_DIRS ${LIBS_PREBUILT_DIR}/include/hunspell) + endif() +endif (STANDALONE) diff --git a/indra/newview/CMakeLists.txt b/indra/newview/CMakeLists.txt index 0ec3e0e08a..fed9ea6790 100644 --- a/indra/newview/CMakeLists.txt +++ b/indra/newview/CMakeLists.txt @@ -13,6 +13,7 @@ include(EXPAT) include(FMOD) include(OPENAL) include(FindOpenGL) +include(Hunspell) include(JsonCpp) include(LLAudio) include(LLCharacter) -- cgit v1.2.3 From 028a05e79467e0c1fd7d63224fb447a964ab7a0b Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Fri, 10 Feb 2012 12:04:27 -0500 Subject: Use wildcards instead of many version-specific lib names on Linux. viewer_manifest.py's Linux_i686Manifest class has contained directives to copy library files with names like (e.g.) "libapr-1.so.0.4.2", which means that every update to any such library requires messing with viewer_manifest.py. But LLManifest.path() claims to support wildcards, and it's more robust to specify "libapr-1.so*" instead. Unfortunately LLManifest.path()'s wildcard support only used to work for files in the source tree (vs. the artwork tree or the build tree). The logic in path() tries each tree in turn, relying on an exception to make it try the next tree. This exception was raised for a nonexistent specific filename -- but it never used to raise that exception for a wildcard matching 0 files. Instead it would simply report "0 files" and proceed, producing an invalid viewer install. Raise that exception for a wildcard matching nothing. This forces path() to consider the artwork tree and the build tree, permitting us to use wildcards in library names. Define an exception specific to LLManifest: ManifestException rather than the generic Python RuntimeException. Make it a subclass of RuntimeException so any existing callers expecting to catch RuntimeException will continue to work. --- indra/lib/python/indra/util/llmanifest.py | 27 +++++++++++++------- indra/newview/viewer_manifest.py | 42 +++++++++++-------------------- 2 files changed, 32 insertions(+), 37 deletions(-) (limited to 'indra') diff --git a/indra/lib/python/indra/util/llmanifest.py b/indra/lib/python/indra/util/llmanifest.py index c33a03034a..237153b756 100644 --- a/indra/lib/python/indra/util/llmanifest.py +++ b/indra/lib/python/indra/util/llmanifest.py @@ -41,6 +41,9 @@ import tarfile import errno import subprocess +class ManifestError(RuntimeError): + pass + def path_ancestors(path): drive, path = os.path.splitdrive(os.path.normpath(path)) result = [] @@ -180,6 +183,9 @@ def usage(srctree=""): arg['description'] % nd) def main(): +## import itertools +## print ' '.join((("'%s'" % item) if ' ' in item else item) +## for item in itertools.chain([sys.executable], sys.argv)) option_names = [arg['name'] + '=' for arg in ARGUMENTS] option_names.append('help') options, remainder = getopt.getopt(sys.argv[1:], "", option_names) @@ -385,7 +391,7 @@ class LLManifest(object): child.stdout.close() status = child.wait() if status: - raise RuntimeError( + raise ManifestError( "Command %s returned non-zero status (%s) \noutput:\n%s" % (command, status, output) ) return output @@ -395,7 +401,7 @@ class LLManifest(object): a) verify that you really have created it b) schedule it for cleanup""" if not os.path.exists(path): - raise RuntimeError, "Should be something at path " + path + raise ManifestError, "Should be something at path " + path self.created_paths.append(path) def put_in_file(self, contents, dst): @@ -550,7 +556,7 @@ class LLManifest(object): except (IOError, os.error), why: errors.append((srcname, dstname, why)) if errors: - raise RuntimeError, errors + raise ManifestError, errors def cmakedirs(self, path): @@ -598,13 +604,16 @@ class LLManifest(object): def check_file_exists(self, path): if not os.path.exists(path) and not os.path.islink(path): - raise RuntimeError("Path %s doesn't exist" % ( - os.path.normpath(os.path.join(os.getcwd(), path)),)) + raise ManifestError("Path %s doesn't exist" % (os.path.abspath(path),)) - wildcard_pattern = re.compile('\*') + wildcard_pattern = re.compile(r'\*') def expand_globs(self, src, dst): src_list = glob.glob(src) + # Assume that if caller specifies a wildcard, s/he wants it to match + # at least one file... + if not src_list: + raise ManifestError("Path %s doesn't exist" % (os.path.abspath(src),)) src_re, d_template = self.wildcard_regex(src.replace('\\', '/'), dst.replace('\\', '/')) for s in src_list: @@ -615,7 +624,7 @@ class LLManifest(object): sys.stdout.write("Processing %s => %s ... " % (src, dst)) sys.stdout.flush() if src == None: - raise RuntimeError("No source file, dst is " + dst) + raise ManifestError("No source file, dst is " + dst) if dst == None: dst = src dst = os.path.join(self.get_dst_prefix(), dst) @@ -639,10 +648,10 @@ class LLManifest(object): return count try: count = try_path(os.path.join(self.get_src_prefix(), src)) - except RuntimeError: + except ManifestError: try: count = try_path(os.path.join(self.get_artwork_prefix(), src)) - except RuntimeError: + except ManifestError: count = try_path(os.path.join(self.get_build_prefix(), src)) print "%d files" % count diff --git a/indra/newview/viewer_manifest.py b/indra/newview/viewer_manifest.py index 0931c4ec9b..d65d51ce32 100755 --- a/indra/newview/viewer_manifest.py +++ b/indra/newview/viewer_manifest.py @@ -1025,41 +1025,27 @@ class Linux_i686Manifest(LinuxManifest): super(Linux_i686Manifest, self).construct() if self.prefix("../packages/lib/release", dst="lib"): - self.path("libapr-1.so") - self.path("libapr-1.so.0") - self.path("libapr-1.so.0.4.2") - self.path("libaprutil-1.so") - self.path("libaprutil-1.so.0") - self.path("libaprutil-1.so.0.3.10") - self.path("libbreakpad_client.so.0.0.0") - self.path("libbreakpad_client.so.0") - self.path("libbreakpad_client.so") + self.path("libapr-1.so*") + self.path("libaprutil-1.so*") + self.path("libbreakpad_client.so*") self.path("libcollada14dom.so") - self.path("libdb-5.1.so") - self.path("libdb-5.so") - self.path("libdb.so") - self.path("libcrypto.so.1.0.0") - self.path("libexpat.so.1.5.2") + self.path("libdb*.so") + self.path("libcrypto.so.*") + self.path("libexpat.so.*") self.path("libssl.so.1.0.0") self.path("libglod.so") self.path("libminizip.so") - self.path("libuuid.so") - self.path("libuuid.so.16") - self.path("libuuid.so.16.0.22") - self.path("libSDL-1.2.so.0.11.3") - self.path("libdirectfb-1.4.so.5.0.4") - self.path("libfusion-1.4.so.5.0.4") - self.path("libdirect-1.4.so.5.0.4") - self.path("libopenjpeg.so.1.4.0") - self.path("libopenjpeg.so.1") - self.path("libopenjpeg.so") + self.path("libuuid.so*") + self.path("libSDL-1.2.so.*") + self.path("libdirectfb-1.*.so.*") + self.path("libfusion-1.*.so.*") + self.path("libdirect-1.*.so.*") + self.path("libopenjpeg.so*") self.path("libalut.so") self.path("libopenal.so", "libopenal.so.1") self.path("libopenal.so", "libvivoxoal.so.1") # vivox's sdk expects this soname - self.path("libfontconfig.so.1.4.4") - self.path("libtcmalloc.so", "libtcmalloc.so") #formerly called google perf tools - self.path("libtcmalloc.so.0", "libtcmalloc.so.0") #formerly called google perf tools - self.path("libtcmalloc.so.0.1.0", "libtcmalloc.so.0.1.0") #formerly called google perf tools + self.path("libfontconfig.so.*") + self.path("libtcmalloc.so*") #formerly called google perf tools try: self.path("libfmod-3.75.so") pass -- cgit v1.2.3 From acd46062fd2edf4b45ab646cbacaf865b169ec30 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Fri, 10 Feb 2012 16:45:18 -0500 Subject: Eliminate ManifestError for wildcards matching 0 files. Turns out that some (many?) wildcard LLManifest.path(wildcard) calls are "just in case": sweep up any (e.g.) "*.tga" files there may be, but no problem if there are none. Change path() logic so it tries the next tree (source, artwork, build) if either a specific (non-wildcard) filename doesn't exist, as now, OR if a wildcard matches 0 files in the current tree. This continues to support "just in case" wildcards, while permitting wildcards to work in the artwork and build trees as well as the source tree. Use a more specific exception than ManifestError for missing file. Only in that case should we try the next tree. Any other ManifestError should propagate. --- indra/lib/python/indra/util/llmanifest.py | 33 ++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) (limited to 'indra') diff --git a/indra/lib/python/indra/util/llmanifest.py b/indra/lib/python/indra/util/llmanifest.py index 237153b756..a4fb77357c 100644 --- a/indra/lib/python/indra/util/llmanifest.py +++ b/indra/lib/python/indra/util/llmanifest.py @@ -42,6 +42,11 @@ import errno import subprocess class ManifestError(RuntimeError): + """Use an exception more specific than generic Python RuntimeError""" + pass + +class MissingError(ManifestError): + """You specified a file that doesn't exist""" pass def path_ancestors(path): @@ -604,16 +609,12 @@ class LLManifest(object): def check_file_exists(self, path): if not os.path.exists(path) and not os.path.islink(path): - raise ManifestError("Path %s doesn't exist" % (os.path.abspath(path),)) + raise MissingError("Path %s doesn't exist" % (os.path.abspath(path),)) wildcard_pattern = re.compile(r'\*') def expand_globs(self, src, dst): src_list = glob.glob(src) - # Assume that if caller specifies a wildcard, s/he wants it to match - # at least one file... - if not src_list: - raise ManifestError("Path %s doesn't exist" % (os.path.abspath(src),)) src_re, d_template = self.wildcard_regex(src.replace('\\', '/'), dst.replace('\\', '/')) for s in src_list: @@ -646,13 +647,23 @@ class LLManifest(object): else: count += self.process_file(src, dst) return count - try: - count = try_path(os.path.join(self.get_src_prefix(), src)) - except ManifestError: + + for pfx in self.get_src_prefix(), self.get_artwork_prefix(), self.get_build_prefix(): try: - count = try_path(os.path.join(self.get_artwork_prefix(), src)) - except ManifestError: - count = try_path(os.path.join(self.get_build_prefix(), src)) + count = try_path(os.path.join(pfx, src)) + except MissingError: + # If src isn't a wildcard, and if that file doesn't exist in + # this pfx, try next pfx. + count = 0 + continue + + # Here try_path() didn't raise MissingError. Did it process any files? + if count: + break + # Even though try_path() didn't raise MissingError, it returned 0 + # files. src is probably a wildcard meant for some other pfx. Loop + # back to try the next. + print "%d files" % count def do(self, *actions): -- cgit v1.2.3 From 22f26725b902cb2e942048d059710169666e4a45 Mon Sep 17 00:00:00 2001 From: Jonathan Yap Date: Fri, 10 Feb 2012 17:40:58 -0500 Subject: STORM-1738 Autocorrect working for nearby chat and IM input boxes warn-on-failure:open-license --- indra/llui/lllineeditor.cpp | 3 +-- indra/llui/lllineeditor.h | 3 +-- indra/newview/llautocorrect.cpp | 2 +- indra/newview/llimfloater.cpp | 5 +++-- indra/newview/llnearbychatbar.cpp | 3 +-- 5 files changed, 7 insertions(+), 9 deletions(-) (limited to 'indra') diff --git a/indra/llui/lllineeditor.cpp b/indra/llui/lllineeditor.cpp index de951d3b56..4d0b972bf1 100644 --- a/indra/llui/lllineeditor.cpp +++ b/indra/llui/lllineeditor.cpp @@ -866,11 +866,10 @@ void LLLineEditor::addChar(const llwchar uni_char) LLUI::reportBadKeystroke(); } -// *TODO implement callback routine if (!mReadOnly && mAutocorrectCallback != NULL) { // call callback - // mAutotocorrectCallback(mText&, mCursorPos&); + mAutocorrectCallback(mText, mCursorPos); } getWindow()->hideCursorUntilMouseMove(); diff --git a/indra/llui/lllineeditor.h b/indra/llui/lllineeditor.h index 9394700e8c..53af9ac996 100644 --- a/indra/llui/lllineeditor.h +++ b/indra/llui/lllineeditor.h @@ -169,8 +169,7 @@ public: virtual BOOL setTextArg( const std::string& key, const LLStringExplicit& text ); virtual BOOL setLabelArg( const std::string& key, const LLStringExplicit& text ); - // *TODO Make this work - typedef boost::function autocorrect_callback_t; + typedef boost::function autocorrect_callback_t; autocorrect_callback_t mAutocorrectCallback; void setAutocorrectCallback(autocorrect_callback_t cb) { mAutocorrectCallback = cb; } void setLabel(const LLStringExplicit &new_label) { mLabel = new_label; } diff --git a/indra/newview/llautocorrect.cpp b/indra/newview/llautocorrect.cpp index 9162b35f45..791d34df0c 100644 --- a/indra/newview/llautocorrect.cpp +++ b/indra/newview/llautocorrect.cpp @@ -349,7 +349,7 @@ std::string AutoCorrect::replaceWords(std::string words) { static LLCachedControl perform_autocorrect(gSavedSettings, "AutoCorrect"); if(!(perform_autocorrect))return words; - //TODO update this function to use the "wordStyle" thing, + //*TODO update this function to use the "wordStyle" thing, //but so far this function is never used, so later boost_tokenizer tokens(words, boost::char_separator(" ")); diff --git a/indra/newview/llimfloater.cpp b/indra/newview/llimfloater.cpp index 8354243bd3..e300f6f32d 100644 --- a/indra/newview/llimfloater.cpp +++ b/indra/newview/llimfloater.cpp @@ -56,7 +56,7 @@ #include "llrootview.h" #include "llspeakers.h" #include "llviewerchat.h" - +#include "llautocorrect.h" LLIMFloater::LLIMFloater(const LLUUID& session_id) : LLTransientDockableFloater(NULL, true, session_id), @@ -251,11 +251,12 @@ BOOL LLIMFloater::postBuild() slide_right->setVisible(!mControlPanel->getParent()->getVisible()); slide_right->setClickedCallback(boost::bind(&LLIMFloater::onSlide, this)); - // *TODO Establish LineEditor with autocorrect callback mInputEditor = getChild("chat_editor"); mInputEditor->setMaxTextLength(1023); // enable line history support for instant message bar mInputEditor->setEnableLineHistory(TRUE); + // *TODO Establish LineEditor with autocorrect callback + mInputEditor->setAutocorrectCallback(boost::bind(&AutoCorrect::autocorrectCallback, AutoCorrect::getInstance(), _1, _2)); LLFontGL* font = LLViewerChat::getChatFont(); mInputEditor->setFont(font); diff --git a/indra/newview/llnearbychatbar.cpp b/indra/newview/llnearbychatbar.cpp index 86244cbaa6..72fb95aca5 100644 --- a/indra/newview/llnearbychatbar.cpp +++ b/indra/newview/llnearbychatbar.cpp @@ -88,8 +88,7 @@ BOOL LLNearbyChatBar::postBuild() { mChatBox = getChild("chat_box"); - // *TODO Establish LineEditor with autocorrect callback -// mChatBox->setAutocorrectCallback(boost::bind(&AutoCorrect::autocorrectCallback, _1, _2)); + mChatBox->setAutocorrectCallback(boost::bind(&AutoCorrect::autocorrectCallback, AutoCorrect::getInstance(), _1, _2)); mChatBox->setCommitCallback(boost::bind(&LLNearbyChatBar::onChatBoxCommit, this)); mChatBox->setKeystrokeCallback(&onChatBoxKeystroke, this); mChatBox->setFocusLostCallback(boost::bind(&onChatBoxFocusLost, _1, this)); -- cgit v1.2.3 From e1fa05d8be51febec618d5ba124dbbab350ab747 Mon Sep 17 00:00:00 2001 From: Jonathan Yap Date: Sat, 11 Feb 2012 15:31:31 -0500 Subject: STORM-1738 Enable floater --- indra/newview/llviewerfloaterreg.cpp | 2 +- indra/newview/llviewermenu.cpp | 9 + .../skins/default/xui/en/floater_autocorrect.xml | 381 +++++++++++++++++---- indra/newview/skins/default/xui/en/menu_viewer.xml | 5 + 4 files changed, 323 insertions(+), 74 deletions(-) (limited to 'indra') diff --git a/indra/newview/llviewerfloaterreg.cpp b/indra/newview/llviewerfloaterreg.cpp index fc71160b2d..116076d789 100644 --- a/indra/newview/llviewerfloaterreg.cpp +++ b/indra/newview/llviewerfloaterreg.cpp @@ -170,7 +170,7 @@ void LLViewerFloaterReg::registerFloaters() LLFloaterReg::add("about_land", "floater_about_land.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("appearance", "floater_my_appearance.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("auction", "floater_auction.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); - LLFloaterReg::add("autocorrect", "floater_autocorrect.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); + LLFloaterReg::add("settings_autocorrect", "floater_autocorrect.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("avatar", "floater_avatar.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("avatar_picker", "floater_avatar_picker.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("avatar_textures", "floater_avatar_textures.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); diff --git a/indra/newview/llviewermenu.cpp b/indra/newview/llviewermenu.cpp index 67f6150dbe..b6a20becb2 100644 --- a/indra/newview/llviewermenu.cpp +++ b/indra/newview/llviewermenu.cpp @@ -1973,6 +1973,14 @@ class LLAdvancedCompressImage : public view_listener_t }; +class LLAdvancedShowAutocorrectSettings : public view_listener_t +{ + bool handleEvent(const LLSD& userdata) + { + LLFloaterReg::showInstance("settings_autocorrect", userdata); + return true; + } +}; ///////////////////////// // SHOW DEBUG SETTINGS // @@ -8235,6 +8243,7 @@ void initialize_menus() view_listener_t::addMenu(new LLAdvancedToggleShowObjectUpdates(), "Advanced.ToggleShowObjectUpdates"); view_listener_t::addMenu(new LLAdvancedCheckShowObjectUpdates(), "Advanced.CheckShowObjectUpdates"); view_listener_t::addMenu(new LLAdvancedCompressImage(), "Advanced.CompressImage"); + view_listener_t::addMenu(new LLAdvancedShowAutocorrectSettings(), "Advanced.ShowAutocorrectSettings"); view_listener_t::addMenu(new LLAdvancedShowDebugSettings(), "Advanced.ShowDebugSettings"); view_listener_t::addMenu(new LLAdvancedEnableViewAdminOptions(), "Advanced.EnableViewAdminOptions"); view_listener_t::addMenu(new LLAdvancedToggleViewAdminOptions(), "Advanced.ToggleViewAdminOptions"); diff --git a/indra/newview/skins/default/xui/en/floater_autocorrect.xml b/indra/newview/skins/default/xui/en/floater_autocorrect.xml index b67b2e7ec0..05683c9907 100644 --- a/indra/newview/skins/default/xui/en/floater_autocorrect.xml +++ b/indra/newview/skins/default/xui/en/floater_autocorrect.xml @@ -1,79 +1,314 @@ - - - + + + + + + + + diff --git a/indra/newview/skins/default/xui/en/menu_viewer.xml b/indra/newview/skins/default/xui/en/menu_viewer.xml index 8b0152b1a2..a1f17ffc17 100644 --- a/indra/newview/skins/default/xui/en/menu_viewer.xml +++ b/indra/newview/skins/default/xui/en/menu_viewer.xml @@ -1877,6 +1877,13 @@ function="Advanced.ToggleConsole" parameter="texture" /> + + + Date: Thu, 26 Apr 2012 13:18:06 -0400 Subject: tracking for copy-to-wear inventory failures --- indra/newview/llappearancemgr.cpp | 3 +++ 1 file changed, 3 insertions(+) (limited to 'indra') diff --git a/indra/newview/llappearancemgr.cpp b/indra/newview/llappearancemgr.cpp index 484de81ac9..73dd64dffe 100644 --- a/indra/newview/llappearancemgr.cpp +++ b/indra/newview/llappearancemgr.cpp @@ -162,6 +162,8 @@ public: mCatID = cat_id; mAppend = append; + LL_DEBUGS("Avatar") << self_av_string() << "starting" << LL_ENDL; + selfStartPhase("wear_inventory_category_callback"); } void fire(const LLUUID& item_id) @@ -174,6 +176,7 @@ public: * after the last item has fired the event and dereferenced it -- if all * the events actually fire! */ + LL_DEBUGS("Avatar") << self_av_string() << " fired on copied item, id " << item_id << LL_ENDL; } protected: -- cgit v1.2.3 From e344b2afa21adf072837f1bcf4b38dd511b76f0e Mon Sep 17 00:00:00 2001 From: Xiaohong Bao Date: Thu, 26 Apr 2012 15:53:35 -0600 Subject: For SH-3121: collect time of reloading all textures from cache and through HTTP when all objects loading are done. --- indra/newview/llappviewer.cpp | 18 ++--- indra/newview/llfloatertexturefetchdebugger.cpp | 60 ++++++++++++++++ indra/newview/llfloatertexturefetchdebugger.h | 2 + indra/newview/lltexturefetch.cpp | 83 +++++++++++++++++++++- indra/newview/lltexturefetch.h | 26 ++++++- indra/newview/llviewertexture.cpp | 8 +++ indra/newview/llviewertexture.h | 2 + .../xui/en/floater_texture_fetch_debugger.xml | 64 ++++++++++++++--- 8 files changed, 242 insertions(+), 21 deletions(-) (limited to 'indra') diff --git a/indra/newview/llappviewer.cpp b/indra/newview/llappviewer.cpp index 3ee53c679f..bb6658dc48 100644 --- a/indra/newview/llappviewer.cpp +++ b/indra/newview/llappviewer.cpp @@ -1219,15 +1219,7 @@ bool LLAppViewer::mainLoop() if(mem_leak_instance) { mem_leak_instance->idle() ; - } - - //texture fetching debugger - LLFloaterTextureFetchDebugger* tex_fetch_debugger_instance = - LLFloaterReg::findTypedInstance("tex_fetch_debugger"); - if(tex_fetch_debugger_instance) - { - tex_fetch_debugger_instance->idle() ; - } + } // canonical per-frame event mainloop.post(newFrame); @@ -1412,6 +1404,14 @@ bool LLAppViewer::mainLoop() LLLFSThread::sLocal->pause(); } + //texture fetching debugger + LLFloaterTextureFetchDebugger* tex_fetch_debugger_instance = + LLFloaterReg::findTypedInstance("tex_fetch_debugger"); + if(tex_fetch_debugger_instance) + { + tex_fetch_debugger_instance->idle() ; + } + if ((LLStartUp::getStartupState() >= STATE_CLEANUP) && (frameTimer.getElapsedTimeF64() > FRAME_STALL_THRESHOLD)) { diff --git a/indra/newview/llfloatertexturefetchdebugger.cpp b/indra/newview/llfloatertexturefetchdebugger.cpp index 6756f9bbc1..448c562134 100644 --- a/indra/newview/llfloatertexturefetchdebugger.cpp +++ b/indra/newview/llfloatertexturefetchdebugger.cpp @@ -58,6 +58,9 @@ LLFloaterTextureFetchDebugger::LLFloaterTextureFetchDebugger(const LLSD& key) mCommitCallbackRegistrar.add("TexFetchDebugger.HTTPLoad", boost::bind(&LLFloaterTextureFetchDebugger::onClickHTTPLoad, this)); mCommitCallbackRegistrar.add("TexFetchDebugger.Decode", boost::bind(&LLFloaterTextureFetchDebugger::onClickDecode, this)); mCommitCallbackRegistrar.add("TexFetchDebugger.GLTexture", boost::bind(&LLFloaterTextureFetchDebugger::onClickGLTexture, this)); + + mCommitCallbackRegistrar.add("TexFetchDebugger.RefetchVisCache", boost::bind(&LLFloaterTextureFetchDebugger::onClickRefetchVisCache, this)); + mCommitCallbackRegistrar.add("TexFetchDebugger.RefetchVisHTTP", boost::bind(&LLFloaterTextureFetchDebugger::onClickRefetchVisHTTP, this)); } //---------------------------------------------- @@ -74,6 +77,10 @@ BOOL LLFloaterTextureFetchDebugger::postBuild(void) mButtonStateMap["http_btn"] = false; mButtonStateMap["decode_btn"] = false; mButtonStateMap["gl_btn"] = false; + + mButtonStateMap["refetchviscache_btn"] = true; + mButtonStateMap["refetchvishttp_btn"] = true; + updateButtons(); return TRUE ; @@ -109,6 +116,8 @@ void LLFloaterTextureFetchDebugger::disableButtons() childDisable("http_btn"); childDisable("decode_btn"); childDisable("gl_btn"); + childDisable("refetchviscache_btn"); + childDisable("refetchvishttp_btn"); } void LLFloaterTextureFetchDebugger::idle() @@ -142,6 +151,11 @@ void LLFloaterTextureFetchDebugger::idle() case LLTextureFetchDebugger::GL_TEX: updateButtons(); break; + case LLTextureFetchDebugger::REFETCH_VIS_CACHE: + updateButtons(); + case LLTextureFetchDebugger::REFETCH_VIS_HTTP: + updateButtons(); + break; default: break; } @@ -184,6 +198,8 @@ void LLFloaterTextureFetchDebugger::onClickClear() mButtonStateMap["http_btn"] = false; mButtonStateMap["decode_btn"] = false; mButtonStateMap["gl_btn"] = false; + mButtonStateMap["refetchviscache_btn"] = true; + mButtonStateMap["refetchvishttp_btn"] = true; updateButtons(); //stop everything @@ -226,6 +242,20 @@ void LLFloaterTextureFetchDebugger::onClickGLTexture() mDebugger->debugGLTextureCreation(); } +void LLFloaterTextureFetchDebugger::onClickRefetchVisCache() +{ + disableButtons(); + + mDebugger->debugRefetchVisibleFromCache(); +} + +void LLFloaterTextureFetchDebugger::onClickRefetchVisHTTP() +{ + disableButtons(); + + mDebugger->debugRefetchVisibleFromHTTP(); +} + void LLFloaterTextureFetchDebugger::draw() { //total number of fetched textures @@ -257,6 +287,7 @@ void LLFloaterTextureFetchDebugger::draw() { getChild("total_fetched_data_label")->setTextArg("[SIZE1]", llformat("%d", mDebugger->getFetchedData() >> 10)); getChild("total_fetched_data_label")->setTextArg("[SIZE2]", llformat("%d", mDebugger->getDecodedData() >> 10)); + getChild("total_fetched_data_label")->setTextArg("[PIXEL]", llformat("%.3f", mDebugger->getFetchedPixels() / 1000000.f)); } //total number of visible fetched data @@ -269,6 +300,7 @@ void LLFloaterTextureFetchDebugger::draw() { getChild("total_fetched_rendered_data_label")->setTextArg("[SIZE1]", llformat("%d", mDebugger->getRenderedData() >> 10)); getChild("total_fetched_rendered_data_label")->setTextArg("[SIZE2]", llformat("%d", mDebugger->getRenderedDecodedData() >> 10)); + getChild("total_fetched_rendered_data_label")->setTextArg("[PIXEL]", llformat("%.3f", mDebugger->getRenderedPixels() / 1000000.f)); } //total time on cache readings @@ -326,5 +358,33 @@ void LLFloaterTextureFetchDebugger::draw() getChild("total_time_fetch_label")->setTextArg("[TIME]", llformat("%.3f", mDebugger->getTotalFetchingTime())); } + //total time on refetching visible textures from cache + if(mDebugger->getRefetchVisCacheTime() < 0.f) + { + getChild("total_time_refetch_vis_cache_label")->setTextArg("[TIME]", std::string("----")); + getChild("total_time_refetch_vis_cache_label")->setTextArg("[SIZE]", std::string("----")); + getChild("total_time_refetch_vis_cache_label")->setTextArg("[PIXEL]", std::string("----")); + } + else + { + getChild("total_time_refetch_vis_cache_label")->setTextArg("[TIME]", llformat("%.3f", mDebugger->getRefetchVisCacheTime())); + getChild("total_time_refetch_vis_cache_label")->setTextArg("[SIZE]", llformat("%d", mDebugger->getRefetchedData() >> 10)); + getChild("total_time_refetch_vis_cache_label")->setTextArg("[PIXEL]", llformat("%.3f", mDebugger->getRefetchedPixels() / 1000000.f)); + } + + //total time on refetching visible textures from http + if(mDebugger->getRefetchVisHTTPTime() < 0.f) + { + getChild("total_time_refetch_vis_http_label")->setTextArg("[TIME]", std::string("----")); + getChild("total_time_refetch_vis_http_label")->setTextArg("[SIZE]", std::string("----")); + getChild("total_time_refetch_vis_http_label")->setTextArg("[PIXEL]", std::string("----")); + } + else + { + getChild("total_time_refetch_vis_http_label")->setTextArg("[TIME]", llformat("%.3f", mDebugger->getRefetchVisHTTPTime())); + getChild("total_time_refetch_vis_http_label")->setTextArg("[SIZE]", llformat("%d", mDebugger->getRefetchedData() >> 10)); + getChild("total_time_refetch_vis_http_label")->setTextArg("[PIXEL]", llformat("%.3f", mDebugger->getRefetchedPixels() / 1000000.f)); + } + LLFloater::draw(); } diff --git a/indra/newview/llfloatertexturefetchdebugger.h b/indra/newview/llfloatertexturefetchdebugger.h index 9f2e62fd2c..7181dc04d5 100644 --- a/indra/newview/llfloatertexturefetchdebugger.h +++ b/indra/newview/llfloatertexturefetchdebugger.h @@ -51,6 +51,8 @@ public: void onClickDecode(); void onClickGLTexture(); + void onClickRefetchVisCache(); + void onClickRefetchVisHTTP(); public: void idle() ; diff --git a/indra/newview/lltexturefetch.cpp b/indra/newview/lltexturefetch.cpp index d7742219bf..2816c16261 100755 --- a/indra/newview/lltexturefetch.cpp +++ b/indra/newview/lltexturefetch.cpp @@ -3139,6 +3139,8 @@ void LLTextureFetchDebugger::init() mHTTPTime = -1.f; mGLCreationTime = -1.f; mTotalFetchingTime = 0.f; + mRefetchVisCacheTime = -1.f; + mRefetchVisHTTPTime = -1.f; mNumFetchedTextures = 0; mNumCacheHits = 0; @@ -3150,12 +3152,19 @@ void LLTextureFetchDebugger::init() mVisibleDecodedData = 0; mRenderedData = 0; mRenderedDecodedData = 0; + mFetchedPixels = 0; + mRenderedPixels = 0; + mRefetchedData = 0; + mRefetchedPixels = 0; + + mFreezeHistory = FALSE; } void LLTextureFetchDebugger::startDebug() { //lock the fetcher mFetcher->lockFetcher(true); + mFreezeHistory = TRUE; //clear the current fetching queue gTextureList.clearFetchingRequests(); @@ -3203,6 +3212,7 @@ void LLTextureFetchDebugger::startDebug() { mRenderedData += mFetchingHistory[i].mFetchedSize; mRenderedDecodedData += mFetchingHistory[i].mDecodedSize; + mRenderedPixels += tex->getWidth() * tex->getHeight(); } } } @@ -3254,6 +3264,8 @@ void LLTextureFetchDebugger::stopDebug() //unlock the fetcher mFetcher->lockFetcher(false); + mFreezeHistory = FALSE; + mTotalFetchingTime = gDebugTimers[0].getElapsedTimeF32(); //reset } //called in the main thread and when the fetching queue is empty @@ -3265,12 +3277,20 @@ void LLTextureFetchDebugger::clearHistory() void LLTextureFetchDebugger::addHistoryEntry(LLTextureFetchWorker* worker) { + if(mFreezeHistory) + { + mRefetchedPixels += worker->mRawImage->getWidth() * worker->mRawImage->getHeight(); + mRefetchedData += worker->mFormattedImage->getDataSize(); + return; + } + if(worker->mInCache) { mNumCacheHits++; } mFetchedData += worker->mFormattedImage->getDataSize(); mDecodedData += worker->mRawImage->getDataSize(); + mFetchedPixels += worker->mRawImage->getWidth() * worker->mRawImage->getHeight(); mFetchingHistory.push_back(FetchEntry(worker->mID, worker->mDecodedDiscard, worker->mFormattedImage->getDataSize(), worker->mRawImage->getDataSize())); //mFetchingHistory.push_back(FetchEntry(worker->mID, worker->mDesiredSize, worker->mHaveAllData ? 0 : worker->mLoadedDiscard, worker->mFormattedImage->getComponents(), @@ -3301,9 +3321,8 @@ void LLTextureFetchDebugger::debugCacheRead() } } -void LLTextureFetchDebugger::debugCacheWrite() +void LLTextureFetchDebugger::clearCache() { - //remove from cache S32 size = mFetchingHistory.size(); { std::set deleted_list; @@ -3316,12 +3335,19 @@ void LLTextureFetchDebugger::debugCacheWrite() } } } +} + +void LLTextureFetchDebugger::debugCacheWrite() +{ + //remove from cache + clearCache(); lockCache(); llassert_always(mState == IDLE); mTimer.reset(); mState = WRITE_CACHE; + S32 size = mFetchingHistory.size(); for(S32 i = 0 ; i < size ; i++) { mFetchingHistory[i].mCacheHandle = mTextureCache->writeToCache(mFetchingHistory[i].mID, LLWorkerThread::PRIORITY_NORMAL, @@ -3403,6 +3429,43 @@ void LLTextureFetchDebugger::debugGLTextureCreation() return; } +//clear fetching results of all textures. +void LLTextureFetchDebugger::clearTextures() +{ + S32 size = mFetchingHistory.size(); + for(S32 i = 0 ; i < size ; i++) + { + LLViewerFetchedTexture* tex = gTextureList.findImage(mFetchingHistory[i].mID) ; + if(tex) + { + tex->clearFetchedResults() ; + } + } +} + +void LLTextureFetchDebugger::debugRefetchVisibleFromCache() +{ + llassert_always(mState == IDLE); + mState = REFETCH_VIS_CACHE; + + clearTextures(); + + mTimer.reset(); + mFetcher->lockFetcher(false); +} + +void LLTextureFetchDebugger::debugRefetchVisibleFromHTTP() +{ + llassert_always(mState == IDLE); + mState = REFETCH_VIS_HTTP; + + clearCache(); + clearTextures(); + + mTimer.reset(); + mFetcher->lockFetcher(false); +} + bool LLTextureFetchDebugger::update() { switch(mState) @@ -3437,6 +3500,22 @@ bool LLTextureFetchDebugger::update() case GL_TEX: mState = IDLE; break; + case REFETCH_VIS_CACHE: + if (LLAppViewer::getTextureFetch()->getNumRequests() == 0) + { + mRefetchVisCacheTime = gDebugTimers[0].getElapsedTimeF32() - mTotalFetchingTime; + mState = IDLE; + mFetcher->lockFetcher(true); + } + break; + case REFETCH_VIS_HTTP: + if (LLAppViewer::getTextureFetch()->getNumRequests() == 0) + { + mRefetchVisHTTPTime = gDebugTimers[0].getElapsedTimeF32() - mTotalFetchingTime; + mState = IDLE; + mFetcher->lockFetcher(true); + } + break; default: mState = IDLE; break; diff --git a/indra/newview/lltexturefetch.h b/indra/newview/lltexturefetch.h index 529a2e6834..fc8855089c 100644 --- a/indra/newview/lltexturefetch.h +++ b/indra/newview/lltexturefetch.h @@ -243,6 +243,10 @@ public: DECODING, HTTP_FETCHING, GL_TEX, + REFETCH_VIS_CACHE, + REFETCH_VIS_HTTP, + REFETCH_ALL_CACHE, + REFETCH_ALL_HTTP, INVALID }; @@ -287,14 +291,17 @@ private: F32 mHTTPTime; F32 mGLCreationTime; + F32 mTotalFetchingTime; + F32 mRefetchVisCacheTime; + F32 mRefetchVisHTTPTime; + LLTimer mTimer; LLTextureFetch* mFetcher; LLTextureCache* mTextureCache; LLImageDecodeThread* mImageDecodeThread; LLCurlRequest* mCurlGetRequest; - - F32 mTotalFetchingTime; + S32 mNumFetchedTextures; S32 mNumCacheHits; S32 mNumVisibleFetchedTextures; @@ -305,7 +312,12 @@ private: U32 mVisibleDecodedData; U32 mRenderedData; U32 mRenderedDecodedData; + U32 mFetchedPixels; + U32 mRenderedPixels; + U32 mRefetchedData; + U32 mRefetchedPixels; + BOOL mFreezeHistory; public: bool update(); //called in the main thread once per frame @@ -322,6 +334,8 @@ public: void debugHTTP(); void debugDecoder(); void debugGLTextureCreation(); + void debugRefetchVisibleFromCache(); + void debugRefetchVisibleFromHTTP(); void callbackCacheRead(S32 id, bool success, LLImageFormatted* image, S32 imagesize, BOOL islocal); @@ -340,6 +354,10 @@ public: U32 getVisibleDecodedData() {return mVisibleDecodedData;} U32 getRenderedData() {return mRenderedData;} U32 getRenderedDecodedData() {return mRenderedDecodedData;} + U32 getFetchedPixels() {return mFetchedPixels;} + U32 getRenderedPixels() {return mRenderedPixels;} + U32 getRefetchedData() {return mRefetchedData;} + U32 getRefetchedPixels() {return mRefetchedPixels;} F32 getCacheReadTime() {return mCacheReadTime;} F32 getCacheWriteTime() {return mCacheWriteTime;} @@ -347,9 +365,13 @@ public: F32 getGLCreationTime() {return mGLCreationTime;} F32 getHTTPTime() {return mHTTPTime;} F32 getTotalFetchingTime() {return mTotalFetchingTime;} + F32 getRefetchVisCacheTime() {return mRefetchVisCacheTime;} + F32 getRefetchVisHTTPTime() {return mRefetchVisHTTPTime;} private: void init(); + void clearTextures();//clear fetching results of all textures. + void clearCache(); void lockFetcher(); void unlockFetcher(); diff --git a/indra/newview/llviewertexture.cpp b/indra/newview/llviewertexture.cpp index 49faae3fdb..a7e2ed85fa 100644 --- a/indra/newview/llviewertexture.cpp +++ b/indra/newview/llviewertexture.cpp @@ -2144,6 +2144,14 @@ bool LLViewerFetchedTexture::updateFetch() return mIsFetching ? true : false; } +void LLViewerFetchedTexture::clearFetchedResults() +{ + llassert_always(!mNeedsCreateTexture && !mIsFetching); + + cleanup(); + destroyGLTexture(); +} + void LLViewerFetchedTexture::forceToDeleteRequest() { if (mHasFetcher) diff --git a/indra/newview/llviewertexture.h b/indra/newview/llviewertexture.h index d0bc534c5a..95896f9d41 100644 --- a/indra/newview/llviewertexture.h +++ b/indra/newview/llviewertexture.h @@ -433,6 +433,8 @@ public: bool updateFetch(); + void clearFetchedResults(); //clear all fetched results, for debug use. + // Override the computation of discard levels if we know the exact output // size of the image. Used for UI textures to not decode, even if we have // more data. diff --git a/indra/newview/skins/default/xui/en/floater_texture_fetch_debugger.xml b/indra/newview/skins/default/xui/en/floater_texture_fetch_debugger.xml index ff7528eeb7..7f95d0e84b 100644 --- a/indra/newview/skins/default/xui/en/floater_texture_fetch_debugger.xml +++ b/indra/newview/skins/default/xui/en/floater_texture_fetch_debugger.xml @@ -2,12 +2,12 @@ + width="540"> - 6, Total number of fetched data/Decoded Data: [SIZE1]KB / [SIZE2]KB + width="530"> + 6, Total number of fetched data: [SIZE1]KB, Decoded Data: [SIZE2]KB, [PIXEL]MPixels - 7, Total number of visible fetched data/Decoded Data: [SIZE1]KB / [SIZE2]KB + 7, Total number of visible data: [SIZE1]KB, Decoded Data: [SIZE2]KB - 8, Total number of rendered fetched data/Decoded Data: [SIZE1]KB / [SIZE2]KB + width="530"> + 8, Total number of rendered data: [SIZE1]KB, Decoded Data: [SIZE2]KB, [PIXEL]MPixels 14, Total time on entire fetching: [TIME] seconds + + 15, Refetching visibles from cache, Time: [TIME] seconds, Fetched: [SIZE]KB, [PIXEL]MPixels + + + 16, Refetching visibles from HTTP, Time: [TIME] seconds, Fetched: [SIZE]KB, [PIXEL]MPixels + + + -- cgit v1.2.3 From 1df7655588a26529882a0ec97a7f23195f813468 Mon Sep 17 00:00:00 2001 From: Xiaohong Bao Date: Thu, 26 Apr 2012 16:55:06 -0600 Subject: for SH-3097: introducing texel pixel ration adjustment --- indra/newview/app_settings/settings.xml | 13 ++++++++++++- indra/newview/llfloatertexturefetchdebugger.cpp | 8 ++++---- indra/newview/llfloatertexturefetchdebugger.h | 3 +-- indra/newview/llviewertexture.cpp | 3 +++ .../skins/default/xui/en/floater_texture_fetch_debugger.xml | 5 +++-- 5 files changed, 23 insertions(+), 9 deletions(-) (limited to 'indra') diff --git a/indra/newview/app_settings/settings.xml b/indra/newview/app_settings/settings.xml index eb3fcc30ee..d24d1ebd6d 100755 --- a/indra/newview/app_settings/settings.xml +++ b/indra/newview/app_settings/settings.xml @@ -10631,6 +10631,17 @@ Value 20.0 + TexelPixelRatio + + Comment + texel pixel ratio = texel / pixel + Persist + 1 + Type + F32 + Value + 1.0 + TextureCameraMotionThreshold Comment @@ -10640,7 +10651,7 @@ Type F32 Value - 0.2 + 0.2 TextureCameraMotionBoost diff --git a/indra/newview/llfloatertexturefetchdebugger.cpp b/indra/newview/llfloatertexturefetchdebugger.cpp index 448c562134..2b34b72055 100644 --- a/indra/newview/llfloatertexturefetchdebugger.cpp +++ b/indra/newview/llfloatertexturefetchdebugger.cpp @@ -37,9 +37,7 @@ #include "llviewerwindow.h" #include "llappviewer.h" #include "lltexturefetch.h" - -//static -F32 LLFloaterTextureFetchDebugger::sTexelPixelRatio = 1.0f; +#include "llviewercontrol.h" LLFloaterTextureFetchDebugger::LLFloaterTextureFetchDebugger(const LLSD& key) : LLFloater(key), @@ -83,6 +81,8 @@ BOOL LLFloaterTextureFetchDebugger::postBuild(void) updateButtons(); + getChild("texel_pixel_ratio")->setValue(gSavedSettings.getF32("TexelPixelRatio")); + return TRUE ; } @@ -165,7 +165,7 @@ void LLFloaterTextureFetchDebugger::idle() //---------------------- void LLFloaterTextureFetchDebugger::onChangeTexelPixelRatio() { - sTexelPixelRatio = getChild("texel_pixel_ratio")->getValue().asReal(); + gSavedSettings.setF32("TexelPixelRatio", getChild("texel_pixel_ratio")->getValue().asReal()); } void LLFloaterTextureFetchDebugger::onClickStart() diff --git a/indra/newview/llfloatertexturefetchdebugger.h b/indra/newview/llfloatertexturefetchdebugger.h index 7181dc04d5..33012c6a3d 100644 --- a/indra/newview/llfloatertexturefetchdebugger.h +++ b/indra/newview/llfloatertexturefetchdebugger.h @@ -62,9 +62,8 @@ private: void updateButtons(); void disableButtons(); -private: - static F32 sTexelPixelRatio; +private: LLTextureFetchDebugger* mDebugger; std::map mButtonStateMap; }; diff --git a/indra/newview/llviewertexture.cpp b/indra/newview/llviewertexture.cpp index a7e2ed85fa..6137b7176f 100644 --- a/indra/newview/llviewertexture.cpp +++ b/indra/newview/llviewertexture.cpp @@ -722,11 +722,14 @@ void LLViewerTexture::forceImmediateUpdate() void LLViewerTexture::addTextureStats(F32 virtual_size, BOOL needs_gltexture) const { + static LLCachedControl sTexelPixelRatio(gSavedSettings,"TexelPixelRatio"); + if(needs_gltexture) { mNeedsGLTexture = TRUE ; } + virtual_size *= sTexelPixelRatio; if(!mMaxVirtualSizeResetCounter) { //flag to reset the values because the old values are used. diff --git a/indra/newview/skins/default/xui/en/floater_texture_fetch_debugger.xml b/indra/newview/skins/default/xui/en/floater_texture_fetch_debugger.xml index 7f95d0e84b..0e8b85e3a7 100644 --- a/indra/newview/skins/default/xui/en/floater_texture_fetch_debugger.xml +++ b/indra/newview/skins/default/xui/en/floater_texture_fetch_debugger.xml @@ -204,13 +204,14 @@ decimal_digits="1" follows="left|top" height="20" - increment="0.1" + increment="0.01" initial_value="1.0" label="17, Ratio of Texel/Pixel:" label_width="130" layout="topleft" left_delta="0" - max_val="128.0" + max_val="10.0" + min_val="0.01" name="texel_pixel_ratio" top_delta="30" width="200"> -- cgit v1.2.3 From e703232cae0e692c813ba119e283ffd2d150fec8 Mon Sep 17 00:00:00 2001 From: Xiaohong Bao Date: Thu, 26 Apr 2012 18:01:17 -0600 Subject: a fix for SH-3097 --- indra/newview/skins/default/xui/en/floater_texture_fetch_debugger.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/newview/skins/default/xui/en/floater_texture_fetch_debugger.xml b/indra/newview/skins/default/xui/en/floater_texture_fetch_debugger.xml index 0e8b85e3a7..44b6a63bca 100644 --- a/indra/newview/skins/default/xui/en/floater_texture_fetch_debugger.xml +++ b/indra/newview/skins/default/xui/en/floater_texture_fetch_debugger.xml @@ -201,7 +201,7 @@ 16, Refetching visibles from HTTP, Time: [TIME] seconds, Fetched: [SIZE]KB, [PIXEL]MPixels Date: Thu, 26 Apr 2012 23:55:40 -0700 Subject: SH-3104 : Implemented HTTP bulk fetch for texture debug console --- indra/newview/lltexturefetch.cpp | 136 ++++++++++++++++++++++++++++++++++++++- indra/newview/lltexturefetch.h | 24 ++++++- 2 files changed, 154 insertions(+), 6 deletions(-) (limited to 'indra') diff --git a/indra/newview/lltexturefetch.cpp b/indra/newview/lltexturefetch.cpp index d7742219bf..8b6f006db1 100755 --- a/indra/newview/lltexturefetch.cpp +++ b/indra/newview/lltexturefetch.cpp @@ -3114,6 +3114,42 @@ private: S32 mID; }; +class LLDebuggerHTTPResponder : public LLCurl::Responder +{ +public: + LLDebuggerHTTPResponder(LLTextureFetchDebugger* debugger, S32 index) + : mDebugger(debugger), mIndex(index) + { + } + virtual void completedRaw(U32 status, const std::string& reason, + const LLChannelDescriptors& channels, + const LLIOPipe::buffer_ptr_t& buffer) + { + bool success = false; + bool partial = false; + if (HTTP_OK <= status && status < HTTP_MULTIPLE_CHOICES) + { + success = true; + if (HTTP_PARTIAL_CONTENT == status) // partial information + { + partial = true; + } + } + if (!success) + { + llinfos << "Fetch Debugger : CURL GET FAILED, index = " << mIndex << ", status:" << status << " reason:" << reason << llendl; + } + mDebugger->callbackHTTP(mIndex, channels, buffer, partial, success); + } + virtual bool followRedir() + { + return true; + } +private: + LLTextureFetchDebugger* mDebugger; + S32 mIndex; +}; + LLTextureFetchDebugger::LLTextureFetchDebugger(LLTextureFetch* fetcher, LLTextureCache* cache, LLImageDecodeThread* imagedecodethread) : mFetcher(fetcher), mTextureCache(cache), @@ -3272,7 +3308,7 @@ void LLTextureFetchDebugger::addHistoryEntry(LLTextureFetchWorker* worker) mFetchedData += worker->mFormattedImage->getDataSize(); mDecodedData += worker->mRawImage->getDataSize(); - mFetchingHistory.push_back(FetchEntry(worker->mID, worker->mDecodedDiscard, worker->mFormattedImage->getDataSize(), worker->mRawImage->getDataSize())); + mFetchingHistory.push_back(FetchEntry(worker->mID, worker->mDesiredSize, worker->mDecodedDiscard, worker->mFormattedImage->getDataSize(), worker->mRawImage->getDataSize())); //mFetchingHistory.push_back(FetchEntry(worker->mID, worker->mDesiredSize, worker->mHaveAllData ? 0 : worker->mLoadedDiscard, worker->mFormattedImage->getComponents(), //worker->mDecodedDiscard, worker->mFormattedImage->getDataSize(), worker->mRawImage->getDataSize())); } @@ -3362,7 +3398,71 @@ void LLTextureFetchDebugger::debugDecoder() void LLTextureFetchDebugger::debugHTTP() { - llinfos << "debug HTTP" << llendl; + llassert_always(mState == IDLE); + + LLViewerRegion* region = gAgent.getRegion(); + if (!region) + { + llinfos << "Fetch Debugger : Current region undefined. Cannot fetch textures through HTTP." << llendl; + return; + } + + mHTTPUrl = region->getHttpUrl(); + if (mHTTPUrl.empty()) + { + llinfos << "Fetch Debugger : Current region URL undefined. Cannot fetch textures through HTTP." << llendl; + return; + } + + mTimer.reset(); + mState = HTTP_FETCHING; + + S32 size = mFetchingHistory.size(); + for (S32 i = 0 ; i < size ; i++) + { + mFetchingHistory[i].mCurlState = FetchEntry::CURL_NOT_DONE; + mFetchingHistory[i].mCurlReceivedSize = 0; + } + mNbCurlRequests = 0; + mNbCurlCompleted = 0; + + fillCurlQueue(); +} + +S32 LLTextureFetchDebugger::fillCurlQueue() +{ + if (mNbCurlRequests == 24) + return mNbCurlRequests; + + S32 size = mFetchingHistory.size(); + for (S32 i = 0 ; i < size ; i++) + { + if (mFetchingHistory[i].mCurlState != FetchEntry::CURL_NOT_DONE) + continue; + std::string texture_url = mHTTPUrl + "/?texture_id=" + mFetchingHistory[i].mID.asString().c_str(); + S32 requestedSize = mFetchingHistory[i].mRequestedSize; + // We request the whole file if the size was not set. + requestedSize = llmax(0,requestedSize); + // We request the whole file if the size was set to an absurdly high value (meaning all file) + requestedSize = (requestedSize == 33554432 ? 0 : requestedSize); + std::vector headers; + headers.push_back("Accept: image/x-j2c"); + bool res = mCurlGetRequest->getByteRange(texture_url, headers, 0, requestedSize, new LLDebuggerHTTPResponder(this, i)); + if (res) + { + mFetchingHistory[i].mCurlState = FetchEntry::CURL_IN_PROGRESS; + mNbCurlRequests++; + // Hack + if (mNbCurlRequests == 24) + break; + } + else + { + break; + } + } + llinfos << "Fetch Debugger : Having " << mNbCurlRequests << " requests through the curl thread." << llendl; + return mNbCurlRequests; } void LLTextureFetchDebugger::debugGLTextureCreation() @@ -3432,7 +3532,13 @@ bool LLTextureFetchDebugger::update() } break; case HTTP_FETCHING: - mState = IDLE; + mCurlGetRequest->process(); + LLCurl::getCurlThread()->update(1); + if (!fillCurlQueue()) + { + mHTTPTime = mTimer.getElapsedTimeF32() ; + mState = IDLE; + } break; case GL_TEX: mState = IDLE; @@ -3471,6 +3577,30 @@ void LLTextureFetchDebugger::callbackDecoded(S32 id, bool success, LLImageRaw* r } } +void LLTextureFetchDebugger::callbackHTTP(S32 id, const LLChannelDescriptors& channels, + const LLIOPipe::buffer_ptr_t& buffer, + bool partial, bool success) +{ + mNbCurlRequests--; + if (success) + { + S32 data_size = buffer->countAfter(channels.in(), NULL); + mFetchingHistory[id].mCurlReceivedSize += data_size; + llinfos << "Fetch Debugger : got results for " << id << ", data_size = " << data_size << ", received = " << mFetchingHistory[id].mCurlReceivedSize << ", requested = " << mFetchingHistory[id].mRequestedSize << ", partial = " << partial << llendl; + if ((mFetchingHistory[id].mCurlReceivedSize >= mFetchingHistory[id].mRequestedSize) || !partial || (mFetchingHistory[id].mRequestedSize == 600)) + { + mFetchingHistory[id].mCurlState = FetchEntry::CURL_DONE; + mNbCurlCompleted++; + } + } + else + { + // Fetch will have to be redone + mFetchingHistory[id].mCurlState = FetchEntry::CURL_NOT_DONE; + } +} + + //--------------------- /////////////////////////////////////////////////////////////////////////////////////////// //End LLTextureFetchDebugger diff --git a/indra/newview/lltexturefetch.h b/indra/newview/lltexturefetch.h index 529a2e6834..892857c816 100644 --- a/indra/newview/lltexturefetch.h +++ b/indra/newview/lltexturefetch.h @@ -249,8 +249,14 @@ public: private: struct FetchEntry { + enum e_curl_state + { + CURL_NOT_DONE = 0, + CURL_IN_PROGRESS, + CURL_DONE + }; LLUUID mID; - //S32 mRequestedSize; + S32 mRequestedSize; //S32 mFetchedDiscard; //S32 mComponents; S32 mDecodedLevel; @@ -260,15 +266,17 @@ private: U32 mCacheHandle; LLPointer mFormattedImage; LLPointer mRawImage; + e_curl_state mCurlState; + S32 mCurlReceivedSize; FetchEntry() : mDecodedLevel(-1), mFetchedSize(0), mDecodedSize(0) {} - FetchEntry(LLUUID& id, /*S32 r_size, S32 f_discard, S32 c,*/ S32 level, S32 f_size, S32 d_size) : + FetchEntry(LLUUID& id, S32 r_size, /*S32 f_discard, S32 c,*/ S32 level, S32 f_size, S32 d_size) : mID(id), - //mRequestedSize(r_size), + mRequestedSize(r_size), //mFetchedDiscard(f_discard), //mComponents(c), mDecodedLevel(level), @@ -306,6 +314,10 @@ private: U32 mRenderedData; U32 mRenderedDecodedData; + std::string mHTTPUrl; + S32 mNbCurlRequests; + S32 mNbCurlCompleted; + public: bool update(); //called in the main thread once per frame @@ -327,6 +339,10 @@ public: S32 imagesize, BOOL islocal); void callbackCacheWrite(S32 id, bool success); void callbackDecoded(S32 id, bool success, LLImageRaw* raw, LLImageRaw* aux); + void callbackHTTP(S32 id, const LLChannelDescriptors& channels, + const LLIOPipe::buffer_ptr_t& buffer, + bool partial, bool success); + e_debug_state getState() {return mState;} S32 getNumFetchedTextures() {return mNumFetchedTextures;} @@ -359,6 +375,8 @@ private: void lockDecoder(); void unlockDecoder(); + + S32 fillCurlQueue(); }; #endif // LL_LLTEXTUREFETCH_H -- cgit v1.2.3 From ed78cc00008b13e4a108635e851b9936688647d0 Mon Sep 17 00:00:00 2001 From: Xiaohong Bao Date: Fri, 27 Apr 2012 12:43:14 -0600 Subject: fix some flaws for SH-3104 --- indra/newview/lltexturefetch.cpp | 46 ++++++++++++++++++++++++++++++++-------- indra/newview/lltexturefetch.h | 8 +++---- 2 files changed, 40 insertions(+), 14 deletions(-) (limited to 'indra') diff --git a/indra/newview/lltexturefetch.cpp b/indra/newview/lltexturefetch.cpp index 0906626743..f2d8c27db7 100755 --- a/indra/newview/lltexturefetch.cpp +++ b/indra/newview/lltexturefetch.cpp @@ -3448,6 +3448,7 @@ void LLTextureFetchDebugger::debugHTTP() { mFetchingHistory[i].mCurlState = FetchEntry::CURL_NOT_DONE; mFetchingHistory[i].mCurlReceivedSize = 0; + mFetchingHistory[i].mHTTPFailCount = 0; } mNbCurlRequests = 0; mNbCurlCompleted = 0; @@ -3487,7 +3488,7 @@ S32 LLTextureFetchDebugger::fillCurlQueue() break; } } - llinfos << "Fetch Debugger : Having " << mNbCurlRequests << " requests through the curl thread." << llendl; + //llinfos << "Fetch Debugger : Having " << mNbCurlRequests << " requests through the curl thread." << llendl; return mNbCurlRequests; } @@ -3513,7 +3514,8 @@ void LLTextureFetchDebugger::debugGLTextureCreation() mTimer.reset(); S32 j = 0 ; - for(S32 i = 0 ; i < size ; i++) + S32 size1 = tex_list.size(); + for(S32 i = 0 ; i < size && j < size1; i++) { if(mFetchingHistory[i].mRawImage.notNull()) { @@ -3597,7 +3599,7 @@ bool LLTextureFetchDebugger::update() case HTTP_FETCHING: mCurlGetRequest->process(); LLCurl::getCurlThread()->update(1); - if (!fillCurlQueue()) + if (!fillCurlQueue() && mNbCurlCompleted == mFetchingHistory.size()) { mHTTPTime = mTimer.getElapsedTimeF32() ; mState = IDLE; @@ -3663,19 +3665,45 @@ void LLTextureFetchDebugger::callbackHTTP(S32 id, const LLChannelDescriptors& ch mNbCurlRequests--; if (success) { + mFetchingHistory[id].mCurlState = FetchEntry::CURL_DONE; + mNbCurlCompleted++; + S32 data_size = buffer->countAfter(channels.in(), NULL); mFetchingHistory[id].mCurlReceivedSize += data_size; - llinfos << "Fetch Debugger : got results for " << id << ", data_size = " << data_size << ", received = " << mFetchingHistory[id].mCurlReceivedSize << ", requested = " << mFetchingHistory[id].mRequestedSize << ", partial = " << partial << llendl; + //llinfos << "Fetch Debugger : got results for " << id << ", data_size = " << data_size << ", received = " << mFetchingHistory[id].mCurlReceivedSize << ", requested = " << mFetchingHistory[id].mRequestedSize << ", partial = " << partial << llendl; if ((mFetchingHistory[id].mCurlReceivedSize >= mFetchingHistory[id].mRequestedSize) || !partial || (mFetchingHistory[id].mRequestedSize == 600)) { - mFetchingHistory[id].mCurlState = FetchEntry::CURL_DONE; - mNbCurlCompleted++; + U8* d_buffer = (U8*)ALLOCATE_MEM(LLImageBase::getPrivatePool(), data_size); + buffer->readAfter(channels.in(), NULL, d_buffer, data_size); + + llassert_always(mFetchingHistory[id].mFormattedImage.isNull()); + { + // For now, create formatted image based on extension + std::string texture_url = mHTTPUrl + "/?texture_id=" + mFetchingHistory[id].mID.asString().c_str(); + std::string extension = gDirUtilp->getExtension(texture_url); + mFetchingHistory[id].mFormattedImage = LLImageFormatted::createFromType(LLImageBase::getCodecFromExtension(extension)); + if (mFetchingHistory[id].mFormattedImage.isNull()) + { + mFetchingHistory[id].mFormattedImage = new LLImageJ2C; // default + } + } + + mFetchingHistory[id].mFormattedImage->setData(d_buffer, data_size); } } - else + else //failed { - // Fetch will have to be redone - mFetchingHistory[id].mCurlState = FetchEntry::CURL_NOT_DONE; + mFetchingHistory[id].mHTTPFailCount++; + if(mFetchingHistory[id].mHTTPFailCount < 5) + { + // Fetch will have to be redone + mFetchingHistory[id].mCurlState = FetchEntry::CURL_NOT_DONE; + } + else //skip + { + mFetchingHistory[id].mCurlState = FetchEntry::CURL_DONE; + mNbCurlCompleted++; + } } } diff --git a/indra/newview/lltexturefetch.h b/indra/newview/lltexturefetch.h index 1538fd78ab..3b08389042 100644 --- a/indra/newview/lltexturefetch.h +++ b/indra/newview/lltexturefetch.h @@ -261,8 +261,6 @@ private: }; LLUUID mID; S32 mRequestedSize; - //S32 mFetchedDiscard; - //S32 mComponents; S32 mDecodedLevel; S32 mFetchedSize; S32 mDecodedSize; @@ -272,6 +270,7 @@ private: LLPointer mRawImage; e_curl_state mCurlState; S32 mCurlReceivedSize; + S32 mHTTPFailCount; FetchEntry() : mDecodedLevel(-1), @@ -281,12 +280,11 @@ private: FetchEntry(LLUUID& id, S32 r_size, /*S32 f_discard, S32 c,*/ S32 level, S32 f_size, S32 d_size) : mID(id), mRequestedSize(r_size), - //mFetchedDiscard(f_discard), - //mComponents(c), mDecodedLevel(level), mFetchedSize(f_size), mDecodedSize(d_size), - mNeedsAux(false) + mNeedsAux(false), + mHTTPFailCount(0) {} }; std::vector mFetchingHistory; -- cgit v1.2.3 From 9c4380a03a7b9d18cdd44662ca56cf44c4766e6f Mon Sep 17 00:00:00 2001 From: Xiaohong Bao Date: Fri, 27 Apr 2012 14:27:48 -0600 Subject: fix a crash on cache write --- indra/newview/lltexturefetch.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'indra') diff --git a/indra/newview/lltexturefetch.cpp b/indra/newview/lltexturefetch.cpp index f2d8c27db7..59a125dcc5 100755 --- a/indra/newview/lltexturefetch.cpp +++ b/indra/newview/lltexturefetch.cpp @@ -3386,10 +3386,13 @@ void LLTextureFetchDebugger::debugCacheWrite() S32 size = mFetchingHistory.size(); for(S32 i = 0 ; i < size ; i++) { - mFetchingHistory[i].mCacheHandle = mTextureCache->writeToCache(mFetchingHistory[i].mID, LLWorkerThread::PRIORITY_NORMAL, - mFetchingHistory[i].mFormattedImage->getData(), mFetchingHistory[i].mFetchedSize, - mFetchingHistory[i].mDecodedLevel == 0 ? mFetchingHistory[i].mFetchedSize : mFetchingHistory[i].mFetchedSize + 1, - new LLDebuggerCacheWriteResponder(this, i)); + if(mFetchingHistory[i].mFormattedImage.notNull()) + { + mFetchingHistory[i].mCacheHandle = mTextureCache->writeToCache(mFetchingHistory[i].mID, LLWorkerThread::PRIORITY_NORMAL, + mFetchingHistory[i].mFormattedImage->getData(), mFetchingHistory[i].mFetchedSize, + mFetchingHistory[i].mDecodedLevel == 0 ? mFetchingHistory[i].mFetchedSize : mFetchingHistory[i].mFetchedSize + 1, + new LLDebuggerCacheWriteResponder(this, i)); + } } } -- cgit v1.2.3 From 3a9aa29a44f8b20ff9aa5c5eeaf7efccc81ae608 Mon Sep 17 00:00:00 2001 From: Xiaohong Bao Date: Fri, 27 Apr 2012 16:38:16 -0600 Subject: fix for a crash on "refetch vis cache" --- indra/newview/llviewertexture.cpp | 1 + 1 file changed, 1 insertion(+) (limited to 'indra') diff --git a/indra/newview/llviewertexture.cpp b/indra/newview/llviewertexture.cpp index 6137b7176f..1b468a7b96 100644 --- a/indra/newview/llviewertexture.cpp +++ b/indra/newview/llviewertexture.cpp @@ -1305,6 +1305,7 @@ void LLViewerFetchedTexture::cleanup() mCachedRawDiscardLevel = -1 ; mCachedRawImageReady = FALSE ; mSavedRawImage = NULL ; + mSavedRawDiscardLevel = -1; } void LLViewerFetchedTexture::setForSculpt() -- cgit v1.2.3 From 164de6c1807a5517cbd2ccf7d16b536aa333e64a Mon Sep 17 00:00:00 2001 From: Xiaohong Bao Date: Fri, 27 Apr 2012 18:32:42 -0600 Subject: fix for a crash on sculpt --- indra/llrender/llimagegl.cpp | 4 ++-- indra/newview/llviewertexture.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'indra') diff --git a/indra/llrender/llimagegl.cpp b/indra/llrender/llimagegl.cpp index ab744fb7ff..bd9953e418 100755 --- a/indra/llrender/llimagegl.cpp +++ b/indra/llrender/llimagegl.cpp @@ -1464,10 +1464,10 @@ void LLImageGL::destroyGLTexture() } LLImageGL::deleteTextures(1, &mTexName); - mTexName = 0; - mCurrentDiscardLevel = -1 ; //invalidate mCurrentDiscardLevel. + mTexName = 0; mGLTextureCreated = FALSE ; } + mCurrentDiscardLevel = -1 ; //invalidate mCurrentDiscardLevel. } diff --git a/indra/newview/llviewertexture.cpp b/indra/newview/llviewertexture.cpp index 1b468a7b96..f27e20c2a2 100644 --- a/indra/newview/llviewertexture.cpp +++ b/indra/newview/llviewertexture.cpp @@ -1146,7 +1146,7 @@ S32 LLViewerTexture::getDiscardLevelInAtlas() const void LLViewerTexture::destroyGLTexture() { - if(mGLTexturep.notNull() && mGLTexturep->getHasGLTexture()) + if(mGLTexturep.notNull()) { mGLTexturep->destroyGLTexture() ; mTextureState = DELETED ; -- cgit v1.2.3 From 3f31c82a1c7a9419891ff2c7b81324e99414395e Mon Sep 17 00:00:00 2001 From: Merov Linden Date: Mon, 30 Apr 2012 17:44:44 -0700 Subject: SH-3124 : Fix crash on exit on Mac --- indra/newview/llviewertexture.cpp | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) (limited to 'indra') diff --git a/indra/newview/llviewertexture.cpp b/indra/newview/llviewertexture.cpp index f27e20c2a2..a889cd9637 100644 --- a/indra/newview/llviewertexture.cpp +++ b/indra/newview/llviewertexture.cpp @@ -390,6 +390,7 @@ void LLViewerTextureManager::cleanup() LLImageGL::sDefaultGLTexture = NULL ; LLViewerTexture::sNullImagep = NULL; LLViewerTexture::sBlackImagep = NULL; + LLViewerTexture::sCheckerBoardImagep = NULL; LLViewerFetchedTexture::sDefaultImagep = NULL; LLViewerFetchedTexture::sSmokeImagep = NULL; LLViewerFetchedTexture::sMissingAssetImagep = NULL; @@ -2156,16 +2157,16 @@ void LLViewerFetchedTexture::clearFetchedResults() destroyGLTexture(); } -void LLViewerFetchedTexture::forceToDeleteRequest() -{ - if (mHasFetcher) - { - LLAppViewer::getTextureFetch()->deleteRequest(getID(), true); - mHasFetcher = FALSE; - mIsFetching = FALSE ; - resetTextureStats(); - } -} +void LLViewerFetchedTexture::forceToDeleteRequest() +{ + if (mHasFetcher) + { + LLAppViewer::getTextureFetch()->deleteRequest(getID(), true); + mHasFetcher = FALSE; + mIsFetching = FALSE ; + resetTextureStats(); + } +} void LLViewerFetchedTexture::setIsMissingAsset() { -- cgit v1.2.3 From c0855030de1e0811b3db8b8d98d089956fda24c8 Mon Sep 17 00:00:00 2001 From: Merov Linden Date: Mon, 30 Apr 2012 19:10:55 -0700 Subject: Fix sculpties being deleted while being still in use in the scene --- indra/newview/llviewertexture.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/newview/llviewertexture.cpp b/indra/newview/llviewertexture.cpp index a889cd9637..90ba21ef34 100644 --- a/indra/newview/llviewertexture.cpp +++ b/indra/newview/llviewertexture.cpp @@ -1147,7 +1147,7 @@ S32 LLViewerTexture::getDiscardLevelInAtlas() const void LLViewerTexture::destroyGLTexture() { - if(mGLTexturep.notNull()) + if(mGLTexturep.notNull() && mGLTexturep->getHasGLTexture()) { mGLTexturep->destroyGLTexture() ; mTextureState = DELETED ; -- cgit v1.2.3 From bea4733193121a3918269101ba68fd7282e158ae Mon Sep 17 00:00:00 2001 From: Jonathan Yap Date: Tue, 1 May 2012 12:19:00 -0400 Subject: STORM-1842 Change variable setting from TRUE to true --- indra/newview/llappviewer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/newview/llappviewer.cpp b/indra/newview/llappviewer.cpp index c0197db4fc..8e8db07078 100644 --- a/indra/newview/llappviewer.cpp +++ b/indra/newview/llappviewer.cpp @@ -4964,7 +4964,7 @@ void LLAppViewer::handleLoginComplete() // we logged in successfully, so save settings on logout llinfos << "Login successful, per account settings will be saved on log out." << llendl; - mSavePerAccountSettings=TRUE; + mSavePerAccountSettings=true; } // *TODO - generalize this and move DSO wrangling to a helper class -brad -- cgit v1.2.3 From 7a20b5be7844d1f41307d3186b0a9e297efd797a Mon Sep 17 00:00:00 2001 From: Dave Parks Date: Tue, 1 May 2012 15:33:16 -0500 Subject: MAINT-775, MAINT-1022 Regression cleanup. --- indra/newview/lldrawable.cpp | 14 ++++--------- indra/newview/llflexibleobject.cpp | 8 +++++--- indra/newview/llflexibleobject.h | 2 +- indra/newview/llspatialpartition.cpp | 40 +++++++++++++++++++++++------------- indra/newview/llvovolume.cpp | 8 +++++--- indra/newview/llvovolume.h | 2 +- indra/newview/pipeline.cpp | 12 +++++------ 7 files changed, 48 insertions(+), 38 deletions(-) (limited to 'indra') diff --git a/indra/newview/lldrawable.cpp b/indra/newview/lldrawable.cpp index d2cedc7035..55fb135898 100644 --- a/indra/newview/lldrawable.cpp +++ b/indra/newview/lldrawable.cpp @@ -551,8 +551,6 @@ F32 LLDrawable::updateXform(BOOL undamped) LLVector3 vec = mCurrentScale-target_scale; - - if (vec*vec > MIN_INTERPOLATE_DISTANCE_SQUARED) { //scale change requires immediate rebuild mCurrentScale = target_scale; @@ -560,18 +558,14 @@ F32 LLDrawable::updateXform(BOOL undamped) } else if (!isRoot() && (!mVObjp->getAngularVelocity().isExactlyZero() || - target_pos != mXform.getPosition() || - target_rot != mXform.getRotation())) + dist_squared > 0.f)) { //child prim moving relative to parent, tag as needing to be rendered atomically and rebuild + dist_squared = 1.f; //keep this object on the move list if (!isState(LLDrawable::ANIMATED_CHILD)) - { + { setState(LLDrawable::ANIMATED_CHILD); gPipeline.markRebuild(this, LLDrawable::REBUILD_ALL, TRUE); - LLSpatialGroup* group = getSpatialGroup(); - if (group) - { - gPipeline.markRebuild(group, TRUE); - } + mVObjp->dirtySpatialGroup(); } } else if (!getVOVolume() && !isAvatar()) diff --git a/indra/newview/llflexibleobject.cpp b/indra/newview/llflexibleobject.cpp index 1876d2dc33..11edb60712 100644 --- a/indra/newview/llflexibleobject.cpp +++ b/indra/newview/llflexibleobject.cpp @@ -818,15 +818,17 @@ LLQuaternion LLVolumeImplFlexible::getEndRotation() }//------------------------------------------------------------------ -void LLVolumeImplFlexible::updateRelativeXform() +void LLVolumeImplFlexible::updateRelativeXform(bool force_identity) { LLQuaternion delta_rot; LLVector3 delta_pos, delta_scale; LLVOVolume* vo = (LLVOVolume*) mVO; + bool use_identity = vo->mDrawable->isSpatialRoot() || force_identity; + //matrix from local space to parent relative/global space - delta_rot = vo->mDrawable->isSpatialRoot() ? LLQuaternion() : vo->mDrawable->getRotation(); - delta_pos = vo->mDrawable->isSpatialRoot() ? LLVector3(0,0,0) : vo->mDrawable->getPosition(); + delta_rot = use_identity ? LLQuaternion() : vo->mDrawable->getRotation(); + delta_pos = use_identity ? LLVector3(0,0,0) : vo->mDrawable->getPosition(); delta_scale = LLVector3(1,1,1); // Vertex transform (4x4) diff --git a/indra/newview/llflexibleobject.h b/indra/newview/llflexibleobject.h index fef43d464d..371d6a0773 100644 --- a/indra/newview/llflexibleobject.h +++ b/indra/newview/llflexibleobject.h @@ -89,7 +89,7 @@ class LLVolumeImplFlexible : public LLVolumeInterface bool isVolumeGlobal() const { return true; } bool isActive() const { return true; } const LLMatrix4& getWorldMatrix(LLXformMatrix* xform) const; - void updateRelativeXform(); + void updateRelativeXform(bool force_identity); void doFlexibleUpdate(); // Called to update the simulation void doFlexibleRebuild(); // Called to rebuild the geometry void preRebuild(); diff --git a/indra/newview/llspatialpartition.cpp b/indra/newview/llspatialpartition.cpp index 1ded126bee..27dea1c7a0 100644 --- a/indra/newview/llspatialpartition.cpp +++ b/indra/newview/llspatialpartition.cpp @@ -699,6 +699,9 @@ void LLSpatialGroup::rebuildMesh() } static LLFastTimer::DeclareTimer FTM_REBUILD_VBO("VBO Rebuilt"); +static LLFastTimer::DeclareTimer FTM_ADD_GEOMETRY_COUNT("Add Geometry"); +static LLFastTimer::DeclareTimer FTM_CREATE_VB("Create VB"); +static LLFastTimer::DeclareTimer FTM_GET_GEOMETRY("Get Geometry"); void LLSpatialPartition::rebuildGeom(LLSpatialGroup* group) { @@ -720,27 +723,36 @@ void LLSpatialPartition::rebuildGeom(LLSpatialGroup* group) //get geometry count U32 index_count = 0; U32 vertex_count = 0; - - addGeometryCount(group, vertex_count, index_count); + + { + LLFastTimer t(FTM_ADD_GEOMETRY_COUNT); + addGeometryCount(group, vertex_count, index_count); + } if (vertex_count > 0 && index_count > 0) { //create vertex buffer containing volume geometry for this node - group->mBuilt = 1.f; - if (group->mVertexBuffer.isNull() || - !group->mVertexBuffer->isWriteable() || - (group->mBufferUsage != group->mVertexBuffer->getUsage() && LLVertexBuffer::sEnableVBOs)) { - group->mVertexBuffer = createVertexBuffer(mVertexDataMask, group->mBufferUsage); - group->mVertexBuffer->allocateBuffer(vertex_count, index_count, true); - stop_glerror(); + LLFastTimer t(FTM_CREATE_VB); + group->mBuilt = 1.f; + if (group->mVertexBuffer.isNull() || + !group->mVertexBuffer->isWriteable() || + (group->mBufferUsage != group->mVertexBuffer->getUsage() && LLVertexBuffer::sEnableVBOs)) + { + group->mVertexBuffer = createVertexBuffer(mVertexDataMask, group->mBufferUsage); + group->mVertexBuffer->allocateBuffer(vertex_count, index_count, true); + stop_glerror(); + } + else + { + group->mVertexBuffer->resizeBuffer(vertex_count, index_count); + stop_glerror(); + } } - else + { - group->mVertexBuffer->resizeBuffer(vertex_count, index_count); - stop_glerror(); + LLFastTimer t(FTM_GET_GEOMETRY); + getGeometry(group); } - - getGeometry(group); } else { diff --git a/indra/newview/llvovolume.cpp b/indra/newview/llvovolume.cpp index 433fa475ee..3430e1a610 100644 --- a/indra/newview/llvovolume.cpp +++ b/indra/newview/llvovolume.cpp @@ -684,7 +684,7 @@ void LLVOVolume::updateTextures() { updateTextureVirtualSize(); - /*if (mDrawable.notNull() && !isVisible() && !mDrawable->isActive()) + if (mDrawable.notNull() && !isVisible() && !mDrawable->isActive()) { //delete vertex buffer to free up some VRAM LLSpatialGroup* group = mDrawable->getSpatialGroup(); if (group) @@ -695,7 +695,7 @@ void LLVOVolume::updateTextures() //it becomes visible group->setState(LLSpatialGroup::GEOM_DIRTY | LLSpatialGroup::MESH_DIRTY | LLSpatialGroup::NEW_DRAWINFO); } - }*/ + } } } @@ -1497,7 +1497,7 @@ void LLVOVolume::updateRelativeXform(bool force_identity) { if (mVolumeImpl) { - mVolumeImpl->updateRelativeXform(); + mVolumeImpl->updateRelativeXform(force_identity); return; } @@ -3984,6 +3984,8 @@ void LLVolumeGeometryManager::registerFace(LLSpatialGroup* group, LLFace* facep, } } + //drawable->getVObj()->setDebugText(llformat("%d", drawable->isState(LLDrawable::ANIMATED_CHILD))); + U8 bump = (type == LLRenderPass::PASS_BUMP || type == LLRenderPass::PASS_POST_BUMP) ? facep->getTextureEntry()->getBumpmap() : 0; LLViewerTexture* tex = facep->getTexture(); diff --git a/indra/newview/llvovolume.h b/indra/newview/llvovolume.h index b2873c9894..c4505b4bd8 100644 --- a/indra/newview/llvovolume.h +++ b/indra/newview/llvovolume.h @@ -79,7 +79,7 @@ public: virtual bool isVolumeGlobal() const = 0; // Are we in global space? virtual bool isActive() const = 0; // Is this object currently active? virtual const LLMatrix4& getWorldMatrix(LLXformMatrix* xform) const = 0; - virtual void updateRelativeXform() = 0; + virtual void updateRelativeXform(bool force_identity = false) = 0; virtual U32 getID() const = 0; virtual void preRebuild() = 0; }; diff --git a/indra/newview/pipeline.cpp b/indra/newview/pipeline.cpp index 4a0ccb3e5d..93b6e9ae17 100644 --- a/indra/newview/pipeline.cpp +++ b/indra/newview/pipeline.cpp @@ -1794,15 +1794,15 @@ void LLPipeline::updateMovedList(LLDrawable::drawable_vector_t& moved_list) if (done) { drawablep->clearState(LLDrawable::ON_MOVE_LIST); - if (drawablep->isState(LLDrawable::ANIMATED_CHILD)) // && drawablep->getVObj()->getAngularVelocity().isExactlyZero()) - { //not a target omega object, will likely not receive any future world matrix updates + if (drawablep->isState(LLDrawable::ANIMATED_CHILD)) + { //will likely not receive any future world matrix updates // -- this keeps attachments from getting stuck in space and falling off your avatar drawablep->clearState(LLDrawable::ANIMATED_CHILD); - LLSpatialGroup* group = drawablep->getSpatialGroup(); - if (group) + markRebuild(drawablep, LLDrawable::REBUILD_VOLUME, TRUE); + if (drawablep->getVObj()) { - group->dirtyGeom(); - } + drawablep->getVObj()->dirtySpatialGroup(TRUE); + } } iter = moved_list.erase(curiter); } -- cgit v1.2.3 From cabc36e993e8876a99c019e19fdf7e2ff0737af8 Mon Sep 17 00:00:00 2001 From: Dave Parks Date: Tue, 1 May 2012 15:59:46 -0500 Subject: MAINT-847 Disable VBO on ATI cards with old drivers by default --- indra/newview/featuretable.txt | 1 + indra/newview/featuretable_xp.txt | 1 + 2 files changed, 2 insertions(+) (limited to 'indra') diff --git a/indra/newview/featuretable.txt b/indra/newview/featuretable.txt index e8a109e661..eeb632acaf 100644 --- a/indra/newview/featuretable.txt +++ b/indra/newview/featuretable.txt @@ -520,6 +520,7 @@ Disregard128DefaultDrawDistance 1 0 list ATIOldDriver RenderAvatarVP 0 0 RenderAvatarCloth 0 0 +RenderVBOEnable 1 0 // ATI cards generally perform better when not using VBOs for streaming data diff --git a/indra/newview/featuretable_xp.txt b/indra/newview/featuretable_xp.txt index 398a64378e..a945f7a693 100644 --- a/indra/newview/featuretable_xp.txt +++ b/indra/newview/featuretable_xp.txt @@ -517,6 +517,7 @@ Disregard128DefaultDrawDistance 1 0 list ATIOldDriver RenderAvatarVP 0 0 RenderAvatarCloth 0 0 +RenderVBOEnable 1 0 // ATI cards generally perform better when not using VBOs for streaming data -- cgit v1.2.3 From aa44ec81e18fa91e718e1a22606b3f385bb8170f Mon Sep 17 00:00:00 2001 From: Xiaohong Bao Date: Tue, 1 May 2012 16:49:28 -0600 Subject: for SH-3118: add a toggle "TextureFetchDebuggerEnabled" to turn the console on and off. --- indra/newview/app_settings/settings.xml | 11 ++++++++++ indra/newview/llappviewer.cpp | 13 +++++++----- indra/newview/lltexturefetch.cpp | 23 ++++++++++++++++----- indra/newview/lltexturefetch.h | 6 ++++++ indra/newview/llviewerfloaterreg.cpp | 6 +++++- indra/newview/llviewermenu.cpp | 11 ++++++++++ indra/newview/llviewertexture.cpp | 5 +++-- indra/newview/llviewertexture.h | 1 + indra/newview/skins/default/xui/en/menu_viewer.xml | 24 ++++++++++++++-------- 9 files changed, 78 insertions(+), 22 deletions(-) (limited to 'indra') diff --git a/indra/newview/app_settings/settings.xml b/indra/newview/app_settings/settings.xml index d24d1ebd6d..c2f3d244f3 100755 --- a/indra/newview/app_settings/settings.xml +++ b/indra/newview/app_settings/settings.xml @@ -10697,6 +10697,17 @@ Value 0 + TextureFetchDebuggerEnabled + + Comment + Enable the texture fetching debugger if set + Persist + 1 + Type + Boolean + Value + 0 + TextureLoadFullRes Comment diff --git a/indra/newview/llappviewer.cpp b/indra/newview/llappviewer.cpp index bb6658dc48..178b96e42e 100644 --- a/indra/newview/llappviewer.cpp +++ b/indra/newview/llappviewer.cpp @@ -1405,12 +1405,15 @@ bool LLAppViewer::mainLoop() } //texture fetching debugger - LLFloaterTextureFetchDebugger* tex_fetch_debugger_instance = - LLFloaterReg::findTypedInstance("tex_fetch_debugger"); - if(tex_fetch_debugger_instance) + if(LLTextureFetchDebugger::isEnabled()) { - tex_fetch_debugger_instance->idle() ; - } + LLFloaterTextureFetchDebugger* tex_fetch_debugger_instance = + LLFloaterReg::findTypedInstance("tex_fetch_debugger"); + if(tex_fetch_debugger_instance) + { + tex_fetch_debugger_instance->idle() ; + } + } if ((LLStartUp::getStartupState() >= STATE_CLEANUP) && (frameTimer.getElapsedTimeF64() > FRAME_STALL_THRESHOLD)) diff --git a/indra/newview/lltexturefetch.cpp b/indra/newview/lltexturefetch.cpp index 59a125dcc5..efb6ed6079 100755 --- a/indra/newview/lltexturefetch.cpp +++ b/indra/newview/lltexturefetch.cpp @@ -56,6 +56,7 @@ #include "llstartup.h" #include "llviewerstats.h" +bool LLTextureFetchDebugger::sDebuggerEnabled = false ; LLStat LLTextureFetch::sCacheHitRate("texture_cache_hits", 128); LLStat LLTextureFetch::sCacheReadLatency("texture_cache_read_latency", 128); @@ -1424,7 +1425,7 @@ bool LLTextureFetchWorker::doWork(S32 param) { if (mDecoded) { - if(!mInLocalCache) + if(mFetcher->getFetchDebugger() && !mInLocalCache) { mFetcher->getFetchDebugger()->addHistoryEntry(this); } @@ -1858,13 +1859,18 @@ LLTextureFetch::LLTextureFetch(LLTextureCache* cache, LLImageDecodeThread* image mHTTPTextureBits(0), mTotalHTTPRequests(0), mCurlGetRequest(NULL), - mQAMode(qa_mode) + mQAMode(qa_mode), + mFetchDebugger(NULL) { mCurlPOSTRequestCount = 0; mMaxBandwidth = gSavedSettings.getF32("ThrottleBandwidthKBPS"); mTextureInfo.setUpLogging(gSavedSettings.getBOOL("LogTextureDownloadsToViewerLog"), gSavedSettings.getBOOL("LogTextureDownloadsToSimulator"), gSavedSettings.getU32("TextureLoggingThreshold")); - mFetchDebugger = new LLTextureFetchDebugger(this, cache, imagedecodethread) ; + LLTextureFetchDebugger::sDebuggerEnabled = gSavedSettings.getBOOL("TextureFetchDebuggerEnabled"); + if(LLTextureFetchDebugger::isEnabled()) + { + mFetchDebugger = new LLTextureFetchDebugger(this, cache, imagedecodethread) ; + } } LLTextureFetch::~LLTextureFetch() @@ -2311,7 +2317,11 @@ void LLTextureFetch::startThread() { // Construct mCurlGetRequest from Worker Thread mCurlGetRequest = new LLCurlRequest(); - mFetchDebugger->setCurlGetRequest(mCurlGetRequest); + + if(mFetchDebugger) + { + mFetchDebugger->setCurlGetRequest(mCurlGetRequest); + } } // WORKER THREAD @@ -2320,7 +2330,10 @@ void LLTextureFetch::endThread() // Destroy mCurlGetRequest from Worker Thread delete mCurlGetRequest; mCurlGetRequest = NULL; - mFetchDebugger->setCurlGetRequest(NULL); + if(mFetchDebugger) + { + mFetchDebugger->setCurlGetRequest(NULL); + } } // WORKER THREAD diff --git a/indra/newview/lltexturefetch.h b/indra/newview/lltexturefetch.h index 3b08389042..107e1623b0 100644 --- a/indra/newview/lltexturefetch.h +++ b/indra/newview/lltexturefetch.h @@ -230,6 +230,7 @@ public: //debug use class LLTextureFetchDebugger { + friend class LLTextureFetch; public: LLTextureFetchDebugger(LLTextureFetch* fetcher, LLTextureCache* cache, LLImageDecodeThread* imagedecodethread) ; ~LLTextureFetchDebugger(); @@ -398,6 +399,11 @@ private: void unlockDecoder(); S32 fillCurlQueue(); + +private: + static bool sDebuggerEnabled; +public: + static bool isEnabled() {return sDebuggerEnabled;} }; #endif // LL_LLTEXTUREFETCH_H diff --git a/indra/newview/llviewerfloaterreg.cpp b/indra/newview/llviewerfloaterreg.cpp index 986b8ac3c5..a7ca7a0836 100644 --- a/indra/newview/llviewerfloaterreg.cpp +++ b/indra/newview/llviewerfloaterreg.cpp @@ -228,7 +228,11 @@ void LLViewerFloaterReg::registerFloaters() LLFloaterReg::add("land_holdings", "floater_land_holdings.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("mem_leaking", "floater_mem_leaking.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); - LLFloaterReg::add("tex_fetch_debugger", "floater_texture_fetch_debugger.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); + + if(gSavedSettings.getBOOL("TextureFetchDebuggerEnabled")) + { + LLFloaterReg::add("tex_fetch_debugger", "floater_texture_fetch_debugger.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); + } LLFloaterReg::add("media_settings", "floater_media_settings.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("message_critical", "floater_critical.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("message_tos", "floater_tos.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); diff --git a/indra/newview/llviewermenu.cpp b/indra/newview/llviewermenu.cpp index 7bdfd6df1d..2a3ba4e603 100644 --- a/indra/newview/llviewermenu.cpp +++ b/indra/newview/llviewermenu.cpp @@ -2286,6 +2286,14 @@ class LLDevelopSetLoggingLevel : public view_listener_t } }; +class LLDevelopTextureFetchDebugger : public view_listener_t +{ + bool handleEvent(const LLSD& userdata) + { + return gSavedSettings.getBOOL("TextureFetchDebuggerEnabled"); + } +}; + ////////////////// // ADMIN MENU // ////////////////// @@ -8308,6 +8316,9 @@ void initialize_menus() // Develop >Set logging level view_listener_t::addMenu(new LLDevelopCheckLoggingLevel(), "Develop.CheckLoggingLevel"); view_listener_t::addMenu(new LLDevelopSetLoggingLevel(), "Develop.SetLoggingLevel"); + + //Develop (Texture Fetch Debug Console) + view_listener_t::addMenu(new LLDevelopTextureFetchDebugger(), "Develop.SetTexFetchDebugger"); // Admin >Object view_listener_t::addMenu(new LLAdminForceTakeCopy(), "Admin.ForceTakeCopy"); diff --git a/indra/newview/llviewertexture.cpp b/indra/newview/llviewertexture.cpp index 90ba21ef34..d83a595220 100644 --- a/indra/newview/llviewertexture.cpp +++ b/indra/newview/llviewertexture.cpp @@ -98,6 +98,8 @@ S32 LLViewerTexture::sMaxSmallImageSize = MAX_CACHED_RAW_IMAGE_AREA ; BOOL LLViewerTexture::sFreezeImageScalingDown = FALSE ; F32 LLViewerTexture::sCurrentTime = 0.0f ; BOOL LLViewerTexture::sUseTextureAtlas = FALSE ; +F32 LLViewerTexture::sTexelPixelRatio = 1.0f; + LLViewerTexture::EDebugTexels LLViewerTexture::sDebugTexelsMode = LLViewerTexture::DEBUG_TEXELS_OFF; const F32 desired_discard_bias_min = -2.0f; // -max number of levels to improve image quality by @@ -407,6 +409,7 @@ void LLViewerTextureManager::cleanup() void LLViewerTexture::initClass() { LLImageGL::sDefaultGLTexture = LLViewerFetchedTexture::sDefaultImagep->getGLTexture() ; + sTexelPixelRatio = gSavedSettings.getF32("TexelPixelRatio"); } // static @@ -723,8 +726,6 @@ void LLViewerTexture::forceImmediateUpdate() void LLViewerTexture::addTextureStats(F32 virtual_size, BOOL needs_gltexture) const { - static LLCachedControl sTexelPixelRatio(gSavedSettings,"TexelPixelRatio"); - if(needs_gltexture) { mNeedsGLTexture = TRUE ; diff --git a/indra/newview/llviewertexture.h b/indra/newview/llviewertexture.h index 95896f9d41..41bf625225 100644 --- a/indra/newview/llviewertexture.h +++ b/indra/newview/llviewertexture.h @@ -310,6 +310,7 @@ protected: } LLGLTextureState; LLGLTextureState mTextureState ; + static F32 sTexelPixelRatio; public: static const U32 sCurrentFileVersion; static S32 sImageCount; diff --git a/indra/newview/skins/default/xui/en/menu_viewer.xml b/indra/newview/skins/default/xui/en/menu_viewer.xml index a1f17ffc17..5d46b0f98d 100644 --- a/indra/newview/skins/default/xui/en/menu_viewer.xml +++ b/indra/newview/skins/default/xui/en/menu_viewer.xml @@ -1876,14 +1876,7 @@ - - - - + - + + + + + + Date: Tue, 1 May 2012 21:29:19 -0600 Subject: fix a sculpt crash --- indra/llrender/llimagegl.cpp | 17 ++++++++++++++--- indra/llrender/llimagegl.h | 1 + indra/newview/llviewertexture.cpp | 5 +++++ 3 files changed, 20 insertions(+), 3 deletions(-) (limited to 'indra') diff --git a/indra/llrender/llimagegl.cpp b/indra/llrender/llimagegl.cpp index bd9953e418..2c13fead97 100755 --- a/indra/llrender/llimagegl.cpp +++ b/indra/llrender/llimagegl.cpp @@ -1464,13 +1464,24 @@ void LLImageGL::destroyGLTexture() } LLImageGL::deleteTextures(1, &mTexName); + mCurrentDiscardLevel = -1 ; //invalidate mCurrentDiscardLevel. mTexName = 0; mGLTextureCreated = FALSE ; - } - mCurrentDiscardLevel = -1 ; //invalidate mCurrentDiscardLevel. + } } - +//force to invalidate the gl texture, most likely a sculpty texture +void LLImageGL::forceToInvalidateGLTexture() +{ + if (mTexName != 0) + { + destroyGLTexture(); + } + else + { + mCurrentDiscardLevel = -1 ; //invalidate mCurrentDiscardLevel. + } +} //---------------------------------------------------------------------------- diff --git a/indra/llrender/llimagegl.h b/indra/llrender/llimagegl.h index 2060be914b..e515d6b324 100755 --- a/indra/llrender/llimagegl.h +++ b/indra/llrender/llimagegl.h @@ -114,6 +114,7 @@ public: // Read back a raw image for this discard level, if it exists BOOL readBackRaw(S32 discard_level, LLImageRaw* imageraw, bool compressed_ok) const; void destroyGLTexture(); + void forceToInvalidateGLTexture(); void setExplicitFormat(LLGLint internal_format, LLGLenum primary_format, LLGLenum type_format = 0, BOOL swap_bytes = FALSE); void setComponents(S8 ncomponents) { mComponents = ncomponents; } diff --git a/indra/newview/llviewertexture.cpp b/indra/newview/llviewertexture.cpp index d83a595220..ea329f6aac 100644 --- a/indra/newview/llviewertexture.cpp +++ b/indra/newview/llviewertexture.cpp @@ -2156,6 +2156,11 @@ void LLViewerFetchedTexture::clearFetchedResults() cleanup(); destroyGLTexture(); + + if(getDiscardLevel() >= 0) //sculpty texture, force to invalidate + { + mGLTexturep->forceToInvalidateGLTexture(); + } } void LLViewerFetchedTexture::forceToDeleteRequest() -- cgit v1.2.3 From 423659c68076f99a73985b9bd1befa5c0f5d3457 Mon Sep 17 00:00:00 2001 From: Dave Parks Date: Wed, 2 May 2012 15:45:38 -0500 Subject: MAINT-775 Particle vertex buffer management optimizations --- indra/llcommon/llstrider.h | 10 ++ indra/newview/llface.cpp | 19 ++- indra/newview/llspatialpartition.h | 7 +- indra/newview/llviewerpartsim.cpp | 2 +- indra/newview/llviewerpartsim.h | 2 + indra/newview/llviewerwindow.cpp | 6 +- indra/newview/llvograss.cpp | 139 +++++++++++++++++++ indra/newview/llvopartgroup.cpp | 265 +++++++++++++++++++++++++++---------- indra/newview/llvopartgroup.h | 13 ++ indra/newview/pipeline.cpp | 26 ++-- 10 files changed, 403 insertions(+), 86 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/llstrider.h b/indra/llcommon/llstrider.h index f4c43bac61..ed9284d2c5 100644 --- a/indra/llcommon/llstrider.h +++ b/indra/llcommon/llstrider.h @@ -44,6 +44,15 @@ public: const LLStrider& operator = (Object *first) { mObjectp = first; return *this;} void setStride (S32 skipBytes) { mSkip = (skipBytes ? skipBytes : sizeof(Object));} + LLStrider operator+(const S32& index) + { + LLStrider ret; + ret.mBytep = mBytep + mSkip*index; + ret.mSkip = mSkip; + + return ret; + } + void skip(const U32 index) { mBytep += mSkip*index;} U32 getSkip() const { return mSkip; } Object* get() { return mObjectp; } @@ -51,6 +60,7 @@ public: Object& operator *() { return *mObjectp; } Object* operator ++(int) { Object* old = mObjectp; mBytep += mSkip; return old; } Object* operator +=(int i) { mBytep += mSkip*i; return mObjectp; } + Object& operator[](U32 index) { return *(Object*)(mBytep + (mSkip * index)); } }; diff --git a/indra/newview/llface.cpp b/indra/newview/llface.cpp index 4108d69e82..97b832520d 100644 --- a/indra/newview/llface.cpp +++ b/indra/newview/llface.cpp @@ -44,6 +44,7 @@ #include "llsky.h" #include "llviewercamera.h" #include "llviewertexturelist.h" +#include "llvopartgroup.h" #include "llvosky.h" #include "llvovolume.h" #include "pipeline.h" @@ -161,7 +162,15 @@ void LLFace::init(LLDrawable* drawablep, LLViewerObject* objp) mGeomCount = 0; mGeomIndex = 0; mIndicesCount = 0; - mIndicesIndex = 0; + if (drawablep->getRenderType() == LLPipeline::RENDER_TYPE_PARTICLES || + drawablep->getRenderType() == LLPipeline::RENDER_TYPE_HUD_PARTICLES) + { //indicate to LLParticlePartition that this particle is uninitialized + mIndicesIndex = 0xFFFFFFFF; + } + else + { + mIndicesIndex = 0; + } mIndexInTex = 0; mTexture = NULL; mTEOffset = -1; @@ -203,6 +212,14 @@ void LLFace::destroy() mTexture->removeFace(this) ; } + if (mDrawablep.notNull() && + (mDrawablep->getRenderType() == LLPipeline::RENDER_TYPE_PARTICLES || + mDrawablep->getRenderType() == LLPipeline::RENDER_TYPE_HUD_PARTICLES) && + mIndicesIndex != 0xFFFFFFFF) + { + LLVOPartGroup::freeVBSlot(getGeomIndex()/4); + } + if (mDrawPoolp) { if (this->isState(LLFace::RIGGED) && mDrawPoolp->getType() == LLDrawPool::POOL_AVATAR) diff --git a/indra/newview/llspatialpartition.h b/indra/newview/llspatialpartition.h index ccc65f3da0..65ae41eeee 100644 --- a/indra/newview/llspatialpartition.h +++ b/indra/newview/llspatialpartition.h @@ -657,6 +657,7 @@ class LLParticlePartition : public LLSpatialPartition { public: LLParticlePartition(); + virtual void rebuildGeom(LLSpatialGroup* group); virtual void getGeometry(LLSpatialGroup* group); virtual void addGeometryCount(LLSpatialGroup* group, U32 &vertex_count, U32& index_count); virtual F32 calcPixelArea(LLSpatialGroup* group, LLCamera& camera); @@ -671,10 +672,14 @@ public: }; //spatial partition for grass (implemented in LLVOGrass.cpp) -class LLGrassPartition : public LLParticlePartition +class LLGrassPartition : public LLSpatialPartition { public: LLGrassPartition(); + virtual void getGeometry(LLSpatialGroup* group); + virtual void addGeometryCount(LLSpatialGroup* group, U32 &vertex_count, U32& index_count); +protected: + U32 mRenderPass; }; //class for wrangling geometry out of volumes (implemented in LLVOVolume.cpp) diff --git a/indra/newview/llviewerpartsim.cpp b/indra/newview/llviewerpartsim.cpp index 6b3e04348a..345023dbfa 100644 --- a/indra/newview/llviewerpartsim.cpp +++ b/indra/newview/llviewerpartsim.cpp @@ -476,7 +476,7 @@ void LLViewerPartSim::checkParticleCount(U32 size) LLViewerPartSim::LLViewerPartSim() { LLMemType mt(LLMemType::MTYPE_PARTICLES); - sMaxParticleCount = gSavedSettings.getS32("RenderMaxPartCount"); + sMaxParticleCount = llmin(gSavedSettings.getS32("RenderMaxPartCount"), LL_MAX_PARTICLE_COUNT); static U32 id_seed = 0; mID = ++id_seed; } diff --git a/indra/newview/llviewerpartsim.h b/indra/newview/llviewerpartsim.h index 3e20f999c0..c9959c63ec 100644 --- a/indra/newview/llviewerpartsim.h +++ b/indra/newview/llviewerpartsim.h @@ -39,6 +39,8 @@ class LLViewerRegion; class LLViewerTexture; class LLVOPartGroup; +#define LL_MAX_PARTICLE_COUNT 8192 + typedef void (*LLVPCallback)(LLViewerPart &part, const F32 dt); /////////////////// diff --git a/indra/newview/llviewerwindow.cpp b/indra/newview/llviewerwindow.cpp index 35527d4977..0a582107af 100755 --- a/indra/newview/llviewerwindow.cpp +++ b/indra/newview/llviewerwindow.cpp @@ -175,6 +175,7 @@ #include "llviewershadermgr.h" #include "llviewerstats.h" #include "llvoavatarself.h" +#include "llvopartgroup.h" #include "llvovolume.h" #include "llworld.h" #include "llworldmapview.h" @@ -4654,6 +4655,8 @@ void LLViewerWindow::stopGL(BOOL save_state) LLVOAvatar::destroyGL(); stop_glerror(); + LLVOPartGroup::destroyGL(); + LLViewerDynamicTexture::destroyGL(); stop_glerror(); @@ -4707,7 +4710,8 @@ void LLViewerWindow::restoreGL(const std::string& progress_message) gBumpImageList.restoreGL(); LLViewerDynamicTexture::restoreGL(); LLVOAvatar::restoreGL(); - + LLVOPartGroup::restoreGL(); + gResizeScreenTexture = TRUE; gWindowResized = TRUE; diff --git a/indra/newview/llvograss.cpp b/indra/newview/llvograss.cpp index 8a79d564d3..be3558aad1 100644 --- a/indra/newview/llvograss.cpp +++ b/indra/newview/llvograss.cpp @@ -34,6 +34,7 @@ #include "llagentcamera.h" #include "llnotificationsutil.h" #include "lldrawable.h" +#include "lldrawpoolalpha.h" #include "llface.h" #include "llsky.h" #include "llsurface.h" @@ -594,6 +595,7 @@ U32 LLVOGrass::getPartitionType() const } LLGrassPartition::LLGrassPartition() +: LLSpatialPartition(LLDrawPoolAlpha::VERTEX_DATA_MASK | LLVertexBuffer::MAP_TEXTURE_INDEX, TRUE, GL_STREAM_DRAW_ARB) { mDrawableType = LLPipeline::RENDER_TYPE_GRASS; mPartitionType = LLViewerRegion::PARTITION_GRASS; @@ -604,6 +606,143 @@ LLGrassPartition::LLGrassPartition() mBufferUsage = GL_DYNAMIC_DRAW_ARB; } +void LLGrassPartition::addGeometryCount(LLSpatialGroup* group, U32& vertex_count, U32& index_count) +{ + group->mBufferUsage = mBufferUsage; + + mFaceList.clear(); + + LLViewerCamera* camera = LLViewerCamera::getInstance(); + for (LLSpatialGroup::element_iter i = group->getData().begin(); i != group->getData().end(); ++i) + { + LLDrawable* drawablep = *i; + + if (drawablep->isDead()) + { + continue; + } + + LLAlphaObject* obj = (LLAlphaObject*) drawablep->getVObj().get(); + obj->mDepth = 0.f; + + if (drawablep->isAnimating()) + { + group->mBufferUsage = GL_STREAM_DRAW_ARB; + } + + U32 count = 0; + for (S32 j = 0; j < drawablep->getNumFaces(); ++j) + { + drawablep->updateFaceSize(j); + + LLFace* facep = drawablep->getFace(j); + if ( !facep || !facep->hasGeometry()) + { + continue; + } + + if ((facep->getGeomCount() + vertex_count) <= 65536) + { + count++; + facep->mDistance = (facep->mCenterLocal - camera->getOrigin()) * camera->getAtAxis(); + obj->mDepth += facep->mDistance; + + mFaceList.push_back(facep); + vertex_count += facep->getGeomCount(); + index_count += facep->getIndicesCount(); + llassert(facep->getIndicesCount() < 65536); + } + else + { + facep->clearVertexBuffer(); + } + } + + obj->mDepth /= count; + } +} + +static LLFastTimer::DeclareTimer FTM_REBUILD_GRASS_VB("Grass VB"); + +void LLGrassPartition::getGeometry(LLSpatialGroup* group) +{ + LLMemType mt(LLMemType::MTYPE_SPACE_PARTITION); + LLFastTimer ftm(FTM_REBUILD_GRASS_VB); + + std::sort(mFaceList.begin(), mFaceList.end(), LLFace::CompareDistanceGreater()); + + U32 index_count = 0; + U32 vertex_count = 0; + + group->clearDrawMap(); + + LLVertexBuffer* buffer = group->mVertexBuffer; + + LLStrider indicesp; + LLStrider verticesp; + LLStrider normalsp; + LLStrider texcoordsp; + LLStrider colorsp; + + buffer->getVertexStrider(verticesp); + buffer->getNormalStrider(normalsp); + buffer->getColorStrider(colorsp); + buffer->getTexCoord0Strider(texcoordsp); + buffer->getIndexStrider(indicesp); + + LLSpatialGroup::drawmap_elem_t& draw_vec = group->mDrawMap[mRenderPass]; + + for (std::vector::iterator i = mFaceList.begin(); i != mFaceList.end(); ++i) + { + LLFace* facep = *i; + LLAlphaObject* object = (LLAlphaObject*) facep->getViewerObject(); + facep->setGeomIndex(vertex_count); + facep->setIndicesIndex(index_count); + facep->setVertexBuffer(buffer); + facep->setPoolType(LLDrawPool::POOL_ALPHA); + object->getGeometry(facep->getTEOffset(), verticesp, normalsp, texcoordsp, colorsp, indicesp); + + vertex_count += facep->getGeomCount(); + index_count += facep->getIndicesCount(); + + S32 idx = draw_vec.size()-1; + + BOOL fullbright = facep->isState(LLFace::FULLBRIGHT); + F32 vsize = facep->getVirtualSize(); + + if (idx >= 0 && draw_vec[idx]->mEnd == facep->getGeomIndex()-1 && + draw_vec[idx]->mTexture == facep->getTexture() && + (U16) (draw_vec[idx]->mEnd - draw_vec[idx]->mStart + facep->getGeomCount()) <= (U32) gGLManager.mGLMaxVertexRange && + //draw_vec[idx]->mCount + facep->getIndicesCount() <= (U32) gGLManager.mGLMaxIndexRange && + draw_vec[idx]->mEnd - draw_vec[idx]->mStart + facep->getGeomCount() < 4096 && + draw_vec[idx]->mFullbright == fullbright) + { + draw_vec[idx]->mCount += facep->getIndicesCount(); + draw_vec[idx]->mEnd += facep->getGeomCount(); + draw_vec[idx]->mVSize = llmax(draw_vec[idx]->mVSize, vsize); + } + else + { + U32 start = facep->getGeomIndex(); + U32 end = start + facep->getGeomCount()-1; + U32 offset = facep->getIndicesStart(); + U32 count = facep->getIndicesCount(); + LLDrawInfo* info = new LLDrawInfo(start,end,count,offset,facep->getTexture(), + //facep->getTexture(), + buffer, fullbright); + info->mExtents[0] = group->mObjectExtents[0]; + info->mExtents[1] = group->mObjectExtents[1]; + info->mVSize = vsize; + draw_vec.push_back(info); + //for alpha sorting + facep->setDrawInfo(info); + } + } + + buffer->flush(); + mFaceList.clear(); +} + // virtual void LLVOGrass::updateDrawable(BOOL force_damped) { diff --git a/indra/newview/llvopartgroup.cpp b/indra/newview/llvopartgroup.cpp index 6ce93d641c..42b35ff7a7 100644 --- a/indra/newview/llvopartgroup.cpp +++ b/indra/newview/llvopartgroup.cpp @@ -48,6 +48,92 @@ const F32 MAX_PART_LIFETIME = 120.f; extern U64 gFrameTime; +LLPointer LLVOPartGroup::sVB = NULL; +S32 LLVOPartGroup::sVBSlotFree[]; +S32* LLVOPartGroup::sVBSlotCursor = NULL; + +//static +void LLVOPartGroup::restoreGL() +{ + for (S32 i = 0; i < LL_MAX_PARTICLE_COUNT; ++i) + { + sVBSlotFree[i] = i; + } + + sVBSlotCursor = sVBSlotFree; + + sVB = new LLVertexBuffer(VERTEX_DATA_MASK, GL_STREAM_DRAW_ARB); + U32 count = LL_MAX_PARTICLE_COUNT; + sVB->allocateBuffer(count*4, count*6, true); + + //indices and texcoords are always the same, set once + LLStrider indicesp; + + sVB->getIndexStrider(indicesp); + + U16 vert_offset = 0; + + for (U32 i = 0; i < LL_MAX_PARTICLE_COUNT; i++) + { + *indicesp++ = vert_offset + 0; + *indicesp++ = vert_offset + 1; + *indicesp++ = vert_offset + 2; + + *indicesp++ = vert_offset + 1; + *indicesp++ = vert_offset + 3; + *indicesp++ = vert_offset + 2; + + vert_offset += 4; + } + + LLStrider texcoordsp; + sVB->getTexCoord0Strider(texcoordsp); + + for (U32 i = 0; i < LL_MAX_PARTICLE_COUNT; i++) + { + *texcoordsp++ = LLVector2(0.f, 1.f); + *texcoordsp++ = LLVector2(0.f, 0.f); + *texcoordsp++ = LLVector2(1.f, 1.f); + *texcoordsp++ = LLVector2(1.f, 0.f); + } + + sVB->flush(); + +} + +//static +void LLVOPartGroup::destroyGL() +{ + sVB = NULL; +} + +//static +S32 LLVOPartGroup::findAvailableVBSlot() +{ + if (sVBSlotCursor >= sVBSlotFree+LL_MAX_PARTICLE_COUNT) + { //no more available slots + return -1; + } + + S32 ret = *sVBSlotCursor; + sVBSlotCursor++; + + return ret; +} + +//static +void LLVOPartGroup::freeVBSlot(S32 idx) +{ + llassert(idx < LL_MAX_PARTICLE_COUNT && idx >= 0); + llassert(sVBSlotCursor > sVBSlotFree); + + if (sVBSlotCursor > sVBSlotFree) + { + sVBSlotCursor--; + *sVBSlotCursor = idx; + } +} + LLVOPartGroup::LLVOPartGroup(const LLUUID &id, const LLPCode pcode, LLViewerRegion *regionp) : LLAlphaObject(id, pcode, regionp), mViewerPartGroupp(NULL) @@ -62,7 +148,6 @@ LLVOPartGroup::~LLVOPartGroup() { } - BOOL LLVOPartGroup::isActive() const { return FALSE; @@ -287,9 +372,6 @@ void LLVOPartGroup::getGeometry(S32 idx, const LLViewerPart &part = *((LLViewerPart*) (mViewerPartGroupp->mParticles[idx])); - U32 vert_offset = mDrawable->getFace(idx)->getGeomIndex(); - - LLVector4a part_pos_agent; part_pos_agent.load3(part.mPosAgent.mV); LLVector4a camera_agent; @@ -361,33 +443,18 @@ void LLVOPartGroup::getGeometry(S32 idx, verticesp->setAdd(ppamu, right); (*verticesp++).getF32ptr()[3] = 0.f; - //*verticesp++ = part_pos_agent + up - right; - //*verticesp++ = part_pos_agent - up - right; - //*verticesp++ = part_pos_agent + up + right; - //*verticesp++ = part_pos_agent - up + right; - *colorsp++ = part.mColor; *colorsp++ = part.mColor; *colorsp++ = part.mColor; *colorsp++ = part.mColor; - *texcoordsp++ = LLVector2(0.f, 1.f); - *texcoordsp++ = LLVector2(0.f, 0.f); - *texcoordsp++ = LLVector2(1.f, 1.f); - *texcoordsp++ = LLVector2(1.f, 0.f); - - *normalsp++ = normal; - *normalsp++ = normal; - *normalsp++ = normal; - *normalsp++ = normal; - - *indicesp++ = vert_offset + 0; - *indicesp++ = vert_offset + 1; - *indicesp++ = vert_offset + 2; - - *indicesp++ = vert_offset + 1; - *indicesp++ = vert_offset + 3; - *indicesp++ = vert_offset + 2; + if (!(part.mFlags & LLPartData::LL_PART_EMISSIVE_MASK)) + { //not fullbright, needs normal + *normalsp++ = normal; + *normalsp++ = normal; + *normalsp++ = normal; + *normalsp++ = normal; + } } U32 LLVOPartGroup::getPartitionType() const @@ -412,6 +479,49 @@ LLHUDParticlePartition::LLHUDParticlePartition() : mPartitionType = LLViewerRegion::PARTITION_HUD_PARTICLE; } +static LLFastTimer::DeclareTimer FTM_REBUILD_PARTICLE_VBO("Particle VBO"); + +void LLParticlePartition::rebuildGeom(LLSpatialGroup* group) +{ + if (group->isDead() || !group->isState(LLSpatialGroup::GEOM_DIRTY)) + { + return; + } + + if (group->changeLOD()) + { + group->mLastUpdateDistance = group->mDistance; + group->mLastUpdateViewAngle = group->mViewAngle; + } + + LLFastTimer ftm(FTM_REBUILD_PARTICLE_VBO); + + group->clearDrawMap(); + + //get geometry count + U32 index_count = 0; + U32 vertex_count = 0; + + addGeometryCount(group, vertex_count, index_count); + + + if (vertex_count > 0 && index_count > 0) + { + group->mBuilt = 1.f; + //use one vertex buffer for all groups + group->mVertexBuffer = LLVOPartGroup::sVB; + getGeometry(group); + } + else + { + group->mVertexBuffer = NULL; + group->mBufferMap.clear(); + } + + group->mLastUpdateTime = gFrameTimeSeconds; + group->clearState(LLSpatialGroup::GEOM_DIRTY); +} + void LLParticlePartition::addGeometryCount(LLSpatialGroup* group, U32& vertex_count, U32& index_count) { group->mBufferUsage = mBufferUsage; @@ -431,11 +541,6 @@ void LLParticlePartition::addGeometryCount(LLSpatialGroup* group, U32& vertex_co LLAlphaObject* obj = (LLAlphaObject*) drawablep->getVObj().get(); obj->mDepth = 0.f; - if (drawablep->isAnimating()) - { - group->mBufferUsage = GL_STREAM_DRAW_ARB; - } - U32 count = 0; for (S32 j = 0; j < drawablep->getNumFaces(); ++j) { @@ -447,36 +552,28 @@ void LLParticlePartition::addGeometryCount(LLSpatialGroup* group, U32& vertex_co continue; } - if ((facep->getGeomCount() + vertex_count) <= 65536) - { - count++; - facep->mDistance = (facep->mCenterLocal - camera->getOrigin()) * camera->getAtAxis(); - obj->mDepth += facep->mDistance; + vertex_count += facep->getGeomCount(); + index_count += facep->getIndicesCount(); + + count++; + facep->mDistance = (facep->mCenterLocal - camera->getOrigin()) * camera->getAtAxis(); + obj->mDepth += facep->mDistance; - mFaceList.push_back(facep); - vertex_count += facep->getGeomCount(); - index_count += facep->getIndicesCount(); - llassert(facep->getIndicesCount() < 65536); - } - else - { - facep->clearVertexBuffer(); - } + mFaceList.push_back(facep); + llassert(facep->getIndicesCount() < 65536); } obj->mDepth /= count; } } -static LLFastTimer::DeclareTimer FTM_REBUILD_GRASS_VB("Grass VB"); -static LLFastTimer::DeclareTimer FTM_REBUILD_PARTICLE_VB("Particle VB"); + +static LLFastTimer::DeclareTimer FTM_REBUILD_PARTICLE_GEOM("Particle Geom"); void LLParticlePartition::getGeometry(LLSpatialGroup* group) { LLMemType mt(LLMemType::MTYPE_SPACE_PARTITION); - LLFastTimer ftm(mDrawableType == LLPipeline::RENDER_TYPE_GRASS ? - FTM_REBUILD_GRASS_VB : - FTM_REBUILD_PARTICLE_VB); + LLFastTimer ftm(FTM_REBUILD_PARTICLE_GEOM); std::sort(mFaceList.begin(), mFaceList.end(), LLFace::CompareDistanceGreater()); @@ -496,21 +593,43 @@ void LLParticlePartition::getGeometry(LLSpatialGroup* group) buffer->getVertexStrider(verticesp); buffer->getNormalStrider(normalsp); buffer->getColorStrider(colorsp); - buffer->getTexCoord0Strider(texcoordsp); - buffer->getIndexStrider(indicesp); - + LLSpatialGroup::drawmap_elem_t& draw_vec = group->mDrawMap[mRenderPass]; for (std::vector::iterator i = mFaceList.begin(); i != mFaceList.end(); ++i) { LLFace* facep = *i; LLAlphaObject* object = (LLAlphaObject*) facep->getViewerObject(); - facep->setGeomIndex(vertex_count); - facep->setIndicesIndex(index_count); - facep->setVertexBuffer(buffer); - facep->setPoolType(LLDrawPool::POOL_ALPHA); - object->getGeometry(facep->getTEOffset(), verticesp, normalsp, texcoordsp, colorsp, indicesp); + + if (facep->getIndicesStart() == 0xFFFFFFFF) + { //set the indices of this face + S32 idx = LLVOPartGroup::findAvailableVBSlot(); + if (idx >= 0) + { + facep->setGeomIndex(idx*4); + facep->setIndicesIndex(idx*6); + facep->setVertexBuffer(LLVOPartGroup::sVB); + facep->setPoolType(LLDrawPool::POOL_ALPHA); + } + else + { + continue; //out of space in particle buffer + } + } + + S32 geom_idx = (S32) facep->getGeomIndex(); + + object->getGeometry(facep->getTEOffset(), + verticesp+geom_idx, + normalsp+geom_idx, + texcoordsp+geom_idx, + colorsp+geom_idx, + indicesp+facep->getIndicesStart()); + llassert(facep->getGeomCount() == 4); + llassert(facep->getIndicesCount() == 6); + + vertex_count += facep->getGeomCount(); index_count += facep->getIndicesCount(); @@ -519,18 +638,31 @@ void LLParticlePartition::getGeometry(LLSpatialGroup* group) BOOL fullbright = facep->isState(LLFace::FULLBRIGHT); F32 vsize = facep->getVirtualSize(); - if (idx >= 0 && draw_vec[idx]->mEnd == facep->getGeomIndex()-1 && + bool batched = false; + + if (idx >= 0 && draw_vec[idx]->mTexture == facep->getTexture() && - (U16) (draw_vec[idx]->mEnd - draw_vec[idx]->mStart + facep->getGeomCount()) <= (U32) gGLManager.mGLMaxVertexRange && - //draw_vec[idx]->mCount + facep->getIndicesCount() <= (U32) gGLManager.mGLMaxIndexRange && - draw_vec[idx]->mEnd - draw_vec[idx]->mStart + facep->getGeomCount() < 4096 && draw_vec[idx]->mFullbright == fullbright) { - draw_vec[idx]->mCount += facep->getIndicesCount(); - draw_vec[idx]->mEnd += facep->getGeomCount(); - draw_vec[idx]->mVSize = llmax(draw_vec[idx]->mVSize, vsize); + if (draw_vec[idx]->mEnd == facep->getGeomIndex()-1) + { + batched = true; + draw_vec[idx]->mCount += facep->getIndicesCount(); + draw_vec[idx]->mEnd += facep->getGeomCount(); + draw_vec[idx]->mVSize = llmax(draw_vec[idx]->mVSize, vsize); + } + else if (draw_vec[idx]->mStart == facep->getGeomIndex()+facep->getGeomCount()+1) + { + batched = true; + draw_vec[idx]->mCount += facep->getIndicesCount(); + draw_vec[idx]->mStart -= facep->getGeomCount(); + draw_vec[idx]->mOffset = facep->getIndicesStart(); + draw_vec[idx]->mVSize = llmax(draw_vec[idx]->mVSize, vsize); + } } - else + + + if (!batched) { U32 start = facep->getGeomIndex(); U32 end = start + facep->getGeomCount()-1; @@ -548,7 +680,6 @@ void LLParticlePartition::getGeometry(LLSpatialGroup* group) } } - buffer->flush(); mFaceList.clear(); } diff --git a/indra/newview/llvopartgroup.h b/indra/newview/llvopartgroup.h index e58fed86d9..dde0b0476d 100644 --- a/indra/newview/llvopartgroup.h +++ b/indra/newview/llvopartgroup.h @@ -31,12 +31,25 @@ #include "v3math.h" #include "v3color.h" #include "llframetimer.h" +#include "llviewerpartsim.h" +#include "llvertexbuffer.h" class LLViewerPartGroup; class LLVOPartGroup : public LLAlphaObject { public: + + //vertex buffer for holding all particles + static LLPointer sVB; + static S32 sVBSlotFree[LL_MAX_PARTICLE_COUNT]; + static S32* sVBSlotCursor; + + static void restoreGL(); + static void destroyGL(); + static S32 findAvailableVBSlot(); + static void freeVBSlot(S32 idx); + enum { VERTEX_DATA_MASK = (1 << LLVertexBuffer::TYPE_VERTEX) | diff --git a/indra/newview/pipeline.cpp b/indra/newview/pipeline.cpp index 93b6e9ae17..c40dafd433 100644 --- a/indra/newview/pipeline.cpp +++ b/indra/newview/pipeline.cpp @@ -3334,21 +3334,7 @@ void LLPipeline::postSort(LLCamera& camera) rebuildPriorityGroups(); llpushcallstacks ; - const S32 bin_count = 1024*8; - - static LLCullResult::drawinfo_list_t alpha_bins[bin_count]; - static U32 bin_size[bin_count]; - - //clear one bin per frame to avoid memory bloat - static S32 clear_idx = 0; - clear_idx = (1+clear_idx)%bin_count; - alpha_bins[clear_idx].clear(); - - for (U32 j = 0; j < bin_count; j++) - { - bin_size[j] = 0; - } - + //build render map for (LLCullResult::sg_list_t::iterator i = sCull->beginVisibleGroups(); i != sCull->endVisibleGroups(); ++i) { @@ -3425,6 +3411,10 @@ void LLPipeline::postSort(LLCamera& camera) { std::sort(sCull->beginAlphaGroups(), sCull->endAlphaGroups(), LLSpatialGroup::CompareDepthGreater()); } + + //flush particle VB + LLVOPartGroup::sVB->flush(); + llpushcallstacks ; // only render if the flag is set. The flag is only set if we are in edit mode or the toggle is set in the menus if (LLFloaterReg::instanceVisible("beacons") && !sShadowRender) @@ -6239,11 +6229,15 @@ void LLPipeline::doResetVertexBuffers() gSky.resetVertexBuffers(); + LLVOPartGroup::destroyGL(); + LLVertexBuffer::cleanupClass(); //delete all name pool caches LLGLNamePool::cleanupPools(); + + if (LLVertexBuffer::sGLCount > 0) { llwarns << "VBO wipe failed -- " << LLVertexBuffer::sGLCount << " buffers remaining." << llendl; @@ -6263,6 +6257,8 @@ void LLPipeline::doResetVertexBuffers() LLPipeline::sTextureBindTest = gSavedSettings.getBOOL("RenderDebugTextureBind"); LLVertexBuffer::initClass(LLVertexBuffer::sEnableVBOs, LLVertexBuffer::sDisableVBOMapping); + + LLVOPartGroup::restoreGL(); } void LLPipeline::renderObjects(U32 type, U32 mask, BOOL texture, BOOL batch_texture) -- cgit v1.2.3 From 681c5de92bd09622de360818682240b0a17403f7 Mon Sep 17 00:00:00 2001 From: "Brad Payne (Vir Linden)" Date: Wed, 2 May 2012 16:48:09 -0400 Subject: SH-3128 FIX - log message cleanup for avatar rezzing --- indra/newview/app_settings/logcontrol.xml | 7 ++++--- indra/newview/llagent.cpp | 4 ++-- indra/newview/llagentwearables.cpp | 2 +- indra/newview/llappearancemgr.cpp | 34 +++++++++++++++---------------- indra/newview/llviewerinventory.cpp | 4 ++-- indra/newview/llvoavatar.cpp | 24 +++++++++++----------- indra/newview/llvoavatarself.cpp | 10 +++++---- 7 files changed, 44 insertions(+), 41 deletions(-) mode change 100644 => 100755 indra/newview/llappearancemgr.cpp mode change 100644 => 100755 indra/newview/llviewerinventory.cpp (limited to 'indra') diff --git a/indra/newview/app_settings/logcontrol.xml b/indra/newview/app_settings/logcontrol.xml index 81e0b5602c..64122bbb6c 100755 --- a/indra/newview/app_settings/logcontrol.xml +++ b/indra/newview/app_settings/logcontrol.xml @@ -42,9 +42,10 @@ tags - Avatar - - + diff --git a/indra/newview/llagent.cpp b/indra/newview/llagent.cpp index e74b7281fd..3367604753 100755 --- a/indra/newview/llagent.cpp +++ b/indra/newview/llagent.cpp @@ -3786,7 +3786,7 @@ void LLAgent::sendAgentSetAppearance() } gAgentAvatarp->sendAppearanceChangeMetrics(); - LL_DEBUGS("Avatar") << gAgentAvatarp->avString() << "TAT: Sent AgentSetAppearance: " << gAgentAvatarp->getBakedStatusForPrintout() << LL_ENDL; + LL_INFOS("Avatar") << gAgentAvatarp->avString() << "TAT: Sent AgentSetAppearance: " << gAgentAvatarp->getBakedStatusForPrintout() << LL_ENDL; //dumpAvatarTEs( "sendAgentSetAppearance()" ); LLMessageSystem* msg = gMessageSystem; @@ -3833,7 +3833,7 @@ void LLAgent::sendAgentSetAppearance() // only update cache entries if we have all our baked textures if (textures_current) { - LL_DEBUGS("Avatar") << gAgentAvatarp->avString() << "TAT: Sending cached texture data" << LL_ENDL; + LL_INFOS("Avatar") << gAgentAvatarp->avString() << "TAT: Sending cached texture data" << LL_ENDL; for (U8 baked_index = 0; baked_index < BAKED_NUM_INDICES; baked_index++) { BOOL generate_valid_hash = TRUE; diff --git a/indra/newview/llagentwearables.cpp b/indra/newview/llagentwearables.cpp index 1aae1714f7..e441f21f90 100755 --- a/indra/newview/llagentwearables.cpp +++ b/indra/newview/llagentwearables.cpp @@ -1645,7 +1645,7 @@ void LLAgentWearables::queryWearableCache() gAgentAvatarp->outputRezTiming("Fetching textures from cache"); } - LL_DEBUGS("Avatar") << gAgentAvatarp->avString() << "Requesting texture cache entry for " << num_queries << " baked textures" << LL_ENDL; + LL_INFOS("Avatar") << gAgentAvatarp->avString() << "Requesting texture cache entry for " << num_queries << " baked textures" << LL_ENDL; gMessageSystem->sendReliable(gAgent.getRegion()->getHost()); gAgentQueryManager.mNumPendingQueries++; gAgentQueryManager.mWearablesCacheQueryID++; diff --git a/indra/newview/llappearancemgr.cpp b/indra/newview/llappearancemgr.cpp old mode 100644 new mode 100755 index 73dd64dffe..faadfb4b87 --- a/indra/newview/llappearancemgr.cpp +++ b/indra/newview/llappearancemgr.cpp @@ -162,7 +162,7 @@ public: mCatID = cat_id; mAppend = append; - LL_DEBUGS("Avatar") << self_av_string() << "starting" << LL_ENDL; + LL_INFOS("Avatar") << self_av_string() << "starting" << LL_ENDL; selfStartPhase("wear_inventory_category_callback"); } @@ -182,7 +182,7 @@ public: protected: ~LLWearInventoryCategoryCallback() { - LL_DEBUGS("Avatar") << self_av_string() << "done all inventory callbacks" << LL_ENDL; + LL_INFOS("Avatar") << self_av_string() << "done all inventory callbacks" << LL_ENDL; selfStopPhase("wear_inventory_category_callback"); @@ -229,7 +229,7 @@ LLUpdateAppearanceOnDestroy::LLUpdateAppearanceOnDestroy(bool update_base_outfit LLUpdateAppearanceOnDestroy::~LLUpdateAppearanceOnDestroy() { - LL_DEBUGS("Avatar") << self_av_string() << "done update appearance on destroy" << LL_ENDL; + LL_INFOS("Avatar") << self_av_string() << "done update appearance on destroy" << LL_ENDL; selfStopPhase("update_appearance_on_destroy"); @@ -492,7 +492,7 @@ void LLWearableHoldingPattern::onAllComplete() } // Update wearables. - LL_DEBUGS("Avatar") << self_av_string() << "Updating agent wearables with " << mResolved << " wearable items " << LL_ENDL; + LL_INFOS("Avatar") << self_av_string() << "Updating agent wearables with " << mResolved << " wearable items " << LL_ENDL; LLAppearanceMgr::instance().updateAgentWearables(this, false); // Update attachments to match those requested. @@ -542,7 +542,7 @@ bool LLWearableHoldingPattern::pollFetchCompletion() if (done) { - LL_DEBUGS("Avatar") << self_av_string() << "polling, done status: " << completed << " timed out " << timed_out + LL_INFOS("Avatar") << self_av_string() << "polling, done status: " << completed << " timed out " << timed_out << " elapsed " << mWaitTime.getElapsedTimeF32() << LL_ENDL; mFired = true; @@ -696,7 +696,7 @@ void LLWearableHoldingPattern::clearCOFLinksForMissingWearables() if ((data.mWearableType < LLWearableType::WT_COUNT) && (!data.mWearable)) { // Wearable link that was never resolved; remove links to it from COF - LL_DEBUGS("Avatar") << self_av_string() << "removing link for unresolved item " << data.mItemID.asString() << LL_ENDL; + LL_INFOS("Avatar") << self_av_string() << "removing link for unresolved item " << data.mItemID.asString() << LL_ENDL; LLAppearanceMgr::instance().removeCOFItemLinks(data.mItemID,false); } } @@ -716,7 +716,7 @@ bool LLWearableHoldingPattern::pollMissingWearables() if (!done) { - LL_DEBUGS("Avatar") << self_av_string() << "polling missing wearables, waiting for items " << mTypesToRecover.size() + LL_INFOS("Avatar") << self_av_string() << "polling missing wearables, waiting for items " << mTypesToRecover.size() << " links " << mTypesToLink.size() << " wearables, timed out " << timed_out << " elapsed " << mWaitTime.getElapsedTimeF32() @@ -763,7 +763,7 @@ void LLWearableHoldingPattern::handleLateArrivals() llwarns << self_av_string() << "Late arrivals not handled - in middle of missing wearables processing" << llendl; } - LL_DEBUGS("Avatar") << self_av_string() << "Need to handle " << mLateArrivals.size() << " late arriving wearables" << LL_ENDL; + LL_INFOS("Avatar") << self_av_string() << "Need to handle " << mLateArrivals.size() << " late arriving wearables" << LL_ENDL; // Update mFoundList using late-arriving wearables. std::set replaced_types; @@ -1450,7 +1450,7 @@ void LLAppearanceMgr::linkAll(const LLUUID& cat_uuid, void LLAppearanceMgr::updateCOF(const LLUUID& category, bool append) { LLViewerInventoryCategory *pcat = gInventory.getCategory(category); - LL_DEBUGS("Avatar") << self_av_string() << "starting, cat " << (pcat ? pcat->getName() : "[UNKNOWN]") << LL_ENDL; + LL_INFOS("Avatar") << self_av_string() << "starting, cat '" << (pcat ? pcat->getName() : "[UNKNOWN]") << "'" << LL_ENDL; const LLUUID cof = getCOF(); @@ -1716,7 +1716,7 @@ void LLAppearanceMgr::updateAppearanceFromCOF(bool update_base_outfit_ordering) BoolSetter setIsInUpdateAppearanceFromCOF(mIsInUpdateAppearanceFromCOF); - LL_DEBUGS("Avatar") << self_av_string() << "starting" << LL_ENDL; + LL_INFOS("Avatar") << self_av_string() << "starting" << LL_ENDL; //checking integrity of the COF in terms of ordering of wearables, //checking and updating links' descriptions of wearables in the COF (before analyzed for "dirty" state) @@ -1892,7 +1892,7 @@ void LLAppearanceMgr::wearInventoryCategory(LLInventoryCategory* category, bool gAgentWearables.notifyLoadingStarted(); - LL_DEBUGS("Avatar") << self_av_string() << "wearInventoryCategory( " << category->getName() + LL_INFOS("Avatar") << self_av_string() << "wearInventoryCategory( " << category->getName() << " )" << LL_ENDL; selfStartPhase("wear_inventory_category_fetch"); @@ -1903,7 +1903,7 @@ void LLAppearanceMgr::wearInventoryCategory(LLInventoryCategory* category, bool void LLAppearanceMgr::wearCategoryFinal(LLUUID& cat_id, bool copy_items, bool append) { - LL_DEBUGS("Avatar") << self_av_string() << "starting" << LL_ENDL; + LL_INFOS("Avatar") << self_av_string() << "starting" << LL_ENDL; selfStopPhase("wear_inventory_category_fetch"); @@ -1988,8 +1988,8 @@ void LLAppearanceMgr::wearInventoryCategoryOnAvatar( LLInventoryCategory* catego // wearables being dirty. if(!category) return; - LL_DEBUGS("Avatar") << self_av_string() << "wearInventoryCategoryOnAvatar( " << category->getName() - << " )" << LL_ENDL; + LL_INFOS("Avatar") << self_av_string() << "wearInventoryCategoryOnAvatar '" << category->getName() + << "'" << LL_ENDL; if (gAgentCamera.cameraCustomizeAvatar()) { @@ -2002,7 +2002,7 @@ void LLAppearanceMgr::wearInventoryCategoryOnAvatar( LLInventoryCategory* catego void LLAppearanceMgr::wearOutfitByName(const std::string& name) { - LL_DEBUGS("Avatar") << self_av_string() << "Wearing category " << name << LL_ENDL; + LL_INFOS("Avatar") << self_av_string() << "Wearing category " << name << LL_ENDL; //inc_busy_count(); LLInventoryModel::cat_array_t cat_array; @@ -2325,7 +2325,7 @@ const std::string OTHER_GESTURES_FOLDER = "Other Gestures"; void LLAppearanceMgr::copyLibraryGestures() { - LL_DEBUGS("Avatar") << self_av_string() << "Copying library gestures" << LL_ENDL; + LL_INFOS("Avatar") << self_av_string() << "Copying library gestures" << LL_ENDL; // Copy gestures LLUUID lib_gesture_cat_id = @@ -2399,7 +2399,7 @@ void LLAppearanceMgr::autopopulateOutfits() // If this is the very first time the user has logged into viewer2+ (from a legacy viewer, or new account) // then auto-populate outfits from the library into the My Outfits folder. - LL_DEBUGS("Avatar") << self_av_string() << "avatar fully visible" << LL_ENDL; + LL_INFOS("Avatar") << self_av_string() << "avatar fully visible" << LL_ENDL; static bool check_populate_my_outfits = true; if (check_populate_my_outfits && diff --git a/indra/newview/llviewerinventory.cpp b/indra/newview/llviewerinventory.cpp old mode 100644 new mode 100755 index 45ca23cdfe..b47a41c44c --- a/indra/newview/llviewerinventory.cpp +++ b/indra/newview/llviewerinventory.cpp @@ -342,8 +342,8 @@ void LLViewerInventoryItem::cloneViewerItem(LLPointer& ne void LLViewerInventoryItem::removeFromServer() { - llinfos << "Removing inventory item " << mUUID << " from server." - << llendl; + lldebugs << "Removing inventory item " << mUUID << " from server." + << llendl; LLInventoryModel::LLCategoryUpdate up(mParentUUID, -1); gInventory.accountForUpdate(up); diff --git a/indra/newview/llvoavatar.cpp b/indra/newview/llvoavatar.cpp index 275c326ef6..ffe5837249 100755 --- a/indra/newview/llvoavatar.cpp +++ b/indra/newview/llvoavatar.cpp @@ -786,13 +786,13 @@ std::string LLVOAvatar::avString() const void LLVOAvatar::debugAvatarRezTime(std::string notification_name, std::string comment) { - LL_DEBUGS("Avatar") << "REZTIME: [ " << (U32)mDebugExistenceTimer.getElapsedTimeF32() - << "sec ]" - << avString() - << "RuthTimer " << (U32)mRuthDebugTimer.getElapsedTimeF32() - << " Notification " << notification_name - << " : " << comment - << llendl; + LL_INFOS("Avatar") << "REZTIME: [ " << (U32)mDebugExistenceTimer.getElapsedTimeF32() + << "sec ]" + << avString() + << "RuthTimer " << (U32)mRuthDebugTimer.getElapsedTimeF32() + << " Notification " << notification_name + << " : " << comment + << llendl; if (gSavedSettings.getBOOL("DebugAvatarRezTime")) { @@ -2859,13 +2859,13 @@ void LLVOAvatar::idleUpdateLoadingEffect() { if (isFullyLoaded() && mFirstFullyVisible && isSelf()) { - LL_DEBUGS("Avatar") << avString() << "self isFullyLoaded, mFirstFullyVisible" << LL_ENDL; + LL_INFOS("Avatar") << avString() << "self isFullyLoaded, mFirstFullyVisible" << LL_ENDL; mFirstFullyVisible = FALSE; LLAppearanceMgr::instance().onFirstFullyVisible(); } if (isFullyLoaded() && mFirstFullyVisible && !isSelf()) { - LL_DEBUGS("Avatar") << avString() << "other isFullyLoaded, mFirstFullyVisible" << LL_ENDL; + LL_INFOS("Avatar") << avString() << "other isFullyLoaded, mFirstFullyVisible" << LL_ENDL; mFirstFullyVisible = FALSE; } if (isFullyLoaded()) @@ -6494,7 +6494,7 @@ void LLVOAvatar::updateRezzedStatusTimers() S32 rez_status = getRezzedStatus(); if (rez_status != mLastRezzedStatus) { - llinfos << avString() << "rez state change: " << mLastRezzedStatus << " -> " << rez_status << llendl; + LL_DEBUGS("Avatar") << avString() << "rez state change: " << mLastRezzedStatus << " -> " << rez_status << LL_ENDL; bool is_cloud_or_gray = (rez_status==0 || rez_status==1); bool was_cloud_or_gray = (mLastRezzedStatus==0 || mLastRezzedStatus==1); bool is_cloud = (rez_status==0); @@ -7180,7 +7180,7 @@ void LLVOAvatar::rebuildHUD() //----------------------------------------------------------------------------- void LLVOAvatar::onFirstTEMessageReceived() { - LL_DEBUGS("Avatar") << avString() << LL_ENDL; + LL_INFOS("Avatar") << avString() << LL_ENDL; if( !mFirstTEMessageReceived ) { mFirstTEMessageReceived = TRUE; @@ -7271,7 +7271,7 @@ void LLVOAvatar::processAvatarAppearance( LLMessageSystem* mesgsys ) BOOL is_first_appearance_message = !mFirstAppearanceMessageReceived; mFirstAppearanceMessageReceived = TRUE; - LL_DEBUGS("Avatar") << avString() << "processAvatarAppearance start " << mID + LL_INFOS("Avatar") << avString() << "processAvatarAppearance start " << mID << " first? " << is_first_appearance_message << " self? " << isSelf() << LL_ENDL; diff --git a/indra/newview/llvoavatarself.cpp b/indra/newview/llvoavatarself.cpp index 9a77e21184..d2609e5587 100755 --- a/indra/newview/llvoavatarself.cpp +++ b/indra/newview/llvoavatarself.cpp @@ -2167,12 +2167,12 @@ public: { if (isGoodStatus(status)) { - llinfos << "OK" << llendl; + LL_DEBUGS("Avatar") << "OK" << LL_ENDL; result(content); } else { - llwarns << "Failed " << status << " reason " << reason << llendl; + LL_WARNS("Avatar") << "Failed " << status << " reason " << reason << LL_ENDL; error(status,reason); } } @@ -2462,7 +2462,9 @@ void LLVOAvatarSelf::outputRezDiagnostics() const // Don't print out non-existent textures. if (j != 0) - LL_DEBUGS("Avatar") << out.str() << llendl; + { + LL_DEBUGS("Avatar") << out.str() << LL_ENDL; + } } LL_DEBUGS("Avatar") << "\t Time points for each upload (start / finish)" << llendl; for (U32 i = 0; i < LLVOAvatarDefines::BAKED_NUM_INDICES; ++i) @@ -2485,7 +2487,7 @@ void LLVOAvatarSelf::outputRezDiagnostics() const void LLVOAvatarSelf::outputRezTiming(const std::string& msg) const { - LL_DEBUGS("Avatar") + LL_INFOS("Avatar") << avString() << llformat("%s. Time from avatar creation: %.2f", msg.c_str(), mDebugSelfLoadTimer.getElapsedTimeF32()) << LL_ENDL; -- cgit v1.2.3 From ca1ecb921cae886369d8f71d8493c76e5a4f2c8a Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Thu, 3 May 2012 18:07:36 -0400 Subject: IQA-490: Dummy out calls to LLTrans::getString() in linux_updater.cpp. It appears that the LLTrans machinery, or at least the way it's used in this program, is buggy: linux-updater.bin has been crashing. Tracebacks and experimentation identify LLTrans as the culprit, so replace it with baked-in string constants copied from strings.xml. (linux-updater.bin was already producing English-only messages because the update_install shell script that calls it was specifically passing the English version of strings.xml.) --- indra/linux_updater/linux_updater.cpp | 149 ++++++++++++++++++++++++++-------- 1 file changed, 116 insertions(+), 33 deletions(-) (limited to 'indra') diff --git a/indra/linux_updater/linux_updater.cpp b/indra/linux_updater/linux_updater.cpp index eed00ac06e..a615e3f07b 100644 --- a/indra/linux_updater/linux_updater.cpp +++ b/indra/linux_updater/linux_updater.cpp @@ -1,4 +1,4 @@ -/** +/** * @file linux_updater.cpp * @author Kyle Ambroff , Tofu Linden * @brief Viewer update program for unix platforms that support GTK+ @@ -6,21 +6,21 @@ * $LicenseInfo:firstyear=2008&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. - * + * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. - * + * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. - * + * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * + * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ @@ -34,10 +34,30 @@ #include "llfile.h" #include "lldir.h" #include "lldiriterator.h" + +/*==========================================================================*| +// IQA-490: Use of LLTrans -- by this program at least -- appears to be buggy. +// With it, the 3.3.2 beta 1 linux-updater.bin crashes; without it seems stable. #include "llxmlnode.h" #include "lltrans.h" +|*==========================================================================*/ + +static class LLTrans +{ +public: + LLTrans(); + static std::string getString(const std::string& key); + +private: + std::string _getString(const std::string& key) const; + + typedef std::map MessageMap; + MessageMap mMessages; +} sLLTransInstance; #include +#include +#include extern "C" { #include @@ -85,6 +105,8 @@ void init_default_trans_args() bool translate_init(std::string comma_delim_path_list, std::string base_xml_name) { + return true; +/*==========================================================================*| init_default_trans_args(); // extract paths string vector from comma-delimited flat string @@ -112,6 +134,7 @@ bool translate_init(std::string comma_delim_path_list, LLTrans::parseStrings(root, default_trans_args); return true; } +|*==========================================================================*/ } @@ -151,7 +174,7 @@ void updater_app_ui_init(UpdaterAppState *app_state) GTK_WIN_POS_CENTER_ALWAYS); gtk_container_set_border_width(GTK_CONTAINER(app_state->window), 12); - g_signal_connect(G_OBJECT(app_state->window), "delete-event", + g_signal_connect(G_OBJECT(app_state->window), "delete-event", G_CALLBACK(on_window_closed), app_state); vbox = gtk_vbox_new(FALSE, 6); @@ -165,7 +188,7 @@ void updater_app_ui_init(UpdaterAppState *app_state) summary_label = gtk_label_new(NULL); gtk_label_set_use_markup(GTK_LABEL(summary_label), TRUE); - gtk_label_set_markup(GTK_LABEL(summary_label), + gtk_label_set_markup(GTK_LABEL(summary_label), label_ostr.str().c_str()); gtk_misc_set_alignment(GTK_MISC(summary_label), 0, 0.5); gtk_box_pack_start(GTK_BOX(vbox), summary_label, FALSE, FALSE, 0); @@ -195,9 +218,9 @@ void updater_app_ui_init(UpdaterAppState *app_state) // set up progress bar, and update it roughly every 1/10 of a second app_state->progress_bar = gtk_progress_bar_new(); - gtk_progress_bar_set_text(GTK_PROGRESS_BAR(app_state->progress_bar), + gtk_progress_bar_set_text(GTK_PROGRESS_BAR(app_state->progress_bar), LLTrans::getString("UpdaterProgressBarTextWithEllipses").c_str()); - gtk_box_pack_start(GTK_BOX(vbox), + gtk_box_pack_start(GTK_BOX(vbox), app_state->progress_bar, FALSE, TRUE, 0); app_state->progress_update_timeout_id = g_timeout_add (UPDATE_PROGRESS_TIMEOUT, progress_update_timeout, app_state); @@ -299,7 +322,7 @@ gpointer worker_thread_cb(gpointer data) g_error_free(error); throw 0; } - + if(tmp_local_filename != NULL) { app_state->file = tmp_local_filename; @@ -342,7 +365,7 @@ gpointer worker_thread_cb(gpointer data) curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, TRUE); curl_easy_setopt(curl, CURLOPT_WRITEDATA, package_file); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, FALSE); - curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, + curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, &download_progress_cb); curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, app_state); @@ -352,8 +375,8 @@ gpointer worker_thread_cb(gpointer data) if (result) { - llerrs << "Failed to download update: " - << app_state->url + llerrs << "Failed to download update: " + << app_state->url << llendl; gdk_threads_enter(); @@ -365,7 +388,7 @@ gpointer worker_thread_cb(gpointer data) throw 0; } } - + // now pulse the progres bar back and forth while the package is // being unpacked gdk_threads_enter(); @@ -386,8 +409,8 @@ gpointer worker_thread_cb(gpointer data) gdk_threads_enter(); display_error(app_state->window, - LLTrans::getString("UpdaterFailInstallTitle"), - LLTrans::getString("UpdaterFailUpdateDescriptive")); + LLTrans::getString("UpdaterFailInstallTitle"), + LLTrans::getString("UpdaterFailUpdateDescriptive")); //"Failed to update " + app_state->app_name, gdk_threads_leave(); throw 0; @@ -402,8 +425,8 @@ gpointer worker_thread_cb(gpointer data) gdk_threads_enter(); display_error(app_state->window, - LLTrans::getString("UpdaterFailStartTitle"), - LLTrans::getString("UpdaterFailUpdateDescriptive")); + LLTrans::getString("UpdaterFailStartTitle"), + LLTrans::getString("UpdaterFailUpdateDescriptive")); gdk_threads_leave(); throw 0; } @@ -448,7 +471,7 @@ gboolean less_anal_gspawnsync(gchar **argv, // restore SIGCHLD handler sigaction(SIGCHLD, &sigchld_backup, NULL); - + return rtn; } @@ -477,7 +500,7 @@ rename_with_sudo_fallback(const std::string& filename, const std::string& newnam { char *src_string_copy = g_strdup(filename.c_str()); char *dst_string_copy = g_strdup(newname.c_str()); - char* argv[] = + char* argv[] = { sudo_cmd, mv_cmd, @@ -492,8 +515,8 @@ rename_with_sudo_fallback(const std::string& filename, const std::string& newnam if (!less_anal_gspawnsync(argv, &stderr_output, &child_exit_status, &spawn_error)) { - llwarns << "Failed to spawn child process: " - << spawn_error->message + llwarns << "Failed to spawn child process: " + << spawn_error->message << llendl; } else if (child_exit_status) @@ -506,7 +529,7 @@ rename_with_sudo_fallback(const std::string& filename, const std::string& newnam { // everything looks good, clear the error code rtncode = 0; - } + } g_free(src_string_copy); g_free(dst_string_copy); @@ -531,7 +554,7 @@ gboolean install_package(std::string package_file, std::string destination) } llinfos << "Found tar command: " << tar_cmd << llendl; - // Unpack the tarball in a temporary place first, then move it to + // Unpack the tarball in a temporary place first, then move it to // its final destination std::string tmp_dest_dir = gDirUtilp->getTempFilename(); if (LLFile::mkdir(tmp_dest_dir, 0744)) @@ -571,8 +594,8 @@ gboolean install_package(std::string package_file, std::string destination) if (!less_anal_gspawnsync(argv, &stderr_output, &child_exit_status, &untar_error)) { - llwarns << "Failed to spawn child process: " - << untar_error->message + llwarns << "Failed to spawn child process: " + << untar_error->message << llendl; return FALSE; } @@ -605,8 +628,8 @@ gboolean install_package(std::string package_file, std::string destination) if (rename_with_sudo_fallback(destination, backup_dir)) { - llwarns << "Failed to move directory: '" - << destination << "' -> '" << backup_dir + llwarns << "Failed to move directory: '" + << destination << "' -> '" << backup_dir << llendl; return FALSE; } @@ -617,7 +640,7 @@ gboolean install_package(std::string package_file, std::string destination) if (rename_with_sudo_fallback(tmp_dest_dir, destination)) { llwarns << "Failed to move installation to the destination: " - << destination + << destination << llendl; return FALSE; } @@ -713,7 +736,7 @@ BOOL spawn_viewer(UpdaterAppState *app_state) if (!success) { - llwarns << "Failed to launch viewer: " << error->message + llwarns << "Failed to launch viewer: " << error->message << llendl; } @@ -772,8 +795,8 @@ void parse_args_and_init(int argc, char **argv, UpdaterAppState *app_state) } } - if (app_state->app_name.empty() - || (app_state->url.empty() && app_state->file.empty()) + if (app_state->app_name.empty() + || (app_state->url.empty() && app_state->file.empty()) || app_state->dest_dir.empty()) { show_usage_and_exit(); @@ -799,7 +822,7 @@ int main(int argc, char **argv) (gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "")); std::string old_log_file = gDirUtilp->getExpandedFilename (LL_PATH_LOGS, "updater.log.old"); - std::string log_file = + std::string log_file = gDirUtilp->getExpandedFilename(LL_PATH_LOGS, "updater.log"); LLFile::rename(log_file, old_log_file); LLError::logToFile(log_file); @@ -841,3 +864,63 @@ int main(int argc, char **argv) return success ? 0 : 1; } +/***************************************************************************** +* Dummy LLTrans implementation (IQA-490) +*****************************************************************************/ +static LLTrans sStaticStrings; + +// lookup +std::string LLTrans::_getString(const std::string& key) const +{ + MessageMap::const_iterator found = mMessages.find(key); + if (found != mMessages.end()) + { + return found->second; + } + LL_WARNS("linux_updater") << "No message for key '" << key + << "' -- add to LLTrans::LLTrans() in linux_updater.cpp" + << LL_ENDL; + return key; +} + +// static lookup +std::string LLTrans::getString(const std::string& key) +{ + return sLLTransInstance._getString(key); +} + +// initialization +LLTrans::LLTrans() +{ + typedef std::pair Pair; + static const Pair data[] = + { + Pair("UpdaterFailDownloadTitle", + "Failed to download update"), + Pair("UpdaterFailInstallTitle", + "Failed to install update"), + Pair("UpdaterFailStartTitle", + "Failed to start viewer"), + Pair("UpdaterFailUpdateDescriptive", + "An error occurred while updating Second Life. " + "Please download the latest version from www.secondlife.com."), + Pair("UpdaterNowInstalling", + "Installing Second Life..."), + Pair("UpdaterNowUpdating", + "Now updating Second Life..."), + Pair("UpdaterProgressBarText", + "Downloading update"), + Pair("UpdaterProgressBarTextWithEllipses", + "Downloading update..."), + Pair("UpdaterUpdatingDescriptive", + "Your Second Life Viewer is being updated to the latest release. " + "This may take some time, so please be patient."), + Pair("UpdaterWindowTitle", + "Second Life Update") + }; + + BOOST_FOREACH(Pair pair, data) + { + mMessages[pair.first] = pair.second; + } +} -- cgit v1.2.3 From fe2e27ffc9031c2af02176e3b2d90edc7cb04ad4 Mon Sep 17 00:00:00 2001 From: Paul ProductEngine Date: Fri, 4 May 2012 20:18:12 +0300 Subject: MAINT-462 FIXED ([PUBLIC]Buy Contents Window Misrepresenting Actual Contents) --- indra/newview/llfloaterbuycontents.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/newview/llfloaterbuycontents.cpp b/indra/newview/llfloaterbuycontents.cpp index a7388d21a3..809d344d01 100644 --- a/indra/newview/llfloaterbuycontents.cpp +++ b/indra/newview/llfloaterbuycontents.cpp @@ -210,7 +210,9 @@ void LLFloaterBuyContents::inventoryChanged(LLViewerObject* obj, LLSD row; BOOL item_is_multi = FALSE; - if ( inv_item->getFlags() & LLInventoryItemFlags::II_FLAGS_LANDMARK_VISITED ) + if ((inv_item->getFlags() & LLInventoryItemFlags::II_FLAGS_LANDMARK_VISITED + || inv_item->getFlags() & LLInventoryItemFlags::II_FLAGS_OBJECT_HAS_MULTIPLE_ITEMS) + && !(inv_item->getFlags() & LLInventoryItemFlags::II_FLAGS_WEARABLES_MASK)) { item_is_multi = TRUE; } -- cgit v1.2.3 From 68ec4d8355326f7c42c8e6fbabe774df6e5f41dd Mon Sep 17 00:00:00 2001 From: Paul ProductEngine Date: Fri, 4 May 2012 20:21:54 +0300 Subject: Linux build fix. GCC doesn't allow to init non-constant references with temporary objects --- indra/newview/llvopartgroup.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) (limited to 'indra') diff --git a/indra/newview/llvopartgroup.cpp b/indra/newview/llvopartgroup.cpp index 42b35ff7a7..49356467a0 100644 --- a/indra/newview/llvopartgroup.cpp +++ b/indra/newview/llvopartgroup.cpp @@ -619,12 +619,13 @@ void LLParticlePartition::getGeometry(LLSpatialGroup* group) S32 geom_idx = (S32) facep->getGeomIndex(); - object->getGeometry(facep->getTEOffset(), - verticesp+geom_idx, - normalsp+geom_idx, - texcoordsp+geom_idx, - colorsp+geom_idx, - indicesp+facep->getIndicesStart()); + verticesp += geom_idx; + normalsp += geom_idx; + texcoordsp += geom_idx; + colorsp += geom_idx; + indicesp += facep->getIndicesStart(); + + object->getGeometry(facep->getTEOffset(), verticesp, normalsp, texcoordsp, colorsp, indicesp); llassert(facep->getGeomCount() == 4); llassert(facep->getIndicesCount() == 6); -- cgit v1.2.3 From bdd17086726b0c47df18935e6833a10b706e3ee5 Mon Sep 17 00:00:00 2001 From: Oz Linden Date: Fri, 4 May 2012 16:40:55 -0400 Subject: increment viewer version to 3.3.3 --- indra/llcommon/llversionviewer.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/llcommon/llversionviewer.h b/indra/llcommon/llversionviewer.h index fafc750690..bfb30f900f 100644 --- a/indra/llcommon/llversionviewer.h +++ b/indra/llcommon/llversionviewer.h @@ -29,7 +29,7 @@ const S32 LL_VERSION_MAJOR = 3; const S32 LL_VERSION_MINOR = 3; -const S32 LL_VERSION_PATCH = 2; +const S32 LL_VERSION_PATCH = 3; const S32 LL_VERSION_BUILD = 0; const char * const LL_CHANNEL = "Second Life Developer"; -- cgit v1.2.3 From e75d889ea142486aed61e5a8d7ebd7f7c494cc91 Mon Sep 17 00:00:00 2001 From: Dave Parks Date: Mon, 7 May 2012 15:06:06 -0500 Subject: MAINT-583 Fix for broken projectors when shadows set to none. --- .../app_settings/shaders/class1/deferred/multiSpotLightF.glsl | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'indra') diff --git a/indra/newview/app_settings/shaders/class1/deferred/multiSpotLightF.glsl b/indra/newview/app_settings/shaders/class1/deferred/multiSpotLightF.glsl index 75de47614c..bff87cb6aa 100644 --- a/indra/newview/app_settings/shaders/class1/deferred/multiSpotLightF.glsl +++ b/indra/newview/app_settings/shaders/class1/deferred/multiSpotLightF.glsl @@ -55,8 +55,6 @@ uniform float far_clip; uniform vec3 proj_origin; //origin of projection to be used for angular attenuation uniform float sun_wash; -uniform int proj_shadow_idx; -uniform float shadow_fade; uniform vec3 center; uniform vec3 color; @@ -143,7 +141,8 @@ void main() discard; } - vec3 norm = texture2DRect(normalMap, frag.xy).xyz*2.0-1.0; + vec3 norm = texture2DRect(normalMap, frag.xy).xyz; + norm = vec3((norm.xy-0.5)*2.0, norm.z); norm = normalize(norm); float l_dist = -dot(lv, proj_n); -- cgit v1.2.3 From 71bbb384b056476bbf1177d20b2ade16ca0a4bcf Mon Sep 17 00:00:00 2001 From: "simon@Simon-PC.lindenlab.com" Date: Mon, 7 May 2012 13:24:52 -0700 Subject: MAINT-753 : [crashhunters] crash at LLVOVolume::updateFaceFlags(). Null pointer checks are good. Reviewed by Kelly --- indra/newview/lldrawable.cpp | 29 +++++--- indra/newview/lldrawable.h | 6 +- indra/newview/llfloaterbvhpreview.cpp | 10 ++- indra/newview/llfloaterimagepreview.cpp | 10 ++- indra/newview/llspatialpartition.cpp | 101 +++++++++++++++---------- indra/newview/lltoolmorph.cpp | 3 +- indra/newview/llviewerjointattachment.cpp | 24 +++++- indra/newview/llviewerobject.cpp | 16 +++- indra/newview/llviewerobjectlist.cpp | 5 +- indra/newview/llviewerwindow.cpp | 6 +- indra/newview/llvoavatar.cpp | 41 ++++++---- indra/newview/llvograss.cpp | 29 +++++--- indra/newview/llvoground.cpp | 3 + indra/newview/llvosurfacepatch.cpp | 64 +++++++++------- indra/newview/llvotree.cpp | 11 ++- indra/newview/llvovolume.cpp | 120 ++++++++++++++++++------------ indra/newview/llvowater.cpp | 4 + indra/newview/pipeline.cpp | 47 ++++++++++-- 18 files changed, 355 insertions(+), 174 deletions(-) (limited to 'indra') diff --git a/indra/newview/lldrawable.cpp b/indra/newview/lldrawable.cpp index 55fb135898..98246162f0 100644 --- a/indra/newview/lldrawable.cpp +++ b/indra/newview/lldrawable.cpp @@ -604,7 +604,11 @@ void LLDrawable::moveUpdatePipeline(BOOL moved) // Update the face centers. for (S32 i = 0; i < getNumFaces(); i++) { - getFace(i)->updateCenterAgent(); + LLFace* face = getFace(i); + if (face) + { + face->updateCenterAgent(); + } } } @@ -734,7 +738,8 @@ void LLDrawable::updateDistance(LLCamera& camera, bool force_update) for (S32 i = 0; i < getNumFaces(); i++) { LLFace* facep = getFace(i); - if (force_update || facep->getPoolType() == LLDrawPool::POOL_ALPHA) + if (facep && + (force_update || facep->getPoolType() == LLDrawPool::POOL_ALPHA)) { LLVector4a box; box.setSub(facep->mExtents[1], facep->mExtents[0]); @@ -833,13 +838,16 @@ void LLDrawable::shiftPos(const LLVector4a &shift_vector) for (S32 i = 0; i < getNumFaces(); i++) { LLFace *facep = getFace(i); - facep->mCenterAgent += LLVector3(shift_vector.getF32ptr()); - facep->mExtents[0].add(shift_vector); - facep->mExtents[1].add(shift_vector); - - if (!volume && facep->hasGeometry()) + if (facep) { - facep->clearVertexBuffer(); + facep->mCenterAgent += LLVector3(shift_vector.getF32ptr()); + facep->mExtents[0].add(shift_vector); + facep->mExtents[1].add(shift_vector); + + if (!volume && facep->hasGeometry()) + { + facep->clearVertexBuffer(); + } } } @@ -961,7 +969,10 @@ void LLDrawable::setSpatialGroup(LLSpatialGroup *groupp) for (S32 i = 0; i < getNumFaces(); ++i) { LLFace* facep = getFace(i); - facep->clearVertexBuffer(); + if (facep) + { + facep->clearVertexBuffer(); + } } } diff --git a/indra/newview/lldrawable.h b/indra/newview/lldrawable.h index 6a3d15db7f..e2064b79f8 100644 --- a/indra/newview/lldrawable.h +++ b/indra/newview/lldrawable.h @@ -334,12 +334,14 @@ inline LLFace* LLDrawable::getFace(const S32 i) const if ((U32) i >= mFaces.size()) { - llerrs << "Invalid face index." << llendl; + llwarns << "Invalid face index." << llendl; + return NULL; } if (!mFaces[i]) { - llerrs << "Null face found." << llendl; + llwarns << "Null face found." << llendl; + return NULL; } return mFaces[i]; diff --git a/indra/newview/llfloaterbvhpreview.cpp b/indra/newview/llfloaterbvhpreview.cpp index ac33a05f42..fa0ad20fdb 100644 --- a/indra/newview/llfloaterbvhpreview.cpp +++ b/indra/newview/llfloaterbvhpreview.cpp @@ -1124,9 +1124,13 @@ BOOL LLPreviewAnimation::render() LLVertexBuffer::unbind(); LLGLDepthTest gls_depth(GL_TRUE); - LLDrawPoolAvatar *avatarPoolp = (LLDrawPoolAvatar *)avatarp->mDrawable->getFace(0)->getPool(); - avatarp->dirtyMesh(); - avatarPoolp->renderAvatars(avatarp); // renders only one avatar + LLFace* face = avatarp->mDrawable->getFace(0); + if (face) + { + LLDrawPoolAvatar *avatarPoolp = (LLDrawPoolAvatar *)face->getPool(); + avatarp->dirtyMesh(); + avatarPoolp->renderAvatars(avatarp); // renders only one avatar + } } gGL.color4f(1,1,1,1); diff --git a/indra/newview/llfloaterimagepreview.cpp b/indra/newview/llfloaterimagepreview.cpp index 92ee8ddac6..6b2492d927 100644 --- a/indra/newview/llfloaterimagepreview.cpp +++ b/indra/newview/llfloaterimagepreview.cpp @@ -704,9 +704,13 @@ BOOL LLImagePreviewAvatar::render() // make sure alpha=0 shows avatar material color LLGLDisable no_blend(GL_BLEND); - LLDrawPoolAvatar *avatarPoolp = (LLDrawPoolAvatar *)avatarp->mDrawable->getFace(0)->getPool(); - gPipeline.enableLightsPreview(); - avatarPoolp->renderAvatars(avatarp); // renders only one avatar + LLFace* face = avatarp->mDrawable->getFace(0); + if (face) + { + LLDrawPoolAvatar *avatarPoolp = (LLDrawPoolAvatar *)face->getPool(); + gPipeline.enableLightsPreview(); + avatarPoolp->renderAvatars(avatarp); // renders only one avatar + } } gGL.popUIMatrix(); diff --git a/indra/newview/llspatialpartition.cpp b/indra/newview/llspatialpartition.cpp index 27dea1c7a0..e886f83671 100644 --- a/indra/newview/llspatialpartition.cpp +++ b/indra/newview/llspatialpartition.cpp @@ -1513,7 +1513,10 @@ void LLSpatialGroup::destroyGL(bool keep_occlusion) for (S32 j = 0; j < drawable->getNumFaces(); j++) { LLFace* facep = drawable->getFace(j); - facep->clearVertexBuffer(); + if (facep) + { + facep->clearVertexBuffer(); + } } } } @@ -2502,18 +2505,21 @@ void pushVerts(LLSpatialGroup* group, U32 mask) void pushVerts(LLFace* face, U32 mask) { - llassert(face->verify()); + if (face) + { + llassert(face->verify()); - LLVertexBuffer* buffer = face->getVertexBuffer(); + LLVertexBuffer* buffer = face->getVertexBuffer(); - if (buffer && (face->getGeomCount() >= 3)) - { - buffer->setBuffer(mask); - U16 start = face->getGeomStart(); - U16 end = start + face->getGeomCount()-1; - U32 count = face->getIndicesCount(); - U16 offset = face->getIndicesStart(); - buffer->drawRange(LLRender::TRIANGLES, start, end, count, offset); + if (buffer && (face->getGeomCount() >= 3)) + { + buffer->setBuffer(mask); + U16 start = face->getGeomStart(); + U16 end = start + face->getGeomCount()-1; + U32 count = face->getIndicesCount(); + U16 offset = face->getIndicesStart(); + buffer->drawRange(LLRender::TRIANGLES, start, end, count, offset); + } } } @@ -2650,7 +2656,7 @@ void renderOctree(LLSpatialGroup* group) for (S32 j = 0; j < drawable->getNumFaces(); j++) { LLFace* face = drawable->getFace(j); - if (face->getVertexBuffer()) + if (face && face->getVertexBuffer()) { if (gFrameTimeSeconds - face->mLastUpdateTime < 0.5f) { @@ -3021,15 +3027,17 @@ void renderBoundingBox(LLDrawable* drawable, BOOL set_color = TRUE) for (S32 i = 0; i < drawable->getNumFaces(); i++) { LLFace* facep = drawable->getFace(i); + if (facep) + { + ext = facep->mExtents; - ext = facep->mExtents; - - pos.setAdd(ext[0], ext[1]); - pos.mul(0.5f); - size.setSub(ext[1], ext[0]); - size.mul(0.5f); + pos.setAdd(ext[0], ext[1]); + pos.mul(0.5f); + size.setSub(ext[1], ext[0]); + size.mul(0.5f); - drawBoxOutline(pos,size); + drawBoxOutline(pos,size); + } } //render drawable bounding box @@ -3521,18 +3529,21 @@ void renderPhysicsShapes(LLSpatialGroup* group) for (S32 i = 0; i < drawable->getNumFaces(); ++i) { LLFace* face = drawable->getFace(i); - LLVertexBuffer* buff = face->getVertexBuffer(); - if (buff) + if (face) { - glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); + LLVertexBuffer* buff = face->getVertexBuffer(); + if (buff) + { + glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); - buff->setBuffer(LLVertexBuffer::MAP_VERTEX); - gGL.diffuseColor3f(0.2f, 0.5f, 0.3f); - buff->draw(LLRender::TRIANGLES, buff->getNumIndices(), 0); + buff->setBuffer(LLVertexBuffer::MAP_VERTEX); + gGL.diffuseColor3f(0.2f, 0.5f, 0.3f); + buff->draw(LLRender::TRIANGLES, buff->getNumIndices(), 0); - gGL.diffuseColor3f(0.2f, 1.f, 0.3f); - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); - buff->draw(LLRender::TRIANGLES, buff->getNumIndices(), 0); + gGL.diffuseColor3f(0.2f, 1.f, 0.3f); + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + buff->draw(LLRender::TRIANGLES, buff->getNumIndices(), 0); + } } } } @@ -3556,6 +3567,7 @@ void renderTexturePriority(LLDrawable* drawable) //LLViewerTexture* imagep = facep->getTexture(); //if (imagep) + if (facep) { //F32 vsize = imagep->mMaxVirtualSize; @@ -3608,7 +3620,11 @@ void renderPoints(LLDrawable* drawablep) gGL.diffuseColor3f(1,1,1); for (S32 i = 0; i < drawablep->getNumFaces(); i++) { - gGL.vertex3fv(drawablep->getFace(i)->mCenterLocal.mV); + LLFace * face = drawablep->getFace(i); + if (face) + { + gGL.vertex3fv(face->mCenterLocal.mV); + } } gGL.end(); } @@ -3685,7 +3701,11 @@ void renderLights(LLDrawable* drawablep) for (S32 i = 0; i < drawablep->getNumFaces(); i++) { - pushVerts(drawablep->getFace(i), LLVertexBuffer::MAP_VERTEX); + LLFace * face = drawablep->getFace(i); + if (face) + { + pushVerts(face, LLVertexBuffer::MAP_VERTEX); + } } const LLVector4a* ext = drawablep->getSpatialExtents(); @@ -4083,18 +4103,21 @@ public: for (U32 i = 0; i < drawable->getNumFaces(); ++i) { LLFace* facep = drawable->getFace(i); - U8 index = facep->getTextureIndex(); - if (facep->mDrawInfo) + if (facep) { - if (index < 255) + U8 index = facep->getTextureIndex(); + if (facep->mDrawInfo) { - if (facep->mDrawInfo->mTextureList.size() <= index) - { - llerrs << "Face texture index out of bounds." << llendl; - } - else if (facep->mDrawInfo->mTextureList[index] != facep->getTexture()) + if (index < 255) { - llerrs << "Face texture index incorrect." << llendl; + if (facep->mDrawInfo->mTextureList.size() <= index) + { + llerrs << "Face texture index out of bounds." << llendl; + } + else if (facep->mDrawInfo->mTextureList[index] != facep->getTexture()) + { + llerrs << "Face texture index incorrect." << llendl; + } } } } diff --git a/indra/newview/lltoolmorph.cpp b/indra/newview/lltoolmorph.cpp index 718201e381..0d5daf129f 100644 --- a/indra/newview/lltoolmorph.cpp +++ b/indra/newview/lltoolmorph.cpp @@ -225,7 +225,8 @@ BOOL LLVisualParamHint::render() LLViewerCamera::getInstance()->setPerspective(FALSE, mOrigin.mX, mOrigin.mY, mFullWidth, mFullHeight, FALSE); - if (gAgentAvatarp->mDrawable.notNull()) + if (gAgentAvatarp->mDrawable.notNull() && + gAgentAvatarp->mDrawable->getFace(0)) { LLDrawPoolAvatar *avatarPoolp = (LLDrawPoolAvatar *)gAgentAvatarp->mDrawable->getFace(0)->getPool(); LLGLDepthTest gls_depth(GL_TRUE, GL_TRUE); diff --git a/indra/newview/llviewerjointattachment.cpp b/indra/newview/llviewerjointattachment.cpp index 4e14824e69..3a04bbed4f 100644 --- a/indra/newview/llviewerjointattachment.cpp +++ b/indra/newview/llviewerjointattachment.cpp @@ -127,7 +127,11 @@ void LLViewerJointAttachment::setupDrawable(LLViewerObject *object) { for (S32 face_num = 0; face_num < object->mDrawable->getNumFaces(); face_num++) { - object->mDrawable->getFace(face_num)->setState(LLFace::HUD_RENDER); + LLFace *face = object->mDrawable->getFace(face_num); + if (face) + { + face->setState(LLFace::HUD_RENDER); + } } } @@ -146,7 +150,11 @@ void LLViewerJointAttachment::setupDrawable(LLViewerObject *object) { for (S32 face_num = 0; face_num < childp->mDrawable->getNumFaces(); face_num++) { - childp->mDrawable->getFace(face_num)->setState(LLFace::HUD_RENDER); + LLFace * face = childp->mDrawable->getFace(face_num); + if (face) + { + face->setState(LLFace::HUD_RENDER); + } } } } @@ -254,7 +262,11 @@ void LLViewerJointAttachment::removeObject(LLViewerObject *object) { for (S32 face_num = 0; face_num < object->mDrawable->getNumFaces(); face_num++) { - object->mDrawable->getFace(face_num)->clearState(LLFace::HUD_RENDER); + LLFace * face = object->mDrawable->getFace(face_num); + if (face) + { + face->clearState(LLFace::HUD_RENDER); + } } } } @@ -272,7 +284,11 @@ void LLViewerJointAttachment::removeObject(LLViewerObject *object) { for (S32 face_num = 0; face_num < childp->mDrawable->getNumFaces(); face_num++) { - childp->mDrawable->getFace(face_num)->clearState(LLFace::HUD_RENDER); + LLFace * face = childp->mDrawable->getFace(face_num); + if (face) + { + face->clearState(LLFace::HUD_RENDER); + } } } } diff --git a/indra/newview/llviewerobject.cpp b/indra/newview/llviewerobject.cpp index e590f29a9a..1aa541793f 100644 --- a/indra/newview/llviewerobject.cpp +++ b/indra/newview/llviewerobject.cpp @@ -432,7 +432,9 @@ void LLViewerObject::dump() const llinfos << "PositionAgent: " << getPositionAgent() << llendl; llinfos << "PositionGlobal: " << getPositionGlobal() << llendl; llinfos << "Velocity: " << getVelocity() << llendl; - if (mDrawable.notNull() && mDrawable->getNumFaces()) + if (mDrawable.notNull() && + mDrawable->getNumFaces() && + mDrawable->getFace(0)) { LLFacePool *poolp = mDrawable->getFace(0)->getPool(); if (poolp) @@ -4467,7 +4469,11 @@ U32 LLViewerObject::getNumVertices() const num_faces = mDrawable->getNumFaces(); for (i = 0; i < num_faces; i++) { - num_vertices += mDrawable->getFace(i)->getGeomCount(); + LLFace * facep = mDrawable->getFace(i); + if (facep) + { + num_vertices += facep->getGeomCount(); + } } } return num_vertices; @@ -4482,7 +4488,11 @@ U32 LLViewerObject::getNumIndices() const num_faces = mDrawable->getNumFaces(); for (i = 0; i < num_faces; i++) { - num_indices += mDrawable->getFace(i)->getIndicesCount(); + LLFace * facep = mDrawable->getFace(i); + if (facep) + { + num_indices += facep->getIndicesCount(); + } } } return num_indices; diff --git a/indra/newview/llviewerobjectlist.cpp b/indra/newview/llviewerobjectlist.cpp index 6912faa9ec..c8ba2b6f58 100644 --- a/indra/newview/llviewerobjectlist.cpp +++ b/indra/newview/llviewerobjectlist.cpp @@ -1718,7 +1718,10 @@ void LLViewerObjectList::generatePickList(LLCamera &camera) LLViewerObject* last_objectp = NULL; for (S32 face_num = 0; face_num < drawablep->getNumFaces(); face_num++) { - LLViewerObject* objectp = drawablep->getFace(face_num)->getViewerObject(); + LLFace * facep = drawablep->getFace(face_num); + if (!facep) continue; + + LLViewerObject* objectp = facep->getViewerObject(); if (objectp && objectp != last_objectp) { diff --git a/indra/newview/llviewerwindow.cpp b/indra/newview/llviewerwindow.cpp index 0a582107af..ca5523dfbd 100755 --- a/indra/newview/llviewerwindow.cpp +++ b/indra/newview/llviewerwindow.cpp @@ -5194,8 +5194,10 @@ void LLPickInfo::getSurfaceInfo() if (objectp->mDrawable.notNull() && mObjectFace > -1) { LLFace* facep = objectp->mDrawable->getFace(mObjectFace); - - mUVCoords = facep->surfaceToTexture(mSTCoords, mIntersection, mNormal); + if (facep) + { + mUVCoords = facep->surfaceToTexture(mSTCoords, mIntersection, mNormal); + } } // and XY coords: diff --git a/indra/newview/llvoavatar.cpp b/indra/newview/llvoavatar.cpp index 7cbb47100d..c221c7fdd8 100644 --- a/indra/newview/llvoavatar.cpp +++ b/indra/newview/llvoavatar.cpp @@ -2004,11 +2004,17 @@ void LLVOAvatar::releaseMeshData() if (mDrawable.notNull()) { LLFace* facep = mDrawable->getFace(0); - facep->setSize(0, 0); - for(S32 i = mNumInitFaces ; i < mDrawable->getNumFaces(); i++) + if (facep) { - facep = mDrawable->getFace(i); facep->setSize(0, 0); + for(S32 i = mNumInitFaces ; i < mDrawable->getNumFaces(); i++) + { + facep = mDrawable->getFace(i); + if (facep) + { + facep->setSize(0, 0); + } + } } } @@ -2093,15 +2099,20 @@ void LLVOAvatar::updateMeshData() part_index-- ; } - LLFace* facep ; + LLFace* facep = NULL; if(f_num < mDrawable->getNumFaces()) { facep = mDrawable->getFace(f_num); } else { - facep = mDrawable->addFace(mDrawable->getFace(0)->getPool(), mDrawable->getFace(0)->getTexture()) ; + facep = mDrawable->getFace(0); + if (facep) + { + facep = mDrawable->addFace(facep->getPool(), facep->getTexture()) ; + } } + if (!facep) continue; // resize immediately facep->setSize(num_vertices, num_indices); @@ -4130,11 +4141,11 @@ U32 LLVOAvatar::renderSkinned(EAvatarRenderPass pass) { //LOD changed or new mesh created, allocate new vertex buffer if needed if (needs_rebuild || mDirtyMesh >= 2 || mVisibilityRank <= 4) { - updateMeshData(); + updateMeshData(); mDirtyMesh = 0; - mNeedsSkin = TRUE; - mDrawable->clearState(LLDrawable::REBUILD_GEOMETRY); - } + mNeedsSkin = TRUE; + mDrawable->clearState(LLDrawable::REBUILD_GEOMETRY); + } } if (LLViewerShaderMgr::instance()->getVertexShaderLevel(LLViewerShaderMgr::SHADER_AVATAR) <= 0) @@ -4159,10 +4170,14 @@ U32 LLVOAvatar::renderSkinned(EAvatarRenderPass pass) mNeedsSkin = FALSE; mLastSkinTime = gFrameTimeSeconds; - LLVertexBuffer* vb = mDrawable->getFace(0)->getVertexBuffer(); - if (vb) + LLFace * face = mDrawable->getFace(0); + if (face) { - vb->flush(); + LLVertexBuffer* vb = face->getVertexBuffer(); + if (vb) + { + vb->flush(); + } } } } @@ -8253,7 +8268,7 @@ BOOL LLVOAvatar::updateLOD() BOOL res = updateJointLODs(); LLFace* facep = mDrawable->getFace(0); - if (!facep->getVertexBuffer()) + if (!facep || !facep->getVertexBuffer()) { dirtyMesh(2); } diff --git a/indra/newview/llvograss.cpp b/indra/newview/llvograss.cpp index be3558aad1..44968342bf 100644 --- a/indra/newview/llvograss.cpp +++ b/indra/newview/llvograss.cpp @@ -381,8 +381,10 @@ BOOL LLVOGrass::updateLOD() { mNumBlades <<= 1; } - - face->setSize(mNumBlades*8, mNumBlades*12); + if (face) + { + face->setSize(mNumBlades*8, mNumBlades*12); + } gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_ALL, TRUE); } else if (num_blades <= (mNumBlades >> 1)) @@ -392,7 +394,10 @@ BOOL LLVOGrass::updateLOD() mNumBlades >>=1; } - face->setSize(mNumBlades*8, mNumBlades*12); + if (face) + { + face->setSize(mNumBlades*8, mNumBlades*12); + } gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_ALL, TRUE); return TRUE; } @@ -450,14 +455,16 @@ void LLVOGrass::plantBlades() } LLFace *face = mDrawable->getFace(0); + if (face) + { + face->setTexture(getTEImage(0)); + face->setState(LLFace::GLOBAL); + face->setSize(mNumBlades * 8, mNumBlades * 12); + face->setVertexBuffer(NULL); + face->setTEOffset(0); + face->mCenterLocal = mPosition + mRegionp->getOriginAgent(); + } - face->setTexture(getTEImage(0)); - face->setState(LLFace::GLOBAL); - face->setSize(mNumBlades * 8, mNumBlades * 12); - face->setVertexBuffer(NULL); - face->setTEOffset(0); - face->mCenterLocal = mPosition + mRegionp->getOriginAgent(); - mDepth = (face->mCenterLocal - LLViewerCamera::getInstance()->getOrigin())*LLViewerCamera::getInstance()->getAtAxis(); mDrawable->setPosition(face->mCenterLocal); mDrawable->movePartition(); @@ -487,6 +494,8 @@ void LLVOGrass::getGeometry(S32 idx, LLColor4U color(255,255,255,255); LLFace *face = mDrawable->getFace(idx); + if (!face) + return; F32 width = sSpeciesTable[mSpecies]->mBladeSizeX; F32 height = sSpeciesTable[mSpecies]->mBladeSizeY; diff --git a/indra/newview/llvoground.cpp b/indra/newview/llvoground.cpp index 0060f81ab5..6da54435e3 100644 --- a/indra/newview/llvoground.cpp +++ b/indra/newview/llvoground.cpp @@ -82,6 +82,7 @@ LLDrawable *LLVOGround::createDrawable(LLPipeline *pipeline) return mDrawable; } +// TO DO - this always returns TRUE, BOOL LLVOGround::updateGeometry(LLDrawable *drawable) { LLStrider verticesp; @@ -96,6 +97,8 @@ BOOL LLVOGround::updateGeometry(LLDrawable *drawable) if (drawable->getNumFaces() < 1) drawable->addFace(poolp, NULL); face = drawable->getFace(0); + if (!face) + return TRUE; if (!face->getVertexBuffer()) { diff --git a/indra/newview/llvosurfacepatch.cpp b/indra/newview/llvosurfacepatch.cpp index bf6158eeaf..94a3111f4c 100644 --- a/indra/newview/llvosurfacepatch.cpp +++ b/indra/newview/llvosurfacepatch.cpp @@ -296,18 +296,20 @@ void LLVOSurfacePatch::updateFaceSize(S32 idx) } LLFace* facep = mDrawable->getFace(idx); - - S32 num_vertices = 0; - S32 num_indices = 0; - - if (mLastStride) + if (facep) { - getGeomSizesMain(mLastStride, num_vertices, num_indices); - getGeomSizesNorth(mLastStride, mLastNorthStride, num_vertices, num_indices); - getGeomSizesEast(mLastStride, mLastEastStride, num_vertices, num_indices); - } + S32 num_vertices = 0; + S32 num_indices = 0; + + if (mLastStride) + { + getGeomSizesMain(mLastStride, num_vertices, num_indices); + getGeomSizesNorth(mLastStride, mLastNorthStride, num_vertices, num_indices); + getGeomSizesEast(mLastStride, mLastEastStride, num_vertices, num_indices); + } - facep->setSize(num_vertices, num_indices); + facep->setSize(num_vertices, num_indices); + } } BOOL LLVOSurfacePatch::updateLOD() @@ -322,30 +324,32 @@ void LLVOSurfacePatch::getGeometry(LLStrider &verticesp, LLStrider &indicesp) { LLFace* facep = mDrawable->getFace(0); + if (facep) + { + U32 index_offset = facep->getGeomIndex(); - U32 index_offset = facep->getGeomIndex(); - - updateMainGeometry(facep, - verticesp, - normalsp, - texCoords0p, - texCoords1p, - indicesp, - index_offset); - updateNorthGeometry(facep, - verticesp, - normalsp, - texCoords0p, - texCoords1p, - indicesp, - index_offset); - updateEastGeometry(facep, + updateMainGeometry(facep, verticesp, normalsp, texCoords0p, texCoords1p, indicesp, index_offset); + updateNorthGeometry(facep, + verticesp, + normalsp, + texCoords0p, + texCoords1p, + indicesp, + index_offset); + updateEastGeometry(facep, + verticesp, + normalsp, + texCoords0p, + texCoords1p, + indicesp, + index_offset); + } } void LLVOSurfacePatch::updateMainGeometry(LLFace *facep, @@ -864,7 +868,11 @@ void LLVOSurfacePatch::dirtyGeom() if (mDrawable) { gPipeline.markRebuild(mDrawable, LLDrawable::REBUILD_ALL, TRUE); - mDrawable->getFace(0)->setVertexBuffer(NULL); + LLFace* facep = mDrawable->getFace(0); + if (facep) + { + facep->setVertexBuffer(NULL); + } mDrawable->movePartition(); } } diff --git a/indra/newview/llvotree.cpp b/indra/newview/llvotree.cpp index 4564207da4..3556bde9a8 100644 --- a/indra/newview/llvotree.cpp +++ b/indra/newview/llvotree.cpp @@ -490,11 +490,16 @@ BOOL LLVOTree::updateGeometry(LLDrawable *drawable) if(mTrunkLOD >= sMAX_NUM_TREE_LOD_LEVELS) //do not display the tree. { mReferenceBuffer = NULL ; - mDrawable->getFace(0)->setVertexBuffer(NULL); + LLFace * facep = drawable->getFace(0); + if (facep) + { + facep->setVertexBuffer(NULL); + } return TRUE ; } - if (mReferenceBuffer.isNull() || !mDrawable->getFace(0)->getVertexBuffer()) + if (mDrawable->getFace(0) && + (mReferenceBuffer.isNull() || !mDrawable->getFace(0)->getVertexBuffer())) { const F32 SRR3 = 0.577350269f; // sqrt(1/3) const F32 SRR2 = 0.707106781f; // sqrt(1/2) @@ -507,6 +512,7 @@ BOOL LLVOTree::updateGeometry(LLDrawable *drawable) S32 lod; LLFace *face = drawable->getFace(0); + if (!face) return TRUE; face->mCenterAgent = getPositionAgent(); face->mCenterLocal = face->mCenterAgent; @@ -879,6 +885,7 @@ void LLVOTree::updateMesh() calcNumVerts(vert_count, index_count, mTrunkLOD, stop_depth, mDepth, mTrunkDepth, mBranches); LLFace* facep = mDrawable->getFace(0); + if (!facep) return; LLVertexBuffer* buff = new LLVertexBuffer(LLDrawPoolTree::VERTEX_DATA_MASK, GL_STATIC_DRAW_ARB); buff->allocateBuffer(vert_count, index_count, TRUE); facep->setVertexBuffer(buff); diff --git a/indra/newview/llvovolume.cpp b/indra/newview/llvovolume.cpp index 3430e1a610..75ab807c39 100644 --- a/indra/newview/llvovolume.cpp +++ b/indra/newview/llvovolume.cpp @@ -520,6 +520,7 @@ void LLVOVolume::animateTextures() for (S32 i = start; i <= end; i++) { LLFace* facep = mDrawable->getFace(i); + if (!facep) continue; if(facep->getVirtualSize() <= MIN_TEX_ANIM_SIZE && facep->mTextureMatrix) continue; const LLTextureEntry* te = facep->getTextureEntry(); @@ -734,8 +735,11 @@ void LLVOVolume::updateTextureVirtualSize(bool forced) for (S32 i = 0; i < num_faces; i++) { LLFace* face = mDrawable->getFace(i); - face->setPixelArea(0.f); - face->setVirtualSize(0.f); + if (face) + { + face->setPixelArea(0.f); + face->setVirtualSize(0.f); + } } return ; @@ -765,6 +769,7 @@ void LLVOVolume::updateTextureVirtualSize(bool forced) for (S32 i = 0; i < num_faces; i++) { LLFace* face = mDrawable->getFace(i); + if (!face) continue; const LLTextureEntry *te = face->getTextureEntry(); LLViewerTexture *imagep = face->getTexture(); if (!imagep || !te || @@ -1268,7 +1273,8 @@ BOOL LLVOVolume::calcLOD() llround(radius, 0.01f)); - if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_LOD_INFO)) + if (gPipeline.hasRenderDebugMask(LLPipeline::RENDER_DEBUG_LOD_INFO) && + mDrawable->getFace(0)) { //setDebugText(llformat("%.2f:%.2f, %d", debug_distance, radius, cur_detail)); @@ -1347,25 +1353,23 @@ void LLVOVolume::updateFaceFlags() for (S32 i = 0; i < getVolume()->getNumFaces(); i++) { LLFace *face = mDrawable->getFace(i); - if (!face) + if (face) { - return; - } - - BOOL fullbright = getTE(i)->getFullbright(); - face->clearState(LLFace::FULLBRIGHT | LLFace::HUD_RENDER | LLFace::LIGHT); + BOOL fullbright = getTE(i)->getFullbright(); + face->clearState(LLFace::FULLBRIGHT | LLFace::HUD_RENDER | LLFace::LIGHT); - if (fullbright || (mMaterial == LL_MCODE_LIGHT)) - { - face->setState(LLFace::FULLBRIGHT); - } - if (mDrawable->isLight()) - { - face->setState(LLFace::LIGHT); - } - if (isHUDAttachment()) - { - face->setState(LLFace::HUD_RENDER); + if (fullbright || (mMaterial == LL_MCODE_LIGHT)) + { + face->setState(LLFace::FULLBRIGHT); + } + if (mDrawable->isLight()) + { + face->setState(LLFace::LIGHT); + } + if (isHUDAttachment()) + { + face->setState(LLFace::HUD_RENDER); + } } } } @@ -1402,6 +1406,8 @@ void LLVOVolume::regenFaces() for (S32 i = 0; i < mNumFaces; i++) { LLFace* facep = count_changed ? addFace(i) : mDrawable->getFace(i); + if (!facep) continue; + facep->setTEOffset(i); facep->setTexture(getTEImage(i)); facep->setViewerObject(this); @@ -1747,16 +1753,19 @@ BOOL LLVOVolume::updateGeometry(LLDrawable *drawable) void LLVOVolume::updateFaceSize(S32 idx) { LLFace* facep = mDrawable->getFace(idx); - if (idx >= getVolume()->getNumVolumeFaces()) + if (facep) { - facep->setSize(0,0, true); - } - else - { - const LLVolumeFace& vol_face = getVolume()->getVolumeFace(idx); - facep->setSize(vol_face.mNumVertices, vol_face.mNumIndices, - true); // <--- volume faces should be padded for 16-byte alignment + if (idx >= getVolume()->getNumVolumeFaces()) + { + facep->setSize(0,0, true); + } + else + { + const LLVolumeFace& vol_face = getVolume()->getVolumeFace(idx); + facep->setSize(vol_face.mNumVertices, vol_face.mNumIndices, + true); // <--- volume faces should be padded for 16-byte alignment + } } } @@ -3129,6 +3138,7 @@ U32 LLVOVolume::getRenderCost(texture_cost_t &textures) const for (S32 i = 0; i < num_faces; ++i) { const LLFace* face = drawablep->getFace(i); + if (!face) continue; const LLTextureEntry* te = face->getTextureEntry(); const LLViewerTexture* img = face->getTexture(); @@ -3400,6 +3410,7 @@ F32 LLVOVolume::getBinRadius() for (S32 i = 0; i < mDrawable->getNumFaces(); i++) { LLFace* face = mDrawable->getFace(i); + if (!face) continue; if (face->getPoolType() == LLDrawPool::POOL_ALPHA && !face->canRenderAsMask()) { @@ -3623,7 +3634,8 @@ BOOL LLVOVolume::lineSegmentIntersect(const LLVector3& start, const LLVector3& e { LLFace* face = mDrawable->getFace(face_hit); - if (pick_transparent || !face->getTexture() || !face->getTexture()->hasGLTexture() || face->getTexture()->getMask(face->surfaceToTexture(tc, p, n))) + if (face && + (pick_transparent || !face->getTexture() || !face->getTexture()->hasGLTexture() || face->getTexture()->getMask(face->surfaceToTexture(tc, p, n)))) { v_end = p; if (face_hitp != NULL) @@ -4233,6 +4245,10 @@ void LLVolumeGeometryManager::rebuildGeom(LLSpatialGroup* group) for (S32 i = 0; i < drawablep->getNumFaces(); i++) { LLFace* facep = drawablep->getFace(i); + if (!facep) + { + continue; + } //ALWAYS null out vertex buffer on rebuild -- if the face lands in a render // batch, it will recover its vertex buffer reference from the spatial group @@ -4453,12 +4469,20 @@ void LLVolumeGeometryManager::rebuildGeom(LLSpatialGroup* group) S32 face; for (face = 0; face < vobj->getNumTEs(); face++) { - drawablep->getFace(face)->setState(LLFace::TEXTURE_ANIM); + LLFace * facep = drawablep->getFace(face); + if (facep) + { + facep->setState(LLFace::TEXTURE_ANIM); + } } } else if (vobj->mTextureAnimp->mFace < vobj->getNumTEs()) { - drawablep->getFace(vobj->mTextureAnimp->mFace)->setState(LLFace::TEXTURE_ANIM); + LLFace * facep = drawablep->getFace(vobj->mTextureAnimp->mFace); + if (facep) + { + facep->setState(LLFace::TEXTURE_ANIM); + } } } @@ -4682,10 +4706,13 @@ void LLVolumeGeometryManager::rebuildMesh(LLSpatialGroup* group) for (S32 i = 0; i < drawablep->getNumFaces(); ++i) { LLFace* face = drawablep->getFace(i); - LLVertexBuffer* buff = face->getVertexBuffer(); - if (face && buff && buff->isLocked()) + if (face) { - buff->flush(); + LLVertexBuffer* buff = face->getVertexBuffer(); + if (buff && buff->isLocked()) + { + buff->flush(); + } } } } @@ -5166,20 +5193,21 @@ void LLGeometryManager::addGeometryCount(LLSpatialGroup* group, U32 &vertex_coun //sum up face verts and indices drawablep->updateFaceSize(i); LLFace* facep = drawablep->getFace(i); - - - if (facep->hasGeometry() && facep->getPixelArea() > FORCE_CULL_AREA && - facep->getGeomCount() + vertex_count <= 65536) + if (facep) { - vertex_count += facep->getGeomCount(); - index_count += facep->getIndicesCount(); + if (facep->hasGeometry() && facep->getPixelArea() > FORCE_CULL_AREA && + facep->getGeomCount() + vertex_count <= 65536) + { + vertex_count += facep->getGeomCount(); + index_count += facep->getIndicesCount(); - //remember face (for sorting) - mFaceList.push_back(facep); - } - else - { - facep->clearVertexBuffer(); + //remember face (for sorting) + mFaceList.push_back(facep); + } + else + { + facep->clearVertexBuffer(); + } } } } diff --git a/indra/newview/llvowater.cpp b/indra/newview/llvowater.cpp index cd78157944..942eff6171 100644 --- a/indra/newview/llvowater.cpp +++ b/indra/newview/llvowater.cpp @@ -146,6 +146,10 @@ BOOL LLVOWater::updateGeometry(LLDrawable *drawable) drawable->addFace(poolp, NULL); } face = drawable->getFace(0); + if (!face) + { + return TRUE; + } // LLVector2 uvs[4]; // LLVector3 vtx[4]; diff --git a/indra/newview/pipeline.cpp b/indra/newview/pipeline.cpp index c40dafd433..34dd15c9a1 100644 --- a/indra/newview/pipeline.cpp +++ b/indra/newview/pipeline.cpp @@ -3173,7 +3173,11 @@ void renderScriptedBeacons(LLDrawable* drawablep) S32 count = drawablep->getNumFaces(); for (face_id = 0; face_id < count; face_id++) { - gPipeline.mHighlightFaces.push_back(drawablep->getFace(face_id) ); + LLFace * facep = drawablep->getFace(face_id); + if (facep) + { + gPipeline.mHighlightFaces.push_back(facep); + } } } } @@ -3199,7 +3203,11 @@ void renderScriptedTouchBeacons(LLDrawable* drawablep) S32 count = drawablep->getNumFaces(); for (face_id = 0; face_id < count; face_id++) { - gPipeline.mHighlightFaces.push_back(drawablep->getFace(face_id) ); + LLFace * facep = drawablep->getFace(face_id); + if (facep) + { + gPipeline.mHighlightFaces.push_back(facep); + } } } } @@ -3224,7 +3232,11 @@ void renderPhysicalBeacons(LLDrawable* drawablep) S32 count = drawablep->getNumFaces(); for (face_id = 0; face_id < count; face_id++) { - gPipeline.mHighlightFaces.push_back(drawablep->getFace(face_id) ); + LLFace * facep = drawablep->getFace(face_id); + if (facep) + { + gPipeline.mHighlightFaces.push_back(facep); + } } } } @@ -3260,7 +3272,11 @@ void renderMOAPBeacons(LLDrawable* drawablep) S32 count = drawablep->getNumFaces(); for (face_id = 0; face_id < count; face_id++) { - gPipeline.mHighlightFaces.push_back(drawablep->getFace(face_id) ); + LLFace * facep = drawablep->getFace(face_id); + if (facep) + { + gPipeline.mHighlightFaces.push_back(facep); + } } } } @@ -3285,7 +3301,11 @@ void renderParticleBeacons(LLDrawable* drawablep) S32 count = drawablep->getNumFaces(); for (face_id = 0; face_id < count; face_id++) { - gPipeline.mHighlightFaces.push_back(drawablep->getFace(face_id) ); + LLFace * facep = drawablep->getFace(face_id); + if (facep) + { + gPipeline.mHighlightFaces.push_back(facep); + } } } } @@ -3303,7 +3323,11 @@ void renderSoundHighlights(LLDrawable* drawablep) S32 count = drawablep->getNumFaces(); for (face_id = 0; face_id < count; face_id++) { - gPipeline.mHighlightFaces.push_back(drawablep->getFace(face_id) ); + LLFace * facep = drawablep->getFace(face_id); + if (facep) + { + gPipeline.mHighlightFaces.push_back(facep); + } } } } @@ -3488,7 +3512,11 @@ void LLPipeline::postSort(LLCamera& camera) { if (object->mDrawable) { - gPipeline.mSelectedFaces.push_back(object->mDrawable->getFace(te)); + LLFace * facep = object->mDrawable->getFace(te); + if (facep) + { + gPipeline.mSelectedFaces.push_back(facep); + } } return true; } @@ -6193,7 +6221,10 @@ void LLPipeline::resetVertexBuffers(LLDrawable* drawable) for (S32 i = 0; i < drawable->getNumFaces(); i++) { LLFace* facep = drawable->getFace(i); - facep->clearVertexBuffer(); + if (facep) + { + facep->clearVertexBuffer(); + } } } -- cgit v1.2.3 From 5c11b6b2e59ea8042d8dac6071b8be4c81293889 Mon Sep 17 00:00:00 2001 From: Merov Linden Date: Tue, 8 May 2012 10:16:14 -0700 Subject: SH-3047 : Tweak of the performance compression data gathering code --- indra/llimage/llimagej2c.cpp | 6 +++++- indra/llimage/llimagej2c.h | 3 ++- 2 files changed, 7 insertions(+), 2 deletions(-) (limited to 'indra') diff --git a/indra/llimage/llimagej2c.cpp b/indra/llimage/llimagej2c.cpp index 4435e0d2a4..452aad25cb 100755 --- a/indra/llimage/llimagej2c.cpp +++ b/indra/llimage/llimagej2c.cpp @@ -464,6 +464,7 @@ LLImageCompressionTester::LLImageCompressionTester() : LLMetricPerformanceTester addMetric("Perf Compression (kB/s)"); mRunBytesInDecompression = 0; + mRunBytesOutDecompression = 0; mRunBytesInCompression = 0; mTotalBytesInDecompression = 0; @@ -556,13 +557,16 @@ void LLImageCompressionTester::updateDecompressionStats(const S32 bytesIn, const mTotalBytesInDecompression += bytesIn; mRunBytesInDecompression += bytesIn; mTotalBytesOutDecompression += bytesOut; + mRunBytesOutDecompression += bytesOut; //if (mRunBytesInDecompression > (1000000)) - if ((mTotalTimeDecompression - mRunTimeDecompression) >= (5.0f)) + if (mRunBytesOutDecompression > (10000000)) + //if ((mTotalTimeDecompression - mRunTimeDecompression) >= (5.0f)) { // Output everything outputTestResults(); // Reset the decompression data of the run mRunBytesInDecompression = 0; + mRunBytesOutDecompression = 0; mRunTimeDecompression = mTotalTimeDecompression; } } diff --git a/indra/llimage/llimagej2c.h b/indra/llimage/llimagej2c.h index 42093e0e64..ce8195940d 100644 --- a/indra/llimage/llimagej2c.h +++ b/indra/llimage/llimagej2c.h @@ -156,7 +156,8 @@ class LLImageCompressionTester : public LLMetricPerformanceTesterBasic U32 mTotalBytesOutDecompression; // Total bytes produced by decompressor U32 mTotalBytesInCompression; // Total bytes fed to compressor U32 mTotalBytesOutCompression; // Total bytes produced by compressor - U32 mRunBytesInDecompression; // Bytes fed to decompressor in this run + U32 mRunBytesInDecompression; // Bytes fed to decompressor in this run + U32 mRunBytesOutDecompression; // Bytes produced by the decompressor in this run U32 mRunBytesInCompression; // Bytes fed to compressor in this run // // Time -- cgit v1.2.3 From 005ce31f41fc60b7b9c7890d354943b3e3568ac9 Mon Sep 17 00:00:00 2001 From: Merov Linden Date: Tue, 8 May 2012 21:42:53 -0700 Subject: SH-3047 : Fix lossless compression for small textures. --- indra/llkdu/llimagej2ckdu.cpp | 31 +++++++++++-------------------- 1 file changed, 11 insertions(+), 20 deletions(-) (limited to 'indra') diff --git a/indra/llkdu/llimagej2ckdu.cpp b/indra/llkdu/llimagej2ckdu.cpp index cbfc34ebb8..53d2a2f3c5 100644 --- a/indra/llkdu/llimagej2ckdu.cpp +++ b/indra/llkdu/llimagej2ckdu.cpp @@ -619,36 +619,27 @@ BOOL LLImageJ2CKDU::encodeImpl(LLImageJ2C &base, const LLImageRaw &raw_image, co // This code is where we specify the target number of bytes for each quality layer. // We're using a logarithmic spacing rule that fits with our way of fetching texture data. // Note: For more info on this layers business, read kdu_codestream::flush() doc in kdu_compressed.h - U32 i = FIRST_PACKET_SIZE; + layer_bytes[nb_layers++] = FIRST_PACKET_SIZE; + U32 i = MIN_LAYER_SIZE; while ((i < max_bytes) && (nb_layers < (MAX_NB_LAYERS-1))) { - if (i == FIRST_PACKET_SIZE * 4) - { - // That really just means that the first layer is FIRST_PACKET_SIZE and the second is MIN_LAYER_SIZE - i = MIN_LAYER_SIZE; - } - layer_bytes[nb_layers] = i; - nb_layers++; + layer_bytes[nb_layers++] = i; i *= 4; } + if (layer_bytes[nb_layers-1] < max_bytes) + { + // Set the last quality layer if necessary so to fit the preset compression ratio + // Use 0 for that last layer for reversible images so all remaining code blocks will be flushed + layer_bytes[nb_layers++] = (reversible ? 0 : max_bytes); + } if (reversible) { codestream.access_siz()->parse_string("Creversible=yes"); - // *TODO: we should use yuv in reversible mode and one res level since those images are small. - // Don't turn this on now though as both create problems on decoding for the moment - //codestream.access_siz()->parse_string("Clevels=1"); + // *TODO: we should use yuv in reversible mode + // Don't turn this on now though as it creates problems on decoding for the moment //codestream.access_siz()->parse_string("Cycc=no"); - // In the reversible case, set the last entry of that table to 0 so that all generated bits will - // indeed be output by the time the last quality layer is encountered. - layer_bytes[nb_layers] = 0; - } - else - { - // Truncate the last quality layer if necessary so to fit the set compression ratio - layer_bytes[nb_layers] = max_bytes; } - nb_layers++; std::string layer_string = llformat("Clayers=%d",nb_layers); codestream.access_siz()->parse_string(layer_string.c_str()); -- cgit v1.2.3 From d29f920c22ca67b13f42680c432b689b80909f42 Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Wed, 9 May 2012 19:55:26 -0400 Subject: CHOP-900: Use new apr_procattr_constrain_handle_set() extension. Now LLProcess explicitly requests APR to limit the handles passed to any child process, instead of wantonly passing whatever happens to be lying around the parent process at the time. This requires the latest APR build. Also revert LLUpdateDownloader::Implementation::mDownloadStream to llofstream (as in rev 1878a57aebd7) instead of apr_file_t*. Using APR for that file was a Band-Aid -- a single whacked mole -- for the problem more systemically addressed by apr_procattr_constrain_handle_set(). --- indra/llcommon/llprocess.cpp | 17 ++++++++++++ .../updater/llupdatedownloader.cpp | 32 ++++++++-------------- 2 files changed, 28 insertions(+), 21 deletions(-) (limited to 'indra') diff --git a/indra/llcommon/llprocess.cpp b/indra/llcommon/llprocess.cpp index 760be6da9b..9667e4e033 100644 --- a/indra/llcommon/llprocess.cpp +++ b/indra/llcommon/llprocess.cpp @@ -539,6 +539,23 @@ LLProcess::LLProcess(const LLSDOrParams& params): apr_procattr_t *procattr = NULL; chkapr(apr_procattr_create(&procattr, gAPRPoolp)); + // IQA-490, CHOP-900: On Windows, ask APR to jump through hoops to + // constrain the set of handles passed to the child process. Before we + // changed to APR, the Windows implementation of LLProcessLauncher called + // CreateProcess(bInheritHandles=FALSE), meaning to pass NO open handles + // to the child process. Now that we support pipes, though, we must allow + // apr_proc_create() to pass bInheritHandles=TRUE. But without taking + // special pains, that causes trouble in a number of ways, due to the fact + // that the viewer is constantly opening and closing files -- most of + // which CreateProcess() passes to every child process! +#if ! defined(APR_HAS_PROCATTR_CONSTRAIN_HANDLE_SET) + // Our special preprocessor symbol isn't even defined -- wrong APR + LL_WARNS("LLProcess") << "This version of APR lacks Linden " + << "apr_procattr_constrain_handle_set() extension" << LL_ENDL; +#else + chkapr(apr_procattr_constrain_handle_set(procattr, 1)); +#endif + // For which of stdin, stdout, stderr should we create a pipe to the // child? In the viewer, there are only a couple viable // apr_procattr_io_set() alternatives: inherit the viewer's own stdxxx diff --git a/indra/viewer_components/updater/llupdatedownloader.cpp b/indra/viewer_components/updater/llupdatedownloader.cpp index abe45cc52b..75e455e3f6 100644 --- a/indra/viewer_components/updater/llupdatedownloader.cpp +++ b/indra/viewer_components/updater/llupdatedownloader.cpp @@ -40,7 +40,6 @@ #include "llthread.h" #include "llupdaterservice.h" #include "llcurl.h" -#include "llapr.h" class LLUpdateDownloader::Implementation: public LLThread @@ -66,7 +65,7 @@ private: LLUpdateDownloader::Client & mClient; CURL * mCurl; LLSD mDownloadData; - apr_file_t* mDownloadStream; + llofstream mDownloadStream; unsigned char mDownloadPercent; std::string mDownloadRecordPath; curl_slist * mHeaderList; @@ -189,7 +188,6 @@ LLUpdateDownloader::Implementation::Implementation(LLUpdateDownloader::Client & mCancelled(false), mClient(client), mCurl(0), - mDownloadStream(NULL), mDownloadPercent(0), mHeaderList(0) { @@ -346,9 +344,12 @@ size_t LLUpdateDownloader::Implementation::onBody(void * buffer, size_t size) if(mCancelled) return 0; // Forces a write error which will halt curl thread. if((size == 0) || (buffer == 0)) return 0; - apr_size_t written(size); - ll_apr_assert_status(apr_file_write(mDownloadStream, buffer, &written)); - return written; + mDownloadStream.write(static_cast(buffer), size); + if(mDownloadStream.bad()) { + return 0; + } else { + return size; + } } @@ -379,8 +380,7 @@ int LLUpdateDownloader::Implementation::onProgress(double downloadSize, double b void LLUpdateDownloader::Implementation::run(void) { CURLcode code = curl_easy_perform(mCurl); - ll_apr_assert_status(apr_file_close(mDownloadStream)); - mDownloadStream = NULL; + mDownloadStream.close(); if(code == CURLE_OK) { LLFile::remove(mDownloadRecordPath); if(validateDownload()) { @@ -459,9 +459,8 @@ void LLUpdateDownloader::Implementation::resumeDownloading(size_t startByte) if(mHeaderList == 0) throw DownloadError("cannot add Range header"); throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_HTTPHEADER, mHeaderList)); - ll_apr_assert_status(apr_file_open(&mDownloadStream, mDownloadData["path"].asString().c_str(), - APR_WRITE | APR_APPEND | APR_BINARY | APR_BUFFERED, - APR_OS_DEFAULT, gAPRPoolp)); + mDownloadStream.open(mDownloadData["path"].asString(), + std::ios_base::out | std::ios_base::binary | std::ios_base::app); start(); } @@ -484,16 +483,7 @@ void LLUpdateDownloader::Implementation::startDownloading(LLURI const & uri, std llofstream dataStream(mDownloadRecordPath); LLSDSerialize::toPrettyXML(mDownloadData, dataStream); - ll_apr_assert_status(apr_file_open(&mDownloadStream, filePath.c_str(), - APR_WRITE | APR_CREATE | APR_TRUNCATE | APR_BINARY | APR_BUFFERED, - APR_OS_DEFAULT, gAPRPoolp)); - // IQA-463: Do NOT let this open file be inherited by child processes. - // That's why we switched from llofstream to apr_file_t. From - // apr_file_open() doc - // http://apr.apache.org/docs/apr/1.4/group__apr__file__io.html#gabda14cbf242fb4fe99055434213e5446 : - // "By default, the returned file descriptor will not be inherited by - // child processes created by apr_proc_create(). This can be changed using - // apr_file_inherit_set()." + mDownloadStream.open(filePath, std::ios_base::out | std::ios_base::binary); initializeCurlGet(uri.asString(), true); start(); } -- cgit v1.2.3 From 7fd22901774ff9dcdfbf4388550275e30200307f Mon Sep 17 00:00:00 2001 From: Merov Linden Date: Wed, 9 May 2012 17:04:02 -0700 Subject: SH-3075 : Fix reversible compression for very small textures. Also supress the forcing to reversible for small textures. --- indra/llkdu/llimagej2ckdu.cpp | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) (limited to 'indra') diff --git a/indra/llkdu/llimagej2ckdu.cpp b/indra/llkdu/llimagej2ckdu.cpp index 53d2a2f3c5..cf88de12b4 100644 --- a/indra/llkdu/llimagej2ckdu.cpp +++ b/indra/llkdu/llimagej2ckdu.cpp @@ -609,13 +609,6 @@ BOOL LLImageJ2CKDU::encodeImpl(LLImageJ2C &base, const LLImageRaw &raw_image, co llassert (base.mRate > 0.f); max_bytes = (U32)((F32)(max_bytes) * base.mRate); - // If the image is very small, code it in a lossless way. - // Note: it'll also have only 1 layer which is fine as there's no point reordering blocks in that case. - if (max_bytes < FIRST_PACKET_SIZE) - { - reversible = true; - } - // This code is where we specify the target number of bytes for each quality layer. // We're using a logarithmic spacing rule that fits with our way of fetching texture data. // Note: For more info on this layers business, read kdu_codestream::flush() doc in kdu_compressed.h @@ -626,27 +619,32 @@ BOOL LLImageJ2CKDU::encodeImpl(LLImageJ2C &base, const LLImageRaw &raw_image, co layer_bytes[nb_layers++] = i; i *= 4; } + // Note: for small images, we can have (max_bytes < FIRST_PACKET_SIZE), hence the test if (layer_bytes[nb_layers-1] < max_bytes) { - // Set the last quality layer if necessary so to fit the preset compression ratio - // Use 0 for that last layer for reversible images so all remaining code blocks will be flushed - layer_bytes[nb_layers++] = (reversible ? 0 : max_bytes); + // Set the last quality layer so to fit the preset compression ratio + layer_bytes[nb_layers++] = max_bytes; } if (reversible) { + // Use 0 for a last quality layer for reversible images so all remaining code blocks will be flushed + // Hack: KDU encoding for reversible images has a bug for small images that leads to j2c images that + // cannot be open or are very blurry. Avoiding that last layer prevents the problem to happen. + if ((base.getWidth() >= 32) || (base.getHeight() >= 32)) + { + layer_bytes[nb_layers++] = 0; + } codestream.access_siz()->parse_string("Creversible=yes"); // *TODO: we should use yuv in reversible mode // Don't turn this on now though as it creates problems on decoding for the moment //codestream.access_siz()->parse_string("Cycc=no"); } - + std::string layer_string = llformat("Clayers=%d",nb_layers); codestream.access_siz()->parse_string(layer_string.c_str()); // Set up data ordering, markers, etc... if precincts or blocks specified - // Note: This code is *not* used in the encoding made by the viewer. It is currently used only - // by llimage_libtest to create various j2c and test alternative compression schemes. if ((mBlocksSize != -1) || (mPrecinctsSize != -1)) { if (mPrecinctsSize != -1) -- cgit v1.2.3 From 95a147dea7a8c4f2a20a2623fda0f9af5ce973ad Mon Sep 17 00:00:00 2001 From: Nat Goodspeed Date: Wed, 9 May 2012 23:03:37 -0400 Subject: CHOP-900: Fix test.cpp merge errors merging up to viewer-release --- indra/test/test.cpp | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) (limited to 'indra') diff --git a/indra/test/test.cpp b/indra/test/test.cpp index 48f20b2e79..9d24383bcc 100644 --- a/indra/test/test.cpp +++ b/indra/test/test.cpp @@ -66,6 +66,7 @@ #pragma warning (pop) #endif +#include #include #include #include @@ -147,17 +148,16 @@ class LLTestCallback : public tut::callback public: LLTestCallback(bool verbose_mode, std::ostream *stream, boost::shared_ptr replayer) : - mVerboseMode(verbose_mode), - mTotalTests(0), - mPassedTests(0), - mFailedTests(0), - mSkippedTests(0), - // By default, capture a shared_ptr to std::cout, with a no-op "deleter" - // so that destroying the shared_ptr makes no attempt to delete std::cout. - mStream(boost::shared_ptr(&std::cout, boost::lambda::_1)), - mReplayer(replayer) - if (stream) - { + mVerboseMode(verbose_mode), + mTotalTests(0), + mPassedTests(0), + mFailedTests(0), + mSkippedTests(0), + // By default, capture a shared_ptr to std::cout, with a no-op "deleter" + // so that destroying the shared_ptr makes no attempt to delete std::cout. + mStream(boost::shared_ptr(&std::cout, boost::lambda::_1)), + mReplayer(replayer) + { if (stream) { // We want a boost::iostreams::tee_device that will stream to two @@ -593,11 +593,11 @@ int main(int argc, char **argv) LLTestCallback* mycallback; if (getenv("TEAMCITY_PROJECT_NAME")) { - mycallback = new LLTCTestCallback(verbose_mode, output, replayer); + mycallback = new LLTCTestCallback(verbose_mode, output.get(), replayer); } else { - mycallback = new LLTestCallback(verbose_mode, output, replayer); + mycallback = new LLTestCallback(verbose_mode, output.get(), replayer); } tut::runner.get().set_callback(mycallback); -- cgit v1.2.3 From a85bf36d4fd5026dac21f95432d06a7c0dd766d4 Mon Sep 17 00:00:00 2001 From: Todd Stinson Date: Thu, 10 May 2012 20:20:55 -0700 Subject: EXP-1928: Adding fundamentals for managing a teleport request in such a way that it can be restarted. --- indra/newview/llagent.cpp | 192 +++++++++++++++++++++++++++++++++++++++++++++- indra/newview/llagent.h | 22 +++++- 2 files changed, 210 insertions(+), 4 deletions(-) (limited to 'indra') diff --git a/indra/newview/llagent.cpp b/indra/newview/llagent.cpp index 3870a3be2e..d7c39ff78d 100755 --- a/indra/newview/llagent.cpp +++ b/indra/newview/llagent.cpp @@ -112,6 +112,81 @@ const F32 MAX_FIDGET_TIME = 20.f; // seconds // The agent instance. LLAgent gAgent; +class LLTeleportRequest +{ +public: + LLTeleportRequest(); + virtual ~LLTeleportRequest(); + + virtual void doTeleport() = 0; + +protected: + +private: + +}; + +class LLTeleportRequestViaLandmark : public LLTeleportRequest +{ +public: + LLTeleportRequestViaLandmark(const LLUUID &pLandmarkId); + virtual ~LLTeleportRequestViaLandmark(); + + virtual void doTeleport(); + +protected: + inline const LLUUID &getLandmarkId() const {return mLandmarkId;}; + +private: + LLUUID mLandmarkId; +}; + +class LLTeleportRequestViaLure : public LLTeleportRequestViaLandmark +{ +public: + LLTeleportRequestViaLure(const LLUUID &pLureId, BOOL pIsLureGodLike); + virtual ~LLTeleportRequestViaLure(); + + virtual void doTeleport(); + +protected: + inline BOOL isLureGodLike() const {return mIsLureGodLike;}; + +private: + BOOL mIsLureGodLike; +}; + +class LLTeleportRequestViaLocation : public LLTeleportRequest +{ +public: + LLTeleportRequestViaLocation(const LLVector3d &pPosGlobal); + virtual ~LLTeleportRequestViaLocation(); + + virtual void doTeleport(); + +protected: + inline const LLVector3d &getPosGlobal() const {return mPosGlobal;}; + +private: + LLVector3d mPosGlobal; +}; + + +class LLTeleportRequestViaLocationLookAt : public LLTeleportRequestViaLocation +{ +public: + LLTeleportRequestViaLocationLookAt(const LLVector3d &pPosGlobal); + virtual ~LLTeleportRequestViaLocationLookAt(); + + virtual void doTeleport(); + +protected: + +private: + +}; + + //-------------------------------------------------------------------- // Statics // @@ -3494,6 +3569,13 @@ void LLAgent::teleportRequest( // Landmark ID = LLUUID::null means teleport home void LLAgent::teleportViaLandmark(const LLUUID& landmark_asset_id) +{ + llassert(mTeleportRequest == NULL); + mTeleportRequest = LLTeleportRequestPtr(new LLTeleportRequestViaLandmark(landmark_asset_id)); + mTeleportRequest->doTeleport(); +} + +void LLAgent::doTeleportViaLandmark(const LLUUID& landmark_asset_id) { LLViewerRegion *regionp = getRegion(); if(regionp && teleportCore()) @@ -3509,6 +3591,13 @@ void LLAgent::teleportViaLandmark(const LLUUID& landmark_asset_id) } void LLAgent::teleportViaLure(const LLUUID& lure_id, BOOL godlike) +{ + llassert(mTeleportRequest == NULL); + mTeleportRequest = LLTeleportRequestPtr(new LLTeleportRequestViaLure(lure_id, godlike)); + mTeleportRequest->doTeleport(); +} + +void LLAgent::doTeleportViaLure(const LLUUID& lure_id, BOOL godlike) { LLViewerRegion* regionp = getRegion(); if(regionp && teleportCore()) @@ -3558,6 +3647,13 @@ void LLAgent::teleportCancel() void LLAgent::teleportViaLocation(const LLVector3d& pos_global) +{ + llassert(mTeleportRequest == NULL); + mTeleportRequest = LLTeleportRequestPtr(new LLTeleportRequestViaLocation(pos_global)); + mTeleportRequest->doTeleport(); +} + +void LLAgent::doTeleportViaLocation(const LLVector3d& pos_global) { LLViewerRegion* regionp = getRegion(); U64 handle = to_region_handle(pos_global); @@ -3600,6 +3696,13 @@ void LLAgent::teleportViaLocation(const LLVector3d& pos_global) // Teleport to global position, but keep facing in the same direction void LLAgent::teleportViaLocationLookAt(const LLVector3d& pos_global) +{ + llassert(mTeleportRequest == NULL); + mTeleportRequest = LLTeleportRequestPtr(new LLTeleportRequestViaLocationLookAt(pos_global)); + mTeleportRequest->doTeleport(); +} + +void LLAgent::doTeleportViaLocationLookAt(const LLVector3d& pos_global) { mbTeleportKeepsLookAt = true; gAgentCamera.setFocusOnAvatar(FALSE, ANIMATE); // detach camera form avatar, so it keeps direction @@ -3620,6 +3723,7 @@ void LLAgent::setTeleportState(ETeleportState state) { case TELEPORT_NONE: mbTeleportKeepsLookAt = false; + mTeleportRequest.reset(); break; case TELEPORT_MOVING: @@ -4034,5 +4138,91 @@ LLAgentQueryManager::~LLAgentQueryManager() { } -// EOF +//----------------------------------------------------------------------------- +// LLTeleportRequest +//----------------------------------------------------------------------------- +LLTeleportRequest::LLTeleportRequest() +{ +} + +LLTeleportRequest::~LLTeleportRequest() +{ +} + +//----------------------------------------------------------------------------- +// LLTeleportRequestViaLandmark +//----------------------------------------------------------------------------- + +LLTeleportRequestViaLandmark::LLTeleportRequestViaLandmark(const LLUUID &pLandmarkId) + : LLTeleportRequest(), + mLandmarkId(pLandmarkId) +{ +} + +LLTeleportRequestViaLandmark::~LLTeleportRequestViaLandmark() +{ +} + +void LLTeleportRequestViaLandmark::doTeleport() +{ + gAgent.doTeleportViaLandmark(getLandmarkId()); +} + +//----------------------------------------------------------------------------- +// LLTeleportRequestViaLure +//----------------------------------------------------------------------------- + +LLTeleportRequestViaLure::LLTeleportRequestViaLure(const LLUUID &pLureId, BOOL pIsLureGodLike) + : LLTeleportRequestViaLandmark(pLureId), + mIsLureGodLike(pIsLureGodLike) +{ +} + +LLTeleportRequestViaLure::~LLTeleportRequestViaLure() +{ +} + +void LLTeleportRequestViaLure::doTeleport() +{ + gAgent.doTeleportViaLure(getLandmarkId(), isLureGodLike()); +} + +//----------------------------------------------------------------------------- +// LLTeleportRequestViaLocation +//----------------------------------------------------------------------------- + +LLTeleportRequestViaLocation::LLTeleportRequestViaLocation(const LLVector3d &pPosGlobal) + : LLTeleportRequest(), + mPosGlobal(pPosGlobal) +{ +} + +LLTeleportRequestViaLocation::~LLTeleportRequestViaLocation() +{ +} + +void LLTeleportRequestViaLocation::doTeleport() +{ + gAgent.doTeleportViaLocation(getPosGlobal()); +} + +//----------------------------------------------------------------------------- +// LLTeleportRequestViaLocationLookAt +//----------------------------------------------------------------------------- + +LLTeleportRequestViaLocationLookAt::LLTeleportRequestViaLocationLookAt(const LLVector3d &pPosGlobal) + : LLTeleportRequestViaLocation(pPosGlobal) +{ +} + +LLTeleportRequestViaLocationLookAt::~LLTeleportRequestViaLocationLookAt() +{ +} + +void LLTeleportRequestViaLocationLookAt::doTeleport() +{ + gAgent.doTeleportViaLocationLookAt(getPosGlobal()); +} + +// EOF diff --git a/indra/newview/llagent.h b/indra/newview/llagent.h index 740770bbdf..3b27d48928 100644 --- a/indra/newview/llagent.h +++ b/indra/newview/llagent.h @@ -35,6 +35,7 @@ #include "llcoordframe.h" // for mFrameAgent #include "llvoavatardefines.h" +#include #include extern const BOOL ANIMATE; @@ -56,6 +57,9 @@ class LLAgentAccess; class LLSLURL; class LLPauseRequestHandle; class LLUIColor; +class LLTeleportRequest; + +typedef boost::shared_ptr LLTeleportRequestPtr; //-------------------------------------------------------------------- // Types @@ -556,9 +560,6 @@ private: // Teleport Actions //-------------------------------------------------------------------- public: - void teleportRequest(const U64& region_handle, - const LLVector3& pos_local, // Go to a named location home - bool look_at_from_camera = false); void teleportViaLandmark(const LLUUID& landmark_id); // Teleport to a landmark void teleportHome() { teleportViaLandmark(LLUUID::null); } // Go home void teleportViaLure(const LLUUID& lure_id, BOOL godlike); // To an invited location @@ -569,6 +570,20 @@ public: protected: bool teleportCore(bool is_local = false); // Stuff for all teleports; returns true if the teleport can proceed +private: + friend class LLTeleportRequest; + friend class LLTeleportRequestViaLandmark; + friend class LLTeleportRequestViaLure; + friend class LLTeleportRequestViaLocation; + friend class LLTeleportRequestViaLocationLookAt; + void teleportRequest(const U64& region_handle, + const LLVector3& pos_local, // Go to a named location home + bool look_at_from_camera = false); + void doTeleportViaLandmark(const LLUUID& landmark_id); // Teleport to a landmark + void doTeleportViaLure(const LLUUID& lure_id, BOOL godlike); // To an invited location + void doTeleportViaLocation(const LLVector3d& pos_global); // To a global location - this will probably need to be deprecated + void doTeleportViaLocationLookAt(const LLVector3d& pos_global);// To a global location, preserving camera rotation + //-------------------------------------------------------------------- // Teleport State //-------------------------------------------------------------------- @@ -577,6 +592,7 @@ public: void setTeleportState(ETeleportState state); private: ETeleportState mTeleportState; + LLTeleportRequestPtr mTeleportRequest; //-------------------------------------------------------------------- // Teleport Message -- cgit v1.2.3 From 8593020037ab299f945ee2ad425ccb79ceba42cf Mon Sep 17 00:00:00 2001 From: Jonathan Yap Date: Fri, 11 May 2012 11:33:03 -0400 Subject: STORM-1852 Altitude display stutters or is clamped when flying higher than 4096m --- indra/newview/llviewerobject.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/newview/llviewerobject.cpp b/indra/newview/llviewerobject.cpp index e590f29a9a..7c6ca90890 100644 --- a/indra/newview/llviewerobject.cpp +++ b/indra/newview/llviewerobject.cpp @@ -2382,10 +2382,11 @@ void LLViewerObject::interpolateLinearMotion(const F64 & time, const F32 & dt) { // This will put the object underground, but we can't tell if it will stop // at ground level or not min_height = LLWorld::getInstance()->getMinAllowedZ(this, new_pos_global); + // Cap maximum height + new_pos.mV[VZ] = llmin(LLWorld::getInstance()->getRegionMaxHeight(), new_pos.mV[VZ]); } new_pos.mV[VZ] = llmax(min_height, new_pos.mV[VZ]); - new_pos.mV[VZ] = llmin(LLWorld::getInstance()->getRegionMaxHeight(), new_pos.mV[VZ]); // Check to see if it's going off the region LLVector3 temp(new_pos); -- cgit v1.2.3 From 9bdb1d82f867147af44def8c1cca3dfb8259b99c Mon Sep 17 00:00:00 2001 From: Oz Linden Date: Fri, 11 May 2012 12:22:43 -0400 Subject: rename feature from "autocorrect" to "autoreplace", change names accordingly --- indra/llui/lllineeditor.cpp | 6 +- indra/llui/lllineeditor.h | 6 +- indra/newview/CMakeLists.txt | 8 +- indra/newview/app_settings/settings.xml | 15 +- .../newview/app_settings/settings_autocorrect.xml | 8369 -------------------- .../newview/app_settings/settings_autoreplace.xml | 8369 ++++++++++++++++++++ indra/newview/llautocorrect.cpp | 458 -- indra/newview/llautocorrect.h | 65 - indra/newview/llautocorrectfloater.cpp | 383 - indra/newview/llautocorrectfloater.h | 75 - indra/newview/llautoreplace.cpp | 458 ++ indra/newview/llautoreplace.h | 65 + indra/newview/llautoreplacefloater.cpp | 383 + indra/newview/llautoreplacefloater.h | 75 + indra/newview/llfloaterpreference.cpp | 4 +- indra/newview/llimfloater.cpp | 6 +- indra/newview/llnearbychatbar.cpp | 4 +- indra/newview/llviewerfloaterreg.cpp | 4 +- indra/newview/llviewermenu.cpp | 6 +- .../skins/default/xui/en/floater_autocorrect.xml | 315 - .../skins/default/xui/en/floater_autoreplace.xml | 315 + indra/newview/skins/default/xui/en/menu_viewer.xml | 4 +- .../default/xui/en/panel_preferences_chat.xml | 2 +- 23 files changed, 9692 insertions(+), 9703 deletions(-) delete mode 100644 indra/newview/app_settings/settings_autocorrect.xml create mode 100644 indra/newview/app_settings/settings_autoreplace.xml delete mode 100644 indra/newview/llautocorrect.cpp delete mode 100644 indra/newview/llautocorrect.h delete mode 100644 indra/newview/llautocorrectfloater.cpp delete mode 100644 indra/newview/llautocorrectfloater.h create mode 100644 indra/newview/llautoreplace.cpp create mode 100644 indra/newview/llautoreplace.h create mode 100644 indra/newview/llautoreplacefloater.cpp create mode 100644 indra/newview/llautoreplacefloater.h delete mode 100644 indra/newview/skins/default/xui/en/floater_autocorrect.xml create mode 100644 indra/newview/skins/default/xui/en/floater_autoreplace.xml (limited to 'indra') diff --git a/indra/llui/lllineeditor.cpp b/indra/llui/lllineeditor.cpp index 1f7843b79d..0f328aa065 100644 --- a/indra/llui/lllineeditor.cpp +++ b/indra/llui/lllineeditor.cpp @@ -152,7 +152,7 @@ LLLineEditor::LLLineEditor(const LLLineEditor::Params& p) mPreeditBgColor(p.preedit_bg_color()), mGLFont(p.font), mContextMenuHandle(), - mAutocorrectCallback() + mAutoreplaceCallback() { llassert( mMaxLengthBytes > 0 ); @@ -866,10 +866,10 @@ void LLLineEditor::addChar(const llwchar uni_char) LLUI::reportBadKeystroke(); } - if (!mReadOnly && mAutocorrectCallback != NULL) + if (!mReadOnly && mAutoreplaceCallback != NULL) { // call callback - mAutocorrectCallback(mText, mCursorPos); + mAutoreplaceCallback(mText, mCursorPos); } getWindow()->hideCursorUntilMouseMove(); diff --git a/indra/llui/lllineeditor.h b/indra/llui/lllineeditor.h index 53af9ac996..cd4be17f37 100644 --- a/indra/llui/lllineeditor.h +++ b/indra/llui/lllineeditor.h @@ -169,9 +169,9 @@ public: virtual BOOL setTextArg( const std::string& key, const LLStringExplicit& text ); virtual BOOL setLabelArg( const std::string& key, const LLStringExplicit& text ); - typedef boost::function autocorrect_callback_t; - autocorrect_callback_t mAutocorrectCallback; - void setAutocorrectCallback(autocorrect_callback_t cb) { mAutocorrectCallback = cb; } + typedef boost::function autoreplace_callback_t; + autoreplace_callback_t mAutoreplaceCallback; + void setAutoreplaceCallback(autoreplace_callback_t cb) { mAutoreplaceCallback = cb; } void setLabel(const LLStringExplicit &new_label) { mLabel = new_label; } const std::string& getLabel() { return mLabel.getString(); } diff --git a/indra/newview/CMakeLists.txt b/indra/newview/CMakeLists.txt index efad75ec59..90468ccbef 100644 --- a/indra/newview/CMakeLists.txt +++ b/indra/newview/CMakeLists.txt @@ -98,8 +98,8 @@ set(viewer_SOURCE_FILES llassetuploadresponders.cpp llattachmentsmgr.cpp llaudiosourcevo.cpp - llautocorrect.cpp - llautocorrectfloater.cpp + llautoreplace.cpp + llautoreplacefloater.cpp llavataractions.cpp llavatariconctrl.cpp llavatarlist.cpp @@ -656,8 +656,8 @@ set(viewer_HEADER_FILES llassetuploadresponders.h llattachmentsmgr.h llaudiosourcevo.h - llautocorrect.h - llautocorrectfloater.h + llautoreplace.h + llautoreplacefloater.h llavataractions.h llavatariconctrl.h llavatarlist.h diff --git a/indra/newview/app_settings/settings.xml b/indra/newview/app_settings/settings.xml index 4adf93e7aa..bc5c293625 100644 --- a/indra/newview/app_settings/settings.xml +++ b/indra/newview/app_settings/settings.xml @@ -346,10 +346,10 @@ Value 0 - AutoCorrect + AutoReplace Comment - Replaces common spelling mistakes with correct word + Replaces keywords with a configured word or phrase Persist 1 Type @@ -1650,17 +1650,6 @@ Value 0 - CmdLineAutocorrect - - Comment - Command for adding new entries to autocorrect - Persist - 1 - Type - String - Value - /addac - CmdLineDisableVoice Comment diff --git a/indra/newview/app_settings/settings_autocorrect.xml b/indra/newview/app_settings/settings_autocorrect.xml deleted file mode 100644 index 4669ba5822..0000000000 --- a/indra/newview/app_settings/settings_autocorrect.xml +++ /dev/null @@ -1,8369 +0,0 @@ - - - Custom - - announce - 0 - author - You - data - - enabled - 1 - priority - 10 - wordStyle - 1 - - Abbreviations - - announce - 0 - author - Wulf / TankMaster - data - - afaic - As far as I am concerned - afaik - As far as I know - afk - (Away from Keyboard) - atm - at the moment - bbiab - (Be back in a bit) - bbl - (Be back later) - brb - (Be Right Back) - btw - By the way - fyi - For your information - fwiw - For what its worth - gtg - (Got to go) - idk - I don't know - iirc - If I recall correctly - imho - in my humble opinion - imo - in my opinion - irl - in real life - lol - (Laughing out Loud) - nm - Not much - np - No problem - nsfw - not safe for work - nvm - Nevermind - rofl - (Rolling on Floor Laughing) - tc - Take care - thx - Thanks - ttfn - Ta Ta for now - ttyl - Talk to you later - ty - Thank you - tyvm - Thank you very much - wb - Welcome back - yw - You're Welcome - yvw - You're very welcome - - enabled - 1 - priority - 4 - wordStyle - 1 - - Spelling Corrections - - announce - 0 - author - LordGregGreg / Wikipedia - data - - Amercia - America - Bernouilli - Bernoulli - Blitzkreig - Blitzkrieg - Bonnano - Bonanno - Brasillian - Brazilian - Britian - Britain - Brittish - British - Buddah - Buddha - Buddist - Buddhist - Cambrige - Cambridge - Capetown - Cape Town - Carmalite - Carmelite - Carnagie - Carnegie - Carnagie-Mellon - Carnegie-Mellon - Carnigie - Carnegie - Carnigie-Mellon - Carnegie-Mellon - Carribbean - Caribbean - Carribean - Caribbean - Carthagian - Carthaginian - Cataline - Catiline - Ceasar - Caesar - Celcius - Celsius - Champange - Champagne - Cincinatti - Cincinnati - Cincinnatti - Cincinnati - Conneticut - Connecticut - Dardenelles - Dardanelles - Dravadian - Dravidian - Enlish - English - Europian - European - Europians - Europeans - Eurpean - European - Eurpoean - European - Farenheit - Fahrenheit - Febuary - February - Feburary - February - Flemmish - Flemish - Formalhaut - Fomalhaut - Foundland - Newfoundland - Fransiscan - Franciscan - Fransiscans - Franciscans - Galations - Galatians - Gameboy - Game Boy - Ghandi - Gandhi - Godounov - Godunov - Gothenberg - Gothenburg - Gottleib - Gottlieb - Guaduloupe - Guadalupe - Guadulupe - Guadalupe - Guatamala - Guatemala - Guatamalan - Guatemalan - Guilia - Giulia - Guilio - Giulio - Guiness - Guinness - Guiseppe - Giuseppe - Habsbourg - Habsburg - Hallowean - Halloween - Heidelburg - Heidelberg - Ihaca - Ithaca - Israelies - Israelis - Janurary - January - Januray - January - Japanes - Japanese - Johanine - Johannine - Jospeh - Joseph - Juadaism - Judaism - Juadism - Judaism - Lybia - Libya - Malcom - Malcolm - Massachussets - Massachusetts - Massachussetts - Massachusetts - Mediteranean - Mediterranean - Michagan - Michigan - Misouri - Missouri - Missisipi - Mississippi - Missisippi - Mississippi - Monserrat - Montserrat - Montnana - Montana - Morisette - Morissette - Morrisette - Morissette - Mythraic - Mithraic - Naploeon - Napoleon - Napolean - Napoleon - Napoleonian - Napoleonic - Nazereth - Nazareth - Newyorker - New Yorker - Novermber - November - Nullabour - Nullarbor - Nuremburg - Nuremberg - Palistian - Palestinian - Palistinian - Palestinian - Palistinians - Palestinians - Papanicalou - Papanicolaou - Peloponnes - Peloponnesus - Pennyslvania - Pennsylvania - Pharoah - Pharaoh - Philipines - Philippines - Phillipine - Philippine - Phillipines - Philippines - Phillippines - Philippines - Phonecian - Phoenecian - Portugese - Portuguese - Postdam - Potsdam - Premonasterians - Premonstratensians - Pucini - Puccini - Puertorrican - Puerto Rican - Puertorricans - Puerto Ricans - Queenland - Queensland - Rockerfeller - Rockefeller - Russion - Russian - Sanhedrim - Sanhedrin - Saterday - Saturday - Saterdays - Saturdays - Sionist - Zionist - Sionists - Zionists - Sixtin - Sistine - Skagerak - Skagerrak - Tolkein - Tolkien - Tuscon - Tucson - Ukranian - Ukrainian - UnitesStates - UnitedStates - Yementite - Yemenite - abandonned - abandoned - aberation - aberration - abilties - abilities - abilty - ability - abondon - abandon - abondoned - abandoned - abondoning - abandoning - abondons - abandons - aborigene - aborigine - abortificant - abortifacient - abreviate - abbreviate - abreviated - abbreviated - abreviation - abbreviation - abritrary - arbitrary - absail - abseil - absailing - abseiling - absense - absence - absolutly - absolutely - absorbsion - absorption - absorbtion - absorption - abundacies - abundances - abundancies - abundances - abundunt - abundant - abutts - abuts - acadamy - academy - acadmic - academic - accademic - academic - accademy - academy - acccused - accused - accelleration - acceleration - accension - ascension - acceptence - acceptance - acceptible - acceptable - accessable - accessible - accidentaly - accidentally - accidently - accidentally - acclimitization - acclimatization - accomadate - accommodate - accomadated - accommodated - accomadates - accommodates - accomadating - accommodating - accomadation - accommodation - accomadations - accommodations - accomdate - accommodate - accomodate - accommodate - accomodated - accommodated - accomodates - accommodates - accomodating - accommodating - accomodation - accommodation - accomodations - accommodations - accompanyed - accompanied - accordeon - accordion - accordian - accordion - accoring - according - accoustic - acoustic - accquainted - acquainted - accrediation - accreditation - accredidation - accreditation - accross - across - accussed - accused - acedemic - academic - acheive - achieve - acheived - achieved - acheivement - achievement - acheivements - achievements - acheives - achieves - acheiving - achieving - acheivment - achievement - acheivments - achievements - achievment - achievement - achievments - achievements - achivement - achievement - achivements - achievements - acknowldeged - acknowledged - acknowledgeing - acknowledging - ackward - awkward - acommodate - accommodate - acomplish - accomplish - acomplished - accomplished - acomplishment - accomplishment - acomplishments - accomplishments - acording - according - acordingly - accordingly - acquaintence - acquaintance - acquaintences - acquaintances - acquiantence - acquaintance - acquiantences - acquaintances - acquited - acquitted - activites - activities - activly - actively - actualy - actually - acuracy - accuracy - acused - accused - acustom - accustom - acustommed - accustomed - adavanced - advanced - adbandon - abandon - additinally - additionally - additionaly - additionally - additonal - additional - additonally - additionally - addmission - admission - addopt - adopt - addopted - adopted - addoptive - adoptive - addres - address - addresable - addressable - addresed - addressed - addresing - addressing - addressess - addresses - addtion - addition - addtional - additional - adecuate - adequate - adequit - adequate - adhearing - adhering - adherance - adherence - admendment - amendment - admininistrative - administrative - adminstered - administered - adminstrate - administrate - adminstration - administration - adminstrative - administrative - adminstrator - administrator - admissability - admissibility - admissable - admissible - admited - admitted - admitedly - admittedly - adn - and - adolecent - adolescent - adquire - acquire - adquired - acquired - adquires - acquires - adquiring - acquiring - adres - address - adresable - addressable - adresing - addressing - adress - address - adressable - addressable - adressed - addressed - adressing - addressing - adventrous - adventurous - advertisment - advertisement - advertisments - advertisements - advesary - adversary - adviced - advised - aeriel - aerial - aeriels - aerials - afair - affair - afficianados - aficionados - afficionado - aficionado - afficionados - aficionados - affilate - affiliate - affilliate - affiliate - affort - afford - aforememtioned - aforementioned - againnst - against - agains - against - agaisnt - against - aganist - against - aggaravates - aggravates - aggreed - agreed - aggreement - agreement - aggregious - egregious - aggresive - aggressive - agian - again - agianst - against - agin - again - agina - again - aginst - against - agravate - aggravate - agre - agree - agred - agreed - agreeement - agreement - agreemnt - agreement - agregate - aggregate - agregates - aggregates - agreing - agreeing - agression - aggression - agressive - aggressive - agressively - aggressively - agressor - aggressor - agricuture - agriculture - agrieved - aggrieved - ahev - have - ahppen - happen - ahve - have - aicraft - aircraft - aiport - airport - airbourne - airborne - aircaft - aircraft - aircrafts - aircraft - airporta - airports - airrcraft - aircraft - aisian - asian - albiet - albeit - alchohol - alcohol - alchoholic - alcoholic - alchol - alcohol - alcholic - alcoholic - alcohal - alcohol - alcoholical - alcoholic - aledge - allege - aledged - alleged - aledges - alleges - alege - allege - aleged - alleged - alegience - allegiance - algebraical - algebraic - algorhitms - algorithms - algoritm - algorithm - algoritms - algorithms - alientating - alienating - alledge - allege - alledged - alleged - alledgedly - allegedly - alledges - alleges - allegedely - allegedly - allegedy - allegedly - allegely - allegedly - allegence - allegiance - allegience - allegiance - allign - align - alligned - aligned - alliviate - alleviate - allopone - allophone - allopones - allophones - allready - already - allthough - although - alltime - all-time - alltogether - altogether - almsot - almost - alochol - alcohol - alomst - almost - alot - a lot - alotted - allotted - alowed - allowed - alowing - allowing - alreayd - already - alse - else - alsot - also - alternitives - alternatives - altho - although - althought - although - altough - although - alusion - allusion - alwasy - always - alwyas - always - amalgomated - amalgamated - amatuer - amateur - amature - armature - amendmant - amendment - amerliorate - ameliorate - amke - make - amking - making - ammend - amend - ammended - amended - ammendment - amendment - ammendments - amendments - ammount - amount - ammused - amused - amoung - among - amoungst - amongst - amung - among - amunition - ammunition - analagous - analogous - analitic - analytic - analogeous - analogous - anarchim - anarchism - anarchistm - anarchism - anbd - and - ancestory - ancestry - ancilliary - ancillary - androgenous - androgynous - androgeny - androgyny - anihilation - annihilation - aniversary - anniversary - annoint - anoint - annointed - anointed - annointing - anointing - annoints - anoints - annouced - announced - annualy - annually - annuled - annulled - anohter - another - anomolies - anomalies - anomolous - anomalous - anomoly - anomaly - anonimity - anonymity - anounced - announced - anouncement - announcement - ansalisation - nasalisation - ansalization - nasalization - ansestors - ancestors - antartic - antarctic - anthromorphization - anthropomorphization - anthropolgist - anthropologist - anthropolgy - anthropology - anual - annual - anulled - annulled - anwsered - answered - anyhwere - anywhere - anyother - any other - anytying - anything - aparent - apparent - aparment - apartment - apenines - apennines - aplication - application - aplied - applied - apolegetics - apologetics - apon - apron - apparant - apparent - apparantly - apparently - appart - apart - appartment - apartment - appartments - apartments - appealling - appealing - appeareance - appearance - appearence - appearance - appearences - appearances - apperance - appearance - apperances - appearances - appereance - appearance - appereances - appearances - applicaiton - application - applicaitons - applications - appologies - apologies - appology - apology - apprearance - appearance - apprieciate - appreciate - approachs - approaches - appropiate - appropriate - appropraite - appropriate - appropropiate - appropriate - approproximate - approximate - approxamately - approximately - approxiately - approximately - approximitely - approximately - aprehensive - apprehensive - apropriate - appropriate - aproximate - approximate - aproximately - approximately - aquaduct - aqueduct - aquaintance - acquaintance - aquainted - acquainted - aquiantance - acquaintance - aquire - acquire - aquired - acquired - aquiring - acquiring - aquisition - acquisition - aquitted - acquitted - aranged - arranged - arangement - arrangement - arbitarily - arbitrarily - arbitary - arbitrary - archaelogists - archaeologists - archaelogy - archaeology - archaoelogy - archaeology - archaology - archaeology - archeaologist - archaeologist - archeaologists - archaeologists - archetect - architect - archetects - architects - archetectural - architectural - archetecturally - architecturally - archetecture - architecture - archiac - archaic - archictect - architect - archimedian - archimedean - architecht - architect - architechturally - architecturally - architechture - architecture - architechtures - architectures - architectual - architectural - archtype - archetype - archtypes - archetypes - aready - already - areodynamics - aerodynamics - argubly - arguably - arguement - argument - arguements - arguments - arised - arose - arival - arrival - armamant - armament - armistace - armistice - arogant - arrogant - arogent - arrogant - aroud - around - arrangment - arrangement - arrangments - arrangements - arround - around - artical - article - artice - article - articel - article - artifical - artificial - artifically - artificially - artillary - artillery - arund - around - asetic - ascetic - asfar - as far - asign - assign - aslo - also - asociated - associated - asorbed - absorbed - asphyxation - asphyxiation - assasin - assassin - assasinate - assassinate - assasinated - assassinated - assasinates - assassinates - assasination - assassination - assasinations - assassinations - assasined - assassinated - assasins - assassins - assassintation - assassination - assemple - assemble - assertation - assertion - asside - aside - assisnate - assassinate - assit - assist - assitant - assistant - assocation - association - assoicate - associate - assoicated - associated - assoicates - associates - assosication - assassination - asssassans - assassins - assualt - assault - assualted - assaulted - assymetric - asymmetric - assymetrical - asymmetrical - asteriod - asteroid - asthetic - aesthetic - asthetical - aesthetical - asthetically - aesthetically - asume - assume - aswell - as well - atain - attain - atempting - attempting - atheistical - atheistic - athenean - athenian - atheneans - athenians - athiesm - atheism - athiest - atheist - atorney - attorney - atribute - attribute - atributed - attributed - atributes - attributes - attaindre - attainder - attemp - attempt - attemped - attempted - attemt - attempt - attemted - attempted - attemting - attempting - attemts - attempts - attendence - attendance - attendent - attendant - attendents - attendants - attened - attended - attension - attention - attitide - attitude - attributred - attributed - attrocities - atrocities - audeince - audience - auromated - automated - austrailia - Australia - austrailian - Australian - auther - author - authobiographic - autobiographic - authobiography - autobiography - authorative - authoritative - authorites - authorities - authorithy - authority - authoritiers - authorities - authoritive - authoritative - authrorities - authorities - autochtonous - autochthonous - autoctonous - autochthonous - automaticly - automatically - automibile - automobile - automonomous - autonomous - autor - author - autority - authority - auxilary - auxiliary - auxillaries - auxiliaries - auxillary - auxiliary - auxilliaries - auxiliaries - auxilliary - auxiliary - availabe - available - availablity - availability - availaible - available - availble - available - availiable - available - availible - available - avalable - available - avalance - avalanche - avaliable - available - avation - aviation - avengence - a vengeance - averageed - averaged - avilable - available - awared - awarded - awya - away - baceause - because - backgorund - background - backrounds - backgrounds - bakc - back - banannas - bananas - bandwith - bandwidth - bankrupcy - bankruptcy - banruptcy - bankruptcy - baout - about - basicaly - basically - basicly - basically - bcak - back - beachead - beachhead - beacuse - because - beastiality - bestiality - beatiful - beautiful - beaurocracy - bureaucracy - beaurocratic - bureaucratic - beautyfull - beautiful - becamae - became - becames - becomes - becasue - because - beccause - because - becomeing - becoming - becomming - becoming - becouse - because - becuase - because - bedore - before - befoer - before - beggin - begin - begginer - beginner - begginers - beginners - beggining - beginning - begginings - beginnings - beggins - begins - begining - beginning - beginnig - beginning - behavour - behavior - beleagured - beleaguered - beleif - belief - beleive - believe - beleived - believed - beleives - believes - beleiving - believing - beligum - belgium - belive - believe - belived - believed - belives - believes - belligerant - belligerent - bellweather - bellwether - bemusemnt - bemusement - beneficary - beneficiary - beng - being - benificial - beneficial - benifit - benefit - benifits - benefits - bergamont - bergamot - beseige - besiege - beseiged - besieged - beseiging - besieging - betwen - between - beween - between - bewteen - between - bilateraly - bilaterally - billingualism - bilingualism - binominal - binomial - bizzare - bizarre - blaim - blame - blaimed - blamed - blessure - blessing - bodydbuilder - bodybuilder - bombardement - bombardment - bombarment - bombardment - bondary - boundary - borke - broke - boundry - boundary - bouyancy - buoyancy - bouyant - buoyant - boyant - buoyant - breakthough - breakthrough - breakthroughts - breakthroughs - breif - brief - breifly - briefly - brethen - brethren - bretheren - brethren - briliant - brilliant - brillant - brilliant - brimestone - brimstone - broacasted - broadcast - broadacasting - broadcasting - broady - broadly - buisness - business - buisnessman - businessman - buoancy - buoyancy - burried - buried - busineses - businesses - busness - business - bussiness - business - caculater - calculator - cacuses - caucuses - cahracters - characters - calaber - caliber - calculater - calculator - calculs - calculus - calenders - calendars - caligraphy - calligraphy - caluclate - calculate - caluclated - calculated - caluculate - calculate - caluculated - calculated - calulate - calculate - calulated - calculated - calulater - calculator - camoflage - camouflage - campain - campaign - campains - campaigns - candadate - candidate - candiate - candidate - candidiate - candidate - cannister - canister - cannisters - canisters - cannnot - cannot - cannonical - canonical - cannotation - connotation - cannotations - connotations - cant - can't - caost - coast - caperbility - capability - capible - capable - captial - capital - captued - captured - capturd - captured - carachter - character - caracterized - characterized - carcas - carcass - carefull - careful - careing - caring - carismatic - charismatic - carnege - carnage - carnige - carnage - carniverous - carnivorous - carreer - career - carrers - careers - cartdridge - cartridge - carthographer - cartographer - cartilege - cartilage - cartilidge - cartilage - cartrige - cartridge - casette - cassette - casion - caisson - cassawory - cassowary - cassowarry - cassowary - casulaties - casualties - casulaty - casualty - catagories - categories - catagorized - categorized - catagory - category - catapillar - caterpillar - catapillars - caterpillars - catapiller - caterpillar - catapillers - caterpillars - catepillar - caterpillar - catepillars - caterpillars - catergorize - categorize - catergorized - categorized - caterpilar - caterpillar - caterpilars - caterpillars - caterpiller - caterpillar - caterpillers - caterpillars - cathlic - catholic - catholocism - catholicism - catterpilar - caterpillar - catterpilars - caterpillars - catterpillar - caterpillar - catterpillars - caterpillars - cattleship - battleship - causalities - casualties - cellpading - cellpadding - cementary - cemetery - cemetarey - cemetery - cemetaries - cemeteries - cemetary - cemetery - cencus - census - censur - censor - cententenial - centennial - centruies - centuries - centruy - century - ceratin - certain - cerimonial - ceremonial - cerimonies - ceremonies - cerimonious - ceremonious - cerimony - ceremony - ceromony - ceremony - certainity - certainty - certian - certain - chalenging - challenging - challange - challenge - challanged - challenged - challege - challenge - changable - changeable - charachter - character - charachters - characters - charactersistic - characteristic - charactor - character - charactors - characters - charasmatic - charismatic - charaterized - characterized - chariman - chairman - charistics - characteristics - cheif - chief - cheifs - chiefs - chemcial - chemical - chemcially - chemically - chemestry - chemistry - chemicaly - chemically - childbird - childbirth - childen - children - choosen - chosen - chracter - character - chuch - church - churchs - churches - circulaton - circulation - circumsicion - circumcision - circut - circuit - ciricuit - circuit - ciriculum - curriculum - civillian - civilian - claer - clear - claerer - clearer - claerly - clearly - claimes - claims - clas - class - clasic - classic - clasical - classical - clasically - classically - cleareance - clearance - clera - clear - clincial - clinical - clinicaly - clinically - cmo - com - cmoputer - computer - co-incided - coincided - coctail - cocktail - coform - conform - cognizent - cognizant - coincedentally - coincidentally - colaborations - collaborations - colateral - collateral - colelctive - collective - collaberative - collaborative - collecton - collection - collegue - colleague - collegues - colleagues - collonade - colonnade - collonies - colonies - collony - colony - collosal - colossal - colonizators - colonizers - comander - commander - comando - commando - comandos - commandos - comany - company - comapany - company - comback - comeback - combanations - combinations - combinatins - combinations - combusion - combustion - comdemnation - condemnation - comemmorates - commemorates - comemoretion - commemoration - comision - commission - comisioned - commissioned - comisioner - commissioner - comisioning - commissioning - comisions - commissions - comission - commission - comissioned - commissioned - comissioner - commissioner - comissioning - commissioning - comissions - commissions - comited - committed - comiting - committing - comitted - committed - comittee - committee - comitting - committing - commandoes - commandos - commedic - comedic - commemerative - commemorative - commemmorate - commemorate - commemmorating - commemorating - commerical - commercial - commerically - commercially - commericial - commercial - commericially - commercially - commerorative - commemorative - comming - coming - comminication - communication - commision - commission - commisioned - commissioned - commisioner - commissioner - commisioning - commissioning - commisions - commissions - commited - committed - commitee - committee - commiting - committing - committe - committee - committment - commitment - committments - commitments - commmemorated - commemorated - commongly - commonly - commonweath - commonwealth - commuications - communications - commuinications - communications - communciation - communication - communiation - communication - communites - communities - compability - compatibility - comparision - comparison - comparisions - comparisons - comparitive - comparative - comparitively - comparatively - compatabilities - compatibilities - compatability - compatibility - compatable - compatible - compatablities - compatibilities - compatablity - compatibility - compatiable - compatible - compatiblities - compatibilities - compatiblity - compatibility - compeitions - competitions - compensantion - compensation - competance - competence - competant - competent - competative - competitive - competion - competition - competitiion - competition - competive - competitive - competiveness - competitiveness - comphrehensive - comprehensive - compitent - competent - completedthe - completed the - completelyl - completely - completetion - completion - complier - compiler - componant - component - comprable - comparable - comprimise - compromise - compulsary - compulsory - compulsery - compulsory - computarized - computerized - concensus - consensus - concider - consider - concidered - considered - concidering - considering - conciders - considers - concieted - conceited - concieved - conceived - concious - conscious - conciously - consciously - conciousness - consciousness - condamned - condemned - condemmed - condemned - condidtion - condition - condidtions - conditions - conditionsof - conditions of - conected - connected - conection - connection - conesencus - consensus - confidental - confidential - confidentally - confidentially - confids - confides - configureable - configurable - confortable - comfortable - congradulations - congratulations - congresional - congressional - conived - connived - conjecutre - conjecture - conjuction - conjunction - conotations - connotations - conquerd - conquered - conquerer - conqueror - conquerers - conquerors - conqured - conquered - conscent - consent - consciouness - consciousness - consdider - consider - consdidered - considered - consdiered - considered - consectutive - consecutive - consenquently - consequently - consentrate - concentrate - consentrated - concentrated - consentrates - concentrates - consept - concept - consequentually - consequently - consequeseces - consequences - consern - concern - conserned - concerned - conserning - concerning - conservitive - conservative - consiciousness - consciousness - consicousness - consciousness - considerd - considered - consideres - considered - consious - conscious - consistant - consistent - consistantly - consistently - consituencies - constituencies - consituency - constituency - consituted - constituted - consitution - constitution - consitutional - constitutional - consolodate - consolidate - consolodated - consolidated - consonent - consonant - consonents - consonants - consorcium - consortium - conspiracys - conspiracies - conspiriator - conspirator - constaints - constraints - constanly - constantly - constarnation - consternation - constatn - constant - constinually - continually - constituant - constituent - constituants - constituents - constituion - constitution - constituional - constitutional - consttruction - construction - constuction - construction - consulant - consultant - consumate - consummate - consumated - consummated - contaiminate - contaminate - containes - contains - contamporaries - contemporaries - contamporary - contemporary - contempoary - contemporary - contemporaneus - contemporaneous - contempory - contemporary - contendor - contender - contibute - contribute - contibuted - contributed - contibutes - contributes - contigent - contingent - contined - continued - continous - continuous - continously - continuously - continueing - continuing - contravercial - controversial - contraversy - controversy - contributer - contributor - contributers - contributors - contritutions - contributions - controled - controlled - controling - controlling - controll - control - controlls - controls - controvercial - controversial - controvercy - controversy - controveries - controversies - controversal - controversial - controversey - controversy - controvertial - controversial - controvery - controversy - contruction - construction - conveinent - convenient - convenant - covenant - convential - conventional - convertables - convertibles - convertion - conversion - conveyer - conveyor - conviced - convinced - convienient - convenient - coordiantion - coordination - coorperations - corporations - copmetitors - competitors - coputer - computer - copywrite - copyright - coridal - cordial - cornmitted - committed - corosion - corrosion - corparate - corporate - corperations - corporations - correcters - correctors - correponding - corresponding - correposding - corresponding - correspondant - correspondent - correspondants - correspondents - corridoors - corridors - corrispond - correspond - corrispondant - correspondent - corrispondants - correspondents - corrisponded - corresponded - corrisponding - corresponding - corrisponds - corresponds - costitution - constitution - coucil - council - counries - countries - countains - contains - countires - countries - coururier - courier - coverted - converted - cpoy - copy - creaeted - created - creedence - credence - critereon - criterion - criterias - criteria - criticists - critics - critising - criticising - critisising - criticising - critisism - criticism - critisisms - criticisms - critisize - criticise - critisized - criticised - critisizes - criticises - critisizing - criticising - critized - criticized - critizing - criticizing - crockodiles - crocodiles - crowm - crown - crtical - critical - crticised - criticised - crucifiction - crucifixion - crusies - cruises - crystalisation - crystallisation - culiminating - culminating - cumulatative - cumulative - curch - church - curcuit - circuit - currenly - currently - curriculem - curriculum - cxan - cyan - cyclinder - cylinder - dacquiri - daiquiri - dael - deal - dalmation - dalmatian - damenor - demeanor - dammage - damage - daugher - daughter - debateable - debatable - decendant - descendant - decendants - descendants - decendent - descendant - decendents - descendants - decideable - decidable - decidely - decidedly - decieved - deceived - decison - decision - decomissioned - decommissioned - decomposit - decompose - decomposited - decomposed - decompositing - decomposing - decomposits - decomposes - decress - decrees - decribe - describe - decribed - described - decribes - describes - decribing - describing - dectect - detect - defendent - defendant - defendents - defendants - deffensively - defensively - deffine - define - deffined - defined - definance - defiance - definate - definite - definately - definitely - definatly - definitely - definetly - definitely - definining - defining - definit - definite - definitly - definitely - definiton - definition - defintion - definition - degrate - degrade - delagates - delegates - delapidated - dilapidated - delerious - delirious - delevopment - development - deliberatly - deliberately - delusionally - delusively - demenor - demeanor - demographical - demographic - demolision - demolition - demorcracy - democracy - demostration - demonstration - denegrating - denigrating - densly - densely - deparment - department - deparmental - departmental - deparments - departments - dependance - dependence - dependancy - dependency - dependant - dependent - deram - dream - deriviated - derived - derivitive - derivative - derogitory - derogatory - descendands - descendants - descibed - described - descision - decision - descisions - decisions - descriibes - describes - descripters - descriptors - descripton - description - desctruction - destruction - descuss - discuss - desgined - designed - deside - decide - desigining - designing - desinations - destinations - desintegrated - disintegrated - desintegration - disintegration - desireable - desirable - desitned - destined - desktiop - desktop - desorder - disorder - desoriented - disoriented - desparate - desperate - despict - depict - despiration - desperation - dessicated - desiccated - dessigned - designed - destablized - destabilized - destory - destroy - detailled - detailed - detatched - detached - deteoriated - deteriorated - deteriate - deteriorate - deterioriating - deteriorating - determinining - determining - detremental - detrimental - devasted - devastated - develope - develop - developement - development - developped - developed - develpment - development - devels - delves - devestated - devastated - devestating - devastating - devide - divide - devided - divided - devistating - devastating - devolopement - development - diablical - diabolical - diamons - diamonds - diaster - disaster - dichtomy - dichotomy - diconnects - disconnects - dicover - discover - dicovered - discovered - dicovering - discovering - dicovers - discovers - dicovery - discovery - dicussed - discussed - didnt - didn't - diea - idea - dieing - dying - dieties - deities - diety - deity - diferent - different - diferrent - different - differentiatiations - differentiations - differnt - different - difficulity - difficulty - diffrent - different - dificulties - difficulties - dificulty - difficulty - dimenions - dimensions - dimention - dimension - dimentional - dimensional - dimentions - dimensions - dimesnional - dimensional - diminuitive - diminutive - dimunitive - diminutive - diosese - diocese - diphtong - diphthong - diphtongs - diphthongs - diplomancy - diplomacy - dipthong - diphthong - dipthongs - diphthongs - dirived - derived - disagreeed - disagreed - disapeared - disappeared - disapointing - disappointing - disappearred - disappeared - disaproval - disapproval - disasterous - disastrous - disatisfaction - dissatisfaction - disatisfied - dissatisfied - disatrous - disastrous - discontentment - discontent - discribe - describe - discribed - described - discribes - describes - discribing - describing - disctinction - distinction - disctinctive - distinctive - disemination - dissemination - disenchanged - disenchanted - disiplined - disciplined - disobediance - disobedience - disobediant - disobedient - disolved - dissolved - disover - discover - dispair - despair - disparingly - disparagingly - dispence - dispense - dispenced - dispensed - dispencing - dispensing - dispicable - despicable - dispite - despite - dispostion - disposition - disproportiate - disproportionate - disputandem - disputandum - disricts - districts - dissagreement - disagreement - dissapear - disappear - dissapearance - disappearance - dissapeared - disappeared - dissapearing - disappearing - dissapears - disappears - dissappear - disappear - dissappears - disappears - dissappointed - disappointed - dissarray - disarray - dissobediance - disobedience - dissobediant - disobedient - dissobedience - disobedience - dissobedient - disobedient - distiction - distinction - distingish - distinguish - distingished - distinguished - distingishes - distinguishes - distingishing - distinguishing - distingquished - distinguished - distrubution - distribution - distruction - destruction - distructive - destructive - ditributed - distributed - diversed - diverged - divice - device - divison - division - divisons - divisions - doccument - document - doccumented - documented - doccuments - documents - docrines - doctrines - doctines - doctrines - documenatry - documentary - doens - does - doesnt - doesn't - doign - doing - dominaton - domination - dominent - dominant - dominiant - dominant - donig - doing - dont - don't - dosen't - doesn't - doub - doubt - doulbe - double - dowloads - downloads - dramtic - dramatic - draughtman - draughtsman - dreasm - dreams - driectly - directly - drnik - drink - druming - drumming - drummless - drumless - dupicate - duplicate - durig - during - durring - during - duting - during - dyas - dryas - eahc - each - ealier - earlier - earlies - earliest - earnt - earned - ecclectic - eclectic - eceonomy - economy - ecidious - deciduous - eclispe - eclipse - ecomonic - economic - ect - etc - eearly - early - efel - evil - effeciency - efficiency - effecient - efficient - effeciently - efficiently - efficency - efficiency - efficent - efficient - efficently - efficiently - efford - effort - effords - efforts - effulence - effluence - eigth - eight - eiter - either - elction - election - electic - electric - electon - electron - electrial - electrical - electricly - electrically - electricty - electricity - elementay - elementary - eleminated - eliminated - eleminating - eliminating - eles - eels - eletricity - electricity - elicided - elicited - eligable - eligible - elimentary - elementary - ellected - elected - elphant - elephant - embarass - embarrass - embarassed - embarrassed - embarassing - embarrassing - embarassment - embarrassment - embargos - embargoes - embarras - embarrass - embarrased - embarrassed - embarrasing - embarrassing - embarrasment - embarrassment - embezelled - embezzled - emblamatic - emblematic - eminate - emanate - eminated - emanated - emision - emission - emited - emitted - emiting - emitting - emition - emission - emmediately - immediately - emmigrated - immigrated - emminently - eminently - emmisaries - emissaries - emmisarries - emissaries - emmisarry - emissary - emmisary - emissary - emmision - emission - emmisions - emissions - emmited - emitted - emmiting - emitting - emmitted - emitted - emmitting - emitting - emnity - enmity - emperical - empirical - emphaised - emphasised - emphsis - emphasis - emphysyma - emphysema - emprisoned - imprisoned - enameld - enameled - enchancement - enhancement - encouraing - encouraging - encryptiion - encryption - encylopedia - encyclopedia - endevors - endeavors - endevour - endeavour - endig - ending - endolithes - endoliths - enduce - induce - ened - need - enflamed - inflamed - enforceing - enforcing - engagment - engagement - engeneer - engineer - engeneering - engineering - engieneer - engineer - engieneers - engineers - enlargment - enlargement - enlargments - enlargements - enourmous - enormous - enourmously - enormously - ensconsed - ensconced - entaglements - entanglements - enteratinment - entertainment - enthusiatic - enthusiastic - entitity - entity - entitlied - entitled - entrepeneur - entrepreneur - entrepeneurs - entrepreneurs - enviorment - environment - enviormental - environmental - enviormentally - environmentally - enviorments - environments - enviornment - environment - enviornmental - environmental - enviornmentalist - environmentalist - enviornmentally - environmentally - enviornments - environments - enviroment - environment - enviromental - environmental - enviromentalist - environmentalist - enviromentally - environmentally - enviroments - environments - envolutionary - evolutionary - envrionments - environments - enxt - next - epidsodes - episodes - epsiode - episode - equialent - equivalent - equilibium - equilibrium - equilibrum - equilibrium - equiped - equipped - equippment - equipment - equitorial - equatorial - equivelant - equivalent - equivelent - equivalent - equivilant - equivalent - equivilent - equivalent - equivlalent - equivalent - erally - really - eratic - erratic - eratically - erratically - eraticly - erratically - errupted - erupted - esential - essential - esitmated - estimated - esle - else - especialy - especially - essencial - essential - essense - essence - essentail - essential - essentialy - essentially - essentual - essential - essesital - essential - estabishes - establishes - establising - establishing - ethnocentricm - ethnocentrism - ethose - those - evenhtually - eventually - eventally - eventually - eventhough - even though - eventially - eventually - eventualy - eventually - everthing - everything - everytime - every time - everyting - everything - eveyr - every - evidentally - evidently - exagerate - exaggerate - exagerated - exaggerated - exagerates - exaggerates - exagerating - exaggerating - exagerrate - exaggerate - exagerrated - exaggerated - exagerrates - exaggerates - exagerrating - exaggerating - examinated - examined - exampt - exempt - exapansion - expansion - excact - exact - excange - exchange - excecute - execute - excecuted - executed - excecutes - executes - excecuting - executing - excecution - execution - excedded - exceeded - excelent - excellent - excell - excel - excellance - excellence - excellant - excellent - excells - excels - excercise - exercise - exchanching - exchanging - excisted - existed - exculsivly - exclusively - execising - exercising - exection - execution - exectued - executed - exeedingly - exceedingly - exelent - excellent - exellent - excellent - exemple - example - exept - except - exeptional - exceptional - exerbate - exacerbate - exerbated - exacerbated - exerciese - exercises - exerpt - excerpt - exerpts - excerpts - exersize - exercise - exerternal - external - exhalted - exalted - exhibtion - exhibition - exibition - exhibition - exibitions - exhibitions - exicting - exciting - exinct - extinct - existance - existence - existant - existent - existince - existence - exliled - exiled - exludes - excludes - exmaple - example - exonorate - exonerate - exoskelaton - exoskeleton - expalin - explain - expatriot - expatriate - expeced - expected - expecially - especially - expeditonary - expeditionary - expeiments - experiments - expell - expel - expells - expels - experiance - experience - experianced - experienced - expiditions - expeditions - expierence - experience - explaination - explanation - explaning - explaining - explictly - explicitly - exploititive - exploitative - explotation - exploitation - expropiated - expropriated - expropiation - expropriation - exressed - expressed - extemely - extremely - extention - extension - extentions - extensions - extered - exerted - extermist - extremist - extint - extinct - extradiction - extradition - extraterrestial - extraterrestrial - extraterrestials - extraterrestrials - extravagent - extravagant - extrememly - extremely - extremeophile - extremophile - extremly - extremely - extrordinarily - extraordinarily - extrordinary - extraordinary - eyar - year - eyars - years - eyasr - years - faciliate - facilitate - faciliated - facilitated - faciliates - facilitates - facilites - facilities - facillitate - facilitate - facinated - fascinated - facist - fascist - familes - families - familliar - familiar - famoust - famous - fanatism - fanaticism - fatc - fact - faught - fought - favoutrable - favourable - feasable - feasible - fedreally - federally - feromone - pheromone - fertily - fertility - fianite - finite - fianlly - finally - ficticious - fictitious - fictious - fictitious - fidn - find - fiercly - fiercely - fightings - fighting - filiament - filament - fimilies - families - finacial - financial - finaly - finally - financialy - financially - firends - friends - firts - first - fisionable - fissionable - flamable - flammable - flawess - flawless - fleed - fled - florescent - fluorescent - flourescent - fluorescent - flourine - fluorine - fluorish - flourish - follwoing - following - folowing - following - fomed - formed - fomr - from - fonetic - phonetic - fontrier - fontier - foootball - football - forbad - forbade - forbiden - forbidden - foreward - foreword - forfiet - forfeit - forhead - forehead - foriegn - foreign - formallize - formalize - formallized - formalized - formaly - formally - formelly - formerly - formidible - formidable - formost - foremost - forsaw - foresaw - forseeable - foreseeable - fortelling - foretelling - forunner - forerunner - foucs - focus - foudn - found - fougth - fought - foundaries - foundries - foundary - foundry - fourties - forties - fourty - forty - fouth - fourth - foward - forward - freind - friend - freindly - friendly - frequentily - frequently - frome - from - fromed - formed - froniter - frontier - fucntion - function - fucntioning - functioning - fufill - fulfill - fufilled - fulfilled - fulfiled - fulfilled - fullfill - fulfill - fullfilled - fulfilled - fundametal - fundamental - fundametals - fundamentals - funguses - fungi - funtion - function - furuther - further - futher - further - futhermore - furthermore - galatic - galactic - gallaxies - galaxies - galvinized - galvanized - ganerate - generate - ganes - games - ganster - gangster - garantee - guarantee - garanteed - guaranteed - garantees - guarantees - garnison - garrison - gaurantee - guarantee - gauranteed - guaranteed - gaurantees - guarantees - gaurd - guard - gaurentee - guarantee - gaurenteed - guaranteed - gaurentees - guarantees - geneological - genealogical - geneologies - genealogies - geneology - genealogy - generaly - generally - generatting - generating - genialia - genitalia - geographicial - geographical - geometrician - geometer - geometricians - geometers - gerat - great - glight - flight - gnawwed - gnawed - godess - goddess - godesses - goddesses - gogin - going - goign - going - gonig - going - gouvener - governor - govement - government - govenment - government - govenrment - government - goverance - governance - goverment - government - govermental - governmental - governer - governor - governmnet - government - govorment - government - govormental - governmental - govornment - government - gracefull - graceful - graet - great - grafitti - graffiti - gramatically - grammatically - grammaticaly - grammatically - grammer - grammar - grat - great - gratuitious - gratuitous - greatful - grateful - greatfully - gratefully - greif - grief - gridles - griddles - gropu - group - grwo - grow - guage - gauge - guarentee - guarantee - guarenteed - guaranteed - guarentees - guarantees - guerilla - guerrilla - guerillas - guerrillas - guerrila - guerrilla - guerrilas - guerrillas - guidence - guidance - gunanine - guanine - gurantee - guarantee - guranteed - guaranteed - gurantees - guarantees - guttaral - guttural - gutteral - guttural - habaeus - habeas - habeus - habeas - haemorrage - haemorrhage - haev - have - halp - help - hapen - happen - hapened - happened - hapening - happening - happend - happened - happended - happened - happenned - happened - harased - harassed - harases - harasses - harasment - harassment - harasments - harassments - harassement - harassment - harras - harass - harrased - harassed - harrases - harasses - harrasing - harassing - harrasment - harassment - harrasments - harassments - harrassed - harassed - harrasses - harassed - harrassing - harassing - harrassment - harassment - harrassments - harassments - hasnt - hasn't - haviest - heaviest - headquarer - headquarter - headquater - headquarter - headquatered - headquartered - headquaters - headquarters - healthercare - healthcare - heared - heard - heathy - healthy - heigher - higher - heirarchy - hierarchy - heiroglyphics - hieroglyphics - helment - helmet - helpfull - helpful - helpped - helped - hemmorhage - hemorrhage - herad - heard - heridity - heredity - heroe - hero - heros - heroes - hertiage - heritage - hertzs - hertz - hesistant - hesitant - heterogenous - heterogeneous - hieght - height - hierachical - hierarchical - hierachies - hierarchies - hierachy - hierarchy - hierarcical - hierarchical - hierarcy - hierarchy - hieroglph - hieroglyph - hieroglphs - hieroglyphs - higer - higher - higest - highest - higway - highway - hillarious - hilarious - himselv - himself - hinderance - hindrance - hinderence - hindrance - hindrence - hindrance - hipopotamus - hippopotamus - hismelf - himself - histocompatability - histocompatibility - historicians - historians - hitsingles - hit singles - holliday - holiday - homestate - home state - homogeneize - homogenize - homogeneized - homogenized - honory - honorary - horrifing - horrifying - hosited - hoisted - hospitible - hospitable - hounour - honour - housr - hours - howver - however - hsitorians - historians - hstory - history - hten - then - htere - there - htey - they - htikn - think - hting - thing - htink - think - htis - this - humer - humor - humerous - humorous - huminoid - humanoid - humoural - humoral - humurous - humorous - husban - husband - hvae - have - hvaing - having - hvea - have - hwihc - which - hwile - while - hwole - whole - hydogen - hydrogen - hydropile - hydrophile - hydropilic - hydrophilic - hydropobe - hydrophobe - hydropobic - hydrophobic - hygeine - hygiene - hypocracy - hypocrisy - hypocrasy - hypocrisy - hypocricy - hypocrisy - hypocrit - hypocrite - hypocrits - hypocrites - i - I - iconclastic - iconoclastic - idaeidae - idea - idaes - ideas - idealogies - ideologies - idealogy - ideology - identicial - identical - identifers - identifiers - ideosyncratic - idiosyncratic - idesa - ideas - idiosyncracy - idiosyncrasy - illegimacy - illegitimacy - illegitmate - illegitimate - illess - illness - illiegal - illegal - illution - illusion - ilness - illness - ilogical - illogical - imagenary - imaginary - imagin - imagine - imaginery - imaginary - imcomplete - incomplete - imediately - immediately - imense - immense - immediatley - immediately - immediatly - immediately - immidately - immediately - immidiately - immediately - immitate - imitate - immitated - imitated - immitating - imitating - immitator - imitator - immunosupressant - immunosuppressant - impecabbly - impeccably - impedence - impedance - implamenting - implementing - impliment - implement - implimented - implemented - imploys - employs - importamt - important - imprioned - imprisoned - imprisonned - imprisoned - improvision - improvisation - improvments - improvements - inablility - inability - inaccessable - inaccessible - inadiquate - inadequate - inadquate - inadequate - inadvertant - inadvertent - inadvertantly - inadvertently - inagurated - inaugurated - inaguration - inauguration - inappropiate - inappropriate - inaugures - inaugurates - inbalance - imbalance - inbalanced - imbalanced - inbetween - between - incarcirated - incarcerated - incidentially - incidentally - incidently - incidentally - inclreased - increased - includ - include - includng - including - incompatabilities - incompatibilities - incompatability - incompatibility - incompatable - incompatible - incompatablities - incompatibilities - incompatablity - incompatibility - incompatiblities - incompatibilities - incompatiblity - incompatibility - incompetance - incompetence - incompetant - incompetent - incomptable - incompatible - incomptetent - incompetent - inconsistant - inconsistent - incoroporated - incorporated - incorperation - incorporation - incorportaed - incorporated - incorprates - incorporates - incorruptable - incorruptible - incramentally - incrementally - increadible - incredible - incredable - incredible - inctroduce - introduce - inctroduced - introduced - incuding - including - incunabla - incunabula - indefinately - indefinitely - indefineable - undefinable - indefinitly - indefinitely - indentical - identical - indepedantly - independently - indepedence - independence - independance - independence - independant - independent - independantly - independently - independece - independence - independendet - independent - indespensable - indispensable - indespensible - indispensable - indictement - indictment - indigineous - indigenous - indipendence - independence - indipendent - independent - indipendently - independently - indispensible - indispensable - indisputible - indisputable - indisputibly - indisputably - indite - indict - individualy - individually - indpendent - independent - indpendently - independently - indulgue - indulge - indutrial - industrial - indviduals - individuals - inefficienty - inefficiently - inevatible - inevitable - inevitible - inevitable - inevititably - inevitably - infalability - infallibility - infallable - infallible - infectuous - infectious - infered - inferred - infilitrate - infiltrate - infilitrated - infiltrated - infilitration - infiltration - infinit - infinite - inflamation - inflammation - influencial - influential - influented - influenced - infomation - information - informtion - information - infrantryman - infantryman - infrigement - infringement - ingenius - ingenious - ingreediants - ingredients - inhabitans - inhabitants - inherantly - inherently - inheritence - inheritance - inital - initial - initally - initially - initation - initiation - initiaitive - initiative - inlcuding - including - inmigrant - immigrant - inmigrants - immigrants - innoculated - inoculated - inocence - innocence - inofficial - unofficial - inot - into - inpeach - impeach - inpolite - impolite - inprisonment - imprisonment - inproving - improving - insectiverous - insectivorous - insensative - insensitive - inseperable - inseparable - insistance - insistence - insitution - institution - insitutions - institutions - inspite - in spite - instade - instead - instatance - instance - institue - institute - instuction - instruction - instuments - instruments - instutionalized - institutionalized - instutions - intuitions - insurence - insurance - intelectual - intellectual - inteligence - intelligence - inteligent - intelligent - intenational - international - intented - intended - intepretation - interpretation - intepretator - interpretor - interational - international - interbread - interbreed - interchangable - interchangeable - interchangably - interchangeably - intercontinetal - intercontinental - intered - interred - interelated - interrelated - interferance - interference - interfereing - interfering - intergrated - integrated - intergration - integration - interm - interim - internation - international - interpet - interpret - interrim - interim - interrugum - interregnum - intertaining - entertaining - interupt - interrupt - intervines - intervenes - intevene - intervene - intial - initial - intially - initially - intrduced - introduced - intrest - interest - introdued - introduced - intruduced - introduced - intrument - instrument - intrumental - instrumental - intruments - instruments - intrusted - entrusted - intutive - intuitive - intutively - intuitively - inudstry - industry - inventer - inventor - invertibrates - invertebrates - investingate - investigate - involvment - involvement - irelevent - irrelevant - iresistable - irresistible - iresistably - irresistibly - iresistible - irresistible - iresistibly - irresistibly - iritable - irritable - iritated - irritated - ironicly - ironically - irregardless - regardless - irrelevent - irrelevant - irreplacable - irreplaceable - irresistable - irresistible - irresistably - irresistibly - isnt - isn't - issueing - issuing - itnroduced - introduced - iunior - junior - iwll - will - iwth - with - jaques - jacques - jeapardy - jeopardy - jewllery - jewellery - jouney - journey - journied - journeyed - journies - journeys - jstu - just - jsut - just - judical - judicial - judisuary - judiciary - juducial - judicial - juristiction - jurisdiction - juristictions - jurisdictions - kindergarden - kindergarten - klenex - kleenex - knifes - knives - knive - knife - knowlege - knowledge - knowlegeable - knowledgeable - knwo - know - knwos - knows - konw - know - konws - knows - kwno - know - labatory - laboratory - labratory - laboratory - laguage - language - laguages - languages - larg - large - largst - largest - larrry - larry - lastr - last - lattitude - latitude - launhed - launched - lavae - larvae - layed - laid - lazyness - laziness - leage - league - leanr - learn - leathal - lethal - lefted - left - legitamate - legitimate - legitmate - legitimate - leibnitz - leibniz - lenght - length - leran - learn - lerans - learns - leutenant - lieutenant - levetate - levitate - levetated - levitated - levetates - levitates - levetating - levitating - levle - level - liasion - liaison - liason - liaison - liasons - liaisons - libary - library - libell - libel - libguistic - linguistic - libguistics - linguistics - libitarianisn - libertarianism - lieing - lying - liek - like - liekd - liked - liesure - leisure - lieuenant - lieutenant - lieved - lived - liftime - lifetime - lightyear - light year - lightyears - light years - likelyhood - likelihood - linnaena - linnaean - lippizaner - lipizzaner - liquify - liquefy - liscense - license - lisence - license - lisense - license - listners - listeners - litature - literature - literaly - literally - literture - literature - littel - little - litterally - literally - liuke - like - livley - lively - lmits - limits - loev - love - lonelyness - loneliness - longitudonal - longitudinal - lonley - lonely - lonly - lonely - loosing - losing - lotharingen - lothringen - lsat - last - lukid - likud - lveo - love - lvoe - love - maching - machine - mackeral - mackerel - magasine - magazine - magincian - magician - magnificient - magnificent - magolia - magnolia - mailny - mainly - maintainance - maintenance - maintainence - maintenance - maintance - maintenance - maintenence - maintenance - maintinaing - maintaining - maintioned - mentioned - majoroty - majority - maked - marked - makse - makes - maltesian - Maltese - mamal - mammal - mamalian - mammalian - managable - manageable - managment - management - maneouvre - manoeuvre - maneouvred - manoeuvred - maneouvres - manoeuvres - maneouvring - manoeuvring - manisfestations - manifestations - manoeuverability - maneuverability - manouver - maneuver - manouverability - maneuverability - manouverable - maneuverable - manouvers - maneuvers - mantained - maintained - manuever - maneuver - manuevers - maneuvers - manufacturedd - manufactured - manufature - manufacture - manufatured - manufactured - manufaturing - manufacturing - manuver - maneuver - mariage - marriage - marjority - majority - markes - marks - marketting - marketing - marmelade - marmalade - marrage - marriage - marraige - marriage - marrtyred - martyred - marryied - married - massmedia - mass media - masterbation - masturbation - mataphysical - metaphysical - materalists - materialist - mathamatics - mathematics - mathematican - mathematician - mathematicas - mathematics - matheticians - mathematicians - mathmatically - mathematically - mathmatician - mathematician - mathmaticians - mathematicians - mccarthyst - mccarthyist - mchanics - mechanics - meaninng - meaning - mear - wear - mechandise - merchandise - medacine - medicine - medeival - medieval - medevial - medieval - mediciney - mediciny - medievel - medieval - mediterainnean - mediterranean - meerkrat - meerkat - melieux - milieux - membranaphone - membranophone - memeber - member - menally - mentally - meranda - Miranda - mercentile - mercantile - messanger - messenger - messenging - messaging - metalic - metallic - metalurgic - metallurgic - metalurgical - metallurgical - metalurgy - metallurgy - metamorphysis - metamorphosis - metaphoricial - metaphorical - meterologist - meteorologist - meterology - meteorology - methaphor - metaphor - methaphors - metaphors - micoscopy - microscopy - midwifes - midwives - mileau - milieu - milennia - millennia - milennium - millennium - mileu - milieu - miliary - military - milion - million - miliraty - military - millenia - millennia - millenial - millennial - millenialism - millennialism - millenium - millennium - millepede - millipede - millioniare - millionaire - millitary - military - millon - million - miltary - military - minature - miniature - minerial - mineral - miniscule - minuscule - ministery - ministry - minstries - ministries - minstry - ministry - minumum - minimum - mirrorred - mirrored - miscelaneous - miscellaneous - miscellanious - miscellaneous - miscellanous - miscellaneous - mischeivous - mischievous - mischevious - mischievous - mischievious - mischievous - misdameanor - misdemeanor - misdameanors - misdemeanors - misdemenor - misdemeanor - misdemenors - misdemeanors - misfourtunes - misfortunes - misile - missile - mispell - misspell - mispelled - misspelled - mispelling - misspelling - missen - mizzen - missle - missile - missonary - missionary - misterious - mysterious - mistery - mystery - misteryous - mysterious - mkae - make - mkaes - makes - mkaing - making - mkea - make - moderm - modem - modle - model - moent - moment - moeny - money - mohammedans - muslims - moil - soil - moleclues - molecules - momento - memento - monestaries - monasteries - monestary - monastery - monickers - monikers - monolite - monolithic - montains - mountains - montanous - mountainous - monts - months - montypic - monotypic - moreso - more so - morgage - mortgage - morroccan - moroccan - morrocco - morocco - morroco - morocco - mortage - mortgage - mosture - moisture - motiviated - motivated - mounth - month - movei - movie - movment - movement - mroe - more - mucuous - mucous - muder - murder - mudering - murdering - muhammadan - muslim - multicultralism - multiculturalism - multipled - multiplied - multiplers - multipliers - munbers - numbers - muncipalities - municipalities - muncipality - municipality - munnicipality - municipality - muscels - muscles - muscial - musical - muscician - musician - muscicians - musicians - mutiliated - mutilated - myraid - myriad - mysef - myself - mysogynist - misogynist - mysogyny - misogyny - mysterous - mysterious - naieve - naive - naturaly - naturally - naturely - naturally - naturual - natural - naturually - naturally - neccesarily - necessarily - neccesary - necessary - neccessarily - necessarily - neccessary - necessary - neccessities - necessities - necesarily - necessarily - necesary - necessary - necessiate - necessitate - neglible - negligible - negligable - negligible - negociate - negotiate - negociation - negotiation - negociations - negotiations - negotation - negotiation - neice - niece - neigborhood - neighborhood - neigbour - neighbour - neigbourhood - neighbourhood - neolitic - neolithic - nessasarily - necessarily - nessecary - necessary - nestin - nesting - neverthless - nevertheless - newletters - newsletters - nickle - nickel - nightfa;; - nightfall - nightime - nighttime - nineth - ninth - ninteenth - nineteenth - ninties - 1990s - ninty - ninety - nkow - know - nkwo - know - nmae - name - noncombatents - noncombatants - nonsence - nonsense - nontheless - nonetheless - noone - no one - norhern - northern - northen - northern - northereastern - northeastern - notabley - notably - noteable - notable - noteably - notably - noteriety - notoriety - noth - north - nothern - northern - noticable - noticeable - noticably - noticeably - noticeing - noticing - noticible - noticeable - notwhithstanding - notwithstanding - noveau - nouveau - nowdays - nowadays - nowe - now - nto - not - nucular - nuclear - nuculear - nuclear - nuisanse - nuisance - numberous - numerous - nusance - nuisance - nutritent - nutrient - nutritents - nutrients - nuturing - nurturing - obediance - obedience - obediant - obedient - obession - obsession - obssessed - obsessed - obstacal - obstacle - obstancles - obstacles - obstruced - obstructed - ocasion - occasion - ocasional - occasional - ocasionally - occasionally - ocasionaly - occasionally - ocasioned - occasioned - ocasions - occasions - ocassion - occasion - ocassional - occasional - ocassionally - occasionally - ocassionaly - occasionally - ocassioned - occasioned - ocassions - occasions - occaison - occasion - occassion - occasion - occassional - occasional - occassionally - occasionally - occassionaly - occasionally - occassioned - occasioned - occassions - occasions - occationally - occasionally - occour - occur - occurance - occurrence - occurances - occurrences - occured - occurred - occurence - occurrence - occurences - occurrences - occuring - occurring - occurr - occur - occurrance - occurrence - occurrances - occurrences - octohedra - octahedra - octohedral - octahedral - octohedron - octahedron - ocuntries - countries - ocuntry - country - ocurr - occur - ocurrance - occurrence - ocurred - occurred - ocurrence - occurrence - offcers - officers - offcially - officially - offereings - offerings - offical - official - offically - officially - officals - officials - officaly - officially - officialy - officially - offred - offered - oftenly - often - oging - going - omision - omission - omited - omitted - omiting - omitting - omlette - omelette - ommision - omission - ommited - omitted - ommiting - omitting - ommitted - omitted - ommitting - omitting - omniverous - omnivorous - omniverously - omnivorously - omre - more - onot - note - onxy - onyx - onyl - only - openess - openness - oponent - opponent - oportunity - opportunity - opose - oppose - oposite - opposite - oposition - opposition - oppenly - openly - oppinion - opinion - opponant - opponent - oppononent - opponent - oppositition - opposition - oppossed - opposed - opprotunity - opportunity - opression - oppression - opressive - oppressive - opthalmic - ophthalmic - opthalmologist - ophthalmologist - opthalmology - ophthalmology - opthamologist - ophthalmologist - optmizations - optimizations - optomism - optimism - orded - ordered - organim - organism - organistion - organisation - organiztion - organization - orgin - origin - orginal - original - orginally - originally - orginize - organise - oridinarily - ordinarily - origanaly - originally - originall - original - originaly - originally - originially - originally - originnally - originally - origional - original - orignally - originally - orignially - originally - otehr - other - oublisher - publisher - ouevre - oeuvre - oustanding - outstanding - overshaddowed - overshadowed - overthere - over there - overwelming - overwhelming - overwheliming - overwhelming - owrk - work - owudl - would - oxigen - oxygen - oximoron - oxymoron - p0enis - penis - paide - paid - paitience - patience - palce - place - paleolitic - paleolithic - paliamentarian - parliamentarian - pallete - palette - pamflet - pamphlet - pamplet - pamphlet - pantomine - pantomime - paralel - parallel - paralell - parallel - paralelly - parallelly - paralely - parallelly - parallely - parallelly - paranthesis - parenthesis - paraphenalia - paraphernalia - parellels - parallels - parituclar - particular - parliment - parliament - parrakeets - parakeets - parralel - parallel - parrallel - parallel - parrallell - parallel - parrallelly - parallelly - parrallely - parallelly - partialy - partially - particually - particularly - particualr - particular - particuarly - particularly - particularily - particularly - particulary - particularly - pary - party - pased - passed - pasengers - passengers - passerbys - passersby - pasttime - pastime - pastural - pastoral - paticular - particular - pattented - patented - pavillion - pavilion - payed - paid - pblisher - publisher - pbulisher - publisher - peacefuland - peaceful and - peageant - pageant - peculure - peculiar - pedestrain - pedestrian - peformed - performed - peice - piece - penatly - penalty - penerator - penetrator - penisula - peninsula - penisular - peninsular - penninsula - peninsula - penninsular - peninsular - pennisula - peninsula - pensinula - peninsula - peom - poem - peoms - poems - peopel - people - peotry - poetry - perade - parade - percepted - perceived - percieve - perceive - percieved - perceived - perenially - perennially - perfomance - performance - perfomers - performers - performence - performance - performes - performed - perhasp - perhaps - perheaps - perhaps - perhpas - perhaps - peripathetic - peripatetic - peristent - persistent - perjery - perjury - perjorative - pejorative - permanant - permanent - permenant - permanent - permenantly - permanently - permissable - permissible - perogative - prerogative - peronal - personal - perosnality - personality - perphas - perhaps - perpindicular - perpendicular - perseverence - perseverance - persistance - persistence - persistant - persistent - personel - personnel - personell - personnel - personnell - personnel - persuded - persuaded - persue - pursue - persued - pursued - persuing - pursuing - persuit - pursuit - persuits - pursuits - pertubation - perturbation - pertubations - perturbations - pessiary - pessary - petetion - petition - phenomenom - phenomenon - phenomenonal - phenomenal - phenomenonly - phenomenally - phenomonenon - phenomenon - phenomonon - phenomenon - phenonmena - phenomena - philisopher - philosopher - philisophical - philosophical - philisophy - philosophy - phillosophically - philosophically - philospher - philosopher - philosphies - philosophies - philosphy - philosophy - phongraph - phonograph - phylosophical - philosophical - physicaly - physically - piblisher - publisher - pich - pitch - pilgrimmage - pilgrimage - pilgrimmages - pilgrimages - pinapple - pineapple - pinnaple - pineapple - pinoneered - pioneered - plagarism - plagiarism - planation - plantation - planed - planned - plantiff - plaintiff - plateu - plateau - plausable - plausible - playright - playwright - playwrite - playwright - playwrites - playwrights - pleasent - pleasant - plebicite - plebiscite - plesant - pleasant - poenis - penis - poeoples - peoples - poety - poetry - poisin - poison - polical - political - polinator - pollinator - polinators - pollinators - politican - politician - politicans - politicians - poltical - political - polute - pollute - poluted - polluted - polutes - pollutes - poluting - polluting - polution - pollution - polyphonyic - polyphonic - polysaccaride - polysaccharide - polysaccharid - polysaccharide - pomegranite - pomegranate - pomotion - promotion - poportional - proportional - popoulation - population - popularaty - popularity - populare - popular - populer - popular - portait - portrait - portayed - portrayed - portraing - portraying - portuguease - portuguese - portugues - Portuguese - posess - possess - posessed - possessed - posesses - possesses - posessing - possessing - posession - possession - posessions - possessions - posion - poison - positon - position - possable - possible - possably - possibly - posseses - possesses - possesing - possessing - possesion - possession - possessess - possesses - possibile - possible - possibilty - possibility - possiblility - possibility - possiblilty - possibility - possiblities - possibilities - possiblity - possibility - possition - position - posthomous - posthumous - postion - position - postive - positive - potatos - potatoes - potrait - portrait - potrayed - portrayed - poulations - populations - poverful - powerful - poweful - powerful - powerfull - powerful - ppublisher - publisher - practial - practical - practially - practically - practicaly - practically - practicioner - practitioner - practicioners - practitioners - practicly - practically - practioner - practitioner - practioners - practitioners - prairy - prairie - prarie - prairie - praries - prairies - pratice - practice - preample - preamble - precedessor - predecessor - preceed - precede - preceeded - preceded - preceeding - preceding - preceeds - precedes - precentage - percentage - precice - precise - precisly - precisely - precurser - precursor - predecesors - predecessors - predicatble - predictable - predicitons - predictions - predomiantly - predominately - prefered - preferred - prefering - preferring - preferrably - preferably - pregancies - pregnancies - preiod - period - preliferation - proliferation - premeire - premiere - premeired - premiered - premillenial - premillennial - preminence - preeminence - premission - permission - preocupation - preoccupation - prepair - prepare - prepartion - preparation - prepatory - preparatory - preperation - preparation - preperations - preparations - preriod - period - presedential - presidential - presense - presence - presidenital - presidential - presidental - presidential - presitgious - prestigious - prespective - perspective - prestigeous - prestigious - prestigous - prestigious - presumabely - presumably - presumibly - presumably - pretection - protection - prevelant - prevalent - preverse - perverse - previvous - previous - pricipal - principal - priciple - principle - priestood - priesthood - primarly - primarily - primative - primitive - primatively - primitively - primatives - primitives - primordal - primordial - priveledges - privileges - privelege - privilege - priveleged - privileged - priveleges - privileges - privelige - privilege - priveliged - privileged - priveliges - privileges - privelleges - privileges - privilage - privilege - priviledge - privilege - priviledges - privileges - privledge - privilege - privte - private - probabilaty - probability - probablistic - probabilistic - probablly - probably - probalibity - probability - probaly - probably - probelm - problem - proccess - process - proccessing - processing - procede - proceed - proceded - proceeded - procedes - proceeds - procedger - procedure - proceding - proceeding - procedings - proceedings - proceedure - procedure - proces - process - processer - processor - proclaimation - proclamation - proclamed - proclaimed - proclaming - proclaiming - proclomation - proclamation - profesion - profession - profesor - professor - professer - professor - proffesed - professed - proffesion - profession - proffesional - professional - proffesor - professor - profilic - prolific - progessed - progressed - programable - programmable - progrom - program - progroms - programs - prohabition - prohibition - prologomena - prolegomena - prominance - prominence - prominant - prominent - prominantly - prominently - prominately - prominently - promiscous - promiscuous - promotted - promoted - pronomial - pronominal - pronouced - pronounced - pronounched - pronounced - pronounciation - pronunciation - proove - prove - prooved - proved - prophacy - prophecy - propietary - proprietary - propmted - prompted - propoganda - propaganda - propogate - propagate - propogates - propagates - propogation - propagation - propostion - proposition - propotions - proportions - propper - proper - propperly - properly - proprietory - proprietary - proseletyzing - proselytizing - protaganist - protagonist - protaganists - protagonists - protocal - protocol - protoganist - protagonist - protrayed - portrayed - protruberance - protuberance - protruberances - protuberances - prouncements - pronouncements - provacative - provocative - provded - provided - provicial - provincial - provinicial - provincial - provisiosn - provision - provisonal - provisional - proximty - proximity - pseudononymous - pseudonymous - pseudonyn - pseudonym - psuedo - pseudo - psycology - psychology - psyhic - psychic - pubilsher - publisher - pubisher - publisher - publiaher - publisher - publically - publicly - publicaly - publicly - publicher - publisher - publihser - publisher - publisehr - publisher - publiser - publisher - publisger - publisher - publisheed - published - publisherr - publisher - publishher - publisher - publishor - publisher - publishre - publisher - publissher - publisher - publlisher - publisher - publsiher - publisher - publusher - publisher - puchasing - purchasing - pulisher - publisher - pumkin - pumpkin - puplisher - publisher - puritannical - puritanical - purposedly - purposely - purpotedly - purportedly - pursuade - persuade - pursuaded - persuaded - pursuades - persuades - pususading - persuading - puting - putting - pwoer - power - pyscic - psychic - qtuie - quiet - quantaty - quantity - quantitiy - quantity - quarantaine - quarantine - questonable - questionable - quicklyu - quickly - quinessential - quintessential - quitted - quit - quizes - quizzes - qutie - quiet - rabinnical - rabbinical - racaus - raucous - radiactive - radioactive - radify - ratify - raelly - really - rarified - rarefied - reaccurring - recurring - reacing - reaching - reacll - recall - readmition - readmission - realitvely - relatively - realsitic - realistic - realtions - relations - realy - really - realyl - really - reasearch - research - rebiulding - rebuilding - rebllions - rebellions - rebounce - rebound - reccomend - recommend - reccomendations - recommendations - reccomended - recommended - reccomending - recommending - reccommend - recommend - reccommended - recommended - reccommending - recommending - reccuring - recurring - receeded - receded - receeding - receding - receivedfrom - received from - recepient - recipient - recepients - recipients - receving - receiving - rechargable - rechargeable - reched - reached - recide - reside - recided - resided - recident - resident - recidents - residents - reciding - residing - reciepents - recipients - reciept - receipt - recieve - receive - recieved - received - reciever - receiver - recievers - receivers - recieves - receives - recieving - receiving - recipiant - recipient - recipiants - recipients - recived - received - recivership - receivership - recogise - recognise - recogize - recognize - recomend - recommend - recomended - recommended - recomending - recommending - recomends - recommends - recommedations - recommendations - reconaissance - reconnaissance - reconcilation - reconciliation - reconized - recognized - reconnaisance - reconnaissance - reconnaissence - reconnaissance - recontructed - reconstructed - recordproducer - record producer - recquired - required - recrational - recreational - recrod - record - recuiting - recruiting - recuring - recurring - recurrance - recurrence - rediculous - ridiculous - reedeming - redeeming - reenforced - reinforced - refect - reflect - refedendum - referendum - referal - referral - referece - reference - refereces - references - refered - referred - referemce - reference - referemces - references - referencs - references - referenece - reference - refereneced - referenced - refereneces - references - referiang - referring - refering - referring - refernce - references - refernces - references - referrence - reference - referrences - references - referrs - refers - reffered - referred - refference - reference - reffering - referring - refrence - reference - refrences - references - refrers - refers - refridgeration - refrigeration - refridgerator - refrigerator - refromist - reformist - refusla - refusal - regardes - regards - regluar - regular - reguarly - regularly - regulaion - regulation - regulaotrs - regulators - regularily - regularly - rehersal - rehearsal - reicarnation - reincarnation - reigining - reigning - reknown - renown - reknowned - renowned - rela - real - relaly - really - relatiopnship - relationship - relativly - relatively - relected - reelected - releive - relieve - releived - relieved - releiver - reliever - releses - releases - relevence - relevance - relevent - relevant - reliablity - reliability - relient - reliant - religeous - religious - religous - religious - religously - religiously - relinqushment - relinquishment - relitavely - relatively - relized - realized - relpacement - replacement - remaing - remaining - remeber - remember - rememberable - memorable - rememberance - remembrance - remembrence - remembrance - remenant - remnant - remenicent - reminiscent - reminent - remnant - reminescent - reminiscent - reminscent - reminiscent - reminsicent - reminiscent - rendevous - rendezvous - rendezous - rendezvous - renedered - rende - renewl - renewal - rennovate - renovate - rennovated - renovated - rennovating - renovating - rennovation - renovation - rentors - renters - reoccurrence - recurrence - reorganision - reorganisation - repatition - repetition - repectively - respectively - repeition - repetition - repentence - repentance - repentent - repentant - repeteadly - repeatedly - repetion - repetition - repid - rapid - reponse - response - reponsible - responsible - reportadly - reportedly - represantative - representative - representive - representative - representives - representatives - reproducable - reproducible - reprtoire - repertoire - repsectively - respectively - reptition - repetition - requirment - requirement - requred - required - resaurant - restaurant - resembelance - resemblance - resembes - resembles - resemblence - resemblance - resevoir - reservoir - residental - residential - resignement - resignment - resistable - resistible - resistence - resistance - resistent - resistant - respectivly - respectively - responce - response - responibilities - responsibilities - responisble - responsible - responnsibilty - responsibility - responsability - responsibility - responsibile - responsible - responsibilites - responsibilities - responsiblities - responsibilities - responsiblity - responsibility - ressemblance - resemblance - ressemble - resemble - ressembled - resembled - ressemblence - resemblance - ressembling - resembling - resssurecting - resurrecting - ressurect - resurrect - ressurected - resurrected - ressurection - resurrection - ressurrection - resurrection - restarant - restaurant - restarants - restaurants - restaraunt - restaurant - restaraunteur - restaurateur - restaraunteurs - restaurateurs - restaraunts - restaurants - restauranteurs - restaurateurs - restauration - restoration - restauraunt - restaurant - resteraunt - restaurant - resteraunts - restaurants - resticted - restricted - restraunt - restraint - resturant - restaurant - resturants - restaurants - resturaunt - restaurant - resturaunts - restaurants - resurecting - resurrecting - retalitated - retaliated - retalitation - retaliation - retreive - retrieve - returnd - returned - revaluated - reevaluated - reveiw - review - reveral - reversal - reversable - reversible - revolutionar - revolutionary - rewitten - rewritten - rewriet - rewrite - rference - reference - rferences - references - rhymme - rhyme - rhythem - rhythm - rhythim - rhythm - rhytmic - rhythmic - rigourous - rigorous - rininging - ringing - rised - rose - rococco - rococo - rocord - record - roomate - roommate - rougly - roughly - rucuperate - recuperate - rudimentatry - rudimentary - rulle - rule - runing - running - runnung - running - russina - Russian - rwite - write - rythem - rhythm - rythim - rhythm - rythm - rhythm - rythmic - rhythmic - rythyms - rhythms - sacrafice - sacrifice - sacreligious - sacrilegious - sacrifical - sacrificial - saftey - safety - safty - safety - salery - salary - sanctionning - sanctioning - sandwhich - sandwich - santioned - sanctioned - sargant - sergeant - sargeant - sergeant - satelite - satellite - satelites - satellites - satisfactority - satisfactorily - satric - satiric - satrical - satirical - satrically - satirically - sattelite - satellite - sattelites - satellites - saught - sought - saveing - saving - saxaphone - saxophone - scaleable - scalable - scandanavia - Scandinavia - scaricity - scarcity - scavanged - scavenged - schedual - schedule - scholarhip - scholarship - scholarstic - scholastic - scientfic - scientific - scientifc - scientific - scientis - scientist - scince - science - scinece - science - scirpt - script - scoll - scroll - screenwrighter - screenwriter - scrutinity - scrutiny - scuptures - sculptures - seach - search - seached - searched - seaches - searches - secratary - secretary - secretery - secretary - sedereal - sidereal - seeked - sought - segementation - segmentation - seguoys - segues - seige - siege - seing - seeing - seinor - senior - seldomly - seldom - senarios - scenarios - senstive - sensitive - sensure - censure - seperate - separate - seperated - separated - seperately - separately - seperates - separates - seperating - separating - seperation - separation - seperatism - separatism - seperatist - separatist - sepina - subpoena - sergent - sergeant - settelement - settlement - settlment - settlement - severeal - several - severley - severely - severly - severely - sevice - service - shadasloo - shadaloo - shaddow - shadow - shadoloo - shadaloo - shamen - shaman - sheat - sheath - sheild - shield - sherif - sheriff - shineing - shining - shiped - shipped - shiping - shipping - shopkeeepers - shopkeepers - shorly - shortly - shortwhile - short while - shoudl - should - shoudln - shouldn't - shouldnt - shouldn't - shreak - shriek - shrinked - shrunk - sicne - since - sideral - sidereal - siezure - seizure - siezures - seizures - siginificant - significant - signficant - significant - signficiant - significant - signfies - signifies - signifantly - significantly - significently - significantly - signifigant - significant - signifigantly - significantly - signitories - signatories - signitory - signatory - similarily - similarly - similiar - similar - similiarity - similarity - similiarly - similarly - simmilar - similar - simpley - simply - simplier - simpler - simultanous - simultaneous - simultanously - simultaneously - sincerley - sincerely - singsog - singsong - sinse - since - skateing - skating - slaugterhouses - slaughterhouses - slighly - slightly - slowy - slowly - smae - same - smealting - smelting - smoe - some - sneeks - sneaks - snese - sneeze - socalism - socialism - socities - societies - soem - some - sofware - software - sohw - show - soilders - soldiers - solatary - solitary - soley - solely - soliders - soldiers - soliliquy - soliloquy - soluable - soluble - somene - someone - somtimes - sometimes - somwhere - somewhere - sophicated - sophisticated - sophmore - sophomore - sorceror - sorcerer - sorrounding - surrounding - sotry - story - sotyr - story - soudn - sound - soudns - sounds - sould - could - sountrack - soundtrack - sourth - south - sourthern - southern - souvenier - souvenir - souveniers - souvenirs - soveits - soviets - sovereignity - sovereignty - soverign - sovereign - soverignity - sovereignty - soverignty - sovereignty - spainish - Spanish - speach - speech - specfic - specific - speciallized - specialized - specifiying - specifying - speciman - specimen - spectauclar - spectacular - spectaulars - spectaculars - spectum - spectrum - speices - species - spendour - splendour - spermatozoan - spermatozoon - spoace - space - sponser - sponsor - sponsered - sponsored - spontanous - spontaneous - sponzored - sponsored - spoonfulls - spoonfuls - sppeches - speeches - spreaded - spread - sprech - speech - spred - spread - spriritual - spiritual - spritual - spiritual - sqaure - square - stablility - stability - stainlees - stainless - staion - station - standars - standards - stange - strange - startegic - strategic - startegies - strategies - startegy - strategy - stateman - statesman - statememts - statements - statment - statement - steriods - steroids - sterotypes - stereotypes - stilus - stylus - stingent - stringent - stiring - stirring - stirrs - stirs - stlye - style - stomache - stomach - stong - strong - stopry - story - storeis - stories - storise - stories - stornegst - strongest - stoyr - story - stpo - stop - stradegies - strategies - stradegy - strategy - strat - start - stratagically - strategically - streemlining - streamlining - stregth - strength - strenghen - strengthen - strenghened - strengthened - strenghening - strengthening - strenght - strength - strenghten - strengthen - strenghtened - strengthened - strenghtening - strengthening - strengtened - strengthened - strenous - strenuous - strictist - strictest - strikely - strikingly - strnad - strand - stroy - story - structual - structural - stubborness - stubbornness - stucture - structure - stuctured - structured - studdy - study - studing - studying - stuggling - struggling - sturcture - structure - subcatagories - subcategories - subcatagory - subcategory - subconsiously - subconsciously - subjudgation - subjugation - submachne - submachine - subpecies - subspecies - subsidary - subsidiary - subsiduary - subsidiary - subsquent - subsequent - subsquently - subsequently - substace - substance - substancial - substantial - substatial - substantial - substituded - substituted - substract - subtract - substracted - subtracted - substracting - subtracting - substraction - subtraction - substracts - subtracts - subtances - substances - subterranian - subterranean - suburburban - suburban - succceeded - succeeded - succcesses - successes - succedded - succeeded - succeded - succeeded - succeds - succeeds - succesful - successful - succesfully - successfully - succesfuly - successfully - succesion - succession - succesive - successive - successfull - successful - successully - successfully - succsess - success - succsessfull - successful - suceed - succeed - suceeded - succeeded - suceeding - succeeding - suceeds - succeeds - sucesful - successful - sucesfully - successfully - sucesfuly - successfully - sucesion - succession - sucess - success - sucesses - successes - sucessful - successful - sucessfull - successful - sucessfully - successfully - sucessfuly - successfully - sucession - succession - sucessive - successive - sucessor - successor - sucessot - successor - sucide - suicide - sucidial - suicidal - sufferage - suffrage - sufferred - suffered - sufferring - suffering - sufficent - sufficient - sufficently - sufficiently - sumary - summary - sunglases - sunglasses - suop - soup - superceeded - superseded - superintendant - superintendent - suphisticated - sophisticated - suplimented - supplemented - supose - suppose - suposed - supposed - suposedly - supposedly - suposes - supposes - suposing - supposing - supplamented - supplemented - suppliementing - supplementing - suppoed - supposed - supposingly - supposedly - suppy - supply - supress - suppress - supressed - suppressed - supresses - suppresses - supressing - suppressing - suprise - surprise - suprised - surprised - suprising - surprising - suprisingly - surprisingly - suprize - surprise - suprized - surprised - suprizing - surprising - suprizingly - surprisingly - surfce - surface - surley - surely - suround - surround - surounded - surrounded - surounding - surrounding - suroundings - surroundings - surounds - surrounds - surplanted - supplanted - surpress - suppress - surpressed - suppressed - surprize - surprise - surprized - surprised - surprizing - surprising - surprizingly - surprisingly - surrended - surrendered - surrepetitious - surreptitious - surrepetitiously - surreptitiously - surreptious - surreptitious - surreptiously - surreptitiously - surronded - surrounded - surrouded - surrounded - surrouding - surrounding - surrundering - surrendering - surveilence - surveillance - surveill - surveil - surveyer - surveyor - surviver - survivor - survivers - survivors - survivied - survived - suseptable - susceptible - suseptible - susceptible - suspention - suspension - swaer - swear - swaers - swears - swepth - swept - swiming - swimming - syas - says - symetrical - symmetrical - symetrically - symmetrically - symetry - symmetry - symettric - symmetric - symmetral - symmetric - symmetricaly - symmetrically - synagouge - synagogue - syncronization - synchronization - synonomous - synonymous - synonymns - synonyms - synphony - symphony - syphyllis - syphilis - sypmtoms - symptoms - syrap - syrup - sysmatically - systematically - sytem - system - sytle - style - tabacco - tobacco - tahn - than - taht - that - talekd - talked - targetted - targeted - targetting - targeting - tast - taste - tath - that - tattooes - tattoos - taxanomic - taxonomic - taxanomy - taxonomy - teached - taught - techician - technician - techicians - technicians - techiniques - techniques - technitian - technician - technnology - technology - technolgy - technology - teh - the - tehy - they - telelevision - television - televsion - television - telphony - telephony - temerature - temperature - tempalte - template - tempaltes - templates - temparate - temperate - temperarily - temporarily - temperment - temperament - tempertaure - temperature - temperture - temperature - temprary - temporary - tenacle - tentacle - tenacles - tentacles - tendacy - tendency - tendancies - tendencies - tendancy - tendency - tennisplayer - tennis player - tepmorarily - temporarily - terrestial - terrestrial - terriories - territories - terriory - territory - territorist - terrorist - territoy - territory - terroist - terrorist - testiclular - testicular - tghe - the - thast - that's - theather - theater - theese - these - theif - thief - theives - thieves - themselfs - themselves - themslves - themselves - ther - there - therafter - thereafter - therby - thereby - theri - their - theyre - they're - thgat - that - thge - the - thier - their - thign - thing - thigns - things - thigsn - things - thikn - think - thikning - thinking - thikns - thinks - thiunk - think - thn - then - thna - than - thne - then - thnig - thing - thnigs - things - thoughout - throughout - threatend - threatened - threatning - threatening - threee - three - threshhold - threshold - thrid - third - throrough - thorough - throughly - thoroughly - throught - throat - througout - throughout - thru - through - thsi - this - thsoe - those - thta - that - thyat - that - tiem - time - tihkn - think - tihs - this - timne - time - tiome - time - tje - the - tjhe - the - tjpanishad - upanishad - tkae - take - tkaes - takes - tkaing - taking - tlaking - talking - tobbaco - tobacco - todays - today's - todya - today - toghether - together - toke - took - tolerence - tolerance - tomatos - tomatoes - tommorow - tomorrow - tommorrow - tomorrow - tongiht - tonight - toriodal - toroidal - tormenters - tormentors - tornadoe - tornado - torpeados - torpedoes - torpedos - torpedoes - tothe - to the - toubles - troubles - tounge - tongue - tourch - torch - towords - towards - towrad - toward - tradionally - traditionally - traditionaly - traditionally - traditionnal - traditional - traditition - tradition - tradtionally - traditionally - trafficed - trafficked - trafficing - trafficking - trafic - traffic - trancendent - transcendent - trancending - transcending - tranform - transform - tranformed - transformed - transcendance - transcendence - transcendant - transcendent - transcendentational - transcendental - transcripting - transcribing - transending - transcending - transesxuals - transsexuals - transfered - transferred - transfering - transferring - transformaton - transformation - transistion - transition - translater - translator - translaters - translators - transmissable - transmissible - transporation - transportation - tremelo - tremolo - tremelos - tremolos - triguered - triggered - triology - trilogy - troling - trolling - troup - troupe - troups - troops - truely - truly - trustworthyness - trustworthiness - turnk - trunk - tust - trust - twelth - twelfth - twon - town - twpo - two - tyhat - that - tyhe - they - typcial - typical - typicaly - typically - tyranies - tyrannies - tyrany - tyranny - tyrranies - tyrannies - tyrrany - tyranny - ubiquitious - ubiquitous - ublisher - publisher - uise - use - ultimely - ultimately - unacompanied - unaccompanied - unahppy - unhappy - unanymous - unanimous - unathorised - unauthorised - unavailible - unavailable - unballance - unbalance - unbeknowst - unbeknownst - unbeleivable - unbelievable - uncertainity - uncertainty - unchallengable - unchallengeable - unchangable - unchangeable - uncompetive - uncompetitive - unconcious - unconscious - unconciousness - unconsciousness - unconfortability - discomfort - uncontitutional - unconstitutional - unconvential - unconventional - undecideable - undecidable - understoon - understood - undesireable - undesirable - undetecable - undetectable - undoubtely - undoubtedly - undreground - underground - uneccesary - unnecessary - unecessary - unnecessary - unequalities - inequalities - unforetunately - unfortunately - unforgetable - unforgettable - unforgiveable - unforgivable - unfortunatley - unfortunately - unfortunatly - unfortunately - unfourtunately - unfortunately - unihabited - uninhabited - unilateraly - unilaterally - unilatreal - unilateral - unilatreally - unilaterally - uninterruped - uninterrupted - uninterupted - uninterrupted - univeral - universal - univeristies - universities - univeristy - university - univerity - university - universtiy - university - univesities - universities - univesity - university - unkown - unknown - unlikey - unlikely - unmanouverable - unmaneuverable - unmistakeably - unmistakably - unneccesarily - unnecessarily - unneccesary - unnecessary - unneccessarily - unnecessarily - unneccessary - unnecessary - unnecesarily - unnecessarily - unnecesary - unnecessary - unoffical - unofficial - unoperational - nonoperational - unoticeable - unnoticeable - unplease - displease - unplesant - unpleasant - unprecendented - unprecedented - unprecidented - unprecedented - unrepentent - unrepentant - unrepetant - unrepentant - unrepetent - unrepentant - unsed - unused - unsubstanciated - unsubstantiated - unsuccesful - unsuccessful - unsuccesfully - unsuccessfully - unsuccessfull - unsuccessful - unsucesful - unsuccessful - unsucesfuly - unsuccessfully - unsucessful - unsuccessful - unsucessfull - unsuccessful - unsucessfully - unsuccessfully - unsuprised - unsurprised - unsuprising - unsurprising - unsuprisingly - unsurprisingly - unsuprized - unsurprised - unsuprizing - unsurprising - unsuprizingly - unsurprisingly - unsurprized - unsurprised - unsurprizing - unsurprising - unsurprizingly - unsurprisingly - untill - until - untranslateable - untranslatable - unuseable - unusable - unusuable - unusable - unviersity - university - unwarrented - unwarranted - unweildly - unwieldy - unwieldly - unwieldy - upcomming - upcoming - upgradded - upgraded - upto - up to - usally - usually - useage - usage - usefull - useful - usefuly - usefully - useing - using - usualy - usually - ususally - usually - vaccum - vacuum - vaccume - vacuum - vacinity - vicinity - vaguaries - vagaries - vaieties - varieties - vailidty - validity - valetta - valletta - valuble - valuable - valueable - valuable - varations - variations - varient - variant - variey - variety - varing - varying - varities - varieties - varity - variety - vasall - vassal - vasalls - vassals - vegatarian - vegetarian - vegitable - vegetable - vegitables - vegetables - vegtable - vegetable - vehicule - vehicle - vell - well - venemous - venomous - vengance - vengeance - vengence - vengeance - verfication - verification - verison - version - verisons - versions - vermillion - vermilion - versitilaty - versatility - versitlity - versatility - vetween - between - veyr - very - vigeur - vigor - vigilence - vigilance - vigourous - vigorous - villian - villain - villification - vilification - villify - vilify - villin - villain - vincinity - vicinity - violentce - violence - virtualy - virtually - virutal - virtual - virutally - virtually - visable - visible - visably - visibly - visting - visiting - vistors - visitors - vitories - victories - volcanoe - volcano - voleyball - volleyball - volontary - voluntary - volonteer - volunteer - volonteered - volunteered - volonteering - volunteering - volonteers - volunteers - volounteer - volunteer - volounteered - volunteered - volounteering - volunteering - volounteers - volunteers - volumne - volume - vreity - variety - vrey - very - vriety - variety - vulnerablility - vulnerability - vyer - very - vyre - very - waht - what - wanna - want to - warantee - warranty - wardobe - wardrobe - warrent - warrant - warrriors - warriors - wasnt - wasn't - wass - was - watn - want - wayword - wayward - weaponary - weaponry - weas - was - wehn - when - weild - wield - weilded - wielded - wendsay - Wednesday - wensday - Wednesday - wereabouts - whereabouts - whant - want - whants - wants - whcih - which - wheras - whereas - wherease - whereas - whereever - wherever - whic - which - whihc - which - whith - with - whlch - which - whn - when - wholey - wholly - wholy - holy - whta - what - whther - whether - wich - which - widesread - widespread - wief - wife - wierd - weird - wiew - view - wih - with - wiht - with - wille - will - willingless - willingness - wirting - writing - withdrawl - withdrawal - witheld - withheld - withh - with - withing - within - withold - withhold - witht - with - witn - with - wiull - will - wnat - want - wnated - wanted - wnats - wants - wohle - whole - wokr - work - wokring - working - wonderfull - wonderful - wont - won't - wordlwide - worldwide - workststion - workstation - worls - world - worstened - worsened - woudl - would - wresters - wrestlers - wriet - write - writen - written - wroet - wrote - wrok - work - wroking - working - wtih - with - wupport - support - xenophoby - xenophobia - yaching - yachting - yaer - year - yaerly - yearly - yaers - years - yatch - yacht - yearm - year - yeasr - years - yeild - yield - yeilding - yielding - yera - year - yeras - years - yersa - years - yotube - YouTube - youre - you're - youseff - yousef - youself - yourself - ytou - you - yuo - you - zeebra - zebra - - enabled - 1 - priority - 5 - wordStyle - 1 - - - diff --git a/indra/newview/app_settings/settings_autoreplace.xml b/indra/newview/app_settings/settings_autoreplace.xml new file mode 100644 index 0000000000..4669ba5822 --- /dev/null +++ b/indra/newview/app_settings/settings_autoreplace.xml @@ -0,0 +1,8369 @@ + + + Custom + + announce + 0 + author + You + data + + enabled + 1 + priority + 10 + wordStyle + 1 + + Abbreviations + + announce + 0 + author + Wulf / TankMaster + data + + afaic + As far as I am concerned + afaik + As far as I know + afk + (Away from Keyboard) + atm + at the moment + bbiab + (Be back in a bit) + bbl + (Be back later) + brb + (Be Right Back) + btw + By the way + fyi + For your information + fwiw + For what its worth + gtg + (Got to go) + idk + I don't know + iirc + If I recall correctly + imho + in my humble opinion + imo + in my opinion + irl + in real life + lol + (Laughing out Loud) + nm + Not much + np + No problem + nsfw + not safe for work + nvm + Nevermind + rofl + (Rolling on Floor Laughing) + tc + Take care + thx + Thanks + ttfn + Ta Ta for now + ttyl + Talk to you later + ty + Thank you + tyvm + Thank you very much + wb + Welcome back + yw + You're Welcome + yvw + You're very welcome + + enabled + 1 + priority + 4 + wordStyle + 1 + + Spelling Corrections + + announce + 0 + author + LordGregGreg / Wikipedia + data + + Amercia + America + Bernouilli + Bernoulli + Blitzkreig + Blitzkrieg + Bonnano + Bonanno + Brasillian + Brazilian + Britian + Britain + Brittish + British + Buddah + Buddha + Buddist + Buddhist + Cambrige + Cambridge + Capetown + Cape Town + Carmalite + Carmelite + Carnagie + Carnegie + Carnagie-Mellon + Carnegie-Mellon + Carnigie + Carnegie + Carnigie-Mellon + Carnegie-Mellon + Carribbean + Caribbean + Carribean + Caribbean + Carthagian + Carthaginian + Cataline + Catiline + Ceasar + Caesar + Celcius + Celsius + Champange + Champagne + Cincinatti + Cincinnati + Cincinnatti + Cincinnati + Conneticut + Connecticut + Dardenelles + Dardanelles + Dravadian + Dravidian + Enlish + English + Europian + European + Europians + Europeans + Eurpean + European + Eurpoean + European + Farenheit + Fahrenheit + Febuary + February + Feburary + February + Flemmish + Flemish + Formalhaut + Fomalhaut + Foundland + Newfoundland + Fransiscan + Franciscan + Fransiscans + Franciscans + Galations + Galatians + Gameboy + Game Boy + Ghandi + Gandhi + Godounov + Godunov + Gothenberg + Gothenburg + Gottleib + Gottlieb + Guaduloupe + Guadalupe + Guadulupe + Guadalupe + Guatamala + Guatemala + Guatamalan + Guatemalan + Guilia + Giulia + Guilio + Giulio + Guiness + Guinness + Guiseppe + Giuseppe + Habsbourg + Habsburg + Hallowean + Halloween + Heidelburg + Heidelberg + Ihaca + Ithaca + Israelies + Israelis + Janurary + January + Januray + January + Japanes + Japanese + Johanine + Johannine + Jospeh + Joseph + Juadaism + Judaism + Juadism + Judaism + Lybia + Libya + Malcom + Malcolm + Massachussets + Massachusetts + Massachussetts + Massachusetts + Mediteranean + Mediterranean + Michagan + Michigan + Misouri + Missouri + Missisipi + Mississippi + Missisippi + Mississippi + Monserrat + Montserrat + Montnana + Montana + Morisette + Morissette + Morrisette + Morissette + Mythraic + Mithraic + Naploeon + Napoleon + Napolean + Napoleon + Napoleonian + Napoleonic + Nazereth + Nazareth + Newyorker + New Yorker + Novermber + November + Nullabour + Nullarbor + Nuremburg + Nuremberg + Palistian + Palestinian + Palistinian + Palestinian + Palistinians + Palestinians + Papanicalou + Papanicolaou + Peloponnes + Peloponnesus + Pennyslvania + Pennsylvania + Pharoah + Pharaoh + Philipines + Philippines + Phillipine + Philippine + Phillipines + Philippines + Phillippines + Philippines + Phonecian + Phoenecian + Portugese + Portuguese + Postdam + Potsdam + Premonasterians + Premonstratensians + Pucini + Puccini + Puertorrican + Puerto Rican + Puertorricans + Puerto Ricans + Queenland + Queensland + Rockerfeller + Rockefeller + Russion + Russian + Sanhedrim + Sanhedrin + Saterday + Saturday + Saterdays + Saturdays + Sionist + Zionist + Sionists + Zionists + Sixtin + Sistine + Skagerak + Skagerrak + Tolkein + Tolkien + Tuscon + Tucson + Ukranian + Ukrainian + UnitesStates + UnitedStates + Yementite + Yemenite + abandonned + abandoned + aberation + aberration + abilties + abilities + abilty + ability + abondon + abandon + abondoned + abandoned + abondoning + abandoning + abondons + abandons + aborigene + aborigine + abortificant + abortifacient + abreviate + abbreviate + abreviated + abbreviated + abreviation + abbreviation + abritrary + arbitrary + absail + abseil + absailing + abseiling + absense + absence + absolutly + absolutely + absorbsion + absorption + absorbtion + absorption + abundacies + abundances + abundancies + abundances + abundunt + abundant + abutts + abuts + acadamy + academy + acadmic + academic + accademic + academic + accademy + academy + acccused + accused + accelleration + acceleration + accension + ascension + acceptence + acceptance + acceptible + acceptable + accessable + accessible + accidentaly + accidentally + accidently + accidentally + acclimitization + acclimatization + accomadate + accommodate + accomadated + accommodated + accomadates + accommodates + accomadating + accommodating + accomadation + accommodation + accomadations + accommodations + accomdate + accommodate + accomodate + accommodate + accomodated + accommodated + accomodates + accommodates + accomodating + accommodating + accomodation + accommodation + accomodations + accommodations + accompanyed + accompanied + accordeon + accordion + accordian + accordion + accoring + according + accoustic + acoustic + accquainted + acquainted + accrediation + accreditation + accredidation + accreditation + accross + across + accussed + accused + acedemic + academic + acheive + achieve + acheived + achieved + acheivement + achievement + acheivements + achievements + acheives + achieves + acheiving + achieving + acheivment + achievement + acheivments + achievements + achievment + achievement + achievments + achievements + achivement + achievement + achivements + achievements + acknowldeged + acknowledged + acknowledgeing + acknowledging + ackward + awkward + acommodate + accommodate + acomplish + accomplish + acomplished + accomplished + acomplishment + accomplishment + acomplishments + accomplishments + acording + according + acordingly + accordingly + acquaintence + acquaintance + acquaintences + acquaintances + acquiantence + acquaintance + acquiantences + acquaintances + acquited + acquitted + activites + activities + activly + actively + actualy + actually + acuracy + accuracy + acused + accused + acustom + accustom + acustommed + accustomed + adavanced + advanced + adbandon + abandon + additinally + additionally + additionaly + additionally + additonal + additional + additonally + additionally + addmission + admission + addopt + adopt + addopted + adopted + addoptive + adoptive + addres + address + addresable + addressable + addresed + addressed + addresing + addressing + addressess + addresses + addtion + addition + addtional + additional + adecuate + adequate + adequit + adequate + adhearing + adhering + adherance + adherence + admendment + amendment + admininistrative + administrative + adminstered + administered + adminstrate + administrate + adminstration + administration + adminstrative + administrative + adminstrator + administrator + admissability + admissibility + admissable + admissible + admited + admitted + admitedly + admittedly + adn + and + adolecent + adolescent + adquire + acquire + adquired + acquired + adquires + acquires + adquiring + acquiring + adres + address + adresable + addressable + adresing + addressing + adress + address + adressable + addressable + adressed + addressed + adressing + addressing + adventrous + adventurous + advertisment + advertisement + advertisments + advertisements + advesary + adversary + adviced + advised + aeriel + aerial + aeriels + aerials + afair + affair + afficianados + aficionados + afficionado + aficionado + afficionados + aficionados + affilate + affiliate + affilliate + affiliate + affort + afford + aforememtioned + aforementioned + againnst + against + agains + against + agaisnt + against + aganist + against + aggaravates + aggravates + aggreed + agreed + aggreement + agreement + aggregious + egregious + aggresive + aggressive + agian + again + agianst + against + agin + again + agina + again + aginst + against + agravate + aggravate + agre + agree + agred + agreed + agreeement + agreement + agreemnt + agreement + agregate + aggregate + agregates + aggregates + agreing + agreeing + agression + aggression + agressive + aggressive + agressively + aggressively + agressor + aggressor + agricuture + agriculture + agrieved + aggrieved + ahev + have + ahppen + happen + ahve + have + aicraft + aircraft + aiport + airport + airbourne + airborne + aircaft + aircraft + aircrafts + aircraft + airporta + airports + airrcraft + aircraft + aisian + asian + albiet + albeit + alchohol + alcohol + alchoholic + alcoholic + alchol + alcohol + alcholic + alcoholic + alcohal + alcohol + alcoholical + alcoholic + aledge + allege + aledged + alleged + aledges + alleges + alege + allege + aleged + alleged + alegience + allegiance + algebraical + algebraic + algorhitms + algorithms + algoritm + algorithm + algoritms + algorithms + alientating + alienating + alledge + allege + alledged + alleged + alledgedly + allegedly + alledges + alleges + allegedely + allegedly + allegedy + allegedly + allegely + allegedly + allegence + allegiance + allegience + allegiance + allign + align + alligned + aligned + alliviate + alleviate + allopone + allophone + allopones + allophones + allready + already + allthough + although + alltime + all-time + alltogether + altogether + almsot + almost + alochol + alcohol + alomst + almost + alot + a lot + alotted + allotted + alowed + allowed + alowing + allowing + alreayd + already + alse + else + alsot + also + alternitives + alternatives + altho + although + althought + although + altough + although + alusion + allusion + alwasy + always + alwyas + always + amalgomated + amalgamated + amatuer + amateur + amature + armature + amendmant + amendment + amerliorate + ameliorate + amke + make + amking + making + ammend + amend + ammended + amended + ammendment + amendment + ammendments + amendments + ammount + amount + ammused + amused + amoung + among + amoungst + amongst + amung + among + amunition + ammunition + analagous + analogous + analitic + analytic + analogeous + analogous + anarchim + anarchism + anarchistm + anarchism + anbd + and + ancestory + ancestry + ancilliary + ancillary + androgenous + androgynous + androgeny + androgyny + anihilation + annihilation + aniversary + anniversary + annoint + anoint + annointed + anointed + annointing + anointing + annoints + anoints + annouced + announced + annualy + annually + annuled + annulled + anohter + another + anomolies + anomalies + anomolous + anomalous + anomoly + anomaly + anonimity + anonymity + anounced + announced + anouncement + announcement + ansalisation + nasalisation + ansalization + nasalization + ansestors + ancestors + antartic + antarctic + anthromorphization + anthropomorphization + anthropolgist + anthropologist + anthropolgy + anthropology + anual + annual + anulled + annulled + anwsered + answered + anyhwere + anywhere + anyother + any other + anytying + anything + aparent + apparent + aparment + apartment + apenines + apennines + aplication + application + aplied + applied + apolegetics + apologetics + apon + apron + apparant + apparent + apparantly + apparently + appart + apart + appartment + apartment + appartments + apartments + appealling + appealing + appeareance + appearance + appearence + appearance + appearences + appearances + apperance + appearance + apperances + appearances + appereance + appearance + appereances + appearances + applicaiton + application + applicaitons + applications + appologies + apologies + appology + apology + apprearance + appearance + apprieciate + appreciate + approachs + approaches + appropiate + appropriate + appropraite + appropriate + appropropiate + appropriate + approproximate + approximate + approxamately + approximately + approxiately + approximately + approximitely + approximately + aprehensive + apprehensive + apropriate + appropriate + aproximate + approximate + aproximately + approximately + aquaduct + aqueduct + aquaintance + acquaintance + aquainted + acquainted + aquiantance + acquaintance + aquire + acquire + aquired + acquired + aquiring + acquiring + aquisition + acquisition + aquitted + acquitted + aranged + arranged + arangement + arrangement + arbitarily + arbitrarily + arbitary + arbitrary + archaelogists + archaeologists + archaelogy + archaeology + archaoelogy + archaeology + archaology + archaeology + archeaologist + archaeologist + archeaologists + archaeologists + archetect + architect + archetects + architects + archetectural + architectural + archetecturally + architecturally + archetecture + architecture + archiac + archaic + archictect + architect + archimedian + archimedean + architecht + architect + architechturally + architecturally + architechture + architecture + architechtures + architectures + architectual + architectural + archtype + archetype + archtypes + archetypes + aready + already + areodynamics + aerodynamics + argubly + arguably + arguement + argument + arguements + arguments + arised + arose + arival + arrival + armamant + armament + armistace + armistice + arogant + arrogant + arogent + arrogant + aroud + around + arrangment + arrangement + arrangments + arrangements + arround + around + artical + article + artice + article + articel + article + artifical + artificial + artifically + artificially + artillary + artillery + arund + around + asetic + ascetic + asfar + as far + asign + assign + aslo + also + asociated + associated + asorbed + absorbed + asphyxation + asphyxiation + assasin + assassin + assasinate + assassinate + assasinated + assassinated + assasinates + assassinates + assasination + assassination + assasinations + assassinations + assasined + assassinated + assasins + assassins + assassintation + assassination + assemple + assemble + assertation + assertion + asside + aside + assisnate + assassinate + assit + assist + assitant + assistant + assocation + association + assoicate + associate + assoicated + associated + assoicates + associates + assosication + assassination + asssassans + assassins + assualt + assault + assualted + assaulted + assymetric + asymmetric + assymetrical + asymmetrical + asteriod + asteroid + asthetic + aesthetic + asthetical + aesthetical + asthetically + aesthetically + asume + assume + aswell + as well + atain + attain + atempting + attempting + atheistical + atheistic + athenean + athenian + atheneans + athenians + athiesm + atheism + athiest + atheist + atorney + attorney + atribute + attribute + atributed + attributed + atributes + attributes + attaindre + attainder + attemp + attempt + attemped + attempted + attemt + attempt + attemted + attempted + attemting + attempting + attemts + attempts + attendence + attendance + attendent + attendant + attendents + attendants + attened + attended + attension + attention + attitide + attitude + attributred + attributed + attrocities + atrocities + audeince + audience + auromated + automated + austrailia + Australia + austrailian + Australian + auther + author + authobiographic + autobiographic + authobiography + autobiography + authorative + authoritative + authorites + authorities + authorithy + authority + authoritiers + authorities + authoritive + authoritative + authrorities + authorities + autochtonous + autochthonous + autoctonous + autochthonous + automaticly + automatically + automibile + automobile + automonomous + autonomous + autor + author + autority + authority + auxilary + auxiliary + auxillaries + auxiliaries + auxillary + auxiliary + auxilliaries + auxiliaries + auxilliary + auxiliary + availabe + available + availablity + availability + availaible + available + availble + available + availiable + available + availible + available + avalable + available + avalance + avalanche + avaliable + available + avation + aviation + avengence + a vengeance + averageed + averaged + avilable + available + awared + awarded + awya + away + baceause + because + backgorund + background + backrounds + backgrounds + bakc + back + banannas + bananas + bandwith + bandwidth + bankrupcy + bankruptcy + banruptcy + bankruptcy + baout + about + basicaly + basically + basicly + basically + bcak + back + beachead + beachhead + beacuse + because + beastiality + bestiality + beatiful + beautiful + beaurocracy + bureaucracy + beaurocratic + bureaucratic + beautyfull + beautiful + becamae + became + becames + becomes + becasue + because + beccause + because + becomeing + becoming + becomming + becoming + becouse + because + becuase + because + bedore + before + befoer + before + beggin + begin + begginer + beginner + begginers + beginners + beggining + beginning + begginings + beginnings + beggins + begins + begining + beginning + beginnig + beginning + behavour + behavior + beleagured + beleaguered + beleif + belief + beleive + believe + beleived + believed + beleives + believes + beleiving + believing + beligum + belgium + belive + believe + belived + believed + belives + believes + belligerant + belligerent + bellweather + bellwether + bemusemnt + bemusement + beneficary + beneficiary + beng + being + benificial + beneficial + benifit + benefit + benifits + benefits + bergamont + bergamot + beseige + besiege + beseiged + besieged + beseiging + besieging + betwen + between + beween + between + bewteen + between + bilateraly + bilaterally + billingualism + bilingualism + binominal + binomial + bizzare + bizarre + blaim + blame + blaimed + blamed + blessure + blessing + bodydbuilder + bodybuilder + bombardement + bombardment + bombarment + bombardment + bondary + boundary + borke + broke + boundry + boundary + bouyancy + buoyancy + bouyant + buoyant + boyant + buoyant + breakthough + breakthrough + breakthroughts + breakthroughs + breif + brief + breifly + briefly + brethen + brethren + bretheren + brethren + briliant + brilliant + brillant + brilliant + brimestone + brimstone + broacasted + broadcast + broadacasting + broadcasting + broady + broadly + buisness + business + buisnessman + businessman + buoancy + buoyancy + burried + buried + busineses + businesses + busness + business + bussiness + business + caculater + calculator + cacuses + caucuses + cahracters + characters + calaber + caliber + calculater + calculator + calculs + calculus + calenders + calendars + caligraphy + calligraphy + caluclate + calculate + caluclated + calculated + caluculate + calculate + caluculated + calculated + calulate + calculate + calulated + calculated + calulater + calculator + camoflage + camouflage + campain + campaign + campains + campaigns + candadate + candidate + candiate + candidate + candidiate + candidate + cannister + canister + cannisters + canisters + cannnot + cannot + cannonical + canonical + cannotation + connotation + cannotations + connotations + cant + can't + caost + coast + caperbility + capability + capible + capable + captial + capital + captued + captured + capturd + captured + carachter + character + caracterized + characterized + carcas + carcass + carefull + careful + careing + caring + carismatic + charismatic + carnege + carnage + carnige + carnage + carniverous + carnivorous + carreer + career + carrers + careers + cartdridge + cartridge + carthographer + cartographer + cartilege + cartilage + cartilidge + cartilage + cartrige + cartridge + casette + cassette + casion + caisson + cassawory + cassowary + cassowarry + cassowary + casulaties + casualties + casulaty + casualty + catagories + categories + catagorized + categorized + catagory + category + catapillar + caterpillar + catapillars + caterpillars + catapiller + caterpillar + catapillers + caterpillars + catepillar + caterpillar + catepillars + caterpillars + catergorize + categorize + catergorized + categorized + caterpilar + caterpillar + caterpilars + caterpillars + caterpiller + caterpillar + caterpillers + caterpillars + cathlic + catholic + catholocism + catholicism + catterpilar + caterpillar + catterpilars + caterpillars + catterpillar + caterpillar + catterpillars + caterpillars + cattleship + battleship + causalities + casualties + cellpading + cellpadding + cementary + cemetery + cemetarey + cemetery + cemetaries + cemeteries + cemetary + cemetery + cencus + census + censur + censor + cententenial + centennial + centruies + centuries + centruy + century + ceratin + certain + cerimonial + ceremonial + cerimonies + ceremonies + cerimonious + ceremonious + cerimony + ceremony + ceromony + ceremony + certainity + certainty + certian + certain + chalenging + challenging + challange + challenge + challanged + challenged + challege + challenge + changable + changeable + charachter + character + charachters + characters + charactersistic + characteristic + charactor + character + charactors + characters + charasmatic + charismatic + charaterized + characterized + chariman + chairman + charistics + characteristics + cheif + chief + cheifs + chiefs + chemcial + chemical + chemcially + chemically + chemestry + chemistry + chemicaly + chemically + childbird + childbirth + childen + children + choosen + chosen + chracter + character + chuch + church + churchs + churches + circulaton + circulation + circumsicion + circumcision + circut + circuit + ciricuit + circuit + ciriculum + curriculum + civillian + civilian + claer + clear + claerer + clearer + claerly + clearly + claimes + claims + clas + class + clasic + classic + clasical + classical + clasically + classically + cleareance + clearance + clera + clear + clincial + clinical + clinicaly + clinically + cmo + com + cmoputer + computer + co-incided + coincided + coctail + cocktail + coform + conform + cognizent + cognizant + coincedentally + coincidentally + colaborations + collaborations + colateral + collateral + colelctive + collective + collaberative + collaborative + collecton + collection + collegue + colleague + collegues + colleagues + collonade + colonnade + collonies + colonies + collony + colony + collosal + colossal + colonizators + colonizers + comander + commander + comando + commando + comandos + commandos + comany + company + comapany + company + comback + comeback + combanations + combinations + combinatins + combinations + combusion + combustion + comdemnation + condemnation + comemmorates + commemorates + comemoretion + commemoration + comision + commission + comisioned + commissioned + comisioner + commissioner + comisioning + commissioning + comisions + commissions + comission + commission + comissioned + commissioned + comissioner + commissioner + comissioning + commissioning + comissions + commissions + comited + committed + comiting + committing + comitted + committed + comittee + committee + comitting + committing + commandoes + commandos + commedic + comedic + commemerative + commemorative + commemmorate + commemorate + commemmorating + commemorating + commerical + commercial + commerically + commercially + commericial + commercial + commericially + commercially + commerorative + commemorative + comming + coming + comminication + communication + commision + commission + commisioned + commissioned + commisioner + commissioner + commisioning + commissioning + commisions + commissions + commited + committed + commitee + committee + commiting + committing + committe + committee + committment + commitment + committments + commitments + commmemorated + commemorated + commongly + commonly + commonweath + commonwealth + commuications + communications + commuinications + communications + communciation + communication + communiation + communication + communites + communities + compability + compatibility + comparision + comparison + comparisions + comparisons + comparitive + comparative + comparitively + comparatively + compatabilities + compatibilities + compatability + compatibility + compatable + compatible + compatablities + compatibilities + compatablity + compatibility + compatiable + compatible + compatiblities + compatibilities + compatiblity + compatibility + compeitions + competitions + compensantion + compensation + competance + competence + competant + competent + competative + competitive + competion + competition + competitiion + competition + competive + competitive + competiveness + competitiveness + comphrehensive + comprehensive + compitent + competent + completedthe + completed the + completelyl + completely + completetion + completion + complier + compiler + componant + component + comprable + comparable + comprimise + compromise + compulsary + compulsory + compulsery + compulsory + computarized + computerized + concensus + consensus + concider + consider + concidered + considered + concidering + considering + conciders + considers + concieted + conceited + concieved + conceived + concious + conscious + conciously + consciously + conciousness + consciousness + condamned + condemned + condemmed + condemned + condidtion + condition + condidtions + conditions + conditionsof + conditions of + conected + connected + conection + connection + conesencus + consensus + confidental + confidential + confidentally + confidentially + confids + confides + configureable + configurable + confortable + comfortable + congradulations + congratulations + congresional + congressional + conived + connived + conjecutre + conjecture + conjuction + conjunction + conotations + connotations + conquerd + conquered + conquerer + conqueror + conquerers + conquerors + conqured + conquered + conscent + consent + consciouness + consciousness + consdider + consider + consdidered + considered + consdiered + considered + consectutive + consecutive + consenquently + consequently + consentrate + concentrate + consentrated + concentrated + consentrates + concentrates + consept + concept + consequentually + consequently + consequeseces + consequences + consern + concern + conserned + concerned + conserning + concerning + conservitive + conservative + consiciousness + consciousness + consicousness + consciousness + considerd + considered + consideres + considered + consious + conscious + consistant + consistent + consistantly + consistently + consituencies + constituencies + consituency + constituency + consituted + constituted + consitution + constitution + consitutional + constitutional + consolodate + consolidate + consolodated + consolidated + consonent + consonant + consonents + consonants + consorcium + consortium + conspiracys + conspiracies + conspiriator + conspirator + constaints + constraints + constanly + constantly + constarnation + consternation + constatn + constant + constinually + continually + constituant + constituent + constituants + constituents + constituion + constitution + constituional + constitutional + consttruction + construction + constuction + construction + consulant + consultant + consumate + consummate + consumated + consummated + contaiminate + contaminate + containes + contains + contamporaries + contemporaries + contamporary + contemporary + contempoary + contemporary + contemporaneus + contemporaneous + contempory + contemporary + contendor + contender + contibute + contribute + contibuted + contributed + contibutes + contributes + contigent + contingent + contined + continued + continous + continuous + continously + continuously + continueing + continuing + contravercial + controversial + contraversy + controversy + contributer + contributor + contributers + contributors + contritutions + contributions + controled + controlled + controling + controlling + controll + control + controlls + controls + controvercial + controversial + controvercy + controversy + controveries + controversies + controversal + controversial + controversey + controversy + controvertial + controversial + controvery + controversy + contruction + construction + conveinent + convenient + convenant + covenant + convential + conventional + convertables + convertibles + convertion + conversion + conveyer + conveyor + conviced + convinced + convienient + convenient + coordiantion + coordination + coorperations + corporations + copmetitors + competitors + coputer + computer + copywrite + copyright + coridal + cordial + cornmitted + committed + corosion + corrosion + corparate + corporate + corperations + corporations + correcters + correctors + correponding + corresponding + correposding + corresponding + correspondant + correspondent + correspondants + correspondents + corridoors + corridors + corrispond + correspond + corrispondant + correspondent + corrispondants + correspondents + corrisponded + corresponded + corrisponding + corresponding + corrisponds + corresponds + costitution + constitution + coucil + council + counries + countries + countains + contains + countires + countries + coururier + courier + coverted + converted + cpoy + copy + creaeted + created + creedence + credence + critereon + criterion + criterias + criteria + criticists + critics + critising + criticising + critisising + criticising + critisism + criticism + critisisms + criticisms + critisize + criticise + critisized + criticised + critisizes + criticises + critisizing + criticising + critized + criticized + critizing + criticizing + crockodiles + crocodiles + crowm + crown + crtical + critical + crticised + criticised + crucifiction + crucifixion + crusies + cruises + crystalisation + crystallisation + culiminating + culminating + cumulatative + cumulative + curch + church + curcuit + circuit + currenly + currently + curriculem + curriculum + cxan + cyan + cyclinder + cylinder + dacquiri + daiquiri + dael + deal + dalmation + dalmatian + damenor + demeanor + dammage + damage + daugher + daughter + debateable + debatable + decendant + descendant + decendants + descendants + decendent + descendant + decendents + descendants + decideable + decidable + decidely + decidedly + decieved + deceived + decison + decision + decomissioned + decommissioned + decomposit + decompose + decomposited + decomposed + decompositing + decomposing + decomposits + decomposes + decress + decrees + decribe + describe + decribed + described + decribes + describes + decribing + describing + dectect + detect + defendent + defendant + defendents + defendants + deffensively + defensively + deffine + define + deffined + defined + definance + defiance + definate + definite + definately + definitely + definatly + definitely + definetly + definitely + definining + defining + definit + definite + definitly + definitely + definiton + definition + defintion + definition + degrate + degrade + delagates + delegates + delapidated + dilapidated + delerious + delirious + delevopment + development + deliberatly + deliberately + delusionally + delusively + demenor + demeanor + demographical + demographic + demolision + demolition + demorcracy + democracy + demostration + demonstration + denegrating + denigrating + densly + densely + deparment + department + deparmental + departmental + deparments + departments + dependance + dependence + dependancy + dependency + dependant + dependent + deram + dream + deriviated + derived + derivitive + derivative + derogitory + derogatory + descendands + descendants + descibed + described + descision + decision + descisions + decisions + descriibes + describes + descripters + descriptors + descripton + description + desctruction + destruction + descuss + discuss + desgined + designed + deside + decide + desigining + designing + desinations + destinations + desintegrated + disintegrated + desintegration + disintegration + desireable + desirable + desitned + destined + desktiop + desktop + desorder + disorder + desoriented + disoriented + desparate + desperate + despict + depict + despiration + desperation + dessicated + desiccated + dessigned + designed + destablized + destabilized + destory + destroy + detailled + detailed + detatched + detached + deteoriated + deteriorated + deteriate + deteriorate + deterioriating + deteriorating + determinining + determining + detremental + detrimental + devasted + devastated + develope + develop + developement + development + developped + developed + develpment + development + devels + delves + devestated + devastated + devestating + devastating + devide + divide + devided + divided + devistating + devastating + devolopement + development + diablical + diabolical + diamons + diamonds + diaster + disaster + dichtomy + dichotomy + diconnects + disconnects + dicover + discover + dicovered + discovered + dicovering + discovering + dicovers + discovers + dicovery + discovery + dicussed + discussed + didnt + didn't + diea + idea + dieing + dying + dieties + deities + diety + deity + diferent + different + diferrent + different + differentiatiations + differentiations + differnt + different + difficulity + difficulty + diffrent + different + dificulties + difficulties + dificulty + difficulty + dimenions + dimensions + dimention + dimension + dimentional + dimensional + dimentions + dimensions + dimesnional + dimensional + diminuitive + diminutive + dimunitive + diminutive + diosese + diocese + diphtong + diphthong + diphtongs + diphthongs + diplomancy + diplomacy + dipthong + diphthong + dipthongs + diphthongs + dirived + derived + disagreeed + disagreed + disapeared + disappeared + disapointing + disappointing + disappearred + disappeared + disaproval + disapproval + disasterous + disastrous + disatisfaction + dissatisfaction + disatisfied + dissatisfied + disatrous + disastrous + discontentment + discontent + discribe + describe + discribed + described + discribes + describes + discribing + describing + disctinction + distinction + disctinctive + distinctive + disemination + dissemination + disenchanged + disenchanted + disiplined + disciplined + disobediance + disobedience + disobediant + disobedient + disolved + dissolved + disover + discover + dispair + despair + disparingly + disparagingly + dispence + dispense + dispenced + dispensed + dispencing + dispensing + dispicable + despicable + dispite + despite + dispostion + disposition + disproportiate + disproportionate + disputandem + disputandum + disricts + districts + dissagreement + disagreement + dissapear + disappear + dissapearance + disappearance + dissapeared + disappeared + dissapearing + disappearing + dissapears + disappears + dissappear + disappear + dissappears + disappears + dissappointed + disappointed + dissarray + disarray + dissobediance + disobedience + dissobediant + disobedient + dissobedience + disobedience + dissobedient + disobedient + distiction + distinction + distingish + distinguish + distingished + distinguished + distingishes + distinguishes + distingishing + distinguishing + distingquished + distinguished + distrubution + distribution + distruction + destruction + distructive + destructive + ditributed + distributed + diversed + diverged + divice + device + divison + division + divisons + divisions + doccument + document + doccumented + documented + doccuments + documents + docrines + doctrines + doctines + doctrines + documenatry + documentary + doens + does + doesnt + doesn't + doign + doing + dominaton + domination + dominent + dominant + dominiant + dominant + donig + doing + dont + don't + dosen't + doesn't + doub + doubt + doulbe + double + dowloads + downloads + dramtic + dramatic + draughtman + draughtsman + dreasm + dreams + driectly + directly + drnik + drink + druming + drumming + drummless + drumless + dupicate + duplicate + durig + during + durring + during + duting + during + dyas + dryas + eahc + each + ealier + earlier + earlies + earliest + earnt + earned + ecclectic + eclectic + eceonomy + economy + ecidious + deciduous + eclispe + eclipse + ecomonic + economic + ect + etc + eearly + early + efel + evil + effeciency + efficiency + effecient + efficient + effeciently + efficiently + efficency + efficiency + efficent + efficient + efficently + efficiently + efford + effort + effords + efforts + effulence + effluence + eigth + eight + eiter + either + elction + election + electic + electric + electon + electron + electrial + electrical + electricly + electrically + electricty + electricity + elementay + elementary + eleminated + eliminated + eleminating + eliminating + eles + eels + eletricity + electricity + elicided + elicited + eligable + eligible + elimentary + elementary + ellected + elected + elphant + elephant + embarass + embarrass + embarassed + embarrassed + embarassing + embarrassing + embarassment + embarrassment + embargos + embargoes + embarras + embarrass + embarrased + embarrassed + embarrasing + embarrassing + embarrasment + embarrassment + embezelled + embezzled + emblamatic + emblematic + eminate + emanate + eminated + emanated + emision + emission + emited + emitted + emiting + emitting + emition + emission + emmediately + immediately + emmigrated + immigrated + emminently + eminently + emmisaries + emissaries + emmisarries + emissaries + emmisarry + emissary + emmisary + emissary + emmision + emission + emmisions + emissions + emmited + emitted + emmiting + emitting + emmitted + emitted + emmitting + emitting + emnity + enmity + emperical + empirical + emphaised + emphasised + emphsis + emphasis + emphysyma + emphysema + emprisoned + imprisoned + enameld + enameled + enchancement + enhancement + encouraing + encouraging + encryptiion + encryption + encylopedia + encyclopedia + endevors + endeavors + endevour + endeavour + endig + ending + endolithes + endoliths + enduce + induce + ened + need + enflamed + inflamed + enforceing + enforcing + engagment + engagement + engeneer + engineer + engeneering + engineering + engieneer + engineer + engieneers + engineers + enlargment + enlargement + enlargments + enlargements + enourmous + enormous + enourmously + enormously + ensconsed + ensconced + entaglements + entanglements + enteratinment + entertainment + enthusiatic + enthusiastic + entitity + entity + entitlied + entitled + entrepeneur + entrepreneur + entrepeneurs + entrepreneurs + enviorment + environment + enviormental + environmental + enviormentally + environmentally + enviorments + environments + enviornment + environment + enviornmental + environmental + enviornmentalist + environmentalist + enviornmentally + environmentally + enviornments + environments + enviroment + environment + enviromental + environmental + enviromentalist + environmentalist + enviromentally + environmentally + enviroments + environments + envolutionary + evolutionary + envrionments + environments + enxt + next + epidsodes + episodes + epsiode + episode + equialent + equivalent + equilibium + equilibrium + equilibrum + equilibrium + equiped + equipped + equippment + equipment + equitorial + equatorial + equivelant + equivalent + equivelent + equivalent + equivilant + equivalent + equivilent + equivalent + equivlalent + equivalent + erally + really + eratic + erratic + eratically + erratically + eraticly + erratically + errupted + erupted + esential + essential + esitmated + estimated + esle + else + especialy + especially + essencial + essential + essense + essence + essentail + essential + essentialy + essentially + essentual + essential + essesital + essential + estabishes + establishes + establising + establishing + ethnocentricm + ethnocentrism + ethose + those + evenhtually + eventually + eventally + eventually + eventhough + even though + eventially + eventually + eventualy + eventually + everthing + everything + everytime + every time + everyting + everything + eveyr + every + evidentally + evidently + exagerate + exaggerate + exagerated + exaggerated + exagerates + exaggerates + exagerating + exaggerating + exagerrate + exaggerate + exagerrated + exaggerated + exagerrates + exaggerates + exagerrating + exaggerating + examinated + examined + exampt + exempt + exapansion + expansion + excact + exact + excange + exchange + excecute + execute + excecuted + executed + excecutes + executes + excecuting + executing + excecution + execution + excedded + exceeded + excelent + excellent + excell + excel + excellance + excellence + excellant + excellent + excells + excels + excercise + exercise + exchanching + exchanging + excisted + existed + exculsivly + exclusively + execising + exercising + exection + execution + exectued + executed + exeedingly + exceedingly + exelent + excellent + exellent + excellent + exemple + example + exept + except + exeptional + exceptional + exerbate + exacerbate + exerbated + exacerbated + exerciese + exercises + exerpt + excerpt + exerpts + excerpts + exersize + exercise + exerternal + external + exhalted + exalted + exhibtion + exhibition + exibition + exhibition + exibitions + exhibitions + exicting + exciting + exinct + extinct + existance + existence + existant + existent + existince + existence + exliled + exiled + exludes + excludes + exmaple + example + exonorate + exonerate + exoskelaton + exoskeleton + expalin + explain + expatriot + expatriate + expeced + expected + expecially + especially + expeditonary + expeditionary + expeiments + experiments + expell + expel + expells + expels + experiance + experience + experianced + experienced + expiditions + expeditions + expierence + experience + explaination + explanation + explaning + explaining + explictly + explicitly + exploititive + exploitative + explotation + exploitation + expropiated + expropriated + expropiation + expropriation + exressed + expressed + extemely + extremely + extention + extension + extentions + extensions + extered + exerted + extermist + extremist + extint + extinct + extradiction + extradition + extraterrestial + extraterrestrial + extraterrestials + extraterrestrials + extravagent + extravagant + extrememly + extremely + extremeophile + extremophile + extremly + extremely + extrordinarily + extraordinarily + extrordinary + extraordinary + eyar + year + eyars + years + eyasr + years + faciliate + facilitate + faciliated + facilitated + faciliates + facilitates + facilites + facilities + facillitate + facilitate + facinated + fascinated + facist + fascist + familes + families + familliar + familiar + famoust + famous + fanatism + fanaticism + fatc + fact + faught + fought + favoutrable + favourable + feasable + feasible + fedreally + federally + feromone + pheromone + fertily + fertility + fianite + finite + fianlly + finally + ficticious + fictitious + fictious + fictitious + fidn + find + fiercly + fiercely + fightings + fighting + filiament + filament + fimilies + families + finacial + financial + finaly + finally + financialy + financially + firends + friends + firts + first + fisionable + fissionable + flamable + flammable + flawess + flawless + fleed + fled + florescent + fluorescent + flourescent + fluorescent + flourine + fluorine + fluorish + flourish + follwoing + following + folowing + following + fomed + formed + fomr + from + fonetic + phonetic + fontrier + fontier + foootball + football + forbad + forbade + forbiden + forbidden + foreward + foreword + forfiet + forfeit + forhead + forehead + foriegn + foreign + formallize + formalize + formallized + formalized + formaly + formally + formelly + formerly + formidible + formidable + formost + foremost + forsaw + foresaw + forseeable + foreseeable + fortelling + foretelling + forunner + forerunner + foucs + focus + foudn + found + fougth + fought + foundaries + foundries + foundary + foundry + fourties + forties + fourty + forty + fouth + fourth + foward + forward + freind + friend + freindly + friendly + frequentily + frequently + frome + from + fromed + formed + froniter + frontier + fucntion + function + fucntioning + functioning + fufill + fulfill + fufilled + fulfilled + fulfiled + fulfilled + fullfill + fulfill + fullfilled + fulfilled + fundametal + fundamental + fundametals + fundamentals + funguses + fungi + funtion + function + furuther + further + futher + further + futhermore + furthermore + galatic + galactic + gallaxies + galaxies + galvinized + galvanized + ganerate + generate + ganes + games + ganster + gangster + garantee + guarantee + garanteed + guaranteed + garantees + guarantees + garnison + garrison + gaurantee + guarantee + gauranteed + guaranteed + gaurantees + guarantees + gaurd + guard + gaurentee + guarantee + gaurenteed + guaranteed + gaurentees + guarantees + geneological + genealogical + geneologies + genealogies + geneology + genealogy + generaly + generally + generatting + generating + genialia + genitalia + geographicial + geographical + geometrician + geometer + geometricians + geometers + gerat + great + glight + flight + gnawwed + gnawed + godess + goddess + godesses + goddesses + gogin + going + goign + going + gonig + going + gouvener + governor + govement + government + govenment + government + govenrment + government + goverance + governance + goverment + government + govermental + governmental + governer + governor + governmnet + government + govorment + government + govormental + governmental + govornment + government + gracefull + graceful + graet + great + grafitti + graffiti + gramatically + grammatically + grammaticaly + grammatically + grammer + grammar + grat + great + gratuitious + gratuitous + greatful + grateful + greatfully + gratefully + greif + grief + gridles + griddles + gropu + group + grwo + grow + guage + gauge + guarentee + guarantee + guarenteed + guaranteed + guarentees + guarantees + guerilla + guerrilla + guerillas + guerrillas + guerrila + guerrilla + guerrilas + guerrillas + guidence + guidance + gunanine + guanine + gurantee + guarantee + guranteed + guaranteed + gurantees + guarantees + guttaral + guttural + gutteral + guttural + habaeus + habeas + habeus + habeas + haemorrage + haemorrhage + haev + have + halp + help + hapen + happen + hapened + happened + hapening + happening + happend + happened + happended + happened + happenned + happened + harased + harassed + harases + harasses + harasment + harassment + harasments + harassments + harassement + harassment + harras + harass + harrased + harassed + harrases + harasses + harrasing + harassing + harrasment + harassment + harrasments + harassments + harrassed + harassed + harrasses + harassed + harrassing + harassing + harrassment + harassment + harrassments + harassments + hasnt + hasn't + haviest + heaviest + headquarer + headquarter + headquater + headquarter + headquatered + headquartered + headquaters + headquarters + healthercare + healthcare + heared + heard + heathy + healthy + heigher + higher + heirarchy + hierarchy + heiroglyphics + hieroglyphics + helment + helmet + helpfull + helpful + helpped + helped + hemmorhage + hemorrhage + herad + heard + heridity + heredity + heroe + hero + heros + heroes + hertiage + heritage + hertzs + hertz + hesistant + hesitant + heterogenous + heterogeneous + hieght + height + hierachical + hierarchical + hierachies + hierarchies + hierachy + hierarchy + hierarcical + hierarchical + hierarcy + hierarchy + hieroglph + hieroglyph + hieroglphs + hieroglyphs + higer + higher + higest + highest + higway + highway + hillarious + hilarious + himselv + himself + hinderance + hindrance + hinderence + hindrance + hindrence + hindrance + hipopotamus + hippopotamus + hismelf + himself + histocompatability + histocompatibility + historicians + historians + hitsingles + hit singles + holliday + holiday + homestate + home state + homogeneize + homogenize + homogeneized + homogenized + honory + honorary + horrifing + horrifying + hosited + hoisted + hospitible + hospitable + hounour + honour + housr + hours + howver + however + hsitorians + historians + hstory + history + hten + then + htere + there + htey + they + htikn + think + hting + thing + htink + think + htis + this + humer + humor + humerous + humorous + huminoid + humanoid + humoural + humoral + humurous + humorous + husban + husband + hvae + have + hvaing + having + hvea + have + hwihc + which + hwile + while + hwole + whole + hydogen + hydrogen + hydropile + hydrophile + hydropilic + hydrophilic + hydropobe + hydrophobe + hydropobic + hydrophobic + hygeine + hygiene + hypocracy + hypocrisy + hypocrasy + hypocrisy + hypocricy + hypocrisy + hypocrit + hypocrite + hypocrits + hypocrites + i + I + iconclastic + iconoclastic + idaeidae + idea + idaes + ideas + idealogies + ideologies + idealogy + ideology + identicial + identical + identifers + identifiers + ideosyncratic + idiosyncratic + idesa + ideas + idiosyncracy + idiosyncrasy + illegimacy + illegitimacy + illegitmate + illegitimate + illess + illness + illiegal + illegal + illution + illusion + ilness + illness + ilogical + illogical + imagenary + imaginary + imagin + imagine + imaginery + imaginary + imcomplete + incomplete + imediately + immediately + imense + immense + immediatley + immediately + immediatly + immediately + immidately + immediately + immidiately + immediately + immitate + imitate + immitated + imitated + immitating + imitating + immitator + imitator + immunosupressant + immunosuppressant + impecabbly + impeccably + impedence + impedance + implamenting + implementing + impliment + implement + implimented + implemented + imploys + employs + importamt + important + imprioned + imprisoned + imprisonned + imprisoned + improvision + improvisation + improvments + improvements + inablility + inability + inaccessable + inaccessible + inadiquate + inadequate + inadquate + inadequate + inadvertant + inadvertent + inadvertantly + inadvertently + inagurated + inaugurated + inaguration + inauguration + inappropiate + inappropriate + inaugures + inaugurates + inbalance + imbalance + inbalanced + imbalanced + inbetween + between + incarcirated + incarcerated + incidentially + incidentally + incidently + incidentally + inclreased + increased + includ + include + includng + including + incompatabilities + incompatibilities + incompatability + incompatibility + incompatable + incompatible + incompatablities + incompatibilities + incompatablity + incompatibility + incompatiblities + incompatibilities + incompatiblity + incompatibility + incompetance + incompetence + incompetant + incompetent + incomptable + incompatible + incomptetent + incompetent + inconsistant + inconsistent + incoroporated + incorporated + incorperation + incorporation + incorportaed + incorporated + incorprates + incorporates + incorruptable + incorruptible + incramentally + incrementally + increadible + incredible + incredable + incredible + inctroduce + introduce + inctroduced + introduced + incuding + including + incunabla + incunabula + indefinately + indefinitely + indefineable + undefinable + indefinitly + indefinitely + indentical + identical + indepedantly + independently + indepedence + independence + independance + independence + independant + independent + independantly + independently + independece + independence + independendet + independent + indespensable + indispensable + indespensible + indispensable + indictement + indictment + indigineous + indigenous + indipendence + independence + indipendent + independent + indipendently + independently + indispensible + indispensable + indisputible + indisputable + indisputibly + indisputably + indite + indict + individualy + individually + indpendent + independent + indpendently + independently + indulgue + indulge + indutrial + industrial + indviduals + individuals + inefficienty + inefficiently + inevatible + inevitable + inevitible + inevitable + inevititably + inevitably + infalability + infallibility + infallable + infallible + infectuous + infectious + infered + inferred + infilitrate + infiltrate + infilitrated + infiltrated + infilitration + infiltration + infinit + infinite + inflamation + inflammation + influencial + influential + influented + influenced + infomation + information + informtion + information + infrantryman + infantryman + infrigement + infringement + ingenius + ingenious + ingreediants + ingredients + inhabitans + inhabitants + inherantly + inherently + inheritence + inheritance + inital + initial + initally + initially + initation + initiation + initiaitive + initiative + inlcuding + including + inmigrant + immigrant + inmigrants + immigrants + innoculated + inoculated + inocence + innocence + inofficial + unofficial + inot + into + inpeach + impeach + inpolite + impolite + inprisonment + imprisonment + inproving + improving + insectiverous + insectivorous + insensative + insensitive + inseperable + inseparable + insistance + insistence + insitution + institution + insitutions + institutions + inspite + in spite + instade + instead + instatance + instance + institue + institute + instuction + instruction + instuments + instruments + instutionalized + institutionalized + instutions + intuitions + insurence + insurance + intelectual + intellectual + inteligence + intelligence + inteligent + intelligent + intenational + international + intented + intended + intepretation + interpretation + intepretator + interpretor + interational + international + interbread + interbreed + interchangable + interchangeable + interchangably + interchangeably + intercontinetal + intercontinental + intered + interred + interelated + interrelated + interferance + interference + interfereing + interfering + intergrated + integrated + intergration + integration + interm + interim + internation + international + interpet + interpret + interrim + interim + interrugum + interregnum + intertaining + entertaining + interupt + interrupt + intervines + intervenes + intevene + intervene + intial + initial + intially + initially + intrduced + introduced + intrest + interest + introdued + introduced + intruduced + introduced + intrument + instrument + intrumental + instrumental + intruments + instruments + intrusted + entrusted + intutive + intuitive + intutively + intuitively + inudstry + industry + inventer + inventor + invertibrates + invertebrates + investingate + investigate + involvment + involvement + irelevent + irrelevant + iresistable + irresistible + iresistably + irresistibly + iresistible + irresistible + iresistibly + irresistibly + iritable + irritable + iritated + irritated + ironicly + ironically + irregardless + regardless + irrelevent + irrelevant + irreplacable + irreplaceable + irresistable + irresistible + irresistably + irresistibly + isnt + isn't + issueing + issuing + itnroduced + introduced + iunior + junior + iwll + will + iwth + with + jaques + jacques + jeapardy + jeopardy + jewllery + jewellery + jouney + journey + journied + journeyed + journies + journeys + jstu + just + jsut + just + judical + judicial + judisuary + judiciary + juducial + judicial + juristiction + jurisdiction + juristictions + jurisdictions + kindergarden + kindergarten + klenex + kleenex + knifes + knives + knive + knife + knowlege + knowledge + knowlegeable + knowledgeable + knwo + know + knwos + knows + konw + know + konws + knows + kwno + know + labatory + laboratory + labratory + laboratory + laguage + language + laguages + languages + larg + large + largst + largest + larrry + larry + lastr + last + lattitude + latitude + launhed + launched + lavae + larvae + layed + laid + lazyness + laziness + leage + league + leanr + learn + leathal + lethal + lefted + left + legitamate + legitimate + legitmate + legitimate + leibnitz + leibniz + lenght + length + leran + learn + lerans + learns + leutenant + lieutenant + levetate + levitate + levetated + levitated + levetates + levitates + levetating + levitating + levle + level + liasion + liaison + liason + liaison + liasons + liaisons + libary + library + libell + libel + libguistic + linguistic + libguistics + linguistics + libitarianisn + libertarianism + lieing + lying + liek + like + liekd + liked + liesure + leisure + lieuenant + lieutenant + lieved + lived + liftime + lifetime + lightyear + light year + lightyears + light years + likelyhood + likelihood + linnaena + linnaean + lippizaner + lipizzaner + liquify + liquefy + liscense + license + lisence + license + lisense + license + listners + listeners + litature + literature + literaly + literally + literture + literature + littel + little + litterally + literally + liuke + like + livley + lively + lmits + limits + loev + love + lonelyness + loneliness + longitudonal + longitudinal + lonley + lonely + lonly + lonely + loosing + losing + lotharingen + lothringen + lsat + last + lukid + likud + lveo + love + lvoe + love + maching + machine + mackeral + mackerel + magasine + magazine + magincian + magician + magnificient + magnificent + magolia + magnolia + mailny + mainly + maintainance + maintenance + maintainence + maintenance + maintance + maintenance + maintenence + maintenance + maintinaing + maintaining + maintioned + mentioned + majoroty + majority + maked + marked + makse + makes + maltesian + Maltese + mamal + mammal + mamalian + mammalian + managable + manageable + managment + management + maneouvre + manoeuvre + maneouvred + manoeuvred + maneouvres + manoeuvres + maneouvring + manoeuvring + manisfestations + manifestations + manoeuverability + maneuverability + manouver + maneuver + manouverability + maneuverability + manouverable + maneuverable + manouvers + maneuvers + mantained + maintained + manuever + maneuver + manuevers + maneuvers + manufacturedd + manufactured + manufature + manufacture + manufatured + manufactured + manufaturing + manufacturing + manuver + maneuver + mariage + marriage + marjority + majority + markes + marks + marketting + marketing + marmelade + marmalade + marrage + marriage + marraige + marriage + marrtyred + martyred + marryied + married + massmedia + mass media + masterbation + masturbation + mataphysical + metaphysical + materalists + materialist + mathamatics + mathematics + mathematican + mathematician + mathematicas + mathematics + matheticians + mathematicians + mathmatically + mathematically + mathmatician + mathematician + mathmaticians + mathematicians + mccarthyst + mccarthyist + mchanics + mechanics + meaninng + meaning + mear + wear + mechandise + merchandise + medacine + medicine + medeival + medieval + medevial + medieval + mediciney + mediciny + medievel + medieval + mediterainnean + mediterranean + meerkrat + meerkat + melieux + milieux + membranaphone + membranophone + memeber + member + menally + mentally + meranda + Miranda + mercentile + mercantile + messanger + messenger + messenging + messaging + metalic + metallic + metalurgic + metallurgic + metalurgical + metallurgical + metalurgy + metallurgy + metamorphysis + metamorphosis + metaphoricial + metaphorical + meterologist + meteorologist + meterology + meteorology + methaphor + metaphor + methaphors + metaphors + micoscopy + microscopy + midwifes + midwives + mileau + milieu + milennia + millennia + milennium + millennium + mileu + milieu + miliary + military + milion + million + miliraty + military + millenia + millennia + millenial + millennial + millenialism + millennialism + millenium + millennium + millepede + millipede + millioniare + millionaire + millitary + military + millon + million + miltary + military + minature + miniature + minerial + mineral + miniscule + minuscule + ministery + ministry + minstries + ministries + minstry + ministry + minumum + minimum + mirrorred + mirrored + miscelaneous + miscellaneous + miscellanious + miscellaneous + miscellanous + miscellaneous + mischeivous + mischievous + mischevious + mischievous + mischievious + mischievous + misdameanor + misdemeanor + misdameanors + misdemeanors + misdemenor + misdemeanor + misdemenors + misdemeanors + misfourtunes + misfortunes + misile + missile + mispell + misspell + mispelled + misspelled + mispelling + misspelling + missen + mizzen + missle + missile + missonary + missionary + misterious + mysterious + mistery + mystery + misteryous + mysterious + mkae + make + mkaes + makes + mkaing + making + mkea + make + moderm + modem + modle + model + moent + moment + moeny + money + mohammedans + muslims + moil + soil + moleclues + molecules + momento + memento + monestaries + monasteries + monestary + monastery + monickers + monikers + monolite + monolithic + montains + mountains + montanous + mountainous + monts + months + montypic + monotypic + moreso + more so + morgage + mortgage + morroccan + moroccan + morrocco + morocco + morroco + morocco + mortage + mortgage + mosture + moisture + motiviated + motivated + mounth + month + movei + movie + movment + movement + mroe + more + mucuous + mucous + muder + murder + mudering + murdering + muhammadan + muslim + multicultralism + multiculturalism + multipled + multiplied + multiplers + multipliers + munbers + numbers + muncipalities + municipalities + muncipality + municipality + munnicipality + municipality + muscels + muscles + muscial + musical + muscician + musician + muscicians + musicians + mutiliated + mutilated + myraid + myriad + mysef + myself + mysogynist + misogynist + mysogyny + misogyny + mysterous + mysterious + naieve + naive + naturaly + naturally + naturely + naturally + naturual + natural + naturually + naturally + neccesarily + necessarily + neccesary + necessary + neccessarily + necessarily + neccessary + necessary + neccessities + necessities + necesarily + necessarily + necesary + necessary + necessiate + necessitate + neglible + negligible + negligable + negligible + negociate + negotiate + negociation + negotiation + negociations + negotiations + negotation + negotiation + neice + niece + neigborhood + neighborhood + neigbour + neighbour + neigbourhood + neighbourhood + neolitic + neolithic + nessasarily + necessarily + nessecary + necessary + nestin + nesting + neverthless + nevertheless + newletters + newsletters + nickle + nickel + nightfa;; + nightfall + nightime + nighttime + nineth + ninth + ninteenth + nineteenth + ninties + 1990s + ninty + ninety + nkow + know + nkwo + know + nmae + name + noncombatents + noncombatants + nonsence + nonsense + nontheless + nonetheless + noone + no one + norhern + northern + northen + northern + northereastern + northeastern + notabley + notably + noteable + notable + noteably + notably + noteriety + notoriety + noth + north + nothern + northern + noticable + noticeable + noticably + noticeably + noticeing + noticing + noticible + noticeable + notwhithstanding + notwithstanding + noveau + nouveau + nowdays + nowadays + nowe + now + nto + not + nucular + nuclear + nuculear + nuclear + nuisanse + nuisance + numberous + numerous + nusance + nuisance + nutritent + nutrient + nutritents + nutrients + nuturing + nurturing + obediance + obedience + obediant + obedient + obession + obsession + obssessed + obsessed + obstacal + obstacle + obstancles + obstacles + obstruced + obstructed + ocasion + occasion + ocasional + occasional + ocasionally + occasionally + ocasionaly + occasionally + ocasioned + occasioned + ocasions + occasions + ocassion + occasion + ocassional + occasional + ocassionally + occasionally + ocassionaly + occasionally + ocassioned + occasioned + ocassions + occasions + occaison + occasion + occassion + occasion + occassional + occasional + occassionally + occasionally + occassionaly + occasionally + occassioned + occasioned + occassions + occasions + occationally + occasionally + occour + occur + occurance + occurrence + occurances + occurrences + occured + occurred + occurence + occurrence + occurences + occurrences + occuring + occurring + occurr + occur + occurrance + occurrence + occurrances + occurrences + octohedra + octahedra + octohedral + octahedral + octohedron + octahedron + ocuntries + countries + ocuntry + country + ocurr + occur + ocurrance + occurrence + ocurred + occurred + ocurrence + occurrence + offcers + officers + offcially + officially + offereings + offerings + offical + official + offically + officially + officals + officials + officaly + officially + officialy + officially + offred + offered + oftenly + often + oging + going + omision + omission + omited + omitted + omiting + omitting + omlette + omelette + ommision + omission + ommited + omitted + ommiting + omitting + ommitted + omitted + ommitting + omitting + omniverous + omnivorous + omniverously + omnivorously + omre + more + onot + note + onxy + onyx + onyl + only + openess + openness + oponent + opponent + oportunity + opportunity + opose + oppose + oposite + opposite + oposition + opposition + oppenly + openly + oppinion + opinion + opponant + opponent + oppononent + opponent + oppositition + opposition + oppossed + opposed + opprotunity + opportunity + opression + oppression + opressive + oppressive + opthalmic + ophthalmic + opthalmologist + ophthalmologist + opthalmology + ophthalmology + opthamologist + ophthalmologist + optmizations + optimizations + optomism + optimism + orded + ordered + organim + organism + organistion + organisation + organiztion + organization + orgin + origin + orginal + original + orginally + originally + orginize + organise + oridinarily + ordinarily + origanaly + originally + originall + original + originaly + originally + originially + originally + originnally + originally + origional + original + orignally + originally + orignially + originally + otehr + other + oublisher + publisher + ouevre + oeuvre + oustanding + outstanding + overshaddowed + overshadowed + overthere + over there + overwelming + overwhelming + overwheliming + overwhelming + owrk + work + owudl + would + oxigen + oxygen + oximoron + oxymoron + p0enis + penis + paide + paid + paitience + patience + palce + place + paleolitic + paleolithic + paliamentarian + parliamentarian + pallete + palette + pamflet + pamphlet + pamplet + pamphlet + pantomine + pantomime + paralel + parallel + paralell + parallel + paralelly + parallelly + paralely + parallelly + parallely + parallelly + paranthesis + parenthesis + paraphenalia + paraphernalia + parellels + parallels + parituclar + particular + parliment + parliament + parrakeets + parakeets + parralel + parallel + parrallel + parallel + parrallell + parallel + parrallelly + parallelly + parrallely + parallelly + partialy + partially + particually + particularly + particualr + particular + particuarly + particularly + particularily + particularly + particulary + particularly + pary + party + pased + passed + pasengers + passengers + passerbys + passersby + pasttime + pastime + pastural + pastoral + paticular + particular + pattented + patented + pavillion + pavilion + payed + paid + pblisher + publisher + pbulisher + publisher + peacefuland + peaceful and + peageant + pageant + peculure + peculiar + pedestrain + pedestrian + peformed + performed + peice + piece + penatly + penalty + penerator + penetrator + penisula + peninsula + penisular + peninsular + penninsula + peninsula + penninsular + peninsular + pennisula + peninsula + pensinula + peninsula + peom + poem + peoms + poems + peopel + people + peotry + poetry + perade + parade + percepted + perceived + percieve + perceive + percieved + perceived + perenially + perennially + perfomance + performance + perfomers + performers + performence + performance + performes + performed + perhasp + perhaps + perheaps + perhaps + perhpas + perhaps + peripathetic + peripatetic + peristent + persistent + perjery + perjury + perjorative + pejorative + permanant + permanent + permenant + permanent + permenantly + permanently + permissable + permissible + perogative + prerogative + peronal + personal + perosnality + personality + perphas + perhaps + perpindicular + perpendicular + perseverence + perseverance + persistance + persistence + persistant + persistent + personel + personnel + personell + personnel + personnell + personnel + persuded + persuaded + persue + pursue + persued + pursued + persuing + pursuing + persuit + pursuit + persuits + pursuits + pertubation + perturbation + pertubations + perturbations + pessiary + pessary + petetion + petition + phenomenom + phenomenon + phenomenonal + phenomenal + phenomenonly + phenomenally + phenomonenon + phenomenon + phenomonon + phenomenon + phenonmena + phenomena + philisopher + philosopher + philisophical + philosophical + philisophy + philosophy + phillosophically + philosophically + philospher + philosopher + philosphies + philosophies + philosphy + philosophy + phongraph + phonograph + phylosophical + philosophical + physicaly + physically + piblisher + publisher + pich + pitch + pilgrimmage + pilgrimage + pilgrimmages + pilgrimages + pinapple + pineapple + pinnaple + pineapple + pinoneered + pioneered + plagarism + plagiarism + planation + plantation + planed + planned + plantiff + plaintiff + plateu + plateau + plausable + plausible + playright + playwright + playwrite + playwright + playwrites + playwrights + pleasent + pleasant + plebicite + plebiscite + plesant + pleasant + poenis + penis + poeoples + peoples + poety + poetry + poisin + poison + polical + political + polinator + pollinator + polinators + pollinators + politican + politician + politicans + politicians + poltical + political + polute + pollute + poluted + polluted + polutes + pollutes + poluting + polluting + polution + pollution + polyphonyic + polyphonic + polysaccaride + polysaccharide + polysaccharid + polysaccharide + pomegranite + pomegranate + pomotion + promotion + poportional + proportional + popoulation + population + popularaty + popularity + populare + popular + populer + popular + portait + portrait + portayed + portrayed + portraing + portraying + portuguease + portuguese + portugues + Portuguese + posess + possess + posessed + possessed + posesses + possesses + posessing + possessing + posession + possession + posessions + possessions + posion + poison + positon + position + possable + possible + possably + possibly + posseses + possesses + possesing + possessing + possesion + possession + possessess + possesses + possibile + possible + possibilty + possibility + possiblility + possibility + possiblilty + possibility + possiblities + possibilities + possiblity + possibility + possition + position + posthomous + posthumous + postion + position + postive + positive + potatos + potatoes + potrait + portrait + potrayed + portrayed + poulations + populations + poverful + powerful + poweful + powerful + powerfull + powerful + ppublisher + publisher + practial + practical + practially + practically + practicaly + practically + practicioner + practitioner + practicioners + practitioners + practicly + practically + practioner + practitioner + practioners + practitioners + prairy + prairie + prarie + prairie + praries + prairies + pratice + practice + preample + preamble + precedessor + predecessor + preceed + precede + preceeded + preceded + preceeding + preceding + preceeds + precedes + precentage + percentage + precice + precise + precisly + precisely + precurser + precursor + predecesors + predecessors + predicatble + predictable + predicitons + predictions + predomiantly + predominately + prefered + preferred + prefering + preferring + preferrably + preferably + pregancies + pregnancies + preiod + period + preliferation + proliferation + premeire + premiere + premeired + premiered + premillenial + premillennial + preminence + preeminence + premission + permission + preocupation + preoccupation + prepair + prepare + prepartion + preparation + prepatory + preparatory + preperation + preparation + preperations + preparations + preriod + period + presedential + presidential + presense + presence + presidenital + presidential + presidental + presidential + presitgious + prestigious + prespective + perspective + prestigeous + prestigious + prestigous + prestigious + presumabely + presumably + presumibly + presumably + pretection + protection + prevelant + prevalent + preverse + perverse + previvous + previous + pricipal + principal + priciple + principle + priestood + priesthood + primarly + primarily + primative + primitive + primatively + primitively + primatives + primitives + primordal + primordial + priveledges + privileges + privelege + privilege + priveleged + privileged + priveleges + privileges + privelige + privilege + priveliged + privileged + priveliges + privileges + privelleges + privileges + privilage + privilege + priviledge + privilege + priviledges + privileges + privledge + privilege + privte + private + probabilaty + probability + probablistic + probabilistic + probablly + probably + probalibity + probability + probaly + probably + probelm + problem + proccess + process + proccessing + processing + procede + proceed + proceded + proceeded + procedes + proceeds + procedger + procedure + proceding + proceeding + procedings + proceedings + proceedure + procedure + proces + process + processer + processor + proclaimation + proclamation + proclamed + proclaimed + proclaming + proclaiming + proclomation + proclamation + profesion + profession + profesor + professor + professer + professor + proffesed + professed + proffesion + profession + proffesional + professional + proffesor + professor + profilic + prolific + progessed + progressed + programable + programmable + progrom + program + progroms + programs + prohabition + prohibition + prologomena + prolegomena + prominance + prominence + prominant + prominent + prominantly + prominently + prominately + prominently + promiscous + promiscuous + promotted + promoted + pronomial + pronominal + pronouced + pronounced + pronounched + pronounced + pronounciation + pronunciation + proove + prove + prooved + proved + prophacy + prophecy + propietary + proprietary + propmted + prompted + propoganda + propaganda + propogate + propagate + propogates + propagates + propogation + propagation + propostion + proposition + propotions + proportions + propper + proper + propperly + properly + proprietory + proprietary + proseletyzing + proselytizing + protaganist + protagonist + protaganists + protagonists + protocal + protocol + protoganist + protagonist + protrayed + portrayed + protruberance + protuberance + protruberances + protuberances + prouncements + pronouncements + provacative + provocative + provded + provided + provicial + provincial + provinicial + provincial + provisiosn + provision + provisonal + provisional + proximty + proximity + pseudononymous + pseudonymous + pseudonyn + pseudonym + psuedo + pseudo + psycology + psychology + psyhic + psychic + pubilsher + publisher + pubisher + publisher + publiaher + publisher + publically + publicly + publicaly + publicly + publicher + publisher + publihser + publisher + publisehr + publisher + publiser + publisher + publisger + publisher + publisheed + published + publisherr + publisher + publishher + publisher + publishor + publisher + publishre + publisher + publissher + publisher + publlisher + publisher + publsiher + publisher + publusher + publisher + puchasing + purchasing + pulisher + publisher + pumkin + pumpkin + puplisher + publisher + puritannical + puritanical + purposedly + purposely + purpotedly + purportedly + pursuade + persuade + pursuaded + persuaded + pursuades + persuades + pususading + persuading + puting + putting + pwoer + power + pyscic + psychic + qtuie + quiet + quantaty + quantity + quantitiy + quantity + quarantaine + quarantine + questonable + questionable + quicklyu + quickly + quinessential + quintessential + quitted + quit + quizes + quizzes + qutie + quiet + rabinnical + rabbinical + racaus + raucous + radiactive + radioactive + radify + ratify + raelly + really + rarified + rarefied + reaccurring + recurring + reacing + reaching + reacll + recall + readmition + readmission + realitvely + relatively + realsitic + realistic + realtions + relations + realy + really + realyl + really + reasearch + research + rebiulding + rebuilding + rebllions + rebellions + rebounce + rebound + reccomend + recommend + reccomendations + recommendations + reccomended + recommended + reccomending + recommending + reccommend + recommend + reccommended + recommended + reccommending + recommending + reccuring + recurring + receeded + receded + receeding + receding + receivedfrom + received from + recepient + recipient + recepients + recipients + receving + receiving + rechargable + rechargeable + reched + reached + recide + reside + recided + resided + recident + resident + recidents + residents + reciding + residing + reciepents + recipients + reciept + receipt + recieve + receive + recieved + received + reciever + receiver + recievers + receivers + recieves + receives + recieving + receiving + recipiant + recipient + recipiants + recipients + recived + received + recivership + receivership + recogise + recognise + recogize + recognize + recomend + recommend + recomended + recommended + recomending + recommending + recomends + recommends + recommedations + recommendations + reconaissance + reconnaissance + reconcilation + reconciliation + reconized + recognized + reconnaisance + reconnaissance + reconnaissence + reconnaissance + recontructed + reconstructed + recordproducer + record producer + recquired + required + recrational + recreational + recrod + record + recuiting + recruiting + recuring + recurring + recurrance + recurrence + rediculous + ridiculous + reedeming + redeeming + reenforced + reinforced + refect + reflect + refedendum + referendum + referal + referral + referece + reference + refereces + references + refered + referred + referemce + reference + referemces + references + referencs + references + referenece + reference + refereneced + referenced + refereneces + references + referiang + referring + refering + referring + refernce + references + refernces + references + referrence + reference + referrences + references + referrs + refers + reffered + referred + refference + reference + reffering + referring + refrence + reference + refrences + references + refrers + refers + refridgeration + refrigeration + refridgerator + refrigerator + refromist + reformist + refusla + refusal + regardes + regards + regluar + regular + reguarly + regularly + regulaion + regulation + regulaotrs + regulators + regularily + regularly + rehersal + rehearsal + reicarnation + reincarnation + reigining + reigning + reknown + renown + reknowned + renowned + rela + real + relaly + really + relatiopnship + relationship + relativly + relatively + relected + reelected + releive + relieve + releived + relieved + releiver + reliever + releses + releases + relevence + relevance + relevent + relevant + reliablity + reliability + relient + reliant + religeous + religious + religous + religious + religously + religiously + relinqushment + relinquishment + relitavely + relatively + relized + realized + relpacement + replacement + remaing + remaining + remeber + remember + rememberable + memorable + rememberance + remembrance + remembrence + remembrance + remenant + remnant + remenicent + reminiscent + reminent + remnant + reminescent + reminiscent + reminscent + reminiscent + reminsicent + reminiscent + rendevous + rendezvous + rendezous + rendezvous + renedered + rende + renewl + renewal + rennovate + renovate + rennovated + renovated + rennovating + renovating + rennovation + renovation + rentors + renters + reoccurrence + recurrence + reorganision + reorganisation + repatition + repetition + repectively + respectively + repeition + repetition + repentence + repentance + repentent + repentant + repeteadly + repeatedly + repetion + repetition + repid + rapid + reponse + response + reponsible + responsible + reportadly + reportedly + represantative + representative + representive + representative + representives + representatives + reproducable + reproducible + reprtoire + repertoire + repsectively + respectively + reptition + repetition + requirment + requirement + requred + required + resaurant + restaurant + resembelance + resemblance + resembes + resembles + resemblence + resemblance + resevoir + reservoir + residental + residential + resignement + resignment + resistable + resistible + resistence + resistance + resistent + resistant + respectivly + respectively + responce + response + responibilities + responsibilities + responisble + responsible + responnsibilty + responsibility + responsability + responsibility + responsibile + responsible + responsibilites + responsibilities + responsiblities + responsibilities + responsiblity + responsibility + ressemblance + resemblance + ressemble + resemble + ressembled + resembled + ressemblence + resemblance + ressembling + resembling + resssurecting + resurrecting + ressurect + resurrect + ressurected + resurrected + ressurection + resurrection + ressurrection + resurrection + restarant + restaurant + restarants + restaurants + restaraunt + restaurant + restaraunteur + restaurateur + restaraunteurs + restaurateurs + restaraunts + restaurants + restauranteurs + restaurateurs + restauration + restoration + restauraunt + restaurant + resteraunt + restaurant + resteraunts + restaurants + resticted + restricted + restraunt + restraint + resturant + restaurant + resturants + restaurants + resturaunt + restaurant + resturaunts + restaurants + resurecting + resurrecting + retalitated + retaliated + retalitation + retaliation + retreive + retrieve + returnd + returned + revaluated + reevaluated + reveiw + review + reveral + reversal + reversable + reversible + revolutionar + revolutionary + rewitten + rewritten + rewriet + rewrite + rference + reference + rferences + references + rhymme + rhyme + rhythem + rhythm + rhythim + rhythm + rhytmic + rhythmic + rigourous + rigorous + rininging + ringing + rised + rose + rococco + rococo + rocord + record + roomate + roommate + rougly + roughly + rucuperate + recuperate + rudimentatry + rudimentary + rulle + rule + runing + running + runnung + running + russina + Russian + rwite + write + rythem + rhythm + rythim + rhythm + rythm + rhythm + rythmic + rhythmic + rythyms + rhythms + sacrafice + sacrifice + sacreligious + sacrilegious + sacrifical + sacrificial + saftey + safety + safty + safety + salery + salary + sanctionning + sanctioning + sandwhich + sandwich + santioned + sanctioned + sargant + sergeant + sargeant + sergeant + satelite + satellite + satelites + satellites + satisfactority + satisfactorily + satric + satiric + satrical + satirical + satrically + satirically + sattelite + satellite + sattelites + satellites + saught + sought + saveing + saving + saxaphone + saxophone + scaleable + scalable + scandanavia + Scandinavia + scaricity + scarcity + scavanged + scavenged + schedual + schedule + scholarhip + scholarship + scholarstic + scholastic + scientfic + scientific + scientifc + scientific + scientis + scientist + scince + science + scinece + science + scirpt + script + scoll + scroll + screenwrighter + screenwriter + scrutinity + scrutiny + scuptures + sculptures + seach + search + seached + searched + seaches + searches + secratary + secretary + secretery + secretary + sedereal + sidereal + seeked + sought + segementation + segmentation + seguoys + segues + seige + siege + seing + seeing + seinor + senior + seldomly + seldom + senarios + scenarios + senstive + sensitive + sensure + censure + seperate + separate + seperated + separated + seperately + separately + seperates + separates + seperating + separating + seperation + separation + seperatism + separatism + seperatist + separatist + sepina + subpoena + sergent + sergeant + settelement + settlement + settlment + settlement + severeal + several + severley + severely + severly + severely + sevice + service + shadasloo + shadaloo + shaddow + shadow + shadoloo + shadaloo + shamen + shaman + sheat + sheath + sheild + shield + sherif + sheriff + shineing + shining + shiped + shipped + shiping + shipping + shopkeeepers + shopkeepers + shorly + shortly + shortwhile + short while + shoudl + should + shoudln + shouldn't + shouldnt + shouldn't + shreak + shriek + shrinked + shrunk + sicne + since + sideral + sidereal + siezure + seizure + siezures + seizures + siginificant + significant + signficant + significant + signficiant + significant + signfies + signifies + signifantly + significantly + significently + significantly + signifigant + significant + signifigantly + significantly + signitories + signatories + signitory + signatory + similarily + similarly + similiar + similar + similiarity + similarity + similiarly + similarly + simmilar + similar + simpley + simply + simplier + simpler + simultanous + simultaneous + simultanously + simultaneously + sincerley + sincerely + singsog + singsong + sinse + since + skateing + skating + slaugterhouses + slaughterhouses + slighly + slightly + slowy + slowly + smae + same + smealting + smelting + smoe + some + sneeks + sneaks + snese + sneeze + socalism + socialism + socities + societies + soem + some + sofware + software + sohw + show + soilders + soldiers + solatary + solitary + soley + solely + soliders + soldiers + soliliquy + soliloquy + soluable + soluble + somene + someone + somtimes + sometimes + somwhere + somewhere + sophicated + sophisticated + sophmore + sophomore + sorceror + sorcerer + sorrounding + surrounding + sotry + story + sotyr + story + soudn + sound + soudns + sounds + sould + could + sountrack + soundtrack + sourth + south + sourthern + southern + souvenier + souvenir + souveniers + souvenirs + soveits + soviets + sovereignity + sovereignty + soverign + sovereign + soverignity + sovereignty + soverignty + sovereignty + spainish + Spanish + speach + speech + specfic + specific + speciallized + specialized + specifiying + specifying + speciman + specimen + spectauclar + spectacular + spectaulars + spectaculars + spectum + spectrum + speices + species + spendour + splendour + spermatozoan + spermatozoon + spoace + space + sponser + sponsor + sponsered + sponsored + spontanous + spontaneous + sponzored + sponsored + spoonfulls + spoonfuls + sppeches + speeches + spreaded + spread + sprech + speech + spred + spread + spriritual + spiritual + spritual + spiritual + sqaure + square + stablility + stability + stainlees + stainless + staion + station + standars + standards + stange + strange + startegic + strategic + startegies + strategies + startegy + strategy + stateman + statesman + statememts + statements + statment + statement + steriods + steroids + sterotypes + stereotypes + stilus + stylus + stingent + stringent + stiring + stirring + stirrs + stirs + stlye + style + stomache + stomach + stong + strong + stopry + story + storeis + stories + storise + stories + stornegst + strongest + stoyr + story + stpo + stop + stradegies + strategies + stradegy + strategy + strat + start + stratagically + strategically + streemlining + streamlining + stregth + strength + strenghen + strengthen + strenghened + strengthened + strenghening + strengthening + strenght + strength + strenghten + strengthen + strenghtened + strengthened + strenghtening + strengthening + strengtened + strengthened + strenous + strenuous + strictist + strictest + strikely + strikingly + strnad + strand + stroy + story + structual + structural + stubborness + stubbornness + stucture + structure + stuctured + structured + studdy + study + studing + studying + stuggling + struggling + sturcture + structure + subcatagories + subcategories + subcatagory + subcategory + subconsiously + subconsciously + subjudgation + subjugation + submachne + submachine + subpecies + subspecies + subsidary + subsidiary + subsiduary + subsidiary + subsquent + subsequent + subsquently + subsequently + substace + substance + substancial + substantial + substatial + substantial + substituded + substituted + substract + subtract + substracted + subtracted + substracting + subtracting + substraction + subtraction + substracts + subtracts + subtances + substances + subterranian + subterranean + suburburban + suburban + succceeded + succeeded + succcesses + successes + succedded + succeeded + succeded + succeeded + succeds + succeeds + succesful + successful + succesfully + successfully + succesfuly + successfully + succesion + succession + succesive + successive + successfull + successful + successully + successfully + succsess + success + succsessfull + successful + suceed + succeed + suceeded + succeeded + suceeding + succeeding + suceeds + succeeds + sucesful + successful + sucesfully + successfully + sucesfuly + successfully + sucesion + succession + sucess + success + sucesses + successes + sucessful + successful + sucessfull + successful + sucessfully + successfully + sucessfuly + successfully + sucession + succession + sucessive + successive + sucessor + successor + sucessot + successor + sucide + suicide + sucidial + suicidal + sufferage + suffrage + sufferred + suffered + sufferring + suffering + sufficent + sufficient + sufficently + sufficiently + sumary + summary + sunglases + sunglasses + suop + soup + superceeded + superseded + superintendant + superintendent + suphisticated + sophisticated + suplimented + supplemented + supose + suppose + suposed + supposed + suposedly + supposedly + suposes + supposes + suposing + supposing + supplamented + supplemented + suppliementing + supplementing + suppoed + supposed + supposingly + supposedly + suppy + supply + supress + suppress + supressed + suppressed + supresses + suppresses + supressing + suppressing + suprise + surprise + suprised + surprised + suprising + surprising + suprisingly + surprisingly + suprize + surprise + suprized + surprised + suprizing + surprising + suprizingly + surprisingly + surfce + surface + surley + surely + suround + surround + surounded + surrounded + surounding + surrounding + suroundings + surroundings + surounds + surrounds + surplanted + supplanted + surpress + suppress + surpressed + suppressed + surprize + surprise + surprized + surprised + surprizing + surprising + surprizingly + surprisingly + surrended + surrendered + surrepetitious + surreptitious + surrepetitiously + surreptitiously + surreptious + surreptitious + surreptiously + surreptitiously + surronded + surrounded + surrouded + surrounded + surrouding + surrounding + surrundering + surrendering + surveilence + surveillance + surveill + surveil + surveyer + surveyor + surviver + survivor + survivers + survivors + survivied + survived + suseptable + susceptible + suseptible + susceptible + suspention + suspension + swaer + swear + swaers + swears + swepth + swept + swiming + swimming + syas + says + symetrical + symmetrical + symetrically + symmetrically + symetry + symmetry + symettric + symmetric + symmetral + symmetric + symmetricaly + symmetrically + synagouge + synagogue + syncronization + synchronization + synonomous + synonymous + synonymns + synonyms + synphony + symphony + syphyllis + syphilis + sypmtoms + symptoms + syrap + syrup + sysmatically + systematically + sytem + system + sytle + style + tabacco + tobacco + tahn + than + taht + that + talekd + talked + targetted + targeted + targetting + targeting + tast + taste + tath + that + tattooes + tattoos + taxanomic + taxonomic + taxanomy + taxonomy + teached + taught + techician + technician + techicians + technicians + techiniques + techniques + technitian + technician + technnology + technology + technolgy + technology + teh + the + tehy + they + telelevision + television + televsion + television + telphony + telephony + temerature + temperature + tempalte + template + tempaltes + templates + temparate + temperate + temperarily + temporarily + temperment + temperament + tempertaure + temperature + temperture + temperature + temprary + temporary + tenacle + tentacle + tenacles + tentacles + tendacy + tendency + tendancies + tendencies + tendancy + tendency + tennisplayer + tennis player + tepmorarily + temporarily + terrestial + terrestrial + terriories + territories + terriory + territory + territorist + terrorist + territoy + territory + terroist + terrorist + testiclular + testicular + tghe + the + thast + that's + theather + theater + theese + these + theif + thief + theives + thieves + themselfs + themselves + themslves + themselves + ther + there + therafter + thereafter + therby + thereby + theri + their + theyre + they're + thgat + that + thge + the + thier + their + thign + thing + thigns + things + thigsn + things + thikn + think + thikning + thinking + thikns + thinks + thiunk + think + thn + then + thna + than + thne + then + thnig + thing + thnigs + things + thoughout + throughout + threatend + threatened + threatning + threatening + threee + three + threshhold + threshold + thrid + third + throrough + thorough + throughly + thoroughly + throught + throat + througout + throughout + thru + through + thsi + this + thsoe + those + thta + that + thyat + that + tiem + time + tihkn + think + tihs + this + timne + time + tiome + time + tje + the + tjhe + the + tjpanishad + upanishad + tkae + take + tkaes + takes + tkaing + taking + tlaking + talking + tobbaco + tobacco + todays + today's + todya + today + toghether + together + toke + took + tolerence + tolerance + tomatos + tomatoes + tommorow + tomorrow + tommorrow + tomorrow + tongiht + tonight + toriodal + toroidal + tormenters + tormentors + tornadoe + tornado + torpeados + torpedoes + torpedos + torpedoes + tothe + to the + toubles + troubles + tounge + tongue + tourch + torch + towords + towards + towrad + toward + tradionally + traditionally + traditionaly + traditionally + traditionnal + traditional + traditition + tradition + tradtionally + traditionally + trafficed + trafficked + trafficing + trafficking + trafic + traffic + trancendent + transcendent + trancending + transcending + tranform + transform + tranformed + transformed + transcendance + transcendence + transcendant + transcendent + transcendentational + transcendental + transcripting + transcribing + transending + transcending + transesxuals + transsexuals + transfered + transferred + transfering + transferring + transformaton + transformation + transistion + transition + translater + translator + translaters + translators + transmissable + transmissible + transporation + transportation + tremelo + tremolo + tremelos + tremolos + triguered + triggered + triology + trilogy + troling + trolling + troup + troupe + troups + troops + truely + truly + trustworthyness + trustworthiness + turnk + trunk + tust + trust + twelth + twelfth + twon + town + twpo + two + tyhat + that + tyhe + they + typcial + typical + typicaly + typically + tyranies + tyrannies + tyrany + tyranny + tyrranies + tyrannies + tyrrany + tyranny + ubiquitious + ubiquitous + ublisher + publisher + uise + use + ultimely + ultimately + unacompanied + unaccompanied + unahppy + unhappy + unanymous + unanimous + unathorised + unauthorised + unavailible + unavailable + unballance + unbalance + unbeknowst + unbeknownst + unbeleivable + unbelievable + uncertainity + uncertainty + unchallengable + unchallengeable + unchangable + unchangeable + uncompetive + uncompetitive + unconcious + unconscious + unconciousness + unconsciousness + unconfortability + discomfort + uncontitutional + unconstitutional + unconvential + unconventional + undecideable + undecidable + understoon + understood + undesireable + undesirable + undetecable + undetectable + undoubtely + undoubtedly + undreground + underground + uneccesary + unnecessary + unecessary + unnecessary + unequalities + inequalities + unforetunately + unfortunately + unforgetable + unforgettable + unforgiveable + unforgivable + unfortunatley + unfortunately + unfortunatly + unfortunately + unfourtunately + unfortunately + unihabited + uninhabited + unilateraly + unilaterally + unilatreal + unilateral + unilatreally + unilaterally + uninterruped + uninterrupted + uninterupted + uninterrupted + univeral + universal + univeristies + universities + univeristy + university + univerity + university + universtiy + university + univesities + universities + univesity + university + unkown + unknown + unlikey + unlikely + unmanouverable + unmaneuverable + unmistakeably + unmistakably + unneccesarily + unnecessarily + unneccesary + unnecessary + unneccessarily + unnecessarily + unneccessary + unnecessary + unnecesarily + unnecessarily + unnecesary + unnecessary + unoffical + unofficial + unoperational + nonoperational + unoticeable + unnoticeable + unplease + displease + unplesant + unpleasant + unprecendented + unprecedented + unprecidented + unprecedented + unrepentent + unrepentant + unrepetant + unrepentant + unrepetent + unrepentant + unsed + unused + unsubstanciated + unsubstantiated + unsuccesful + unsuccessful + unsuccesfully + unsuccessfully + unsuccessfull + unsuccessful + unsucesful + unsuccessful + unsucesfuly + unsuccessfully + unsucessful + unsuccessful + unsucessfull + unsuccessful + unsucessfully + unsuccessfully + unsuprised + unsurprised + unsuprising + unsurprising + unsuprisingly + unsurprisingly + unsuprized + unsurprised + unsuprizing + unsurprising + unsuprizingly + unsurprisingly + unsurprized + unsurprised + unsurprizing + unsurprising + unsurprizingly + unsurprisingly + untill + until + untranslateable + untranslatable + unuseable + unusable + unusuable + unusable + unviersity + university + unwarrented + unwarranted + unweildly + unwieldy + unwieldly + unwieldy + upcomming + upcoming + upgradded + upgraded + upto + up to + usally + usually + useage + usage + usefull + useful + usefuly + usefully + useing + using + usualy + usually + ususally + usually + vaccum + vacuum + vaccume + vacuum + vacinity + vicinity + vaguaries + vagaries + vaieties + varieties + vailidty + validity + valetta + valletta + valuble + valuable + valueable + valuable + varations + variations + varient + variant + variey + variety + varing + varying + varities + varieties + varity + variety + vasall + vassal + vasalls + vassals + vegatarian + vegetarian + vegitable + vegetable + vegitables + vegetables + vegtable + vegetable + vehicule + vehicle + vell + well + venemous + venomous + vengance + vengeance + vengence + vengeance + verfication + verification + verison + version + verisons + versions + vermillion + vermilion + versitilaty + versatility + versitlity + versatility + vetween + between + veyr + very + vigeur + vigor + vigilence + vigilance + vigourous + vigorous + villian + villain + villification + vilification + villify + vilify + villin + villain + vincinity + vicinity + violentce + violence + virtualy + virtually + virutal + virtual + virutally + virtually + visable + visible + visably + visibly + visting + visiting + vistors + visitors + vitories + victories + volcanoe + volcano + voleyball + volleyball + volontary + voluntary + volonteer + volunteer + volonteered + volunteered + volonteering + volunteering + volonteers + volunteers + volounteer + volunteer + volounteered + volunteered + volounteering + volunteering + volounteers + volunteers + volumne + volume + vreity + variety + vrey + very + vriety + variety + vulnerablility + vulnerability + vyer + very + vyre + very + waht + what + wanna + want to + warantee + warranty + wardobe + wardrobe + warrent + warrant + warrriors + warriors + wasnt + wasn't + wass + was + watn + want + wayword + wayward + weaponary + weaponry + weas + was + wehn + when + weild + wield + weilded + wielded + wendsay + Wednesday + wensday + Wednesday + wereabouts + whereabouts + whant + want + whants + wants + whcih + which + wheras + whereas + wherease + whereas + whereever + wherever + whic + which + whihc + which + whith + with + whlch + which + whn + when + wholey + wholly + wholy + holy + whta + what + whther + whether + wich + which + widesread + widespread + wief + wife + wierd + weird + wiew + view + wih + with + wiht + with + wille + will + willingless + willingness + wirting + writing + withdrawl + withdrawal + witheld + withheld + withh + with + withing + within + withold + withhold + witht + with + witn + with + wiull + will + wnat + want + wnated + wanted + wnats + wants + wohle + whole + wokr + work + wokring + working + wonderfull + wonderful + wont + won't + wordlwide + worldwide + workststion + workstation + worls + world + worstened + worsened + woudl + would + wresters + wrestlers + wriet + write + writen + written + wroet + wrote + wrok + work + wroking + working + wtih + with + wupport + support + xenophoby + xenophobia + yaching + yachting + yaer + year + yaerly + yearly + yaers + years + yatch + yacht + yearm + year + yeasr + years + yeild + yield + yeilding + yielding + yera + year + yeras + years + yersa + years + yotube + YouTube + youre + you're + youseff + yousef + youself + yourself + ytou + you + yuo + you + zeebra + zebra + + enabled + 1 + priority + 5 + wordStyle + 1 + + + diff --git a/indra/newview/llautocorrect.cpp b/indra/newview/llautocorrect.cpp deleted file mode 100644 index acbb790dff..0000000000 --- a/indra/newview/llautocorrect.cpp +++ /dev/null @@ -1,458 +0,0 @@ -/** - * @file llautocorrect.cpp - * @brief Auto Correct Manager - * - * $LicenseInfo:firstyear=2012&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2012, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * $/LicenseInfo$ - */ - -#include "llviewerprecompiledheaders.h" -#include "llautocorrect.h" -#include "llsdserialize.h" -#include "llboost.h" -#include "llcontrol.h" -#include "llviewercontrol.h" -#include "llnotificationsutil.h" - -AutoCorrect* AutoCorrect::sInstance; - -AutoCorrect::AutoCorrect() -{ - sInstance = this; - sInstance->loadFromDisk(); -} - -AutoCorrect::~AutoCorrect() -{ - sInstance = NULL; -} - -void AutoCorrect::autocorrectCallback(LLUIString& inputText, S32& cursorPos) -{ - static LLCachedControl perform_autocorrect(gSavedSettings, "AutoCorrect"); - if(perform_autocorrect) - { - S32 wordStart = 0; - S32 wordEnd = cursorPos-1; - - if(wordEnd < 1) - return; - - LLWString text = inputText.getWString(); - - if(text.size()<1) - return; - - if(LLWStringUtil::isPartOfWord(text[wordEnd])) - return;//we only check on word breaks - - wordEnd--; - - if(LLWStringUtil::isPartOfWord(text[wordEnd])) - { - while ((wordEnd > 0) && (' ' != text[wordEnd-1])) - { - wordEnd--; - } - - wordStart=wordEnd; - - while ((wordEnd < (S32)text.length()) && (' ' != text[wordEnd])) - { - wordEnd++; - } - - std::string strLastWord = std::string(text.begin(), text.end()); - std::string lastTypedWord = strLastWord.substr(wordStart, wordEnd-wordStart); - std::string correctedWord(replaceWord(lastTypedWord)); - - if(correctedWord != lastTypedWord) - { - LLWString strNew = utf8str_to_wstring(correctedWord); - LLWString strOld = utf8str_to_wstring(lastTypedWord); - int nDiff = strNew.size() - strOld.size(); - - //int wordStart = regText.find(lastTypedWord); - text.replace(wordStart,lastTypedWord.length(),strNew); - inputText = wstring_to_utf8str(text); - cursorPos+=nDiff; - } - } - } -} - -AutoCorrect* AutoCorrect::getInstance() -{ - if(sInstance)return sInstance; - else - { - sInstance = new AutoCorrect(); - return sInstance; - } -} -void AutoCorrect::save() -{ - saveToDisk(mAutoCorrects); -} -std::string AutoCorrect::getFileName() -{ - std::string path=gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, ""); - - if (!path.empty()) - { - path = gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, "settings_autocorrect.xml"); - } - return path; -} -std::string AutoCorrect::getDefaultFileName() -{ - std::string path=gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, ""); - - if (!path.empty()) - { - path = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "settings_autocorrect.xml"); - } - return path; -} -LLSD AutoCorrect::exportList(std::string listName) -{ - LLSD toReturn; - if(mAutoCorrects.has(listName)) - { - toReturn["listName"]=listName; - toReturn["data"]=mAutoCorrects[listName]["data"]; - toReturn["author"]=mAutoCorrects[listName]["author"]; - toReturn["wordStyle"]=mAutoCorrects[listName]["wordStyle"]; - toReturn["priority"]=mAutoCorrects[listName]["priority"]; - } - return toReturn; -} -BOOL AutoCorrect::addCorrectionList(LLSD newList) -{ - if(newList.has("listName")) - { - std::string name = newList["listName"]; - //if(!mAutoCorrects.has(name)){ - LLSD newPart; - newPart["data"]=newList["data"]; - newPart["enabled"]=TRUE; - newPart["announce"]=FALSE; - newPart["author"]=newList["author"]; - newPart["wordStyle"]=newList["wordStyle"]; - newPart["priority"]=newList["priority"].asInteger(); - llinfos << "adding new list with settings priority "<fileExists(filename)) - { - std::string defaultName = getDefaultFileName(); - llinfos << " user settings file doesnt exist, going to try and read default one from "<fileExists(defaultName)) - { - LLSD blankllsd; - llifstream file; - file.open(defaultName.c_str()); - if (file.is_open()) - { - LLSDSerialize::fromXMLDocument(blankllsd, file); - } - file.close(); - saveToDisk(blankllsd); - }else - saveToDisk(getExampleLLSD()); - } - else - { - llifstream file; - file.open(filename.c_str()); - if (file.is_open()) - { - LLSDSerialize::fromXML(mAutoCorrects, file); - } - file.close(); - } -} -void AutoCorrect::saveToDisk(LLSD newSettings) -{ - mAutoCorrects=newSettings; - std::string filename=getFileName(); - llofstream file; - file.open(filename.c_str()); - LLSDSerialize::toPrettyXML(mAutoCorrects, file); - file.close(); -} -void AutoCorrect::runTest() -{ - std::string startS("He just abandonned all his abilties"); - std::string endS = replaceWords(startS); - llinfos << "!!! Test of autoreplace; start with "< perform_autocorrect(gSavedSettings, "AutoCorrect"); - if(!(perform_autocorrect))return currentWord; - //loop through priorities - for(int currentPriority = 10;currentPriority>=0;currentPriority--) - { - LLSD::map_const_iterator loc_it = mAutoCorrects.beginMap(); - LLSD::map_const_iterator loc_end = mAutoCorrects.endMap(); - for (; loc_it != loc_end; ++loc_it) - { - const std::string& location = (*loc_it).first; - //llinfos << "location is "< " << replacement.c_str() << llendl; - return replacement; - } - } - } - } - return currentWord; -} -std::string AutoCorrect::replaceWords(std::string words) -{ - static LLCachedControl perform_autocorrect(gSavedSettings, "AutoCorrect"); - if(!(perform_autocorrect))return words; - //*TODO update this function to use the "wordStyle" thing, - //but so far this function is never used, so later - - boost_tokenizer tokens(words, boost::char_separator(" ")); - for (boost_tokenizer::iterator token_iter = tokens.begin(); token_iter != tokens.end(); ++token_iter) - { - std::string currentWord(*token_iter); - LLSD::map_const_iterator loc_it = mAutoCorrects.beginMap(); - LLSD::map_const_iterator loc_end = mAutoCorrects.endMap(); - for (; loc_it != loc_end; ++loc_it) - { - const std::string& location = (*loc_it).first; - const LLSD& loc_map = (*loc_it).second; - if((loc_map["data"].has(currentWord))&&(loc_map["enabled"].asBoolean())) - { - std::string replacement = loc_map["data"][currentWord]; - if(loc_map["announce"].asBoolean()) - { - LLSD args; - //"[Before]" has been auto replaced by "[Replacement]" - // based on your [ListName] list. - args["BEFORE"] = currentWord; - args["LISTNAME"]=location; - args["REPLACEMENT"]=replacement; - LLNotificationsUtil::add("AutoReplace",args); - } - lldebugs << "found a word in list " << location.c_str() << " and it will replace " << currentWord.c_str() << " => " << replacement.c_str() << llendl; - int wordStart = words.find(currentWord); - words.replace(wordStart,currentWord.length(),replacement); - return replaceWords(words);//lol recursion! - } - } - } - return words; -} -BOOL AutoCorrect::addEntryToList(std::string wrong, std::string right, std::string listName) -{ - // *HACK: Make sure the "Custom" list exists, because the design of this - // system prevents us from updating it by changing the original file... - if(mAutoCorrects.has(listName)) - { - mAutoCorrects[listName]["data"][wrong]=right; - return TRUE; - } - else if(listName == "Custom") - { - mAutoCorrects[listName]["announce"] = 0; - mAutoCorrects[listName]["author"] = "You"; - mAutoCorrects[listName]["data"][wrong] = right; - mAutoCorrects[listName]["enabled"] = 1; - mAutoCorrects[listName]["priority"] = 10; - mAutoCorrects[listName]["wordStyle"] = 1; - return TRUE; - } - - return FALSE; -} -BOOL AutoCorrect::removeEntryFromList(std::string wrong, std::string listName) -{ - if(mAutoCorrects.has(listName)) - { - if(mAutoCorrects[listName]["data"].has(wrong)) - { - mAutoCorrects[listName]["data"].erase(wrong); - return TRUE; - } - } - return FALSE; -} - -LLSD AutoCorrect::getExampleLLSD() -{ - LLSD toReturn; - - LLSD listone; - LLSD listtwo; - - LLSD itemOne; - itemOne["wrong"]="wrong1"; - itemOne["right"]="right1"; - listone[0]=itemOne; - - LLSD itemTwo; - itemTwo["wrong"]="wrong2"; - itemTwo["right"]="right2"; - listone[1]=itemTwo; - - toReturn["listOne"]=listone; - - - itemOne["wrong"]="secondwrong1"; - itemOne["right"]="secondright1"; - listone[0]=itemOne; - - itemTwo["wrong"]="secondwrong2"; - itemTwo["right"]="secondright2"; - listone[1]=itemTwo; - - toReturn["listTwo"]=listone; - - return toReturn; -} - diff --git a/indra/newview/llautocorrect.h b/indra/newview/llautocorrect.h deleted file mode 100644 index 82cf75f3cf..0000000000 --- a/indra/newview/llautocorrect.h +++ /dev/null @@ -1,65 +0,0 @@ -/** - * @file llautocorrect.h - * @brief Auto Correct Manager - * @copyright Copyright (c) 2011 LordGregGreg Back - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - */ -#ifndef AUTO_CORRECT -#define AUTO_CORRECT - -#include "lllineeditor.h" - -class AutoCorrect : public LLSingleton -{ - AutoCorrect(); - ~AutoCorrect(); - static AutoCorrect* sInstance; -public: - void autocorrectCallback(LLUIString& inputText, S32& cursorPos); - static AutoCorrect* getInstance(); - BOOL addCorrectionList(LLSD newList); - BOOL removeCorrectionList(std::string listName); - BOOL setListEnabled(std::string listName, BOOL enabled); - BOOL setListAnnounceeState(std::string listName, BOOL announce); - BOOL setListPriority(std::string listName, int priority); - BOOL setListStyle(std::string listName, BOOL announce); - std::string replaceWords(std::string words); - std::string replaceWord(std::string currentWord); - BOOL addEntryToList(std::string wrong, std::string right, std::string listName); - BOOL removeEntryFromList(std::string wrong, std::string listName); - BOOL saveListToDisk(std::string listName, std::string fileName); - LLSD exportList(std::string listName); - void runTest(); - LLSD getAutoCorrects(); - LLSD getAutoCorrectEntries(std::string listName); - void save(); - - void loadFromDisk(); - -private: - friend class LLSingleton; - void saveToDisk(LLSD newSettings); - LLSD getExampleLLSD(); - std::string getFileName(); - std::string getDefaultFileName(); - - LLSD mAutoCorrects; - -}; - - - -#endif diff --git a/indra/newview/llautocorrectfloater.cpp b/indra/newview/llautocorrectfloater.cpp deleted file mode 100644 index 10bc30c0b4..0000000000 --- a/indra/newview/llautocorrectfloater.cpp +++ /dev/null @@ -1,383 +0,0 @@ -/** - * @file llautocorrectfloater.cpp - * @brief Auto Correct List floater - * - * $LicenseInfo:firstyear=2012&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2012, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * $/LicenseInfo$ - */ - -#include "llviewerprecompiledheaders.h" - -#include "llautocorrectfloater.h" - -#include "llagentdata.h" -#include "llcommandhandler.h" -#include "llfloater.h" -#include "lluictrlfactory.h" -#include "llagent.h" -#include "llpanel.h" -#include "llbutton.h" -#include "llcolorswatch.h" -#include "llcombobox.h" -#include "llview.h" -#include "llhttpclient.h" -#include "llbufferstream.h" -#include "llcheckboxctrl.h" -#include "llviewercontrol.h" - -#include "llui.h" -#include "llcontrol.h" -#include "llscrollingpanellist.h" -#include "llautocorrect.h" -#include "llfilepicker.h" -#include "llfile.h" -#include "llsdserialize.h" -//#include "llfloaterchat.h" -#include "llchat.h" -#include "llinventorymodel.h" -#include "llhost.h" -#include "llassetstorage.h" -#include "roles_constants.h" -#include "llviewertexteditor.h" -#include - -#include -#include "llfloaterreg.h" -#include "llinspecttoast.h" -#include "llnotificationhandler.h" -#include "llnotificationmanager.h" - - -AutoCorrectFloater::AutoCorrectFloater(const LLSD& key) : -LLFloater(key) -{ -} -void AutoCorrectFloater::onClose(bool app_quitting) -{ - destroy(); -} - -BOOL AutoCorrectFloater::postBuild(void) -{ - - namesList = getChild("ac_list_name"); - entryList = getChild("ac_list_entry"); - mOldText = getChild("ac_old_text"); - mNewText = getChild("ac_new_text"); - - childSetCommitCallback("ac_enable",onBoxCommitEnabled,this); - - childSetCommitCallback("ac_list_enabled",onEntrySettingChange,this); - childSetCommitCallback("ac_list_show",onEntrySettingChange,this); - childSetCommitCallback("ac_list_style",onEntrySettingChange,this); - childSetCommitCallback("ac_priority",onEntrySettingChange,this); - - - - updateEnabledStuff(); - updateNamesList(); - - - namesList->setCommitOnSelectionChange(TRUE); - childSetCommitCallback("ac_list_name", onSelectName, this); - - childSetAction("ac_deletelist",removeList,this); - childSetAction("ac_rementry",deleteEntry,this); - childSetAction("ac_exportlist",exportList,this); - childSetAction("ac_addentry",addEntry,this); - childSetAction("ac_loadlist",loadList,this); - - return true; -} - -void AutoCorrectFloater::onSelectName(LLUICtrl* ctrl, void* user_data) -{ - if ( user_data ) - { - AutoCorrectFloater* self = ( AutoCorrectFloater* )user_data; - if ( self ) - self->updateItemsList(); - } - -} -void AutoCorrectFloater::updateItemsList() -{ - entryList->deleteAllItems(); - if((namesList->getAllSelected().size())<=0) - { - - updateListControlsEnabled(FALSE); - return; - } - - updateListControlsEnabled(TRUE); - std::string listName= namesList->getFirstSelected()->getColumn(0)->getValue().asString(); - - LLSD listData = AutoCorrect::getInstance()->getAutoCorrectEntries(listName); - childSetValue("ac_list_enabled",listData["enabled"].asBoolean()); - childSetValue("ac_list_style",listData["wordStyle"].asBoolean()); - childSetValue("ac_list_show",listData["announce"].asBoolean()); - childSetValue("ac_text_name",listName); - childSetValue("ac_text_author",listData["author"]); - childSetValue("ac_priority",listData["priority"]); - - LLSD autoCorrects = listData["data"]; - LLSD::map_const_iterator loc_it = autoCorrects.beginMap(); - LLSD::map_const_iterator loc_end = autoCorrects.endMap(); - for ( ; loc_it != loc_end; ++loc_it) - { - const std::string& wrong = (*loc_it).first; - const std::string& right = (*loc_it).second; - - //std::string lentry(wrong+"=>"+right); - - LLSD element; - element["id"] = wrong; - LLSD& s_column = element["columns"][0]; - s_column["column"] = "Search"; - s_column["value"] = wrong; - s_column["font"] = "SANSSERIF"; - LLSD& r_column = element["columns"][1]; - r_column["column"] = "Replace"; - r_column["value"] = right; - r_column["font"] = "SANSSERIF"; - - entryList->addElement(element, ADD_BOTTOM); - } - -} -void AutoCorrectFloater::updateNamesList() -{ - namesList->deleteAllItems(); - if(!gSavedSettings.getBOOL("AutoCorrect")) - { - updateItemsList(); - return; - } - LLSD autoCorrects = AutoCorrect::getInstance()->getAutoCorrects(); - LLSD::map_const_iterator loc_it = autoCorrects.beginMap(); - LLSD::map_const_iterator loc_end = autoCorrects.endMap(); - for ( ; loc_it != loc_end; ++loc_it) - { - const std::string& listName = (*loc_it).first; - - LLSD element; - element["id"] = listName; - LLSD& friend_column = element["columns"][0]; - friend_column["column"] = "Entries"; - friend_column["value"] = listName; - //friend_column["font"] = "SANSSERIF"; - const LLSD& loc_map = (*loc_it).second; - if(loc_map["enabled"].asBoolean()) - friend_column["font"] = "SANSSERIF"; - //friend_column["style"] = "BOLD"; - else - friend_column["font"] = "SANSSERIF_SMALL"; - //friend_column["style"] = "NORMAL"; - if(namesList) - namesList->addElement(element, ADD_BOTTOM); - } - updateItemsList(); -} -void AutoCorrectFloater::updateListControlsEnabled(BOOL selected) -{ - - childSetEnabled("ac_text1",selected); - childSetEnabled("ac_text2",selected); - childSetEnabled("ac_text_name",selected); - childSetEnabled("ac_text_author",selected); - childSetEnabled("ac_list_enabled",selected); - childSetEnabled("ac_list_show",selected); - childSetEnabled("ac_list_style",selected); - childSetEnabled("ac_deletelist",selected); - childSetEnabled("ac_exportlist",selected); - childSetEnabled("ac_addentry",selected); - childSetEnabled("ac_rementry",selected); - childSetEnabled("ac_priority",selected); - -} -void AutoCorrectFloater::updateEnabledStuff() -{ - BOOL autocorrect = gSavedSettings.getBOOL("AutoCorrect"); - if(autocorrect) - { - LLCheckBoxCtrl *enBox = getChild("ac_enable"); - enBox->setDisabledColor(LLColor4::red); - getChild("ac_enable")->setEnabledColor(LLColor4(1.0f,0.0f,0.0f,1.0f)); - }else - { - getChild("ac_enable")->setEnabledColor( - LLUIColorTable::instance().getColor( "LabelTextColor" )); - } - - childSetEnabled("ac_list_name", autocorrect); - childSetEnabled("ac_list_entry", autocorrect); - updateListControlsEnabled(autocorrect); - updateNamesList(); - AutoCorrect::getInstance()->save(); - -} -void AutoCorrectFloater::setData(void * data) -{ -} -void AutoCorrectFloater::onBoxCommitEnabled(LLUICtrl* caller, void* user_data) -{ - if ( user_data ) - { - AutoCorrectFloater* self = ( AutoCorrectFloater* )user_data; - if ( self ) - { - self->updateEnabledStuff(); - } - } -} -void AutoCorrectFloater::onEntrySettingChange(LLUICtrl* caller, void* user_data) -{ - if ( user_data ) - { - AutoCorrectFloater* self = ( AutoCorrectFloater* )user_data; - if ( self ) - { - std::string listName= self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); - AutoCorrect::getInstance()->setListEnabled(listName,self->childGetValue("ac_list_enabled").asBoolean()); - AutoCorrect::getInstance()->setListAnnounceeState(listName,self->childGetValue("ac_list_show").asBoolean()); - AutoCorrect::getInstance()->setListStyle(listName,self->childGetValue("ac_list_style").asBoolean()); - AutoCorrect::getInstance()->setListPriority(listName,self->childGetValue("ac_priority").asInteger()); - - //sInstance->updateEnabledStuff(); - self->updateItemsList(); - AutoCorrect::getInstance()->save(); - } - } -} -void AutoCorrectFloater::deleteEntry(void* data) -{ - if ( data ) - { - AutoCorrectFloater* self = ( AutoCorrectFloater* )data; - if ( self ) - { - - std::string listName=self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); - - if((self->entryList->getAllSelected().size())>0) - { - std::string wrong= self->entryList->getFirstSelected()->getColumn(0)->getValue().asString(); - AutoCorrect::getInstance()->removeEntryFromList(wrong,listName); - self->updateItemsList(); - AutoCorrect::getInstance()->save(); - } - } - } -} -void AutoCorrectFloater::loadList(void* data) -{ - LLFilePicker& picker = LLFilePicker::instance(); - - if(!picker.getOpenFile( LLFilePicker::FFLOAD_XML) ) - {return; - } - llifstream file; - file.open(picker.getFirstFile().c_str()); - LLSD blankllsd; - if (file.is_open()) - { - LLSDSerialize::fromXMLDocument(blankllsd, file); - } - file.close(); - gSavedSettings.setBOOL("AutoCorrect",true); - AutoCorrect::getInstance()->addCorrectionList(blankllsd); - if ( data ) - { - AutoCorrectFloater* self = ( AutoCorrectFloater* )data; - if ( self ) - self->updateEnabledStuff(); - } -} -void AutoCorrectFloater::removeList(void* data) -{ - if ( data ) - { - AutoCorrectFloater* self = ( AutoCorrectFloater* )data; - if ( self ) - { - std::string listName= self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); - AutoCorrect::getInstance()->removeCorrectionList(listName); - self->updateEnabledStuff(); - } - - } -} -void AutoCorrectFloater::exportList(void *data) -{ - if ( data ) - { - AutoCorrectFloater* self = ( AutoCorrectFloater* )data; - if ( self ) - { - std::string listName=self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); - - LLFilePicker& picker = LLFilePicker::instance(); - - if(!picker.getSaveFile( LLFilePicker::FFSAVE_XML) ) - {return; - } - llofstream file; - file.open(picker.getFirstFile().c_str()); - LLSDSerialize::toPrettyXML(AutoCorrect::getInstance()->exportList(listName), file); - file.close(); - } - - } -} -void AutoCorrectFloater::addEntry(void* data) -{ - if ( data ) - { - AutoCorrectFloater* self = ( AutoCorrectFloater* )data; - if ( self ) - { - std::string listName= self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); - std::string wrong = self->mOldText->getText(); - std::string right = self->mNewText->getText(); - if(wrong != "" && right != "") - { - AutoCorrect::getInstance()->addEntryToList(wrong, right, listName); - self->updateItemsList(); - AutoCorrect::getInstance()->save(); - } - } - } -} -AutoCorrectFloater* AutoCorrectFloater::showFloater() -{ - AutoCorrectFloater *floater = dynamic_cast(LLFloaterReg::getInstance("autocorrect")); - if(floater) - { - floater->setVisible(true); - floater->setFrontmost(true); - floater->center(); - return floater; - } - else - { - LL_WARNS("AutoCorrect") << "Can't find floater!" << LL_ENDL; - return NULL; - } -} diff --git a/indra/newview/llautocorrectfloater.h b/indra/newview/llautocorrectfloater.h deleted file mode 100644 index 2a02f6cc82..0000000000 --- a/indra/newview/llautocorrectfloater.h +++ /dev/null @@ -1,75 +0,0 @@ -/** - * @file llautocorrectfloater.h - * @brief Auto Correct List floater - * @copyright Copyright (c) 2011 LordGregGreg Back - * - * $LicenseInfo:firstyear=2012&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2012, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * $/LicenseInfo$ - */ - -#ifndef AUTOCORRECTFLOATER_H -#define AUTOCORRECTFLOATER_H - -#include "llfloater.h" -#include "llmediactrl.h" -#include "llscrolllistctrl.h" -#include "lllineeditor.h" - -#include "llviewerinventory.h" -#include - -class AutoCorrectFloater : -public LLFloater -{ -public: - AutoCorrectFloater(const LLSD& key); - - /*virtual*/ BOOL postBuild(); - /*virtual*/ void onClose(bool app_quitting); - - static AutoCorrectFloater* showFloater(); - - void setData(void * data); - void updateEnabledStuff(); - void updateNamesList(); - void updateListControlsEnabled(BOOL selected); - void updateItemsList(); - - LLScrollListCtrl *namesList; - LLScrollListCtrl *entryList; - LLLineEditor* mOldText; - LLLineEditor* mNewText; - //LLPanel * empanel; -private: - //static JCInvDropTarget* mNotecardDropTarget; - static void onBoxCommitEnabled(LLUICtrl* caller, void* user_data); - static void onEntrySettingChange(LLUICtrl* caller, void* user_data); - static void onSelectName(LLUICtrl* caller, void* user_data); - //static void ResponseItemDrop(LLViewerInventoryItem* item); - //static void onNotecardLoadComplete(LLVFS *vfs,const LLUUID& asset_uuid,LLAssetType::EType type,void* user_data, S32 status, LLExtStat ext_status); - - - static void deleteEntry(void* data); - static void addEntry(void* data); - static void exportList(void* data); - static void removeList(void* data); - static void loadList(void* data); -}; - -#endif // AUTOCORRECTFLOATER_H diff --git a/indra/newview/llautoreplace.cpp b/indra/newview/llautoreplace.cpp new file mode 100644 index 0000000000..a5683e4190 --- /dev/null +++ b/indra/newview/llautoreplace.cpp @@ -0,0 +1,458 @@ +/** + * @file llautoreplace.cpp + * @brief Auto Replace Manager + * + * $LicenseInfo:firstyear=2012&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2012, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * $/LicenseInfo$ + */ + +#include "llviewerprecompiledheaders.h" +#include "llautoreplace.h" +#include "llsdserialize.h" +#include "llboost.h" +#include "llcontrol.h" +#include "llviewercontrol.h" +#include "llnotificationsutil.h" + +AutoReplace* AutoReplace::sInstance; + +AutoReplace::AutoReplace() +{ + sInstance = this; + sInstance->loadFromDisk(); +} + +AutoReplace::~AutoReplace() +{ + sInstance = NULL; +} + +void AutoReplace::autoreplaceCallback(LLUIString& inputText, S32& cursorPos) +{ + static LLCachedControl perform_autoreplace(gSavedSettings, "AutoReplace"); + if(perform_autoreplace) + { + S32 wordStart = 0; + S32 wordEnd = cursorPos-1; + + if(wordEnd < 1) + return; + + LLWString text = inputText.getWString(); + + if(text.size()<1) + return; + + if(LLWStringUtil::isPartOfWord(text[wordEnd])) + return;//we only check on word breaks + + wordEnd--; + + if(LLWStringUtil::isPartOfWord(text[wordEnd])) + { + while ((wordEnd > 0) && (' ' != text[wordEnd-1])) + { + wordEnd--; + } + + wordStart=wordEnd; + + while ((wordEnd < (S32)text.length()) && (' ' != text[wordEnd])) + { + wordEnd++; + } + + std::string strLastWord = std::string(text.begin(), text.end()); + std::string lastTypedWord = strLastWord.substr(wordStart, wordEnd-wordStart); + std::string replaceedWord(replaceWord(lastTypedWord)); + + if(replaceedWord != lastTypedWord) + { + LLWString strNew = utf8str_to_wstring(replaceedWord); + LLWString strOld = utf8str_to_wstring(lastTypedWord); + int nDiff = strNew.size() - strOld.size(); + + //int wordStart = regText.find(lastTypedWord); + text.replace(wordStart,lastTypedWord.length(),strNew); + inputText = wstring_to_utf8str(text); + cursorPos+=nDiff; + } + } + } +} + +AutoReplace* AutoReplace::getInstance() +{ + if(sInstance)return sInstance; + else + { + sInstance = new AutoReplace(); + return sInstance; + } +} +void AutoReplace::save() +{ + saveToDisk(mAutoReplaces); +} +std::string AutoReplace::getFileName() +{ + std::string path=gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, ""); + + if (!path.empty()) + { + path = gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, "settings_autoreplace.xml"); + } + return path; +} +std::string AutoReplace::getDefaultFileName() +{ + std::string path=gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, ""); + + if (!path.empty()) + { + path = gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "settings_autoreplace.xml"); + } + return path; +} +LLSD AutoReplace::exportList(std::string listName) +{ + LLSD toReturn; + if(mAutoReplaces.has(listName)) + { + toReturn["listName"]=listName; + toReturn["data"]=mAutoReplaces[listName]["data"]; + toReturn["author"]=mAutoReplaces[listName]["author"]; + toReturn["wordStyle"]=mAutoReplaces[listName]["wordStyle"]; + toReturn["priority"]=mAutoReplaces[listName]["priority"]; + } + return toReturn; +} +BOOL AutoReplace::addReplacementList(LLSD newList) +{ + if(newList.has("listName")) + { + std::string name = newList["listName"]; + //if(!mAutoReplaces.has(name)){ + LLSD newPart; + newPart["data"]=newList["data"]; + newPart["enabled"]=TRUE; + newPart["announce"]=FALSE; + newPart["author"]=newList["author"]; + newPart["wordStyle"]=newList["wordStyle"]; + newPart["priority"]=newList["priority"].asInteger(); + llinfos << "adding new list with settings priority "<fileExists(filename)) + { + std::string defaultName = getDefaultFileName(); + llinfos << " user settings file doesnt exist, going to try and read default one from "<fileExists(defaultName)) + { + LLSD blankllsd; + llifstream file; + file.open(defaultName.c_str()); + if (file.is_open()) + { + LLSDSerialize::fromXMLDocument(blankllsd, file); + } + file.close(); + saveToDisk(blankllsd); + }else + saveToDisk(getExampleLLSD()); + } + else + { + llifstream file; + file.open(filename.c_str()); + if (file.is_open()) + { + LLSDSerialize::fromXML(mAutoReplaces, file); + } + file.close(); + } +} +void AutoReplace::saveToDisk(LLSD newSettings) +{ + mAutoReplaces=newSettings; + std::string filename=getFileName(); + llofstream file; + file.open(filename.c_str()); + LLSDSerialize::toPrettyXML(mAutoReplaces, file); + file.close(); +} +void AutoReplace::runTest() +{ + std::string startS("He just abandonned all his abilties"); + std::string endS = replaceWords(startS); + llinfos << "!!! Test of autoreplace; start with "< perform_autoreplace(gSavedSettings, "AutoReplace"); + if(!(perform_autoreplace))return currentWord; + //loop through priorities + for(int currentPriority = 10;currentPriority>=0;currentPriority--) + { + LLSD::map_const_iterator loc_it = mAutoReplaces.beginMap(); + LLSD::map_const_iterator loc_end = mAutoReplaces.endMap(); + for (; loc_it != loc_end; ++loc_it) + { + const std::string& location = (*loc_it).first; + //llinfos << "location is "< " << replacement.c_str() << llendl; + return replacement; + } + } + } + } + return currentWord; +} +std::string AutoReplace::replaceWords(std::string words) +{ + static LLCachedControl perform_autoreplace(gSavedSettings, "AutoReplace"); + if(!(perform_autoreplace))return words; + //*TODO update this function to use the "wordStyle" thing, + //but so far this function is never used, so later + + boost_tokenizer tokens(words, boost::char_separator(" ")); + for (boost_tokenizer::iterator token_iter = tokens.begin(); token_iter != tokens.end(); ++token_iter) + { + std::string currentWord(*token_iter); + LLSD::map_const_iterator loc_it = mAutoReplaces.beginMap(); + LLSD::map_const_iterator loc_end = mAutoReplaces.endMap(); + for (; loc_it != loc_end; ++loc_it) + { + const std::string& location = (*loc_it).first; + const LLSD& loc_map = (*loc_it).second; + if((loc_map["data"].has(currentWord))&&(loc_map["enabled"].asBoolean())) + { + std::string replacement = loc_map["data"][currentWord]; + if(loc_map["announce"].asBoolean()) + { + LLSD args; + //"[Before]" has been auto replaced by "[Replacement]" + // based on your [ListName] list. + args["BEFORE"] = currentWord; + args["LISTNAME"]=location; + args["REPLACEMENT"]=replacement; + LLNotificationsUtil::add("AutoReplace",args); + } + lldebugs << "found a word in list " << location.c_str() << " and it will replace " << currentWord.c_str() << " => " << replacement.c_str() << llendl; + int wordStart = words.find(currentWord); + words.replace(wordStart,currentWord.length(),replacement); + return replaceWords(words);//lol recursion! + } + } + } + return words; +} +BOOL AutoReplace::addEntryToList(std::string wrong, std::string right, std::string listName) +{ + // *HACK: Make sure the "Custom" list exists, because the design of this + // system prevents us from updating it by changing the original file... + if(mAutoReplaces.has(listName)) + { + mAutoReplaces[listName]["data"][wrong]=right; + return TRUE; + } + else if(listName == "Custom") + { + mAutoReplaces[listName]["announce"] = 0; + mAutoReplaces[listName]["author"] = "You"; + mAutoReplaces[listName]["data"][wrong] = right; + mAutoReplaces[listName]["enabled"] = 1; + mAutoReplaces[listName]["priority"] = 10; + mAutoReplaces[listName]["wordStyle"] = 1; + return TRUE; + } + + return FALSE; +} +BOOL AutoReplace::removeEntryFromList(std::string wrong, std::string listName) +{ + if(mAutoReplaces.has(listName)) + { + if(mAutoReplaces[listName]["data"].has(wrong)) + { + mAutoReplaces[listName]["data"].erase(wrong); + return TRUE; + } + } + return FALSE; +} + +LLSD AutoReplace::getExampleLLSD() +{ + LLSD toReturn; + + LLSD listone; + LLSD listtwo; + + LLSD itemOne; + itemOne["wrong"]="wrong1"; + itemOne["right"]="right1"; + listone[0]=itemOne; + + LLSD itemTwo; + itemTwo["wrong"]="wrong2"; + itemTwo["right"]="right2"; + listone[1]=itemTwo; + + toReturn["listOne"]=listone; + + + itemOne["wrong"]="secondwrong1"; + itemOne["right"]="secondright1"; + listone[0]=itemOne; + + itemTwo["wrong"]="secondwrong2"; + itemTwo["right"]="secondright2"; + listone[1]=itemTwo; + + toReturn["listTwo"]=listone; + + return toReturn; +} + diff --git a/indra/newview/llautoreplace.h b/indra/newview/llautoreplace.h new file mode 100644 index 0000000000..b11c124a62 --- /dev/null +++ b/indra/newview/llautoreplace.h @@ -0,0 +1,65 @@ +/** + * @file llautoreplace.h + * @brief Auto Replace Manager + * @copyright Copyright (c) 2011 LordGregGreg Back + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +#ifndef AUTO_REPLACE +#define AUTO_REPLACE + +#include "lllineeditor.h" + +class AutoReplace : public LLSingleton +{ + AutoReplace(); + ~AutoReplace(); + static AutoReplace* sInstance; +public: + void autoreplaceCallback(LLUIString& inputText, S32& cursorPos); + static AutoReplace* getInstance(); + BOOL addReplacementList(LLSD newList); + BOOL removeReplacementList(std::string listName); + BOOL setListEnabled(std::string listName, BOOL enabled); + BOOL setListAnnounceeState(std::string listName, BOOL announce); + BOOL setListPriority(std::string listName, int priority); + BOOL setListStyle(std::string listName, BOOL announce); + std::string replaceWords(std::string words); + std::string replaceWord(std::string currentWord); + BOOL addEntryToList(std::string wrong, std::string right, std::string listName); + BOOL removeEntryFromList(std::string wrong, std::string listName); + BOOL saveListToDisk(std::string listName, std::string fileName); + LLSD exportList(std::string listName); + void runTest(); + LLSD getAutoReplaces(); + LLSD getAutoReplaceEntries(std::string listName); + void save(); + + void loadFromDisk(); + +private: + friend class LLSingleton; + void saveToDisk(LLSD newSettings); + LLSD getExampleLLSD(); + std::string getFileName(); + std::string getDefaultFileName(); + + LLSD mAutoReplaces; + +}; + + + +#endif diff --git a/indra/newview/llautoreplacefloater.cpp b/indra/newview/llautoreplacefloater.cpp new file mode 100644 index 0000000000..01950adb37 --- /dev/null +++ b/indra/newview/llautoreplacefloater.cpp @@ -0,0 +1,383 @@ +/** + * @file llautoreplacefloater.cpp + * @brief Auto Replace List floater + * + * $LicenseInfo:firstyear=2012&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2012, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * $/LicenseInfo$ + */ + +#include "llviewerprecompiledheaders.h" + +#include "llautoreplacefloater.h" + +#include "llagentdata.h" +#include "llcommandhandler.h" +#include "llfloater.h" +#include "lluictrlfactory.h" +#include "llagent.h" +#include "llpanel.h" +#include "llbutton.h" +#include "llcolorswatch.h" +#include "llcombobox.h" +#include "llview.h" +#include "llhttpclient.h" +#include "llbufferstream.h" +#include "llcheckboxctrl.h" +#include "llviewercontrol.h" + +#include "llui.h" +#include "llcontrol.h" +#include "llscrollingpanellist.h" +#include "llautoreplace.h" +#include "llfilepicker.h" +#include "llfile.h" +#include "llsdserialize.h" +//#include "llfloaterchat.h" +#include "llchat.h" +#include "llinventorymodel.h" +#include "llhost.h" +#include "llassetstorage.h" +#include "roles_constants.h" +#include "llviewertexteditor.h" +#include + +#include +#include "llfloaterreg.h" +#include "llinspecttoast.h" +#include "llnotificationhandler.h" +#include "llnotificationmanager.h" + + +AutoReplaceFloater::AutoReplaceFloater(const LLSD& key) : +LLFloater(key) +{ +} +void AutoReplaceFloater::onClose(bool app_quitting) +{ + destroy(); +} + +BOOL AutoReplaceFloater::postBuild(void) +{ + + namesList = getChild("ac_list_name"); + entryList = getChild("ac_list_entry"); + mOldText = getChild("ac_old_text"); + mNewText = getChild("ac_new_text"); + + childSetCommitCallback("ac_enable",onBoxCommitEnabled,this); + + childSetCommitCallback("ac_list_enabled",onEntrySettingChange,this); + childSetCommitCallback("ac_list_show",onEntrySettingChange,this); + childSetCommitCallback("ac_list_style",onEntrySettingChange,this); + childSetCommitCallback("ac_priority",onEntrySettingChange,this); + + + + updateEnabledStuff(); + updateNamesList(); + + + namesList->setCommitOnSelectionChange(TRUE); + childSetCommitCallback("ac_list_name", onSelectName, this); + + childSetAction("ac_deletelist",removeList,this); + childSetAction("ac_rementry",deleteEntry,this); + childSetAction("ac_exportlist",exportList,this); + childSetAction("ac_addentry",addEntry,this); + childSetAction("ac_loadlist",loadList,this); + + return true; +} + +void AutoReplaceFloater::onSelectName(LLUICtrl* ctrl, void* user_data) +{ + if ( user_data ) + { + AutoReplaceFloater* self = ( AutoReplaceFloater* )user_data; + if ( self ) + self->updateItemsList(); + } + +} +void AutoReplaceFloater::updateItemsList() +{ + entryList->deleteAllItems(); + if((namesList->getAllSelected().size())<=0) + { + + updateListControlsEnabled(FALSE); + return; + } + + updateListControlsEnabled(TRUE); + std::string listName= namesList->getFirstSelected()->getColumn(0)->getValue().asString(); + + LLSD listData = AutoReplace::getInstance()->getAutoReplaceEntries(listName); + childSetValue("ac_list_enabled",listData["enabled"].asBoolean()); + childSetValue("ac_list_style",listData["wordStyle"].asBoolean()); + childSetValue("ac_list_show",listData["announce"].asBoolean()); + childSetValue("ac_text_name",listName); + childSetValue("ac_text_author",listData["author"]); + childSetValue("ac_priority",listData["priority"]); + + LLSD autoReplaces = listData["data"]; + LLSD::map_const_iterator loc_it = autoReplaces.beginMap(); + LLSD::map_const_iterator loc_end = autoReplaces.endMap(); + for ( ; loc_it != loc_end; ++loc_it) + { + const std::string& wrong = (*loc_it).first; + const std::string& right = (*loc_it).second; + + //std::string lentry(wrong+"=>"+right); + + LLSD element; + element["id"] = wrong; + LLSD& s_column = element["columns"][0]; + s_column["column"] = "Search"; + s_column["value"] = wrong; + s_column["font"] = "SANSSERIF"; + LLSD& r_column = element["columns"][1]; + r_column["column"] = "Replace"; + r_column["value"] = right; + r_column["font"] = "SANSSERIF"; + + entryList->addElement(element, ADD_BOTTOM); + } + +} +void AutoReplaceFloater::updateNamesList() +{ + namesList->deleteAllItems(); + if(!gSavedSettings.getBOOL("AutoReplace")) + { + updateItemsList(); + return; + } + LLSD autoReplaces = AutoReplace::getInstance()->getAutoReplaces(); + LLSD::map_const_iterator loc_it = autoReplaces.beginMap(); + LLSD::map_const_iterator loc_end = autoReplaces.endMap(); + for ( ; loc_it != loc_end; ++loc_it) + { + const std::string& listName = (*loc_it).first; + + LLSD element; + element["id"] = listName; + LLSD& friend_column = element["columns"][0]; + friend_column["column"] = "Entries"; + friend_column["value"] = listName; + //friend_column["font"] = "SANSSERIF"; + const LLSD& loc_map = (*loc_it).second; + if(loc_map["enabled"].asBoolean()) + friend_column["font"] = "SANSSERIF"; + //friend_column["style"] = "BOLD"; + else + friend_column["font"] = "SANSSERIF_SMALL"; + //friend_column["style"] = "NORMAL"; + if(namesList) + namesList->addElement(element, ADD_BOTTOM); + } + updateItemsList(); +} +void AutoReplaceFloater::updateListControlsEnabled(BOOL selected) +{ + + childSetEnabled("ac_text1",selected); + childSetEnabled("ac_text2",selected); + childSetEnabled("ac_text_name",selected); + childSetEnabled("ac_text_author",selected); + childSetEnabled("ac_list_enabled",selected); + childSetEnabled("ac_list_show",selected); + childSetEnabled("ac_list_style",selected); + childSetEnabled("ac_deletelist",selected); + childSetEnabled("ac_exportlist",selected); + childSetEnabled("ac_addentry",selected); + childSetEnabled("ac_rementry",selected); + childSetEnabled("ac_priority",selected); + +} +void AutoReplaceFloater::updateEnabledStuff() +{ + BOOL autoreplace = gSavedSettings.getBOOL("AutoReplace"); + if(autoreplace) + { + LLCheckBoxCtrl *enBox = getChild("ac_enable"); + enBox->setDisabledColor(LLColor4::red); + getChild("ac_enable")->setEnabledColor(LLColor4(1.0f,0.0f,0.0f,1.0f)); + }else + { + getChild("ac_enable")->setEnabledColor( + LLUIColorTable::instance().getColor( "LabelTextColor" )); + } + + childSetEnabled("ac_list_name", autoreplace); + childSetEnabled("ac_list_entry", autoreplace); + updateListControlsEnabled(autoreplace); + updateNamesList(); + AutoReplace::getInstance()->save(); + +} +void AutoReplaceFloater::setData(void * data) +{ +} +void AutoReplaceFloater::onBoxCommitEnabled(LLUICtrl* caller, void* user_data) +{ + if ( user_data ) + { + AutoReplaceFloater* self = ( AutoReplaceFloater* )user_data; + if ( self ) + { + self->updateEnabledStuff(); + } + } +} +void AutoReplaceFloater::onEntrySettingChange(LLUICtrl* caller, void* user_data) +{ + if ( user_data ) + { + AutoReplaceFloater* self = ( AutoReplaceFloater* )user_data; + if ( self ) + { + std::string listName= self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); + AutoReplace::getInstance()->setListEnabled(listName,self->childGetValue("ac_list_enabled").asBoolean()); + AutoReplace::getInstance()->setListAnnounceeState(listName,self->childGetValue("ac_list_show").asBoolean()); + AutoReplace::getInstance()->setListStyle(listName,self->childGetValue("ac_list_style").asBoolean()); + AutoReplace::getInstance()->setListPriority(listName,self->childGetValue("ac_priority").asInteger()); + + //sInstance->updateEnabledStuff(); + self->updateItemsList(); + AutoReplace::getInstance()->save(); + } + } +} +void AutoReplaceFloater::deleteEntry(void* data) +{ + if ( data ) + { + AutoReplaceFloater* self = ( AutoReplaceFloater* )data; + if ( self ) + { + + std::string listName=self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); + + if((self->entryList->getAllSelected().size())>0) + { + std::string wrong= self->entryList->getFirstSelected()->getColumn(0)->getValue().asString(); + AutoReplace::getInstance()->removeEntryFromList(wrong,listName); + self->updateItemsList(); + AutoReplace::getInstance()->save(); + } + } + } +} +void AutoReplaceFloater::loadList(void* data) +{ + LLFilePicker& picker = LLFilePicker::instance(); + + if(!picker.getOpenFile( LLFilePicker::FFLOAD_XML) ) + {return; + } + llifstream file; + file.open(picker.getFirstFile().c_str()); + LLSD blankllsd; + if (file.is_open()) + { + LLSDSerialize::fromXMLDocument(blankllsd, file); + } + file.close(); + gSavedSettings.setBOOL("AutoReplace",true); + AutoReplace::getInstance()->addReplacementList(blankllsd); + if ( data ) + { + AutoReplaceFloater* self = ( AutoReplaceFloater* )data; + if ( self ) + self->updateEnabledStuff(); + } +} +void AutoReplaceFloater::removeList(void* data) +{ + if ( data ) + { + AutoReplaceFloater* self = ( AutoReplaceFloater* )data; + if ( self ) + { + std::string listName= self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); + AutoReplace::getInstance()->removeReplacementList(listName); + self->updateEnabledStuff(); + } + + } +} +void AutoReplaceFloater::exportList(void *data) +{ + if ( data ) + { + AutoReplaceFloater* self = ( AutoReplaceFloater* )data; + if ( self ) + { + std::string listName=self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); + + LLFilePicker& picker = LLFilePicker::instance(); + + if(!picker.getSaveFile( LLFilePicker::FFSAVE_XML) ) + {return; + } + llofstream file; + file.open(picker.getFirstFile().c_str()); + LLSDSerialize::toPrettyXML(AutoReplace::getInstance()->exportList(listName), file); + file.close(); + } + + } +} +void AutoReplaceFloater::addEntry(void* data) +{ + if ( data ) + { + AutoReplaceFloater* self = ( AutoReplaceFloater* )data; + if ( self ) + { + std::string listName= self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); + std::string wrong = self->mOldText->getText(); + std::string right = self->mNewText->getText(); + if(wrong != "" && right != "") + { + AutoReplace::getInstance()->addEntryToList(wrong, right, listName); + self->updateItemsList(); + AutoReplace::getInstance()->save(); + } + } + } +} +AutoReplaceFloater* AutoReplaceFloater::showFloater() +{ + AutoReplaceFloater *floater = dynamic_cast(LLFloaterReg::getInstance("autoreplace")); + if(floater) + { + floater->setVisible(true); + floater->setFrontmost(true); + floater->center(); + return floater; + } + else + { + LL_WARNS("AutoReplace") << "Can't find floater!" << LL_ENDL; + return NULL; + } +} diff --git a/indra/newview/llautoreplacefloater.h b/indra/newview/llautoreplacefloater.h new file mode 100644 index 0000000000..213cf93a30 --- /dev/null +++ b/indra/newview/llautoreplacefloater.h @@ -0,0 +1,75 @@ +/** + * @file llautoreplacefloater.h + * @brief Auto Replace List floater + * @copyright Copyright (c) 2011 LordGregGreg Back + * + * $LicenseInfo:firstyear=2012&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2012, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * $/LicenseInfo$ + */ + +#ifndef AUTOREPLACEFLOATER_H +#define AUTOREPLACEFLOATER_H + +#include "llfloater.h" +#include "llmediactrl.h" +#include "llscrolllistctrl.h" +#include "lllineeditor.h" + +#include "llviewerinventory.h" +#include + +class AutoReplaceFloater : +public LLFloater +{ +public: + AutoReplaceFloater(const LLSD& key); + + /*virtual*/ BOOL postBuild(); + /*virtual*/ void onClose(bool app_quitting); + + static AutoReplaceFloater* showFloater(); + + void setData(void * data); + void updateEnabledStuff(); + void updateNamesList(); + void updateListControlsEnabled(BOOL selected); + void updateItemsList(); + + LLScrollListCtrl *namesList; + LLScrollListCtrl *entryList; + LLLineEditor* mOldText; + LLLineEditor* mNewText; + //LLPanel * empanel; +private: + //static JCInvDropTarget* mNotecardDropTarget; + static void onBoxCommitEnabled(LLUICtrl* caller, void* user_data); + static void onEntrySettingChange(LLUICtrl* caller, void* user_data); + static void onSelectName(LLUICtrl* caller, void* user_data); + //static void ResponseItemDrop(LLViewerInventoryItem* item); + //static void onNotecardLoadComplete(LLVFS *vfs,const LLUUID& asset_uuid,LLAssetType::EType type,void* user_data, S32 status, LLExtStat ext_status); + + + static void deleteEntry(void* data); + static void addEntry(void* data); + static void exportList(void* data); + static void removeList(void* data); + static void loadList(void* data); +}; + +#endif // AUTOREPLACEFLOATER_H diff --git a/indra/newview/llfloaterpreference.cpp b/indra/newview/llfloaterpreference.cpp index 9954878ae4..362904f0f8 100755 --- a/indra/newview/llfloaterpreference.cpp +++ b/indra/newview/llfloaterpreference.cpp @@ -35,7 +35,7 @@ #include "llfloaterpreference.h" #include "message.h" -#include "llautocorrectfloater.h" +#include "llautoreplacefloater.h" #include "llagent.h" #include "llavatarconstants.h" #include "llcheckboxctrl.h" @@ -355,7 +355,7 @@ LLFloaterPreference::LLFloaterPreference(const LLSD& key) gSavedSettings.getControl("NameTagShowFriends")->getCommitSignal()->connect(boost::bind(&handleNameTagOptionChanged, _2)); gSavedSettings.getControl("UseDisplayNames")->getCommitSignal()->connect(boost::bind(&handleDisplayNamesOptionChanged, _2)); - mCommitCallbackRegistrar.add("Pref.ShowAC", boost::bind(&AutoCorrectFloater::showFloater)); + mCommitCallbackRegistrar.add("Pref.ShowAC", boost::bind(&AutoReplaceFloater::showFloater)); LLAvatarPropertiesProcessor::getInstance()->addObserver( gAgent.getID(), this ); } diff --git a/indra/newview/llimfloater.cpp b/indra/newview/llimfloater.cpp index e300f6f32d..670db3773e 100644 --- a/indra/newview/llimfloater.cpp +++ b/indra/newview/llimfloater.cpp @@ -56,7 +56,7 @@ #include "llrootview.h" #include "llspeakers.h" #include "llviewerchat.h" -#include "llautocorrect.h" +#include "llautoreplace.h" LLIMFloater::LLIMFloater(const LLUUID& session_id) : LLTransientDockableFloater(NULL, true, session_id), @@ -255,8 +255,8 @@ BOOL LLIMFloater::postBuild() mInputEditor->setMaxTextLength(1023); // enable line history support for instant message bar mInputEditor->setEnableLineHistory(TRUE); - // *TODO Establish LineEditor with autocorrect callback - mInputEditor->setAutocorrectCallback(boost::bind(&AutoCorrect::autocorrectCallback, AutoCorrect::getInstance(), _1, _2)); + // *TODO Establish LineEditor with autoreplace callback + mInputEditor->setAutoreplaceCallback(boost::bind(&AutoReplace::autoreplaceCallback, AutoReplace::getInstance(), _1, _2)); LLFontGL* font = LLViewerChat::getChatFont(); mInputEditor->setFont(font); diff --git a/indra/newview/llnearbychatbar.cpp b/indra/newview/llnearbychatbar.cpp index 07516d4b4f..a3aeadbfb8 100644 --- a/indra/newview/llnearbychatbar.cpp +++ b/indra/newview/llnearbychatbar.cpp @@ -51,7 +51,7 @@ #include "lltranslate.h" #include "llresizehandle.h" -#include "llautocorrect.h" +#include "llautoreplace.h" S32 LLNearbyChatBar::sLastSpecialChatChannel = 0; @@ -88,7 +88,7 @@ BOOL LLNearbyChatBar::postBuild() { mChatBox = getChild("chat_box"); - mChatBox->setAutocorrectCallback(boost::bind(&AutoCorrect::autocorrectCallback, AutoCorrect::getInstance(), _1, _2)); + mChatBox->setAutoreplaceCallback(boost::bind(&AutoReplace::autoreplaceCallback, AutoReplace::getInstance(), _1, _2)); mChatBox->setCommitCallback(boost::bind(&LLNearbyChatBar::onChatBoxCommit, this)); mChatBox->setKeystrokeCallback(&onChatBoxKeystroke, this); mChatBox->setFocusLostCallback(boost::bind(&onChatBoxFocusLost, _1, this)); diff --git a/indra/newview/llviewerfloaterreg.cpp b/indra/newview/llviewerfloaterreg.cpp index 20face6d89..b2480a1805 100644 --- a/indra/newview/llviewerfloaterreg.cpp +++ b/indra/newview/llviewerfloaterreg.cpp @@ -30,7 +30,7 @@ #include "llfloaterreg.h" #include "llviewerfloaterreg.h" -#include "llautocorrectfloater.h" +#include "llautoreplacefloater.h" #include "llcompilequeue.h" #include "llcallfloater.h" #include "llfasttimerview.h" @@ -170,7 +170,7 @@ void LLViewerFloaterReg::registerFloaters() LLFloaterReg::add("about_land", "floater_about_land.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("appearance", "floater_my_appearance.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("auction", "floater_auction.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); - LLFloaterReg::add("settings_autocorrect", "floater_autocorrect.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); + LLFloaterReg::add("settings_autoreplace", "floater_autoreplace.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("avatar", "floater_avatar.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("avatar_picker", "floater_avatar_picker.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("avatar_textures", "floater_avatar_textures.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); diff --git a/indra/newview/llviewermenu.cpp b/indra/newview/llviewermenu.cpp index 0aafb6ea73..af3189f1b7 100644 --- a/indra/newview/llviewermenu.cpp +++ b/indra/newview/llviewermenu.cpp @@ -1982,11 +1982,11 @@ class LLAdvancedCompressImage : public view_listener_t }; -class LLAdvancedShowAutocorrectSettings : public view_listener_t +class LLAdvancedShowAutoreplaceSettings : public view_listener_t { bool handleEvent(const LLSD& userdata) { - LLFloaterReg::showInstance("settings_autocorrect", userdata); + LLFloaterReg::showInstance("settings_autoreplace", userdata); return true; } }; @@ -8291,7 +8291,7 @@ void initialize_menus() view_listener_t::addMenu(new LLAdvancedToggleShowObjectUpdates(), "Advanced.ToggleShowObjectUpdates"); view_listener_t::addMenu(new LLAdvancedCheckShowObjectUpdates(), "Advanced.CheckShowObjectUpdates"); view_listener_t::addMenu(new LLAdvancedCompressImage(), "Advanced.CompressImage"); - view_listener_t::addMenu(new LLAdvancedShowAutocorrectSettings(), "Advanced.ShowAutocorrectSettings"); + view_listener_t::addMenu(new LLAdvancedShowAutoreplaceSettings(), "Advanced.ShowAutoreplaceSettings"); view_listener_t::addMenu(new LLAdvancedShowDebugSettings(), "Advanced.ShowDebugSettings"); view_listener_t::addMenu(new LLAdvancedEnableViewAdminOptions(), "Advanced.EnableViewAdminOptions"); view_listener_t::addMenu(new LLAdvancedToggleViewAdminOptions(), "Advanced.ToggleViewAdminOptions"); diff --git a/indra/newview/skins/default/xui/en/floater_autocorrect.xml b/indra/newview/skins/default/xui/en/floater_autocorrect.xml deleted file mode 100644 index ab6e65c847..0000000000 --- a/indra/newview/skins/default/xui/en/floater_autocorrect.xml +++ /dev/null @@ -1,315 +0,0 @@ - - - - -- cgit v1.2.3 From 6d9c0fab8f2c19fa624e3c1f697ee9c7f08d9245 Mon Sep 17 00:00:00 2001 From: Oz Linden Date: Fri, 11 May 2012 14:31:45 -0400 Subject: remove author tracking, non-wordstyle option, and notifications --- .../newview/app_settings/settings_autoreplace.xml | 18 ------ indra/newview/llautoreplace.cpp | 71 ---------------------- indra/newview/llautoreplace.h | 2 - indra/newview/llautoreplacefloater.cpp | 5 -- .../skins/default/xui/en/floater_autoreplace.xml | 63 +------------------ .../newview/skins/default/xui/en/notifications.xml | 7 --- 6 files changed, 1 insertion(+), 165 deletions(-) (limited to 'indra') diff --git a/indra/newview/app_settings/settings_autoreplace.xml b/indra/newview/app_settings/settings_autoreplace.xml index 4669ba5822..790cd62a02 100644 --- a/indra/newview/app_settings/settings_autoreplace.xml +++ b/indra/newview/app_settings/settings_autoreplace.xml @@ -2,25 +2,15 @@ Custom - announce - 0 - author - You data enabled 1 priority 10 - wordStyle - 1 Abbreviations - announce - 0 - author - Wulf / TankMaster data afaic @@ -90,15 +80,9 @@ 1 priority 4 - wordStyle - 1 Spelling Corrections - announce - 0 - author - LordGregGreg / Wikipedia data Amercia @@ -8362,8 +8346,6 @@ 1 priority 5 - wordStyle - 1 diff --git a/indra/newview/llautoreplace.cpp b/indra/newview/llautoreplace.cpp index a5683e4190..fa46f53e96 100644 --- a/indra/newview/llautoreplace.cpp +++ b/indra/newview/llautoreplace.cpp @@ -137,8 +137,6 @@ LLSD AutoReplace::exportList(std::string listName) { toReturn["listName"]=listName; toReturn["data"]=mAutoReplaces[listName]["data"]; - toReturn["author"]=mAutoReplaces[listName]["author"]; - toReturn["wordStyle"]=mAutoReplaces[listName]["wordStyle"]; toReturn["priority"]=mAutoReplaces[listName]["priority"]; } return toReturn; @@ -152,9 +150,6 @@ BOOL AutoReplace::addReplacementList(LLSD newList) LLSD newPart; newPart["data"]=newList["data"]; newPart["enabled"]=TRUE; - newPart["announce"]=FALSE; - newPart["author"]=newList["author"]; - newPart["wordStyle"]=newList["wordStyle"]; newPart["priority"]=newList["priority"].asInteger(); llinfos << "adding new list with settings priority "< " << replacement.c_str() << llendl; return replacement; } @@ -353,8 +297,6 @@ std::string AutoReplace::replaceWords(std::string words) { static LLCachedControl perform_autoreplace(gSavedSettings, "AutoReplace"); if(!(perform_autoreplace))return words; - //*TODO update this function to use the "wordStyle" thing, - //but so far this function is never used, so later boost_tokenizer tokens(words, boost::char_separator(" ")); for (boost_tokenizer::iterator token_iter = tokens.begin(); token_iter != tokens.end(); ++token_iter) @@ -369,16 +311,6 @@ std::string AutoReplace::replaceWords(std::string words) if((loc_map["data"].has(currentWord))&&(loc_map["enabled"].asBoolean())) { std::string replacement = loc_map["data"][currentWord]; - if(loc_map["announce"].asBoolean()) - { - LLSD args; - //"[Before]" has been auto replaced by "[Replacement]" - // based on your [ListName] list. - args["BEFORE"] = currentWord; - args["LISTNAME"]=location; - args["REPLACEMENT"]=replacement; - LLNotificationsUtil::add("AutoReplace",args); - } lldebugs << "found a word in list " << location.c_str() << " and it will replace " << currentWord.c_str() << " => " << replacement.c_str() << llendl; int wordStart = words.find(currentWord); words.replace(wordStart,currentWord.length(),replacement); @@ -399,12 +331,9 @@ BOOL AutoReplace::addEntryToList(std::string wrong, std::string right, std::stri } else if(listName == "Custom") { - mAutoReplaces[listName]["announce"] = 0; - mAutoReplaces[listName]["author"] = "You"; mAutoReplaces[listName]["data"][wrong] = right; mAutoReplaces[listName]["enabled"] = 1; mAutoReplaces[listName]["priority"] = 10; - mAutoReplaces[listName]["wordStyle"] = 1; return TRUE; } diff --git a/indra/newview/llautoreplace.h b/indra/newview/llautoreplace.h index b11c124a62..6c531d0040 100644 --- a/indra/newview/llautoreplace.h +++ b/indra/newview/llautoreplace.h @@ -33,9 +33,7 @@ public: BOOL addReplacementList(LLSD newList); BOOL removeReplacementList(std::string listName); BOOL setListEnabled(std::string listName, BOOL enabled); - BOOL setListAnnounceeState(std::string listName, BOOL announce); BOOL setListPriority(std::string listName, int priority); - BOOL setListStyle(std::string listName, BOOL announce); std::string replaceWords(std::string words); std::string replaceWord(std::string currentWord); BOOL addEntryToList(std::string wrong, std::string right, std::string listName); diff --git a/indra/newview/llautoreplacefloater.cpp b/indra/newview/llautoreplacefloater.cpp index 01950adb37..ab299aeffe 100644 --- a/indra/newview/llautoreplacefloater.cpp +++ b/indra/newview/llautoreplacefloater.cpp @@ -131,10 +131,7 @@ void AutoReplaceFloater::updateItemsList() LLSD listData = AutoReplace::getInstance()->getAutoReplaceEntries(listName); childSetValue("ac_list_enabled",listData["enabled"].asBoolean()); - childSetValue("ac_list_style",listData["wordStyle"].asBoolean()); - childSetValue("ac_list_show",listData["announce"].asBoolean()); childSetValue("ac_text_name",listName); - childSetValue("ac_text_author",listData["author"]); childSetValue("ac_priority",listData["priority"]); LLSD autoReplaces = listData["data"]; @@ -201,7 +198,6 @@ void AutoReplaceFloater::updateListControlsEnabled(BOOL selected) childSetEnabled("ac_text1",selected); childSetEnabled("ac_text2",selected); childSetEnabled("ac_text_name",selected); - childSetEnabled("ac_text_author",selected); childSetEnabled("ac_list_enabled",selected); childSetEnabled("ac_list_show",selected); childSetEnabled("ac_list_style",selected); @@ -256,7 +252,6 @@ void AutoReplaceFloater::onEntrySettingChange(LLUICtrl* caller, void* user_data) { std::string listName= self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); AutoReplace::getInstance()->setListEnabled(listName,self->childGetValue("ac_list_enabled").asBoolean()); - AutoReplace::getInstance()->setListAnnounceeState(listName,self->childGetValue("ac_list_show").asBoolean()); AutoReplace::getInstance()->setListStyle(listName,self->childGetValue("ac_list_style").asBoolean()); AutoReplace::getInstance()->setListPriority(listName,self->childGetValue("ac_priority").asInteger()); diff --git a/indra/newview/skins/default/xui/en/floater_autoreplace.xml b/indra/newview/skins/default/xui/en/floater_autoreplace.xml index 5f53e61fa2..f68aeacb97 100644 --- a/indra/newview/skins/default/xui/en/floater_autoreplace.xml +++ b/indra/newview/skins/default/xui/en/floater_autoreplace.xml @@ -126,39 +126,6 @@ name="ac_text_name"> List Name - - Author: - - - - Author Name - - - -- cgit v1.2.3 From f509b492226a570bfc8bab0bd50b2e041679ff9f Mon Sep 17 00:00:00 2001 From: Oz Linden Date: Fri, 11 May 2012 15:31:35 -0400 Subject: missed one setListStyle --- indra/newview/llautoreplacefloater.cpp | 1 - 1 file changed, 1 deletion(-) (limited to 'indra') diff --git a/indra/newview/llautoreplacefloater.cpp b/indra/newview/llautoreplacefloater.cpp index ab299aeffe..c2d7be269b 100644 --- a/indra/newview/llautoreplacefloater.cpp +++ b/indra/newview/llautoreplacefloater.cpp @@ -252,7 +252,6 @@ void AutoReplaceFloater::onEntrySettingChange(LLUICtrl* caller, void* user_data) { std::string listName= self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); AutoReplace::getInstance()->setListEnabled(listName,self->childGetValue("ac_list_enabled").asBoolean()); - AutoReplace::getInstance()->setListStyle(listName,self->childGetValue("ac_list_style").asBoolean()); AutoReplace::getInstance()->setListPriority(listName,self->childGetValue("ac_priority").asInteger()); //sInstance->updateEnabledStuff(); -- cgit v1.2.3 From c946408519450a577a81e741091bf84e3822a4b6 Mon Sep 17 00:00:00 2001 From: Dave Parks Date: Fri, 11 May 2012 14:42:29 -0500 Subject: MAINT-586 Starting logging OpenGL version and shader level to simulator --- indra/llrender/llgl.cpp | 7 +++++-- indra/llrender/llgl.h | 3 ++- indra/newview/llviewerstats.cpp | 18 ++++++++++++++++++ 3 files changed, 25 insertions(+), 3 deletions(-) (limited to 'indra') diff --git a/indra/llrender/llgl.cpp b/indra/llrender/llgl.cpp index 013b86f32c..639d967853 100644 --- a/indra/llrender/llgl.cpp +++ b/indra/llrender/llgl.cpp @@ -558,7 +558,8 @@ bool LLGLManager::initGL() parse_gl_version( &mDriverVersionMajor, &mDriverVersionMinor, &mDriverVersionRelease, - &mDriverVersionVendorString ); + &mDriverVersionVendorString, + &mGLVersionString); mGLVersion = mDriverVersionMajor + mDriverVersionMinor * .1f; @@ -2053,7 +2054,7 @@ void LLGLManager::initGLStates() //////////////////////////////////////////////////////////////////////////////// -void parse_gl_version( S32* major, S32* minor, S32* release, std::string* vendor_specific ) +void parse_gl_version( S32* major, S32* minor, S32* release, std::string* vendor_specific, std::string* version_string ) { // GL_VERSION returns a null-terminated string with the format: // .[.] [] @@ -2069,6 +2070,8 @@ void parse_gl_version( S32* major, S32* minor, S32* release, std::string* vendor return; } + version_string->assign(version); + std::string ver_copy( version ); S32 len = (S32)strlen( version ); /* Flawfinder: ignore */ S32 i = 0; diff --git a/indra/llrender/llgl.h b/indra/llrender/llgl.h index 5a33c98708..9c3a47bd50 100644 --- a/indra/llrender/llgl.h +++ b/indra/llrender/llgl.h @@ -141,6 +141,7 @@ public: S32 mGLSLVersionMajor; S32 mGLSLVersionMinor; std::string mDriverVersionVendorString; + std::string mGLVersionString; S32 mVRAM; // VRAM in MB S32 mGLMaxVertexRange; @@ -423,7 +424,7 @@ extern LLMatrix4 gGLObliqueProjectionInverse; void init_glstates(); -void parse_gl_version( S32* major, S32* minor, S32* release, std::string* vendor_specific ); +void parse_gl_version( S32* major, S32* minor, S32* release, std::string* vendor_specific, std::string* version_string ); extern BOOL gClothRipple; extern BOOL gHeadlessClient; diff --git a/indra/newview/llviewerstats.cpp b/indra/newview/llviewerstats.cpp index c88122f22c..28dea8aa04 100644 --- a/indra/newview/llviewerstats.cpp +++ b/indra/newview/llviewerstats.cpp @@ -789,6 +789,24 @@ void send_stats() system["gpu_class"] = (S32)LLFeatureManager::getInstance()->getGPUClass(); system["gpu_vendor"] = gGLManager.mGLVendorShort; system["gpu_version"] = gGLManager.mDriverVersionVendorString; + system["opengl_version"] = gGLManager.mGLVersionString; + + S32 shader_level = 0; + if (LLPipeline::sRenderDeferred) + { + shader_level = 3; + } + else if (gPipeline.canUseWindLightShadersOnObjects()) + { + shader_level = 2; + } + else if (gPipeline.canUseVertexShaders()) + { + shader_level = 1; + } + + + system["shader_level"] = shader_level; LLSD &download = body["downloads"]; -- cgit v1.2.3 From 8fc4195ac0ab523b0940dd9a6af0c2a58b044006 Mon Sep 17 00:00:00 2001 From: Dave Parks Date: Fri, 11 May 2012 16:20:21 -0500 Subject: Fix for linux build that doesn't stomp memory randomly or break particle rendering --- indra/newview/llvopartgroup.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'indra') diff --git a/indra/newview/llvopartgroup.cpp b/indra/newview/llvopartgroup.cpp index 49356467a0..b6adc776cc 100644 --- a/indra/newview/llvopartgroup.cpp +++ b/indra/newview/llvopartgroup.cpp @@ -619,13 +619,13 @@ void LLParticlePartition::getGeometry(LLSpatialGroup* group) S32 geom_idx = (S32) facep->getGeomIndex(); - verticesp += geom_idx; - normalsp += geom_idx; - texcoordsp += geom_idx; - colorsp += geom_idx; - indicesp += facep->getIndicesStart(); + LLStrider cur_idx = indicesp + facep->getIndicesStart(); + LLStrider cur_vert = verticesp + geom_idx; + LLStrider cur_norm = normalsp + geom_idx; + LLStrider cur_tc = texcoordsp + geom_idx; + LLStrider cur_col = colorsp + geom_idx; - object->getGeometry(facep->getTEOffset(), verticesp, normalsp, texcoordsp, colorsp, indicesp); + object->getGeometry(facep->getTEOffset(), cur_vert, cur_norm, cur_tc, cur_col, cur_idx); llassert(facep->getGeomCount() == 4); llassert(facep->getIndicesCount() == 6); -- cgit v1.2.3 From cca85dea6755a90f9f6b4c3174743bb0abc4f73e Mon Sep 17 00:00:00 2001 From: Todd Stinson Date: Fri, 11 May 2012 19:39:44 -0700 Subject: EXP-1928: First pass at building the functionality to restart teleport after increasing the maturity preference level to match the intended teleport region. There are probably still some cases that are broken and bugs. --- indra/newview/llagent.cpp | 151 ++++++++++++++++++++++++++++++++++---- indra/newview/llagent.h | 31 +++++++- indra/newview/llviewermessage.cpp | 32 +++++--- 3 files changed, 185 insertions(+), 29 deletions(-) (limited to 'indra') diff --git a/indra/newview/llagent.cpp b/indra/newview/llagent.cpp index d7c39ff78d..fb217f2186 100755 --- a/indra/newview/llagent.cpp +++ b/indra/newview/llagent.cpp @@ -320,6 +320,12 @@ LLAgent::LLAgent() : mAgentAccess(new LLAgentAccess(gSavedSettings)), mCanEditParcel(false), mTeleportSourceSLURL(new LLSLURL), + mCurrentTeleportRequest(), + mFailedTeleportRequest(), + mTeleportFinishedSlot(), + mTeleportFailedSlot(), + mIsMaturityRatingChangingDuringTeleport(false), + mMaturityRatingChange(0), mTeleportState( TELEPORT_NONE ), mRegionp(NULL), @@ -406,7 +412,14 @@ void LLAgent::init() gSavedSettings.getControl("PreferredMaturity")->getValidateSignal()->connect(boost::bind(&LLAgent::validateMaturity, this, _2)); gSavedSettings.getControl("PreferredMaturity")->getSignal()->connect(boost::bind(&LLAgent::handleMaturity, this, _2)); - LLViewerParcelMgr::getInstance()->addAgentParcelChangedCallback(boost::bind(&LLAgent::parcelChangedCallback)); + if (!mTeleportFinishedSlot.connected()) + { + mTeleportFinishedSlot = LLViewerParcelMgr::getInstance()->setTeleportFinishedCallback(boost::bind(&LLAgent::handleTeleportFinished, this)); + } + if (!mTeleportFailedSlot.connected()) + { + mTeleportFailedSlot = LLViewerParcelMgr::getInstance()->setTeleportFailedCallback(boost::bind(&LLAgent::handleTeleportFailed, this)); + } mInitialized = TRUE; } @@ -417,6 +430,14 @@ void LLAgent::init() void LLAgent::cleanup() { mRegionp = NULL; + if (mTeleportFinishedSlot.connected()) + { + mTeleportFinishedSlot.disconnect(); + } + if (mTeleportFailedSlot.connected()) + { + mTeleportFailedSlot.disconnect(); + } } //----------------------------------------------------------------------------- @@ -2457,7 +2478,49 @@ int LLAgent::convertTextToMaturity(char text) return LLAgentAccess::convertTextToMaturity(text); } -bool LLAgent::sendMaturityPreferenceToServer(int preferredMaturity) +class LLMaturityPreferencesResponder : public LLHTTPClient::Responder +{ +public: + LLMaturityPreferencesResponder(LLAgent::maturity_preferences_callback_t pMaturityPreferencesCallback); + virtual ~LLMaturityPreferencesResponder(); + + virtual void result(const LLSD &pContent); + virtual void error(U32 pStatus, const std::string& pReason); + +protected: + +private: + LLAgent::maturity_preferences_callback_t mMaturityPreferencesCallback; +}; + +LLMaturityPreferencesResponder::LLMaturityPreferencesResponder(LLAgent::maturity_preferences_callback_t pMaturityPreferencesCallback) + : LLHTTPClient::Responder(), + mMaturityPreferencesCallback(pMaturityPreferencesCallback) +{ +} + +LLMaturityPreferencesResponder::~LLMaturityPreferencesResponder() +{ +} + +void LLMaturityPreferencesResponder::result(const LLSD &pContent) +{ + if (!mMaturityPreferencesCallback.empty()) + { + mMaturityPreferencesCallback(pContent); + } +} + +void LLMaturityPreferencesResponder::error(U32 pStatus, const std::string& pReason) +{ + if (!mMaturityPreferencesCallback.empty()) + { + LLSD empty; + mMaturityPreferencesCallback(empty); + } +} + +bool LLAgent::sendMaturityPreferenceToServer(int preferredMaturity, maturity_preferences_callback_t pMaturityPreferencesCallback) { if (!getRegion()) return false; @@ -2485,7 +2548,8 @@ bool LLAgent::sendMaturityPreferenceToServer(int preferredMaturity) body["access_prefs"] = access_prefs; llinfos << "Sending access prefs update to " << (access_prefs["max"].asString()) << " via capability to: " << url << llendl; - LLHTTPClient::post(url, body, new LLHTTPClient::Responder()); // Ignore response + LLHTTPClient::ResponderPtr responderPtr = LLHTTPClient::ResponderPtr(new LLMaturityPreferencesResponder(pMaturityPreferencesCallback)); + LLHTTPClient::post(url, body, responderPtr); return true; } return false; @@ -3538,6 +3602,62 @@ bool LLAgent::teleportCore(bool is_local) return true; } +void LLAgent::restartFailedTeleportRequest() +{ + // XXX stinson 05/11/2012 llassert(hasFailedTeleportRequest()); + if (hasFailedTeleportRequest()) + { + mFailedTeleportRequest->doTeleport(); + } +} + +void LLAgent::clearFailedTeleportRequest() +{ + // XXX stinson 05/11/2012 llassert(hasFailedTeleportRequest()); + if (hasFailedTeleportRequest()) + { + mFailedTeleportRequest.reset(); + } +} + +void LLAgent::setMaturityRatingChangeDuringTeleport(int pMaturityRatingChange) +{ + mIsMaturityRatingChangingDuringTeleport = true; + mMaturityRatingChange = pMaturityRatingChange; +} + +void LLAgent::handleTeleportFinished() +{ + // XXX stinson 05/11/2012 llassert(hasCurrentTeleportRequest()); + if (hasCurrentTeleportRequest()) + { + mCurrentTeleportRequest.reset(); + } + if (hasFailedTeleportRequest()) + { + clearFailedTeleportRequest(); + } + if (mIsMaturityRatingChangingDuringTeleport) + { + // notify user that the maturity preference has been changed + LLSD args; + args["RATING"] = LLViewerRegion::accessToString(mMaturityRatingChange); + LLNotificationsUtil::add("PreferredMaturityChanged", args); + mIsMaturityRatingChangingDuringTeleport = false; + } +} + +void LLAgent::handleTeleportFailed() +{ + // XXX stinson 05/11/2012 llassert(hasCurrentTeleportRequest()); + // XXX stinson 05/11/2012 llassert(!hasFailedTeleportRequest()); + if (hasCurrentTeleportRequest()) + { + mFailedTeleportRequest = mCurrentTeleportRequest; + } + mIsMaturityRatingChangingDuringTeleport = false; +} + void LLAgent::teleportRequest( const U64& region_handle, const LLVector3& pos_local, @@ -3570,9 +3690,9 @@ void LLAgent::teleportRequest( // Landmark ID = LLUUID::null means teleport home void LLAgent::teleportViaLandmark(const LLUUID& landmark_asset_id) { - llassert(mTeleportRequest == NULL); - mTeleportRequest = LLTeleportRequestPtr(new LLTeleportRequestViaLandmark(landmark_asset_id)); - mTeleportRequest->doTeleport(); + // XXX stinson 05/11/2012 llassert(!hasCurrentTeleportRequest()); + mCurrentTeleportRequest = LLTeleportRequestPtr(new LLTeleportRequestViaLandmark(landmark_asset_id)); + mCurrentTeleportRequest->doTeleport(); } void LLAgent::doTeleportViaLandmark(const LLUUID& landmark_asset_id) @@ -3592,9 +3712,9 @@ void LLAgent::doTeleportViaLandmark(const LLUUID& landmark_asset_id) void LLAgent::teleportViaLure(const LLUUID& lure_id, BOOL godlike) { - llassert(mTeleportRequest == NULL); - mTeleportRequest = LLTeleportRequestPtr(new LLTeleportRequestViaLure(lure_id, godlike)); - mTeleportRequest->doTeleport(); + // XXX stinson 05/11/2012 llassert(!hasCurrentTeleportRequest()); + mCurrentTeleportRequest = LLTeleportRequestPtr(new LLTeleportRequestViaLure(lure_id, godlike)); + mCurrentTeleportRequest->doTeleport(); } void LLAgent::doTeleportViaLure(const LLUUID& lure_id, BOOL godlike) @@ -3648,9 +3768,9 @@ void LLAgent::teleportCancel() void LLAgent::teleportViaLocation(const LLVector3d& pos_global) { - llassert(mTeleportRequest == NULL); - mTeleportRequest = LLTeleportRequestPtr(new LLTeleportRequestViaLocation(pos_global)); - mTeleportRequest->doTeleport(); + // XXX stinson 05/11/2012 llassert(!hasCurrentTeleportRequest()); + mCurrentTeleportRequest = LLTeleportRequestPtr(new LLTeleportRequestViaLocation(pos_global)); + mCurrentTeleportRequest->doTeleport(); } void LLAgent::doTeleportViaLocation(const LLVector3d& pos_global) @@ -3697,9 +3817,9 @@ void LLAgent::doTeleportViaLocation(const LLVector3d& pos_global) // Teleport to global position, but keep facing in the same direction void LLAgent::teleportViaLocationLookAt(const LLVector3d& pos_global) { - llassert(mTeleportRequest == NULL); - mTeleportRequest = LLTeleportRequestPtr(new LLTeleportRequestViaLocationLookAt(pos_global)); - mTeleportRequest->doTeleport(); + // XXX stinson 05/11/2012 llassert(!hasCurrentTeleportRequest()); + mCurrentTeleportRequest = LLTeleportRequestPtr(new LLTeleportRequestViaLocationLookAt(pos_global)); + mCurrentTeleportRequest->doTeleport(); } void LLAgent::doTeleportViaLocationLookAt(const LLVector3d& pos_global) @@ -3723,7 +3843,6 @@ void LLAgent::setTeleportState(ETeleportState state) { case TELEPORT_NONE: mbTeleportKeepsLookAt = false; - mTeleportRequest.reset(); break; case TELEPORT_MOVING: diff --git a/indra/newview/llagent.h b/indra/newview/llagent.h index 3b27d48928..07ceaf11b1 100644 --- a/indra/newview/llagent.h +++ b/indra/newview/llagent.h @@ -35,6 +35,7 @@ #include "llcoordframe.h" // for mFrameAgent #include "llvoavatardefines.h" +#include #include #include @@ -570,12 +571,32 @@ public: protected: bool teleportCore(bool is_local = false); // Stuff for all teleports; returns true if the teleport can proceed + //-------------------------------------------------------------------- + // Teleport State + //-------------------------------------------------------------------- + +public: + inline bool hasCurrentTeleportRequest() {return (mCurrentTeleportRequest != NULL);}; + inline bool hasFailedTeleportRequest() {return (mFailedTeleportRequest != NULL);}; + void restartFailedTeleportRequest(); + void clearFailedTeleportRequest(); + void setMaturityRatingChangeDuringTeleport(int pMaturityRatingChange); + private: friend class LLTeleportRequest; friend class LLTeleportRequestViaLandmark; friend class LLTeleportRequestViaLure; friend class LLTeleportRequestViaLocation; friend class LLTeleportRequestViaLocationLookAt; + + LLTeleportRequestPtr mCurrentTeleportRequest; + LLTeleportRequestPtr mFailedTeleportRequest; + boost::signals2::connection mTeleportFinishedSlot; + boost::signals2::connection mTeleportFailedSlot; + + bool mIsMaturityRatingChangingDuringTeleport; + int mMaturityRatingChange; + void teleportRequest(const U64& region_handle, const LLVector3& pos_local, // Go to a named location home bool look_at_from_camera = false); @@ -584,6 +605,9 @@ private: void doTeleportViaLocation(const LLVector3d& pos_global); // To a global location - this will probably need to be deprecated void doTeleportViaLocationLookAt(const LLVector3d& pos_global);// To a global location, preserving camera rotation + void handleTeleportFinished(); + void handleTeleportFailed(); + //-------------------------------------------------------------------- // Teleport State //-------------------------------------------------------------------- @@ -592,7 +616,6 @@ public: void setTeleportState(ETeleportState state); private: ETeleportState mTeleportState; - LLTeleportRequestPtr mTeleportRequest; //-------------------------------------------------------------------- // Teleport Message @@ -668,8 +691,10 @@ public: bool isAdult() const; void setTeen(bool teen); void setMaturity(char text); - static int convertTextToMaturity(char text); - bool sendMaturityPreferenceToServer(int preferredMaturity); // ! "U8" instead of "int"? + static int convertTextToMaturity(char text); + + typedef boost::function maturity_preferences_callback_t; + bool sendMaturityPreferenceToServer(int preferredMaturity, maturity_preferences_callback_t pMaturityPreferencesCallback = NULL); // ! "U8" instead of "int"? // Maturity callbacks for PreferredMaturity control variable void handleMaturity(const LLSD& newvalue); diff --git a/indra/newview/llviewermessage.cpp b/indra/newview/llviewermessage.cpp index 2917fee62e..3712e56f7c 100755 --- a/indra/newview/llviewermessage.cpp +++ b/indra/newview/llviewermessage.cpp @@ -5385,7 +5385,20 @@ static void process_money_balance_reply_extended(LLMessageSystem* msg) } } - +void handle_maturity_preference_change(const LLSD &pResponse, int pMaturityRatingChange) +{ + if (pResponse.isUndefined()) + { + // XXX stinson 05/11/2012 llinfos << "Maturity response ==> " << llendl; + gAgent.clearFailedTeleportRequest(); + } + else + { + // XXX stinson 05/11/2012 linfos << "Maturity response ==> '" << pResponse << "'" << llendl; + gAgent.setMaturityRatingChangeDuringTeleport(pMaturityRatingChange); + gAgent.restartFailedTeleportRequest(); + } +} bool handle_special_notification_callback(const LLSD& notification, const LLSD& response) { @@ -5396,12 +5409,11 @@ bool handle_special_notification_callback(const LLSD& notification, const LLSD& // set the preference to the maturity of the region we're calling int preferredMaturity = notification["payload"]["_region_access"].asInteger(); gSavedSettings.setU32("PreferredMaturity", preferredMaturity); - gAgent.sendMaturityPreferenceToServer(preferredMaturity); - - // notify user that the maturity preference has been changed - LLSD args; - args["RATING"] = LLViewerRegion::accessToString(preferredMaturity); - LLNotificationsUtil::add("PreferredMaturityChanged", args); + gAgent.sendMaturityPreferenceToServer(preferredMaturity, boost::bind(&handle_maturity_preference_change, _1, preferredMaturity)); + } + else + { + gAgent.clearFailedTeleportRequest(); } return false; @@ -6147,6 +6159,9 @@ void process_teleport_failed(LLMessageSystem *msg, void**) std::string big_reason; LLSD args; + // Let the interested parties know that teleport failed. + LLViewerParcelMgr::getInstance()->onTeleportFailed(); + // if we have additional alert data if (msg->has(_PREHASH_AlertInfo) && msg->getSizeFast(_PREHASH_AlertInfo, _PREHASH_Message) > 0) { @@ -6205,9 +6220,6 @@ void process_teleport_failed(LLMessageSystem *msg, void**) LLNotificationsUtil::add("CouldNotTeleportReason", args); - // Let the interested parties know that teleport failed. - LLViewerParcelMgr::getInstance()->onTeleportFailed(); - if( gAgent.getTeleportState() != LLAgent::TELEPORT_NONE ) { gAgent.setTeleportState( LLAgent::TELEPORT_NONE ); -- cgit v1.2.3 From ce17ae8a182cf8b1acd88bbbb3dceb7ff39fd0ff Mon Sep 17 00:00:00 2001 From: Oz Linden Date: Sat, 12 May 2012 07:29:25 -0400 Subject: STORM-1738: get autoreplace preferences working, clean up some coding and naming conventions --- indra/newview/CMakeLists.txt | 4 +- indra/newview/llautoreplacefloater.cpp | 377 --------------------- indra/newview/llautoreplacefloater.h | 75 ---- indra/newview/llfloaterautoreplacesettings.cpp | 367 ++++++++++++++++++++ indra/newview/llfloaterautoreplacesettings.h | 70 ++++ indra/newview/llfloaterpreference.cpp | 12 +- indra/newview/llfloaterpreference.h | 1 + indra/newview/llviewerfloaterreg.cpp | 4 +- .../skins/default/xui/en/floater_autoreplace.xml | 4 +- .../default/xui/en/panel_preferences_chat.xml | 2 +- 10 files changed, 455 insertions(+), 461 deletions(-) delete mode 100644 indra/newview/llautoreplacefloater.cpp delete mode 100644 indra/newview/llautoreplacefloater.h create mode 100644 indra/newview/llfloaterautoreplacesettings.cpp create mode 100644 indra/newview/llfloaterautoreplacesettings.h (limited to 'indra') diff --git a/indra/newview/CMakeLists.txt b/indra/newview/CMakeLists.txt index 90468ccbef..a45467324b 100644 --- a/indra/newview/CMakeLists.txt +++ b/indra/newview/CMakeLists.txt @@ -99,7 +99,6 @@ set(viewer_SOURCE_FILES llattachmentsmgr.cpp llaudiosourcevo.cpp llautoreplace.cpp - llautoreplacefloater.cpp llavataractions.cpp llavatariconctrl.cpp llavatarlist.cpp @@ -171,6 +170,7 @@ set(viewer_SOURCE_FILES llfloaterabout.cpp llfloaterbvhpreview.cpp llfloaterauction.cpp + llfloaterautoreplacesettings.cpp llfloateravatar.cpp llfloateravatarpicker.cpp llfloateravatartextures.cpp @@ -657,7 +657,6 @@ set(viewer_HEADER_FILES llattachmentsmgr.h llaudiosourcevo.h llautoreplace.h - llautoreplacefloater.h llavataractions.h llavatariconctrl.h llavatarlist.h @@ -729,6 +728,7 @@ set(viewer_HEADER_FILES llfloaterabout.h llfloaterbvhpreview.h llfloaterauction.h + llfloaterautoreplacesettings.h llfloateravatar.h llfloateravatarpicker.h llfloateravatartextures.h diff --git a/indra/newview/llautoreplacefloater.cpp b/indra/newview/llautoreplacefloater.cpp deleted file mode 100644 index c2d7be269b..0000000000 --- a/indra/newview/llautoreplacefloater.cpp +++ /dev/null @@ -1,377 +0,0 @@ -/** - * @file llautoreplacefloater.cpp - * @brief Auto Replace List floater - * - * $LicenseInfo:firstyear=2012&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2012, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * $/LicenseInfo$ - */ - -#include "llviewerprecompiledheaders.h" - -#include "llautoreplacefloater.h" - -#include "llagentdata.h" -#include "llcommandhandler.h" -#include "llfloater.h" -#include "lluictrlfactory.h" -#include "llagent.h" -#include "llpanel.h" -#include "llbutton.h" -#include "llcolorswatch.h" -#include "llcombobox.h" -#include "llview.h" -#include "llhttpclient.h" -#include "llbufferstream.h" -#include "llcheckboxctrl.h" -#include "llviewercontrol.h" - -#include "llui.h" -#include "llcontrol.h" -#include "llscrollingpanellist.h" -#include "llautoreplace.h" -#include "llfilepicker.h" -#include "llfile.h" -#include "llsdserialize.h" -//#include "llfloaterchat.h" -#include "llchat.h" -#include "llinventorymodel.h" -#include "llhost.h" -#include "llassetstorage.h" -#include "roles_constants.h" -#include "llviewertexteditor.h" -#include - -#include -#include "llfloaterreg.h" -#include "llinspecttoast.h" -#include "llnotificationhandler.h" -#include "llnotificationmanager.h" - - -AutoReplaceFloater::AutoReplaceFloater(const LLSD& key) : -LLFloater(key) -{ -} -void AutoReplaceFloater::onClose(bool app_quitting) -{ - destroy(); -} - -BOOL AutoReplaceFloater::postBuild(void) -{ - - namesList = getChild("ac_list_name"); - entryList = getChild("ac_list_entry"); - mOldText = getChild("ac_old_text"); - mNewText = getChild("ac_new_text"); - - childSetCommitCallback("ac_enable",onBoxCommitEnabled,this); - - childSetCommitCallback("ac_list_enabled",onEntrySettingChange,this); - childSetCommitCallback("ac_list_show",onEntrySettingChange,this); - childSetCommitCallback("ac_list_style",onEntrySettingChange,this); - childSetCommitCallback("ac_priority",onEntrySettingChange,this); - - - - updateEnabledStuff(); - updateNamesList(); - - - namesList->setCommitOnSelectionChange(TRUE); - childSetCommitCallback("ac_list_name", onSelectName, this); - - childSetAction("ac_deletelist",removeList,this); - childSetAction("ac_rementry",deleteEntry,this); - childSetAction("ac_exportlist",exportList,this); - childSetAction("ac_addentry",addEntry,this); - childSetAction("ac_loadlist",loadList,this); - - return true; -} - -void AutoReplaceFloater::onSelectName(LLUICtrl* ctrl, void* user_data) -{ - if ( user_data ) - { - AutoReplaceFloater* self = ( AutoReplaceFloater* )user_data; - if ( self ) - self->updateItemsList(); - } - -} -void AutoReplaceFloater::updateItemsList() -{ - entryList->deleteAllItems(); - if((namesList->getAllSelected().size())<=0) - { - - updateListControlsEnabled(FALSE); - return; - } - - updateListControlsEnabled(TRUE); - std::string listName= namesList->getFirstSelected()->getColumn(0)->getValue().asString(); - - LLSD listData = AutoReplace::getInstance()->getAutoReplaceEntries(listName); - childSetValue("ac_list_enabled",listData["enabled"].asBoolean()); - childSetValue("ac_text_name",listName); - childSetValue("ac_priority",listData["priority"]); - - LLSD autoReplaces = listData["data"]; - LLSD::map_const_iterator loc_it = autoReplaces.beginMap(); - LLSD::map_const_iterator loc_end = autoReplaces.endMap(); - for ( ; loc_it != loc_end; ++loc_it) - { - const std::string& wrong = (*loc_it).first; - const std::string& right = (*loc_it).second; - - //std::string lentry(wrong+"=>"+right); - - LLSD element; - element["id"] = wrong; - LLSD& s_column = element["columns"][0]; - s_column["column"] = "Search"; - s_column["value"] = wrong; - s_column["font"] = "SANSSERIF"; - LLSD& r_column = element["columns"][1]; - r_column["column"] = "Replace"; - r_column["value"] = right; - r_column["font"] = "SANSSERIF"; - - entryList->addElement(element, ADD_BOTTOM); - } - -} -void AutoReplaceFloater::updateNamesList() -{ - namesList->deleteAllItems(); - if(!gSavedSettings.getBOOL("AutoReplace")) - { - updateItemsList(); - return; - } - LLSD autoReplaces = AutoReplace::getInstance()->getAutoReplaces(); - LLSD::map_const_iterator loc_it = autoReplaces.beginMap(); - LLSD::map_const_iterator loc_end = autoReplaces.endMap(); - for ( ; loc_it != loc_end; ++loc_it) - { - const std::string& listName = (*loc_it).first; - - LLSD element; - element["id"] = listName; - LLSD& friend_column = element["columns"][0]; - friend_column["column"] = "Entries"; - friend_column["value"] = listName; - //friend_column["font"] = "SANSSERIF"; - const LLSD& loc_map = (*loc_it).second; - if(loc_map["enabled"].asBoolean()) - friend_column["font"] = "SANSSERIF"; - //friend_column["style"] = "BOLD"; - else - friend_column["font"] = "SANSSERIF_SMALL"; - //friend_column["style"] = "NORMAL"; - if(namesList) - namesList->addElement(element, ADD_BOTTOM); - } - updateItemsList(); -} -void AutoReplaceFloater::updateListControlsEnabled(BOOL selected) -{ - - childSetEnabled("ac_text1",selected); - childSetEnabled("ac_text2",selected); - childSetEnabled("ac_text_name",selected); - childSetEnabled("ac_list_enabled",selected); - childSetEnabled("ac_list_show",selected); - childSetEnabled("ac_list_style",selected); - childSetEnabled("ac_deletelist",selected); - childSetEnabled("ac_exportlist",selected); - childSetEnabled("ac_addentry",selected); - childSetEnabled("ac_rementry",selected); - childSetEnabled("ac_priority",selected); - -} -void AutoReplaceFloater::updateEnabledStuff() -{ - BOOL autoreplace = gSavedSettings.getBOOL("AutoReplace"); - if(autoreplace) - { - LLCheckBoxCtrl *enBox = getChild("ac_enable"); - enBox->setDisabledColor(LLColor4::red); - getChild("ac_enable")->setEnabledColor(LLColor4(1.0f,0.0f,0.0f,1.0f)); - }else - { - getChild("ac_enable")->setEnabledColor( - LLUIColorTable::instance().getColor( "LabelTextColor" )); - } - - childSetEnabled("ac_list_name", autoreplace); - childSetEnabled("ac_list_entry", autoreplace); - updateListControlsEnabled(autoreplace); - updateNamesList(); - AutoReplace::getInstance()->save(); - -} -void AutoReplaceFloater::setData(void * data) -{ -} -void AutoReplaceFloater::onBoxCommitEnabled(LLUICtrl* caller, void* user_data) -{ - if ( user_data ) - { - AutoReplaceFloater* self = ( AutoReplaceFloater* )user_data; - if ( self ) - { - self->updateEnabledStuff(); - } - } -} -void AutoReplaceFloater::onEntrySettingChange(LLUICtrl* caller, void* user_data) -{ - if ( user_data ) - { - AutoReplaceFloater* self = ( AutoReplaceFloater* )user_data; - if ( self ) - { - std::string listName= self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); - AutoReplace::getInstance()->setListEnabled(listName,self->childGetValue("ac_list_enabled").asBoolean()); - AutoReplace::getInstance()->setListPriority(listName,self->childGetValue("ac_priority").asInteger()); - - //sInstance->updateEnabledStuff(); - self->updateItemsList(); - AutoReplace::getInstance()->save(); - } - } -} -void AutoReplaceFloater::deleteEntry(void* data) -{ - if ( data ) - { - AutoReplaceFloater* self = ( AutoReplaceFloater* )data; - if ( self ) - { - - std::string listName=self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); - - if((self->entryList->getAllSelected().size())>0) - { - std::string wrong= self->entryList->getFirstSelected()->getColumn(0)->getValue().asString(); - AutoReplace::getInstance()->removeEntryFromList(wrong,listName); - self->updateItemsList(); - AutoReplace::getInstance()->save(); - } - } - } -} -void AutoReplaceFloater::loadList(void* data) -{ - LLFilePicker& picker = LLFilePicker::instance(); - - if(!picker.getOpenFile( LLFilePicker::FFLOAD_XML) ) - {return; - } - llifstream file; - file.open(picker.getFirstFile().c_str()); - LLSD blankllsd; - if (file.is_open()) - { - LLSDSerialize::fromXMLDocument(blankllsd, file); - } - file.close(); - gSavedSettings.setBOOL("AutoReplace",true); - AutoReplace::getInstance()->addReplacementList(blankllsd); - if ( data ) - { - AutoReplaceFloater* self = ( AutoReplaceFloater* )data; - if ( self ) - self->updateEnabledStuff(); - } -} -void AutoReplaceFloater::removeList(void* data) -{ - if ( data ) - { - AutoReplaceFloater* self = ( AutoReplaceFloater* )data; - if ( self ) - { - std::string listName= self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); - AutoReplace::getInstance()->removeReplacementList(listName); - self->updateEnabledStuff(); - } - - } -} -void AutoReplaceFloater::exportList(void *data) -{ - if ( data ) - { - AutoReplaceFloater* self = ( AutoReplaceFloater* )data; - if ( self ) - { - std::string listName=self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); - - LLFilePicker& picker = LLFilePicker::instance(); - - if(!picker.getSaveFile( LLFilePicker::FFSAVE_XML) ) - {return; - } - llofstream file; - file.open(picker.getFirstFile().c_str()); - LLSDSerialize::toPrettyXML(AutoReplace::getInstance()->exportList(listName), file); - file.close(); - } - - } -} -void AutoReplaceFloater::addEntry(void* data) -{ - if ( data ) - { - AutoReplaceFloater* self = ( AutoReplaceFloater* )data; - if ( self ) - { - std::string listName= self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); - std::string wrong = self->mOldText->getText(); - std::string right = self->mNewText->getText(); - if(wrong != "" && right != "") - { - AutoReplace::getInstance()->addEntryToList(wrong, right, listName); - self->updateItemsList(); - AutoReplace::getInstance()->save(); - } - } - } -} -AutoReplaceFloater* AutoReplaceFloater::showFloater() -{ - AutoReplaceFloater *floater = dynamic_cast(LLFloaterReg::getInstance("autoreplace")); - if(floater) - { - floater->setVisible(true); - floater->setFrontmost(true); - floater->center(); - return floater; - } - else - { - LL_WARNS("AutoReplace") << "Can't find floater!" << LL_ENDL; - return NULL; - } -} diff --git a/indra/newview/llautoreplacefloater.h b/indra/newview/llautoreplacefloater.h deleted file mode 100644 index 213cf93a30..0000000000 --- a/indra/newview/llautoreplacefloater.h +++ /dev/null @@ -1,75 +0,0 @@ -/** - * @file llautoreplacefloater.h - * @brief Auto Replace List floater - * @copyright Copyright (c) 2011 LordGregGreg Back - * - * $LicenseInfo:firstyear=2012&license=viewerlgpl$ - * Second Life Viewer Source Code - * Copyright (C) 2012, Linden Research, Inc. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * $/LicenseInfo$ - */ - -#ifndef AUTOREPLACEFLOATER_H -#define AUTOREPLACEFLOATER_H - -#include "llfloater.h" -#include "llmediactrl.h" -#include "llscrolllistctrl.h" -#include "lllineeditor.h" - -#include "llviewerinventory.h" -#include - -class AutoReplaceFloater : -public LLFloater -{ -public: - AutoReplaceFloater(const LLSD& key); - - /*virtual*/ BOOL postBuild(); - /*virtual*/ void onClose(bool app_quitting); - - static AutoReplaceFloater* showFloater(); - - void setData(void * data); - void updateEnabledStuff(); - void updateNamesList(); - void updateListControlsEnabled(BOOL selected); - void updateItemsList(); - - LLScrollListCtrl *namesList; - LLScrollListCtrl *entryList; - LLLineEditor* mOldText; - LLLineEditor* mNewText; - //LLPanel * empanel; -private: - //static JCInvDropTarget* mNotecardDropTarget; - static void onBoxCommitEnabled(LLUICtrl* caller, void* user_data); - static void onEntrySettingChange(LLUICtrl* caller, void* user_data); - static void onSelectName(LLUICtrl* caller, void* user_data); - //static void ResponseItemDrop(LLViewerInventoryItem* item); - //static void onNotecardLoadComplete(LLVFS *vfs,const LLUUID& asset_uuid,LLAssetType::EType type,void* user_data, S32 status, LLExtStat ext_status); - - - static void deleteEntry(void* data); - static void addEntry(void* data); - static void exportList(void* data); - static void removeList(void* data); - static void loadList(void* data); -}; - -#endif // AUTOREPLACEFLOATER_H diff --git a/indra/newview/llfloaterautoreplacesettings.cpp b/indra/newview/llfloaterautoreplacesettings.cpp new file mode 100644 index 0000000000..3dfcfba936 --- /dev/null +++ b/indra/newview/llfloaterautoreplacesettings.cpp @@ -0,0 +1,367 @@ +/** + * @file llautoreplacefloater.cpp + * @brief Auto Replace List floater + * + * $LicenseInfo:firstyear=2012&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2012, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * $/LicenseInfo$ + */ + +#include "llviewerprecompiledheaders.h" + +#include "llfloaterautoreplacesettings.h" + +#include "llagentdata.h" +#include "llcommandhandler.h" +#include "llfloater.h" +#include "lluictrlfactory.h" +#include "llagent.h" +#include "llpanel.h" +#include "llbutton.h" +#include "llcolorswatch.h" +#include "llcombobox.h" +#include "llview.h" +#include "llhttpclient.h" +#include "llbufferstream.h" +#include "llcheckboxctrl.h" +#include "llviewercontrol.h" + +#include "llui.h" +#include "llcontrol.h" +#include "llscrollingpanellist.h" +#include "llautoreplace.h" +#include "llfilepicker.h" +#include "llfile.h" +#include "llsdserialize.h" +//#include "llfloaterchat.h" +#include "llchat.h" +#include "llinventorymodel.h" +#include "llhost.h" +#include "llassetstorage.h" +#include "roles_constants.h" +#include "llviewertexteditor.h" +#include + +#include +#include "llfloaterreg.h" +#include "llinspecttoast.h" +#include "llnotificationhandler.h" +#include "llnotificationmanager.h" + + +LLFloaterAutoReplaceSettings::LLFloaterAutoReplaceSettings(const LLSD& key) + : LLFloater(key) + , namesList(NULL) + , entryList(NULL) + , mOldText(NULL) + , mNewText(NULL) +{ +} +void LLFloaterAutoReplaceSettings::onClose(bool app_quitting) +{ + destroy(); +} + +BOOL LLFloaterAutoReplaceSettings::postBuild(void) +{ + + namesList = getChild("ac_list_name"); + entryList = getChild("ac_list_entry"); + mOldText = getChild("ac_old_text"); + mNewText = getChild("ac_new_text"); + + childSetCommitCallback("ac_enable",onBoxCommitEnabled,this); + + childSetCommitCallback("ac_list_enabled",onEntrySettingChange,this); + childSetCommitCallback("ac_list_show",onEntrySettingChange,this); + childSetCommitCallback("ac_list_style",onEntrySettingChange,this); + childSetCommitCallback("ac_priority",onEntrySettingChange,this); + + updateEnabledStuff(); + updateNamesList(); + + namesList->setCommitOnSelectionChange(TRUE); + childSetCommitCallback("ac_list_name", onSelectName, this); + + childSetAction("ac_deletelist",removeList,this); + childSetAction("ac_rementry",deleteEntry,this); + childSetAction("ac_exportlist",exportList,this); + childSetAction("ac_addentry",addEntry,this); + childSetAction("ac_loadlist",loadList,this); + + return true; +} + +void LLFloaterAutoReplaceSettings::onSelectName(LLUICtrl* ctrl, void* user_data) +{ + if ( user_data ) + { + LLFloaterAutoReplaceSettings* self = ( LLFloaterAutoReplaceSettings* )user_data; + if ( self ) + { + self->updateItemsList(); + } + } +} +void LLFloaterAutoReplaceSettings::updateItemsList() +{ + entryList->deleteAllItems(); + if((namesList->getAllSelected().size())<=0) + { + updateListControlsEnabled(FALSE); + return; + } + + updateListControlsEnabled(TRUE); + std::string listName= namesList->getFirstSelected()->getColumn(0)->getValue().asString(); + + LLSD listData = AutoReplace::getInstance()->getAutoReplaceEntries(listName); + childSetValue("ac_list_enabled",listData["enabled"].asBoolean()); + childSetValue("ac_text_name",listName); + childSetValue("ac_priority",listData["priority"]); + + LLSD autoReplaces = listData["data"]; + LLSD::map_const_iterator loc_it = autoReplaces.beginMap(); + LLSD::map_const_iterator loc_end = autoReplaces.endMap(); + for ( ; loc_it != loc_end; ++loc_it) + { + const std::string& wrong = (*loc_it).first; + const std::string& right = (*loc_it).second; + + LLSD element; + element["id"] = wrong; + LLSD& s_column = element["columns"][0]; + s_column["column"] = "Search"; + s_column["value"] = wrong; + s_column["font"] = "SANSSERIF"; + LLSD& r_column = element["columns"][1]; + r_column["column"] = "Replace"; + r_column["value"] = right; + r_column["font"] = "SANSSERIF"; + + entryList->addElement(element, ADD_BOTTOM); + } + +} +void LLFloaterAutoReplaceSettings::updateNamesList() +{ + namesList->deleteAllItems(); + if(!gSavedSettings.getBOOL("AutoReplace")) + { + updateItemsList(); + return; + } + LLSD autoReplaces = AutoReplace::getInstance()->getAutoReplaces(); + LLSD::map_const_iterator loc_it = autoReplaces.beginMap(); + LLSD::map_const_iterator loc_end = autoReplaces.endMap(); + for ( ; loc_it != loc_end; ++loc_it) + { + const std::string& listName = (*loc_it).first; + + LLSD element; + element["id"] = listName; + LLSD& friend_column = element["columns"][0]; + friend_column["column"] = "Entries"; + friend_column["value"] = listName; + //friend_column["font"] = "SANSSERIF"; + const LLSD& loc_map = (*loc_it).second; + if(loc_map["enabled"].asBoolean()) + { + friend_column["font"] = "SANSSERIF"; + } + else + { + friend_column["font"] = "SANSSERIF_SMALL"; + } + if(namesList) + { + namesList->addElement(element, ADD_BOTTOM); + } + } + updateItemsList(); +} +void LLFloaterAutoReplaceSettings::updateListControlsEnabled(BOOL selected) +{ + + childSetEnabled("ac_text1",selected); + childSetEnabled("ac_text2",selected); + childSetEnabled("ac_text_name",selected); + childSetEnabled("ac_list_enabled",selected); + childSetEnabled("ac_list_show",selected); + childSetEnabled("ac_list_style",selected); + childSetEnabled("ac_deletelist",selected); + childSetEnabled("ac_exportlist",selected); + childSetEnabled("ac_addentry",selected); + childSetEnabled("ac_rementry",selected); + childSetEnabled("ac_priority",selected); + +} +void LLFloaterAutoReplaceSettings::updateEnabledStuff() +{ + BOOL autoreplace = gSavedSettings.getBOOL("AutoReplace"); + if(autoreplace) + { + LLCheckBoxCtrl *enBox = getChild("ac_enable"); + enBox->setDisabledColor(LLColor4::red); + getChild("ac_enable")->setEnabledColor(LLColor4(1.0f,0.0f,0.0f,1.0f)); + } + else + { + getChild("ac_enable")->setEnabledColor( + LLUIColorTable::instance().getColor( "LabelTextColor" )); + } + + childSetEnabled("ac_list_name", autoreplace); + childSetEnabled("ac_list_entry", autoreplace); + updateListControlsEnabled(autoreplace); + updateNamesList(); + AutoReplace::getInstance()->save(); + +} +void LLFloaterAutoReplaceSettings::setData(void * data) +{ +} +void LLFloaterAutoReplaceSettings::onBoxCommitEnabled(LLUICtrl* caller, void* user_data) +{ + if ( user_data ) + { + LLFloaterAutoReplaceSettings* self = ( LLFloaterAutoReplaceSettings* )user_data; + if ( self ) + { + self->updateEnabledStuff(); + } + } +} +void LLFloaterAutoReplaceSettings::onEntrySettingChange(LLUICtrl* caller, void* user_data) +{ + if ( user_data ) + { + LLFloaterAutoReplaceSettings* self = ( LLFloaterAutoReplaceSettings* )user_data; + if ( self ) + { + std::string listName= self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); + AutoReplace::getInstance()->setListEnabled(listName,self->childGetValue("ac_list_enabled").asBoolean()); + AutoReplace::getInstance()->setListPriority(listName,self->childGetValue("ac_priority").asInteger()); + + //sInstance->updateEnabledStuff(); + self->updateItemsList(); + AutoReplace::getInstance()->save(); + } + } +} +void LLFloaterAutoReplaceSettings::deleteEntry(void* data) +{ + if ( data ) + { + LLFloaterAutoReplaceSettings* self = ( LLFloaterAutoReplaceSettings* )data; + if ( self ) + { + + std::string listName=self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); + + if((self->entryList->getAllSelected().size())>0) + { + std::string wrong= self->entryList->getFirstSelected()->getColumn(0)->getValue().asString(); + AutoReplace::getInstance()->removeEntryFromList(wrong,listName); + self->updateItemsList(); + AutoReplace::getInstance()->save(); + } + } + } +} +void LLFloaterAutoReplaceSettings::loadList(void* data) +{ + LLFilePicker& picker = LLFilePicker::instance(); + + if(!picker.getOpenFile( LLFilePicker::FFLOAD_XML) ) + { + return; + } + llifstream file; + file.open(picker.getFirstFile().c_str()); + LLSD blankllsd; + if (file.is_open()) + { + LLSDSerialize::fromXMLDocument(blankllsd, file); + } + file.close(); + gSavedSettings.setBOOL("AutoReplace",true); + AutoReplace::getInstance()->addReplacementList(blankllsd); + if ( data ) + { + LLFloaterAutoReplaceSettings* self = ( LLFloaterAutoReplaceSettings* )data; + if ( self ) + { + self->updateEnabledStuff(); + } + } +} +void LLFloaterAutoReplaceSettings::removeList(void* data) +{ + if ( data ) + { + LLFloaterAutoReplaceSettings* self = ( LLFloaterAutoReplaceSettings* )data; + if ( self ) + { + std::string listName= self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); + AutoReplace::getInstance()->removeReplacementList(listName); + self->updateEnabledStuff(); + } + + } +} +void LLFloaterAutoReplaceSettings::exportList(void *data) +{ + if ( data ) + { + LLFloaterAutoReplaceSettings* self = ( LLFloaterAutoReplaceSettings* )data; + if ( self ) + { + std::string listName=self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); + + LLFilePicker& picker = LLFilePicker::instance(); + if(picker.getSaveFile( LLFilePicker::FFSAVE_XML) ) + { + llofstream file; + file.open(picker.getFirstFile().c_str()); + LLSDSerialize::toPrettyXML(AutoReplace::getInstance()->exportList(listName), file); + file.close(); + } + } + } +} +void LLFloaterAutoReplaceSettings::addEntry(void* data) +{ + if ( data ) + { + LLFloaterAutoReplaceSettings* self = ( LLFloaterAutoReplaceSettings* )data; + if ( self ) + { + std::string listName= self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); + std::string wrong = self->mOldText->getText(); + std::string right = self->mNewText->getText(); + if(wrong != "" && right != "") + { + AutoReplace::getInstance()->addEntryToList(wrong, right, listName); + self->updateItemsList(); + AutoReplace::getInstance()->save(); + } + } + } +} + diff --git a/indra/newview/llfloaterautoreplacesettings.h b/indra/newview/llfloaterautoreplacesettings.h new file mode 100644 index 0000000000..dd0acb613b --- /dev/null +++ b/indra/newview/llfloaterautoreplacesettings.h @@ -0,0 +1,70 @@ +/** + * @file llfloaterautoreplacesettings.h + * @brief Auto Replace List floater + * @copyright Copyright (c) 2011 LordGregGreg Back + * + * $LicenseInfo:firstyear=2012&license=viewerlgpl$ + * Second Life Viewer Source Code + * Copyright (C) 2012, Linden Research, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * $/LicenseInfo$ + */ + +#ifndef LLFLOATERAUTOREPLACESETTINGS_H +#define LLFLOATERAUTOREPLACESETTINGS_H + +#include "llfloater.h" +#include "llmediactrl.h" +#include "llscrolllistctrl.h" +#include "lllineeditor.h" + +#include "llviewerinventory.h" +#include + +class LLFloaterAutoReplaceSettings : +public LLFloater +{ +public: + LLFloaterAutoReplaceSettings(const LLSD& key); + + /*virtual*/ BOOL postBuild(); + /*virtual*/ void onClose(bool app_quitting); + + void setData(void * data); + void updateEnabledStuff(); + void updateNamesList(); + void updateListControlsEnabled(BOOL selected); + void updateItemsList(); + + LLScrollListCtrl *namesList; + LLScrollListCtrl *entryList; + LLLineEditor* mOldText; + LLLineEditor* mNewText; + +private: + + static void onBoxCommitEnabled(LLUICtrl* caller, void* user_data); + static void onEntrySettingChange(LLUICtrl* caller, void* user_data); + static void onSelectName(LLUICtrl* caller, void* user_data); + + static void deleteEntry(void* data); + static void addEntry(void* data); + static void exportList(void* data); + static void removeList(void* data); + static void loadList(void* data); +}; + +#endif // LLFLOATERAUTOREPLACESETTINGS_H diff --git a/indra/newview/llfloaterpreference.cpp b/indra/newview/llfloaterpreference.cpp index 7ef8125896..2c383f09ba 100755 --- a/indra/newview/llfloaterpreference.cpp +++ b/indra/newview/llfloaterpreference.cpp @@ -35,7 +35,7 @@ #include "llfloaterpreference.h" #include "message.h" -#include "llautoreplacefloater.h" +#include "llfloaterautoreplacesettings.h" #include "llagent.h" #include "llavatarconstants.h" #include "llcheckboxctrl.h" @@ -346,7 +346,7 @@ LLFloaterPreference::LLFloaterPreference(const LLSD& key) mCommitCallbackRegistrar.add("Pref.BlockList", boost::bind(&LLFloaterPreference::onClickBlockList, this)); mCommitCallbackRegistrar.add("Pref.Proxy", boost::bind(&LLFloaterPreference::onClickProxySettings, this)); mCommitCallbackRegistrar.add("Pref.TranslationSettings", boost::bind(&LLFloaterPreference::onClickTranslationSettings, this)); - mCommitCallbackRegistrar.add("Pref.AutoReplace.", boost::bind(&AutoReplaceFloater::showFloater, this)); + mCommitCallbackRegistrar.add("Pref.AutoReplace", boost::bind(&LLFloaterPreference::onClickAutoReplace, this)); sSkin = gSavedSettings.getString("SkinCurrent"); @@ -605,6 +605,9 @@ void LLFloaterPreference::cancel() // hide translation settings floater LLFloaterReg::hideInstance("prefs_translation"); + // hide translation settings floater + LLFloaterReg::hideInstance("prefs_autoreplace"); + // cancel hardware menu LLFloaterHardwareSettings* hardware_settings = LLFloaterReg::getTypedInstance("prefs_hardware_settings"); if (hardware_settings) @@ -1516,6 +1519,11 @@ void LLFloaterPreference::onClickTranslationSettings() LLFloaterReg::showInstance("prefs_translation"); } +void LLFloaterPreference::onClickAutoReplace() +{ + LLFloaterReg::showInstance("prefs_autoreplace"); +} + void LLFloaterPreference::onClickActionChange() { mClickActionDirty = true; diff --git a/indra/newview/llfloaterpreference.h b/indra/newview/llfloaterpreference.h index ec5994e917..0b63002345 100644 --- a/indra/newview/llfloaterpreference.h +++ b/indra/newview/llfloaterpreference.h @@ -157,6 +157,7 @@ public: void onClickBlockList(); void onClickProxySettings(); void onClickTranslationSettings(); + void onClickAutoReplace(); void applyUIColor(LLUICtrl* ctrl, const LLSD& param); void getUIColor(LLUICtrl* ctrl, const LLSD& param); diff --git a/indra/newview/llviewerfloaterreg.cpp b/indra/newview/llviewerfloaterreg.cpp index b2480a1805..d66f742a70 100644 --- a/indra/newview/llviewerfloaterreg.cpp +++ b/indra/newview/llviewerfloaterreg.cpp @@ -30,7 +30,7 @@ #include "llfloaterreg.h" #include "llviewerfloaterreg.h" -#include "llautoreplacefloater.h" +#include "llfloaterautoreplacesettings.h" #include "llcompilequeue.h" #include "llcallfloater.h" #include "llfasttimerview.h" @@ -170,7 +170,6 @@ void LLViewerFloaterReg::registerFloaters() LLFloaterReg::add("about_land", "floater_about_land.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("appearance", "floater_my_appearance.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("auction", "floater_auction.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); - LLFloaterReg::add("settings_autoreplace", "floater_autoreplace.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("avatar", "floater_avatar.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("avatar_picker", "floater_avatar_picker.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("avatar_textures", "floater_avatar_textures.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); @@ -250,6 +249,7 @@ void LLViewerFloaterReg::registerFloaters() LLFloaterReg::add("prefs_proxy", "floater_preferences_proxy.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("prefs_hardware_settings", "floater_hardware_settings.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("prefs_translation", "floater_translation_settings.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); + LLFloaterReg::add("prefs_autoreplace", "floater_autoreplace.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("perm_prefs", "floater_perm_prefs.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("picks", "floater_picks.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("pref_joystick", "floater_joystick.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); diff --git a/indra/newview/skins/default/xui/en/floater_autoreplace.xml b/indra/newview/skins/default/xui/en/floater_autoreplace.xml index f68aeacb97..17f64c1433 100644 --- a/indra/newview/skins/default/xui/en/floater_autoreplace.xml +++ b/indra/newview/skins/default/xui/en/floater_autoreplace.xml @@ -96,7 +96,7 @@ -- cgit v1.2.3 From 0f5d636a1a45500fc49cc713e6f93160c4fafe0b Mon Sep 17 00:00:00 2001 From: Oz Linden Date: Sat, 12 May 2012 07:51:38 -0400 Subject: STORM-1738: remove unimplemented notecard target from autoreplace settings floater --- .../skins/default/xui/en/floater_autoreplace.xml | 21 --------------------- 1 file changed, 21 deletions(-) (limited to 'indra') diff --git a/indra/newview/skins/default/xui/en/floater_autoreplace.xml b/indra/newview/skins/default/xui/en/floater_autoreplace.xml index 17f64c1433..5baae4f0d4 100644 --- a/indra/newview/skins/default/xui/en/floater_autoreplace.xml +++ b/indra/newview/skins/default/xui/en/floater_autoreplace.xml @@ -38,27 +38,6 @@ name="ac_loadlist" label="Load List.." tool_tip="Click this to load a previously exported list from a file."/> - - - - Date: Sat, 12 May 2012 12:59:07 -0400 Subject: STORM-1738: fix class name and other coding standards issues --- indra/newview/llautoreplace.cpp | 107 ++++++++++++++++--------- indra/newview/llautoreplace.h | 18 ++--- indra/newview/llfloaterautoreplacesettings.cpp | 26 +++--- indra/newview/llimfloater.cpp | 2 +- indra/newview/llnearbychatbar.cpp | 2 +- 5 files changed, 90 insertions(+), 65 deletions(-) (limited to 'indra') diff --git a/indra/newview/llautoreplace.cpp b/indra/newview/llautoreplace.cpp index fa46f53e96..10005aee9f 100644 --- a/indra/newview/llautoreplace.cpp +++ b/indra/newview/llautoreplace.cpp @@ -30,20 +30,20 @@ #include "llviewercontrol.h" #include "llnotificationsutil.h" -AutoReplace* AutoReplace::sInstance; +LLAutoReplace* LLAutoReplace::sInstance; -AutoReplace::AutoReplace() +LLAutoReplace::LLAutoReplace() { sInstance = this; sInstance->loadFromDisk(); } -AutoReplace::~AutoReplace() +LLAutoReplace::~LLAutoReplace() { sInstance = NULL; } -void AutoReplace::autoreplaceCallback(LLUIString& inputText, S32& cursorPos) +void LLAutoReplace::autoreplaceCallback(LLUIString& inputText, S32& cursorPos) { static LLCachedControl perform_autoreplace(gSavedSettings, "AutoReplace"); if(perform_autoreplace) @@ -52,16 +52,22 @@ void AutoReplace::autoreplaceCallback(LLUIString& inputText, S32& cursorPos) S32 wordEnd = cursorPos-1; if(wordEnd < 1) + { return; - + } + LLWString text = inputText.getWString(); if(text.size()<1) + { return; - + } + if(LLWStringUtil::isPartOfWord(text[wordEnd])) + { return;//we only check on word breaks - + } + wordEnd--; if(LLWStringUtil::isPartOfWord(text[wordEnd])) @@ -80,11 +86,11 @@ void AutoReplace::autoreplaceCallback(LLUIString& inputText, S32& cursorPos) std::string strLastWord = std::string(text.begin(), text.end()); std::string lastTypedWord = strLastWord.substr(wordStart, wordEnd-wordStart); - std::string replaceedWord(replaceWord(lastTypedWord)); + std::string replacedWord(replaceWord(lastTypedWord)); - if(replaceedWord != lastTypedWord) + if(replacedWord != lastTypedWord) { - LLWString strNew = utf8str_to_wstring(replaceedWord); + LLWString strNew = utf8str_to_wstring(replacedWord); LLWString strOld = utf8str_to_wstring(lastTypedWord); int nDiff = strNew.size() - strOld.size(); @@ -97,20 +103,21 @@ void AutoReplace::autoreplaceCallback(LLUIString& inputText, S32& cursorPos) } } -AutoReplace* AutoReplace::getInstance() +LLAutoReplace* LLAutoReplace::getInstance() { - if(sInstance)return sInstance; - else + if(!sInstance) { - sInstance = new AutoReplace(); - return sInstance; + sInstance = new LLAutoReplace(); } + return sInstance; } -void AutoReplace::save() + +void LLAutoReplace::save() { saveToDisk(mAutoReplaces); } -std::string AutoReplace::getFileName() + +std::string LLAutoReplace::getFileName() { std::string path=gDirUtilp->getExpandedFilename(LL_PATH_USER_SETTINGS, ""); @@ -120,7 +127,8 @@ std::string AutoReplace::getFileName() } return path; } -std::string AutoReplace::getDefaultFileName() + +std::string LLAutoReplace::getDefaultFileName() { std::string path=gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, ""); @@ -130,7 +138,8 @@ std::string AutoReplace::getDefaultFileName() } return path; } -LLSD AutoReplace::exportList(std::string listName) + +LLSD LLAutoReplace::exportList(std::string listName) { LLSD toReturn; if(mAutoReplaces.has(listName)) @@ -141,12 +150,12 @@ LLSD AutoReplace::exportList(std::string listName) } return toReturn; } -BOOL AutoReplace::addReplacementList(LLSD newList) + +BOOL LLAutoReplace::addReplacementList(LLSD newList) { if(newList.has("listName")) { std::string name = newList["listName"]; - //if(!mAutoReplaces.has(name)){ LLSD newPart; newPart["data"]=newList["data"]; newPart["enabled"]=TRUE; @@ -155,11 +164,11 @@ BOOL AutoReplace::addReplacementList(LLSD newList) mAutoReplaces[name]=newPart; return TRUE; - } return FALSE; } -BOOL AutoReplace::removeReplacementList(std::string listName) + +BOOL LLAutoReplace::removeReplacementList(std::string listName) { if(mAutoReplaces.has(listName)) { @@ -168,7 +177,8 @@ BOOL AutoReplace::removeReplacementList(std::string listName) } return FALSE; } -BOOL AutoReplace::setListEnabled(std::string listName, BOOL enabled) + +BOOL LLAutoReplace::setListEnabled(std::string listName, BOOL enabled) { if(mAutoReplaces.has(listName)) { @@ -178,7 +188,8 @@ BOOL AutoReplace::setListEnabled(std::string listName, BOOL enabled) return FALSE; } -BOOL AutoReplace::setListPriority(std::string listName, int priority) + +BOOL LLAutoReplace::setListPriority(std::string listName, int priority) { if(mAutoReplaces.has(listName)) { @@ -187,11 +198,13 @@ BOOL AutoReplace::setListPriority(std::string listName, int priority) } return FALSE; } -LLSD AutoReplace::getAutoReplaces() + +LLSD LLAutoReplace::getAutoReplaces() { return mAutoReplaces; } -void AutoReplace::loadFromDisk() + +void LLAutoReplace::loadFromDisk() { std::string filename=getFileName(); if (filename.empty()) @@ -214,8 +227,11 @@ void AutoReplace::loadFromDisk() } file.close(); saveToDisk(blankllsd); - }else - saveToDisk(getExampleLLSD()); + } + else + { + saveToDisk(getExampleLLSD()); + } } else { @@ -228,7 +244,8 @@ void AutoReplace::loadFromDisk() file.close(); } } -void AutoReplace::saveToDisk(LLSD newSettings) + +void LLAutoReplace::saveToDisk(LLSD newSettings) { mAutoReplaces=newSettings; std::string filename=getFileName(); @@ -237,7 +254,8 @@ void AutoReplace::saveToDisk(LLSD newSettings) LLSDSerialize::toPrettyXML(mAutoReplaces, file); file.close(); } -void AutoReplace::runTest() + +void LLAutoReplace::runTest() { std::string startS("He just abandonned all his abilties"); std::string endS = replaceWords(startS); @@ -245,7 +263,8 @@ void AutoReplace::runTest() } -BOOL AutoReplace::saveListToDisk(std::string listName, std::string fileName) + +BOOL LLAutoReplace::saveListToDisk(std::string listName, std::string fileName) { if(mAutoReplaces.has(listName)) { @@ -257,7 +276,8 @@ BOOL AutoReplace::saveListToDisk(std::string listName, std::string fileName) } return FALSE; } -LLSD AutoReplace::getAutoReplaceEntries(std::string listName) + +LLSD LLAutoReplace::getAutoReplaceEntries(std::string listName) { LLSD toReturn; if(mAutoReplaces.has(listName)) @@ -266,7 +286,8 @@ LLSD AutoReplace::getAutoReplaceEntries(std::string listName) } return toReturn; } -std::string AutoReplace::replaceWord(std::string currentWord) + +std::string LLAutoReplace::replaceWord(std::string currentWord) { static LLCachedControl perform_autoreplace(gSavedSettings, "AutoReplace"); if(!(perform_autoreplace))return currentWord; @@ -293,11 +314,15 @@ std::string AutoReplace::replaceWord(std::string currentWord) } return currentWord; } -std::string AutoReplace::replaceWords(std::string words) + +std::string LLAutoReplace::replaceWords(std::string words) { static LLCachedControl perform_autoreplace(gSavedSettings, "AutoReplace"); - if(!(perform_autoreplace))return words; - + if(!(perform_autoreplace)) + { + return words; + } + boost_tokenizer tokens(words, boost::char_separator(" ")); for (boost_tokenizer::iterator token_iter = tokens.begin(); token_iter != tokens.end(); ++token_iter) { @@ -320,7 +345,8 @@ std::string AutoReplace::replaceWords(std::string words) } return words; } -BOOL AutoReplace::addEntryToList(std::string wrong, std::string right, std::string listName) + +BOOL LLAutoReplace::addEntryToList(std::string wrong, std::string right, std::string listName) { // *HACK: Make sure the "Custom" list exists, because the design of this // system prevents us from updating it by changing the original file... @@ -339,7 +365,8 @@ BOOL AutoReplace::addEntryToList(std::string wrong, std::string right, std::stri return FALSE; } -BOOL AutoReplace::removeEntryFromList(std::string wrong, std::string listName) + +BOOL LLAutoReplace::removeEntryFromList(std::string wrong, std::string listName) { if(mAutoReplaces.has(listName)) { @@ -352,7 +379,7 @@ BOOL AutoReplace::removeEntryFromList(std::string wrong, std::string listName) return FALSE; } -LLSD AutoReplace::getExampleLLSD() +LLSD LLAutoReplace::getExampleLLSD() { LLSD toReturn; diff --git a/indra/newview/llautoreplace.h b/indra/newview/llautoreplace.h index 6c531d0040..27533c4ef1 100644 --- a/indra/newview/llautoreplace.h +++ b/indra/newview/llautoreplace.h @@ -17,19 +17,19 @@ * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ -#ifndef AUTO_REPLACE -#define AUTO_REPLACE +#ifndef LLAUTOREPLACE_H +#define LLAUTOREPLACE_H #include "lllineeditor.h" -class AutoReplace : public LLSingleton +class LLAutoReplace : public LLSingleton { - AutoReplace(); - ~AutoReplace(); - static AutoReplace* sInstance; + LLAutoReplace(); + ~LLAutoReplace(); + static LLAutoReplace* sInstance; public: void autoreplaceCallback(LLUIString& inputText, S32& cursorPos); - static AutoReplace* getInstance(); + static LLAutoReplace* getInstance(); BOOL addReplacementList(LLSD newList); BOOL removeReplacementList(std::string listName); BOOL setListEnabled(std::string listName, BOOL enabled); @@ -48,7 +48,7 @@ public: void loadFromDisk(); private: - friend class LLSingleton; + friend class LLSingleton; void saveToDisk(LLSD newSettings); LLSD getExampleLLSD(); std::string getFileName(); @@ -58,6 +58,4 @@ private: }; - - #endif diff --git a/indra/newview/llfloaterautoreplacesettings.cpp b/indra/newview/llfloaterautoreplacesettings.cpp index 3dfcfba936..1a52e5d493 100644 --- a/indra/newview/llfloaterautoreplacesettings.cpp +++ b/indra/newview/llfloaterautoreplacesettings.cpp @@ -130,7 +130,7 @@ void LLFloaterAutoReplaceSettings::updateItemsList() updateListControlsEnabled(TRUE); std::string listName= namesList->getFirstSelected()->getColumn(0)->getValue().asString(); - LLSD listData = AutoReplace::getInstance()->getAutoReplaceEntries(listName); + LLSD listData = LLAutoReplace::getInstance()->getAutoReplaceEntries(listName); childSetValue("ac_list_enabled",listData["enabled"].asBoolean()); childSetValue("ac_text_name",listName); childSetValue("ac_priority",listData["priority"]); @@ -166,7 +166,7 @@ void LLFloaterAutoReplaceSettings::updateNamesList() updateItemsList(); return; } - LLSD autoReplaces = AutoReplace::getInstance()->getAutoReplaces(); + LLSD autoReplaces = LLAutoReplace::getInstance()->getAutoReplaces(); LLSD::map_const_iterator loc_it = autoReplaces.beginMap(); LLSD::map_const_iterator loc_end = autoReplaces.endMap(); for ( ; loc_it != loc_end; ++loc_it) @@ -230,7 +230,7 @@ void LLFloaterAutoReplaceSettings::updateEnabledStuff() childSetEnabled("ac_list_entry", autoreplace); updateListControlsEnabled(autoreplace); updateNamesList(); - AutoReplace::getInstance()->save(); + LLAutoReplace::getInstance()->save(); } void LLFloaterAutoReplaceSettings::setData(void * data) @@ -255,12 +255,12 @@ void LLFloaterAutoReplaceSettings::onEntrySettingChange(LLUICtrl* caller, void* if ( self ) { std::string listName= self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); - AutoReplace::getInstance()->setListEnabled(listName,self->childGetValue("ac_list_enabled").asBoolean()); - AutoReplace::getInstance()->setListPriority(listName,self->childGetValue("ac_priority").asInteger()); + LLAutoReplace::getInstance()->setListEnabled(listName,self->childGetValue("ac_list_enabled").asBoolean()); + LLAutoReplace::getInstance()->setListPriority(listName,self->childGetValue("ac_priority").asInteger()); //sInstance->updateEnabledStuff(); self->updateItemsList(); - AutoReplace::getInstance()->save(); + LLAutoReplace::getInstance()->save(); } } } @@ -277,9 +277,9 @@ void LLFloaterAutoReplaceSettings::deleteEntry(void* data) if((self->entryList->getAllSelected().size())>0) { std::string wrong= self->entryList->getFirstSelected()->getColumn(0)->getValue().asString(); - AutoReplace::getInstance()->removeEntryFromList(wrong,listName); + LLAutoReplace::getInstance()->removeEntryFromList(wrong,listName); self->updateItemsList(); - AutoReplace::getInstance()->save(); + LLAutoReplace::getInstance()->save(); } } } @@ -301,7 +301,7 @@ void LLFloaterAutoReplaceSettings::loadList(void* data) } file.close(); gSavedSettings.setBOOL("AutoReplace",true); - AutoReplace::getInstance()->addReplacementList(blankllsd); + LLAutoReplace::getInstance()->addReplacementList(blankllsd); if ( data ) { LLFloaterAutoReplaceSettings* self = ( LLFloaterAutoReplaceSettings* )data; @@ -319,7 +319,7 @@ void LLFloaterAutoReplaceSettings::removeList(void* data) if ( self ) { std::string listName= self->namesList->getFirstSelected()->getColumn(0)->getValue().asString(); - AutoReplace::getInstance()->removeReplacementList(listName); + LLAutoReplace::getInstance()->removeReplacementList(listName); self->updateEnabledStuff(); } @@ -339,7 +339,7 @@ void LLFloaterAutoReplaceSettings::exportList(void *data) { llofstream file; file.open(picker.getFirstFile().c_str()); - LLSDSerialize::toPrettyXML(AutoReplace::getInstance()->exportList(listName), file); + LLSDSerialize::toPrettyXML(LLAutoReplace::getInstance()->exportList(listName), file); file.close(); } } @@ -357,9 +357,9 @@ void LLFloaterAutoReplaceSettings::addEntry(void* data) std::string right = self->mNewText->getText(); if(wrong != "" && right != "") { - AutoReplace::getInstance()->addEntryToList(wrong, right, listName); + LLAutoReplace::getInstance()->addEntryToList(wrong, right, listName); self->updateItemsList(); - AutoReplace::getInstance()->save(); + LLAutoReplace::getInstance()->save(); } } } diff --git a/indra/newview/llimfloater.cpp b/indra/newview/llimfloater.cpp index 670db3773e..63eedcdfea 100644 --- a/indra/newview/llimfloater.cpp +++ b/indra/newview/llimfloater.cpp @@ -256,7 +256,7 @@ BOOL LLIMFloater::postBuild() // enable line history support for instant message bar mInputEditor->setEnableLineHistory(TRUE); // *TODO Establish LineEditor with autoreplace callback - mInputEditor->setAutoreplaceCallback(boost::bind(&AutoReplace::autoreplaceCallback, AutoReplace::getInstance(), _1, _2)); + mInputEditor->setAutoreplaceCallback(boost::bind(&LLAutoReplace::autoreplaceCallback, LLAutoReplace::getInstance(), _1, _2)); LLFontGL* font = LLViewerChat::getChatFont(); mInputEditor->setFont(font); diff --git a/indra/newview/llnearbychatbar.cpp b/indra/newview/llnearbychatbar.cpp index a3aeadbfb8..2a1d3b9fc5 100644 --- a/indra/newview/llnearbychatbar.cpp +++ b/indra/newview/llnearbychatbar.cpp @@ -88,7 +88,7 @@ BOOL LLNearbyChatBar::postBuild() { mChatBox = getChild("chat_box"); - mChatBox->setAutoreplaceCallback(boost::bind(&AutoReplace::autoreplaceCallback, AutoReplace::getInstance(), _1, _2)); + mChatBox->setAutoreplaceCallback(boost::bind(&LLAutoReplace::autoreplaceCallback, LLAutoReplace::getInstance(), _1, _2)); mChatBox->setCommitCallback(boost::bind(&LLNearbyChatBar::onChatBoxCommit, this)); mChatBox->setKeystrokeCallback(&onChatBoxKeystroke, this); mChatBox->setFocusLostCallback(boost::bind(&onChatBoxFocusLost, _1, this)); -- cgit v1.2.3 From 502e89971f8cf22c49e9c42c38f0aee54a0654c5 Mon Sep 17 00:00:00 2001 From: Jonathan Yap Date: Mon, 14 May 2012 13:20:06 -0400 Subject: STORM-1812 Tweak how music is restarted for teleport within a parcel --- indra/newview/llpanelnearbymedia.cpp | 2 +- indra/newview/llvieweraudio.cpp | 2 +- indra/newview/llviewerparcelmgr.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) (limited to 'indra') diff --git a/indra/newview/llpanelnearbymedia.cpp b/indra/newview/llpanelnearbymedia.cpp index c01adc3c35..a50d9074f7 100644 --- a/indra/newview/llpanelnearbymedia.cpp +++ b/indra/newview/llpanelnearbymedia.cpp @@ -176,7 +176,7 @@ void LLPanelNearByMedia::handleMediaAutoPlayChanged(const LLSD& newvalue) { // update mParcelAudioAutoStart if AUTO_PLAY_MEDIA_SETTING changes mParcelAudioAutoStart = gSavedSettings.getBOOL(LLViewerMedia::AUTO_PLAY_MEDIA_SETTING) && - gSavedSettings.getBOOL("MediaTentativeAutoPlay"); + gSavedSettings.getBOOL("MediaTentativeAutoPlay"); } /*virtual*/ diff --git a/indra/newview/llvieweraudio.cpp b/indra/newview/llvieweraudio.cpp index 0114c292dc..c04e6eeb5c 100644 --- a/indra/newview/llvieweraudio.cpp +++ b/indra/newview/llvieweraudio.cpp @@ -268,7 +268,7 @@ void LLViewerAudio::onTeleportFinished(const LLVector3d& pos, const bool& local) LLParcel* parcel = LLViewerParcelMgr::getInstance()->getAgentParcel(); if (parcel) { - LLViewerParcelMgr::optionally_start_music(parcel->getMusicURL()); + mNextStreamURI = parcel->getMusicURL(); } } } diff --git a/indra/newview/llviewerparcelmgr.cpp b/indra/newview/llviewerparcelmgr.cpp index a89fafdc62..ae9c31bfe7 100644 --- a/indra/newview/llviewerparcelmgr.cpp +++ b/indra/newview/llviewerparcelmgr.cpp @@ -1778,7 +1778,7 @@ void LLViewerParcelMgr::optionally_start_music(const std::string& music_url) { // only play music when you enter a new parcel if the UI control for this // was not *explicitly* stopped by the user. (part of SL-4878) - LLPanelNearByMedia* nearby_media_panel = gStatusBar->getNearbyMediaPanel();; + LLPanelNearByMedia* nearby_media_panel = gStatusBar->getNearbyMediaPanel(); if ((nearby_media_panel && nearby_media_panel->getParcelAudioAutoStart()) || // or they have expressed no opinion in the UI, but have autoplay on... -- cgit v1.2.3 From c4dfdcb338aaeeb4e3adc4e1aef4f5b190ef5c57 Mon Sep 17 00:00:00 2001 From: "Brad Payne (Vir Linden)" Date: Mon, 14 May 2012 18:02:53 -0400 Subject: partial fix for SH-3132 - reduce max concurrent http requests to same level as in release --- indra/newview/lltexturefetch.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/newview/lltexturefetch.cpp b/indra/newview/lltexturefetch.cpp index efb6ed6079..e2af497a7d 100755 --- a/indra/newview/lltexturefetch.cpp +++ b/indra/newview/lltexturefetch.cpp @@ -1161,7 +1161,7 @@ bool LLTextureFetchWorker::doWork(S32 param) //1, not openning too many file descriptors at the same time; //2, control the traffic of http so udp gets bandwidth. // - static const S32 MAX_NUM_OF_HTTP_REQUESTS_IN_QUEUE = 24 ; + static const S32 MAX_NUM_OF_HTTP_REQUESTS_IN_QUEUE = 8 ; if(mFetcher->getNumHTTPRequests() > MAX_NUM_OF_HTTP_REQUESTS_IN_QUEUE) { return false ; //wait. -- cgit v1.2.3 From 34e7226ac88e14d4cfed6bc0d63da215afe0ac88 Mon Sep 17 00:00:00 2001 From: Kitty Barnett Date: Tue, 15 May 2012 13:13:44 +0200 Subject: STORM-276 FIXED Squiggles overflow line editor height when font size is set to large - Also reduced squiggle width from 6 to 4 and prevented running past the end of a word --- indra/llrender/llfontgl.cpp | 10 ++++++++++ indra/llrender/llfontgl.h | 2 ++ indra/llui/lllineeditor.cpp | 15 +++++++++++---- indra/llui/lltextbase.cpp | 11 +++++++---- 4 files changed, 30 insertions(+), 8 deletions(-) (limited to 'indra') diff --git a/indra/llrender/llfontgl.cpp b/indra/llrender/llfontgl.cpp index fccbf37a8d..4dc2fcd714 100644 --- a/indra/llrender/llfontgl.cpp +++ b/indra/llrender/llfontgl.cpp @@ -422,6 +422,16 @@ S32 LLFontGL::renderUTF8(const std::string &text, S32 begin_offset, S32 x, S32 y } // font metrics - override for LLFontFreetype that returns units of virtual pixels +F32 LLFontGL::getAscenderHeight() const +{ + return mFontFreetype->getAscenderHeight() / sScaleY; +} + +F32 LLFontGL::getDescenderHeight() const +{ + return mFontFreetype->getDescenderHeight() / sScaleY; +} + S32 LLFontGL::getLineHeight() const { return llceil(mFontFreetype->getAscenderHeight() / sScaleY) + llceil(mFontFreetype->getDescenderHeight() / sScaleY); diff --git a/indra/llrender/llfontgl.h b/indra/llrender/llfontgl.h index 74bdbb43e7..5ed5d2c4eb 100644 --- a/indra/llrender/llfontgl.h +++ b/indra/llrender/llfontgl.h @@ -115,6 +115,8 @@ public: S32 renderUTF8(const std::string &text, S32 begin_offset, S32 x, S32 y, const LLColor4 &color, HAlign halign, VAlign valign, U8 style = NORMAL, ShadowType shadow = NO_SHADOW) const; // font metrics - override for LLFontFreetype that returns units of virtual pixels + F32 getAscenderHeight() const; + F32 getDescenderHeight() const; S32 getLineHeight() const; S32 getWidth(const std::string& utf8text) const; diff --git a/indra/llui/lllineeditor.cpp b/indra/llui/lllineeditor.cpp index f119b0d9bc..d87b9d930c 100644 --- a/indra/llui/lllineeditor.cpp +++ b/indra/llui/lllineeditor.cpp @@ -1727,6 +1727,10 @@ void LLLineEditor::draw() background.stretch( -mBorderThickness ); S32 lineeditor_v_pad = (background.getHeight() - mGLFont->getLineHeight()) / 2; + if (mSpellCheck) + { + lineeditor_v_pad += 1; + } drawBackground(); @@ -1945,12 +1949,15 @@ void LLLineEditor::draw() if (pxEnd > pxWidth) pxEnd = pxWidth; + S32 pxBottom = (S32)(text_bottom + mGLFont->getDescenderHeight()); + gGL.color4ub(255, 0, 0, 200); - while (pxStart < pxEnd) + while (pxStart + 1 < pxEnd) { - gl_line_2d(pxStart, (S32)text_bottom - 2, pxStart + 3, (S32)text_bottom + 1); - gl_line_2d(pxStart + 3, (S32)text_bottom + 1, pxStart + 6, (S32)text_bottom - 2); - pxStart += 6; + gl_line_2d(pxStart, pxBottom, pxStart + 2, pxBottom - 2); + if (pxStart + 3 < pxEnd) + gl_line_2d(pxStart + 2, pxBottom - 3, pxStart + 4, pxBottom - 1); + pxStart += 4; } } } diff --git a/indra/llui/lltextbase.cpp b/indra/llui/lltextbase.cpp index 990c442b73..4db1efdd20 100644 --- a/indra/llui/lltextbase.cpp +++ b/indra/llui/lltextbase.cpp @@ -688,12 +688,15 @@ void LLTextBase::drawText() squiggle_start += squiggle_end / 2 - pony * 3; squiggle_end = squiggle_start + pony * 6; + S32 squiggle_bottom = text_rect.mBottom + (S32)cur_segment->getStyle()->getFont()->getDescenderHeight(); + gGL.color4ub(255, 0, 0, 200); - while (squiggle_start < squiggle_end) + while (squiggle_start + 1 < squiggle_end) { - gl_line_2d(squiggle_start, text_rect.mBottom - 2, squiggle_start + 3, text_rect.mBottom + 1); - gl_line_2d(squiggle_start + 3, text_rect.mBottom + 1, squiggle_start + 6, text_rect.mBottom - 2); - squiggle_start += 6; + gl_line_2d(squiggle_start, squiggle_bottom, squiggle_start + 2, squiggle_bottom - 2); + if (squiggle_start + 3 < squiggle_end) + gl_line_2d(squiggle_start + 2, squiggle_bottom - 3, squiggle_start + 4, squiggle_bottom - 1); + squiggle_start += 4; } if (misspell_it->second > seg_end) -- cgit v1.2.3 From 8199cc997aeaccc72b5bd5389ded8afc7b9c379c Mon Sep 17 00:00:00 2001 From: Kitty Barnett Date: Tue, 15 May 2012 14:09:13 +0200 Subject: STORM-276 FIXED Right-to-left line editor selection becomes invisible if the cursor moves --- indra/llui/lllineeditor.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'indra') diff --git a/indra/llui/lllineeditor.cpp b/indra/llui/lllineeditor.cpp index d87b9d930c..83527ae5ad 100644 --- a/indra/llui/lllineeditor.cpp +++ b/indra/llui/lllineeditor.cpp @@ -1805,14 +1805,14 @@ void LLLineEditor::draw() { S32 select_left; S32 select_right; - if( mSelectionStart < getCursor() ) + if (mSelectionStart < mSelectionEnd) { select_left = mSelectionStart; - select_right = getCursor(); + select_right = mSelectionEnd; } else { - select_left = getCursor(); + select_left = mSelectionEnd; select_right = mSelectionStart; } -- cgit v1.2.3 From 89b0b6ac7198653d989dea78ee1c3d3f4f61161f Mon Sep 17 00:00:00 2001 From: Dave Parks Date: Tue, 15 May 2012 16:42:04 -0500 Subject: MAINT-616 Different VBO Pooling scheme -- populate VBO pool with buffers that are likely to be requested, but never reuse a previously used buffer. --- indra/llrender/llvertexbuffer.cpp | 79 +++- indra/llrender/llvertexbuffer.h | 16 +- indra/newview/llvovolume.cpp | 755 ++++++++++++++++++++------------------ indra/newview/pipeline.cpp | 7 + 4 files changed, 486 insertions(+), 371 deletions(-) (limited to 'indra') diff --git a/indra/llrender/llvertexbuffer.cpp b/indra/llrender/llvertexbuffer.cpp index 1b179bdbb1..7b12304967 100644 --- a/indra/llrender/llvertexbuffer.cpp +++ b/indra/llrender/llvertexbuffer.cpp @@ -38,7 +38,7 @@ #include "llglslshader.h" #include "llmemory.h" -#define LL_VBO_POOLING 0 +#define LL_VBO_POOLING 1 //Next Highest Power Of Two //helper function, returns first number > v that is a power of 2, or v if v is already a power of 2 @@ -67,6 +67,7 @@ U32 wpo2(U32 i) const U32 LL_VBO_BLOCK_SIZE = 2048; +const U32 LL_VBO_POOL_MAX_SEED_SIZE = 256*1024; U32 vbo_block_size(U32 size) { //what block size will fit size? @@ -79,6 +80,7 @@ U32 vbo_block_index(U32 size) return vbo_block_size(size)/LL_VBO_BLOCK_SIZE; } +const U32 LL_VBO_POOL_SEED_COUNT = vbo_block_index(LL_VBO_POOL_MAX_SEED_SIZE); //============================================================================ @@ -169,8 +171,15 @@ public: }; +LLVBOPool::LLVBOPool(U32 vboUsage, U32 vboType) +: mUsage(vboUsage), mType(vboType) +{ + mMissCount.resize(LL_VBO_POOL_SEED_COUNT); + std::fill(mMissCount.begin(), mMissCount.end(), 0); +} + -volatile U8* LLVBOPool::allocate(U32& name, U32 size) +volatile U8* LLVBOPool::allocate(U32& name, U32 size, bool for_seed) { llassert(vbo_block_size(size) == size); @@ -183,14 +192,20 @@ volatile U8* LLVBOPool::allocate(U32& name, U32 size) if (mFreeList.size() <= i) { mFreeList.resize(i+1); + mMissCount.resize(i+1); } - if (mFreeList[i].empty()) + if (mFreeList[i].empty() || for_seed) { //make a new buffer glGenBuffersARB(1, &name); glBindBufferARB(mType, name); + if (!for_seed && i < LL_VBO_POOL_SEED_COUNT) + { //record this miss + mMissCount[i]++; + } + if (mType == GL_ARRAY_BUFFER_ARB) { LLVertexBuffer::sAllocatedBytes += size; @@ -211,6 +226,25 @@ volatile U8* LLVBOPool::allocate(U32& name, U32 size) } glBindBufferARB(mType, 0); + + if (for_seed) + { //put into pool for future use + llassert(mFreeList.size() > i); + + Record rec; + rec.mGLName = name; + rec.mClientData = ret; + + if (mType == GL_ARRAY_BUFFER_ARB) + { + sBytesPooled += size; + } + else + { + sIndexBytesPooled += size; + } + mFreeList[i].push_back(rec); + } } else { @@ -263,7 +297,7 @@ void LLVBOPool::release(U32 name, volatile U8* buffer, U32 size) { llassert(vbo_block_size(size) == size); -#if LL_VBO_POOLING +#if 0 && LL_VBO_POOLING U32 i = vbo_block_index(size); @@ -304,6 +338,31 @@ void LLVBOPool::release(U32 name, volatile U8* buffer, U32 size) #endif } +void LLVBOPool::seedPool() +{ + U32 dummy_name = 0; + + if (mFreeList.size() < LL_VBO_POOL_SEED_COUNT) + { + mFreeList.resize(LL_VBO_POOL_SEED_COUNT); + } + + for (U32 i = 0; i < LL_VBO_POOL_SEED_COUNT; i++) + { + if (mMissCount[i] > mFreeList[i].size()) + { + U32 size = i*LL_VBO_BLOCK_SIZE; + + S32 count = mMissCount[i] - mFreeList[i].size(); + for (U32 j = 0; j < count; ++j) + { + allocate(dummy_name, size, true); + } + } + } +} + + void LLVBOPool::cleanup() { U32 size = 1; @@ -339,6 +398,9 @@ void LLVBOPool::cleanup() size *= 2; } + + //reset miss counts + std::fill(mMissCount.begin(), mMissCount.end(), 0); } @@ -373,6 +435,15 @@ U32 LLVertexBuffer::sGLMode[LLRender::NUM_MODES] = }; +//static +void LLVertexBuffer::seedPools() +{ + sStreamVBOPool.seedPool(); + sDynamicVBOPool.seedPool(); + sStreamIBOPool.seedPool(); + sDynamicIBOPool.seedPool(); +} + //static void LLVertexBuffer::setupClientArrays(U32 data_mask) { diff --git a/indra/llrender/llvertexbuffer.h b/indra/llrender/llvertexbuffer.h index 7477dec3ad..a64daa1a90 100644 --- a/indra/llrender/llvertexbuffer.h +++ b/indra/llrender/llvertexbuffer.h @@ -57,20 +57,20 @@ public: static U32 sBytesPooled; static U32 sIndexBytesPooled; - LLVBOPool(U32 vboUsage, U32 vboType) - : mUsage(vboUsage) - , mType(vboType) - {} - + LLVBOPool(U32 vboUsage, U32 vboType); + const U32 mUsage; const U32 mType; //size MUST be a power of 2 - volatile U8* allocate(U32& name, U32 size); + volatile U8* allocate(U32& name, U32 size, bool for_seed = false); //size MUST be the size provided to allocate that returned the given name void release(U32 name, volatile U8* buffer, U32 size); + //batch allocate buffers to be provided to the application on demand + void seedPool(); + //destroy all records in mFreeList void cleanup(); @@ -83,6 +83,8 @@ public: typedef std::list record_list_t; std::vector mFreeList; + std::vector mMissCount; + }; class LLGLFence @@ -129,6 +131,8 @@ public: static bool sUseVAO; static bool sPreferStreamDraw; + static void seedPools(); + static void initClass(bool use_vbo, bool no_vbo_mapping); static void cleanupClass(); static void setupClientArrays(U32 data_mask); diff --git a/indra/newview/llvovolume.cpp b/indra/newview/llvovolume.cpp index 75ab807c39..6d4565ec2f 100644 --- a/indra/newview/llvovolume.cpp +++ b/indra/newview/llvovolume.cpp @@ -639,7 +639,7 @@ BOOL LLVOVolume::idleUpdate(LLAgent &agent, LLWorld &world, const F64 &time) { LLViewerObject::idleUpdate(agent, world, time); - static LLFastTimer::DeclareTimer ftm("Volume"); + static LLFastTimer::DeclareTimer ftm("Volume Idle"); LLFastTimer t(ftm); if (mDead || mDrawable.isNull()) @@ -3945,8 +3945,11 @@ bool can_batch_texture(LLFace* facep) return true; } +static LLFastTimer::DeclareTimer FTM_REGISTER_FACE("Register Face"); + void LLVolumeGeometryManager::registerFace(LLSpatialGroup* group, LLFace* facep, U32 type) { + LLFastTimer t(FTM_REGISTER_FACE); LLMemType mt(LLMemType::MTYPE_SPACE_PARTITION); if (facep->getViewerObject()->isSelected() && LLSelectMgr::getInstance()->mHideSelectedObjects) @@ -4091,7 +4094,9 @@ void LLVolumeGeometryManager::getGeometry(LLSpatialGroup* group) } -static LLFastTimer::DeclareTimer FTM_REBUILD_VOLUME_VB("Volume"); +static LLFastTimer::DeclareTimer FTM_REBUILD_VOLUME_VB("Volume VB"); +static LLFastTimer::DeclareTimer FTM_REBUILD_VOLUME_FACE_LIST("Build Face List"); +static LLFastTimer::DeclareTimer FTM_REBUILD_VOLUME_GEN_DRAW_INFO("Gen Draw Info"); static LLDrawPoolAvatar* get_avatar_drawpool(LLViewerObject* vobj) { @@ -4122,6 +4127,8 @@ static LLDrawPoolAvatar* get_avatar_drawpool(LLViewerObject* vobj) void LLVolumeGeometryManager::rebuildGeom(LLSpatialGroup* group) { + + if (group->changeLOD()) { group->mLastUpdateDistance = group->mDistance; @@ -4133,17 +4140,15 @@ void LLVolumeGeometryManager::rebuildGeom(LLSpatialGroup* group) { if (group->isState(LLSpatialGroup::MESH_DIRTY) && !LLPipeline::sDelayVBUpdate) { - LLFastTimer ftm2(FTM_REBUILD_VOLUME_VB); - rebuildMesh(group); } return; } + LLFastTimer ftm(FTM_REBUILD_VOLUME_VB); + group->mBuilt = 1.f; - LLFastTimer ftm2(FTM_REBUILD_VOLUME_VB); - LLVOAvatar* pAvatarVO = NULL; LLSpatialBridge* bridge = group->mSpatialPartition->asBridge(); @@ -4192,371 +4197,375 @@ void LLVolumeGeometryManager::rebuildGeom(LLSpatialGroup* group) bool emissive = false; - //get all the faces into a list - for (LLSpatialGroup::element_iter drawable_iter = group->getData().begin(); drawable_iter != group->getData().end(); ++drawable_iter) { - LLDrawable* drawablep = *drawable_iter; - - if (drawablep->isDead() || drawablep->isState(LLDrawable::FORCE_INVISIBLE) ) + LLFastTimer t(FTM_REBUILD_VOLUME_FACE_LIST); + + //get all the faces into a list + for (LLSpatialGroup::element_iter drawable_iter = group->getData().begin(); drawable_iter != group->getData().end(); ++drawable_iter) { - continue; - } + LLDrawable* drawablep = *drawable_iter; + + if (drawablep->isDead() || drawablep->isState(LLDrawable::FORCE_INVISIBLE) ) + { + continue; + } - if (drawablep->isAnimating()) - { //fall back to stream draw for animating verts - useage = GL_STREAM_DRAW_ARB; - } + if (drawablep->isAnimating()) + { //fall back to stream draw for animating verts + useage = GL_STREAM_DRAW_ARB; + } - LLVOVolume* vobj = drawablep->getVOVolume(); + LLVOVolume* vobj = drawablep->getVOVolume(); - if (!vobj) - { - continue; - } + if (!vobj) + { + continue; + } - if (vobj->isMesh() && - (vobj->getVolume() && !vobj->getVolume()->isMeshAssetLoaded() || !gMeshRepo.meshRezEnabled())) - { - continue; - } + if (vobj->isMesh() && + (vobj->getVolume() && !vobj->getVolume()->isMeshAssetLoaded() || !gMeshRepo.meshRezEnabled())) + { + continue; + } - LLVolume* volume = vobj->getVolume(); - if (volume) - { - const LLVector3& scale = vobj->getScale(); - group->mSurfaceArea += volume->getSurfaceArea() * llmax(llmax(scale.mV[0], scale.mV[1]), scale.mV[2]); - } + LLVolume* volume = vobj->getVolume(); + if (volume) + { + const LLVector3& scale = vobj->getScale(); + group->mSurfaceArea += volume->getSurfaceArea() * llmax(llmax(scale.mV[0], scale.mV[1]), scale.mV[2]); + } - llassert_always(vobj); - vobj->updateTextureVirtualSize(true); - vobj->preRebuild(); + llassert_always(vobj); + vobj->updateTextureVirtualSize(true); + vobj->preRebuild(); - drawablep->clearState(LLDrawable::HAS_ALPHA); + drawablep->clearState(LLDrawable::HAS_ALPHA); - bool rigged = vobj->isAttachment() && - vobj->isMesh() && - gMeshRepo.getSkinInfo(vobj->getVolume()->getParams().getSculptID(), vobj); + bool rigged = vobj->isAttachment() && + vobj->isMesh() && + gMeshRepo.getSkinInfo(vobj->getVolume()->getParams().getSculptID(), vobj); - bool bake_sunlight = LLPipeline::sBakeSunlight && drawablep->isStatic(); + bool bake_sunlight = LLPipeline::sBakeSunlight && drawablep->isStatic(); - bool is_rigged = false; + bool is_rigged = false; - //for each face - for (S32 i = 0; i < drawablep->getNumFaces(); i++) - { - LLFace* facep = drawablep->getFace(i); - if (!facep) + //for each face + for (S32 i = 0; i < drawablep->getNumFaces(); i++) { - continue; - } + LLFace* facep = drawablep->getFace(i); + if (!facep) + { + continue; + } - //ALWAYS null out vertex buffer on rebuild -- if the face lands in a render - // batch, it will recover its vertex buffer reference from the spatial group - facep->setVertexBuffer(NULL); + //ALWAYS null out vertex buffer on rebuild -- if the face lands in a render + // batch, it will recover its vertex buffer reference from the spatial group + facep->setVertexBuffer(NULL); - //sum up face verts and indices - drawablep->updateFaceSize(i); + //sum up face verts and indices + drawablep->updateFaceSize(i); - if (rigged) - { - if (!facep->isState(LLFace::RIGGED)) - { //completely reset vertex buffer - facep->clearVertexBuffer(); - } + if (rigged) + { + if (!facep->isState(LLFace::RIGGED)) + { //completely reset vertex buffer + facep->clearVertexBuffer(); + } - facep->setState(LLFace::RIGGED); - is_rigged = true; + facep->setState(LLFace::RIGGED); + is_rigged = true; - //get drawpool of avatar with rigged face - LLDrawPoolAvatar* pool = get_avatar_drawpool(vobj); + //get drawpool of avatar with rigged face + LLDrawPoolAvatar* pool = get_avatar_drawpool(vobj); - //Determine if we've received skininfo that contains an - //alternate bind matrix - if it does then apply the translational component - //to the joints of the avatar. - bool pelvisGotSet = false; + //Determine if we've received skininfo that contains an + //alternate bind matrix - if it does then apply the translational component + //to the joints of the avatar. + bool pelvisGotSet = false; - if ( pAvatarVO ) - { - LLUUID currentId = vobj->getVolume()->getParams().getSculptID(); - const LLMeshSkinInfo* pSkinData = gMeshRepo.getSkinInfo( currentId, vobj ); - - if ( pSkinData ) + if ( pAvatarVO ) { - const int bindCnt = pSkinData->mAlternateBindMatrix.size(); - if ( bindCnt > 0 ) - { - const int jointCnt = pSkinData->mJointNames.size(); - const F32 pelvisZOffset = pSkinData->mPelvisOffset; - bool fullRig = (jointCnt>=20) ? true : false; - if ( fullRig ) - { - for ( int i=0; igetVolume()->getParams().getSculptID(); + const LLMeshSkinInfo* pSkinData = gMeshRepo.getSkinInfo( currentId, vobj ); + + if ( pSkinData ) + { + const int bindCnt = pSkinData->mAlternateBindMatrix.size(); + if ( bindCnt > 0 ) + { + const int jointCnt = pSkinData->mJointNames.size(); + const F32 pelvisZOffset = pSkinData->mPelvisOffset; + bool fullRig = (jointCnt>=20) ? true : false; + if ( fullRig ) { - std::string lookingForJoint = pSkinData->mJointNames[i].c_str(); - //llinfos<<"joint name "<getJoint( lookingForJoint ); - if ( pJoint && pJoint->getId() != currentId ) - { - pJoint->setId( currentId ); - const LLVector3& jointPos = pSkinData->mAlternateBindMatrix[i].getTranslation(); - //Set the joint position - pJoint->storeCurrentXform( jointPos ); - //If joint is a pelvis then handle old/new pelvis to foot values - if ( lookingForJoint == "mPelvis" ) - { + for ( int i=0; imJointNames[i].c_str(); + //llinfos<<"joint name "<getJoint( lookingForJoint ); + if ( pJoint && pJoint->getId() != currentId ) + { + pJoint->setId( currentId ); + const LLVector3& jointPos = pSkinData->mAlternateBindMatrix[i].getTranslation(); + //Set the joint position pJoint->storeCurrentXform( jointPos ); - if ( !pAvatarVO->hasPelvisOffset() ) - { - pAvatarVO->setPelvisOffset( true, jointPos, pelvisZOffset ); - //Trigger to rebuild viewer AV - pelvisGotSet = true; + //If joint is a pelvis then handle old/new pelvis to foot values + if ( lookingForJoint == "mPelvis" ) + { + pJoint->storeCurrentXform( jointPos ); + if ( !pAvatarVO->hasPelvisOffset() ) + { + pAvatarVO->setPelvisOffset( true, jointPos, pelvisZOffset ); + //Trigger to rebuild viewer AV + pelvisGotSet = true; + } } - } + } } - } - } + } + } } } - } - //If we've set the pelvis to a new position we need to also rebuild some information that the - //viewer does at launch (e.g. body size etc.) - if ( pelvisGotSet ) - { - pAvatarVO->postPelvisSetRecalc(); - } - - if (pool) - { - const LLTextureEntry* te = facep->getTextureEntry(); - - //remove face from old pool if it exists - LLDrawPool* old_pool = facep->getPool(); - if (old_pool && old_pool->getType() == LLDrawPool::POOL_AVATAR) + //If we've set the pelvis to a new position we need to also rebuild some information that the + //viewer does at launch (e.g. body size etc.) + if ( pelvisGotSet ) { - ((LLDrawPoolAvatar*) old_pool)->removeRiggedFace(facep); + pAvatarVO->postPelvisSetRecalc(); } - //add face to new pool - LLViewerTexture* tex = facep->getTexture(); - U32 type = gPipeline.getPoolTypeFromTE(te, tex); - - if (type == LLDrawPool::POOL_ALPHA) + if (pool) { - if (te->getColor().mV[3] > 0.f) + const LLTextureEntry* te = facep->getTextureEntry(); + + //remove face from old pool if it exists + LLDrawPool* old_pool = facep->getPool(); + if (old_pool && old_pool->getType() == LLDrawPool::POOL_AVATAR) + { + ((LLDrawPoolAvatar*) old_pool)->removeRiggedFace(facep); + } + + //add face to new pool + LLViewerTexture* tex = facep->getTexture(); + U32 type = gPipeline.getPoolTypeFromTE(te, tex); + + if (type == LLDrawPool::POOL_ALPHA) + { + if (te->getColor().mV[3] > 0.f) + { + if (te->getFullbright()) + { + pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_FULLBRIGHT_ALPHA); + } + else + { + pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_ALPHA); + } + } + } + else if (te->getShiny()) { if (te->getFullbright()) { - pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_FULLBRIGHT_ALPHA); + pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_FULLBRIGHT_SHINY); } else { - pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_ALPHA); + if (LLPipeline::sRenderDeferred) + { + pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_SIMPLE); + } + else + { + pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_SHINY); + } } } - } - else if (te->getShiny()) - { - if (te->getFullbright()) - { - pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_FULLBRIGHT_SHINY); - } else { - if (LLPipeline::sRenderDeferred) + if (te->getFullbright()) { - pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_SIMPLE); + pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_FULLBRIGHT); } else { - pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_SHINY); + pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_SIMPLE); } } - } - else - { - if (te->getFullbright()) - { - pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_FULLBRIGHT); - } - else + + if (te->getGlow()) { - pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_SIMPLE); + pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_GLOW); } - } - - if (te->getGlow()) - { - pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_GLOW); - } - if (LLPipeline::sRenderDeferred) - { - if (type != LLDrawPool::POOL_ALPHA && !te->getFullbright()) + if (LLPipeline::sRenderDeferred) { - if (te->getBumpmap()) + if (type != LLDrawPool::POOL_ALPHA && !te->getFullbright()) { - pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_DEFERRED_BUMP); - } - else - { - pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_DEFERRED_SIMPLE); + if (te->getBumpmap()) + { + pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_DEFERRED_BUMP); + } + else + { + pool->addRiggedFace(facep, LLDrawPoolAvatar::RIGGED_DEFERRED_SIMPLE); + } } } } - } - continue; - } - else - { - if (facep->isState(LLFace::RIGGED)) - { //face is not rigged but used to be, remove from rigged face pool - LLDrawPoolAvatar* pool = (LLDrawPoolAvatar*) facep->getPool(); - if (pool) - { - pool->removeRiggedFace(facep); - } - facep->clearState(LLFace::RIGGED); + continue; } - } - - - if (cur_total > max_total || facep->getIndicesCount() <= 0 || facep->getGeomCount() <= 0) - { - facep->clearVertexBuffer(); - continue; - } - - cur_total += facep->getGeomCount(); - - if (facep->hasGeometry() && facep->getPixelArea() > FORCE_CULL_AREA) - { - const LLTextureEntry* te = facep->getTextureEntry(); - LLViewerTexture* tex = facep->getTexture(); - - if (te->getGlow() >= 1.f/255.f) - { - emissive = true; - } - - if (facep->isState(LLFace::TEXTURE_ANIM)) + else { - if (!vobj->mTexAnimMode) - { - facep->clearState(LLFace::TEXTURE_ANIM); + if (facep->isState(LLFace::RIGGED)) + { //face is not rigged but used to be, remove from rigged face pool + LLDrawPoolAvatar* pool = (LLDrawPoolAvatar*) facep->getPool(); + if (pool) + { + pool->removeRiggedFace(facep); + } + facep->clearState(LLFace::RIGGED); } } - BOOL force_simple = (facep->getPixelArea() < FORCE_SIMPLE_RENDER_AREA); - U32 type = gPipeline.getPoolTypeFromTE(te, tex); - if (type != LLDrawPool::POOL_ALPHA && force_simple) - { - type = LLDrawPool::POOL_SIMPLE; - } - facep->setPoolType(type); - if (vobj->isHUDAttachment()) + if (cur_total > max_total || facep->getIndicesCount() <= 0 || facep->getGeomCount() <= 0) { - facep->setState(LLFace::FULLBRIGHT); + facep->clearVertexBuffer(); + continue; } - if (vobj->mTextureAnimp && vobj->mTexAnimMode) + cur_total += facep->getGeomCount(); + + if (facep->hasGeometry() && facep->getPixelArea() > FORCE_CULL_AREA) { - if (vobj->mTextureAnimp->mFace <= -1) + const LLTextureEntry* te = facep->getTextureEntry(); + LLViewerTexture* tex = facep->getTexture(); + + if (te->getGlow() >= 1.f/255.f) { - S32 face; - for (face = 0; face < vobj->getNumTEs(); face++) - { - LLFace * facep = drawablep->getFace(face); - if (facep) - { - facep->setState(LLFace::TEXTURE_ANIM); - } - } + emissive = true; } - else if (vobj->mTextureAnimp->mFace < vobj->getNumTEs()) + + if (facep->isState(LLFace::TEXTURE_ANIM)) { - LLFace * facep = drawablep->getFace(vobj->mTextureAnimp->mFace); - if (facep) + if (!vobj->mTexAnimMode) { - facep->setState(LLFace::TEXTURE_ANIM); + facep->clearState(LLFace::TEXTURE_ANIM); } } - } - if (type == LLDrawPool::POOL_ALPHA) - { - if (facep->canRenderAsMask()) - { //can be treated as alpha mask - simple_faces.push_back(facep); - } - else + BOOL force_simple = (facep->getPixelArea() < FORCE_SIMPLE_RENDER_AREA); + U32 type = gPipeline.getPoolTypeFromTE(te, tex); + if (type != LLDrawPool::POOL_ALPHA && force_simple) { - if (te->getColor().mV[3] > 0.f) - { //only treat as alpha in the pipeline if < 100% transparent - drawablep->setState(LLDrawable::HAS_ALPHA); - } - alpha_faces.push_back(facep); + type = LLDrawPool::POOL_SIMPLE; } - } - else - { - if (drawablep->isState(LLDrawable::REBUILD_VOLUME)) + facep->setPoolType(type); + + if (vobj->isHUDAttachment()) { - facep->mLastUpdateTime = gFrameTimeSeconds; + facep->setState(LLFace::FULLBRIGHT); } - if (gPipeline.canUseWindLightShadersOnObjects() - && LLPipeline::sRenderBump) + if (vobj->mTextureAnimp && vobj->mTexAnimMode) { - if (te->getBumpmap()) - { //needs normal + binormal - bump_faces.push_back(facep); + if (vobj->mTextureAnimp->mFace <= -1) + { + S32 face; + for (face = 0; face < vobj->getNumTEs(); face++) + { + LLFace * facep = drawablep->getFace(face); + if (facep) + { + facep->setState(LLFace::TEXTURE_ANIM); + } + } + } + else if (vobj->mTextureAnimp->mFace < vobj->getNumTEs()) + { + LLFace * facep = drawablep->getFace(vobj->mTextureAnimp->mFace); + if (facep) + { + facep->setState(LLFace::TEXTURE_ANIM); + } } - else if (te->getShiny() || !te->getFullbright()) - { //needs normal + } + + if (type == LLDrawPool::POOL_ALPHA) + { + if (facep->canRenderAsMask()) + { //can be treated as alpha mask simple_faces.push_back(facep); } - else - { //doesn't need normal - facep->setState(LLFace::FULLBRIGHT); - fullbright_faces.push_back(facep); + else + { + if (te->getColor().mV[3] > 0.f) + { //only treat as alpha in the pipeline if < 100% transparent + drawablep->setState(LLDrawable::HAS_ALPHA); + } + alpha_faces.push_back(facep); } } else { - if (te->getBumpmap() && LLPipeline::sRenderBump) - { //needs normal + binormal - bump_faces.push_back(facep); + if (drawablep->isState(LLDrawable::REBUILD_VOLUME)) + { + facep->mLastUpdateTime = gFrameTimeSeconds; } - else if ((te->getShiny() && LLPipeline::sRenderBump) || - !(te->getFullbright() || bake_sunlight)) - { //needs normal - simple_faces.push_back(facep); + + if (gPipeline.canUseWindLightShadersOnObjects() + && LLPipeline::sRenderBump) + { + if (te->getBumpmap()) + { //needs normal + binormal + bump_faces.push_back(facep); + } + else if (te->getShiny() || !te->getFullbright()) + { //needs normal + simple_faces.push_back(facep); + } + else + { //doesn't need normal + facep->setState(LLFace::FULLBRIGHT); + fullbright_faces.push_back(facep); + } } - else - { //doesn't need normal - facep->setState(LLFace::FULLBRIGHT); - fullbright_faces.push_back(facep); + else + { + if (te->getBumpmap() && LLPipeline::sRenderBump) + { //needs normal + binormal + bump_faces.push_back(facep); + } + else if ((te->getShiny() && LLPipeline::sRenderBump) || + !(te->getFullbright() || bake_sunlight)) + { //needs normal + simple_faces.push_back(facep); + } + else + { //doesn't need normal + facep->setState(LLFace::FULLBRIGHT); + fullbright_faces.push_back(facep); + } } } } + else + { //face has no renderable geometry + facep->clearVertexBuffer(); + } } - else - { //face has no renderable geometry - facep->clearVertexBuffer(); - } - } - if (is_rigged) - { - drawablep->setState(LLDrawable::RIGGED); - } - else - { - drawablep->clearState(LLDrawable::RIGGED); + if (is_rigged) + { + drawablep->setState(LLDrawable::RIGGED); + } + else + { + drawablep->clearState(LLDrawable::RIGGED); + } } } @@ -4623,15 +4632,15 @@ void LLVolumeGeometryManager::rebuildGeom(LLSpatialGroup* group) } } -static LLFastTimer::DeclareTimer FTM_VOLUME_GEOM("Volume Geometry"); -static LLFastTimer::DeclareTimer FTM_VOLUME_GEOM_PARTIAL("Terse Rebuild"); void LLVolumeGeometryManager::rebuildMesh(LLSpatialGroup* group) { llassert(group); if (group && group->isState(LLSpatialGroup::MESH_DIRTY) && !group->isState(LLSpatialGroup::GEOM_DIRTY)) { - LLFastTimer tm(FTM_VOLUME_GEOM); + LLFastTimer ftm(FTM_REBUILD_VOLUME_VB); + LLFastTimer t(FTM_REBUILD_VOLUME_GEN_DRAW_INFO); //make sure getgeometryvolume shows up in the right place in timers + S32 num_mapped_veretx_buffer = LLVertexBuffer::sMappedCount ; group->mBuilt = 1.f; @@ -4640,7 +4649,6 @@ void LLVolumeGeometryManager::rebuildMesh(LLSpatialGroup* group) for (LLSpatialGroup::element_iter drawable_iter = group->getData().begin(); drawable_iter != group->getData().end(); ++drawable_iter) { - LLFastTimer t(FTM_VOLUME_GEOM_PARTIAL); LLDrawable* drawablep = *drawable_iter; if (!drawablep->isDead() && drawablep->isState(LLDrawable::REBUILD_ALL) ) @@ -4747,8 +4755,20 @@ struct CompareBatchBreakerModified } }; +static LLFastTimer::DeclareTimer FTM_GEN_DRAW_INFO_SORT("Draw Info Face Sort"); +static LLFastTimer::DeclareTimer FTM_GEN_DRAW_INFO_FACE_SIZE("Face Sizing"); +static LLFastTimer::DeclareTimer FTM_GEN_DRAW_INFO_ALLOCATE("Allocate VB"); +static LLFastTimer::DeclareTimer FTM_GEN_DRAW_INFO_FIND_VB("Find VB"); +static LLFastTimer::DeclareTimer FTM_GEN_DRAW_INFO_RESIZE_VB("Resize VB"); + + + + + void LLVolumeGeometryManager::genDrawInfo(LLSpatialGroup* group, U32 mask, std::vector& faces, BOOL distance_sort, BOOL batch_textures) { + LLFastTimer t(FTM_REBUILD_VOLUME_GEN_DRAW_INFO); + U32 buffer_usage = group->mBufferUsage; #if LL_DARWIN @@ -4766,15 +4786,18 @@ void LLVolumeGeometryManager::genDrawInfo(LLSpatialGroup* group, U32 mask, std:: U32 max_vertices = (gSavedSettings.getS32("RenderMaxVBOSize")*1024)/LLVertexBuffer::calcVertexSize(group->mSpatialPartition->mVertexDataMask); max_vertices = llmin(max_vertices, (U32) 65535); - if (!distance_sort) - { - //sort faces by things that break batches - std::sort(faces.begin(), faces.end(), CompareBatchBreakerModified()); - } - else { - //sort faces by distance - std::sort(faces.begin(), faces.end(), LLFace::CompareDistanceGreater()); + LLFastTimer t(FTM_GEN_DRAW_INFO_SORT); + if (!distance_sort) + { + //sort faces by things that break batches + std::sort(faces.begin(), faces.end(), CompareBatchBreakerModified()); + } + else + { + //sort faces by distance + std::sort(faces.begin(), faces.end(), LLFace::CompareDistanceGreater()); + } } bool hud_group = group->isHUDGroup() ; @@ -4839,57 +4862,86 @@ void LLVolumeGeometryManager::genDrawInfo(LLSpatialGroup* group, U32 mask, std:: std::vector texture_list; - if (batch_textures) { - U8 cur_tex = 0; - facep->setTextureIndex(cur_tex); - texture_list.push_back(tex); - - //if (can_batch_texture(facep)) + LLFastTimer t(FTM_GEN_DRAW_INFO_FACE_SIZE); + if (batch_textures) { - while (i != faces.end()) + U8 cur_tex = 0; + facep->setTextureIndex(cur_tex); + texture_list.push_back(tex); + + //if (can_batch_texture(facep)) { - facep = *i; - if (facep->getTexture() != tex) + while (i != faces.end()) { - if (distance_sort) - { //textures might be out of order, see if texture exists in current batch - bool found = false; - for (U32 tex_idx = 0; tex_idx < texture_list.size(); ++tex_idx) - { - if (facep->getTexture() == texture_list[tex_idx]) + facep = *i; + if (facep->getTexture() != tex) + { + if (distance_sort) + { //textures might be out of order, see if texture exists in current batch + bool found = false; + for (U32 tex_idx = 0; tex_idx < texture_list.size(); ++tex_idx) { - cur_tex = tex_idx; - found = true; - break; + if (facep->getTexture() == texture_list[tex_idx]) + { + cur_tex = tex_idx; + found = true; + break; + } } - } - if (!found) + if (!found) + { + cur_tex = texture_list.size(); + } + } + else { - cur_tex = texture_list.size(); + cur_tex++; } - } - else - { - cur_tex++; - } - if (!can_batch_texture(facep)) - { //face is bump mapped or has an animated texture matrix -- can't - //batch more than 1 texture at a time - break; + if (!can_batch_texture(facep)) + { //face is bump mapped or has an animated texture matrix -- can't + //batch more than 1 texture at a time + break; + } + + if (cur_tex >= texture_index_channels) + { //cut batches when index channels are depleted + break; + } + + tex = facep->getTexture(); + + texture_list.push_back(tex); } - if (cur_tex >= texture_index_channels) - { //cut batches when index channels are depleted + if (geom_count + facep->getGeomCount() > max_vertices) + { //cut batches on geom count too big break; } - tex = facep->getTexture(); + ++i; + index_count += facep->getIndicesCount(); + geom_count += facep->getGeomCount(); - texture_list.push_back(tex); + facep->setTextureIndex(cur_tex); } + } + + tex = texture_list[0]; + } + else + { + while (i != faces.end() && + (LLPipeline::sTextureBindTest || (distance_sort || (*i)->getTexture() == tex))) + { + facep = *i; + + + //face has no texture index + facep->mDrawInfo = NULL; + facep->setTextureIndex(255); if (geom_count + facep->getGeomCount() > max_vertices) { //cut batches on geom count too big @@ -4899,40 +4951,16 @@ void LLVolumeGeometryManager::genDrawInfo(LLSpatialGroup* group, U32 mask, std:: ++i; index_count += facep->getIndicesCount(); geom_count += facep->getGeomCount(); - - facep->setTextureIndex(cur_tex); } } - - tex = texture_list[0]; } - else - { - while (i != faces.end() && - (LLPipeline::sTextureBindTest || (distance_sort || (*i)->getTexture() == tex))) - { - facep = *i; - - //face has no texture index - facep->mDrawInfo = NULL; - facep->setTextureIndex(255); - - if (geom_count + facep->getGeomCount() > max_vertices) - { //cut batches on geom count too big - break; - } - - ++i; - index_count += facep->getIndicesCount(); - geom_count += facep->getGeomCount(); - } - } - //create/delete/resize vertex buffer if needed LLVertexBuffer* buffer = NULL; + if (group->mBufferUsage != GL_DYNAMIC_DRAW_ARB) { //try to find a buffer to reuse + LLFastTimer t(FTM_GEN_DRAW_INFO_FIND_VB); LLSpatialGroup::buffer_texture_map_t::iterator found_iter = group->mBufferMap[mask].find(*face_iter); if (found_iter != group->mBufferMap[mask].end()) @@ -4943,23 +4971,28 @@ void LLVolumeGeometryManager::genDrawInfo(LLSpatialGroup* group, U32 mask, std:: } } } - - if (!buffer || !buffer->isWriteable()) - { //create new buffer if needed - buffer = createVertexBuffer(mask, buffer_usage); - buffer->allocateBuffer(geom_count, index_count, TRUE); - } - else - { //resize pre-existing buffer - if (LLVertexBuffer::sEnableVBOs && buffer->getUsage() != buffer_usage || - buffer->getTypeMask() != mask) - { + + { + LLFastTimer t(FTM_GEN_DRAW_INFO_ALLOCATE); + + if (!buffer || !buffer->isWriteable()) + { //create new buffer if needed buffer = createVertexBuffer(mask, buffer_usage); buffer->allocateBuffer(geom_count, index_count, TRUE); } - else - { - buffer->resizeBuffer(geom_count, index_count); + else + { //resize pre-existing buffer + LLFastTimer t(FTM_GEN_DRAW_INFO_RESIZE_VB); + if (LLVertexBuffer::sEnableVBOs && buffer->getUsage() != buffer_usage || + buffer->getTypeMask() != mask) + { + buffer = createVertexBuffer(mask, buffer_usage); + buffer->allocateBuffer(geom_count, index_count, TRUE); + } + else + { + buffer->resizeBuffer(geom_count, index_count); + } } } diff --git a/indra/newview/pipeline.cpp b/indra/newview/pipeline.cpp index 34dd15c9a1..a691302cb9 100644 --- a/indra/newview/pipeline.cpp +++ b/indra/newview/pipeline.cpp @@ -2450,6 +2450,8 @@ BOOL LLPipeline::updateDrawableGeom(LLDrawable* drawablep, BOOL priority) return update_complete; } +static LLFastTimer::DeclareTimer FTM_SEED_VBO_POOLS("Seed VBO Pool"); + void LLPipeline::updateGL() { while (!LLGLUpdate::sGLQ.empty()) @@ -2459,6 +2461,11 @@ void LLPipeline::updateGL() glu->mInQ = FALSE; LLGLUpdate::sGLQ.pop_front(); } + + { //seed VBO Pools + LLFastTimer t(FTM_SEED_VBO_POOLS); + LLVertexBuffer::seedPools(); + } } void LLPipeline::rebuildPriorityGroups() -- cgit v1.2.3 From 91acda05d57c360924a46696a44a5b7841b84543 Mon Sep 17 00:00:00 2001 From: Todd Stinson Date: Tue, 15 May 2012 16:49:13 -0700 Subject: EXP-1928: Removing some commented asserts following more development testing. --- indra/newview/llagent.cpp | 10 +--------- indra/newview/llviewermessage.cpp | 3 +-- 2 files changed, 2 insertions(+), 11 deletions(-) (limited to 'indra') diff --git a/indra/newview/llagent.cpp b/indra/newview/llagent.cpp index fb217f2186..d27fc252d8 100755 --- a/indra/newview/llagent.cpp +++ b/indra/newview/llagent.cpp @@ -3604,7 +3604,7 @@ bool LLAgent::teleportCore(bool is_local) void LLAgent::restartFailedTeleportRequest() { - // XXX stinson 05/11/2012 llassert(hasFailedTeleportRequest()); + llassert(hasFailedTeleportRequest()); if (hasFailedTeleportRequest()) { mFailedTeleportRequest->doTeleport(); @@ -3613,7 +3613,6 @@ void LLAgent::restartFailedTeleportRequest() void LLAgent::clearFailedTeleportRequest() { - // XXX stinson 05/11/2012 llassert(hasFailedTeleportRequest()); if (hasFailedTeleportRequest()) { mFailedTeleportRequest.reset(); @@ -3628,7 +3627,6 @@ void LLAgent::setMaturityRatingChangeDuringTeleport(int pMaturityRatingChange) void LLAgent::handleTeleportFinished() { - // XXX stinson 05/11/2012 llassert(hasCurrentTeleportRequest()); if (hasCurrentTeleportRequest()) { mCurrentTeleportRequest.reset(); @@ -3649,8 +3647,6 @@ void LLAgent::handleTeleportFinished() void LLAgent::handleTeleportFailed() { - // XXX stinson 05/11/2012 llassert(hasCurrentTeleportRequest()); - // XXX stinson 05/11/2012 llassert(!hasFailedTeleportRequest()); if (hasCurrentTeleportRequest()) { mFailedTeleportRequest = mCurrentTeleportRequest; @@ -3690,7 +3686,6 @@ void LLAgent::teleportRequest( // Landmark ID = LLUUID::null means teleport home void LLAgent::teleportViaLandmark(const LLUUID& landmark_asset_id) { - // XXX stinson 05/11/2012 llassert(!hasCurrentTeleportRequest()); mCurrentTeleportRequest = LLTeleportRequestPtr(new LLTeleportRequestViaLandmark(landmark_asset_id)); mCurrentTeleportRequest->doTeleport(); } @@ -3712,7 +3707,6 @@ void LLAgent::doTeleportViaLandmark(const LLUUID& landmark_asset_id) void LLAgent::teleportViaLure(const LLUUID& lure_id, BOOL godlike) { - // XXX stinson 05/11/2012 llassert(!hasCurrentTeleportRequest()); mCurrentTeleportRequest = LLTeleportRequestPtr(new LLTeleportRequestViaLure(lure_id, godlike)); mCurrentTeleportRequest->doTeleport(); } @@ -3768,7 +3762,6 @@ void LLAgent::teleportCancel() void LLAgent::teleportViaLocation(const LLVector3d& pos_global) { - // XXX stinson 05/11/2012 llassert(!hasCurrentTeleportRequest()); mCurrentTeleportRequest = LLTeleportRequestPtr(new LLTeleportRequestViaLocation(pos_global)); mCurrentTeleportRequest->doTeleport(); } @@ -3817,7 +3810,6 @@ void LLAgent::doTeleportViaLocation(const LLVector3d& pos_global) // Teleport to global position, but keep facing in the same direction void LLAgent::teleportViaLocationLookAt(const LLVector3d& pos_global) { - // XXX stinson 05/11/2012 llassert(!hasCurrentTeleportRequest()); mCurrentTeleportRequest = LLTeleportRequestPtr(new LLTeleportRequestViaLocationLookAt(pos_global)); mCurrentTeleportRequest->doTeleport(); } diff --git a/indra/newview/llviewermessage.cpp b/indra/newview/llviewermessage.cpp index 3712e56f7c..56522bc819 100755 --- a/indra/newview/llviewermessage.cpp +++ b/indra/newview/llviewermessage.cpp @@ -5389,12 +5389,11 @@ void handle_maturity_preference_change(const LLSD &pResponse, int pMaturityRatin { if (pResponse.isUndefined()) { - // XXX stinson 05/11/2012 llinfos << "Maturity response ==> " << llendl; + // XXX stinson 05/15/2012 : should report some notification that the preference has not changed gAgent.clearFailedTeleportRequest(); } else { - // XXX stinson 05/11/2012 linfos << "Maturity response ==> '" << pResponse << "'" << llendl; gAgent.setMaturityRatingChangeDuringTeleport(pMaturityRatingChange); gAgent.restartFailedTeleportRequest(); } -- cgit v1.2.3 From 52b624aa3db193cec0980e369be3ff1a8e5faa24 Mon Sep 17 00:00:00 2001 From: Todd Stinson Date: Tue, 15 May 2012 19:10:03 -0700 Subject: EXP-1928: Removing ability to restart a teleport via lure because the re-attempt will fail on the server. --- indra/newview/llagent.cpp | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/newview/llagent.cpp b/indra/newview/llagent.cpp index d27fc252d8..3b1e894ed3 100755 --- a/indra/newview/llagent.cpp +++ b/indra/newview/llagent.cpp @@ -3604,7 +3604,6 @@ bool LLAgent::teleportCore(bool is_local) void LLAgent::restartFailedTeleportRequest() { - llassert(hasFailedTeleportRequest()); if (hasFailedTeleportRequest()) { mFailedTeleportRequest->doTeleport(); @@ -3707,8 +3706,29 @@ void LLAgent::doTeleportViaLandmark(const LLUUID& landmark_asset_id) void LLAgent::teleportViaLure(const LLUUID& lure_id, BOOL godlike) { +#if 0 + // stinson 05/15/2012 : cannot restart a teleport via lure because of server-side restrictions + // The current scenario is as follows: + // 1. User A initializes a request for User B to teleport via lure + // 2. User B accepts the teleport via lure request + // 3. The server sees the init request from User A and the accept request from User B and matches them up + // 4. The server then removes the paired requests up from the "queue" + // 5. The server then fails User B's teleport for reason of maturity level (for example) + // 6. User B's viewer prompts user to increase their maturity level profile value. + // 7. User B confirms and accepts increase in maturity level + // 8. User B's viewer then attempts to teleport via lure again + // 9. This fails on the server because User A's initial request has been removed from the "queue" in step 4 mCurrentTeleportRequest = LLTeleportRequestPtr(new LLTeleportRequestViaLure(lure_id, godlike)); mCurrentTeleportRequest->doTeleport(); +#else + // Clear any current and failed teleports. + mCurrentTeleportRequest.reset(); + clearFailedTeleportRequest(); + + // Do not persist the teleport via lure request as it is only temporary and cannot be restarted + LLTeleportRequestPtr currentTeleportRequest = LLTeleportRequestPtr(new LLTeleportRequestViaLure(lure_id, godlike)); + currentTeleportRequest->doTeleport(); +#endif } void LLAgent::doTeleportViaLure(const LLUUID& lure_id, BOOL godlike) -- cgit v1.2.3 From 6809b5068ffd0e0daece06af5dad56c32dfe2966 Mon Sep 17 00:00:00 2001 From: William Todd Stinson Date: Wed, 16 May 2012 01:24:44 -0700 Subject: EXP-1928: Changing the actual copy for the teleport and maturity preference notifications. --- indra/newview/skins/default/xui/en/notifications.xml | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) (limited to 'indra') diff --git a/indra/newview/skins/default/xui/en/notifications.xml b/indra/newview/skins/default/xui/en/notifications.xml index 59dd17ea9d..517da99a84 100644 --- a/indra/newview/skins/default/xui/en/notifications.xml +++ b/indra/newview/skins/default/xui/en/notifications.xml @@ -4111,28 +4111,30 @@ You are not allowed in that region due to your maturity Rating. type="alertmodal"> fail confirm -You are not allowed in that Region due to your maturity Rating preference. - -To enter the desired region, please change your maturity Rating preference. This will allow you to search for and access [REGIONMATURITY] content. To undo any changes, go to Me > Preferences > General. +The region you're trying to visit contains [REGIONMATURITY] content, but your current preferences are set to exclude [REGIONMATURITY] content. We can change your preferences, or you can cancel this teleport.
- - - - - - - - Choose model file - - - - - Advanced users: If you are familiar with 3D content creation tools you may wish to use the Advanced Uploader. - - - - Choose model file to upload - - - - - Second Life supports COLLADA (.dae) files - - - - - - Dimensions (meters): - - - X Y Z - - - - - - WARNING: - - - You will not be able to complete the final step of uploading this model to the Second Life servers. [secondlife:///app/floater/learn_more Find out how] to set up your account for mesh model uploads. - - - - - - - - - Optimize model - - - - We have optimized the model for performance. Adjust it further if you wish. - - - Generating Level of Detail - - - Generate Level of Detail: High - - Generate Level of Detail: Medium - - Generate Level of Detail: Low - - Generate Level of Detail: Lowest - - - Performance - Faster rendering -Less detail -Lower prim weight - Accuracy - Slower rendering -More detail -Higher prim weight - - - ' - - ' - - ' - - - - Geometry preview - - - - - - High detail - - - Medium detail - - - Low detail - - - Lowest detail - - - - - - - - - Adjust physics - - - - We will create a shape for the outer hull of the model. Adjust the shape's detail level as needed for the intended purpose of your model. - - - Performance - Faster rendering -Less detail -Lower prim weight - Accuracy - Slower rendering -More detail -Higher prim weight - - - Examples: -Moving objects -Flying objects -Vehicles - Examples: -Small static objects -Less detailed objects -Simple furniture - Examples: -Static objects -Detailed objects -Buildings - - - - Physics preview - - - - - - High detail - - - Medium detail - - - Low detail - - - Lowest detail - - - - - - - - - Review - - - - Impact to parcel/region: [EQUIV] prim equivalents - - Your account will be charged an upload fee of L$ [FEE]. - - By clicking the upload button, you confirm that you have the appropriate rights to the material contained in the model. - - - - - - - - - - - Upload complete - - - - Your model has been uploaded. - - - You will find it in the Objects folder in your inventory. - - Your account has been charged L$ [FEE]. - - - - - - + + + + + \ No newline at end of file diff --git a/indra/newview/skins/default/xui/en/panel_preferences_spellcheck.xml b/indra/newview/skins/default/xui/en/panel_preferences_spellcheck.xml deleted file mode 100644 index f1b16c5d0d..0000000000 --- a/indra/newview/skins/default/xui/en/panel_preferences_spellcheck.xml +++ /dev/null @@ -1,136 +0,0 @@ - - - - - Main dictionary : - - - - - Additional dictionaries : - - - Available - - - Active - - - - - - - -- cgit v1.2.3 From 8e6202ad53415695f0c0f40a366b4f329ff8b714 Mon Sep 17 00:00:00 2001 From: Jonathan Yap Date: Thu, 31 May 2012 06:20:12 -0400 Subject: STORM-1812 Added teleport started callback --- indra/newview/llvieweraudio.cpp | 26 +++++++++++--------------- indra/newview/llviewermessage.cpp | 4 ++++ indra/newview/llviewermessage.h | 4 +++- 3 files changed, 18 insertions(+), 16 deletions(-) (limited to 'indra') diff --git a/indra/newview/llvieweraudio.cpp b/indra/newview/llvieweraudio.cpp index 7ac0d3aeaa..8d8c401dac 100644 --- a/indra/newview/llvieweraudio.cpp +++ b/indra/newview/llvieweraudio.cpp @@ -65,6 +65,7 @@ LLViewerAudio::~LLViewerAudio() { mTeleportFailedConnection.disconnect(); mTeleportFinishedConnection.disconnect(); + mTeleportStartedConnection.disconnect(); } void LLViewerAudio::registerIdleListener() @@ -74,7 +75,6 @@ void LLViewerAudio::registerIdleListener() mIdleListnerActive = true; doOnIdleRepeating(boost::bind(boost::bind(&LLViewerAudio::onIdleUpdate, this))); } - } void LLViewerAudio::startInternetStreamWithAutoFade(std::string streamURI) @@ -254,7 +254,16 @@ F32 LLViewerAudio::getFadeVolume() void LLViewerAudio::onTeleportStarted() { -llwarns << "DBG teleport started" << llendl; + if (!LLViewerAudio::getInstance()->getForcedTeleportFade()) + { + // Even though the music was turned off it was starting up (with autoplay disabled) occasionally + // after a failed teleport or after an intra-parcel teleport. Also, the music sometimes was not + // restarting after a successful intra-parcel teleport. Setting mWasPlaying fixes these issues. + LLViewerAudio::getInstance()->setWasPlaying(!gAudiop->getInternetStreamURL().empty()); + LLViewerAudio::getInstance()->setForcedTeleportFade(true); + LLViewerAudio::getInstance()->startInternetStreamWithAutoFade(LLStringUtil::null); + LLViewerAudio::getInstance()->setNextStreamURI(LLStringUtil::null); + } } void LLViewerAudio::onTeleportFailed() @@ -398,23 +407,10 @@ void audio_update_volume(bool force_update) { if (!progress_view_visible && LLViewerAudio::getInstance()->getForcedTeleportFade()) { -LL_WARNS("FADING") << "DBG ForcedTeleportFade = true, WasPlaying = " << !gAudiop->getInternetStreamURL().empty() << " stream ='" << gAudiop->getInternetStreamURL() << "'" << LL_ENDL; LLViewerAudio::getInstance()->setWasPlaying(!gAudiop->getInternetStreamURL().empty()); LLViewerAudio::getInstance()->setForcedTeleportFade(false); } - if (progress_view_visible && !LLViewerAudio::getInstance()->getForcedTeleportFade()) - { -LL_WARNS("FADING") << "DBG ForcedTeleportFade = false, WasPlaying = " << !gAudiop->getInternetStreamURL().empty() << " stream ='" << gAudiop->getInternetStreamURL() << "'" << LL_ENDL; - // Even though the music was turned off it was starting up (with autoplay disabled) occasionally - // after a failed teleport or after an intra-parcel teleport. Also, the music sometimes was not - // restarting after a successful intra-parcel teleport. Setting mWasPlaying fixes these issues. - LLViewerAudio::getInstance()->setWasPlaying(!gAudiop->getInternetStreamURL().empty()); - LLViewerAudio::getInstance()->setForcedTeleportFade(true); - LLViewerAudio::getInstance()->startInternetStreamWithAutoFade(LLStringUtil::null); - LLViewerAudio::getInstance()->setNextStreamURI(LLStringUtil::null); - } - F32 music_volume = gSavedSettings.getF32("AudioLevelMusic"); BOOL music_muted = gSavedSettings.getBOOL("MuteMusic"); F32 fade_volume = LLViewerAudio::getInstance()->getFadeVolume(); diff --git a/indra/newview/llviewermessage.cpp b/indra/newview/llviewermessage.cpp index 33ce8a79e1..536d3d2056 100755 --- a/indra/newview/llviewermessage.cpp +++ b/indra/newview/llviewermessage.cpp @@ -3417,6 +3417,9 @@ void process_teleport_start(LLMessageSystem *msg, void**) LL_DEBUGS("Messaging") << "Got TeleportStart with TeleportFlags=" << teleport_flags << ". gTeleportDisplay: " << gTeleportDisplay << ", gAgent.mTeleportState: " << gAgent.getTeleportState() << LL_ENDL; + // *NOTE: The server sends two StartTeleport packets when you are teleporting to a LM + LLViewerMessage::getInstance()->mTeleportStartedSignal(); + if (teleport_flags & TELEPORT_FLAGS_DISABLE_CANCEL) { gViewerWindow->setProgressCancelButtonVisible(FALSE); @@ -3436,6 +3439,7 @@ void process_teleport_start(LLMessageSystem *msg, void**) make_ui_sound("UISndTeleportOut"); LL_INFOS("Messaging") << "Teleport initiated by remote TeleportStart message with TeleportFlags: " << teleport_flags << LL_ENDL; + // Don't call LLFirstUse::useTeleport here because this could be // due to being killed, which would send you home, not to a Telehub } diff --git a/indra/newview/llviewermessage.h b/indra/newview/llviewermessage.h index e4fc77c06d..f326a5b29b 100644 --- a/indra/newview/llviewermessage.h +++ b/indra/newview/llviewermessage.h @@ -36,6 +36,9 @@ #include "stdenums.h" #include "llnotifications.h" +#include +#include + // // Forward declarations // @@ -211,7 +214,6 @@ public: typedef boost::signals2::signal teleport_started_signal_t; boost::signals2::connection setTeleportStartedCallback(teleport_started_callback_t cb); -protected: teleport_started_signal_t mTeleportStartedSignal; }; -- cgit v1.2.3 From 76234b48256a93c6a0f9dd1d3807706b1039a181 Mon Sep 17 00:00:00 2001 From: Kitty Barnett Date: Thu, 31 May 2012 17:08:14 +0200 Subject: STORM-276 FIXED "Add to Ignore" doesn't trigger --- indra/llui/llspellcheck.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/llui/llspellcheck.cpp b/indra/llui/llspellcheck.cpp index aa39e21a96..bde3b56741 100644 --- a/indra/llui/llspellcheck.cpp +++ b/indra/llui/llspellcheck.cpp @@ -142,7 +142,7 @@ void LLSpellChecker::addToIgnoreList(const std::string& word) { std::string word_lower(word); LLStringUtil::toLower(word_lower); - if (mIgnoreList.end() != std::find(mIgnoreList.begin(), mIgnoreList.end(), word_lower)) + if (mIgnoreList.end() == std::find(mIgnoreList.begin(), mIgnoreList.end(), word_lower)) { mIgnoreList.push_back(word_lower); addToDictFile(getDictionaryUserPath() + mDictFile + DICT_IGNORE_SUFFIX + ".dic", word_lower); -- cgit v1.2.3 From d7303541ccd4ea1420de4cd11ff824aeb171fae7 Mon Sep 17 00:00:00 2001 From: Kitty Barnett Date: Thu, 31 May 2012 17:37:19 +0200 Subject: STORM-276 FIXED Line editor misspells are checked every frame --- indra/llui/lllineeditor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/llui/lllineeditor.cpp b/indra/llui/lllineeditor.cpp index 352854c629..1e0b194e44 100644 --- a/indra/llui/lllineeditor.cpp +++ b/indra/llui/lllineeditor.cpp @@ -1883,7 +1883,7 @@ void LLLineEditor::draw() // Calculate start and end indices for the first and last visible word U32 start = prevWordPos(mScrollHPos), end = nextWordPos(mScrollHPos + rendered_text); - if ( (mSpellCheckStart != start) || (mSpellCheckEnd = end) ) + if ( (mSpellCheckStart != start) || (mSpellCheckEnd != end) ) { const LLWString& text = mText.getWString().substr(start, end); -- cgit v1.2.3 From defbd61d318d0da12fdea208cf2b2297d9a6b122 Mon Sep 17 00:00:00 2001 From: Dave Parks Date: Thu, 31 May 2012 13:25:19 -0500 Subject: MAINT-639 Fix for random rainbow effects on some prims. --- indra/newview/llface.cpp | 54 ++++++++------------------------------------ indra/newview/llface.h | 11 ++------- indra/newview/llvovolume.cpp | 40 ++++---------------------------- 3 files changed, 15 insertions(+), 90 deletions(-) (limited to 'indra') diff --git a/indra/newview/llface.cpp b/indra/newview/llface.cpp index bc8d7fa71f..49a20d5ef9 100644 --- a/indra/newview/llface.cpp +++ b/indra/newview/llface.cpp @@ -187,12 +187,6 @@ void LLFace::init(LLDrawable* drawablep, LLViewerObject* objp) mFaceColor = LLColor4(1,0,0,1); - mLastVertexBuffer = mVertexBuffer; - mLastGeomCount = mGeomCount; - mLastGeomIndex = mGeomIndex; - mLastIndicesCount = mIndicesCount; - mLastIndicesIndex = mIndicesIndex; - mImportanceToCamera = 0.f ; mBoundingSphereRadius = 0.0f ; @@ -219,6 +213,7 @@ void LLFace::destroy() mIndicesIndex != 0xFFFFFFFF) { LLVOPartGroup::freeVBSlot(getGeomIndex()/4); + mIndicesIndex = 0xFFFFFFFF; } if (mDrawPoolp) @@ -390,7 +385,6 @@ void LLFace::setSize(S32 num_vertices, S32 num_indices, bool align) mGeomCount = num_vertices; mIndicesCount = num_indices; mVertexBuffer = NULL; - mLastVertexBuffer = NULL; } llassert(verify()); @@ -783,12 +777,6 @@ BOOL LLFace::genVolumeBBoxes(const LLVolume &volume, S32 f, LLMatrix4a mat_normal; mat_normal.loadu(mat_normal_in); - //if (mDrawablep->isState(LLDrawable::REBUILD_VOLUME)) - //{ //vertex buffer no longer valid - // mVertexBuffer = NULL; - // mLastVertexBuffer = NULL; - //} - //VECTORIZE THIS LLVector4a min,max; @@ -1050,30 +1038,13 @@ bool LLFace::calcAlignedPlanarTE(const LLFace* align_to, LLVector2* res_st_offs void LLFace::updateRebuildFlags() { - if (!mDrawablep->isState(LLDrawable::REBUILD_VOLUME)) - { - BOOL moved = TRUE; - if (mLastVertexBuffer == mVertexBuffer && - !mVertexBuffer->isEmpty()) - { //this face really doesn't need to be regenerated, try real hard not to do so - if (mLastGeomCount == mGeomCount && - mLastGeomIndex == mGeomIndex && - mLastIndicesCount == mIndicesCount && - mLastIndicesIndex == mIndicesIndex) - { //data is in same location in vertex buffer - moved = FALSE; - } - } - mLastMoveTime = gFrameTimeSeconds; - - if (moved) - { - mDrawablep->setState(LLDrawable::REBUILD_VOLUME); - } + if (mDrawablep->isState(LLDrawable::REBUILD_VOLUME)) + { //this rebuild is zero overhead (direct consequence of some change that affects this face) + mLastUpdateTime = gFrameTimeSeconds; } else - { - mLastUpdateTime = gFrameTimeSeconds; + { //this rebuild is overhead (side effect of some change that does not affect this face) + mLastMoveTime = gFrameTimeSeconds; } } @@ -1228,9 +1199,7 @@ BOOL LLFace::getGeometryVolume(const LLVolume& volume, << " VF Num Indices: " << num_indices << " Indices Index: " << mIndicesIndex << " VB Num Indices: " << mVertexBuffer->getNumIndices() << llendl; - llwarns << "Last Indices Count: " << mLastIndicesCount - << " Last Indices Index: " << mLastIndicesIndex - << " Face Index: " << f + llwarns << " Face Index: " << f << " Pool Type: " << mPoolType << llendl; return FALSE; } @@ -1404,6 +1373,7 @@ BOOL LLFace::getGeometryVolume(const LLVolume& volume, static LLCachedControl use_transform_feedback(gSavedSettings, "RenderUseTransformFeedback"); +#ifdef GL_TRANSFORM_FEEDBACK_BUFFER if (use_transform_feedback && gTransformPositionProgram.mProgramObject && //transform shaders are loaded mVertexBuffer->useVBOs() && //target buffer is in VRAM @@ -1547,6 +1517,7 @@ BOOL LLFace::getGeometryVolume(const LLVolume& volume, } } else +#endif { //if it's not fullbright and has no normals, bake sunlight based on face normal //bool bake_sunlight = !getTextureEntry()->getFullbright() && @@ -2167,12 +2138,6 @@ BOOL LLFace::getGeometryVolume(const LLVolume& volume, } - mLastVertexBuffer = mVertexBuffer; - mLastGeomCount = mGeomCount; - mLastGeomIndex = mGeomIndex; - mLastIndicesCount = mIndicesCount; - mLastIndicesIndex = mIndicesIndex; - return TRUE; } @@ -2751,7 +2716,6 @@ void LLFace::setVertexBuffer(LLVertexBuffer* buffer) void LLFace::clearVertexBuffer() { mVertexBuffer = NULL; - mLastVertexBuffer = NULL; } //static diff --git a/indra/newview/llface.h b/indra/newview/llface.h index c31f357693..76ea5c853a 100644 --- a/indra/newview/llface.h +++ b/indra/newview/llface.h @@ -224,7 +224,7 @@ public: //vertex buffer tracking void setVertexBuffer(LLVertexBuffer* buffer); - void clearVertexBuffer(); //sets mVertexBuffer and mLastVertexBuffer to NULL + void clearVertexBuffer(); //sets mVertexBuffer to NULL LLVertexBuffer* getVertexBuffer() const { return mVertexBuffer; } U32 getRiggedVertexBufferDataMask() const; S32 getRiggedIndex(U32 type) const; @@ -257,8 +257,7 @@ public: private: LLPointer mVertexBuffer; - LLPointer mLastVertexBuffer; - + U32 mState; LLFacePool* mDrawPoolp; U32 mPoolType; @@ -271,12 +270,6 @@ private: U32 mIndicesIndex; // index into draw pool for indices (yeah, I know!) S32 mIndexInTex ; - //previous rebuild's geometry info - U16 mLastGeomCount; - U16 mLastGeomIndex; - U32 mLastIndicesCount; - U32 mLastIndicesIndex; - LLXformMatrix* mXform; LLPointer mTexture; LLPointer mDrawablep; diff --git a/indra/newview/llvovolume.cpp b/indra/newview/llvovolume.cpp index 9d6a12cc6e..c4e7ea44b4 100644 --- a/indra/newview/llvovolume.cpp +++ b/indra/newview/llvovolume.cpp @@ -4987,45 +4987,13 @@ void LLVolumeGeometryManager::genDrawInfo(LLSpatialGroup* group, U32 mask, std:: } } - //create/delete/resize vertex buffer if needed + //create vertex buffer LLVertexBuffer* buffer = NULL; - if (group->mBufferUsage != GL_DYNAMIC_DRAW_ARB) - { //try to find a buffer to reuse - LLFastTimer t(FTM_GEN_DRAW_INFO_FIND_VB); - LLSpatialGroup::buffer_texture_map_t::iterator found_iter = group->mBufferMap[mask].find(*face_iter); - - if (found_iter != group->mBufferMap[mask].end()) - { - if ((U32) buffer_index < found_iter->second.size()) - { - buffer = found_iter->second[buffer_index]; - } - } - } - { LLFastTimer t(FTM_GEN_DRAW_INFO_ALLOCATE); - - if (!buffer || !buffer->isWriteable()) - { //create new buffer if needed - buffer = createVertexBuffer(mask, buffer_usage); - buffer->allocateBuffer(geom_count, index_count, TRUE); - } - else - { //resize pre-existing buffer - LLFastTimer t(FTM_GEN_DRAW_INFO_RESIZE_VB); - if (LLVertexBuffer::sEnableVBOs && buffer->getUsage() != buffer_usage || - buffer->getTypeMask() != mask) - { - buffer = createVertexBuffer(mask, buffer_usage); - buffer->allocateBuffer(geom_count, index_count, TRUE); - } - else - { - buffer->resizeBuffer(geom_count, index_count); - } - } + buffer = createVertexBuffer(mask, buffer_usage); + buffer->allocateBuffer(geom_count, index_count, TRUE); } group->mGeometryBytes += buffer->getSize() + buffer->getIndicesSize(); @@ -5070,7 +5038,7 @@ void LLVolumeGeometryManager::genDrawInfo(LLSpatialGroup* group, U32 mask, std:: llassert(!facep->isState(LLFace::RIGGED)); facep->getGeometryVolume(*volume, te_idx, - vobj->getRelativeXform(), vobj->getRelativeXformInvTrans(), index_offset); + vobj->getRelativeXform(), vobj->getRelativeXformInvTrans(), index_offset,true); if (drawablep->isState(LLDrawable::ANIMATED_CHILD)) { -- cgit v1.2.3 From e2e33c0ed5f2acbbfe35c46b1298ed56eb9d1003 Mon Sep 17 00:00:00 2001 From: Kitty Barnett Date: Thu, 31 May 2012 20:47:14 +0200 Subject: STORM-276 FIXED Last word in a line editor isn't spell checked --- indra/llui/lllineeditor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/llui/lllineeditor.cpp b/indra/llui/lllineeditor.cpp index 1e0b194e44..ae1f7f2419 100644 --- a/indra/llui/lllineeditor.cpp +++ b/indra/llui/lllineeditor.cpp @@ -1905,7 +1905,7 @@ void LLLineEditor::draw() { word_end++; } - if (word_end >= text.length()) + if (word_end > text.length()) break; // Don't process words shorter than 3 characters -- cgit v1.2.3 From 5e5dbd718e65dc30365bf435a7a865e7f95096cc Mon Sep 17 00:00:00 2001 From: Oz Linden Date: Thu, 31 May 2012 16:12:52 -0400 Subject: fix spell checker floater registration --- indra/newview/llfloaterspellchecksettings.h | 6 +++--- indra/newview/llviewerfloaterreg.cpp | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'indra') diff --git a/indra/newview/llfloaterspellchecksettings.h b/indra/newview/llfloaterspellchecksettings.h index 33c376fff6..2fbf47617a 100644 --- a/indra/newview/llfloaterspellchecksettings.h +++ b/indra/newview/llfloaterspellchecksettings.h @@ -24,8 +24,8 @@ * $/LicenseInfo$ */ -#ifndef LLFLOATERAUTOREPLACESETTINGS_H -#define LLFLOATERAUTOREPLACESETTINGS_H +#ifndef LLFLOATERSPELLCHECKERSETTINGS_H +#define LLFLOATERSPELLCHECKERSETTINGS_H #include "llfloater.h" @@ -45,4 +45,4 @@ protected: void refreshDictionaryLists(bool from_settings); }; -#endif // LLFLOATERAUTOREPLACESETTINGS_H +#endif // LLFLOATERSPELLCHECKERSETTINGS_H diff --git a/indra/newview/llviewerfloaterreg.cpp b/indra/newview/llviewerfloaterreg.cpp index d310e5a09a..4d84262a3a 100644 --- a/indra/newview/llviewerfloaterreg.cpp +++ b/indra/newview/llviewerfloaterreg.cpp @@ -249,8 +249,8 @@ void LLViewerFloaterReg::registerFloaters() LLFloaterReg::add("preferences", "floater_preferences.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("prefs_proxy", "floater_preferences_proxy.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("prefs_hardware_settings", "floater_hardware_settings.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); - LLFloaterReg::add("prefs_spellchecker", "floater_spellcheck.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("prefs_translation", "floater_translation_settings.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); + LLFloaterReg::add("prefs_spellchecker", "floater_spellcheck.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("prefs_autoreplace", "floater_autoreplace.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("perm_prefs", "floater_perm_prefs.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); LLFloaterReg::add("picks", "floater_picks.xml", (LLFloaterBuildFunc)&LLFloaterReg::build); -- cgit v1.2.3 From fabc4e470b338c1f7d09fa86373ca82d7a08532d Mon Sep 17 00:00:00 2001 From: Todd Stinson Date: Fri, 1 Jun 2012 11:32:57 -0700 Subject: EXP-1950: Correcting typo in notification. --- indra/newview/skins/default/xui/en/notifications.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'indra') diff --git a/indra/newview/skins/default/xui/en/notifications.xml b/indra/newview/skins/default/xui/en/notifications.xml index 1b4123efaa..458b164ce0 100644 --- a/indra/newview/skins/default/xui/en/notifications.xml +++ b/indra/newview/skins/default/xui/en/notifications.xml @@ -4115,7 +4115,7 @@ The region you're trying to visit contains [REGIONMATURITY] content, but your cu type="alertmodal"> fail confirm -The region you're trying to visit contains [REGIONMATURITY] content, but your current preferences are set to exclude [REGIONMATURITY] content. We can change your preferences, or you can cancel. After your preferences are changed, you may attempt enter the region again. +The region you're trying to visit contains [REGIONMATURITY] content, but your current preferences are set to exclude [REGIONMATURITY] content. We can change your preferences, or you can cancel. After your preferences are changed, you may attempt to enter the region again.
-- cgit v1.2.3 From 32063b59994c4e08f37f59fddf6bb2e7af252a9d Mon Sep 17 00:00:00 2001 From: Todd Stinson Date: Tue, 12 Jun 2012 16:58:59 -0700 Subject: EXP-1953: Altering the behavior of building an LLTextBase such that icons are appended in place rather than prepended out of context. --- indra/llui/lltextbase.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'indra') diff --git a/indra/llui/lltextbase.cpp b/indra/llui/lltextbase.cpp index 7aeeae298f..ef17fa4887 100644 --- a/indra/llui/lltextbase.cpp +++ b/indra/llui/lltextbase.cpp @@ -1699,9 +1699,6 @@ void LLTextBase::appendTextImpl(const std::string &new_text, const LLStyle::Para while ( LLUrlRegistry::instance().findUrl(text, match, boost::bind(&LLTextBase::replaceUrl, this, _1, _2, _3)) ) { - - LLTextUtil::processUrlMatch(&match,this); - start = match.getStart(); end = match.getEnd()+1; @@ -1737,6 +1734,8 @@ void LLTextBase::appendTextImpl(const std::string &new_text, const LLStyle::Para } } + LLTextUtil::processUrlMatch(&match,this); + // move on to the rest of the text after the Url if (end < (S32)text.length()) { -- cgit v1.2.3 From 5a76b1dc2fcb5b81c0c8f2a6c1539a23441260f6 Mon Sep 17 00:00:00 2001 From: Todd Stinson Date: Tue, 12 Jun 2012 17:29:03 -0700 Subject: EXP-1953: Updating copy after Leo creating the final copy in the jira. --- indra/newview/skins/default/xui/en/notifications.xml | 13 ++++++++----- indra/newview/skins/default/xui/en/strings.xml | 2 +- 2 files changed, 9 insertions(+), 6 deletions(-) (limited to 'indra') diff --git a/indra/newview/skins/default/xui/en/notifications.xml b/indra/newview/skins/default/xui/en/notifications.xml index 7b01b928b4..2376365505 100644 --- a/indra/newview/skins/default/xui/en/notifications.xml +++ b/indra/newview/skins/default/xui/en/notifications.xml @@ -6270,7 +6270,8 @@ Your object named <nolink>[OBJECTFROMNAME]</nolink> has given you th type="offer"> [NAME_SLURL] has offered to teleport you to their location: -[MESSAGE] - [MATURITY_STR] <icon>[MATURITY_ICON]</icon> +“[MESSAGE]” +<icon>[MATURITY_ICON]</icon> - [MATURITY_STR] confirm