Typica is a free program for professional coffee roasters. https://typica.us
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

typica.w 705KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020
  1. % Instructions for generating source code and documentation
  2. % Step 1. Convert metapost diagrams into PDF documents
  3. % $ mptopdf pipes.mp ; epstopdf pipes.ps
  4. % $ mptopdf roast.mp ; epstopdf roast.ps
  5. % $ mptopdf search.mp ; epstopdf search.ps
  6. % Step 2. Weave and typeset
  7. % $ cweave typica
  8. % $ pdftex typica
  9. % Step 3. Tangle and moc
  10. % $ ctangle typica ; mv typica.c typica.cpp
  11. % $ moc typica.cpp > moc_typica.cpp
  12. %
  13. % If you have trouble compiling, check to make sure the required headers are in
  14. % your header search path and check to make sure the required libraries are
  15. % linked. If using qmake to generate a project file, remember to add the
  16. % following lines to your .pro file:
  17. % QT += xml
  18. % QT += script
  19. % Document style instructions
  20. \input graphicx.tex
  21. \mark{\noexpand\nullsec0{A Note on Notation}}
  22. \def\pn{Typica}
  23. \def\filebase{typica}
  24. \def\version{1.7.0 \number\year-\number\month-\number\day}
  25. \def\years{2007--2016}
  26. \def\title{\pn{} (Version \version)}
  27. \newskip\dangerskipb
  28. \newskip\dangerskip
  29. \dangerskip=20pt
  30. \dangerskipb=42pt
  31. \def\hang{\hangindent\dangerskip}
  32. \def\hangb{\hangindent\dangerskipb}
  33. \font\manual=manfnt at 12pt
  34. \def\danbend{{\manual\char127}}
  35. \def\datanger{\medbreak\begingroup\clubpenalty=10000
  36. \def\par{\endgraf\endgroup\medbreak} \noindent\hang\hangafter=-2
  37. \hbox to0pt{\hskip-3.5pc\danbend\hfill}}
  38. \outer\def\danger{\datanger}%
  39. %
  40. \def\datangerb{\medbreak\begingroup\clubpenalty=10000
  41. \def\par{\endgraf\endgroup\medbreak} \noindent\hang\hangafter=-2
  42. \hbox to0pt{\hskip-3.5pc\danbend\hfill}}
  43. \outer\def\dangerb{\datangerb}
  44. \def\endanger{\medskip}
  45. \def\nullsec{\S1}
  46. \def\lheader{\mainfont\the\pageno\kern1pc(\topsecno)\eightrm
  47. \qquad\grouptitle\hfill\title}
  48. \def\rheader{\eightrm\title\hfill\grouptitle\qquad\mainfont
  49. (\topsecno)\kern1pc\the\pageno}
  50. \def\botofcontents{\vfill
  51. \noindent Copyright \copyright\ \years~Neal Evan Wilson
  52. \bigskip\noindent Permission is hereby granted, free of charge, to any
  53. person obtaining a copy of this software and associated documentation files
  54. (the ``Software''), to deal in the Software without restriction, including
  55. without limitation the rights to use, copy, modify, merge, publish,
  56. distribute, sublicense, and/or sell copies of the Software, and to permit
  57. persons to whom the Software is furnished to do so, subject to the following
  58. conditions:\medskip
  59. The above copyright notice and this permission notice shall be included in
  60. all copies or substantial portions of the Software.\medskip
  61. THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  62. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  63. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  64. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  65. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  66. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  67. IN THE SOFTWARE.
  68. \bigskip\noindent Parts of \pn{} are from QextSerialPort which is used under the
  69. MIT license as follows:
  70. \bigskip\noindent Copyright \copyright\ 2000--2003 Wayne Roth
  71. \noindent Copyright \copyright\ 2004--2007 Stefan Sander
  72. \noindent Copyright \copyright\ 2007 Michal Policht
  73. \noindent Copyright \copyright\ 2008 Brandon Fosdick
  74. \noindent Copyright \copyright\ 2009--2010 Liam Staskawicz
  75. \noindent Copyright \copyright\ 2011 Debao Zhang
  76. \bigskip\noindent Web: http://code.google.com/p/qextserialport/
  77. \bigskip\noindent Permission is hereby granted, free of charge, to any person obtaining
  78. a copy of this software and associated documentation files (the
  79. ``Software''), to deal in the Software without restriction, including
  80. without limitation the rights to use, copy, modify, merge, publish,
  81. distribute, sublicense, and/or sell copies of the Software, and to
  82. permit persons to whom the Software is furnished to do so, subject to
  83. the following conditions:
  84. The above copyright notice and this permission notice shall be
  85. included in all copies or substantial portions of the Software.
  86. THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
  87. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  88. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  89. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  90. LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  91. OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  92. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  93. }
  94. \let\K=\leftarrow
  95. \def\CPLUSPLUS/{{%
  96. \mc C{\hbox{\kern.5pt\raise1pt\hbox{\sevenrm+\kern-1pt+}\kern.5pt}}
  97. \spacefactor1000}}
  98. \def\PP{\uparrow}
  99. \def\MM{\downarrow}
  100. \newbox\DCBox
  101. \setbox\DCBox=\hbox{$\in$}
  102. \def\DC{\copy\DCBox}
  103. \newbox\MODbox \setbox\MODbox=\hbox{\eightrm MOD}
  104. \def\MOD{\mathbin{\copy\MODbox}}
  105. % Title page
  106. \font\authorfont=cmr12
  107. \null\vfill
  108. \centerline{\titlefont \pn}
  109. \vskip 18pt\centerline{(Version \version)}
  110. \vskip 24pt\centerline{\authorfont Neal Evan Wilson}
  111. \vfill
  112. \titletrue\eject\hbox to 0pt{}
  113. \pageno=0 \titletrue\eject
  114. \secpagedepth=1
  115. % Convenience macros
  116. \def\newline{\vskip\baselineskip}
  117. \def\cweb{\.{CWEB}}
  118. \def\web{\.{WEB}}
  119. \newcount\footnotenumber
  120. \def\nfnote{\global\advance\footnotenumber by 1
  121. \footnote{$^{\the\footnotenumber}$}}
  122. % Listing macro from The TeXBook. See page 381 for an explaination.
  123. \def\uncatcodespecials{\def\do##1{\catcode`##1=12 }\dospecials}
  124. \newcount\lineno
  125. \def\setupverbatim{\tt \lineno=0
  126. \def\par{\leavevmode\endgraf} \catcode`\`=\active
  127. \obeylines \uncatcodespecials \obeyspaces
  128. \everypar{\advance\lineno by1 \llap{\sevenrm\the\lineno\ \ }}}
  129. {\obeyspaces\global\let =\ }
  130. \def\listing#1{\par\begingroup\setupverbatim\input#1 \endgroup}
  131. % Javascript chunk handling
  132. \def\jsfile#1#2{\Y\B\4\X\secno:\.{#1}\X${}\E{}\6$\par
  133. \listing{#2}}
  134. % Type formatting
  135. @s QTime int
  136. @s QMetaType int
  137. @s DAQ int
  138. @s Channel int
  139. @s QString int
  140. @s QObject int
  141. @s QThread int
  142. @s DAQImplementation int
  143. @s QVector int
  144. @s TaskHandle int
  145. @s qint32 int
  146. @s int32 int
  147. @s QMessageBox int
  148. @s QLCDNumber int
  149. @s QWidget int
  150. @s AnnotationButton int
  151. @s AnnotationSpinBox int
  152. @s QPushButton int
  153. @s QTimer int
  154. @s QAction int
  155. @s QApplication int
  156. @s PackLayout int
  157. @s QLayout int
  158. @s QLayoutItem int
  159. @s QRect int
  160. @s QList int
  161. @s QSize int
  162. @s QGraphicsScene int
  163. @s SceneButton int
  164. @s QGraphicsSceneMouseEvent int
  165. @s QPoint int
  166. @s true const
  167. @s false const
  168. @s QGraphicsView int
  169. @s QGraphicsTextItem int
  170. @s QFrame int
  171. @s QPaintDevice int
  172. @s QColor int
  173. @s QBrush int
  174. @s QHash int
  175. @s QPointF int
  176. @s QGraphicsLineItem int
  177. @s MeasurementModel int
  178. @s QTableView int
  179. @s QVariant int
  180. @s QAbstractItemView int
  181. @s QAbstractItemModel int
  182. @s QStringList int
  183. @s QModelIndex int
  184. @s MeasurementList int
  185. @s QVariantList int
  186. @s QSplitter int
  187. @s QHBoxLayout int
  188. @s QMainWindow int
  189. @s QCoreApplication int
  190. @s QSettings int
  191. @s QMenu int
  192. @s QCloseEvent int
  193. @s LogEditWindow int
  194. @s QFile int
  195. @s QFileInfo int
  196. @s QDir int
  197. @s QXmlStreamWriter int
  198. @s QXmlStreamReader int
  199. @s QIODevice int
  200. @s QLabel int
  201. @s QTimeEdit int
  202. @s QSpinBox int
  203. @s QDoubleSpinBox int
  204. @s ThermocoupleType int
  205. @s TemperatureUnits int
  206. @s Qt int
  207. @s emit throw
  208. @s TemperatureDisplay int
  209. @s ZeroEmitter int
  210. @s MeasurementAdapter int
  211. @s GraphView int
  212. @s ZoomLog int
  213. @s TimerDisplay int
  214. @s QBoxLayout int
  215. @s WidgetDecorator int
  216. @s XMLInput int
  217. @s XMLOutput int
  218. @s CSVOutput int
  219. @s QTextStream int
  220. @s QTranslator int
  221. @s QLocale int
  222. @s Application int
  223. @s QScriptContext int
  224. @s QScriptEngine int
  225. @s QScriptEngineDebugger int
  226. @s QScriptValue int
  227. @s FakeDAQ int
  228. @s QMenuBar int
  229. @s QKeySequence int
  230. @s QFileDialog int
  231. @s Measurement int
  232. @s Date int
  233. @s QLibrary int
  234. @s daqfp int
  235. @s QResizeEvent int
  236. @s QVBoxLayout int
  237. @s QByteArray int
  238. @s QSqlDatabase int
  239. @s QComboBox int
  240. @s QXmlStreamAttribute int
  241. @s QSqlQuery int
  242. @s QLineEdit int
  243. @s QDoubleValidator int
  244. @s QIntValidator int
  245. @s QTextEdit int
  246. @s QStandardItemModel int
  247. @s QValidator int
  248. @s QMap int
  249. @s QDomElement int
  250. @s QDomNodeList int
  251. @s QDomNode int
  252. @s QStack int
  253. @s QDomDocument int
  254. @s QDomNamedNodeMap int
  255. @s QFormLayout int
  256. @s QAbstractButton int
  257. @s QAbstractScrollArea int
  258. @s SqlComboBox int
  259. @s QUuid int
  260. @s SqlComboBoxDelegate int
  261. @s QItemDelegate int
  262. @s SqlConnectionSetup int
  263. @s QDialog int
  264. @s QCheckBox int
  265. @s SaltModel int
  266. @s QStyleOptionViewItem int
  267. @s QBuffer int
  268. @s QDateEdit int
  269. @s QCalendarWidget int
  270. @s QDate int
  271. @s QFocusEvent int
  272. @s QGridLayout int
  273. @s QScrollArea int
  274. @s QSqlQueryModel int
  275. @s QSqlRecord int
  276. @s QSqlResult int
  277. @s SqlQueryConnection int
  278. @s QFont int
  279. @s SqlQueryView int
  280. @s QTextDocument int
  281. @s QTextCursor int
  282. @s QTextFrame int
  283. @s ReportTable int
  284. @s QTextTable int
  285. @s QTextTableFormat int
  286. @s QTextFrameFormat int
  287. @s QTextTableCell int
  288. @s QPrinter int
  289. @s QPrintDialog int
  290. @s QSqlError int
  291. @s FormArray int
  292. @s QRegExp int
  293. @s QRegExpValidator int
  294. @s QDomDocumentFragment int
  295. @s QStackedLayout int
  296. @s QMouseEvent int
  297. @s QGraphicsPolygonItem int
  298. @s QPolygonF int
  299. @s QGraphicsPathItem int
  300. @s QPainterPath int
  301. @s QXmlQuery int
  302. @s QGraphicsItem int
  303. @s QWebView int
  304. @s QUrl int
  305. @s QShowEvent int
  306. @s QDateTimeEdit int
  307. @s ThresholdDetector int
  308. @s EdgeDirection int
  309. @s DeviceTreeModelNode int
  310. @s QMetaObject int
  311. @s QTreeView int
  312. @s QToolButton int
  313. @s QextPortInfo int
  314. @s QextSerialEnumerator int
  315. @s QMetaEnum int
  316. @s quint16 int
  317. @s QextSerialPort int
  318. @s QGroupBox int
  319. @s QVariantMap int
  320. @s QIcon int
  321. @s QFileInfoList int
  322. @s QMetaMethod int
  323. @f error normal
  324. @f line normal
  325. @f signals public
  326. @f slots int
  327. @f qRegisterMetaType make_pair
  328. @f READ TeX
  329. @f WRITE TeX
  330. @f tr TeX
  331. @f this TeX
  332. @f foreach while
  333. @f qobject_cast make_pair
  334. @f t1 TeX
  335. @f t2 TeX
  336. @f AppInstance TeX
  337. @f getself make_pair
  338. @f TYPE TeX
  339. @f argument make_pair
  340. @f toScriptValue make_pair
  341. @f arg1 TeX
  342. @f arg2 TeX
  343. @f arg3 TeX
  344. @f arg4 TeX
  345. @f findChild make_pair
  346. @f qscriptvalue_cast make_pair
  347. \def\READ{\kern4pt{\tt READ}\kern4pt}
  348. \def\WRITE{\kern4pt{\tt WRITE}\kern4pt}
  349. \def\tr{\delta}
  350. \def\this{\forall}
  351. \def\t#1{t_{#1}}
  352. \def\AppInstance{\.{AppInstance}}
  353. \def\TYPE{\cal T\kern1pt}
  354. \def\arg#1{arg_{#1}}
  355. % Document
  356. @** A Note on Notation.
  357. \noindent As noted by Falkoff and Iverson\nfnote{A.~D.~Falkoff and
  358. K.~E.~Iverson, ``The Design of APL'' (1973)}~there is little need to limit the
  359. typography used to represent a computer program in print. The printed code of
  360. \pn{} uses a number of notations that I have found useful in making clear the
  361. intent of the code. For example, a common mistake in \CPLUSPLUS/ \kern-0.5em
  362. code is the confusion of assignment ({\tt =}) with a test for equality
  363. ({\tt ==}). The \web{} convention of using |=| for assignment and |==| to test
  364. for equality makes such errors obvious at a glance. A list of special symbols
  365. and the equivalent \CPLUSPLUS/text is provided in Table \secno. Most of these
  366. symbols should be familiar\nfnote{The {\tt NULL} symbol is a break with the
  367. conventions of most Qt applications. According the the \CPLUSPLUS/standard, |0|
  368. is both an integer constant and a null pointer constant. Most programs using Qt
  369. use |0| in place of any name for the null pointer, however conceptually these
  370. are two very different things. The notation chosen here was used by Knuth for
  371. similar purposes and seems to have worked well there.}.
  372. \medskip
  373. \settabs 9 \columns
  374. \+&&&{\tt =}&|=|&Assignment\cr
  375. \+&&&{\tt --}&|--|&Decrement\cr
  376. \+&&&{\tt ==}&|==|&Equality Test\cr
  377. \+&&&{\tt >=}&|>=|&Greater or Equal Test\cr
  378. \+&&&{\tt ++}&|++|&Increment\cr
  379. \+&&&{\tt !=}&|!=|&Inequality Test\cr
  380. \+&&&{\tt <=}&|<=|&Less or Equal Test\cr
  381. \+&&&{\tt \char'046\char'046}&$\land$&Logical AND\cr
  382. \+&&&{\tt \char'174\char'174}&$\lor$&Logical OR\cr
  383. \+&&&{\tt ::}&|::|&Member of\cr
  384. \+&&&{\tt !}&|!|&Negation\cr
  385. \+&&&{\tt NULL}&|NULL|&Null Pointer\cr
  386. \+&&&{\tt this}&|this|&Object\cr
  387. \+&&&{\tt \%}&|%|&Remainder\cr
  388. \+&&&{\tt tr()}&|tr()|&Translate\cr
  389. \smallskip
  390. \centerline{Table \secno: Special Characters In \pn}
  391. \medskip
  392. Reserved words are set in bold face. As some of these reserved words are also
  393. the names of types, type names that are not specified in \CPLUSPLUS/are also
  394. set in bold face. Type placeholders in template definitions, however, are set in
  395. caligraphic capitals to emphasize that it will be replaced with a real type at
  396. compile time. Variables and class members are set in italics, character strings
  397. are set in a typewriter style with visible spaces. Macro names are also set in
  398. typewriter style. Numeric constants and plain text comments are set in an
  399. upright roman style. Comments containing \CEE/ or mathematics are styled as
  400. such. Code that will be interpreted by the ECMA-262 host environment has no
  401. pretty printing.
  402. \danger With apologies to prof.~Knuth\nfnote{This symbol was introduced in
  403. {\underbar{Computers~\char'046~Typesetting}}@q'@> (Knuth, 1984) to point out material
  404. that is for ``wizards only.'' It seems to be as appropriate a symbol as any to
  405. point out the darker corners of this program.}, code that is known to be
  406. potentially buggy is flagged with a dangerous bend sign. Some of this code is
  407. buggy due to issues with the code \pn{} depends on, others are things that
  408. should be fixed in \pn{}. Of course, there may also be bugs that have not yet
  409. been noticed or have not been attached to a particular block of code.\endanger
  410. A basic familiarity with literate programming techniques (particularly the
  411. conventions of \cweb{}), Qt, and \CPLUSPLUS/is recommended before altering the
  412. program, but an effort has been made to keep the program understandable for
  413. those who are only interested in studying it.
  414. @** Introduction.
  415. \noindent A common tool in the craft of coffee roasting is the data logger.
  416. Perhaps the most commonly used of these fall into the category of manual data
  417. loggers which require the roaster to use paper and a writing utensil,
  418. periodically recording measurements and noting control changes and observations
  419. of interest as needed.
  420. While there are many benefits to recording roast data\nfnote{Torrey Lee, Stephan
  421. Diedrich, Carl Staub, and Jack Newall, ``How to Obtain Excellence with Drum
  422. Roasters'' (2002) {\it Specialty Coffee Association of America 14$^{th}$ Annual
  423. Conference and Exhibition}}, there are a number of limitations to the manual
  424. approach; maintaining the records in a useful order is time consuming and error
  425. prone, it is difficult to work with aggregates of such records, and the
  426. attention required to log the data by hand can distract from the roasting. Using
  427. a computer with automatic data logging software designed with coffee roasting in
  428. mind can reduce or eliminate these deficiencies. \pn{} is one such program.
  429. The file {\tt \filebase.w} contains both \CPLUSPLUS/source code and the
  430. documentation for that code. This file is intended to be processed by
  431. \cweb\nfnote{Donald E. Knuth and Silvio Levy, ``The \cweb{} System of Structured
  432. Documentation'' (1994)}~to produce source code for your compiler and plain
  433. \TeX{}\nfnote{\TeX{} (pronounced $\tau\epsilon\chi$) is a trademark of the
  434. American Mathematical Society.} documentation that can be used to generate a PDF
  435. document for gorgeous printable documentation. These generated files may have
  436. been distributed with your copy of {\tt \filebase.w} for convenience.
  437. Changes to the program can be made in three ways. \cweb{} provides a patching
  438. mechanism which can be used to experiment with the code without risk of
  439. clobbering it. Instructions for the construction of such a change file can be
  440. found in the \cweb{} documentation. Adding the name of the change file to the
  441. invocation of {\tt ctangle} and {\tt cweave} will incorporate that change
  442. seamlessly in both source and documentation files. A section is provided at the
  443. end of this program for use with this mechanism in the case that new sections
  444. must be added. Another way to create persistent modifications is to alter
  445. {\tt \filebase.w} however this may make it more difficult to use changes with
  446. future versions of the software. Changes should not be made to
  447. {\tt \filebase.cpp} if these changes are expected to persist. Finally, it is
  448. possible to make many changes to how the program looks and behaves by creating a
  449. new configuration document for the program to load. Modifications made in this
  450. way do not even require recompiling the software. Examples that can serve as a
  451. starting point for such customizations are provided with \pn{}.
  452. \pn{} is a work in progress. There are several portions of the documentation
  453. that contain suggestions for future improvement. These notes provide clues for
  454. my future development plans. Naturally, if you have needs which are not quite
  455. addressed by this program, you should feel free to modify the code to suit your
  456. needs. Hopefully this will be easy to do.
  457. In the spirit of Benjamin Franklin\nfnote{``\dots as we enjoy great advantages
  458. from the inventions of others, we should be glad of an opportunity to serve
  459. others by any invention of ours; and this we should do freely and
  460. generously.''
  461. --- Benjamin Franklin, \underbar{The Private Life of the Late
  462. Benjamin Franklin, LL.D.~Originally
  463. Written By Himself, And Now}\par\noindent
  464. \underbar{Translated From The French} (1793)}, \pn{} is shared
  465. with minimal restriction (see the license after the table of contents for legal
  466. requirements). Libraries used by \pn{} may have other restrictions. Before
  467. undertaking to distribute a binary created from this code, you may want to
  468. either determine your rights with regard to these libraries or modify the
  469. program to remove them.
  470. As CWEB generates files with the wrong extension, we leave the default
  471. generated file empty.
  472. @c
  473. /* Nothing to see here. */
  474. @ The following is an overview of the structure of \pn:
  475. @(typica.cpp@>=
  476. #define PROGRAM_NAME "Typica"
  477. @<Header files to include@>@/
  478. @<Class declarations@>@/
  479. @<Function prototypes for scripting@>@/
  480. @<Logging function prototype@>@/
  481. @<Class implementations@>@/
  482. @<Functions for scripting@>@/
  483. @<Logging function implementation@>@/
  484. @<The main program@>
  485. #include "moc_typica.cpp"
  486. @ \pn{} is made of a number of distinct classes.
  487. @<Class implementations@>=
  488. @<NodeInserter implementation@>@/
  489. @<Measurement implementation@>@/
  490. @<DAQ Implementation@>@/
  491. @<DataqSdkDevice implementation@>@/
  492. @<FakeDAQ Implementation@>@/
  493. @<Channel Implementation@>@/
  494. @<TemperatureDisplay Implementation@>@/
  495. @<MeasurementTimeOffset Implementation@>@/
  496. @<ZeroEmitter Implementation@>@/
  497. @<MeasurementAdapter Implementation@>@/
  498. @<GraphView Implementation@>@/
  499. @<ZoomLog Implementation@>@/
  500. @<MeasurementModel Implementation@>@/
  501. @<AnnotationButton Implementation@>@/
  502. @<AnnotationSpinBox Implementation@>@/
  503. @<TimerDisplay Implementation@>@/
  504. @<PackLayout Implementation@>@/
  505. @<SceneButton Implementation@>@/
  506. @<WidgetDecorator Implementation@>@/
  507. @<LogEditWindow Implementation@>@/
  508. @<XMLOutput Implementation@>@/
  509. @<XMLInput Implementation@>@/
  510. @<CSVOutput Implementation@>@/
  511. @<SaltModel Implementation@>@/
  512. @<SqlComboBox Implementation@>@/
  513. @<SqlComboBoxDelegate Implementation@>@/
  514. @<Application Implementation@>@/
  515. @<SqlConnectionSetup implementation@>@/
  516. @<SqlQueryView implementation@>@/
  517. @<SqlQueryConnection implementation@>@/
  518. @<ReportTable implementation@>@/
  519. @<FormArray implementation@>@/
  520. @<ScaleControl implementation@>@/
  521. @<IntensityControl implementation@>@/
  522. @<ThresholdDetector Implementation@>@/
  523. @<PortSelector implementation@>@/
  524. @<BaudSelector implementation@>@/
  525. @<ParitySelector implementation@>@/
  526. @<FlowSelector implementation@>@/
  527. @<StopSelector implementation@>@/
  528. @<ModbusConfigurator implementation@>@/
  529. @<ShortHexSpinBox implementation@>@/
  530. @<ModbusRTUDevice implementation@>@/
  531. @<DeviceTreeModelNode implementation@>@/
  532. @<DeviceTreeModel implementation@>@/
  533. @<BasicDeviceConfigurationWidget implementation@>@/
  534. @<DeviceConfigurationWindow implementation@>@/
  535. @<Ni9211TcConfWidget implementation@>@/
  536. @<NiDaqMxBase9211ConfWidget implementation@>@/
  537. @<NiDaqMxBaseDriverConfWidget implementation@>@/
  538. @<ReportAction implementation@>@/
  539. @<NumericDelegate implementation@>@/
  540. @<NiDaqMxDriverConfWidget implementation@>@/
  541. @<NiDaqMx9211ConfWidget implementation@>@/
  542. @<NiDaqMxTc01ConfWidget implementation@>@/
  543. @<ModbusRtuPortConfWidget implementation@>@/
  544. @<ModbusRtuDeviceConfWidget implementation@>@/
  545. @<ModbusRtuDeviceTPvConfWidget implementation@>@/
  546. @<ModbusRtuDeviceTSvConfWidget implementation@>@/
  547. @<RoasterConfWidget implementation@>@/
  548. @<AnnotationButtonConfWidget implementation@>@/
  549. @<NoteSpinConfWidget implementation@>@/
  550. @<LinearCalibrator Implementation@>@/
  551. @<LinearSplineInterpolator Implementation@>@/
  552. @<LinearSplineInterpolationConfWidget implementation@>@/
  553. @<TranslationConfWidget implementation@>@/
  554. @<FreeAnnotationConfWidget implementation@>@/
  555. @<RateOfChange implementation@>@/
  556. @<SettingsWindow implementation@>@/
  557. @<GraphSettingsWidget implementation@>@/
  558. @<DataqSdkDeviceConfWidget implementation@>@/
  559. @<SerialScaleConfWidget implementation@>@/
  560. @<ValueAnnotation implementation@>@/
  561. @<ValueAnnotationConfWidget implementation@>@/
  562. @<ModbusNG implementation@>@/
  563. @<ThresholdAnnotationConfWidget implementation@>@/
  564. @<Annotator implementation@>@/
  565. @ A few headers are required for various parts of \pn{}. These allow the use of
  566. various Qt modules.
  567. @<Header files to include@>=
  568. #include <QtCore>
  569. #include <QtGui>
  570. #include <QtScript>
  571. #include <QtScriptTools>
  572. #include <QtXml>
  573. #include <QtSql>
  574. #include <QtDebug>
  575. #include <QtXmlPatterns>
  576. #include <QtWebKit>
  577. #include <QtSvg>
  578. @ New code is being written in separate files in a long term effort to improve
  579. organization of the code. The result of this is that some additional headers
  580. are required here.
  581. @<Header files to include@>=
  582. #include "helpmenu.h"
  583. @** The Scripting Engine.
  584. \noindent The main enhancement of \pn{} version 1.1 is the introduction of a
  585. scriptable environment. This change allows people to easily customize \pn{}
  586. without having to alter the program code. Instead, the user interface and
  587. program data flow is set up with a small script that runs in an ECMA-262 host
  588. environment\nfnote{Standard ECMA-262, 3$^{\rm{rd}}$ Edition\par\hbox{\indent%
  589. \pdfURL{%
  590. http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf}%
  591. {http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf}}}
  592. which requires
  593. significantly less expertise to modify than \pn{} itself. Such a scripting
  594. environment will be familiar to anybody with experience using JavaScript on web
  595. pages or ActionScript in Flash. \pn{}'@q'@>s configuration system was later updated
  596. to support running several script fragments found in an XML configuration
  597. document.
  598. Most of the application classes are available from the scripting environment.
  599. The functions that make this possible are presented along with the classes. A
  600. selection of classes provided by Qt are also available. These are presented
  601. here.
  602. This chunk provides two |QScriptValue| objects which are used in other sections
  603. appended to this chunk.
  604. @<Set up the scripting engine@>=
  605. QScriptEngine *engine = new QScriptEngine;
  606. QScriptValue constructor;
  607. QScriptValue value;
  608. @ A common task when working with objects created from a script is finding the
  609. object a method is called on from the current script context. The code for this
  610. is simple, but lengthy. This is shortened with the use of a template function
  611. that obtains the object in question and casts it to the appropriate type. If an
  612. incorrect type is specified, a null pointer or similarly invalid value will be
  613. returned.
  614. @<Functions for scripting@>=
  615. template<class TYPE> TYPE@, getself(QScriptContext *context)
  616. {
  617. TYPE@, self = qobject_cast<TYPE>(context->thisObject().toQObject());
  618. return self;
  619. }
  620. template<> QTime getself(QScriptContext *context)
  621. {
  622. QTime self = context->thisObject().toVariant().toTime();
  623. return self;
  624. }
  625. template<> QByteArray getself(QScriptContext *context)
  626. {
  627. QByteArray self = context->thisObject().toVariant().toByteArray();
  628. return self;
  629. }
  630. template<> SqlQueryConnection* getself(QScriptContext *context)
  631. {
  632. SqlQueryConnection *self =@|
  633. (SqlQueryConnection *)qscriptvalue_cast<void *>(context->thisObject());
  634. return self;
  635. }
  636. template<> QXmlQuery* getself(QScriptContext *context)
  637. {
  638. QXmlQuery *self =
  639. (QXmlQuery *)qscriptvalue_cast<void *>(context->thisObject());
  640. return self;
  641. }
  642. template<> QXmlStreamWriter* getself(QScriptContext *context)
  643. {
  644. QXmlStreamWriter *self = @|
  645. (QXmlStreamWriter *)qscriptvalue_cast<void *>(context->thisObject());
  646. return self;
  647. }
  648. template<> QXmlStreamReader* getself(QScriptContext *context)
  649. {
  650. QXmlStreamReader *self = @|
  651. (QXmlStreamReader *)qscriptvalue_cast<void *>(context->thisObject());
  652. return self;
  653. }
  654. @ Another common task is obtaining the arguments of a method call from the
  655. script context and casting these arguments to the proper type. This is once
  656. again done with templates.
  657. @<Functions for scripting@>=
  658. template<class TYPE> TYPE@, argument(int arg, QScriptContext *context)
  659. {
  660. TYPE@, argument = qobject_cast<TYPE>(context->argument(arg).toQObject());
  661. return argument;
  662. }
  663. template<> QString argument(int arg, QScriptContext *context)
  664. {
  665. return context->argument(arg).toString();
  666. }
  667. template<> QVariant argument(int arg, QScriptContext *context)
  668. {
  669. return context->argument(arg).toVariant();
  670. }
  671. template<> int argument(int arg, QScriptContext *context)
  672. {
  673. return context->argument(arg).toInt32();
  674. }
  675. template<> SqlQueryConnection* argument(int arg, QScriptContext *context)
  676. {
  677. return (SqlQueryConnection *)
  678. qscriptvalue_cast<void *>(context->argument(arg));
  679. }
  680. template<> QModelIndex argument(int arg, QScriptContext *context)
  681. {
  682. return qscriptvalue_cast<QModelIndex>(context->argument(arg));
  683. }
  684. template<> double argument(int arg, QScriptContext *context)
  685. {
  686. return (double)(context->argument(arg).toNumber());
  687. }
  688. template<> Units::Unit argument(int arg, QScriptContext *context)
  689. {
  690. return (Units::Unit)(context->argument(arg).toInt32());
  691. }
  692. template<> QByteArray argument(int arg, QScriptContext *context)
  693. {
  694. return qscriptvalue_cast<QByteArray>(context->argument(arg));
  695. }
  696. @ The scripting engine is informed of a number of classes defined elsewhere in
  697. the program. Code related to scripting these classes is grouped with the code
  698. implementing the classes. Additionally, there are several classes from Qt which
  699. are also made scriptable. These are detailed in the following sections.
  700. @* Exposing an Object Hierarchy to the Host Environment.
  701. \noindent While QtScript does a generally acceptable job of exposing
  702. information about objects that are available through the meta-object system,
  703. some methods require special handling in order to make them fully available to
  704. the host environment. Several functions are provided which provide a
  705. |QScriptValue| with these additional properties. The functions providing these
  706. properties also call other functions providing the properties of any base
  707. classes. In this way, any additional functionality provided to the host
  708. environment for a base class is also provided for any class that inherits that
  709. base class.
  710. For example, a |QBoxLayout| created in a script will have properties from
  711. |QLayout| which in turn brings in properties from |QObject| and |QLayoutItem|.
  712. A |QMainWindow| would bring in properties from |QWidget| which would bring in
  713. properties from |QObject|.
  714. Neither all methods nor all Qt classes are available from the host environment.
  715. When adding functionality to the host environment, there is a priority on
  716. classes and methods that are useful for \pn{}'@q'@>s intended purpose.
  717. @* Base Classes.
  718. \noindent There are a few classes that are base classes of classes exposed to
  719. the scripting engine. There is no need for the host environment to allow the
  720. creation of these base classes and there may not be methods that must be added
  721. as properties in derived classes, however stub functions are provided so that
  722. in the event that a method from one of these base classes is needed later, it
  723. can be added once for all derived classes.
  724. The first of these is |QObject|.
  725. @<Function prototypes for scripting@>=
  726. void setQObjectProperties(QScriptValue value, QScriptEngine *engine);
  727. @ As there are no properties that need to be set for this class and as this
  728. class does not inherit any other class, nothing needs to be done in this method.
  729. It will, however, be called by subclasses in case this changes in the future.
  730. @<Functions for scripting@>=
  731. void setQObjectProperties(QScriptValue, QScriptEngine *)
  732. {
  733. /* Nothing needs to be done here. */
  734. }
  735. @ The same can be done for |QPaintDevice| and |QLayoutItem|.
  736. @<Function prototypes for scripting@>=
  737. void setQPaintDeviceProperties(QScriptValue value, QScriptEngine *engine);
  738. void setQLayoutItemProperties(QScriptValue value, QScriptEngine *engine);
  739. @ The implementations are similarly empty.
  740. @<Functions for scripting@>=
  741. void setQPaintDeviceProperties(QScriptValue, QScriptEngine *)
  742. {
  743. /* Nothing needs to be done here. */
  744. }
  745. void setQLayoutItemProperties(QScriptValue, QScriptEngine *)
  746. {
  747. /* Nothing needs to be done here. */
  748. }
  749. @* Scripting QWidget.
  750. \noindent The first interesting class in this hierarchy is |QWidget|. This is
  751. mainly used as a base class for other widgets and in such a role it is not
  752. particularly interesting. It is, however, possible to apply a layout to a
  753. |QWidget| and use that to manage the size and position of one or more child
  754. widgets. A few functions are used to accomplish this.
  755. @<Function prototypes for scripting@>=
  756. void setQWidgetProperties(QScriptValue value, QScriptEngine *engine);
  757. QScriptValue constructQWidget(QScriptContext *context, QScriptEngine *engine);
  758. QScriptValue QWidget_setLayout(QScriptContext *context, QScriptEngine *engine);
  759. QScriptValue QWidget_activateWindow(QScriptContext *context,
  760. QScriptEngine *engine);
  761. @ The script constructor must be passed to the scripting engine.
  762. @<Set up the scripting engine@>=
  763. constructor = engine->newFunction(constructQWidget);
  764. value = engine->newQMetaObject(&QWidget::staticMetaObject, constructor);
  765. engine->globalObject().setProperty("QWidget", value);
  766. @ The constructor creates a script value, but uses another function to add
  767. properties that wrap methods we want to make available to subclasses. Note that
  768. properties of the base classes are added before properties of this class. This
  769. procedure ensures that properties added from base classes can be be replaced in
  770. subclasses.
  771. @<Functions for scripting@>=
  772. QScriptValue constructQWidget(QScriptContext *, QScriptEngine *engine)
  773. {
  774. QScriptValue object = engine->newQObject(new QWidget);
  775. setQWidgetProperties(object, engine);
  776. return object;
  777. }
  778. void setQWidgetProperties(QScriptValue value, QScriptEngine *engine)
  779. {
  780. setQObjectProperties(value, engine);
  781. setQPaintDeviceProperties(value, engine);
  782. value.setProperty("setLayout", engine->newFunction(QWidget_setLayout));
  783. value.setProperty("activateWindow",
  784. engine->newFunction(QWidget_activateWindow));
  785. }
  786. @ This just leaves the property implementations. |QWidget::setLayout()| takes
  787. one argument, a |QLayout| and returns |void|. This wrapper duplicates this
  788. interface. |QWidget::activateWindow()| takes no arguments and returns nothing
  789. meaningful.
  790. @<Functions for scripting@>=
  791. QScriptValue QWidget_setLayout(QScriptContext *context, QScriptEngine *)
  792. {
  793. if(context->argumentCount() == 1)
  794. {
  795. QWidget *self = getself<QWidget *>(context);
  796. QLayout *layout = argument<QLayout *>(0, context);
  797. if(layout)
  798. {
  799. self->setLayout(layout);
  800. }
  801. else
  802. {
  803. context->throwError("Incorrect argument type passed to "@|
  804. "QWidget::setLayout(). This method requires "@|
  805. "a QLayout.");
  806. }
  807. }
  808. else
  809. {
  810. context->throwError("Incorrect number of arguments passed to "@|
  811. "QWidget::setLayout(). This method takes one "@|
  812. "QLayout as an argument.");
  813. }
  814. return QScriptValue();
  815. }
  816. QScriptValue QWidget_activateWindow(QScriptContext *context,
  817. QScriptEngine *)
  818. {
  819. QWidget *self = getself<QWidget *>(context);
  820. self->activateWindow();
  821. return QScriptValue();
  822. }
  823. @* Scripting QMessageBox.
  824. \noindent Some features require that \pn{} pauses an operation until further
  825. information can be obtained. An example of this is discretionary validation
  826. where input is checked and if it seems unlikely but not impossible to be
  827. correct a dialog should come up asking if that input is correct. If it is not,
  828. the operation should be cancelled and the person using \pn{} should be allowed
  829. to correct the information and try again.
  830. For this use case, it is not necessary to fully expose the |QMessageBox| class.
  831. Instead, it is enough to provide a function that will raise an appropriate
  832. message and return the selected action.
  833. @<Function prototypes for scripting@>=
  834. QScriptValue displayWarning(QScriptContext *context, QScriptEngine *engine);
  835. QScriptValue displayError(QScriptContext *context, QScriptEngine *engine);
  836. @ This function is exposed to the host environment.
  837. @<Set up the scripting engine@>=
  838. constructor = engine->newFunction(displayWarning);
  839. engine->globalObject().setProperty("displayWarning", constructor);
  840. constructor = engine->newFunction(displayError);
  841. engine->globalObject().setProperty("displayError", constructor);
  842. @ The function takes some arguments.
  843. @<Functions for scripting@>=
  844. QScriptValue displayWarning(QScriptContext *context, QScriptEngine *)
  845. {
  846. QMessageBox::StandardButton selection = QMessageBox::warning(NULL,
  847. argument<QString>(0, context),
  848. argument<QString>(1, context),
  849. QMessageBox::Ok | QMessageBox::Cancel);
  850. if(selection == QMessageBox::Ok) {
  851. return QScriptValue(true);
  852. }
  853. return QScriptValue(false);
  854. }
  855. QScriptValue displayError(QScriptContext *context, QScriptEngine *)
  856. {
  857. QMessageBox::critical(NULL, argument<QString>(0, context),
  858. argument<QString>(1, context));
  859. return QScriptValue();
  860. }
  861. @* Scripting QMainWindow.
  862. \noindent Rather than directly exposing |QMainWindow| to the scripting engine,
  863. we expose a class derived from |QMainWindow| with a minor change allowing the
  864. script to be notified when the window is about to be closed.
  865. This allows us to save settings for objects populating the window. Close
  866. handlers can be established by connecting to the |aboutToClose()| signal which
  867. is emitted in the |closeEvent()| handler. The close event is always accepted
  868. after the script has had a chance to respond, so this cannot be used to present
  869. an, ``Are you sure?'' message without additional modification.
  870. Slots are also provided for saving the size and position of the window to
  871. settings and restoring the window geometry from these settings.
  872. As of version 1.4 window geometry management is provided for all windows. The
  873. |restoreSizeAndPosition()| and |saveSizeAndPosition()| methods should be
  874. considered depreciated.
  875. Version 1.6 adds a new property for handling the |windowModified| property
  876. such that an appropriate prompt is provided to confirm or cancel close events.
  877. @<Class declarations@>=
  878. class ScriptQMainWindow : public QMainWindow@/
  879. {@t\1@>@/
  880. Q_OBJECT@;@/
  881. Q_PROPERTY(QString closePrompt READ closePrompt WRITE setClosePrompt)@;@/
  882. public:@/
  883. ScriptQMainWindow();
  884. QString closePrompt();@/
  885. @t\4@>public slots@t\kern-3pt@>:@/
  886. void show();
  887. void saveSizeAndPosition(const QString &key);
  888. void restoreSizeAndPosition(const QString &key);
  889. void displayStatus(const QString &message = QString());
  890. void setClosePrompt(QString prompt);@/
  891. protected:@/
  892. void closeEvent(QCloseEvent *event);
  893. void showEvent(QShowEvent *event);@/
  894. signals:@/
  895. void aboutToClose(void);@/
  896. private:@/
  897. QString cprompt;@t\2@>@/
  898. }@t\kern-3pt@>;
  899. @ The implementation of these functions is simple.
  900. @<Functions for scripting@>=
  901. ScriptQMainWindow::ScriptQMainWindow()@+: QMainWindow(NULL),
  902. cprompt(tr("Closing this window may result in loss of data. Continue?"))@/
  903. {
  904. /* Nothing needs to be done here. */
  905. }
  906. void ScriptQMainWindow::saveSizeAndPosition(const QString &key)
  907. {
  908. QSettings settings;
  909. settings.beginGroup(key);
  910. settings.setValue("pos", pos());
  911. settings.setValue("size", size());
  912. settings.endGroup();
  913. }
  914. void ScriptQMainWindow::restoreSizeAndPosition(const QString &key)
  915. {
  916. QSettings settings;
  917. settings.beginGroup(key);
  918. if(settings.contains("size"))
  919. {
  920. resize(settings.value("size").toSize());
  921. }
  922. if(settings.contains("pos"))
  923. {
  924. move(settings.value("pos").toPoint());
  925. }
  926. settings.endGroup();
  927. }
  928. void ScriptQMainWindow::displayStatus(const QString &message)
  929. {
  930. statusBar()->showMessage(message);
  931. }
  932. void ScriptQMainWindow::showEvent(QShowEvent *event)
  933. {
  934. if(!event->spontaneous())
  935. {
  936. @<Restore window geometry@>@;
  937. event->accept();
  938. }
  939. else
  940. {
  941. event->ignore();
  942. }
  943. }
  944. void ScriptQMainWindow::show()
  945. {
  946. QMainWindow::show();
  947. }
  948. @ When a close event occurs, we check the |windowModified| property to
  949. determine if closing the window could result in loss of data. If this is
  950. true, we allow the event to be cancelled. Otherwise, a signal is emitted which
  951. allows scripts to perform any cleanup that may be required before closing the
  952. window and the window geometry data is saved before allowing the window to
  953. close.
  954. @<Functions for scripting@>=
  955. void ScriptQMainWindow::closeEvent(QCloseEvent *event)
  956. {
  957. if(isWindowModified()) {
  958. @<Allow close event to be cancelled@>@;
  959. }
  960. emit aboutToClose();
  961. @<Save window geometry@>@;
  962. event->accept();
  963. }
  964. @ The prompt text for our confirmation window is provided through the
  965. |closePrompt| property.
  966. @<Allow close event to be cancelled@>=
  967. QMessageBox::StandardButton result;
  968. result = QMessageBox::warning(this, "Typica", closePrompt(),
  969. QMessageBox::Ok | QMessageBox::Cancel);
  970. if(result == QMessageBox::Cancel)
  971. {
  972. event->ignore();
  973. return;
  974. }
  975. @ Implementation of the |closePrompt| property is trivial.
  976. @<Functions for scripting@>=
  977. QString ScriptQMainWindow::closePrompt()
  978. {
  979. return cprompt;
  980. }
  981. void ScriptQMainWindow::setClosePrompt(QString prompt)
  982. {
  983. cprompt = prompt;
  984. }
  985. @ Window geometry management from version 1.4 on makes use of the window ID to
  986. produce an appropriate QSettings key. This decision relies on the ID being set
  987. before any show or close events are received and it relies on every distinct
  988. type of window having a unique ID. If this is not the case then other things
  989. are likely very broken. Note that with this approach multiple instances of the
  990. same type of window will use the same key. This may not be ideal in all cases,
  991. but further refinements can be produced if necessary.
  992. @<Save window geometry@>=
  993. QSettings settings;
  994. settings.setValue(QString("geometries/%1").arg(objectName()), saveGeometry());
  995. @ Restoring saved geometry is performed similarly to saving it.
  996. @<Restore window geometry@>=
  997. QSettings settings;
  998. restoreGeometry(settings.value(QString("geometries/%1").arg(objectName())).
  999. toByteArray());
  1000. @ Three functions are required to obtain the required functionality from a
  1001. script. A fourth adds properties for the object hierarchy.
  1002. @<Function prototypes for scripting@>=
  1003. QScriptValue constructQMainWindow(QScriptContext *context,
  1004. QScriptEngine *engine);
  1005. QScriptValue QMainWindow_setCentralWidget(QScriptContext *context,@|
  1006. QScriptEngine *engine);
  1007. QScriptValue QMainWindow_menuBar(QScriptContext *context,
  1008. QScriptEngine *engine);
  1009. void setQMainWindowProperties(QScriptValue value, QScriptEngine *engine);
  1010. @ Of these, the engine only needs to be informed of the constructor initially.
  1011. @<Set up the scripting engine@>=
  1012. constructor = engine->newFunction(constructQMainWindow);
  1013. value = engine->newQMetaObject(&ScriptQMainWindow::staticMetaObject,
  1014. constructor);
  1015. engine->globalObject().setProperty("QMainWindow", value);
  1016. @ The constructor calls a function to add the additional properties to the
  1017. newly created value.
  1018. @<Functions for scripting@>=
  1019. QScriptValue constructQMainWindow(QScriptContext *, QScriptEngine *engine)
  1020. {
  1021. QScriptValue object = engine->newQObject(new ScriptQMainWindow);
  1022. setQMainWindowProperties(object, engine);
  1023. return object;
  1024. }
  1025. void setQMainWindowProperties(QScriptValue value, QScriptEngine *engine)
  1026. {
  1027. setQWidgetProperties(value, engine);
  1028. value.setProperty("setCentralWidget",
  1029. engine->newFunction(QMainWindow_setCentralWidget));
  1030. value.setProperty("menuBar", engine->newFunction(QMainWindow_menuBar));
  1031. }
  1032. @ The |"setCentralWidget"| property is used for setting a widget in the main
  1033. area of the window. In \pn{} this will usually be a |QSplitter| object, but it
  1034. could also be a bare |QWidget| with a layout managing multiple widgets or a
  1035. custom widget defined in a local change. This is a simple wrapper around
  1036. |QMainWindow::setCentralWidget()|.
  1037. @<Functions for scripting@>=
  1038. QScriptValue QMainWindow_setCentralWidget(QScriptContext *context,
  1039. QScriptEngine *)
  1040. {
  1041. if(context->argumentCount() == 1)
  1042. {
  1043. QMainWindow *self = getself<QMainWindow *>(context);
  1044. QWidget *widget = argument<QWidget *>(0, context);
  1045. if(widget)
  1046. {
  1047. self->setCentralWidget(widget);
  1048. }
  1049. else
  1050. {
  1051. context->throwError("Incorrect argument type passed to "@|
  1052. "QMainWindow::setCentralWidget(). This "@|
  1053. "method requires a QWidget.");
  1054. }
  1055. }
  1056. else
  1057. {
  1058. context->throwError("Incorrect number of arguments passed to "@|
  1059. "QMainWindow::setCentralWidget(). This method "@|
  1060. "takes one QWidget as an argument.");
  1061. }
  1062. return QScriptValue();
  1063. }
  1064. @ The |"menuBar"| property requires that we expose |QMenuBar| to the scripting
  1065. environment in a limited fashion. We don'@q'@>t need to allow scripts to create a
  1066. new menu bar as it can be obtained from the window, however to add the menus to
  1067. the menu bar, we need to add a property to the |QMenuBar| object before passing
  1068. it back.
  1069. @<Functions for scripting@>=
  1070. QScriptValue QMainWindow_menuBar(QScriptContext *context, QScriptEngine *engine)
  1071. {
  1072. QScriptValue object;
  1073. if(context->argumentCount() == 0)
  1074. {
  1075. QMainWindow *self = getself<@[QMainWindow *@]>(context);
  1076. QMenuBar *bar = self->menuBar();
  1077. object = engine->newQObject(bar);
  1078. setQMenuBarProperties(object, engine);
  1079. }
  1080. else
  1081. {
  1082. context->throwError("Incorrect number of arguments passed to "@|
  1083. "QMainWindow::menuBar(). This method takes no "@|
  1084. "arguments.");
  1085. }
  1086. return object;
  1087. }
  1088. @ The previous function is the only place a new |QMenuBar| is created through
  1089. the host environment. Two functions are used in handling this object creation.
  1090. @<Function prototypes for scripting@>=
  1091. void setQMenuBarProperties(QScriptValue value, QScriptEngine *engine);
  1092. QScriptValue QMenuBar_addMenu(QScriptContext *context, QScriptEngine *engine);
  1093. @ The first of these adds the appropriate properties to the newly created
  1094. object.
  1095. @<Functions for scripting@>=
  1096. void setQMenuBarProperties(QScriptValue value, QScriptEngine *engine)
  1097. {
  1098. setQWidgetProperties(value, engine);
  1099. value.setProperty("addMenu", engine->newFunction(QMenuBar_addMenu));
  1100. }
  1101. @ This function can be used to add new menus to a menu bar. In order to do
  1102. anything with the newly created menus, two properties are added to the |QMenu|
  1103. objects which allow actions to be added as menu items and allow separators to be
  1104. placed between groups of menu items.
  1105. At the time of this writing, there are three |QMenuBar::addMenu()| methods. This
  1106. function wraps |QMenu* QMenuBar::addMenu(const QString &title)|.
  1107. @<Functions for scripting@>=
  1108. QScriptValue QMenuBar_addMenu(QScriptContext *context, QScriptEngine *engine)
  1109. {
  1110. QScriptValue object;
  1111. if(context->argumentCount() == 1)
  1112. {
  1113. QMenuBar *self = getself<@[QMenuBar *@]>(context);
  1114. QString title = argument<QString>(0, context);
  1115. object = engine->newQObject(self->addMenu(title));
  1116. setQMenuProperties(object, engine);
  1117. }
  1118. else
  1119. {
  1120. context->throwError("Incorrect number of arguments passed to "@|
  1121. "QMenuBar::addMenu(). This method takes one "@|
  1122. "string as an argument.");
  1123. }
  1124. return object;
  1125. }
  1126. @ These three functions allow adding items to the menu and adding separators
  1127. between groups of items.
  1128. @<Function prototypes for scripting@>=
  1129. void setQMenuProperties(QScriptValue value, QScriptEngine *engine);
  1130. QScriptValue QMenu_addAction(QScriptContext *context, QScriptEngine *engine);
  1131. QScriptValue QMenu_addSeparator(QScriptContext *context, QScriptEngine *engine);
  1132. @ The first of these add properties to newly created |QMenu| objects.
  1133. @<Functions for scripting@>=
  1134. void setQMenuProperties(QScriptValue value, QScriptEngine *engine)
  1135. {
  1136. setQWidgetProperties(value, engine);
  1137. value.setProperty("addAction", engine->newFunction(QMenu_addAction));
  1138. value.setProperty("addSeparator", engine->newFunction(QMenu_addSeparator));
  1139. }
  1140. @ These functions are simple wrappers around |QMenu| methods.
  1141. @<Functions for scripting@>=
  1142. QScriptValue QMenu_addAction(QScriptContext *context, QScriptEngine *)
  1143. {
  1144. if(context->argumentCount() == 1)
  1145. {
  1146. QMenu *self = getself<@[QMenu *@]>(context);
  1147. QAction *action = argument<QAction *>(0, context);
  1148. if(action)
  1149. {
  1150. self->addAction(action);
  1151. }
  1152. else
  1153. {
  1154. context->throwError("Incorrect argument type passed to "@|
  1155. "QMenu::addAction(). This method requires a "@|
  1156. "QAction.");
  1157. }
  1158. }
  1159. else
  1160. {
  1161. context->throwError("Incorrect number of arguments passed to "@|
  1162. "QMenu::addAction(). This method takes one "@|
  1163. "QAction as an argument.");
  1164. }
  1165. return QScriptValue();
  1166. }
  1167. QScriptValue QMenu_addSeparator(QScriptContext *context, QScriptEngine *)
  1168. {
  1169. if(context->argumentCount() == 0)
  1170. {
  1171. QMenu *self = getself<@[QMenu *@]>(context);
  1172. self->addSeparator();
  1173. }
  1174. else
  1175. {
  1176. context->throwError("Incorrect number of arguments passed to "@|
  1177. "QMenu::addSeparator(). This method takes no "@|
  1178. "arguments.");
  1179. }
  1180. return QScriptValue();
  1181. }
  1182. @* Scripting QFrame.
  1183. \noindent |QFrame| is another class for which little needs to be done. It exists
  1184. as a subclass of |QWidget| and a superclass for |QSplitter|, |QLCDNumber|, and
  1185. |QAbstractScrollArea| among other classes.
  1186. @<Function prototypes for scripting@>=
  1187. void setQFrameProperties(QScriptValue value, QScriptEngine *engine);
  1188. QScriptValue constructQFrame(QScriptContext *context, QScriptEngine *engine);
  1189. @ The constructor must be passed to the scripting engine.
  1190. @<Set up the scripting engine@>=
  1191. constructor = engine->newFunction(constructQFrame);
  1192. value = engine->newQMetaObject(&QFrame::staticMetaObject, constructor);
  1193. engine->globalObject().setProperty("QFrame", value);
  1194. @ The implementation of these functions should seem familiar.
  1195. @<Functions for scripting@>=
  1196. QScriptValue constructQFrame(QScriptContext *, QScriptEngine *engine)
  1197. {
  1198. QScriptValue object = engine->newQObject(new QFrame);
  1199. setQFrameProperties(object, engine);
  1200. return object;
  1201. }
  1202. void setQFrameProperties(QScriptValue value, QScriptEngine *engine)
  1203. {
  1204. setQWidgetProperties(value, engine);
  1205. }
  1206. @* Scripting QLabel.
  1207. \noindent When constructing an interface wholly or partially through dynamic
  1208. means rather than entirely through the XML configuration document it can
  1209. sometimes be desirable to construct |QLabel| instances. This is usually used
  1210. to provide a very small amount of text.
  1211. @<Function prototypes for scripting@>=
  1212. void setQLabelProperties(QScriptValue value, QScriptEngine *engine);
  1213. QScriptValue constructQLabel(QScriptContext *context, QScriptEngine *engine);
  1214. @ The constructor must be passed to the scripting engine.
  1215. @<Set up the scripting engine@>=
  1216. constructor = engine->newFunction(constructQLabel);
  1217. value = engine->newQMetaObject(&QLabel::staticMetaObject, constructor);
  1218. engine->globalObject().setProperty("QLabel", value);
  1219. @ In the constructor we allow an optional argument to specify the text of the
  1220. label.
  1221. @<Functions for scripting@>=
  1222. QScriptValue constructQLabel(QScriptContext *context, QScriptEngine *engine)
  1223. {
  1224. QString text;
  1225. if(context->argumentCount() == 1)
  1226. {
  1227. text = argument<QString>(0, context);
  1228. }
  1229. QScriptValue object = engine->newQObject(new QLabel(text));
  1230. setQLabelProperties(object, engine);
  1231. return object;
  1232. }
  1233. void setQLabelProperties(QScriptValue value, QScriptEngine *engine)
  1234. {
  1235. setQFrameProperties(value, engine);
  1236. }
  1237. @* Scripting QSvgWidget.
  1238. \noindent Sometimes it is useful to provide a space for simple drawings without
  1239. the need for all of the other capabilities of a web view. This was introduced
  1240. as a way to draw box plots to help guide the creation of roast specifications.
  1241. @<Function prototypes for scripting@>=
  1242. void setQSvgWidgetProperties(QScriptValue value, QScriptEngine *engine);
  1243. QScriptValue constructQSvgWidget(QScriptContext *context,
  1244. QScriptEngine *engine);
  1245. QScriptValue QSvgWidget_loadDevice(QScriptContext *context,
  1246. QScriptEngine *engine);
  1247. void addSvgWidgetToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  1248. QStack<QLayout *> *layoutStack);
  1249. @ The constructor must be passed to the scripting engine.
  1250. @<Set up the scripting engine@>=
  1251. constructor = engine->newFunction(constructQSvgWidget);
  1252. value = engine->newQMetaObject(&QSvgWidget::staticMetaObject, constructor);
  1253. engine->globalObject().setProperty("QSvgWidget", value);
  1254. @ The constructor is trivial.
  1255. @<Functions for scripting@>=
  1256. QScriptValue constructQSvgWidget(QScriptContext *,
  1257. QScriptEngine *engine)
  1258. {
  1259. QScriptValue object = engine->newQObject(new QSvgWidget);
  1260. setQSvgWidgetProperties(object, engine);
  1261. return object;
  1262. }
  1263. @ A property is added that allows loading data from a |QIODevice|.
  1264. @<Functions for scripting@>=
  1265. void setQSvgWidgetProperties(QScriptValue value, QScriptEngine *engine)
  1266. {
  1267. setQWidgetProperties(value, engine);
  1268. value.setProperty("loadDevice",
  1269. engine->newFunction(QSvgWidget_loadDevice));
  1270. }
  1271. QScriptValue QSvgWidget_loadDevice(QScriptContext *context, QScriptEngine *)
  1272. {
  1273. if(context->argumentCount() == 1)
  1274. {
  1275. QSvgWidget *self = getself<@[QSvgWidget *@]>(context);
  1276. QIODevice *device = argument<QIODevice *>(0, context);
  1277. device->reset();
  1278. QByteArray data = device->readAll();
  1279. self->load(data);
  1280. }
  1281. else
  1282. {
  1283. context->throwError("Incorrect number of arguments passed to "@|
  1284. "QSvgWidget::loadData(). This method takes one "@|
  1285. "QIODevice as an argument.");
  1286. }
  1287. return QScriptValue();
  1288. }
  1289. @ Additional work is needed to allow including this from the XML description of
  1290. a window.
  1291. @<Additional box layout elements@>=
  1292. else if(currentElement.tagName() == "svgwidget")
  1293. {
  1294. addSvgWidgetToLayout(currentElement, widgetStack, layoutStack);
  1295. }
  1296. @ The function used to create this follows the usual pattern.
  1297. @<Functions for scripting@>=
  1298. void addSvgWidgetToLayout(QDomElement element, QStack<QWidget *> *,
  1299. QStack<QLayout *> *layoutStack)
  1300. {
  1301. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  1302. QSvgWidget *widget = new QSvgWidget;
  1303. layout->addWidget(widget);
  1304. QString id = element.attribute("id");
  1305. if(!id.isEmpty())
  1306. {
  1307. widget->setObjectName(id);
  1308. }
  1309. }
  1310. @* Scripting QLineEdit.
  1311. \noindent Similarly, we may want to allow line edits in interfaces defined
  1312. through the host environment. For example, this is used for the free text
  1313. annotation control for roasters this has been configured on.
  1314. @<Function prototypes for scripting@>=
  1315. void setQLineEditProperties(QScriptValue value, QScriptEngine *engine);
  1316. QScriptValue constructQLineEdit(QScriptContext *context, QScriptEngine *engine);
  1317. @ The constructor must be passed to the host environment.
  1318. @<Set up the scripting engine@>=
  1319. constructor = engine->newFunction(constructQLineEdit);
  1320. value = engine->newQMetaObject(&QLineEdit::staticMetaObject, constructor);
  1321. engine->globalObject().setProperty("QLineEdit", value);
  1322. @ The constructor is trivial.
  1323. @<Functions for scripting@>=
  1324. QScriptValue constructQLineEdit(QScriptContext *, QScriptEngine *engine)
  1325. {
  1326. QScriptValue object = engine->newQObject(new QLineEdit());
  1327. setQLineEditProperties(object, engine);
  1328. return object;
  1329. }
  1330. @ At present all of the QLineEdit functionality exposed through this interface
  1331. is provided automatically through the meta-object system.
  1332. @<Functions for scripting@>=
  1333. void setQLineEditProperties(QScriptValue value, QScriptEngine *engine)
  1334. {
  1335. setQWidgetProperties(value, engine);
  1336. }
  1337. @* Scripting QSplitter.
  1338. \noindent The |QSplitter| class is one of the main classes used for user
  1339. interface object layout in \pn{}. To provide this class to the scripting engine,
  1340. we provide five functions: a constructor, a method for adding widgets to the
  1341. splitter, a method for saving the size of each widget in the splitter, a
  1342. method for restoring these saved sizes, and a function for adding these methods
  1343. as properties of newly created |QSplitter| objects.
  1344. @<Function prototypes for scripting@>=
  1345. QScriptValue constructQSplitter(QScriptContext *context, QScriptEngine *engine);
  1346. QScriptValue QSplitter_addWidget(QScriptContext *context,
  1347. QScriptEngine *engine);
  1348. QScriptValue QSplitter_saveState(QScriptContext *context,
  1349. QScriptEngine *engine);
  1350. QScriptValue QSplitter_restoreState(QScriptContext *context,
  1351. QScriptEngine *engine);
  1352. QScriptValue QSplitter_count(QScriptContext *context,
  1353. QScriptEngine *engine);
  1354. void setQSplitterProperties(QScriptValue value, QScriptEngine *engine);
  1355. @ Of these, the scripting engine must be informed of the constructor.
  1356. @<Set up the scripting engine@>=
  1357. constructor = engine->newFunction(constructQSplitter);
  1358. value = engine->newQMetaObject(&QSplitter::staticMetaObject, constructor);
  1359. engine->globalObject().setProperty("QSplitter", value);
  1360. @ The constructor creates the object and adds the required properties to it.
  1361. @<Functions for scripting@>=
  1362. QScriptValue constructQSplitter(QScriptContext *, QScriptEngine *engine)
  1363. {
  1364. QScriptValue object = engine->newQObject(new QSplitter);
  1365. setQSplitterProperties(object, engine);
  1366. return object;
  1367. }
  1368. void setQSplitterProperties(QScriptValue value, QScriptEngine *engine)
  1369. {
  1370. setQFrameProperties(value, engine);
  1371. value.setProperty("addWidget", engine->newFunction(QSplitter_addWidget));
  1372. value.setProperty("saveState", engine->newFunction(QSplitter_saveState));
  1373. value.setProperty("restoreState",
  1374. engine->newFunction(QSplitter_restoreState));
  1375. value.setProperty("count", engine->newFunction(QSplitter_count));
  1376. }
  1377. @ The |"addWidget"| property is a simple wrapper around
  1378. |QSplitter::addWidget()|.
  1379. @<Functions for scripting@>=
  1380. QScriptValue QSplitter_addWidget(QScriptContext *context, QScriptEngine *)
  1381. {
  1382. if(context->argumentCount() == 1)
  1383. {
  1384. QSplitter *self = getself<QSplitter *>(context);
  1385. QWidget *widget = argument<QWidget *>(0, context);
  1386. if(widget)
  1387. {
  1388. self->addWidget(widget);
  1389. }
  1390. else
  1391. {
  1392. context->throwError("Incorrect argument type passed to "@|
  1393. "QSplitter::addWidget(). This method "@|
  1394. "requires a QWidget.");
  1395. }
  1396. }
  1397. else
  1398. {
  1399. context->throwError("Incorrect number of arguments passed to "@|
  1400. "QSplitter::addWidget(). This method takes one "@|
  1401. "QWidget as an argument.");
  1402. }
  1403. return QScriptValue();
  1404. }
  1405. @ The methods for saving and restoring the state of a splitter do not behave
  1406. well when the number of widgets contained in the splitter increase. This is a
  1407. problem in the logging view where we may want to allow zero width indicators
  1408. but reconfiguration can cause the number of indicators to increase. This would
  1409. result in the right most indicators such as the batch timer disappearing. Most
  1410. people do not notice the splitter handle or think to drag that to the left to
  1411. correct this issue so it would be better to save the number of indicators when
  1412. saving the state and if the number of indicators does not match, we should not
  1413. restore the obsolete saved state.
  1414. @<Functions for scripting@>=
  1415. QScriptValue QSplitter_count(QScriptContext *context, QScriptEngine *)
  1416. {
  1417. QSplitter *self = getself<QSplitter *>(context);
  1418. return QScriptValue(self->count());
  1419. }
  1420. @ When saving and restoring the state of a splitter, we always want to do this
  1421. through a |QSettings| object. For this, we take an extra argument specifying the
  1422. settings key to read from or write to. Unlike the equivalent functions called
  1423. from native code, neither of these functions called from a script will return
  1424. the data being saved.
  1425. @<Functions for scripting@>=
  1426. QScriptValue QSplitter_saveState(QScriptContext *context, QScriptEngine *)
  1427. {
  1428. if(context->argumentCount() == 1)
  1429. {
  1430. QSplitter *self = getself<QSplitter *>(context);
  1431. QString key = argument<QString>(0, context);
  1432. QSettings settings;
  1433. settings.setValue(key, self->saveState());
  1434. }
  1435. else
  1436. {
  1437. context->throwError("Incorrect number of arguments passed to "@|
  1438. "QSplitter::saveState(). This method takes one "@|
  1439. "string as an argument.");
  1440. }
  1441. return QScriptValue();
  1442. }
  1443. QScriptValue QSplitter_restoreState(QScriptContext *context, QScriptEngine *)
  1444. {
  1445. if(context->argumentCount() == 1)
  1446. {
  1447. QSplitter *self = getself<QSplitter *>(context);
  1448. QString key = argument<QString>(0, context);
  1449. QSettings settings;
  1450. self->restoreState(settings.value(key).toByteArray());
  1451. }
  1452. else
  1453. {
  1454. context->throwError("Incorrect number of arguments passed to "@|
  1455. "QSplitter::restoreState(). This method takes "@|
  1456. "one string as an argument.");
  1457. }
  1458. return QScriptValue();
  1459. }
  1460. @* Scripting Layout classes.
  1461. \noindent Layout classes simplify managing the size and position of widgets in a
  1462. user interface. Qt provides several such classes, including |QBoxLayout| which
  1463. can be used to construct a variety of different interfaces. As widgets
  1464. containing a layout should not really need to care which layout is being used,
  1465. the |QLayout| class acts as an abstract base for all layout classes. A bare
  1466. |QLayout| will never be constructed, however subclasses can make use of the
  1467. |addWidget()| property.
  1468. @<Function prototypes for scripting@>=
  1469. void setQLayoutProperties(QScriptValue value, QScriptEngine *engine);
  1470. QScriptValue QLayout_addWidget(QScriptContext *context, QScriptEngine *engine);
  1471. @ The implementation is trivial.
  1472. @<Functions for scripting@>=
  1473. void setQLayoutProperties(QScriptValue value, QScriptEngine *engine)
  1474. {
  1475. setQLayoutItemProperties(value, engine);
  1476. value.setProperty("addWidget", engine->newFunction(QLayout_addWidget));
  1477. }
  1478. QScriptValue QLayout_addWidget(QScriptContext *context, QScriptEngine *)
  1479. {
  1480. if(context->argumentCount() == 1)
  1481. {
  1482. QLayout *self = getself<QLayout *>(context);
  1483. QWidget *widget = argument<QWidget *>(0, context);
  1484. if(widget)
  1485. {
  1486. self->addWidget(widget);
  1487. }
  1488. else
  1489. {
  1490. context->throwError("Incorrect argument type passed to "@|
  1491. "QLayout::addWidget(). This method requires "@|
  1492. "a QWidget.");
  1493. }
  1494. }
  1495. else
  1496. {
  1497. context->throwError("Incorrect number of arguments passed to "@|
  1498. "QLayout::addWidget(). This method takes one "@|
  1499. "QWidget as an argument.");
  1500. }
  1501. return QScriptValue();
  1502. }
  1503. @ |QBoxLayout| is a more interesting layout class. This allows widgets to be
  1504. arranged in a single row or column and can be used, for example, to arrange a
  1505. row of buttons as in figure \secno.
  1506. \medskip
  1507. \resizebox*{6.3in}{!}{\includegraphics{boxlayoutexample}}
  1508. \smallskip
  1509. \centerline{Figure \secno: Buttons in a |QBoxLayout|.}
  1510. \medskip
  1511. This class makes use of the |addWidget()| method from |QLayout|.
  1512. @<Function prototypes for scripting@>=
  1513. QScriptValue constructQBoxLayout(QScriptContext *context,
  1514. QScriptEngine *engine);
  1515. void setQBoxLayoutProperties(QScriptValue value, QScriptEngine *engine);
  1516. QScriptValue QBoxLayout_addLayout(QScriptContext *context, QScriptEngine *engine);
  1517. QScriptValue QBoxLayout_addWidget(QScriptContext *context, QScriptEngine *engine);
  1518. @ The script constructor must be passed to the scripting engine.
  1519. @<Set up the scripting engine@>=
  1520. constructor = engine->newFunction(constructQBoxLayout);
  1521. value = engine->newQMetaObject(&QBoxLayout::staticMetaObject, constructor);
  1522. engine->globalObject().setProperty("QBoxLayout", value);
  1523. @ The implementation of these functions should seem familiar by now. Note that
  1524. while a horizontal layout is provided by default, this can be changed from the
  1525. script once the layout is created.
  1526. @<Functions for scripting@>=
  1527. QScriptValue constructQBoxLayout(QScriptContext *, QScriptEngine *engine)
  1528. {
  1529. QScriptValue object =
  1530. engine->newQObject(new QBoxLayout(QBoxLayout::LeftToRight));
  1531. setQBoxLayoutProperties(object, engine);
  1532. return object;
  1533. }
  1534. void setQBoxLayoutProperties(QScriptValue value, QScriptEngine *engine)
  1535. {
  1536. setQLayoutProperties(value, engine);
  1537. value.setProperty("addLayout", engine->newFunction(QBoxLayout_addLayout));
  1538. value.setProperty("addWidget", engine->newFunction(QBoxLayout_addWidget));
  1539. }
  1540. QScriptValue QBoxLayout_addLayout(QScriptContext *context, QScriptEngine *)
  1541. {
  1542. if(context->argumentCount() > 0 && context->argumentCount() < 3)
  1543. {
  1544. QBoxLayout *self = getself<QBoxLayout *>(context);
  1545. QLayout *layout = argument<QLayout *>(0, context);
  1546. int stretch = 0;
  1547. if(context->argumentCount() == 2)
  1548. {
  1549. stretch = argument<int>(1, context);
  1550. }
  1551. if(layout)
  1552. {
  1553. self->addLayout(layout, stretch);
  1554. }
  1555. else
  1556. {
  1557. context->throwError("Incorrect argument type passed to "@|
  1558. "QLayout::addLayout(). This method requires "@|
  1559. "a QLayout.");
  1560. }
  1561. }
  1562. else
  1563. {
  1564. context->throwError("Incorrect number of arguments passed to "@|
  1565. "QLayout::addLayout(). This method takes one "@|
  1566. "QLayout as an argument and optionally one integer.");
  1567. }
  1568. return QScriptValue();
  1569. }
  1570. @ We override the base class wrapper for |addWidget| to add two optional
  1571. arguments: one specifies the stretch factor of the widget and the other
  1572. specifies the alignment of the widget within the layout.
  1573. @<Functions for scripting@>=
  1574. QScriptValue QBoxLayout_addWidget(QScriptContext *context, QScriptEngine *)
  1575. {
  1576. if(context->argumentCount() > 0 && context->argumentCount() < 4)
  1577. {
  1578. QBoxLayout *self = getself<QBoxLayout *>(context);
  1579. QWidget *widget = argument<QWidget *>(0, context);
  1580. int stretch = 0;
  1581. Qt::Alignment alignment = 0;
  1582. if(context->argumentCount() > 1)
  1583. {
  1584. stretch = argument<int>(1, context);
  1585. }
  1586. if(context->argumentCount() > 2)
  1587. {
  1588. alignment = (Qt::Alignment)(argument<int>(2, context));
  1589. }
  1590. if(widget)
  1591. {
  1592. self->addWidget(widget, stretch, alignment);
  1593. }
  1594. else
  1595. {
  1596. context->throwError("Incorrect argument type passed to "@|
  1597. "QBoxLayout::addWidget(). This method requires "@|
  1598. "a QWidget.");
  1599. }
  1600. }
  1601. else
  1602. {
  1603. context->throwError("Incorrect number of arguments passed to "@|
  1604. "QBoxLayout::addWidget(). This method takes one "@|
  1605. "QWidget and optionally up to two integers as "@|
  1606. "arguments.");
  1607. }
  1608. return QScriptValue();
  1609. }
  1610. @* Scripting QAction.
  1611. \noindent The |QAction| class is used in \pn{} to create menu items and respond
  1612. to the selection of these items. Three functions are required for our scripting
  1613. needs with regard to this class.
  1614. @<Function prototypes for scripting@>=
  1615. QScriptValue constructQAction(QScriptContext *context, QScriptEngine *engine);
  1616. QScriptValue QAction_setShortcut(QScriptContext *context,
  1617. QScriptEngine *engine);
  1618. void setQActionProperties(QScriptValue value, QScriptEngine *engine);
  1619. @ The scripting engine must be informed of the constructor.
  1620. @<Set up the scripting engine@>=
  1621. constructor = engine->newFunction(constructQAction);
  1622. value = engine->newQMetaObject(&QAction::staticMetaObject, constructor);
  1623. engine->globalObject().setProperty("QAction", value);
  1624. @ The constructor is simple, however some might sensibly question why the
  1625. |"setShortcut"| property is needed at all. Why not have scripts simply set the
  1626. |shortcut| property of the |QAction| directly? The answer to this is that the
  1627. property expects data of the |QKeySequence| type. While this can be created from
  1628. a |QString|, passing a string to the property through the scripting engine did
  1629. not work at the time this was written.
  1630. @<Functions for scripting@>=
  1631. QScriptValue constructQAction(QScriptContext *, QScriptEngine *engine)
  1632. {
  1633. QScriptValue object = engine->newQObject(new QAction(NULL));
  1634. setQActionProperties(object, engine);
  1635. return object;
  1636. }
  1637. void setQActionProperties(QScriptValue value, QScriptEngine *engine)
  1638. {
  1639. setQObjectProperties(value, engine);
  1640. value.setProperty("setShortcut", engine->newFunction(QAction_setShortcut));
  1641. }
  1642. QScriptValue QAction_setShortcut(QScriptContext *context, QScriptEngine *)
  1643. {
  1644. if(context->argumentCount() == 1)
  1645. {
  1646. QAction *self = getself<@[QAction *@]>(context);
  1647. self->setShortcut(argument<QString>(0, context));
  1648. }
  1649. else
  1650. {
  1651. context->throwError("Incorrect number of arguments passed to "@|
  1652. "QAction::setShortcut(). This method takes one "@|
  1653. "string as an argument.");
  1654. }
  1655. return QScriptValue();
  1656. }
  1657. @* Scripting QFileDialog.
  1658. \noindent |QFileDialog| provides two static member functions which is all that
  1659. we need. The objects returned from these methods are built on the |QDialog|
  1660. abstract base class.
  1661. @<Function prototypes for scripting@>=
  1662. QScriptValue QFileDialog_getOpenFileName(QScriptContext *context,
  1663. QScriptEngine *engine);
  1664. QScriptValue QFileDialog_getSaveFileName(QScriptContext *context,
  1665. QScriptEngine *engine);
  1666. void setQFileDialogProperties(QScriptValue value, QScriptEngine *engine);
  1667. void setQDialogProperties(QScriptValue value, QScriptEngine *engine);
  1668. @ The scripting engine must be informed of the wrapper functions for the static
  1669. methods.
  1670. @<Set up the scripting engine@>=
  1671. value = engine->newQMetaObject(&QFileDialog::staticMetaObject);
  1672. value.setProperty("getOpenFileName",
  1673. engine->newFunction(QFileDialog_getOpenFileName));
  1674. value.setProperty("getSaveFileName",
  1675. engine->newFunction(QFileDialog_getSaveFileName));
  1676. engine->globalObject().setProperty("QFileDialog", value);
  1677. @ This function is just a simple wrapper around the |QFileDialog| method, but
  1678. the object returned has any properties added to the base class available.
  1679. @<Functions for scripting@>=
  1680. QScriptValue QFileDialog_getOpenFileName(QScriptContext *context,
  1681. QScriptEngine *engine)
  1682. {
  1683. QScriptValue retval;
  1684. if(context->argumentCount() == 3)
  1685. {
  1686. QWidget *widget = argument<QWidget *>(0, context);
  1687. if(widget)
  1688. {
  1689. QString caption = argument<QString>(1, context);
  1690. QString dir = argument<QString>(2, context);
  1691. retval = QScriptValue(engine,
  1692. QFileDialog::getOpenFileName(widget, caption,
  1693. dir, "", 0, 0));
  1694. setQFileDialogProperties(retval, engine);
  1695. }
  1696. else
  1697. {
  1698. context->throwError("Incorrect argument type passed to "@|
  1699. "QFileDialog::getOpenFileName(). The first "@|
  1700. "argument to this method must be a QWidget.");
  1701. }
  1702. }
  1703. else
  1704. {
  1705. context->throwError("Incorrect number of arguments passed to "@|
  1706. "QFileDialog::getOpenFileName(). This method "@|
  1707. "takes one QWidget followed by two strings for a "@|
  1708. "total of three arguments.");
  1709. }
  1710. return retval;
  1711. }
  1712. @ Similarly, this just wraps |QFileDialog::getSaveFileName()|.
  1713. @<Functions for scripting@>=
  1714. QScriptValue QFileDialog_getSaveFileName(QScriptContext *context,
  1715. QScriptEngine *engine)
  1716. {
  1717. QScriptValue retval;
  1718. if(context->argumentCount() == 3)
  1719. {
  1720. QWidget *widget = argument<QWidget *>(0, context);
  1721. if(widget)
  1722. {
  1723. QString caption = argument<QString>(1, context);
  1724. QString dir = argument<QString>(2, context);
  1725. retval = QScriptValue(engine,
  1726. QFileDialog::getSaveFileName(widget, caption,
  1727. dir, "", 0, 0));
  1728. setQFileDialogProperties(retval, engine);
  1729. }
  1730. else
  1731. {
  1732. context->throwError("Incorrect argument type passed to "@|
  1733. "QFileDialog::getSaveFileName(). The first "@|
  1734. "argument to this method must be a QWidget.");
  1735. }
  1736. }
  1737. else
  1738. {
  1739. context->throwError("Incorrect number of arguments passed to "@|
  1740. "QFileDialog::getSaveFileName(). This method "@|
  1741. "takes one QWidget followed by two strings for a "@|
  1742. "total of three arguments.");
  1743. }
  1744. return retval;
  1745. }
  1746. @ Adding object hierarchy properties to the objects created above is simple.
  1747. @<Functions for scripting@>=
  1748. void setQFileDialogProperties(QScriptValue value, QScriptEngine *engine)
  1749. {
  1750. setQDialogProperties(value, engine);
  1751. }
  1752. void setQDialogProperties(QScriptValue value, QScriptEngine *engine)
  1753. {
  1754. setQWidgetProperties(value, engine);
  1755. }
  1756. @* Scripting QFile.
  1757. \noindent When using a |QFile| in a script, we only need the constructor and two
  1758. functions for hooking it in with the rest of the object hierarchy.
  1759. @<Function prototypes for scripting@>=
  1760. QScriptValue constructQFile(QScriptContext *context, QScriptEngine *engine);
  1761. void setQFileProperties(QScriptValue value, QScriptEngine *engine);
  1762. QScriptValue QFile_remove(QScriptContext *context, QScriptEngine *engine);
  1763. void setQIODeviceProperties(QScriptValue value, QScriptEngine *engine);
  1764. QScriptValue QIODevice_open(QScriptContext *context, QScriptEngine *engine);
  1765. QScriptValue QIODevice_close(QScriptContext *context, QScriptEngine *engine);
  1766. QScriptValue QIODevice_readToString(QScriptContext *context,
  1767. QScriptEngine *engine);
  1768. QScriptValue QIODevice_putChar(QScriptContext *context, QScriptEngine *engine);
  1769. QScriptValue QIODevice_writeString(QScriptContext *context, QScriptEngine *engine);
  1770. QScriptValue QIODevice_writeBytes(QScriptContext *context, QScriptEngine *engine);
  1771. QScriptValue QIODevice_readBytes(QScriptContext *context, QScriptEngine *engine);
  1772. QScriptValue QIODevice_peek(QScriptContext *context, QScriptEngine *engine);
  1773. QScriptValue QIODevice_read(QScriptContext *context, QScriptEngine *engine);
  1774. @ This function is passed to the scripting engine.
  1775. @<Set up the scripting engine@>=
  1776. constructor = engine->newFunction(constructQFile);
  1777. value = engine->newQMetaObject(&QFile::staticMetaObject, constructor);
  1778. engine->globalObject().setProperty("QFile", value);
  1779. @ The implementation is trivial.
  1780. @<Functions for scripting@>=
  1781. QScriptValue constructQFile(QScriptContext *context, QScriptEngine *engine)
  1782. {
  1783. QScriptValue object =
  1784. engine->newQObject(new QFile(argument<QString>(0, context)));@/
  1785. setQFileProperties(object, engine);
  1786. return object;
  1787. }
  1788. @ |QFile| gets a wrapper around |remove()| to support deleting temporary files.
  1789. @<Functions for scripting@>=
  1790. void setQFileProperties(QScriptValue value, QScriptEngine *engine)
  1791. {
  1792. setQIODeviceProperties(value, engine);
  1793. value.setProperty("remove", engine->newFunction(QFile_remove));
  1794. }
  1795. QScriptValue QFile_remove(QScriptContext *context, QScriptEngine *engine)
  1796. {
  1797. QFile *self = getself<QFile *>(context);
  1798. bool retval = self->remove();
  1799. return QScriptValue(engine, retval);
  1800. }
  1801. @ Although we aren'@q'@>t going to create any instances of |QIODevice| directly,
  1802. subclasses such as |QFile| and |QBuffer| get two additional properties for
  1803. opening and closing the device.
  1804. In order to solve some class interoperability issues, a convenience method is
  1805. also added which is equivalent to creating a |QString| from the |QByteArray|
  1806. returned from the |readAll()| method.
  1807. @<Functions for scripting@>=
  1808. void setQIODeviceProperties(QScriptValue value, QScriptEngine *engine)
  1809. {
  1810. setQObjectProperties(value, engine);
  1811. value.setProperty("open", engine->newFunction(QIODevice_open));
  1812. value.setProperty("close", engine->newFunction(QIODevice_close));
  1813. value.setProperty("readToString",
  1814. engine->newFunction(QIODevice_readToString));
  1815. value.setProperty("putChar", engine->newFunction(QIODevice_putChar));
  1816. value.setProperty("writeString", engine->newFunction(QIODevice_writeString));
  1817. value.setProperty("writeBytes", engine->newFunction(QIODevice_writeBytes));
  1818. value.setProperty("readBytes", engine->newFunction(QIODevice_readBytes));
  1819. value.setProperty("peek", engine->newFunction(QIODevice_peek));
  1820. value.setProperty("read", engine->newFunction(QIODevice_read));
  1821. }
  1822. @ These are simple wrappers. In the case of the |open()| property, one argument
  1823. may be passed specifying the mode used for opening. The supported values for
  1824. this are 1 (Read Only), 2 (Write Only), and 3 (Read Write). If this argument is
  1825. not passed, it is assumed that the user wants read and write access.
  1826. @<Functions for scripting@>=
  1827. QScriptValue QIODevice_open(QScriptContext *context, QScriptEngine *)
  1828. {
  1829. QIODevice *self = getself<QIODevice *>(context);
  1830. bool retval = false;
  1831. if(context->argumentCount() == 1)
  1832. {
  1833. switch(argument<int>(0, context))
  1834. {
  1835. case 1:
  1836. retval = self->open(QIODevice::ReadOnly);
  1837. break;
  1838. case 2:
  1839. retval = self->open(QIODevice::WriteOnly);
  1840. break;
  1841. case 3:
  1842. retval = self->open(QIODevice::ReadWrite);
  1843. break;
  1844. default:
  1845. break;
  1846. }
  1847. }
  1848. else
  1849. {
  1850. retval = self->open(QIODevice::ReadWrite);
  1851. }
  1852. return QScriptValue(retval);
  1853. }
  1854. QScriptValue QIODevice_close(QScriptContext *context, QScriptEngine *)
  1855. {
  1856. QIODevice *self = getself<QIODevice *>(context);
  1857. self->close();
  1858. return QScriptValue();
  1859. }
  1860. @ The |readToString()| method is a simple extension of |QIODevice::readAll()| to
  1861. interface with classes that expect document data in the form of a string. Most
  1862. notably, this includes |QWebView|.
  1863. @<Functions for scripting@>=
  1864. QScriptValue QIODevice_readToString(QScriptContext *context, QScriptEngine *)
  1865. {
  1866. QIODevice *self = getself<QIODevice *>(context);
  1867. self->reset();
  1868. return QScriptValue(QString(self->readAll()));
  1869. }
  1870. @ In support of serial port communications, wrappers around two methods for
  1871. writing data have been added. As these are valid for other classes derived from
  1872. |QIODevice|, they are added here so the functionality is available more
  1873. broadly.
  1874. As we are unable to pass a type that guarantees only a single character, we
  1875. instead accept a string and only pass along the first character.
  1876. @<Functions for scripting@>=
  1877. QScriptValue QIODevice_putChar(QScriptContext *context, QScriptEngine *)
  1878. {
  1879. QIODevice *self = getself<QIODevice *>(context);
  1880. if(context->argumentCount() == 1)
  1881. {
  1882. return QScriptValue(self->putChar(argument<QString>(0, context).toUtf8().at(0)));
  1883. }
  1884. context->throwError("Incorrect number of arguments passed to "@|
  1885. "QIODevice::putChar()");
  1886. return QScriptValue();
  1887. }
  1888. @ Two wrappers are provided around |QIODevice::write()| for outputting
  1889. multi-byte data. If we are writing strings that are valid UTF-8, we can use the
  1890. |writeString| wrapper, but if we require full control over exactly which bytes
  1891. are output, the |writeBytes| wrapper is more appropriate.
  1892. @<Functions for scripting@>=
  1893. QScriptValue QIODevice_writeString(QScriptContext *context, QScriptEngine *)
  1894. {
  1895. QIODevice *self = getself<QIODevice *>(context);
  1896. if(context->argumentCount() == 1)
  1897. {
  1898. self->write(argument<QString>(0, context).toUtf8());
  1899. }
  1900. else
  1901. {
  1902. context->throwError("Incorrect number of arguments passed to "@|
  1903. "QIODevice::writeString()");
  1904. }
  1905. return QScriptValue();
  1906. }
  1907. QScriptValue QIODevice_writeBytes(QScriptContext *context, QScriptEngine *)
  1908. {
  1909. QIODevice *self = getself<QIODevice *>(context);
  1910. if(context->argumentCount() == 1)
  1911. {
  1912. self->write(argument<QByteArray>(0, context));
  1913. }
  1914. else
  1915. {
  1916. context->throwError("Incorrect number of arguments passed to "@|
  1917. "QIODevice::writeBytes()");
  1918. }
  1919. return QScriptValue();
  1920. }
  1921. @ The readBytes method is an alternate wrapper around |QByteArray::readAll()|
  1922. which returns the |QByteArray| instead of converting this to a |QString|.
  1923. @<Functions for scripting@>=
  1924. QScriptValue QIODevice_readBytes(QScriptContext *context, QScriptEngine *engine)
  1925. {
  1926. QIODevice *self = getself<QIODevice *>(context);
  1927. QScriptValue value = engine->toScriptValue<QByteArray>(self->readAll());
  1928. setQByteArrayProperties(value, engine);
  1929. return value;
  1930. }
  1931. @ Wrappers around |peek()| and |read()| are also provided.
  1932. @<Functions for scripting@>=
  1933. QScriptValue QIODevice_peek(QScriptContext *context, QScriptEngine *engine)
  1934. {
  1935. QIODevice *self = getself<QIODevice *>(context);
  1936. QScriptValue value = engine->toScriptValue<QByteArray>(
  1937. self->peek(argument<int>(0, context)));
  1938. setQByteArrayProperties(value, engine);
  1939. return value;
  1940. }
  1941. QScriptValue QIODevice_read(QScriptContext *context, QScriptEngine *engine)
  1942. {
  1943. QIODevice *self = getself<QIODevice *>(context);
  1944. QScriptValue value = engine->toScriptValue<QByteArray>(
  1945. self->read(argument<int>(0, context)));
  1946. setQByteArrayProperties(value, engine);
  1947. return value;
  1948. }
  1949. @* Scripting QProcess.
  1950. \noindent Sometimes it is useful to have \pn work with an external program.
  1951. The initial use case was document generation by typesetting instructions to a
  1952. file and then running \TeX to generate a shelf sign or a sheet of labels.
  1953. Other likely use cases include interfacing with external programs that output
  1954. measurement streams. There are several methods which we may want to expose,
  1955. however this is being done only as needed.
  1956. @<Function prototypes for scripting@>=
  1957. QScriptValue constructQProcess(QScriptContext *context, QScriptEngine *engine);
  1958. void setQProcessProperties(QScriptValue value, QScriptEngine *engine);
  1959. QScriptValue QProcess_execute(QScriptContext *context, QScriptEngine *engine);
  1960. QScriptValue QProcess_startDetached(QScriptContext *context, QScriptEngine *engine);
  1961. QScriptValue QProcess_setWorkingDirectory(QScriptContext *context, QScriptEngine *engine);
  1962. QScriptValue QProcess_start(QScriptContext *context, QScriptEngine *engine);
  1963. @ We follow the same pattern with this as with many other types.
  1964. @<Set up the scripting engine@>=
  1965. constructor = engine->newFunction(constructQProcess);
  1966. value = engine->newQMetaObject(&QProcess::staticMetaObject, constructor);
  1967. engine->globalObject().setProperty("QProcess", value);
  1968. @ The constructor is trivial.
  1969. @<Functions for scripting@>=
  1970. QScriptValue constructQProcess(QScriptContext *, QScriptEngine *engine)
  1971. {
  1972. QScriptValue object = engine->newQObject(new QProcess);
  1973. setQProcessProperties(object, engine);
  1974. return object;
  1975. }
  1976. @ As |QProcess| is a |QIODevice| we inherit some properties from that. We also
  1977. expose some details that are specific to |QProcess|.
  1978. @<Functions for scripting@>=
  1979. void setQProcessProperties(QScriptValue value, QScriptEngine *engine)
  1980. {
  1981. setQIODeviceProperties(value, engine);
  1982. value.setProperty("execute", engine->newFunction(QProcess_execute));
  1983. value.setProperty("startDetached", engine->newFunction(QProcess_startDetached));
  1984. value.setProperty("setWorkingDirectory", engine->newFunction(QProcess_setWorkingDirectory));
  1985. value.setProperty("start", engine->newFunction(QProcess_start));
  1986. }
  1987. @ The |execute()| method comes in two flavors: one with arguments and one without.
  1988. We always call the one with arguments and simply pass in an empty list if no
  1989. arguments are specified.
  1990. @<Functions for scripting@>=
  1991. QScriptValue QProcess_execute(QScriptContext *context, QScriptEngine *)
  1992. {
  1993. QProcess *self = getself<QProcess *>(context);
  1994. QString program = argument<QString>(0, context);
  1995. QStringList arguments = QStringList();
  1996. if(context->argumentCount() > 1) {
  1997. arguments = argument<QVariant>(1, context).toStringList();
  1998. }
  1999. int retval = self->execute(program, arguments);
  2000. return QScriptValue(retval);
  2001. }
  2002. @ Similarly |startDetached()| can be called in a few different ways.
  2003. @<Functions for scripting@>=
  2004. QScriptValue QProcess_startDetached(QScriptContext *context, QScriptEngine *)
  2005. {
  2006. QProcess *self = getself<QProcess *>(context);
  2007. QString program = argument<QString>(0, context);
  2008. QStringList arguments = QStringList();
  2009. if(context->argumentCount() > 1) {
  2010. arguments = argument<QVariant>(1, context).toStringList();
  2011. }
  2012. QString workingDirectory = "";
  2013. if(context->argumentCount() > 2) {
  2014. workingDirectory = argument<QString>(2, context);
  2015. }
  2016. bool retval;
  2017. switch(context->argumentCount())
  2018. {
  2019. case 1:
  2020. retval = self->startDetached(program);
  2021. break;
  2022. case 2:
  2023. retval = self->startDetached(program, arguments);
  2024. break;
  2025. case 3:
  2026. retval = self->startDetached(program, arguments, workingDirectory);
  2027. break;
  2028. default:
  2029. retval = false;
  2030. }
  2031. return QScriptValue(retval);
  2032. }
  2033. @ Sometimes we care about the working directory for our program.
  2034. @<Functions for scripting@>=
  2035. QScriptValue QProcess_setWorkingDirectory(QScriptContext *context, QScriptEngine *)
  2036. {
  2037. QProcess *self = getself<QProcess *>(context);
  2038. QString directory = argument<QString>(0, context);
  2039. self->setWorkingDirectory(directory);
  2040. return QScriptValue();
  2041. }
  2042. @ When using the |start()| method we always assume that we want read and write
  2043. access.
  2044. @<Functions for scripting@>=
  2045. QScriptValue QProcess_start(QScriptContext *context, QScriptEngine *)
  2046. {
  2047. QProcess *self = getself<QProcess *>(context);
  2048. QString program = argument<QString>(0, context);
  2049. QStringList arguments = QStringList();
  2050. if(context->argumentCount() > 1) {
  2051. arguments = argument<QVariant>(1, context).toStringList();
  2052. }
  2053. self->start(program, arguments);
  2054. return QScriptValue();
  2055. }
  2056. @ In order to work with |QByteArray| this should also be exposed to the host
  2057. environment.
  2058. @<Function prototypes for scripting@>=
  2059. QScriptValue QByteArray_toScriptValue(QScriptEngine *engine, const QByteArray &bytes);
  2060. void QByteArray_fromScriptValue(const QScriptValue &value, QByteArray &bytes);
  2061. QScriptValue constructQByteArray(QScriptContext *context, QScriptEngine *engine);
  2062. void setQByteArrayProperties(QScriptValue value, QScriptEngine *engine);
  2063. QScriptValue QByteArray_fromHex(QScriptContext *context, QScriptEngine *engine);
  2064. QScriptValue QByteArray_getAt(QScriptContext *context, QScriptEngine *engine);
  2065. QScriptValue QByteArray_setAt(QScriptContext *context, QScriptEngine *engine);
  2066. QScriptValue QByteArray_appendBytes(QScriptContext *context, QScriptEngine *engine);
  2067. QScriptValue QByteArray_appendString(QScriptContext *context, QScriptEngine *engine);
  2068. QScriptValue QByteArray_size(QScriptContext *context, QScriptEngine *engine);
  2069. QScriptValue QByteArray_left(QScriptContext *context, QScriptEngine *engine);
  2070. QScriptValue QByteArray_right(QScriptContext *context, QScriptEngine *engine);
  2071. QScriptValue QByteArray_mid(QScriptContext *context, QScriptEngine *engine);
  2072. QScriptValue QByteArray_chop(QScriptContext *context, QScriptEngine *engine);
  2073. QScriptValue QByteArray_remove(QScriptContext *context, QScriptEngine *engine);
  2074. QScriptValue QByteArray_toInt8(QScriptContext *context, QScriptEngine *engine);
  2075. QScriptValue QByteArray_toInt16(QScriptContext *context, QScriptEngine *engine);
  2076. QScriptValue QByteArray_toInt32(QScriptContext *context, QScriptEngine *engine);
  2077. QScriptValue QByteArray_toFloat(QScriptContext *context, QScriptEngine *engine);
  2078. QScriptValue QByteArray_toDouble(QScriptContext *context, QScriptEngine *engine);
  2079. @ First, we provide some functionns for moving array data across the
  2080. language barrier.
  2081. @<Functions for scripting@>=
  2082. QScriptValue QByteArray_toScriptValue(QScriptEngine *engine, const QByteArray &bytes)
  2083. {
  2084. QScriptValue object = engine->newVariant(QVariant(bytes));
  2085. setQByteArrayProperties(object, engine);
  2086. return object;
  2087. }
  2088. void QByteArray_fromScriptValue(const QScriptValue &value, QByteArray &bytes)
  2089. {
  2090. bytes = value.toVariant().toByteArray();
  2091. }
  2092. @ We register this our conversion functions and allow creation of new arrays
  2093. next.
  2094. @<Set up the scripting engine@>=
  2095. qScriptRegisterMetaType(engine, QByteArray_toScriptValue, QByteArray_fromScriptValue);
  2096. constructor = engine->newFunction(constructQByteArray);
  2097. engine->globalObject().setProperty("QByteArray", constructor);
  2098. @ The constructor is straightforward.
  2099. @<Functions for scripting@>=
  2100. QScriptValue constructQByteArray(QScriptContext *, QScriptEngine *engine)
  2101. {
  2102. QScriptValue object = engine->toScriptValue<QByteArray>(QByteArray());
  2103. setQByteArrayProperties(object, engine);
  2104. return object;
  2105. }
  2106. @ There are many methods which are not automatically available which we may
  2107. want to have wrappers around. These should be added as required.
  2108. @<Functions for scripting@>=
  2109. void setQByteArrayProperties(QScriptValue value, QScriptEngine *engine)
  2110. {
  2111. value.setProperty("fromHex", engine->newFunction(QByteArray_fromHex));
  2112. value.setProperty("getAt", engine->newFunction(QByteArray_getAt));
  2113. value.setProperty("setAt", engine->newFunction(QByteArray_setAt));
  2114. value.setProperty("appendBytes", engine->newFunction(QByteArray_appendBytes));
  2115. value.setProperty("appendString", engine->newFunction(QByteArray_appendString));
  2116. value.setProperty("size", engine->newFunction(QByteArray_size));
  2117. value.setProperty("left", engine->newFunction(QByteArray_left));
  2118. value.setProperty("right", engine->newFunction(QByteArray_right));
  2119. value.setProperty("mid", engine->newFunction(QByteArray_mid));
  2120. value.setProperty("chop", engine->newFunction(QByteArray_chop));
  2121. value.setProperty("remove", engine->newFunction(QByteArray_remove));
  2122. value.setProperty("toInt8", engine->newFunction(QByteArray_toInt8));
  2123. value.setProperty("toInt16", engine->newFunction(QByteArray_toInt16));
  2124. value.setProperty("toInt32", engine->newFunction(QByteArray_toInt32));
  2125. value.setProperty("toFloat", engine->newFunction(QByteArray_toFloat));
  2126. value.setProperty("toDouble", engine->newFunction(QByteArray_toDouble));
  2127. }
  2128. @ Perhaps the easiest way to deal with fixed byte strings for serial
  2129. communications across script boundaries is to use a hex encoded string.
  2130. @<Functions for scripting@>=
  2131. QScriptValue QByteArray_fromHex(QScriptContext *context, QScriptEngine *engine)
  2132. {
  2133. QByteArray self = getself<QByteArray>(context);
  2134. QByteArray retval;
  2135. retval = self.fromHex(argument<QString>(0, context).toUtf8());
  2136. QScriptValue value = engine->toScriptValue<QByteArray>(retval);
  2137. setQByteArrayProperties(value, engine);
  2138. return value;
  2139. }
  2140. @ A pair of methods is provided for getting and setting values at a particular
  2141. byte.
  2142. @<Functions for scripting@>=
  2143. QScriptValue QByteArray_getAt(QScriptContext *context, QScriptEngine *)
  2144. {
  2145. QByteArray self = getself<QByteArray>(context);
  2146. return QScriptValue((int)(self.at(argument<int>(0, context))));
  2147. }
  2148. QScriptValue QByteArray_setAt(QScriptContext *context, QScriptEngine *)
  2149. {
  2150. QByteArray self = getself<QByteArray>(context);
  2151. self[argument<int>(0, context)] = (char)(argument<int>(1, context));
  2152. return QScriptValue();
  2153. }
  2154. @ Methods are provided for appending either another |QByteArray| or a string
  2155. to a |QByteArray|. The only difference between these functions is the expected
  2156. argument type.
  2157. @<Functions for scripting@>=
  2158. QScriptValue QByteArray_appendBytes(QScriptContext *context, QScriptEngine *engine)
  2159. {
  2160. QByteArray self = getself<QByteArray>(context);
  2161. QScriptValue value =
  2162. engine->toScriptValue<QByteArray>(
  2163. self.append(argument<QByteArray>(0, context)));
  2164. setQByteArrayProperties(value, engine);
  2165. return value;
  2166. }
  2167. QScriptValue QByteArray_appendString(QScriptContext *context, QScriptEngine *engine)
  2168. {
  2169. QByteArray self = getself<QByteArray>(context);
  2170. QScriptValue value = engine->toScriptValue<QByteArray>(
  2171. self.append(argument<QString>(0, context)));
  2172. setQByteArrayProperties(value, engine);
  2173. return value;
  2174. }
  2175. @ Checking the size of our byte array frequently a requirement.
  2176. @<Functions for scripting@>=
  2177. QScriptValue QByteArray_size(QScriptContext *context, QScriptEngine *)
  2178. {
  2179. QByteArray self = getself<QByteArray>(context);
  2180. return QScriptValue(self.size());
  2181. }
  2182. @ It is also frequently useful to be able to work with specific parts of a byte
  2183. array, so a few methods are provided for carving these up.
  2184. @<Functions for scripting@>=
  2185. QScriptValue QByteArray_left(QScriptContext *context, QScriptEngine *engine)
  2186. {
  2187. QByteArray self = getself<QByteArray>(context);
  2188. QScriptValue value = engine->toScriptValue<QByteArray>(
  2189. self.left(argument<int>(0, context)));
  2190. setQByteArrayProperties(value, engine);
  2191. return value;
  2192. }
  2193. QScriptValue QByteArray_right(QScriptContext *context, QScriptEngine *engine)
  2194. {
  2195. QByteArray self = getself<QByteArray>(context);
  2196. QScriptValue value = engine->toScriptValue<QByteArray>(
  2197. self.right(argument<int>(0, context)));
  2198. setQByteArrayProperties(value, engine);
  2199. return value;
  2200. }
  2201. QScriptValue QByteArray_mid(QScriptContext *context, QScriptEngine *engine)
  2202. {
  2203. QByteArray self = getself<QByteArray>(context);
  2204. int length = -1;
  2205. if(context->argumentCount() > 1)
  2206. {
  2207. length = argument<int>(1, context);
  2208. }
  2209. QScriptValue value = engine->toScriptValue<QByteArray>(
  2210. self.mid(argument<int>(0, context), length));
  2211. setQByteArrayProperties(value, engine);
  2212. return value;
  2213. }
  2214. @ We may also want to remove bytes from an array.
  2215. @<Functions for scripting@>=
  2216. QScriptValue QByteArray_chop(QScriptContext *context, QScriptEngine *)
  2217. {
  2218. QByteArray self = getself<QByteArray>(context);
  2219. self.chop(argument<int>(0, context));
  2220. return QScriptValue();
  2221. }
  2222. QScriptValue QByteArray_remove(QScriptContext *context, QScriptEngine *engine)
  2223. {
  2224. QByteArray self = getself<QByteArray>(context);
  2225. QScriptValue value = engine->toScriptValue<QByteArray>(
  2226. self.remove(argument<int>(0, context), argument<int>(1, context)));
  2227. setQByteArrayProperties(value, engine);
  2228. return value;
  2229. }
  2230. @ When receiving data in a byte array, bytes are sometimes intended to
  2231. represent 8, 16, or 32 bit integers. In such cases we often want to perform
  2232. some computation on these values so having the ability to split off that
  2233. portion of the array (for example, with |mid()|) and convert to a Number is
  2234. useful.
  2235. @<Functions for scripting@>=
  2236. QScriptValue QByteArray_toInt8(QScriptContext *context, QScriptEngine *)
  2237. {
  2238. QByteArray self = getself<QByteArray>(context);
  2239. int value = 0;
  2240. char *bytes = (char *)&value;
  2241. bytes[0] = self[0];
  2242. return QScriptValue(value);
  2243. }
  2244. QScriptValue QByteArray_toInt16(QScriptContext *context, QScriptEngine *)
  2245. {
  2246. QByteArray self = getself<QByteArray>(context);
  2247. int value = 0;
  2248. char *bytes = (char *)&value;
  2249. bytes[0] = self[0];
  2250. bytes[1] = self[1];
  2251. return QScriptValue(value);
  2252. }
  2253. QScriptValue QByteArray_toInt32(QScriptContext *context, QScriptEngine *)
  2254. {
  2255. QByteArray self = getself<QByteArray>(context);
  2256. int value = 0;
  2257. char *bytes = (char *)&value;
  2258. bytes[0] = self[0];
  2259. bytes[1] = self[1];
  2260. bytes[2] = self[2];
  2261. bytes[3] = self[3];
  2262. return QScriptValue(value);
  2263. }
  2264. @ Similar methods are provided for converting bytes to a |float| or |double|.
  2265. Note that the return value from |toFloat| will, in the host environment, be
  2266. represented as a |double|.
  2267. @<Functions for scripting@>=
  2268. QScriptValue QByteArray_toFloat(QScriptContext *context, QScriptEngine *)
  2269. {
  2270. QByteArray self = getself<QByteArray>(context);
  2271. float value = 0.0;
  2272. char *bytes = (char *)&value;
  2273. bytes[0] = self[0];
  2274. bytes[1] = self[1];
  2275. bytes[2] = self[2];
  2276. bytes[3] = self[3];
  2277. return QScriptValue(value);
  2278. }
  2279. QScriptValue QByteArray_toDouble(QScriptContext *context, QScriptEngine *)
  2280. {
  2281. QByteArray self = getself<QByteArray>(context);
  2282. double value = 0.0;
  2283. char *bytes = (char *)&value;
  2284. bytes[0] = self[0];
  2285. bytes[1] = self[1];
  2286. bytes[2] = self[2];
  2287. bytes[3] = self[3];
  2288. bytes[4] = self[4];
  2289. bytes[5] = self[5];
  2290. bytes[6] = self[6];
  2291. bytes[7] = self[7];
  2292. return QScriptValue(value);
  2293. }
  2294. @ Some protocols require manipulating larger than 8 bit numbers as a sequence
  2295. of bytes. To facilitate this, methods are provided to construct a |QByteArray|
  2296. from different sized numbers. 8 bit numbers are provided for uniformity.
  2297. @<Function prototypes for scripting@>=
  2298. QScriptValue bytesFromInt8(QScriptContext *context, QScriptEngine *engine);
  2299. QScriptValue bytesFromInt16(QScriptContext *context, QScriptEngine *engine);
  2300. QScriptValue bytesFromInt32(QScriptContext *context, QScriptEngine *engine);
  2301. QScriptValue bytesFromFloat(QScriptContext *context, QScriptEngine *engine);
  2302. QScriptValue bytesFromDouble(QScriptContext *context, QScriptEngine *engine);
  2303. @ These are globally available.
  2304. @<Set up the scripting engine@>=
  2305. engine->globalObject().setProperty("bytesFromInt8", engine->newFunction(bytesFromInt8));
  2306. engine->globalObject().setProperty("bytesFromInt16", engine->newFunction(bytesFromInt16));
  2307. engine->globalObject().setProperty("bytesFromInt32", engine->newFunction(bytesFromInt32));
  2308. engine->globalObject().setProperty("bytesFromFloat", engine->newFunction(bytesFromFloat));
  2309. engine->globalObject().setProperty("bytesFromDouble", engine->newFunction(bytesFromDouble));
  2310. @ The methods all work by casting the appropriate numeric type to a |char *|
  2311. and copying the bytes to a new |QByteArray|. Note that the ECMA-262 standard
  2312. only has one type of number and this is an IEEE 754 binary64 double precision
  2313. floating point number. Functions other than |bytesFromDouble| will be cast
  2314. from |double|.
  2315. @<Functions for scripting@>=
  2316. QScriptValue bytesFromInt8(QScriptContext *context, QScriptEngine *engine)
  2317. {
  2318. qint8 value = (qint8)(argument<int>(0, context));
  2319. char *bytes = (char *)&value;
  2320. QByteArray retval;
  2321. retval.resize(1);
  2322. retval[0] = bytes[0];
  2323. QScriptValue v = engine->toScriptValue<QByteArray>(retval);
  2324. setQByteArrayProperties(v, engine);
  2325. return v;
  2326. }
  2327. QScriptValue bytesFromInt16(QScriptContext *context, QScriptEngine *engine)
  2328. {
  2329. qint16 value = (qint16)(argument<int>(0, context));
  2330. char *bytes = (char *)&value;
  2331. QByteArray retval;
  2332. retval.resize(2);
  2333. retval[0] = bytes[0];
  2334. retval[1] = bytes[1];
  2335. QScriptValue v = engine->toScriptValue<QByteArray>(retval);
  2336. setQByteArrayProperties(v, engine);
  2337. return v;
  2338. }
  2339. QScriptValue bytesFromInt32(QScriptContext *context, QScriptEngine *engine)
  2340. {
  2341. qint32 value = (qint32)(argument<int>(0, context));
  2342. char *bytes = (char *)&value;
  2343. QByteArray retval;
  2344. retval.resize(4);
  2345. retval[0] = bytes[0];
  2346. retval[1] = bytes[1];
  2347. retval[2] = bytes[2];
  2348. retval[3] = bytes[3];
  2349. QScriptValue v = engine->toScriptValue<QByteArray>(retval);
  2350. setQByteArrayProperties(v, engine);
  2351. return v;
  2352. }
  2353. QScriptValue bytesFromFloat(QScriptContext *context, QScriptEngine *engine)
  2354. {
  2355. float value = (float)(argument<double>(0, context));
  2356. char *bytes = (char *)&value;
  2357. QByteArray retval;
  2358. retval.resize(4);
  2359. retval[0] = bytes[0];
  2360. retval[1] = bytes[1];
  2361. retval[2] = bytes[2];
  2362. retval[3] = bytes[3];
  2363. QScriptValue v = engine->toScriptValue<QByteArray>(retval);
  2364. setQByteArrayProperties(v, engine);
  2365. return v;
  2366. }
  2367. QScriptValue bytesFromDouble(QScriptContext *context, QScriptEngine *engine)
  2368. {
  2369. double value = (double)(argument<double>(0, context));
  2370. char *bytes = (char *)&value;
  2371. QByteArray retval;
  2372. retval.resize(8);
  2373. retval[0] = bytes[0];
  2374. retval[1] = bytes[1];
  2375. retval[2] = bytes[2];
  2376. retval[3] = bytes[3];
  2377. retval[4] = bytes[4];
  2378. retval[5] = bytes[5];
  2379. retval[6] = bytes[6];
  2380. retval[7] = bytes[7];
  2381. QScriptValue v = engine->toScriptValue<QByteArray>(retval);
  2382. setQByteArrayProperties(v, engine);
  2383. return v;
  2384. }
  2385. @* Scripting QBuffer.
  2386. \noindent Sometimes it is desirable to load a roast profile from a file. At
  2387. other times, it is more useful to load that profile from a byte array stored in
  2388. a database. The |XMLInput| class takes data from a |QIODevice| object, which
  2389. means that we can choose from a |QFile| when we want the former or a |QBuffer|
  2390. when we want the latter.
  2391. @<Function prototypes for scripting@>=
  2392. QScriptValue constructQBuffer(QScriptContext *context, QScriptEngine *engine);
  2393. void setQBufferProperties(QScriptValue value, QScriptEngine *engine);
  2394. QScriptValue QBuffer_setData(QScriptContext *context, QScriptEngine *engine);
  2395. @ The host environment needs to be aware of the constructor.
  2396. @<Set up the scripting engine@>=
  2397. constructor = engine->newFunction(constructQBuffer);
  2398. value = engine->newQMetaObject(&QBuffer::staticMetaObject, constructor);
  2399. engine->globalObject().setProperty("QBuffer", value);
  2400. @ The implementation is trivial.
  2401. @<Functions for scripting@>=
  2402. QScriptValue constructQBuffer(QScriptContext *context, QScriptEngine *engine)
  2403. {
  2404. QByteArray *array = new QByteArray(argument<QString>(0, context).toAscii());
  2405. QScriptValue object = engine->newQObject(new QBuffer(array));
  2406. setQBufferProperties(object, engine);
  2407. return object;
  2408. }
  2409. void setQBufferProperties(QScriptValue value, QScriptEngine *engine)
  2410. {
  2411. setQIODeviceProperties(value, engine);
  2412. value.setProperty("setData", engine->newFunction(QBuffer_setData));
  2413. }
  2414. QScriptValue QBuffer_setData(QScriptContext *context, QScriptEngine *)
  2415. {
  2416. QBuffer *self = getself<QBuffer *>(context);
  2417. self->setData(argument<QString>(0, context).toAscii());
  2418. return QScriptValue();
  2419. }
  2420. @* Scripting QXmlQuery.
  2421. \noindent Sometimes we have some XML data in a file or a buffer and we would
  2422. like to extract certain information from that data in the host environment.
  2423. Rather than write complicated string manipulation routines in an attempt to deal
  2424. with this sensibly, we can use the XQuery language to extract the information we
  2425. want. One common use case for this is extracting all measurements from a roast
  2426. profile that are associated with an annotation.
  2427. @<Function prototypes for scripting@>=
  2428. QScriptValue constructXQuery(QScriptContext *context, QScriptEngine *engine);
  2429. QScriptValue XQuery_bind(QScriptContext *context, QScriptEngine *engine);
  2430. QScriptValue XQuery_exec(QScriptContext *context, QScriptEngine *engine);
  2431. QScriptValue XQuery_setQuery(QScriptContext *context, QScriptEngine *engine);
  2432. QScriptValue XQuery_invalidate(QScriptContext *context, QScriptEngine *engine);
  2433. void setXQueryProperties(QScriptValue value, QScriptEngine *engine);
  2434. @ The constructor must be registered with the host environment. This is done a
  2435. bit differently from most classes as |QXmlQuery| is not a |QObject|.
  2436. @<Set up the scripting engine@>=
  2437. constructor = engine->newFunction(constructXQuery);
  2438. engine->globalObject().setProperty("XQuery", constructor);
  2439. @ The constructor just needs to make sure the functions we want to make
  2440. available are applied. A method is also provided to free the |QXmlQuery|.
  2441. @<Functions for scripting@>=
  2442. QScriptValue constructXQuery(QScriptContext *, QScriptEngine *engine)
  2443. {
  2444. QScriptValue object = engine->toScriptValue<void *>(new QXmlQuery);
  2445. setXQueryProperties(object, engine);
  2446. return object;
  2447. }
  2448. QScriptValue XQuery_invalidate(QScriptContext *context, QScriptEngine *)
  2449. {
  2450. QXmlQuery *self = getself<QXmlQuery *>(context);
  2451. delete self;
  2452. return QScriptValue();
  2453. }
  2454. void setXQueryProperties(QScriptValue value, QScriptEngine *engine)
  2455. {
  2456. value.setProperty("bind", engine->newFunction(XQuery_bind));
  2457. value.setProperty("exec", engine->newFunction(XQuery_exec));
  2458. value.setProperty("setQuery", engine->newFunction(XQuery_setQuery));
  2459. value.setProperty("invalidate", engine->newFunction(XQuery_invalidate));
  2460. }
  2461. @ The |bind()| property can be used to specify a |QIODevice| to be referenced by
  2462. a variable within a query.
  2463. @<Functions for scripting@>=
  2464. QScriptValue XQuery_bind(QScriptContext *context, QScriptEngine *)
  2465. {
  2466. QXmlQuery *self = getself<QXmlQuery *>(context);
  2467. QIODevice *buffer = argument<QIODevice *>(1, context);
  2468. self->bindVariable(argument<QString>(0, context), buffer);
  2469. return QScriptValue();
  2470. }
  2471. @ A method is also required for setting the query we wish to conduct.
  2472. @<Functions for scripting@>=
  2473. QScriptValue XQuery_setQuery(QScriptContext *context, QScriptEngine *)
  2474. {
  2475. QXmlQuery *self = getself<QXmlQuery *>(context);
  2476. self->setQuery(argument<QString>(0, context));
  2477. return QScriptValue();
  2478. }
  2479. @ This method runs the previously specified query.
  2480. @<Functions for scripting@>=
  2481. QScriptValue XQuery_exec(QScriptContext *context, QScriptEngine *)
  2482. {
  2483. QXmlQuery *self = getself<QXmlQuery *>(context);
  2484. QString result;
  2485. self->evaluateTo(&result);
  2486. return QScriptValue(result);
  2487. }
  2488. @* Scripting QXmlStreamWriter.
  2489. \noindent There are some cases where it may be desirable to produce XML from the
  2490. host environment. While there are several ways to accomplish this, the
  2491. |QXmlStreamWriter| class greatly simplifies generating complex XML documents.
  2492. This class is not related to |QObject|, so several functions are needed to
  2493. expose the functionality of this class to the host environment.
  2494. @<Function prototypes for scripting@>=
  2495. QScriptValue constructXmlWriter(QScriptContext *context, QScriptEngine *engine);
  2496. QScriptValue XmlWriter_setDevice(QScriptContext *context,
  2497. QScriptEngine *engine);
  2498. QScriptValue XmlWriter_writeAttribute(QScriptContext *context,
  2499. QScriptEngine *engine);
  2500. QScriptValue XmlWriter_writeCDATA(QScriptContext *context,
  2501. QScriptEngine *engine);
  2502. QScriptValue XmlWriter_writeCharacters(QScriptContext *context,
  2503. QScriptEngine *engine);
  2504. QScriptValue XmlWriter_writeDTD(QScriptContext *context, QScriptEngine *engine);
  2505. QScriptValue XmlWriter_writeEmptyElement(QScriptContext *context,
  2506. QScriptEngine *engine);
  2507. QScriptValue XmlWriter_writeEndDocument(QScriptContext *context,
  2508. QScriptEngine *engine);
  2509. QScriptValue XmlWriter_writeEndElement(QScriptContext *context,
  2510. QScriptEngine *engine);
  2511. QScriptValue XmlWriter_writeEntityReference(QScriptContext *context,
  2512. QScriptEngine *engine);
  2513. QScriptValue XmlWriter_writeProcessingInstruction(QScriptContext *context,
  2514. QScriptEngine *engine);
  2515. QScriptValue XmlWriter_writeStartDocument(QScriptContext *context,
  2516. QScriptEngine *engine);
  2517. QScriptValue XmlWriter_writeStartElement(QScriptContext *context,
  2518. QScriptEngine *engine);
  2519. QScriptValue XmlWriter_writeTextElement(QScriptContext *context,
  2520. QScriptEngine *engine);
  2521. void setXmlWriterProperties(QScriptValue value, QScriptEngine *engine);
  2522. @ The constructor must be registered with the host environment.
  2523. @<Set up the scripting engine@>=
  2524. constructor = engine->newFunction(constructXmlWriter);
  2525. engine->globalObject().setProperty("XmlWriter", constructor);
  2526. @ The constructor takes an optional argument allowing the output device to be
  2527. specified.
  2528. @<Functions for scripting@>=
  2529. QScriptValue constructXmlWriter(QScriptContext *context, QScriptEngine *engine)
  2530. {
  2531. QXmlStreamWriter *retval;
  2532. if(context->argumentCount() == 1)
  2533. {
  2534. retval = new QXmlStreamWriter(argument<QIODevice *>(0, context));
  2535. }
  2536. else
  2537. {
  2538. retval = new QXmlStreamWriter;
  2539. }
  2540. QScriptValue object = engine->toScriptValue<void *>(retval);
  2541. setXmlWriterProperties(object, engine);
  2542. return object;
  2543. }
  2544. void setXmlWriterProperties(QScriptValue value, QScriptEngine *engine)
  2545. {
  2546. value.setProperty("setDevice", engine->newFunction(XmlWriter_setDevice));
  2547. value.setProperty("writeAttribute",
  2548. engine->newFunction(XmlWriter_writeAttribute));
  2549. value.setProperty("writeCDATA", engine->newFunction(XmlWriter_writeCDATA));
  2550. value.setProperty("writeCharacters",
  2551. engine->newFunction(XmlWriter_writeCharacters));
  2552. value.setProperty("writeDTD", engine->newFunction(XmlWriter_writeDTD));
  2553. value.setProperty("writeEmptyElement",
  2554. engine->newFunction(XmlWriter_writeEmptyElement));
  2555. value.setProperty("writeEndDocument",
  2556. engine->newFunction(XmlWriter_writeEndDocument));
  2557. value.setProperty("writeEndElement",
  2558. engine->newFunction(XmlWriter_writeEndElement));
  2559. value.setProperty("writeEntityReference",
  2560. engine->newFunction(XmlWriter_writeEntityReference));
  2561. value.setProperty("writeProcessingInstruction",
  2562. engine->newFunction(XmlWriter_writeProcessingInstruction));
  2563. value.setProperty("writeStartDocument",
  2564. engine->newFunction(XmlWriter_writeStartDocument));
  2565. value.setProperty("writeStartElement",
  2566. engine->newFunction(XmlWriter_writeStartElement));
  2567. value.setProperty("writeTextElement",
  2568. engine->newFunction(XmlWriter_writeTextElement));
  2569. }
  2570. @ If the output device needs to be changed or if one is not passed to the
  2571. constructor, the |setDevice()| method can be used.
  2572. @<Functions for scripting@>=
  2573. QScriptValue XmlWriter_setDevice(QScriptContext *context, QScriptEngine *)
  2574. {
  2575. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2576. QIODevice *device = argument<QIODevice *>(0, context);
  2577. self->setDevice(device);
  2578. return QScriptValue();
  2579. }
  2580. @ The remaining functions are simple wrappers used for writing various types of
  2581. data. After creating a writer and setting the output device, the start of the
  2582. document should be written. One argument is required containing the XML version
  2583. number. Another function handles writing the end of the document.
  2584. @<Functions for scripting@>=
  2585. QScriptValue XmlWriter_writeStartDocument(QScriptContext *context,
  2586. QScriptEngine *)
  2587. {
  2588. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2589. self->writeStartDocument(argument<QString>(0, context));
  2590. return QScriptValue();
  2591. }
  2592. QScriptValue XmlWriter_writeEndDocument(QScriptContext *context,
  2593. QScriptEngine *)
  2594. {
  2595. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2596. self->writeEndDocument();
  2597. return QScriptValue();
  2598. }
  2599. @ After the start of the document, a DTD is commonly needed.
  2600. @<Functions for scripting@>=
  2601. QScriptValue XmlWriter_writeDTD(QScriptContext *context, QScriptEngine *)
  2602. {
  2603. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2604. self->writeDTD(argument<QString>(0, context));
  2605. return QScriptValue();
  2606. }
  2607. @ After this, elements need to be written. For this, we write the start
  2608. element, any attributes needed, character data, and the end element.
  2609. @<Functions for scripting@>=
  2610. QScriptValue XmlWriter_writeStartElement(QScriptContext *context,
  2611. QScriptEngine *)
  2612. {
  2613. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2614. self->writeStartElement(argument<QString>(0, context));
  2615. return QScriptValue();
  2616. }
  2617. QScriptValue XmlWriter_writeAttribute(QScriptContext *context, QScriptEngine *)
  2618. {
  2619. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2620. self->writeAttribute(argument<QString>(0, context),
  2621. argument<QString>(1, context));
  2622. return QScriptValue();
  2623. }
  2624. QScriptValue XmlWriter_writeCharacters(QScriptContext *context, QScriptEngine *)
  2625. {
  2626. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2627. self->writeCharacters(argument<QString>(0, context));
  2628. return QScriptValue();
  2629. }
  2630. QScriptValue XmlWriter_writeEndElement(QScriptContext *context, QScriptEngine *)
  2631. {
  2632. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2633. self->writeEndElement();
  2634. return QScriptValue();
  2635. }
  2636. @ For convenience, two other methods are provided for writing elements. Elements
  2637. which do not require anything between the start and end elements can be created
  2638. with |writeEmptyElement()|. Elements which do not require attributes, but do
  2639. contain text can be created with |writeTextElement()|.
  2640. @<Functions for scripting@>=
  2641. QScriptValue XmlWriter_writeEmptyElement(QScriptContext *context,
  2642. QScriptEngine *)
  2643. {
  2644. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2645. self->writeEmptyElement(argument<QString>(0, context));
  2646. return QScriptValue();
  2647. }
  2648. QScriptValue XmlWriter_writeTextElement(QScriptContext *context,
  2649. QScriptEngine *)
  2650. {
  2651. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2652. self->writeTextElement(argument<QString>(0, context),
  2653. argument<QString>(1, context));
  2654. return QScriptValue();
  2655. }
  2656. @ Less commonly needed are functions for writing CDATA sections, entity
  2657. references, and processing instructions.
  2658. @<Functions for scripting@>=
  2659. QScriptValue XmlWriter_writeCDATA(QScriptContext *context, QScriptEngine *)
  2660. {
  2661. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2662. self->writeCDATA(argument<QString>(0, context));
  2663. return QScriptValue();
  2664. }
  2665. QScriptValue XmlWriter_writeEntityReference(QScriptContext *context,
  2666. QScriptEngine *)
  2667. {
  2668. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2669. self->writeEntityReference(argument<QString>(0, context));
  2670. return QScriptValue();
  2671. }
  2672. QScriptValue XmlWriter_writeProcessingInstruction(QScriptContext *context,
  2673. QScriptEngine *)
  2674. {
  2675. QXmlStreamWriter *self = getself<QXmlStreamWriter *>(context);
  2676. self->writeProcessingInstruction(argument<QString>(0, context),
  2677. argument<QString>(1, context));
  2678. return QScriptValue();
  2679. }
  2680. @* Scripting QXmlStreamReader.
  2681. \noindent When a serializer is written using |QXmlStreamWriter|, a corresponding
  2682. deserializer should also be written. While there are several possible ways to do
  2683. this, using |QXmlStreamReader| is often the best choice. \pn{} provides a subset
  2684. of the functionality from this class which should be adequate for most purposes.
  2685. @<Function prototypes for scripting@>=
  2686. QScriptValue constructXmlReader(QScriptContext *context, QScriptEngine *engine);
  2687. QScriptValue XmlReader_atEnd(QScriptContext *context, QScriptEngine *engine);
  2688. QScriptValue XmlReader_attribute(QScriptContext *context,
  2689. QScriptEngine *engine);
  2690. QScriptValue XmlReader_hasAttribute(QScriptContext *context,
  2691. QScriptEngine *engine);
  2692. QScriptValue XmlReader_isDTD(QScriptContext *context, QScriptEngine *engine);
  2693. QScriptValue XmlReader_isStartElement(QScriptContext *context,
  2694. QScriptEngine *engine);
  2695. QScriptValue XmlReader_name(QScriptContext *context, QScriptEngine *engine);
  2696. QScriptValue XmlReader_readElementText(QScriptContext *context,
  2697. QScriptEngine *engine);
  2698. QScriptValue XmlReader_readNext(QScriptContext *context, QScriptEngine *engine);
  2699. QScriptValue XmlReader_text(QScriptContext *context, QScriptEngine *engine);
  2700. void setXmlReaderProperties(QScriptValue value, QScriptEngine *engine);
  2701. @ The constructor must be registered with the host environment.
  2702. @<Set up the scripting engine@>=
  2703. constructor = engine->newFunction(constructXmlReader);
  2704. engine->globalObject().setProperty("XmlReader", constructor);
  2705. @ The constructor requires an argument specifying the output device. This can be
  2706. any |QIODevice|. The |open()| method must be called on the device before passing
  2707. it as an argument to this function.
  2708. @<Functions for scripting@>=
  2709. QScriptValue constructXmlReader(QScriptContext *context, QScriptEngine *engine)
  2710. {
  2711. QXmlStreamReader *retval =
  2712. new QXmlStreamReader(argument<QIODevice *>(0, context));
  2713. QScriptValue object = engine->toScriptValue<void *>(retval);
  2714. setXmlReaderProperties(object, engine);
  2715. return object;
  2716. }
  2717. void setXmlReaderProperties(QScriptValue value, QScriptEngine *engine)
  2718. {
  2719. value.setProperty("atEnd", engine->newFunction(XmlReader_atEnd));
  2720. value.setProperty("attribute", engine->newFunction(XmlReader_attribute));
  2721. value.setProperty("hasAttribute",
  2722. engine->newFunction(XmlReader_hasAttribute));
  2723. value.setProperty("isDTD", engine->newFunction(XmlReader_isDTD));
  2724. value.setProperty("isStartElement",
  2725. engine->newFunction(XmlReader_isStartElement));
  2726. value.setProperty("name", engine->newFunction(XmlReader_name));
  2727. value.setProperty("readElementText",
  2728. engine->newFunction(XmlReader_readElementText));
  2729. value.setProperty("readNext",
  2730. engine->newFunction(XmlReader_readNext));
  2731. value.setProperty("text", engine->newFunction(XmlReader_text));
  2732. }
  2733. @ Most of the functions are simple member function wrappers. Two of these
  2734. properties are not. These are the |attribute()| and |hasAttribute()| properties.
  2735. @<Functions for scripting@>=
  2736. QScriptValue XmlReader_attribute(QScriptContext *context, QScriptEngine *)
  2737. {
  2738. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2739. QString retval =
  2740. self->attributes().value(argument<QString>(0, context)).toString();
  2741. return QScriptValue(retval);
  2742. }
  2743. QScriptValue XmlReader_hasAttribute(QScriptContext *context, QScriptEngine *)
  2744. {
  2745. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2746. bool retval =
  2747. self->attributes().hasAttribute(argument<QString>(0, context));
  2748. return QScriptValue(retval);
  2749. }
  2750. @ Other properties can be used for determining how to proceed with the
  2751. processing.
  2752. @<Functions for scripting@>=
  2753. QScriptValue XmlReader_atEnd(QScriptContext *context, QScriptEngine *)
  2754. {
  2755. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2756. return QScriptValue(self->atEnd());
  2757. }
  2758. QScriptValue XmlReader_isDTD(QScriptContext *context, QScriptEngine *)
  2759. {
  2760. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2761. return QScriptValue(self->isDTD());
  2762. }
  2763. QScriptValue XmlReader_isStartElement(QScriptContext *context, QScriptEngine *)
  2764. {
  2765. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2766. return QScriptValue(self->isStartElement());
  2767. }
  2768. @ We move from one element to the next with the |readNext()| property.
  2769. @<Functions for scripting@>=
  2770. QScriptValue XmlReader_readNext(QScriptContext *context, QScriptEngine *)
  2771. {
  2772. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2773. self->readNext();
  2774. return QScriptValue();
  2775. }
  2776. @ The remaining properties return the element name and text.
  2777. @<Functions for scripting@>=
  2778. QScriptValue XmlReader_name(QScriptContext *context, QScriptEngine *)
  2779. {
  2780. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2781. return QScriptValue(self->name().toString());
  2782. }
  2783. QScriptValue XmlReader_readElementText(QScriptContext *context, QScriptEngine *)
  2784. {
  2785. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2786. return QScriptValue(self->readElementText());
  2787. }
  2788. QScriptValue XmlReader_text(QScriptContext *context, QScriptEngine *)
  2789. {
  2790. QXmlStreamReader *self = getself<QXmlStreamReader *>(context);
  2791. return QScriptValue(self->text().toString());
  2792. }
  2793. @* Scripting QSettings.
  2794. \noindent Rather than have a script create a |QSettings| object when it needs to
  2795. save or load settings, the object is provided along with properties for getting
  2796. and setting values. Two functions are needed for this along with a third which
  2797. ensures any properties added to |QObject| are also available to |QSettings| from
  2798. the host environment.
  2799. @<Function prototypes for scripting@>=
  2800. QScriptValue QSettings_value(QScriptContext *context, QScriptEngine *engine);
  2801. QScriptValue QSettings_setValue(QScriptContext *context, QScriptEngine *engine);
  2802. void setQSettingsProperties(QScriptValue value, QScriptEngine *engine);
  2803. @ The object with properties for these functions is passed to the scripting
  2804. engine.
  2805. @<Set up the scripting engine@>=
  2806. value = engine->newQObject(&settings);
  2807. setQSettingsProperties(value, engine);
  2808. engine->globalObject().setProperty("QSettings", value);
  2809. @ Adding properties to the |QSettings| object should seem familiar.
  2810. @<Functions for scripting@>=
  2811. void setQSettingsProperties(QScriptValue value, QScriptEngine *engine)
  2812. {
  2813. setQObjectProperties(value, engine);
  2814. value.setProperty("value", engine->newFunction(QSettings_value));
  2815. value.setProperty("setValue", engine->newFunction(QSettings_setValue));
  2816. }
  2817. @ When getting a value from saved settings, there is the possibility that there
  2818. will not be a value saved for the requested key. An optional second argument can
  2819. be used to supply a default value.
  2820. @<Functions for scripting@>=
  2821. QScriptValue QSettings_value(QScriptContext *context, QScriptEngine *engine)
  2822. {
  2823. QScriptValue object;
  2824. if(context->argumentCount() == 1 || context->argumentCount() == 2)
  2825. {
  2826. QSettings settings;
  2827. QString key = argument<QString>(0, context);
  2828. QVariant value;
  2829. QVariant retval;
  2830. if(context->argumentCount() > 1)
  2831. {
  2832. value = argument<QVariant>(1, context);
  2833. retval = settings.value(key, value);
  2834. }
  2835. else
  2836. {
  2837. retval = settings.value(key);
  2838. }
  2839. object = engine->newVariant(retval);
  2840. }
  2841. else
  2842. {
  2843. context->throwError("Incorrect number of arguments passed to "@|
  2844. "QSettings::value(). This method takes one "@|
  2845. "string and one optional variant type.");
  2846. }
  2847. return object;
  2848. }
  2849. QScriptValue QSettings_setValue(QScriptContext *context, QScriptEngine *)
  2850. {
  2851. if(context->argumentCount() == 2)
  2852. {
  2853. QSettings settings;
  2854. QString key = argument<QString>(0, context);
  2855. QVariant value = argument<QVariant>(1, context);
  2856. settings.setValue(key, value);
  2857. }
  2858. else
  2859. {
  2860. context->throwError("Incorrect number of arguments passed to "@|
  2861. "QSettings::setValue(). This method takes one "@|
  2862. "string and one variant type for a total of two "@|
  2863. "arguments.");
  2864. }
  2865. return QScriptValue();
  2866. }
  2867. @* Scripting QLCDNumber.
  2868. \noindent |QLCDNumber| is used as a base class for \pn{}'@q'@>s |TemperatureDisplay|
  2869. and |TimerDisplay| classes, but it can also be used on its own for the display
  2870. of mainly numeric information.
  2871. @<Function prototypes for scripting@>=
  2872. QScriptValue constructQLCDNumber(QScriptContext *context,
  2873. QScriptEngine *engine);
  2874. void setQLCDNumberProperties(QScriptValue value, QScriptEngine *engine);
  2875. @ The constructor must be passed to the scripting engine.
  2876. @<Set up the scripting engine@>=
  2877. constructor = engine->newFunction(constructQLCDNumber);
  2878. value = engine->newQMetaObject(&QLCDNumber::staticMetaObject, constructor);
  2879. engine->globalObject().setProperty("QLCDNumber", value);
  2880. @ There is nothing special about the implementation.
  2881. @<Functions for scripting@>=
  2882. QScriptValue constructQLCDNumber(QScriptContext *, QScriptEngine *engine)
  2883. {
  2884. QScriptValue object = engine->newQObject(new QLCDNumber());
  2885. setQLCDNumberProperties(object, engine);
  2886. return object;
  2887. }
  2888. void setQLCDNumberProperties(QScriptValue value, QScriptEngine *engine)
  2889. {
  2890. setQFrameProperties(value, engine);
  2891. }
  2892. @* Scripting QTime.
  2893. \noindent |QTime| is a little different from the classes examined so far. This
  2894. class can be used for synchonizing time among various objects by creating a
  2895. common base reference time. This should not be needed as ECMA-262 already
  2896. specifies a |Date| class, however this has historically been troublesome to use.
  2897. One thing that makes this class different is that it is not related to
  2898. |QObject|. This makes usefully exposing it to the scripting engine a little more
  2899. difficult.
  2900. @<Function prototypes for scripting@>=
  2901. QScriptValue constructQTime(QScriptContext *context, QScriptEngine *engine);
  2902. QScriptValue QTime_addMSecs(QScriptContext *context, QScriptEngine *engine);
  2903. QScriptValue QTime_addSecs(QScriptContext *context, QScriptEngine *engine);
  2904. QScriptValue QTime_elapsed(QScriptContext *context, QScriptEngine *engine);
  2905. QScriptValue QTime_hour(QScriptContext *context, QScriptEngine *engine);
  2906. QScriptValue QTime_isNull(QScriptContext *context, QScriptEngine *engine);
  2907. QScriptValue QTime_isValid(QScriptContext *context, QScriptEngine *engine);
  2908. QScriptValue QTime_minute(QScriptContext *context, QScriptEngine *engine);
  2909. QScriptValue QTime_msec(QScriptContext *context, QScriptEngine *engine);
  2910. QScriptValue QTime_msecsTo(QScriptContext *context, QScriptEngine *engine);
  2911. QScriptValue QTime_restart(QScriptContext *context, QScriptEngine *engine);
  2912. QScriptValue QTime_second(QScriptContext *context, QScriptEngine *engine);
  2913. QScriptValue QTime_secsTo(QScriptContext *context, QScriptEngine *engine);
  2914. QScriptValue QTime_setHMS(QScriptContext *context, QScriptEngine *engine);
  2915. QScriptValue QTime_start(QScriptContext *context, QScriptEngine *engine);
  2916. QScriptValue QTime_toString(QScriptContext *context, QScriptEngine *engine);
  2917. QScriptValue QTime_currentTime(QScriptContext *context, QScriptEngine *engine);
  2918. QScriptValue QTime_fromString(QScriptContext *context, QScriptEngine *engine);
  2919. QScriptValue QTime_valueOf(QScriptContext *context, QScriptEngine *engine);
  2920. void setQTimeProperties(QScriptValue value, QScriptEngine *engine);
  2921. @ We must tell the script engine about the constructor. This is not done in
  2922. quite the same way as is done for |QObject| derived types.
  2923. @<Set up the scripting engine@>=
  2924. constructor = engine->newFunction(constructQTime);
  2925. engine->globalObject().setProperty("QTime", constructor);
  2926. @ The constructor has a couple interesting twists. The first is the ability to
  2927. accept a variable number of integer arguments. The other is that |QTime| is not
  2928. derived from |QObject|. The lack of |break| statements in the |switch| is
  2929. intended.
  2930. @<Functions for scripting@>=
  2931. QScriptValue constructQTime(QScriptContext *context,
  2932. QScriptEngine *engine)
  2933. {
  2934. QScriptValue object;
  2935. if(context->argumentCount() == 0 ||
  2936. (context->argumentCount() >= 2 && context->argumentCount() <= 4))@/
  2937. {
  2938. int arg1 = 0;
  2939. int arg2 = 0;
  2940. int arg3 = 0;
  2941. int arg4 = 0;
  2942. switch(context->argumentCount())
  2943. {@t\1@>@/
  2944. case 4:@/
  2945. arg4 = argument<int>(3, context);
  2946. case 3:@/
  2947. arg3 = argument<int>(2, context);
  2948. case 2:@/
  2949. arg2 = argument<int>(1, context);
  2950. arg1 = argument<int>(0, context);
  2951. default:@/
  2952. break;@t\2@>@/
  2953. }
  2954. if(context->argumentCount())
  2955. {
  2956. object = engine->toScriptValue<QTime>(QTime(arg1, arg2, arg3,
  2957. arg4));
  2958. }
  2959. else
  2960. {
  2961. object = engine->toScriptValue<QTime>(QTime());
  2962. }
  2963. setQTimeProperties(object, engine);
  2964. }
  2965. else
  2966. {
  2967. context->throwError("Incorrect number of arguments passed to "@|
  2968. "QTime::QTime(). This method takes zero, two, "@|
  2969. "three, or four integer arguments.");
  2970. }
  2971. return object;
  2972. }
  2973. @ In order to use the various |QTime| methods, we must add wrapper functions as
  2974. properties of newly created script objects. The last two of these should really
  2975. be callable without starting from an existing |QTime|.
  2976. @<Functions for scripting@>=
  2977. void setQTimeProperties(QScriptValue value, QScriptEngine *engine)
  2978. {
  2979. value.setProperty("addMSecs", engine->newFunction(QTime_addMSecs));
  2980. value.setProperty("addSecs", engine->newFunction(QTime_addSecs));
  2981. value.setProperty("elapsed", engine->newFunction(QTime_elapsed));
  2982. value.setProperty("hour", engine->newFunction(QTime_hour));
  2983. value.setProperty("isNull", engine->newFunction(QTime_isNull));
  2984. value.setProperty("isValid", engine->newFunction(QTime_isValid));
  2985. value.setProperty("minute", engine->newFunction(QTime_minute));
  2986. value.setProperty("msec", engine->newFunction(QTime_msec));
  2987. value.setProperty("msecsTo", engine->newFunction(QTime_msecsTo));
  2988. value.setProperty("restart", engine->newFunction(QTime_restart));
  2989. value.setProperty("second", engine->newFunction(QTime_second));
  2990. value.setProperty("secsTo", engine->newFunction(QTime_secsTo));
  2991. value.setProperty("setHMS", engine->newFunction(QTime_setHMS));
  2992. value.setProperty("start", engine->newFunction(QTime_start));
  2993. value.setProperty("toString", engine->newFunction(QTime_toString));
  2994. value.setProperty("currentTime", engine->newFunction(QTime_currentTime));
  2995. value.setProperty("fromString", engine->newFunction(QTime_fromString));
  2996. value.setProperty("valueOf", engine->newFunction(QTime_valueOf));
  2997. }
  2998. @ The |valueOf()| method exposes a numeric representation of the time
  2999. suitable for use in comparing two time values. With this it is possible to
  3000. take two |QTime| values in script code {\tt t1} and {\tt t2} and get the
  3001. expected results from {\tt t1 == t2}, {\tt t1 < t2}, {\tt t1 > t2} and
  3002. similar comparative operations.
  3003. @<Functions for scripting@>=
  3004. QScriptValue QTime_valueOf(QScriptContext *context, QScriptEngine *)
  3005. {
  3006. QTime self = getself<QTime>(context);
  3007. int retval = (self.hour() * 60 * 60 * 1000) + (self.minute() * 60 * 1000) +
  3008. (self.second() * 1000) + self.msec();
  3009. return QScriptValue(retval);
  3010. }
  3011. @ These functions are effectively wrapper functions around existing |QTime|
  3012. functionality with some error checking for the scripting engine.
  3013. The |addMSecs()| and |addSecs()| methods return a new |QTime| object.
  3014. @<Functions for scripting@>=
  3015. QScriptValue QTime_addMSecs(QScriptContext *context, QScriptEngine *engine)
  3016. {
  3017. QTime time;
  3018. QScriptValue retval;
  3019. if(context->argumentCount() == 1)
  3020. {
  3021. QTime self = getself<QTime>(context);
  3022. time = self.addMSecs(argument<int>(0, context));
  3023. retval = engine->toScriptValue<QTime>(time);
  3024. setQTimeProperties(retval, engine);
  3025. }
  3026. else
  3027. {
  3028. context->throwError("Incorrect number of arguments passed to "@|
  3029. "QTime::addMSecs(). This method takes one "@|
  3030. "integer as an argument.");
  3031. }
  3032. return retval;
  3033. }
  3034. QScriptValue QTime_addSecs(QScriptContext *context, QScriptEngine *engine)
  3035. {
  3036. QTime time;
  3037. QScriptValue retval;
  3038. if(context->argumentCount() == 1)
  3039. {
  3040. QTime self = getself<QTime>(context);
  3041. time = self.addSecs(argument<int>(0, context));
  3042. retval = engine->toScriptValue<QTime>(time);
  3043. setQTimeProperties(retval, engine);
  3044. }
  3045. else
  3046. {
  3047. context->throwError("Incorrect number of arguments passed to "@|
  3048. "QTime::addSecs(). This method takes one "@|
  3049. "integer as an argument.");
  3050. }
  3051. return retval;
  3052. }
  3053. @ The |elapsed()| method returns an integer value.
  3054. @<Functions for scripting@>=
  3055. QScriptValue QTime_elapsed(QScriptContext *context, QScriptEngine *engine)
  3056. {
  3057. QScriptValue retval;
  3058. if(context->argumentCount() == 0)
  3059. {
  3060. QTime self = getself<QTime>(context);
  3061. retval = QScriptValue(engine, self.elapsed());
  3062. }
  3063. else
  3064. {
  3065. context->throwError("Incorrect number of arguments passed to "@|
  3066. "QTime::elapsed(). This method takes no "@|
  3067. "arguments.");
  3068. }
  3069. return retval;
  3070. }
  3071. @ The |hour()|, |minute()|, |second()| and |msec()| methods return an integer
  3072. with various parts of the time. The |hour()| method is typical of these methods.
  3073. @<Functions for scripting@>=
  3074. QScriptValue QTime_hour(QScriptContext *context, QScriptEngine *engine)
  3075. {
  3076. QScriptValue retval;
  3077. if(context->argumentCount() == 0)
  3078. {
  3079. QTime self = getself<QTime>(context);
  3080. retval = QScriptValue(engine, self.hour());
  3081. }
  3082. else
  3083. {
  3084. context->throwError("Incorrect number of arguments passed to "@|
  3085. "QTime::hour(). This method takes no "@|
  3086. "arguments.");
  3087. }
  3088. return retval;
  3089. }
  3090. @ The |minute()|, |second()|, and |msec()| methods are implemented similarly.
  3091. @<Functions for scripting@>=
  3092. QScriptValue QTime_minute(QScriptContext *context, QScriptEngine *engine)
  3093. {
  3094. QScriptValue retval;
  3095. if(context->argumentCount() == 0)
  3096. {
  3097. QTime self = getself<QTime>(context);
  3098. retval = QScriptValue(engine, self.minute());
  3099. }
  3100. else
  3101. {
  3102. context->throwError("Incorrect number of arguments passed to "@|
  3103. "QTime::minute(). This method takes no "@|
  3104. "arguments.");
  3105. }
  3106. return retval;
  3107. }
  3108. QScriptValue QTime_second(QScriptContext *context, QScriptEngine *engine)
  3109. {
  3110. QScriptValue retval;
  3111. if(context->argumentCount() == 0)
  3112. {
  3113. QTime self = getself<QTime>(context);
  3114. retval = QScriptValue(engine, self.second());
  3115. }
  3116. else
  3117. {
  3118. context->throwError("Incorrect number of arguments passed to "@|
  3119. "QTime::second(). This method takes no "@|
  3120. "arguments.");
  3121. }
  3122. return retval;
  3123. }
  3124. QScriptValue QTime_msec(QScriptContext *context, QScriptEngine *engine)
  3125. {
  3126. QScriptValue retval;
  3127. if(context->argumentCount() == 0)
  3128. {
  3129. QTime self = getself<QTime>(context);
  3130. retval = QScriptValue(engine, self.msec());
  3131. }
  3132. else
  3133. {
  3134. context->throwError("Incorrect number of arguments passed to "@|
  3135. "QTime::msec(). This method takes no "@|
  3136. "arguments.");
  3137. }
  3138. return retval;
  3139. }
  3140. @ The |isNull()| and |isValid()| methods return a boolean value. A |QTime| is
  3141. considered null if it was created with a constructor with no arguments. It is
  3142. considered invalid if it is null or if part of the time is out of range.
  3143. @<Functions for scripting@>=
  3144. QScriptValue QTime_isNull(QScriptContext *context, QScriptEngine *engine)
  3145. {
  3146. QScriptValue retval;
  3147. if(context->argumentCount() == 0)
  3148. {
  3149. QTime self = getself<QTime>(context);
  3150. retval = QScriptValue(engine, self.isNull());
  3151. }
  3152. else
  3153. {
  3154. context->throwError("Incorrect number of arguments passed to "@|
  3155. "QTime::isNull(). This method takes no "@|
  3156. "arguments.");
  3157. }
  3158. return retval;
  3159. }
  3160. QScriptValue QTime_isValid(QScriptContext *context, QScriptEngine *engine)
  3161. {
  3162. QScriptValue retval;
  3163. if(context->argumentCount() == 0)
  3164. {
  3165. QTime self = getself<QTime>(context);
  3166. retval = QScriptValue(engine, self.isValid());
  3167. }
  3168. else
  3169. {
  3170. context->throwError("Incorrect number of arguments passed to "@|
  3171. "QTime::isValid(). This method takes no "@|
  3172. "arguments.");
  3173. }
  3174. return retval;
  3175. }
  3176. @ The |secsTo()| and |msecsTo()| methods return an integer value indicating the
  3177. number of seconds or milliseconds until a |QTime| argument.
  3178. @<Functions for scripting@>=
  3179. QScriptValue QTime_msecsTo(QScriptContext *context, QScriptEngine *engine)
  3180. {
  3181. QScriptValue retval;
  3182. if(context->argumentCount() == 1)
  3183. {
  3184. QTime self = getself<QTime>(context);
  3185. QTime arg = argument<QVariant>(0, context).toTime();
  3186. retval = QScriptValue(engine, self.msecsTo(arg));
  3187. }
  3188. else
  3189. {
  3190. context->throwError("Incorrect number of arguments passed to "@|
  3191. "QTime::msecsTo(). This method takes one QTime.");
  3192. }
  3193. return retval;
  3194. }
  3195. QScriptValue QTime_secsTo(QScriptContext *context, QScriptEngine *engine)
  3196. {
  3197. QScriptValue retval;
  3198. if(context->argumentCount() == 1)
  3199. {
  3200. QTime self = getself<QTime>(context);
  3201. QTime arg = argument<QVariant>(0, context).toTime();
  3202. retval = QScriptValue(engine, self.secsTo(arg));
  3203. }
  3204. else
  3205. {
  3206. context->throwError("Incorrect number of arguments passed to "@|
  3207. "QTime::secsTo(). This method takes one QTime.");
  3208. }
  3209. return retval;
  3210. }
  3211. @ The |start()| and |restart()| methods each set the value of the |QTime()| to
  3212. the current time. The |restart()| method additionally returns the same value as
  3213. the |elapsed()| method.
  3214. @<Functions for scripting@>=
  3215. QScriptValue QTime_restart(QScriptContext *context, QScriptEngine *engine)
  3216. {
  3217. QScriptValue retval;
  3218. if(context->argumentCount() == 0)
  3219. {
  3220. QTime self = getself<QTime>(context);
  3221. retval = QScriptValue(engine, self.restart());
  3222. }
  3223. else
  3224. {
  3225. context->throwError("Incorrect number of arguments passed to "@|
  3226. "QTime::restart(). This method takes no "@|
  3227. "arguments.");
  3228. }
  3229. return retval;
  3230. }
  3231. QScriptValue QTime_start(QScriptContext *context, QScriptEngine *)
  3232. {
  3233. if(context->argumentCount() == 0)
  3234. {
  3235. QTime self = getself<QTime>(context);
  3236. self.start();
  3237. }
  3238. else
  3239. {
  3240. context->throwError("Incorrect number of arguments passed to "@|
  3241. "QTime::start(). This method takes no arguments.");
  3242. }
  3243. return QScriptValue();
  3244. }
  3245. @ The slightly inappropriately named |setHMS()| method changes the current value
  3246. of the time and returns a boolean to indicate if the new time value is valid.
  3247. @<Functions for scripting@>=
  3248. QScriptValue QTime_setHMS(QScriptContext *context, QScriptEngine *engine)
  3249. {
  3250. QScriptValue retval;
  3251. if(context->argumentCount() == 3 || context->argumentCount() == 4)
  3252. {
  3253. QTime self = getself<QTime>(context);
  3254. int arg1 = 0;
  3255. int arg2 = 0;
  3256. int arg3 = 0;
  3257. int arg4 = 0;
  3258. switch(context->argumentCount())@/
  3259. {@t\1@>@/
  3260. case 4:@/
  3261. arg4 = argument<int>(3, context);
  3262. case 3:@/
  3263. arg3 = argument<int>(2, context);
  3264. arg2 = argument<int>(1, context);
  3265. arg1 = argument<int>(0, context);
  3266. default:@/
  3267. break;@t\2@>@/
  3268. }
  3269. retval = QScriptValue(engine, self.setHMS(arg1, arg2, arg3, arg4));
  3270. }
  3271. else
  3272. {
  3273. context->throwError("Incorrect number of arguments passed to "@|
  3274. "QTime::setHMS(). This method takes three or "@|
  3275. "four integer arguments.");
  3276. }
  3277. return retval;
  3278. }
  3279. @ The |toString()| method returns a string representation of the time. See the
  3280. Qt documentation for instructions on creating a valid format string.
  3281. @<Functions for scripting@>=
  3282. QScriptValue QTime_toString(QScriptContext *context, QScriptEngine *engine)
  3283. {
  3284. QScriptValue retval;
  3285. if(context->argumentCount() == 1)
  3286. {
  3287. QTime self = getself<QTime>(context);
  3288. retval = QScriptValue(engine, self.toString(argument<QString>(0, context)));
  3289. }
  3290. else
  3291. {
  3292. context->throwError("Incorrect number of arguments passed to "@|
  3293. "QTime::toString(). This method takes one QString "@|
  3294. "as an argument.");
  3295. }
  3296. return retval;
  3297. }
  3298. @ The |currentTime()| and |fromString()| methods return a new |QTime| object.
  3299. These methods make no reference to the any other existing |QTime|.
  3300. @<Functions for scripting@>=
  3301. QScriptValue QTime_currentTime(QScriptContext *, QScriptEngine *engine)
  3302. {
  3303. QScriptValue object;
  3304. object = engine->toScriptValue<QTime>(QTime::currentTime());
  3305. setQTimeProperties(object, engine);
  3306. return object;
  3307. }
  3308. QScriptValue QTime_fromString(QScriptContext *context, QScriptEngine *engine)
  3309. {
  3310. QScriptValue object;
  3311. if(context->argumentCount() == 2)
  3312. {
  3313. QString time = argument<QString>(0, context);
  3314. QString format = argument<QString>(1, context);
  3315. object = engine->toScriptValue<QTime>(QTime::fromString(time, format));
  3316. setQTimeProperties(object, engine);
  3317. }
  3318. else
  3319. {
  3320. context->throwError("Incorrect number of arguments passed to "@|
  3321. "QTime::fromString(). This method takes two "@|
  3322. "string arguments.");
  3323. }
  3324. return object;
  3325. }
  3326. @ In order to pass |QTime| objects back from a script, we also need to overload
  3327. |argument()| for this type.
  3328. @<Functions for scripting@>=
  3329. template<> QTime argument(int arg, QScriptContext *context)
  3330. {
  3331. return qscriptvalue_cast<QTime>(context->argument(arg));
  3332. }
  3333. @* Scripting Item View Classes.
  3334. \noindent |QAbstractScrollArea| is a |QFrame| that serves as the base class for
  3335. classes such as |QGraphicsView| and |QAbstractItemView|. Objects from this class
  3336. are not created directly.
  3337. @<Function prototypes for scripting@>=
  3338. void setQAbstractScrollAreaProperties(QScriptValue value,
  3339. QScriptEngine *engine);
  3340. @ The implementation of this is simple.
  3341. @<Functions for scripting@>=
  3342. void setQAbstractScrollAreaProperties(QScriptValue value, QScriptEngine *engine)
  3343. {
  3344. setQFrameProperties(value, engine);
  3345. }
  3346. @ This class is used by the |QAbstractItemView| class. This is another class
  3347. that we do not need a script constructor for.
  3348. @<Function prototypes for scripting@>=
  3349. void setQAbstractItemViewProperties(QScriptValue value, QScriptEngine *engine);
  3350. @ This function has another simple implementation.
  3351. @<Functions for scripting@>=
  3352. void setQAbstractItemViewProperties(QScriptValue value, QScriptEngine *engine)
  3353. {
  3354. setQAbstractScrollAreaProperties(value, engine);
  3355. }
  3356. @ The |QGraphicsView| and |QTableView| classes form the base of \pn{} classes.
  3357. @<Function prototypes for scripting@>=
  3358. void setQGraphicsViewProperties(QScriptValue value, QScriptEngine *engine);
  3359. void setQTableViewProperties(QScriptValue value, QScriptEngine *engine);
  3360. @ Again, the implementations are boring.
  3361. @<Functions for scripting@>=
  3362. void setQGraphicsViewProperties(QScriptValue value, QScriptEngine *engine)
  3363. {
  3364. setQAbstractScrollAreaProperties(value, engine);
  3365. }
  3366. void setQTableViewProperties(QScriptValue value, QScriptEngine *engine)
  3367. {
  3368. setQAbstractItemViewProperties(value, engine);
  3369. }
  3370. @* Scripting Button Classes.
  3371. \noindent \pn{} provides an |AnnotationButton| class which is a special kind of
  3372. |QPushButton| which in turn comes from |QAbstractButton|. While
  3373. |AnnotationButton| can be used in exactly the same way as a |QPushButton|, if
  3374. an annotation is not needed, there is little reason not to use the base class.
  3375. @<Function prototypes for scripting@>=
  3376. void setQAbstractButtonProperties(QScriptValue value, QScriptEngine *engine);
  3377. void setQPushButtonProperties(QScriptValue value, QScriptEngine *engine);
  3378. QScriptValue constructQPushButton(QScriptContext *context,
  3379. QScriptEngine *engine);
  3380. @ The constructor for |QPushButton| should be passed to the scripting engine.
  3381. @<Set up the scripting engine@>=
  3382. constructor = engine->newFunction(constructQPushButton);
  3383. value = engine->newQMetaObject(&QPushButton::staticMetaObject, constructor);
  3384. engine->globalObject().setProperty("QPushButton", value);
  3385. @ The implementation should seem familiar.
  3386. @<Functions for scripting@>=
  3387. QScriptValue constructQPushButton(QScriptContext *, QScriptEngine *engine)
  3388. {
  3389. QScriptValue object = engine->newQObject(new QPushButton());
  3390. setQPushButtonProperties(object, engine);
  3391. return object;
  3392. }
  3393. void setQPushButtonProperties(QScriptValue value, QScriptEngine *engine)
  3394. {
  3395. setQAbstractButtonProperties(value, engine);
  3396. }
  3397. void setQAbstractButtonProperties(QScriptValue value, QScriptEngine *engine)
  3398. {
  3399. setQWidgetProperties(value, engine);
  3400. }
  3401. @* Scripting QSqlQuery.
  3402. \noindent With this class exposed to the host environment, it becomes possible
  3403. for script code to execute SQL queries and evaluate the result.
  3404. Rather than use |QSqlQuery| directly, however, we use a proxy \nfnote{Erich
  3405. Gamma, Richard Helm, Raph Johnson, and John
  3406. Vlissides,\par\indent\underbar{Design Patterns: elements of reusable
  3407. object-oriented software} (1995) pp. 207--217} class. This class obtains its own
  3408. database connection and handles properly closing and removing these connections
  3409. when the query object is destroyed.
  3410. @<Class declarations@>=
  3411. class SqlQueryConnection : public QSqlQuery@/
  3412. {
  3413. public:@/
  3414. SqlQueryConnection(const QString &query = QString());
  3415. ~SqlQueryConnection();
  3416. QSqlQuery* operator->() const;
  3417. private:@/
  3418. QString connection;
  3419. QSqlQuery *q;
  3420. };
  3421. @ The constructor can be somewhat simplified from the four forms of |QSqlQuery|.
  3422. We are not interested in creating an object from a |QSqlResult| or from another
  3423. |QSqlQuery|. The database connection is managed by the class itself so the
  3424. constructor only needs an optional string containing a query. This is used to
  3425. initialize a real |QSqlQuery| object.
  3426. @<SqlQueryConnection implementation@>=
  3427. SqlQueryConnection::SqlQueryConnection(const QString &query)
  3428. {
  3429. QSqlDatabase database = AppInstance->database();
  3430. database.open();
  3431. q = new QSqlQuery(query, database);
  3432. connection = database.connectionName();
  3433. }
  3434. @ The destructor handles removing the |QSqlQuery| and the database connection
  3435. associated with it. The extra brackets introduce a new scope for the
  3436. |QSqlDatabase| so that it is out of scope when the connection is removed.
  3437. @<SqlQueryConnection implementation@>=
  3438. SqlQueryConnection::~SqlQueryConnection()
  3439. {
  3440. delete q;
  3441. {
  3442. QSqlDatabase database = QSqlDatabase::database(connection);
  3443. database.close();
  3444. }
  3445. QSqlDatabase::removeDatabase(connection);
  3446. }
  3447. @ For all other functionality, we simply forward the request to our |QSqlQuery|
  3448. object.
  3449. @<SqlQueryConnection implementation@>=
  3450. QSqlQuery* SqlQueryConnection::operator->() const
  3451. {
  3452. return q;
  3453. }
  3454. @ In order to use this new class in the host environment, a number of functions
  3455. are needed.
  3456. @<Function prototypes for scripting@>=
  3457. void setQSqlQueryProperties(QScriptValue value, QScriptEngine *engine);
  3458. QScriptValue constructQSqlQuery(QScriptContext *context, QScriptEngine *engine);
  3459. QScriptValue QSqlQuery_bind(QScriptContext *context, QScriptEngine *engine);
  3460. QScriptValue QSqlQuery_bindDeviceData(QScriptContext *context,
  3461. QScriptEngine *engine);
  3462. QScriptValue QSqlQuery_bindFileData(QScriptContext *context,
  3463. QScriptEngine *engine);
  3464. QScriptValue QSqlQuery_exec(QScriptContext *context,
  3465. QScriptEngine *engine);
  3466. QScriptValue QSqlQuery_executedQuery(QScriptContext *context,
  3467. QScriptEngine *engine);
  3468. QScriptValue QSqlQuery_invalidate(QScriptContext *context, QScriptEngine *engine);
  3469. QScriptValue QSqlQuery_next(QScriptContext *context, QScriptEngine *engine);
  3470. QScriptValue QSqlQuery_prepare(QScriptContext *context, QScriptEngine *engine);
  3471. QScriptValue QSqlQuery_value(QScriptContext *context, QScriptEngine *engine);
  3472. @ For conceptual convenience we simply pretend that we are working with a real
  3473. |QSqlQuery| object.
  3474. @<Set up the scripting engine@>=
  3475. constructor = engine->newFunction(constructQSqlQuery);
  3476. engine->globalObject().setProperty("QSqlQuery", constructor);
  3477. @ With connection creation no longer needed in the constructor, all that is
  3478. needed is object creation and applying the appropriate properties to the script
  3479. value.
  3480. @<Functions for scripting@>=
  3481. QScriptValue constructQSqlQuery(QScriptContext *, QScriptEngine *engine)
  3482. {
  3483. SqlQueryConnection *obj = new SqlQueryConnection();
  3484. QScriptValue object =
  3485. engine->toScriptValue<void *>(obj);
  3486. setQSqlQueryProperties(object, engine);
  3487. return object;
  3488. }
  3489. @ As this class does not derive from |QObject|, we must wrap all of the methods
  3490. we might want to use.
  3491. @<Functions for scripting@>=
  3492. void setQSqlQueryProperties(QScriptValue value, QScriptEngine *engine)
  3493. {
  3494. value.setProperty("bind", engine->newFunction(QSqlQuery_bind));
  3495. value.setProperty("bindFileData",
  3496. engine->newFunction(QSqlQuery_bindFileData));
  3497. value.setProperty("bindDeviceData",
  3498. engine->newFunction(QSqlQuery_bindDeviceData));
  3499. value.setProperty("exec", engine->newFunction(QSqlQuery_exec));
  3500. value.setProperty("executedQuery", engine->newFunction(QSqlQuery_executedQuery));
  3501. value.setProperty("invalidate", engine->newFunction(QSqlQuery_invalidate));
  3502. value.setProperty("next", engine->newFunction(QSqlQuery_next));
  3503. value.setProperty("prepare", engine->newFunction(QSqlQuery_prepare));
  3504. value.setProperty("value", engine->newFunction(QSqlQuery_value));
  3505. }
  3506. @ Most of these properties are wrappers around existing |QSqlQuery| functions.
  3507. @<Functions for scripting@>=
  3508. QScriptValue QSqlQuery_exec(QScriptContext *context, QScriptEngine *engine)
  3509. {
  3510. QSqlQuery *q = getself<SqlQueryConnection *>(context)->operator->();
  3511. QScriptValue retval;
  3512. if(context->argumentCount() == 1)
  3513. {
  3514. retval = QScriptValue(engine,
  3515. q->exec(argument<QString>(0, context)));
  3516. }
  3517. else
  3518. {
  3519. retval = QScriptValue(engine, q->exec());
  3520. }
  3521. if(q->lastError().isValid())
  3522. {
  3523. qDebug() << q->lastQuery();
  3524. qDebug() << q->lastError().text();
  3525. }
  3526. return retval;
  3527. }
  3528. QScriptValue QSqlQuery_executedQuery(QScriptContext *context, QScriptEngine *)
  3529. {
  3530. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3531. return QScriptValue(query->lastQuery());
  3532. }
  3533. QScriptValue QSqlQuery_next(QScriptContext *context, QScriptEngine *engine)
  3534. {
  3535. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3536. return QScriptValue(engine, query->next());
  3537. }
  3538. QScriptValue QSqlQuery_value(QScriptContext *context, QScriptEngine *engine)
  3539. {
  3540. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3541. return QScriptValue(engine,
  3542. query->value(argument<int>(0, context)).toString());
  3543. }
  3544. @ For prepared queries, we support binding variables available to the script,
  3545. data available in a named file, or data from any open |QIODevice|.
  3546. @<Functions for scripting@>=
  3547. QScriptValue QSqlQuery_prepare(QScriptContext *context, QScriptEngine *engine)
  3548. {
  3549. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3550. return QScriptValue(engine, query->prepare(argument<QString>(0, context)));
  3551. }
  3552. QScriptValue QSqlQuery_bind(QScriptContext *context, QScriptEngine *)
  3553. {
  3554. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3555. query->bindValue(argument<QString>(0, context),
  3556. argument<QVariant>(1, context));
  3557. return QScriptValue();
  3558. }
  3559. QScriptValue QSqlQuery_bindFileData(QScriptContext *context,
  3560. QScriptEngine *)
  3561. {
  3562. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3563. QString placeholder = argument<QString>(0, context);
  3564. QString filename = argument<QString>(1, context);
  3565. QFile file(filename);
  3566. QByteArray data;
  3567. if(file.open(QIODevice::ReadOnly))
  3568. {
  3569. data = file.readAll();
  3570. file.close();
  3571. }
  3572. query->bindValue(placeholder, data);
  3573. return QScriptValue();
  3574. }
  3575. QScriptValue QSqlQuery_bindDeviceData(QScriptContext *context,
  3576. QScriptEngine *)
  3577. {
  3578. QSqlQuery *query = getself<SqlQueryConnection *>(context)->operator->();
  3579. QString placeholder = argument<QString>(0, context);
  3580. QIODevice *device = argument<QIODevice *>(1, context);
  3581. device->reset();
  3582. QByteArray data;
  3583. data = device->readAll();
  3584. query->bindValue(placeholder, data);
  3585. return QScriptValue();
  3586. }
  3587. @ To avoid leaking database connections, we add the |invalidate()| property
  3588. which destroys our object. The object on which this method is called must not be
  3589. used after calling this method. In script code this will typically be used as in
  3590. the following example:
  3591. {\tt query = query.invalidate();}
  3592. @<Functions for scripting@>=
  3593. QScriptValue QSqlQuery_invalidate(QScriptContext *context, QScriptEngine *)
  3594. {
  3595. SqlQueryConnection *query = getself<SqlQueryConnection *>(context);
  3596. delete query;
  3597. return QScriptValue::UndefinedValue;
  3598. }
  3599. @* Other scripting functions.
  3600. \noindent There are a few functions that are exposed to the scripting engine
  3601. that are not associated with any class. Two functions are used for extracting
  3602. information from file names. Another is used to construct array values from SQL
  3603. array values. There is also a function for setting the default font for the
  3604. application or some part of the application.
  3605. @<Function prototypes for scripting@>=
  3606. QScriptValue baseName(QScriptContext *context, QScriptEngine *engine);
  3607. QScriptValue dir(QScriptContext *context, QScriptEngine *engine);
  3608. QScriptValue sqlToArray(QScriptContext *context, QScriptEngine *engine);
  3609. QScriptValue setFont(QScriptContext *context, QScriptEngine *engine);
  3610. QScriptValue annotationFromRecord(QScriptContext *context,
  3611. QScriptEngine *engine);
  3612. QScriptValue setTabOrder(QScriptContext *context, QScriptEngine *engine);
  3613. QScriptValue saveFileFromDatabase(QScriptContext *context, QScriptEngine *engine);
  3614. QScriptValue scriptTr(QScriptContext *context, QScriptEngine *engine);
  3615. @ These functions are passed to the scripting engine.
  3616. @<Set up the scripting engine@>=
  3617. engine->globalObject().setProperty("baseName", engine->newFunction(baseName));
  3618. engine->globalObject().setProperty("dir", engine->newFunction(dir));
  3619. engine->globalObject().setProperty("sqlToArray",
  3620. engine->newFunction(sqlToArray));
  3621. engine->globalObject().setProperty("setFont", engine->newFunction(setFont));
  3622. engine->globalObject().setProperty("annotationFromRecord",
  3623. engine->newFunction(annotationFromRecord));
  3624. engine->globalObject().setProperty("setTabOrder",
  3625. engine->newFunction(setTabOrder));
  3626. engine->globalObject().setProperty("saveFileFromDatabase",
  3627. engine->newFunction(saveFileFromDatabase));
  3628. engine->globalObject().setProperty("TTR", engine->newFunction(scriptTr));
  3629. @ These functions are not part of an object. They expect a string specifying
  3630. the path to a file and return a string with either the name of the file without
  3631. the path and extension or the path of the directory containing the file.
  3632. @<Functions for scripting@>=
  3633. QScriptValue baseName(QScriptContext *context, QScriptEngine *engine)
  3634. {
  3635. QFileInfo info(argument<QString>(0, context));
  3636. QScriptValue retval(engine, info.baseName());
  3637. return retval;
  3638. }
  3639. QScriptValue dir(QScriptContext *context, QScriptEngine *engine)
  3640. {
  3641. QFileInfo info(argument<QString>(0, context));
  3642. QDir dir = info.dir();
  3643. QScriptValue retval(engine, dir.path());
  3644. return retval;
  3645. }
  3646. @ This function takes a file ID and a file name and copies file data stored in
  3647. the database out to the file system.
  3648. @<Functions for scripting@>=
  3649. QScriptValue saveFileFromDatabase(QScriptContext *context, QScriptEngine *)
  3650. {
  3651. SqlQueryConnection h;
  3652. QSqlQuery *query = h.operator->();
  3653. QString q = "SELECT file FROM files WHERE id = :file";
  3654. query->prepare(q);
  3655. query->bindValue(":file", argument<int>(0, context));
  3656. query->exec();
  3657. query->next();
  3658. QByteArray array = query->value(0).toByteArray();
  3659. QFile file(argument<QString>(1, context));
  3660. file.open(QIODevice::WriteOnly);
  3661. file.write(array);
  3662. file.close();
  3663. return QScriptValue();
  3664. }
  3665. @ This function takes a string representing a SQL array and returns an array
  3666. value.
  3667. @<Functions for scripting@>=
  3668. QScriptValue sqlToArray(QScriptContext *context, QScriptEngine *engine)
  3669. {
  3670. QString source = argument<QString>(0, context);
  3671. source.remove(0, 1);
  3672. source.chop(1);
  3673. QStringList elements = source.split(",");
  3674. QString element;
  3675. QScriptValue dest = engine->newArray(elements.size());
  3676. int i = 0;
  3677. foreach(element, elements)
  3678. {
  3679. if(element.startsWith("\"") && element.endsWith("\""))
  3680. {
  3681. element.chop(1);
  3682. element = element.remove(0, 1);
  3683. }
  3684. dest.setProperty(i, QScriptValue(engine, element));
  3685. i++;
  3686. }
  3687. return dest;
  3688. }
  3689. @ This function can be used to set the default font for the application or on
  3690. a per-class hierarchy basis.
  3691. @<Functions for scripting@>=
  3692. QScriptValue setFont(QScriptContext *context, QScriptEngine *)
  3693. {
  3694. QString font = argument<QString>(0, context);
  3695. QString classname;
  3696. if(context->argumentCount() > 1)
  3697. {
  3698. classname = argument<QString>(1, context);
  3699. QApplication::setFont(QFont(font), classname.toLatin1().constData());
  3700. }
  3701. else
  3702. {
  3703. QApplication::setFont(QFont(font));
  3704. }
  3705. return QScriptValue();
  3706. }
  3707. @ This function was briefly used prior to adding support for |QXmlQuery| in the
  3708. host environment. The function is now depreciated and should not be used.
  3709. @<Functions for scripting@>=
  3710. QScriptValue annotationFromRecord(QScriptContext *context, QScriptEngine *)
  3711. {
  3712. SqlQueryConnection h;
  3713. QSqlQuery *query = h.operator->();
  3714. QString q = "SELECT file FROM files WHERE id = :file";
  3715. query->prepare(q);
  3716. query->bindValue(":file", argument<int>(0, context));
  3717. query->exec();
  3718. query->next();
  3719. QByteArray array = query->value(0).toByteArray();
  3720. QBuffer buffer(&array);
  3721. buffer.open(QIODevice::ReadOnly);
  3722. QXmlQuery xquery;
  3723. xquery.bindVariable("profile", &buffer);
  3724. QString xq;
  3725. xq = "for $b in doc($profile) //tuple where exists($b/annotation) return $b";
  3726. xquery.setQuery(xq);
  3727. QString result;
  3728. xquery.evaluateTo(&result);
  3729. return QScriptValue(result);
  3730. }
  3731. @ This function can be used to change the tab order for controls in Typica.
  3732. Changes to the example configuration in \pn{} 1.4 made the default handling
  3733. of tab controls in the logging window unacceptable.
  3734. @<Functions for scripting@>=
  3735. QScriptValue setTabOrder(QScriptContext *context, QScriptEngine *)
  3736. {
  3737. QWidget::setTabOrder(argument<QWidget*>(0, context),
  3738. argument<QWidget*>(1, context));
  3739. return QScriptValue();
  3740. }
  3741. @ This function is used to allow text that must be placed in scripts to be
  3742. translated into other languages.
  3743. @<Functions for scripting@>=
  3744. QScriptValue scriptTr(QScriptContext *context, QScriptEngine *)
  3745. {
  3746. return QScriptValue(QCoreApplication::translate(
  3747. "configuration",
  3748. argument<QString>(1, context).toUtf8().data()));
  3749. }
  3750. @** Application Configuration.
  3751. \noindent While \pn{} is intended as a data logging application, the diversity
  3752. of equipment and supporting technology precludes the option of providing a
  3753. single interface for common tasks. It is important that the application can be
  3754. configured to work with different roasting equipment, databases, and the like.
  3755. To accomplish this, \pn{} utilizes an XML description of the desired application
  3756. configuration and provides an ECMA-262 host environment which allows application
  3757. dataflow to be configured.
  3758. The scripting environment provides access to elements of the XML file and also
  3759. allows access to most of the application classes. A selection of classes
  3760. provided by Qt is also available. See the section on The Scripting Engine for
  3761. more details.
  3762. \danger While the code is the ultimate documentation of what is possible with
  3763. this interface, additional documentation should be provided to document the
  3764. meaning of supported elements and the objects available through the scripting
  3765. engine.\endanger
  3766. The application configuration is loaded when the program is started.
  3767. Starting with version 1.4, we check for a command line option with the path to
  3768. the configuration file and load that instead of prompting for the information
  3769. if possible.
  3770. @<Load the application configuration@>=
  3771. QStringList arguments = QCoreApplication::arguments();
  3772. int position = arguments.indexOf("-c");
  3773. QString filename = QString();
  3774. if(position != -1)
  3775. {
  3776. if(arguments.size() >= position + 1)
  3777. {
  3778. filename = arguments.at(position + 1);
  3779. }
  3780. }
  3781. if(filename.isEmpty())
  3782. {
  3783. filename = QFileDialog::getOpenFileName(NULL, "Open Configuration File",
  3784. settings.value("config", "").toString());
  3785. }
  3786. QDir directory;
  3787. if(!filename.isEmpty())
  3788. {
  3789. QFile file(filename);
  3790. QFileInfo info(filename);
  3791. directory = info.dir();
  3792. QTextCodec::setCodecForTr(QTextCodec::codecForName("utf-8"));
  3793. QTranslator *configtr = new QTranslator;
  3794. if(configtr->load(QString("config.%1").arg(QLocale::system().name()),
  3795. QString("%1/Translations").arg(directory.canonicalPath())))
  3796. {
  3797. QCoreApplication::installTranslator(configtr);
  3798. }
  3799. settings.setValue("config", directory.path());
  3800. if(file.open(QIODevice::ReadOnly))
  3801. {
  3802. app.configuration()->setContent(&file, true);
  3803. }
  3804. }
  3805. @<Substitute included fragments@>@;
  3806. @ The {\tt <application>} element can contain an arbitrary number of
  3807. {\tt <include>} elements. These elements should not appear in the DOM. Instead,
  3808. the element should be replaced by the content of the specified document.
  3809. @<Substitute included fragments@>=
  3810. QDomElement root = app.configuration()->documentElement();
  3811. QDomNodeList children = root.childNodes();
  3812. QString replacementDoc;
  3813. QDomDocument includedDoc;
  3814. QDomDocumentFragment fragment;
  3815. for(int i = 0; i < children.size(); i++)
  3816. {
  3817. QDomNode currentNode = children.at(i);
  3818. QDomElement currentElement;
  3819. if(currentNode.nodeName() == "include")
  3820. {
  3821. currentElement = currentNode.toElement();
  3822. if(currentElement.hasAttribute("src"))
  3823. {
  3824. replacementDoc = directory.path();
  3825. replacementDoc.append('/');
  3826. replacementDoc.append(currentElement.attribute("src"));
  3827. QFile doc(replacementDoc);
  3828. if(doc.open(QIODevice::ReadOnly))
  3829. {
  3830. includedDoc.setContent(&doc, true);
  3831. fragment = includedDoc.createDocumentFragment();
  3832. fragment.appendChild(includedDoc.documentElement());
  3833. root.replaceChild(fragment, currentNode);
  3834. doc.close();
  3835. }
  3836. }
  3837. }
  3838. }
  3839. @ Simply loading the configuration document does not display a user interface or
  3840. set up any objects that allow the program to do anything. To do this, a script
  3841. obtained from the configuration document is run. The root element of the
  3842. document should be {\tt <application>}. This element should have a number of
  3843. child elements including {\tt <window>} elements which describe the various
  3844. windows that can be opened in the application and {\tt <program>} elements
  3845. containing script code. These {\tt <program>} elements can occur in a number of
  3846. different contexts including within {\tt <window>} elements which would indicate
  3847. that such scripts should be evaluated when the window being described is
  3848. created. After the configuration document is loaded, all {\tt <program>}
  3849. elements that are direct children of the {\tt <application>} element are
  3850. concatenated and the script is run.
  3851. Before the script is run and user interface elements are drawn, we also check
  3852. for {\tt <style>} elements which can be used to set up a stylesheet for the
  3853. application.
  3854. @<Find and evaluate starting script@>=
  3855. QString styleText;
  3856. QString programText;
  3857. QDomElement currentElement;
  3858. for(int i = 0; i < children.size(); i++)
  3859. {
  3860. QDomNode currentNode = children.at(i);
  3861. if(currentNode.nodeName() == "style")
  3862. {
  3863. currentElement = currentNode.toElement();
  3864. styleText.append(currentElement.text());
  3865. }
  3866. else if(currentNode.nodeName() == "program")
  3867. {
  3868. currentElement = currentNode.toElement();
  3869. programText.append(currentElement.text());
  3870. }
  3871. }
  3872. app.setStyleSheet(styleText);
  3873. QScriptValue result = engine->evaluate(programText);
  3874. @<Report scripting errors@>
  3875. @ When a script is evaluated, there is a chance that there will be some error in
  3876. the execution of that script. If this occurs, we want to report that.
  3877. @<Report scripting errors@>=
  3878. if(engine->hasUncaughtException())
  3879. {
  3880. int line = engine->uncaughtExceptionLineNumber();
  3881. qDebug() << "Uncaught excpetion at line " << line << " : " <<
  3882. result.toString();
  3883. QString trace;
  3884. foreach(trace, engine->uncaughtExceptionBacktrace())
  3885. {
  3886. qDebug() << trace;
  3887. }
  3888. }
  3889. @* Creating a window.
  3890. \noindent When a configuration document is loaded, none of the {\tt <window>}
  3891. elements are interpreted or used to create a graphical user interface. Instead,
  3892. any {\tt <program>} elements that are immediate children of the
  3893. {\tt <application>} element are interpreted. In order to convert a
  3894. {\tt <window>} element into a window displayed on screen, the script in the
  3895. {\tt <program>} elements must call a function to display a specified window.
  3896. Report windows can be produced by scripts in a similar, but slightly different
  3897. manner.
  3898. \danger This design works, but it'@q'@>s not particularly good design. It was written
  3899. under severe time constraints and should be redesigned or at least cleaned up
  3900. and reorganized.\endanger
  3901. @<Function prototypes for scripting@>=
  3902. QScriptValue createWindow(QScriptContext *context, QScriptEngine *engine);
  3903. QScriptValue createReport(QScriptContext *context, QScriptEngine *engine);
  3904. void addLayoutToWidget(QDomElement element, QStack<QWidget*> *widgetStack,
  3905. QStack<QLayout*> *layoutStack);
  3906. void addLayoutToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3907. QStack<QLayout *> *layoutStack);
  3908. void addSplitterToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3909. QStack<QLayout *> *layoutStack);
  3910. void addSplitterToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  3911. QStack<QLayout *> *layoutStack);
  3912. void populateGridLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3913. QStack<QLayout *> *layoutStack);
  3914. void populateBoxLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3915. QStack<QLayout *> *layoutStack);
  3916. void populateSplitter(QDomElement element, QStack<QWidget *> *widgetStack,@|
  3917. QStack<QLayout *> *layoutStack);
  3918. void populateWidget(QDomElement element, QStack<QWidget *> *widgetStack,@|
  3919. QStack<QLayout *> *layoutStack);
  3920. void populateStackedLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3921. QStack<QLayout *> *layoutStack);
  3922. void addTemperatureDisplayToSplitter(QDomElement element,@|
  3923. QStack<QWidget *> *widgetStack,
  3924. QStack<QLayout *> *layoutStack);
  3925. void addTemperatureDisplayToLayout(QDomElement element,@|
  3926. QStack<QWidget *> *widgetStack,
  3927. QStack<QLayout *> *layoutStack);
  3928. void addTimerDisplayToSplitter(QDomElement element,@|
  3929. QStack<QWidget *> *widgetStack,
  3930. QStack<QLayout *> *layoutStack);
  3931. void addTimerDisplayToLayout(QDomElement element,@|
  3932. QStack<QWidget *> *widgetStack,
  3933. QStack<QLayout *> *layoutStack);
  3934. void addDecorationToSplitter(QDomElement element,@|
  3935. QStack<QWidget *> *widgetStack,
  3936. QStack<QLayout *> *layoutStack);
  3937. void addDecorationToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3938. QStack<QLayout *> *layoutStack);
  3939. void addWidgetToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  3940. QStack<QLayout *> *layoutStack);
  3941. void addButtonToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3942. QStack<QLayout *> *layoutStack);
  3943. void addZoomLogToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  3944. QStack<QLayout *> *layoutStack);
  3945. void addGraphToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  3946. QStack<QLayout *> *layoutStack);
  3947. void addSqlDropToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3948. QStack<QLayout *> *layoutStack);
  3949. void addSaltToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  3950. QStack<QLayout *> *layoutStack);
  3951. void addLineToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  3952. QStack<QLayout *> *layoutStack);
  3953. void addTextToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  3954. QStack<QLayout *> *layoutStack);
  3955. void addSqlQueryViewToLayout(QDomElement element,
  3956. QStack<QWidget *> *widgetStack,
  3957. QStack<QLayout *> *layoutStack);
  3958. void addCalendarToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3959. QStack<QLayout *> *layoutStack);
  3960. void addSpinBoxToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  3961. QStack<QLayout *> *layoutStack);
  3962. @ The functions for creating windows must be made available to the scripting
  3963. engine.
  3964. @<Set up the scripting engine@>=
  3965. engine->globalObject().setProperty("createWindow",
  3966. engine->newFunction(createWindow));
  3967. engine->globalObject().setProperty("createReport",
  3968. engine->newFunction(createReport));
  3969. @ This function must examine the configuration document in search of the
  3970. appropriate window element, parse the contents of that element, and create a
  3971. multitude of objects, all of which must be passed to the scripting engine.
  3972. @<Functions for scripting@>=
  3973. QScriptValue createWindow(QScriptContext *context, QScriptEngine *engine)@/
  3974. {
  3975. QString targetID = argument<QString>(0, context);
  3976. QDomNode element;
  3977. QScriptValue object;
  3978. @<Find the window element@>@;
  3979. if(!element.isNull())
  3980. {
  3981. @<Display the window@>@;
  3982. }
  3983. return object;
  3984. }
  3985. @ Report files are not part of the configuration document and must be created
  3986. differently. While there is a special menu type that handles all of this
  3987. without involving the host environment, scripted generation and manipulation of
  3988. report windows requires another function. This function will only work after a
  3989. window with a reports menu has been created.
  3990. @<Functions for scripting@>=
  3991. QScriptValue createReport(QScriptContext *context, QScriptEngine *engine)
  3992. {
  3993. QString targetID = argument<QString>(0, context);
  3994. QFile file(QString("reports:%1").arg(targetID));
  3995. QScriptValue object;
  3996. if(file.open(QIODevice::ReadOnly))
  3997. {
  3998. QDomDocument document;
  3999. document.setContent(&file, true);
  4000. QDomElement element = document.documentElement();
  4001. if(!element.isNull())
  4002. {
  4003. @<Display the window@>@;
  4004. }
  4005. file.close();
  4006. }
  4007. return object;
  4008. }
  4009. @ First we must locate the {\tt <window>} element. The most sensible way to do
  4010. this would require that each {\tt <window>} element has an ID attribute and
  4011. search the DOM tree for that ID. Unfortunately, as of this writing,
  4012. |QDomDocument::elementByID()| always returns a null element, so that won'@q'@>t work.
  4013. Instead, we search the tree for all {\tt <window>} elements and then examine
  4014. the resulting list to find the element with the appropriate ID.
  4015. @<Find the window element@>=
  4016. QDomNodeList windows =
  4017. AppInstance->configuration()->documentElement().elementsByTagName("window");
  4018. QDomNode nullNode;
  4019. int i = 0;
  4020. element = nullNode;
  4021. while(i < windows.count())
  4022. {
  4023. element = windows.at(i);
  4024. QDomNamedNodeMap attributes = element.attributes();
  4025. if(attributes.contains("id"))
  4026. {
  4027. if(attributes.namedItem("id").toAttr().value() == targetID)
  4028. {
  4029. break;
  4030. }
  4031. }
  4032. element = nullNode;
  4033. i++;
  4034. }
  4035. @ In order to display a window, we start by creating a new |ScriptQMainWindow|
  4036. and set the central widget of that window to a new |QWidget|. After this, we see
  4037. if the window element has any children and proceed to populate the window.
  4038. When creating child elements, care must be taken that all objects are descended
  4039. from the window. If an object is descended from the window and has an object
  4040. name, it will be possible for script code to recover the created object.
  4041. As of version 1.4, the window itself is given the value of its {\tt id}
  4042. attribute as an object name to facilitate automatic window geometry management.
  4043. @<Display the window@>=
  4044. ScriptQMainWindow *window = new ScriptQMainWindow;
  4045. window->setObjectName(targetID);
  4046. object = engine->newQObject(window);
  4047. setQMainWindowProperties(object, engine);
  4048. QWidget *central = new(QWidget);
  4049. central->setParent(window);
  4050. central->setObjectName("centralWidget");
  4051. window->setCentralWidget(central);
  4052. if(element.hasChildNodes())
  4053. {
  4054. @<Process window children@>@;
  4055. }
  4056. @<Insert help menu@>@;
  4057. window->show();
  4058. @ Three element types make sense as top level children of a {\tt <window>}
  4059. element. An element representing a layout element can be used to apply that
  4060. layout to the central widget. An element representing a menu can be used to add
  4061. a menu to the window. A {\tt <program>} element can be used to specify a script
  4062. to be run after the window has been assembled.
  4063. \danger As the window comes with a blank central widget, elements representing
  4064. a widget to be used as the central widget of the window cannot be used directly
  4065. here. If only one widget is needed in the window, there is a need to create a
  4066. layout element and place that widget in the layout. Also note that there is not
  4067. enough error checking in the following code. Provide invalid input at your
  4068. peril.\endanger
  4069. Program fragments pulled from the window description are executed with the
  4070. newly created window available as {\tt this}. When such a fragment is run, the
  4071. entire description of the window will have already been evaluated and any
  4072. necessary objects created. Obtaining a child object of the window can be done
  4073. by calling |findChildObject()|.
  4074. @<Process window children@>=
  4075. QStack<QWidget*> widgetStack;
  4076. QStack<QLayout*> layoutStack;
  4077. QString windowScript;
  4078. widgetStack.push(central);
  4079. QDomNodeList windowChildren = element.childNodes();
  4080. int i = 0;
  4081. while(i < windowChildren.count())
  4082. {
  4083. QDomNode current;
  4084. QDomElement element;
  4085. current = windowChildren.at(i);
  4086. if(current.isElement())
  4087. {
  4088. element = current.toElement();
  4089. if(element.tagName() == "program")
  4090. {
  4091. windowScript.append(element.text());
  4092. }
  4093. else if(element.tagName() == "layout")
  4094. {
  4095. element.setAttribute("trcontext", "configuration");
  4096. addLayoutToWidget(element, &widgetStack, &layoutStack);
  4097. }
  4098. else if(element.tagName() == "menu")
  4099. {
  4100. @<Process menus@>@;
  4101. }
  4102. }
  4103. i++;
  4104. }
  4105. QScriptValue oldThis = context->thisObject();
  4106. context->setThisObject(object);
  4107. QScriptValue result = engine->evaluate(windowScript);
  4108. @<Report scripting errors@>@;
  4109. context->setThisObject(oldThis);
  4110. @ Elements representing menus may provide a number of child elements
  4111. representing the items in that menu. The XML portion of the configuration will
  4112. not provide any information on what these menu items do. The contents of the
  4113. {\tt <program>} element for the window will need to request the |QAction|
  4114. objects and connect a signal from that object to the desired functionality.
  4115. One special consideration is the Reports menu. This menu will populate itself
  4116. according to its own logic and will have a {\tt type} property of
  4117. {\tt "reports"} and a {\tt src} property indicating the directory where reports
  4118. can be found.
  4119. @<Process menus@>=
  4120. QMenuBar *bar = window->menuBar();
  4121. bar->setParent(window);
  4122. bar->setObjectName("menuBar");
  4123. if(element.hasAttribute("name"))
  4124. {
  4125. QMenu *menu = bar->addMenu(QCoreApplication::translate("configuration",
  4126. element.attribute("name").toUtf8().data()));
  4127. menu->setParent(bar);
  4128. if(element.hasAttribute("type"))
  4129. {
  4130. if(element.attribute("type") == "reports")
  4131. {
  4132. if(element.hasAttribute("src"))
  4133. {
  4134. @<Populate reports menu@>@;
  4135. }
  4136. }
  4137. }
  4138. if(element.hasChildNodes())
  4139. {
  4140. @<Process menu items@>@;
  4141. }
  4142. }
  4143. @ To add items to a menu, we check for {\tt <item>} elements under the
  4144. {\tt <menu>} element and create a |QAction| for each item.
  4145. @<Process menu items@>=
  4146. QDomNodeList menuItems = element.childNodes();
  4147. int j = 0;
  4148. while(j < menuItems.count())
  4149. {
  4150. QDomNode item = menuItems.at(j);
  4151. if(item.isElement())
  4152. {
  4153. QDomElement itemElement = item.toElement();
  4154. if(itemElement.tagName() == "item")
  4155. {
  4156. QAction *itemAction = new QAction(QCoreApplication::translate("configuration",
  4157. itemElement.text().toUtf8().data()), menu);
  4158. if(itemElement.hasAttribute("id"))
  4159. {
  4160. itemAction->setObjectName(itemElement.attribute("id"));
  4161. }
  4162. if(itemElement.hasAttribute("shortcut"))
  4163. {
  4164. itemAction->setShortcut(itemElement.attribute("shortcut"));
  4165. }
  4166. menu->addAction(itemAction);
  4167. }
  4168. else if(itemElement.tagName() == "separator")
  4169. {
  4170. menu->addSeparator();
  4171. }
  4172. }
  4173. j++;
  4174. }
  4175. @i helpmenu.w
  4176. @i licensewindow.w
  4177. @ A layout can contain a number of different elements including a variety of
  4178. widget types and other layouts. This function is responsible for applying any
  4179. layout class to the widget currently being populated and processing children of
  4180. the {\tt <layout>} element to populate that layout. External stacks are used to
  4181. keep track of which widgets and layouts are currently being populated. The
  4182. {\tt type} attribute is used to determine what sort of layout should be created.
  4183. Currently, {\tt horizontal}, {\tt vertical}, {\tt grid}, and {\tt stack} types
  4184. are supported. The first two resolve to |QBoxLayout| layouts, {\tt grid}
  4185. resolves to a |QGridLayout|, and {\tt stack} resolves to a |QStackedLayout|.
  4186. @<Functions for scripting@>=
  4187. void addLayoutToWidget(QDomElement element, QStack<QWidget*> *widgetStack,
  4188. QStack<QLayout*> *layoutStack)
  4189. {
  4190. if(element.hasAttribute("type"))
  4191. {
  4192. @<Create and populate layout@>@;
  4193. QWidget *widget = widgetStack->top();
  4194. if(layout)
  4195. {
  4196. widget->setLayout(layout);
  4197. }
  4198. layoutStack->pop();
  4199. }
  4200. }
  4201. @ As there are multiple places where a {\tt <layout>} element is parsed with
  4202. slightly different semantics, the code for creating and populating the layout is
  4203. broken out so that code written to support additional layout types only needs to
  4204. be written once.
  4205. @<Create and populate layout@>=
  4206. QLayout *layout;
  4207. QString layoutType = element.attribute("type");
  4208. if(layoutType == "horizontal")
  4209. {
  4210. layout = new QHBoxLayout;
  4211. layoutStack->push(layout);
  4212. populateBoxLayout(element, widgetStack, layoutStack);
  4213. }
  4214. else if(layoutType == "vertical")
  4215. {
  4216. layout = new QVBoxLayout;
  4217. layoutStack->push(layout);
  4218. populateBoxLayout(element, widgetStack, layoutStack);
  4219. }
  4220. else if(layoutType == "grid")
  4221. {
  4222. layout = new QGridLayout;
  4223. layoutStack->push(layout);
  4224. populateGridLayout(element, widgetStack, layoutStack);
  4225. }
  4226. else if(layoutType == "stack")
  4227. {
  4228. layout = new QStackedLayout;
  4229. layoutStack->push(layout);
  4230. populateStackedLayout(element, widgetStack, layoutStack);
  4231. }
  4232. if(element.hasAttribute("id"))
  4233. {
  4234. layout->setObjectName(element.attribute("id"));
  4235. }
  4236. if(element.hasAttribute("spacing"))
  4237. {
  4238. layout->setSpacing(element.attribute("spacing").toInt());
  4239. }
  4240. if(element.hasAttribute("margin"))
  4241. {
  4242. int m = element.attribute("margin").toInt();
  4243. layout->setContentsMargins(m, m, m, m);
  4244. }
  4245. @ Stacked layouts are a bit different from the other types. A stacked layout has
  4246. an arbitrary number of {\tt <page>} children which are just a |QWidget| which
  4247. can have the same child elements as {\tt <widget>} elements elsewhere. Only the
  4248. first page will be visible initially, however it is possible to use script code
  4249. to set the currently visible page provided that an ID is set for the layout.
  4250. @<Functions for scripting@>=
  4251. void populateStackedLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4252. QStack<QLayout *> *layoutStack)
  4253. {
  4254. QDomNodeList children = element.childNodes();
  4255. QStackedLayout *layout = qobject_cast<QStackedLayout *>(layoutStack->top());
  4256. for(int i = 0; i < children.count(); i++)
  4257. {
  4258. QDomNode current;
  4259. QDomElement currentElement;
  4260. current = children.at(i);
  4261. if(current.isElement())
  4262. {
  4263. currentElement = current.toElement();
  4264. if(currentElement.tagName() == "page")
  4265. {
  4266. QWidget *widget = new QWidget;
  4267. layout->addWidget(widget);
  4268. widgetStack->push(widget);
  4269. currentElement.setAttribute("trcontext", "configuration");
  4270. populateWidget(currentElement, widgetStack, layoutStack);
  4271. widgetStack->pop();
  4272. }
  4273. }
  4274. }
  4275. }
  4276. @ Using a grid layout is a bit different from using a box layout. Child elements
  4277. with various attributes are required to take full advantage of this layout type.
  4278. All direct children of a grid layout element should be {\tt <row>} elements
  4279. which may have optional {\tt height} and {\tt stretch} attributes which apply to
  4280. that row.
  4281. @<Functions for scripting@>=
  4282. void populateGridLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4283. QStack<QLayout *> *layoutStack)
  4284. {
  4285. QDomNodeList children = element.childNodes();
  4286. int row = -1;
  4287. QGridLayout *layout = qobject_cast<QGridLayout *>(layoutStack->top());
  4288. for(int i = 0; i < children.count(); i++)
  4289. {
  4290. QDomNode current;
  4291. QDomElement currentElement;
  4292. current = children.at(i);
  4293. if(current.isElement())
  4294. {
  4295. currentElement = current.toElement();
  4296. if(currentElement.tagName() == "row")
  4297. {
  4298. row++;
  4299. if(currentElement.hasAttribute("height"))
  4300. {
  4301. layout->setRowMinimumHeight(row,
  4302. currentElement.attribute("height").toInt());
  4303. }
  4304. if(currentElement.hasAttribute("stretch"))
  4305. {
  4306. layout->setRowStretch(row,
  4307. currentElement.attribute("stretch").toInt());
  4308. }
  4309. @<Populate grid layout row@>@;
  4310. }
  4311. }
  4312. }
  4313. }
  4314. @ Each {\tt <row>} may have arbitrarily many {\tt <column>} children. A row with
  4315. nothing in it or that is entirely populated by spanning cells from previous rows
  4316. might have no children.
  4317. The {\tt <column>} element supports several optional attributes. The
  4318. {\tt column} attribute can be used to specify which column the element refers
  4319. to. Sibling {\tt <column>} elements will refer to columns farther right unless
  4320. a lower column number is specified. This does mean that it is possible to
  4321. specify the same column more than once, however actually doing so is not
  4322. recommended. The {\tt width} attribute specifies the minimum width of the
  4323. column. If multiple cells in a column specify this attribute, the last one takes
  4324. priority. Similarly, the {\tt stretch} attribute specifies the column stretch.
  4325. The {\tt rowspan} and {\tt colspan} attributes can be used for cells that span
  4326. more than one row or column. A value of |-1| can be used to have the cell span
  4327. to the last row or column in the layout.
  4328. Once the attributes of the cell are known, a |QHBoxLayout| is added to the
  4329. layout at the appropriate location in the grid and it is this layout which is
  4330. further populated by child elements. Anything that can be placed under a
  4331. {\tt <layout>} element with {\tt "horizontal"} or {\tt "vertical"} {\tt type}
  4332. attribute can be a child of a {\tt <column>} element in this context.
  4333. @<Populate grid layout row@>=
  4334. int column = -1;
  4335. QDomNodeList rowChildren = currentElement.childNodes();
  4336. for(int j = 0; j < rowChildren.count(); j++)
  4337. {
  4338. QDomNode columnNode;
  4339. QDomElement columnElement;
  4340. columnNode = rowChildren.at(j);
  4341. if(columnNode.isElement())
  4342. {
  4343. columnElement = columnNode.toElement();
  4344. if(columnElement.tagName() == "column")
  4345. {
  4346. column++;
  4347. if(columnElement.hasAttribute("column"))
  4348. {
  4349. column = columnElement.attribute("column").toInt();
  4350. }
  4351. if(columnElement.hasAttribute("width"))
  4352. {
  4353. layout->setColumnMinimumWidth(column,
  4354. columnElement.attribute("width").toInt());
  4355. }
  4356. if(columnElement.hasAttribute("stretch"))
  4357. {
  4358. layout->setColumnStretch(column,
  4359. columnElement.attribute("stretch").toInt());
  4360. }
  4361. int hspan = 1;
  4362. int vspan = 1;
  4363. if(columnElement.hasAttribute("rowspan"))
  4364. {
  4365. vspan = columnElement.attribute("rowspan").toInt();
  4366. }
  4367. if(columnElement.hasAttribute("colspan"))
  4368. {
  4369. hspan = columnElement.attribute("colspan").toInt();
  4370. }
  4371. QHBoxLayout *cell = new QHBoxLayout;
  4372. layout->addLayout(cell, row, column, vspan, hspan);
  4373. layoutStack->push(cell);
  4374. columnElement.setAttribute("trcontext", "configuration");
  4375. populateBoxLayout(columnElement, widgetStack, layoutStack);
  4376. layoutStack->pop();
  4377. }
  4378. }
  4379. }
  4380. @ Box layouts are populated by checking for child elements representing
  4381. supported widget types and layouts and adding these to the current layout.
  4382. @<Functions for scripting@>=
  4383. void populateBoxLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4384. QStack<QLayout *> *layoutStack)
  4385. {
  4386. QDomNodeList children = element.childNodes();
  4387. for(int i = 0; i < children.count(); i++)
  4388. {
  4389. QDomNode current;
  4390. QDomElement currentElement;
  4391. current = children.at(i);
  4392. if(current.isElement())
  4393. {
  4394. currentElement = current.toElement();
  4395. currentElement.setAttribute("trcontext", "configuration");
  4396. if(currentElement.tagName() == "button")
  4397. {
  4398. addButtonToLayout(currentElement, widgetStack, layoutStack);
  4399. }
  4400. else if(currentElement.tagName() == "calendar")
  4401. {
  4402. addCalendarToLayout(currentElement, widgetStack, layoutStack);
  4403. }
  4404. else if(currentElement.tagName() == "decoration")
  4405. {
  4406. addDecorationToLayout(currentElement, widgetStack,
  4407. layoutStack);
  4408. }
  4409. else if(currentElement.tagName() == "layout")
  4410. {
  4411. addLayoutToLayout(currentElement, widgetStack, layoutStack);
  4412. }
  4413. else if(currentElement.tagName() == "splitter")
  4414. {
  4415. addSplitterToLayout(currentElement, widgetStack, layoutStack);
  4416. }
  4417. else if(currentElement.tagName() == "label")
  4418. {
  4419. QBoxLayout *layout =
  4420. qobject_cast<QBoxLayout *>(layoutStack->top());
  4421. QLabel *label = new QLabel(QCoreApplication::translate(
  4422. "configuration",
  4423. currentElement.text().toUtf8().data()));
  4424. layout->addWidget(label);
  4425. }
  4426. else if(currentElement.tagName() == "lcdtemperature")
  4427. {
  4428. addTemperatureDisplayToLayout(currentElement, widgetStack,
  4429. layoutStack);
  4430. }
  4431. else if(currentElement.tagName() == "lcdtimer")
  4432. {
  4433. addTimerDisplayToLayout(currentElement, widgetStack,
  4434. layoutStack);
  4435. }
  4436. else if(currentElement.tagName() == "line")
  4437. {
  4438. addLineToLayout(currentElement, widgetStack, layoutStack);
  4439. }
  4440. else if(currentElement.tagName() == "report")
  4441. {
  4442. addReportToLayout(currentElement, widgetStack, layoutStack);
  4443. }
  4444. else if(currentElement.tagName() == "sqldrop")
  4445. {
  4446. addSqlDropToLayout(currentElement, widgetStack, layoutStack);
  4447. }
  4448. else if(currentElement.tagName() == "sqltablearray")
  4449. {
  4450. addSaltToLayout(currentElement, widgetStack, layoutStack);
  4451. }
  4452. else if(currentElement.tagName() == "sqlview")
  4453. {
  4454. addSqlQueryViewToLayout(currentElement, widgetStack,
  4455. layoutStack);
  4456. }
  4457. else if(currentElement.tagName() == "textarea")
  4458. {
  4459. addTextToLayout(currentElement, widgetStack, layoutStack);
  4460. }
  4461. else if(currentElement.tagName() == "spinbox")
  4462. {
  4463. addSpinBoxToLayout(currentElement, widgetStack, layoutStack);
  4464. }
  4465. else if(currentElement.tagName() == "formarray")
  4466. {
  4467. addFormArrayToLayout(currentElement, widgetStack, layoutStack);
  4468. }
  4469. else if(currentElement.tagName() =="hscale")
  4470. {
  4471. addScaleControlToLayout(currentElement, widgetStack,
  4472. layoutStack);
  4473. }
  4474. else if(currentElement.tagName() == "vscale")
  4475. {
  4476. addIntensityControlToLayout(currentElement, widgetStack,
  4477. layoutStack);
  4478. }
  4479. else if(currentElement.tagName() == "webview")
  4480. {
  4481. addWebViewToLayout(currentElement, widgetStack, layoutStack);
  4482. }
  4483. else if(currentElement.tagName() == "stretch")
  4484. {
  4485. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4486. layout->addStretch();
  4487. }
  4488. @<Additional box layout elements@>@;
  4489. }
  4490. }
  4491. }
  4492. @ Box layouts support adding additional layouts to the layout. The form of the
  4493. function is very similar to |addLayoutToWidget()|.
  4494. @<Functions for scripting@>=
  4495. void addLayoutToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4496. QStack<QLayout *> *layoutStack)
  4497. {
  4498. QLayout *targetLayout = layoutStack->pop();
  4499. QBoxLayout *boxLayout = qobject_cast<QBoxLayout *>(targetLayout);
  4500. if(element.hasAttribute("type"))
  4501. {
  4502. @<Create and populate layout@>@;
  4503. boxLayout->addLayout(layout);
  4504. layoutStack->pop();
  4505. }
  4506. layoutStack->push(targetLayout);
  4507. }
  4508. @ A splitter is similar to a layout in that it manages the size and position of
  4509. one or more widgets, however it is not a layout and therefore needs to be
  4510. handled separately.
  4511. @<Functions for scripting@>=
  4512. void addSplitterToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  4513. QStack<QLayout *> *layoutStack)
  4514. {
  4515. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4516. QSplitter *splitter = new(QSplitter);
  4517. layout->addWidget(splitter);
  4518. @<Set up splitter@>@;
  4519. }
  4520. @ As there are multiple places where a splitter element must be examined, the
  4521. common code is set aside.
  4522. @<Set up splitter@>=
  4523. QString orientation = element.attribute("type");
  4524. if(orientation == "horizontal")
  4525. {
  4526. splitter->setOrientation(Qt::Horizontal);
  4527. }
  4528. else if(orientation == "vertical")
  4529. {
  4530. splitter->setOrientation(Qt::Vertical);
  4531. }
  4532. QString id = element.attribute("id");
  4533. if(!id.isEmpty())
  4534. {
  4535. splitter->setObjectName(id);
  4536. }
  4537. if(element.hasChildNodes())
  4538. {
  4539. widgetStack->push(splitter);
  4540. populateSplitter(element, widgetStack, layoutStack);
  4541. widgetStack->pop();
  4542. }
  4543. @ When populating a splitter, it is important to note that only widgets can be
  4544. added. If a layout is needed, this can be handled by adding a |QWidget| and
  4545. applying the layout to that widget.
  4546. @<Functions for scripting@>=
  4547. void populateSplitter(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4548. QStack<QLayout *> *layoutStack)
  4549. {
  4550. QDomNodeList children = element.childNodes();
  4551. for(int i = 0; i < children.count(); i++)
  4552. {
  4553. QDomNode current;
  4554. QDomElement currentElement;
  4555. current = children.at(i);
  4556. if(current.isElement())
  4557. {
  4558. currentElement = current.toElement();
  4559. currentElement.setAttribute("trcontext", "configuration");
  4560. if(currentElement.tagName() == "decoration")
  4561. {
  4562. addDecorationToSplitter(currentElement, widgetStack,
  4563. layoutStack);
  4564. }
  4565. else if(currentElement.tagName() == "graph")
  4566. {
  4567. addGraphToSplitter(currentElement, widgetStack, layoutStack);
  4568. }
  4569. else if(currentElement.tagName() == "splitter")
  4570. {
  4571. addSplitterToSplitter(currentElement, widgetStack, layoutStack);
  4572. }
  4573. else if(currentElement.tagName() == "lcdtemperature")
  4574. {
  4575. addTemperatureDisplayToSplitter(currentElement, widgetStack,
  4576. layoutStack);
  4577. }
  4578. else if(currentElement.tagName() == "lcdtimer")
  4579. {
  4580. addTimerDisplayToSplitter(currentElement, widgetStack,
  4581. layoutStack);
  4582. }
  4583. else if(currentElement.tagName() == "measurementtable")
  4584. {
  4585. addZoomLogToSplitter(currentElement, widgetStack, layoutStack);
  4586. }
  4587. else if(currentElement.tagName() == "widget")
  4588. {
  4589. addWidgetToSplitter(currentElement, widgetStack, layoutStack);
  4590. }
  4591. }
  4592. }
  4593. }
  4594. @ Adding a splitter to a splitter is similar to adding it to a layout.
  4595. @<Functions for scripting@>=
  4596. void addSplitterToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4597. QStack<QLayout *> *layoutStack)
  4598. {
  4599. QSplitter *parent = qobject_cast<QSplitter *>(widgetStack->top());
  4600. QSplitter *splitter = new(QSplitter);
  4601. splitter->setParent(parent);
  4602. parent->addWidget(splitter);
  4603. @<Set up splitter@>@;
  4604. }
  4605. @ Temperature displays are useful to have in an application such as this. At
  4606. present, this code only supports the {\tt id} attribute. It may be useful in the
  4607. future to allow other attributes for changing default attributes of the
  4608. indicator rather than needing to pull the object from script code and set
  4609. changes there.
  4610. @<Functions for scripting@>=
  4611. void addTemperatureDisplayToSplitter(QDomElement element,@|
  4612. QStack<QWidget *> *widgetStack,
  4613. QStack<QLayout *> *)
  4614. {
  4615. TemperatureDisplay *display = new(TemperatureDisplay);
  4616. if(element.hasAttribute("id"))
  4617. {
  4618. display->setObjectName(element.attribute("id"));
  4619. }
  4620. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4621. splitter->addWidget(display);
  4622. }
  4623. void addTemperatureDisplayToLayout(QDomElement element,@|
  4624. QStack<QWidget *> *,
  4625. QStack<QLayout *> *layoutStack)
  4626. {
  4627. TemperatureDisplay *display = new(TemperatureDisplay);
  4628. if(element.hasAttribute("id"))
  4629. {
  4630. display->setObjectName(element.attribute("id"));
  4631. }
  4632. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4633. layout->addWidget(display);
  4634. }
  4635. @ Timer displays are similarly useful to have. The default format for a timer
  4636. display is {\tt hh:mm:ss}, but this can be changed through the {\tt format}
  4637. attribute of an {\tt <lcdtimer>} element.
  4638. @<Functions for scripting@>=
  4639. void addTimerDisplayToSplitter(QDomElement element,@|
  4640. QStack<QWidget *> *widgetStack,
  4641. QStack<QLayout *> *)
  4642. {
  4643. TimerDisplay *display = new(TimerDisplay);
  4644. if(element.hasAttribute("id"))
  4645. {
  4646. display->setObjectName(element.attribute("id"));
  4647. }
  4648. if(element.hasAttribute("format"))
  4649. {
  4650. display->setDisplayFormat(element.attribute("format"));
  4651. }
  4652. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4653. splitter->addWidget(display);
  4654. }
  4655. void addTimerDisplayToLayout(QDomElement element,@|
  4656. QStack<QWidget *> *,
  4657. QStack<QLayout *> *layoutStack)
  4658. {
  4659. TimerDisplay *display = new(TimerDisplay);
  4660. if(element.hasAttribute("id"))
  4661. {
  4662. display->setObjectName(element.attribute("id"));
  4663. }
  4664. if(element.hasAttribute("format"))
  4665. {
  4666. display->setDisplayFormat(element.attribute("format"));
  4667. }
  4668. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4669. layout->addWidget(display);
  4670. }
  4671. @ When multiple timer or temperature displays are required, it can be useful to
  4672. provide a label to indicate just what is being measured.
  4673. @<Functions for scripting@>=
  4674. void addDecorationToLayout(QDomElement element, QStack<QWidget *> *,@|
  4675. QStack<QLayout *> *layoutStack)
  4676. {
  4677. @<Set up decoration@>@;
  4678. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4679. layout->addWidget(decoration);
  4680. }
  4681. void addDecorationToSplitter(QDomElement element,
  4682. QStack<QWidget *> *widgetStack,
  4683. QStack<QLayout *> *)
  4684. {
  4685. @<Set up decoration@>@;
  4686. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4687. splitter->addWidget(decoration);
  4688. }
  4689. @ The decoration needs a label text, an orientation, and the widget to be
  4690. labeled.
  4691. @<Set up decoration@>=
  4692. QString labelText =
  4693. QCoreApplication::translate("configuration",
  4694. element.attribute("name").toUtf8().data());
  4695. Qt::Orientations@, orientation = Qt::Horizontal;
  4696. if(element.hasAttribute("type"))
  4697. {
  4698. if(element.attribute("type") == "horizontal")
  4699. {
  4700. orientation = Qt::Horizontal;
  4701. }
  4702. else if(element.attribute("type") == "vertical")
  4703. {
  4704. orientation = Qt::Vertical;
  4705. }
  4706. }
  4707. @<Find widget to decorate@>@;
  4708. WidgetDecorator *decoration = new WidgetDecorator(theWidget, labelText,
  4709. orientation);
  4710. if(element.hasAttribute("id"))
  4711. {
  4712. decoration->setObjectName(element.attribute("id"));
  4713. }
  4714. @ The widget to decorate should be found as a child of the {\tt <decoration>}
  4715. element.
  4716. @<Find widget to decorate@>=
  4717. QWidget *theWidget = NULL;
  4718. QDomNodeList children = element.childNodes();
  4719. for(int i = 0; i < children.count(); i++)
  4720. {
  4721. QDomNode item = children.at(i);
  4722. if(item.isElement())
  4723. {
  4724. QDomElement itemElement = item.toElement();
  4725. if(itemElement.tagName() == "lcdtemperature")
  4726. {
  4727. TemperatureDisplay *display = new TemperatureDisplay;
  4728. if(itemElement.hasAttribute("id"))
  4729. {
  4730. display->setObjectName(itemElement.attribute("id"));
  4731. }
  4732. theWidget = display;
  4733. }
  4734. else if(itemElement.tagName() == "lcdtimer")
  4735. {
  4736. TimerDisplay *display = new TimerDisplay;
  4737. if(itemElement.hasAttribute("id"))
  4738. {
  4739. display->setObjectName(itemElement.attribute("id"));
  4740. }
  4741. if(itemElement.hasAttribute("format"))
  4742. {
  4743. display->setDisplayFormat(itemElement.attribute("format"));
  4744. }
  4745. theWidget = display;
  4746. }
  4747. }
  4748. }
  4749. @ As splitters cannot contain layouts directly, there is a need to allow
  4750. otherwise empty widgets to be included in a splitter for cases where a splitter
  4751. should manage several widgets together as a group. A row of annotation buttons
  4752. is an example of such a layout.
  4753. @<Functions for scripting@>=
  4754. void addWidgetToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4755. QStack<QLayout *> *layoutStack)
  4756. {
  4757. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4758. QWidget *widget = new QWidget;
  4759. if(element.hasAttribute("id"))
  4760. {
  4761. widget->setObjectName(element.attribute("id"));
  4762. }
  4763. splitter->addWidget(widget);
  4764. if(element.hasChildNodes())
  4765. {
  4766. widgetStack->push(widget);
  4767. populateWidget(element, widgetStack, layoutStack);
  4768. widgetStack->pop();
  4769. }
  4770. }
  4771. void populateWidget(QDomElement element, QStack<QWidget *> *widgetStack,@|
  4772. QStack<QLayout *> *layoutStack)
  4773. {
  4774. QDomNodeList children = element.childNodes();
  4775. for(int i = 0; i < children.count(); i++)
  4776. {
  4777. QDomNode current;
  4778. QDomElement currentElement;
  4779. current = children.at(i);
  4780. if(current.isElement())
  4781. {
  4782. currentElement = current.toElement();
  4783. if(currentElement.tagName() == "layout")
  4784. {
  4785. currentElement.setAttribute("trcontext", "configuration");
  4786. addLayoutToWidget(currentElement, widgetStack, layoutStack);
  4787. }
  4788. }
  4789. }
  4790. }
  4791. @ There are two types of buttons that can be added to a layout. There are normal
  4792. push buttons and there are annotation buttons. Other button types may be added
  4793. in the future.
  4794. @<Functions for scripting@>=
  4795. void addButtonToLayout(QDomElement element, QStack<QWidget *> *,@|
  4796. QStack<QLayout *> *layoutStack)
  4797. {
  4798. QAbstractButton *button = NULL;
  4799. QString text =
  4800. QCoreApplication::translate("configuration",
  4801. element.attribute("name").toUtf8().data());
  4802. if(element.hasAttribute("type"))
  4803. {
  4804. QString type = element.attribute("type");
  4805. if(type == "annotation")
  4806. {
  4807. AnnotationButton *abutton = new AnnotationButton(text);
  4808. if(element.hasAttribute("annotation"))
  4809. {
  4810. abutton->setAnnotation(element.attribute("annotation"));
  4811. }
  4812. if(element.hasAttribute("series"))
  4813. {
  4814. abutton->setTemperatureColumn(element.attribute("series").
  4815. toInt());
  4816. }
  4817. if(element.hasAttribute("column"))
  4818. {
  4819. abutton->setAnnotationColumn(element.attribute("column").
  4820. toInt());
  4821. }
  4822. button = abutton;
  4823. }
  4824. else if(type == "check")
  4825. {
  4826. button = new QCheckBox(text);
  4827. }
  4828. else if(type == "push")
  4829. {
  4830. button = new QPushButton(text);
  4831. }
  4832. }
  4833. if(element.hasAttribute("id"))
  4834. {
  4835. button->setObjectName(element.attribute("id"));
  4836. }
  4837. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4838. layout->addWidget(button);
  4839. }
  4840. @ While annotation buttons are useful for many batch notes, a spin box is
  4841. sometimes a better input choice. There are several attributes that can be set on
  4842. a spin box. These include text to be included in the annotation before and after
  4843. the value of the spin box, the temperature and annotation columns, the range of
  4844. values available in the spin box, the precision of allowed values, and the
  4845. amount by which increment and decrement operations change the value.
  4846. @<Functions for scripting@>=
  4847. void addSpinBoxToLayout(QDomElement element, QStack<QWidget *> *,@|
  4848. QStack<QLayout *> *layoutStack)
  4849. {
  4850. AnnotationSpinBox *box = new AnnotationSpinBox("", "", NULL);
  4851. if(element.hasAttribute("pretext"))
  4852. {
  4853. box->setPretext(QCoreApplication::translate(
  4854. "configuration",
  4855. element.attribute("pretext").toUtf8().data()));
  4856. }
  4857. if(element.hasAttribute("posttext"))
  4858. {
  4859. box->setPosttext(QCoreApplication::translate(
  4860. "configuration",
  4861. element.attribute("posttext").toUtf8().data()));
  4862. }
  4863. if(element.hasAttribute("series"))
  4864. {
  4865. box->setTemperatureColumn(element.attribute("series").toInt());
  4866. }
  4867. if(element.hasAttribute("column"))
  4868. {
  4869. box->setAnnotationColumn(element.attribute("column").toInt());
  4870. }
  4871. if(element.hasAttribute("min"))
  4872. {
  4873. box->setMinimum(element.attribute("min").toDouble());
  4874. }
  4875. if(element.hasAttribute("max"))
  4876. {
  4877. box->setMaximum(element.attribute("max").toDouble());
  4878. }
  4879. if(element.hasAttribute("decimals"))
  4880. {
  4881. box->setDecimals(element.attribute("decimals").toInt());
  4882. }
  4883. if(element.hasAttribute("step"))
  4884. {
  4885. box->setSingleStep(element.attribute("step").toDouble());
  4886. }
  4887. if(element.hasAttribute("id"))
  4888. {
  4889. box->setObjectName(element.attribute("id"));
  4890. }
  4891. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  4892. layout->addWidget(box);
  4893. }
  4894. @ Previously, in order to change a |ZoomLog| from the default set of columns,
  4895. script code would need to alter the column set. While this works fine on a Mac,
  4896. this did not work very well under Windows. For the current version, I would like
  4897. to remove the need to deal with table columns from the host environment. The
  4898. first step for this is allowing column descriptions in XML. After this, I'@q'@>d like
  4899. to remove the default column set from the widget code and provide some better
  4900. functionality for dealing with additional data sets.
  4901. When creating the |ZoomLog| here, we check for {\tt <column>} child elements
  4902. which specify the names of the columns.
  4903. @<Functions for scripting@>=
  4904. void addZoomLogToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4905. QStack<QLayout *> *)
  4906. {
  4907. ZoomLog *widget = new ZoomLog;
  4908. if(element.hasAttribute("id"))
  4909. {
  4910. widget->setObjectName(element.attribute("id"));
  4911. }
  4912. if(element.hasChildNodes())
  4913. {
  4914. QDomNodeList children = element.childNodes();
  4915. int column = 0;
  4916. for(int i = 0; i < children.count(); i++)
  4917. {
  4918. QDomNode current;
  4919. QDomElement currentElement;
  4920. current = children.at(i);
  4921. if(current.isElement())
  4922. {
  4923. currentElement = current.toElement();
  4924. if(currentElement.tagName() == "column")
  4925. {
  4926. QString text =
  4927. QCoreApplication::translate(
  4928. "configuration",
  4929. currentElement.text().toUtf8().data());
  4930. widget->setHeaderData(column, text);
  4931. column++;
  4932. }
  4933. }
  4934. }
  4935. }
  4936. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4937. if(splitter)
  4938. {
  4939. splitter->addWidget(widget);
  4940. }
  4941. else
  4942. {
  4943. qDebug() << "Splitter not found at top of widget stack!";
  4944. }
  4945. }
  4946. @ The last of the widgets needed to duplicate the window provided in previous
  4947. versions of \pn{} is the |GraphView|.
  4948. @<Functions for scripting@>=
  4949. void addGraphToSplitter(QDomElement element, QStack<QWidget *> *widgetStack,
  4950. QStack<QLayout *> *)
  4951. {
  4952. GraphView *view = new GraphView;
  4953. if(element.hasAttribute("id"))
  4954. {
  4955. view->setObjectName(element.attribute("id"));
  4956. }
  4957. QSplitter *splitter = qobject_cast<QSplitter *>(widgetStack->top());
  4958. splitter->addWidget(view);
  4959. }
  4960. @ When interacting with a database, it can be useful to provide a combo box
  4961. populated by the results of a database query. One way to do this is through a
  4962. |SqlComboBox| widget.
  4963. @<Functions for scripting@>=
  4964. void addSqlDropToLayout(QDomElement element, QStack<QWidget *> *,@|
  4965. QStack<QLayout *> *layoutStack)
  4966. {
  4967. SqlComboBox *box = new SqlComboBox();
  4968. if(element.hasAttribute("data"))
  4969. {
  4970. box->setDataColumn(element.attribute("data").toInt());
  4971. }
  4972. if(element.hasAttribute("display"))
  4973. {
  4974. box->setDisplayColumn(element.attribute("display").toInt());
  4975. }
  4976. if(element.hasAttribute("showdata"))
  4977. {
  4978. if(element.attribute("showdata") == "true")
  4979. {
  4980. box->showData(true);
  4981. }
  4982. }
  4983. if(element.hasAttribute("editable"))
  4984. {
  4985. if(element.attribute("editable") == "true")
  4986. {
  4987. box->setEditable(true);
  4988. }
  4989. }
  4990. if(element.hasChildNodes())
  4991. {
  4992. QDomNodeList children = element.childNodes();
  4993. for(int i = 0; i < children.count(); i++)
  4994. {
  4995. QDomNode current;
  4996. QDomElement currentElement;
  4997. current = children.at(i);
  4998. if(current.isElement())
  4999. {
  5000. currentElement = current.toElement();
  5001. if(currentElement.tagName() == "null")
  5002. {
  5003. box->addNullOption();
  5004. }
  5005. else if(currentElement.tagName() == "query")
  5006. {
  5007. box->addSqlOptions(currentElement.text());
  5008. }
  5009. }
  5010. }
  5011. }
  5012. if(element.hasAttribute("id"))
  5013. {
  5014. box->setObjectName(element.attribute("id"));
  5015. }
  5016. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5017. layout->addWidget(box);
  5018. }
  5019. @ The next database aware widget that can be useful to have in \pn{} is a
  5020. {\bf S}QL {\bf A}rray {\bf L}iteral {\bf T}able. As might be apparent from the
  5021. name, this is a table view with an associated model and delegates appropriate
  5022. for creating ordered arrays to pass into a database. Each column represents an
  5023. array of values. The most common use of this is in cases where it is important
  5024. to produce multiple arrays of the same size in which each element of one array
  5025. is related to the element in the same position of another array. For example,
  5026. when roasting coffee there are times when some may want to add more than one
  5027. coffee to the roaster at a time. In order to correctly track the green coffee
  5028. inventory and so that the roasting log may have an accurate record of what is
  5029. really happening, insertions on the roasting log provide two arrays, one
  5030. representing all of the coffees being added to the roaster, the other the amount
  5031. of each of these coffees. The database can then use a trigger function to
  5032. examine these arrays and produce the necessary entries in the use table which in
  5033. turn update the record containing the amount of each green coffee currently in
  5034. stock.
  5035. While a generic |QTableView| is used here, there is a need to add functionality
  5036. specific to using this table with a |SaltModel| when obtaining this widget from
  5037. the host environment. In order to accomodate this, we add a dynamic property to
  5038. the view to identify the type of table in the absense of a unique class name.
  5039. @<Functions for scripting@>=
  5040. void addSaltToLayout(QDomElement element, QStack<QWidget *> *,@|
  5041. QStack<QLayout *> *layoutStack)
  5042. {
  5043. QTableView *view = new QTableView;
  5044. view->setProperty("tabletype", QVariant(QString("SaltTable")));
  5045. SaltModel *model = new SaltModel(element.childNodes().count());
  5046. if(element.hasAttribute("id"))
  5047. {
  5048. view->setObjectName(element.attribute("id"));
  5049. }
  5050. if(element.hasChildNodes())
  5051. {
  5052. QDomNodeList children = element.childNodes();
  5053. int currentColumn = 0;
  5054. for(int i = 0; i < children.count(); i++)
  5055. {
  5056. QDomNode current;
  5057. QDomElement currentElement;
  5058. current = children.at(i);
  5059. if(current.isElement())
  5060. {
  5061. currentElement = current.toElement();
  5062. if(currentElement.tagName() == "column")
  5063. {
  5064. if(currentElement.hasAttribute("name"))
  5065. {
  5066. model->setHeaderData(currentColumn,
  5067. Qt::Horizontal,
  5068. QCoreApplication::translate(
  5069. "configuration",
  5070. currentElement.attribute("name").toUtf8().data()));
  5071. }
  5072. if(currentElement.hasAttribute("delegate"))
  5073. {
  5074. @<Set column delegate from XML attribute@>@;
  5075. }
  5076. currentColumn++;
  5077. }
  5078. }
  5079. }
  5080. }
  5081. view->setModel(model);
  5082. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5083. layout->addWidget(view);
  5084. }
  5085. @ It is often desirable to restrict the allowed values in an entry to either a
  5086. set of specific values or to a particular type of value. Delegates can be set
  5087. on a column to enforce such restrictions.
  5088. @<Set column delegate from XML attribute@>=
  5089. if(currentElement.attribute("delegate") == "sql")
  5090. {
  5091. @<Assign column delegate from SQL@>@;
  5092. }
  5093. else if(currentElement.attribute("delegate") == "numeric")
  5094. {
  5095. @<Assign numeric column delegate@>@;
  5096. }
  5097. @ When using a |SaltModel|, there are times where the array values being
  5098. inserted are identification numbers representing some record that already exists
  5099. in the database. For example, the id number representing a green coffee in the
  5100. table of items. In such a case, it is beneficial to provide a delegate capable
  5101. of presenting a human readable list of choices.
  5102. @<Assign column delegate from SQL@>=
  5103. SqlComboBoxDelegate *delegate = new SqlComboBoxDelegate;
  5104. SqlComboBox *widget = new SqlComboBox();
  5105. if(currentElement.hasAttribute("nulltext"))
  5106. {
  5107. widget->setNullText(currentElement.attribute("nulltext"));
  5108. }
  5109. if(currentElement.hasAttribute("nulldata"))
  5110. {
  5111. widget->setNullData(QVariant(currentElement.attribute("nulldata")));
  5112. }
  5113. if(currentElement.hasAttribute("null"))
  5114. {
  5115. if(currentElement.attribute("null") == "true")
  5116. {
  5117. widget->addNullOption();
  5118. }
  5119. }
  5120. if(currentElement.hasAttribute("showdata"))
  5121. {
  5122. if(currentElement.attribute("showdata") == "true")
  5123. {
  5124. widget->showData(true);
  5125. }
  5126. }
  5127. if(currentElement.hasAttribute("data"))
  5128. {
  5129. widget->setDataColumn(currentElement.attribute("data").toInt());
  5130. }
  5131. if(currentElement.hasAttribute("display"))
  5132. {
  5133. widget->setDisplayColumn(currentElement.attribute("display").toInt());
  5134. }
  5135. widget->addSqlOptions(currentElement.text());
  5136. delegate->setWidget(widget);
  5137. view->setItemDelegateForColumn(currentColumn, delegate);
  5138. @ Another common use is allowing numeric values. At present this only
  5139. restricts input to numbers, however it may be useful to provide other options
  5140. such as restricting the range of allowed values in the future.
  5141. @<Assign numeric column delegate@>=
  5142. NumericDelegate *delegate = new NumericDelegate;
  5143. view->setItemDelegateForColumn(currentColumn, delegate);
  5144. @ The |NumericDelegate| will only set the display value to a number, but it
  5145. will perform mathematical calculations that are entered into the editor as
  5146. well. This allows a person to type something like $13.26+5.06$ with the result
  5147. of the expression ($18.32$) appearing in the table.
  5148. @<Class declarations@>=
  5149. class NumericDelegate : public QItemDelegate@/
  5150. {
  5151. @[Q_OBJECT@]@;
  5152. public:@/
  5153. NumericDelegate(QObject *parent = NULL);
  5154. QWidget *createEditor(QWidget *parent,
  5155. const QStyleOptionViewItem &option,@|
  5156. const QModelIndex &index) const;
  5157. void setEditorData(QWidget *editor, const QModelIndex &index) const;
  5158. void setModelData(QWidget *editor, QAbstractItemModel *model,@|
  5159. const QModelIndex &index) const;
  5160. void updateEditorGeometry(QWidget *editor,
  5161. const QStyleOptionViewItem &option,@|
  5162. const QModelIndex &index) const;
  5163. };
  5164. @ There is nothing special about the constructor.
  5165. @<NumericDelegate implementation@>=
  5166. NumericDelegate::NumericDelegate(QObject *parent) :
  5167. QItemDelegate(parent)
  5168. {
  5169. /* Nothing needs to be done here. */
  5170. }
  5171. @ Two roles are used by this delegate. The edit role should contain whatever
  5172. text has been entered in the editor while the display role contain the numeric
  5173. result of any expression that has been entered. Our editor only requires the
  5174. first of these.
  5175. @<NumericDelegate implementation@>=
  5176. void NumericDelegate::setEditorData(QWidget *editor,
  5177. const QModelIndex &index) const
  5178. {
  5179. QString value = index.model()->data(index, Qt::EditRole).toString();
  5180. QLineEdit *line = static_cast<QLineEdit*>(editor);
  5181. line->setText(value);
  5182. }
  5183. @ When editing is finished, the expression text must be saved back to the
  5184. model and the expression should be evaluated to set the display role. We make
  5185. use of the existing scripting engine to evaluate the expression, but only
  5186. preserve the result in the display role if the result of that expression is
  5187. numeric.
  5188. @<NumericDelegate implementation@>=
  5189. void NumericDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
  5190. const QModelIndex &index) const
  5191. {
  5192. QLineEdit *line = static_cast<QLineEdit*>(editor);
  5193. model->setData(index, line->text(), Qt::EditRole);
  5194. QScriptEngine *engine = AppInstance->engine;
  5195. engine->pushContext();
  5196. QString script = QString("Number(%1)").arg(line->text());
  5197. QScriptValue result = engine->evaluate(line->text());
  5198. if(result.isNumber())
  5199. {
  5200. model->setData(index, result.toVariant(), Qt::DisplayRole);
  5201. }
  5202. else
  5203. {
  5204. model->setData(index, QVariant(), Qt::DisplayRole);
  5205. }
  5206. engine->popContext();
  5207. }
  5208. @ There is nothing special about the line edit used for this.
  5209. @<NumericDelegate implementation@>=
  5210. QWidget* NumericDelegate::createEditor(QWidget *parent,
  5211. const QStyleOptionViewItem &,
  5212. const QModelIndex &) const
  5213. {
  5214. return (new QLineEdit(parent));
  5215. }
  5216. @ To ensure that the editor is displayed appropriately, we must pass the
  5217. geometry data to our editor.
  5218. @<NumericDelegate implementation@>=
  5219. void NumericDelegate::updateEditorGeometry(QWidget *editor,
  5220. const QStyleOptionViewItem &option,
  5221. const QModelIndex &) const
  5222. {
  5223. editor->setGeometry(option.rect);
  5224. }
  5225. @ The same general technique is useful for input to a |QLineEdit|, but there is
  5226. no model backing that widget to preserve multiple data roles. One way to get
  5227. this functionality without too much effort is to abuse |QValidator| to evaluate
  5228. expressions.
  5229. @<Class declarations@>=
  5230. class ScriptValidator : public QValidator
  5231. {
  5232. Q_OBJECT
  5233. public:
  5234. ScriptValidator(QValidator *validator, QObject *parent = NULL);
  5235. void fixup(QString &input) const;
  5236. QValidator::State validate(QString &input, int &pos) const;
  5237. private:
  5238. QValidator *v;
  5239. };
  5240. @ The key to this is in the |fixup()| method. Here we over-write input with the
  5241. result of the script evaluation.
  5242. @<ScriptValidator implementation@>=
  5243. void ScriptValidator::fixup(QString &input) const
  5244. {
  5245. QScriptEngine *engine = AppInstance->engine;
  5246. engine->pushContext();
  5247. input = engine->evaluate(input).toString();
  5248. engine->popContext();
  5249. }
  5250. @ This validator is intended to be used in conjunction with another one which
  5251. determines if the result of the expression is acceptable. In this case
  5252. |Invalid| is never returned.
  5253. @<ScriptValidator implementation@>=
  5254. QValidator::State ScriptValidator::validate(QString &input, int &pos) const
  5255. {
  5256. if(v)
  5257. {
  5258. if(v->validate(input, pos) == QValidator::Acceptable)
  5259. {
  5260. return QValidator::Acceptable;
  5261. }
  5262. }
  5263. return QValidator::Intermediate;
  5264. }
  5265. @ The constructor is trivial.
  5266. @<ScriptValidator implementation@>=
  5267. ScriptValidator::ScriptValidator(QValidator *validator, QObject *parent)
  5268. : QValidator(parent), v(validator)
  5269. {
  5270. /* Nothing needs to be done here. */
  5271. }
  5272. @ This is included in typica.cpp.
  5273. @<Class implementations@>=
  5274. @<ScriptValidator implementation@>
  5275. @ Line edits are useful when the user is expected to enter text without a
  5276. predetermined set of values.
  5277. Several attributes are supported on line edits. In addition to the usual
  5278. {\tt id} attribute, there is also a {\tt writable} attribute which, if
  5279. {\tt false}, can be used to create read only text areas which can only be edited
  5280. from script code. A {\tt validator} attribute allows entered text to be
  5281. restricted. This can take one of three values. If the value is {\tt "numeric"},
  5282. input is restricted to numeric values. If the value is {\tt "integer"}, input is
  5283. restricted to integer values. Finally, if the value is {\tt "expression"}, input
  5284. is restricted to text which matches a regular expression specified as the value
  5285. of the {\tt expression} attribute.
  5286. Note that when integer and numeric validators are specified, these are set for
  5287. a |ScriptValidator| to enable some basic expression evaluation.
  5288. @<Functions for scripting@>=
  5289. void addLineToLayout(QDomElement element, QStack<QWidget *> *,@|
  5290. QStack<QLayout *> *layoutStack)
  5291. {
  5292. QLineEdit *widget = new QLineEdit(element.text());
  5293. if(element.hasAttribute("id"))
  5294. {
  5295. widget->setObjectName(element.attribute("id"));
  5296. }
  5297. if(element.hasAttribute("writable"))
  5298. {
  5299. if(element.attribute("writable") == "false")
  5300. {
  5301. widget->setReadOnly(true);
  5302. }
  5303. }
  5304. if(element.hasAttribute("validator"))
  5305. {
  5306. if(element.attribute("validator") == "numeric")
  5307. {
  5308. widget->setValidator(new ScriptValidator(new QDoubleValidator));
  5309. }
  5310. else if(element.attribute("validator") == "integer")
  5311. {
  5312. widget->setValidator(new ScriptValidator(new QIntValidator));
  5313. }
  5314. else if(element.attribute("validator") == "expression" &&
  5315. element.hasAttribute("expression"))
  5316. {
  5317. widget->setValidator(new QRegExpValidator(
  5318. QRegExp(element.attribute("expression")),
  5319. NULL));
  5320. }
  5321. }
  5322. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5323. layout->addWidget(widget);
  5324. }
  5325. @ It is natural for certain database fields to enter potentially large amounts
  5326. of free form text, for example, notes and annotations.
  5327. @<Functions for scripting@>=
  5328. void addTextToLayout(QDomElement element, QStack<QWidget *> *,@|
  5329. QStack<QLayout *> *layoutStack)
  5330. {
  5331. QTextEdit *widget = new QTextEdit;
  5332. if(element.hasAttribute("id"))
  5333. {
  5334. widget->setObjectName(element.attribute("id"));
  5335. }
  5336. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5337. layout->addWidget(widget);
  5338. }
  5339. @ The common use of |SqlQueryView| calls for the possibility of changing the
  5340. query during use. As such, there is little reason to accept attributes other
  5341. than an id for obtaining the view in a script.
  5342. @<Functions for scripting@>=
  5343. void addSqlQueryViewToLayout(QDomElement element,
  5344. QStack<QWidget *> *,@|
  5345. QStack<QLayout *> *layoutStack)
  5346. {
  5347. SqlQueryView *view = new SqlQueryView;
  5348. if(element.hasAttribute("id"))
  5349. {
  5350. view->setObjectName(element.attribute("id"));
  5351. }
  5352. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5353. layout->addWidget(view);
  5354. }
  5355. @ When the user is expected to enter a date, it is appropriate to use a date
  5356. editor. This one provides a calendar.
  5357. @<Functions for scripting@>=
  5358. void addCalendarToLayout(QDomElement element, QStack<QWidget *> *,@|
  5359. QStack<QLayout *> *layoutStack)
  5360. {
  5361. QWidget *widget;
  5362. if(element.hasAttribute("time"))
  5363. {
  5364. if(element.attribute("time") == "true")
  5365. {
  5366. QDateTimeEdit *edit = new QDateTimeEdit;
  5367. edit->setDateTime(QDateTime::currentDateTime());
  5368. edit->setCalendarPopup(true);
  5369. edit->setDisplayFormat("yyyy-MM-dd hh:mm:ss");
  5370. widget = qobject_cast<QWidget *>(edit);
  5371. }
  5372. else
  5373. {
  5374. QDateEdit *edit = new QDateEdit;
  5375. edit->setDate(QDate::currentDate());
  5376. edit->setCalendarPopup(true);
  5377. edit->setDisplayFormat("yyyy-MM-dd");
  5378. widget = qobject_cast<QWidget *>(edit);
  5379. }
  5380. }
  5381. else
  5382. {
  5383. QDateEdit *edit = new QDateEdit;
  5384. edit->setDate(QDate::currentDate());
  5385. edit->setCalendarPopup(true);
  5386. edit->setDisplayFormat("yyyy-MM-dd");
  5387. widget = qobject_cast<QWidget *>(edit);
  5388. }
  5389. if(element.hasAttribute("id"))
  5390. {
  5391. widget->setObjectName(element.attribute("id"));
  5392. }
  5393. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  5394. layout->addWidget(widget);
  5395. }
  5396. @ Some additional properties are added to this object when it is retrieved by
  5397. the host environment.
  5398. @<Functions for scripting@>=
  5399. void setQDateEditProperties(QScriptValue value, QScriptEngine *engine)
  5400. {
  5401. setQDateTimeEditProperties(value, engine);
  5402. }
  5403. void setQDateTimeEditProperties(QScriptValue value, QScriptEngine *engine)
  5404. {
  5405. setQAbstractSpinBoxProperties(value, engine);
  5406. value.setProperty("setDate", engine->newFunction(QDateTimeEdit_setDate));
  5407. value.setProperty("day", engine->newFunction(QDateTimeEdit_day));
  5408. value.setProperty("month", engine->newFunction(QDateTimeEdit_month));
  5409. value.setProperty("year", engine->newFunction(QDateTimeEdit_year));
  5410. value.setProperty("setToCurrentTime",
  5411. engine->newFunction(QDateTimeEdit_setToCurrentTime));
  5412. }
  5413. @ Certain operations on a |QDateEdit| are easier with a few convenience
  5414. properties that bypass the need to use the built in |date| property. For
  5415. example, an editor that should be set to 1 January of the current year can
  5416. obtain the year and set the date without directly using a |QDate| object.
  5417. @<Functions for scripting@>=
  5418. QScriptValue QDateTimeEdit_setDate(QScriptContext *context, QScriptEngine *)
  5419. {
  5420. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  5421. if(context->argumentCount() == 3)
  5422. {
  5423. self->setDate(QDate(argument<int>(0, context),
  5424. argument<int>(1, context),
  5425. argument<int>(2, context)));
  5426. }
  5427. else
  5428. {
  5429. context->throwError("Incorrect number of arguments passed to "
  5430. "QDateTimeEdit::setDate(). This method takes three integer arguments "
  5431. "specifying the year, month, and day.");
  5432. }
  5433. return QScriptValue();
  5434. }
  5435. QScriptValue QDateTimeEdit_day(QScriptContext *context, QScriptEngine *)
  5436. {
  5437. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  5438. return QScriptValue(self->date().day());
  5439. }
  5440. QScriptValue QDateTimeEdit_month(QScriptContext *context, QScriptEngine *)
  5441. {
  5442. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  5443. return QScriptValue(self->date().month());
  5444. }
  5445. QScriptValue QDateTimeEdit_year(QScriptContext *context, QScriptEngine *)
  5446. {
  5447. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  5448. return QScriptValue(self->date().year());
  5449. }
  5450. QScriptValue QDateTimeEdit_setToCurrentTime(QScriptContext *context, QScriptEngine *)
  5451. {
  5452. QDateTimeEdit *self = getself<QDateTimeEdit *>(context);
  5453. self->setDateTime(QDateTime::currentDateTime());
  5454. return QScriptValue();
  5455. }
  5456. @ A few function prototypes are needed for this.
  5457. @<Function prototypes for scripting@>=
  5458. void setQDateEditProperties(QScriptValue value, QScriptEngine *engine);
  5459. void setQDateTimeEditProperties(QScriptValue value, QScriptEngine *engine);
  5460. QScriptValue QDateTimeEdit_setDate(QScriptContext *context,
  5461. QScriptEngine *engine);
  5462. QScriptValue QDateTimeEdit_day(QScriptContext *context, QScriptEngine *engine);
  5463. QScriptValue QDateTimeEdit_month(QScriptContext *context,
  5464. QScriptEngine *engine);
  5465. QScriptValue QDateTimeEdit_year(QScriptContext *context, QScriptEngine *engine);
  5466. QScriptValue QDateTimeEdit_setToCurrentTime(QScriptContext *context, QScriptEngine *engine);
  5467. @ In order to get to objects created from the XML description, it is necessary
  5468. to provide a function that can be called to retrieve children of a given widget.
  5469. When providing such an object to the script, it is necessary to determine the
  5470. type of that object and add the appropriate properties.
  5471. @<Function prototypes for scripting@>=
  5472. QScriptValue findChildObject(QScriptContext *context, QScriptEngine *engine);
  5473. @ This function must be made available to the scripting engine.
  5474. @<Set up the scripting engine@>=
  5475. engine->globalObject().setProperty("findChildObject",
  5476. engine->newFunction(findChildObject));
  5477. @ This function takes a script value representing some object which may have
  5478. been created from an XML description and a string containing the name of the
  5479. requested child element.
  5480. @<Functions for scripting@>=
  5481. QScriptValue findChildObject(QScriptContext *context, QScriptEngine *engine)
  5482. {
  5483. QObject *parent = argument<QObject *>(0, context);
  5484. QString name = argument<QString>(1, context);
  5485. QObject *object = parent->findChild<QObject *>(name);
  5486. QScriptValue value;
  5487. if(object)
  5488. {
  5489. value = engine->newQObject(object);
  5490. QString className = object->metaObject()->className();
  5491. @<Set object properties based on class name@>@;
  5492. }
  5493. return value;
  5494. }
  5495. @ Properties are added for a large number of class types.
  5496. @<Set object properties based on class name@>=
  5497. if(className == "TemperatureDisplay")
  5498. {
  5499. setTemperatureDisplayProperties(value, engine);
  5500. }
  5501. else if(className == "TimerDisplay")
  5502. {
  5503. setTimerDisplayProperties(value, engine);
  5504. }
  5505. else if(className == "QAction")
  5506. {
  5507. setQActionProperties(value, engine);
  5508. }
  5509. else if(className == "QBoxLayout")
  5510. {
  5511. setQBoxLayoutProperties(value, engine);
  5512. }
  5513. else if(className == "QDateEdit")
  5514. {
  5515. setQDateEditProperties(value, engine);
  5516. }
  5517. else if(className == "QDateTimeEdit")
  5518. {
  5519. setQDateTimeEditProperties(value, engine);
  5520. }
  5521. else if(className == "QFrame")
  5522. {
  5523. setQFrameProperties(value, engine);
  5524. }
  5525. else if(className == "QHBoxLayout")
  5526. {
  5527. setQBoxLayoutProperties(value, engine);
  5528. }
  5529. else if(className == "QLCDNumber")
  5530. {
  5531. setQLCDNumberProperties(value, engine);
  5532. }
  5533. else if(className == "QMenu")
  5534. {
  5535. setQMenuProperties(value, engine);
  5536. }
  5537. else if(className == "QMenuBar")
  5538. {
  5539. setQMenuBarProperties(value, engine);
  5540. }
  5541. else if(className == "QPushButton")
  5542. {
  5543. setQPushButtonProperties(value, engine);
  5544. }
  5545. else if(className == "QSplitter")
  5546. {
  5547. setQSplitterProperties(value, engine);
  5548. }
  5549. else if(className == "QTableView")
  5550. {
  5551. if(object->property("tabletype").isValid())
  5552. {
  5553. if(object->property("tabletype").toString() == "SaltTable")
  5554. {
  5555. setSaltTableProperties(value, engine);
  5556. }
  5557. }
  5558. }
  5559. else if(className == "QVBoxLayout")
  5560. {
  5561. setQBoxLayoutProperties(value, engine);
  5562. }
  5563. else if(className == "QWidget")
  5564. {
  5565. setQWidgetProperties(value, engine);
  5566. }
  5567. else if(className == "ScriptQMainWindow")
  5568. {
  5569. setQMainWindowProperties(value, engine);
  5570. }
  5571. else if(className == "SqlComboBox")
  5572. {
  5573. setSqlComboBoxProperties(value, engine);
  5574. }
  5575. else if(className == "SqlQueryView")
  5576. {
  5577. setSqlQueryViewProperties(value, engine);
  5578. }
  5579. else if(className == "ZoomLog")
  5580. {
  5581. setZoomLogProperties(value, engine);
  5582. }
  5583. else if(className == "QTextEdit")
  5584. {
  5585. setQTextEditProperties(value, engine);
  5586. }
  5587. else if(className == "QWebView")
  5588. {
  5589. setQWebViewProperties(value, engine);
  5590. }
  5591. else if(className == "QLineEdit")
  5592. {
  5593. setQLineEditProperties(value, engine);
  5594. }
  5595. else if(className == "QSvgWidget")
  5596. {
  5597. setQSvgWidgetProperties(value, engine);
  5598. }
  5599. @ In the list of classes, the SaltTable entry is for a class which does not
  5600. strictly exist on its own. It is, however, useful to provide some custom
  5601. properties when passing such an object to the host environment.
  5602. @<Function prototypes for scripting@>=
  5603. void setSaltTableProperties(QScriptValue value, QScriptEngine *engine);
  5604. QScriptValue SaltTable_bindableColumnArray(QScriptContext *context,
  5605. QScriptEngine *engine);
  5606. QScriptValue SaltTable_bindableQuotedColumnArray(QScriptContext *context,
  5607. QScriptEngine *engine);
  5608. QScriptValue SaltTable_columnSum(QScriptContext *context,
  5609. QScriptEngine *engine);
  5610. QScriptValue SaltTable_columnArray(QScriptContext *context,
  5611. QScriptEngine *engine);
  5612. QScriptValue SaltTable_data(QScriptContext *context, QScriptEngine *engine);
  5613. QScriptValue SaltTable_model(QScriptContext *context, QScriptEngine *engine);
  5614. QScriptValue SaltTable_quotedColumnArray(QScriptContext *context,
  5615. QScriptEngine *engine);
  5616. QScriptValue SaltTable_setData(QScriptContext *context, QScriptEngine *engine);
  5617. QScriptValue SaltTable_clear(QScriptContext *context, QScriptEngine *engine);
  5618. QScriptValue SaltTable_removeRow(QScriptContext *context, QScriptEngine *engine);
  5619. QScriptValue SaltTable_findData(QScriptContext *context, QScriptEngine *engine);
  5620. @ There are times when it is useful to obtain the sum of values in a column of
  5621. a SaltTable object. For example, when a column represents the weight of the
  5622. green coffee used in a batch, a sum of that column provides the total weight of
  5623. the batch which, when presented to the user, can be used to catch errors in
  5624. measuring batches or entering data.
  5625. @<Functions for scripting@>=
  5626. QScriptValue SaltTable_columnSum(QScriptContext *context, QScriptEngine *engine)
  5627. {
  5628. QTableView *self = getself<QTableView *>(context);
  5629. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5630. QString datum;
  5631. double total = 0.0;
  5632. int column = argument<int>(0, context);
  5633. int role = argument<int>(1, context);
  5634. for(int i = 0; i < model->rowCount(); i++)
  5635. {
  5636. datum = model->data(model->index(i, column), role).toString();
  5637. if(!datum.isEmpty())
  5638. {
  5639. total += datum.toDouble();
  5640. }
  5641. }
  5642. return QScriptValue(engine, total);
  5643. }
  5644. @ Another common use of the SaltTable is producing the text for an array literal
  5645. to pass into a SQL query. The |SaltModel| used by this table makes this simple.
  5646. There are four functions for this functionality for different use cases.
  5647. @<Functions for scripting@>=
  5648. QScriptValue SaltTable_columnArray(QScriptContext *context,
  5649. QScriptEngine *engine)
  5650. {
  5651. QTableView *self = getself<QTableView *>(context);
  5652. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5653. int column = argument<int>(0, context);
  5654. int role = argument<int>(1, context);
  5655. QString literal = model->arrayLiteral(column, role);
  5656. return QScriptValue(engine, literal);
  5657. }
  5658. QScriptValue SaltTable_quotedColumnArray(QScriptContext *context,
  5659. QScriptEngine *engine)
  5660. {
  5661. QTableView *self = getself<QTableView *>(context);
  5662. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5663. int column = argument<int>(0, context);
  5664. int role = argument<int>(1, context);
  5665. QString literal = model->quotedArrayLiteral(column, role);
  5666. return QScriptValue(engine, literal);
  5667. }
  5668. QScriptValue SaltTable_bindableColumnArray(QScriptContext *context,
  5669. QScriptEngine *engine)
  5670. {
  5671. QTableView *self = getself<QTableView *>(context);
  5672. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5673. int column = argument<int>(0, context);
  5674. int role = argument<int>(1, context);
  5675. QString literal = model->arrayLiteral(column, role);
  5676. literal.chop(1);
  5677. literal = literal.remove(0, 1);
  5678. return QScriptValue(engine, literal);
  5679. }
  5680. QScriptValue SaltTable_bindableQuotedColumnArray(QScriptContext *context,
  5681. QScriptEngine *engine)
  5682. {
  5683. QTableView *self = getself<QTableView *>(context);
  5684. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5685. int column = argument<int>(0, context);
  5686. int role = argument<int>(1, context);
  5687. QString literal = model->quotedArrayLiteral(column, role);
  5688. literal.chop(1);
  5689. literal = literal.remove(0, 1);
  5690. return QScriptValue(engine, literal);
  5691. }
  5692. @ In order to obtain signals related to changes in the model, we need a way to
  5693. get to the model from the host environment.
  5694. @<Functions for scripting@>=
  5695. QScriptValue SaltTable_model(QScriptContext *context, QScriptEngine *engine)
  5696. {
  5697. QTableView *self = getself<QTableView *>(context);
  5698. QScriptValue value = engine->newQObject(self->model());
  5699. return value;
  5700. }
  5701. @ While this table was originally intended strictly for user input, there are a
  5702. few use cases in which it is useful to allow scripts to set the values in the
  5703. table. This can be done with |setData|. This method takes four arguments: the
  5704. row and column of the table being set, the value to set, and the role of the
  5705. data being set.
  5706. @<Functions for scripting@>=
  5707. QScriptValue SaltTable_setData(QScriptContext *context, QScriptEngine *)
  5708. {
  5709. QTableView *self = getself<QTableView *>(context);
  5710. int row = argument<int>(0, context);
  5711. int column = argument<int>(1, context);
  5712. QVariant value = argument<QVariant>(2, context);
  5713. int role = argument<int>(3, context);
  5714. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5715. QModelIndex cell = model->index(row, column);
  5716. model->setData(cell, value, role);
  5717. self->update(cell);
  5718. return QScriptValue();
  5719. }
  5720. @ It is sometimes useful to obtain the data from a single cell of the table.
  5721. This can be done with the |data()| property.
  5722. @<Functions for scripting@>=
  5723. QScriptValue SaltTable_data(QScriptContext *context, QScriptEngine *engine)
  5724. {
  5725. QTableView *self = getself<QTableView *>(context);
  5726. int row = argument<int>(0, context);
  5727. int column = argument<int>(1, context);
  5728. int role = argument<int>(2, context);
  5729. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5730. QModelIndex cell = model->index(row, column);
  5731. QVariant value = model->data(cell, role);
  5732. QScriptValue retval = engine->newVariant(value);
  5733. retval.setProperty("value", QScriptValue(value.toString()));
  5734. return retval;
  5735. }
  5736. @ There are times when it is useful to clear the content of a table. This is
  5737. used, for example, in the green coffees table after changing the roasted coffee
  5738. item to eliminate excess rows in the case where the previously selected item
  5739. was a pre-roast blend.
  5740. @<Functions for scripting@>=
  5741. QScriptValue SaltTable_clear(QScriptContext *context, QScriptEngine *)
  5742. {
  5743. QTableView *self = getself<QTableView *>(context);
  5744. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5745. model->clear();
  5746. return QScriptValue();
  5747. }
  5748. @ It is sometimes useful to remove a row from a table. This is done in the new
  5749. batch window when the coffee for a row is set to a NULL item.
  5750. @<Functions for scripting@>=
  5751. QScriptValue SaltTable_removeRow(QScriptContext *context, QScriptEngine *engine)
  5752. {
  5753. QTableView *self = getself<QTableView *>(context);
  5754. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5755. int row = argument<int>(0, context);
  5756. return engine->newVariant(model->removeRow(row));
  5757. }
  5758. @ To remove the correct row, it is sometimes useful to query the table for
  5759. special values. This is done with the |findData()| method on the underlying
  5760. model.
  5761. @<Functions for scripting@>=
  5762. QScriptValue SaltTable_findData(QScriptContext *context, QScriptEngine *engine)
  5763. {
  5764. QTableView *self = getself<QTableView *>(context);
  5765. SaltModel *model = qobject_cast<SaltModel *>(self->model());
  5766. QVariant value = argument<QVariant>(0, context);
  5767. int column = argument<int>(1, context);
  5768. return engine->newVariant(model->findData(value, column));
  5769. }
  5770. @ These functions need to be added as properties of the table when it is passed
  5771. to the host environment.
  5772. @<Functions for scripting@>=
  5773. void setSaltTableProperties(QScriptValue value, QScriptEngine *engine)
  5774. {
  5775. setQWidgetProperties(value, engine);
  5776. value.setProperty("columnArray",
  5777. engine->newFunction(SaltTable_columnArray));
  5778. value.setProperty("quotedColumnArray",
  5779. engine->newFunction(SaltTable_quotedColumnArray));
  5780. value.setProperty("bindableColumnArray",
  5781. engine->newFunction(SaltTable_bindableColumnArray));
  5782. value.setProperty("bindableQuotedColumnArray",
  5783. engine->newFunction(SaltTable_bindableQuotedColumnArray));
  5784. value.setProperty("columnSum", engine->newFunction(SaltTable_columnSum));
  5785. value.setProperty("data", engine->newFunction(SaltTable_data));
  5786. value.setProperty("model", engine->newFunction(SaltTable_model));
  5787. value.setProperty("setData", engine->newFunction(SaltTable_setData));
  5788. value.setProperty("clear", engine->newFunction(SaltTable_clear));
  5789. value.setProperty("removeRow", engine->newFunction(SaltTable_removeRow));
  5790. value.setProperty("findData", engine->newFunction(SaltTable_findData));
  5791. }
  5792. @ The |SqlComboBox| is another class that is not constructed from scripts but is
  5793. useful to access from them. A property is added to obtain the current user data
  5794. from the widget.
  5795. @<Function prototypes for scripting@>=
  5796. void setSqlComboBoxProperties(QScriptValue value, QScriptEngine *engine);
  5797. void setQComboBoxProperties(QScriptValue value, QScriptEngine *engine);
  5798. QScriptValue QComboBox_currentData(QScriptContext *context,
  5799. QScriptEngine *engine);
  5800. QScriptValue QComboBox_addItem(QScriptContext *context, QScriptEngine *engine);
  5801. QScriptValue QComboBox_setModel(QScriptContext *context, QScriptEngine *engine);
  5802. QScriptValue QComboBox_findText(QScriptContext *context, QScriptEngine *engine);
  5803. QScriptValue QComboBox_findData(QScriptContext *context, QScriptEngine *engine);
  5804. @ These functions should seem familiar by now.
  5805. @<Functions for scripting@>=
  5806. void setSqlComboBoxProperties(QScriptValue value, QScriptEngine *engine)
  5807. {
  5808. setQComboBoxProperties(value, engine);
  5809. }
  5810. void setQComboBoxProperties(QScriptValue value, QScriptEngine *engine)
  5811. {
  5812. setQWidgetProperties(value, engine);
  5813. value.setProperty("currentData",
  5814. engine->newFunction(QComboBox_currentData));
  5815. value.setProperty("addItem", engine->newFunction(QComboBox_addItem));
  5816. value.setProperty("setModel", engine->newFunction(QComboBox_setModel));
  5817. value.setProperty("findText", engine->newFunction(QComboBox_findText));
  5818. value.setProperty("findData", engine->newFunction(QComboBox_findData));
  5819. }
  5820. QScriptValue QComboBox_currentData(QScriptContext *context,
  5821. QScriptEngine *engine)
  5822. {
  5823. QComboBox *self = getself<QComboBox *>(context);
  5824. return QScriptValue(engine,
  5825. self->itemData(self->currentIndex()).toString());
  5826. }
  5827. QScriptValue QComboBox_addItem(QScriptContext *context, QScriptEngine *)
  5828. {
  5829. QComboBox *self = getself<QComboBox *>(context);
  5830. self->addItem(argument<QString>(0, context));
  5831. return QScriptValue();
  5832. }
  5833. QScriptValue QComboBox_setModel(QScriptContext *context, QScriptEngine *)
  5834. {
  5835. QComboBox *self = getself<QComboBox *>(context);
  5836. self->setModel(argument<QAbstractItemModel *>(0, context));
  5837. return QScriptValue();
  5838. }
  5839. QScriptValue QComboBox_findText(QScriptContext *context, QScriptEngine *engine)
  5840. {
  5841. QComboBox *self = getself<QComboBox *>(context);
  5842. return QScriptValue(engine, self->findText(argument<QString>(0, context)));
  5843. }
  5844. QScriptValue QComboBox_findData(QScriptContext *context, QScriptEngine *engine)
  5845. {
  5846. QComboBox *self = getself<QComboBox *>(context);
  5847. return QScriptValue(engine, self->findData(argument<QVariant>(0, context)));
  5848. }
  5849. @i abouttypica.w
  5850. @** A representation of temperature measurements.
  5851. \noindent Most of the information in a roast log will be temperature
  5852. measurements. These measurements are made of two components: the measured
  5853. temperature and the time at which that measurement was taken.
  5854. Measurement times are represented as instances of |QTime|.
  5855. @i units.w
  5856. @ We will require the |units.h| header.
  5857. @<Header files to include@>=
  5858. #include "units.h"
  5859. @i measurement.w
  5860. @** The Main Measurement Pipeline.
  5861. \noindent Measurements are sent through \pn{} in a way similar to liquid moving
  5862. through a series of connected pipes. \pn{} is not something that you just dump
  5863. measurements on. It'@q'@>s not a big truck\nfnote{Senator Ted Stevens (R-Alaska) on
  5864. network neutrality, June 28, 2006\par
  5865. \hbox{\indent\pdfURL{http://media.publicknowledge.org/stevens-on-nn.mp3}%
  5866. {http://media.publicknowledge.org/stevens-on-nn.mp3}}}. In most cases the
  5867. connections between classes (represented by arrows in Figure \secno) are made
  5868. with Qt'@q'@>s signals and slots mechanism\nfnote{Qt 4.4.3: Signals and Slots\par
  5869. \hbox{\indent\pdfURL{http://doc.trolltech.com/4.4/signalsandslots.html}%
  5870. {http://doc.trolltech.com/4.4/signalsandslots.html}}}, but
  5871. these
  5872. connections can
  5873. also be made through direct function calls as is the case with the connection
  5874. between |ZoomLog| and |MeasurementModel|.
  5875. \medskip
  5876. \includegraphics{pipes}
  5877. \smallskip
  5878. \centerline{Figure \secno: Example Flow of Measurement objects in \pn}
  5879. \medskip
  5880. Please note that Figure \secno~is representative of a typical configuration. Now
  5881. that the flow of measurements through \pn{} is determined by a script specified
  5882. by the user, whatever pipeline is needed can be specified at run time.
  5883. @* The DAQ class.
  5884. \noindent The |DAQ| class represents a piece of hardware that allows the
  5885. computer to read measurements from one or more thermocouples. Presently this
  5886. class is only handles continuous sampling on devices from National Instruments.
  5887. It should be simple to modify this class to handle similar devices from other
  5888. vendors.
  5889. Each device is represented by a single instance of this class. Multiple channels
  5890. can be used on a device if the device supports it.
  5891. Two enumerations are declared in this class to be used as arguments to
  5892. |newChannel()|. The first is used to set the measurement unit for the channel.
  5893. As the measurements themselves do not carry this information, it is important to
  5894. keep track of this information. The values come from {\tt nidaqmxbase.h} and can
  5895. be used to select among Fahrenheit, Celsius, Kelvin, and Rankine. The
  5896. second enumeration, |ThermocoupleType|, should be used to specify the type of
  5897. thermocouple connected to the device. If this does not match reality, the
  5898. measurements will not be correct. The meanings of the values should be obvious
  5899. from the names.
  5900. \danger When this class was originally written the method of thread handling
  5901. used was considered appropriate. New functionality in |QThread| has made this
  5902. no longer the case. This class is currently planned for depreciation once a
  5903. replacement class hierarchy more suited to multiple hardware types is available
  5904. however if this is not ready soon it may be beneficial to rewrite this class to
  5905. conform to current best practices.\endanger
  5906. @<Class declarations@>=
  5907. class Channel;
  5908. class DAQImplementation;@/
  5909. class DAQ : public QObject@;@/
  5910. {@t\1@>@/
  5911. Q_OBJECT@/
  5912. Q_ENUMS(ThermocoupleType)@;@/
  5913. DAQImplementation *imp;@/
  5914. @t\4@>private slots@t\kern-3pt@>:@/
  5915. void threadFinished();
  5916. public:@;
  5917. DAQ(QString device, const QString &driver = QString("nidaqmxbase"));
  5918. ~DAQ();@/
  5919. Channel* newChannel(int units, int thermocouple);@/
  5920. @[Q_INVOKABLE@,@, void@]@, setClockRate(double Hz);@t\2\2@>@/
  5921. @[Q_INVOKABLE@,@, void@]@, start();@t\2\2@>@/
  5922. @[Q_INVOKABLE@,@, void@]@, stop();@t\2\2@>@/
  5923. enum ThermocoupleType@/
  5924. {
  5925. @!TypeJ = 10072,
  5926. @!TypeK = 10073,
  5927. @!TypeN = 10077,
  5928. @!TypeR = 10082,
  5929. @!TypeS = 10085,
  5930. @!TypeT = 10086,
  5931. @!TypeB = 10047,
  5932. @!TypeE = 10055
  5933. };@t\2@>@/
  5934. }@t\kern-3pt@>;
  5935. @ The |DAQ| class has as a private member an instance of a class called
  5936. |DAQImplementation|. The two classes together create and run a new thread of
  5937. execution. This thread spends most of its time blocking while waiting for a new
  5938. measurement to become available. When a new measurement is available, that
  5939. measurement is passed to the appropriate channel which in turn passes it to any
  5940. interested object.
  5941. @<Class declarations@>=
  5942. class DAQImplementation : public QThread@;@/
  5943. {@;
  5944. Q_OBJECT@;@/
  5945. public:@;
  5946. DAQImplementation(const QString &driverinfo);
  5947. ~DAQImplementation();
  5948. void run();
  5949. void measure();
  5950. @<Library function pointers@>@;
  5951. @<DAQImplementation member data@>@;
  5952. }@+@t\kern-3pt@>;
  5953. @ In order to solve some minor problems, NI-DAQmxBase is no longer linked at
  5954. compile time. Rather, this is now linked at runtime through a |QLibrary| object.
  5955. In order to use functions from this library, these functions must be stored in
  5956. function pointers. Fortunately, all of these functions can be expressed with the
  5957. same pointer type. Unfortunately, this way of doing things offers very little
  5958. debugging information in the event that something is not quite right.
  5959. @<Library function pointers@>=
  5960. typedef int (*daqfp)(...);
  5961. daqfp read;
  5962. daqfp errorInfo;
  5963. daqfp startTask;
  5964. daqfp createTask;
  5965. daqfp createChannel;
  5966. daqfp setClock;
  5967. daqfp stopTask;
  5968. daqfp clearTask;
  5969. daqfp resetDevice;
  5970. daqfp waitForMeasurement;
  5971. @ |DAQImplementation| also maintains information about the device and the
  5972. channels the measurements are sent to.
  5973. @<DAQImplementation member data@>=
  5974. bool useBase;
  5975. QString device;
  5976. QVector<Channel*> channelMap;
  5977. unsigned int handle;@/
  5978. int error;
  5979. int channels;
  5980. bool ready;
  5981. QLibrary driver;
  5982. QVector<Units::Unit> unitMap;
  5983. @ Most of the interesting work associated with the |DAQ| class is handled in
  5984. the |measure()| method of |DAQImplementation|. This function will block until a
  5985. measurement is available. Once |buffer| is filled by |DAQmxBaseReadAnalogF64()|
  5986. that function returns and new |Measurement| objects are created based on the
  5987. information in the buffer. These measurements are sent to |Channel| objects
  5988. tracked by |channelMap|.
  5989. Up until version 1.0.7 there was a bug in this code that would prevent the code
  5990. from working when more than one channel is requested. This has been corrected.
  5991. With version 1.0.9, time measurement is moved out of the loop, reducing the
  5992. number of calls in cases of more than 1 measurement and ensuring that all
  5993. simultaneously obtained measurements have the same time stamp.
  5994. @<DAQ Implementation@>=
  5995. void DAQImplementation::measure()@t\2@>@/
  5996. @t\4@>{@/
  5997. int samplesRead = 0;
  5998. double buffer[channels];
  5999. error = read((unsigned int)(handle), (signed long)(1), (double)(10.0),@|
  6000. (unsigned long)(0), buffer, (unsigned long)(channels),@|
  6001. &samplesRead, (signed long)(0));@/
  6002. if(error)@/
  6003. @t\1@>{@/
  6004. ready = false;@t\2@>@/
  6005. }
  6006. else@/
  6007. {
  6008. if(samplesRead)@/
  6009. {
  6010. QTime time = QTime::currentTime();@/
  6011. for(int i = 0; i < samplesRead; i++)@/
  6012. {
  6013. for(int j = 0; j < channels; j++)@/
  6014. {
  6015. double measuredValue = buffer[j+(i*channels)];
  6016. Measurement measure(measuredValue, time,
  6017. unitMap[j]);
  6018. channelMap[@,j]->input(measure);
  6019. }
  6020. }
  6021. }
  6022. }
  6023. @t\4@>}
  6024. @ It was noted that |DAQmxBaseReadAnalogF64()| blocks until it is able to fill
  6025. the |buffer| passed to it. To prevent this behavior from having adverse effects
  6026. on the rest of the program, measure is called from a loop running in its own
  6027. thread of execution. When the thread is started, it begins its execution from
  6028. the |run()| method of |DAQImplementation| which overrides the |run()| method of
  6029. |QThread|. Here the priority of the thread is set in an attempt to cut down on
  6030. the variation in time between recorded measurements.
  6031. The while loop is controlled by |ready| which is set to |false| when there is an
  6032. error in collecting a measurement or when the user wants to exit the program. It
  6033. could also be set to |false| when the |DAQ| is reconfigured.
  6034. @<DAQ Implementation@>=
  6035. void DAQImplementation::run()
  6036. {
  6037. setPriority(QThread::TimeCriticalPriority);
  6038. while(ready)
  6039. {
  6040. measure();
  6041. }
  6042. }
  6043. @ When this loop exits, |DAQImplementation| emits a finished signal to indicate
  6044. that the thread is no longer running. This could be due to perfectly normal
  6045. conditions, but there could also be a problem that the user must be informed of.
  6046. That signal is connected to a function that checks for error conditions and
  6047. reports them if needed.
  6048. @<DAQ Implementation@>=
  6049. void DAQ::threadFinished()
  6050. {
  6051. if(imp->error)
  6052. {
  6053. @<Display DAQ Error@>@;
  6054. }
  6055. }
  6056. @ Errors are displayed with a |QMessageBox|. NIDAQmxBase provides the message
  6057. strings for these errors, but this should probably change as these error strings
  6058. are generally completely unrelated to what the problem really is. For example,
  6059. ``Error: -1'' usually means that the device is not plugged in.
  6060. ``Error: -200170'' usually means that \pn{} or another program using the device
  6061. did not exit cleanly. A table of replacement warning messages should be added to
  6062. this program.
  6063. \bigskip
  6064. \settabs 5 \columns
  6065. \+Error Code & NIDAQmxBase Text & & Likely Cause\cr
  6066. \+\hrulefill & \hrulefill & \hrulefill & \hrulefill & \hrulefill & \hrulefill\cr
  6067. \+ -1 & Not implemented for this device & & The device is not plugged in.\cr
  6068. \+ & type. & \cr
  6069. \+ -200170 & Physical channel specified & & The program did not exit cleanly\cr
  6070. \+ & does not exist on this device. & & or another program is using the\cr
  6071. \+ & Refer to the documentation for & & device.\cr
  6072. \+ & channels available on this device.\cr
  6073. \+ -1073807194 & {\it{(No text)}} & & The device has been unplugged.\cr
  6074. \medskip
  6075. \centerline{Table \secno: Error codes, text, and what they really mean.}
  6076. \bigskip
  6077. There are two calls to |DAQmxBaseGetExtendedErrorInfo()| to obtain the error
  6078. messages. The first is used just to obtain the length of the error string. That
  6079. length is then used to allocate space for the error message. The second call
  6080. fills that string. This isn'@q'@>t allowed by ISO \CPLUSPLUS/\nfnote{%
  6081. \CPLUSPLUS/Dynamic Arrays (Crowl and Austern, May 16, 2008)\par
  6082. \hbox{\indent\pdfURL{%
  6083. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2648.html}{%
  6084. http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2648.html}}} but it
  6085. works with gcc. If this is a problem, the first call can be
  6086. removed and the buffer can be set large enough to fit the largest error message
  6087. that will be produced. Heap allocation could be used, but then we need to
  6088. remember to free the memory allocated to the string. Alternately, we can get rid
  6089. of \CEE/ style strings and write our own error messages. This would be the
  6090. preferred correction.
  6091. @<Display DAQ Error@>=
  6092. imp->ready = false;
  6093. QMessageBox warning;
  6094. warning.setStandardButtons(QMessageBox::Cancel);
  6095. warning.setIcon(QMessageBox::Warning);
  6096. warning.setText(QString(tr("Error: %1")).arg(imp->error));
  6097. unsigned long bytes = imp->errorInfo(NULL, 0);
  6098. char string[bytes];
  6099. imp->errorInfo(string, bytes);
  6100. warning.setInformativeText(QString(string));
  6101. warning.setWindowTitle(QString(PROGRAM_NAME));
  6102. warning.exec();
  6103. @ Starting the thread is almost as simple as ending it. The hardware is
  6104. instructed to begin taking measurements. If there is an error, this is handled.
  6105. Otherwise, the finished signal from |DAQImplementation| is connected to
  6106. |threadFinished()| and the new thread is started. The call to |imp->start()|
  6107. starts a new thread and passes control of that thread to |imp->run()|. The main
  6108. thread of execution returns without waiting for the new thread to do anything.
  6109. The call to |DAQmxBaseStartTask()| requires some time before the first
  6110. measurement is available. This is one of the reasons we start gathering
  6111. measurements before we really need them and continue to collect them until it is
  6112. time to exit the program.
  6113. @<DAQ Implementation@>=
  6114. void DAQ::start()
  6115. {
  6116. if(imp->ready)
  6117. {
  6118. imp->error = imp->startTask(imp->handle);
  6119. if(imp->error)
  6120. {
  6121. @<Display DAQ Error@>@;
  6122. }
  6123. else
  6124. {
  6125. connect(imp, SIGNAL(finished()), this, SLOT(threadFinished()));
  6126. imp->start();
  6127. }
  6128. }
  6129. }
  6130. void DAQ::stop()
  6131. {
  6132. if(imp->useBase)
  6133. {
  6134. imp->ready = @[false@];
  6135. imp->wait(ULONG_MAX);
  6136. imp->stopTask(imp->handle);
  6137. }
  6138. else
  6139. {
  6140. imp->ready = @[false@];
  6141. imp->error = imp->stopTask(imp->handle);
  6142. if(imp->error)
  6143. {
  6144. @<Display DAQ Error@>@;
  6145. }
  6146. imp->error = imp->clearTask(imp->handle);
  6147. if(imp->error)
  6148. {
  6149. @<Display DAQ Error@>@;
  6150. }
  6151. }
  6152. }
  6153. @ Setting up the DAQ begins by constructing a new |DAQ| object. The constructor
  6154. takes as its argument a string indicating the name of the device and will
  6155. typically be something like |"Dev1"|. This creates a new task which is required
  6156. for the setup that follows once a new |DAQ| is created.
  6157. @<DAQ Implementation@>=
  6158. DAQ::DAQ(QString device, const QString &driver) : imp(new DAQImplementation(driver))@/
  6159. @t\4\4@>{@/
  6160. imp->device = device;
  6161. imp->error = imp->createTask(device.toAscii().data(), &(imp->handle));
  6162. if(imp->error)@/
  6163. {
  6164. @<Display DAQ Error@>@;
  6165. }
  6166. else@/
  6167. @t\1@>{@/
  6168. imp->ready = true;@t\2@>@/
  6169. }@/
  6170. @t\4\4@>}
  6171. @ Once the |DAQ| is created, one or more channels can be added to that |DAQ|.
  6172. All |Channel| objects are created by the |DAQ| class and are managed by the
  6173. |DAQ| class. When a new channel is created, a pointer is passed back allowing
  6174. other classes to connect to the channel. Measurements cannot be read from the
  6175. |DAQ| directly. They must at some point pass through a channel.
  6176. @<DAQ Implementation@>=
  6177. Channel* DAQ::newChannel(int units, int thermocouple)
  6178. {
  6179. Channel *retval = new Channel();
  6180. imp->channelMap[imp->channels] = retval;
  6181. imp->unitMap[imp->channels] = (Units::Unit)units;
  6182. imp->channels++;
  6183. if(imp->ready)
  6184. {
  6185. if(imp->useBase)
  6186. {
  6187. imp->error = imp->createChannel(imp->handle,
  6188. QString("%1/ai%2").arg(imp->device).
  6189. arg(imp->channels - 1).
  6190. toAscii().data(),
  6191. "", (double)(-1.0), (double)(100.0),
  6192. (signed long)(units),
  6193. (signed long)(thermocouple),
  6194. (signed long)(10200), (double)(0),
  6195. "");
  6196. }
  6197. else
  6198. {
  6199. imp->error = imp->createChannel(imp->handle,
  6200. QString("%1/ai%2").arg(imp->device).
  6201. arg(imp->channels - 1).
  6202. toAscii().data(),
  6203. "", (double)(50.0), (double)(500.0),
  6204. (signed long)(units),
  6205. (signed long)(thermocouple),
  6206. (signed long)(10200), (double)(0),
  6207. "");
  6208. }
  6209. if(imp->error)
  6210. {
  6211. @<Display DAQ Error@>@;
  6212. }
  6213. }
  6214. return retval;
  6215. }
  6216. @ Once the channels are created, it is necessary to set the clock rate of the
  6217. DAQ. The clock rate chosen must be supported by the hardware. The clock rates
  6218. supported by the hardware may be altered by the number of channels in use.
  6219. The amount of time between measurements may vary slightly. A test configuration
  6220. at Wilson's Coffee \char'046~Tea used a 4Hz clock rate and provides measurements
  6221. every 251$\pm$1ms with 80\% of measurements spaced 251ms apart.
  6222. @<DAQ Implementation@>=
  6223. void DAQ::setClockRate(double Hz)
  6224. {
  6225. if(imp->ready)
  6226. {
  6227. imp->error = imp->setClock(imp->handle, "OnboardClock", Hz,
  6228. (signed long)(10280), (signed long)(10123),
  6229. (unsigned long long)(1));
  6230. if(imp->error)
  6231. {
  6232. @<Display DAQ Error@>@;
  6233. }
  6234. }
  6235. }
  6236. @ Before the program exits, the |DAQ| should be deleted. The destructor
  6237. instructs the measurement thread to stop, waits for it to finish, and resets the
  6238. device. If this is not done, an error would be issued the next time a program
  6239. attempted to use the device.
  6240. @<DAQ Implementation@>=
  6241. DAQ::~DAQ()@/
  6242. {
  6243. if(imp->useBase)
  6244. {
  6245. imp->resetDevice(imp->device.toAscii().data());
  6246. imp->clearTask(imp->handle);
  6247. }
  6248. else
  6249. {
  6250. if(imp->ready)
  6251. {
  6252. imp->ready = @[false@];
  6253. imp->wait(ULONG_MAX);
  6254. imp->stopTask(imp->handle);
  6255. imp->resetDevice(imp->device.toAscii().data());
  6256. imp->clearTask(imp->handle);
  6257. }
  6258. }
  6259. delete imp;
  6260. }
  6261. @ This just leaves the constructor and destructor for |DAQImplementation|. The
  6262. way the program is currently written, the number of channels available on the
  6263. |DAQ| is limited to 4. If a known larger number is required, the value here can
  6264. simply be set larger, however the best long term solution would be to modify
  6265. |newChannel()| to resize |channelMap| as more channels are added.
  6266. The constructor handles loading NI-DAQmxBase and preparing function pointers for
  6267. the symbols used in \pn{}.
  6268. @<DAQ Implementation@>=
  6269. DAQImplementation::DAQImplementation(const QString &driverinfo)
  6270. : QThread(NULL), channelMap(4), handle(0), error(0), channels(0), ready(false),
  6271. unitMap(4)@/
  6272. {
  6273. if(driverinfo == "nidaqmxbase")
  6274. {
  6275. useBase = true;
  6276. }
  6277. else
  6278. {
  6279. useBase = false;
  6280. }
  6281. if(useBase)
  6282. {
  6283. driver.setFileName("nidaqmxbase.framework/nidaqmxbase");
  6284. if(!driver.load())
  6285. {
  6286. driver.setFileName("nidaqmxbase");
  6287. if(!driver.load())
  6288. {
  6289. QMessageBox::critical(NULL, tr("Typica: Driver not found"),
  6290. tr("Failed to find nidaqmxbase. Please install it."));
  6291. QApplication::quit();
  6292. }
  6293. }
  6294. }
  6295. else
  6296. {
  6297. driver.setFileName("nicaiu");
  6298. if(!driver.load())
  6299. {
  6300. QMessageBox::critical(NULL, tr("Typica: Driver not found"),
  6301. tr("Failed to find nidaqmx. Please install it."));
  6302. QApplication::quit();
  6303. }
  6304. }
  6305. if(useBase)
  6306. {
  6307. if((createTask = (daqfp) driver.resolve("DAQmxBaseCreateTask")) == 0 || @|
  6308. (startTask = (daqfp) driver.resolve("DAQmxBaseStartTask")) == 0 || @|
  6309. (stopTask = (daqfp) driver.resolve("DAQmxBaseStopTask")) == 0 || @|
  6310. (clearTask = (daqfp) driver.resolve("DAQmxBaseClearTask")) == 0 || @|
  6311. (createChannel = (daqfp) driver.resolve("DAQmxBaseCreateAIThrmcplChan"))
  6312. == 0 || @|
  6313. (setClock = (daqfp) driver.resolve("DAQmxBaseCfgSampClkTiming")) ==
  6314. 0 || @|
  6315. (read = (daqfp) driver.resolve("DAQmxBaseReadAnalogF64")) == 0 || @|
  6316. (errorInfo = (daqfp) driver.resolve("DAQmxBaseGetExtendedErrorInfo")) ==
  6317. 0 || @|
  6318. (resetDevice = (daqfp) driver.resolve("DAQmxBaseResetDevice")) == 0)@/
  6319. {
  6320. waitForMeasurement = NULL;
  6321. QMessageBox::critical(NULL, tr("Typica: Link error"),
  6322. tr("Failed to link a required symbol in NI-DAQmxBase."));
  6323. QApplication::quit();
  6324. }
  6325. }
  6326. else
  6327. {
  6328. if((createTask = (daqfp)driver.resolve("DAQmxCreateTask")) == 0 || @|
  6329. (startTask = (daqfp)driver.resolve("DAQmxStartTask")) == 0 || @|
  6330. (stopTask = (daqfp)driver.resolve("DAQmxStopTask")) == 0 || @|
  6331. (clearTask = (daqfp)driver.resolve("DAQmxClearTask")) == 0 || @|
  6332. (createChannel = (daqfp)driver.resolve("DAQmxCreateAIThrmcplChan"))
  6333. == 0 || @|
  6334. (setClock = (daqfp)driver.resolve("DAQmxCfgSampClkTiming")) == 0 || @|
  6335. (read = (daqfp)driver.resolve("DAQmxReadAnalogF64")) == 0 || @|
  6336. (errorInfo = (daqfp)driver.resolve("DAQmxGetExtendedErrorInfo")) ==
  6337. 0 || @|
  6338. (resetDevice = (daqfp)driver.resolve("DAQmxResetDevice")) == 0 ||
  6339. (waitForMeasurement = (daqfp)driver.resolve("DAQmxWaitUntilTaskDone")) == 0)
  6340. {
  6341. QMessageBox::critical(NULL, tr("Typica: Link error"),
  6342. tr("Failed to link a required symbol in NI-DAQmx."));
  6343. QApplication::quit();
  6344. }
  6345. }
  6346. }
  6347. DAQImplementation::~DAQImplementation()
  6348. {
  6349. driver.unload();
  6350. }
  6351. @ When exposing the |DAQ| class to the scripting engine, we need to provide a
  6352. constructor that can be called from a script and we need a way to call
  6353. |DAQ::newChannel()|. Other methods that are useful when called from a script are
  6354. made available automatically with the |Q_INVOKABLE| macro, however this does not
  6355. work for methods such as |newChannel()| which return a pointer to a |Channel|
  6356. object.
  6357. @<Function prototypes for scripting@>=
  6358. QScriptValue constructDAQ(QScriptContext *context, QScriptEngine *engine);
  6359. QScriptValue DAQ_newChannel(QScriptContext *context, QScriptEngine *engine);
  6360. void setDAQProperties(QScriptValue value, QScriptEngine *engine);
  6361. @ These functions and the values from |Units::Unit| must be made available to
  6362. the host environment. The latter because this was widely used in configurations
  6363. before this enumeration was removed from the |DAQ| class. As these properties
  6364. must be available without an instance, the properties must be added here.
  6365. @<Set up the scripting engine@>=
  6366. constructor = engine->newFunction(constructDAQ);
  6367. value = engine->newQMetaObject(&DAQ::staticMetaObject, constructor);
  6368. value.setProperty("Fahrenheit", Units::Fahrenheit);
  6369. value.setProperty("Celsius", Units::Celsius);
  6370. value.setProperty("Kelvin", Units::Kelvin);
  6371. value.setProperty("Rankine", Units::Rankine);
  6372. engine->globalObject().setProperty("DAQ", value);
  6373. @ When creating a new |DAQ|, we make sure that it is owned by the script engine.
  6374. This is necessary to ensure that the destructor is called before \pn{} exits.
  6375. Just as the constructor requires an argument that specifies the device name, the
  6376. constructor available from a script also requires this argument.
  6377. @<Functions for scripting@>=
  6378. QScriptValue constructDAQ(QScriptContext *context, QScriptEngine *engine)
  6379. {
  6380. QScriptValue object;
  6381. if(context->argumentCount() == 1)
  6382. {
  6383. object = engine->newQObject(new DAQ(argument<QString>(0, context)),
  6384. QScriptEngine::ScriptOwnership);
  6385. setDAQProperties(object, engine);
  6386. }
  6387. else if(context->argumentCount() == 2)
  6388. {
  6389. object = engine->newQObject(new DAQ(argument<QString>(0, context),
  6390. argument<QString>(1, context)),
  6391. QScriptEngine::ScriptOwnership);
  6392. setDAQProperties(object, engine);
  6393. }
  6394. else
  6395. {
  6396. context->throwError("Incorrect number of arguments passed to DAQ"@|
  6397. "constructor. The DAQ constructor takes one"@|
  6398. "string as an argument specifying a device name."@|
  6399. "Example: Dev1");
  6400. }
  6401. return object;
  6402. }
  6403. @ As |DAQ| inherits |QObject|, we add the |newChannel()| property after adding
  6404. any |QObject| properties.
  6405. @<Functions for scripting@>=
  6406. void setDAQProperties(QScriptValue value, QScriptEngine *engine)
  6407. {
  6408. setQObjectProperties(value, engine);
  6409. value.setProperty("newChannel", engine->newFunction(DAQ_newChannel));
  6410. }
  6411. @ The |newChannel()| method method also requires that two arguments are provided
  6412. by the script.
  6413. @<Functions for scripting@>=
  6414. QScriptValue DAQ_newChannel(QScriptContext *context, QScriptEngine *engine)
  6415. {
  6416. DAQ *self = getself<@[DAQ *@]>(context);
  6417. QScriptValue object;
  6418. if(self)
  6419. {
  6420. object =
  6421. engine->newQObject(self->newChannel(argument<int>(0, context),@|
  6422. argument<int>(1, context)));
  6423. setChannelProperties(object, engine);
  6424. }
  6425. return object;
  6426. }
  6427. @ Sometimes it can be useful to test other parts of the program (for example,
  6428. when developing new scripts) when the DAQ hardware is not available. In these
  6429. cases, it is possible to temporarily use the |FakeDAQ| class. This class mimics
  6430. the |DAQ| class, but just makes up the measurements sent to the rest of the
  6431. program.
  6432. @<Class declarations@>=
  6433. class FakeDAQImplementation : public QThread@/
  6434. {@/
  6435. Q_OBJECT@;
  6436. public:@/
  6437. FakeDAQImplementation();
  6438. ~FakeDAQImplementation();
  6439. void run();
  6440. void measure();
  6441. QVector<Channel *> channelMap;
  6442. int channels;
  6443. bool ready;
  6444. double clockRate;
  6445. };@/
  6446. class FakeDAQ : public QObject@/
  6447. {@/
  6448. Q_OBJECT@;
  6449. FakeDAQImplementation *imp;
  6450. public:@/
  6451. FakeDAQ(QString device);
  6452. ~FakeDAQ();
  6453. Channel *newChannel(int units, int thermocouple);@/
  6454. @[Q_INVOKABLE@,@, void@]@, setClockRate(double Hz);@t\2\2@>@/
  6455. @[Q_INVOKABLE@,@, void@]@, start();@t\2\2@>@/
  6456. };
  6457. @ Just as in the |DAQ| class, most of the interesting stuff happens in
  6458. |measure()|. For each invokation of the method, we sleep for some amount of time
  6459. based on the clock rate then create a |Measurement| object at random for each
  6460. |Channel| that has been created.
  6461. @<FakeDAQ Implementation@>=
  6462. void FakeDAQImplementation::measure()
  6463. {
  6464. msleep((int)(1000/clockRate));
  6465. QTime time = QTime::currentTime();
  6466. for(int i = 0; i < channels; i++)
  6467. {
  6468. Measurement measure(qrand() % 500, time);
  6469. channelMap[i]->input(measure);
  6470. }
  6471. }
  6472. @ To call |measure|, we need to flesh out the rest of |FakeDAQImplementation|.
  6473. @<FakeDAQ Implementation@>=
  6474. void FakeDAQImplementation::run()
  6475. {
  6476. setPriority(QThread::TimeCriticalPriority);
  6477. while(ready)
  6478. {
  6479. measure();
  6480. }
  6481. }
  6482. FakeDAQImplementation::FakeDAQImplementation() : QThread(NULL), channelMap(4),
  6483. channels(0), ready(false), clockRate(1)@/
  6484. {
  6485. /* Nothing has to be done here. */
  6486. }
  6487. FakeDAQImplementation::~FakeDAQImplementation()
  6488. {
  6489. /* Nothing has to be done here. */
  6490. }
  6491. @ Next we need an implementation for the |FakeDAQ| class. This is simplified by
  6492. the fact that we are just using a random number generator to generate
  6493. measurements rather than special hardware for obtaining measurements.
  6494. @<FakeDAQ Implementation@>=
  6495. void FakeDAQ::start()
  6496. {
  6497. if(imp->ready)
  6498. {
  6499. imp->start();
  6500. }
  6501. }@#
  6502. FakeDAQ::FakeDAQ(QString) : imp(new FakeDAQImplementation())@t\2\2@>@/
  6503. {@t\1@>@/
  6504. imp->ready = true;@t\2@>@/
  6505. }@#
  6506. Channel* FakeDAQ::newChannel(int, int)
  6507. {
  6508. Channel *retval;
  6509. if(imp->ready)
  6510. {
  6511. retval = new Channel();
  6512. imp->channelMap[imp->channels] = retval;
  6513. imp->channels++;
  6514. }
  6515. else
  6516. {
  6517. return NULL;
  6518. }
  6519. return retval;
  6520. }
  6521. void FakeDAQ::setClockRate(double Hz)
  6522. {
  6523. if(imp->ready)
  6524. {
  6525. imp->clockRate = Hz;
  6526. }
  6527. }@#
  6528. FakeDAQ::~FakeDAQ()@t\2\2@>@/
  6529. {@t\1@>@/
  6530. imp->ready = false;
  6531. imp->wait(ULONG_MAX);
  6532. delete imp;@t\2@>@/
  6533. }
  6534. @ As the entire purpose of the |FakeDAQ| class is for testing purposes from
  6535. within the scripting engine, we need to make it available to the scripting
  6536. engine. This is done in a manner very similar to how the |DAQ| class is handled.
  6537. @<Function prototypes for scripting@>=
  6538. QScriptValue constructFakeDAQ(QScriptContext *context, QScriptEngine *engine);
  6539. QScriptValue FakeDAQ_newChannel(QScriptContext *context, QScriptEngine *engine);
  6540. void setFakeDAQProperties(QScriptValue value, QScriptEngine *engine);
  6541. @ The scripting engine is informed of the constructor.
  6542. @<Set up the scripting engine@>=
  6543. constructor = engine->newFunction(constructFakeDAQ);
  6544. value = engine->newQMetaObject(&FakeDAQ::staticMetaObject, constructor);
  6545. engine->globalObject().setProperty("FakeDAQ", value);
  6546. @ The constructor sets a property to allow calling |newChannel()| on a |FakeDAQ|
  6547. created from a script.
  6548. @<Functions for scripting@>=
  6549. QScriptValue constructFakeDAQ(QScriptContext *context,
  6550. QScriptEngine *engine)
  6551. {
  6552. QScriptValue object;
  6553. if(context->argumentCount() == 1)
  6554. {
  6555. object =
  6556. engine->newQObject(new FakeDAQ(argument<QString>(0, context)),
  6557. QScriptEngine::ScriptOwnership);
  6558. setFakeDAQProperties(object, engine);
  6559. }
  6560. else
  6561. {
  6562. context->throwError("Incorrect number of arguments passed to DAQ"@|
  6563. "constructor. The DAQ constructor takes one"@|
  6564. "string as an argument specifying a device name."@|
  6565. "Example: Dev1");
  6566. }
  6567. return object;
  6568. }
  6569. void setFakeDAQProperties(QScriptValue value, QScriptEngine *engine)
  6570. {
  6571. setQObjectProperties(value, engine);
  6572. value.setProperty("newChannel", engine->newFunction(FakeDAQ_newChannel));
  6573. }
  6574. QScriptValue FakeDAQ_newChannel(QScriptContext *context, QScriptEngine *engine)
  6575. {
  6576. FakeDAQ *self = getself<@[FakeDAQ *@]>(context);
  6577. QScriptValue object;
  6578. if(self)
  6579. {
  6580. object =
  6581. engine->newQObject(self->newChannel(argument<int>(0, context),@|
  6582. argument<int>(1, context)));
  6583. setChannelProperties(object, engine);
  6584. }
  6585. return object;
  6586. }
  6587. @* The Channel class.
  6588. \noindent |Channel| is a simple class. It is a subclass of |QObject| so it can
  6589. use Qt'@q'@>s signals and slots mechanism. Any object that is interested in
  6590. measurements from a channel can connect to the |newData| signal the channel
  6591. emits. Any number of objects can make this connection and each will receive a
  6592. copy of the measurement.
  6593. |Channel| objects should only be created by the |DAQ| class.
  6594. @<Class declarations@>=
  6595. class Channel : public QObject@;@/
  6596. {@t\1@>@/
  6597. Q_OBJECT@/
  6598. public:@;
  6599. Channel();
  6600. ~Channel();@/
  6601. @t\4@>public slots@t\kern-3pt@>:@;
  6602. void input(Measurement measurement);@/
  6603. signals:@;
  6604. void newData(Measurement);@t\2@>@/
  6605. };
  6606. @ The implementation of this class is trivial.
  6607. @<Channel Implementation@>=
  6608. Channel::Channel() : QObject(NULL)@/
  6609. {
  6610. /* Nothing has to be done here. */
  6611. }
  6612. Channel::~Channel()
  6613. {
  6614. /* Nothing has to be done here. */
  6615. }
  6616. void Channel::input(Measurement measurement)
  6617. {
  6618. emit newData(measurement);
  6619. }
  6620. @ A function is provided for use when a channel is created by a DAQ from a
  6621. script.
  6622. @<Function prototypes for scripting@>=
  6623. void setChannelProperties(QScriptValue value, QScriptEngine *engine);
  6624. @ The implementation is trivial.
  6625. @<Functions for scripting@>=
  6626. void setChannelProperties(QScriptValue value, QScriptEngine *engine)
  6627. {
  6628. setQObjectProperties(value, engine);
  6629. }
  6630. @* Calibration and Unit Conversion.
  6631. \noindent One of the planned features for \pn{} is support for hardware that
  6632. collects non-temperature measurements. This is frequently handled with analog
  6633. voltage signals which are proportional to some range in a meaningful unit. Some
  6634. hardware also requires calibration in software. In many cases both of these can
  6635. be handled at the same time with a single mapping in the form:
  6636. $$f(x) = L_1 + (x - L_2){U_1 - L_1\over{U_2 - L_2}}$$
  6637. \noindent where $L_1$ is the logical lower bound, $L_2$ is the measured lower
  6638. bound, $U_1$ is the logical upper bound, $U_2$ is the measured upper bound, and
  6639. $x$ is the value we wish to map from the range $\lbrack L_2, U_2 \rbrack$ to
  6640. the range $\lbrack L_1, U_1 \rbrack$.
  6641. Some use cases require a closed range but others require that this constraint
  6642. is loosened to allow extrapolation. Both are provided by this class.
  6643. Starting in \pn{} 1.6 this class has both the |measurement| and the
  6644. |newData| signals. This allows a |LinearCalibrator| to be treated like a
  6645. |Channel| when used with a |DataqSdkDevice|.
  6646. @<Class declarations@>=
  6647. class LinearCalibrator : public QObject@/
  6648. {@/
  6649. @[Q_OBJECT@]@;
  6650. @[Q_PROPERTY(double measuredLower READ measuredLower
  6651. WRITE setMeasuredLower)@]@;
  6652. @[Q_PROPERTY(double measuredUpper READ measuredUpper
  6653. WRITE setMeasuredUpper)@]@;
  6654. @[Q_PROPERTY(double mappedLower READ mappedLower WRITE setMappedLower)@]@;
  6655. @[Q_PROPERTY(double mappedUpper READ mappedUpper WRITE setMappedUpper)@]@;
  6656. @[Q_PROPERTY(bool closedRange READ isClosedRange WRITE setClosedRange)@]@;
  6657. @[Q_PROPERTY(double sensitivity READ sensitivity WRITE setSensitivity)@]@;
  6658. public:@/
  6659. LinearCalibrator(QObject *parent = NULL);
  6660. double measuredLower();
  6661. double measuredUpper();
  6662. double mappedLower();
  6663. double mappedUpper();
  6664. bool isClosedRange();
  6665. double sensitivity();
  6666. @t\4@>@[public slots@t\kern-3pt@>:@]@;
  6667. void setMeasuredLower(double lower);
  6668. void setMeasuredUpper(double upper);
  6669. void setMappedLower(double lower);
  6670. void setMappedUpper(double upper);
  6671. void setClosedRange(bool closed);
  6672. void setSensitivity(double sensitivity);
  6673. Measurement newMeasurement(Measurement measure);
  6674. @t\4@>@[signals:@]@;
  6675. void measurement(Measurement measure);
  6676. void newData(Measurement measure);
  6677. private:@/
  6678. double Lo1;
  6679. double Lo2;
  6680. double Up1;
  6681. double Up2;
  6682. double sensitivitySetting;
  6683. bool clamp;
  6684. };
  6685. @ When the measured range and the mapped range are identical and the range is
  6686. open, we have an identity mapping. This is the default state in a newly
  6687. constructed |LinearCalibrator| which should quickly be changed.
  6688. @<LinearCalibrator Implementation@>=
  6689. LinearCalibrator::LinearCalibrator(QObject *parent) :
  6690. QObject(parent), Lo1(0), Lo2(0), Up1(1), Up2(1), sensitivitySetting(0.0), clamp(false)@/
  6691. {
  6692. connect(this, SIGNAL(measurement(Measurement)), this, SIGNAL(newData(Measurement)));
  6693. }
  6694. @ The functional portion of the class is in the |newMeasurement()| slot. This
  6695. will receive measurements as they come in and emit a |measurement()| signal for
  6696. each with the calibration and unit adjustment performed.
  6697. This method also handles any rounding needed if there has been a call to
  6698. |setSensitivity()|.
  6699. @<LinearCalibrator Implementation@>=
  6700. Measurement LinearCalibrator::newMeasurement(Measurement measure)
  6701. {
  6702. double outval = Lo1 + (measure.temperature() - Lo2) * (Up1 - Lo1)/(Up2 - Lo2);
  6703. if(clamp)
  6704. {
  6705. if(outval < Lo1)
  6706. {
  6707. outval = Lo1;
  6708. }
  6709. else if(outval > Up1)
  6710. {
  6711. outval = Up1;
  6712. }
  6713. }
  6714. if(sensitivitySetting >= 0.05)
  6715. {
  6716. int temp = qRound(outval/sensitivitySetting);
  6717. outval = temp * sensitivitySetting;
  6718. }
  6719. Measurement adjusted(outval, measure.time(), measure.scale());
  6720. emit measurement(adjusted);
  6721. return adjusted;
  6722. }
  6723. @ The rest of the class consists of trivial accessor methods.
  6724. @<LinearCalibrator Implementation@>=
  6725. double LinearCalibrator::measuredLower()
  6726. {
  6727. return Lo2;
  6728. }
  6729. double LinearCalibrator::measuredUpper()
  6730. {
  6731. return Up2;
  6732. }
  6733. double LinearCalibrator::mappedLower()
  6734. {
  6735. return Lo1;
  6736. }
  6737. double LinearCalibrator::mappedUpper()
  6738. {
  6739. return Up1;
  6740. }
  6741. bool LinearCalibrator::isClosedRange()
  6742. {
  6743. return clamp;
  6744. }
  6745. void LinearCalibrator::setMeasuredLower(double lower)
  6746. {
  6747. Lo2 = lower;
  6748. }
  6749. void LinearCalibrator::setMeasuredUpper(double upper)
  6750. {
  6751. Up2 = upper;
  6752. }
  6753. void LinearCalibrator::setMappedLower(double lower)
  6754. {
  6755. Lo1 = lower;
  6756. }
  6757. void LinearCalibrator::setMappedUpper(double upper)
  6758. {
  6759. Up1 = upper;
  6760. }
  6761. void LinearCalibrator::setClosedRange(bool closed)
  6762. {
  6763. clamp = closed;
  6764. }
  6765. void LinearCalibrator::setSensitivity(double sensitivity)
  6766. {
  6767. sensitivitySetting = sensitivity;
  6768. }
  6769. double LinearCalibrator::sensitivity()
  6770. {
  6771. return sensitivitySetting;
  6772. }
  6773. @ Finally, we make this class available to the scripting engine. Two functions
  6774. are required for this.
  6775. @<Function prototypes for scripting@>=
  6776. QScriptValue constructLinearCalibrator(QScriptContext *context,
  6777. QScriptEngine *engine);
  6778. void setLinearCalibratorProperties(QScriptValue value, QScriptEngine *engine);
  6779. @ The scripting engine is informed of the constructor.
  6780. @<Set up the scripting engine@>=
  6781. constructor = engine->newFunction(constructLinearCalibrator);
  6782. value = engine->newQMetaObject(&LinearCalibrator::staticMetaObject,
  6783. constructor);
  6784. engine->globalObject().setProperty("LinearCalibrator", value);
  6785. @ The implementation of these functions is typical for this application.
  6786. @<Functions for scripting@>=
  6787. QScriptValue constructLinearCalibrator(QScriptContext *, QScriptEngine *engine)
  6788. {
  6789. QScriptValue object = engine->newQObject(new LinearCalibrator(NULL));
  6790. setLinearCalibratorProperties(object, engine);
  6791. return object;
  6792. }
  6793. void setLinearCalibratorProperties(QScriptValue value, QScriptEngine *engine)
  6794. {
  6795. setQObjectProperties(value, engine);
  6796. }
  6797. @* Linear Spline Interpolation.
  6798. \noindent While linear interpolation is adequate for many purposes, it fails
  6799. when a nonlinear mapping is required. The primary use case is to calibrate
  6800. multiple coffee roasters so that roast profiles can be shared among coffee
  6801. roasters with sufficiently similar heat transfer characteristics even if
  6802. differences in the measurement hardware result in different measured values.
  6803. By recording measured values at several points known to be equivalent due to
  6804. easily observable physical changes in the coffee it is possible to use linear
  6805. spline interpolation to produce a data series that approximates on one machine
  6806. the measurements that would have been produced at another. Acceptable results
  6807. may be available with surprisingly few data points.
  6808. It was originally suspected that cubic spline interpolation would produce a
  6809. more accurate mapping, but testing with linear spline interpolation produced
  6810. results good enough that more complex mappings were not needed. Cubic spline
  6811. interpolation may still be implemented in the future, but it is a low
  6812. priority.
  6813. @<Class declarations@>=
  6814. class LinearSplineInterpolator : public QObject@/
  6815. {@/
  6816. @[Q_OBJECT@]@;@/
  6817. public:@/
  6818. LinearSplineInterpolator(QObject *parent = NULL);
  6819. @[Q_INVOKABLE@,@, void@]@, add_pair(double source, double destination);@t\2\2@>@/
  6820. @[public slots@]:@/
  6821. Measurement newMeasurement(Measurement measure);
  6822. @[signals@]:@/
  6823. void newData(Measurement measure);
  6824. private:@/
  6825. void make_interpolators();
  6826. QMap<double, double> *pairs;
  6827. QList<LinearCalibrator *> *interpolators;@/
  6828. };
  6829. @ We take advantage of the fact that iterating over a QMap always returns
  6830. entries in key order. When new measurement pairs are specified, the
  6831. interpolators are regenerated. There is significant room for performance
  6832. improvement.
  6833. @<LinearSplineInterpolator Implementation@>=
  6834. void LinearSplineInterpolator::add_pair(double source, double destination)
  6835. {
  6836. pairs->insert(source, destination);
  6837. make_interpolators();
  6838. }
  6839. void LinearSplineInterpolator::make_interpolators()
  6840. {
  6841. if(pairs->size() > 1)
  6842. {
  6843. while(interpolators->size() > 0)
  6844. {
  6845. LinearCalibrator *removed = interpolators->takeFirst();
  6846. removed->deleteLater();
  6847. }
  6848. QMap<double, double>::const_iterator i = pairs->constBegin();
  6849. QMap<double, double>::const_iterator j = i + 1;
  6850. while(j != pairs->constEnd())
  6851. {
  6852. LinearCalibrator *segment = new LinearCalibrator();
  6853. segment->setMeasuredLower(i.key());
  6854. segment->setMappedLower(i.value());
  6855. segment->setMeasuredUpper(j.key());
  6856. segment->setMappedUpper(j.value());
  6857. segment->setClosedRange(false);
  6858. interpolators->append(segment);
  6859. connect(segment, SIGNAL(measurement(Measurement)), this, SIGNAL(newData(Measurement)));
  6860. i++;
  6861. j++;
  6862. }
  6863. }
  6864. }
  6865. LinearSplineInterpolator::LinearSplineInterpolator(QObject *parent) :
  6866. QObject(parent), pairs(new QMap<double, double>),
  6867. interpolators(new QList<LinearCalibrator *>)
  6868. {
  6869. /* Nothing needs to be done here. */
  6870. }
  6871. Measurement LinearSplineInterpolator::newMeasurement(Measurement measure)
  6872. {
  6873. QMap<double, double>::const_iterator i = pairs->constBegin();
  6874. int index = -1;
  6875. while(i != pairs->constEnd())
  6876. {
  6877. if(measure.temperature() <= i.key())
  6878. {
  6879. break;
  6880. }
  6881. i++;
  6882. index++;
  6883. }
  6884. if(index < 0)
  6885. {
  6886. index = 0;
  6887. }
  6888. if(index >= interpolators->size())
  6889. {
  6890. index = interpolators->size() - 1;
  6891. }
  6892. if(interpolators->at(index) != NULL)
  6893. {
  6894. return interpolators->at(index)->newMeasurement(measure);
  6895. }
  6896. return Measurement();
  6897. }
  6898. @ This is exposed to the scripting environment as usual.
  6899. @<Function prototypes for scripting@>=
  6900. QScriptValue constructLinearSplineInterpolator(QScriptContext *context, QScriptEngine *engine);
  6901. void setLinearSplineInterpolatorProperties(QScriptValue value, QScriptEngine *engine);
  6902. @ As usual.
  6903. @<Set up the scripting engine@>=
  6904. constructor = engine->newFunction(constructLinearSplineInterpolator);
  6905. value = engine->newQMetaObject(&LinearSplineInterpolator::staticMetaObject, constructor);
  6906. engine->globalObject().setProperty("LinearSplineInterpolator", value);
  6907. @ And again as usual.
  6908. @<Functions for scripting@>=
  6909. QScriptValue constructLinearSplineInterpolator(QScriptContext *, QScriptEngine *engine)
  6910. {
  6911. QScriptValue object = engine->newQObject(new LinearSplineInterpolator(NULL));
  6912. setLinearSplineInterpolatorProperties(object, engine);
  6913. return object;
  6914. }
  6915. void setLinearSplineInterpolatorProperties(QScriptValue value, QScriptEngine *engine)
  6916. {
  6917. setQObjectProperties(value, engine);
  6918. }
  6919. @* The TemperatureDisplay class.
  6920. Now that measurements have been generated by the |DAQ| and passed to a
  6921. |Channel|, any object that is interested in these measurements can connect to
  6922. the channel and use the measurements it sends out. So far, the time on each
  6923. measurement is the time at which it was collected. Unfortunately, this is often
  6924. not what we want. It is more useful to have the time relative to some other
  6925. point in time such as the start of the batch.
  6926. Until the measurement time is adjusted, the measurements are really only useful
  6927. to classes that do not care about the measurement time. The |TemperatureDisplay|
  6928. class is such a class. It receives measurements and displays the most recently
  6929. measured temperature.
  6930. This is a specialization of |QLCDNumber|.
  6931. @<Class declarations@>=
  6932. class TemperatureDisplay : public QLCDNumber@/
  6933. {@t\1@>@/
  6934. Q_OBJECT@;
  6935. int unit;
  6936. bool r;
  6937. public:@/
  6938. TemperatureDisplay(QWidget *parent = NULL);
  6939. ~TemperatureDisplay();@/
  6940. @t\4@>public slots@t\kern-3pt@>:@/
  6941. void setValue(Measurement temperature);
  6942. void invalidate();
  6943. void setDisplayUnits(Units::Unit scale);
  6944. void setRelativeMode(bool relative);@t\2@>@/
  6945. };
  6946. @ Starting in version 1.6 this widget is also used for displaying a relative
  6947. temperature value in the form of the rate of change indicator. To calculate
  6948. this correctly in Celsius or Kelvin we must have a way to bypass the
  6949. conversions for absolute measures.
  6950. @<TemperatureDisplay Implementation@>=
  6951. void TemperatureDisplay::setRelativeMode(bool relative)
  6952. {
  6953. r = relative;
  6954. }
  6955. @ Displaying a temperature is a simple matter of taking the temperature
  6956. component from the measurement and converting it to a string. Presently, this
  6957. code assumes that the measurements are in degrees Fahrenheit. If the code
  6958. becomes smarter about measurement units it might be a good idea to change this.
  6959. |QLCDNumber| is capable of displaying more than just numbers, so the call to
  6960. display takes a string which in this case consists of the temperature to the
  6961. $1\over100$th of a degree and might be followed by '@q'@> which will be
  6962. converted to $^\circ$ and the letter F, C, or r to indicate the unit. This
  6963. class should be mofified to allow a user specified precision.
  6964. @<TemperatureDisplay Implementation@>=
  6965. void TemperatureDisplay::setValue(Measurement temperature)
  6966. {
  6967. QString number;
  6968. switch(unit)
  6969. {
  6970. case Units::Fahrenheit:
  6971. display(QString("%1'F").
  6972. arg(number.setNum(temperature.toFahrenheit().temperature(), 'f',
  6973. 2)));
  6974. break;
  6975. case Units::Celsius:
  6976. if(!r) {
  6977. display(QString("%1'C").
  6978. arg(number.setNum(temperature.toCelsius().temperature(), 'f',
  6979. 2)));
  6980. } else {
  6981. number.setNum(temperature.temperature() * (5.0/9.0), 'f', 2);
  6982. display(QString("%1'C").arg(number));
  6983. }
  6984. break;
  6985. case Units::Kelvin:
  6986. if(!r) {
  6987. display(QString("%1").
  6988. arg(number.setNum(temperature.toKelvin().temperature(), 'f',
  6989. 2)));
  6990. } else {
  6991. number.setNum(temperature.temperature() * (5.0/9.0), 'f', 2);
  6992. display(QString("%1").arg(number));
  6993. }
  6994. break;
  6995. case Units::Rankine:
  6996. display(QString("%1'r").
  6997. arg(number.setNum(temperature.toRankine().temperature(), 'f',
  6998. 2)));
  6999. break;
  7000. case Units::Unitless:
  7001. display(QString("%1").arg(number.setNum(temperature.temperature(), 'f', 0)));
  7002. break;
  7003. default:
  7004. switch(temperature.scale())
  7005. {
  7006. case Units::Fahrenheit:
  7007. display(QString("%1'F").
  7008. arg(number.setNum(temperature.temperature(), 'f', 2)));
  7009. break;
  7010. case Units::Celsius:
  7011. display(QString("%1'C").
  7012. arg(number.setNum(temperature.temperature(), 'f', 2)));
  7013. break;
  7014. case Units::Kelvin:
  7015. display(QString("%1").
  7016. arg(number.setNum(temperature.temperature(), 'f', 2)));
  7017. break;
  7018. case Units::Rankine:
  7019. display(QString("%1'r").
  7020. arg(number.setNum(temperature.temperature(), 'f', 2)));
  7021. break;
  7022. case Units::Unitless:
  7023. display(QString("%1").arg(number.setNum(temperature.temperature(), 'f', 0)));
  7024. break;
  7025. default:
  7026. qDebug() << "Warning: Attempting to convert a non-temperature unit to a temperature unit";
  7027. break;
  7028. }
  7029. break;
  7030. }
  7031. }
  7032. @ Before measurements are displayed, we set a more sensible default display
  7033. style and an initial string. These defaults can all be overridden with calls to
  7034. the usual |QLCDNumber| methods.
  7035. \medskip
  7036. \resizebox*{6.3in}{!}{\includegraphics{QLCDNumber.png}}
  7037. \smallskip
  7038. \centerline{Figure \secno: Outline (Qt default) and Filled |QLCDNumber| Example}
  7039. \medskip
  7040. @<TemperatureDisplay Implementation@>=
  7041. TemperatureDisplay::TemperatureDisplay(QWidget *parent) :
  7042. QLCDNumber(8, parent), unit(Units::Fahrenheit), r(false)@/
  7043. {
  7044. setSegmentStyle(Filled);
  7045. display("---.--'F");
  7046. }
  7047. @ While it is not currently used, it would be good to allow an error state to
  7048. be easily discernible from a very stable temperature. Currently, if an error
  7049. occurs that results in the measurement thread exiting, no new measurements will
  7050. be generated and the temperature display will continue to read the most recent
  7051. measured value. If an error signal were emitted, it could be connected to the
  7052. following code to change the display to reflect the fact that the current
  7053. temperature is unknown.
  7054. @<TemperatureDisplay Implementation@>=
  7055. void TemperatureDisplay::invalidate()
  7056. {
  7057. display("---.--'F");
  7058. }
  7059. @ \pn{} supports the display of multiple types of unit. Typically, we use the
  7060. Auto scale which will cause |TemperatureDisplay| objects to display measurements
  7061. in whichever scale the measurement is associated with. Alternately, we can fix
  7062. the scale to a different supported scale and convert measurements to that scale
  7063. prior to display.
  7064. @<TemperatureDisplay Implementation@>=
  7065. void TemperatureDisplay::setDisplayUnits(Units::Unit scale)
  7066. {
  7067. unit = scale;
  7068. }
  7069. @ All that is left to deal with is the empty destructor.
  7070. @<TemperatureDisplay Implementation@>=
  7071. TemperatureDisplay::~TemperatureDisplay()
  7072. {
  7073. /* Nothing has to be done here. */
  7074. }
  7075. @ To use a |TemperatureDisplay| from a script, we need a function to pass a new
  7076. object to the scripting engine.
  7077. @<Function prototypes for scripting@>=
  7078. QScriptValue constructTemperatureDisplay(QScriptContext *context,
  7079. QScriptEngine *engine);
  7080. void setTemperatureDisplayProperties(QScriptValue value, QScriptEngine *engine);
  7081. QScriptValue TemperatureDisplay_setDisplayUnits(QScriptContext *context,
  7082. QScriptEngine *engine);
  7083. @ The scripting engine must be informed of this function.
  7084. @<Set up the scripting engine@>=
  7085. constructor = engine->newFunction(constructTemperatureDisplay);
  7086. value = engine->newQMetaObject(&TemperatureDisplay::staticMetaObject,
  7087. constructor);
  7088. engine->globalObject().setProperty("TemperatureDisplay", value);
  7089. @ The constructor is trivial.
  7090. @<Functions for scripting@>=
  7091. QScriptValue constructTemperatureDisplay(QScriptContext *,
  7092. QScriptEngine *engine)
  7093. {
  7094. QScriptValue object = engine->newQObject(new TemperatureDisplay);
  7095. setTemperatureDisplayProperties(object, engine);
  7096. return object;
  7097. }
  7098. void setTemperatureDisplayProperties(QScriptValue value, QScriptEngine *engine)
  7099. {
  7100. setQLCDNumberProperties(value, engine);
  7101. value.setProperty("setDisplayUnits",
  7102. engine->newFunction(TemperatureDisplay_setDisplayUnits));
  7103. }
  7104. @ There seems to be a bad interaction when enumerated value types as used as
  7105. the argument to slot methods called through QtScript. Script code that attempts
  7106. to make use of the enumeration appears to get the value without any type
  7107. information. When attempting to use that value as an argument the meta-object
  7108. system cannot find an appropriate match and the script just hangs silently.
  7109. The solution is to wrap such methods in the script bindings and explicitly cast
  7110. the argument value to the enumerated type. This looks stupid but it works.
  7111. @<Functions for scripting@>=
  7112. QScriptValue TemperatureDisplay_setDisplayUnits(QScriptContext *context, QScriptEngine *)
  7113. {
  7114. TemperatureDisplay *self = getself<@[TemperatureDisplay *@]>(context);
  7115. self->setDisplayUnits((Units::Unit)argument<int>(0, context));
  7116. return QScriptValue();
  7117. }
  7118. @* The MeasurementTimeOffset class.
  7119. When a |DAQ| object creates a |Measurement| object, the time component is a
  7120. system time. In most cases, the system time is not interesting and a more useful
  7121. time would be relative to the start of a process. This class should be used as a
  7122. filter, taking measurements with a system time stamp and producing measurements
  7123. with a relative time.
  7124. @<Class declarations@>=
  7125. class MeasurementTimeOffset : public QObject@/
  7126. {@t\1@>@/
  7127. Q_OBJECT@;
  7128. QTime epoch;
  7129. QTime previous;
  7130. bool hasPrevious;@/
  7131. public:@;
  7132. MeasurementTimeOffset(QTime zero);
  7133. QTime zeroTime();@/
  7134. @t\4@>public slots@t\kern-3pt@>:@;
  7135. void newMeasurement(Measurement measure);
  7136. void setZeroTime(QTime zero);
  7137. signals:@;
  7138. void measurement(Measurement measure);@t\2@>@/
  7139. }@t\kern-3pt@>;
  7140. @ The interesting part of this class is the function which takes a measurement
  7141. with a system time and produces a new measurement with a time relative to some
  7142. start time.
  7143. When using this class, it is possible that a measurement will arrive with a time
  7144. slightly before a newly chosen epoch. In such a case we do not want to simply
  7145. subtract the epoch from the measurement time as other classes will interpret
  7146. this incorrectly as a measurement time slightly less than 1 hour. This means
  7147. that we need to check if the measurement time is before the epoch. If it is, we
  7148. consider it to have been generated at the epoch rather than before. Aren't race
  7149. conditions fun?
  7150. Additionally, since we're only getting time of day information, some special
  7151. handling must be done for time series that cross the boundary between days. We
  7152. should never get measurements out of order, so keeping a record of the previous
  7153. measurement and verifying that the new measurement comes after it is sufficient.
  7154. @<MeasurementTimeOffset Implementation@>=
  7155. void MeasurementTimeOffset::newMeasurement(Measurement measure)@t\2\2@>@/
  7156. {@t\1@>@/
  7157. if(measure.time() < epoch)@/
  7158. {
  7159. if(hasPrevious)@/
  7160. {
  7161. QTime jitBase(epoch.hour() - 1, epoch.minute(), epoch.second(),
  7162. epoch.msec());
  7163. QTime jitComp(epoch.hour(), measure.time().minute(),
  7164. measure.time().second(), measure.time().msec());
  7165. int relTime = jitBase.msecsTo(jitComp);
  7166. @<Produce and emit relative time@>@;
  7167. }
  7168. else@/
  7169. {
  7170. Measurement rel = measure;
  7171. rel.setTime(QTime(0, 0, 0, 0));
  7172. emit measurement(rel);
  7173. }
  7174. }
  7175. else@/
  7176. {
  7177. int relTime = epoch.msecsTo(measure.time());
  7178. @<Produce and emit relative time@>@;
  7179. }
  7180. hasPrevious = true;
  7181. previous = measure.time();@t\2@>@/
  7182. }
  7183. @ The measurement emitted has a time with the number of minutes, seconds, and
  7184. milliseconds since the start of the batch. We never generate a time greater
  7185. than 1 hour.
  7186. @<Produce and emit relative time@>=
  7187. QTime newTime(0, 0, 0, 0);
  7188. newTime = newTime.addMSecs(relTime);
  7189. if(newTime.hour() > 0)
  7190. {
  7191. newTime.setHMS(0, newTime.minute(), newTime.second(), newTime.msec());
  7192. }
  7193. Measurement rel = measure;
  7194. rel.setTime(newTime);
  7195. emit measurement(rel);
  7196. @ The rest of the code handles updating and reporting the reference time.
  7197. @<MeasurementTimeOffset Implementation@>=
  7198. MeasurementTimeOffset::MeasurementTimeOffset(QTime zero) : epoch(zero),
  7199. previous(0, 0, 0, 0), hasPrevious(false)
  7200. {
  7201. /* Nothing has to be done here. */
  7202. }
  7203. QTime MeasurementTimeOffset::zeroTime()
  7204. {
  7205. return epoch;
  7206. }
  7207. void MeasurementTimeOffset::setZeroTime(QTime zero)
  7208. {
  7209. epoch = zero;
  7210. hasPrevious = false;
  7211. }
  7212. @ Two functions are required to make this class available to the scripting
  7213. engine.
  7214. @<Function prototypes for scripting@>=
  7215. QScriptValue constructMeasurementTimeOffset(QScriptContext *context,@|
  7216. QScriptEngine *engine);
  7217. void setMeasurementTimeOffsetProperties(QScriptValue value,
  7218. QScriptEngine *engine);
  7219. @ The scripting engine must be informed of the constructor.
  7220. @<Set up the scripting engine@>=
  7221. constructor = engine->newFunction(constructMeasurementTimeOffset);
  7222. value = engine->newQMetaObject(&MeasurementTimeOffset::staticMetaObject,
  7223. constructor);
  7224. engine->globalObject().setProperty("MeasurementTimeOffset", value);
  7225. @ Previously, another property was added to the newly created object. That
  7226. method is believed to be obsolete and has been removed. Careful testing will
  7227. need to be done to verify that this decision was sane. I was very hungry when
  7228. that change was made.
  7229. @<Functions for scripting@>=
  7230. QScriptValue constructMeasurementTimeOffset(QScriptContext *,
  7231. QScriptEngine *engine)
  7232. {
  7233. QScriptValue object =@|
  7234. engine->newQObject(new MeasurementTimeOffset(QTime::currentTime()));
  7235. setMeasurementTimeOffsetProperties(object, engine);
  7236. return object;
  7237. }
  7238. void setMeasurementTimeOffsetProperties(QScriptValue value,
  7239. QScriptEngine *engine)
  7240. {
  7241. setQObjectProperties(value, engine);
  7242. }
  7243. @* Measured value threshold detection.
  7244. \noindent There are times when one might want to detect when a measured value
  7245. from a data series has passed a given value, with the limitation that we are
  7246. only interested in the ascending or descending edge. This can be used, for
  7247. example, to translate roast profile data in a graph along the time axis such
  7248. that the bean temperature series are aligned at a given
  7249. temperature.\nfnote{More details on the reasoning behind why one might want
  7250. to do this are provided at:\par\indent\pdfURL{http://youtu.be/hS0SfzypyFQ}
  7251. {http://youtu.be/hS0SfzypyFQ}} For this we can use a |ThresholdDetector|.
  7252. If we would like to catch changes on both the ascending and descending edge, we
  7253. can use two objects, however it may be a good idea to use more than two to
  7254. allow for sane behavior in the face of hysteresis.
  7255. @<Class declarations@>=
  7256. class ThresholdDetector : public QObject@/
  7257. {
  7258. @[Q_OBJECT@]@;
  7259. @[Q_ENUMS(EdgeDirection)@]@;
  7260. public:@/
  7261. enum EdgeDirection {
  7262. Ascending, Descending
  7263. };
  7264. ThresholdDetector(double value);
  7265. @[public slots@]:@/
  7266. void newMeasurement(Measurement measure);
  7267. void setThreshold(double value);
  7268. void setEdgeDirection(EdgeDirection direction);
  7269. signals:@/
  7270. void timeForValue(double);
  7271. private:@/
  7272. bool previousValueValid;
  7273. double previousValue;
  7274. double threshold;
  7275. EdgeDirection currentDirection;
  7276. };
  7277. @ This class emits the time in seconds when a given measurement crosses the
  7278. threshold value in the appropriate direction.
  7279. This was previously written with |previousValue| initialized negative and a
  7280. check that |previousValue| was non-negative. When the |ThresholdDetector| is
  7281. connected to a data source representing temperature measurements this is a
  7282. reasonable choice, however it breaks when connected to a rate of change series.
  7283. To make this more generally correct, a boolean is checked to determine if a
  7284. previous value has been set.
  7285. @<ThresholdDetector Implementation@>=
  7286. void ThresholdDetector::newMeasurement(Measurement measure)
  7287. {
  7288. if((currentDirection == Ascending && previousValue < threshold &&
  7289. previousValueValid) || (currentDirection == Descending &&
  7290. previousValue > threshold && previousValueValid))
  7291. {
  7292. if((currentDirection == Ascending && measure.temperature() >= threshold) ||
  7293. (currentDirection == Descending && measure.temperature() <= threshold))
  7294. {
  7295. double offset = measure.time().hour() * 60 * 60;
  7296. offset += measure.time().minute() * 60;
  7297. offset += measure.time().second();
  7298. offset += measure.time().msec()/1000;
  7299. emit timeForValue(offset);
  7300. }
  7301. }
  7302. previousValue = measure.temperature();
  7303. previousValueValid = true;
  7304. }
  7305. ThresholdDetector::ThresholdDetector(double value) : QObject(NULL),
  7306. previousValueValid(false),
  7307. previousValue(-1), threshold(value), currentDirection(Ascending)
  7308. {
  7309. /* Nothing needs to be done here. */
  7310. }
  7311. void ThresholdDetector::setThreshold(double value)
  7312. {
  7313. threshold = value;
  7314. }
  7315. void ThresholdDetector::setEdgeDirection(EdgeDirection direction)
  7316. {
  7317. currentDirection = direction;
  7318. }
  7319. @ This is exposed to the host environment.
  7320. @<Function prototypes for scripting@>=
  7321. QScriptValue constructThresholdDetector(QScriptContext *context, QScriptEngine *engine);
  7322. void setThresholdDetectorProperties(QScriptValue value, QScriptEngine *engine);
  7323. @ Inform the engine of the constructor.
  7324. @<Set up the scripting engine@>=
  7325. constructor = engine->newFunction(constructThresholdDetector);
  7326. value = engine->newQMetaObject(&ThresholdDetector::staticMetaObject, constructor);
  7327. engine->globalObject().setProperty("ThresholdDetector", value);
  7328. @ Implementation. At present I'@q'@>m not bothering to implement constructor
  7329. arguments here and am aligning on a fixed point. Another slot method was added
  7330. to restore adjustability.
  7331. @<Functions for scripting@>=
  7332. QScriptValue constructThresholdDetector(QScriptContext *, QScriptEngine *engine)
  7333. {
  7334. QScriptValue object = engine->newQObject(new ThresholdDetector(300));
  7335. return object;
  7336. }
  7337. void setThresholdDetectorProperties(QScriptValue value, QScriptEngine *engine)
  7338. {
  7339. setQObjectProperties(value, engine);
  7340. }
  7341. @* The ZeroEmitter class.
  7342. \noindent Now that it is possible to record the time a measurement was taken
  7343. relative to an arbitrary start time, there is a minor problem left for logging.
  7344. It is extremely unlikely that a measurement will be passed through at the epoch.
  7345. For this, what we want to do is save the previous measurement and make it
  7346. available at time 0 whenever the start time is reset. This is the role of the
  7347. |ZeroEmitter| class.
  7348. Another problem is that most classes that are interested in a relative time are
  7349. also interested in logging multiple sets of temperature data. To facilitate this
  7350. an integer is emitted. Different temperature measurement sources should be set
  7351. to emit different numbers. A table view would place measurements in the
  7352. indicated column. A graph view would use different colors to plot different sets
  7353. of data.
  7354. @<Class declarations@>=
  7355. class ZeroEmitter : public QObject@/
  7356. {@t\1@>@/
  7357. @[Q_OBJECT@]@;
  7358. @[Q_PROPERTY(int column READ column WRITE setColumn)@]@;
  7359. Measurement cache;
  7360. int col;
  7361. public:@/
  7362. ZeroEmitter(int tempcolumn = 1);
  7363. int column();
  7364. double lastTemperature();@/
  7365. @t\4@>public slots@t\kern-3pt@>:@;
  7366. void newMeasurement(Measurement measure);
  7367. void setColumn(int column);
  7368. void emitZero();
  7369. signals:@;
  7370. void measurement(Measurement measure, int tempcolumn);@t\2@>@/
  7371. }@t\kern-3pt@>;
  7372. @ The implementation of the class is trivial.
  7373. @<ZeroEmitter Implementation@>=
  7374. ZeroEmitter::ZeroEmitter(int tempcolumn) : QObject(NULL), col(tempcolumn)@;
  7375. {
  7376. /* Nothing has to be done here. */
  7377. }
  7378. int ZeroEmitter::column()
  7379. {
  7380. return col;
  7381. }
  7382. double ZeroEmitter::lastTemperature()
  7383. {
  7384. return cache.temperature();
  7385. }
  7386. void ZeroEmitter::newMeasurement(Measurement measure)
  7387. {
  7388. cache = measure;
  7389. }
  7390. void ZeroEmitter::setColumn(int column)
  7391. {
  7392. col = column;
  7393. }
  7394. void ZeroEmitter::emitZero()
  7395. {
  7396. cache.setTime(QTime(0, 0, 0, 0));
  7397. emit measurement(cache, col);
  7398. }
  7399. @ Making this class available to scripts requires only two functions.
  7400. @<Function prototypes for scripting@>=
  7401. QScriptValue constructZeroEmitter(QScriptContext *context,
  7402. QScriptEngine *engine);
  7403. void setZeroEmitterProperties(QScriptValue value, QScriptEngine *engine);
  7404. @ To use it, we must inform the engine of the constructor.
  7405. @<Set up the scripting engine@>=
  7406. constructor = engine->newFunction(constructZeroEmitter);
  7407. value = engine->newQMetaObject(&ZeroEmitter::staticMetaObject, constructor);
  7408. engine->globalObject().setProperty("ZeroEmitter", value);
  7409. @ The implementation of the constructor is trivial.
  7410. @<Functions for scripting@>=
  7411. QScriptValue constructZeroEmitter(QScriptContext *context,
  7412. QScriptEngine *engine)
  7413. {
  7414. QScriptValue object =
  7415. engine->newQObject(new ZeroEmitter(argument<int>(0, context)));
  7416. setZeroEmitterProperties(object, engine);
  7417. return object;
  7418. }
  7419. void setZeroEmitterProperties(QScriptValue value, QScriptEngine *engine)
  7420. {
  7421. setQObjectProperties(value, engine);
  7422. }
  7423. @* The MeasurementAdapter class.
  7424. \noindent The last of the measurement filter classes is the |MeasurementAdapter|
  7425. class. This takes measurements, typically from a |MeasurementTimeOffset|, and
  7426. sends the measurement out with a number to indicate which data series the
  7427. measurement belongs to.
  7428. The measurement pipeline could probably be made simpler by introducing a series
  7429. identifier into the measurement class.
  7430. @<Class declarations@>=
  7431. class MeasurementAdapter : public QObject@/
  7432. {@t\1@>@/
  7433. Q_OBJECT@;
  7434. int col;
  7435. public:@/
  7436. MeasurementAdapter(int tempcolumn);
  7437. int column();@/
  7438. @t\4@>public slots@t\kern-3pt@>:@/
  7439. void newMeasurement(Measurement measure);
  7440. void setColumn(int column);
  7441. signals:@/
  7442. void measurement(Measurement measure, int tempcolumn);@t\2@>@/
  7443. }@t\kern-3pt@>;
  7444. @ The implementation of this filter class is trivial.
  7445. @<MeasurementAdapter Implementation@>=
  7446. MeasurementAdapter::MeasurementAdapter(int tempcolumn) : col(tempcolumn)@;
  7447. {
  7448. /* Nothing has to be done here. */
  7449. }
  7450. int MeasurementAdapter::column()
  7451. {
  7452. return col;
  7453. }
  7454. void MeasurementAdapter::newMeasurement(Measurement measure)
  7455. {
  7456. emit measurement(measure, col);
  7457. }
  7458. void MeasurementAdapter::setColumn(int column)
  7459. {
  7460. col = column;
  7461. }
  7462. @ This filter class is also available from the host environment.
  7463. @<Function prototypes for scripting@>=
  7464. QScriptValue constructMeasurementAdapter(QScriptContext *context,
  7465. QScriptEngine *engine);
  7466. void setMeasurementAdapterProperties(QScriptValue value, QScriptEngine *engine);
  7467. @ As usual, the engine must be informed of the constructor.
  7468. @<Set up the scripting engine@>=
  7469. constructor = engine->newFunction(constructMeasurementAdapter);
  7470. value = engine->newQMetaObject(&MeasurementAdapter::staticMetaObject,
  7471. constructor);
  7472. engine->globalObject().setProperty("MeasurementAdapter", value);
  7473. @ The implementation is trivial.
  7474. @<Functions for scripting@>=
  7475. QScriptValue constructMeasurementAdapter(QScriptContext *context,
  7476. QScriptEngine *engine)
  7477. {
  7478. QScriptValue object =
  7479. engine->newQObject(new MeasurementAdapter(argument<int>(0, context)));
  7480. setMeasurementAdapterProperties(object, engine);
  7481. return object;
  7482. }
  7483. void setMeasurementAdapterProperties(QScriptValue value, QScriptEngine *engine)
  7484. {
  7485. setQObjectProperties(value, engine);
  7486. }
  7487. @* A graph of temperature over time.
  7488. \noindent A useful tool when roasting is a visual depiction of the current batch
  7489. as it happens, possibly laid over a previously recorded target profile. The
  7490. |GraphView| class can take multiple sets of temperature data and produce such a
  7491. visualization.
  7492. \medskip
  7493. \centerline{\includegraphics{roast}}
  7494. \smallskip
  7495. \centerline{Figure \secno: A Typical Roast}
  7496. \medskip
  7497. This class assumes that temperature data will be passed in the correct order.
  7498. @<Class declarations@>=
  7499. class GraphView : public QGraphicsView@/
  7500. {@t\1@>@/
  7501. Q_OBJECT@;
  7502. QGraphicsScene *theScene;@/
  7503. QMap<int, QList<QGraphicsLineItem * > * > *graphLines;@/
  7504. QMap<int, QPointF> *prevPoints;
  7505. QMap<int, double> *translations;
  7506. QList<QGraphicsItem *> *gridLinesF;
  7507. QList<QGraphicsItem *> *gridLinesC;
  7508. QList<QGraphicsItem *> *relativeGridLines;
  7509. bool relativeEnabled;
  7510. bool timeIndicatorEnabled;
  7511. QGraphicsLineItem *timeLine;
  7512. LinearSplineInterpolator *relativeAdjuster;@/
  7513. public:@/
  7514. GraphView(QWidget *parent = NULL);
  7515. void removeSeries(int column);@/
  7516. protected:@/
  7517. void resizeEvent(QResizeEvent *event);@/
  7518. @t\4@>public slots@t\kern-3pt@>:@/
  7519. void newMeasurement(Measurement measure, int tempcolumn);
  7520. void setSeriesTranslation(int column, double offset);
  7521. void setTimeIndicatorEnabled(bool enabled);
  7522. void clear();
  7523. void showF();
  7524. void showC();@t\2@>@/
  7525. }@t\kern-3pt@>;
  7526. @ I decided that it would probably be best to keep the graph area the same even
  7527. with different roast lengths over different temperature ranges so that similar
  7528. portions between these graphs would continue to look similar rather than
  7529. constantly attempting to select the best way to display the data currently in
  7530. the view.
  7531. I have chosen to represent roasting times of up to 20 minutes and temperatures
  7532. between 0 and 500$^\circ$ Fahrenheit. This should certainly be configurable at
  7533. run time, but until that is implemented, roasters who routinely roast batches
  7534. for longer periods of time will want to change the constructor. This class
  7535. should probably be modified to allow the user to specify several characteristics
  7536. of the display.
  7537. This class must also deal with the fact that coordinates in a |QGraphicsScene|
  7538. are not quite the same as coordinates in a cartesian plane. The easiest way to
  7539. deal with this is to negate the y coordinate and translate the viewport to the
  7540. area we draw in.
  7541. A small margin area left around the edges of the graph. This should probably be
  7542. configurable for those with particularly small displays.
  7543. @<GraphView Implementation@>=
  7544. GraphView::GraphView(QWidget *parent) : QGraphicsView(parent),
  7545. theScene(new QGraphicsScene),@/
  7546. graphLines(new QMap<int, QList<QGraphicsLineItem *> *>),@/
  7547. prevPoints(new QMap<int, QPointF>),
  7548. translations(new QMap<int, double>),
  7549. gridLinesF(new QList<QGraphicsItem *>),
  7550. gridLinesC(new QList<QGraphicsItem *>),
  7551. relativeGridLines(new QList<QGraphicsItem *>),
  7552. relativeEnabled(false),
  7553. timeIndicatorEnabled(false),
  7554. timeLine(new QGraphicsLineItem),
  7555. relativeAdjuster(new LinearSplineInterpolator)@/
  7556. {
  7557. setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  7558. setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  7559. setScene(theScene);
  7560. setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
  7561. QPen timePen;
  7562. timePen.setColor(QColor(160, 160, 164, 127)); //gray, half opacity
  7563. timeLine->setPen(timePen);
  7564. timeLine->setLine(0, 0, 0, -500);
  7565. timeLine->hide();
  7566. theScene->addItem(timeLine);
  7567. @<Draw temperature axis and grid lines@>;
  7568. @<Draw secondary axes@>@;
  7569. @<Draw time axis and ticks@>;
  7570. fitInView(theScene->sceneRect().adjusted(-50,-50,50,50));
  7571. }
  7572. @ Grid lines are drawn every 100 degrees. These lines are labeled with
  7573. |setHtml()| for convenient access to the $^\circ$ symbol. If \pn{} is modified
  7574. to allow different units, this code should also be modified.
  7575. As of version 1.3.3 it is possible to switch the graph between degrees
  7576. Fahrenheit and degrees Celcius. Celcius grid lines are drawn but initially
  7577. hidden. Both the grid lines and the labels are added to a list depending on the
  7578. unit so that when changing from one view to another all that needs to happen is
  7579. hide one list of items and show another.
  7580. @<Draw temperature axis and grid lines@>=
  7581. QGraphicsLineItem *tempaxis = new QGraphicsLineItem;
  7582. tempaxis->setLine(-10, -500, -10, 0);
  7583. theScene->addItem(tempaxis);
  7584. QGraphicsLineItem *gridLine;
  7585. QGraphicsTextItem *label;
  7586. for(int y = -100; y > -600; y -= 100)@/
  7587. {@/
  7588. gridLine = new QGraphicsLineItem;
  7589. gridLine->setLine(0, y, 1200, y);
  7590. theScene->addItem(gridLine);
  7591. label = new QGraphicsTextItem;
  7592. label->setHtml(QString("%1&deg;F").arg(-y));
  7593. label->setPos(-55, y - (label->boundingRect().height() / 2));
  7594. theScene->addItem(label);
  7595. gridLinesF->append(gridLine);
  7596. gridLinesF->append(label);
  7597. }
  7598. for(int degC = 50; degC <= 250; degC += 50)
  7599. {
  7600. gridLine = new QGraphicsLineItem;
  7601. int y = -(degC * (9.0/5.0) + 32);
  7602. gridLine->setLine(0, y, 1200, y);
  7603. gridLine->hide();
  7604. theScene->addItem(gridLine);
  7605. gridLinesC->append(gridLine);
  7606. label = new QGraphicsTextItem;
  7607. label->setHtml(QString("%1&deg;C").arg(degC));
  7608. label->setPos(-55, y - (label->boundingRect().height() / 2));
  7609. label->hide();
  7610. theScene->addItem(label);
  7611. gridLinesC->append(label);
  7612. }
  7613. @ If we are going to plot relative temperature measurements, we must obtain
  7614. information on how we wish to do that from settings. We take advantage of the
  7615. fact that iterating over the keys in a |QMap| produces results in sorted order.
  7616. While drawing the grid lines we also set up the |relativeAdjuster| that will be
  7617. used to transform incoming measurements to our coordinate system.
  7618. @<Draw secondary axes@>=
  7619. QSettings settings;
  7620. if(settings.contains("settings/graph/relative/enable"))
  7621. {
  7622. if(settings.value("settings/graph/relative/enable").toBool())
  7623. {
  7624. relativeEnabled = @[true@];
  7625. QColor relativeColor = QColor(settings.value("settings/graph/relative/color").toString());
  7626. QString unit = QString(settings.value(@|"settings/graph/relative/unit").toInt() == 0 ? "F" : "C");
  7627. QMap<double, QString> relativeAxisPairs;
  7628. QStringList relativeAxisLabels = settings.value(@|"settings/graph/relative/grid").toString().split(QRegExp("[\\s,]+"), QString::SkipEmptyParts);
  7629. foreach(QString item, relativeAxisLabels)
  7630. {
  7631. relativeAxisPairs.insert(item.toDouble(), item);
  7632. }
  7633. if(relativeAxisPairs.size() > 1)
  7634. {
  7635. double skip = 500.0 / (relativeAxisPairs.size() - 1);
  7636. double y = 0;
  7637. foreach(double key, relativeAxisPairs.keys())
  7638. {
  7639. gridLine = new QGraphicsLineItem;
  7640. gridLine->setLine(0, y, 1205, y);
  7641. gridLine->setPen(QPen(relativeColor));
  7642. theScene->addItem(gridLine);
  7643. relativeGridLines->append(gridLine);
  7644. label = new QGraphicsTextItem;
  7645. label->setHtml(QString("%1&deg;%2").arg(relativeAxisPairs.value(key)).arg(unit));
  7646. label->setPos(1210, y - (label->boundingRect().height() / 2));
  7647. theScene->addItem(label);
  7648. relativeGridLines->append(label);
  7649. if(unit == "F")
  7650. {
  7651. relativeAdjuster->add_pair(key, -y);
  7652. }
  7653. else
  7654. {
  7655. relativeAdjuster->add_pair(key * (9.0/5.0), -y);
  7656. }
  7657. y -= skip;
  7658. }
  7659. }
  7660. }
  7661. }
  7662. @ Two slots are used to switch between the different sets of grid lines.
  7663. @<GraphView Implementation@>=
  7664. void GraphView::showF()
  7665. {
  7666. for(int i = 0; i < gridLinesF->size(); i++)
  7667. {
  7668. gridLinesF->at(i)->show();
  7669. }
  7670. for(int i = 0; i < gridLinesC->size(); i++)
  7671. {
  7672. gridLinesC->at(i)->hide();
  7673. }
  7674. }
  7675. void GraphView::showC()
  7676. {
  7677. for(int i = 0; i < gridLinesF->size(); i++)
  7678. {
  7679. gridLinesF->at(i)->hide();
  7680. }
  7681. for(int i = 0; i < gridLinesC->size(); i++)
  7682. {
  7683. gridLinesC->at(i)->show();
  7684. }
  7685. }
  7686. @ The time axis has a tick every two minutes. The use of the |?| tertiary
  7687. operator shifts the labels with two digits a little more than labels with only
  7688. one digit. If it worked, a more resilient approach would be to take the width of
  7689. the label and center it under the tick.
  7690. @<Draw time axis and ticks@>=
  7691. QGraphicsLineItem *timeaxis = new QGraphicsLineItem;
  7692. timeaxis->setLine(0, 10, 1200, 10);
  7693. theScene->addItem(timeaxis);
  7694. for(int x = 0; x < 1201; x += 120)@/
  7695. {@/
  7696. QGraphicsLineItem *tick = new QGraphicsLineItem;
  7697. tick->setLine(x, 0, x, 20);
  7698. theScene->addItem(tick);
  7699. QGraphicsTextItem *label = new QGraphicsTextItem;
  7700. label->setPlainText(QString("%1").arg(x/60));
  7701. label->setPos(x - (label->boundingRect().width() / 2), 20);
  7702. theScene->addItem(label);
  7703. }
  7704. @ Typically, the user will be able to resize the graph. When the widget is
  7705. resized, we should fit the graph to the new size of the widget. This is safe to
  7706. do as we have already turned off the scroll bars.
  7707. @<GraphView Implementation@>=
  7708. void GraphView::resizeEvent(QResizeEvent *)
  7709. {
  7710. fitInView(theScene->sceneRect().adjusted(-50,-50,50,50));
  7711. }
  7712. @ When adding a new measurement, there are three cases that should be
  7713. considered. In the case of the first measurement, no drawing occurs. A |QList|
  7714. of line items is initialized when the second measurement is taken. Subsequent
  7715. measurements are able to simply append new line segments to the list.
  7716. Relative measurements are first converted to the coordinate system of the
  7717. appropriate secondary axis.
  7718. @<GraphView Implementation@>=
  7719. #define FULLTIMETOINT(t) (t.msec() + (t.second() * 1000) + (t.minute() * 60 * 1000))
  7720. void GraphView::newMeasurement(Measurement measure, int tempcolumn)@/
  7721. {@/
  7722. double offset = 0;
  7723. if(measure.contains("relative"))
  7724. {
  7725. if(measure.value("relative").toBool())
  7726. {
  7727. if(relativeEnabled)
  7728. {
  7729. measure.setTemperature(relativeAdjuster->newMeasurement(measure).temperature());
  7730. }
  7731. else
  7732. {
  7733. return;
  7734. }
  7735. }
  7736. }
  7737. if(translations->contains(tempcolumn))
  7738. {
  7739. offset = translations->value(tempcolumn);
  7740. }
  7741. if(prevPoints->contains(tempcolumn))@/
  7742. @t\1@>{@/
  7743. @<At least one measurement exists@>@;
  7744. if(graphLines->contains(tempcolumn))@/
  7745. {@t\1@>
  7746. /* More than one measurement existed. */
  7747. graphLines->value(tempcolumn)->append(segment);@t\2@>@/
  7748. }@/
  7749. else@/
  7750. {@/
  7751. /* This is the second measurement. */
  7752. QList<QGraphicsLineItem *> *newLine =
  7753. new QList<QGraphicsLineItem *>;@/
  7754. newLine->append(segment);
  7755. graphLines->insert(tempcolumn, newLine);
  7756. }@t\2@>@/
  7757. }@/
  7758. else@/
  7759. {@/
  7760. @<Handle the first measurement@>@;
  7761. }
  7762. }
  7763. @ There are some parts of the code that are correct, but seem somewhat goofy.
  7764. This is especially true surrounding the graphics view architecture as this was
  7765. not working correctly when I wrote the code that uses it. The code as it is
  7766. written works for me, but when these workarounds are no longer needed it would
  7767. be better to remove them. Handling values on the time axis is one example of
  7768. this.
  7769. Some might question the use of an integer data type, particularly when storing
  7770. the result of a division operation. While this could be a concern if high
  7771. resolution wall sized displays become common, is is expected that in most cases
  7772. with sufficiently high sample rates, many data points will map to the same pixel
  7773. even with the minor data loss below.
  7774. In the case of the first measurement,
  7775. @<Handle the first measurement@>=
  7776. int x = FULLTIMETOINT(measure.time())/1000;
  7777. prevPoints->insert(tempcolumn, QPointF(x, measure.temperature()));
  7778. if(timeIndicatorEnabled)
  7779. {
  7780. timeLine->setLine(x, 0, x, -500);
  7781. }
  7782. @ When at least one measurement already exists, we need to handle drawing the
  7783. line between the new measurement and the previous measurement.
  7784. \danger At present, the color chosen for these lines is based on the temperature
  7785. column passed to the graph. It would be better if colors could be passed to the
  7786. view for a specified series rather than have this hard coded. \endanger
  7787. @<At least one measurement exists@>=
  7788. QGraphicsLineItem *segment = new QGraphicsLineItem;
  7789. QPointF nextPoint(FULLTIMETOINT(measure.time())/1000, measure.temperature());
  7790. segment->setLine(prevPoints->value(tempcolumn).x() + offset,
  7791. -(prevPoints->value(tempcolumn).y()),
  7792. nextPoint.x() + offset, -(nextPoint.y()));
  7793. static QColor p[12] = {Qt::yellow, Qt::blue, Qt::cyan, Qt::red, Qt::magenta,
  7794. Qt::green, Qt::darkGreen, Qt::darkMagenta,
  7795. Qt::darkRed, Qt::darkCyan, Qt::darkBlue,
  7796. Qt::darkYellow};
  7797. segment->setPen(p[tempcolumn % 12]);
  7798. theScene->addItem(segment);
  7799. prevPoints->insert(tempcolumn, nextPoint);
  7800. if(timeIndicatorEnabled)
  7801. {
  7802. timeLine->setLine(nextPoint.x() + offset, 0, nextPoint.x() + offset, -500);
  7803. }
  7804. @ In addition to adding data to the view, we also sometimes want to clear the
  7805. view of data.
  7806. @<GraphView Implementation@>=
  7807. void GraphView::clear()
  7808. {
  7809. int i;
  7810. foreach(i, prevPoints->keys())
  7811. {
  7812. removeSeries(i);
  7813. }
  7814. translations->clear();
  7815. }
  7816. @ Removing a set of data from the view involves removing the lines from the
  7817. scene and removing the column from a couple data structures.
  7818. @<GraphView Implementation@>=
  7819. void GraphView::removeSeries(int column)
  7820. {
  7821. if(graphLines->contains(column))
  7822. {
  7823. QList<QGraphicsLineItem *> *series = graphLines->value(column);
  7824. QGraphicsLineItem *segment;
  7825. foreach(segment, *series)
  7826. {
  7827. theScene->removeItem(segment);
  7828. }
  7829. qDeleteAll(*series);
  7830. }
  7831. graphLines->remove(column);
  7832. prevPoints->remove(column);
  7833. }
  7834. @ Second prototype for data series translation.
  7835. @<GraphView Implementation@>=
  7836. void GraphView::setSeriesTranslation(int column, double offset)
  7837. {
  7838. if(graphLines->contains(column))
  7839. {
  7840. QList<QGraphicsLineItem *> *series = graphLines->value(column);
  7841. QGraphicsLineItem *segment;
  7842. foreach(segment, *series)
  7843. {
  7844. segment->setPos(segment->pos().x()+offset, segment->pos().y());
  7845. }
  7846. }
  7847. if(translations->contains(column))
  7848. {
  7849. translations->insert(column, offset + translations->value(column));
  7850. }
  7851. else
  7852. {
  7853. translations->insert(column, offset);
  7854. }
  7855. }
  7856. @ Starting in \pn{} 1.6 it is possible to add a vertical line indicating the
  7857. time position of the most recent measurement. This should be hidden for loading
  7858. target roast profiles and shown depending on preference. A new method controls
  7859. this.
  7860. @<GraphView Implementation@>=
  7861. void GraphView::setTimeIndicatorEnabled(bool enabled)
  7862. {
  7863. timeIndicatorEnabled = enabled;
  7864. if(enabled)
  7865. {
  7866. timeLine->show();
  7867. }
  7868. else
  7869. {
  7870. timeLine->hide();
  7871. }
  7872. }
  7873. @ These functions are required to create a |GraphView| object from a script.
  7874. @<Function prototypes for scripting@>=
  7875. void setGraphViewProperties(QScriptValue value, QScriptEngine *engine);
  7876. QScriptValue constructGraphView(QScriptContext *context, QScriptEngine *engine);
  7877. @ The scripting engine must be informed of the constructor.
  7878. @<Set up the scripting engine@>=
  7879. constructor = engine->newFunction(constructGraphView);
  7880. value = engine->newQMetaObject(&GraphView::staticMetaObject, constructor);
  7881. engine->globalObject().setProperty("GraphView", value);
  7882. @ The function implementation is trivial.
  7883. @<Functions for scripting@>=
  7884. QScriptValue constructGraphView(QScriptContext *, QScriptEngine *engine)
  7885. {
  7886. QScriptValue object = engine->newQObject(new GraphView);
  7887. setGraphViewProperties(object, engine);
  7888. return object;
  7889. }
  7890. void setGraphViewProperties(QScriptValue value, QScriptEngine *engine)
  7891. {
  7892. setQGraphicsViewProperties(value, engine);
  7893. }
  7894. @* A table of roasting data.
  7895. \noindent A typical roast log is a table listing temperature measurements taken
  7896. at regular intervals. The introduction of a computer brings several advantages.
  7897. A human does not need to record the measurements. Every measurement taken can be
  7898. logged, but the measurements do not all need to be displayed. The |ZoomLog|
  7899. class presents a table with time, temperature, and annotation for one or more
  7900. sets of roasting data and allows the user to select from a few different levels
  7901. of detail.
  7902. Experience has shown that one measurement every 30 or 15 seconds is most useful,
  7903. but it is also possible to view one measurement every 1, 5, 10, or 60 seconds
  7904. and there is an option to view every measurement collected. This last is what is
  7905. saved to a file.
  7906. The zooming log is implemented by keeping a measurement model with every level
  7907. of detail of interest and making sure that new measurements get to the models
  7908. they belong in. Switching the level of detail of the view then becomes a matter
  7909. of changing which model the view is using. This is very inefficient in terms of
  7910. space, but it is very fast and simple to code.
  7911. Starting in version 1.4, column sizes are persisted automatically using the
  7912. same method as described in the section on |SqlQueryView|.
  7913. @<Class declarations@>=
  7914. class MeasurementModel;@/
  7915. class ZoomLog : public QTableView@/
  7916. {@/
  7917. @[Q_OBJECT@]@;
  7918. @<ZoomLog private member data@>@;
  7919. void switchLOD(MeasurementModel *m);@/
  7920. @[private slots@]:@/
  7921. void centerOn(int row);
  7922. void persistColumnResize(int column, int oldsize, int newsize);
  7923. void restoreColumnWidths();
  7924. public:@/
  7925. ZoomLog();
  7926. QVariant data(int row, int column) const;
  7927. int rowCount();
  7928. bool saveXML(QIODevice *device);
  7929. bool saveCSV(QIODevice *device);
  7930. QString lastTime(int series);
  7931. @[Q_INVOKABLE@,@, Units::Unit displayUnits()@];@t\2\2@>@/
  7932. @[public slots@]:@/
  7933. void setVisible(bool visibility);
  7934. void setHeaderData(int section, QString text);
  7935. void LOD_ms();
  7936. void LOD_1s();
  7937. void LOD_5s();
  7938. void LOD_10s();
  7939. void LOD_15s();
  7940. void LOD_30s();
  7941. void LOD_1m();
  7942. void newMeasurement(Measurement measure, int tempcolumn);
  7943. void newAnnotation(QString annotation, int tempcolumn,
  7944. int annotationcolumn);
  7945. void clear();
  7946. void addOutputTemperatureColumn(int column);
  7947. void addOutputControlColumn(int column);
  7948. void addOutputAnnotationColumn(int column);
  7949. void clearOutputColumns();
  7950. void setDisplayUnits(Units::Unit scale);
  7951. void addToCurrentColumnSet(int column);
  7952. void clearCurrentColumnSet();@/
  7953. protected:@/
  7954. virtual void showEvent(QShowEvent *event);
  7955. };
  7956. @ This class uses a different model for each level of detail and provides logic
  7957. for placing measurements and annotations in the appropriate models. A list of
  7958. each model is provided for conveniently performing operations that apply to
  7959. every model.
  7960. @<ZoomLog private member data@>=
  7961. MeasurementModel *model_ms;
  7962. MeasurementModel *model_1s;
  7963. MeasurementModel *model_5s;
  7964. MeasurementModel *model_10s;
  7965. MeasurementModel *model_15s;
  7966. MeasurementModel *model_30s;
  7967. MeasurementModel *model_1m;
  7968. QList<MeasurementModel *> modelSet;
  7969. QHash<int, Measurement> lastMeasurement;
  7970. MeasurementModel *currentModel;
  7971. QList<int> saveTempCols;
  7972. QList<int> saveControlCols;
  7973. QList<int> saveNoteCols;
  7974. QList<int> currentColumnSet;
  7975. @ Most of the functionality this class provides is in getting measurements to
  7976. the right models. Every measurement goes to the full detail model. We also keep
  7977. track of the most recent measurement to detect the first measurement in a new
  7978. second and pass all of these on to the 1 second level of detail model. Some of
  7979. these are also passed to other models. Additionally, the models that store
  7980. coarser data strip the millisecond portion of the time.
  7981. A decision was made to present data promptly. With a high sample rate, some
  7982. might prefer an average of a few measurements near the reported time, but such
  7983. a feature does not exist in \pn{} currently.
  7984. The first measurement is always added to each model.
  7985. @<ZoomLog Implementation@>=
  7986. void ZoomLog::newMeasurement(Measurement measure, int tempcolumn)
  7987. {
  7988. if(measure.time() != QTime(0, 0, 0, 0))
  7989. {
  7990. @<Synthesize measurements for slow hardware@>@;
  7991. }
  7992. model_ms->newMeasurement(measure, tempcolumn);
  7993. if(lastMeasurement.contains(tempcolumn))
  7994. {
  7995. if(measure.time().second() !=
  7996. lastMeasurement.value(tempcolumn).time().second())
  7997. {
  7998. Measurement adjusted = measure;
  7999. QTime adjtime(0, measure.time().minute(), measure.time().second(), 0);
  8000. adjusted.setTime(adjtime);
  8001. model_1s->newMeasurement(adjusted, tempcolumn);
  8002. if(adjusted.time().second() % 5 == 0)
  8003. {
  8004. model_5s->newMeasurement(adjusted, tempcolumn);
  8005. if(adjusted.time().second() % 10 == 0)
  8006. {
  8007. model_10s->newMeasurement(adjusted, tempcolumn);
  8008. }
  8009. if(adjusted.time().second() % 15 == 0)
  8010. {
  8011. model_15s->newMeasurement(adjusted, tempcolumn);
  8012. if(adjusted.time().second() % 30 == 0)
  8013. {
  8014. model_30s->newMeasurement(adjusted, tempcolumn);
  8015. if(adjusted.time().second() == 0)
  8016. {
  8017. model_1m->newMeasurement(adjusted, tempcolumn);
  8018. }
  8019. }
  8020. }
  8021. }
  8022. }
  8023. @<Synthesize measurements for columns in set@>@;
  8024. }
  8025. else
  8026. {
  8027. @<Add the first measurement to every model@>@;
  8028. }
  8029. lastMeasurement.insert(tempcolumn, measure);
  8030. }
  8031. @ The first measurement in a series should be the epoch measurement. This
  8032. should exist in every level of detail.
  8033. @<Add the first measurement to every model@>=
  8034. MeasurementModel *m;
  8035. foreach(m, modelSet)
  8036. {
  8037. m->newMeasurement(measure, tempcolumn);
  8038. }
  8039. @ Some measurement hardware in use cannot guarantee delivery of at least one
  8040. measurement per second. This causes problems for the current |ZoomLog|
  8041. implementation as, for example, if there is no measurement at a time where
  8042. the seconds are divisible by 5, there will be no entry in that view. This can
  8043. result in situations where the |ZoomLog| at its default view of one measurement
  8044. every 30 seconds might not display any data at all aside from the first
  8045. measurement, the last measurement, and any measurement that happens to have an
  8046. annotation associated with it. The solution in this case is to synthesize
  8047. measurements so that the |ZoomLog| thinks it gets at least one measurement
  8048. every second.
  8049. The current approach simply replicates the last measurement every second until
  8050. the time for the most recent measurement is reached, however it would likely be
  8051. better to interpolate values between the two most recent real measurements as
  8052. this would match the graphic representation rather than altering it when later
  8053. reviewing the batch.
  8054. @<Synthesize measurements for slow hardware@>=
  8055. if(lastMeasurement.contains(tempcolumn))
  8056. {
  8057. if(lastMeasurement[tempcolumn].time() < measure.time())
  8058. {
  8059. QList<QTime> timelist;
  8060. for(QTime i = lastMeasurement.value(tempcolumn).time().addSecs(1); i < measure.time(); i = i.addSecs(1))
  8061. {
  8062. timelist.append(i);
  8063. }
  8064. for(int i = 0; i < timelist.size(); i++)
  8065. {
  8066. Measurement synthesized = measure;
  8067. synthesized.setTime(timelist[i]);
  8068. newMeasurement(synthesized, tempcolumn);
  8069. }
  8070. }
  8071. }
  8072. @ New to \pn{} 1.4 is the concept of a current column set. This was added to
  8073. improve support for devices where measurements on different data series may not
  8074. arrive at exactly the same time and for multi-device configurations where
  8075. measurements from different devices are unlikely to arrive at the same time.
  8076. This can cause issues with log annotations and serialization. The solution is
  8077. to group all columns that are logically part of the same data acquisition
  8078. process and as measurements come in, the most recent measurement from other
  8079. columns can be duplicated at the new time. Two methods are responsible for
  8080. managing this measurement set. One adds a column to the set and the other
  8081. removes all columns from the set.
  8082. @<ZoomLog Implementation@>=
  8083. void ZoomLog::addToCurrentColumnSet(int column)
  8084. {
  8085. currentColumnSet.append(column);
  8086. }
  8087. void ZoomLog::clearCurrentColumnSet()
  8088. {
  8089. currentColumnSet.clear();
  8090. }
  8091. @ Replicating the measurements occurs as measurements are delivered. Note
  8092. that this code will not be called for the first measurement in each column.
  8093. @<Synthesize measurements for columns in set@>=
  8094. if(currentColumnSet.contains(tempcolumn))
  8095. {
  8096. int replicationcolumn;
  8097. foreach(replicationcolumn, currentColumnSet)
  8098. {
  8099. if(replicationcolumn != tempcolumn)
  8100. {
  8101. if(lastMeasurement.contains(replicationcolumn))
  8102. {
  8103. if(measure.time() > lastMeasurement.value(replicationcolumn).time())
  8104. {
  8105. Measurement synthetic = lastMeasurement.value(replicationcolumn);
  8106. synthetic.setTime(measure.time());
  8107. model_ms->newMeasurement(synthetic, replicationcolumn);
  8108. if(synthetic.time().second() != lastMeasurement.value(replicationcolumn).time().second())@/
  8109. {
  8110. Measurement adjusted = synthetic;
  8111. adjusted.setTime(QTime(0, synthetic.time().minute(), synthetic.time().second(), 0));
  8112. model_1s->newMeasurement(adjusted, replicationcolumn);
  8113. if(adjusted.time().second() % 5 == 0)
  8114. {
  8115. model_5s->newMeasurement(adjusted, replicationcolumn);
  8116. if(adjusted.time().second() % 10 == 0)
  8117. {
  8118. model_10s->newMeasurement(adjusted, replicationcolumn);
  8119. }
  8120. if(adjusted.time().second() % 15 == 0)
  8121. {
  8122. model_15s->newMeasurement(adjusted, replicationcolumn);
  8123. if(adjusted.time().second() % 30 == 0)
  8124. {
  8125. model_30s->newMeasurement(adjusted, replicationcolumn);
  8126. if(adjusted.time().second() == 0)
  8127. {
  8128. model_1m->newMeasurement(adjusted, replicationcolumn);
  8129. }
  8130. }
  8131. }
  8132. }
  8133. }
  8134. lastMeasurement[replicationcolumn] = synthetic;
  8135. }
  8136. }
  8137. }
  8138. }
  8139. }
  8140. @ Just as the first measurement should exist at every level of detail, so should
  8141. any annotations. The measurement models will, when presented with an annotation,
  8142. apply it to the most recently entered measurement in the specified data series.
  8143. This presents a problem for the coarser views as the data point the annotation
  8144. belongs to most likely does not exist in that view. Furthermore, the model as it
  8145. is currently written will overwrite annotations that already exist on a
  8146. measurement if it is still the most recently entered. When collecting samples
  8147. during profile development, it is common to produce several annotations in a
  8148. short amount of time. The most useful thing to do in such a case is to add the
  8149. most recent measurement to each model and then apply the annotation. This, of
  8150. course, should only be done if there is a most recent measurement. An annotation
  8151. regarding the starting condition of the roaster should apply to the yet to be
  8152. recorded time zero measurement.
  8153. Note that only the value from the temperature column specified is displayed in
  8154. the row with the annotation. It would be better to check the full detail model
  8155. to determine if there are other measurements at the annotation time and present
  8156. these as well. Another possibility in the case of data not existing in other
  8157. temperature columns would be to interpolate a value from the existing data in
  8158. these columns, however this is potentially challenging as I would want to keep
  8159. true measurements distinct from estimations.
  8160. @<ZoomLog Implementation@>=
  8161. void ZoomLog::newAnnotation(QString annotation, int tempcolumn,
  8162. int annotationcolumn)
  8163. {
  8164. model_ms->newAnnotation(annotation, tempcolumn, annotationcolumn);
  8165. MeasurementModel *m;
  8166. if(lastMeasurement.contains(tempcolumn))
  8167. {
  8168. foreach(m, modelSet)
  8169. {
  8170. m->newMeasurement(lastMeasurement.value(tempcolumn), tempcolumn);
  8171. }
  8172. }
  8173. foreach(m, modelSet)
  8174. {
  8175. m->newAnnotation(annotation, tempcolumn, annotationcolumn);
  8176. }
  8177. }
  8178. @ As measurements are added to the model, the model will emit rowChanged
  8179. signals. These signals are connected to a function here that will attempt to
  8180. scroll the view to keep the most recently entered data in the center of the
  8181. view.
  8182. @<ZoomLog Implementation@>=
  8183. void ZoomLog::centerOn(int row)
  8184. {
  8185. scrollTo(currentModel->index(row, 0), QAbstractItemView::PositionAtCenter);
  8186. }
  8187. @ Once we are done with the data in the table, we want to clear it to prepare
  8188. for new data. This also clears the lists holding the output columns to use when
  8189. saving data.
  8190. @<ZoomLog Implementation@>=
  8191. void ZoomLog::clear()
  8192. {
  8193. MeasurementModel *m;
  8194. foreach(m, modelSet)
  8195. {
  8196. m->clear();
  8197. }
  8198. lastMeasurement.clear();
  8199. saveTempCols.clear();
  8200. saveControlCols.clear();
  8201. saveNoteCols.clear();
  8202. }
  8203. @ These are depreciated methods originally written to assist in serializing
  8204. model data prior to the introduction of the |XMLOutput| class. These methods are
  8205. likely to be removed in a future version of the program.
  8206. @<ZoomLog Implementation@>=
  8207. QVariant ZoomLog::data(int row, int column) const
  8208. {
  8209. return model_ms->data(model_ms->index(row, column, QModelIndex()),
  8210. Qt::DisplayRole);
  8211. }
  8212. int ZoomLog::rowCount()
  8213. {
  8214. return model_ms->rowCount();
  8215. }
  8216. @ This method initializes an |XMLOutput| instance, passes the columns that we
  8217. would like to save to that object, and uses it to write an XML file with the
  8218. desired data to the specified device.
  8219. Since the output format does not currently specify a unit, there is an
  8220. assumption that the XML output will always have measurements in Fahrenheit. If
  8221. the model is not currently displaying measurements in Fahrenheit, it is asked to
  8222. do so before writing the XML data. User preference is restored after the XML
  8223. data has been written. Since this change is only performed on |model_ms|, most
  8224. users will never notice this.
  8225. @<ZoomLog Implementation@>=
  8226. bool ZoomLog::saveXML(QIODevice *device)
  8227. {
  8228. Units::Unit prevUnits = model_ms->displayUnits();
  8229. if(prevUnits != Units::Fahrenheit)
  8230. {
  8231. model_ms->setDisplayUnits(Units::Fahrenheit);
  8232. }
  8233. XMLOutput writer(model_ms, device, 0);
  8234. int c;
  8235. foreach(c, saveTempCols)
  8236. {
  8237. writer.addTemperatureColumn(model_ms->headerData(c, Qt::Horizontal).
  8238. toString(), c);
  8239. }
  8240. foreach(c, saveControlCols)
  8241. {
  8242. writer.addControlColumn(model_ms->headerData(c, Qt::Horizontal).
  8243. toString(), c);
  8244. }
  8245. foreach(c, saveNoteCols)
  8246. {
  8247. writer.addAnnotationColumn(model_ms->headerData(c, Qt::Horizontal).
  8248. toString(), c);
  8249. }
  8250. bool retval = writer.output();
  8251. if(prevUnits != Units::Fahrenheit)
  8252. {
  8253. model_ms->setDisplayUnits(prevUnits);
  8254. }
  8255. return retval;
  8256. }
  8257. @ This method is similar to |saveXML()|. The main difference is that CSV data is
  8258. exported instead of XML.
  8259. @<ZoomLog Implementation@>=
  8260. bool ZoomLog::saveCSV(QIODevice *device)
  8261. {
  8262. CSVOutput writer(currentModel, device, 0);
  8263. int c;
  8264. foreach(c, saveTempCols)
  8265. {
  8266. writer.addTemperatureColumn(model_ms->headerData(c, Qt::Horizontal).
  8267. toString(), c);
  8268. }
  8269. foreach(c, saveControlCols)
  8270. {
  8271. writer.addControlColumn(model_ms->headerData(c, Qt::Horizontal).
  8272. toString(), c);
  8273. }
  8274. foreach(c, saveNoteCols)
  8275. {
  8276. writer.addAnnotationColumn(model_ms->headerData(c, Qt::Horizontal).
  8277. toString(), c);
  8278. }
  8279. return writer.output();
  8280. }
  8281. @ Several little functions, all alike\nfnote{If you get the reference, you may
  8282. enjoy reading another \cweb{} program:\par\indent\pdfURL{%
  8283. http://www-cs-staff.stanford.edu/$\sim$uno/programs/advent.w.gz}
  8284. {http://www-cs-staff.stanford.edu/~uno/programs/advent.w.gz}}, are used to
  8285. switch the view from one level of detail to another.
  8286. @<ZoomLog Implementation@>=
  8287. void ZoomLog::switchLOD(MeasurementModel *m)
  8288. {
  8289. disconnect(currentModel, SIGNAL(rowChanged(int)), this, 0);
  8290. setModel(m);
  8291. currentModel = m;
  8292. connect(currentModel, SIGNAL(rowChanged(int)), this, SLOT(centerOn(int)));
  8293. }
  8294. void ZoomLog::LOD_ms()
  8295. {
  8296. switchLOD(model_ms);
  8297. }
  8298. void ZoomLog::LOD_1s()
  8299. {
  8300. switchLOD(model_1s);
  8301. }
  8302. void ZoomLog::LOD_5s()
  8303. {
  8304. switchLOD(model_5s);
  8305. }
  8306. void ZoomLog::LOD_10s()
  8307. {
  8308. switchLOD(model_10s);
  8309. }
  8310. void ZoomLog::LOD_15s()
  8311. {
  8312. switchLOD(model_15s);
  8313. }
  8314. void ZoomLog::LOD_30s()
  8315. {
  8316. switchLOD(model_30s);
  8317. }
  8318. void ZoomLog::LOD_1m()
  8319. {
  8320. switchLOD(model_1m);
  8321. }
  8322. @ It can be useful to display temperature measurements in various units. To do
  8323. so, we simply tell all of the models which unit to provide data in. It is also
  8324. possible to obtain the currently selected unit.
  8325. @<ZoomLog Implementation@>=
  8326. void ZoomLog::setDisplayUnits(Units::Unit scale)
  8327. {
  8328. model_ms->setDisplayUnits(scale);
  8329. model_1s->setDisplayUnits(scale);
  8330. model_5s->setDisplayUnits(scale);
  8331. model_10s->setDisplayUnits(scale);
  8332. model_15s->setDisplayUnits(scale);
  8333. model_30s->setDisplayUnits(scale);
  8334. model_1m->setDisplayUnits(scale);
  8335. }
  8336. Units::Unit ZoomLog::displayUnits()
  8337. {
  8338. return model_ms->displayUnits();
  8339. }
  8340. @ For convenience, a method is provided for returning a string containing the
  8341. time of the last inserted measurement in a given data series.
  8342. @<ZoomLog Implementation@>=
  8343. QString ZoomLog::lastTime(int series)
  8344. {
  8345. Measurement measure = lastMeasurement.value(series);
  8346. QTime time = measure.time();
  8347. return time.toString("h:mm:ss.zzz");
  8348. }
  8349. @ This just leaves the initial table setup.
  8350. @<ZoomLog Implementation@>=
  8351. ZoomLog::ZoomLog() : QTableView(NULL), model_ms(new MeasurementModel(this)),
  8352. model_1s(new MeasurementModel(this)),@/ model_5s(new MeasurementModel(this)),
  8353. model_10s(new MeasurementModel(this)),@/ model_15s(new MeasurementModel(this)),
  8354. model_30s(new MeasurementModel(this)),@/ model_1m(new MeasurementModel(this))@/
  8355. {@/
  8356. setEditTriggers(QAbstractItemView::NoEditTriggers);
  8357. setSelectionMode(QAbstractItemView::NoSelection);
  8358. modelSet << model_ms << model_1s << model_5s << model_10s << model_15s <<
  8359. model_30s << model_1m;
  8360. currentModel = model_30s;
  8361. setModel(currentModel);
  8362. connect(currentModel, SIGNAL(rowChanged(int)), this, SLOT(centerOn(int)));
  8363. connect(horizontalHeader(), SIGNAL(sectionResized(int, int, int)),
  8364. this, SLOT(persistColumnResize(int, int, int)));
  8365. connect(horizontalHeader(), SIGNAL(sectionCountChanged(int, int)),
  8366. this, SLOT(restoreColumnWidths()));
  8367. }
  8368. @ A new method was added to this class for version 1.0.7. This allows header
  8369. data to be set on the log and have it propagate to the model set. The longer
  8370. term plan involves removing the hard coding of some of the header data.
  8371. @<ZoomLog Implementation@>=
  8372. void ZoomLog::setHeaderData(int section, QString text)
  8373. {
  8374. MeasurementModel *m;
  8375. foreach(m, modelSet)
  8376. {
  8377. m->setHeaderData(section, Qt::Horizontal, QVariant(text));
  8378. }
  8379. }
  8380. @ As of version 1.2.3, these methods replace similar methods added for version
  8381. 1.0.8. The main difference is that it is now possible to save multiple data
  8382. series to the same output document.
  8383. Starting in version 1.6 it is possible to save control columns. These should
  8384. contain unitless data which should remain unaffected by the current displayed
  8385. unit.
  8386. @<ZoomLog Implementation@>=
  8387. void ZoomLog::addOutputTemperatureColumn(int column)
  8388. {
  8389. saveTempCols.append(column);
  8390. }
  8391. void ZoomLog::addOutputControlColumn(int column)
  8392. {
  8393. saveControlCols.append(column);
  8394. }
  8395. void ZoomLog::addOutputAnnotationColumn(int column)
  8396. {
  8397. saveNoteCols.append(column);
  8398. }
  8399. void ZoomLog::clearOutputColumns()
  8400. {
  8401. saveTempCols.clear();
  8402. saveControlCols.clear();
  8403. saveNoteCols.clear();
  8404. }
  8405. @ Starting in version 1.4 two methods have been introduced which are used to
  8406. save and restore column widths.
  8407. @<ZoomLog Implementation@>=
  8408. void ZoomLog::persistColumnResize(int column, int, int newsize)
  8409. {
  8410. @<Save updated column size@>@;
  8411. }
  8412. void ZoomLog::restoreColumnWidths()
  8413. {
  8414. @<Restore table column widths@>@;
  8415. }
  8416. void ZoomLog::setVisible(bool visibility)
  8417. {
  8418. QTableView::setVisible(visibility);
  8419. }
  8420. void ZoomLog::showEvent(QShowEvent *)
  8421. {
  8422. @<Restore table column widths@>@;
  8423. }
  8424. @ The |ZoomLog| class is one of the more complicated classes to expose to the
  8425. scripting engine. In addition to a script constructor, we also need functions
  8426. for saving and restoring the state of the display and functions for saving data
  8427. from the log in the supported formats.
  8428. @<Function prototypes for scripting@>=
  8429. void setZoomLogProperties(QScriptValue value, QScriptEngine *engine);
  8430. QScriptValue constructZoomLog(QScriptContext *context, QScriptEngine *engine);
  8431. QScriptValue ZoomLog_saveXML(QScriptContext *context, QScriptEngine *engine);
  8432. QScriptValue ZoomLog_saveCSV(QScriptContext *context, QScriptEngine *engine);
  8433. QScriptValue ZoomLog_saveState(QScriptContext *context, QScriptEngine *engine);
  8434. QScriptValue ZoomLog_restoreState(QScriptContext *context,
  8435. QScriptEngine *engine);
  8436. QScriptValue ZoomLog_lastTime(QScriptContext *context, QScriptEngine *engine);
  8437. QScriptValue ZoomLog_saveTemporary(QScriptContext *context,
  8438. QScriptEngine *engnie);
  8439. QScriptValue ZoomLog_setDisplayUnits(QScriptContext *context,
  8440. QScriptEngine *engine);
  8441. @ Of these, the global object only needs to know about the constructor.
  8442. @<Set up the scripting engine@>=
  8443. constructor = engine->newFunction(constructZoomLog);
  8444. value = engine->newQMetaObject(&ZoomLog::staticMetaObject, constructor);
  8445. engine->globalObject().setProperty("ZoomLog", value);
  8446. @ The script constructor sets properties on the newly created object to allow
  8447. the other functions to be called.
  8448. @<Functions for scripting@>=
  8449. QScriptValue constructZoomLog(QScriptContext *, QScriptEngine *engine)@/
  8450. {@/
  8451. QScriptValue object = engine->newQObject(new ZoomLog);
  8452. setZoomLogProperties(object, engine);
  8453. return object;@/
  8454. }
  8455. void setZoomLogProperties(QScriptValue value, QScriptEngine *engine)
  8456. {
  8457. setQTableViewProperties(value, engine);
  8458. value.setProperty("saveXML", engine->newFunction(ZoomLog_saveXML));
  8459. value.setProperty("saveCSV", engine->newFunction(ZoomLog_saveCSV));
  8460. value.setProperty("saveState", engine->newFunction(ZoomLog_saveState));
  8461. value.setProperty("restoreState",
  8462. engine->newFunction(ZoomLog_restoreState));
  8463. value.setProperty("lastTime", engine->newFunction(ZoomLog_lastTime));
  8464. value.setProperty("saveTemporary",
  8465. engine->newFunction(ZoomLog_saveTemporary));
  8466. value.setProperty("setDisplayUnits", engine->newFunction(ZoomLog_setDisplayUnits));
  8467. }
  8468. @ The functions for saving data are simple wrappers around the corresponding
  8469. calls in |ZoomLog|, except for a function added for saving data to a temporary
  8470. file. The last provides the name of the file saved for use in copying that data
  8471. to a database entry.
  8472. @<Functions for scripting@>=
  8473. QScriptValue ZoomLog_saveXML(QScriptContext *context, QScriptEngine *engine)
  8474. {
  8475. ZoomLog *self = getself<ZoomLog *>(context);
  8476. bool retval = self->saveXML(argument<QIODevice *>(0, context));
  8477. return QScriptValue(engine, retval);
  8478. }
  8479. QScriptValue ZoomLog_saveCSV(QScriptContext *context, QScriptEngine *engine)
  8480. {
  8481. ZoomLog *self = getself<ZoomLog *>(context);
  8482. bool retval = self->saveCSV(argument<QIODevice *>(0, context));
  8483. return QScriptValue(engine, retval);
  8484. }
  8485. QScriptValue ZoomLog_saveTemporary(QScriptContext *context,
  8486. QScriptEngine *engine)
  8487. {
  8488. ZoomLog *self = getself<ZoomLog *>(context);
  8489. QString filename = QDir::tempPath();
  8490. filename.append("/");
  8491. filename.append(QUuid::createUuid().toString());
  8492. filename.append(".xml");
  8493. QFile *file = new QFile(filename);
  8494. self->saveXML(file);
  8495. file->close();
  8496. delete file;
  8497. return QScriptValue(engine, filename);
  8498. }
  8499. @ The remaining functions are convenience functions for use with the scripting
  8500. engine. One will save the column widths to a |QSettings| object. Another will
  8501. restore the column widths from settings. Finally, there is a function for
  8502. obtaining a string representation of the most recent measurement from a data
  8503. series.
  8504. \danger There are a couple of problems with these functions. First, the body of
  8505. these functions would probably be better off as methods in the |ZoomLog| class
  8506. proper, either as slots or |Q_INVOKABLE| so the special scripting functions
  8507. could be eliminated. Second, rather than polluting the settings with separate
  8508. entries for each column, it would probably be better to store all of these
  8509. values in an array.\endanger
  8510. |ZoomLog_saveState()| was changed in version 1.2.3 to not save a new value for
  8511. the column width if that width is |0|. This was done mainly to ease debugging.
  8512. Similarly, |ZoomLog_restoreState()| picks a new default value when |0| is
  8513. encountered.
  8514. @<Functions for scripting@>=
  8515. QScriptValue ZoomLog_saveState(QScriptContext *context, QScriptEngine *)
  8516. {
  8517. ZoomLog *self = getself<@[ZoomLog *@]>(context);
  8518. QString key = argument<QString>(0, context);
  8519. int columns = argument<int>(1, context);
  8520. QSettings settings;
  8521. for(int i = 0; i < columns; i++)
  8522. {
  8523. if(self->columnWidth(i))
  8524. {
  8525. settings.beginGroup(key);
  8526. settings.setValue(QString("%1").arg(i), self->columnWidth(i));
  8527. settings.endGroup();
  8528. }
  8529. }
  8530. return QScriptValue();
  8531. }
  8532. QScriptValue ZoomLog_restoreState(QScriptContext *context, QScriptEngine *)
  8533. {
  8534. ZoomLog *self = getself<@[ZoomLog *@]>(context);
  8535. QString key = argument<QString>(0, context);
  8536. int columns = argument<int>(1, context);
  8537. QSettings settings;
  8538. for(int i = 0; i < columns; i++)
  8539. {
  8540. settings.beginGroup(key);
  8541. self->setColumnWidth(i,
  8542. settings.value(QString("%1").arg(i), 80).toInt());
  8543. if(settings.value(QString("%1").arg(i), 80).toInt() == 0)
  8544. {
  8545. self->setColumnWidth(i, 80);
  8546. }
  8547. settings.endGroup();
  8548. }
  8549. return QScriptValue();
  8550. }
  8551. QScriptValue ZoomLog_lastTime(QScriptContext *context, QScriptEngine *engine)
  8552. {
  8553. ZoomLog *self = getself<@[ZoomLog *@]>(context);
  8554. return QScriptValue(engine, self->lastTime(argument<int>(0, context)));
  8555. }
  8556. @ There seems to be a bad interaction when enumerated value types as used as
  8557. the argument to slot methods called through QtScript. Script code that attempts
  8558. to make use of the enumeration appears to get the value without any type
  8559. information. When attempting to use that value as an argument the meta-object
  8560. system cannot find an appropriate match and the script just hangs silently.
  8561. The solution is to wrap such methods in the script bindings and explicitly cast
  8562. the argument value to the enumerated type. This looks stupid but it works.
  8563. @<Functions for scripting@>=
  8564. QScriptValue ZoomLog_setDisplayUnits(QScriptContext *context, QScriptEngine *)
  8565. {
  8566. ZoomLog *self = getself<@[ZoomLog *@]>(context);
  8567. self->setDisplayUnits((Units::Unit)argument<int>(0, context));
  8568. return QScriptValue();
  8569. }
  8570. @* A model for roasting data.
  8571. \noindent Qt provides a tool called the model view architecture. This provides a
  8572. uniform interface allowing different types of model classes to work with
  8573. different types of view classes without either needing to know implementation
  8574. details of the other. \pn{} provides the |MeasurementModel| as a specialization
  8575. of |QAbstractItemModel| for use in this architecture.
  8576. @<Class declarations@>=
  8577. class MeasurementList;@/
  8578. class MeasurementModel : public QAbstractItemModel@/
  8579. {@t\1@>@/
  8580. Q_OBJECT@;
  8581. Units::Unit unit;
  8582. QList<MeasurementList *> *entries;
  8583. QStringList *hData;
  8584. int colcount;
  8585. QHash<int, int> *lastTemperature;
  8586. QList<MeasurementList *>::iterator@, lastInsertion;
  8587. QHash<int, bool> *controlColumns;
  8588. public:@/
  8589. MeasurementModel(QObject *parent = NULL);
  8590. ~MeasurementModel();
  8591. int rowCount(const QModelIndex &parent = QModelIndex()) const;
  8592. int columnCount(const QModelIndex &parent = QModelIndex()) const;
  8593. bool setHeaderData(int section, Qt::Orientation orientation,
  8594. const QVariant &value,@|int role = Qt::DisplayRole);
  8595. QVariant data(const QModelIndex &index, int role) const;
  8596. bool setData(const QModelIndex &index, const QVariant &value,
  8597. int role = Qt::EditRole);
  8598. Qt::ItemFlags flags(const QModelIndex &index) const;
  8599. QVariant headerData(int section, Qt::Orientation orientation,
  8600. int role = Qt::DisplayRole) const;
  8601. QModelIndex index(int row, int column,
  8602. const QModelIndex &parent = QModelIndex()) const;
  8603. QModelIndex parent(const QModelIndex &index) const;
  8604. Units::Unit displayUnits();@/
  8605. @t\4@>public slots@t\kern-3pt@>:@/
  8606. void newMeasurement(Measurement measure, int tempcolumn);
  8607. void newAnnotation(QString annotation, int tempcolumn,
  8608. int annotationColumn);
  8609. void clear();
  8610. void setDisplayUnits(Units::Unit scale);
  8611. signals:@/
  8612. void rowChanged(int);@t\2@>@/
  8613. }@t\kern-3pt@>;
  8614. @ The measurement model stores its data in a list of measurement lists. This
  8615. allows the model to store as many sets of data as needed. In order to keep
  8616. measurements in the model sorted by time, the measurement list adds two
  8617. comparison functions.
  8618. @<Class declarations@>=
  8619. class MeasurementList : public QVariantList@/
  8620. {@t\1@>@/
  8621. @t\4@>public:@/
  8622. bool operator<(const MeasurementList &other) const;
  8623. bool operator==(const MeasurementList &other) const;@t\2@>@/
  8624. }@t\kern-3pt@>;
  8625. @ The overload of |<| checks if the time in one list (always stored in the first
  8626. column) is less than the time stored in the second. The overload of |==| is used
  8627. in an optimization that allows us to skip the search procedure on model
  8628. insertion.
  8629. @<MeasurementModel Implementation@>=
  8630. bool MeasurementList::operator<(const MeasurementList &other) const
  8631. {
  8632. return this->first().toTime() < other.first().toTime();
  8633. }
  8634. bool MeasurementList::operator==(const MeasurementList &other) const
  8635. {
  8636. return this->first().toTime() == other.first().toTime();
  8637. }
  8638. @ The |MeasurementModel| class extends the |QAbstractItemModel| class to work
  8639. better with measurements and annotations that are passed around in \pn{}. Many
  8640. of the class methods are required because of that choice. For example, the
  8641. parent function which is never used directly:
  8642. @<MeasurementModel Implementation@>=
  8643. QModelIndex MeasurementModel::parent(const QModelIndex&) const
  8644. {
  8645. return QModelIndex();
  8646. }
  8647. @ Perhaps the most complicated part of this class is the code for dealing with a
  8648. new measurement. This is complicated by the requirement to insert measurements
  8649. while keeping the model sorted by time.
  8650. @<MeasurementModel Implementation@>=
  8651. void MeasurementModel::newMeasurement(Measurement measure, int tempcolumn)
  8652. {
  8653. if(measure.scale() == Units::Unitless)
  8654. {
  8655. controlColumns->insert(tempcolumn, true);
  8656. }
  8657. else
  8658. {
  8659. controlColumns->insert(tempcolumn, false);
  8660. }
  8661. MeasurementList *temp;
  8662. temp = new MeasurementList;
  8663. temp->append(QVariant(measure.time()));
  8664. @<Find the insertion point@>@;
  8665. MeasurementList *newEntry;
  8666. int insertion;
  8667. if(i != entries->end())
  8668. {
  8669. insertion = entries->indexOf(*i);
  8670. if((*i)->first().toTime() == measure.time())
  8671. {
  8672. @<Insert a new measurement at an existing time@>@;
  8673. }
  8674. else
  8675. {
  8676. @<Insert a new measurement somewhere else@>@;
  8677. }
  8678. }
  8679. else
  8680. {
  8681. @<Append a measurement@>@;
  8682. }
  8683. if(tempcolumn >= colcount)
  8684. {
  8685. colcount = tempcolumn + 1;
  8686. }
  8687. emit rowChanged(insertion);
  8688. delete temp;
  8689. }
  8690. @ To find the insertion point for new measurements we use a binary search of the
  8691. existing data. The code below is a direct adaptation of Program B\nfnote{%
  8692. \underbar{The Art of Computer Programming} Volume 3 Sorting and Searching 2nd
  8693. ed. (Knuth, 1997) Section 6.2.1: Searching an Ordered Table} modified to use
  8694. list iterators and control structures more familiar to \CPLUSPLUS/programmers
  8695. rather than {\mc MIX} machine codes. When the loop exits |i| is the insertion
  8696. point.
  8697. \medskip
  8698. \centerline{\includegraphics{search}}
  8699. \smallskip
  8700. \centerline{Figure \secno: Binary Search}
  8701. \medskip
  8702. @<Find the insertion point@>=
  8703. @<Scan from most recent insertion@>@;
  8704. if(quickscan == false)
  8705. {
  8706. i = entries->begin();
  8707. QList<MeasurementList *>::iterator@, u = entries->end();
  8708. QList<MeasurementList *>::iterator@, midpoint;
  8709. int n = u - i;
  8710. int rA;
  8711. while(n > 0)@/
  8712. {
  8713. rA = n>>1; /* |rA = |~$\bigl\lfloor{n\over2}\bigr\rfloor$ */
  8714. midpoint = i + rA;
  8715. if(**midpoint < *temp)@/
  8716. {
  8717. i = midpoint + 1;
  8718. n -= rA + 1;
  8719. }
  8720. else@/
  8721. {
  8722. n = rA;
  8723. }
  8724. }
  8725. }
  8726. @ The binary search, while correct, is not a particularly optimal choice for
  8727. this application. While the average running time for this is on the order of
  8728. $\ln N$ when each insertion point is equally likely, the reality of this
  8729. application is that insertions will likely be at the beginning of the list, at
  8730. the point of the most recent insertion, or a short distance from the most recent
  8731. insertion. By first considering the possibility that the measurement should be
  8732. inserted at or near the most recent measurement, shorter, more constant running
  8733. times as $N$ increases can be obtained.
  8734. To do this, when the number of measurements in the list is above a small number
  8735. which must be greater than 1, we check first if the insertion point is at the
  8736. last insertion (the |<| comparison fails and we do an |==| comparison before
  8737. giving up), then we check a small number of rows for either the end of the list,
  8738. in which case the insertion point is at the end, or for a point at which the |<|
  8739. comparison fails. If neither condition holds for a small number of comparisons
  8740. we resort to the binary search.
  8741. Performance measurements with this modification compared with previous versions
  8742. shows that this provides a huge performance boost.
  8743. @<Scan from most recent insertion@>=
  8744. @[QList<MeasurementList *>::iterator@, i@] = lastInsertion;@/
  8745. bool quickscan = false;@/
  8746. if(entries->size() > 5)@/
  8747. {@t\1@>@/
  8748. if(**i < *temp)@/
  8749. {@t\1@>@/
  8750. i += 1;@/
  8751. for(int j = 10; j > 0; j--)@/
  8752. {@t\1@>@/
  8753. if(i != entries->end())@/
  8754. {@t\1@>@/
  8755. if(**i < *temp)@/
  8756. {
  8757. i += 1;
  8758. }@/
  8759. else@/
  8760. {@t\1@>@/
  8761. quickscan = true;
  8762. break;@t\2@>@/
  8763. }@t\2@>@/
  8764. }@/
  8765. else@/
  8766. {@t\1@>@/
  8767. quickscan = true;
  8768. break;@t\2@>@/
  8769. }@t\2@>@/
  8770. }@t\2@>@/
  8771. }@/
  8772. else@/
  8773. {@t\1@>@/
  8774. if(**i == *temp)@/
  8775. {@t\1@>@/
  8776. quickscan = true;@t\2@>@/
  8777. }@t\2@>@/
  8778. }@t\2@>@/
  8779. }
  8780. @ If the chosen insertion point is at an existing time, we don'@q'@>t need to
  8781. worry about inserting rows. There may be a need to increase the size of the
  8782. measurement list to accept an entry in a new data series.
  8783. @<Insert a new measurement at an existing time@>=
  8784. if((*i)->size() < tempcolumn + 1)
  8785. {
  8786. for(int j = (*i)->size() - 1; j < tempcolumn + 1; j++)
  8787. {
  8788. (*i)->append(QVariant());
  8789. }
  8790. }
  8791. (*i)->replace(tempcolumn, measure);
  8792. lastInsertion = i;
  8793. emit dataChanged(createIndex(insertion, tempcolumn),
  8794. createIndex(insertion, tempcolumn));
  8795. lastTemperature->insert(tempcolumn, insertion);
  8796. @ If the measurement is not past the end of the existing data and the insertion
  8797. point has a different time, we need to use |beginInsertRows()| and
  8798. |endInsertRows()| to notify any attached view that a new row will be added.
  8799. @<Insert a new measurement somewhere else@>=
  8800. beginInsertRows(QModelIndex(), insertion, insertion);
  8801. newEntry = new MeasurementList;
  8802. newEntry->append(QVariant(measure.time()));
  8803. for(int j = 0; j < tempcolumn + 1; j++)
  8804. {
  8805. newEntry->append(QVariant());
  8806. }
  8807. newEntry->replace(tempcolumn, measure);
  8808. lastInsertion = entries->insert(i, newEntry);
  8809. endInsertRows();
  8810. lastTemperature->insert(tempcolumn, insertion);
  8811. @ If the insertion point is past the end of the existing data, a new row should
  8812. be appended to the data. This only needs to be a separate case to prevent the
  8813. comparison with a nonexistent entry. This is very similar to the case of
  8814. inserting at a new time anywhere else.
  8815. @<Append a measurement@>=
  8816. insertion = entries->size();@/
  8817. @<Insert a new measurement somewhere else@>
  8818. @ The other bit of code that'@q'@>s a little bit more complicated than other
  8819. parts of the class handles adding annotations to the data. Two signals are
  8820. emitted in this method. The |dataChanged| signal is expected by view classes
  8821. that can use this model. The |rowChanged| signal is used by |ZoomLog| to scroll
  8822. the view to the row the annotation has been added to. This is mainly useful
  8823. when loading a target profile and entering the first annotation prior to
  8824. starting the batch.
  8825. @<MeasurementModel Implementation@>=
  8826. void MeasurementModel::newAnnotation(QString annotation, int tempcolumn,@|
  8827. int annotationColumn)
  8828. {
  8829. int r;
  8830. if(lastTemperature->contains(tempcolumn))
  8831. {
  8832. r = lastTemperature->value(tempcolumn);
  8833. }
  8834. else
  8835. {
  8836. r = 0;
  8837. }
  8838. if(r == 0 && entries->size() == 0)
  8839. {
  8840. @<Create the first row@>@;
  8841. }
  8842. MeasurementList *row = entries->at(r);
  8843. if(row->size() <= annotationColumn)
  8844. {
  8845. for(int i = row->size() - 1; i < annotationColumn + 1; i++)
  8846. {
  8847. row->append(QVariant());
  8848. }
  8849. }
  8850. row->replace(annotationColumn, annotation);
  8851. emit dataChanged(createIndex(r, annotationColumn),
  8852. createIndex(r, annotationColumn));
  8853. emit rowChanged(r);
  8854. if(annotationColumn > colcount - 1)
  8855. {
  8856. colcount = annotationColumn + 1;
  8857. }
  8858. }
  8859. @ There is no need to further complicate the function by adding the annotation
  8860. when the first row is created.
  8861. @<Create the first row@>=
  8862. beginInsertRows(QModelIndex(), 0, 0);
  8863. MeasurementList *newEntry = new MeasurementList;
  8864. newEntry->append(QVariant(QTime(0, 0, 0, 0)));
  8865. entries->append(newEntry);
  8866. endInsertRows();
  8867. @ Clearing the model data is a simple matter of deleting every row, remembering
  8868. to let any attached views know that we are doing this, and resetting the number
  8869. of columns.
  8870. @<MeasurementModel Implementation@>=
  8871. void MeasurementModel::clear()
  8872. {
  8873. beginRemoveRows(QModelIndex(), 0, entries->size());
  8874. while(entries->size() != 0)
  8875. {
  8876. MeasurementList *row = entries->takeFirst();
  8877. delete row;
  8878. }
  8879. endRemoveRows();
  8880. colcount = hData->size();
  8881. lastTemperature->clear();
  8882. reset();
  8883. }
  8884. @ While these methods for adding measurements and annotations are fine when
  8885. recording a stream of measurements, either from the |DAQ| or when loading saved
  8886. data, there are also cases where we'@q'@>d like to edit the data in the model
  8887. directly from the table view. For this, we need to reimplement |setData()|.
  8888. Note that editing from the |ZoomLog| has never been supported. While stream
  8889. inserted data currently preserves all properties of inserted measurements,
  8890. using |setData| it is possible to insert a numeric value as if it were a
  8891. measurement. Such an entry will not have any additional information associated
  8892. and cannot be expected to exhibit behavior implemented through the use of that
  8893. extra information.
  8894. Very little input checking is done here. Editable views may want to place
  8895. delegates\nfnote{Qt 4.4: Delegate Classes\par\indent\hbox{%
  8896. \pdfURL{http://doc.trolltech.com/4.4/model-view-delegate.html}{%
  8897. http://doc.trolltech.com/4.4/model-view-delegate.html}}} on the columns to make
  8898. editing the data easier and less error prone.
  8899. @<MeasurementModel Implementation@>=
  8900. bool MeasurementModel::setData(const QModelIndex &index,
  8901. const QVariant &value, int role)@t\2\2@>@/
  8902. {@t\1@>@/
  8903. if(role != Qt::EditRole && role != Qt::DisplayRole)@/
  8904. {@t\1@>@/
  8905. return false;@t\2@>@/
  8906. }@/
  8907. @<Check that the index is valid@>@;
  8908. if(!valid)@/
  8909. {@t\1@>@/
  8910. return false;@t\2@>@/
  8911. }@/
  8912. MeasurementList *row = entries->at(index.row());
  8913. if(index.column() >= row->size())
  8914. {
  8915. @<Expand the row to prepare for new data@>@;
  8916. }
  8917. if(index.column() == 0)
  8918. {
  8919. @<Edit data in the time column@>@;
  8920. }
  8921. else
  8922. {
  8923. @<Edit data in other columns@>@;
  8924. }
  8925. return true;@t\2@>@/
  8926. }
  8927. @ There is no sense in attempting to edit the data if there isn'@q'@>t any data
  8928. available to edit. This check is also used when retrieving data from the model.
  8929. @<Check that the index is valid@>=
  8930. bool valid = false;
  8931. if(index.isValid())@/
  8932. {@t\1@>@/
  8933. if(index.row() < entries->size())@/
  8934. {@t\1@>@/
  8935. if(index.column() < colcount)@/
  8936. {@t\1@>@/
  8937. valid = true;@t\2@>@/
  8938. }@t\2@>@/
  8939. }@t\2@>@/
  8940. }
  8941. @ When editing data, there might not be anything where we want to add the data.
  8942. For example, adding an annotation to an otherwise unannotated measurement. This
  8943. is fine, but we need to expand the row instead of inserting data out of bounds.
  8944. @<Expand the row to prepare for new data@>=
  8945. for(int i = row->size() - 1; i < index.column(); i++)
  8946. {
  8947. row->append(QVariant());
  8948. }
  8949. @ Changing time data must be considered separately from other data. As the model
  8950. keeps itself sorted based on the time field, allowing the user to get the model
  8951. data out of order would result in poorly defined behavior later. Our approach is
  8952. to remove the row from the model temporarily then reuse the code from
  8953. |newMeasurement()| to find the new insertion point. No attempt is made to merge
  8954. the contents from two rows with identical times, but an attempt is made to not
  8955. be too rigid in what we expect the user to enter. If an invalid time is entered,
  8956. we give up and leave the data as we found it.
  8957. @<Edit data in the time column@>=
  8958. QTime time;@/
  8959. if(!(time = QTime::fromString(value.toString(), "m:s.z")).isValid())@/
  8960. {@t\1@>@/
  8961. if(!(time = QTime::fromString(value.toString(), "m:s")).isValid())@/
  8962. {@t\1@>@/
  8963. return false;@t\2@>@/
  8964. }@t\2@>@/
  8965. }@/
  8966. row = entries->takeAt(index.row());
  8967. row->replace(index.column(), QVariant(time));
  8968. MeasurementList *temp = row;
  8969. @<Find the insertion point@>@;
  8970. entries->insert(i, row);
  8971. int newRow = entries->indexOf(*i);
  8972. if(newRow < index.row())@/
  8973. {
  8974. emit dataChanged(createIndex(newRow, index.column()), index);
  8975. }
  8976. else@/
  8977. {
  8978. emit dataChanged(index, createIndex(newRow, index.column()));
  8979. }
  8980. @ Data in other columns is a little easier to handle.
  8981. @<Edit data in other columns@>=
  8982. row->replace(index.column(), value);
  8983. emit dataChanged(index, index);
  8984. @ As it has already been established that the first column is always considered
  8985. the time of the measurement, this assumption can be built into the model
  8986. constructor.
  8987. @<MeasurementModel Implementation@>=
  8988. MeasurementModel::MeasurementModel(QObject *parent) : QAbstractItemModel(parent),
  8989. unit(Units::Fahrenheit), hData(new QStringList),
  8990. lastTemperature(new QHash<int, int>),
  8991. controlColumns(new QHash<int, bool>)@/
  8992. {
  8993. colcount = 1;
  8994. entries = new QList<MeasurementList *>;
  8995. lastInsertion = entries->begin();
  8996. hData->append(tr("Time"));
  8997. }
  8998. @ In the destructor we need to remember to clean up after ourselves.
  8999. @<MeasurementModel Implementation@>=
  9000. MeasurementModel::~MeasurementModel()
  9001. {
  9002. clear();
  9003. delete entries;
  9004. delete hData;
  9005. }
  9006. @ A pair of functions are used to determine the number of rows and columns the
  9007. model provides. No entries in the model have children, so the parent should
  9008. always be the invisible root object. If it isn'@q'@>t, we should return 0.
  9009. @<MeasurementModel Implementation@>=
  9010. int MeasurementModel::rowCount(const QModelIndex &parent) const
  9011. {
  9012. if(parent == QModelIndex())
  9013. {
  9014. return entries->size();
  9015. }
  9016. return 0;
  9017. }
  9018. int MeasurementModel::columnCount(const QModelIndex &parent) const
  9019. {
  9020. if(parent == QModelIndex())
  9021. {
  9022. return colcount;
  9023. }
  9024. return 0;
  9025. }
  9026. @ The model maintains a set of header data. At present, it only supports header
  9027. data at the top of the model due to the author'@q'@>s preference to not have row
  9028. numbers littering the left of the table (the time column is sufficient to
  9029. identify the row for the user).
  9030. The model view architecture supports the concept of different data roles in the
  9031. header data. At present, this model ignores the role when setting header data.
  9032. @<MeasurementModel Implementation@>=
  9033. bool MeasurementModel::setHeaderData(int section, Qt::Orientation orientation,@|
  9034. const QVariant &value, int)@t\2@>@/
  9035. @t\4@>{@/
  9036. if(orientation == Qt::Horizontal)@/
  9037. {@t\1@>@/
  9038. if(hData->size() < section + 1)@/
  9039. {@/
  9040. for(int i = hData->size(); i < section + 1; i++)@/
  9041. {@/
  9042. if(colcount < i)@/
  9043. {@/
  9044. beginInsertColumns(QModelIndex(), i, i);
  9045. }
  9046. hData->append(QString());
  9047. if(colcount < i)@/
  9048. {@/
  9049. endInsertColumns();
  9050. }
  9051. }
  9052. }
  9053. hData->replace(section, value.toString());
  9054. emit headerDataChanged(orientation, section, section);
  9055. if(colcount < section + 1)@/
  9056. {@/
  9057. colcount = section + 1;
  9058. }@/
  9059. return true;@t\2@>@/
  9060. }@/
  9061. return false;@/
  9062. @t\4@>}
  9063. @ While the current implementation always receives measurements in degrees
  9064. Fahrenheit, international users often want to see data presented in Celsius. To
  9065. do this, a slot is provided to allow selecting among different units. When this
  9066. method is called, the model indicates that all attached views must update all
  9067. displayed data and requests for temperature data will have any needed conversion
  9068. performed before sending that information to the view. Another method is
  9069. available to request a number identifyin the currently displayed units.
  9070. @<MeasurementModel Implementation@>=
  9071. void MeasurementModel::setDisplayUnits(Units::Unit scale)
  9072. {
  9073. beginResetModel();
  9074. unit = scale;
  9075. endResetModel();
  9076. }
  9077. Units::Unit MeasurementModel::displayUnits()
  9078. {
  9079. return unit;
  9080. }
  9081. @ A model is generally quite useless if the data the model contains cannot be
  9082. retrieved. To do this, we check that the index requested is a valid index that
  9083. is within the bounds of the model data and that a role we understand has been
  9084. requested. If none of these conditions are met, a default constructed |QVariant|
  9085. is returned.
  9086. At present, |Qt::DisplayRole| and |Qt::EditRole| are supported. These return the
  9087. same thing. Views will request the display role for presenting the information
  9088. to the user, but they will request the edit role if the user attempts to modify
  9089. the data through a view.
  9090. As of version 1.6, |Qt::UserRole| allows retrieval of raw measurement data.
  9091. @<MeasurementModel Implementation@>=
  9092. QVariant MeasurementModel::data(const QModelIndex &index, int role) const@/
  9093. {@/
  9094. @<Check that the index is valid@>@;
  9095. if(!valid)
  9096. {
  9097. return QVariant();
  9098. }
  9099. MeasurementList *row = entries->at(index.row());
  9100. if(role == Qt::UserRole)
  9101. {
  9102. return QVariant(row->at(index.column()));
  9103. }
  9104. if(role == Qt::DisplayRole || role == Qt::EditRole)
  9105. {
  9106. if(index.column() > row->size())
  9107. {
  9108. return QVariant();
  9109. }
  9110. else
  9111. {
  9112. if(index.column() == 0)
  9113. {
  9114. return QVariant(row->at(0).toTime().toString("mm:ss.zzz"));
  9115. }
  9116. else if(lastTemperature->contains(index.column()))
  9117. {
  9118. QVariantMap v = row->at(index.column()).toMap();
  9119. if(!v.contains("measurement"))
  9120. {
  9121. return QVariant();
  9122. }
  9123. if((Units::Unit)(v.value("unit").toInt()) == Units::Unitless)
  9124. {
  9125. return v.value("measurement");
  9126. }
  9127. else
  9128. {
  9129. if(v.contains("relative"))
  9130. {
  9131. if(v.value("relative").toBool())
  9132. {
  9133. return QVariant(QString("%1").@|arg(Units::convertRelativeTemperature(v.value("measurement").
  9134. toDouble(),@| (Units::Unit)(v.value("unit").toInt()), unit)));
  9135. }
  9136. }
  9137. return QVariant(QString("%1").@|
  9138. arg(Units::convertTemperature(v.value("measurement").toDouble(),@|
  9139. (Units::Unit)(v.value("unit").toInt()), unit)));
  9140. }
  9141. }
  9142. return QVariant(row->at(index.column()).toString());
  9143. }
  9144. }
  9145. return QVariant();@/
  9146. }
  9147. @ Views also must be able to retrieve the header data.
  9148. @<MeasurementModel Implementation@>=
  9149. QVariant MeasurementModel::headerData(int section, Qt::Orientation orientation,
  9150. int role ) const
  9151. {
  9152. if(orientation == Qt::Horizontal)
  9153. {
  9154. if(role == Qt::DisplayRole)
  9155. {
  9156. if(section < hData->size())
  9157. {
  9158. return QVariant(hData->at(section));
  9159. }
  9160. }
  9161. }
  9162. return QVariant();
  9163. }
  9164. @ Views will sometimes request information about the interactions available for
  9165. an index. In the case of this model, each index is treated in the same way.
  9166. It may be a good idea to extend the model class to allow models that can be
  9167. edited through the view such as the table view presented in the |LogEditWindow|
  9168. and models that probably shouldn'@q'@>t be edited in the view, such as the models
  9169. managed by |ZoomLog|. This could be done by subclassing and only reimplementing
  9170. this method. Otherwise, a new method to specify that the user should not edit
  9171. the model could be provided and a flag would be checked here.
  9172. @<MeasurementModel Implementation@>=
  9173. Qt::ItemFlags MeasurementModel::flags(const QModelIndex &index) const@/
  9174. {@/
  9175. @<Check that the index is valid@>@;
  9176. if(valid)
  9177. {
  9178. return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable;
  9179. }
  9180. return 0;
  9181. }
  9182. @ Much of the way models are interacted with in Qt'@q'@>s model view architecture is
  9183. through model indices. The model is responsible for creating these indices from
  9184. row column pairs.
  9185. @<MeasurementModel Implementation@>=
  9186. QModelIndex MeasurementModel::index(int row, int column,
  9187. const QModelIndex &parent) const@t\2\2@>@/
  9188. {@t\1@>@/
  9189. if(parent == QModelIndex())@/
  9190. {@t\1@>@/
  9191. if(row < entries->size() && entries->isEmpty() == false)@/
  9192. {@/
  9193. if(column < entries->at(row)->size())@/
  9194. {@/
  9195. return createIndex(row, column);@/
  9196. }@/
  9197. }@t\2@>@/
  9198. }@/
  9199. return QModelIndex();@/
  9200. @t\4@>}
  9201. @** Annotating roast data.
  9202. \noindent In addition to recording time temperature pairs, \pn{} allows the user
  9203. to annotate the roasting log to indicate control changes, the end of the batch,
  9204. or samples collected from the roast. It is important that these annotations can
  9205. be applied to the roasting log quickly. This is the purpose of the
  9206. |AnnotationButton| class.
  9207. @<Class declarations@>=
  9208. class AnnotationButton : public QPushButton@/
  9209. {@t\1@>@/
  9210. Q_OBJECT@;
  9211. QString note;
  9212. int tc;
  9213. int ac;
  9214. int count;
  9215. public:@/
  9216. AnnotationButton(const QString &text, QWidget *parent = NULL);@/
  9217. @t\4@>public slots@t\kern-3pt@>:@/
  9218. void setAnnotation(const QString &annotation);
  9219. void setTemperatureColumn(int tempcolumn);
  9220. void setAnnotationColumn(int annotationcolumn);
  9221. void annotate();
  9222. void resetCount();
  9223. signals:@/
  9224. void annotation(QString annotation, int tempcolumn,
  9225. int notecolumn);@t\2@>@/
  9226. }@t\kern-3pt@>;
  9227. @ Setting up a new annotation button begins with the constructor. This takes a
  9228. string specifying the text that will appear on the button and optionally a
  9229. parent widget. This is also a sensible place to set up the desired behavior the
  9230. button should exhibit when clicked.
  9231. @<AnnotationButton Implementation@>=
  9232. AnnotationButton::AnnotationButton(const QString &text, QWidget *parent) :
  9233. QPushButton(text, parent), note(""), tc(0), ac(0), count(0)@/
  9234. {
  9235. connect(this, SIGNAL(clicked()), this, SLOT(annotate()));
  9236. }
  9237. @ The slot that is called when the button is clicked needs to be able to handle
  9238. two types of annotations. Simple annotations send the same annotation every time
  9239. the button is clicked. Counting annotations are annotation strings that have a
  9240. |"%1"| somewhere in the string. That substring will be replaced with an integer
  9241. that is incremented before the annotation is sent. This integer is initialized
  9242. to 0. It will be incremented to 1 the first time the button is clicked and that
  9243. will be the replacement value.
  9244. @<AnnotationButton Implementation@>=
  9245. void AnnotationButton::annotate()
  9246. {
  9247. if(note.contains("%1"))
  9248. {
  9249. count++;
  9250. emit annotation(note.arg(count), tc, ac);
  9251. }
  9252. else
  9253. {
  9254. emit annotation(note, tc, ac);
  9255. }
  9256. }
  9257. @ A few methods are available to indicate which temperature series the
  9258. annotation should be applied to, which column in a table view the annotation
  9259. should be entered in, and what text should be in the annotation.
  9260. @<AnnotationButton Implementation@>=
  9261. void AnnotationButton::setTemperatureColumn(int tempcolumn)
  9262. {
  9263. tc = tempcolumn;
  9264. }
  9265. void AnnotationButton::setAnnotationColumn(int annotationcolumn)
  9266. {
  9267. ac = annotationcolumn;
  9268. }
  9269. void AnnotationButton::setAnnotation(const QString &annotation)
  9270. {
  9271. note = annotation;
  9272. }
  9273. @ Finally, in the case of counting annotations, there should be a way to reset
  9274. the number used in the annotation.
  9275. @<AnnotationButton Implementation@>=
  9276. void AnnotationButton::resetCount()
  9277. {
  9278. count = 0;
  9279. }
  9280. @ A script constructor is needed to allow an |AnnotationButton| to be created
  9281. from a script.
  9282. @<Function prototypes for scripting@>=
  9283. QScriptValue constructAnnotationButton(QScriptContext *context,
  9284. QScriptEngine *engine);
  9285. void setAnnotationButtonProperties(QScriptValue value, QScriptEngine *engine);
  9286. @ In order to use this, the engine needs to be informed of the function.
  9287. @<Set up the scripting engine@>=
  9288. constructor = engine->newFunction(constructAnnotationButton);
  9289. value = engine->newQMetaObject(&AnnotationButton::staticMetaObject,
  9290. constructor);
  9291. engine->globalObject().setProperty("AnnotationButton", value);
  9292. @ The implementation is trivial.
  9293. @<Functions for scripting@>=
  9294. QScriptValue constructAnnotationButton(QScriptContext *context,
  9295. QScriptEngine *engine)
  9296. {
  9297. QScriptValue object =
  9298. engine->newQObject(new AnnotationButton(argument<QString>(0, context)));
  9299. setAnnotationButtonProperties(object, engine);
  9300. return object;
  9301. }
  9302. void setAnnotationButtonProperties(QScriptValue value, QScriptEngine *engine)
  9303. {
  9304. setQPushButtonProperties(value, engine);
  9305. }
  9306. @* A spin box for annotations.
  9307. \noindent While the annotation button is adequate for most log annotation tasks,
  9308. there are some times where the log should contain a small number of numerical
  9309. observations where it is inconvenient or cost prohibitive to enable automated
  9310. logging. For these tasks, a spin box that produces an appropriate annotation may
  9311. be useful.
  9312. @<Class declarations@>=
  9313. class AnnotationSpinBox : public QDoubleSpinBox@/
  9314. {@t\1@>@/
  9315. Q_OBJECT@;
  9316. QString pretext;
  9317. QString posttext;
  9318. int tc;
  9319. int ac;
  9320. bool change;
  9321. public:
  9322. AnnotationSpinBox(const QString &pret, const QString &postt,
  9323. QWidget *parent = NULL);@/
  9324. @t\4@>public slots@t\kern-3pt@>:@/
  9325. void setPretext(const QString &pret);
  9326. void setPosttext(const QString &postt);
  9327. void setTemperatureColumn(int tempcolumn);
  9328. void setAnnotationColumn(int annotationcolumn);
  9329. void annotate();
  9330. void resetChange();
  9331. signals:@/
  9332. void annotation(QString annotation, int tempcolumn,
  9333. int notecolumn);@t\2@>@/
  9334. }@t\kern-3pt@>;
  9335. @ Setting up a new annotation spin box begins with the constructor. This takes
  9336. two strings specifying optional text that may appear before or after the
  9337. numerical value of the spin box in the annotation. No spaces are placed between
  9338. the text and the numerical values, so if such spacing is required, it must be
  9339. included in the relevant string.
  9340. This function also sets up the behavior for firing annotation events. An
  9341. annotation should be fired when the user presses enter while the spin box has
  9342. focus. This implementation will also attempt to fire an annotation when the
  9343. spin box loses focus. No annotation is fired if the value of the spin box has
  9344. not been changed since the previous annotation event.
  9345. @<AnnotationSpinBox Implementation@>=
  9346. AnnotationSpinBox::AnnotationSpinBox(const QString &pret,
  9347. const QString &postt,@|
  9348. QWidget *parent)
  9349. : QDoubleSpinBox(parent), pretext(pret), posttext(postt)@/
  9350. {
  9351. resetChange();
  9352. connect(this, SIGNAL(editingFinished()), this, SLOT(annotate()));
  9353. connect(this, SIGNAL(valueChanged(double)), this, SLOT(resetChange()));
  9354. }
  9355. @ The |resetChange()| signal just sets a boolean which is checked prior to
  9356. sending an annotation. This is called automatically when the value of the spin
  9357. box is changed, but it should also be called when a batch is finished in case
  9358. the first required annotation is the same as the last required annotation from
  9359. the previous batch.
  9360. @<AnnotationSpinBox Implementation@>=
  9361. void AnnotationSpinBox::resetChange()@t\2\2@>@/
  9362. {@t\1@>@/
  9363. change = true;@t\2@>@/
  9364. }
  9365. @ The annotation slot is responsible for determining if an annotation should be
  9366. sent. The current implementation is to only attempt to send such a signal when
  9367. the |editingFinished()| signal is emitted, however this could also be connected
  9368. to other signals.
  9369. @<AnnotationSpinBox Implementation@>=
  9370. void AnnotationSpinBox::annotate()@t\2\2@>@/
  9371. {@t\1@>@/
  9372. if(change)@/
  9373. {@t\1@>@/
  9374. change = false;@/
  9375. emit annotation(QString("%1%2%3").arg(pretext).
  9376. arg(value()).arg(posttext), tc, ac);@t\2@>@/
  9377. }@t\2@>@/
  9378. }
  9379. @ These methods set various properties of the annotation.
  9380. @<AnnotationSpinBox Implementation@>=
  9381. void AnnotationSpinBox::setTemperatureColumn(int tempcolumn)
  9382. {
  9383. tc = tempcolumn;
  9384. }
  9385. void AnnotationSpinBox::setAnnotationColumn(int annotationcolumn)
  9386. {
  9387. ac = annotationcolumn;
  9388. }
  9389. void AnnotationSpinBox::setPretext(const QString &pret)
  9390. {
  9391. pretext = pret;
  9392. }
  9393. void AnnotationSpinBox::setPosttext(const QString &postt)
  9394. {
  9395. posttext = postt;
  9396. }
  9397. @ Two functions are needed to interface |AnnotationSpinBox| with the host
  9398. environment. Additional functions are required for setting up inheritance
  9399. properly.
  9400. @<Function prototypes for scripting@>=
  9401. QScriptValue constructAnnotationSpinBox(QScriptContext *context,
  9402. QScriptEngine *engine);
  9403. void setAnnotationSpinBoxProperties(QScriptValue value, QScriptEngine *engine);
  9404. void setQDoubleSpinBoxProperties(QScriptValue value, QScriptEngine *engine);
  9405. void setQAbstractSpinBoxProperties(QScriptValue value, QScriptEngine *engine);
  9406. @ The first of these is passed into the host environment.
  9407. @<Set up the scripting engine@>=
  9408. constructor = engine->newFunction(constructAnnotationSpinBox);
  9409. value = engine->newQMetaObject(&AnnotationSpinBox::staticMetaObject,
  9410. constructor);
  9411. engine->globalObject().setProperty("AnnotationSpinBox", value);
  9412. @ The script constructor creates a new object and passes it to a function that
  9413. is responsible for setting up properties in the inheritance chain.
  9414. @<Functions for scripting@>=
  9415. QScriptValue constructAnnotationSpinBox(QScriptContext *context,
  9416. QScriptEngine *engine)
  9417. {
  9418. QScriptValue object = engine->newQObject(new AnnotationSpinBox(
  9419. argument<QString>(0, context), argument<QString>(1, context)));
  9420. setAnnotationSpinBoxProperties(object, engine);
  9421. return object;
  9422. }
  9423. void setAnnotationSpinBoxProperties(QScriptValue value, QScriptEngine *engine)
  9424. {
  9425. setQDoubleSpinBoxProperties(value, engine);
  9426. }
  9427. void setQDoubleSpinBoxProperties(QScriptValue value, QScriptEngine *engine)
  9428. {
  9429. setQAbstractSpinBoxProperties(value, engine);
  9430. }
  9431. void setQAbstractSpinBoxProperties(QScriptValue value, QScriptEngine *engine)
  9432. {
  9433. setQWidgetProperties(value, engine);
  9434. }
  9435. @** A digital timer.
  9436. \noindent Before \pn{} was a data logger, it was a simple digital timer written
  9437. because there were no shops in Racine that could sell a simple dual digital
  9438. count up timer at a time when my first timer was malfunctioning. After
  9439. attempting to purchase a replacement device at several stores that have sold
  9440. such devices in the past, I decided to spend a couple hours writing my own
  9441. timer.
  9442. For historical reasons, the |TimerDisplay| class is considerably more functional
  9443. than \pn{} requires. Those needing only a digital timer can extract the code for
  9444. this class and use it in a timer application. This should work on any platform
  9445. supported by Qt.
  9446. @<Class declarations@>=
  9447. class TimerDisplay : public QLCDNumber@/
  9448. {@t\1@>@/
  9449. Q_OBJECT@/
  9450. @<TimerDisplay Properties@>@;
  9451. @t\4@>private slots@t\kern-3pt@>:@/
  9452. void updateTime();
  9453. void setCountUpMode();
  9454. void setCountDownMode();
  9455. void setClockMode();
  9456. public:@/
  9457. TimerDisplay(QWidget *parent = NULL);
  9458. ~TimerDisplay();
  9459. enum TimerMode
  9460. {
  9461. CountUp,
  9462. CountDown,
  9463. Clock
  9464. };
  9465. QString value();
  9466. QTime seconds();
  9467. TimerMode mode();
  9468. bool isRunning();
  9469. QTime resetValue();
  9470. QString displayFormat();
  9471. bool autoReset();@/
  9472. @t\4@>public slots@t\kern-3pt@>:@/
  9473. void setTimer(QTime value = QTime(0, 0, 0));
  9474. void setMode(TimerMode mode);
  9475. void startTimer();
  9476. void stopTimer();
  9477. void copyTimer();
  9478. void setResetValue(QTime value = QTime(0, 0, 0));
  9479. void reset();
  9480. void setDisplayFormat(QString format);
  9481. void setAutoReset(bool reset);
  9482. void updateDisplay();
  9483. signals:@/
  9484. void valueChanged(QTime);
  9485. void runStateChanged(bool);@/
  9486. private:@/
  9487. @<TimerDisplay Private Variables@>@;@t\2@>@/
  9488. }@t\kern-3pt@>;
  9489. @ Qt provides a property system based on its meta-object system. This allows for
  9490. a number of advanced features which \pn{} does not use. The properties available
  9491. for the TimerDisplay class exist for historical reasons, but there are some
  9492. plans for future development which may make use of them. The properties may also
  9493. be useful for someone using this class in another program.
  9494. @<TimerDisplay Properties@>=
  9495. Q_PROPERTY(QTime seconds READ seconds WRITE setTimer)@/
  9496. Q_PROPERTY(TimerMode mode READ mode WRITE setMode)@/
  9497. Q_PROPERTY(bool running READ isRunning)@/
  9498. Q_PROPERTY(QTime resetValue READ resetValue WRITE setResetValue)@/
  9499. Q_PROPERTY(QString displayFormat READ displayFormat WRITE setDisplayFormat)@/
  9500. Q_PROPERTY(bool autoReset READ autoReset WRITE setAutoReset)@/
  9501. Q_PROPERTY(QString value READ value)@/
  9502. @ A number of private variables are used to implement this class.
  9503. @<TimerDisplay Private Variables@>=
  9504. QTime s;
  9505. QTime r;
  9506. QTimer clock;
  9507. TimerDisplay::TimerMode m;
  9508. bool running;
  9509. bool ar;
  9510. QAction *startAction;
  9511. QAction *stopAction;
  9512. QAction *resetAction;
  9513. QString f;
  9514. QTime relative;
  9515. QTime base;
  9516. @ |TimerDisplay| is a specialization of |QLCDNumber| designed for time keeping
  9517. purposes. It sets up a timer that fires roughly every half second to see if it
  9518. needs to update itself. The constructor sets this up, but does not start the
  9519. timer. The class provides three actions which can be used to start, stop, or
  9520. reset the timer. These actions are also set up in the constructor.
  9521. By default, the timer will display its time in hours, minutes, and seconds. This
  9522. can be changed as is done with the batch timer (it is expected that nobody will
  9523. want to spend an hour or more to roast a batch of coffee). The display style is
  9524. also changed to a sensible default, but this can be changed with the usual
  9525. |QLCDNumber| methods.
  9526. @<TimerDisplay Implementation@>=
  9527. TimerDisplay::TimerDisplay(QWidget *parent) : QLCDNumber(8, parent),
  9528. s(QTime(0, 0, 0)), r(QTime(0, 0, 0)), clock(NULL),@/ m(TimerDisplay::CountUp),
  9529. running(false), ar(false), startAction(new QAction(tr("Start"), NULL)),@/
  9530. stopAction(new QAction(tr("Stop"), NULL)),
  9531. resetAction(new QAction(tr("Reset"), NULL)),@/ f(QString("hh:mm:ss")),
  9532. relative(QTime::currentTime()), base(QTime(0, 0, 0))@/
  9533. {
  9534. connect(startAction, SIGNAL(triggered(bool)), this, SLOT(startTimer()));
  9535. connect(stopAction, SIGNAL(triggered(bool)), this, SLOT(stopTimer()));
  9536. connect(resetAction, SIGNAL(triggered(bool)), this, SLOT(reset()));
  9537. clock.setInterval(500);
  9538. clock.setSingleShot(false);
  9539. connect(&clock, SIGNAL(timeout()), this, SLOT(updateTime()));
  9540. setSegmentStyle(Filled);
  9541. updateDisplay();
  9542. }
  9543. @ The complicated bits are all in the |updateTime()| method. The behavior of
  9544. this function depends on the current |TimerMode| of the display.
  9545. @<TimerDisplay Implementation@>=
  9546. void TimerDisplay::updateTime()
  9547. {
  9548. QTime time;
  9549. int cseconds = 0;
  9550. int oseconds = 0;
  9551. int r = 0;
  9552. QTime nt = QTime(0, 0, 0);
  9553. int n = 0;
  9554. int bseconds = 0;
  9555. switch(m)@/
  9556. {@t\1@>@/
  9557. case TimerDisplay::CountUp:@/
  9558. @<Check for Timer Increment@>;
  9559. break;
  9560. case TimerDisplay::CountDown:@/
  9561. @<Check for Timer Decrement@>;
  9562. break;
  9563. case TimerDisplay::Clock:@/
  9564. @<Check for Clock Change@>;
  9565. break;
  9566. default:@/
  9567. Q_ASSERT_X(false, "updateTime", "invalid timer mode");
  9568. break;@t\2@>@/
  9569. }
  9570. updateDisplay();
  9571. }
  9572. @ To have the timer count up, we calculate the value that the timer should
  9573. indicate and compare it to the time indicated. If there is a difference, we
  9574. update the time to the new value and send emit a signal.
  9575. @<Check for Timer Increment@>=
  9576. @<Load seconds since base time into r@>@;
  9577. nt = nt.addSecs(r);
  9578. if(nt != s)
  9579. {
  9580. s = nt;
  9581. emit valueChanged(s);
  9582. }
  9583. @ Here we want to calculate the number of seconds in the current time, the
  9584. number of seconds in a base time, and the difference between the two. The
  9585. value loaded into oseconds could probably be cached.
  9586. @<Load seconds since base time into r@>=
  9587. #define TIMETOINT(t) ((t.hour() * 60 * 60) + (t.minute() * 60) + (t.second()))
  9588. time = QTime::currentTime();
  9589. cseconds = TIMETOINT(time);
  9590. oseconds = TIMETOINT(relative);
  9591. r = cseconds - oseconds;
  9592. @ The logic for a count down timer is very similar to the logic for a count up
  9593. timer. A key difference is that we don'@q'@>t want to continue counting down if the
  9594. timer has already reached 0.
  9595. @<Check for Timer Decrement@>=
  9596. if(s > QTime(0, 0, 0))@/
  9597. {@/
  9598. @<Load seconds since base time into r@>@;
  9599. bseconds = TIMETOINT(base);
  9600. n = bseconds - r;
  9601. nt = nt.addSecs(n);
  9602. if(nt != s)
  9603. {
  9604. s = nt;
  9605. emit valueChanged(s);
  9606. }
  9607. } else {
  9608. stopTimer();
  9609. }
  9610. @ The clock mode is the simplest case as it just needs to find out if the time
  9611. has changed.
  9612. @<Check for Clock Change@>=
  9613. time = QTime::currentTime();
  9614. if(time != s)
  9615. {
  9616. s = time;
  9617. emit valueChanged(s);
  9618. }
  9619. @ When counting up or down, it is important to record the time at which the
  9620. timer starts. The clock that triggers time updates must also be started. The
  9621. timer also needs to reset its value if that behavior is desired.
  9622. @<TimerDisplay Implementation@>=
  9623. #define TIMESUBTRACT(t1, t2) (t1.addSecs(-(TIMETOINT(t2))).addSecs(-t2.msec()))
  9624. void TimerDisplay::startTimer()@t\2\2@>@/
  9625. {@t\1@>@/
  9626. if(!running)@/
  9627. {@t\1@>@/
  9628. relative = QTime::currentTime();
  9629. if(ar)@/
  9630. {
  9631. reset();
  9632. }
  9633. else
  9634. {
  9635. relative = TIMESUBTRACT(relative, s);
  9636. }
  9637. if(m == Clock)@/
  9638. {
  9639. updateTime();
  9640. }
  9641. base = s;
  9642. clock.start();@/
  9643. running = true;
  9644. emit runStateChanged(true);@t\2@>@/
  9645. }@t\2@>@/
  9646. }
  9647. @ Stopping the timer is a little simpler. Remember to stop the clock so we
  9648. aren'@q'@>t updating senselessly.
  9649. @<TimerDisplay Implementation@>=
  9650. void TimerDisplay::stopTimer()@t\2\2@>@/
  9651. {@t\1@>@/
  9652. if(running)@/
  9653. {@t\1@>@/
  9654. clock.stop();@/
  9655. running = false;
  9656. emit runStateChanged(false);@t\2@>@/
  9657. }@t\2@>@/
  9658. }
  9659. @ The clock is also stopped in the destructor.
  9660. @<TimerDisplay Implementation@>=
  9661. TimerDisplay::~TimerDisplay()
  9662. {
  9663. clock.stop();
  9664. }
  9665. @ The rest of the functions are trivial. There are functions for changing the
  9666. timer mode:
  9667. @<TimerDisplay Implementation@>=
  9668. void TimerDisplay::setCountUpMode()
  9669. {
  9670. m = TimerDisplay::CountUp;
  9671. }
  9672. void TimerDisplay::setCountDownMode()
  9673. {
  9674. m = TimerDisplay::CountDown;
  9675. }
  9676. void TimerDisplay::setClockMode()
  9677. {
  9678. m = TimerDisplay::Clock;
  9679. }
  9680. @ There are a few functions to obtain information about the state of the timer.
  9681. @<TimerDisplay Implementation@>=
  9682. QString TimerDisplay::value()
  9683. {
  9684. return s.toString(f);
  9685. }
  9686. QTime TimerDisplay::seconds()
  9687. {
  9688. return s;
  9689. }
  9690. TimerDisplay::TimerMode TimerDisplay::mode()
  9691. {
  9692. return m;
  9693. }
  9694. bool TimerDisplay::isRunning()
  9695. {
  9696. return running;
  9697. }
  9698. QTime TimerDisplay::resetValue()
  9699. {
  9700. return r;
  9701. }
  9702. QString TimerDisplay::displayFormat()
  9703. {
  9704. return f;
  9705. }
  9706. bool TimerDisplay::autoReset()
  9707. {
  9708. return ar;
  9709. }
  9710. @ There are also some functions for setting aspects of the timer state.
  9711. @<TimerDisplay Implementation@>=
  9712. void TimerDisplay::setTimer(QTime value)
  9713. {
  9714. if(value.isValid())
  9715. {
  9716. s = value;
  9717. updateDisplay();
  9718. emit valueChanged(value);
  9719. }
  9720. }
  9721. void TimerDisplay::setMode(TimerDisplay::TimerMode mode)
  9722. {
  9723. m = mode;
  9724. }
  9725. void TimerDisplay::setResetValue(QTime value)
  9726. {
  9727. r = value;
  9728. }
  9729. void TimerDisplay::setDisplayFormat(QString format)
  9730. {
  9731. f = format;
  9732. setNumDigits(format.length());
  9733. }
  9734. void TimerDisplay::setAutoReset(bool reset)
  9735. {
  9736. ar = reset;
  9737. }
  9738. @ |TimerDisplay| supports using the system clipboard to copy the current timer
  9739. value.
  9740. @<TimerDisplay Implementation@>=
  9741. void TimerDisplay::copyTimer()
  9742. {
  9743. QApplication::clipboard()->setText(value());
  9744. }
  9745. @ Resetting the timer is simple. We don'@q'@>t reset the timer if it is still running
  9746. mainly to prevent accidents.
  9747. @<TimerDisplay Implementation@>=
  9748. void TimerDisplay::reset()
  9749. {
  9750. if(!running)
  9751. {
  9752. s = r;
  9753. updateDisplay();
  9754. }
  9755. }
  9756. @ Finally, there is the function for changing the text of the display to the
  9757. current time value.
  9758. @<TimerDisplay Implementation@>=
  9759. void TimerDisplay::updateDisplay()
  9760. {
  9761. display(value());
  9762. }
  9763. @ Exposing |TimerDisplay| to the host environment is simple.
  9764. @<Function prototypes for scripting@>=
  9765. QScriptValue constructTimerDisplay(QScriptContext *context,
  9766. QScriptEngine *engine);
  9767. void setTimerDisplayProperties(QScriptValue value, QScriptEngine *engine);
  9768. QScriptValue TimerDisplay_setTimerMode(QScriptContext *context, QScriptEngine *engine);
  9769. @ The engine must be informed of the script constructor.
  9770. @<Set up the scripting engine@>=
  9771. constructor = engine->newFunction(constructTimerDisplay);
  9772. value = engine->newQMetaObject(&TimerDisplay::staticMetaObject, constructor);
  9773. engine->globalObject().setProperty("TimerDisplay", value);
  9774. @ The implementation of these functions is trivial.
  9775. @<Functions for scripting@>=
  9776. QScriptValue constructTimerDisplay(QScriptContext *, QScriptEngine *engine)
  9777. {
  9778. QScriptValue object = engine->newQObject(new TimerDisplay);
  9779. setTimerDisplayProperties(object, engine);
  9780. return object;
  9781. }
  9782. void setTimerDisplayProperties(QScriptValue value, QScriptEngine *engine)
  9783. {
  9784. setQLCDNumberProperties(value, engine);
  9785. value.setProperty("setTimerMode", engine->newFunction(TimerDisplay_setTimerMode));
  9786. }
  9787. @ A new feature in \pn{} 1.6.4 benefits from having the ability to set the
  9788. timer mode from a script. Rather than exposing the |enum| responsible for this
  9789. to the host environment, a new function is provided to allow integer based
  9790. setting.
  9791. @<Functions for scripting@>=
  9792. QScriptValue TimerDisplay_setTimerMode(QScriptContext *context, QScriptEngine *)
  9793. {
  9794. TimerDisplay *self = getself<TimerDisplay *>(context);
  9795. if(self)
  9796. {
  9797. switch(argument<int>(0, context))
  9798. {
  9799. case 0:
  9800. self->setMode(TimerDisplay::CountUp);
  9801. break;
  9802. case 1:
  9803. self->setMode(TimerDisplay::CountDown);
  9804. break;
  9805. case 2:
  9806. self->setMode(TimerDisplay::Clock);
  9807. break;
  9808. default:
  9809. break;
  9810. }
  9811. }
  9812. return QScriptValue();
  9813. }
  9814. @** The Human Computer Interface.
  9815. \noindent A few classes are required for putting the rest of the program
  9816. together in a way that it can be used by a human. There is a layout class for
  9817. arranging widgets in a way that is not simple with the layouts provided by Qt.
  9818. There are classes for labeling the various indicators. There are also window
  9819. classes that put all of this together in a useful and usable way. One of these
  9820. classes is currently depreciated.
  9821. @* The PackLayout Class.
  9822. \noindent The |PackLayout| class provides functionality similar to the
  9823. |QBoxLayout| class in Qt. It allows the construction of a row or column of
  9824. widgets. Each item will take up space along the orientation of the layout equal
  9825. to its size hint except for the last widget which will take up all remaining
  9826. space. Widgets will be resized in the direction perpendicular to the orientation
  9827. of the layout to use all available space.
  9828. This class was originally written with the |WidgetDecorator| class which we will
  9829. get to later in mind, but it has found use in other places where the left or top
  9830. most widgets should not be resized.
  9831. By default, a new |PackLayout| will arrange widgets horizontally. This can be
  9832. changed with a call to |setOrientation()|.
  9833. @<Class declarations@>=
  9834. class PackLayout : public QLayout@/
  9835. {@/
  9836. int doLayout(const QRect &rect, bool testOnly) const;@/
  9837. QList<QLayoutItem *> itemList;@/
  9838. Qt::Orientations@, orientation;@/
  9839. public:@/
  9840. PackLayout(QWidget *parent, int margin = 0, int spacing = -1);
  9841. PackLayout(int spacing = -1);
  9842. ~PackLayout();
  9843. void addItem(QLayoutItem *item);
  9844. Qt::Orientations@, expandingDirections() const;
  9845. bool hasHeightForWidth() const;
  9846. int heightForWidth(int width) const;
  9847. int count() const;
  9848. QLayoutItem *itemAt(int index) const;
  9849. QSize minimumSize() const;
  9850. void setGeometry(const QRect &rect);
  9851. void setOrientation(Qt::Orientations direction);
  9852. QSize sizeHint() const;
  9853. QLayoutItem *takeAt(int index);
  9854. };
  9855. @ The interesting portion of this class is in |doLayout()|. This function goes
  9856. over the items in the layout and sets the geometry appropriately.
  9857. The seemingly odd choice of returning |y| at the end of this function (indeed of
  9858. having a return value at all) is to allow this function to provide the return
  9859. value needed in |heightForWidth()|.
  9860. If |testOnly| is set to |true|, |y| will be calculated, but the widget geometry
  9861. will not be changed.
  9862. @<PackLayout Implementation@>=
  9863. int PackLayout::doLayout(const QRect &rect, bool testOnly) const
  9864. {
  9865. int x = rect.x();
  9866. int y = rect.y();
  9867. QLayoutItem *item;
  9868. if(orientation == Qt::Horizontal)
  9869. {
  9870. @<Lay the widgets out horizontally@>@;
  9871. }
  9872. else
  9873. {
  9874. @<Lay the widgets out vertically@>@;
  9875. }
  9876. return y;
  9877. }
  9878. @ To lay the widgets out horizontally, we go over each item in the list taking
  9879. the width of the size hint and spacing into account unless the item is the last
  9880. item in the list, in which case the right of the widget needs to be at the end
  9881. of the available space. We use the foreach construction that Qt provides to
  9882. iterate over each item in the list in much the same way as foreach constructions
  9883. are used in languages that support them directly.
  9884. @<Lay the widgets out horizontally@>=
  9885. foreach(item, itemList)
  9886. {
  9887. int nextX = x + item->sizeHint().width() + spacing();
  9888. int right = x + item->sizeHint().width();
  9889. if(item == itemList.last())
  9890. {
  9891. right = rect.right();
  9892. }
  9893. int bottom = rect.bottom();
  9894. if(!testOnly)
  9895. {
  9896. item->setGeometry(QRect(QPoint(x, y), QPoint(right, bottom)));
  9897. }
  9898. x = nextX;
  9899. }
  9900. @ Laying out the widgets vertically is very similar.
  9901. @<Lay the widgets out vertically@>=
  9902. foreach(item, itemList)
  9903. {
  9904. int nextY = y + item->sizeHint().height() + spacing();
  9905. int bottom = y + item->sizeHint().height();
  9906. if(item == itemList.last())
  9907. {
  9908. bottom = rect.bottom();
  9909. }
  9910. int right = rect.right();
  9911. if(!testOnly)
  9912. {
  9913. item->setGeometry(QRect(QPoint(x, y), QPoint(right, bottom)));
  9914. }
  9915. y = nextY;
  9916. }
  9917. @ As a layout class, there are a number of things the class should be able to do
  9918. in order to play nicely with other classes. One of these is determining the
  9919. minimum size of the layout. The minimum size of the layout is equal to the space
  9920. required for each item in the layout plus the margin space. The margin space
  9921. will be equal to twice the specified margin in each direction to account for a
  9922. top, bottom, left, and right margin.
  9923. @<PackLayout Implementation@>=
  9924. QSize PackLayout::minimumSize() const
  9925. {
  9926. QSize size;
  9927. QLayoutItem *item;
  9928. foreach(item, itemList)
  9929. {
  9930. if(orientation == Qt::Horizontal)
  9931. {
  9932. size += QSize(item->minimumSize().width(), 0);
  9933. if(size.height() < item->minimumSize().height())
  9934. {
  9935. size.setHeight(item->minimumSize().height());
  9936. }
  9937. }
  9938. else
  9939. {
  9940. size += QSize(0, item->minimumSize().height());
  9941. if(size.width() < item->minimumSize().width())
  9942. {
  9943. size.setWidth(item->minimumSize().width());
  9944. }
  9945. }
  9946. }
  9947. size += QSize(2*margin(), 2*margin());
  9948. return size;
  9949. }
  9950. @ |PackLayout| features two constructors. One allows for setting the margin,
  9951. spacing, and a parent widget at the time of construction. The other creates a
  9952. parentless layout which will have to be added to another widget or layout.
  9953. @<PackLayout Implementation@>=
  9954. PackLayout::PackLayout(QWidget *parent, int margin, int spacing) :
  9955. QLayout(parent)@/
  9956. {
  9957. setMargin(margin);
  9958. setSpacing(spacing);
  9959. setOrientation(Qt::Horizontal);
  9960. }
  9961. PackLayout::PackLayout(int spacing)
  9962. {
  9963. setSpacing(spacing);
  9964. setOrientation(Qt::Horizontal);
  9965. }
  9966. @ In Qt, items in a layout are owned by that layout. When the layout is
  9967. destroyed, all of the items in that layout must also be deleted.
  9968. @<PackLayout Implementation@>=
  9969. PackLayout::~PackLayout()
  9970. {
  9971. QLayoutItem *item;
  9972. while((item = takeAt(0)))
  9973. {
  9974. delete item;
  9975. }
  9976. }
  9977. @ Deleting the items uses the |takeAt()| method to remove each widget from the
  9978. layout prior to deleting it. The item requested should exist, but if it doesn'@q'@>t,
  9979. |NULL| is returned.
  9980. @<PackLayout Implementation@>=
  9981. QLayoutItem* PackLayout::takeAt(int index)
  9982. {
  9983. if(index >= 0 && index < itemList.size())
  9984. {
  9985. return itemList.takeAt(index);
  9986. }
  9987. else
  9988. {
  9989. return NULL;
  9990. }
  9991. }
  9992. @ If we are interested in which item is in a particular position in the layout
  9993. but do not want to remove it from the layout, |itemAt()| provides that.
  9994. @<PackLayout Implementation@>=
  9995. QLayoutItem* PackLayout::itemAt(int index) const
  9996. {
  9997. if(index >= 0 && index < itemList.size())
  9998. {
  9999. return itemList.at(index);
  10000. }
  10001. else
  10002. {
  10003. return NULL;
  10004. }
  10005. }
  10006. @ A layout class is not very useful unless there is a way to get items into the
  10007. layout. The |QLayoutItem| class is designed in such a way that it is possible to
  10008. pass pointers to objects that inherit |QLayout| or |QWidget|.
  10009. The base |QLayout| class provides an |addWidget()| method that will use our
  10010. version of |addItem()|. That should be used when adding a widget to the layout.
  10011. The Qt documentation recommends also providing an |addLayout()| method so that
  10012. other code does not need to call this method, but that has not been provided
  10013. yet.
  10014. @<PackLayout Implementation@>=
  10015. void PackLayout::addItem(QLayoutItem *item)
  10016. {
  10017. itemList.append(item);
  10018. }
  10019. @ It is sometimes useful to know how many items are in a layout.
  10020. @<PackLayout Implementation@>=
  10021. int PackLayout::count() const@;@/
  10022. {@/
  10023. return itemList.size();@/
  10024. }
  10025. @ A few more functions are needed to make the layout class work well with other
  10026. classes. For more details, please consult the Qt Reference
  10027. Documentation\nfnote{Qt Reference Documentation\par\indent\hbox{%
  10028. \pdfURL{http://doc.trolltech.com/4.3/index.html}%
  10029. {http://doc.trolltech.com/4.3/index.html}}}
  10030. @<PackLayout Implementation@>=
  10031. Qt::Orientations PackLayout::expandingDirections() const
  10032. {
  10033. return Qt::Vertical | Qt::Horizontal;
  10034. }
  10035. bool PackLayout::hasHeightForWidth() const@t\2\2@>@/
  10036. {@t\1@>@/
  10037. return false;@t\2@>@/
  10038. }@/
  10039. int PackLayout::heightForWidth(int width) const
  10040. {
  10041. return doLayout(QRect(0, 0, width, 0), true);
  10042. }
  10043. void PackLayout::setGeometry(const QRect &rect)
  10044. {
  10045. QLayout::setGeometry(rect);
  10046. doLayout(rect, false);
  10047. }
  10048. QSize PackLayout::sizeHint() const
  10049. {
  10050. return minimumSize();
  10051. }
  10052. @ It was mentioned previously that this layout is capable of lining widgets up
  10053. in a row or presenting them in a column. This is done with the
  10054. |setOrientation()| method.
  10055. @<PackLayout Implementation@>=
  10056. void PackLayout::setOrientation(Qt::Orientations direction)
  10057. {
  10058. orientation = direction;
  10059. doLayout(geometry(), false);
  10060. }
  10061. @* The SceneButton Class.
  10062. \noindent Ordinarily, mouse down events that are passed from a |QGraphicsView|
  10063. to an interactive |QGraphicsScene| will continue to pass that click down to an
  10064. item in the scene. This class is used when we are interested in a click anywhere
  10065. in the view and it doesn'@q'@>t really matter where in the scene that click occurred
  10066. or even if there is a graphics item at that point. Any click passed to the
  10067. |SceneButton| will cause the scene to emit a signal containing the screen
  10068. coordinates of the click.
  10069. This was originally designed for use in the |WidgetDecorator| class. While the
  10070. functionality provided is not currently used, the original plan was to use this
  10071. to provide access to configuration options.
  10072. It is possible that this class is no longer necessary even if features it was
  10073. made for are implemented.
  10074. @<Class declarations@>=
  10075. class SceneButton : public QGraphicsScene@/
  10076. {@/
  10077. Q_OBJECT@;
  10078. public:@/
  10079. SceneButton();
  10080. ~SceneButton();
  10081. protected:@/
  10082. void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent);
  10083. signals:@/
  10084. void clicked(QPoint pos);
  10085. };
  10086. @ The implementation is trivial.
  10087. @<SceneButton Implementation@>=
  10088. SceneButton::SceneButton() : QGraphicsScene()@/
  10089. {
  10090. /* Nothing has to be done here. */
  10091. }
  10092. SceneButton::~SceneButton()
  10093. {
  10094. /* Nothing has to be done here. */
  10095. }
  10096. void SceneButton::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent)
  10097. {
  10098. emit clicked(mouseEvent->buttonDownScreenPos(mouseEvent->button()));
  10099. }
  10100. @* The WidgetDecorator Class.
  10101. \noindent The |WidgetDecorator| class provides a way to label various widgets
  10102. while also providing additional options for interacting with them. The
  10103. decoration can exist to the left or atop the widget being decorated. When the
  10104. label is to the left of the widget, the label text is rotated.
  10105. This class is likely to change considerably in the future as features are added
  10106. that allow actions to be added to the decoration to allow various configuration
  10107. options.
  10108. @<Class declarations@>=
  10109. class WidgetDecorator : public QWidget@/
  10110. {
  10111. Q_OBJECT@;
  10112. PackLayout *layout;
  10113. QGraphicsView *label;
  10114. QGraphicsTextItem *text;
  10115. SceneButton *scene;
  10116. public:@/
  10117. WidgetDecorator(QWidget *widget, const QString &labeltext,@|
  10118. Qt::Orientations@, orientation = Qt::Horizontal,@|
  10119. QWidget *parent = NULL, Qt::WindowFlags f = 0);
  10120. ~WidgetDecorator();
  10121. void setBackgroundBrush(QBrush background);
  10122. void setTextColor(QColor color);
  10123. };
  10124. @ Almost everything this class currently does is handled in the constructor.
  10125. @<WidgetDecorator Implementation@>=
  10126. WidgetDecorator::WidgetDecorator(QWidget *widget, const QString &labeltext,
  10127. Qt::Orientations orientation,
  10128. QWidget *parent, Qt::WindowFlags f)@/:
  10129. QWidget(parent, f), label(new QGraphicsView()),
  10130. scene(new SceneButton())@t\2@>@/
  10131. {
  10132. layout = new PackLayout(this);
  10133. layout->setOrientation(orientation);
  10134. @<Prepare the graphics view@>@;
  10135. @<Add the label to the scene@>@;
  10136. @<Adjust the decoration width@>@;
  10137. @<Pack widgets into the layout@>@;
  10138. }
  10139. @ The decoration is a |QGraphicsView|. To get this to look right, we need to
  10140. make sure there aren'@q'@>t any scroll bars and there shouldn'@q'@>t be a frame
  10141. surrounding it. While we'@q'@>re at it, we allow it to accept clicks, though this
  10142. functionality is not yet used.
  10143. @<Prepare the graphics view@>=
  10144. label->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  10145. label->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  10146. label->setFrameShape(QFrame::NoFrame);
  10147. label->setInteractive(true);
  10148. @ The |QGraphicsView| needs a scene to display anything. The scene consists of a
  10149. background which, by default is solid cyan. This can be changed later by setting
  10150. a different background brush. Text also needs to be added to the scene. If the
  10151. decoration is to the left of the widget, the text needs to be rotated.
  10152. @<Add the label to the scene@>=
  10153. scene->setBackgroundBrush(Qt::cyan);
  10154. text = scene->addText(labeltext);
  10155. if(orientation == Qt::Horizontal)
  10156. {
  10157. text->rotate(270.0);
  10158. }
  10159. label->setScene(scene);
  10160. @ The decoration should have the text centered in the view. The widget should
  10161. also be no wider (or taller for horizontal orientation) than necessary for the
  10162. text.
  10163. The case for horizontal orientation here may seem a little strange, however the
  10164. dimensions of the bounding rectangle are not affected by rotation. This means
  10165. that even though we want the width of the rotated text, this is the same as the
  10166. height of the text.
  10167. @<Adjust the decoration width@>=
  10168. if(orientation == Qt::Horizontal)
  10169. {
  10170. label->setMaximumWidth((int)(text->boundingRect().height() + 1));
  10171. }
  10172. else
  10173. {
  10174. label->setMaximumHeight((int)(text->boundingRect().height() + 1));
  10175. }
  10176. label->centerOn(text);
  10177. @ Once the decoration is ready, the decoration and the widget being decorated
  10178. can be added to the layout. A minimum size for the compound widget is also
  10179. calculated.
  10180. @<Pack widgets into the layout@>=
  10181. layout->addWidget(label);
  10182. layout->addWidget(widget);
  10183. if(orientation == Qt::Horizontal)
  10184. {
  10185. setMinimumSize(widget->sizeHint().width() + label->sizeHint().width(),
  10186. widget->sizeHint().height());
  10187. }
  10188. else
  10189. {
  10190. setMinimumSize(widget->sizeHint().width(),
  10191. widget->sizeHint().height() + label->sizeHint().height());
  10192. }
  10193. @ As mentioned previously, it is possible to change the background pattern for
  10194. the decoration. It is also possible to change the color of the text.
  10195. @<WidgetDecorator Implementation@>=
  10196. void WidgetDecorator::setBackgroundBrush(QBrush background)
  10197. {
  10198. scene->setBackgroundBrush(background);
  10199. }
  10200. void WidgetDecorator::setTextColor(QColor color)
  10201. {
  10202. text->setDefaultTextColor(color);
  10203. }
  10204. @ Finally, there is a destructor.
  10205. @<WidgetDecorator Implementation@>=
  10206. WidgetDecorator::~WidgetDecorator()
  10207. {
  10208. /* Nothing has to be done here. */
  10209. }
  10210. @ In order to create a decorated widget from a script, we need these functions.
  10211. @<Function prototypes for scripting@>=
  10212. void setWidgetDecoratorProperties(QScriptValue value, QScriptEngine *engine);
  10213. QScriptValue constructWidgetDecorator(QScriptContext *context,
  10214. QScriptEngine *engine);
  10215. @ The scripting engine must be informed of this function.
  10216. @<Set up the scripting engine@>=
  10217. constructor = engine->newFunction(constructWidgetDecorator);
  10218. value = engine->newQMetaObject(&WidgetDecorator::staticMetaObject, constructor);
  10219. engine->globalObject().setProperty("WidgetDecorator", value);
  10220. @ The constructor is slightly more complex than other script constructors, but
  10221. still simple.
  10222. @<Functions for scripting@>=
  10223. QScriptValue constructWidgetDecorator(QScriptContext *context,
  10224. QScriptEngine *engine)
  10225. {
  10226. QWidget *widget = argument<QWidget *>(0, context);
  10227. QString text = argument<QString>(1, context);
  10228. Qt::Orientations@, orientation;
  10229. switch(argument<int>(2, context))@/
  10230. {@t\1@>@/
  10231. case 2:@/
  10232. orientation = Qt::Vertical;
  10233. break;
  10234. default:@/
  10235. orientation = Qt::Horizontal;
  10236. break;@t\2@>@/
  10237. }
  10238. QScriptValue object =
  10239. engine->newQObject(new WidgetDecorator(widget, text, orientation));
  10240. setWidgetDecoratorProperties(object, engine);
  10241. return object;
  10242. }
  10243. void setWidgetDecoratorProperties(QScriptValue value, QScriptEngine *engine)
  10244. {
  10245. setQWidgetProperties(value, engine);
  10246. }
  10247. @* The LogEditWindow Class.
  10248. \noindent This class will be depreciated in a future release once I have
  10249. confirmed that the class can be replaced by the configuration system. It has not
  10250. been updated to support new functionality added in version 1.2.3 and use of this
  10251. class is highly discouraged.
  10252. While the logging window provided in the example configuration is fine for
  10253. recording an existing roast, there are some who would like to be able to use
  10254. \pn{} to work with data collected with a manual logger. Different controls are
  10255. useful in such a case. The |LogEditWindow| provides this.
  10256. @<Class declarations@>=
  10257. class LogEditWindow : public QMainWindow@/
  10258. {@t\1@>@/
  10259. Q_OBJECT@;
  10260. QWidget *centralWidget;
  10261. PackLayout *mainLayout;
  10262. QHBoxLayout *addRowsLayout;
  10263. QLabel *startTimeLabel;
  10264. QTimeEdit *startTime;
  10265. QLabel *endTimeLabel;
  10266. QTimeEdit *endTime;
  10267. QLabel *intervalLabel;
  10268. QSpinBox *interval;
  10269. QPushButton *addRows;
  10270. QAction *saveXml;
  10271. QAction *saveCsv;
  10272. QAction *openXml;
  10273. MeasurementModel *model;
  10274. QTableView *log;@/
  10275. @t\4@>private slots@t\kern-3pt@>:@/
  10276. void addTheRows();
  10277. void saveXML();
  10278. void saveCSV();
  10279. void openXML();@/
  10280. protected:@/
  10281. void closeEvent(QCloseEvent *event);@/
  10282. public:@/
  10283. LogEditWindow();@t\2@>@/
  10284. }@t\kern-3pt@>;
  10285. @ This window provides controls for adding rows to a measurement. Typically, the
  10286. data on a manual roast log will have measurements at regular intervals with the
  10287. possible exception of a few points where there are control changes or the end of
  10288. the batch. The routine for adding rows is capable of adding a single row, rows
  10289. in a range of times at regular intervals, or rows in a range of times at regular
  10290. intervals plus one time at the end.
  10291. @<LogEditWindow Implementation@>=
  10292. void LogEditWindow::addTheRows()
  10293. {
  10294. QTime s = startTime->time();
  10295. while(s < endTime->time())
  10296. {
  10297. model->newMeasurement(Measurement(0, s), 1);
  10298. s = s.addSecs(interval->value());
  10299. }
  10300. model->newMeasurement(Measurement(0, endTime->time()), 1);
  10301. }
  10302. @ The window is prepared in its constructor.
  10303. @<LogEditWindow Implementation@>=
  10304. LogEditWindow::LogEditWindow() : QMainWindow(NULL),
  10305. centralWidget(new QWidget(NULL)), mainLayout(new PackLayout(0)),@|
  10306. addRowsLayout(new QHBoxLayout(NULL)),
  10307. startTimeLabel(new QLabel("Start Time")),@|
  10308. startTime(new QTimeEdit(QTime(0, 0, 0, 0))),@|
  10309. endTimeLabel(new QLabel("End Time")),
  10310. endTime(new QTimeEdit(QTime(0, 20, 0, 0))),@|
  10311. intervalLabel(new QLabel("Interval (seconds)")),@|
  10312. interval(new QSpinBox()),
  10313. addRows(new QPushButton("Add Rows")),@|
  10314. saveXml(new QAction(tr("Save Profile As..."), NULL)),@|
  10315. saveCsv(new QAction(tr("Export CSV"), NULL)),@|
  10316. openXml(new QAction(tr("Load Target Profile..."), NULL)),@|
  10317. model(new MeasurementModel()),
  10318. log(new QTableView())@/
  10319. {
  10320. @<Restore editor window geometry from settings@>@;
  10321. @<Set up the editor control bar@>@;
  10322. @<Prepare the model@>@;
  10323. @<Prepare the log table@>@;
  10324. mainLayout->addItem(addRowsLayout);
  10325. mainLayout->addWidget(log);
  10326. centralWidget->setLayout(mainLayout);
  10327. setCentralWidget(centralWidget);
  10328. QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
  10329. fileMenu->addAction(openXml);
  10330. connect(openXml, SIGNAL(triggered()), this, SLOT(openXML()));
  10331. fileMenu->addAction(saveXml);
  10332. connect(saveXml, SIGNAL(triggered()), this, SLOT(saveXML()));
  10333. fileMenu->addAction(saveCsv);
  10334. connect(saveCsv, SIGNAL(triggered()), this, SLOT(saveCSV()));
  10335. }
  10336. @ The window keeps its previous size and location in settings. These need to be
  10337. restored when a new window is created.
  10338. @<Restore editor window geometry from settings@>=
  10339. QSettings settings;
  10340. resize(settings.value("logSize", QSize(620,400)).toSize());
  10341. move(settings.value("logPos", QPoint(200,60)).toPoint());
  10342. @ When a new window is opened, it starts with an empty profile. If this is used
  10343. to manually enter a profile rather than edit an existing profile, rows will need
  10344. to be added. For this, we provide a set of controls where a start time, an end
  10345. time, and an interval in seconds is specified along with a button that, when
  10346. pressed, will produce a row in the model for the starting time, the ending time,
  10347. and regularly spaced times between the two. If only a single row is needed, this
  10348. can be produced by setting the start and end times the same.
  10349. @<Set up the editor control bar@>=
  10350. mainLayout->setOrientation(Qt::Vertical);
  10351. addRowsLayout->addSpacing(10);
  10352. addRowsLayout->addWidget(startTimeLabel);
  10353. addRowsLayout->addWidget(startTime);
  10354. addRowsLayout->addSpacing(10);
  10355. startTime->setDisplayFormat("mm:ss");
  10356. addRowsLayout->addWidget(endTimeLabel);
  10357. addRowsLayout->addWidget(endTime);
  10358. addRowsLayout->addSpacing(10);
  10359. endTime->setDisplayFormat("mm:ss");
  10360. addRowsLayout->addWidget(intervalLabel);
  10361. addRowsLayout->addWidget(interval);
  10362. addRowsLayout->addSpacing(10);
  10363. interval->setRange(0, 60);
  10364. interval->setValue(30);
  10365. addRowsLayout->addWidget(addRows);
  10366. addRowsLayout->addSpacing(10);
  10367. connect(addRows, SIGNAL(clicked()), this, SLOT(addTheRows()));
  10368. @ The model will have three columns: Time, Temperature, and Annotation. This
  10369. probably should not be hard coded.
  10370. @<Prepare the model@>=
  10371. model->setHeaderData(0, Qt::Horizontal, "Time");
  10372. model->setHeaderData(1, Qt::Horizontal, "Temperature");
  10373. model->setHeaderData(2, Qt::Horizontal, "Annotation");
  10374. model->clear();
  10375. @ The profile is presented in a table view. The columns should be wide enough to
  10376. contain a label, the data contained in the column, and an editor delegate.
  10377. @<Prepare the log table@>=
  10378. log->setModel(model);
  10379. log->setColumnWidth(0, 100);
  10380. log->setColumnWidth(1, 100);
  10381. log->setColumnWidth(2, 100);
  10382. @ Most users will want to save a profile after they'@q'@>ve edited it. We also
  10383. provide CSV export here. Note that this class only supports logs with a single
  10384. temperature and a single annotation column. As the class is considered
  10385. depreciated, it will not be extended to support arbitrarily many columns.
  10386. @<LogEditWindow Implementation@>=
  10387. void LogEditWindow::saveXML()
  10388. {
  10389. QSettings settings;
  10390. QString lastDir = settings.value("lastDirectory").toString();
  10391. QString filename = QFileDialog::getSaveFileName(this, tr("Save Log As..."),
  10392. lastDir, "", 0);
  10393. QFile file(filename);
  10394. XMLOutput writer(model, &file, 0);
  10395. writer.addTemperatureColumn("Temperature", 1);
  10396. writer.addAnnotationColumn("Annotation", 2);
  10397. if(writer.output())
  10398. {
  10399. QFileInfo info(filename);
  10400. QDir directory = info.dir();
  10401. lastDir = directory.path();
  10402. settings.setValue("lastDirectory", lastDir);
  10403. }
  10404. }
  10405. void LogEditWindow::saveCSV()
  10406. {
  10407. QSettings settings;
  10408. QString lastDir = settings.value("lastDirectory").toString();
  10409. QString filename = QFileDialog::getSaveFileName(this, tr("Export As..."),
  10410. lastDir, "", 0);
  10411. QFile file(filename);
  10412. CSVOutput writer(model, &file, 0);
  10413. writer.addTemperatureColumn("Temperature", 1);
  10414. writer.addAnnotationColumn("Annotation", 2);
  10415. if(writer.output())
  10416. {
  10417. QFileInfo info(filename);
  10418. QDir directory = info.dir();
  10419. lastDir = directory.path();
  10420. settings.setValue("lastDirectory", lastDir);
  10421. }
  10422. }
  10423. @ Some may want to open a previously saved profile, for example, to adjust the
  10424. position of an annotation. Note that this class is not appropriate for editing
  10425. profiles with more than one temperature column.
  10426. @<LogEditWindow Implementation@>=
  10427. void LogEditWindow::openXML()
  10428. {
  10429. QSettings settings;
  10430. QString lastDir = settings.value("lastDirectory").toString();
  10431. QString filename = QFileDialog::getOpenFileName(this, tr("Open XML Log..."),
  10432. lastDir, "", 0);
  10433. if(filename.isNull())
  10434. {
  10435. return;
  10436. }
  10437. QFile file(filename);
  10438. XMLInput reader(&file, 1);
  10439. connect(&reader, SIGNAL(measure(Measurement, int)),
  10440. model, SLOT(newMeasurement(Measurement, int)));
  10441. connect(&reader, SIGNAL(annotation(QString, int, int)),
  10442. model, SLOT(newAnnotation(QString, int, int)));
  10443. if(reader.input())
  10444. {
  10445. QFileInfo info(filename);
  10446. setWindowTitle(QString(tr("%1 - %2")).@|
  10447. arg(QCoreApplication::applicationName()).arg(info.baseName()));
  10448. QDir directory = info.dir();
  10449. lastDir = directory.path();
  10450. settings.setValue("lastDirectory", lastDir);
  10451. }
  10452. }
  10453. @ The window should remember its last size and position, so we store this
  10454. information in settings when the window is closed.
  10455. @<LogEditWindow Implementation@>=
  10456. void LogEditWindow::closeEvent(QCloseEvent *event)
  10457. {
  10458. QSettings settings;
  10459. settings.setValue("logSize", size());
  10460. settings.setValue("logPos", pos());
  10461. event->accept();
  10462. }
  10463. @ One function is required to instantiate this class from a script.
  10464. @<Function prototypes for scripting@>=
  10465. QScriptValue constructLogEditWindow(QScriptContext *context,
  10466. QScriptEngine *engine);
  10467. @ The engine must be informed of this function.
  10468. @<Set up the scripting engine@>=
  10469. constructor = engine->newFunction(constructLogEditWindow);
  10470. value = engine->newQMetaObject(&LogEditWindow::staticMetaObject, constructor);
  10471. engine->globalObject().setProperty("LogEditWindow", value);
  10472. @ The constructor just creates the window and passes it back to the engine.
  10473. @<Functions for scripting@>=
  10474. QScriptValue constructLogEditWindow(QScriptContext *, QScriptEngine *engine)
  10475. {
  10476. QScriptValue object = engine->newQObject(new LogEditWindow);
  10477. return object;
  10478. }
  10479. @** File IO.
  10480. \noindent So far, the data is all stored in memory. It is often useful to save
  10481. data to a file or read back previously saved data. Presently, two formats are
  10482. supported: an XML format which can also be read back in and CSV which can easily
  10483. be used with many external tools.
  10484. File IO is handled by a few classes: one per input format and one per output
  10485. format. The classes in the following sections should be simple enough to follow
  10486. that it should be clear how to extend \pn{} to support other formats if needed.
  10487. Should additional output formats be required, it may be beneficial to
  10488. reimplement the serializers as subclasses of a new abstract serializer class in
  10489. order to share common code among them where reusing \cweb{} chunks is not an
  10490. appropriate technique.
  10491. @* XML Output.
  10492. \noindent An XML format has been chosen as the native format for \pn{} because
  10493. of Qt'@q'@>s excellent support for reading and writing such documents. Using this
  10494. capability is less error prone than developing a new, more compact format.
  10495. Another reason to choose XML is that it becomes quite easy to modify saved data
  10496. in a text editor and still end up with something \pn{} will understand.
  10497. The structure of the file we will produce is simple, however it has been
  10498. modified from a simpler structure that was used in versions of Typica prior to
  10499. 1.2.3. How to read these files can be determined by the document type found at
  10500. the start of the file. At the start of the file, there should be one or more
  10501. {\tt <tempseries>} elements and one or more {\tt <noteseries>} elements. These
  10502. are empty elements with a {\tt name} attribute which can be used to label the
  10503. column in a view. Once these column declarations have been written, a
  10504. {\tt <roast>} element is produced which contains a set of zero or more
  10505. {\tt <tuple>} elements. Each tuple contains one {\tt <time>} element containing
  10506. the time of the measurement relative to the start of the batch and optionally
  10507. one or more {\tt <temperature>} and {\tt <annotation>} elements containing
  10508. measurement and annotation data associated with that time. The
  10509. {\tt <temperature>} and {\tt <annotation>} elements have a {\tt series}
  10510. attribute where the value of the attribute matches the {\tt name} attribute of a
  10511. {\tt <tempseries>} or {\tt <noteseries>} element which allows each measurement
  10512. to be placed in the correct data series regardless of element ordering in the
  10513. document.
  10514. There are certain oddities about this format compared with other XML based
  10515. formats. The order of some elements in the current implementation affects the
  10516. behavior of the program and there is no longer a proper root element. This
  10517. format may be extended in future versions of \pn{} to support additional
  10518. functionality or to improve the robustness of the format. Should such
  10519. modifications occur, an effort should be made to ensure that \pn{} continues to
  10520. support the import of old data.
  10521. As of version 1.0.8, this class is derived from |QObject| for easier integration
  10522. with the scripting engine.
  10523. The |temperatureColumns| and |annotationColumns| member data structures are
  10524. currently a |QMap| rather than a |QHash| because the number of data series in a
  10525. single file is likely to be small enough that the difference in lookup time
  10526. should be negligeable and the ability to iterate over the keys in the |QMap| in
  10527. sorted order is useful.
  10528. @<Class declarations@>=
  10529. class XMLOutput : public QObject@/
  10530. {@/
  10531. Q_OBJECT@;@/
  10532. MeasurementModel *data;
  10533. QIODevice *out;
  10534. int time;
  10535. QMap<int, QString> temperatureColumns;
  10536. QMap<int, QString> controlColumns;
  10537. QMap<int, QString> annotationColumns;
  10538. public:@/
  10539. XMLOutput(MeasurementModel *model, QIODevice *device, int timec = 0);
  10540. void addTemperatureColumn(const QString &series, int column);
  10541. void addControlColumn(const QString &series, int column);
  10542. void addAnnotationColumn(const QString &series, int column);
  10543. void setModel(MeasurementModel *model);
  10544. void setTimeColumn(int column);
  10545. void setDevice(QIODevice *device);
  10546. bool output();
  10547. };
  10548. @ The interesting part of this class is the |output| routine. This goes over the
  10549. data in the model and constructs an appropriate XML document. If the operation
  10550. fails, the function returns |false|, otherwise it returns |true|.
  10551. @<XMLOutput Implementation@>=
  10552. bool XMLOutput::output()@t\2\2@>@/
  10553. {@t\1@>@/
  10554. if(!out->open(QIODevice::WriteOnly | QIODevice::Text))@/
  10555. {@t\1@>@/
  10556. return false;@t\2@>@/
  10557. }@/
  10558. QXmlStreamWriter xmlout(out);
  10559. xmlout.writeStartDocument("1.0");
  10560. xmlout.writeDTD("<!DOCTYPE roastlog3.0>");
  10561. xmlout.writeStartElement("roastlog");
  10562. @<Output the column declarations@>@;
  10563. xmlout.writeStartElement("roast");
  10564. bool oresult;
  10565. for(int i = 0; i < data->rowCount(); i++)@/
  10566. {
  10567. @<Check if row should be output@>@;
  10568. if(oresult)
  10569. {
  10570. @<Output tuple element@>@;
  10571. }
  10572. }
  10573. xmlout.writeEndElement();
  10574. xmlout.writeEndElement();
  10575. xmlout.writeEndDocument();
  10576. out->close();@/
  10577. return true;@t\2@>@/
  10578. }
  10579. @ Temperature column declarations are output before annotation column
  10580. declarations. Within each category, column declarations are output in order by
  10581. column number.
  10582. @<Output the column declarations@>=
  10583. foreach(int c, temperatureColumns.keys())
  10584. {
  10585. xmlout.writeStartElement("tempseries");
  10586. xmlout.writeAttribute("name", temperatureColumns.value(c));
  10587. xmlout.writeEndElement();
  10588. }
  10589. foreach(int c, controlColumns.keys())
  10590. {
  10591. xmlout.writeStartElement("controlseries");
  10592. xmlout.writeAttribute("name", controlColumns.value(c));
  10593. xmlout.writeEndElement();
  10594. }
  10595. foreach(int c, annotationColumns.keys())
  10596. {
  10597. xmlout.writeStartElement("noteseries");
  10598. xmlout.writeAttribute("name", annotationColumns.value(c));
  10599. xmlout.writeEndElement();
  10600. }
  10601. @ When checking a row in the model to determine if it contains values that need
  10602. to be written, we want to know if any of the temperature or annotation columns
  10603. contain a value. If at least one of these columns is not empty for this row, we
  10604. need to output a tuple for that row.
  10605. @<Check if row should be output@>=
  10606. oresult = false;@/
  10607. foreach(int c, temperatureColumns.keys())@/
  10608. {@t\1@>@/
  10609. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  10610. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))@/
  10611. {@t\1@>@/
  10612. oresult = true;
  10613. break;@t\2@>@/
  10614. }@t\2@>@/
  10615. }@/
  10616. foreach(int c, controlColumns.keys())
  10617. {
  10618. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  10619. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))
  10620. {
  10621. oresult = true;
  10622. break;
  10623. }
  10624. }
  10625. if(oresult == false)@/
  10626. {@t\1@>@/
  10627. foreach(int c, annotationColumns.keys())@/
  10628. {@t\1@>@/
  10629. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  10630. !(data->data(data->index(i, c), Qt::DisplayRole).toString().
  10631. isEmpty()))@/
  10632. {@t\1@>@/
  10633. oresult = true;
  10634. break;@t\2@>@/
  10635. }@t\2@>@/
  10636. }@t\2@>@/
  10637. }
  10638. @ Now that we know that values from the current row should be output, we can
  10639. produce a {\tt <tuple>} element, a {\tt <time>} element for that tuple, and then
  10640. iterate over the set of columns we might want to output, producing an
  10641. appropriate element for each non-empty column for that row.
  10642. @<Output tuple element@>=
  10643. xmlout.writeStartElement("tuple");
  10644. xmlout.writeTextElement("time", data->data(data->index(i, time),
  10645. Qt::DisplayRole).toString());
  10646. foreach(int c, temperatureColumns.keys())@/
  10647. {
  10648. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  10649. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))@/
  10650. {
  10651. xmlout.writeStartElement("temperature");
  10652. xmlout.writeAttribute("series", temperatureColumns.value(c));
  10653. if(data->data(data->index(i, c), Qt::UserRole).toMap().contains("relative"))
  10654. {
  10655. if(data->data(data->index(i, c), Qt::UserRole).toMap().value("relative").toBool())
  10656. {
  10657. xmlout.writeAttribute("relative", "true");
  10658. }
  10659. }
  10660. xmlout.writeCharacters(data->data(data->index(i, c), Qt::DisplayRole).
  10661. toString());
  10662. xmlout.writeEndElement();
  10663. }
  10664. }
  10665. foreach(int c, controlColumns.keys())
  10666. {
  10667. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  10668. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))
  10669. {
  10670. xmlout.writeStartElement("control");
  10671. xmlout.writeAttribute("series", controlColumns.value(c));
  10672. xmlout.writeCharacters(data->data(data->index(i, c), Qt::DisplayRole).toString());
  10673. xmlout.writeEndElement();
  10674. }
  10675. }
  10676. foreach(int c, annotationColumns.keys())@/
  10677. {
  10678. if(data->data(data->index(i, c), Qt::DisplayRole).isValid() &&
  10679. !(data->data(data->index(i, c), Qt::DisplayRole).toString().isEmpty()))@/
  10680. {
  10681. xmlout.writeStartElement("annotation");
  10682. xmlout.writeAttribute("series", annotationColumns.value(c));
  10683. xmlout.writeCharacters(data->data(data->index(i, c), Qt::DisplayRole).
  10684. toString());
  10685. xmlout.writeEndElement();
  10686. }
  10687. }
  10688. xmlout.writeEndElement();
  10689. @ The rest of the class just initializes the private member data.
  10690. @<XMLOutput Implementation@>=
  10691. XMLOutput::XMLOutput(MeasurementModel *model, QIODevice *device, int timec)
  10692. : QObject(NULL), data(model), out(device), time(timec)@/
  10693. {
  10694. /* Nothing has to be done here. */
  10695. }@;
  10696. void XMLOutput::setModel(MeasurementModel *model)
  10697. {
  10698. data = model;
  10699. }
  10700. void XMLOutput::setTimeColumn(int column)
  10701. {
  10702. time = column;
  10703. }
  10704. void XMLOutput::setDevice(QIODevice *device)
  10705. {
  10706. out = device;
  10707. }
  10708. @ As of version 1.2.3, the old |setTemperatureColumn()| and
  10709. |setAnnotationColumn()| methods have been replaced with the
  10710. |addTemperatureColumn()| and |addAnnotationColumn()| methods respectively. The
  10711. main difference is that the new methods take a column name in addition to a
  10712. number and it is now possible to specify multiple columns of each category for
  10713. export.
  10714. @<XMLOutput Implementation@>=
  10715. void XMLOutput::addTemperatureColumn(const QString &series, int column)
  10716. {
  10717. temperatureColumns.insert(column, series);
  10718. }
  10719. void XMLOutput::addControlColumn(const QString &series, int column)
  10720. {
  10721. controlColumns.insert(column, series);
  10722. }
  10723. void XMLOutput::addAnnotationColumn(const QString &series, int column)
  10724. {
  10725. annotationColumns.insert(column, series);
  10726. }
  10727. @* XML Input.
  10728. \noindent Once model data can be saved to a file, it is useful to be able to
  10729. read that data back in. This is a little different from reading data out of a
  10730. model as more than one object is potentially interested in the data. Instead, we
  10731. emit signals for measurements and annotations. This class has been modified to
  10732. support both the current (as of version 1.2.3) output of the |XMLOutput| class
  10733. and the older version. If changes are made to |XMLOutput| this class may also
  10734. need to be modified.
  10735. The main differences in the current version of this class are that the first
  10736. column is specified rather than specifying temperature and annotation columns
  10737. separately and additional signals are emitted to allow views to prepare for an
  10738. arbitrary number of columns.
  10739. The |newTemperatureColumn| and |newAnnotationColumn| signals can be used to set
  10740. up column headers while the |lastColumn| signal can be used to shift live data
  10741. streams to unoccupied columns.
  10742. @<Class declarations@>=
  10743. class XMLInput : public QObject@/
  10744. {
  10745. Q_OBJECT@;
  10746. int firstc;
  10747. QIODevice *in;
  10748. public:@/
  10749. XMLInput(QIODevice *input, int c);
  10750. void setFirstColumn(int column);
  10751. void setDevice(QIODevice *device);
  10752. bool input();
  10753. signals:@/
  10754. void measure(Measurement, int);
  10755. void annotation(QString, int, int);
  10756. void newTemperatureColumn(int, QString);
  10757. void newAnnotationColumn(int, QString);
  10758. void lastColumn(int);
  10759. };
  10760. @ The main point of interest here is the |input()| method. If the file is read
  10761. successfully, |true| is returned. Otherwise, |false| is returned.
  10762. @<XMLInput Implementation@>=
  10763. bool XMLInput::input()@t\2\2@>@/
  10764. {@t\1@>@/
  10765. if(!in->open(QIODevice::ReadOnly | QIODevice::Text))@/
  10766. {@t\1@>@/
  10767. return false;@t\2@>@/
  10768. }@/
  10769. QXmlStreamReader xmlin(in);
  10770. QMap<QString, int> temperatureColumns;
  10771. QMap<QString, int> annotationColumns;
  10772. int nextColumn = firstc;
  10773. @<Read column declarations@>@;
  10774. QTime timeval = QTime();
  10775. double tempval = 0;
  10776. QString noteval = QString();
  10777. int column;
  10778. int counter = 0;@/
  10779. while(!xmlin.atEnd())@/
  10780. {@/
  10781. @<Read XML file@>@;
  10782. }@/
  10783. return true;@t\2@>@/
  10784. }
  10785. @ A data file may or may not contain elements that specify the name of a column.
  10786. In order to determine how to proceed, we should check the doctype of the input
  10787. file. This should be the first element of the input file encountered.
  10788. \danger There is not nearly enough error checking here.
  10789. \endanger
  10790. @<Read column declarations@>=
  10791. while(!xmlin.isDTD())
  10792. {
  10793. xmlin.readNext();
  10794. }
  10795. if(xmlin.isDTD())
  10796. {
  10797. if(xmlin.text() == "<!DOCTYPE roastlog>")
  10798. {
  10799. @<Emit old format column specification@>@;
  10800. }
  10801. else
  10802. {
  10803. xmlin.readNext();
  10804. @<Scan for column declarations and emit@>@;
  10805. }
  10806. }
  10807. @ Old format data will not have column declarations. This means that we must
  10808. produce a default set of signals rather than waiting to read elements describing
  10809. the columns.
  10810. @<Emit old format column specification@>=
  10811. emit newTemperatureColumn(firstc, "Bean");
  10812. emit newAnnotationColumn(firstc + 1, "Note");
  10813. emit lastColumn(firstc + 1);
  10814. @ The current format will have column declarations prior to the {\tt <roast>}
  10815. element. We can just read until we hit that element and emit the appropriate
  10816. signals as elements are encountered.
  10817. @<Scan for column declarations and emit@>=
  10818. while(xmlin.name() != "roast")
  10819. {
  10820. if(xmlin.isStartElement())
  10821. {
  10822. if((xmlin.name() == "tempseries") || (xmlin.name() == "controlseries"))
  10823. {
  10824. temperatureColumns.insert(xmlin.attributes().value("name").
  10825. toString(),
  10826. nextColumn);
  10827. emit newTemperatureColumn(nextColumn,
  10828. xmlin.attributes().value("name").
  10829. toString());
  10830. nextColumn++;
  10831. }
  10832. else if(xmlin.name() == "noteseries")
  10833. {
  10834. annotationColumns.insert(xmlin.attributes().value("name").
  10835. toString(), nextColumn);
  10836. emit newAnnotationColumn(nextColumn,
  10837. xmlin.attributes().value("name").
  10838. toString());
  10839. nextColumn++;
  10840. }
  10841. }
  10842. xmlin.readNext();
  10843. }
  10844. emit lastColumn(nextColumn - 1);
  10845. @ Now we are ready to read measurements from the file. When encountering a
  10846. {\tt <time>} element, we record the time and move on. For {\tt <temperature>}
  10847. and {\tt <annotation>} elements, we emit the appropriate signal. This is handled
  10848. slightly differently depending on which version of the file format is being
  10849. used. Note that there is not nearly enough error checking here and we are
  10850. basically ignoring {\tt <tuple>} elements.
  10851. Due to the typically large number of measurements taken over the course of a
  10852. roast and the amount of time often taken to process these measurements when they
  10853. are read from a file, there is a need to periodically pass control back to the
  10854. event loop to remain responsive to user input.
  10855. @<Read XML file@>=
  10856. xmlin.readNext();
  10857. if(xmlin.isStartElement())
  10858. {
  10859. @<Read measurement data@>@;
  10860. }
  10861. counter++;
  10862. if(counter % 100 == 0)
  10863. {
  10864. QCoreApplication::processEvents();
  10865. }
  10866. @ When reading start elements, it is safe to ignore {\tt <tuple>} and
  10867. {\tt <roast>}. Technically, this means that the program can read certain types
  10868. of invalid data. The Robustness Principle\nfnote{``Be liberal in what you
  10869. accept, and conservative in what you send,'' --- Robert Braden, {\it RFC 1122
  10870. \S 1.2.2}} is generally applicable to any type of data exchange. That said,
  10871. malformed data is not guaranteed readable in the future, even if it does work
  10872. now.
  10873. \danger One set of test input caused this code to emit an empty annotation for
  10874. every measurement. This is the reason for wrapping the annotation signal
  10875. emission to check for this. The detected annotation elements were not present in
  10876. the input stream and I have absolutely no idea where the program came up with
  10877. them. \endanger
  10878. @<Read measurement data@>=
  10879. if(xmlin.name() == "time")
  10880. {
  10881. timeval = QTime::fromString(xmlin.readElementText(), "mm:ss.zzz");
  10882. }
  10883. else if(xmlin.name() == "temperature")
  10884. {
  10885. column = xmlin.attributes().hasAttribute("series") ?
  10886. temperatureColumns.value(xmlin.attributes().value("series").toString()) : firstc;
  10887. bool relative = (xmlin.attributes().value("relative") == "true");
  10888. tempval = xmlin.readElementText().toDouble();
  10889. Measurement measurement(tempval, timeval);
  10890. if(relative)
  10891. {
  10892. measurement.insert("relative", true);
  10893. }
  10894. emit measure(measurement, column);
  10895. }
  10896. else if(xmlin.name() == "control")
  10897. {
  10898. column = xmlin.attributes().value("series").toString().isEmpty() ?
  10899. firstc : temperatureColumns.value(xmlin.attributes().
  10900. value("series").toString());
  10901. tempval = xmlin.readElementText().toDouble();
  10902. Measurement measurement(tempval, timeval, Units::Unitless);
  10903. emit measure(measurement, column);
  10904. }
  10905. else if(xmlin.name() == "annotation")
  10906. {
  10907. column = xmlin.attributes().value("series").toString().isEmpty() ?
  10908. firstc + 1 : annotationColumns.value(xmlin.attributes().
  10909. value("series").toString());
  10910. noteval = xmlin.readElementText();
  10911. if(!noteval.isEmpty())
  10912. {
  10913. emit annotation(noteval, firstc, column);
  10914. }
  10915. }
  10916. @ The other methods just set the private member data.
  10917. @<XMLInput Implementation@>=
  10918. XMLInput::XMLInput(QIODevice *input, int c) :
  10919. firstc(c), in(input)@/
  10920. {@/
  10921. /* Nothing has to be done here. */
  10922. }
  10923. void XMLInput::setFirstColumn(int column)
  10924. {
  10925. firstc = column;
  10926. }
  10927. void XMLInput::setDevice(QIODevice *device)
  10928. {
  10929. in = device;
  10930. }
  10931. @ In order to allow scripts to instantiate the |XMLInput| class, we need a
  10932. constructor and a wrapper around the |input()| method.
  10933. @<Function prototypes for scripting@>=
  10934. QScriptValue constructXMLInput(QScriptContext *context, QScriptEngine *engine);
  10935. QScriptValue XMLInput_input(QScriptContext *context, QScriptEngine *engine);
  10936. @ The script constructor is passed to the scripting engine.
  10937. @<Set up the scripting engine@>=
  10938. constructor = engine->newFunction(constructXMLInput);
  10939. value = engine->newQMetaObject(&XMLInput::staticMetaObject, constructor);
  10940. engine->globalObject().setProperty("XMLInput", value);
  10941. @ The implementation should seem familiar.
  10942. @<Functions for scripting@>=
  10943. QScriptValue constructXMLInput(QScriptContext *context, QScriptEngine *engine)
  10944. {
  10945. QIODevice *device = argument<QIODevice *>(0, context);
  10946. QScriptValue object = engine->newQObject(new XMLInput(&*device,
  10947. argument<int>(1, context)));
  10948. object.setProperty("input", engine->newFunction(XMLInput_input));
  10949. return object;
  10950. }
  10951. QScriptValue XMLInput_input(QScriptContext *context, QScriptEngine *)
  10952. {
  10953. XMLInput *self = getself<@[XMLInput *@]>(context);
  10954. self->input();
  10955. return QScriptValue();
  10956. }
  10957. @* CSV Output.
  10958. \noindent While XML is convenient for \pn{}, other programs may not handle this
  10959. format well. For this purpose, we use a text file with comma separated values.
  10960. Data in this format can easily be handled by shell scripts, simple programs, and
  10961. any spreadsheet (though some may handle the time column poorly).
  10962. We do not need to concern ourselves with reading data in this format back in,
  10963. but there is no reason a class could not be written to do this.
  10964. The structure of this class is very similar to the |XMLOutput| class.
  10965. @<Class declarations@>=
  10966. class CSVOutput@/
  10967. {@/
  10968. MeasurementModel *data;
  10969. QIODevice *out;
  10970. int time;
  10971. QMap<int, QString> temperatureColumns;
  10972. QMap<int, QString> controlColumns;
  10973. QMap<int, QString> annotationColumns;@/
  10974. public:@/
  10975. CSVOutput(MeasurementModel *model, QIODevice *device, int timec = 0);
  10976. void addTemperatureColumn(const QString &series, int column);
  10977. void addControlColumn(const QString &series, int column);
  10978. void addAnnotationColumn(const QString &series, int column);
  10979. void setModel(MeasurementModel *model);
  10980. void setTimeColumn(int column);
  10981. void setDevice(QIODevice *device);
  10982. bool output();@/
  10983. };
  10984. @ Very little needs to be done to output the data. We open the output stream
  10985. and, if the output stream was successfully opened, we look for measurements and
  10986. output the text, remembering to output a comma between items and a newline after
  10987. each record. If the data is successfully output, |true| is returned, otherwise
  10988. we return |false|.
  10989. The comparably simple structure of the CSV format allows us to just fling the
  10990. data onto a text stream.
  10991. @<CSVOutput Implementation@>=
  10992. bool CSVOutput::output()@t\2\2@>@/
  10993. {@t\1@>@/
  10994. if(!out->open(QIODevice::WriteOnly | QIODevice::Text))@/
  10995. {@t\1@>@/
  10996. return false;@t\2@>@/
  10997. }@/
  10998. QTextStream output(out);
  10999. @<Output CSV column headers@>@;
  11000. bool oresult;
  11001. for(int i = 0; i < data->rowCount(); i++)@/
  11002. {
  11003. @<Check if row should be output@>@;
  11004. if(oresult)
  11005. {
  11006. @<Output CSV row@>@;
  11007. }
  11008. }
  11009. out->close();@/
  11010. return true;@t\2@>@/
  11011. }
  11012. @ Before writing the data, we output a row containing the name of each column.
  11013. @<Output CSV column headers@>=
  11014. output << "Time";
  11015. foreach(int c, temperatureColumns.keys())
  11016. {
  11017. output << ',' << temperatureColumns.value(c);
  11018. }
  11019. foreach(int c, controlColumns.keys())
  11020. {
  11021. output << ',' << controlColumns.value(c);
  11022. }
  11023. foreach(int c, annotationColumns.keys())
  11024. {
  11025. output << ',' << annotationColumns.value(c);
  11026. }
  11027. output << '\n';
  11028. @ Once the header information has been written, we can proceed to output the
  11029. real data. The algorithm for doing this has been changed as of version 1.2.3
  11030. with the result that most uses will now produce more delimiters than the same
  11031. data in previous versions. This should have no impact on the ability of other
  11032. programs to interact with data produced by \pn{}. The code to handle output in
  11033. this way is much easier to read. A future version might once again suppress
  11034. superfluous commas, however the presence of these commas is not considered a
  11035. serious issue at this time.
  11036. @<Output CSV row@>=
  11037. output << data->data(data->index(i, time), Qt::DisplayRole).toString();
  11038. foreach(int c, temperatureColumns.keys())
  11039. {
  11040. output << ',' << data->data(data->index(i, c), Qt::DisplayRole).toString();
  11041. }
  11042. foreach(int c, controlColumns.keys())
  11043. {
  11044. output << ',' << data->data(data->index(i, c), Qt::DisplayRole).toString();
  11045. }
  11046. foreach(int c, annotationColumns.keys())
  11047. {
  11048. output << ',' << data->data(data->index(i, c), Qt::DisplayRole).toString();
  11049. }
  11050. output << '\n';
  11051. @ The rest of the class just initializes the private member data. See notes
  11052. on the implementation of |XMLOutput|.
  11053. @<CSVOutput Implementation@>=
  11054. CSVOutput::CSVOutput(MeasurementModel *model, QIODevice *device, int timec) :
  11055. data(model), out(device), time(timec)@/
  11056. {
  11057. /* Nothing has to be done here. */
  11058. }@;
  11059. void CSVOutput::setModel(MeasurementModel *model)
  11060. {
  11061. data = model;
  11062. }
  11063. void CSVOutput::setTimeColumn(int column)
  11064. {
  11065. time = column;
  11066. }
  11067. void CSVOutput::addTemperatureColumn(const QString &series, int column)
  11068. {
  11069. temperatureColumns.insert(column, series);
  11070. }
  11071. void CSVOutput::addControlColumn(const QString &series, int column)
  11072. {
  11073. controlColumns.insert(column, series);
  11074. }
  11075. void CSVOutput::addAnnotationColumn(const QString &series, int column)
  11076. {
  11077. annotationColumns.insert(column, series);
  11078. }
  11079. void CSVOutput::setDevice(QIODevice *device)
  11080. {
  11081. out = device;
  11082. }
  11083. @i webview.w
  11084. @* The Application class.
  11085. The |Application| class represents the \pn{} program. It is responsible for
  11086. setting up the settings object and localization in addition to the normal
  11087. responsibilities of |QApplication|. In addition to declaring the class, we also
  11088. define a macro that returns the |Application| instance.
  11089. @<Class declarations@>=
  11090. #define AppInstance (qobject_cast<@[Application *@]>(qApp))
  11091. class NodeInserter;
  11092. class DeviceTreeModel;
  11093. class Application : public QApplication@/
  11094. {@/
  11095. @[Q_OBJECT@]@;
  11096. public:@/
  11097. Application(int &argc, char **argv);
  11098. QDomDocument* configuration();
  11099. @<Device configuration members@>@;
  11100. QSqlDatabase database();
  11101. QScriptEngine *engine;@/
  11102. @[public slots@]:@/
  11103. @<Extended Application slots@>@;
  11104. private:@/
  11105. @<Application private data members@>@;
  11106. QDomDocument conf;
  11107. };
  11108. @ The constructor for this class handles a few things that had previously been
  11109. handled in |main()|.
  11110. @<Application Implementation@>=
  11111. Application::Application(int &argc, char **argv) : QApplication(argc, argv)@/
  11112. {
  11113. @<Allow use of the default QSettings constructor@>@;
  11114. @<Load translation objects@>@;
  11115. @<Register meta-types@>@;
  11116. @<Register top level device configuration nodes@>@;
  11117. }
  11118. @ We use |QSettings| objects throughout \pn{} to remember details such as the
  11119. size and position of windows and the most recently used directory. To simplify
  11120. the creation of these objects, we specify some details up front. This allows us
  11121. to use the default constructor rather than specifying these things every time we
  11122. need an object.
  11123. @<Allow use of the default QSettings constructor@>=
  11124. setOrganizationName("Wilson's Coffee & Tea");
  11125. setOrganizationDomain("wilsonscoffee.com");
  11126. setApplicationName(PROGRAM_NAME);
  11127. @ Much of the user visible text in \pn{} is wrapped in a call to |tr()|. Such
  11128. text can be replaced with translated text based on the user'@q'@>s locale. For more
  11129. details, see the Qt Linguist manual.
  11130. @<Load translation objects@>=
  11131. QTranslator *base = new QTranslator;
  11132. if(base->load(QString("qt_%1").arg(QLocale::system().name()), QString("%1/Translations").arg(QCoreApplication::applicationDirPath())))
  11133. {
  11134. installTranslator(base);
  11135. }
  11136. QTranslator *app = new QTranslator;
  11137. if(app->load(QString("%1_%2").arg("Typica").arg(QLocale::system().name()), QString("%1/Translations").arg(QCoreApplication::applicationDirPath())))
  11138. {
  11139. installTranslator(app);
  11140. }
  11141. @ We also want to be able to access the application instance from within the
  11142. scripting engine. We don'@q'@>t need to be able to create new instances, just access
  11143. the one that already exists.
  11144. @<Set up the scripting engine@>=
  11145. value = engine->newQObject(AppInstance);
  11146. engine->globalObject().setProperty("Application", value);
  11147. @ The |configuration()| method provides access to an XML document containing the
  11148. current application configuration. The object is populated in |main()|.
  11149. @<Application Implementation@>=
  11150. QDomDocument* Application::configuration()
  11151. {
  11152. return &conf;
  11153. }
  11154. @ The |database()| method provides access to a database connection for use by
  11155. database aware widgets.
  11156. @<Application Implementation@>=
  11157. QSqlDatabase Application::database()
  11158. {
  11159. QString connectionName;
  11160. QSqlDatabase connection =
  11161. QSqlDatabase::database(QLatin1String(QSqlDatabase::defaultConnection), false);
  11162. do
  11163. {
  11164. connectionName = QUuid::createUuid().toString();
  11165. } while (QSqlDatabase::connectionNames().contains(connectionName));
  11166. return QSqlDatabase::cloneDatabase(connection, QString(connectionName));
  11167. }
  11168. @** Table editor for ordered arrays with SQL relations.
  11169. \noindent A database in use at Wilson's Coffee \char'046~Tea stores information
  11170. for a roasting log and uses entered information to adjust inventory tracking
  11171. tables. This roasting log connects the use of unroasted coffee with the creation
  11172. of roasted coffee. In order to support roasting coffee from more than one lot at
  11173. the same time, the columns that specify the types of coffee used and the amount
  11174. of each coffee are entered as ordered arrays in which the first entry in the
  11175. array specifying an unroasted coffee is associated with the first entry in the
  11176. array specifying the amount of coffee used. While most batches will involve only
  11177. a single unroasted coffee, the database has no limitation on the number of
  11178. coffees that may be roasted in a single batch. An additional characteristic of
  11179. this table is that the database requires an identification number for unroasted
  11180. coffee items, but it would be better to provide a list of acceptable items with
  11181. human readable names.
  11182. A scrollable area containing a table view which can provide the necessary input
  11183. delegates (such as a combo box for SQL relations) and validators which ensures
  11184. that there is always at least one empty row available for input with convenience
  11185. functions for extracting the arrays needed for database insertion would be ideal
  11186. for this.
  11187. To get this, we need a simple table model based on |QStandardItemModel|
  11188. or |QAbstractItemModel|. The model should ensure that there is always at least
  11189. one empty row available for editing. It should also provide a function for
  11190. obtaining a string that presents all values from a specified column with a given
  11191. role as an array literal suitable for binding to an SQL query.
  11192. A class based on |QComboBox| providing options selected from an SQL query will
  11193. be needed. This can be used as a standalone widget elsewhere, but here it is
  11194. also needed as an editor class for a column delegate. Another delegate class
  11195. allows input in another column to be constrained by a |QValidator| (in this case
  11196. a |QDoubleValidator|).
  11197. A class based on |QTableView| brings all of these classes together and presents
  11198. them to the user.
  11199. @* A table model for producing SQL array literals.
  11200. \noindent This is a simple table model which provides two somewhat unusual
  11201. features. First, it always provides at least one empty row at the end of the
  11202. data. Second, it provides SQL array literals for columns in the model.
  11203. \danger At some point I would like to replace this model and |MeasurementModel|
  11204. with an improved table model suitable to replace both. Some preliminary design
  11205. work suggests that this improvement simplifies \pn{} considerably both
  11206. internally and in the data flow configuration. This has not yet been done due to
  11207. development time constraints.\endanger
  11208. @<Class declarations@>=
  11209. class SaltModel : public QAbstractItemModel@/
  11210. {
  11211. Q_OBJECT@t\2\2@>@/
  11212. QList<QList<QMap<int, QVariant> > > modelData;
  11213. QStringList hData;
  11214. int colcount;@t\1\1@>@/
  11215. public:@/
  11216. SaltModel(int columns);
  11217. ~SaltModel();
  11218. int rowCount(const QModelIndex &parent = QModelIndex()) const;
  11219. int columnCount(const QModelIndex &parent = QModelIndex()) const;
  11220. bool setHeaderData(int section, Qt::Orientation@, orientation,
  11221. const QVariant &value, int role = Qt::DisplayRole);
  11222. QVariant data(const QModelIndex &index, int role) const;
  11223. bool setData(const QModelIndex &index, const QVariant &value,
  11224. int role = Qt::EditRole);
  11225. Qt::ItemFlags@, flags(const QModelIndex &index) const;
  11226. QVariant headerData(int section, Qt::Orientation@, orientation,
  11227. int role = Qt::DisplayRole) const;
  11228. QModelIndex index(int row, int column,
  11229. const QModelIndex &parent = QModelIndex()) const;
  11230. QModelIndex parent(const QModelIndex &index) const;
  11231. QString arrayLiteral(int column, int role) const;
  11232. QString quotedArrayLiteral(int column, int role) const;
  11233. void clear();
  11234. bool removeRows(int row, int count,
  11235. const QModelIndex &parent = QModelIndex());
  11236. int findData(const QVariant &value, int column, int role = Qt::UserRole);
  11237. };
  11238. @ The only unique methods in this class are the |arrayLiteral| and
  11239. |quotedArrayLiteral| methods. These take a column number and a data role and
  11240. produce a SQL array literal for every entry in that column with the specified
  11241. role. The string will take the form of
  11242. {\tt{'\LB row 1, row 2, }}$\dots$ {\tt{row N\RB '}}.
  11243. This is done simply by starting with a string identifying the start of an array
  11244. literal, looping over the rows in the model while appending any data found along
  11245. with the commas to separate values. If any data is found, the extra comma and
  11246. space are removed from the constructed string. Finally, text marking the end of
  11247. the array literal is added.
  11248. The |arrayLiteral| method is appropriate where the expected values are numeric.
  11249. The |quotedArrayLiteral| method is appropriate where the expected values are
  11250. text. The values in the array will have quotation marks around them for the
  11251. |quotedArrayLiteral|. Note that when binding these values to placeholders in a
  11252. SQL query the leading and trailing single quote characters should be removed.
  11253. \danger The way this method is currently used is quite harmless. Data from one
  11254. column is integer data obtained as a result of a previous database query and
  11255. data from the other column is restricted by the view to numeric data. Please
  11256. note, however, that it would be extremely stupid to use code such as this when
  11257. user input cannot be controlled so tightly. Were this model used with a view
  11258. that allows general text input, it would be trivial to construct an SQL
  11259. injection attack.
  11260. \medskip
  11261. \centerline{\includegraphics[width=6in]{exploits_of_a_mom}}
  11262. \smallskip
  11263. \centerline{Figure \secno: An Example of an SQL injection attack.\nfnote{%
  11264. Comic copyright Randall Munroe. Original can be found at:~%
  11265. \pdfURL{%
  11266. http://xkcd.com/327/}%
  11267. {http://xkcd.com/327/}}}
  11268. \medskip
  11269. \endanger
  11270. @<SaltModel Implementation@>=
  11271. QString SaltModel::arrayLiteral(int column, int role) const
  11272. {
  11273. QString literal = "'{";
  11274. for(int i = 0; i < rowCount(); i++)
  11275. {
  11276. QString datum = data(index(i, column), role).toString();
  11277. if(!datum.isEmpty())
  11278. {
  11279. literal.append(datum);
  11280. literal.append(", ");
  11281. }
  11282. }
  11283. if(literal.size() > 2)
  11284. {
  11285. literal.chop(2);
  11286. }
  11287. literal.append("}'");
  11288. return literal;
  11289. }
  11290. QString SaltModel::quotedArrayLiteral(int column, int role) const
  11291. {
  11292. QString literal = "'{";
  11293. for(int i = 0; i < rowCount(); i++)
  11294. {
  11295. QString datum = data(index(i, column), role).toString();
  11296. if(!datum.isEmpty())
  11297. {
  11298. literal.append("\"");
  11299. literal.append(datum);
  11300. literal.append("\", ");
  11301. }
  11302. }
  11303. if(literal.size() > 2)
  11304. {
  11305. literal.chop(2);
  11306. }
  11307. literal.append("}'");
  11308. return literal;
  11309. }
  11310. @ No entries in this model have children.
  11311. @<SaltModel Implementation@>=
  11312. QModelIndex SaltModel::parent(const QModelIndex &) const
  11313. {
  11314. return QModelIndex();
  11315. }
  11316. @ The |setData()| method is called by delegates on views when the user enters
  11317. new data. This method must check to determine if the data is being entered in
  11318. the last row to increase the size of the table.
  11319. The end of this function may seem a little strange. Why not simply look up the
  11320. map and insert information directly into the model data? Well, as of this
  11321. writing, that doesn'@q'@>t work. There are two ways around that problem. One is to
  11322. have the lists store references and dereference the real data. The other option
  11323. is to obtain a copy of the row, then a copy of the cell, update the cell, then
  11324. replace the old value of the cell in the copy of the row, then replace the old
  11325. values of the row in the real data. The other option would probably be more
  11326. efficient, but this does work.
  11327. @<SaltModel Implementation@>=
  11328. bool SaltModel::setData(const QModelIndex &index, const QVariant &value,
  11329. int role)@t\2\2@>@/
  11330. {@t\1@>@/
  11331. @<Check that the SaltModel index is valid@>@;
  11332. if(!valid)@/
  11333. {@t\1@>@/
  11334. return false;@t\2@>@/
  11335. }
  11336. if(index.row() == modelData.size() - 1)@/
  11337. {
  11338. beginInsertRows(QModelIndex(), modelData.size(), modelData.size());
  11339. @<Expand the SaltModel@>@;
  11340. endInsertRows();
  11341. }
  11342. QList<QMap<int, QVariant> > row = modelData.at(index.row());
  11343. QMap<int, QVariant> cell = row.at(index.column());
  11344. cell.insert(role, value);
  11345. if(role == Qt::EditRole)@/
  11346. {
  11347. cell.insert(Qt::DisplayRole, value);
  11348. }
  11349. row.replace(index.column(), cell);
  11350. modelData.replace(index.row(), row);
  11351. emit dataChanged(index, index);@/
  11352. return true;@t\2@>@/
  11353. }
  11354. @ Some model operations require checking that a model index is valid. This
  11355. chunk is used in these cases.
  11356. @<Check that the SaltModel index is valid@>=
  11357. bool valid = false;@/
  11358. if(index.isValid())@/
  11359. {@t\1@>@/
  11360. if(index.row() < modelData.size())@/
  11361. {@t\1@>@/
  11362. if(index.column() < colcount)@/
  11363. {@t\1@>@/
  11364. valid = true;@t\2@>@/
  11365. }@t\2@>@/
  11366. }@t\2@>@/
  11367. }
  11368. @ When data is modified in the last row of the table, the model must be expanded
  11369. to allow for additional data.
  11370. @<Expand the SaltModel@>=
  11371. QList<QMap<int, QVariant> > newRow;
  11372. QMap<int, QVariant> defaults;
  11373. for(int i = 0; i < colcount; i++)
  11374. {
  11375. newRow.append(defaults);
  11376. }
  11377. modelData.append(newRow);
  11378. @ The number of columns in the table is specified in the model constructor.
  11379. @<SaltModel Implementation@>=
  11380. SaltModel::SaltModel(int columns) : QAbstractItemModel(), colcount(columns)
  11381. {
  11382. for(int i = 0; i < columns; i++)
  11383. {
  11384. hData << "";
  11385. }
  11386. @<Expand the SaltModel@>@;
  11387. }
  11388. @ The destructor doesn'@q'@>t need to do anything.
  11389. @<SaltModel Implementation@>=
  11390. SaltModel::~SaltModel()
  11391. {
  11392. /* Nothing needs to be done here. */
  11393. }
  11394. @ A pair of methods provide the number of rows and columns in the model. No
  11395. entries in the model have children, so the parent should always be the invisible
  11396. root object.
  11397. @<SaltModel Implementation@>=
  11398. int SaltModel::rowCount(const QModelIndex &parent) const
  11399. {
  11400. return (parent == QModelIndex() ? modelData.size() : 0);
  11401. }
  11402. int SaltModel::columnCount(const QModelIndex &parent) const
  11403. {
  11404. return (parent == QModelIndex() ? colcount : 0);
  11405. }
  11406. @ The model maintains header data for labeling the model columns.
  11407. @<SaltModel Implementation@>=
  11408. bool SaltModel::setHeaderData(int section, Qt::Orientation@, orientation,@|
  11409. const QVariant &value, int)@t\2\2@>@/
  11410. {@t\1@>@/
  11411. if(orientation == Qt::Horizontal && section < colcount)@/
  11412. {@t\1@>@/
  11413. hData.replace(section, value.toString());@/
  11414. emit headerDataChanged(orientation, section, section);@/
  11415. return true;@t\2@>@/
  11416. }@/
  11417. return false;@t\2@>@/
  11418. }
  11419. @ Views need to be able to retrieve model and header data.
  11420. @<SaltModel Implementation@>=
  11421. QVariant SaltModel::data(const QModelIndex &index, int role) const
  11422. {
  11423. @<Check that the SaltModel index is valid@>@;
  11424. if(!valid)
  11425. {
  11426. return QVariant();
  11427. }
  11428. QList<QMap<int,QVariant> > row = modelData.at(index.row());
  11429. QMap<int,QVariant> cell = row.at(index.column());
  11430. return cell.value(role, QVariant());
  11431. }
  11432. QVariant SaltModel::headerData(int section, Qt::Orientation@, orientation,
  11433. int role) const
  11434. {
  11435. if(orientation == Qt::Horizontal && role == Qt::DisplayRole &&
  11436. section < colcount)
  11437. {
  11438. return QVariant(hData.at(section));
  11439. }
  11440. return QVariant();
  11441. }
  11442. @ Views need to know certain details such as if an item in the view can be
  11443. altered by the view. For this model, all valid indices can be edited.
  11444. @<SaltModel Implementation@>=
  11445. Qt::ItemFlags SaltModel::flags(const QModelIndex &index) const
  11446. {
  11447. @<Check that the SaltModel index is valid@>@;
  11448. if(valid)
  11449. {
  11450. return Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDropEnabled;
  11451. }
  11452. return 0;
  11453. }
  11454. @ So far, many of the methods use model indices. The model is responsible for
  11455. creating these.
  11456. @<SaltModel Implementation@>=
  11457. QModelIndex SaltModel::index(int row, int column,
  11458. const QModelIndex &parent) const
  11459. {
  11460. if(parent == QModelIndex())
  11461. {
  11462. if(row < modelData.size() && column < colcount)
  11463. {
  11464. return createIndex(row, column);
  11465. }
  11466. }
  11467. return QModelIndex();
  11468. }
  11469. @ There are some times when it is useful to clear the model data. Note that
  11470. column header data is retained and the table will contain a single empty row
  11471. after this method is called.
  11472. @<SaltModel Implementation@>=
  11473. void SaltModel::clear()
  11474. {
  11475. beginResetModel();
  11476. modelData.clear();
  11477. @<Expand the SaltModel@>@;
  11478. endResetModel();
  11479. }
  11480. @ Another commonly useful operation is the ability to remove rows from the
  11481. model. The new batch window uses this feature to eliminate rows in which the
  11482. coffee is set to NULL. Note that if all rows of the model are removed, a new
  11483. empty row will be created.
  11484. @<SaltModel Implementation@>=
  11485. bool SaltModel::removeRows(int row, int count,
  11486. const QModelIndex &parent)
  11487. {
  11488. if(parent == QModelIndex())
  11489. {
  11490. if(row >= 0 && count > 0 && (row + count - 1) < modelData.size())
  11491. {
  11492. beginRemoveRows(parent, row, row + count - 1);
  11493. for(int i = 0; i < count; i++)
  11494. {
  11495. modelData.removeAt(row);
  11496. }
  11497. endRemoveRows();
  11498. if(modelData.size() == 0)
  11499. {
  11500. beginInsertRows(parent, 0, 0);
  11501. @<Expand the SaltModel@>@;
  11502. endInsertRows();
  11503. }
  11504. return @[true@];
  11505. }
  11506. }
  11507. return @[false@];
  11508. }
  11509. @ To find the row number for removal operations it is useful to search for
  11510. special values on a given role. The |findData()| method returns the first row
  11511. in which the given value matches for a particular column and a particular role
  11512. or |-1| if no such match exists.
  11513. @<SaltModel Implementation@>=
  11514. int SaltModel::findData(const QVariant &value, int column, int role)
  11515. {
  11516. for(int i = 0; i < modelData.size(); i++)
  11517. {
  11518. if(modelData.at(i).size() > column)
  11519. {
  11520. if(modelData.at(i).at(column).contains(role))
  11521. {
  11522. if(modelData.at(i).at(column).value(role) == value)
  11523. {
  11524. return i;
  11525. }
  11526. }
  11527. }
  11528. }
  11529. return -1;
  11530. }
  11531. @* A Delegate for SQL Relations.
  11532. \noindent The first column of the table view being described is responsible for
  11533. providing item numbers to the database. Requiring that these numbers be entered
  11534. directly is prone to not particularly user friendly and almost encourages input
  11535. errors. These item numbers, however, refer to the items table in the database
  11536. which includes, among other details, a human readable text string naming the
  11537. item. This delegate provides the user with a drop down menu from which such a
  11538. string may be selected with this information provided by the database itself.
  11539. When the user selects an item, it informs the model not only of the text string
  11540. in the display role, but also of the id number in a user data role which can
  11541. later be queried in order to properly craft the appropriate query.
  11542. This is implemented with two classes. The first is a |QComboBox| which queries
  11543. the database and maintains a mapping of id to text. This is made its own widget
  11544. as it is useful without being turned into a delegate. The second class provides
  11545. this widget as a delegate and handles communications between it and the model.
  11546. @<Class declarations@>=
  11547. class SqlComboBox : public QComboBox@/
  11548. {@t\1@>@/
  11549. Q_OBJECT@;
  11550. int dataColumn;
  11551. int displayColumn;
  11552. bool dataColumnShown;
  11553. QString specialNullText;
  11554. QVariant specialNullData;
  11555. public:@/
  11556. SqlComboBox();
  11557. ~SqlComboBox();
  11558. SqlComboBox* clone(QWidget *parent);@/
  11559. @t\4@>public slots@t\kern-3pt@>:@/
  11560. void addNullOption();
  11561. void addSqlOptions(QString query);
  11562. void setDataColumn(int column);
  11563. void setDisplayColumn(int column);
  11564. void showData(bool show);
  11565. void setNullText(QString nullText);
  11566. void setNullData(QVariant nullData);@t\2@>@/
  11567. }@t\kern-3pt@>;
  11568. @ In order to make this class work a little more nicely as an item delegate,
  11569. the |clone()| method has been provided to create a new object with the same
  11570. options as a prototype.
  11571. @<SqlComboBox Implementation@>=
  11572. SqlComboBox* SqlComboBox::clone(QWidget *parent)
  11573. {
  11574. SqlComboBox *widget = new SqlComboBox();
  11575. widget->setParent(parent);
  11576. for(int i = 0; i < count(); i++)
  11577. {
  11578. widget->addItem(itemText(i), itemData(i));
  11579. }
  11580. return widget;
  11581. }
  11582. @ When using this class, we must first decide if the data column is shown. If
  11583. this is desired, the entries displayed will contain both the value from the
  11584. display column followed by the value from the data column. This can be useful in
  11585. cases where the same text is used for two different items.
  11586. @<SqlComboBox Implementation@>=
  11587. void SqlComboBox::showData(bool show)
  11588. {
  11589. dataColumnShown = show;
  11590. }
  11591. @ Next, there is a need to know if the NULL value may legally be selected. Where
  11592. this is the case, we generally want this to be inserted first. As the
  11593. |QComboBox| supports storing both display and user data, much of the code is a
  11594. thin wrapper around calls to the base class. The text and data for the NULL
  11595. value can be set arbitrarily, which can be useful in certain cases. Note that
  11596. any customization of the NULL text or data must be set before a call to
  11597. |addNullOption()|.
  11598. @<SqlComboBox Implementation@>=
  11599. void SqlComboBox::addNullOption()
  11600. {
  11601. addItem(specialNullText, specialNullData);
  11602. }
  11603. void SqlComboBox::setNullText(QString nullText)
  11604. {
  11605. specialNullText = nullText;
  11606. }
  11607. void SqlComboBox::setNullData(QVariant nullData)
  11608. {
  11609. specialNullData = nullData;
  11610. }
  11611. @ Typically, the SQL query used to populate this widget will request two columns
  11612. of data. One column is used as the display data, the other as user data. This is
  11613. done to present a human readable string where a database query needs an
  11614. identification number. By default, column |0| is used in both roles. If this
  11615. is not desired, the methods to change that must be called before specifying the
  11616. query.
  11617. @<SqlComboBox Implementation@>=
  11618. void SqlComboBox::setDataColumn(int column)
  11619. {
  11620. dataColumn = column;
  11621. }
  11622. void SqlComboBox::setDisplayColumn(int column)
  11623. {
  11624. displayColumn = column;
  11625. }
  11626. @ Once the widget is properly configured, we can run the SQL query and populate
  11627. the combo box with the results.
  11628. @<SqlComboBox Implementation@>=
  11629. void SqlComboBox::addSqlOptions(QString query)
  11630. {
  11631. SqlQueryConnection h;
  11632. QSqlQuery *dbquery = h.operator->();
  11633. if(!dbquery->exec(query))
  11634. {
  11635. QSqlError error = dbquery->lastError();
  11636. qDebug() << error.databaseText();
  11637. qDebug() << error.driverText();
  11638. qDebug() << error.text();
  11639. qDebug() << dbquery->lastQuery();
  11640. /* Throw an error here, please. */
  11641. }
  11642. while(dbquery->next())
  11643. {
  11644. QString displayValue(dbquery->value(displayColumn).toString());
  11645. QString dataValue(dbquery->value(dataColumn).toString());
  11646. if(dataColumnShown)
  11647. {
  11648. displayValue.append(QString(" (%1)").arg(dataValue));
  11649. }
  11650. addItem(displayValue, dataValue);
  11651. }
  11652. }
  11653. @ The constructor initializes some private member data. A size policy is also
  11654. set on the pop up. This allows the pop up to appear wider than the combo box to
  11655. allow more data to appear. On Linux this appears to also change the text elide
  11656. mode to something that is conveniently more appropriate for the use cases in
  11657. Typica. Note that this was not enough of a change to force the pop up to be
  11658. wide enough to contain all of the text for especially long items, but if the
  11659. combo box is wide enough the pop up will match that width.
  11660. The destructor is trivial.
  11661. @<SqlComboBox Implementation@>=
  11662. SqlComboBox::SqlComboBox() :
  11663. dataColumn(0), displayColumn(0), dataColumnShown(false),
  11664. specialNullText(tr("Unknown")), specialNullData(QVariant::String)
  11665. {
  11666. view()->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
  11667. }
  11668. SqlComboBox::~SqlComboBox()
  11669. {
  11670. /* Nothing needs to be done here. */
  11671. }
  11672. @ To use this class as an editor delegate in a model we wrap the class in a
  11673. |QItemDelegate|.
  11674. @<Class declarations@>=
  11675. class SqlComboBoxDelegate : public QItemDelegate@/
  11676. {
  11677. Q_OBJECT@;
  11678. SqlComboBox *delegate;
  11679. public:@/
  11680. SqlComboBoxDelegate(QObject *parent = NULL);
  11681. QWidget *createEditor(QWidget *parent,
  11682. const QStyleOptionViewItem &option,@|
  11683. const QModelIndex &index) const;
  11684. void setEditorData(QWidget *editor, const QModelIndex &index) const;
  11685. void setModelData(QWidget *editor, QAbstractItemModel *model,@|
  11686. const QModelIndex &index) const;
  11687. void setWidget(SqlComboBox *widget);
  11688. virtual QSize sizeHint() const;
  11689. void updateEditorGeometry(QWidget *editor,
  11690. const QStyleOptionViewItem &option,@|
  11691. const QModelIndex &index) const;
  11692. };
  11693. @ Rather than set the values for the combo box through the delegate class, we
  11694. create the editor and pass it in to the delegate.
  11695. @<SqlComboBoxDelegate Implementation@>=
  11696. void SqlComboBoxDelegate::setWidget(SqlComboBox *widget)
  11697. {
  11698. delegate = widget;
  11699. }
  11700. @ When a view requests this delegate, we simply return the widget that was
  11701. previously passed in.
  11702. @<SqlComboBoxDelegate Implementation@>=
  11703. QWidget* SqlComboBoxDelegate::createEditor(QWidget *parent,@|
  11704. const QStyleOptionViewItem &,
  11705. const QModelIndex &) const
  11706. {
  11707. return delegate->clone(parent);
  11708. }
  11709. @ To set the appropriate editor data, we check the value in the model and
  11710. attempt to set the value to match that.
  11711. @<SqlComboBoxDelegate Implementation@>=
  11712. void SqlComboBoxDelegate::setEditorData(QWidget *editor,
  11713. const QModelIndex &index) const
  11714. {
  11715. SqlComboBox *self = qobject_cast<SqlComboBox *>(editor);
  11716. self->setCurrentIndex(self->findData(
  11717. index.model()->data(index,
  11718. Qt::UserRole).toString()));
  11719. }
  11720. @ When setting the model data, we need to specify both the display role and the
  11721. user data role.
  11722. @<SqlComboBoxDelegate Implementation@>=
  11723. void SqlComboBoxDelegate::setModelData(QWidget *editor,@|
  11724. QAbstractItemModel *model,
  11725. const QModelIndex &index) const
  11726. {
  11727. SqlComboBox *self = qobject_cast<SqlComboBox *>(editor);
  11728. model->setData(index, self->itemData(self->currentIndex(), Qt::UserRole),
  11729. Qt::UserRole);
  11730. model->setData(index, self->currentText(), Qt::DisplayRole);
  11731. }
  11732. @ This is needed to play nicely with the model view architecture.
  11733. @<SqlComboBoxDelegate Implementation@>=
  11734. void SqlComboBoxDelegate::updateEditorGeometry(QWidget *editor,
  11735. const QStyleOptionViewItem &option,
  11736. const QModelIndex &) const
  11737. {
  11738. editor->setGeometry(option.rect);
  11739. }
  11740. @ When this delegate is used in a table view, we want to be able to provide a
  11741. size hint that can be used to resize the column in order to fit the delegate.
  11742. @<SqlComboBoxDelegate Implementation@>=
  11743. QSize SqlComboBoxDelegate::sizeHint() const
  11744. {
  11745. return delegate->sizeHint();
  11746. }
  11747. @ Finally, we need a constructor.
  11748. @<SqlComboBoxDelegate Implementation@>=
  11749. SqlComboBoxDelegate::SqlComboBoxDelegate(QObject *parent)
  11750. : QItemDelegate(parent)@/
  11751. {
  11752. /* Nothing needs to be done here. */
  11753. }
  11754. @** The main program.
  11755. The |main()| function is where program execution starts. Most of the work
  11756. required here is taken care of for us by the |Application| object.
  11757. The odd handling of argc is required to prevent segmentation faults in the Linux
  11758. build.
  11759. @<The main program@>=
  11760. int main(int argc, char **argv)@/
  11761. {@/
  11762. int *c = &argc;
  11763. Application app(*c, argv);
  11764. QSettings settings;
  11765. @<Set up logging@>@;
  11766. @<Set up icons@>@;
  11767. @<Set up fonts@>@;
  11768. @<Register device configuration widgets@>@;
  11769. @<Prepare the database connection@>@;
  11770. @<Load the application configuration@>@;
  11771. @<Set up the scripting engine@>@;
  11772. app.engine = engine;
  11773. @<Find and evaluate starting script@>@;
  11774. int retval = app.exec();
  11775. delete engine;
  11776. return retval;@/
  11777. }
  11778. @ \pn{} 1.6.3 introduces optional logging of diagnostic messages to a file. By
  11779. default this feature is not enabled. A sensible future refinement to this would
  11780. allow specification of where this file should be created.
  11781. @<Set up logging@>=
  11782. if(settings.value("settings/advanced/logging", false).toBool())
  11783. {
  11784. qInstallMsgHandler(messageFileOutput);
  11785. }
  11786. @ This requires that we have our messageFileOutput function.
  11787. @<Logging function prototype@>=
  11788. void messageFileOutput(QtMsgType type, const char *msg);
  11789. @ The current implementation is straightforward.
  11790. @<Logging function implementation@>=
  11791. void messageFileOutput(QtMsgType, const char *msg)
  11792. {
  11793. QFile output("Typica-"+QDate::currentDate().toString("yyyy-MM-dd")+".log");
  11794. output.open(QIODevice::WriteOnly | QIODevice::Append);
  11795. QTextStream outstream(&output);
  11796. outstream << msg << "\r\n";
  11797. }
  11798. @ \pn{} 1.4 introduces the ability to use icons in certain interface elements.
  11799. Some commonly desired public domain graphics are provided by the Tango Desktop
  11800. Project. We also set an application level default window icon.
  11801. @<Set up icons@>=
  11802. QStringList themeSearchPath = QIcon::themeSearchPaths();
  11803. themeSearchPath.append(":/resources/icons/tango");
  11804. QIcon::setThemeSearchPaths(themeSearchPath);
  11805. QIcon::setThemeName(":/resources/icons/tango");
  11806. app.setWindowIcon(QIcon(":/resources/icons/appicons/logo.svg"));
  11807. @ Similarly some elements make use of a special font which is loaded from
  11808. resource data.
  11809. There has been a report of a bug which I have not been able to reproduce and
  11810. which the original reporter has not yet gotten back to me with the results of
  11811. a test, so I have opted for an alternate approach which does not preclude the
  11812. use of the earlier plan but which may solve the matter. This brings in the
  11813. TeX Gyre Pagella font and sets this as the default standard font for all web
  11814. views.
  11815. @s QFontDatabase int
  11816. @s QWebSettings int
  11817. @<Set up fonts@>=
  11818. QFile entypo(":/resources/fonts/entypo.ttf");
  11819. entypo.open(QIODevice::ReadOnly);
  11820. QFontDatabase::addApplicationFontFromData(entypo.readAll());
  11821. entypo.close();
  11822. QFontDatabase::addApplicationFont(":/resources/fonts/texgyrepagella-regular.otf");
  11823. QFontDatabase::addApplicationFont(":/resources/fonts/texgyrepagella-bold.otf");
  11824. QFontDatabase::addApplicationFont(":/resources/fonts/texgyrepagella-bolditalic.otf");
  11825. QFontDatabase::addApplicationFont(":/resources/fonts/texgyrepagella-italic.otf");
  11826. QWebSettings::globalSettings()->setFontFamily(QWebSettings::StandardFont, "Tex Gyre Pagella");
  11827. @ Some widgets provided by \pn{} require access to a database in order to work.
  11828. To simplify using these widgets, the application will request information
  11829. needed to connect to a database. The use of two distinct |if| blocks rather than
  11830. an |if|$\dots$|else| construction is used because the data from settings can be
  11831. changed if an attempt to connect to the database fails.
  11832. @<Prepare the database connection@>=
  11833. if(settings.value("database/exists", "false").toString() == "true")
  11834. {
  11835. @<Try connecting to the database@>@;
  11836. }
  11837. if(settings.value("database/exists", "false").toString() == "false")
  11838. {
  11839. @<Prompt for database connection information@>@;
  11840. }
  11841. @ In order to connect to the database, we need five pieces of information: the
  11842. name of a database driver (PostgreSQL is recommended for now), the host name of
  11843. the computer running the database, the name of the database, the name of the
  11844. user connecting to the database, and that user'@q'@>s password. This information will
  11845. be stored in the user settings for the application so that the database
  11846. connection can be established without prompting the user next time. A class is
  11847. provided to gather this information.
  11848. @<Class declarations@>=
  11849. class SqlConnectionSetup : public QDialog@/
  11850. {@t\1@>@/
  11851. Q_OBJECT@;
  11852. public:@/
  11853. SqlConnectionSetup();
  11854. ~SqlConnectionSetup();@/
  11855. @t\4@>public slots@t\kern-3pt@>:@/
  11856. void testConnection();
  11857. private:@/
  11858. QFormLayout *formLayout;
  11859. QComboBox *driver;
  11860. QLineEdit *hostname;
  11861. QLineEdit *portnumber;
  11862. QLineEdit *dbname;
  11863. QLineEdit *user;
  11864. QLineEdit *password;
  11865. QVBoxLayout *layout;
  11866. QHBoxLayout *buttons;
  11867. QPushButton *cancelButton;
  11868. QPushButton *connectButton;@t\2@>@/
  11869. }@t\kern-3pt@>;
  11870. @ The constructor sets up this widget. The destructor does nothing.
  11871. @<SqlConnectionSetup implementation@>=
  11872. SqlConnectionSetup::SqlConnectionSetup() :
  11873. formLayout(new QFormLayout), driver(new QComboBox), hostname(new QLineEdit),
  11874. portnumber(new QLineEdit),
  11875. dbname(new QLineEdit), user(new QLineEdit), password(new QLineEdit),
  11876. layout(new QVBoxLayout), buttons(new QHBoxLayout),
  11877. cancelButton(new QPushButton(tr("Cancel"))),
  11878. connectButton(new QPushButton(tr("Connect")))@/
  11879. {
  11880. driver->addItem("PostgreSQL", "QPSQL");
  11881. formLayout->addRow(tr("Database driver:"), driver);
  11882. formLayout->addRow(tr("Host name:"), hostname);
  11883. formLayout->addRow(tr("Port number:"), portnumber);
  11884. portnumber->setText("5432");
  11885. formLayout->addRow(tr("Database name:"), dbname);
  11886. formLayout->addRow(tr("User name:"), user);
  11887. password->setEchoMode(QLineEdit::Password);
  11888. formLayout->addRow(tr("Password:"), password);
  11889. layout->addLayout(formLayout);
  11890. buttons->addStretch(1);
  11891. buttons->addWidget(cancelButton);
  11892. connect(cancelButton, SIGNAL(clicked(bool)), this, SLOT(reject()));
  11893. buttons->addWidget(connectButton);
  11894. layout->addLayout(buttons);
  11895. connect(connectButton, SIGNAL(clicked(bool)), this, SLOT(testConnection()));
  11896. connectButton->setDefault(true);
  11897. setLayout(layout);
  11898. setModal(true);
  11899. }
  11900. SqlConnectionSetup::~SqlConnectionSetup()
  11901. {
  11902. /* Nothing needs to be done here. */
  11903. }
  11904. @ The |testConnection()| method checks if the information provided can be used
  11905. to open a new database connection.
  11906. @<SqlConnectionSetup implementation@>=
  11907. void SqlConnectionSetup::testConnection()
  11908. {
  11909. QSqlDatabase database =
  11910. QSqlDatabase::addDatabase(driver->itemData(driver->currentIndex()).
  11911. toString());
  11912. database.setConnectOptions("application_name=Typica");
  11913. database.setHostName(hostname->text());
  11914. database.setPort(portnumber->text().toInt());
  11915. database.setDatabaseName(dbname->text());
  11916. database.setUserName(user->text());
  11917. database.setPassword(password->text());
  11918. if(database.open())
  11919. {
  11920. QSettings settings;
  11921. settings.setValue("database/exists", "true");
  11922. settings.setValue("database/driver",
  11923. driver->itemData(driver->currentIndex()).toString());
  11924. settings.setValue("database/hostname", hostname->text());
  11925. settings.setValue("database/portnumber", portnumber->text());
  11926. settings.setValue("database/dbname", dbname->text());
  11927. settings.setValue("database/user", user->text());
  11928. settings.setValue("database/password", password->text());
  11929. database.close();
  11930. accept();
  11931. }
  11932. else
  11933. {
  11934. QMessageBox::information(this, tr("Database connection failed"),
  11935. tr("Failed to connect to database."));
  11936. }
  11937. }
  11938. @ In order to prompt for connection information, we simply create a
  11939. |SqlConnectionSetup| object and call |exec()|. When control returns, the
  11940. settings will either contain appropriate connection information or we have to
  11941. give up on getting that information from the user for now.
  11942. @<Prompt for database connection information@>=
  11943. SqlConnectionSetup dialog;
  11944. dialog.exec();
  11945. @ If we have connected to a database in the previous running of the application,
  11946. we try to connect to the same database automatically rather than prompt the
  11947. user. If the connection attempt fails, we can fall back on asking the user for
  11948. help.
  11949. @<Try connecting to the database@>=
  11950. QSqlDatabase database =
  11951. QSqlDatabase::addDatabase(settings.value("database/driver").toString());
  11952. database.setConnectOptions("application_name=Typica");
  11953. database.setHostName(settings.value("database/hostname").toString());
  11954. database.setPort(settings.value("database/portnumber", 5432).toInt());
  11955. database.setDatabaseName(settings.value("database/dbname").toString());
  11956. database.setUserName(settings.value("database/user").toString());
  11957. database.setPassword(settings.value("database/password").toString());
  11958. if(!database.open())
  11959. {
  11960. settings.setValue("database/exists", "false");
  11961. }
  11962. else
  11963. {
  11964. database.close();
  11965. }
  11966. @** Viewing a record of batches.
  11967. \noindent It is frequently useful to present a table view with the results of a
  11968. SQL query and have a way of interacting with that view to obtain more details
  11969. related to a given record in that table. For this purpose, \pn{} provides a
  11970. widget based on |QTableView| which presents information from a
  11971. |QSqlQueryModel|. The table emits signals when an entry in the table is double
  11972. clicked. One of these contains the data from the first column of that row and
  11973. is suitable for use when a primary key is presented in that column and this is
  11974. sufficient for the desired drill down. The other signal provides the row number
  11975. which can be used along with a reference to the table to obtain the data in any
  11976. column.
  11977. This class also automatically persists column widths when these are changed.
  11978. @<Class declarations@>=
  11979. class SqlQueryView : public QTableView@/
  11980. {@/
  11981. @[Q_OBJECT@]@;
  11982. public:@/
  11983. SqlQueryView(QWidget *parent = NULL);
  11984. void setQuery(const QString &query);
  11985. bool setHeaderData(int section, Qt::Orientation@, orientation,
  11986. const QVariant &value, int role);
  11987. @[Q_INVOKABLE@,@, QVariant@]@, data(int row, int column,
  11988. int role = Qt::DisplayRole);@t\2\2@>@/
  11989. signals:@/
  11990. void openEntry(QString key);
  11991. void openEntryRow(int row);@/
  11992. protected:@/
  11993. virtual void showEvent(QShowEvent *event);@/
  11994. @[private slots@]:@/
  11995. void openRow(const QModelIndex &index);
  11996. void persistColumnResize(int column, int oldsize, int newsize);@/
  11997. };
  11998. @ The constructor sets up the communication between the model and the view and
  11999. also provides the connection needed to notice when columns change size to
  12000. persist that preference.
  12001. @<SqlQueryView implementation@>=
  12002. SqlQueryView::SqlQueryView(QWidget *parent) : QTableView(parent)
  12003. {
  12004. setModel(new QSqlQueryModel);
  12005. connect(this, SIGNAL(doubleClicked(QModelIndex)),
  12006. this, SLOT(openRow(QModelIndex)));
  12007. connect(horizontalHeader(), SIGNAL(sectionResized(int, int, int)),
  12008. this, SLOT(persistColumnResize(int, int, int)));
  12009. }
  12010. @ Column width persistance requires two methods. First we have a slot
  12011. method which is called when a column width is changed. This is saved with
  12012. |QSettings| under a key utilizing the name of the window, the name of the
  12013. table, and the column number.
  12014. @<SqlQueryView implementation@>=
  12015. void SqlQueryView::persistColumnResize(int column, int, int newsize)
  12016. {
  12017. @<Save updated column size@>@;
  12018. }
  12019. @ The body of this function has been split out so that it can be shared with
  12020. other table views without the need to introduce a new common base class.
  12021. @<Save updated column size@>=
  12022. QSettings settings;
  12023. @<Obtain top level widget@>@;
  12024. settings.setValue(QString("columnWidths/%1/%2/%3").
  12025. arg(topLevelWidget->objectName()).
  12026. arg(objectName()).arg(column),
  12027. QVariant(newsize));
  12028. @ To determine which window a given table is in, we just follow
  12029. |parentWidget()| until there isn'@q'@>t one. It is possible that the table view
  12030. will also be the window, however this is not advised as it is easier for the
  12031. settings key to be non-unique in such a case.
  12032. @<Obtain top level widget@>=
  12033. QWidget *topLevelWidget = this;
  12034. while(topLevelWidget->parentWidget())
  12035. {
  12036. topLevelWidget = topLevelWidget->parentWidget();
  12037. }
  12038. @ We restore column widths in response to a show event. One of these should be
  12039. received just before the widget is shown so the widget should appear correctly.
  12040. @<SqlQueryView implementation@>=
  12041. void SqlQueryView::showEvent(QShowEvent *event)
  12042. {
  12043. @<Restore table column widths@>@;
  12044. event->accept();
  12045. }
  12046. @ Similarly, most of the body of this method has also been split into a chunk
  12047. so that it might be shared with other classes.
  12048. @<Restore table column widths@>=
  12049. QSettings settings;
  12050. @<Obtain top level widget@>
  12051. QString baseKey =
  12052. QString("columnWidths/%1/%2").arg(topLevelWidget->objectName()).
  12053. arg(objectName());
  12054. for(int i = 0; i < model()->columnCount(); i++)
  12055. {
  12056. QString key = QString("%1/%2").arg(baseKey).arg(i);
  12057. if(settings.contains(key))
  12058. {
  12059. setColumnWidth(i, settings.value(key).toInt());
  12060. }
  12061. }
  12062. @ A slot is required for obtaining the information to send out in our signals.
  12063. @<SqlQueryView implementation@>=
  12064. void SqlQueryView::openRow(const QModelIndex &index)
  12065. {
  12066. emit openEntry(((QSqlQueryModel *)model())->record(index.row()).value(0).toString());
  12067. emit openEntryRow(index.row());
  12068. }
  12069. @ The other functions are wrappers around model methods.
  12070. @<SqlQueryView implementation@>=
  12071. void SqlQueryView::setQuery(const QString &query)
  12072. {
  12073. QSqlDatabase database = AppInstance->database();
  12074. database.open();
  12075. QSqlQuery q(query, database);
  12076. ((QSqlQueryModel*)model())->setQuery(q);
  12077. database.close();
  12078. }
  12079. bool SqlQueryView::setHeaderData(int section, Qt::Orientation@, orientation,
  12080. const QVariant &value, int role)
  12081. {
  12082. return model()->setHeaderData(section, orientation, value, role);
  12083. }
  12084. @ A method is also provided to allow scripts to access the data.
  12085. @<SqlQueryView implementation@>=
  12086. QVariant SqlQueryView::data(int row, int column, int role)
  12087. {
  12088. return model()->data(model()->index(row, column), role);
  12089. }
  12090. @ To use this class, it is useful to expose it to the host environment.
  12091. @<Function prototypes for scripting@>=
  12092. void setSqlQueryViewProperties(QScriptValue value, QScriptEngine *engine);
  12093. QScriptValue constructSqlQueryView(QScriptContext *context,
  12094. QScriptEngine *engine);
  12095. QScriptValue SqlQueryView_setQuery(QScriptContext *context,
  12096. QScriptEngine *engine);
  12097. QScriptValue SqlQueryView_setHeaderData(QScriptContext *context,
  12098. QScriptEngine *engine);
  12099. @ The script constructor is passed to the host environment.
  12100. @<Set up the scripting engine@>=
  12101. constructor = engine->newFunction(constructSqlQueryView);
  12102. value = engine->newQMetaObject(&SqlQueryView::staticMetaObject, constructor);
  12103. engine->globalObject().setProperty("SqlQueryView", value);
  12104. @ Next we construct the view, add properties to access its methods from the host
  12105. environment, and pass that back.
  12106. @<Functions for scripting@>=
  12107. QScriptValue constructSqlQueryView(QScriptContext *, QScriptEngine *engine)
  12108. {
  12109. QScriptValue object = engine->newQObject(new SqlQueryView);
  12110. setSqlQueryViewProperties(object, engine);
  12111. return object;
  12112. }
  12113. void setSqlQueryViewProperties(QScriptValue value, QScriptEngine *engine)
  12114. {
  12115. setQTableViewProperties(value, engine);
  12116. value.setProperty("setHeaderData",
  12117. engine->newFunction(SqlQueryView_setHeaderData));
  12118. value.setProperty("setQuery", engine->newFunction(SqlQueryView_setQuery));
  12119. }
  12120. @ The properties added are simplified wrappers around the class methods.
  12121. @<Functions for scripting@>=
  12122. QScriptValue SqlQueryView_setQuery(QScriptContext *context, QScriptEngine *)
  12123. {
  12124. SqlQueryView *self = getself<SqlQueryView *>(context);
  12125. QString query = argument<QString>(0, context);
  12126. self->setQuery(query);
  12127. self->reset();
  12128. return QScriptValue();
  12129. }
  12130. QScriptValue SqlQueryView_setHeaderData(QScriptContext *context,
  12131. QScriptEngine *)
  12132. {
  12133. SqlQueryView *self = getself<SqlQueryView *>(context);
  12134. int section = argument<int>(0, context);
  12135. QString data = argument<QString>(1, context);
  12136. self->setHeaderData(section, Qt::Horizontal, data, Qt::DisplayRole);
  12137. return QScriptValue();
  12138. }
  12139. @** Reporting.
  12140. \noindent \pn{} version 1.4 added a new type of menu which is designed to
  12141. handle reports. This makes extensive use of the previously existing reporting
  12142. system at present which makes modifying existing reports to work with the new
  12143. system very simple. Further changes may be introduced in the future that
  12144. substantially depart from this in order to simplify report files.
  12145. Previously to add a new report to a configuration, you needed to create the
  12146. report, add an {\tt <include>} tag in the main configuration file to bring that
  12147. report into the application configuration, then in any window with a Reports
  12148. menu you would need to add the report to that menu in its configuration file
  12149. and write a small bit of JavaScript to obtain a reference to that new menu
  12150. item and create the report when that menu item is triggered. This is highly
  12151. repetetive, error prone, and with the new approach it is not needed at all.
  12152. To add a new report to a configuration using the new approach one need only
  12153. save the new report file in the appropriate directory and \pn{} will detect
  12154. this, add it to any Reports menus that may exist, and handle all of the details
  12155. of generating these reports on demand.
  12156. The Reports menu is created in a configuration as a {\tt <menu>} element with
  12157. three attributes. The {\tt name} attribute as usual is the name of the menu
  12158. item. The {\tt type} attribute will have a value of {\tt "reports"} and the
  12159. {\tt src} attribute will indicate the directory to search for reports to
  12160. populate that menu. This allows for multiple Reports menus with different
  12161. reports in each menu if desired.
  12162. Reports are added to the menu in the order of the file names in the reports
  12163. directory.
  12164. \danger While it should not be an issue with the limited number of reports
  12165. presently distributed with Typica, the approach taken to implementing this menu
  12166. type is highly inefficient. There are many optimizations available if this
  12167. becomes problematic.\endanger
  12168. When a report menu is generated, the directory used for this is added as a
  12169. search path for the |"reports"| prefix. This is used by the |createReport()|
  12170. script method and is intended to allow access to reports from outside of the
  12171. Report menu.
  12172. @<Populate reports menu@>=
  12173. QSettings settings;
  12174. QString reportDirectory = QString("%1/%2").arg(settings.value("config").
  12175. toString()).
  12176. arg(element.attribute("src"));
  12177. QDir::addSearchPath("reports", reportDirectory);
  12178. QDir directory(reportDirectory);
  12179. directory.setFilter(QDir::Files);
  12180. directory.setSorting(QDir::Name);
  12181. QStringList nameFilter;
  12182. nameFilter << "*.xml";
  12183. directory.setNameFilters(nameFilter);
  12184. QFileInfoList reportFiles = directory.entryInfoList();
  12185. for(int i = 0; i < reportFiles.size(); i++)
  12186. {
  12187. QFileInfo reportFile = reportFiles.at(i);
  12188. @<Add report to reports menu@>@;
  12189. }
  12190. @ The menu items themselves are a subclass of |QAction| which holds all of the
  12191. information needed to respond to its activation by generating the appropriate
  12192. report.
  12193. @<Class declarations@>=
  12194. class ReportAction : public QAction@/
  12195. {@/
  12196. @[Q_OBJECT@]@;
  12197. public:@/
  12198. ReportAction(const QString &fileName, const QString &reportName,
  12199. QObject *parent = NULL);@/
  12200. @[private slots@]:@/
  12201. void createReport();@/
  12202. private:@/
  12203. QString reportFile;@/
  12204. };
  12205. @ The constructor receives the name of the report file which is used to
  12206. generate the report when needed and the name of the report which is used as the
  12207. name presented in the menu.
  12208. @<ReportAction implementation@>=
  12209. ReportAction::ReportAction(const QString &fileName, const QString &reportName,
  12210. QObject *parent) :
  12211. QAction(reportName, parent), reportFile(fileName)
  12212. {
  12213. connect(this, SIGNAL(triggered()), this, SLOT(createReport()));
  12214. }
  12215. @ The slot method is responsible for creating the new report. This is very
  12216. similar to the old approach and reuses much of the same code. Of particular
  12217. note is the |targetID| variable. This is set to facilitate window geometry
  12218. management, though this should probably be set from the {\tt id} attribute
  12219. of the {\tt <window>} element in the file to preserve window geometry
  12220. settings if the configuration is moved to another location in the file
  12221. system.
  12222. @<ReportAction implementation@>=
  12223. void ReportAction::createReport()
  12224. {
  12225. QFile file(reportFile);
  12226. QDomDocument document;
  12227. if(file.open(QIODevice::ReadOnly))
  12228. {
  12229. document.setContent(&file, true);
  12230. QDomElement element = document.documentElement();
  12231. QScriptEngine *engine = AppInstance->engine;
  12232. QScriptContext *context = engine->pushContext();
  12233. QScriptValue object;
  12234. QString targetID = reportFile;
  12235. @<Display the window@>@;
  12236. file.close();
  12237. engine->popContext();
  12238. }
  12239. }
  12240. @ With the |ReportAction| available, we are now ready to add reports to the
  12241. Reports menu. To do this we check each file in the given directory to determine
  12242. if it is a report file, obtain the report title and location within the menu
  12243. hierarchy from the file data, create the actions, and add them to the menu.
  12244. @<Add report to reports menu@>=
  12245. QString path = reportFile.absoluteFilePath();
  12246. QFile file(path);
  12247. if(file.open(QIODevice::ReadOnly))
  12248. {
  12249. QDomDocument document;
  12250. document.setContent(&file, true);
  12251. QDomElement root = document.documentElement();
  12252. QString translationContext = root.attribute("id");
  12253. QDomNode titleNode = root.elementsByTagName("reporttitle").at(0);
  12254. if(!titleNode.isNull())
  12255. {
  12256. QDomElement titleElement = titleNode.toElement();
  12257. QString title = QCoreApplication::translate("configuration",
  12258. titleElement.text().toUtf8().data());
  12259. if(!title.isEmpty())
  12260. {
  12261. QStringList hierarchy = title.split(":->");
  12262. QMenu *insertionPoint = menu;
  12263. @<Traverse report menu hierarchy@>
  12264. ReportAction *action = new ReportAction(path, hierarchy.last());
  12265. insertionPoint->addAction(action);
  12266. }
  12267. }
  12268. }
  12269. @ \pn{} allows the Reports menu to contain arbitrarily deep menu hierarchies.
  12270. It is advised to keep these hierarchies shallow.
  12271. @<Traverse report menu hierarchy@>=
  12272. for(int j = 0; j < hierarchy.size() - 1; j++)
  12273. {
  12274. QObjectList menuList = insertionPoint->children();
  12275. bool menuFound = @[false@];
  12276. for(int k = 0; k < menuList.size(); k++)
  12277. {
  12278. QMenu *currentItem = qobject_cast<QMenu*>(menuList.at(k));
  12279. if(currentItem)
  12280. {
  12281. if(currentItem->title() == hierarchy.at(j))
  12282. {
  12283. menuFound = @[true@];
  12284. insertionPoint = currentItem;
  12285. break;
  12286. }
  12287. }
  12288. }
  12289. if(!menuFound)
  12290. {
  12291. insertionPoint = insertionPoint->addMenu(hierarchy.at(j));
  12292. }
  12293. }
  12294. @ \noindent The reporting functionality in \pn{} is based on the Scribe framework
  12295. in Qt. This brings several benefits, including making it easy to print reports
  12296. or save reports as plain text or HTML.
  12297. Reports are specified in the \pn{}'@q'@>s configuration document and can include both
  12298. static elements and elements that are populated by external data such as the
  12299. result of a SQL query.
  12300. @<Function prototypes for scripting@>=
  12301. void addReportToLayout(QDomElement element, QStack<QWidget *> *widgetStack,
  12302. QStack<QLayout *> *layoutStack);
  12303. @ When adding a report to a layout, we must not only add the widget to the
  12304. layout, but also construct the document.
  12305. @<Functions for scripting@>=
  12306. void addReportToLayout(QDomElement element, QStack<QWidget *> *,@|
  12307. QStack<QLayout *> *layoutStack)
  12308. {
  12309. QTextEdit *widget = new QTextEdit;
  12310. if(element.hasAttribute("id"))
  12311. {
  12312. widget->setObjectName(element.attribute("id"));
  12313. }
  12314. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  12315. layout->addWidget(widget);
  12316. QTextDocument *document = new QTextDocument;
  12317. QFont defaultFont;
  12318. defaultFont.setPointSize(11);
  12319. document->setDefaultFont(defaultFont);
  12320. QTextCursor cursor(document);
  12321. @<Construct report document@>@;
  12322. widget->setDocument(document);
  12323. }
  12324. @ Several child elements are allowed under the {\tt <report>} element. These
  12325. should be processed in order to produce the final report document.
  12326. @<Construct report document@>=
  12327. QDomNodeList children = element.childNodes();
  12328. for(int i = 0; i < children.count(); i++)
  12329. {
  12330. QDomNode current;
  12331. QDomElement currentElement;
  12332. current = children.at(i);
  12333. if(current.isElement())
  12334. {
  12335. currentElement = current.toElement();
  12336. @<Process report document elements@>@;
  12337. }
  12338. }
  12339. @ If any custom styling for HTML content is required, a {\tt <style>} element
  12340. should be placed in the report description before any such content.
  12341. @<Process report document elements@>=
  12342. if(currentElement.tagName() == "style")
  12343. {
  12344. document->setDefaultStyleSheet(currentElement.text());
  12345. }
  12346. @ One common need is the ability to insert static text, such as the title of the
  12347. report. In order to simplify formatting, the text can be interpreted as HTML.
  12348. Note that to avoid having HTML tags eaten by the parser, the text of this
  12349. element should be a CDATA section.
  12350. @<Process report document elements@>=
  12351. if(currentElement.tagName() == "html")
  12352. {
  12353. cursor.insertHtml(currentElement.text());
  12354. }
  12355. @ If no special formatting is needed, a plain text element can be used. This
  12356. might be extended in the future to allow attributes for specifying the character
  12357. formatting to be used with the text.
  12358. @<Process report document elements@>=
  12359. if(currentElement.tagName() == "text")
  12360. {
  12361. cursor.insertText(currentElement.text());
  12362. }
  12363. @ One of the more interesting elements of a report is the {\tt <table>} element.
  12364. This is an element which can change its contents in response to changes in user
  12365. controls.
  12366. @<Process report document elements@>=
  12367. if(currentElement.tagName() == "table")
  12368. {
  12369. QTextFrame *frame = cursor.insertFrame(QTextFrameFormat());
  12370. ReportTable *table = new ReportTable(frame, currentElement);
  12371. table->setParent(widget);
  12372. if(currentElement.hasAttribute("id"))
  12373. {
  12374. table->setObjectName(currentElement.attribute("id"));
  12375. }
  12376. }
  12377. @ The |ReportTable| class is responsible for parsing {\tt <table>} child
  12378. elements and inserting the table into the document at the correct location.
  12379. @<Class declarations@>=
  12380. class ReportTable : public QObject@/
  12381. {@t\1@>@/
  12382. Q_OBJECT@;
  12383. QTextFrame *area;
  12384. QDomElement configuration;
  12385. QMap<QString, QVariant> bindings;
  12386. public:@/
  12387. ReportTable(QTextFrame *frame, QDomElement description);
  12388. ~ReportTable();
  12389. @[Q_INVOKABLE@,@, void@]@, bind(QString placeholder, QVariant value);@t\2\2@>@/
  12390. @t\4@>public slots@t\kern-3pt@>:@/
  12391. void refresh();@t\2@>@/
  12392. }@t\kern-3pt@>;
  12393. @ The |ReportTable| class takes a |QTextFrame| and |QDomElement| pointer in
  12394. its constructor. The former is used to establish the bounds of the table within
  12395. a document and the latter is used for generating the table contents.
  12396. @<ReportTable implementation@>=
  12397. ReportTable::ReportTable(QTextFrame *frame, QDomElement description) :
  12398. area(frame), configuration(description)
  12399. {
  12400. refresh();
  12401. }
  12402. ReportTable::~ReportTable()
  12403. {
  12404. }
  12405. @ In order to change the table contents based on user controls, the |bind()|
  12406. method allows a placeholder to be replaced with a value when evaluating a SQL
  12407. query.
  12408. @<ReportTable implementation@>=
  12409. void ReportTable::bind(QString placeholder, QVariant value)
  12410. {
  12411. bindings.insert(placeholder, value);
  12412. }
  12413. @ All of the interesting work is done in the |refresh()| slot. This method
  12414. deletes the current content of the frame and creates a table based on the
  12415. description of the table in the configuration document.
  12416. @<ReportTable implementation@>=
  12417. void ReportTable::refresh()
  12418. {
  12419. @<Delete current report table content@>@;
  12420. int rows = 1;
  12421. int columns = 1;
  12422. int currentRow = 0;
  12423. QTextTable *table = cursor.insertTable(rows, columns);
  12424. @<Set table formatting@>@;
  12425. @<Reconstruct report table content@>@;
  12426. if(rows > 1)
  12427. {
  12428. table->removeRows(0, 1);
  12429. }
  12430. }
  12431. @ Deleting the current content of the table involves using a cursor to select
  12432. everything in the frame and then removing that selection. There are more optimal
  12433. ways to do this but if there are performance problems with this, you may want to
  12434. reconsider what you are trying to do.
  12435. @<Delete current report table content@>=
  12436. QTextCursor cursor = area->firstCursorPosition();
  12437. while(cursor < area->lastCursorPosition())
  12438. {
  12439. cursor.movePosition(QTextCursor::Right, QTextCursor::KeepAnchor);
  12440. }
  12441. cursor.removeSelectedText();
  12442. @ When creating a new table, we may need to alter the formatting of that table.
  12443. To do this, we get the current format, modify that based on attributes of the
  12444. {\tt <table>} element, and apply the modified copy to the newly constructed
  12445. table.
  12446. @<Set table formatting@>=
  12447. QTextTableFormat format = table->format();
  12448. format.setBorderStyle(QTextFrameFormat::BorderStyle_None);
  12449. if(configuration.hasAttribute("align"))
  12450. {
  12451. if(configuration.attribute("align") == "center")
  12452. {
  12453. format.setAlignment(Qt::AlignHCenter);
  12454. }
  12455. }
  12456. table->setFormat(format);
  12457. @ To reconstruct the table, we need to parse the description of the table.
  12458. @<Reconstruct report table content@>=
  12459. QDomNodeList children = configuration.childNodes();
  12460. for(int i = 0; i < children.count(); i++)
  12461. {
  12462. QDomNode current;
  12463. QDomElement currentElement;
  12464. current = children.at(i);
  12465. if(current.isElement())
  12466. {
  12467. currentElement = current.toElement();
  12468. if(currentElement.tagName() == "query")
  12469. {
  12470. @<Add SQL query results to report table@>@;
  12471. }
  12472. else if(currentElement.tagName() == "row")
  12473. {
  12474. @<Add new row to report table@>@;
  12475. }
  12476. }
  12477. }
  12478. @ The text of a {\tt <query>} element will be the query desired in the table.
  12479. This might include placeholders that must be bound to values before the query is
  12480. executed. If query execution results in an error (as it will if it contains
  12481. placeholders that have not yet had values bound to them), there will be no
  12482. change to the table and the next child element, if any, will be processed.
  12483. @<Add SQL query results to report table@>=
  12484. SqlQueryConnection h;
  12485. QSqlQuery *query = h.operator->();
  12486. query->prepare(currentElement.text());
  12487. foreach(QString key, bindings.uniqueKeys())
  12488. {
  12489. if(currentElement.text().contains(key))
  12490. {
  12491. query->bindValue(key, bindings.value(key));
  12492. }
  12493. }
  12494. query->exec();
  12495. if(!query->next())
  12496. {
  12497. continue;
  12498. }
  12499. if(query->record().count() > columns)
  12500. {
  12501. table->appendColumns(query->record().count() - columns);
  12502. }
  12503. do
  12504. {
  12505. table->appendRows(1);
  12506. rows++;
  12507. currentRow++;
  12508. for(int j = 0; j < query->record().count(); j++)
  12509. {
  12510. QTextTableCell cell = table->cellAt(currentRow, j);
  12511. cursor = cell.firstCursorPosition();
  12512. cursor.insertText(query->value(j).toString());
  12513. }
  12514. } while(query->next());
  12515. @ It is sometimes desirable to add fixed data such as column headers to a table.
  12516. This is done with the {\tt <row>} element.
  12517. Technically, this isn'@q'@>t needed. The same results can be produced by using a
  12518. {\tt <query>} element to select constant data, but this approach saves a trip to
  12519. the database.
  12520. @<Add new row to report table@>=
  12521. table->appendRows(1);
  12522. currentRow++;
  12523. rows++;
  12524. QDomNodeList rowChildren = currentElement.childNodes();
  12525. int currentColumn = 0;
  12526. for(int j = 0; j < rowChildren.count(); j++)
  12527. {
  12528. QDomNode node;
  12529. QDomElement nodeElement;
  12530. node = rowChildren.at(j);
  12531. if(node.isElement())
  12532. {
  12533. nodeElement = node.toElement();
  12534. if(nodeElement.tagName() == "cell")
  12535. {
  12536. if(currentColumn == columns)
  12537. {
  12538. table->appendColumns(1);
  12539. columns++;
  12540. }
  12541. QTextTableCell cell = table->cellAt(currentRow, currentColumn);
  12542. cursor = cell.firstCursorPosition();
  12543. cursor.insertText(nodeElement.text());
  12544. currentColumn++;
  12545. }
  12546. }
  12547. }
  12548. @ In order to expose report printing capabilities, we provide a property on
  12549. |QTextEdit| objects to handle this.
  12550. @<Function prototypes for scripting@>=
  12551. void setQTextEditProperties(QScriptValue value, QScriptEngine *engine);
  12552. QScriptValue QTextEdit_print(QScriptContext *context, QScriptEngine *engine);
  12553. @ This function is a trivial adaptation from the Qt documentation.
  12554. @<Functions for scripting@>=
  12555. QScriptValue QTextEdit_print(QScriptContext *context, QScriptEngine *)
  12556. {
  12557. QTextEdit *self = getself<QTextEdit *>(context);
  12558. QTextDocument *document = self->document();
  12559. QPrinter printer;
  12560. QPrintDialog printwindow(&printer, self);
  12561. if(printwindow.exec() != QDialog::Accepted)
  12562. {
  12563. return QScriptValue();
  12564. }
  12565. document->print(&printer);
  12566. return QScriptValue();
  12567. }
  12568. @ The host environment must be informed of this function.
  12569. @<Functions for scripting@>=
  12570. void setQTextEditProperties(QScriptValue value, QScriptEngine *engine)
  12571. {
  12572. setQAbstractScrollAreaProperties(value, engine);
  12573. value.setProperty("print", engine->newFunction(QTextEdit_print));
  12574. }
  12575. @i daterangeselector.w
  12576. @** An area for repeated user interface elements.
  12577. \noindent There are multiple use cases in which it is useful to specify a
  12578. complex aggregation of user interface elements to be repeated arbitrarily many
  12579. times. For example, placing multiple copies of a cupping form in a single area
  12580. for conveniently entering observations for all coffees in a particular session
  12581. or providing any number of copies of the form for entering coffee purchase
  12582. information. The |FormArray| widget provides this capability, allowing the
  12583. XML portion of the configuration document to specify the form once and allowing
  12584. the host environment to access the copies.
  12585. Slots and the |Q_INVOKABLE| macro are used to simplify the use of this class
  12586. from the host environment.
  12587. @<Class declarations@>=
  12588. class FormArray : public QScrollArea@/
  12589. {@t\1@>@/
  12590. Q_OBJECT@;
  12591. QDomElement configuration;
  12592. QWidget itemContainer;
  12593. QVBoxLayout itemLayout;
  12594. int maxwidth;
  12595. int maxheight;
  12596. public:@/
  12597. FormArray(QDomElement description);
  12598. @[Q_INVOKABLE@,@, QWidget*@] elementAt(int index);@t\2\2@>@/
  12599. @[Q_INVOKABLE@,@, int@] elements();@t\2\2@>@/
  12600. @t\4@>public slots@t\kern-3pt@>:@/
  12601. void addElements(int copies = 1);
  12602. void removeAllElements();
  12603. void setMaximumElementWidth(int width);
  12604. void setMaximumElementHeight(int height);@t\2@>@/
  12605. }@t\kern-3pt@>;
  12606. @ The |FormArray| is just a |QScrollArea| providing a view onto a |QWidget|
  12607. containing a layout which has arbitrarily many copies of a |QWidget| with
  12608. contents determined by the configuration document used to create the
  12609. |FormArray|.
  12610. @<FormArray implementation@>=
  12611. FormArray::FormArray(QDomElement description) : configuration(description),
  12612. maxwidth(-1), maxheight(-1)@/
  12613. {
  12614. setWidget(&itemContainer);
  12615. itemContainer.setLayout(&itemLayout);
  12616. }
  12617. @ The |FormArray| was initially created by an XML element. A copy of this is
  12618. stored in the private variable |configuration|. This can have the same child
  12619. elements as {\tt <widget>}, allowing us to reuse the function for creating
  12620. populating the widget. When adding a new element, we must resize the
  12621. |itemContainer|, otherwise Qt will attempt to cram all widgets in the layout
  12622. into the same vertical space as was previously required. The result is not
  12623. attractive. We also set a minimum width just in case the newly created widget is
  12624. the first one added to the area.
  12625. @<FormArray implementation@>=
  12626. void FormArray::addElements(int copies)
  12627. {
  12628. QStack<QWidget *> *widgetStack = new QStack<QWidget *>;
  12629. QStack<QLayout *> *layoutStack = new QStack<QLayout *>;
  12630. QWidget *widget;
  12631. for(int i = 0; i < copies; i++)
  12632. {
  12633. widget = new QWidget;
  12634. if(maxwidth > -1)
  12635. {
  12636. widget->setMaximumWidth(maxwidth);
  12637. }
  12638. if(maxheight > -1)
  12639. {
  12640. widget->setMaximumHeight(maxheight);
  12641. }
  12642. if(configuration.hasChildNodes())
  12643. {
  12644. widgetStack->push(widget);
  12645. populateWidget(configuration, widgetStack, layoutStack);
  12646. widgetStack->pop();
  12647. widget->setMinimumHeight(widget->sizeHint().height());
  12648. itemLayout.addWidget(widget);
  12649. if(widget->sizeHint().height() > maxheight && maxheight > -1)
  12650. {
  12651. itemContainer.setMinimumHeight(maxheight * elements() + 50);
  12652. }
  12653. else
  12654. {
  12655. itemContainer.setMinimumHeight(itemContainer.sizeHint().height()
  12656. + widget->sizeHint().height());
  12657. }
  12658. if(maxwidth > -1)
  12659. {
  12660. itemContainer.setMinimumWidth(maxwidth + 50);
  12661. }
  12662. else
  12663. {
  12664. itemContainer.setMinimumWidth(widget->sizeHint().width() + 50);
  12665. }
  12666. }
  12667. }
  12668. }
  12669. @ In order to retrieve a widget from the area, we use the |elementAt()| method.
  12670. The pointer returned by this function can be used as the first argument to
  12671. |findChildObject()| in the host environment in order to find any widget in the
  12672. form.
  12673. @<FormArray implementation@>=
  12674. QWidget* FormArray::elementAt(int index)
  12675. {
  12676. if(index < itemLayout.count())
  12677. {
  12678. QLayoutItem *item = itemLayout.itemAt(index);
  12679. return item->widget();
  12680. }
  12681. else
  12682. {
  12683. return NULL;
  12684. }
  12685. }
  12686. @ Removing all elements is trivial, however we must be sure to reset the size of
  12687. |itemContainer|.
  12688. @<FormArray implementation@>=
  12689. void FormArray::removeAllElements()
  12690. {
  12691. while(itemLayout.count() > 0)
  12692. {
  12693. QLayoutItem *item;
  12694. item = itemLayout.itemAt(0);
  12695. item->widget()->hide();
  12696. itemLayout.removeWidget(item->widget());
  12697. }
  12698. itemContainer.setMinimumHeight(0);
  12699. }
  12700. @ This just leaves a method for determining the number of elements already in
  12701. the view. This is equal to the number of items in the layout.
  12702. @<FormArray implementation@>=
  12703. int FormArray::elements()
  12704. {
  12705. return itemLayout.count();
  12706. }
  12707. @ Some widgets do not behave well in a |FormArray| setting and will try to use
  12708. an excess of screen space. In these cases, constraining the size of the elements
  12709. can be beneficial. These just set private member variables which are used when
  12710. adding new elements.
  12711. @<FormArray implementation@>=
  12712. void FormArray::setMaximumElementWidth(int width)
  12713. {
  12714. maxwidth = width;
  12715. }
  12716. void FormArray::setMaximumElementHeight(int height)
  12717. {
  12718. maxheight = height;
  12719. }
  12720. @ In order to create an instance of this class from the configuration document,
  12721. a {\tt <formarray>} element is used. This can be added to any layout.
  12722. @<Function prototypes for scripting@>=
  12723. void addFormArrayToLayout(QDomElement element, QStack<QWidget *> *widgetStack,@|
  12724. QStack<QLayout *> *layoutStack);
  12725. @ Processing child elements is deferred until a call to
  12726. |FormArray::addElements()| has been made.
  12727. @<Functions for scripting@>=
  12728. void addFormArrayToLayout(QDomElement element, QStack<QWidget *> *,@|
  12729. QStack<QLayout *> *layoutStack)
  12730. {
  12731. FormArray *widget = new FormArray(element);
  12732. if(element.hasAttribute("id"))
  12733. {
  12734. widget->setObjectName(element.attribute("id"));
  12735. }
  12736. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  12737. layout->addWidget(widget);
  12738. }
  12739. @** Scale widgets.
  12740. \noindent One of the most commonly used methods of documenting the properties of
  12741. a coffee is through a cupping form. Several such forms exist to meet different
  12742. needs, however most involve several scales which can be marked to determine some
  12743. aspect of a particular attribute. Some of these scales are scored values which,
  12744. when considered with other scored values produce a numerical representation of
  12745. the quality of a given coffee. Others are unscored values which serve to provide
  12746. additional documentation of a property. For example, when the SCAA cupping form
  12747. expanded to the current form of ten scored properties with defects subtracted
  12748. from the total, a second scale was added for the acidity property. The scored
  12749. scale is used for marking the quality of the acidity while another unscored
  12750. scale is used for marking the intensity of that acidity.
  12751. Previously, in order to enter cupping information in \pn{}, numeric entry fields
  12752. were used. While this was very efficient for transcribing paper cupping forms
  12753. (and this was, in fact, the principal use case for our prototype cupping form
  12754. database software), it is not a form that lends itself to convenient use at the
  12755. cupping table.
  12756. Two new widgets are therefore introduced which allows a cupper to simply click
  12757. at some point on the scale to record that impression. Unfortunately, this is
  12758. still something of a tradeoff. It is not quite so efficient as using a paper
  12759. form in my experience, however it is faster than transcribing a stack of cupping
  12760. forms, particularly when working with cuppers with ambiguous handwriting. By
  12761. moving data acquisition to the point of data generation, a more useful record
  12762. can be produced for use in aggregate analysis.
  12763. @* The Horizontal Scale.
  12764. \noindent Several cupping forms make use of 10 point scales for the quality of
  12765. various attributes. The |ScaleControl| widget provides such a scale. It
  12766. consists of a bar with major ticks at 0, 5, and 10 and minor ticks at integer
  12767. values within this range. The first click sets both the initial and final value
  12768. of the scale while subsequent clicks adjust only the final value. A pair of
  12769. controls at each end of the scale allows the user to adjust either of these
  12770. values to compensate for imprecision at the point of the click. The two values,
  12771. an initial unscored value and a final scored value, provide some limited
  12772. temporal documentation. That is, it documents how the perception of a coffee
  12773. changes as it cools.
  12774. The widget is implemented as a |QGraphicsView| subclass. Please note that the
  12775. scale widgets are not particularly robust. In order to support a broader range
  12776. of cupping forms, there are plans to extend this class to allow user defined
  12777. range and tick patterns and user defined colors for the indicators.
  12778. @<Class declarations@>=
  12779. class ScaleControl : public QGraphicsView@/
  12780. {@t\1@>@/
  12781. Q_OBJECT@/
  12782. Q_PROPERTY(double initialValue READ initialValue WRITE setInitialValue)@/
  12783. Q_PROPERTY(double finalValue READ finalValue WRITE setFinalValue)@/
  12784. @<ScaleControl private members@>@t\2\2@>@/
  12785. public:@/
  12786. ScaleControl();
  12787. double initialValue(void);
  12788. double finalValue(void);
  12789. virtual QSize sizeHint() const;@/
  12790. @[public slots@]:@/
  12791. void setInitialValue(double value);
  12792. void setFinalValue(double value);@/
  12793. signals:@/
  12794. void initialChanged(double);
  12795. void finalChanged(double);@/
  12796. protected:@/
  12797. virtual void mousePressEvent(QMouseEvent *event);
  12798. virtual void mouseReleaseEvent(QMouseEvent *event);@t\2@>@/
  12799. }@t\kern-4pt@>;
  12800. @ The private variables available to instances of this class are used for
  12801. managing various aspects of the widget.
  12802. @<ScaleControl private members@>=
  12803. QGraphicsScene scene;
  12804. QGraphicsPolygonItem initialDecrement;
  12805. QGraphicsPolygonItem initialIncrement;
  12806. QGraphicsPolygonItem finalDecrement;
  12807. QGraphicsPolygonItem finalIncrement;
  12808. QGraphicsPolygonItem initialIndicator;
  12809. QGraphicsPolygonItem finalIndicator;
  12810. QGraphicsPathItem scaleLine;
  12811. QPolygonF left;
  12812. QPolygonF right;
  12813. QPolygonF down;
  12814. QPolygonF up;
  12815. QPainterPath scalePath;
  12816. QBrush initialBrush;
  12817. QBrush finalBrush;
  12818. double nonScoredValue;
  12819. double scoredValue;
  12820. bool initialSet;
  12821. bool finalSet;
  12822. bool scaleDown;
  12823. @ The constructor sets up the scene displayed by this widget. There is
  12824. considerable room for improvement here.
  12825. @<ScaleControl implementation@>=
  12826. ScaleControl::ScaleControl() : QGraphicsView(NULL, NULL), nonScoredValue(-1),
  12827. scoredValue(-1), initialSet(false), finalSet(false), scaleDown(false)
  12828. {
  12829. left << QPointF(0, 5) << QPointF(10, 0) << QPointF(10, 10) <<
  12830. QPointF(0, 5);
  12831. right << QPointF(10, 5) << QPointF(0, 0) << QPointF(0, 10) <<
  12832. QPointF(10, 5);
  12833. down << QPointF(0, 0) << QPointF(-5, -10) << QPointF(5, -10) <<
  12834. QPointF(0, 0);
  12835. up << QPointF(0, 0) << QPointF(-5, 10) << QPointF(4, 10) << QPointF(0, 0);
  12836. initialBrush.setColor(QColor(170, 170, 255));
  12837. initialBrush.setStyle(Qt::SolidPattern);
  12838. finalBrush.setColor(Qt::blue);
  12839. finalBrush.setStyle(Qt::SolidPattern);
  12840. initialDecrement.setPolygon(left);
  12841. initialDecrement.setBrush(initialBrush);
  12842. initialDecrement.setPos(0, 0);
  12843. scene.addItem(&initialDecrement);
  12844. initialIncrement.setPolygon(right);
  12845. initialIncrement.setBrush(initialBrush);
  12846. initialIncrement.setPos(122, 0);
  12847. scene.addItem(&initialIncrement);
  12848. finalDecrement.setPolygon(left);
  12849. finalDecrement.setBrush(finalBrush);
  12850. finalDecrement.setPos(0, 12);
  12851. scene.addItem(&finalDecrement);
  12852. finalIncrement.setPolygon(right);
  12853. finalIncrement.setBrush(finalBrush);
  12854. finalIncrement.setPos(122, 12);
  12855. scene.addItem(&finalIncrement);
  12856. scalePath.moveTo(0, 10);
  12857. scalePath.lineTo(100, 10);
  12858. scalePath.moveTo(0, 0);
  12859. scalePath.lineTo(0, 20);
  12860. scalePath.moveTo(10, 5);
  12861. scalePath.lineTo(10, 15);
  12862. scalePath.moveTo(20, 5);
  12863. scalePath.lineTo(20, 15);
  12864. scalePath.moveTo(30, 5);
  12865. scalePath.lineTo(30, 15);
  12866. scalePath.moveTo(40, 5);
  12867. scalePath.lineTo(40, 15);
  12868. scalePath.moveTo(50, 0);
  12869. scalePath.lineTo(50, 20);
  12870. scalePath.moveTo(60, 5);
  12871. scalePath.lineTo(60, 15);
  12872. scalePath.moveTo(70, 5);
  12873. scalePath.lineTo(70, 15);
  12874. scalePath.moveTo(80, 5);
  12875. scalePath.lineTo(80, 15);
  12876. scalePath.moveTo(90, 5);
  12877. scalePath.lineTo(90, 15);
  12878. scalePath.moveTo(100, 0);
  12879. scalePath.lineTo(100, 20);
  12880. scaleLine.setPath(scalePath);
  12881. scaleLine.setPos(16, 1);
  12882. scene.addItem(&scaleLine);
  12883. setScene(&scene);
  12884. initialIndicator.setPolygon(down);
  12885. initialIndicator.setBrush(initialBrush);
  12886. finalIndicator.setPolygon(up);
  12887. finalIndicator.setBrush(finalBrush);
  12888. setMinimumSize(sizeHint());
  12889. setMaximumSize(sizeHint());
  12890. setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  12891. setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  12892. setMinimumSize(sizeHint());
  12893. }
  12894. @ The size hint forces a smaller representation of the widget, making it easier
  12895. to arrange with other widgets.
  12896. @<ScaleControl implementation@>=
  12897. QSize ScaleControl::sizeHint() const
  12898. {
  12899. return QSize(140, 30);
  12900. }
  12901. @ The methods for setting the values represented on the scale must ensure that
  12902. the appropriate indicator is drawn and position it appropriately.
  12903. @<ScaleControl implementation@>=
  12904. void ScaleControl::setInitialValue(double value)@t\2\2@>@/
  12905. {@t\1@>@/
  12906. if(value >= 0 && value <= 10)@/
  12907. {@t\1@>@/
  12908. nonScoredValue = value;
  12909. if(!initialSet)
  12910. {
  12911. scene.addItem(&initialIndicator);
  12912. }
  12913. initialSet = true;
  12914. initialIndicator.setPos(value * 10 + 16, 10);
  12915. emit initialChanged(value);
  12916. if(!finalSet)
  12917. {
  12918. setFinalValue(value);
  12919. }@t\2@>@/
  12920. }@t\2@>@/
  12921. }@/@/
  12922. void ScaleControl::setFinalValue(double value)@t\2\2@>@/
  12923. {@t\1@>@/
  12924. if(value >= 0 && value <= 10)@/
  12925. {@t\1@>@/
  12926. scoredValue = value;
  12927. if(!finalSet)@/
  12928. {
  12929. scene.addItem(&finalIndicator);
  12930. }
  12931. finalSet = true;
  12932. finalIndicator.setPos(value * 10 + 16, 11);
  12933. emit finalChanged(value);@t\2@>@/
  12934. }@t\2@>@/
  12935. }
  12936. @ These values can, of course, be retrieved programmatically.
  12937. @<ScaleControl implementation@>=
  12938. double ScaleControl::initialValue(void)
  12939. {
  12940. return nonScoredValue;
  12941. }
  12942. double ScaleControl::finalValue(void)
  12943. {
  12944. return scoredValue;
  12945. }
  12946. @ This only leaves the matter of handling interaction with the widget. A future
  12947. version of this class might split the various interface elements in the scene
  12948. into distinct classes capable of using the event propagation capabilities
  12949. provided by the graphics view framework, however with the current design, we
  12950. must do a little more work.
  12951. There are two events which must be accepted in order to register a click on a
  12952. given portion of the scale. One event is generated when the mouse button is
  12953. pressed.
  12954. @<ScaleControl implementation@>=
  12955. void ScaleControl::mousePressEvent(QMouseEvent *event)
  12956. {
  12957. @<Check that the left button was pressed@>@;
  12958. scaleDown = @[true@];
  12959. event->accept();
  12960. }
  12961. @ The primary action button on the mouse is the left button. While there might
  12962. be sensible interactions to provide in response to other buttons, these are not
  12963. presently supported.
  12964. @<Check that the left button was pressed@>=
  12965. if(event->button() != Qt::LeftButton)
  12966. {
  12967. event->ignore();
  12968. return;
  12969. }
  12970. @ Most of the click event handling is done in response to releasing the mouse
  12971. button. In this event handler we must determine if the click occurred in a
  12972. clickable portion of the scale and take the appropriate action in response.
  12973. @<ScaleControl implementation@>=
  12974. void ScaleControl::mouseReleaseEvent(QMouseEvent *event)@t\2\2@>@/
  12975. {@t\1@>@/
  12976. @<Check that the left button was pressed@>@;
  12977. if(!scaleDown)
  12978. {
  12979. event->ignore();
  12980. return;
  12981. }
  12982. scaleDown = false;
  12983. QPointF sceneCoordinate = mapToScene(event->x(), event->y());
  12984. @<Handle clicks in the decrement controls@>@;
  12985. @<Handle clicks in the increment controls@>@;
  12986. @<Handle clicks in the scale area@>@;
  12987. event->ignore();
  12988. return;@t\2@>@/
  12989. }
  12990. @ As currently implemented, each horizontal pixel position represents a value
  12991. evenly divisible by $0.1$. It is, however, quite common to see vaues with a
  12992. $.25$ or $.75$ after the whole number on cupping forms. In order to make it
  12993. possible to select such values without vastly increasing the length of the
  12994. scale, the increment and decrement controls adjust the represented value by
  12995. $0.05$.
  12996. @<Handle clicks in the decrement controls@>=
  12997. if(sceneCoordinate.x() >= 0 && sceneCoordinate.x() <= 10)
  12998. {
  12999. if(sceneCoordinate.y() >= 0 && sceneCoordinate.y() <= 10)
  13000. {
  13001. if(initialSet)
  13002. {
  13003. setInitialValue(nonScoredValue - 0.05);
  13004. }
  13005. event->accept();
  13006. return;
  13007. }
  13008. else if(sceneCoordinate.y() >= 12 && sceneCoordinate.y() <= 22)
  13009. {
  13010. if(finalSet)
  13011. {
  13012. setFinalValue(scoredValue - 0.05);
  13013. event->accept();
  13014. return;
  13015. }
  13016. }
  13017. }
  13018. @ Incrementing represented values is done in the same manner as decrementing
  13019. them.
  13020. @<Handle clicks in the increment controls@>=
  13021. else if(sceneCoordinate.x() >= 122 && sceneCoordinate.x() <= 132)
  13022. {
  13023. if(sceneCoordinate.y() >= 0 && sceneCoordinate.y() <= 10)
  13024. {
  13025. if(initialSet)
  13026. {
  13027. setInitialValue(nonScoredValue + 0.05);
  13028. event->accept();
  13029. return;
  13030. }
  13031. }
  13032. else if(sceneCoordinate.y() >= 12 && sceneCoordinate.y() <= 22)
  13033. {
  13034. if(finalSet)
  13035. {
  13036. setFinalValue(scoredValue + 0.05);
  13037. event->accept();
  13038. return;
  13039. }
  13040. }
  13041. }
  13042. @ When handling clicks in the scale area, there is a difference between the
  13043. first click and any subsequent click.
  13044. @<Handle clicks in the scale area@>=
  13045. double relativeX = sceneCoordinate.x() - 16;
  13046. if(initialSet)
  13047. {
  13048. if(relativeX >= 0 && relativeX <= 100)
  13049. {
  13050. setFinalValue(relativeX / 10.0);
  13051. event->accept();
  13052. return;
  13053. }
  13054. }
  13055. else
  13056. {
  13057. if(relativeX >= 0 && relativeX <= 100)
  13058. {
  13059. setInitialValue(relativeX / 10.0);
  13060. event->accept();
  13061. return;
  13062. }
  13063. }
  13064. @* The Vertical Scale.
  13065. \noindent In addition to the horizontal scale, there is also a vertical scale.
  13066. The implementation of this class is in some ways a bit simpler as only one value
  13067. must be retained. While there is no prohibition on using this scale for scored
  13068. values (and this might enable a rather compact representation which might be
  13069. useful in some applications), its intent is for unscored values which are less
  13070. likely to change over time. If the dry aroma of a coffee changes significantly
  13071. during a cupping session, you are most likely waiting far too long to pour the
  13072. water.
  13073. @<Class declarations@>=
  13074. class IntensityControl : public QGraphicsView@/
  13075. {@/
  13076. @[Q_OBJECT@]@;
  13077. @[Q_PROPERTY(double value READ value WRITE setValue)@]@;
  13078. QGraphicsScene scene;
  13079. QGraphicsPolygonItem decrement;
  13080. QGraphicsPolygonItem increment;
  13081. QGraphicsPolygonItem indicator;
  13082. QGraphicsPathItem scaleLine;
  13083. QPolygonF left;
  13084. QPolygonF up;
  13085. QPolygonF down;
  13086. QPainterPath scalePath;
  13087. QBrush theBrush;
  13088. double theValue;
  13089. bool valueSet;
  13090. bool scaleDown;
  13091. public:@/
  13092. IntensityControl();
  13093. double value();
  13094. virtual QSize sizeHint() const;@/
  13095. @[public slots@]:@/
  13096. void setValue(double val);@/
  13097. signals:@/
  13098. void valueChanged(double);@/
  13099. protected:@/
  13100. virtual void mousePressEvent(QMouseEvent *event);
  13101. virtual void mouseReleaseEvent(QMouseEvent *event);@/
  13102. };
  13103. @ Note the similarity between this constructor and the the |ScaleControl|
  13104. constructor.
  13105. @<IntensityControl implementation@>=
  13106. IntensityControl::IntensityControl() : QGraphicsView(NULL, NULL), theValue(-1),
  13107. valueSet(false), scaleDown(false)
  13108. {
  13109. setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  13110. setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  13111. left << QPointF(0, 0) << QPointF(10, -5) << QPointF(10, 5) << QPointF(0, 0);
  13112. down << QPointF(0, 0) << QPointF(10, 0) << QPointF(5, 10) << QPointF(0, 0);
  13113. up << QPointF(0, 10) << QPointF(10, 10) << QPointF(5, 0) << QPointF(0, 10);
  13114. theBrush.setColor(Qt::blue);
  13115. theBrush.setStyle(Qt::SolidPattern);
  13116. increment.setPolygon(up);
  13117. increment.setBrush(theBrush);
  13118. increment.setPos(0, 0);
  13119. scene.addItem(&increment);
  13120. decrement.setPolygon(down);
  13121. decrement.setBrush(theBrush);
  13122. decrement.setPos(0, 122);
  13123. scene.addItem(&decrement);
  13124. scalePath.moveTo(5, 0);
  13125. scalePath.lineTo(5, 100);
  13126. scalePath.moveTo(0, 0);
  13127. scalePath.lineTo(10, 0);
  13128. scalePath.moveTo(0, 10);
  13129. scalePath.lineTo(10, 10);
  13130. scalePath.moveTo(0, 20);
  13131. scalePath.lineTo(10, 20);
  13132. scalePath.moveTo(0, 30);
  13133. scalePath.lineTo(10, 30);
  13134. scalePath.moveTo(0, 40);
  13135. scalePath.lineTo(10, 40);
  13136. scalePath.moveTo(0, 50);
  13137. scalePath.lineTo(10, 50);
  13138. scalePath.moveTo(0, 60);
  13139. scalePath.lineTo(10, 60);
  13140. scalePath.moveTo(0, 70);
  13141. scalePath.lineTo(10, 70);
  13142. scalePath.moveTo(0, 80);
  13143. scalePath.lineTo(10, 80);
  13144. scalePath.moveTo(0, 90);
  13145. scalePath.lineTo(10, 90);
  13146. scalePath.moveTo(0, 100);
  13147. scalePath.lineTo(10, 100);
  13148. scaleLine.setPath(scalePath);
  13149. scaleLine.setPos(0, 16);
  13150. scene.addItem(&scaleLine);
  13151. setScene(&scene);
  13152. indicator.setPolygon(left);
  13153. indicator.setBrush(theBrush);
  13154. setMinimumSize(sizeHint());
  13155. setMaximumSize(sizeHint());
  13156. }
  13157. @ Once again, the size hint reduces the default size of the widget.
  13158. @<IntensityControl implementation@>=
  13159. QSize IntensityControl::sizeHint() const
  13160. {
  13161. return QSize(25, 160);
  13162. }
  13163. @ To support a more intuitive numerical representation, higher values should map
  13164. to higher positions on the scale. This is contrary to the coordinate system
  13165. provided by Qt, so the code setting the position of the indicator on the scale
  13166. must account for this.
  13167. During testing of this class, I found that it was impossible to select the
  13168. values 0 or 10 either through a click or with the increment or decrement
  13169. controls. Adding two additional execution branches corrects this issue.
  13170. @<IntensityControl implementation@>=
  13171. void IntensityControl::setValue(double val)
  13172. {
  13173. if(val >= 0 && val <= 10)
  13174. {
  13175. theValue = val;
  13176. if(!valueSet)
  13177. {
  13178. scene.addItem(&indicator);
  13179. }
  13180. valueSet = @[true@];
  13181. indicator.setPos(6, (100 - (val * 10)) + 16);
  13182. emit(valueChanged(val));
  13183. }
  13184. else if(val < 1)
  13185. {
  13186. setValue(0);
  13187. }
  13188. else
  13189. {
  13190. setValue(10);
  13191. }
  13192. }
  13193. double IntensityControl::value()
  13194. {
  13195. return theValue;
  13196. }
  13197. @ Mouse event handling is similar as well. The mouse press event simply notes
  13198. that the button has been pressed.
  13199. @<IntensityControl implementation@>=
  13200. void IntensityControl::mousePressEvent(QMouseEvent *event)
  13201. {
  13202. @<Check that the left button was pressed@>@;
  13203. scaleDown = @[true@];
  13204. event->accept();
  13205. }
  13206. @ Since there are fewer clickable areas there are fewer regions to check while
  13207. handling the mouse release event. Just as the |setValue()| method must
  13208. compensate for a mismatch between the scale and the underlying coordinate
  13209. system, so must click handling in the scale area take this into consideration
  13210. when determining which value the click intends.
  13211. @<IntensityControl implementation@>=
  13212. void IntensityControl::mouseReleaseEvent(QMouseEvent *event)
  13213. {
  13214. @<Check that the left button was pressed@>@;
  13215. if(!scaleDown)
  13216. {
  13217. event->ignore();
  13218. return;
  13219. }
  13220. scaleDown = @[false@];
  13221. QPointF sceneCoordinate = mapToScene(event->x(), event->y());
  13222. if(sceneCoordinate.x() >= 0 && sceneCoordinate.x() <= 16)
  13223. {
  13224. if(sceneCoordinate.y() >= 0 && sceneCoordinate.y() <= 10)
  13225. {
  13226. if(valueSet)
  13227. {
  13228. setValue(theValue + 0.05);
  13229. }
  13230. event->accept();
  13231. return;
  13232. }
  13233. else if(sceneCoordinate.y() >= 122 && sceneCoordinate.y() <= 132)
  13234. {
  13235. if(valueSet)
  13236. {
  13237. setValue(theValue - 0.05);
  13238. }
  13239. event->accept();
  13240. return;
  13241. }
  13242. else if(sceneCoordinate.y() >= 16 && sceneCoordinate.y() <= 116)
  13243. {
  13244. setValue(10 - ((sceneCoordinate.y() - 16) / 10.0));
  13245. event->accept();
  13246. return;
  13247. }
  13248. }
  13249. }
  13250. @* Scripting the Scale Widgets.
  13251. \noindent Scale widgets can be added through the configuration system with
  13252. {\tt <hscale>} and {\tt <vscale>} elements. These can be added to layouts.
  13253. @<Function prototypes for scripting@>=
  13254. void addScaleControlToLayout(QDomElement element,
  13255. QStack<QWidget *> *widgetStack,
  13256. QStack<QLayout *> *layoutStack);
  13257. void addIntensityControlToLayout(QDomElement element,
  13258. QStack<QWidget *> *widgetStack,
  13259. QStack<QLayout *> *layoutStack);
  13260. @ Adding these widgets is done in the same way as adding other widgets.
  13261. @<Functions for scripting@>=
  13262. void addScaleControlToLayout(QDomElement element, QStack<QWidget *> *,
  13263. QStack<QLayout *> *layoutStack)
  13264. {
  13265. ScaleControl *scale = new ScaleControl;
  13266. if(element.hasAttribute("id"))
  13267. {
  13268. scale->setObjectName(element.attribute("id"));
  13269. }
  13270. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  13271. layout->addWidget(scale);
  13272. }
  13273. void addIntensityControlToLayout(QDomElement element, QStack<QWidget *> *,
  13274. QStack<QLayout *> *layoutStack)
  13275. {
  13276. IntensityControl *scale = new IntensityControl;
  13277. if(element.hasAttribute("id"))
  13278. {
  13279. scale->setObjectName(element.attribute("id"));
  13280. }
  13281. QBoxLayout *layout = qobject_cast<QBoxLayout *>(layoutStack->top());
  13282. layout->addWidget(scale);
  13283. }
  13284. @** Device Configuration.
  13285. \noindent Starting in \pn{} 1.4, all supported measurement hardware is
  13286. available from the same build and it is possible to use multiple devices from
  13287. differernt vendors at the same time. In previous versions, there were very few
  13288. available hardware configurations and a small number of example configuration
  13289. documents covered the needs of most people using the software. As more hardware
  13290. is supported and more people with distinct needs start using \pn{}, that
  13291. approach becomes unsustainable and the need for in-program configuration
  13292. becomes increasingly pronounced.
  13293. Device configuration is coupled to configuration of the logging window and
  13294. it is possible to configure multiple different roasters with different hardware
  13295. and other customizations of the logging window specific to a particular
  13296. machine.
  13297. The core of this is the use of an XML document saved with |QSettings| under
  13298. the |"DeviceConfiguration"| key. Within the root {\tt <DeviceConfiguration>}
  13299. element there are two grouping elements: {\tt <devices>} and
  13300. {\tt <references>}. The terminology was developed at a time when it was
  13301. thought that hardware configuration and logging view configuration would be
  13302. decoupled from each other, however the benefits of combining these far
  13303. outweighed the minor loss of flexibility with this approach.
  13304. Within the {\tt <devices>} tag there are arbitrarily many {\tt <node>} tags
  13305. which themselves may contain {\tt <node>} tags nested to any depth. Each of
  13306. these has two attributes, a {\tt name} attribute which specifies the display
  13307. text used to represent that node and a {\tt reference} attribute with a
  13308. unique value. Typica will generate a UUID for each node to use as the unique
  13309. value but this is not strictly required. The {\tt name} attribute does not
  13310. need to be unique and will generally be supplied by the person using the
  13311. software. The top level {\tt node} elements represent a coffee roaster and
  13312. the sub-elements can represent hardware, annotation controls, and possibly
  13313. other configurable features.
  13314. Within the {\tt <references>} tag there are as many {\tt <reference>} tags as
  13315. there are {\tt <node>} tags. Each of these has an {\tt id} attribute which
  13316. matches the {\tt reference} attribute in a {\tt <node>} tag and a {\tt driver}
  13317. attribute which is used to determine which class should be used to interact
  13318. with these settings. In the case of device configuration, this allows a
  13319. determination of which class should be used to generate an editor for settings
  13320. related to that node. Within each {\tt <reference>} tag is an arbitrary number
  13321. of {\tt <attribute>} tags with {\tt name} and {\tt value} attributes. Code for
  13322. providing the settings widgets and device interfaces can use these for any
  13323. desired purpose, but it is common to have one {\tt <attribute>} tag per setting
  13324. appropriate for a given node and possibly more to identify the concept a
  13325. particular node represents.
  13326. The global |Application| object is extended to maintain a |QDomDocument|
  13327. representation of this XML document.
  13328. @<Application private data members@>=
  13329. QDomDocument deviceConfigurationDocument;
  13330. @ Two methods are also provided for interacting with this document. The
  13331. |deviceConfiguration()| method returns a pointer to the private data member,
  13332. loading the XML from |QSettings| if required and creating a new document with
  13333. no {\tt <node>} tags if the document does not exist in settings. The
  13334. |saveDeviceConfiguration()| method serializes the |QDomDocument| to settings.
  13335. @<Device configuration members@>=
  13336. QDomDocument deviceConfiguration();
  13337. @ The method for saving should be a slot so a model representing this data
  13338. can persist changes through the signals and slots mechanism rather than
  13339. requiring the calls to be explicitn.
  13340. @<Extended Application slots@>=
  13341. void saveDeviceConfiguration();
  13342. @ Serializing the current configuration is trivial.
  13343. @<Application Implementation@>=
  13344. void Application::saveDeviceConfiguration()
  13345. {
  13346. QSettings settings;
  13347. settings.setValue("DeviceConfiguration",
  13348. QVariant(deviceConfigurationDocument.toByteArray()));
  13349. }
  13350. @ Producing a pointer to a loaded configuration only slightly more complicated.
  13351. If the configuration has been previously loaded we just return the pointer.
  13352. Otherwise, we attempt to load the document.
  13353. @<Application Implementation@>=
  13354. QDomDocument Application::deviceConfiguration()
  13355. {
  13356. if(deviceConfigurationDocument.isNull())
  13357. {
  13358. @<Load device configuration document from settings@>@;
  13359. }
  13360. return deviceConfigurationDocument;
  13361. }
  13362. @ In most cases a document will already exist in settings, but we must verify
  13363. this and create a new document if it does not exist. We also clear device
  13364. configuration settings if the configuration document is invalid.
  13365. @<Load device configuration document from settings@>=
  13366. QSettings settings;
  13367. QByteArray document = settings.value("DeviceConfiguration").toByteArray();
  13368. QString etext;
  13369. int eline;
  13370. int ecol;
  13371. if(document.length() == 0)
  13372. {
  13373. qDebug() << "Loaded settings length is 0. Creating new configuration.";
  13374. @<Create device configuration document@>@;
  13375. }
  13376. else
  13377. {
  13378. if(!deviceConfigurationDocument.setContent(document, false,
  13379. &etext, &eline, &ecol))
  13380. {
  13381. @<Report configuration loading error@>@;
  13382. @<Create device configuration document@>@;
  13383. }
  13384. }
  13385. @ Rather than generate the empty device configuration programmatically, we keep
  13386. an empty device configuration document as a resource.
  13387. @<Create device configuration document@>=
  13388. QFile emptyDocument(":/resources/xml/EmptyDeviceConfiguration.xml");
  13389. emptyDocument.open(QIODevice::ReadOnly);
  13390. if(!deviceConfigurationDocument.setContent(&emptyDocument, false,
  13391. &etext, &eline, &ecol))
  13392. {
  13393. @<Report configuration loading error@>@;
  13394. }
  13395. else
  13396. {
  13397. saveDeviceConfiguration();
  13398. }
  13399. @ There isn'@q'@>t really anything that can be done if the device configuration data
  13400. is corrupt, but an error message can be produced if the program happens to have
  13401. access to a debugging console.
  13402. @<Report configuration loading error@>=
  13403. qDebug() << QString(tr("An error occurred loading device configuration."));
  13404. qDebug() << QString(tr("Line %1, Column %2")).arg(eline).arg(ecol);
  13405. qDebug() << etext;
  13406. @* Model and view for device configuration hierarchy.
  13407. \noindent When manipulating device configuration data, it can be useful to
  13408. present the device hierarchy in a tree view. To do this, we use two classes to
  13409. produce a tree model. This is slightly extended and modified from an example
  13410. in the Qt documentation.\nfnote{Simple DOM Model Example:\par\indent\pdfURL{%
  13411. http://doc.qt.nokia.com/4.7-snapshot/itemviews-simpledommodel.html}
  13412. {http://doc.qt.nokia.com/4.7-snapshot/itemviews-simpledommodel.html}}
  13413. Our model uses the |DeviceTreeModelNode| class to cache the |QDomNode|
  13414. instances with the data we want.
  13415. @<Class declarations@>=
  13416. class DeviceTreeModelNode
  13417. {
  13418. public:
  13419. DeviceTreeModelNode(QDomNode &node, int row,
  13420. DeviceTreeModelNode *parent = NULL);
  13421. ~DeviceTreeModelNode();
  13422. DeviceTreeModelNode *child(int index);
  13423. DeviceTreeModelNode *parent();
  13424. QDomNode node() const;
  13425. int row();
  13426. private:
  13427. QDomNode domNode;
  13428. QHash<int, DeviceTreeModelNode*> children;
  13429. int rowNumber;
  13430. DeviceTreeModelNode *parentItem;
  13431. };
  13432. @ Implementation of this helper class is trivial.
  13433. @<DeviceTreeModelNode implementation@>=
  13434. DeviceTreeModelNode::DeviceTreeModelNode(QDomNode &node, int row,
  13435. DeviceTreeModelNode *parent)
  13436. : domNode(node), rowNumber(row), parentItem(parent)
  13437. {
  13438. /* Nothing needs to be done here. */
  13439. }
  13440. DeviceTreeModelNode::~DeviceTreeModelNode()
  13441. {
  13442. QHash<int, DeviceTreeModelNode *>::iterator@, i;
  13443. for(i = children.begin(); i != children.end(); i++)
  13444. {
  13445. delete i.value();
  13446. }
  13447. }
  13448. DeviceTreeModelNode *DeviceTreeModelNode::parent()
  13449. {
  13450. return parentItem;
  13451. }
  13452. int DeviceTreeModelNode::row()
  13453. {
  13454. return rowNumber;
  13455. }
  13456. QDomNode DeviceTreeModelNode::node() const
  13457. {
  13458. return domNode;
  13459. }
  13460. DeviceTreeModelNode *DeviceTreeModelNode::child(int index)
  13461. {
  13462. if(children.contains(index))
  13463. {
  13464. return children[index];
  13465. }
  13466. if(index >= 0 && index < domNode.childNodes().count())
  13467. {
  13468. QDomNode childNode = domNode.childNodes().item(index);
  13469. DeviceTreeModelNode *childItem = new DeviceTreeModelNode(childNode,
  13470. index, this);
  13471. children[index] = childItem;
  13472. return childItem;
  13473. }
  13474. return NULL;
  13475. }
  13476. @ The model class provides a single column representation of the {\tt devices}
  13477. section of the device configuration document. It provides methods for editing
  13478. the name of any node, for adding new nodes to the model, for deleting any node
  13479. in the model, and for obtaining the {\tt reference} element corresponding to
  13480. a given node.
  13481. @<Class declarations@>=
  13482. class DeviceTreeModel : public QAbstractItemModel@/
  13483. {@/
  13484. @[Q_OBJECT@]@;
  13485. public:@/
  13486. DeviceTreeModel(QObject *parent = NULL);
  13487. ~DeviceTreeModel();
  13488. QVariant data(const QModelIndex &index, int role) const;
  13489. Qt::ItemFlags flags(const QModelIndex &index) const;
  13490. QVariant headerData(int section, Qt::Orientation orientation,
  13491. int role = Qt::DisplayRole) const;
  13492. QModelIndex index(int row, int column,
  13493. const QModelIndex &parent = QModelIndex()) const;
  13494. QModelIndex parent(const QModelIndex &child) const;
  13495. int rowCount(const QModelIndex &parent = QModelIndex()) const;
  13496. int columnCount(const QModelIndex &parent = QModelIndex()) const;
  13497. bool setData(const QModelIndex &index, const QVariant &value,
  13498. int role);
  13499. bool removeRows(int row, int count, const QModelIndex &parent);
  13500. QDomElement referenceElement(const QString &id);
  13501. @[public slots@]:@/
  13502. void newNode(const QString &name, const QString &driver,
  13503. const QModelIndex &parent);
  13504. private:@/
  13505. QDomDocument document;
  13506. DeviceTreeModelNode *root;
  13507. QDomNode referenceSection;
  13508. QDomNode treeRoot;
  13509. };
  13510. @ In the constructor we locate the {\tt devices} and {\tt references} sections
  13511. of the passed in document. Our tree of cached |QDomNode| elements starts with
  13512. the former and is expanded as needed.
  13513. @<DeviceTreeModel implementation@>=
  13514. DeviceTreeModel::DeviceTreeModel(QObject *parent)
  13515. : QAbstractItemModel(parent)
  13516. {
  13517. document = AppInstance->deviceConfiguration();
  13518. QDomNodeList elements = document.elementsByTagName("devices");
  13519. if(elements.size() != 1)
  13520. {
  13521. qDebug() << "Unexpected result when loading device map.";
  13522. }
  13523. treeRoot = elements.at(0);
  13524. root = new DeviceTreeModelNode(treeRoot, 0);
  13525. elements = document.elementsByTagName("references");
  13526. if(elements.size() != 1)
  13527. {
  13528. qDebug() << "No references section. Creating.";
  13529. referenceSection = document.createElement("references");
  13530. document.appendChild(referenceSection);
  13531. }
  13532. else
  13533. {
  13534. referenceSection = elements.at(0);
  13535. }
  13536. connect(this, SIGNAL(dataChanged(QModelIndex, QModelIndex)),
  13537. AppInstance, SLOT(saveDeviceConfiguration()));
  13538. connect(this, SIGNAL(modelReset()),
  13539. AppInstance, SLOT(saveDeviceConfiguration()));
  13540. connect(this, SIGNAL(rowsInserted(QModelIndex, int, int)),
  13541. AppInstance, SLOT(saveDeviceConfiguration()));
  13542. }
  13543. @ We only provide a single column for our model, so |columnCount()| can simply
  13544. return a constant. The |rowCount()| method can return a variety of values
  13545. depending on the parent node.
  13546. @<DeviceTreeModel implementation@>=
  13547. int DeviceTreeModel::columnCount(const QModelIndex &) const
  13548. {
  13549. return 1;
  13550. }
  13551. int DeviceTreeModel::rowCount(const QModelIndex &parent) const
  13552. {
  13553. if(parent.column() > 0)
  13554. {
  13555. return 0;
  13556. }
  13557. @<Get parent item from index@>@;
  13558. return parentItem->node().childNodes().count();
  13559. }
  13560. @ If an invalid index is passed as the parent index, we assume the parent to
  13561. be the root element.
  13562. @<Get parent item from index@>=
  13563. DeviceTreeModelNode *parentItem;
  13564. if(!parent.isValid())
  13565. {
  13566. parentItem = root;
  13567. }
  13568. else
  13569. {
  13570. parentItem = static_cast<DeviceTreeModelNode *>(parent.internalPointer());
  13571. }
  13572. @ As seen in |rowCount()|, we keep a pointer to the cached node in our model
  13573. indices.
  13574. @<DeviceTreeModel implementation@>=
  13575. QModelIndex DeviceTreeModel::index(int row, int column,
  13576. const QModelIndex &parent) const
  13577. {
  13578. if(!hasIndex(row, column, parent))
  13579. {
  13580. return QModelIndex();
  13581. }
  13582. @<Get parent item from index@>@;
  13583. DeviceTreeModelNode *childItem = parentItem->child(row);
  13584. if(childItem)
  13585. {
  13586. return createIndex(row, column, childItem);
  13587. }
  13588. return QModelIndex();
  13589. }
  13590. @ We can also request an index for the parent of a given index.
  13591. @<DeviceTreeModel implementation@>=
  13592. QModelIndex DeviceTreeModel::parent(const QModelIndex &child) const
  13593. {
  13594. if(!child.isValid())
  13595. {
  13596. return QModelIndex();
  13597. }
  13598. DeviceTreeModelNode *childItem =
  13599. static_cast<DeviceTreeModelNode *>(child.internalPointer());
  13600. DeviceTreeModelNode *parentItem = childItem->parent();
  13601. if(!parentItem || parentItem == root)
  13602. {
  13603. return QModelIndex();
  13604. }
  13605. return createIndex(parentItem->row(), 0, parentItem);
  13606. }
  13607. @ All items should be enabled, selectable, and editable.
  13608. @<DeviceTreeModel implementation@>=
  13609. Qt::ItemFlags DeviceTreeModel::flags(const QModelIndex &index) const
  13610. {
  13611. if(!index.isValid())
  13612. {
  13613. return 0;
  13614. }
  13615. return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
  13616. }
  13617. @ Each node in the model maintains two pieces of information. One is the
  13618. display value for the node which is held in the {\tt name} attribute of the
  13619. corresponding XML element. The other is a reference ID held in the
  13620. {\tt reference} attribute.
  13621. @<DeviceTreeModel implementation@>=
  13622. QVariant DeviceTreeModel::data(const QModelIndex &index, int role) const
  13623. {
  13624. if(!index.isValid())
  13625. {
  13626. return QVariant();
  13627. }
  13628. if(role != Qt::DisplayRole && role != Qt::UserRole && role != Qt::EditRole)
  13629. {
  13630. return QVariant();
  13631. }
  13632. DeviceTreeModelNode *item =
  13633. static_cast<DeviceTreeModelNode *>(index.internalPointer());
  13634. QDomNode node = item->node();
  13635. QDomElement element = node.toElement();
  13636. switch(role)
  13637. {
  13638. case Qt::DisplayRole:@/
  13639. case Qt::EditRole:@/
  13640. return QVariant(element.attribute("name"));
  13641. case Qt::UserRole:@/
  13642. return QVariant(element.attribute("reference"));
  13643. default:@/
  13644. return QVariant();
  13645. }
  13646. return QVariant();
  13647. }
  13648. @ The reference value is managed by the model and should never be changed. The
  13649. display value for a node is, however, editable. These changes must propagate
  13650. back to the XML document underlying the model.
  13651. @<DeviceTreeModel implementation@>=
  13652. bool DeviceTreeModel::setData(const QModelIndex &index,
  13653. const QVariant &value, int)@;@/
  13654. {@t\1@>@/
  13655. if(!index.isValid())@/
  13656. {@t\1@>@/
  13657. return false;@t\2@>@/
  13658. }@/
  13659. DeviceTreeModelNode *item =
  13660. static_cast<DeviceTreeModelNode *>(index.internalPointer());
  13661. QDomNode node = item->node();
  13662. QDomElement element = node.toElement();
  13663. element.setAttribute("name", value.toString());
  13664. emit dataChanged(index, index);@;
  13665. return true;@t\2@>@/
  13666. }
  13667. @ A custom method is provided for adding new nodes to the model. This generates
  13668. the two XML elements needed for the node. The |name| parameter is the display
  13669. name of the new node, the |driver| parameter is used as the value for the
  13670. {\tt driver} attribute in the {\tt reference} element which will be used to
  13671. determine what classes are used to work with that data.
  13672. @<DeviceTreeModel implementation@>=
  13673. void DeviceTreeModel::newNode(const QString &name, const QString &driver,
  13674. const QModelIndex &parent)
  13675. {
  13676. QString referenceID = QUuid::createUuid().toString();
  13677. @<Get parent item from index@>@;
  13678. QDomNode parentNode = parentItem->node();
  13679. int newRowNumber = rowCount(parent);
  13680. beginInsertRows(parent, newRowNumber, newRowNumber);
  13681. QDomElement deviceElement = document.createElement("node");
  13682. deviceElement.setAttribute("name", name);
  13683. deviceElement.setAttribute("reference", referenceID);
  13684. parentNode.appendChild(deviceElement);
  13685. QDomElement referenceElement = document.createElement("reference");
  13686. referenceElement.setAttribute("id", referenceID);
  13687. referenceElement.setAttribute("driver", driver);
  13688. referenceSection.appendChild(referenceElement);
  13689. endInsertRows();
  13690. }
  13691. @ We can also delete nodes. When deleting a node, both XML elements are
  13692. removed and our node cache is invalidated.
  13693. @<DeviceTreeModel implementation@>=
  13694. bool DeviceTreeModel::removeRows(int row, int count, const QModelIndex &parent)@t\2\2@>@/
  13695. {@t\1@>@/
  13696. @<Get parent item from index@>@;
  13697. QDomNode parentNode = parentItem->node();
  13698. QDomNodeList childNodes = parentNode.childNodes();@;
  13699. if(childNodes.size() < row + count)@/
  13700. {@t\1@>@/
  13701. return false;@t\2@>@/
  13702. }@/
  13703. beginRemoveRows(parent, row, row + count - 1);
  13704. QList<QDomElement> removalList;
  13705. for(int i = row; i < row + count; i++)
  13706. {
  13707. removalList.append(childNodes.at(i).toElement());
  13708. }
  13709. QDomElement element;
  13710. QDomElement reference;
  13711. for(int i = 0; i < count; i++)
  13712. {
  13713. element = removalList.at(i);
  13714. if(element.hasAttribute("reference"))
  13715. {
  13716. reference = referenceElement(element.attribute("reference"));
  13717. if(!reference.isNull())
  13718. {
  13719. referenceSection.removeChild(reference);
  13720. }
  13721. }
  13722. parentNode.removeChild(element);
  13723. }
  13724. endRemoveRows();
  13725. beginResetModel();
  13726. delete root;
  13727. root = new DeviceTreeModelNode(treeRoot, 0);
  13728. endResetModel();@;
  13729. return true;@t\2@>@/
  13730. }
  13731. @ Another custom method obtains the {\tt reference} element for a given
  13732. reference ID.
  13733. @<DeviceTreeModel implementation@>=
  13734. QDomElement DeviceTreeModel::referenceElement(const QString &id)
  13735. {
  13736. QDomNodeList childNodes = referenceSection.childNodes();
  13737. QDomElement element;
  13738. for(int i = 0; i < childNodes.size(); i++)
  13739. {
  13740. element = childNodes.at(i).toElement();
  13741. if(element.hasAttribute("id"))
  13742. {
  13743. if(element.attribute("id") == id)
  13744. {
  13745. return element;
  13746. }
  13747. }
  13748. }
  13749. return QDomElement();
  13750. }
  13751. @ We don'@q'@>t want any headers, so |headerData()| is very simple.
  13752. @<DeviceTreeModel implementation@>=
  13753. QVariant DeviceTreeModel::headerData(int, Qt::Orientation, int) const
  13754. {
  13755. return QVariant();
  13756. }
  13757. @ The destructor destroys the node cache. The destructor for the top level node
  13758. will recursively destroy all child nodes.
  13759. @<DeviceTreeModel implementation@>=
  13760. DeviceTreeModel::~DeviceTreeModel()
  13761. {
  13762. delete root;
  13763. }
  13764. @ Exposing this class to the host environment allows a number of interesting
  13765. possibilities. Setting the model to a combo box, for example, allows the
  13766. selection of top level nodes representing a particular coffee roaster. It is
  13767. also useful to have the ability to traverse a specified sub-tree of the model
  13768. to set up a logging view that matches the configuration for such a selected
  13769. roaster.
  13770. @<Function prototypes for scripting@>=
  13771. QScriptValue constructDeviceTreeModel(QScriptContext *context,
  13772. QScriptEngine *engine);
  13773. void setDeviceTreeModelProperties(QScriptValue value, QScriptEngine *engine);
  13774. void setQAbstractItemModelProperties(QScriptValue value, QScriptEngine *engine);
  13775. QScriptValue DeviceTreeModel_referenceElement(QScriptContext *context,
  13776. QScriptEngine *engine);
  13777. QScriptValue QAbstractItemModel_data(QScriptContext *context, QScriptEngine *engine);
  13778. QScriptValue QAbstractItemModel_index(QScriptContext *context, QScriptEngine *engine);
  13779. QScriptValue QAbstractItemModel_rowCount(QScriptContext *context, QScriptEngine *engine);
  13780. QScriptValue QAbstractItemModel_hasChildren(QScriptContext *context, QScriptEngine *engine);
  13781. @ The constructor is trivial.
  13782. @<Functions for scripting@>=
  13783. QScriptValue constructDeviceTreeModel(QScriptContext *, QScriptEngine *engine)
  13784. {
  13785. QScriptValue object = engine->newQObject(new DeviceTreeModel);
  13786. setDeviceTreeModelProperties(object, engine);
  13787. return object;
  13788. }
  13789. @ As usual the host environment is informed of this constructor.
  13790. @<Set up the scripting engine@>=
  13791. constructor = engine->newFunction(constructDeviceTreeModel);
  13792. value = engine->newQMetaObject(&DeviceTreeModel::staticMetaObject,
  13793. constructor);
  13794. engine->globalObject().setProperty("DeviceTreeModel", value);
  13795. @ A number of properties are set to allow script code to traverse the model.
  13796. Most of these properties are properly members of |QAbstractItemModel| and
  13797. the code is written to allow any models that may be exposed to the host
  13798. environment in the future to make use of these as well. Note that this is not
  13799. a full set of functionality but only what I needed to implement a particular
  13800. feature set.
  13801. @<Functions for scripting@>=
  13802. void setDeviceTreeModelProperties(QScriptValue value, QScriptEngine *engine)
  13803. {
  13804. setQAbstractItemModelProperties(value, engine);
  13805. value.setProperty("referenceElement",
  13806. engine->newFunction(DeviceTreeModel_referenceElement));
  13807. }
  13808. void setQAbstractItemModelProperties(QScriptValue value, QScriptEngine *engine)
  13809. {
  13810. setQObjectProperties(value, engine);
  13811. value.setProperty("data", engine->newFunction(QAbstractItemModel_data));
  13812. value.setProperty("index", engine->newFunction(QAbstractItemModel_index));
  13813. value.setProperty("rowCount", engine->newFunction(QAbstractItemModel_rowCount));
  13814. value.setProperty("hasChildren", engine->newFunction(QAbstractItemModel_hasChildren));
  13815. }
  13816. @ The wrapped call to |referenceElement| does a little more than might be
  13817. expected. Rather than returning a |QDomElement| and leaving it up to script
  13818. code to traverse the sub-tree, we create a |QVariantMap| which in script code
  13819. is translated as an object with the keys as properties of the object containing
  13820. the values of those keys. This is populated by first specifying a {\tt driver}
  13821. key with its value from the {\tt driver} attribute of the {\tt reference} node.
  13822. We then examine the {\tt <attribute>} sub-elements and use the {\tt name}
  13823. attribute as keys and the {\tt value} attribute as values to fill out the rest
  13824. of the map.
  13825. @<Functions for scripting@>=
  13826. QScriptValue DeviceTreeModel_referenceElement(QScriptContext *context,
  13827. QScriptEngine *engine)
  13828. {
  13829. DeviceTreeModel *model = getself<DeviceTreeModel *>(context);
  13830. QDomElement referenceElement = model->referenceElement(argument<QString>(0, context));
  13831. QDomNodeList configData = referenceElement.elementsByTagName("attribute");
  13832. QDomElement node;
  13833. QVariantMap retval;
  13834. retval.insert("driver", referenceElement.attribute("driver"));
  13835. for(int i = 0; i < configData.size(); i++)
  13836. {
  13837. node = configData.at(i).toElement();
  13838. retval.insert(node.attribute("name"), node.attribute("value"));
  13839. }
  13840. return engine->toScriptValue(retval);
  13841. }
  13842. QScriptValue QAbstractItemModel_data(QScriptContext *context, QScriptEngine *engine)
  13843. {
  13844. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  13845. QModelIndex index = argument<QModelIndex>(0, context);
  13846. int role = argument<int>(1, context);
  13847. return engine->toScriptValue(model->data(index, role));
  13848. }
  13849. QScriptValue QAbstractItemModel_index(QScriptContext *context, QScriptEngine *engine)
  13850. {
  13851. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  13852. int row = 0;
  13853. int column = 0;
  13854. QModelIndex index;
  13855. if(context->argumentCount() > 1)
  13856. {
  13857. row = argument<int>(0, context);
  13858. column = argument<int>(1, context);
  13859. }
  13860. if(context->argumentCount() > 2)
  13861. {
  13862. index = argument<QModelIndex>(2, context);
  13863. }
  13864. QModelIndex retval = model->index(row, column, index);
  13865. return engine->toScriptValue(retval);
  13866. }
  13867. QScriptValue QAbstractItemModel_rowCount(QScriptContext *context,
  13868. QScriptEngine *)
  13869. {
  13870. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  13871. QModelIndex index;
  13872. if(context->argumentCount() == 1)
  13873. {
  13874. index = argument<QModelIndex>(0, context);
  13875. }
  13876. return QScriptValue(model->rowCount(index));
  13877. }
  13878. QScriptValue QAbstractItemModel_hasChildren(QScriptContext *context,
  13879. QScriptEngine *engine)
  13880. {
  13881. QAbstractItemModel *model = getself<QAbstractItemModel *>(context);
  13882. QModelIndex index;
  13883. if(context->argumentCount() == 1)
  13884. {
  13885. index = argument<QModelIndex>(0, context);
  13886. }
  13887. return QScriptValue(engine, model->hasChildren(index));
  13888. }
  13889. @ Some additional work is needed to handle |QModelIndex| appropriately. First
  13890. we declare that as a metatype.
  13891. @<Class declarations@>=
  13892. Q_DECLARE_METATYPE(QModelIndex)
  13893. @ Next we need a pair of functions to convert |QModelIndex| to and from script
  13894. values.
  13895. @<Function prototypes for scripting@>=
  13896. QScriptValue QModelIndex_toScriptValue(QScriptEngine *engine, const QModelIndex &index);
  13897. void QModelIndex_fromScriptValue(const QScriptValue &value, QModelIndex &index);
  13898. @ These are implemented thusly.
  13899. @<Functions for scripting@>=
  13900. QScriptValue QModelIndex_toScriptValue(QScriptEngine *engine, const QModelIndex &index)
  13901. {
  13902. QVariant var;
  13903. var.setValue(index);
  13904. QScriptValue object = engine->newVariant(var);
  13905. return object;
  13906. }
  13907. void QModelIndex_fromScriptValue(const QScriptValue &value, QModelIndex &index)
  13908. {
  13909. index = value.toVariant().value<QModelIndex>();
  13910. }
  13911. @ Finally we register this with the engine.
  13912. @<Set up the scripting engine@>=
  13913. qScriptRegisterMetaType(engine, QModelIndex_toScriptValue, QModelIndex_fromScriptValue);
  13914. @* Device Configuration Widgets.
  13915. \noindent Each node in the {\tt devices} section of the |DeviceTreeModel| is
  13916. associated with a {\tt reference} element that provides a driver string which
  13917. can be used to identify the classes used to interact with the device
  13918. configuration data. An example of this is selecting which widget to use when
  13919. selecting a node in a configuration window. These widgets must be registered
  13920. to the appropriate driver string in advance. This is currently handled through
  13921. the |Application| instance, though it would probably be better to split this
  13922. into its own class at some point in the future.
  13923. @<Application private data members@>=
  13924. QHash<QString, QMetaObject> deviceConfigurationWidgets;
  13925. @ Two methods register widgets and retrieve an instance of the appropriate
  13926. widget for a given node in the device configuration model.
  13927. @<Device configuration members@>=
  13928. void registerDeviceConfigurationWidget(QString driver, QMetaObject widget);
  13929. QWidget* deviceConfigurationWidget(DeviceTreeModel *model,
  13930. const QModelIndex &index);
  13931. @ Registration is a simple wrapper around the underlying |QHash|.
  13932. @<Application Implementation@>=
  13933. void Application::registerDeviceConfigurationWidget(QString driver,
  13934. QMetaObject widget)
  13935. {
  13936. deviceConfigurationWidgets.insert(driver, widget);
  13937. }
  13938. @ Obtaining the configuration widget for a given node involves looking up the
  13939. reference element, extracting the driver string, looking up the associated
  13940. meta-object, and returning a new instance of that object.
  13941. As there is no concept of an invalid |QMetaObject| we default to the static
  13942. meta-object for a |QWidget| if a widget for the specified driver string is not
  13943. registered and check for this prior to creating a new instance of the
  13944. configuration widget.
  13945. @<Application Implementation@>=
  13946. QWidget* Application::deviceConfigurationWidget(DeviceTreeModel *model,
  13947. const QModelIndex &index)
  13948. {
  13949. QVariant nodeReference = index.data(Qt::UserRole);
  13950. QDomElement referenceElement = model->referenceElement(
  13951. model->data(index, Qt::UserRole).toString());
  13952. QMetaObject metaObject =
  13953. deviceConfigurationWidgets.value(referenceElement.attribute("driver"),
  13954. QWidget::staticMetaObject);
  13955. QWidget *editor;
  13956. if(metaObject.className() == QWidget::staticMetaObject.className())
  13957. {
  13958. editor = NULL;
  13959. }
  13960. else
  13961. {
  13962. editor = qobject_cast<QWidget *>(
  13963. metaObject.newInstance(Q_ARG(DeviceTreeModel *, model),
  13964. Q_ARG(QModelIndex, index)));
  13965. }
  13966. return editor;
  13967. }
  13968. @ Every node type should have an associated editor and the editors for nodes
  13969. which can have child nodes should be able to handle creating these child nodes.
  13970. This leaves the problem of creating the top level nodes. For this we must have
  13971. a way to register three key pieces of information: the text which should appear
  13972. for selecting a new top level node to add to the configuration, the default
  13973. name for a node of that type, and the registered driver string associated with
  13974. that node type. The most likely use for this information is in constructing a
  13975. menu. |QAction| seems like a good fit, but this cannot pass all of the
  13976. required information. Part of the chosen solution is a |QAction| subclass
  13977. which takes all three pieces of information and provides a new signal to
  13978. supply the information needed to add a new top level node.
  13979. @<Class declarations@>=
  13980. class NodeInserter : public QAction@/
  13981. {@/
  13982. @[Q_OBJECT@]@;
  13983. public:@/
  13984. NodeInserter(const QString &title, const QString &name,
  13985. const QString &driver, QObject *parent = NULL);
  13986. signals:@/
  13987. void triggered(QString name, QString driver);
  13988. @[private slots@]:@/
  13989. void onTriggered();
  13990. private:@/
  13991. QString defaultNodeName;
  13992. QString driverString;
  13993. };
  13994. @ The constructor saves the information that will later be emitted and connects
  13995. the |triggered()| signal from |QAction| to a private slot which emits our new
  13996. |triggered()| signal.
  13997. @<NodeInserter implementation@>=
  13998. NodeInserter::NodeInserter(const QString &title, const QString &name,
  13999. const QString &driver, QObject *parent) :
  14000. QAction(title, parent), defaultNodeName(name), driverString(driver)
  14001. {
  14002. connect(this, SIGNAL(triggered()), this, SLOT(onTriggered()));
  14003. }
  14004. void NodeInserter::onTriggered()
  14005. {
  14006. emit triggered(defaultNodeName, driverString);
  14007. }
  14008. @ An interface for adding top level nodes to the device configuration needs to
  14009. be able to access a list of these actions so we make this available through the
  14010. |Application| instance. Once again, it would be better to split device
  14011. configuration registration data to a separate class and there should be
  14012. accessors around this.
  14013. Note that this terminology was introduced when it was assumed that device
  14014. configuration and logging view configuration would be separate. It is likely
  14015. that a future code cleanup will remove this in favor of handling the top level
  14016. of the device configuration hierarchy (under roaster specification) in the same
  14017. way that sub-nodes are handled.
  14018. @<Device configuration members@>=
  14019. QList<NodeInserter *> topLevelNodeInserters;
  14020. @ With this done, we can now produce a window which allows someone to easily
  14021. edit the device configuration.
  14022. As of version 1.6 this class is no longer a window but just a |QWidget| which
  14023. is inserted into another more general settings window. The name of the class
  14024. should be changed in a future version to reflect this change.
  14025. @<Class declarations@>=
  14026. class DeviceConfigurationWindow : public QWidget
  14027. {
  14028. @[Q_OBJECT@]@;
  14029. public:@/
  14030. DeviceConfigurationWindow();
  14031. @[public slots@]:@/
  14032. void addDevice();
  14033. void removeNode();
  14034. void newSelection(const QModelIndex &index);
  14035. @[private slots@]:@/
  14036. void resizeColumn();
  14037. private:@/
  14038. QDomDocument document;
  14039. DeviceTreeModel *model;
  14040. QTreeView *view;
  14041. QScrollArea *configArea;
  14042. };
  14043. @ This window consists of two main panels separated by a splitter. The left
  14044. panel presents a tree view of the current device configuration and a set of
  14045. controls that allows someone to either add a new top level node to the
  14046. configuration or delete any node in the configuration along with all of its
  14047. child nodes.
  14048. The right panel provides a |QScrollArea|. When a node is selected from the tree
  14049. view, the appropriate configuration widget will be inserted into that area.
  14050. When a configuration widget adds a new node to the device model, the parent
  14051. node (which should be the currently selected node but the code does not assume
  14052. this) is expanded to show the new child node if it has not already been
  14053. expanded.
  14054. @<DeviceConfigurationWindow implementation@>=
  14055. DeviceConfigurationWindow::DeviceConfigurationWindow() : QWidget(NULL),
  14056. view(new QTreeView), configArea(new QScrollArea)
  14057. {
  14058. QSplitter *splitter = new QSplitter;
  14059. QWidget *leftWidget = new QWidget;
  14060. leftWidget->setMinimumWidth(200);
  14061. QVBoxLayout *left = new QVBoxLayout;
  14062. view->setAnimated(true);
  14063. view->setSelectionMode(QAbstractItemView::SingleSelection);
  14064. document = AppInstance->deviceConfiguration();
  14065. model = new DeviceTreeModel;
  14066. view->setModel(model);
  14067. view->setTextElideMode(Qt::ElideNone);
  14068. view->expandAll();
  14069. view->resizeColumnToContents(0);
  14070. connect(model, SIGNAL(modelReset()), view, SLOT(expandAll()));
  14071. QHBoxLayout *treeButtons = new QHBoxLayout;
  14072. QToolButton *addDeviceButton = new QToolButton;
  14073. addDeviceButton->setIcon(QIcon::fromTheme("list-add"));
  14074. addDeviceButton->setToolTip(tr("New Roaster"));
  14075. connect(addDeviceButton, SIGNAL(clicked()),
  14076. this, SLOT(addDevice()));
  14077. QToolButton *removeNodeButton = new QToolButton;
  14078. removeNodeButton->setIcon(QIcon::fromTheme("list-remove"));
  14079. removeNodeButton->setToolTip(tr("Delete Selection"));
  14080. connect(removeNodeButton, SIGNAL(clicked()), this, SLOT(removeNode()));
  14081. treeButtons->addWidget(addDeviceButton);
  14082. treeButtons->addWidget(removeNodeButton);
  14083. left->addWidget(view);
  14084. left->addLayout(treeButtons);
  14085. leftWidget->setLayout(left);
  14086. splitter->addWidget(leftWidget);
  14087. configArea->setMinimumWidth(580);
  14088. configArea->setMinimumHeight(460);
  14089. configArea->setWidgetResizable(true);
  14090. splitter->addWidget(configArea);
  14091. QVBoxLayout *centralLayout = new QVBoxLayout;
  14092. centralLayout->addWidget(splitter);
  14093. setLayout(centralLayout);
  14094. connect(view, SIGNAL(activated(QModelIndex)),
  14095. this, SLOT(newSelection(QModelIndex)));
  14096. connect(view, SIGNAL(clicked(QModelIndex)),
  14097. this, SLOT(newSelection(QModelIndex)));
  14098. connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)),
  14099. view, SLOT(expand(QModelIndex)));
  14100. connect(model, SIGNAL(rowsInserted(QModelIndex, int, int)),
  14101. this, SLOT(resizeColumn()));
  14102. connect(model, SIGNAL(rowsRemoved(QModelIndex, int, int)),
  14103. this, SLOT(resizeColumn()));
  14104. }
  14105. @ Adding a new top level node to the model is just a matter of extracting the
  14106. required information from the signal requesting that addition.
  14107. @<DeviceConfigurationWindow implementation@>=
  14108. void DeviceConfigurationWindow::addDevice()
  14109. {
  14110. model->newNode(tr("New Roaster"), "roaster", QModelIndex());
  14111. }
  14112. @ Removing the currently selected node is also simple.
  14113. @<DeviceConfigurationWindow implementation@>=
  14114. void DeviceConfigurationWindow::removeNode()
  14115. {
  14116. QModelIndex index = view->currentIndex();
  14117. if(index.isValid())
  14118. {
  14119. int row = index.row();
  14120. QModelIndex parent = index.parent();
  14121. model->removeRow(row, parent);
  14122. }
  14123. }
  14124. @ Due to most of the required logic being implemented in
  14125. |Application::deviceConfigurationWidget()|, inserting the proper editor in the
  14126. right area is also trivial.
  14127. @<DeviceConfigurationWindow implementation@>=
  14128. void DeviceConfigurationWindow::newSelection(const QModelIndex &index)
  14129. {
  14130. QWidget *editor = AppInstance->deviceConfigurationWidget(model, index);
  14131. if(editor)
  14132. {
  14133. configArea->setWidget(editor);
  14134. editor->show();
  14135. }
  14136. }
  14137. @ As nodes are added deeper in the device hierarchy or as nodes obtain longer
  14138. names, the nodes names may be elided by default rather than indicate that the
  14139. view can be scrolled horizontally. There has been feedback that this behavior
  14140. is not preferred so instead as the model data changes we expand the column
  14141. instead.
  14142. @<DeviceConfigurationWindow implementation@>=
  14143. void DeviceConfigurationWindow::resizeColumn()
  14144. {
  14145. view->resizeColumnToContents(0);
  14146. }
  14147. @ At least for the initial testing of this feature it will be useful if we can
  14148. instantiate this from the host environment. For this we at least require a
  14149. constructor.
  14150. Now that this widget is available through a more general settings window it may
  14151. be better to remove direct access to this class from the host environment.
  14152. @<Function prototypes for scripting@>=
  14153. QScriptValue constructDeviceConfigurationWindow(QScriptContext *context,
  14154. QScriptEngine *engine);
  14155. @ The constructor is trivial.
  14156. @<Functions for scripting@>=
  14157. QScriptValue constructDeviceConfigurationWindow(QScriptContext *,
  14158. QScriptEngine *engine)
  14159. {
  14160. QScriptValue object = engine->newQObject(new DeviceConfigurationWindow);
  14161. return object;
  14162. }
  14163. @ Finally we inform the host environment of this constructor.
  14164. @<Set up the scripting engine@>=
  14165. constructor = engine->newFunction(constructDeviceConfigurationWindow);
  14166. value = engine->newQMetaObject(&DeviceConfigurationWindow::staticMetaObject,
  14167. constructor);
  14168. engine->globalObject().setProperty("DeviceConfigurationWindow", value);
  14169. @* A Base Class for Device Configuration Widgets.
  14170. \noindent There are certain operations that are very commonly required
  14171. among device configuration widgets. These common elements have been implemented
  14172. in a base class.
  14173. @<Class declarations@>=
  14174. class BasicDeviceConfigurationWidget : public QWidget
  14175. {
  14176. @[Q_OBJECT@]@;
  14177. public:@/
  14178. BasicDeviceConfigurationWidget(DeviceTreeModel *model,
  14179. const QModelIndex &index);
  14180. @[public slots@]:@/
  14181. void insertChildNode(const QString &name, const QString &driver);
  14182. void updateAttribute(const QString &name, const QString &value);
  14183. protected:@/
  14184. DeviceTreeModel *deviceModel;
  14185. QModelIndex currentNode;
  14186. };
  14187. @ The constructor just passes its arguments to a pair of protected data
  14188. members. These are commonly required in subclasses but need not be exposed
  14189. outside of this branch of the object hierarchy.
  14190. @<BasicDeviceConfigurationWidget implementation@>=
  14191. BasicDeviceConfigurationWidget::BasicDeviceConfigurationWidget(
  14192. DeviceTreeModel *model, const QModelIndex &index)
  14193. : QWidget(NULL), deviceModel(model), currentNode(index)
  14194. {
  14195. /* Nothing needs to be done here. */
  14196. }
  14197. @ The |updateAttribute()| method sets the value property of an attribute
  14198. element of a given name that is a child of the current node, creating the
  14199. element if it does not exist.
  14200. @<BasicDeviceConfigurationWidget implementation@>=
  14201. void BasicDeviceConfigurationWidget::updateAttribute(const QString &name,
  14202. const QString &value)
  14203. {
  14204. QDomElement referenceElement = deviceModel->referenceElement(
  14205. deviceModel->data(currentNode, Qt::UserRole).toString());
  14206. QDomNodeList configData = referenceElement.elementsByTagName("attribute");
  14207. QDomElement node;
  14208. bool found = @[false@];
  14209. for(int i = 0; i < configData.size(); i++)
  14210. {
  14211. node = configData.at(i).toElement();
  14212. if(node.attribute("name") == name)
  14213. {
  14214. node.setAttribute("value", value);
  14215. found = @[true@];
  14216. break;
  14217. }
  14218. }
  14219. if(!found)
  14220. {
  14221. node = AppInstance->deviceConfiguration().createElement("attribute");
  14222. node.setAttribute("name", name);
  14223. node.setAttribute("value", value);
  14224. referenceElement.appendChild(node);
  14225. }
  14226. AppInstance->saveDeviceConfiguration();
  14227. }
  14228. @ The |insertChildNode()| method constructs a new node with the specified name
  14229. and driver as a child of the current node. Node insertion is a generic
  14230. operation that does not require any knowledge of the configuration options that
  14231. will be presented in that node.
  14232. @<BasicDeviceConfigurationWidget implementation@>=
  14233. void BasicDeviceConfigurationWidget::insertChildNode(const QString &name,
  14234. const QString &driver)
  14235. {
  14236. deviceModel->newNode(name, driver, currentNode);
  14237. }
  14238. @** Configuration of Top Level Roaster Nodes.
  14239. \noindent The first configuration widget required is one for defining a coffee
  14240. roaster. This stores the identification number that will be used for machine
  14241. references in the database and also provides controls for adding all of the
  14242. required child nodes for hardware and configurable elements of the logging
  14243. window that may vary from one machine to the next.
  14244. All of the configuration widgets follow a similar pattern. One important detail
  14245. to note is that these configuration widgets are instantiated through Qt'@q'@>s
  14246. meta-object system. All of these constructors take a |DeviceTreeModel *| and a
  14247. |QModelIndex &| as arguments and they are marked as |Q_INVOKABLE|.
  14248. @<Class declarations@>=
  14249. class RoasterConfWidget : public BasicDeviceConfigurationWidget
  14250. {
  14251. @[Q_OBJECT@]@;
  14252. public:@/
  14253. @[Q_INVOKABLE@]@, RoasterConfWidget(DeviceTreeModel *model,
  14254. const QModelIndex &index);
  14255. @[private slots@]:@/
  14256. void updateRoasterId(int id);
  14257. void updateCapacityCheck(int value);
  14258. void updateCapacity(const QString &value);
  14259. void updateCapacityUnit(const QString &value);
  14260. };
  14261. @ Aside from the ID number used to identify the roaster in the database we also
  14262. need controls to add child nodes. In order to limit the number of options in
  14263. menus for adding child nodes, these are organized into groups that are
  14264. available through different controls.
  14265. @<RoasterConfWidget implementation@>=
  14266. RoasterConfWidget::RoasterConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  14267. : BasicDeviceConfigurationWidget(model, index)
  14268. {
  14269. QVBoxLayout *layout = new QVBoxLayout;
  14270. QPushButton *addDeviceButton = new QPushButton(tr("Add Device"));
  14271. QMenu *deviceMenu = new QMenu;
  14272. NodeInserter *insertAction;
  14273. foreach(insertAction, AppInstance->topLevelNodeInserters)
  14274. {
  14275. connect(insertAction, SIGNAL(triggered(QString, QString)),
  14276. this, SLOT(insertChildNode(QString, QString)));
  14277. deviceMenu->addAction(insertAction);
  14278. }
  14279. addDeviceButton->setMenu(deviceMenu);
  14280. layout->addWidget(addDeviceButton);
  14281. QPushButton *addAnnotationControlButton = new QPushButton(tr("Add Annotation Control"));
  14282. QMenu *annotationMenu = new QMenu;
  14283. NodeInserter *basicButtonInserter = new NodeInserter(tr("Annotation Button"), tr("Annotation Button"), "annotationbutton");
  14284. NodeInserter *countingButtonInserter = new NodeInserter(tr("Counting Button"), tr("Counting Button"), "reconfigurablebutton");
  14285. NodeInserter *spinBoxInserter = new NodeInserter(tr("Numeric Entry"), tr("Numeric Entry"), "annotationspinbox");
  14286. NodeInserter *freeAnnotationInserter = new NodeInserter(tr("Free Text"),
  14287. tr("Free Text"),
  14288. "freeannotation");
  14289. annotationMenu->addAction(basicButtonInserter);
  14290. annotationMenu->addAction(countingButtonInserter);
  14291. annotationMenu->addAction(spinBoxInserter);
  14292. annotationMenu->addAction(freeAnnotationInserter);
  14293. connect(basicButtonInserter, SIGNAL(triggered(QString, QString)),
  14294. this, SLOT(insertChildNode(QString, QString)));
  14295. connect(countingButtonInserter, SIGNAL(triggered(QString, QString)),
  14296. this, SLOT(insertChildNode(QString, QString)));
  14297. connect(spinBoxInserter, SIGNAL(triggered(QString, QString)),
  14298. this, SLOT(insertChildNode(QString, QString)));
  14299. connect(freeAnnotationInserter, SIGNAL(triggered(QString, QString)),
  14300. this, SLOT(insertChildNode(QString, QString)));
  14301. @<Add annotation control node inserters@>@;
  14302. addAnnotationControlButton->setMenu(annotationMenu);
  14303. layout->addWidget(addAnnotationControlButton);
  14304. QPushButton *timersButton = new QPushButton(tr("Extra Timers"));
  14305. QMenu *timersMenu = new QMenu;
  14306. NodeInserter *coolingTimerInserter = new NodeInserter(tr("Cooling Timer"), tr("Cooling Timer"), "coolingtimer");
  14307. NodeInserter *rangeTimerInserter = new NodeInserter(tr("Range Timer"), tr("Range Timer"), "rangetimer");
  14308. NodeInserter *multirangeTimerInserter = new NodeInserter(tr("Multi-Range Timer"), tr("Multi-Range Timer"), "multirangetimer");
  14309. timersMenu->addAction(coolingTimerInserter);
  14310. timersMenu->addAction(rangeTimerInserter);
  14311. timersMenu->addAction(multirangeTimerInserter);
  14312. connect(coolingTimerInserter, SIGNAL(triggered(QString, QString)),
  14313. this, SLOT(insertChildNode(QString, QString)));
  14314. connect(rangeTimerInserter, SIGNAL(triggered(QString, QString)),
  14315. this, SLOT(insertChildNode(QString, QString)));
  14316. connect(multirangeTimerInserter, SIGNAL(triggered(QString, QString)),
  14317. this, SLOT(insertChildNode(QString, QString)));
  14318. timersButton->setMenu(timersMenu);
  14319. layout->addWidget(timersButton);
  14320. QPushButton *advancedButton = new QPushButton(tr("Advanced Features"));
  14321. QMenu *advancedMenu = new QMenu;
  14322. NodeInserter *linearsplineinserter = new NodeInserter(tr("Linear Spline Interpolated Series"), tr("Linear Spline Interpolated Series"), "linearspline");
  14323. advancedMenu->addAction(linearsplineinserter);
  14324. NodeInserter *translationinserter = new NodeInserter(tr("Profile Translation"), tr("Profile Translation"), "translation");
  14325. advancedMenu->addAction(translationinserter);
  14326. connect(linearsplineinserter, SIGNAL(triggered(QString, QString)), this, SLOT(insertChildNode(QString, QString)));
  14327. connect(translationinserter, SIGNAL(triggered(QString, QString)), this, SLOT(insertChildNode(QString, QString)));
  14328. @<Add node inserters to advanced features menu@>@;
  14329. advancedButton->setMenu(advancedMenu);
  14330. layout->addWidget(advancedButton);
  14331. QHBoxLayout *idLayout = new QHBoxLayout;
  14332. QLabel *idLabel = new QLabel(tr("Machine ID for database:"));
  14333. idLayout->addWidget(idLabel);
  14334. QSpinBox *id = new QSpinBox;
  14335. idLayout->addWidget(id);
  14336. idLayout->addStretch();
  14337. layout->addLayout(idLayout);
  14338. QHBoxLayout *capacityLayout = new QHBoxLayout;
  14339. QCheckBox *capacityCheckEnabled = new QCheckBox(tr("Maximum batch size:"));
  14340. QDoubleSpinBox *capacity = new QDoubleSpinBox;
  14341. capacity->setMinimum(0.0);
  14342. capacity->setDecimals(3);
  14343. capacity->setMaximum(999999.999);
  14344. QComboBox *capacityUnit = new QComboBox;
  14345. capacityUnit->addItem("g");
  14346. capacityUnit->addItem("Kg");
  14347. capacityUnit->addItem("oz");
  14348. capacityUnit->addItem("Lb");
  14349. capacityUnit->setCurrentIndex(3);
  14350. capacityLayout->addWidget(capacityCheckEnabled);
  14351. capacityLayout->addWidget(capacity);
  14352. capacityLayout->addWidget(capacityUnit);
  14353. capacityLayout->addStretch();
  14354. layout->addLayout(capacityLayout);
  14355. layout->addStretch();
  14356. @<Get device configuration data for current node@>@;
  14357. for(int i = 0; i < configData.size(); i++)
  14358. {
  14359. node = configData.at(i).toElement();
  14360. if(node.attribute("name") == "databaseid")
  14361. {
  14362. id->setValue(node.attribute("value").toInt());
  14363. }
  14364. else if(node.attribute("name") == "checkcapacity")
  14365. {
  14366. capacityCheckEnabled->setChecked(node.attribute("value") == "true");
  14367. }
  14368. else if(node.attribute("name") == "capacity")
  14369. {
  14370. capacity->setValue(node.attribute("value").toDouble());
  14371. }
  14372. else if(node.attribute("name") == "capacityunit")
  14373. {
  14374. capacityUnit->setCurrentIndex(capacityUnit->findText(node.attribute("value")));
  14375. }
  14376. }
  14377. updateRoasterId(id->value());
  14378. connect(id, SIGNAL(valueChanged(int)), this, SLOT(updateRoasterId(int)));
  14379. connect(capacityCheckEnabled, SIGNAL(stateChanged(int)), this, SLOT(updateCapacityCheck(int)));
  14380. connect(capacity, SIGNAL(valueChanged(QString)), this, SLOT(updateCapacity(QString)));
  14381. connect(capacityUnit, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateCapacityUnit(QString)));
  14382. setLayout(layout);
  14383. }
  14384. @ Iterating over the configuration data associated with the current node is
  14385. required in nearly every configuration widget. The specifics of the loop
  14386. vary, but there is likely a better way to generalize that. Until then,
  14387. obtaining a |QDomNodeList| with the required data to iterate over has been
  14388. split off as its own chunk to reduce the risk of errors associated with typing
  14389. the same code many times.
  14390. @<Get device configuration data for current node@>=
  14391. QDomElement referenceElement =
  14392. model->referenceElement(model->data(index, Qt::UserRole).toString());
  14393. QDomNodeList configData = referenceElement.elementsByTagName("attribute");
  14394. QDomElement node;
  14395. @ We need to propagate changes to the configuration fields to the device
  14396. configuration document. The |updateAttribute()| method in the base class
  14397. makes this trivial.
  14398. @<RoasterConfWidget implementation@>=
  14399. void RoasterConfWidget::updateRoasterId(int id)
  14400. {
  14401. updateAttribute("databaseid", QString("%1").arg(id));
  14402. }
  14403. void RoasterConfWidget::updateCapacityCheck(int value)
  14404. {
  14405. updateAttribute("checkcapacity", value == Qt::Checked ? "true" : "false");
  14406. }
  14407. void RoasterConfWidget::updateCapacity(const QString &value)
  14408. {
  14409. updateAttribute("capacity", value);
  14410. }
  14411. void RoasterConfWidget::updateCapacityUnit(const QString &value)
  14412. {
  14413. updateAttribute("capacityunit", value);
  14414. }
  14415. @ Finally we must register the configuration widget so that it can be
  14416. instantiated at the appropriate time.
  14417. @<Register device configuration widgets@>=
  14418. app.registerDeviceConfigurationWidget("roaster", RoasterConfWidget::staticMetaObject);
  14419. @** Configuration for NI-DAQmx Base devices.
  14420. \noindent The primary concern in supporting hardware that communicates through
  14421. NI-DAQmx Base is in configurations using a single NI USB 9211 (for NI-DAQmx
  14422. Base 2.x) or NI USB 9211A (for NI-DAQmx Base 3.x), but if it is reasonable to
  14423. do so I'@q'@>d like to later add support for multiple device configurations and
  14424. limited support for other devices including the ability to use devices with
  14425. voltage inputs for non-temperature measurement data. The top priority, however,
  14426. is in continuing to support hardware that people are already using with Typica.
  14427. In order to more easily implement these future plans, device configuration is
  14428. handled with three configuration tiers. The top level configuration node
  14429. indicates that we are using NI-DAQmx Base. Here we can add a child node
  14430. representing either a NI USB 9211 or NI USB 9211A. From a configuration
  14431. perspective these are identical with the default node name as the only
  14432. difference. From the device configuration we can specify the device identifier
  14433. and add channels to the device. In the channel nodes we specify the
  14434. thermocouple type.
  14435. @<Class declarations@>=
  14436. class NiDaqMxBaseDriverConfWidget : public BasicDeviceConfigurationWidget
  14437. {
  14438. @[Q_OBJECT@]@;
  14439. public:@/
  14440. @[Q_INVOKABLE@]@, NiDaqMxBaseDriverConfWidget(DeviceTreeModel *model,@|
  14441. const QModelIndex &index);
  14442. };
  14443. @ There is very little to configure here so there isn'@q'@>t much for the
  14444. constructor to do. We do need to keep a reference to the node we are
  14445. configuring so that child nodes can later be added. At present, no real
  14446. configuration data other than the existence of the node is required so
  14447. there is no need to read any configuration data here.
  14448. @<NiDaqMxBaseDriverConfWidget implementation@>=
  14449. NiDaqMxBaseDriverConfWidget::NiDaqMxBaseDriverConfWidget(
  14450. DeviceTreeModel *model, const QModelIndex &index) :
  14451. BasicDeviceConfigurationWidget(model, index)
  14452. {
  14453. QHBoxLayout *layout = new QHBoxLayout;
  14454. QToolButton *addDeviceButton = new QToolButton;
  14455. addDeviceButton->setText(tr("Add Device"));
  14456. NodeInserter *add9211 = new NodeInserter("NI USB 9211", "NI USB 9211",
  14457. "nidaqmxbase9211series");
  14458. NodeInserter *add9211a = new NodeInserter("NI USB 9211A", "NI USB 9211A",
  14459. "nidaqmxbase9211series");
  14460. connect(add9211, SIGNAL(triggered(QString, QString)),
  14461. this, SLOT(insertChildNode(QString, QString)));
  14462. connect(add9211a, SIGNAL(triggered(QString, QString)),
  14463. this, SLOT(insertChildNode(QString, QString)));
  14464. QMenu *deviceMenu = new QMenu;
  14465. deviceMenu->addAction(add9211);
  14466. deviceMenu->addAction(add9211a);
  14467. addDeviceButton->setMenu(deviceMenu);
  14468. addDeviceButton->setPopupMode(QToolButton::InstantPopup);
  14469. layout->addWidget(addDeviceButton);
  14470. setLayout(layout);
  14471. }
  14472. @ Both the NI USB 9211 and NI USB 9211A are identical from a configuration
  14473. perspective. The only difference is the version of NI-DAQmx Base required for
  14474. use. As the API does not provide a way of determining which version is
  14475. installed, ensuring that the appropriate software is installed without
  14476. conflicts is left as an exercise for the person attempting to use \pn{}.
  14477. @<Class declarations@>=
  14478. class NiDaqMxBase9211ConfWidget : public BasicDeviceConfigurationWidget
  14479. {
  14480. Q_OBJECT
  14481. public:
  14482. Q_INVOKABLE NiDaqMxBase9211ConfWidget(DeviceTreeModel *device,
  14483. const QModelIndex &index);
  14484. private slots:
  14485. void addChannel();
  14486. void updateDeviceId(const QString &newId);
  14487. };
  14488. @ There are two controls required in a configuration widget for this device.
  14489. The first is the device identifier (for example, "Dev1"), the second is a
  14490. button for adding channels to the device. On a generic device we would also
  14491. need to set the clock rate, but with this hardware it is possible to determine
  14492. the maximum clock rate from the channels defined.
  14493. @<NiDaqMxBase9211ConfWidget implementation@>=
  14494. NiDaqMxBase9211ConfWidget::NiDaqMxBase9211ConfWidget(DeviceTreeModel *model,
  14495. const QModelIndex &index)
  14496. : BasicDeviceConfigurationWidget(model, index)
  14497. {
  14498. QVBoxLayout *layout = new QVBoxLayout;
  14499. QHBoxLayout *deviceIdLayout = new QHBoxLayout;
  14500. QLabel *label = new QLabel(tr("Device ID:"));
  14501. QLineEdit *deviceId = new QLineEdit;
  14502. deviceIdLayout->addWidget(label);
  14503. deviceIdLayout->addWidget(deviceId);
  14504. QPushButton *addChannelButton = new QPushButton(tr("Add Channel"));
  14505. layout->addLayout(deviceIdLayout);
  14506. layout->addWidget(addChannelButton);
  14507. @<Get device configuration data for current node@>@;
  14508. for(int i = 0; i < configData.size(); i++)
  14509. {
  14510. node = configData.at(i).toElement();
  14511. if(node.attribute("name") == "deviceID")
  14512. {
  14513. deviceId->setText(node.attribute("value", "Dev1"));
  14514. break;
  14515. }
  14516. }
  14517. updateDeviceId(deviceId->text());
  14518. connect(addChannelButton, SIGNAL(clicked()),
  14519. this, SLOT(addChannel()));
  14520. connect(deviceId, SIGNAL(textEdited(QString)),
  14521. this, SLOT(updateDeviceId(QString)));
  14522. setLayout(layout);
  14523. }
  14524. @ Updating the attribute tag under the reference element associated with the
  14525. current node is handled in the base class so we just need to pass in the
  14526. appropriate name value pair.
  14527. @<NiDaqMxBase9211ConfWidget implementation@>=
  14528. void NiDaqMxBase9211ConfWidget::updateDeviceId(const QString &newId)
  14529. {
  14530. updateAttribute("deviceID", newId);
  14531. }
  14532. @ Adding channels is just like adding any other sort of node.
  14533. @<NiDaqMxBase9211ConfWidget implementation@>=
  14534. void NiDaqMxBase9211ConfWidget::addChannel()
  14535. {
  14536. insertChildNode(tr("Thermocouple channel"), "ni9211seriestc");
  14537. }
  14538. @ Finally, we need a configuration widget to handle our thermocouple channels.
  14539. Ordinarily we would need three pieces of information for each channel. First
  14540. there is the thermocouple channel. Previously this was left implied by the
  14541. order of requests for a new channel, but more flexible configuration options
  14542. become possible with a more explicit specification. Since this widget is device
  14543. specific, all of the options can be easily enumerated to match markings on the
  14544. device. Next is the thermocouple type. Many options are supported, but I would
  14545. like to ensure that the most commonly used choices are listed first. The other
  14546. piece of information that DAQmx or DAQmx Base require is the measurement unit.
  14547. As all of Typica'@q'@>s internal operations are in Fahrenheit there is no need to
  14548. make this configurable so long as everything else that can display temperature
  14549. measurements can perform the appropriate conversions.
  14550. Note that as there are no configuration differences between the various
  14551. device combinations using an NI 9211 module with regard to thermocouple channel
  14552. configuration, we can use this widget with all device combinations that make
  14553. use of such a module.
  14554. @<Class declarations@>=
  14555. class Ni9211TcConfWidget : public BasicDeviceConfigurationWidget
  14556. {@/
  14557. @[Q_OBJECT@]@;
  14558. public:@/
  14559. Q_INVOKABLE@,@, Ni9211TcConfWidget(DeviceTreeModel *device,
  14560. const QModelIndex &index);
  14561. @[private slots@]:@/
  14562. void updateThermocoupleType(const QString &type);
  14563. void updateColumnName(const QString &name);
  14564. void updateHidden(bool hidden);
  14565. };
  14566. @ This follows the same pattern of previous device configuration widgets. The
  14567. constructor provides the required configuration controls and slot methods
  14568. catch configuration changes and update the underlying XML document
  14569. appropriately.
  14570. @<Ni9211TcConfWidget implementation@>=
  14571. Ni9211TcConfWidget::Ni9211TcConfWidget(DeviceTreeModel *model,
  14572. const QModelIndex &index) :
  14573. BasicDeviceConfigurationWidget(model, index)
  14574. {
  14575. QFormLayout *layout = new QFormLayout;
  14576. QLineEdit *columnName = new QLineEdit;
  14577. layout->addRow(tr("Column Name:"), columnName);
  14578. QComboBox *typeSelector = new QComboBox;
  14579. typeSelector->addItem("J");
  14580. typeSelector->addItem("K");
  14581. typeSelector->addItem("T");
  14582. typeSelector->addItem("B");
  14583. typeSelector->addItem("E");
  14584. typeSelector->addItem("N");
  14585. typeSelector->addItem("R");
  14586. typeSelector->addItem("S");
  14587. layout->addRow(tr("Thermocouple Type:"), typeSelector);
  14588. QCheckBox *hideSeries = new QCheckBox("Hide this channel");
  14589. layout->addRow(hideSeries);
  14590. setLayout(layout);
  14591. @<Get device configuration data for current node@>@;
  14592. for(int i = 0; i < configData.size(); i++)
  14593. {
  14594. node = configData.at(i).toElement();
  14595. if(node.attribute("name") == "type")
  14596. {
  14597. typeSelector->setCurrentIndex(
  14598. typeSelector->findText(node.attribute("value")));
  14599. }
  14600. else if(node.attribute("name") == "columnname")
  14601. {
  14602. columnName->setText(node.attribute("value"));
  14603. }
  14604. else if(node.attribute("name") == "hidden")
  14605. {
  14606. hideSeries->setChecked(node.attribute("value") == "true");
  14607. }
  14608. }
  14609. updateThermocoupleType(typeSelector->currentText());
  14610. updateColumnName(columnName->text());
  14611. updateHidden(hideSeries->isChecked());
  14612. connect(typeSelector, SIGNAL(currentIndexChanged(QString)),
  14613. this, SLOT(updateThermocoupleType(QString)));
  14614. connect(columnName, SIGNAL(textEdited(QString)), this, SLOT(updateColumnName(QString)));
  14615. connect(hideSeries, SIGNAL(toggled(bool)), this, SLOT(updateHidden(bool)));
  14616. }
  14617. @ Two slots are used to pass configuration changes back to the underlying XML
  14618. representation.
  14619. @<Ni9211TcConfWidget implementation@>=
  14620. void Ni9211TcConfWidget::updateThermocoupleType(const QString &type)
  14621. {
  14622. updateAttribute("type", type);
  14623. }
  14624. void Ni9211TcConfWidget::updateColumnName(const QString &name)
  14625. {
  14626. updateAttribute("columnname", name);
  14627. }
  14628. void Ni9211TcConfWidget::updateHidden(bool hidden)
  14629. {
  14630. updateAttribute("hidden", hidden ? "true" : "false");
  14631. }
  14632. @ These three widgets need to be registered so the configuration widget can
  14633. instantiate them when the nodes are selected.
  14634. @<Register device configuration widgets@>=
  14635. app.registerDeviceConfigurationWidget("nidaqmxbase",
  14636. NiDaqMxBaseDriverConfWidget::staticMetaObject);
  14637. app.registerDeviceConfigurationWidget("nidaqmxbase9211series",
  14638. NiDaqMxBase9211ConfWidget::staticMetaObject);
  14639. app.registerDeviceConfigurationWidget("ni9211seriestc",
  14640. Ni9211TcConfWidget::staticMetaObject);
  14641. @ Furthermore, we should create the NodeInserter objects for adding top level
  14642. nodes to the configuration. Preferably we would only allow top level nodes to
  14643. be inserted when all prerequisite software is available.
  14644. @<Register top level device configuration nodes@>=
  14645. NodeInserter *inserter = new NodeInserter(tr("NI DAQmx Base Device"),
  14646. tr("NI DAQmx Base"),
  14647. "nidaqmxbase", NULL);
  14648. topLevelNodeInserters.append(inserter);
  14649. @** Configuration of NI-DAQmx devices.
  14650. \noindent The other main class of hardware currently supported in Typica is a
  14651. small set of devices that require NI-DAQmx. This includes a few combinations of
  14652. the NI 9211 in different carriers and the NI USB TC01. Additional hardware may
  14653. be added to this set in the future.
  14654. The approach here is very similar to the approach used to configure NI-DAQmx
  14655. Base devices, starting with a widget for adding child device nodes.
  14656. @<Class declarations@>=
  14657. class NiDaqMxDriverConfWidget : public BasicDeviceConfigurationWidget
  14658. {
  14659. @[Q_OBJECT@]@;
  14660. public:
  14661. @[Q_INVOKABLE@]@, NiDaqMxDriverConfWidget(DeviceTreeModel *model,
  14662. const QModelIndex &index);
  14663. };
  14664. @ Under our driver node we want to have the ability to insert device specific
  14665. child nodes.
  14666. @<NiDaqMxDriverConfWidget implementation@>=
  14667. NiDaqMxDriverConfWidget::NiDaqMxDriverConfWidget(DeviceTreeModel *model,
  14668. const QModelIndex &index)
  14669. : BasicDeviceConfigurationWidget(model, index)
  14670. {
  14671. QHBoxLayout *layout = new QHBoxLayout;
  14672. QToolButton *addDeviceButton = new QToolButton;
  14673. addDeviceButton->setText(tr("Add Device"));
  14674. NodeInserter *add9211a = new NodeInserter("NI USB 9211A", "NI USB 9211A",
  14675. "nidaqmx9211series");
  14676. NodeInserter *addtc01 = new NodeInserter("NI USB TC01", "NI USB TC01",
  14677. "nidaqmxtc01");
  14678. connect(add9211a, SIGNAL(triggered(QString, QString)),
  14679. this, SLOT(insertChildNode(QString, QString)));
  14680. connect(addtc01, SIGNAL(triggered(QString, QString)),
  14681. this, SLOT(insertChildNode(QString, QString)));
  14682. QMenu *deviceMenu = new QMenu;
  14683. deviceMenu->addAction(add9211a);
  14684. deviceMenu->addAction(addtc01);
  14685. addDeviceButton->setMenu(deviceMenu);
  14686. addDeviceButton->setPopupMode(QToolButton::InstantPopup);
  14687. layout->addWidget(addDeviceButton);
  14688. setLayout(layout);
  14689. }
  14690. @ Devices based on the 9211 module are essentially the same aside from device
  14691. naming convention. Configuring these is very similar to configuring similar
  14692. devices when using NI-DAQmx Base.
  14693. @<Class declarations@>=
  14694. class NiDaqMx9211ConfWidget : public BasicDeviceConfigurationWidget
  14695. {
  14696. @[Q_OBJECT@]@;
  14697. public:@/
  14698. @[Q_INVOKABLE@]@, NiDaqMx9211ConfWidget(DeviceTreeModel *model,
  14699. const QModelIndex &index);
  14700. @[private slots@]:@/
  14701. void addChannel();
  14702. void updateDeviceId(const QString &newId);
  14703. };
  14704. @ Implementation is essentially identical to the NI-DAQmx Base class. It is
  14705. likely that there will be differences if this is ever extended to support
  14706. automatic detection of connected hardware. While NI-DAQmx Base does not
  14707. provide a way to query device identifiers, it uses a consistent naming scheme
  14708. by which device identifiers can be discovered. While NI-DAQmx lacks the same
  14709. consistency in device identifiers, it does provide a way to query that
  14710. information.
  14711. @<NiDaqMx9211ConfWidget implementation@>=
  14712. NiDaqMx9211ConfWidget::NiDaqMx9211ConfWidget(DeviceTreeModel *model,
  14713. const QModelIndex &index)
  14714. : BasicDeviceConfigurationWidget(model, index)
  14715. {
  14716. QVBoxLayout *layout = new QVBoxLayout;
  14717. QHBoxLayout *deviceIdLayout = new QHBoxLayout;
  14718. QLabel *label = new QLabel(tr("Device ID:"));
  14719. QLineEdit *deviceId = new QLineEdit;
  14720. deviceIdLayout->addWidget(label);
  14721. deviceIdLayout->addWidget(deviceId);
  14722. QPushButton *addChannelButton = new QPushButton(tr("Add Channel"));
  14723. layout->addLayout(deviceIdLayout);
  14724. layout->addWidget(addChannelButton);
  14725. @<Get device configuration data for current node@>@;
  14726. for(int i = 0; i < configData.size(); i++)
  14727. {
  14728. node = configData.at(i).toElement();
  14729. if(node.attribute("name") == "deviceID")
  14730. {
  14731. deviceId->setText(node.attribute("value","Dev1"));
  14732. break;
  14733. }
  14734. }
  14735. updateDeviceId(deviceId->text());
  14736. connect(addChannelButton, SIGNAL(clicked()), this, SLOT(addChannel()));
  14737. connect(deviceId, SIGNAL(textEdited(QString)),
  14738. this, SLOT(updateDeviceId(QString)));
  14739. setLayout(layout);
  14740. }
  14741. void NiDaqMx9211ConfWidget::updateDeviceId(const QString &newId)
  14742. {
  14743. updateAttribute("deviceID", newId);
  14744. }
  14745. void NiDaqMx9211ConfWidget::addChannel()
  14746. {
  14747. insertChildNode(tr("Thermocouple channel"), "ni9211seriestc");
  14748. }
  14749. @ There is no need to create a configuration widget specific to the 9211 module
  14750. used in NI-DAQmx. The widget already used for NI-DAQmx Base can be used without
  14751. modification.
  14752. Configuring Typica for use with the NI USB-TC01 can be slightly simplified as
  14753. the device only has a single thermocouple channel. We can configure this without
  14754. requiring another node.
  14755. @<Class declarations@>=
  14756. class NiDaqMxTc01ConfWidget : public BasicDeviceConfigurationWidget
  14757. {
  14758. @[Q_OBJECT@]@;
  14759. public:@/
  14760. @[Q_INVOKABLE@]@, NiDaqMxTc01ConfWidget(DeviceTreeModel *model,
  14761. const QModelIndex &index);
  14762. @[private slots@]:@/
  14763. void updateDeviceId(const QString &newId);
  14764. void updateThermocoupleType(const QString &type);
  14765. void updateColumnName(const QString &name);
  14766. void updateHidden(bool hidden);
  14767. };
  14768. @ The implementation is similar to the other configuration widgets.
  14769. @<NiDaqMxTc01ConfWidget implementation@>=
  14770. NiDaqMxTc01ConfWidget::NiDaqMxTc01ConfWidget(DeviceTreeModel *model,
  14771. const QModelIndex &index)
  14772. : BasicDeviceConfigurationWidget(model, index)
  14773. {
  14774. QFormLayout *layout = new QFormLayout;
  14775. QLineEdit *deviceId = new QLineEdit;
  14776. layout->addRow(tr("Device ID:"), deviceId);
  14777. QLineEdit *columnName = new QLineEdit;
  14778. layout->addRow(tr("Column Name:"), columnName);
  14779. QComboBox *typeSelector = new QComboBox;
  14780. typeSelector->addItem("J");
  14781. typeSelector->addItem("K");
  14782. typeSelector->addItem("T");
  14783. typeSelector->addItem("B");
  14784. typeSelector->addItem("E");
  14785. typeSelector->addItem("N");
  14786. typeSelector->addItem("R");
  14787. typeSelector->addItem("S");
  14788. layout->addRow(tr("Thermocouple Type:"), typeSelector);
  14789. QCheckBox *hideSeries = new QCheckBox(tr("Hide this channel"));
  14790. layout->addRow(hideSeries);
  14791. @<Get device configuration data for current node@>@;
  14792. for(int i = 0; i < configData.size(); i++)
  14793. {
  14794. node = configData.at(i).toElement();
  14795. if(node.attribute("name") == "deviceID")
  14796. {
  14797. deviceId->setText(node.attribute("value"));
  14798. }
  14799. else if(node.attribute("name") == "type")
  14800. {
  14801. typeSelector->setCurrentIndex(typeSelector->findText(node.attribute("value")));
  14802. }
  14803. else if(node.attribute("name") == "columnname")
  14804. {
  14805. columnName->setText(node.attribute("value"));
  14806. }
  14807. else if(node.attribute("name") == "hidden")
  14808. {
  14809. hideSeries->setChecked(node.attribute("value") == "true");
  14810. }
  14811. }
  14812. updateDeviceId(deviceId->text());
  14813. updateThermocoupleType(typeSelector->currentText());
  14814. updateColumnName(columnName->text());
  14815. updateHidden(hideSeries->isChecked());
  14816. connect(deviceId, SIGNAL(textEdited(QString)), this, SLOT(updateDeviceId(QString)));
  14817. connect(typeSelector, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateThermocoupleType(QString)));
  14818. connect(columnName, SIGNAL(textEdited(QString)), this, SLOT(updateColumnName(QString)));
  14819. setLayout(layout);
  14820. connect(hideSeries, SIGNAL(toggled(bool)), this, SLOT(updateHidden(bool)));
  14821. }
  14822. void NiDaqMxTc01ConfWidget::updateDeviceId(const QString &newId)
  14823. {
  14824. updateAttribute("deviceID", newId);
  14825. }
  14826. void NiDaqMxTc01ConfWidget::updateThermocoupleType(const QString &type)
  14827. {
  14828. updateAttribute("type", type);
  14829. }
  14830. void NiDaqMxTc01ConfWidget::updateColumnName(const QString &name)
  14831. {
  14832. updateAttribute("columnname", name);
  14833. }
  14834. void NiDaqMxTc01ConfWidget::updateHidden(bool hidden)
  14835. {
  14836. updateAttribute("hidden", hidden ? "true" : "false");
  14837. }
  14838. @ These configuration widgets need to be registered so they can be instantiated
  14839. in response to node selections.
  14840. @<Register device configuration widgets@>=
  14841. app.registerDeviceConfigurationWidget("nidaqmx", NiDaqMxDriverConfWidget::staticMetaObject);
  14842. app.registerDeviceConfigurationWidget("nidaqmx9211series", NiDaqMx9211ConfWidget::staticMetaObject);
  14843. app.registerDeviceConfigurationWidget("nidaqmxtc01", NiDaqMxTc01ConfWidget::staticMetaObject);
  14844. @ A |NodeInserter| for the driver configuration widget is also needed. Note that
  14845. at present NI DAQmx is only available on Windows so we do not bother to show
  14846. the option on other platforms. It would be generally preferable to replace this
  14847. with a check at runtime to determine if the required library exists. That could
  14848. be done with anything that requires third party installed code, leaving by
  14849. default only those options which have no external dependencies.
  14850. @<Register top level device configuration nodes@>=
  14851. #ifdef Q_OS_WIN32
  14852. inserter = new NodeInserter(tr("NI DAQmx Device"), tr("NI DAQmx"), "nidaqmx", NULL);
  14853. topLevelNodeInserters.append(inserter);
  14854. #endif
  14855. @** Configuration of Serial Port Devices.
  14856. \noindent It is possible to communicate with a number of devices through a
  14857. serial port. To do this, the appropriate settings for opening the port are
  14858. required and the communications protocol understood by the device must be
  14859. known. Serial port communications are provided by QextSerialPort. That
  14860. project was released under the MIT license.\nfnote{See the license text for
  14861. more information.} Additional headers are required.
  14862. @<Header files to include@>=
  14863. #include "qextserialport.h"
  14864. #include "qextserialenumerator.h"
  14865. @ Some custom widgets are provided which allow selecting the relevant
  14866. connection options from combo boxes. First there is a widget for selecting
  14867. the desired serial port. The drop down is pre-populated with any serial ports
  14868. that could be automatically detected, but the field can also be edited to
  14869. other values as may be required if the hardware is not connected during
  14870. configuration.
  14871. @<Class declarations@>=
  14872. class PortSelector : public QComboBox
  14873. {
  14874. Q_OBJECT
  14875. public:
  14876. PortSelector(QWidget *parent = NULL);
  14877. private slots:
  14878. void addDevice(QextPortInfo port);
  14879. private:
  14880. QextSerialEnumerator *lister;
  14881. };
  14882. @ The implementation is trivial.
  14883. @<PortSelector implementation@>=
  14884. PortSelector::PortSelector(QWidget *parent) : QComboBox(parent),
  14885. lister(new QextSerialEnumerator)
  14886. {
  14887. QList<QextPortInfo> ports = QextSerialEnumerator::getPorts();
  14888. QextPortInfo port;
  14889. foreach(port, ports)
  14890. {
  14891. #ifdef Q_OS_WIN32
  14892. addItem(port.portName);
  14893. #else
  14894. addItem(port.physName);
  14895. #endif
  14896. }
  14897. lister->setUpNotifications();
  14898. connect(lister, SIGNAL(deviceDiscovered(QextPortInfo)),
  14899. this, SLOT(addDevice(QextPortInfo)));
  14900. setEditable(true);
  14901. }
  14902. void PortSelector::addDevice(QextPortInfo port)
  14903. {
  14904. addItem(port.portName);
  14905. }
  14906. @ Next is a widget which allows selecting the baud rate. Only rates supported
  14907. by the current operating system are available to select.
  14908. A later version of QextSerialPort than is used by \pn{} provides a helper
  14909. class which can be used more conveniently to create this sort of control. As
  14910. this is not yet available to \pn{}, we instead copy the |enum| specifying
  14911. the appropriate values into the class and use Qt'@q'@>s meta-object system to
  14912. populate the combo box based on the values in that |enum|.
  14913. @<Class declarations@>=
  14914. class BaudSelector : public QComboBox
  14915. {
  14916. Q_OBJECT
  14917. Q_ENUMS(BaudRateType)
  14918. public:
  14919. BaudSelector(QWidget *parent = NULL);
  14920. enum BaudRateType
  14921. {
  14922. #if defined(Q_OS_UNIX) || defined(qdoc)
  14923. BAUD50 = 50, //POSIX ONLY
  14924. BAUD75 = 75, //POSIX ONLY
  14925. BAUD134 = 134, //POSIX ONLY
  14926. BAUD150 = 150, //POSIX ONLY
  14927. BAUD200 = 200, //POSIX ONLY
  14928. BAUD1800 = 1800, //POSIX ONLY
  14929. #if defined(B76800) || defined(qdoc)
  14930. BAUD76800 = 76800, //POSIX ONLY
  14931. #endif
  14932. #if (defined(B230400) && defined(B4000000)) || defined(qdoc)
  14933. BAUD230400 = 230400, //POSIX ONLY
  14934. BAUD460800 = 460800, //POSIX ONLY
  14935. BAUD500000 = 500000, //POSIX ONLY
  14936. BAUD576000 = 576000, //POSIX ONLY
  14937. BAUD921600 = 921600, //POSIX ONLY
  14938. BAUD1000000 = 1000000, //POSIX ONLY
  14939. BAUD1152000 = 1152000, //POSIX ONLY
  14940. BAUD1500000 = 1500000, //POSIX ONLY
  14941. BAUD2000000 = 2000000, //POSIX ONLY
  14942. BAUD2500000 = 2500000, //POSIX ONLY
  14943. BAUD3000000 = 3000000, //POSIX ONLY
  14944. BAUD3500000 = 3500000, //POSIX ONLY
  14945. BAUD4000000 = 4000000, //POSIX ONLY
  14946. #endif
  14947. #endif
  14948. #if defined(Q_OS_WIN) || defined(qdoc)
  14949. BAUD14400 = 14400, //WINDOWS ONLY
  14950. BAUD56000 = 56000, //WINDOWS ONLY
  14951. BAUD128000 = 128000, //WINDOWS ONLY
  14952. BAUD256000 = 256000, //WINDOWS ONLY
  14953. #endif
  14954. BAUD110 = 110,
  14955. BAUD300 = 300,
  14956. BAUD600 = 600,
  14957. BAUD1200 = 1200,
  14958. BAUD2400 = 2400,
  14959. BAUD4800 = 4800,
  14960. BAUD9600 = 9600,
  14961. BAUD19200 = 19200,
  14962. BAUD38400 = 38400,
  14963. BAUD57600 = 57600,
  14964. BAUD115200 = 115200
  14965. };
  14966. };
  14967. @ As the |enum| values are identical to the baud rates represented, we only
  14968. the numeric values, ignoring the names which are rather ugly.
  14969. @<BaudSelector implementation@>=
  14970. BaudSelector::BaudSelector(QWidget *parent) : QComboBox(parent)
  14971. {
  14972. QMetaObject meta = BaudSelector::staticMetaObject;
  14973. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("BaudRateType"));
  14974. for(int i = 0; i < type.keyCount(); i++)
  14975. {
  14976. addItem(QString("%1").arg(type.value(i)));
  14977. }
  14978. }
  14979. @ This same technique is used in a widget for selecting parity.
  14980. @<Class declarations@>=
  14981. class ParitySelector : public QComboBox
  14982. {
  14983. Q_OBJECT
  14984. Q_ENUMS(ParityType)
  14985. public:
  14986. ParitySelector(QWidget *parent = NULL);
  14987. enum ParityType
  14988. {
  14989. PAR_NONE,
  14990. PAR_ODD,
  14991. PAR_EVEN,
  14992. #if defined(Q_OS_WIN) || defined(qdoc)
  14993. PAR_MARK, //WINDOWS ONLY
  14994. #endif
  14995. PAR_SPACE
  14996. };
  14997. };
  14998. @ Implementation is similar to |BaudSelector| but as the values have no
  14999. apparent relation to what is represented we present the value names, placing
  15000. the corresponding value in the user data space associated with each entry.
  15001. The names here are ugly and not amenable to localization so this approach
  15002. should be reconsidered later.
  15003. @<ParitySelector implementation@>=
  15004. ParitySelector::ParitySelector(QWidget *parent) : QComboBox(parent)
  15005. {
  15006. QMetaObject meta = ParitySelector::staticMetaObject;
  15007. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("ParityType"));
  15008. for(int i = 0; i < type.keyCount(); i++)
  15009. {
  15010. addItem(QString(type.key(i)), QVariant(type.value(i)));
  15011. }
  15012. }
  15013. @ Similarly, we have a widget for selecting a method for flow control.
  15014. @<Class declarations@>=
  15015. class FlowSelector : public QComboBox
  15016. {
  15017. @[Q_OBJECT@]@;
  15018. @[Q_ENUMS(FlowType)@]@;
  15019. public:@/
  15020. FlowSelector(QWidget *parent = NULL);
  15021. enum FlowType
  15022. {
  15023. FLOW_OFF,
  15024. FLOW_HARDWARE,
  15025. FLOW_XONXOFF
  15026. };
  15027. };
  15028. @ Implementation follows the same pattern as in |ParitySelector|.
  15029. @<FlowSelector implementation@>=
  15030. FlowSelector::FlowSelector(QWidget *parent) : QComboBox(parent)
  15031. {
  15032. QMetaObject meta = FlowSelector::staticMetaObject;
  15033. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("FlowType"));
  15034. for(int i = 0; i < type.keyCount(); i++)
  15035. {
  15036. addItem(QString(type.key(i)), QVariant(type.value(i)));
  15037. }
  15038. }
  15039. @ We assume that the number of data bits will always be 8, though it may be
  15040. useful to later provide a control for selecting this for use with other devices
  15041. where this may not be assumed or for the sake of completion. This only leaves
  15042. specifying the number of stop bits.
  15043. @<Class declarations@>=
  15044. class StopSelector : public QComboBox
  15045. {
  15046. @[Q_OBJECT@]@;
  15047. @[Q_ENUMS(StopBitsType)@]@;
  15048. public:@/
  15049. StopSelector(QWidget *parent = NULL);
  15050. enum StopBitsType
  15051. {
  15052. STOP_1,
  15053. #if defined(Q_OS_WIN) || defined(qdoc)
  15054. STOP_1_5, //WINDOWS ONLY
  15055. #endif
  15056. STOP_2
  15057. };
  15058. };
  15059. @ Implementation should be familiar by now.
  15060. @<StopSelector implementation@>=
  15061. StopSelector::StopSelector(QWidget *parent) : QComboBox(parent)
  15062. {
  15063. QMetaObject meta = StopSelector::staticMetaObject;
  15064. QMetaEnum type = meta.enumerator(meta.indexOfEnumerator("StopBitsType"));
  15065. for(int i = 0; i < type.keyCount(); i++)
  15066. {
  15067. addItem(QString(type.key(i)), QVariant(type.value(i)));
  15068. }
  15069. }
  15070. @** Configuration of Serial Devices Using Modbus RTU.
  15071. \noindent The following sections contain the details of older code related to
  15072. Modbus RTU support. While the various selector widgets are shared with the new
  15073. code, the configuration widgets and device interfaces are being replaced.
  15074. One protocol that is used across a broad class of devices is called
  15075. Modbus RTU. This protocol allows multiple devices to be chained together on a
  15076. two wire bus which can be connected to a single serial port. The communication
  15077. protocol involves a single message which is sent from a master device (in this
  15078. case the computer running Typica) to a slave device (the device we would like
  15079. to obtain information from) which is followed by a response message from the
  15080. slave to the master. After a brief wait the master can then send another
  15081. message to any slave on the bus and this process repeats. Every outgoing
  15082. message provides a station address to identify which slave on the bus should
  15083. respond, a function code to identify which of a broad class of operations has
  15084. been requested, the required data for the function specified, and a cyclic
  15085. redundancy check to validate the message.
  15086. @** A Spin Box with Hexadecimal Representation.
  15087. \noindent Common convention for communications documentation for devices that
  15088. use Modbus RTU is that relative addresses are specified in hexadecimal
  15089. representation. In order to simplify initial device configuration, it would be
  15090. best that input widgets both accept input in base 16 and display values as a
  15091. four digit hexadecimal value.
  15092. @<Class declarations@>=
  15093. class ShortHexSpinBox : public QSpinBox
  15094. {
  15095. @[Q_OBJECT@]@;
  15096. public:@/
  15097. ShortHexSpinBox(QWidget *parent = NULL);
  15098. virtual QValidator::State validate(QString &input, int &pos) const;@/
  15099. protected:@/
  15100. virtual int valueFromText(const QString &text) const;
  15101. virtual QString textFromValue(int value) const;@/
  15102. };
  15103. @ For this we can set some new defaults in the constructor and must override
  15104. three methods.
  15105. @<ShortHexSpinBox implementation@>=
  15106. ShortHexSpinBox::ShortHexSpinBox(QWidget *parent) : QSpinBox(parent)
  15107. {
  15108. setMinimum(0);
  15109. setMaximum(0xFFFF);
  15110. setPrefix("0x");
  15111. setMinimumWidth(65);
  15112. }
  15113. QValidator::State ShortHexSpinBox::validate(QString &input, int &) const
  15114. {
  15115. if(input.size() == 2)
  15116. {
  15117. return QValidator::Intermediate;
  15118. }
  15119. bool okay;
  15120. input.toInt(&okay, 16);
  15121. if(okay)
  15122. {
  15123. return QValidator::Acceptable;
  15124. }
  15125. return QValidator::Invalid;
  15126. }
  15127. int ShortHexSpinBox::valueFromText(const QString &text) const
  15128. {
  15129. return text.toInt(NULL, 16);
  15130. }
  15131. QString ShortHexSpinBox::textFromValue(int value) const
  15132. {
  15133. QString retval;
  15134. retval.setNum(value, 16);
  15135. while(retval.size() < 4)
  15136. {
  15137. retval.prepend("0");
  15138. }
  15139. return retval.toUpper();
  15140. }
  15141. @** Configuration Widgets for Modbus RTU Devices.
  15142. \noindent While the top level configuration widgets seen so far have not had
  15143. any configuration details beyond the ability to add devices under the driver,
  15144. in the case of a serial port with Modbus RTU devices it is reasonable to
  15145. provide the connection details which will be shared by all devices on the bus.
  15146. @<Class declarations@>=
  15147. class ModbusRtuPortConfWidget : public BasicDeviceConfigurationWidget
  15148. {
  15149. @[Q_OBJECT@]@;
  15150. public:
  15151. @[Q_INVOKABLE@]@, ModbusRtuPortConfWidget(DeviceTreeModel *model,
  15152. const QModelIndex &index);
  15153. @[private slots@]:@/
  15154. void updatePort(const QString &newPort);
  15155. void updateBaudRate(const QString &newRate);
  15156. void updateParity(const QString &newParity);
  15157. void updateFlowControl(const QString &newFlow);
  15158. void updateStopBits(const QString &newStopBits);
  15159. };
  15160. @ Aside from the extra information compared with other configuration widgets
  15161. previously described, there is nothing surprising about the implementation.
  15162. @<ModbusRtuPortConfWidget implementation@>=
  15163. ModbusRtuPortConfWidget::ModbusRtuPortConfWidget(DeviceTreeModel *model,
  15164. const QModelIndex &index)
  15165. : BasicDeviceConfigurationWidget(model, index)
  15166. {
  15167. QFormLayout *layout = new QFormLayout;
  15168. QToolButton *addDeviceButton = new QToolButton;
  15169. addDeviceButton->setText(tr("Add Device"));
  15170. NodeInserter *addModbusRtuDevice = new NodeInserter("Modbus RTU Device",
  15171. "Modbus RTU Device",
  15172. "modbusrtudevice");
  15173. connect(addModbusRtuDevice, SIGNAL(triggered(QString, QString)),
  15174. this, SLOT(insertChildNode(QString, QString)));
  15175. QMenu *deviceMenu = new QMenu;
  15176. deviceMenu->addAction(addModbusRtuDevice);
  15177. addDeviceButton->setMenu(deviceMenu);
  15178. addDeviceButton->setPopupMode(QToolButton::InstantPopup);
  15179. layout->addRow(QString(), addDeviceButton);
  15180. PortSelector *port = new PortSelector;
  15181. layout->addRow(tr("Port:"), port);
  15182. connect(port, SIGNAL(currentIndexChanged(QString)),
  15183. this, SLOT(updatePort(QString)));
  15184. connect(port, SIGNAL(editTextChanged(QString)),
  15185. this, SLOT(updatePort(QString)));
  15186. BaudSelector *rate = new BaudSelector;
  15187. layout->addRow(tr("Baud:"), rate);
  15188. connect(rate, SIGNAL(currentIndexChanged(QString)),
  15189. this, SLOT(updateBaudRate(QString)));
  15190. ParitySelector *parity = new ParitySelector;
  15191. layout->addRow(tr("Parity:"), parity);
  15192. connect(parity, SIGNAL(currentIndexChanged(QString)),
  15193. this, SLOT(updateParity(QString)));
  15194. FlowSelector *flow = new FlowSelector;
  15195. layout->addRow(tr("Flow Control:"), flow);
  15196. connect(flow, SIGNAL(currentIndexChanged(QString)),
  15197. this, SLOT(updateFlowControl(QString)));
  15198. StopSelector *stop = new StopSelector;
  15199. layout->addRow(tr("Stop Bits:"), stop);
  15200. connect(stop, SIGNAL(currentIndexChanged(QString)),
  15201. this, SLOT(updateStopBits(QString)));
  15202. @<Get device configuration data for current node@>@;
  15203. for(int i = 0; i < configData.size(); i++)
  15204. {
  15205. node = configData.at(i).toElement();
  15206. if(node.attribute("name") == "port")
  15207. {
  15208. int j = port->findText(node.attribute("value"));
  15209. if(j >= 0)
  15210. {
  15211. port->setCurrentIndex(j);
  15212. }
  15213. else
  15214. {
  15215. port->insertItem(0, node.attribute("value"));
  15216. port->setCurrentIndex(0);
  15217. }
  15218. }
  15219. else if(node.attribute("name") == "baudrate")
  15220. {
  15221. rate->setCurrentIndex(rate->findText(node.attribute("value")));
  15222. }
  15223. else if(node.attribute("name") == "parity")
  15224. {
  15225. parity->setCurrentIndex(parity->findText(node.attribute("value")));
  15226. }
  15227. else if(node.attribute("name") == "flowcontrol")
  15228. {
  15229. flow->setCurrentIndex(flow->findText(node.attribute("value")));
  15230. }
  15231. else if(node.attribute("name") == "stopbits")
  15232. {
  15233. stop->setCurrentIndex(stop->findText(node.attribute("value")));
  15234. }
  15235. }
  15236. updatePort(port->currentText());
  15237. updateBaudRate(rate->currentText());
  15238. updateParity(parity->currentText());
  15239. updateFlowControl(flow->currentText());
  15240. updateStopBits(stop->currentText());
  15241. setLayout(layout);
  15242. }
  15243. void ModbusRtuPortConfWidget::updatePort(const QString &newPort)
  15244. {
  15245. updateAttribute("port", newPort);
  15246. }
  15247. void ModbusRtuPortConfWidget::updateBaudRate(const QString &newRate)
  15248. {
  15249. updateAttribute("baudrate", newRate);
  15250. }
  15251. void ModbusRtuPortConfWidget::updateParity(const QString &newParity)
  15252. {
  15253. updateAttribute("parity", newParity);
  15254. }
  15255. void ModbusRtuPortConfWidget::updateFlowControl(const QString &newFlow)
  15256. {
  15257. updateAttribute("flowcontrol", newFlow);
  15258. }
  15259. void ModbusRtuPortConfWidget::updateStopBits(const QString &newStopBits)
  15260. {
  15261. updateAttribute("stopbits", newStopBits);
  15262. }
  15263. @ From here we need to provide a widget for configuring a particular device.
  15264. At a minimum this would require setting the station number to a value between
  15265. 0 and 255. Zero is typically the broadcast address which reaches all devices
  15266. on the bus and is not generally recommended for use except in particular
  15267. circumstances. There are, however, a number of settings that influence all of
  15268. the currently supported child nodes and these settings are in the device
  15269. configuration widget instead of requiring that information to be duplicated
  15270. across multiple child nodes.
  15271. The Modbus RTU protocol is very general in scope and leaves many of the
  15272. details of how to do certain things up to the manufacturer. For rudimentary
  15273. support of devices using this protocol, the documentation for several devices
  15274. was consulted and a test rig with one device was set up. There are a number of
  15275. assumptions made for this initial support and to better support additional
  15276. device classes it may become necessary to expand on what is provided initially.
  15277. The primary focus presently is on the use of PID controllers as temperature
  15278. indicators with the ability to modify a set value in the case where this is
  15279. used as a controller rather than just a display.
  15280. All of the devices studied prior to adding this support made use of scaled
  15281. integer representation. In order to correctly determine the measured process
  15282. value it is necessary to know the unit of the measurement and the position of
  15283. the decimal point. It is generally possible to query this information, however
  15284. it may be useful to provide a way to specify fixed values in the event that a
  15285. device exposes these details in a way that is incompatible with my assumptions.
  15286. @<Class declarations@>=
  15287. class ModbusRtuDeviceConfWidget : public BasicDeviceConfigurationWidget
  15288. {
  15289. @[Q_OBJECT@]@;
  15290. public:@/
  15291. @[Q_INVOKABLE@]@, ModbusRtuDeviceConfWidget(DeviceTreeModel *model,
  15292. const QModelIndex &index);
  15293. @[private slots@]:@/
  15294. void updateStationNumber(int newStation);
  15295. void updateFixedUnit(bool newFixed);
  15296. void updateFixedDecimal(bool newFixed);
  15297. void updateUnit(const QString &newUnit);
  15298. void updateUnitAddress(int newAddress);
  15299. void updateValueF(int newValue);
  15300. void updateValueC(int newValue);
  15301. void updatePrecisionAddress(int newAddress);
  15302. void updatePrecisionValue(int newValue);
  15303. private:@/
  15304. QStackedLayout *unitSpecificationLayout;
  15305. QStackedLayout *decimalSpecificationLayout;
  15306. };
  15307. @ This widget has a number of differences from previous configuration widgets.
  15308. Perhaps most significantly there are controls which do not provide a text based
  15309. signal on state change. We also set certain controls as disabled when the
  15310. provided values are not relevant to operations such as when switching between
  15311. fixed decimal position and looking up decimal position from the device. Aside
  15312. from these details the widget operates according to the same principles as the
  15313. other widgets already seen.
  15314. @<ModbusRtuDeviceConfWidget implementation@>=
  15315. ModbusRtuDeviceConfWidget::ModbusRtuDeviceConfWidget(DeviceTreeModel *model,
  15316. const QModelIndex &index)
  15317. : BasicDeviceConfigurationWidget(model, index),
  15318. unitSpecificationLayout(new QStackedLayout),
  15319. decimalSpecificationLayout(new QStackedLayout)
  15320. {
  15321. QVBoxLayout *layout = new QVBoxLayout;
  15322. QToolButton *addChannelButton = new QToolButton;
  15323. addChannelButton->setText(tr("Add Channel"));
  15324. NodeInserter *addTemperaturePV = new NodeInserter("Temperature Process Value",
  15325. "Temperature Process Value",
  15326. "modbustemperaturepv");
  15327. NodeInserter *addTemperatureSV = new NodeInserter("Temperature Set Value",
  15328. "Temperature Set Value",
  15329. "modbustemperaturesv");
  15330. connect(addTemperaturePV, SIGNAL(triggered(QString, QString)),
  15331. this, SLOT(insertChildNode(QString, QString)));
  15332. connect(addTemperatureSV, SIGNAL(triggered(QString, QString)),
  15333. this, SLOT(insertChildNode(QString, QString)));
  15334. QMenu *channelMenu = new QMenu;
  15335. channelMenu->addAction(addTemperaturePV);
  15336. channelMenu->addAction(addTemperatureSV);
  15337. addChannelButton->setMenu(channelMenu);
  15338. addChannelButton->setPopupMode(QToolButton::InstantPopup);
  15339. layout->addWidget(addChannelButton);
  15340. QHBoxLayout *stationLayout = new QHBoxLayout;
  15341. QLabel *stationLabel = new QLabel(tr("Station:"));
  15342. QSpinBox *stationNumber = new QSpinBox;
  15343. stationNumber->setMinimum(0);
  15344. stationNumber->setMaximum(255);
  15345. stationLayout->addWidget(stationLabel);
  15346. stationLayout->addWidget(stationNumber);
  15347. layout->addLayout(stationLayout);
  15348. QCheckBox *fixedUnit = new QCheckBox(tr("Fixed Temperature Unit"));
  15349. layout->addWidget(fixedUnit);
  15350. QWidget *fixedUnitPlaceholder = new QWidget(this);
  15351. QHBoxLayout *fixedUnitLayout = new QHBoxLayout;
  15352. QLabel *fixedUnitLabel = new QLabel(tr("Temperature Unit:"));
  15353. QComboBox *fixedUnitSelector = new QComboBox;
  15354. fixedUnitSelector->addItem("Fahrenheit");
  15355. fixedUnitSelector->addItem("Celsius");
  15356. fixedUnitLayout->addWidget(fixedUnitLabel);
  15357. fixedUnitLayout->addWidget(fixedUnitSelector);
  15358. fixedUnitPlaceholder->setLayout(fixedUnitLayout);
  15359. unitSpecificationLayout->addWidget(fixedUnitPlaceholder);
  15360. QWidget *queriedUnitPlaceholder = new QWidget(this);
  15361. QFormLayout *queriedUnitLayout = new QFormLayout;
  15362. ShortHexSpinBox *unitAddress = new ShortHexSpinBox;
  15363. queriedUnitLayout->addRow(tr("Function 0x03 Unit Address:"), unitAddress);
  15364. QSpinBox *valueF = new QSpinBox;
  15365. valueF->setMinimum(0);
  15366. valueF->setMaximum(65535);
  15367. queriedUnitLayout->addRow(tr("Value for Fahrenheit"), valueF);
  15368. QSpinBox *valueC = new QSpinBox;
  15369. valueC->setMinimum(0);
  15370. valueC->setMaximum(65535);
  15371. queriedUnitLayout->addRow(tr("Value for Celsius"), valueC);
  15372. queriedUnitPlaceholder->setLayout(queriedUnitLayout);
  15373. unitSpecificationLayout->addWidget(queriedUnitPlaceholder);
  15374. layout->addLayout(unitSpecificationLayout);
  15375. QCheckBox *fixedPrecision = new QCheckBox(tr("Fixed Precision"));
  15376. layout->addWidget(fixedPrecision);
  15377. QWidget *fixedPrecisionPlaceholder = new QWidget(this);
  15378. QFormLayout *fixedPrecisionLayout = new QFormLayout;
  15379. QSpinBox *fixedPrecisionValue = new QSpinBox;
  15380. fixedPrecisionValue->setMinimum(0);
  15381. fixedPrecisionValue->setMaximum(9);
  15382. fixedPrecisionLayout->addRow("Places after the decimal point:",
  15383. fixedPrecisionValue);
  15384. fixedPrecisionPlaceholder->setLayout(fixedPrecisionLayout);
  15385. decimalSpecificationLayout->addWidget(fixedPrecisionPlaceholder);
  15386. QWidget *queriedPrecisionPlaceholder = new QWidget(this);
  15387. QFormLayout *queriedPrecisionLayout = new QFormLayout;
  15388. ShortHexSpinBox *precisionAddress = new ShortHexSpinBox;
  15389. queriedPrecisionLayout->addRow("Function 0x03 Decimal Position Address:",
  15390. precisionAddress);
  15391. queriedPrecisionPlaceholder->setLayout(queriedPrecisionLayout);
  15392. decimalSpecificationLayout->addWidget(queriedPrecisionPlaceholder);
  15393. layout->addLayout(decimalSpecificationLayout);
  15394. @<Get device configuration data for current node@>@;
  15395. for(int i = 0; i < configData.size(); i++)
  15396. {
  15397. node = configData.at(i).toElement();
  15398. if(node.attribute("name") == "station")
  15399. {
  15400. stationNumber->setValue(node.attribute("value").toInt());
  15401. }
  15402. else if(node.attribute("name") == "fixedunit")
  15403. {
  15404. if(node.attribute("value") == "true")
  15405. {
  15406. fixedUnit->setCheckState(Qt::Checked);
  15407. }
  15408. else if(node.attribute("value") == "false")
  15409. {
  15410. fixedUnit->setCheckState(Qt::Unchecked);
  15411. }
  15412. }
  15413. else if(node.attribute("name") == "fixedprecision")
  15414. {
  15415. fixedPrecisionValue->setValue(node.attribute("value").toInt());
  15416. }
  15417. else if(node.attribute("name") == "unit")
  15418. {
  15419. fixedUnitSelector->setCurrentIndex(fixedUnitSelector->findText(node.attribute("value")));
  15420. }
  15421. else if(node.attribute("name") == "unitaddress")
  15422. {
  15423. unitAddress->setValue(node.attribute("value").toInt());
  15424. }
  15425. else if(node.attribute("name") == "fvalue")
  15426. {
  15427. valueF->setValue(node.attribute("value").toInt());
  15428. }
  15429. else if(node.attribute("name") == "cvalue")
  15430. {
  15431. valueC->setValue(node.attribute("value").toInt());
  15432. }
  15433. else if(node.attribute("name") == "precisionaddress")
  15434. {
  15435. precisionAddress->setValue(node.attribute("value").toInt());
  15436. }
  15437. else if(node.attribute("name") == "precision")
  15438. {
  15439. fixedPrecisionValue->setValue(node.attribute("value").toInt());
  15440. }
  15441. }
  15442. updateStationNumber(stationNumber->value());
  15443. updateFixedUnit(fixedUnit->isChecked());
  15444. updateFixedDecimal(fixedPrecision->isChecked());
  15445. updateUnit(fixedUnitSelector->currentText());
  15446. updateUnitAddress(unitAddress->value());
  15447. updateValueF(valueF->value());
  15448. updateValueC(valueC->value());
  15449. updatePrecisionAddress(precisionAddress->value());
  15450. updatePrecisionValue(fixedPrecisionValue->value());
  15451. connect(stationNumber, SIGNAL(valueChanged(int)),
  15452. this, SLOT(updateStationNumber(int)));
  15453. connect(fixedUnitSelector, SIGNAL(currentIndexChanged(QString)),
  15454. this, SLOT(updateUnit(QString)));
  15455. connect(unitAddress, SIGNAL(valueChanged(int)),
  15456. this, SLOT(updateUnitAddress(int)));
  15457. connect(valueF, SIGNAL(valueChanged(int)),
  15458. this, SLOT(updateValueF(int)));
  15459. connect(valueC, SIGNAL(valueChanged(int)),
  15460. this, SLOT(updateValueC(int)));
  15461. connect(fixedUnit, SIGNAL(toggled(bool)),
  15462. this, SLOT(updateFixedUnit(bool)));
  15463. connect(fixedPrecision, SIGNAL(toggled(bool)),
  15464. this, SLOT(updateFixedDecimal(bool)));
  15465. connect(fixedPrecisionValue, SIGNAL(valueChanged(int)),
  15466. this, SLOT(updatePrecisionValue(int)));
  15467. connect(precisionAddress, SIGNAL(valueChanged(int)),
  15468. this, SLOT(updatePrecisionAddress(int)));
  15469. setLayout(layout);
  15470. }
  15471. void ModbusRtuDeviceConfWidget::updateStationNumber(int newStation)
  15472. {
  15473. updateAttribute("station", QString("%1").arg(newStation));
  15474. }
  15475. void ModbusRtuDeviceConfWidget::updateFixedUnit(bool newFixed)
  15476. {
  15477. if(newFixed)
  15478. {
  15479. unitSpecificationLayout->setCurrentIndex(0);
  15480. updateAttribute("fixedunit", "true");
  15481. }
  15482. else
  15483. {
  15484. unitSpecificationLayout->setCurrentIndex(1);
  15485. updateAttribute("fixedunit", "false");
  15486. }
  15487. }
  15488. void ModbusRtuDeviceConfWidget::updateFixedDecimal(bool newFixed)
  15489. {
  15490. if(newFixed)
  15491. {
  15492. decimalSpecificationLayout->setCurrentIndex(0);
  15493. updateAttribute("fixedprecision", "true");
  15494. }
  15495. else
  15496. {
  15497. decimalSpecificationLayout->setCurrentIndex(1);
  15498. updateAttribute("fixedprecision", "false");
  15499. }
  15500. }
  15501. void ModbusRtuDeviceConfWidget::updateUnit(const QString &newUnit)
  15502. {
  15503. updateAttribute("unit", newUnit);
  15504. }
  15505. void ModbusRtuDeviceConfWidget::updateUnitAddress(int newAddress)
  15506. {
  15507. updateAttribute("unitaddress", QString("%1").arg(newAddress));
  15508. }
  15509. void ModbusRtuDeviceConfWidget::updateValueF(int newValue)
  15510. {
  15511. updateAttribute("fvalue", QString("%1").arg(newValue));
  15512. }
  15513. void ModbusRtuDeviceConfWidget::updateValueC(int newValue)
  15514. {
  15515. updateAttribute("cvalue", QString("%1").arg(newValue));
  15516. }
  15517. void ModbusRtuDeviceConfWidget::updatePrecisionAddress(int newAddress)
  15518. {
  15519. updateAttribute("precisionaddress", QString("%1").arg(newAddress));
  15520. }
  15521. void ModbusRtuDeviceConfWidget::updatePrecisionValue(int newValue)
  15522. {
  15523. updateAttribute("precision", QString("%1").arg(newValue));
  15524. }
  15525. @ Initial Modbus RTU support is very limited and only considers temperature
  15526. process and set values. While in some cases it would be possible to cleverly
  15527. adapt this support to broader categories this is an area that must be extended
  15528. later to cover at least unitless control values and on/off status values. It
  15529. would be ideal to cover a broad range of useful properties. To read process
  15530. values we need to know the address that the current process value can be read
  15531. from.
  15532. @<Class declarations@>=
  15533. class ModbusRtuDeviceTPvConfWidget : public BasicDeviceConfigurationWidget
  15534. {
  15535. @[Q_OBJECT@]@/
  15536. public:@/
  15537. @[Q_INVOKABLE@]@, ModbusRtuDeviceTPvConfWidget(DeviceTreeModel *model,
  15538. const QModelIndex &index);
  15539. @[private slots@]:@/
  15540. void updateAddress(int newAddress);
  15541. };
  15542. @ This requires only a single field to store the address to query the current
  15543. process value.
  15544. @<ModbusRtuDeviceTPvConfWidget implementation@>=
  15545. ModbusRtuDeviceTPvConfWidget::ModbusRtuDeviceTPvConfWidget(DeviceTreeModel *model,
  15546. const QModelIndex &index)
  15547. : BasicDeviceConfigurationWidget(model, index)
  15548. {
  15549. QFormLayout *layout = new QFormLayout;
  15550. ShortHexSpinBox *address = new ShortHexSpinBox;
  15551. layout->addRow(tr("Function 0x04 Process Value Address"), address);
  15552. @<Get device configuration data for current node@>@;
  15553. for(int i = 0; i < configData.size(); i++)
  15554. {
  15555. node = configData.at(i).toElement();
  15556. if(node.attribute("name") == "address")
  15557. {
  15558. address->setValue(node.attribute("value").toInt());
  15559. break;
  15560. }
  15561. }
  15562. updateAddress(address->value());
  15563. connect(address, SIGNAL(valueChanged(int)), this, SLOT(updateAddress(int)));
  15564. setLayout(layout);
  15565. }
  15566. void ModbusRtuDeviceTPvConfWidget::updateAddress(int newAddress)
  15567. {
  15568. updateAttribute("address", QString("%1").arg(newAddress));
  15569. }
  15570. @ Set values are slightly more complicated as we may want either a fixed range
  15571. or the ability to query the device for its current allowed range, but nothing
  15572. is here that hasn'@q'@>t been seen elsewhere.
  15573. @<Class declarations@>=
  15574. class ModbusRtuDeviceTSvConfWidget : public BasicDeviceConfigurationWidget@/
  15575. {@/
  15576. @[Q_OBJECT@]@;
  15577. public:@/
  15578. Q_INVOKABLE@, ModbusRtuDeviceTSvConfWidget(DeviceTreeModel *model,
  15579. const QModelIndex &index);
  15580. @[private slots@]:@/
  15581. void updateReadAddress(int newAddress);
  15582. void updateWriteAddress(int newAddress);
  15583. void updateFixedRange(bool fixed);
  15584. void updateLower(const QString &lower);
  15585. void updateUpper(const QString &upper);
  15586. void updateLowerAddress(int newAddress);
  15587. void updateUpperAddress(int newAddress);@/
  15588. private:@/
  15589. QStackedLayout *boundsLayout;
  15590. };
  15591. @ Upper and lower bounds when operating on a fixed range are still subject to
  15592. decimal position rules in the parent node. It may be a good idea to enforce
  15593. this, however at present the person configuring the system is trusted to know
  15594. what they are doing.
  15595. @<ModbusRtuDeviceTSvConfWidget implementation@>=
  15596. ModbusRtuDeviceTSvConfWidget::ModbusRtuDeviceTSvConfWidget(DeviceTreeModel *model,
  15597. const QModelIndex &index)
  15598. : BasicDeviceConfigurationWidget(model, index), boundsLayout(new QStackedLayout)
  15599. {
  15600. QVBoxLayout *layout = new QVBoxLayout;
  15601. QFormLayout *addressLayout = new QFormLayout;
  15602. ShortHexSpinBox *readAddress = new ShortHexSpinBox;
  15603. ShortHexSpinBox *writeAddress = new ShortHexSpinBox;
  15604. addressLayout->addRow(tr("Function 0x04 Read Set Value Address:"), readAddress);
  15605. addressLayout->addRow(tr("Function 0x06 Write Set Value Address:"), writeAddress);
  15606. layout->addLayout(addressLayout);
  15607. QCheckBox *fixedRange = new QCheckBox(tr("Fixed Set Value Range"));
  15608. layout->addWidget(fixedRange);
  15609. QWidget *queriedRangePlaceholder = new QWidget(this);
  15610. QFormLayout *queriedRangeLayout = new QFormLayout;
  15611. ShortHexSpinBox *lowerAddress = new ShortHexSpinBox;
  15612. ShortHexSpinBox *upperAddress = new ShortHexSpinBox;
  15613. queriedRangeLayout->addRow(tr("Function 0x03 Minimum Set Value Address"),
  15614. lowerAddress);
  15615. queriedRangeLayout->addRow(tr("Function 0x03 Maximum Set Value Address"),
  15616. upperAddress);
  15617. queriedRangePlaceholder->setLayout(queriedRangeLayout);
  15618. boundsLayout->addWidget(queriedRangePlaceholder);
  15619. QWidget *fixedRangePlaceholder = new QWidget(this);
  15620. QFormLayout *fixedRangeLayout = new QFormLayout;
  15621. QLineEdit *fixedLower = new QLineEdit;
  15622. QLineEdit *fixedUpper = new QLineEdit;
  15623. fixedRangeLayout->addRow(tr("Minimum Set Value:"), fixedLower);
  15624. fixedRangeLayout->addRow(tr("Maximum Set Value:"), fixedUpper);
  15625. fixedRangePlaceholder->setLayout(fixedRangeLayout);
  15626. boundsLayout->addWidget(fixedRangePlaceholder);
  15627. layout->addLayout(boundsLayout);
  15628. @<Get device configuration data for current node@>@;
  15629. for(int i = 0; i < configData.size(); i++)
  15630. {
  15631. node = configData.at(i).toElement();
  15632. if(node.attribute("name") == "readaddress")
  15633. {
  15634. readAddress->setValue(node.attribute("value").toInt());
  15635. }
  15636. else if(node.attribute("name") == "writeaddress")
  15637. {
  15638. writeAddress->setValue(node.attribute("value").toInt());
  15639. }
  15640. else if(node.attribute("name") == "fixedrange")
  15641. {
  15642. if(node.attribute("value") == "true")
  15643. {
  15644. fixedRange->setCheckState(Qt::Checked);
  15645. }
  15646. else if(node.attribute("value") == "false")
  15647. {
  15648. fixedRange->setCheckState(Qt::Unchecked);
  15649. }
  15650. }
  15651. else if(node.attribute("name") == "fixedlower")
  15652. {
  15653. fixedLower->setText(node.attribute("value"));
  15654. }
  15655. else if(node.attribute("name") == "fixedupper")
  15656. {
  15657. fixedUpper->setText(node.attribute("value"));
  15658. }
  15659. else if(node.attribute("name") == "loweraddress")
  15660. {
  15661. lowerAddress->setValue(node.attribute("value").toInt());
  15662. }
  15663. else if(node.attribute("name") == "upperaddress")
  15664. {
  15665. upperAddress->setValue(node.attribute("value").toInt());
  15666. }
  15667. }
  15668. updateReadAddress(readAddress->value());
  15669. updateWriteAddress(writeAddress->value());
  15670. updateFixedRange(fixedRange->isChecked());
  15671. updateLower(fixedLower->text());
  15672. updateUpper(fixedUpper->text());
  15673. updateLowerAddress(lowerAddress->value());
  15674. updateUpperAddress(upperAddress->value());
  15675. connect(readAddress, SIGNAL(valueChanged(int)),
  15676. this, SLOT(updateReadAddress(int)));
  15677. connect(writeAddress, SIGNAL(valueChanged(int)),
  15678. this, SLOT(updateWriteAddress(int)));
  15679. connect(fixedRange, SIGNAL(toggled(bool)), this, SLOT(updateFixedRange(bool)));
  15680. connect(fixedLower, SIGNAL(textChanged(QString)),
  15681. this, SLOT(updateLower(QString)));
  15682. connect(fixedUpper, SIGNAL(textChanged(QString)),
  15683. this, SLOT(updateUpper(QString)));
  15684. connect(lowerAddress, SIGNAL(valueChanged(int)),
  15685. this, SLOT(updateLowerAddress(int)));
  15686. connect(upperAddress, SIGNAL(valueChanged(int)),
  15687. this, SLOT(updateUpperAddress(int)));
  15688. setLayout(layout);
  15689. }
  15690. void ModbusRtuDeviceTSvConfWidget::updateReadAddress(int newAddress)
  15691. {
  15692. updateAttribute("readaddress", QString("%1").arg(newAddress));
  15693. }
  15694. void ModbusRtuDeviceTSvConfWidget::updateWriteAddress(int newAddress)
  15695. {
  15696. updateAttribute("writeaddress", QString("%1").arg(newAddress));
  15697. }
  15698. void ModbusRtuDeviceTSvConfWidget::updateFixedRange(bool fixed)
  15699. {
  15700. if(fixed)
  15701. {
  15702. updateAttribute("fixedrange", "true");
  15703. boundsLayout->setCurrentIndex(1);
  15704. }
  15705. else
  15706. {
  15707. updateAttribute("fixedrange", "false");
  15708. boundsLayout->setCurrentIndex(0);
  15709. }
  15710. }
  15711. void ModbusRtuDeviceTSvConfWidget::updateLower(const QString &lower)
  15712. {
  15713. updateAttribute("fixedlower", lower);
  15714. }
  15715. void ModbusRtuDeviceTSvConfWidget::updateUpper(const QString &upper)
  15716. {
  15717. updateAttribute("fixedupper", upper);
  15718. }
  15719. void ModbusRtuDeviceTSvConfWidget::updateLowerAddress(int newAddress)
  15720. {
  15721. updateAttribute("loweraddress", QString("%1").arg(newAddress));
  15722. }
  15723. void ModbusRtuDeviceTSvConfWidget::updateUpperAddress(int newAddress)
  15724. {
  15725. updateAttribute("upperaddress", QString("%1").arg(newAddress));
  15726. }
  15727. @ The configuration widgets need to be registered.
  15728. @<Register device configuration widgets@>=
  15729. app.registerDeviceConfigurationWidget("modbusrtuport", ModbusRtuPortConfWidget::staticMetaObject);
  15730. app.registerDeviceConfigurationWidget("modbusrtudevice", ModbusRtuDeviceConfWidget::staticMetaObject);
  15731. app.registerDeviceConfigurationWidget("modbustemperaturepv", ModbusRtuDeviceTPvConfWidget::staticMetaObject);
  15732. app.registerDeviceConfigurationWidget("modbustemperaturesv", ModbusRtuDeviceTSvConfWidget::staticMetaObject);
  15733. @ A |NodeInserter| for the driver configuration widget is also needed. Note
  15734. that this is temporarily disabled. These configuration widgets will become
  15735. useful when I rearchitect the Modbus RTU support in a future release.
  15736. @<Register top level device configuration nodes@>=
  15737. #if 0
  15738. inserter = new NodeInserter(tr("Modbus RTU Port"), tr("Modbus RTU Port"), "modbusrtuport", NULL);
  15739. topLevelNodeInserters.append(inserter);
  15740. #endif
  15741. @** Configuration of Annotation Controls.
  15742. \noindent Aside from the details of hardware devices, the logging view must
  15743. also be able to set up log annotation controls. A few different control types
  15744. are offered. These include simple push buttons which insert a fixed annotation
  15745. when activated, push buttons which insert a value that includes a number which
  15746. is incremented every time the button is pressed, free text entry fields, and
  15747. numeric entry fields.
  15748. The basic push button control should allow configuration of both the button
  15749. text and the annotation text.
  15750. @<Class declarations@>=
  15751. class AnnotationButtonConfWidget : public BasicDeviceConfigurationWidget
  15752. {
  15753. @[Q_OBJECT@]@;
  15754. public:@/
  15755. @[Q_INVOKABLE@]@, AnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  15756. @[private slots@]:@/
  15757. void updateButtonText(const QString &text);
  15758. void updateAnnotationText(const QString &text);
  15759. };
  15760. @ The constructor sets up the controls for editing this data.
  15761. @<AnnotationButtonConfWidget implementation@>=
  15762. AnnotationButtonConfWidget::AnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  15763. : BasicDeviceConfigurationWidget(model, index)
  15764. {
  15765. QFormLayout *layout = new QFormLayout;
  15766. QLineEdit *buttonTextEdit = new QLineEdit;
  15767. QLineEdit *annotationTextEdit = new QLineEdit;
  15768. layout->addRow(tr("Button Text:"), buttonTextEdit);
  15769. layout->addRow(tr("Annotation Text:"), annotationTextEdit);
  15770. @<Get device configuration data for current node@>@;
  15771. for(int i = 0; i < configData.size(); i++)
  15772. {
  15773. node = configData.at(i).toElement();
  15774. if(node.attribute("name") == "buttontext")
  15775. {
  15776. buttonTextEdit->setText(node.attribute("value"));
  15777. }
  15778. else if(node.attribute("name") == "annotationtext")
  15779. {
  15780. annotationTextEdit->setText(node.attribute("value"));
  15781. }
  15782. }
  15783. updateButtonText(buttonTextEdit->text());
  15784. updateAnnotationText(annotationTextEdit->text());
  15785. connect(buttonTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateButtonText(QString)));
  15786. connect(annotationTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateAnnotationText(QString)));
  15787. setLayout(layout);
  15788. }
  15789. @ The slots are implemented trivially.
  15790. @<AnnotationButtonConfWidget implementation@>=
  15791. void AnnotationButtonConfWidget::updateButtonText(const QString &text)
  15792. {
  15793. updateAttribute("buttontext", text);
  15794. }
  15795. void AnnotationButtonConfWidget::updateAnnotationText(const QString &text)
  15796. {
  15797. updateAttribute("annotationtext", text);
  15798. }
  15799. @ The control must be registered.
  15800. @<Register device configuration widgets@>=
  15801. app.registerDeviceConfigurationWidget("annotationbutton", AnnotationButtonConfWidget::staticMetaObject);
  15802. @ Closely related to the previous control is one which provides parameterized
  15803. text. Technically this is not needed as both this and the previous
  15804. configuration control map to the same widget in the logging view and
  15805. parameterized annotation text can be used with either. The reason for
  15806. separating these is to indicate that it should be possible to change the text
  15807. and reset the number without altering the default configuration or requiring a
  15808. reinitialization of the logging view.
  15809. @<Class declarations@>=
  15810. class ReconfigurableAnnotationButtonConfWidget : public BasicDeviceConfigurationWidget@/
  15811. {@/
  15812. @[Q_OBJECT@]@;
  15813. public:@/
  15814. Q_INVOKABLE ReconfigurableAnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  15815. @[private slots@]:@/
  15816. void updateButtonText(const QString &text);
  15817. void updateAnnotationText(const QString &text);
  15818. };
  15819. @ The key difference in implementation is the addition of some documentation on
  15820. how to specify a numeric placeholder in the annotation text.
  15821. @<AnnotationButtonConfWidget implementation@>=
  15822. ReconfigurableAnnotationButtonConfWidget::ReconfigurableAnnotationButtonConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  15823. : BasicDeviceConfigurationWidget(model, index)
  15824. {
  15825. QFormLayout *layout = new QFormLayout;
  15826. QLineEdit *buttonTextEdit = new QLineEdit;
  15827. QLineEdit *annotationTextEdit = new QLineEdit;
  15828. layout->addRow(tr("Button Text:"), buttonTextEdit);
  15829. layout->addRow(tr("Annotation Text:"), annotationTextEdit);
  15830. @<Get device configuration data for current node@>@;
  15831. for(int i = 0; i < configData.size(); i++)
  15832. {
  15833. node = configData.at(i).toElement();
  15834. if(node.attribute("name") == "buttontext")
  15835. {
  15836. buttonTextEdit->setText(node.attribute("value"));
  15837. }
  15838. else if(node.attribute("name") == "annotationtext")
  15839. {
  15840. annotationTextEdit->setText(node.attribute("value"));
  15841. }
  15842. }
  15843. updateButtonText(buttonTextEdit->text());
  15844. updateAnnotationText(annotationTextEdit->text());
  15845. connect(buttonTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateButtonText(QString)));
  15846. connect(annotationTextEdit, SIGNAL(textEdited(QString)), this, SLOT(updateAnnotationText(QString)));
  15847. QTextEdit *documentation = new QTextEdit;
  15848. documentation->setHtml(tr("If the <b>Annotation Text</b> contains <tt>%1</tt>, this will be replaced in the annotation with a number that increments each time the button is pressed."));
  15849. documentation->setReadOnly(true);
  15850. layout->addRow("", documentation);
  15851. setLayout(layout);
  15852. }
  15853. void ReconfigurableAnnotationButtonConfWidget::updateButtonText(const QString &text)
  15854. {
  15855. updateAttribute("buttontext", text);
  15856. }
  15857. void ReconfigurableAnnotationButtonConfWidget::updateAnnotationText(const QString &text)
  15858. {
  15859. updateAttribute("annotationtext", text);
  15860. }
  15861. @ The control must be registered as usual.
  15862. @<Register device configuration widgets@>=
  15863. app.registerDeviceConfigurationWidget("reconfigurablebutton", ReconfigurableAnnotationButtonConfWidget::staticMetaObject);
  15864. @ While it is generally better to have all measurements logged automatically,
  15865. many roasters would like to keep track of infrequently altered control
  15866. variables which have not been set up for automated logging. A reading from the
  15867. manometer after a fuel adjustment, for example, is frequently not available by
  15868. automated means. In cases such as this, providing for numeric annotation entry
  15869. may be desired. The |AnnotationSpinBox| provides for this. There are a few
  15870. details that are important in this. First is a label to better indicate to the
  15871. operator what values in this control represent. The range of allowed values and
  15872. the number of decimal places is important. This control also allows the
  15873. specification of text to precede and/or follow the numeric value and this must
  15874. be configurable.
  15875. @<Class declarations@>=
  15876. class NoteSpinConfWidget : public BasicDeviceConfigurationWidget
  15877. {
  15878. @[Q_OBJECT@]@;
  15879. public:@/
  15880. @[Q_INVOKABLE@]@, NoteSpinConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  15881. @[private slots@]:@/
  15882. void updateLabel(const QString &text);
  15883. void updateMinimum(const QString &minimum);
  15884. void updateMaximum(const QString &maximum);
  15885. void updatePrecision(int precision);
  15886. void updatePretext(const QString &text);
  15887. void updatePosttext(const QString &text);
  15888. };
  15889. @ There is nothing new in the implementation of note.
  15890. @<NoteSpinConfWidget implementation@>=
  15891. NoteSpinConfWidget::NoteSpinConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  15892. : BasicDeviceConfigurationWidget(model, index)
  15893. {
  15894. QFormLayout *layout = new QFormLayout;
  15895. QLineEdit *labelEdit = new QLineEdit;
  15896. layout->addRow(tr("Control Label: "), labelEdit);
  15897. QLineEdit *minimumEdit = new QLineEdit;
  15898. layout->addRow(tr("Minimum Value: "), minimumEdit);
  15899. QLineEdit *maximumEdit = new QLineEdit;
  15900. layout->addRow(tr("Maximum Value: "), maximumEdit);
  15901. QSpinBox *precisionEdit = new QSpinBox;
  15902. precisionEdit->setMinimum(0);
  15903. precisionEdit->setMaximum(9);
  15904. layout->addRow(tr("Precision"), precisionEdit);
  15905. QLineEdit *pretext = new QLineEdit;
  15906. layout->addRow(tr("Prefix text"), pretext);
  15907. QLineEdit *posttext = new QLineEdit;
  15908. layout->addRow(tr("Suffix text"), posttext);
  15909. @<Get device configuration data for current node@>@;
  15910. for(int i = 0; i < configData.size(); i++)
  15911. {
  15912. node = configData.at(i).toElement();
  15913. if(node.attribute("name") == "label")
  15914. {
  15915. labelEdit->setText(node.attribute("value"));
  15916. }
  15917. else if(node.attribute("name") == "minimum")
  15918. {
  15919. minimumEdit->setText(node.attribute("value"));
  15920. }
  15921. else if(node.attribute("name") == "maximum")
  15922. {
  15923. maximumEdit->setText(node.attribute("value"));
  15924. }
  15925. else if(node.attribute("name") == "precision")
  15926. {
  15927. precisionEdit->setValue(node.attribute("value").toInt());
  15928. }
  15929. else if(node.attribute("name") == "pretext")
  15930. {
  15931. pretext->setText(node.attribute("value"));
  15932. }
  15933. else if(node.attribute("name") == "posttext")
  15934. {
  15935. posttext->setText(node.attribute("value"));
  15936. }
  15937. }
  15938. updateLabel(labelEdit->text());
  15939. updateMinimum(minimumEdit->text());
  15940. updateMaximum(maximumEdit->text());
  15941. updatePrecision(precisionEdit->value());
  15942. updatePretext(pretext->text());
  15943. updatePosttext(posttext->text());
  15944. connect(labelEdit, SIGNAL(textEdited(QString)), this, SLOT(updateLabel(QString)));
  15945. connect(minimumEdit, SIGNAL(textEdited(QString)), this, SLOT(updateMinimum(QString)));
  15946. connect(maximumEdit, SIGNAL(textEdited(QString)), this, SLOT(updateMaximum(QString)));
  15947. connect(precisionEdit, SIGNAL(valueChanged(int)), this, SLOT(updatePrecision(int)));
  15948. connect(pretext, SIGNAL(textEdited(QString)), this, SLOT(updatePretext(QString)));
  15949. connect(posttext, SIGNAL(textEdited(QString)), this, SLOT(updatePosttext(QString)));
  15950. setLayout(layout);
  15951. }
  15952. void NoteSpinConfWidget::updateLabel(const QString &text)
  15953. {
  15954. updateAttribute("label", text);
  15955. }
  15956. void NoteSpinConfWidget::updateMinimum(const QString &minimum)
  15957. {
  15958. updateAttribute("minimum", minimum);
  15959. }
  15960. void NoteSpinConfWidget::updateMaximum(const QString &maximum)
  15961. {
  15962. updateAttribute("maximum", maximum);
  15963. }
  15964. void NoteSpinConfWidget::updatePrecision(int precision)
  15965. {
  15966. updateAttribute("precision", QString("%1").arg(precision));
  15967. }
  15968. void NoteSpinConfWidget::updatePretext(const QString &text)
  15969. {
  15970. updateAttribute("pretext", text);
  15971. }
  15972. void NoteSpinConfWidget::updatePosttext(const QString &text)
  15973. {
  15974. updateAttribute("posttext", text);
  15975. }
  15976. @ Configuration widget registration is as usual.
  15977. @<Register device configuration widgets@>=
  15978. app.registerDeviceConfigurationWidget("annotationspinbox", NoteSpinConfWidget::staticMetaObject);
  15979. @i freeannotation.w
  15980. @i settings.w
  15981. @** Communicating with a Device through Modbus RTU.
  15982. \noindent The classes described here need to be further generalized to support
  15983. communications with multiple devices on the same port. The interface is based
  15984. on the |DAQ| class but extended to support additional functionality.
  15985. @<Class declarations@>=
  15986. class ModbusRTUDevice : public QObject
  15987. {
  15988. @[Q_OBJECT@]@;
  15989. public:@/
  15990. ModbusRTUDevice(DeviceTreeModel *model, const QModelIndex &index);
  15991. ~ModbusRTUDevice();
  15992. void queueMessage(QByteArray request, QObject *object, const char *callback);
  15993. @[Q_INVOKABLE@,@, double@]@, SVLower();@t\2\2@>@/
  15994. @[Q_INVOKABLE@,@, double@]@, SVUpper();@t\2\2@>@/
  15995. @[Q_INVOKABLE@,@, int@]@, decimals();@t\2\2@>@/
  15996. QList<Channel*> channels;@/
  15997. @[public slots@]:@/
  15998. void outputSV(double sv);@/
  15999. signals:@/
  16000. void SVLowerChanged(double);
  16001. void SVUpperChanged(double);
  16002. void SVDecimalChanged(int);
  16003. void queueEmpty();@/
  16004. @[private slots@]:@/
  16005. void dataAvailable();
  16006. void sendNextMessage();
  16007. void decimalResponse(QByteArray response);
  16008. void unitResponse(QByteArray response);
  16009. void svlResponse(QByteArray response);
  16010. void svuResponse(QByteArray response);
  16011. void requestMeasurement();
  16012. void mResponse(QByteArray response);
  16013. void ignore(QByteArray response);
  16014. void timeout();@/
  16015. private:@/
  16016. QextSerialPort *port;
  16017. QByteArray responseBuffer;
  16018. QList<QByteArray> messageQueue;
  16019. QList<QObject *> retObjQueue;
  16020. QList<char *> callbackQueue;
  16021. quint16 calculateCRC(QByteArray data);
  16022. QTimer *messageDelayTimer;
  16023. QTimer *commTimeout;
  16024. int delayTime;
  16025. char station;
  16026. int decimalPosition;
  16027. int valueF;
  16028. int valueC;
  16029. bool unitIsF;
  16030. double outputSVLower;
  16031. double outputSVUpper;
  16032. QByteArray outputSVStub;
  16033. QByteArray pvStub;
  16034. QByteArray svStub;
  16035. QByteArray mStub;
  16036. quint16 pvaddress;
  16037. quint16 svaddress;
  16038. bool svenabled;
  16039. bool readingsv;
  16040. double savedpv;
  16041. bool waiting;
  16042. };
  16043. @ The constructor reads its configuration from the configuration sub-tree of the
  16044. port node. This was adapted from a prototype implementation which used
  16045. |QSettings| to store this data. Note that this will only process the first
  16046. device specified on the port, the first process value on that device, and the
  16047. first set value on that device. A much more versatile architecture has been
  16048. planned for a future release which allows multiple devices per bus and
  16049. arbitrarily many monitored addresses per device. Communications are initiated
  16050. immediately upon construction.
  16051. @<ModbusRTUDevice implementation@>=
  16052. ModbusRTUDevice::ModbusRTUDevice(DeviceTreeModel *model,@| const QModelIndex &index)
  16053. : QObject(NULL), messageDelayTimer(new QTimer), commTimeout(new QTimer), unitIsF(@[true@]), readingsv(@[false@]),
  16054. waiting(@[false@])@/
  16055. {@/
  16056. QDomElement portReferenceElement = model->referenceElement(model->data(index,
  16057. Qt::UserRole).toString());
  16058. QDomNodeList portConfigData = portReferenceElement.elementsByTagName("attribute");
  16059. QDomElement node;
  16060. QVariantMap attributes;
  16061. for(int i = 0; i < portConfigData.size(); i++)
  16062. {
  16063. node = portConfigData.at(i).toElement();
  16064. attributes.insert(node.attribute("name"), node.attribute("value"));
  16065. }
  16066. port = new QextSerialPort(attributes.value("port").toString(),
  16067. QextSerialPort::EventDriven);
  16068. int baudRate = attributes.value("baud").toInt();
  16069. port->setBaudRate((BaudRateType)baudRate);
  16070. double temp = ((double)(1) / (double)(baudRate)) * 48;
  16071. delayTime = (int)(temp * 3000);
  16072. messageDelayTimer->setSingleShot(true);
  16073. commTimeout->setSingleShot(true);
  16074. connect(messageDelayTimer, SIGNAL(timeout()), this, SLOT(sendNextMessage()));
  16075. connect(commTimeout, SIGNAL(timeout()), this, SLOT(timeout()));
  16076. port->setDataBits(DATA_8);
  16077. port->setParity((ParityType)attributes.value("parity").toInt());
  16078. port->setStopBits((StopBitsType)attributes.value("stop").toInt());
  16079. port->setFlowControl((FlowType)attributes.value("flow").toInt());
  16080. connect(port, SIGNAL(readyRead()), this, SLOT(dataAvailable()));
  16081. port->open(QIODevice::ReadWrite);
  16082. station = (char)attributes.value("station").toInt();
  16083. if(attributes.value("decimalQuery") == "true")
  16084. {
  16085. decimalPosition = 0;
  16086. QByteArray message;
  16087. message.append(station);
  16088. message.append((char)0x03);
  16089. quint16 address = (quint16)attributes.value("decimalAddress").toInt();
  16090. char *addressBytes = (char*)&address;
  16091. message.append(addressBytes[1]);
  16092. message.append(addressBytes[0]);
  16093. message.append((char)0x00);
  16094. message.append((char)0x01);
  16095. queueMessage(message, this, "decimalResponse(QByteArray)");
  16096. }
  16097. else
  16098. {
  16099. decimalPosition = attributes.value("decimalPosition").toInt();
  16100. }
  16101. valueF = attributes.value("valueF").toInt();
  16102. valueC = attributes.value("valueC").toInt();
  16103. if(attributes.value("unitQuery") == "true")
  16104. {
  16105. QByteArray message;
  16106. message.append(station);
  16107. message.append((char)0x03);
  16108. quint16 address = (quint16)attributes.value("unitAddress").toInt();
  16109. char *addressBytes = (char*)&address;
  16110. message.append(addressBytes[1]);
  16111. message.append(addressBytes[0]);
  16112. message.append((char)0x00);
  16113. message.append((char)0x01);
  16114. queueMessage(message, this, "unitResponse(QByteArray)");
  16115. }
  16116. else
  16117. {
  16118. if(attributes.value("fixedUnit") == "Celsius")
  16119. {
  16120. unitIsF = @[false@];
  16121. }
  16122. }
  16123. if(attributes.value("sVWritable") == "true")
  16124. {
  16125. if(attributes.value("deviceLimit") == "true")
  16126. {
  16127. QByteArray lmessage;
  16128. lmessage.append(station);
  16129. lmessage.append((char)0x03);
  16130. quint16 laddress = (quint16)attributes.value("sVLowerAddr").toInt();
  16131. char *addressBytes = (char*)&laddress;
  16132. lmessage.append(addressBytes[1]);
  16133. lmessage.append(addressBytes[0]);
  16134. lmessage.append((char)0x00);
  16135. lmessage.append((char)0x01);
  16136. queueMessage(lmessage, this, "svlResponse(QByteArray)");
  16137. QByteArray umessage;
  16138. umessage.append(station);
  16139. umessage.append((char)0x03);
  16140. quint16 uaddress = (quint16)attributes.value("sVUpperAddr").toInt();
  16141. addressBytes = (char*)&uaddress;
  16142. umessage.append(addressBytes[1]);
  16143. umessage.append(addressBytes[0]);
  16144. umessage.append((char)0x00);
  16145. umessage.append((char)0x01);
  16146. queueMessage(umessage, this, "svuResponse(QByteArray)");
  16147. }
  16148. else
  16149. {
  16150. outputSVLower = attributes.value("sVLower").toDouble();
  16151. outputSVUpper = attributes.value("sVUpper").toDouble();
  16152. }
  16153. outputSVStub.append(station);
  16154. outputSVStub.append((char)0x06);
  16155. quint16 address = (quint16)attributes.value("sVOutputAddr").toInt();
  16156. char *addressBytes = (char*)&address;
  16157. outputSVStub.append(addressBytes[1]);
  16158. outputSVStub.append(addressBytes[0]);
  16159. }
  16160. Channel *pv = new Channel;
  16161. channels.append(pv);
  16162. pvStub.append(station);
  16163. pvStub.append((char)0x04);
  16164. pvaddress = (quint16)attributes.value("pVAddress").toInt();
  16165. char *pvac = (char*)&pvaddress;
  16166. pvStub.append(pvac[1]);
  16167. pvStub.append(pvac[0]);
  16168. pvStub.append((char)0x00);
  16169. pvStub.append((char)0x01);
  16170. svenabled = attributes.value("sVEnabled").toBool();
  16171. if(svenabled)
  16172. {
  16173. Channel *sv = new Channel;
  16174. channels.append(sv);
  16175. svStub.append(station);
  16176. svStub.append((char)0x04);
  16177. svaddress = (quint16)attributes.value("sVReadAddress").toInt();
  16178. char *svac = (char*)&svaddress;
  16179. svStub.append(svac[1]);
  16180. svStub.append(svac[0]);
  16181. svStub.append((char)0x00);
  16182. svStub.append((char)0x01);
  16183. if(svaddress - pvaddress == 1)
  16184. {
  16185. mStub.append(station);
  16186. mStub.append((char)0x04);
  16187. mStub.append(pvac[1]);
  16188. mStub.append(pvac[0]);
  16189. mStub.append((char)0x00);
  16190. mStub.append((char)0x02);
  16191. }
  16192. }
  16193. connect(this, SIGNAL(queueEmpty()), this, SLOT(requestMeasurement()));
  16194. requestMeasurement();
  16195. }
  16196. double ModbusRTUDevice::SVLower()
  16197. {
  16198. return outputSVLower;
  16199. }
  16200. double ModbusRTUDevice::SVUpper()
  16201. {
  16202. return outputSVUpper;
  16203. }
  16204. int ModbusRTUDevice::decimals()
  16205. {
  16206. return decimalPosition;
  16207. }
  16208. void ModbusRTUDevice::decimalResponse(QByteArray response)
  16209. {
  16210. quint16 temp;
  16211. char *tchar = (char*)&temp;
  16212. tchar[1] = response.at(3);
  16213. tchar[0] = response.at(4);
  16214. decimalPosition = temp;
  16215. emit SVDecimalChanged(decimalPosition);
  16216. qDebug() << "Received decimal response";
  16217. }
  16218. void ModbusRTUDevice::unitResponse(QByteArray response)
  16219. {
  16220. quint16 temp;
  16221. char *tchar = (char*)&temp;
  16222. tchar[1] = response.at(3);
  16223. tchar[0] = response.at(4);
  16224. int value = temp;
  16225. if(value == valueF)
  16226. {
  16227. unitIsF = @[true@];
  16228. }
  16229. else
  16230. {
  16231. unitIsF = @[false@];
  16232. }
  16233. qDebug() << "Received unit response";
  16234. }
  16235. void ModbusRTUDevice::svlResponse(QByteArray response)
  16236. {
  16237. quint16 temp;
  16238. char *tchar = (char*)&temp;
  16239. tchar[1] = response.at(3);
  16240. tchar[0] = response.at(4);
  16241. outputSVLower = (double)temp;
  16242. for(int i = 0; i < decimalPosition; i++)
  16243. {
  16244. outputSVLower /= 10;
  16245. }
  16246. emit SVLowerChanged(outputSVLower);
  16247. qDebug() << "Received set value lower bound response";
  16248. }
  16249. void ModbusRTUDevice::svuResponse(QByteArray response)
  16250. {
  16251. quint16 temp;
  16252. char *tchar = (char*)&temp;
  16253. tchar[1] = response.at(3);
  16254. tchar[0] = response.at(4);
  16255. outputSVUpper = (double)temp;
  16256. for(int i = 0; i < decimalPosition; i++)
  16257. {
  16258. outputSVUpper /= 10;
  16259. }
  16260. emit SVUpperChanged(outputSVUpper);
  16261. qDebug() << "Received set value upper bound response";
  16262. }
  16263. void ModbusRTUDevice::requestMeasurement()
  16264. {
  16265. if(mStub.length() > 0)
  16266. {
  16267. queueMessage(mStub, this, "mResponse(QByteArray)");
  16268. }
  16269. else
  16270. {
  16271. queueMessage(pvStub, this, "mResponse(QByteArray)");
  16272. if(svenabled)
  16273. {
  16274. queueMessage(svStub, this, "mResponse(QByteArray)");
  16275. }
  16276. }
  16277. }
  16278. void ModbusRTUDevice::mResponse(QByteArray response)
  16279. {
  16280. QTime time = QTime::currentTime();
  16281. if(response.at(2) == 0x04)
  16282. {
  16283. @<Process PV and SV@>@;
  16284. }
  16285. else
  16286. {
  16287. @<Process PV or SV@>@;
  16288. }
  16289. }
  16290. @ There are two ways that we might request measurement data. All of the
  16291. devices I'@q'@>ve seen documented provide function 0x4 addresses for PV and SV
  16292. such that SV can be obtained from the address immediately after the address
  16293. from which we obtain PV. In this case we request both values at the same time.
  16294. @<Process PV and SV@>=
  16295. quint16 pv;
  16296. quint16 sv;
  16297. char *pvBytes = (char*)&pv;
  16298. char *svBytes = (char*)&sv;
  16299. pvBytes[1] = response.at(3);
  16300. pvBytes[0] = response.at(4);
  16301. svBytes[1] = response.at(5);
  16302. svBytes[0] = response.at(6);
  16303. double pvOut = (double)pv;
  16304. double svOut = (double)sv;
  16305. for(int i = 0; i < decimalPosition; i++)
  16306. {
  16307. pvOut /= 10;
  16308. svOut /= 10;
  16309. }
  16310. if(!unitIsF)
  16311. {
  16312. pvOut = pvOut * 9 / 5 + 32;
  16313. svOut = svOut * 9 / 5 + 32;
  16314. }
  16315. Measurement pvm(pvOut, time, Units::Fahrenheit);
  16316. Measurement svm(svOut, time, Units::Fahrenheit);
  16317. channels.at(0)->input(pvm);
  16318. channels.at(1)->input(svm);
  16319. @ When not measuring PV and SV at the same time, there are two possibilities.
  16320. One possibility is that SV is not enabled and we will only be reading from PV.
  16321. The other possibility is that we are alternating between reading PV and SV.
  16322. @<Process PV or SV@>=
  16323. quint16 value;
  16324. char *valueBytes = (char*)&value;
  16325. valueBytes[1] = response.at(3);
  16326. valueBytes[0] = response.at(4);
  16327. double valueOut = (double)value;
  16328. for(int i = 0; i < decimalPosition; i++)
  16329. {
  16330. valueOut /= 10;
  16331. }
  16332. if(!unitIsF)
  16333. {
  16334. valueOut = valueOut * 9 / 5 + 32;
  16335. }
  16336. if(!svenabled)
  16337. {
  16338. Measurement vm(valueOut, time, Units::Fahrenheit);
  16339. channels.at(0)->input(vm);
  16340. }
  16341. else
  16342. {
  16343. if(readingsv)
  16344. {
  16345. Measurement pvm(savedpv, time, Units::Fahrenheit);
  16346. Measurement svm(valueOut, time, Units::Fahrenheit);
  16347. channels.at(0)->input(pvm);
  16348. channels.at(1)->input(svm);
  16349. readingsv = false;
  16350. }
  16351. else
  16352. {
  16353. savedpv = valueOut;
  16354. readingsv = true;
  16355. }
  16356. }
  16357. @ The destructor should close the port.
  16358. @<ModbusRTUDevice implementation@>=
  16359. ModbusRTUDevice::~ModbusRTUDevice()
  16360. {
  16361. commTimeout->stop();
  16362. messageDelayTimer->stop();
  16363. port->close();
  16364. }
  16365. @ When data is available it should be read into a buffer. The start of the
  16366. buffer should always be the start of a response and there should never be
  16367. more than one response in the buffer at a time. It is, however, likely that
  16368. this buffer will have incomplete data. This means that we must determine when
  16369. the full response is available before passing the complete response along to
  16370. the appropriate method. If the response has not been received in full, nothing
  16371. is done. We'@q'@>ll be notified of more data shortly.
  16372. When the message we see the response for was queued, a callback was also
  16373. registered to handle the response. Once we have the complete message, we pass
  16374. the response along to the callback that was registered for that message,
  16375. remove the message and callback information from the message queue, and start
  16376. a timer which will trigger sending the next message after a safe amount of
  16377. time has passed.
  16378. If a response is received with an invalid CRC, we do not pass that message
  16379. out. Instead, the message handling queues are kept as they are and the previous
  16380. command will be sent again once the message delay timer is finished.
  16381. @<ModbusRTUDevice implementation@>=
  16382. void ModbusRTUDevice::dataAvailable()
  16383. {
  16384. if(messageDelayTimer->isActive())
  16385. {
  16386. messageDelayTimer->stop();
  16387. }
  16388. responseBuffer.append(port->readAll());
  16389. @<Check Modbus RTU message size@>@;
  16390. commTimeout->stop();
  16391. if(calculateCRC(responseBuffer) == 0)
  16392. {
  16393. QObject *object = retObjQueue.at(0);
  16394. char *method = callbackQueue.at(0);
  16395. QMetaMethod metamethod = @| object->metaObject()->
  16396. method(object->metaObject()->
  16397. indexOfMethod(@|QMetaObject::normalizedSignature(method)));
  16398. metamethod.invoke(object, Qt::QueuedConnection,
  16399. Q_ARG(QByteArray, responseBuffer));
  16400. messageQueue.removeAt(0);
  16401. retObjQueue.removeAt(0);
  16402. callbackQueue.removeAt(0);
  16403. }
  16404. else
  16405. {
  16406. qDebug() << "CRC failed";
  16407. }
  16408. messageDelayTimer->start(delayTime);
  16409. waiting = @[false@];
  16410. responseBuffer.clear();
  16411. }
  16412. @ In Modbus RTU, a response message starts with one byte identifying the device
  16413. the message was sent from, one byte indicating the function, a variable number
  16414. of bytes with the response data, and two bytes used to verify that the response
  16415. was correctly received. In the event of a normal response, messages will be at
  16416. least six bytes long, but in the event of an error it is possible for a message
  16417. to be five bytes long.
  16418. Messages with a function number of 0x01 or 0x02 will be 6 bytes in length.
  16419. Messages with a function number of 0x03 or 0x04 will be at least 7 bytes in
  16420. length with the total length determined by the sum of 5 and the value in the
  16421. fifth byte. Messages with a function number of 0x05, 0x06, or 0x10 will be 8
  16422. bytes in length. Messages with a function number greater than 0x80 will be five
  16423. bytes in length.
  16424. @<Check Modbus RTU message size@>=
  16425. if(responseBuffer.size() < 5)
  16426. {
  16427. return;
  16428. }
  16429. switch(responseBuffer.at(1))
  16430. {
  16431. case 0x01:
  16432. case 0x02:
  16433. if(responseBuffer.size() < 6)
  16434. {
  16435. return;
  16436. }
  16437. responseBuffer = responseBuffer.left(6);
  16438. break;
  16439. case 0x03:
  16440. case 0x04:
  16441. if(responseBuffer.size() < 5 + responseBuffer.at(2))
  16442. {
  16443. return;
  16444. }
  16445. responseBuffer = responseBuffer.left(5 + responseBuffer.at(2));
  16446. break;
  16447. case 0x05:
  16448. case 0x06:
  16449. case 0x10:
  16450. if(responseBuffer.size() < 8)
  16451. {
  16452. return;
  16453. }
  16454. responseBuffer = responseBuffer.left(8);
  16455. break;
  16456. }
  16457. @ When sending and receiving messages, it is necessary to calculate a 16 bit
  16458. cyclic redundancy check code. The algorithm used to calculate this is specified
  16459. by the Modbus RTU protocol documentation. When sending a message, |data| should
  16460. be the message to send except for the CRC bytes which will be appended once
  16461. this method calculates them. When receiving a message, passing the complete
  16462. message back through this method should result in a return value of |0|. Any
  16463. other value indicates an error.
  16464. @<ModbusRTUDevice implementation@>=
  16465. quint16 ModbusRTUDevice::calculateCRC(QByteArray data)
  16466. {
  16467. quint16 retval = 0xFFFF;
  16468. int i = 0;
  16469. while(i < data.size())
  16470. {
  16471. retval ^= 0x00FF & (quint16)data.at(i);
  16472. for(int j = 0; j < 8; j++)
  16473. {
  16474. if(retval & 1)
  16475. {
  16476. retval = (retval >> 1) ^ 0xA001;
  16477. }
  16478. else
  16479. {
  16480. retval >>= 1;
  16481. }
  16482. }
  16483. i++;
  16484. }
  16485. return retval;
  16486. }
  16487. @ When preparing an instance of ModbusRTUDevice, several messages may need to
  16488. be sent to the device in order to determine important details such as how
  16489. measurement data should be interpreted. During normal operation, messages
  16490. might be sent interactively between regular messages to acquire data. When
  16491. queueing a message, we also specify an object and method the response should be
  16492. sent to.
  16493. @<ModbusRTUDevice implementation@>=
  16494. void ModbusRTUDevice::queueMessage(QByteArray request, QObject *object,
  16495. const char *callback)
  16496. {
  16497. messageQueue.append(request);
  16498. retObjQueue.append(object);
  16499. callbackQueue.append(const_cast<char*>(callback));
  16500. if(messageQueue.size() == 1 && !(messageDelayTimer->isActive()))
  16501. {
  16502. sendNextMessage();
  16503. }
  16504. }
  16505. void ModbusRTUDevice::sendNextMessage()
  16506. {
  16507. if(messageQueue.size() > 0 && !waiting)
  16508. {
  16509. QByteArray message = messageQueue.at(0);
  16510. quint16 crc = calculateCRC(message);
  16511. char *check = (char*)&crc;
  16512. message.append(check[0]);
  16513. message.append(check[1]);
  16514. qDebug() << "Writing" << message.toHex();
  16515. port->write(message);
  16516. commTimeout->start(2000);
  16517. messageDelayTimer->start(delayTime);
  16518. waiting = @[true@];
  16519. }
  16520. else
  16521. {
  16522. emit queueEmpty();
  16523. }
  16524. }
  16525. void ModbusRTUDevice::outputSV(double value)
  16526. {
  16527. for(int i = 0; i < decimalPosition; i++)
  16528. {
  16529. value *= 10;
  16530. }
  16531. quint16 outval = (quint16)value;
  16532. QByteArray message(outputSVStub);
  16533. char *valBytes = (char*)&outval;
  16534. message.append(valBytes[1]);
  16535. message.append(valBytes[0]);
  16536. queueMessage(message, this, "ignore(QByteArray)");
  16537. }
  16538. @ We don'@q'@>t care about the response when sending a new SV.
  16539. @<ModbusRTUDevice implementation@>=
  16540. void ModbusRTUDevice::ignore(QByteArray)
  16541. {
  16542. return;
  16543. }
  16544. @ Sometimes a communications failure will occur in which a response to a
  16545. command is never received. To reset communications we set a timer whenever a
  16546. command is sent and stop that once a full response is received. If the timer
  16547. times out, we should clear the response buffer and attempt to re-establish
  16548. communications. Currently this timeout is hard coded at 2 seconds, however
  16549. this should be configurable and smaller values may well be acceptable.
  16550. @<ModbusRTUDevice implementation@>=
  16551. void ModbusRTUDevice::timeout()
  16552. {
  16553. qDebug() << "Communications timeout.";
  16554. responseBuffer.clear();
  16555. waiting = false;
  16556. messageDelayTimer->start();
  16557. }
  16558. @ This class must be exposed to the host environment.
  16559. @<Function prototypes for scripting@>=
  16560. QScriptValue constructModbusRTUDevice(QScriptContext *context, QScriptEngine *engine);
  16561. QScriptValue ModbusRTUDevice_pVChannel(QScriptContext *context, QScriptEngine *engine);
  16562. QScriptValue ModbusRTUDevice_sVChannel(QScriptContext *context, QScriptEngine *engine);
  16563. void setModbusRTUDeviceProperties(QScriptValue value, QScriptEngine *engine);
  16564. @ The host environment is informed of the constructor.
  16565. @<Set up the scripting engine@>=
  16566. constructor = engine->newFunction(constructModbusRTUDevice);
  16567. value = engine->newQMetaObject(&ModbusRTUDevice::staticMetaObject, constructor);
  16568. engine->globalObject().setProperty("ModbusRTUDevice", value);
  16569. @ The constructor takes the configuration model and the index to the device of
  16570. interest as arguments rather than provide a large number of property setters to
  16571. handle initialization.
  16572. @<Functions for scripting@>=
  16573. QScriptValue constructModbusRTUDevice(QScriptContext *context, QScriptEngine *engine)
  16574. {
  16575. QScriptValue object;
  16576. if(context->argumentCount() == 2)
  16577. {
  16578. object = engine->newQObject(new ModbusRTUDevice(argument<DeviceTreeModel *>(0, context),
  16579. argument<QModelIndex>(1, context)),
  16580. QScriptEngine::ScriptOwnership);
  16581. setModbusRTUDeviceProperties(object, engine);
  16582. }
  16583. else
  16584. {
  16585. context->throwError("Incorrect number of arguments passed to "@|
  16586. "ModbusRTUDevice constructor. This takes the configuration model "@|
  16587. "and an index.");
  16588. }
  16589. return object;
  16590. }
  16591. @ The host environment needs a way to gain access to the channel objects.
  16592. @<Functions for scripting@>=
  16593. QScriptValue ModbusRTUDevice_pVChannel(QScriptContext *context, QScriptEngine *engine)
  16594. {
  16595. ModbusRTUDevice *self = getself<ModbusRTUDevice *>(context);
  16596. QScriptValue object;
  16597. if(self)
  16598. {
  16599. if(self->channels.size() > 0)
  16600. {
  16601. object = engine->newQObject(self->channels.at(0));
  16602. setChannelProperties(object, engine);
  16603. }
  16604. }
  16605. return object;
  16606. }
  16607. QScriptValue ModbusRTUDevice_sVChannel(QScriptContext *context, QScriptEngine *engine)
  16608. {
  16609. ModbusRTUDevice *self = getself<ModbusRTUDevice *>(context);
  16610. QScriptValue object;
  16611. if(self)
  16612. {
  16613. if(self->channels.size() > 1)
  16614. {
  16615. object = engine->newQObject(self->channels.at(1));
  16616. setChannelProperties(object, engine);
  16617. }
  16618. }
  16619. return object;
  16620. }
  16621. @ These methods are set as properties when the object is created.
  16622. @<Functions for scripting@>=
  16623. void setModbusRTUDeviceProperties(QScriptValue value, QScriptEngine *engine)
  16624. {
  16625. setQObjectProperties(value, engine);
  16626. value.setProperty("pVChannel", engine->newFunction(ModbusRTUDevice_pVChannel));
  16627. value.setProperty("sVChannel", engine->newFunction(ModbusRTUDevice_sVChannel));
  16628. }
  16629. @* Modbus RTU device configuration widget.
  16630. \noindent This class was minimally adapted from a prototype implementation to
  16631. use the new configuration system introduced in \pn{} 1.4.
  16632. With all of the custom widgets for specifying a device configuration in place,
  16633. we can proceed to combine these in a form. As all of the options might use more
  16634. screen space than is available we make this scrollable. Some reorganization of
  16635. this will be done prior to release to enable the use of multiple devices on the
  16636. port which may obviate the need for this, but as there are those who prefer to
  16637. have a small screen it may be better to leave the scroll area in place even
  16638. after such a change.
  16639. @<Class declarations@>=
  16640. class ModbusConfigurator : public BasicDeviceConfigurationWidget
  16641. {
  16642. @[Q_OBJECT@]@;
  16643. public:@/
  16644. Q_INVOKABLE@,@, ModbusConfigurator(DeviceTreeModel *model, const QModelIndex &index);@/
  16645. @[private slots@]:@/
  16646. void updatePort(const QString &newPort);
  16647. void updateBaudRate(const QString &newRate);
  16648. void updateParity(const QString &newParity);
  16649. void updateFlowControl(const QString &newFlow);
  16650. void updateStopBits(const QString &newStopBits);
  16651. void updateStation(int station);
  16652. void updateFixedDecimal(bool fixed);
  16653. void updateDecimalAddress(int address);
  16654. void updateDecimalPosition(int position);
  16655. void updateFixedUnit(bool fixed);
  16656. void updateUnitAddress(int address);
  16657. void updateValueForF(int value);
  16658. void updateValueForC(int value);
  16659. void updateUnit(const QString &newUnit);
  16660. void updatePVAddress(int address);
  16661. void updateSVEnabled(bool enabled);
  16662. void updateSVReadAddress(int address);
  16663. void updateDeviceLimit(bool query);
  16664. void updateSVLowerAddress(int address);
  16665. void updateSVUpperAddress(int address);
  16666. void updateSVLower(double value);
  16667. void updateSVUpper(double value);
  16668. void updateSVWritable(bool canWriteSV);
  16669. void updateSVWriteAddress(int address);
  16670. void updatePVColumnName(const QString &name);
  16671. void updateSVColumnName(const QString &name);
  16672. void updatePVHidden(bool hidden);
  16673. void updateSVHidden(bool hidden);@/
  16674. private:@/
  16675. PortSelector *port;
  16676. BaudSelector *baud;
  16677. ParitySelector *parity;
  16678. FlowSelector *flow;
  16679. StopSelector *stop;
  16680. QSpinBox *station;
  16681. QCheckBox *decimalQuery;
  16682. ShortHexSpinBox *decimalAddress;
  16683. QSpinBox *decimalPosition;
  16684. QCheckBox *unitQuery;
  16685. ShortHexSpinBox *unitAddress;
  16686. QSpinBox *valueF;
  16687. QSpinBox *valueC;
  16688. QComboBox *fixedUnit;
  16689. ShortHexSpinBox *pVAddress;
  16690. QCheckBox *sVEnabled;
  16691. ShortHexSpinBox *sVReadAddress;
  16692. QCheckBox *deviceLimit;
  16693. ShortHexSpinBox *sVLowerAddr;
  16694. ShortHexSpinBox *sVUpperAddr;
  16695. QDoubleSpinBox *sVLower;
  16696. QDoubleSpinBox *sVUpper;
  16697. QCheckBox *sVWritable;
  16698. ShortHexSpinBox *sVOutputAddr;
  16699. QLineEdit *pVColumnName;
  16700. QLineEdit *sVColumnName;
  16701. };
  16702. @ Implementation.
  16703. @<ModbusConfigurator implementation@>=
  16704. ModbusConfigurator::ModbusConfigurator(DeviceTreeModel *model, const QModelIndex &index)
  16705. : BasicDeviceConfigurationWidget(model, index),
  16706. port(new PortSelector), baud(new BaudSelector), parity(new ParitySelector),
  16707. flow(new FlowSelector), stop(new StopSelector), station(new QSpinBox),
  16708. decimalQuery(new QCheckBox(tr("Enable"))),
  16709. decimalAddress(new ShortHexSpinBox), decimalPosition(new QSpinBox),
  16710. unitQuery(new QCheckBox(tr("Enable"))),
  16711. unitAddress(new ShortHexSpinBox), valueF(new QSpinBox),
  16712. valueC(new QSpinBox), fixedUnit(new QComboBox),
  16713. pVAddress(new ShortHexSpinBox),
  16714. sVEnabled(new QCheckBox(tr("Enable"))),
  16715. sVReadAddress(new ShortHexSpinBox),
  16716. deviceLimit(new QCheckBox(tr("Enable"))),
  16717. sVLowerAddr(new ShortHexSpinBox), sVUpperAddr(new ShortHexSpinBox),
  16718. sVLower(new QDoubleSpinBox), sVUpper(new QDoubleSpinBox),
  16719. sVWritable(new QCheckBox(tr("Enable"))),
  16720. sVOutputAddr(new ShortHexSpinBox),
  16721. pVColumnName(new QLineEdit), sVColumnName(new QLineEdit)
  16722. {
  16723. QHBoxLayout *layout = new QHBoxLayout;
  16724. QWidget *form = new QWidget;
  16725. QHBoxLayout *masterLayout = new QHBoxLayout;
  16726. QVBoxLayout *portAndDeviceLayout = new QVBoxLayout;
  16727. QVBoxLayout *seriesLayout = new QVBoxLayout;
  16728. QFormLayout *serialSection = new QFormLayout;
  16729. serialSection->addRow(QString(tr("Port:")), port);
  16730. serialSection->addRow(QString(tr("Baud rate:")), baud);
  16731. serialSection->addRow(QString(tr("Parity:")), parity);
  16732. serialSection->addRow(QString(tr("Flow control:")), flow);
  16733. serialSection->addRow(QString(tr("Stop bits:")), stop);
  16734. QGroupBox *serialSectionBox = new QGroupBox(tr("Serial Port Configuration"));
  16735. serialSectionBox->setLayout(serialSection);
  16736. portAndDeviceLayout->addWidget(serialSectionBox);
  16737. QFormLayout *deviceSection = new QFormLayout;
  16738. station->setMinimum(1);
  16739. station->setMaximum(255);
  16740. decimalPosition->setMinimum(0);
  16741. decimalPosition->setMaximum(9);
  16742. valueF->setMinimum(0);
  16743. valueF->setMaximum(0xFFFF);
  16744. valueC->setMinimum(0);
  16745. valueC->setMaximum(0xFFFF);
  16746. fixedUnit->addItem(tr("Fahrenheit"), QVariant(QString("F")));
  16747. fixedUnit->addItem(tr("Celsius"), QVariant(QString("C")));
  16748. deviceSection->addRow(tr("Station:"), station);
  16749. deviceSection->addRow(tr("Decimal position from device:"), decimalQuery);
  16750. deviceSection->addRow(tr("Decimal position relative address:"), decimalAddress);
  16751. deviceSection->addRow(tr("Fixed decimal position:"), decimalPosition);
  16752. deviceSection->addRow(tr("Measurement unit from device:"), unitQuery);
  16753. deviceSection->addRow(tr("Current unit relative address:"), unitAddress);
  16754. deviceSection->addRow(tr("Value for Fahrenheit:"), valueF);
  16755. deviceSection->addRow(tr("Value for Celsius:"), valueC);
  16756. deviceSection->addRow(tr("Fixed unit:"), fixedUnit);
  16757. QGroupBox *deviceSectionBox = new QGroupBox(tr("Device Configuration"));
  16758. deviceSectionBox->setLayout(deviceSection);
  16759. portAndDeviceLayout->addWidget(deviceSectionBox);
  16760. QFormLayout *pVSection = new QFormLayout;
  16761. pVSection->addRow(tr("Value relative address:"), pVAddress);
  16762. pVSection->addRow(tr("PV column name:"), pVColumnName);
  16763. QCheckBox *pVHideBox = new QCheckBox(tr("Hide this channel"));
  16764. pVSection->addRow(pVHideBox);
  16765. QGroupBox *processValueBox = new QGroupBox(tr("Process Value"));
  16766. processValueBox->setLayout(pVSection);
  16767. seriesLayout->addWidget(processValueBox);
  16768. QFormLayout *sVSection = new QFormLayout;
  16769. sVLower->setDecimals(1);
  16770. sVLower->setMinimum(0.0);
  16771. sVLower->setMaximum(999.9);
  16772. sVUpper->setDecimals(1);
  16773. sVUpper->setMinimum(0.0);
  16774. sVUpper->setMaximum(999.9);
  16775. sVSection->addRow(tr("Set value:"), sVEnabled);
  16776. sVSection->addRow(tr("Read relative address:"), sVReadAddress);
  16777. sVSection->addRow(tr("SV column name:"), sVColumnName);
  16778. sVSection->addRow(tr("Limits from device:"), deviceLimit);
  16779. sVSection->addRow(tr("Lower limit relative address:"), sVLowerAddr);
  16780. sVSection->addRow(tr("Upper limit relative address:"), sVUpperAddr);
  16781. sVSection->addRow(tr("Lower limit:"), sVLower);
  16782. sVSection->addRow(tr("Upper limit:"), sVUpper);
  16783. sVSection->addRow(tr("Output set value:"), sVWritable);
  16784. sVSection->addRow(tr("Output relative address:"), sVOutputAddr);
  16785. QCheckBox *sVHideBox = new QCheckBox(tr("Hide this channel"));
  16786. sVSection->addRow(sVHideBox);
  16787. QGroupBox *setValueBox = new QGroupBox(tr("Set Value"));
  16788. setValueBox->setLayout(sVSection);
  16789. seriesLayout->addWidget(setValueBox);
  16790. masterLayout->addLayout(portAndDeviceLayout);
  16791. masterLayout->addLayout(seriesLayout);
  16792. form->setLayout(masterLayout);
  16793. @<Get device configuration data for current node@>@;
  16794. for(int i = 0; i < configData.size(); i++)
  16795. {
  16796. node = configData.at(i).toElement();
  16797. if(node.attribute("name") == "port")
  16798. {
  16799. QString portname = node.attribute("value");
  16800. int idx = port->findText(portname);
  16801. if(idx >= 0)
  16802. {
  16803. port->setCurrentIndex(idx);
  16804. }
  16805. else
  16806. {
  16807. port->addItem(portname);
  16808. }
  16809. }
  16810. else if(node.attribute("name") == "baud")
  16811. {
  16812. baud->setCurrentIndex(baud->findText(node.attribute("value")));
  16813. }
  16814. else if(node.attribute("name") == "parity")
  16815. {
  16816. parity->setCurrentIndex(parity->findData(node.attribute("value")));
  16817. }
  16818. else if(node.attribute("name") == "flow")
  16819. {
  16820. flow->setCurrentIndex(flow->findData(node.attribute("value")));
  16821. }
  16822. else if(node.attribute("name") == "stop")
  16823. {
  16824. stop->setCurrentIndex(stop->findData(node.attribute("value")));
  16825. }
  16826. else if(node.attribute("name") == "station")
  16827. {
  16828. station->setValue(node.attribute("value").toInt());
  16829. }
  16830. else if(node.attribute("name") == "decimalQuery")
  16831. {
  16832. if(node.attribute("value") == "true")
  16833. {
  16834. decimalQuery->setChecked(true);
  16835. }
  16836. else
  16837. {
  16838. decimalQuery->setChecked(false);
  16839. }
  16840. }
  16841. else if(node.attribute("name") == "decimalAddress")
  16842. {
  16843. decimalAddress->setValue(node.attribute("value").toInt());
  16844. }
  16845. else if(node.attribute("name") == "decimalPosition")
  16846. {
  16847. decimalPosition->setValue(node.attribute("value").toInt());
  16848. }
  16849. else if(node.attribute("name") == "unitQuery")
  16850. {
  16851. if(node.attribute("value") == "true")
  16852. {
  16853. unitQuery->setChecked(true);
  16854. }
  16855. else
  16856. {
  16857. unitQuery->setChecked(false);
  16858. }
  16859. }
  16860. else if(node.attribute("name") == "unitAddress")
  16861. {
  16862. unitAddress->setValue(node.attribute("value").toInt());
  16863. }
  16864. else if(node.attribute("name") == "valueF")
  16865. {
  16866. valueF->setValue(node.attribute("value").toInt());
  16867. }
  16868. else if(node.attribute("name") == "valueC")
  16869. {
  16870. valueC->setValue(node.attribute("value").toInt());
  16871. }
  16872. else if(node.attribute("name") == "fixedUnit")
  16873. {
  16874. fixedUnit->setCurrentIndex(fixedUnit->findText(node.attribute("value")));
  16875. }
  16876. else if(node.attribute("name") == "pVAddress")
  16877. {
  16878. pVAddress->setValue(node.attribute("value").toInt());
  16879. }
  16880. else if(node.attribute("name") == "sVEnabled")
  16881. {
  16882. if(node.attribute("value") == "true")
  16883. {
  16884. sVEnabled->setChecked(true);
  16885. }
  16886. else
  16887. {
  16888. sVEnabled->setChecked(false);
  16889. }
  16890. }
  16891. else if(node.attribute("name") == "sVReadAddress")
  16892. {
  16893. sVReadAddress->setValue(node.attribute("value").toInt());
  16894. }
  16895. else if(node.attribute("name") == "deviceLimit")
  16896. {
  16897. if(node.attribute("value") == "true")
  16898. {
  16899. deviceLimit->setChecked(true);
  16900. }
  16901. else
  16902. {
  16903. deviceLimit->setChecked(false);
  16904. }
  16905. }
  16906. else if(node.attribute("name") == "sVLowerAddr")
  16907. {
  16908. sVLowerAddr->setValue(node.attribute("value").toInt());
  16909. }
  16910. else if(node.attribute("name") == "sVUpperAddr")
  16911. {
  16912. sVUpperAddr->setValue(node.attribute("value").toInt());
  16913. }
  16914. else if(node.attribute("name") == "sVLower")
  16915. {
  16916. sVLower->setValue(node.attribute("value").toDouble());
  16917. }
  16918. else if(node.attribute("name") == "sVUpper")
  16919. {
  16920. sVUpper->setValue(node.attribute("value").toDouble());
  16921. }
  16922. else if(node.attribute("name") == "sVWritable")
  16923. {
  16924. if(node.attribute("value") == "true")
  16925. {
  16926. sVWritable->setChecked(true);
  16927. }
  16928. else
  16929. {
  16930. sVWritable->setChecked(false);
  16931. }
  16932. }
  16933. else if(node.attribute("name") == "sVOutputAddr")
  16934. {
  16935. sVOutputAddr->setValue(node.attribute("value").toInt());
  16936. }
  16937. else if(node.attribute("name") == "pvcolname")
  16938. {
  16939. pVColumnName->setText(node.attribute("value"));
  16940. }
  16941. else if(node.attribute("name") == "svcolname")
  16942. {
  16943. sVColumnName->setText(node.attribute("value"));
  16944. }
  16945. else if(node.attribute("name") == "pvhidden")
  16946. {
  16947. pVHideBox->setChecked(node.attribute("value") == "true");
  16948. }
  16949. else if(node.attribute("name") == "svhidden")
  16950. {
  16951. sVHideBox->setChecked(node.attribute("value") == "true");
  16952. }
  16953. }
  16954. updatePort(port->currentText());
  16955. updateBaudRate(baud->currentText());
  16956. updateParity(parity->itemData(parity->currentIndex()).toString());
  16957. updateFlowControl(flow->itemData(flow->currentIndex()).toString());
  16958. updateStopBits(stop->itemData(stop->currentIndex()).toString());
  16959. updateStation(station->value());
  16960. updateFixedDecimal(decimalQuery->isChecked());
  16961. updateDecimalAddress(decimalAddress->value());
  16962. updateDecimalPosition(decimalPosition->value());
  16963. updateFixedUnit(unitQuery->isChecked());
  16964. updateUnitAddress(unitAddress->value());
  16965. updateValueForF(valueF->value());
  16966. updateValueForC(valueC->value());
  16967. updateUnit(fixedUnit->currentText());
  16968. updatePVAddress(pVAddress->value());
  16969. updateSVEnabled(sVEnabled->isChecked());
  16970. updateSVReadAddress(sVReadAddress->value());
  16971. updateDeviceLimit(deviceLimit->isChecked());
  16972. updateSVLowerAddress(sVLowerAddr->value());
  16973. updateSVUpperAddress(sVUpperAddr->value());
  16974. updateSVLower(sVLower->value());
  16975. updateSVUpper(sVUpper->value());
  16976. updateSVWritable(sVWritable->isChecked());
  16977. updateSVWriteAddress(sVOutputAddr->value());
  16978. updatePVColumnName(pVColumnName->text());
  16979. updateSVColumnName(sVColumnName->text());
  16980. updatePVHidden(pVHideBox->isChecked());
  16981. updateSVHidden(sVHideBox->isChecked());
  16982. connect(port, SIGNAL(currentIndexChanged(QString)), this, SLOT(updatePort(QString)));
  16983. connect(port, SIGNAL(editTextChanged(QString)), this, SLOT(updatePort(QString)));
  16984. connect(baud, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateBaudRate(QString)));
  16985. connect(parity, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateParity(QString)));
  16986. connect(flow, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateFlowControl(QString)));
  16987. connect(stop, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateStopBits(QString)));
  16988. connect(station, SIGNAL(valueChanged(int)), this, SLOT(updateStation(int)));
  16989. connect(decimalQuery, SIGNAL(toggled(bool)), this, SLOT(updateFixedDecimal(bool)));
  16990. connect(decimalAddress, SIGNAL(valueChanged(int)), this, SLOT(updateDecimalAddress(int)));
  16991. connect(decimalPosition, SIGNAL(valueChanged(int)), this, SLOT(updateDecimalPosition(int)));
  16992. connect(unitQuery, SIGNAL(toggled(bool)), this, SLOT(updateFixedUnit(bool)));
  16993. connect(unitAddress, SIGNAL(valueChanged(int)), this, SLOT(updateUnitAddress(int)));
  16994. connect(valueF, SIGNAL(valueChanged(int)), this, SLOT(updateValueForF(int)));
  16995. connect(valueC, SIGNAL(valueChanged(int)), this, SLOT(updateValueForC(int)));
  16996. connect(fixedUnit, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateUnit(QString)));
  16997. connect(pVAddress, SIGNAL(valueChanged(int)), this, SLOT(updatePVAddress(int)));
  16998. connect(sVEnabled, SIGNAL(toggled(bool)), this, SLOT(updateSVEnabled(bool)));
  16999. connect(sVReadAddress, SIGNAL(valueChanged(int)), this, SLOT(updateSVReadAddress(int)));
  17000. connect(deviceLimit, SIGNAL(toggled(bool)), this, SLOT(updateDeviceLimit(bool)));
  17001. connect(sVLowerAddr, SIGNAL(valueChanged(int)), this, SLOT(updateSVLowerAddress(int)));
  17002. connect(sVUpperAddr, SIGNAL(valueChanged(int)), this, SLOT(updateSVUpperAddress(int)));
  17003. connect(sVLower, SIGNAL(valueChanged(double)), this, SLOT(updateSVLower(double)));
  17004. connect(sVUpper, SIGNAL(valueChanged(double)), this, SLOT(updateSVUpper(double)));
  17005. connect(sVWritable, SIGNAL(toggled(bool)), this, SLOT(updateSVWritable(bool)));
  17006. connect(sVOutputAddr, SIGNAL(valueChanged(int)), this, SLOT(updateSVWriteAddress(int)));
  17007. connect(pVColumnName, SIGNAL(textEdited(QString)), this, SLOT(updatePVColumnName(QString)));
  17008. connect(sVColumnName, SIGNAL(textEdited(QString)), this, SLOT(updateSVColumnName(QString)));
  17009. connect(pVHideBox, SIGNAL(toggled(bool)), this, SLOT(updatePVHidden(bool)));
  17010. connect(sVHideBox, SIGNAL(toggled(bool)), this, SLOT(updateSVHidden(bool)));
  17011. layout->addWidget(form);
  17012. setLayout(layout);
  17013. }
  17014. void ModbusConfigurator::updatePort(const QString &newPort)
  17015. {
  17016. updateAttribute("port", newPort);
  17017. }
  17018. void ModbusConfigurator::updateBaudRate(const QString &newRate)
  17019. {
  17020. updateAttribute("baud", newRate);
  17021. }
  17022. void ModbusConfigurator::updateParity(const QString &)
  17023. {
  17024. updateAttribute("parity", parity->itemData(parity->currentIndex()).toString());
  17025. }
  17026. void ModbusConfigurator::updateFlowControl(const QString &)
  17027. {
  17028. updateAttribute("flow", flow->itemData(flow->currentIndex()).toString());
  17029. }
  17030. void ModbusConfigurator::updateStopBits(const QString &)
  17031. {
  17032. updateAttribute("stop", stop->itemData(stop->currentIndex()).toString());
  17033. }
  17034. void ModbusConfigurator::updateStation(int station)
  17035. {
  17036. updateAttribute("station", QString("%1").arg(station));
  17037. }
  17038. void ModbusConfigurator::updateFixedDecimal(bool fixed)
  17039. {
  17040. updateAttribute("decimalQuery", fixed ? "true" : "false");
  17041. }
  17042. void ModbusConfigurator::updateDecimalAddress(int address)
  17043. {
  17044. updateAttribute("decimalAddress", QString("%1").arg(address));
  17045. }
  17046. void ModbusConfigurator::updateDecimalPosition(int position)
  17047. {
  17048. updateAttribute("decimalPosition", QString("%1").arg(position));
  17049. }
  17050. void ModbusConfigurator::updateFixedUnit(bool fixed)
  17051. {
  17052. updateAttribute("unitQuery", fixed ? "true" : "false");
  17053. }
  17054. void ModbusConfigurator::updateUnitAddress(int address)
  17055. {
  17056. updateAttribute("unitAddress", QString("%1").arg(address));
  17057. }
  17058. void ModbusConfigurator::updateValueForF(int value)
  17059. {
  17060. updateAttribute("valueF", QString("%1").arg(value));
  17061. }
  17062. void ModbusConfigurator::updateValueForC(int value)
  17063. {
  17064. updateAttribute("valueC", QString("%1").arg(value));
  17065. }
  17066. void ModbusConfigurator::updateUnit(const QString &newUnit)
  17067. {
  17068. updateAttribute("fixedUnit", newUnit);
  17069. }
  17070. void ModbusConfigurator::updatePVAddress(int address)
  17071. {
  17072. updateAttribute("pVAddress", QString("%1").arg(address));
  17073. }
  17074. void ModbusConfigurator::updateSVEnabled(bool enabled)
  17075. {
  17076. updateAttribute("sVEnabled", enabled ? "true" : "false");
  17077. }
  17078. void ModbusConfigurator::updateSVReadAddress(int address)
  17079. {
  17080. updateAttribute("sVReadAddress", QString("%1").arg(address));
  17081. }
  17082. void ModbusConfigurator::updateDeviceLimit(bool query)
  17083. {
  17084. updateAttribute("deviceLimit", query ? "true" : "false");
  17085. }
  17086. void ModbusConfigurator::updateSVLowerAddress(int address)
  17087. {
  17088. updateAttribute("sVLowerAddr", QString("%1").arg(address));
  17089. }
  17090. void ModbusConfigurator::updateSVUpperAddress(int address)
  17091. {
  17092. updateAttribute("sVUpperAddr", QString("%1").arg(address));
  17093. }
  17094. void ModbusConfigurator::updateSVLower(double value)
  17095. {
  17096. updateAttribute("sVLower", QString("%1").arg(value));
  17097. }
  17098. void ModbusConfigurator::updateSVUpper(double value)
  17099. {
  17100. updateAttribute("sVUpper", QString("%1").arg(value));
  17101. }
  17102. void ModbusConfigurator::updateSVWritable(bool canWriteSV)
  17103. {
  17104. updateAttribute("sVWritable", canWriteSV ? "true" : "false");
  17105. }
  17106. void ModbusConfigurator::updateSVWriteAddress(int address)
  17107. {
  17108. updateAttribute("sVOutputAddr", QString("%1").arg(address));
  17109. }
  17110. void ModbusConfigurator::updatePVColumnName(const QString &name)
  17111. {
  17112. updateAttribute("pvcolname", name);
  17113. }
  17114. void ModbusConfigurator::updateSVColumnName(const QString &name)
  17115. {
  17116. updateAttribute("svcolname", name);
  17117. }
  17118. void ModbusConfigurator::updatePVHidden(bool hidden)
  17119. {
  17120. updateAttribute("pvhidden", hidden ? "true" : "false");
  17121. }
  17122. void ModbusConfigurator::updateSVHidden(bool hidden)
  17123. {
  17124. updateAttribute("svhidden", hidden ? "true" : "false");
  17125. }
  17126. @ This is registered with the configuration system.
  17127. @<Register device configuration widgets@>=
  17128. app.registerDeviceConfigurationWidget("modbusrtu", ModbusConfigurator::staticMetaObject);
  17129. @ A |NodeInserter| for the driver configuration widget is also needed.
  17130. @<Register top level device configuration nodes@>=
  17131. inserter = new NodeInserter(tr("Modbus RTU Device"), tr("Modbus RTU Device"), "modbusrtu", NULL);
  17132. topLevelNodeInserters.append(inserter);
  17133. @i modbus.w
  17134. @i unsupportedserial.w
  17135. @i phidgets.w
  17136. @* Configuration widget for a calibrated data series.
  17137. \noindent This control is used for adding a |LinearSplineInterpolator| to the
  17138. logging view.
  17139. @<Class declarations@>=
  17140. class LinearSplineInterpolationConfWidget : public BasicDeviceConfigurationWidget
  17141. {
  17142. @[Q_OBJECT@]@/
  17143. public:@/
  17144. @[Q_INVOKABLE@]@, LinearSplineInterpolationConfWidget(DeviceTreeModel *model,
  17145. const QModelIndex &index);
  17146. @[private slots@]:@/
  17147. void updateSourceColumn(const QString &source);
  17148. void updateDestinationColumn(const QString &dest);
  17149. void updateKnots();
  17150. private:@/
  17151. SaltModel *tablemodel;
  17152. };
  17153. @ This is configured by specifying a source column name, a destination column
  17154. name, and a two column table. Note that while we only have one widget handling
  17155. the mapping data, we store each column of the table in its own attribute.
  17156. @<LinearSplineInterpolationConfWidget implementation@>=
  17157. LinearSplineInterpolationConfWidget::LinearSplineInterpolationConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  17158. : BasicDeviceConfigurationWidget(model, index), tablemodel(new SaltModel(2))
  17159. {
  17160. QFormLayout *layout = new QFormLayout;
  17161. QLineEdit *source = new QLineEdit;
  17162. layout->addRow(tr("Source column name:"), source);
  17163. QLineEdit *destination = new QLineEdit;
  17164. layout->addRow(tr("Destination column name:"), destination);
  17165. tablemodel->setHeaderData(0, Qt::Horizontal, "Input");
  17166. tablemodel->setHeaderData(1, Qt::Horizontal, "Output");
  17167. QTableView *mappingTable = new QTableView;
  17168. mappingTable->setModel(tablemodel);
  17169. NumericDelegate *delegate = new NumericDelegate;
  17170. mappingTable->setItemDelegate(delegate);
  17171. layout->addRow(tr("Mapping data:"), mappingTable);
  17172. @<Get device configuration data for current node@>@;
  17173. for(int i = 0; i < configData.size(); i++)
  17174. {
  17175. node = configData.at(i).toElement();
  17176. if(node.attribute("name") == "source")
  17177. {
  17178. source->setText(node.attribute("value"));
  17179. }
  17180. else if(node.attribute("name") == "destination")
  17181. {
  17182. destination->setText(node.attribute("value"));
  17183. }
  17184. else if(node.attribute("name") == "sourcevalues")
  17185. {
  17186. @<Convert numeric array literal to list@>@;
  17187. int column = 0;
  17188. @<Populate model column from list@>@;
  17189. }
  17190. else if(node.attribute("name") == "destinationvalues")
  17191. {
  17192. @<Convert numeric array literal to list@>@;
  17193. int column = 1;
  17194. @<Populate model column from list@>@;
  17195. }
  17196. }
  17197. updateSourceColumn(source->text());
  17198. updateDestinationColumn(destination->text());
  17199. updateKnots();
  17200. connect(source, SIGNAL(textEdited(QString)), this, SLOT(updateSourceColumn(QString)));
  17201. connect(destination, SIGNAL(textEdited(QString)), this, SLOT(updateDestinationColumn(QString)));
  17202. connect(tablemodel, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(updateKnots()));
  17203. setLayout(layout);
  17204. }
  17205. @ The saved data will have come from a previous call to
  17206. |SaltModel::arrayLiteral()| to repopulate the model we need to strip off the
  17207. the start and end of the strings and split them back into separate elements.
  17208. @<Convert numeric array literal to list@>=
  17209. QString data = node.attribute("value");
  17210. if(data.length() > 3)
  17211. {
  17212. data.chop(2);
  17213. data = data.remove(0, 2);
  17214. }
  17215. QStringList itemList = data.split(",");
  17216. @ Once the saved string has been split, the values can be inserted into the
  17217. model.
  17218. @<Populate model column from list@>=
  17219. for(int j = 0; j < itemList.size(); j++)
  17220. {
  17221. tablemodel->setData(tablemodel->index(j, column),
  17222. QVariant(itemList.at(j).toDouble()),
  17223. Qt::DisplayRole);
  17224. }
  17225. @ When data in the table is changed we simply overwrite any previously saved
  17226. data with the current data.
  17227. @<LinearSplineInterpolationConfWidget implementation@>=
  17228. void LinearSplineInterpolationConfWidget::updateKnots()
  17229. {
  17230. updateAttribute("sourcevalues", tablemodel->arrayLiteral(0, Qt::DisplayRole));
  17231. updateAttribute("destinationvalues", tablemodel->arrayLiteral(1, Qt::DisplayRole));
  17232. }
  17233. void LinearSplineInterpolationConfWidget::updateSourceColumn(const QString &source)
  17234. {
  17235. updateAttribute("source", source);
  17236. }
  17237. void LinearSplineInterpolationConfWidget::updateDestinationColumn(const QString &dest)
  17238. {
  17239. updateAttribute("destination", dest);
  17240. }
  17241. @ The widget is registered with the configuration system.
  17242. @<Register device configuration widgets@>=
  17243. app.registerDeviceConfigurationWidget("linearspline", LinearSplineInterpolationConfWidget::staticMetaObject);
  17244. @* Additional Timers.
  17245. \noindent \pn{} 1.6.4 adds support for more timer indicators than just the
  17246. default batch timer. Three new timer types are supported. The first is a
  17247. cooling timer. This is a timer that is initially set to 0, but at the end of a
  17248. batch this is set to a configured time and starts counting down. There are no
  17249. data logging requirements and this is purely a convenience feature, but one
  17250. that supports product and personnel safety best practices as it helps to
  17251. eliminate the practice of a person reaching into the cooling tray as it
  17252. agitates to test if the coffee has cooled.
  17253. @<Class declarations@>=
  17254. class CoolingTimerConfWidget : public BasicDeviceConfigurationWidget
  17255. {
  17256. @[Q_OBJECT@]@/
  17257. public:@/
  17258. @[Q_INVOKABLE@]@, CoolingTimerConfWidget(DeviceTreeModel *model,
  17259. const QModelIndex &index);
  17260. @[private slots@]:@/
  17261. void updateResetTime(QTime time);
  17262. };
  17263. @ The only configurable detail is the vaue the timer should reset to. For this
  17264. a |QTimeEdit| is fine.
  17265. @<CoolingTimerConfWidget implementation@>=
  17266. CoolingTimerConfWidget::CoolingTimerConfWidget(DeviceTreeModel *model,
  17267. const QModelIndex &index)
  17268. : BasicDeviceConfigurationWidget(model, index)
  17269. {
  17270. QHBoxLayout *layout = new QHBoxLayout;
  17271. QLabel *label = new QLabel(tr("Cooling Time: "));
  17272. QTimeEdit *editor = new QTimeEdit;
  17273. editor->setDisplayFormat("mm:ss");
  17274. @<Get device configuration data for current node@>@;
  17275. for(int i = 0; i < configData.size(); i++)
  17276. {
  17277. node = configData.at(i).toElement();
  17278. if(node.attribute("name") == "reset")
  17279. {
  17280. editor->setTime(QTime::fromString(node.attribute("value"), "mm:ss"));
  17281. }
  17282. }
  17283. updateResetTime(editor->time());
  17284. connect(editor, SIGNAL(timeChanged(QTime)),
  17285. this, SLOT(updateResetTime(QTime)));
  17286. layout->addWidget(label);
  17287. layout->addWidget(editor);
  17288. setLayout(layout);
  17289. }
  17290. void CoolingTimerConfWidget::updateResetTime(QTime time)
  17291. {
  17292. updateAttribute("reset", time.toString("mm:ss"));
  17293. }
  17294. @ The widget is registered with the configuration system.
  17295. @<Register device configuration widgets@>=
  17296. app.registerDeviceConfigurationWidget("coolingtimer",
  17297. CoolingTimerConfWidget::staticMetaObject);
  17298. @ The implementation chunk for now is in the main source file.
  17299. @<Class implementations@>=
  17300. @<CoolingTimerConfWidget implementation@>
  17301. @ The other two timer types are intended for measuring ranges of interest
  17302. within a batch. These have more configuration options. First is the range
  17303. timer. Someone setting this up needs to decide how the timer is started.
  17304. Sensible options include starting the timer at the start of the batch,
  17305. starting the timer when a button is pressed, or starting the timer when a set
  17306. point is reached on the ascent of a named data series. Stopping the timer is
  17307. also a configurable concern. This will be stopped at the end of the batch,
  17308. but it might be stopped sooner on reaching some threshold or when a button is
  17309. pressed. There are also questions of how the information is persisted with the
  17310. roasting records.
  17311. @<Class declarations@>=
  17312. class RangeTimerConfWidget : public BasicDeviceConfigurationWidget
  17313. {
  17314. @[Q_OBJECT@]@;
  17315. public:@/
  17316. @[Q_INVOKABLE@]@, RangeTimerConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  17317. @[private slots@]:@/
  17318. void updateStartButtonText(const QString &text);
  17319. void updateStopButtonText(const QString &text);
  17320. void updateStartColumnName(const QString &text);
  17321. void updateStopColumnName(const QString &text);
  17322. void updateStartValue(const QString &text);
  17323. void updateStopValue(const QString &text);
  17324. void updateStartTrigger(int option);
  17325. void updateStopTrigger(int option);
  17326. };
  17327. @ The constructor sets up controls for configuring these details.
  17328. @<RangeTimerConfWidget implementation@>=
  17329. RangeTimerConfWidget::RangeTimerConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  17330. : BasicDeviceConfigurationWidget(model, index)
  17331. {
  17332. QVBoxLayout *layout = new QVBoxLayout;
  17333. QGroupBox *startConfigurationGroup = new QGroupBox(tr("Start trigger"));
  17334. QRadioButton *startBatchOption = new QRadioButton(tr("Start of batch"));
  17335. QRadioButton *buttonOption = new QRadioButton(tr("Manual"));
  17336. QRadioButton *thresholdOption = new QRadioButton(tr("At temperature"));
  17337. QButtonGroup *startOptionGroup = new QButtonGroup;
  17338. startOptionGroup->addButton(startBatchOption, 1);
  17339. startOptionGroup->addButton(buttonOption, 2);
  17340. startOptionGroup->addButton(thresholdOption, 3);
  17341. startBatchOption->setChecked(true);
  17342. QGridLayout *startOptions = new QGridLayout;
  17343. startOptions->addWidget(startBatchOption, 0, 0);
  17344. startOptions->addWidget(buttonOption, 1, 0);
  17345. startOptions->addWidget(thresholdOption, 2, 0);
  17346. QLabel *buttonTextLabel = new QLabel(tr("Button Text: "));
  17347. QLineEdit *buttonTextEdit = new QLineEdit;
  17348. QHBoxLayout *buttonTextOptions = new QHBoxLayout;
  17349. buttonTextOptions->addWidget(buttonTextLabel);
  17350. buttonTextOptions->addWidget(buttonTextEdit);
  17351. startOptions->addLayout(buttonTextOptions, 1, 1);
  17352. QFormLayout *thresholdOptions = new QFormLayout;
  17353. QLineEdit *startColumnName = new QLineEdit;
  17354. QLineEdit *startValue = new QLineEdit;
  17355. thresholdOptions->addRow(tr("Column Name: "), startColumnName);
  17356. thresholdOptions->addRow(tr("Value: "), startValue);
  17357. startOptions->addLayout(thresholdOptions, 2, 1);
  17358. startConfigurationGroup->setLayout(startOptions);
  17359. layout->addWidget(startConfigurationGroup);
  17360. QGroupBox *stopConfigurationGroup = new QGroupBox(tr("Stop trigger"));
  17361. QRadioButton *stopBatchOption = new QRadioButton(tr("End of batch"));
  17362. QRadioButton *stopButtonOption = new QRadioButton(tr("Manual"));
  17363. QRadioButton *stopThresholdOption = new QRadioButton(tr("At temperature"));
  17364. QButtonGroup *stopOptionGroup = new QButtonGroup;
  17365. stopOptionGroup->addButton(stopBatchOption, 1);
  17366. stopOptionGroup->addButton(stopButtonOption, 2);
  17367. stopOptionGroup->addButton(stopThresholdOption, 3);
  17368. stopBatchOption->setChecked(true);
  17369. QGridLayout *stopOptions = new QGridLayout;
  17370. stopOptions->addWidget(stopBatchOption, 0, 0);
  17371. stopOptions->addWidget(stopButtonOption, 1, 0);
  17372. stopOptions->addWidget(stopThresholdOption, 2, 0);
  17373. QLabel *stopButtonLabel = new QLabel(tr("Button Text: "));
  17374. QLineEdit *stopButtonEdit = new QLineEdit;
  17375. QHBoxLayout *stopButtonTextOptions = new QHBoxLayout;
  17376. stopButtonTextOptions->addWidget(stopButtonLabel);
  17377. stopButtonTextOptions->addWidget(stopButtonEdit);
  17378. stopOptions->addLayout(stopButtonTextOptions, 1, 1);
  17379. QLineEdit *stopColumnName = new QLineEdit;
  17380. QLineEdit *stopValue = new QLineEdit;
  17381. QFormLayout *stopThresholdOptions = new QFormLayout;
  17382. stopThresholdOptions->addRow(tr("Column Name: "), stopColumnName);
  17383. stopThresholdOptions->addRow(tr("Value: "), stopValue);
  17384. stopOptions->addLayout(stopThresholdOptions, 2, 1);
  17385. stopConfigurationGroup->setLayout(stopOptions);
  17386. layout->addWidget(stopConfigurationGroup);
  17387. @<Get device configuration data for current node@>@;
  17388. for(int i = 0; i < configData.size(); i++)
  17389. {
  17390. node = configData.at(i).toElement();
  17391. if(node.attribute("name") == "startbuttontext")
  17392. {
  17393. buttonTextEdit->setText(node.attribute("value"));
  17394. }
  17395. else if(node.attribute("name") == "stopbuttontext")
  17396. {
  17397. stopButtonEdit->setText(node.attribute("value"));
  17398. }
  17399. else if(node.attribute("name") == "startcolumnname")
  17400. {
  17401. startColumnName->setText(node.attribute("value"));
  17402. }
  17403. else if(node.attribute("name") == "stopcolumnname")
  17404. {
  17405. stopColumnName->setText(node.attribute("value"));
  17406. }
  17407. else if(node.attribute("name") == "startvalue")
  17408. {
  17409. startValue->setText(node.attribute("value"));
  17410. }
  17411. else if(node.attribute("name") == "stopvalue")
  17412. {
  17413. stopValue->setText(node.attribute("value"));
  17414. }
  17415. else if(node.attribute("name") == "starttrigger")
  17416. {
  17417. if(node.attribute("value") == "batch")
  17418. {
  17419. startBatchOption->setChecked(true);
  17420. }
  17421. else if(node.attribute("value") == "manual")
  17422. {
  17423. buttonOption->setChecked(true);
  17424. }
  17425. else if(node.attribute("value") == "value")
  17426. {
  17427. thresholdOption->setChecked(true);
  17428. }
  17429. }
  17430. else if(node.attribute("name") == "stoptrigger")
  17431. {
  17432. if(node.attribute("value") == "batch")
  17433. {
  17434. stopBatchOption->setChecked(true);
  17435. }
  17436. else if(node.attribute("value") == "manual")
  17437. {
  17438. stopButtonOption->setChecked(true);
  17439. }
  17440. else if(node.attribute("value") == "value")
  17441. {
  17442. stopThresholdOption->setChecked(true);
  17443. }
  17444. }
  17445. }
  17446. updateStartButtonText(buttonTextEdit->text());
  17447. updateStopButtonText(stopButtonEdit->text());
  17448. updateStartColumnName(startColumnName->text());
  17449. updateStopColumnName(stopColumnName->text());
  17450. updateStartValue(startValue->text());
  17451. updateStopValue(stopValue->text());
  17452. updateStartTrigger(startOptionGroup->checkedId());
  17453. updateStopTrigger(stopOptionGroup->checkedId());
  17454. setLayout(layout);
  17455. connect(buttonTextEdit, SIGNAL(textChanged(QString)),
  17456. this, SLOT(updateStartButtonText(QString)));
  17457. connect(stopButtonEdit, SIGNAL(textChanged(QString)),
  17458. this, SLOT(updateStopButtonText(QString)));
  17459. connect(startColumnName, SIGNAL(textChanged(QString)),
  17460. this, SLOT(updateStartColumnName(QString)));
  17461. connect(stopColumnName, SIGNAL(textChanged(QString)),
  17462. this, SLOT(updateStopColumnName(QString)));
  17463. connect(startValue, SIGNAL(textChanged(QString)),
  17464. this, SLOT(updateStartValue(QString)));
  17465. connect(stopValue, SIGNAL(textChanged(QString)),
  17466. this, SLOT(updateStopValue(QString)));
  17467. connect(startOptionGroup, SIGNAL(buttonClicked(int)),
  17468. this, SLOT(updateStartTrigger(int)));
  17469. connect(stopOptionGroup, SIGNAL(buttonClicked(int)),
  17470. this, SLOT(updateStopTrigger(int)));
  17471. }
  17472. @ Small methods update the configuration as usual.
  17473. @<RangeTimerConfWidget implementation@>=
  17474. void RangeTimerConfWidget::updateStartButtonText(const QString &text)
  17475. {
  17476. updateAttribute("startbuttontext", text);
  17477. }
  17478. void RangeTimerConfWidget::updateStopButtonText(const QString &text)
  17479. {
  17480. updateAttribute("stopbuttontext", text);
  17481. }
  17482. void RangeTimerConfWidget::updateStartColumnName(const QString &text)
  17483. {
  17484. updateAttribute("startcolumnname", text);
  17485. }
  17486. void RangeTimerConfWidget::updateStopColumnName(const QString &text)
  17487. {
  17488. updateAttribute("stopcolumnname", text);
  17489. }
  17490. void RangeTimerConfWidget::updateStartValue(const QString &text)
  17491. {
  17492. updateAttribute("startvalue", text);
  17493. }
  17494. void RangeTimerConfWidget::updateStopValue(const QString &text)
  17495. {
  17496. updateAttribute("stopvalue", text);
  17497. }
  17498. void RangeTimerConfWidget::updateStartTrigger(int option)
  17499. {
  17500. switch(option)
  17501. {
  17502. case 1:
  17503. updateAttribute("starttrigger", "batch");
  17504. break;
  17505. case 2:
  17506. updateAttribute("starttrigger", "manual");
  17507. break;
  17508. case 3:
  17509. updateAttribute("starttrigger", "value");
  17510. break;
  17511. default:
  17512. break;
  17513. }
  17514. }
  17515. void RangeTimerConfWidget::updateStopTrigger(int option)
  17516. {
  17517. switch(option)
  17518. {
  17519. case 1:
  17520. updateAttribute("stoptrigger", "batch");
  17521. break;
  17522. case 2:
  17523. updateAttribute("stoptrigger", "manual");
  17524. break;
  17525. case 3:
  17526. updateAttribute("stoptrigger", "value");
  17527. break;
  17528. default:
  17529. break;
  17530. }
  17531. }
  17532. @ The widget is registered with the configuration system.
  17533. @<Register device configuration widgets@>=
  17534. app.registerDeviceConfigurationWidget("rangetimer",
  17535. RangeTimerConfWidget::staticMetaObject);
  17536. @ The implementation chunk for now is in the main source file.
  17537. @<Class implementations@>=
  17538. @<RangeTimerConfWidget implementation@>
  17539. @ The multirange timer is a little different. To keep configuration tractible,
  17540. this is slightly less general purpose than the range timer and only supports
  17541. automatic triggering on a single data series.
  17542. @<Class declarations@>=
  17543. class MultiRangeTimerConfWidget : public BasicDeviceConfigurationWidget
  17544. {
  17545. @[Q_OBJECT@]@/
  17546. public:@/
  17547. @[Q_INVOKABLE@]@, MultiRangeTimerConfWidget(DeviceTreeModel *model,
  17548. const QModelIndex &index);
  17549. @[private slots@]:@/
  17550. void updateColumnName(const QString &text);
  17551. void updateRangeData();
  17552. private:@/
  17553. SaltModel *tablemodel;
  17554. };
  17555. @ These limitations allow a rather small set of controls for configuration. A
  17556. line edit to specify the data series used for automatic triggering and a table
  17557. which specifies the name of the timed range and an ending temperature.
  17558. @<MultiRangeTimerConfWidget implementation@>=
  17559. MultiRangeTimerConfWidget::MultiRangeTimerConfWidget(DeviceTreeModel *model,
  17560. const QModelIndex &index)
  17561. : BasicDeviceConfigurationWidget(model, index), tablemodel(new SaltModel(2))
  17562. {
  17563. QFormLayout *layout = new QFormLayout;
  17564. QLineEdit *trigger = new QLineEdit;
  17565. layout->addRow(tr("Trigger column name:"), trigger);
  17566. tablemodel->setHeaderData(0, Qt::Horizontal, "Range Name");
  17567. tablemodel->setHeaderData(1, Qt::Horizontal, "End Temperature");
  17568. QTableView *rangeTable = new QTableView;
  17569. rangeTable->setModel(tablemodel);
  17570. layout->addRow(tr("Range data:"), rangeTable);
  17571. @<Get device configuration data for current node@>@;
  17572. for(int i = 0; i < configData.size(); i++)
  17573. {
  17574. node = configData.at(i).toElement();
  17575. if(node.attribute("name") == "trigger")
  17576. {
  17577. trigger->setText(node.attribute("value"));
  17578. }
  17579. else if(node.attribute("name") == "rangenames")
  17580. {
  17581. QString data = node.attribute("value");
  17582. if(data.length() > 3)
  17583. {
  17584. data.chop(2);
  17585. data = data.remove(0, 2);
  17586. }
  17587. QStringList itemList = data.split(", ");
  17588. for(int j = 0; j < itemList.size(); j++)
  17589. {
  17590. QString item = itemList.at(j);
  17591. item.chop(1);
  17592. item = item.remove(0, 1);
  17593. tablemodel->setData(tablemodel->index(j, 0),
  17594. QVariant(item), Qt::DisplayRole);
  17595. }
  17596. }
  17597. else if(node.attribute("name") == "endtemps")
  17598. {
  17599. @<Convert numeric array literal to list@>@;
  17600. int column = 1;
  17601. @<Populate model column from list@>@;
  17602. }
  17603. }
  17604. updateColumnName(trigger->text());
  17605. updateRangeData();
  17606. connect(trigger, SIGNAL(textEdited(QString)), this, SLOT(updateColumnName(QString)));
  17607. connect(tablemodel, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(updateRangeData()));
  17608. setLayout(layout);
  17609. }
  17610. @ The update mechanisms are reasonably straightforward. Table updates just
  17611. refresh the entire table instead of attempting to be clever about updating only
  17612. the element that changed.
  17613. @<MultiRangeTimerConfWidget implementation@>=
  17614. void MultiRangeTimerConfWidget::updateRangeData()
  17615. {
  17616. updateAttribute("rangenames", tablemodel->quotedArrayLiteral(0, Qt::DisplayRole));
  17617. updateAttribute("endtemps", tablemodel->arrayLiteral(1, Qt::DisplayRole));
  17618. }
  17619. void MultiRangeTimerConfWidget::updateColumnName(const QString &text)
  17620. {
  17621. updateAttribute("trigger", text);
  17622. }
  17623. @ The widget is registered with the configuration system.
  17624. @<Register device configuration widgets@>=
  17625. app.registerDeviceConfigurationWidget("multirangetimer",
  17626. MultiRangeTimerConfWidget::staticMetaObject);
  17627. @ The implementation is in the main source file.
  17628. @<Class implementations@>=
  17629. @<MultiRangeTimerConfWidget implementation@>
  17630. @* Profile Translation Configuration Widget.
  17631. \noindent Configuring profile translation requires knowing which column to use
  17632. for matching purposes and the value to match.
  17633. @<Class declarations@>=
  17634. class TranslationConfWidget : public BasicDeviceConfigurationWidget
  17635. {
  17636. @[Q_OBJECT@]@;
  17637. public:@/
  17638. @[Q_INVOKABLE@]@, TranslationConfWidget(DeviceTreeModel *model, const QModelIndex &index);
  17639. @[private slots@]:@/
  17640. void updateMatchingColumn(const QString &column);
  17641. void updateTemperature();
  17642. private:@/
  17643. QDoubleSpinBox *temperatureValue;
  17644. QComboBox *unitSelector;
  17645. };
  17646. @ The constructor sets up our user interface.
  17647. @<TranslationConfWidget implementation@>=
  17648. TranslationConfWidget::TranslationConfWidget(DeviceTreeModel *model, const QModelIndex &index)
  17649. : BasicDeviceConfigurationWidget(model, index),
  17650. temperatureValue(new QDoubleSpinBox), unitSelector(new QComboBox)
  17651. {
  17652. unitSelector->addItem("Fahrenheit");
  17653. unitSelector->addItem("Celsius");
  17654. temperatureValue->setMinimum(0);
  17655. temperatureValue->setMaximum(1000);
  17656. QFormLayout *layout = new QFormLayout;
  17657. QLineEdit *column = new QLineEdit;
  17658. layout->addRow(tr("Column to match:"), column);
  17659. layout->addRow(tr("Unit:"), unitSelector);
  17660. layout->addRow(tr("Value:"), temperatureValue);
  17661. @<Get device configuration data for current node@>@;
  17662. for(int i = 0; i < configData.size(); i++)
  17663. {
  17664. node = configData.at(i).toElement();
  17665. if(node.attribute("name") == "column")
  17666. {
  17667. column->setText(node.attribute("value"));
  17668. }
  17669. else if(node.attribute("name") == "unit")
  17670. {
  17671. unitSelector->setCurrentIndex(unitSelector->findText(node.attribute("value")));
  17672. }
  17673. else if(node.attribute("name") == "value")
  17674. {
  17675. temperatureValue->setValue(node.attribute("value").toDouble());
  17676. }
  17677. }
  17678. updateMatchingColumn(column->text());
  17679. updateTemperature();
  17680. connect(column, SIGNAL(textEdited(QString)), this, SLOT(updateMatchingColumn(QString)));
  17681. connect(unitSelector, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateTemperature()));
  17682. connect(temperatureValue, SIGNAL(valueChanged(double)), this, SLOT(updateTemperature()));
  17683. setLayout(layout);
  17684. }
  17685. @ To update the temperature at which to match we save both the values of the
  17686. two widgets which control this and the value in Fahrenheit so we don'@q'@>t need to
  17687. run unit conversions during view initialization.
  17688. @<TranslationConfWidget implementation@>=
  17689. void TranslationConfWidget::updateTemperature()
  17690. {
  17691. updateAttribute("unit", unitSelector->currentText());
  17692. updateAttribute("value", QString("%1").arg(temperatureValue->value()));
  17693. if(unitSelector->currentText() == "Fahrenheit")
  17694. {
  17695. updateAttribute("FValue", QString("%1").arg(temperatureValue->value()));
  17696. }
  17697. else
  17698. {
  17699. updateAttribute("FValue", QString("%1").arg(temperatureValue->value() * 9 / 5 + 32));
  17700. }
  17701. }
  17702. void TranslationConfWidget::updateMatchingColumn(const QString &column)
  17703. {
  17704. updateAttribute("column", column);
  17705. }
  17706. @ This is registered with the configuration system.
  17707. @<Register device configuration widgets@>=
  17708. app.registerDeviceConfigurationWidget("translation", TranslationConfWidget::staticMetaObject);
  17709. @i rate.w
  17710. @i dataqsdk.w
  17711. @i scales.w
  17712. @i valueannotation.w
  17713. @i thresholdannotation.w
  17714. @** Local changes.
  17715. \noindent This is the end of \pn{} as distributed by its author. It is expected
  17716. that some might have need of a program like \pn, but require some modification.
  17717. The patching capabilities of \cweb{} can be used to produce these local
  17718. modifications. This section is provided for those whose change requirements are
  17719. sufficiently extensive to require the introduction of new sections to the
  17720. program.
  17721. @** Index.
  17722. \noindent Following is a list of identifiers used in \pn, with underlined
  17723. entries pointing to where \cweb{} has guessed that the identifier was defined.
  17724. All references are to section numbers instead of page numbers.
  17725. \def\nullsec{--}