mainform.cpp 232 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278
  1. /*
  2. ktigcc - TIGCC IDE for KDE
  3. Copyright (C) 2004-2007 Kevin Kofler
  4. Copyright (C) 2006 Joey Adams
  5. Copyright (C) 2007 Konrad Meyer
  6. This program is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2, or (at your option)
  9. any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with this program; if not, write to the Free Software Foundation,
  16. Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  17. */
  18. #include <k3listview.h>
  19. class DnDListView : public K3ListView {
  20. private:
  21. public:
  22. DnDListView (QWidget * parent = 0) : K3ListView(parent) {}
  23. // Make my hand-coded drag&drop code work (public part).
  24. // Maybe the built-in drag&drop support in K3ListView could be made to work as
  25. // expected, but for now just bypass it to use the existing code I wrote for
  26. // QListView.
  27. virtual void takeItem(Q3ListViewItem *i) {Q3ListView::takeItem(i);}
  28. virtual void setAcceptDrops(bool on) {Q3ListView::setAcceptDrops(on);}
  29. protected:
  30. virtual Q3DragObject *dragObject();
  31. virtual void dropEvent (QDropEvent *e);
  32. virtual void dragEnterEvent (QDragEnterEvent *e);
  33. virtual void dragMoveEvent (QDragMoveEvent *e);
  34. // Make my hand-coded drag&drop code work (protected part).
  35. virtual void contentsDragMoveEvent(QDragMoveEvent *e) {
  36. Q3ListView::contentsDragMoveEvent(e);
  37. }
  38. virtual void contentsMouseMoveEvent(QMouseEvent *e) {
  39. Q3ListView::contentsMouseMoveEvent(e);
  40. }
  41. virtual void contentsDragLeaveEvent(QDragLeaveEvent *e) {
  42. Q3ListView::contentsDragLeaveEvent(e);
  43. }
  44. virtual void contentsDropEvent(QDropEvent *e) {
  45. Q3ListView::contentsDropEvent(e);
  46. }
  47. virtual void contentsDragEnterEvent(QDragEnterEvent *e) {
  48. Q3ListView::contentsDragEnterEvent(e);
  49. }
  50. virtual void startDrag() {
  51. Q3ListView::startDrag();
  52. }
  53. virtual void rename(Q3ListViewItem *item, int c);
  54. virtual void keyPressEvent(QKeyEvent *e);
  55. };
  56. // Yes, this is an ugly hack... Any better suggestions?
  57. #define K3ListView DnDListView
  58. #include "mainform.h"
  59. #undef K3ListView
  60. #include <QVariant>
  61. #include <QHash>
  62. #include <QImage>
  63. #include <QString>
  64. #include <QStringList>
  65. #include <QByteArray>
  66. #include <QPair>
  67. #include <QRegExp>
  68. #include <QApplication>
  69. #include <QLabel>
  70. #include <QStatusBar>
  71. #include <QTimer>
  72. #include <QDateTime>
  73. #include <Q3DragObject>
  74. #include <QDir>
  75. #include <QClipboard>
  76. #include <QShortcut>
  77. #include <QEventLoop>
  78. #include <QCoreApplication>
  79. #include <QDockWidget>
  80. #include <QFileInfo>
  81. #include <QDateTime>
  82. #include <QTextCodec>
  83. #include <QTextDocument>
  84. #include <QTimer>
  85. #include <QToolButton>
  86. #include <Q3ListBox>
  87. #include <QTimerEvent>
  88. #include <Q3PtrList>
  89. #include <QList>
  90. #include <QVector>
  91. #include <QDragMoveEvent>
  92. #include <QDragLeaveEvent>
  93. #include <QKeyEvent>
  94. #include <QResizeEvent>
  95. #include <QEvent>
  96. #include <QDropEvent>
  97. #include <Q3PopupMenu>
  98. #include <QDragEnterEvent>
  99. #include <QPixmap>
  100. #include <QMouseEvent>
  101. #include <QCloseEvent>
  102. #include <QAssistantClient>
  103. #include <QDBusConnection>
  104. #include <QDBusReply>
  105. #include <kapplication.h>
  106. #include <kparts/factory.h>
  107. #include <klibloader.h>
  108. #include <ktexteditor/editor.h>
  109. #include <ktexteditor/document.h>
  110. #include <ktexteditor/view.h>
  111. #include <ktexteditor/cursor.h>
  112. #include <ktexteditor/range.h>
  113. #include <ktexteditor/smartcursor.h>
  114. #include <ktexteditor/smartinterface.h>
  115. #include <ktexteditor/commandinterface.h>
  116. #include <ktexteditor/configinterface.h>
  117. #include <kconfig.h>
  118. #include <kconfiggroup.h>
  119. #include <ktexteditor/configpage.h>
  120. #include <kaboutdata.h>
  121. #include <khelpmenu.h>
  122. #include <kfiledialog.h>
  123. #include <kurl.h>
  124. #include <kmessagebox.h>
  125. #include <kdirwatch.h>
  126. #include <kfinddialog.h>
  127. #include <kfind.h>
  128. #include <kreplacedialog.h>
  129. #include <kreplace.h>
  130. #include <kglobal.h>
  131. #include <kicontheme.h>
  132. #include <kicon.h>
  133. #include <kiconloader.h>
  134. #include <kprocess.h>
  135. #include <kshell.h>
  136. #include <ktextbrowser.h>
  137. #include <krun.h>
  138. #include <kpushbutton.h>
  139. #include <kmacroexpander.h>
  140. #include <kstandardaction.h>
  141. #include <cstdio>
  142. #include <cstdlib>
  143. #include <cstring>
  144. #include <unistd.h>
  145. #include <glib.h>
  146. #include <ticonv.h>
  147. #include <ticables.h>
  148. #include <tifiles.h>
  149. #include <ticalcs.h>
  150. #include "ktigcc.h"
  151. #include "srcfilewin.h"
  152. #include "tpr.h"
  153. #include "preferences.h"
  154. #include "projectoptions.h"
  155. #include "errorlist.h"
  156. #include "programoutput.h"
  157. #include "tiemu.h"
  158. #include "callbacks.h"
  159. #include "parsing.h"
  160. #include "functions.h"
  161. #include "toolsdlg.h"
  162. #include "newsdlg.h"
  163. #include "completion.h"
  164. #if defined(Q_WS_X11)
  165. #include <kwindowsystem.h>
  166. #define ACTIVATE_WINDOW(winid) KWindowSystem::activateWindow(winid)
  167. #elif defined(Q_WS_WIN)
  168. #include <windows.h>
  169. #define ACTIVATE_WINDOW(winid) SetForegroundWindow(winid)
  170. #else
  171. #define ACTIVATE_WINDOW(winid) ((void)0)
  172. #endif
  173. using std::puts;
  174. using std::exit;
  175. #define TIGCC_TPR_Filter "*.tpr|TIGCC Projects (*.tpr)\n"
  176. #define TIGCC_H_Filter "*.h|Header Files (*.h)\n"
  177. #define TIGCC_C_Filter "*.c|C Files (*.c)\n"
  178. #define TIGCC_S_Filter "*.s|GNU Assembly Files (*.s)\n"
  179. #define TIGCC_ASM_Filter "*.asm|A68k Assembly Files (*.asm)\n"
  180. #define TIGCC_QLL_Filter "*.qll|Quill Files (*.qll)\n"
  181. #define TIGCC_O_Filter "*.o|Object Files (*.o)\n"
  182. #define TIGCC_A_Filter "*.a|Archive Files (*.a)\n"
  183. #define TIGCC_TXT_Filter "*.txt|Text Files (*.txt)\n"
  184. #define TIGCCAllFilter "*|All Files (*)"
  185. enum {TIGCCOpenProjectFileFilter,TIGCCAddFilesFilter};
  186. #define IS_CATEGORY(item) ((item) && ((item)==hFilesListItem \
  187. || (item)==cFilesListItem \
  188. || (item)==sFilesListItem \
  189. || (item)==asmFilesListItem \
  190. || (item)==qllFilesListItem \
  191. || (item)==oFilesListItem \
  192. || (item)==aFilesListItem \
  193. || (item)==txtFilesListItem \
  194. || (item)==othFilesListItem))
  195. #define IS_EDITABLE_CATEGORY(item) ((item) && ((item)==hFilesListItem \
  196. || (item)==cFilesListItem \
  197. || (item)==sFilesListItem \
  198. || (item)==asmFilesListItem \
  199. || (item)==qllFilesListItem \
  200. || (item)==txtFilesListItem))
  201. #define IS_FOLDER(item) ((item) && (item)->rtti()==0x716CC0)
  202. #define IS_FILE(item) ((item) && (item)->rtti()==0x716CC1)
  203. #define CATEGORY_OF(category,item) Q3ListViewItem *category=(item); \
  204. while (category->parent()->rtti()==0x716CC0) \
  205. category=category->parent()
  206. #define COUNTER_FOR_CATEGORY(category) ((category)==hFilesListItem?hFileCount: \
  207. (category)==cFilesListItem?cFileCount: \
  208. (category)==sFilesListItem?sFileCount: \
  209. (category)==asmFilesListItem?asmFileCount: \
  210. (category)==qllFilesListItem?qllFileCount: \
  211. (category)==oFilesListItem?oFileCount: \
  212. (category)==aFilesListItem?aFileCount: \
  213. (category)==txtFilesListItem?txtFileCount: \
  214. othFileCount)
  215. #define CURRENT_VIEW (static_cast<KTextEditor::View *>(widgetStack->visibleWidget()))
  216. #define SYSICON(sysname,name) (preferences.useSystemIcons?KIconLoader::global()->loadIcon((sysname),KIconLoader::Small,KIconLoader::SizeSmall):QPixmap(":/images/" name))
  217. #define SET_TEXT_SAFE(doc,text) do { \
  218. disableViewEvents=TRUE; \
  219. (doc)->setText((text)); \
  220. disableViewEvents=FALSE; \
  221. } while(0)
  222. static Q3ListViewItem *currentListItem;
  223. static Q3ListViewItem *replaceCurrentDocument;
  224. static int replaceCurrentLine;
  225. static bool compiling;
  226. class KReplaceWithSelection : public KReplace {
  227. public:
  228. KReplaceWithSelection(const QString &pattern, const QString &replacement,
  229. long options, QWidget *parent=0) :
  230. KReplace(pattern,replacement,options,parent), m_haveSelection(FALSE) {}
  231. void setSelection(int selStartLine, int selStartCol,
  232. int selEndLine, int selEndCol)
  233. {
  234. m_haveSelection=TRUE;
  235. m_selStartLine=selStartLine;
  236. m_selStartCol=selStartCol;
  237. m_selEndLine=selEndLine;
  238. m_selEndCol=selEndCol;
  239. }
  240. void setSelection(const KTextEditor::Range &selRange)
  241. {
  242. m_haveSelection=TRUE;
  243. selRange.start().position(m_selStartLine,m_selStartCol);
  244. selRange.end().position(m_selEndLine,m_selEndCol);
  245. }
  246. void invalidateSelection() {m_haveSelection=FALSE;}
  247. bool haveSelection() {
  248. // If another document was put under the cursor, invalidate selection.
  249. // The m_haveSelection&& is technically redundant, but necessary to avoid
  250. // possible undefined behavior if replaceCurrentDocument has been deleted.
  251. if (m_haveSelection&&currentListItem!=replaceCurrentDocument)
  252. m_haveSelection=FALSE;
  253. return m_haveSelection;
  254. }
  255. int selStartLine() {return m_selStartLine;}
  256. int selStartCol() {return m_selStartCol;}
  257. int selEndLine() {return m_selEndLine;}
  258. int selEndCol() {return m_selEndCol;}
  259. // Override to ask for restarting when replacing in a selection.
  260. bool shouldRestart(bool forceAsking=FALSE, bool showNumMatches=TRUE)
  261. {
  262. return KReplace::shouldRestart(forceAsking||m_haveSelection,showNumMatches);
  263. }
  264. protected:
  265. virtual bool validateMatch(const QString &text, int index, int matchedlength)
  266. {
  267. if (!KReplace::validateMatch(text,index,matchedlength)) return FALSE;
  268. // If another document was put under the cursor, invalidate selection.
  269. // The m_haveSelection&& is technically redundant, but necessary to avoid
  270. // possible undefined behavior if replaceCurrentDocument has been deleted.
  271. if (m_haveSelection&&currentListItem!=replaceCurrentDocument)
  272. m_haveSelection=FALSE;
  273. if (!m_haveSelection) return TRUE;
  274. if (replaceCurrentLine==m_selStartLine && replaceCurrentLine==m_selEndLine)
  275. return (index>=m_selStartCol)&&(index+matchedlength<=m_selEndCol);
  276. else if (replaceCurrentLine==m_selStartLine)
  277. return (index>=m_selStartCol);
  278. else if (replaceCurrentLine==m_selEndLine)
  279. return (index+matchedlength<=m_selEndCol);
  280. else
  281. return (replaceCurrentLine>=m_selStartLine&&replaceCurrentLine<=m_selEndLine);
  282. }
  283. private:
  284. bool m_haveSelection;
  285. int m_selStartLine, m_selStartCol, m_selEndLine, m_selEndCol;
  286. };
  287. static KReplaceWithSelection *kreplace;
  288. // All the methods are inline because otherwise QT Designer will mistake them
  289. // for slots of the main form.
  290. class ListViewFolder : public K3ListViewItem {
  291. public:
  292. ListViewFolder(Q3ListView *parent) : K3ListViewItem(parent)
  293. {
  294. setPixmap(0,SYSICON("folder","folder1.png"));
  295. setDragEnabled(TRUE);
  296. setDropEnabled(TRUE);
  297. }
  298. ListViewFolder(Q3ListViewItem *parent) : K3ListViewItem(parent)
  299. {
  300. setPixmap(0,SYSICON("folder","folder1.png"));
  301. setDragEnabled(TRUE);
  302. setDropEnabled(TRUE);
  303. }
  304. ListViewFolder(Q3ListView *parent, Q3ListViewItem *after)
  305. : K3ListViewItem(parent, after)
  306. {
  307. setPixmap(0,SYSICON("folder","folder1.png"));
  308. setDropEnabled(TRUE);
  309. setDragEnabled(TRUE);
  310. }
  311. ListViewFolder(Q3ListViewItem *parent, Q3ListViewItem *after)
  312. : K3ListViewItem(parent, after)
  313. {
  314. setPixmap(0,SYSICON("folder","folder1.png"));
  315. setDragEnabled(TRUE);
  316. setDropEnabled(TRUE);
  317. }
  318. virtual int rtti(void) const {return 0x716CC0;}
  319. // Work around gratuitous API difference. Why do I have to do this? That's
  320. // what startRename is a virtual method for. K3ListViewItem should do this.
  321. virtual void startRename(int col)
  322. {
  323. static_cast<K3ListView *>(listView())->rename(this,col);
  324. }
  325. protected:
  326. };
  327. class ListViewFile : public K3ListViewItem {
  328. public:
  329. ListViewFile(Q3ListView *parent) : K3ListViewItem(parent),
  330. kateView(NULL), isNew(TRUE),
  331. modifiedSinceLastCompile(TRUE)
  332. {
  333. setPixmap(0,SYSICON("unknown","filex.png"));
  334. setDragEnabled(TRUE);
  335. setDropEnabled(TRUE);
  336. setRenameEnabled(0,TRUE);
  337. }
  338. ListViewFile(Q3ListViewItem *parent) : K3ListViewItem(parent),
  339. kateView(NULL), isNew(TRUE),
  340. modifiedSinceLastCompile(TRUE)
  341. {
  342. setPixmap(0,SYSICON("unknown","filex.png"));
  343. setDragEnabled(TRUE);
  344. setDropEnabled(TRUE);
  345. setRenameEnabled(0,TRUE);
  346. }
  347. ListViewFile(Q3ListView *parent, Q3ListViewItem *after)
  348. : K3ListViewItem(parent, after), kateView(NULL), isNew(TRUE),
  349. modifiedSinceLastCompile(TRUE)
  350. {
  351. setPixmap(0,SYSICON("unknown","filex.png"));
  352. setDropEnabled(TRUE);
  353. setDragEnabled(TRUE);
  354. setRenameEnabled(0,TRUE);
  355. }
  356. ListViewFile(Q3ListViewItem *parent, Q3ListViewItem *after)
  357. : K3ListViewItem(parent, after), kateView(NULL),
  358. isNew(TRUE), modifiedSinceLastCompile(TRUE)
  359. {
  360. setPixmap(0,SYSICON("unknown","filex.png"));
  361. setDragEnabled(TRUE);
  362. setDropEnabled(TRUE);
  363. setRenameEnabled(0,TRUE);
  364. }
  365. virtual ~ListViewFile()
  366. {
  367. MainForm::deleteErrorsForLVFile(this);
  368. if (kreplace && replaceCurrentDocument==this) {
  369. replaceCurrentDocument=static_cast<Q3ListViewItem *>(NULL);
  370. kreplace->invalidateSelection();
  371. }
  372. if (!fileName.isEmpty() && fileName[0]=='/')
  373. KDirWatch::self()->removeFile(fileName);
  374. if (kateView) {
  375. KTextEditor::Document *doc=kateView->document();
  376. delete kateView;
  377. delete doc;
  378. }
  379. }
  380. virtual int rtti(void) const {return 0x716CC1;}
  381. KTextEditor::View *kateView;
  382. QString fileName; // full name of the file
  383. bool isNew;
  384. bool modifiedSinceLastCompile;
  385. LineStartList lineStartList;
  386. // Work around gratuitous API difference. Why do I have to do this? That's
  387. // what startRename is a virtual method for. K3ListViewItem should do this.
  388. virtual void startRename(int col)
  389. {
  390. static_cast<K3ListView *>(listView())->rename(this,col);
  391. }
  392. protected:
  393. };
  394. class ListViewRoot : public K3ListViewItem {
  395. public:
  396. ListViewRoot(Q3ListView *parent) : K3ListViewItem(parent)
  397. {
  398. setRenameEnabled(0,TRUE);
  399. // dragging not really allowed, but don't let the cursor run around when dragged
  400. setDragEnabled(TRUE);
  401. }
  402. ListViewRoot(Q3ListViewItem *parent) : K3ListViewItem(parent)
  403. {
  404. setRenameEnabled(0,TRUE);
  405. // dragging not really allowed, but don't let the cursor run around when dragged
  406. setDragEnabled(TRUE);
  407. }
  408. ListViewRoot(Q3ListView *parent, Q3ListViewItem *after)
  409. : K3ListViewItem(parent, after)
  410. {
  411. setRenameEnabled(0,TRUE);
  412. // dragging not really allowed, but don't let the cursor run around when dragged
  413. setDragEnabled(TRUE);
  414. }
  415. ListViewRoot(Q3ListViewItem *parent, Q3ListViewItem *after)
  416. : K3ListViewItem(parent, after)
  417. {
  418. setRenameEnabled(0,TRUE);
  419. // dragging not really allowed, but don't let the cursor run around when dragged
  420. setDragEnabled(TRUE);
  421. }
  422. // Work around gratuitous API difference. Why do I have to do this? That's
  423. // what startRename is a virtual method for. K3ListViewItem should do this.
  424. virtual void startRename(int col)
  425. {
  426. static_cast<K3ListView *>(listView())->rename(this,col);
  427. }
  428. protected:
  429. };
  430. // These should be instance variables in clean C++, but QT Designer won't let me
  431. // touch the class definition, so this is all I can do. And there is only one
  432. // instance of MainForm anyway.
  433. static Q3ListViewItem *rootListItem;
  434. static Q3ListViewItem *hFilesListItem;
  435. static Q3ListViewItem *cFilesListItem;
  436. static Q3ListViewItem *sFilesListItem;
  437. static Q3ListViewItem *asmFilesListItem;
  438. static Q3ListViewItem *qllFilesListItem;
  439. static Q3ListViewItem *oFilesListItem;
  440. static Q3ListViewItem *aFilesListItem;
  441. static Q3ListViewItem *txtFilesListItem;
  442. static Q3ListViewItem *othFilesListItem;
  443. static bool projectIsDirty, projectNeedsRelink;
  444. static QLabel *leftStatusLabel;
  445. static QLabel *rowStatusLabel;
  446. static QLabel *colStatusLabel;
  447. static QLabel *charsStatusLabel;
  448. static QLabel *rightStatusLabel;
  449. static KHelpMenu *khelpmenu;
  450. static Q3PopupMenu *te_popup;
  451. static bool headersModified;
  452. static QDockWidget *errorListDock;
  453. static ErrorList *errorList;
  454. static unsigned errorCountTotal=0,errorCountErrors=0,errorCountWarnings=0;
  455. static QString programOutput;
  456. QAssistantClient *assistant;
  457. static unsigned fileCount=0, hFileCount=0, cFileCount=0, sFileCount=0, asmFileCount=0, qllFileCount=0, oFileCount=0, aFileCount=0, txtFileCount=0, othFileCount=0;
  458. tprSettings settings;
  459. tprLibOpts libopts;
  460. static QString projectFileName;
  461. static QString lastDirectory;
  462. QClipboard *clipboard;
  463. static QShortcut *shortcuts[18];
  464. static KFindDialog *kfinddialog;
  465. QStringList findHistory, replacementHistory;
  466. static Q3ListViewItem *findCurrentDocument;
  467. static int findCurrentLine;
  468. QList<SourceFileWindow *> sourceFiles;
  469. static Q3PopupMenu *findFunctionsPopup;
  470. bool have_usb;
  471. Tools tools, tempTools;
  472. int toolIndex;
  473. bool disableViewEvents=FALSE;
  474. Q3DragObject *DnDListView::dragObject() {
  475. Q3ListViewItem *currItem=selectedItem();
  476. if (currItem==rootListItem || currItem->parent()==rootListItem)
  477. return NULL;
  478. Q3StoredDrag *storedDrag=new Q3StoredDrag("x-ktigcc-dnd", this);
  479. static QByteArray data(sizeof(Q3ListViewItem*));
  480. data.duplicate(reinterpret_cast<char *>(&currItem),
  481. sizeof(Q3ListViewItem*));
  482. storedDrag->setEncodedData(data);
  483. return storedDrag;
  484. }
  485. void DnDListView::dropEvent(QDropEvent *e) {
  486. if (!compiling && e->source()==this && e->provides("x-ktigcc-dnd")) {
  487. Q3ListViewItem *currItem;
  488. currItem = *reinterpret_cast<Q3ListViewItem * const *>((const char *)e->encodedData("x-ktigcc-dnd"));
  489. if (IS_FOLDER(currItem) && !IS_CATEGORY(currItem)) {
  490. // dropping folder
  491. // can only drop on folder or category
  492. Q3ListViewItem *item=itemAt(e->pos());
  493. if (IS_FOLDER(item)) {
  494. // need same category
  495. CATEGORY_OF(srcCategory,currItem);
  496. CATEGORY_OF(destCategory,item);
  497. if (srcCategory == destCategory) {
  498. // can't move folder into itself
  499. for (Q3ListViewItem *destFolder=item; IS_FOLDER(destFolder); destFolder=destFolder->parent()) {
  500. if (destFolder==currItem) goto ignore;
  501. }
  502. // move folder
  503. e->accept();
  504. currItem->parent()->takeItem(currItem);
  505. item->insertItem(currItem);
  506. // put it at the right place
  507. if (currItem->nextSibling()) {
  508. Q3ListViewItem *lastItem=currItem->nextSibling();
  509. while(lastItem->nextSibling())
  510. lastItem=lastItem->nextSibling();
  511. currItem->moveItem(lastItem);
  512. }
  513. projectIsDirty=TRUE;
  514. projectNeedsRelink=TRUE;
  515. } else {ignore: e->ignore();}
  516. } else e->ignore();
  517. } else if (IS_FILE(currItem)) {
  518. // dropping file
  519. Q3ListViewItem *item=itemAt(e->pos());
  520. if (IS_FOLDER(item)) {
  521. // drop on folder
  522. // don't allow more than one Quill file per project
  523. CATEGORY_OF(srcCategory,currItem);
  524. CATEGORY_OF(destCategory,item);
  525. if (qllFilesListItem && srcCategory != qllFilesListItem
  526. && destCategory == qllFilesListItem && qllFileCount) {
  527. ignore2: e->ignore();
  528. } else {
  529. // moving from editable to non-editable category -
  530. // prompt for saving
  531. if (IS_EDITABLE_CATEGORY(srcCategory)
  532. && !IS_EDITABLE_CATEGORY(destCategory)) {
  533. if (static_cast<MainForm *>(parent()->parent()->parent())->fileSavePrompt(currItem))
  534. goto ignore2;
  535. if (!static_cast<ListViewFile *>(currItem)->fileName.isEmpty()
  536. && static_cast<ListViewFile *>(currItem)->fileName[0]=='/')
  537. KDirWatch::self()->removeFile(static_cast<ListViewFile *>(currItem)->fileName);
  538. }
  539. // moving from non-editable to editable category
  540. if (!IS_EDITABLE_CATEGORY(srcCategory)
  541. && IS_EDITABLE_CATEGORY(destCategory)) {
  542. static_cast<ListViewFile *>(currItem)->kateView=reinterpret_cast<KTextEditor::View *>(static_cast<MainForm *>(parent()->parent()->parent())->createView(static_cast<ListViewFile *>(currItem)->fileName,QString::null,destCategory));
  543. MainForm::createErrorCursorsForSourceFile(currItem);
  544. // force reloading the text buffer
  545. if (currentListItem==currItem)
  546. currentListItem=NULL;
  547. }
  548. // move file
  549. e->accept();
  550. currItem->parent()->takeItem(currItem);
  551. COUNTER_FOR_CATEGORY(srcCategory)--;
  552. item->insertItem(currItem);
  553. COUNTER_FOR_CATEGORY(destCategory)++;
  554. // put it at the right place
  555. if (IS_FILE(currItem->nextSibling())) {
  556. Q3ListViewItem *lastItem=currItem->nextSibling();
  557. while(IS_FILE(lastItem->nextSibling()))
  558. lastItem=lastItem->nextSibling();
  559. currItem->moveItem(lastItem);
  560. }
  561. projectIsDirty=TRUE;
  562. projectNeedsRelink=TRUE;
  563. setSelected(currItem,TRUE);
  564. ensureItemVisible(currItem);
  565. // update editor and counters
  566. static_cast<MainForm *>(parent()->parent()->parent())->fileTreeClicked(currItem);
  567. // moving from non-editable to editable category
  568. if (!IS_EDITABLE_CATEGORY(srcCategory)
  569. && IS_EDITABLE_CATEGORY(destCategory)) {
  570. if (!static_cast<ListViewFile *>(currItem)->fileName.isEmpty()
  571. && static_cast<ListViewFile *>(currItem)->fileName[0]=='/')
  572. KDirWatch::self()->addFile(static_cast<ListViewFile *>(currItem)->fileName);
  573. }
  574. // moving from editable to non-editable category
  575. if (IS_EDITABLE_CATEGORY(srcCategory)
  576. && !IS_EDITABLE_CATEGORY(destCategory)) {
  577. KTextEditor::Document *doc=static_cast<ListViewFile *>(currItem)->kateView->document();
  578. delete static_cast<ListViewFile *>(currItem)->kateView;
  579. delete doc;
  580. static_cast<ListViewFile *>(currItem)->kateView=NULL;
  581. }
  582. // moving from editable to editable category
  583. if (IS_EDITABLE_CATEGORY(srcCategory)
  584. && IS_EDITABLE_CATEGORY(destCategory)
  585. && srcCategory!=destCategory) {
  586. // update highlighting mode
  587. QString fileText=static_cast<ListViewFile *>(currItem)->kateView->document()->text();
  588. static_cast<ListViewFile *>(currItem)->kateView->document()->setHighlightingMode(
  589. (destCategory==qllFilesListItem?
  590. QLL_HL_MODE:
  591. (destCategory==sFilesListItem||(destCategory==hFilesListItem&&!fileText.isNull()&&!fileText.isEmpty()&&fileText[0]=='|'))?
  592. S_HL_MODE:
  593. (destCategory==asmFilesListItem||(destCategory==hFilesListItem&&!fileText.isNull()&&!fileText.isEmpty()&&fileText[0]==';'))?
  594. ASM_HL_MODE:
  595. (destCategory==cFilesListItem||destCategory==hFilesListItem)?
  596. C_HL_MODE:
  597. "None"));
  598. }
  599. // update icon
  600. currItem->setPixmap(0,
  601. destCategory==cFilesListItem||destCategory==qllFilesListItem?SYSICON("source-c","filec.png"):
  602. destCategory==hFilesListItem?SYSICON("source-h","fileh.png"):
  603. destCategory==sFilesListItem||destCategory==asmFilesListItem?SYSICON("source-s","files.png"):
  604. destCategory==txtFilesListItem?SYSICON("txt","filet.png"):
  605. destCategory==oFilesListItem||destCategory==aFilesListItem?SYSICON("binary","fileo.png"):
  606. SYSICON("unknown","filex.png"));
  607. }
  608. } else if (IS_FILE(item)) {
  609. // drop on file
  610. // need same parent, but different items
  611. if (currItem->parent() == item->parent()
  612. && currItem != item) {
  613. // reorder files
  614. // figure out which one is the first
  615. for (Q3ListViewItem *i=currItem->parent()->firstChild();i;
  616. i=i->nextSibling()) {
  617. if (i==currItem) {
  618. // currItem is first, move currItem after item
  619. e->accept();
  620. currItem->moveItem(item);
  621. projectIsDirty=TRUE;
  622. projectNeedsRelink=TRUE;
  623. break;
  624. } else if (i==item) {
  625. // item is first, move currItem before item
  626. e->accept();
  627. currItem->moveItem(item);
  628. item->moveItem(currItem);
  629. projectIsDirty=TRUE;
  630. projectNeedsRelink=TRUE;
  631. break;
  632. }
  633. }
  634. } else e->ignore();
  635. } else e->ignore();
  636. } else e->ignore();
  637. } else e->ignore();
  638. }
  639. void DnDListView::dragEnterEvent(QDragEnterEvent *e) {
  640. if (!compiling && e->source()==this&&(e->provides("x-ktigcc-dnd")))
  641. e->accept();
  642. }
  643. void DnDListView::dragMoveEvent(QDragMoveEvent *e) {
  644. if (!compiling && e->source()==this && e->provides("x-ktigcc-dnd")) {
  645. Q3ListViewItem *currItem;
  646. currItem = *reinterpret_cast<Q3ListViewItem * const *>((const char *)e->encodedData("x-ktigcc-dnd"));
  647. if (IS_FOLDER(currItem) && !IS_CATEGORY(currItem)) {
  648. // dropping folder
  649. // can only drop on folder or category
  650. Q3ListViewItem *item=itemAt(e->pos());
  651. if (IS_FOLDER(item)) {
  652. // need same category
  653. CATEGORY_OF(srcCategory,currItem);
  654. CATEGORY_OF(destCategory,item);
  655. if (srcCategory == destCategory) {
  656. // can't move folder into itself
  657. for (Q3ListViewItem *destFolder=item; IS_FOLDER(destFolder); destFolder=destFolder->parent()) {
  658. if (destFolder==currItem) goto ignore;
  659. }
  660. e->accept();
  661. } else {ignore: e->ignore();}
  662. } else e->ignore();
  663. } else if (IS_FILE(currItem)) {
  664. // dropping file
  665. Q3ListViewItem *item=itemAt(e->pos());
  666. if (IS_FOLDER(item)) {
  667. // drop on folder
  668. // don't allow more than one Quill file per project
  669. CATEGORY_OF(srcCategory,currItem);
  670. CATEGORY_OF(destCategory,item);
  671. if (qllFilesListItem && srcCategory != qllFilesListItem
  672. && destCategory == qllFilesListItem && qllFileCount)
  673. e->ignore();
  674. else
  675. e->accept();
  676. } else if (IS_FILE(item)) {
  677. // drop on file
  678. // need same parent, but different items
  679. if (currItem->parent() == item->parent()
  680. && currItem != item) e->accept(); else e->ignore();
  681. } else e->ignore();
  682. } else e->ignore();
  683. } else e->ignore();
  684. }
  685. // K3ListView::rename won't work properly if I don't do this. :-/
  686. void DnDListView::rename(Q3ListViewItem *item, int c) {
  687. QCoreApplication::processEvents(QEventLoop::ExcludeUserInput,1000);
  688. ensureItemVisible(item);
  689. QCoreApplication::processEvents(QEventLoop::ExcludeUserInput,1000);
  690. K3ListView::rename(item,c);
  691. }
  692. void DnDListView::keyPressEvent(QKeyEvent *e)
  693. {
  694. if (e->key()==Qt::Key_Delete && e->state()==0) {
  695. Q3ListViewItem *item=currentItem();
  696. if (item)
  697. static_cast<MainForm *>(parent()->parent()->parent())->removeItem(item);
  698. e->accept();
  699. } else QWidget::keyPressEvent(e);
  700. }
  701. enum ErrorTypes {etError, etWarning, etInfo};
  702. class ErrorListItem : public K3ListViewItem {
  703. public:
  704. ErrorListItem(MainForm *pMainForm, ErrorTypes errType,
  705. const QString &errFile, const QString &errFunc,
  706. const QString &errMsg, int errLine, int errColumn)
  707. : K3ListViewItem(errorList->errorListView,
  708. errorList->errorListView->lastItem()),
  709. lvFile(0), srcFile(0), cursor(0), errorLine(-1), errorColumn(0),
  710. mainForm(pMainForm), errorType(errType)
  711. {
  712. QString errMessage=errMsg.trimmed();
  713. if (!errMessage.isEmpty()) errMessage[0]=errMessage[0].toUpper();
  714. switch(errType) {
  715. case etError:
  716. setPixmap(0,SYSICON("dialog-error","error.png"));
  717. break;
  718. case etWarning:
  719. setPixmap(0,SYSICON("dialog-warning","warning.png"));
  720. break;
  721. default:
  722. setPixmap(0,SYSICON("dialog-information","info.png"));
  723. break;
  724. }
  725. setText(0,errMessage);
  726. setText(1,errFile);
  727. setText(2,errFunc=="__exit"?"_exit":
  728. (errFunc=="__main"?"_main":errFunc));
  729. if (!errFile.isEmpty() && !errFile.endsWith(".a")) {
  730. // Look for the source file with the error.
  731. if (!findSourceFile(errFile) && errFile.endsWith(".o")) {
  732. QString errSrcFile=errFile;
  733. int lengthWoExt=errSrcFile.length()-2;
  734. errSrcFile.truncate(lengthWoExt);
  735. errSrcFile.append(".c");
  736. if (!findSourceFile(errSrcFile)) {
  737. errSrcFile.truncate(lengthWoExt);
  738. errSrcFile.append(".s");
  739. if (!findSourceFile(errSrcFile)) {
  740. errSrcFile.truncate(lengthWoExt);
  741. errSrcFile.append(".asm");
  742. findSourceFile(errSrcFile);
  743. }
  744. }
  745. }
  746. // Not found. Try to open it instead.
  747. // Don't do this if the name ends with ".tpr" because that would cause
  748. // openProject to close the current project and load the new one instead.
  749. if (!lvFile && !srcFile && !errFile.endsWith(".tpr",FALSE)) {
  750. if (errFile.contains('/')&&getPathType(errFile)==PATH_FILE)
  751. mainForm->openProject(errFile);
  752. else if (getPathType(QString("%1/include/c/%2").arg(tigcc_base).arg(errFile))==PATH_FILE)
  753. mainForm->openProject(QString("%1/include/c/%2").arg(tigcc_base).arg(errFile));
  754. else if (getPathType(QString("%1/include/asm/%2").arg(tigcc_base).arg(errFile))==PATH_FILE)
  755. mainForm->openProject(QString("%1/include/asm/%2").arg(tigcc_base).arg(errFile));
  756. else if (getPathType(QString("%1/include/s/%2").arg(tigcc_base).arg(errFile))==PATH_FILE)
  757. mainForm->openProject(QString("%1/include/s/%2").arg(tigcc_base).arg(errFile));
  758. findSourceFile(errFile);
  759. }
  760. }
  761. if (errLine!=-1 && (lvFile || srcFile)) {
  762. if (errColumn==-1) errColumn=0;
  763. const LineStartList &lineStartList=lvFile?lvFile->lineStartList
  764. :srcFile->lineStartList;
  765. if (lineStartList.isEmpty()) {
  766. errorLine=errLine;
  767. errorColumn=errColumn;
  768. } else if (errLine<lineStartList.count()) {
  769. QPair<unsigned,unsigned> pos=lineStartList[errLine];
  770. errorLine=(int)pos.first;
  771. errorColumn=(int)pos.second+errColumn;
  772. }
  773. createCursor();
  774. }
  775. if (preferences.jumpToError && errType==etError
  776. && errorList->errorListView->selectedItems().isEmpty()) {
  777. errorList->errorListView->setSelected(this,TRUE);
  778. jumpToLocation();
  779. }
  780. errorCountTotal++;
  781. if (errType==etError) errorCountErrors++;
  782. if (errType==etWarning) errorCountWarnings++;
  783. errorList->errorCount->setText(QString::number(errorCountErrors));
  784. errorList->warningCount->setText(QString::number(errorCountWarnings));
  785. mainForm->projectErrorsAndWarningsAction->setEnabled(TRUE);
  786. mainForm->projectErrorsAndWarnings(TRUE);
  787. }
  788. virtual ~ErrorListItem()
  789. {
  790. if (errorType==etError) errorCountErrors--;
  791. if (errorType==etWarning) errorCountWarnings--;
  792. errorList->errorCount->setText(QString::number(errorCountErrors));
  793. errorList->warningCount->setText(QString::number(errorCountWarnings));
  794. if (!--errorCountTotal) {
  795. mainForm->projectErrorsAndWarnings(FALSE);
  796. mainForm->projectErrorsAndWarningsAction->setEnabled(FALSE);
  797. }
  798. }
  799. virtual int rtti(void) const {return static_cast<int>(errorType);}
  800. void createCursor(void)
  801. {
  802. if (errorLine!=-1) {
  803. KTextEditor::View *kateView=lvFile?lvFile->kateView:(srcFile?srcFile->kateView
  804. :static_cast<KTextEditor::View *>(NULL));
  805. if (kateView && errorLine<kateView->document()->lines()) {
  806. // Extract the main token for the error message.
  807. QString errMessage=text(0);
  808. int quotePos=errMessage.find('\'');
  809. if (quotePos>=0) {
  810. QString token=errMessage.mid(quotePos+1);
  811. int quotePos2=token.find('\'');
  812. if (quotePos2>=0) {
  813. token.truncate(quotePos2);
  814. if (!token.isEmpty()) {
  815. // Skip whitespace up to this token. TIGCC IDE does that too. Must
  816. // have something to do with how source splitting works.
  817. int i=errorColumn;
  818. QString textLine=kateView->document()->line(errorLine);
  819. int lineLength=kateView->document()->lineLength(errorLine);
  820. int tokenLength=token.length();
  821. while ((i<lineLength) && textLine[i].isSpace()
  822. && textLine.mid(i,tokenLength)!=token) i++;
  823. if (textLine.mid(i,tokenLength)==token) errorColumn=i;
  824. }
  825. }
  826. }
  827. KTextEditor::SmartInterface* smart =
  828. qobject_cast<KTextEditor::SmartInterface*>(kateView->document());
  829. cursor=smart->newSmartCursor(errorLine,errorColumn);
  830. }
  831. }
  832. }
  833. void jumpToLocation(void)
  834. {
  835. // If the error corresponds to a list view file, select it. This will also
  836. // instantiate the Kate view and call createCursor for us.
  837. if (lvFile) mainForm->fileTreeClicked(lvFile);
  838. // If it corresponds to an external source file, activate the window.
  839. if (srcFile) ACTIVATE_WINDOW(srcFile->winId());
  840. // Now jump to the cursor's location if we have one.
  841. KTextEditor::View *kateView=lvFile?lvFile->kateView:(srcFile?srcFile->kateView
  842. :static_cast<KTextEditor::View *>(NULL));
  843. if (cursor && kateView)
  844. kateView->setCursorPosition(*cursor);
  845. }
  846. ListViewFile *lvFile;
  847. SourceFileWindow *srcFile;
  848. KTextEditor::SmartCursor *cursor;
  849. private:
  850. int errorLine;
  851. int errorColumn;
  852. MainForm *mainForm;
  853. ErrorTypes errorType;
  854. bool findSourceFile(const QString &fileName)
  855. {
  856. bool inProject;
  857. void *sourceFile;
  858. bool found=mainForm->findSourceFile(inProject,sourceFile,fileName);
  859. if (found) {
  860. if (inProject)
  861. lvFile=reinterpret_cast<ListViewFile *>(sourceFile);
  862. else
  863. srcFile=reinterpret_cast<SourceFileWindow *>(sourceFile);
  864. }
  865. return found;
  866. }
  867. };
  868. // This static helper function is needed because of limitations of both .ui.h
  869. // files and C++: we can't have methods of other classes than MainForm here
  870. // unless we write them into the class definition or Qt Designer gets confused,
  871. // and C++ won't let 2 classes reference each other in methods declared within
  872. // the class definition. And item is of type QListViewItem rather than
  873. // ListViewFile because of another Qt Designer limitation: It isn't possible to
  874. // use custom types in a .ui file method because it doesn't forward-declare them
  875. // properly.
  876. void MainForm::deleteErrorsForLVFile(Q3ListViewItem *item)
  877. {
  878. Q3ListViewItemIterator lvit(errorList->errorListView);
  879. Q3ListViewItem *errorItem;
  880. while ((errorItem=lvit.current())) {
  881. ++lvit;
  882. if (static_cast<ErrorListItem *>(errorItem)->lvFile
  883. ==static_cast<ListViewFile *>(item))
  884. delete errorItem;
  885. }
  886. }
  887. // Another static helper function, in this case because srcfilewin.ui.h doesn't
  888. // have access to ErrorListItem for similar reasons. (I'd have to duplicate the
  889. // class definition, one time with inline functions and one time without.)
  890. void MainForm::deleteErrorsForSrcFile(void *srcFile)
  891. {
  892. Q3ListViewItemIterator lvit(errorList->errorListView);
  893. Q3ListViewItem *errorItem;
  894. while ((errorItem=lvit.current())) {
  895. ++lvit;
  896. if (static_cast<ErrorListItem *>(errorItem)->srcFile
  897. ==reinterpret_cast<SourceFileWindow *>(srcFile))
  898. delete errorItem;
  899. }
  900. }
  901. // And another.
  902. void MainForm::createErrorCursorsForSourceFile(Q3ListViewItem *item)
  903. {
  904. Q3ListViewItemIterator lvit(errorList->errorListView);
  905. Q3ListViewItem *errorItem;
  906. for (errorItem=lvit.current();errorItem;errorItem=(++lvit).current()) {
  907. if (static_cast<ErrorListItem *>(errorItem)->lvFile
  908. ==static_cast<ListViewFile *>(item))
  909. static_cast<ErrorListItem *>(errorItem)->createCursor();
  910. }
  911. }
  912. // And the last.
  913. void MainForm::deleteOverwrittenErrorsIn(void *srcFile)
  914. {
  915. SourceFileWindow *sourceFile=reinterpret_cast<SourceFileWindow *>(srcFile);
  916. Q3ListViewItemIterator lvit(errorList->errorListView);
  917. ErrorListItem *errorItem;
  918. while ((errorItem=static_cast<ErrorListItem *>(lvit.current()))) {
  919. ++lvit;
  920. if (errorItem->srcFile==sourceFile && errorItem->cursor) {
  921. int line,col;
  922. errorItem->cursor->position(line,col);
  923. int curline,curcol;
  924. sourceFile->kateView->cursorPosition().position(curline,curcol);
  925. if (curline==line && curcol==col)
  926. delete errorItem;
  927. }
  928. }
  929. }
  930. void MainForm::errorListView_clicked(Q3ListViewItem *item)
  931. {
  932. if (item) {
  933. static_cast<ErrorListItem *>(item)->jumpToLocation();
  934. errorList->setFocus();
  935. }
  936. }
  937. bool MainForm::findSourceFile(bool &inProject, void *&srcFile, const QString &fileName)
  938. {
  939. bool compareAbsPaths=fileName.contains('/');
  940. Q3ListViewItemIterator lvit(fileTree);
  941. Q3ListViewItem *item;
  942. for (item=lvit.current();item;item=(++lvit).current()) {
  943. if (IS_FILE(item)
  944. && (compareAbsPaths?fileName==static_cast<ListViewFile *>(item)->fileName
  945. :fileName==QFileInfo(static_cast<ListViewFile *>(item)->fileName).fileName())) {
  946. inProject=TRUE;
  947. srcFile=static_cast<ListViewFile *>(item);
  948. return TRUE;
  949. }
  950. }
  951. foreach (SourceFileWindow *sourceFile, sourceFiles) {
  952. if (compareAbsPaths?fileName==sourceFile->fileName
  953. :fileName==QFileInfo(sourceFile->fileName).fileName()) {
  954. inProject=FALSE;
  955. srcFile=sourceFile;
  956. return TRUE;
  957. }
  958. }
  959. return FALSE;
  960. }
  961. void sendCommand(KTextEditor::View *view, const QString &cmd)
  962. {
  963. KTextEditor::CommandInterface *cmdIface=
  964. qobject_cast<KTextEditor::CommandInterface*>(view->document()->editor());
  965. KTextEditor::Command *command=cmdIface->queryCommand(cmd);
  966. QString msg; // thrown away
  967. command->exec(view,cmd,msg);
  968. }
  969. void setTabWidth(KTextEditor::View *view, unsigned tabWidth)
  970. {
  971. sendCommand(view,QString("set-tab-width %1").arg(tabWidth));
  972. }
  973. MainForm::MainForm(QWidget* parent, const char* name, Qt::WindowFlags fl)
  974. : QMainWindow(parent, name, fl)
  975. {
  976. setupUi(this);
  977. (void)statusBar();
  978. QPixmap smallIcon(":/images/ktigcc.png");
  979. QPixmap largeIcon(":/images/icon.png");
  980. QIcon windowIcon(smallIcon);
  981. windowIcon.addPixmap(largeIcon);
  982. setWindowIcon(windowIcon);
  983. #ifdef Q_WS_X11
  984. KWindowSystem::setIcons(winId(),largeIcon,smallIcon);
  985. #endif
  986. ticables_library_init();
  987. tifiles_library_init();
  988. ticalcs_library_init();
  989. have_usb=ticables_is_usb_enabled();
  990. compiling=FALSE;
  991. headersModified=FALSE;
  992. loadPreferences();
  993. loadSystemHeaderCompletion();
  994. fileNewFolderAction->setEnabled(FALSE);
  995. te_popup = new Q3PopupMenu(this);
  996. te_popup->insertItem("&Open file at cursor",0);
  997. te_popup->insertItem("&Find symbol declaration",1);
  998. te_popup->insertSeparator();
  999. te_popup->insertItem("&Undo",2);
  1000. te_popup->insertItem("&Redo",3);
  1001. te_popup->insertSeparator();
  1002. te_popup->insertItem("&Clear",4);
  1003. te_popup->insertItem("Cu&t",5);
  1004. te_popup->insertItem("Cop&y",6);
  1005. te_popup->insertItem("&Paste",7);
  1006. te_popup->insertSeparator();
  1007. te_popup->insertItem("&Select all",8);
  1008. te_popup->insertSeparator();
  1009. te_popup->insertItem("&Increase indent",9);
  1010. te_popup->insertItem("&Decrease indent",10);
  1011. connect(te_popup,SIGNAL(aboutToShow()),this,SLOT(te_popup_aboutToShow()));
  1012. connect(te_popup,SIGNAL(activated(int)),this,SLOT(te_popup_activated(int)));
  1013. QList<int> list;
  1014. list.append(150);
  1015. list.append(500);
  1016. splitter->setSizes(list);
  1017. leftStatusLabel=new QLabel("0 Files Total",this);
  1018. leftStatusLabel->setMaximumWidth(splitter->sizes().first());
  1019. statusBar()->addWidget(leftStatusLabel,1);
  1020. rowStatusLabel=new QLabel("",this);
  1021. rowStatusLabel->setAlignment(Qt::AlignRight);
  1022. statusBar()->addWidget(rowStatusLabel,1);
  1023. rowStatusLabel->hide();
  1024. colStatusLabel=new QLabel("",this);
  1025. colStatusLabel->setAlignment(Qt::AlignRight);
  1026. statusBar()->addWidget(colStatusLabel,1);
  1027. colStatusLabel->hide();
  1028. charsStatusLabel=new QLabel("",this);
  1029. statusBar()->addWidget(charsStatusLabel,1);
  1030. charsStatusLabel->hide();
  1031. rightStatusLabel=new QLabel("",this);
  1032. rightStatusLabel->setMaximumWidth(splitter->sizes().last());
  1033. statusBar()->addWidget(rightStatusLabel,1);
  1034. statusBar()->setSizeGripEnabled(FALSE);
  1035. connect(statusBar(),SIGNAL(messageChanged(const QString &)),this,SLOT(statusBar_messageChanged(const QString &)));
  1036. fileTree->setSorting(-1);
  1037. fileTree->setColumnWidthMode(0,Q3ListView::Maximum);
  1038. fileTree->header()->hide();
  1039. fileTree->setAlternateBackground(QColor());
  1040. rootListItem=new ListViewRoot(fileTree);
  1041. rootListItem->setText(0,"Project1");
  1042. rootListItem->setPixmap(0,SYSICON("exec","tpr.png"));
  1043. rootListItem->setOpen(TRUE);
  1044. Q3ListViewItem *folderListItem=new ListViewFolder(rootListItem);
  1045. hFilesListItem=folderListItem;
  1046. folderListItem->setText(0,"Header Files");
  1047. folderListItem=new ListViewFolder(rootListItem,folderListItem);
  1048. cFilesListItem=folderListItem;
  1049. folderListItem->setText(0,"C Files");
  1050. folderListItem=new ListViewFolder(rootListItem,folderListItem);
  1051. sFilesListItem=folderListItem;
  1052. folderListItem->setText(0,"GNU Assembly Files");
  1053. char a68k_path[strlen(tigcc_base)+10];
  1054. sprintf(a68k_path, "%s/bin/a68k", tigcc_base);
  1055. if(access(a68k_path, F_OK) != -1) {
  1056. folderListItem=new ListViewFolder(rootListItem,folderListItem);
  1057. asmFilesListItem=folderListItem;
  1058. folderListItem->setText(0,"A68k Assembly Files");
  1059. } else {
  1060. asmFilesListItem=NULL;
  1061. fileNewA68kAssemblyHeaderAction->setVisible(FALSE);
  1062. fileNewA68kAssemblySourceFileAction->setVisible(FALSE);
  1063. }
  1064. if (quill_drv) {
  1065. folderListItem=new ListViewFolder(rootListItem,folderListItem);
  1066. qllFilesListItem=folderListItem;
  1067. folderListItem->setText(0,"Quill Files");
  1068. } else {
  1069. qllFilesListItem=NULL;
  1070. fileNewQuillSourceFileAction->setVisible(FALSE);
  1071. }
  1072. folderListItem=new ListViewFolder(rootListItem,folderListItem);
  1073. oFilesListItem=folderListItem;
  1074. folderListItem->setText(0,"Object Files");
  1075. folderListItem=new ListViewFolder(rootListItem,folderListItem);
  1076. aFilesListItem=folderListItem;
  1077. folderListItem->setText(0,"Archive Files");
  1078. folderListItem=new ListViewFolder(rootListItem,folderListItem);
  1079. txtFilesListItem=folderListItem;
  1080. folderListItem->setText(0,"Text Files");
  1081. folderListItem=new ListViewFolder(rootListItem,folderListItem);
  1082. othFilesListItem=folderListItem;
  1083. folderListItem->setText(0,"Other Files");
  1084. khelpmenu=new KHelpMenu(this,pabout);
  1085. assistant=new QAssistantClient("",this);
  1086. QStringList args(QString("-profile"));
  1087. args.append(QString("%1/doc/html/qt-assistant.adp").arg(tigcc_base));
  1088. assistant->setArguments(args);
  1089. lastDirectory=QString("%1/tigcc-projects").arg(QDir::homePath());
  1090. if (!QDir(lastDirectory).exists() && !QDir().mkdir(lastDirectory))
  1091. lastDirectory=QString("%1/projects").arg(tigcc_base);
  1092. projectFileName="";
  1093. projectIsDirty=FALSE;
  1094. projectNeedsRelink=FALSE;
  1095. connect(KDirWatch::self(),SIGNAL(created(const QString &)),this,SLOT(KDirWatch_dirty(const QString &)));
  1096. connect(KDirWatch::self(),SIGNAL(dirty(const QString &)),this,SLOT(KDirWatch_dirty(const QString &)));
  1097. KDirWatch::self()->startScan();
  1098. clipboard=QApplication::clipboard();
  1099. connect(clipboard,SIGNAL(dataChanged()),this,SLOT(clipboard_dataChanged()));
  1100. shortcuts[0]=new QShortcut(Qt::ALT+Qt::Key_Backspace,this);
  1101. shortcuts[0]->setEnabled(FALSE);
  1102. shortcuts[1]=new QShortcut(Qt::SHIFT+Qt::ALT+Qt::Key_Backspace,this);
  1103. shortcuts[1]->setEnabled(FALSE);
  1104. shortcuts[2]=new QShortcut(Qt::SHIFT+Qt::Key_Delete,this);
  1105. shortcuts[2]->setEnabled(FALSE);
  1106. shortcuts[3]=new QShortcut(Qt::CTRL+Qt::Key_Insert,this);
  1107. shortcuts[3]->setEnabled(FALSE);
  1108. shortcuts[4]=new QShortcut(Qt::SHIFT+Qt::Key_Insert,this);
  1109. shortcuts[4]->setEnabled(FALSE);
  1110. shortcuts[5]=new QShortcut(Qt::Key_F1,this);
  1111. shortcuts[5]->setEnabled(FALSE);
  1112. shortcuts[6]=new QShortcut(Qt::Key_Enter,this);
  1113. shortcuts[6]->setEnabled(FALSE);
  1114. shortcuts[7]=new QShortcut(Qt::Key_Return,this);
  1115. shortcuts[7]->setEnabled(FALSE);
  1116. shortcuts[8]=new QShortcut(Qt::CTRL+Qt::Key_J,this);
  1117. shortcuts[8]->setEnabled(FALSE);
  1118. shortcuts[9]=new QShortcut(Qt::CTRL+Qt::Key_Space,this);
  1119. shortcuts[9]->setEnabled(FALSE);
  1120. shortcuts[10]=new QShortcut(Qt::CTRL+Qt::Key_M,this);
  1121. shortcuts[10]->setEnabled(FALSE);
  1122. shortcuts[11]=new QShortcut(Qt::CTRL+Qt::Key_Tab,this);
  1123. shortcuts[11]->setEnabled(TRUE);
  1124. shortcuts[12]=new QShortcut(Qt::CTRL+Qt::Key_G,this);
  1125. shortcuts[12]->setEnabled(TRUE);
  1126. shortcuts[13]=new QShortcut(Qt::SHIFT+Qt::CTRL+Qt::ALT+Qt::Key_F9,this);
  1127. shortcuts[13]->setEnabled(TRUE);
  1128. shortcuts[14]=new QShortcut(Qt::SHIFT+Qt::ALT+Qt::Key_F8,this);
  1129. shortcuts[14]->setEnabled(TRUE);
  1130. shortcuts[15]=new QShortcut(Qt::CTRL+Qt::ALT+Qt::Key_F9,this);
  1131. shortcuts[15]->setEnabled(TRUE);
  1132. shortcuts[16]=new QShortcut(Qt::CTRL+Qt::Key_F9,this);
  1133. shortcuts[16]->setEnabled(TRUE);
  1134. shortcuts[17]=new QShortcut(Qt::CTRL+Qt::Key_Return,this);
  1135. shortcuts[17]->setEnabled(FALSE);
  1136. connect(shortcuts[0],SIGNAL(activated()),this,SLOT(shortcut_0_activated()));
  1137. connect(shortcuts[1],SIGNAL(activated()),this,SLOT(shortcut_1_activated()));
  1138. connect(shortcuts[2],SIGNAL(activated()),this,SLOT(shortcut_2_activated()));
  1139. connect(shortcuts[3],SIGNAL(activated()),this,SLOT(shortcut_3_activated()));
  1140. connect(shortcuts[4],SIGNAL(activated()),this,SLOT(shortcut_4_activated()));
  1141. connect(shortcuts[5],SIGNAL(activated()),this,SLOT(shortcut_5_activated()));
  1142. connect(shortcuts[6],SIGNAL(activated()),this,SLOT(shortcut_6_activated()));
  1143. connect(shortcuts[7],SIGNAL(activated()),this,SLOT(shortcut_7_activated()));
  1144. connect(shortcuts[8],SIGNAL(activated()),this,SLOT(shortcut_8_activated()));
  1145. connect(shortcuts[9],SIGNAL(activated()),this,SLOT(shortcut_9_activated()));
  1146. connect(shortcuts[10],SIGNAL(activated()),this,SLOT(shortcut_10_activated()));
  1147. connect(shortcuts[11],SIGNAL(activated()),this,SLOT(shortcut_11_activated()));
  1148. connect(shortcuts[12],SIGNAL(activated()),this,SLOT(shortcut_12_activated()));
  1149. connect(shortcuts[13],SIGNAL(activated()),this,SLOT(shortcut_13_activated()));
  1150. connect(shortcuts[14],SIGNAL(activated()),this,SLOT(shortcut_14_activated()));
  1151. connect(shortcuts[15],SIGNAL(activated()),this,SLOT(shortcut_15_activated()));
  1152. connect(shortcuts[16],SIGNAL(activated()),this,SLOT(shortcut_16_activated()));
  1153. connect(shortcuts[17],SIGNAL(activated()),this,SLOT(findOpenFileAtCursor()));
  1154. kfinddialog = static_cast<KFindDialog *>(NULL);
  1155. kreplace = static_cast<KReplaceWithSelection *>(NULL);
  1156. connect(fileNewAction,SIGNAL(triggered()),this,SLOT(fileNewProject()));
  1157. if (preferences.useSystemIcons) {
  1158. // Set the preferred icon size so system toolbar icons don't get annoying
  1159. // padding.
  1160. int toolbarIconSize=KIconLoader().currentSize(KIconLoader::MainToolbar);
  1161. setIconSize(QSize(toolbarIconSize,toolbarIconSize));
  1162. fileNewAction->setIcon(KIcon("document-new"));
  1163. fileNewMenu->menuAction()->setIcon(KIcon("document-new"));
  1164. fileOpenAction->setIcon(KIcon("document-open"));
  1165. fileSaveAllAction->setIcon(KIcon("document-save"));
  1166. filePrintAction->setIcon(KIcon("document-print"));
  1167. filePrintQuicklyAction->setIcon(KIcon("document-print"));
  1168. editClearAction->setIcon(KIcon("edit-delete"));
  1169. editCutAction->setIcon(KIcon("edit-cut"));
  1170. editCopyAction->setIcon(KIcon("edit-copy"));
  1171. editPasteAction->setIcon(KIcon("edit-paste"));
  1172. projectAddFilesAction->setIcon(KIcon("edit-add"));
  1173. projectCompileAction->setIcon(KIcon("compfile"));
  1174. projectMakeAction->setIcon(KIcon("make-kdevelop"));
  1175. projectBuildAction->setIcon(KIcon("rebuild"));
  1176. helpContentsAction->setIcon(KIcon("help-contents"));
  1177. helpDocumentationAction->setIcon(KIcon("help-contents"));
  1178. helpSearchAction->setIcon(KIcon("file-find"));
  1179. findFindAction->setIcon(KIcon("edit-find"));
  1180. if (KIconLoader::global()->iconPath("edit-find-replace",KIconLoader::Small,TRUE).isEmpty())
  1181. findReplaceAction->setIcon(KIcon("file-find"));
  1182. else
  1183. findReplaceAction->setIcon(KIcon("edit-find-replace"));
  1184. helpIndexAction->setIcon(KIcon("fileview-text"));
  1185. editUndoAction->setIcon(KIcon("edit-undo"));
  1186. editRedoAction->setIcon(KIcon("edit-redo"));
  1187. findFunctionsAction->setIcon(KIcon("view-tree"));
  1188. editIncreaseIndentAction->setIcon(KIcon("format-indent-more"));
  1189. editDecreaseIndentAction->setIcon(KIcon("format-indent-less"));
  1190. projectStopCompilationAction->setIcon(KIcon("process-stop"));
  1191. projectForceQuitAction->setIcon(KIcon("dialog-cancel"));
  1192. helpNewsAction->setIcon(KIcon("kontact-news"));
  1193. debugRunAction->setIcon(KIcon("media-playback-start"));
  1194. debugPauseAction->setIcon(KIcon("media-playback-pause"));
  1195. toolsConfigureAction->setIcon(KIcon("configure"));
  1196. debugResetAction->setIcon(KIcon("media-playback-stop"));
  1197. } else fileNewMenu->menuAction()->setIcon(QIcon(QPixmap(":/images/00.png")));
  1198. QToolButton *fileNewButton=static_cast<QToolButton *>(toolBar
  1199. ->widgetForAction(fileNewAction));
  1200. fileNewButton->setPopupMode(QToolButton::MenuButtonPopup);
  1201. fileNewButton->setMenu(fileNewMenu);
  1202. QToolButton *fileOpenButton=static_cast<QToolButton *>(toolBar
  1203. ->widgetForAction(fileOpenAction));
  1204. QMenu *fileOpenMenu=new QMenu(this);
  1205. fileOpenMenu->setObjectName(QString::fromUtf8("fileOpenMenu"));
  1206. fileOpenMenu->addAction(fileRecent1Action);
  1207. fileOpenMenu->addAction(fileRecent2Action);
  1208. fileOpenMenu->addAction(fileRecent3Action);
  1209. fileOpenMenu->addAction(fileRecent4Action);
  1210. fileOpenButton->setPopupMode(QToolButton::MenuButtonPopup);
  1211. fileOpenButton->setMenu(fileOpenMenu);
  1212. QToolButton *findFunctionsButton=static_cast<QToolButton *>(toolBar
  1213. ->widgetForAction(findFunctionsAction));
  1214. findFunctionsPopup=new Q3PopupMenu(findFunctionsButton);
  1215. connect(findFunctionsPopup,SIGNAL(aboutToShow()),
  1216. this,SLOT(findFunctionsPopup_aboutToShow()));
  1217. connect(findFunctionsPopup,SIGNAL(aboutToHide()),
  1218. this,SLOT(findFunctionsPopup_aboutToHide()));
  1219. connect(findFunctionsPopup,SIGNAL(activated(int)),
  1220. this,SLOT(findFunctionsPopup_activated(int)));
  1221. findFunctionsButton->setPopupMode(QToolButton::MenuButtonPopup);
  1222. findFunctionsButton->setMenu(findFunctionsPopup);
  1223. errorListDock=new QDockWidget("Errors and Warnings",this);
  1224. errorListDock->setFloating(false);
  1225. errorListDock->setFeatures(QDockWidget::DockWidgetClosable|QDockWidget::DockWidgetFloatable);
  1226. errorListDock->setAllowedAreas(Qt::BottomDockWidgetArea);
  1227. errorList=new ErrorList(errorListDock);
  1228. errorListDock->setWidget(errorList);
  1229. addDockWidget(Qt::BottomDockWidgetArea,errorListDock);
  1230. errorList->show();
  1231. errorListDock->hide();
  1232. connect(errorListDock,SIGNAL(visibilityChanged(bool)),
  1233. this,SLOT(projectErrorsAndWarnings(bool)));
  1234. errorList->errorListView->setSorting(-1);
  1235. errorList->errorListView->setAlternateBackground(QColor());
  1236. connect(errorList->errorListView,SIGNAL(clicked(Q3ListViewItem *)),
  1237. this,SLOT(errorListView_clicked(Q3ListViewItem *)));
  1238. if (preferences.linkTarget!=LT_TIEMU) {
  1239. debugPauseAction->setEnabled(FALSE);
  1240. debugResetAction->setEnabled(FALSE);
  1241. }
  1242. if (preferences.linkTarget==LT_NONE) {
  1243. menuBar()->setItemVisible(5,FALSE); //debugMenu
  1244. debugRunAction->setVisible(FALSE);
  1245. debugPauseAction->setVisible(FALSE);
  1246. }
  1247. KConfigGroup recentFiles=pconfig->group("Recent files");
  1248. if (parg) {
  1249. QString fileName=QDir().absoluteFilePath(parg);
  1250. if (!openProject(fileName)) goto openRecent;
  1251. } else {
  1252. openRecent:;
  1253. QString mostrecent=recentFiles.readEntry("Current project");
  1254. if (!mostrecent.isNull() && !mostrecent.isEmpty())
  1255. openProject(mostrecent);
  1256. }
  1257. updateRecent();
  1258. KConfigGroup toolsConfig=pconfig->group("Tools");
  1259. unsigned toolCount=toolsConfig.readEntry("Count",0u);
  1260. tools.resize(toolCount);
  1261. for (unsigned idx=0; idx<toolCount; idx++) {
  1262. pconfig->setGroup(QString("Tool %1").arg(idx));
  1263. Tool &tool=tools[idx];
  1264. tool.title=toolsConfig.readEntry("Title");
  1265. tool.commandLine=toolsConfig.readEntry("Command Line");
  1266. tool.workingDirectory=toolsConfig.readEntry("Working Directory");
  1267. tool.runInTerminal=toolsConfig.readEntry("Terminal",false);
  1268. }
  1269. updateToolsMenu();
  1270. connect(toolsMenu,SIGNAL(activated(int)),this,SLOT(toolsMenu_activated(int)));
  1271. startTimer(100);
  1272. if (preferences.downloadHeadlines) {
  1273. NewsDialog newsDialog(this);
  1274. if (newsDialog.loadNews())
  1275. newsDialog.exec();
  1276. }
  1277. }
  1278. MainForm::~MainForm()
  1279. {
  1280. while (!sourceFiles.isEmpty()) {
  1281. delete sourceFiles.first();
  1282. }
  1283. if (kreplace) delete kreplace;
  1284. if (kfinddialog) delete kfinddialog;
  1285. for (int i=0; i<18; i++) delete shortcuts[i];
  1286. delete te_popup;
  1287. delete leftStatusLabel;
  1288. delete rowStatusLabel;
  1289. delete colStatusLabel;
  1290. delete charsStatusLabel;
  1291. delete rightStatusLabel;
  1292. delete rootListItem;
  1293. delete khelpmenu;
  1294. delete assistant;
  1295. delete errorList;
  1296. delete errorListDock;
  1297. ticalcs_library_exit();
  1298. tifiles_library_exit();
  1299. ticables_library_exit();
  1300. }
  1301. void MainForm::te_popup_aboutToShow()
  1302. {
  1303. te_popup->setItemEnabled(0,findOpenFileAtCursorAction->isEnabled());
  1304. te_popup->setItemEnabled(1,findFindSymbolDeclarationAction->isEnabled());
  1305. te_popup->setItemEnabled(2,editUndoAction->isEnabled());
  1306. te_popup->setItemEnabled(3,editRedoAction->isEnabled());
  1307. te_popup->setItemEnabled(4,editClearAction->isEnabled());
  1308. te_popup->setItemEnabled(5,editCutAction->isEnabled());
  1309. te_popup->setItemEnabled(6,editCopyAction->isEnabled());
  1310. te_popup->setItemEnabled(7,editPasteAction->isEnabled());
  1311. te_popup->setItemEnabled(8,editSelectAllAction->isEnabled());
  1312. te_popup->setItemEnabled(9,editIncreaseIndentAction->isEnabled());
  1313. te_popup->setItemEnabled(10,editDecreaseIndentAction->isEnabled());
  1314. }
  1315. void MainForm::te_popup_activated(int index)
  1316. {
  1317. switch (index) {
  1318. case 0: findOpenFileAtCursor(); break;
  1319. case 1: findFindSymbolDeclaration(); break;
  1320. case 2: editUndo(); break;
  1321. case 3: editRedo(); break;
  1322. case 4: editClear(); break;
  1323. case 5: editCut(); break;
  1324. case 6: editCopy(); break;
  1325. case 7: editPaste(); break;
  1326. case 8: editSelectAll(); break;
  1327. case 9: editIncreaseIndent(); break;
  1328. case 10: editDecreaseIndent(); break;
  1329. default: break;
  1330. }
  1331. }
  1332. void MainForm::shortcutActivated(int index)
  1333. {
  1334. if (CURRENT_VIEW && CURRENT_VIEW->hasFocus()) {
  1335. switch (index) {
  1336. case 0: editUndo(); break;
  1337. case 1: editRedo(); break;
  1338. case 2: editCut(); break;
  1339. case 3: editCopy(); break;
  1340. case 4: editPaste(); break;
  1341. case 5: // F1 context help
  1342. {
  1343. int line,col,i;
  1344. CURRENT_VIEW->cursorPosition().position(line,col);
  1345. QString textLine=CURRENT_VIEW->document()->line(line);
  1346. QString wordUnderCursor;
  1347. for (i=col-1;i>=0;i--) {
  1348. QChar c=textLine[i];
  1349. if ((c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9')
  1350. || c=='_' || c=='$' || c=='#')
  1351. wordUnderCursor.prepend(c);
  1352. }
  1353. int len=textLine.length();
  1354. for (i=col;i<len;i++) {
  1355. QChar c=textLine[i];
  1356. if ((c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9')
  1357. || c=='_' || c=='$' || c=='#')
  1358. wordUnderCursor.append(c);
  1359. }
  1360. // always open at least the index
  1361. force_qt_assistant_page(1);
  1362. assistant->openAssistant();
  1363. if (wordUnderCursor.isEmpty()) return;
  1364. QString docFile=lookup_doc_keyword(wordUnderCursor);
  1365. if (docFile.isEmpty()) return;
  1366. // wait for Qt Assistant to actually open
  1367. while (!assistant->isOpen())
  1368. QCoreApplication::processEvents(QEventLoop::ExcludeUserInput,1000);
  1369. assistant->showPage(QString(tigcc_base)+QString("/doc/html/")+docFile);
  1370. break;
  1371. }
  1372. case 6:
  1373. case 7:
  1374. // keyReturn is not in any interface, but it's a public slot...
  1375. CURRENT_VIEW->qt_metacall(QMetaObject::InvokeMetaMethod,
  1376. CURRENT_VIEW->metaObject()->indexOfMethod("keyReturn()"),NULL);
  1377. current_view_newLineHook();
  1378. break;
  1379. case 8:
  1380. new TemplatePopup(CURRENT_VIEW);
  1381. break;
  1382. case 9:
  1383. case 10:
  1384. if (IS_FILE(currentListItem)
  1385. && CURRENT_VIEW==static_cast<ListViewFile *>(currentListItem)->kateView) {
  1386. QString fileText=CURRENT_VIEW->document()->text();
  1387. CATEGORY_OF(category,currentListItem);
  1388. // Completion only operates on C files.
  1389. if (category==cFilesListItem || category==qllFilesListItem
  1390. || (category==hFilesListItem && !fileText.isEmpty()
  1391. && fileText[0]!='|' && fileText[0]!=';')) {
  1392. // Disable newLineHook.
  1393. shortcuts[6]->setEnabled(FALSE);
  1394. shortcuts[7]->setEnabled(FALSE);
  1395. new CompletionPopup(CURRENT_VIEW,pathInProject(currentListItem),this,this);
  1396. }
  1397. }
  1398. break;
  1399. case 11: // next file
  1400. case 12:
  1401. case_11:
  1402. {
  1403. Q3ListViewItem *item=currentListItem;
  1404. if (!item) item=rootListItem;
  1405. Q3ListViewItem *origItem=item;
  1406. do {
  1407. item=item->itemBelow();
  1408. if (!item) item=rootListItem;
  1409. if (item==origItem) return; // no suitable items to select
  1410. } while (item==rootListItem || IS_CATEGORY(item));
  1411. fileTreeClicked(item);
  1412. if (CURRENT_VIEW) CURRENT_VIEW->setFocus();
  1413. break;
  1414. }
  1415. case 13: // switch transfer target
  1416. case 14:
  1417. case_13:
  1418. {
  1419. preferences.linkTarget=(preferences.linkTarget==LT_TIEMU)?LT_REALCALC:LT_TIEMU;
  1420. savePreferences();
  1421. // Apply the preferences to the debug menu.
  1422. debugPauseAction->setEnabled(!compiling&&preferences.linkTarget==LT_TIEMU);
  1423. debugResetAction->setEnabled(!compiling&&preferences.linkTarget==LT_TIEMU);
  1424. bool runnable=!settings.archive&&!settings.flash_os&&preferences.linkTarget!=LT_NONE;
  1425. menuBar()->setItemVisible(5,runnable); //debugMenu
  1426. debugRunAction->setVisible(runnable);
  1427. debugPauseAction->setVisible(runnable);
  1428. break;
  1429. }
  1430. case 15: projectCompile(); break;
  1431. case 16: projectMake(); break;
  1432. default: break;
  1433. }
  1434. } else {
  1435. switch (index) {
  1436. case 6:
  1437. case 7:
  1438. {
  1439. QKeyEvent *keyEvent=new QKeyEvent(QEvent::KeyPress,Qt::Key_Return,'\n',0,"\n");
  1440. QApplication::postEvent(focusWidget(),keyEvent);
  1441. break;
  1442. }
  1443. case 11: goto case_11;
  1444. case 12: goto case_11;
  1445. case 13: goto case_13;
  1446. case 14: goto case_13;
  1447. case 15: projectCompile(); break;
  1448. case 16: projectMake(); break;
  1449. default: break;
  1450. }
  1451. }
  1452. }
  1453. void MainForm::completionPopup_closed()
  1454. {
  1455. if (IS_FILE(currentListItem)) {
  1456. CATEGORY_OF(category,currentListItem->parent());
  1457. if (IS_EDITABLE_CATEGORY(category)) {
  1458. // Restore newLineHook.
  1459. shortcuts[6]->setEnabled(TRUE);
  1460. shortcuts[7]->setEnabled(TRUE);
  1461. }
  1462. }
  1463. }
  1464. void MainForm::shortcut_0_activated()
  1465. {
  1466. shortcutActivated(0);
  1467. }
  1468. void MainForm::shortcut_1_activated()
  1469. {
  1470. shortcutActivated(1);
  1471. }
  1472. void MainForm::shortcut_2_activated()
  1473. {
  1474. shortcutActivated(2);
  1475. }
  1476. void MainForm::shortcut_3_activated()
  1477. {
  1478. shortcutActivated(3);
  1479. }
  1480. void MainForm::shortcut_4_activated()
  1481. {
  1482. shortcutActivated(4);
  1483. }
  1484. void MainForm::shortcut_5_activated()
  1485. {
  1486. shortcutActivated(5);
  1487. }
  1488. void MainForm::shortcut_6_activated()
  1489. {
  1490. shortcutActivated(6);
  1491. }
  1492. void MainForm::shortcut_7_activated()
  1493. {
  1494. shortcutActivated(7);
  1495. }
  1496. void MainForm::shortcut_8_activated()
  1497. {
  1498. shortcutActivated(8);
  1499. }
  1500. void MainForm::shortcut_9_activated()
  1501. {
  1502. shortcutActivated(9);
  1503. }
  1504. void MainForm::shortcut_10_activated()
  1505. {
  1506. shortcutActivated(10);
  1507. }
  1508. void MainForm::shortcut_11_activated()
  1509. {
  1510. shortcutActivated(11);
  1511. }
  1512. void MainForm::shortcut_12_activated()
  1513. {
  1514. shortcutActivated(12);
  1515. }
  1516. void MainForm::shortcut_13_activated()
  1517. {
  1518. shortcutActivated(13);
  1519. }
  1520. void MainForm::shortcut_14_activated()
  1521. {
  1522. shortcutActivated(14);
  1523. }
  1524. void MainForm::shortcut_15_activated()
  1525. {
  1526. shortcutActivated(15);
  1527. }
  1528. void MainForm::shortcut_16_activated()
  1529. {
  1530. shortcutActivated(16);
  1531. }
  1532. void MainForm::clearProject()
  1533. {
  1534. headersModified=FALSE;
  1535. newSettings(&settings,&libopts);
  1536. rootListItem->setText(0,"Project1");
  1537. projectFileName="";
  1538. fileTreeClicked(rootListItem);
  1539. // Better do this now or the file destructors will have to iterate over the
  1540. // error list each time, and I'd have to clear the list at the end anyway
  1541. // because an error might not have a source file assigned.
  1542. errorList->errorListView->clear();
  1543. programOutput=QString::null;
  1544. projectProgramOutputAction->setEnabled(FALSE);
  1545. Q3ListViewItem *f, *next;
  1546. for (f=hFilesListItem->firstChild();f;f=next) {
  1547. next=f->nextSibling();
  1548. delete f;
  1549. }
  1550. for (f=cFilesListItem->firstChild();f;f=next) {
  1551. next=f->nextSibling();
  1552. delete f;
  1553. }
  1554. for (f=sFilesListItem->firstChild();f;f=next) {
  1555. next=f->nextSibling();
  1556. delete f;
  1557. }
  1558. if (asmFilesListItem) {
  1559. for (f=asmFilesListItem->firstChild();f;f=next) {
  1560. next=f->nextSibling();
  1561. delete f;
  1562. }
  1563. }
  1564. if (qllFilesListItem) {
  1565. for (f=qllFilesListItem->firstChild();f;f=next) {
  1566. next=f->nextSibling();
  1567. delete f;
  1568. }
  1569. }
  1570. for (f=oFilesListItem->firstChild();f;f=next) {
  1571. next=f->nextSibling();
  1572. delete f;
  1573. }
  1574. for (f=aFilesListItem->firstChild();f;f=next) {
  1575. next=f->nextSibling();
  1576. delete f;
  1577. }
  1578. for (f=txtFilesListItem->firstChild();f;f=next) {
  1579. next=f->nextSibling();
  1580. delete f;
  1581. }
  1582. for (f=othFilesListItem->firstChild();f;f=next) {
  1583. next=f->nextSibling();
  1584. delete f;
  1585. }
  1586. fileCount=cFileCount=hFileCount=sFileCount=asmFileCount=qllFileCount=oFileCount=aFileCount=txtFileCount=othFileCount=0;
  1587. projectCompletion.clear();
  1588. projectIsDirty=FALSE;
  1589. projectNeedsRelink=FALSE;
  1590. menuBar()->setItemVisible(5,preferences.linkTarget!=LT_NONE); //debugMenu
  1591. debugRunAction->setVisible(preferences.linkTarget!=LT_NONE);
  1592. debugPauseAction->setVisible(preferences.linkTarget!=LT_NONE);
  1593. updateLeftStatusLabel();
  1594. }
  1595. void MainForm::fileNewProject()
  1596. {
  1597. if (compiling || savePrompt())
  1598. return;
  1599. clearProject();
  1600. KConfigGroup recentFiles=pconfig->group("Recent files");
  1601. recentFiles.writeEntry("Current project","");
  1602. pconfig->sync();
  1603. }
  1604. QString MainForm::findFilter(unsigned short job)
  1605. {
  1606. QString ret;
  1607. if (job==TIGCCOpenProjectFileFilter)
  1608. {
  1609. ret="*.tpr *.h *.c *.s ";
  1610. if (asmFilesListItem)
  1611. ret+="*.asm ";
  1612. if (qllFilesListItem)
  1613. ret+="*.qll ";
  1614. ret+="*.txt";
  1615. ret+="|All TIGCC Files ("+ret+")\n"
  1616. TIGCC_TPR_Filter TIGCC_H_Filter TIGCC_C_Filter TIGCC_S_Filter;
  1617. if (asmFilesListItem)
  1618. ret+=TIGCC_ASM_Filter;
  1619. if (qllFilesListItem)
  1620. ret+=TIGCC_QLL_Filter;
  1621. ret+=TIGCC_TXT_Filter TIGCCAllFilter;
  1622. }
  1623. else if (job==TIGCCAddFilesFilter)
  1624. {
  1625. ret="*.h *.c *.s ";
  1626. if (asmFilesListItem)
  1627. ret+="*.asm ";
  1628. if (qllFilesListItem)
  1629. ret+="*.qll ";
  1630. ret+="*.o *.a *.txt";
  1631. ret+="|All TIGCC Files ("+ret+")\n"
  1632. TIGCC_H_Filter TIGCC_C_Filter TIGCC_S_Filter;
  1633. if (asmFilesListItem)
  1634. ret+=TIGCC_ASM_Filter;
  1635. if (qllFilesListItem)
  1636. ret+=TIGCC_QLL_Filter;
  1637. ret+=TIGCC_O_Filter TIGCC_A_Filter TIGCC_TXT_Filter TIGCCAllFilter;
  1638. }
  1639. return ret;
  1640. }
  1641. QString MainForm::SGetFileName(int mode,const QString &fileFilter,const QString &caption,QWidget *parent)
  1642. {
  1643. QString ret;
  1644. if (static_cast<KFileDialog::OperationMode>(mode)==KFileDialog::Opening)
  1645. ret=KFileDialog::getOpenFileName(lastDirectory,fileFilter,parent,caption);
  1646. else
  1647. ret=KFileDialog::getSaveFileName(lastDirectory,fileFilter,parent,caption);
  1648. if (!ret.isNull())
  1649. {
  1650. KUrl dir;
  1651. dir.setPath(ret);
  1652. dir.setFileName("");
  1653. lastDirectory=dir.path();
  1654. }
  1655. return ret;
  1656. }
  1657. //no mode, since it you can't save multiple.
  1658. QStringList MainForm::SGetFileName_Multiple(const QString &fileFilter,const QString &caption,QWidget *parent)
  1659. {
  1660. QStringList ret;
  1661. ret=KFileDialog::getOpenFileNames(lastDirectory,fileFilter,parent,caption);
  1662. if (!ret.empty())
  1663. {
  1664. KUrl dir;
  1665. dir.setPath(ret[0]);
  1666. dir.setFileName("");
  1667. lastDirectory=dir.path();
  1668. }
  1669. return ret;
  1670. }
  1671. void MainForm::updateRecent()
  1672. {
  1673. KConfigGroup recentFiles=pconfig->group("Recent files");
  1674. QString recent=recentFiles.readEntry("Recent file 1");
  1675. if (recent.isNull())
  1676. fileRecent1Action->setVisible(FALSE);
  1677. else {
  1678. QString recentcut=recent.mid(recent.findRev('/')+1);
  1679. recentcut.truncate(recentcut.findRev('.'));
  1680. fileRecent1Action->setVisible(TRUE);
  1681. fileRecent1Action->setText(recentcut);
  1682. fileRecent1Action->setStatusTip(recent);
  1683. }
  1684. recent=recentFiles.readEntry("Recent file 2");
  1685. if (recent.isNull())
  1686. fileRecent2Action->setVisible(FALSE);
  1687. else {
  1688. QString recentcut=recent.mid(recent.findRev('/')+1);
  1689. recentcut.truncate(recentcut.findRev('.'));
  1690. fileRecent2Action->setVisible(TRUE);
  1691. fileRecent2Action->setText(recentcut);
  1692. fileRecent2Action->setStatusTip(recent);
  1693. }
  1694. recent=recentFiles.readEntry("Recent file 3");
  1695. if (recent.isNull())
  1696. fileRecent3Action->setVisible(FALSE);
  1697. else {
  1698. QString recentcut=recent.mid(recent.findRev('/')+1);
  1699. recentcut.truncate(recentcut.findRev('.'));
  1700. fileRecent3Action->setVisible(TRUE);
  1701. fileRecent3Action->setText(recentcut);
  1702. fileRecent3Action->setStatusTip(recent);
  1703. }
  1704. recent=recentFiles.readEntry("Recent file 4");
  1705. if (recent.isNull())
  1706. fileRecent4Action->setVisible(FALSE);
  1707. else {
  1708. QString recentcut=recent.mid(recent.findRev('/')+1);
  1709. recentcut.truncate(recentcut.findRev('.'));
  1710. fileRecent4Action->setVisible(TRUE);
  1711. fileRecent4Action->setText(recentcut);
  1712. fileRecent4Action->setStatusTip(recent);
  1713. }
  1714. }
  1715. void MainForm::addRecent(const QString &fileName)
  1716. {
  1717. unsigned i,j;
  1718. // Pick up any changes to the list of recent files from other instances
  1719. pconfig->sync();
  1720. pconfig->reparseConfiguration();
  1721. KConfigGroup recentFiles=pconfig->group("Recent files");
  1722. // Find recent file to overwrite. If it isn't one of the first 3, by
  1723. // elimination, it is the last, thus the test only goes up to <4, not <=4.
  1724. for (i=1;i<4;i++) {
  1725. QString recenti=recentFiles.readEntry(QString("Recent file %1").arg(i));
  1726. if (recenti.isNull() || !recenti.compare(fileName))
  1727. break;
  1728. }
  1729. // Move entries up
  1730. for (j=i;j>1;j--) {
  1731. recentFiles.writeEntry(QString("Recent file %1").arg(j),recentFiles.readEntry(QString("Recent file %1").arg(j-1)));
  1732. }
  1733. // The first recent file is the current project.
  1734. recentFiles.writeEntry("Recent file 1",fileName);
  1735. recentFiles.writeEntry("Current project",fileName);
  1736. pconfig->sync();
  1737. updateRecent();
  1738. }
  1739. Q3ListViewItem * MainForm::openFile(Q3ListViewItem * category, Q3ListViewItem * parent, const QString &fileCaption, const QString &fileName)
  1740. {
  1741. switch (getPathType(fileName)) {
  1742. case PATH_FILE: // OK
  1743. break;
  1744. case PATH_NOTFOUND:
  1745. KMessageBox::error(this,QString("File \'%1\' not found").arg(fileName));
  1746. return NULL;
  1747. default:
  1748. KMessageBox::error(this,QString("\'%1\' is not a regular file").arg(fileName));
  1749. return NULL;
  1750. }
  1751. Q3ListViewItem *item=NULL, *next=parent->firstChild();
  1752. for (; IS_FILE(next); next=item->nextSibling())
  1753. item=next;
  1754. ListViewFile *newFile=item?new ListViewFile(parent,item)
  1755. :new ListViewFile(parent);
  1756. newFile->isNew=FALSE;
  1757. newFile->modifiedSinceLastCompile=FALSE;
  1758. newFile->setText(0,fileCaption);
  1759. newFile->setPixmap(0,
  1760. category==cFilesListItem||category==qllFilesListItem?SYSICON("source-c","filec.png"):
  1761. category==hFilesListItem?SYSICON("source-h","fileh.png"):
  1762. category==sFilesListItem||category==asmFilesListItem?SYSICON("source-s","files.png"):
  1763. category==txtFilesListItem?SYSICON("txt","filet.png"):
  1764. category==oFilesListItem||category==aFilesListItem?SYSICON("binary","fileo.png"):
  1765. SYSICON("unknown","filex.png"));
  1766. newFile->fileName=fileName;
  1767. if (IS_EDITABLE_CATEGORY(category)) {
  1768. newFile->kateView=reinterpret_cast<KTextEditor::View *>(createView(fileName,QString::null,category));
  1769. KDirWatch::self()->addFile(fileName);
  1770. }
  1771. fileCount++;
  1772. COUNTER_FOR_CATEGORY(category)++;
  1773. return newFile;
  1774. }
  1775. Q3ListViewItem *MainForm::createFolder(Q3ListViewItem *parent,const QString &name)
  1776. {
  1777. Q3ListViewItem *item=parent->firstChild();
  1778. Q3ListViewItem *startItem=item;
  1779. Q3ListViewItem *newItem;
  1780. for (; item; item=item->nextSibling())
  1781. {
  1782. if (IS_FOLDER(item) && !item->text(0).compare(name))
  1783. return item;
  1784. }
  1785. item=NULL;
  1786. for (;startItem;startItem=item->nextSibling())
  1787. item=startItem;
  1788. newItem=item?new ListViewFolder(parent,item)
  1789. :new ListViewFolder(parent);
  1790. newItem->setText(0,name);
  1791. newItem->setOpen(TRUE);
  1792. return newItem;
  1793. }
  1794. void *MainForm::createView(const QString &fileName, const QString &fileText, Q3ListViewItem *category)
  1795. {
  1796. // Create Document object.
  1797. KParts::Factory *factory = (KParts::Factory *)
  1798. KLibLoader::self()->factory ("katepart");
  1799. if (!factory) qFatal("Failed to load KatePart");
  1800. KTextEditor::Document *doc = (KTextEditor::Document *)
  1801. factory->createPart(0,this,"KTextEditor::Document");
  1802. // Open the file.
  1803. doc->setEncoding(preferences.useCalcCharset?"TI-89":QTextCodec::codecForLocale()->name());
  1804. if (!fileName.isNull()) doc->openUrl(KUrl(fileName));
  1805. // Set text.
  1806. if (!fileText.isNull()) {
  1807. SET_TEXT_SAFE(doc,fileText);
  1808. doc->setModified(FALSE);
  1809. // clearUndo and clearRedo are not in any interface, but they are public slots...
  1810. doc->qt_metacall(QMetaObject::InvokeMetaMethod,
  1811. doc->metaObject()->indexOfMethod("clearUndo()"),NULL);
  1812. doc->qt_metacall(QMetaObject::InvokeMetaMethod,
  1813. doc->metaObject()->indexOfMethod("clearRedo()"),NULL);
  1814. }
  1815. // Create View object.
  1816. KTextEditor::View *newView = (KTextEditor::View *) doc->createView(widgetStack);
  1817. newView->hide();
  1818. newView->setSizePolicy(QSizePolicy(QSizePolicy::Ignored,QSizePolicy::Ignored,0,0));
  1819. // Set highlighting mode.
  1820. QString firstLine;
  1821. if (doc->lines()) firstLine=doc->line(0);
  1822. newView->document()->setHighlightingMode(
  1823. (category==qllFilesListItem?
  1824. QLL_HL_MODE:
  1825. (category==sFilesListItem||(category==hFilesListItem&&!firstLine.isEmpty()&&firstLine[0]=='|'))?
  1826. S_HL_MODE:
  1827. (category==asmFilesListItem||(category==hFilesListItem&&!firstLine.isEmpty()&&firstLine[0]==';'))?
  1828. ASM_HL_MODE:
  1829. (category==cFilesListItem||category==hFilesListItem)?
  1830. C_HL_MODE:
  1831. "None"));
  1832. // Set options.
  1833. KTextEditor::ConfigInterface *configiface
  1834. =qobject_cast<KTextEditor::ConfigInterface*>(newView);
  1835. configiface->setConfigValue("dynamic-word-wrap",false);
  1836. if (preferences.removeTrailingSpaces) {
  1837. sendCommand(newView,"set-remove-trailing-space 1");
  1838. sendCommand(newView,"set-remove-trailing-space-save 1");
  1839. } else {
  1840. sendCommand(newView,"set-remove-trailing-space 0");
  1841. sendCommand(newView,"set-remove-trailing-space-save 0");
  1842. }
  1843. setTabWidth(newView,
  1844. (category==sFilesListItem||category==asmFilesListItem||((category==hFilesListItem&&!firstLine.isEmpty()&&(firstLine[0]=='|'||firstLine[0]==';'))))?preferences.tabWidthAsm:
  1845. (category==cFilesListItem||category==qllFilesListItem||category==hFilesListItem)?preferences.tabWidthC:
  1846. 8
  1847. );
  1848. connect(newView,SIGNAL(cursorPositionChanged(KTextEditor::View*,const KTextEditor::Cursor&)),this,SLOT(current_view_cursorPositionChanged(KTextEditor::View*,const KTextEditor::Cursor&)));
  1849. connect(newView,SIGNAL(textInserted(KTextEditor::View*,const KTextEditor::Cursor&,const QString&)),
  1850. this,SLOT(current_view_textInserted(KTextEditor::View*,const KTextEditor::Cursor&,const QString&)));
  1851. connect(newView,SIGNAL(selectionChanged(KTextEditor::View*)),this,SLOT(current_view_selectionChanged(KTextEditor::View*)));
  1852. connect(newView->document(),SIGNAL(textChanged(KTextEditor::Document*)),this,SLOT(current_view_textChanged(KTextEditor::Document*)));
  1853. connect(newView->document(),SIGNAL(undoChanged()),this,SLOT(current_view_undoChanged()));
  1854. newView->setContextMenu(te_popup);
  1855. newView->setCursorPosition(KTextEditor::Cursor(0,0));
  1856. newView->action(KStandardAction::name(KStandardAction::Find))->setShortcut(QKeySequence());
  1857. return newView;
  1858. }
  1859. void MainForm::adoptSourceFile(void *srcFile)
  1860. {
  1861. if (compiling) return;
  1862. SourceFileWindow *sourceFile=reinterpret_cast<SourceFileWindow *>(srcFile);
  1863. QString fileName=sourceFile->fileName;
  1864. KTextEditor::View *newView=sourceFile->kateView;
  1865. // Determine category and caption.
  1866. Q3ListViewItem *category=othFilesListItem;
  1867. QString suffix,caption;
  1868. int p;
  1869. p=fileName.findRev('/');
  1870. if (p<0) p=-1;
  1871. caption=fileName.mid(p+1);
  1872. p=caption.findRev('.');
  1873. if (p>=0) {
  1874. suffix=caption.mid(p+1);
  1875. caption.truncate(p);
  1876. }
  1877. if (!checkFileName(fileName,extractAllFileNames())) {
  1878. KMessageBox::error(this,QString("The file \'%1\' is already included in the project.").arg(caption));
  1879. return;
  1880. }
  1881. if (!suffix.compare("h"))
  1882. category=hFilesListItem;
  1883. else if (!suffix.compare("c"))
  1884. category=cFilesListItem;
  1885. else if (!suffix.compare("s"))
  1886. category=sFilesListItem;
  1887. else if (!suffix.compare("asm"))
  1888. category=asmFilesListItem;
  1889. else if (!suffix.compare("qll"))
  1890. category=qllFilesListItem;
  1891. else
  1892. category=txtFilesListItem;
  1893. if (category && category==qllFilesListItem && qllFileCount) {
  1894. KMessageBox::error(this,"There may be only one Quill source file in each project.","Quill Error");
  1895. return;
  1896. }
  1897. if (!category)
  1898. category=txtFilesListItem;
  1899. // Create file tree entry.
  1900. Q3ListViewItem *item=NULL, *next=category->firstChild();
  1901. for (; IS_FILE(next); next=item->nextSibling())
  1902. item=next;
  1903. ListViewFile *newFile=item?new ListViewFile(category,item)
  1904. :new ListViewFile(category);
  1905. newFile->isNew=FALSE;
  1906. newFile->setText(0,caption);
  1907. newFile->setPixmap(0,
  1908. category==cFilesListItem||category==qllFilesListItem?SYSICON("source-c","filec.png"):
  1909. category==hFilesListItem?SYSICON("source-h","fileh.png"):
  1910. category==sFilesListItem||category==asmFilesListItem?SYSICON("source-s","files.png"):
  1911. SYSICON("txt","filet.png"));
  1912. newFile->fileName=fileName;
  1913. newFile->modifiedSinceLastCompile=newView->document()->isModified();
  1914. // Adopt View object.
  1915. newFile->kateView=newView;
  1916. newView->hide();
  1917. newView->reparent(widgetStack,QPoint());
  1918. newView->setSizePolicy(QSizePolicy(QSizePolicy::Ignored,QSizePolicy::Ignored,0,0));
  1919. KDirWatch::self()->addFile(fileName);
  1920. fileCount++;
  1921. COUNTER_FOR_CATEGORY(category)++;
  1922. // Set highlighting mode.
  1923. QString fileText=newView->document()->text();
  1924. newView->document()->setHighlightingMode(
  1925. (category==qllFilesListItem?
  1926. QLL_HL_MODE:
  1927. (category==sFilesListItem||(category==hFilesListItem&&!fileText.isNull()&&!fileText.isEmpty()&&fileText[0]=='|'))?
  1928. S_HL_MODE:
  1929. (category==asmFilesListItem||(category==hFilesListItem&&!fileText.isNull()&&!fileText.isEmpty()&&fileText[0]==';'))?
  1930. ASM_HL_MODE:
  1931. (category==cFilesListItem||category==hFilesListItem)?
  1932. C_HL_MODE:
  1933. "None"));
  1934. // Set options.
  1935. setTabWidth(newView,
  1936. (category==sFilesListItem||category==asmFilesListItem||((category==hFilesListItem&&!fileText.isNull()&&!fileText.isEmpty()&&(fileText[0]=='|'||fileText[0]==';'))))?preferences.tabWidthAsm:
  1937. (category==cFilesListItem||category==qllFilesListItem||category==hFilesListItem)?preferences.tabWidthC:
  1938. 8
  1939. );
  1940. connect(newView,SIGNAL(cursorPositionChanged(KTextEditor::View*,const KTextEditor::Cursor&)),this,SLOT(current_view_cursorPositionChanged(KTextEditor::View*,const KTextEditor::Cursor&)));
  1941. connect(newView,SIGNAL(textInserted(KTextEditor::View*,const KTextEditor::Cursor&,const QString&)),
  1942. this,SLOT(current_view_textInserted(KTextEditor::View*,const KTextEditor::Cursor&,const QString&)));
  1943. connect(newView,SIGNAL(selectionChanged(KTextEditor::View*)),this,SLOT(current_view_selectionChanged(KTextEditor::View*)));
  1944. connect(newView->document(),SIGNAL(textChanged(KTextEditor::Document*)),this,SLOT(current_view_textChanged(KTextEditor::Document*)));
  1945. connect(newView->document(),SIGNAL(undoChanged()),this,SLOT(current_view_undoChanged()));
  1946. newView->setContextMenu(te_popup);
  1947. // Mark project dirty.
  1948. projectIsDirty=TRUE;
  1949. projectNeedsRelink=TRUE;
  1950. // Select file.
  1951. fileTreeClicked(newFile);
  1952. // Update errors to point to the in-project source file instead of the
  1953. // external one.
  1954. Q3ListViewItemIterator lvit(errorList->errorListView);
  1955. Q3ListViewItem *errorItem;
  1956. for (errorItem=lvit.current();errorItem;errorItem=(++lvit).current()) {
  1957. if (static_cast<ErrorListItem *>(errorItem)->srcFile==sourceFile) {
  1958. static_cast<ErrorListItem *>(errorItem)->srcFile=static_cast<SourceFileWindow *>(NULL);
  1959. static_cast<ErrorListItem *>(errorItem)->lvFile=newFile;
  1960. }
  1961. }
  1962. // Close separate source view.
  1963. sourceFile->kateView=static_cast<KTextEditor::View *>(NULL);
  1964. sourceFile->deleteLater();
  1965. }
  1966. void MainForm::fileOpen_addList(Q3ListViewItem *category,void *fileListV,void *dir, const QString &open_file)
  1967. {
  1968. int i,e;
  1969. int p,pslash;
  1970. KUrl tmp;
  1971. TPRFileList *fileList=(TPRFileList*)fileListV;
  1972. QString caption;
  1973. QString treePath;
  1974. Q3ListViewItem *parent;
  1975. e=fileList->path.count();
  1976. if (e) category->setOpen(TRUE);
  1977. for (i=0;i<e;i++)
  1978. {
  1979. tmp=*reinterpret_cast<const KUrl *>(dir);
  1980. kurlNewFileName(tmp,fileList->path[i]);
  1981. caption=fileList->path[i];
  1982. //fixed suffix truncation for file paths such as "/root/.dot/nodot" so it wouldn't truncate to "/root/"
  1983. p=caption.findRev('.');
  1984. pslash=caption.findRev('/');
  1985. if (p>=0&&p>pslash) caption.truncate(p);
  1986. if (pslash>=0) caption.remove(0,pslash+1);
  1987. treePath=fileList->folder[i].trimmed();
  1988. //check for a backslash at the end and remove it if it's there.
  1989. if (!treePath.isEmpty() && treePath[treePath.length()-1]=='\\')
  1990. treePath.truncate(treePath.length()-1);
  1991. parent=category;
  1992. if (!treePath.isEmpty())
  1993. {
  1994. while ((p=treePath.find('\\'))>=0)
  1995. {
  1996. parent=createFolder(parent,treePath.left(p));
  1997. treePath.remove(0,p+1);
  1998. }
  1999. parent=createFolder(parent,treePath);
  2000. }
  2001. ListViewFile *newFile=static_cast<ListViewFile *>(openFile(category,parent,caption,tmp.path()));
  2002. if (!newFile) continue;
  2003. if (!newFile->fileName.compare(open_file))
  2004. fileTreeClicked(newFile);
  2005. }
  2006. }
  2007. // Returns TRUE if the file is a project, FALSE if the file is a source file.
  2008. bool MainForm::openProject(const QString &fileName)
  2009. {
  2010. TPRDataStruct TPRData;
  2011. KUrl dir;
  2012. bool isProject=fileName.endsWith(".tpr",FALSE);
  2013. dir.setPath(fileName);
  2014. switch (getPathType(fileName)) {
  2015. case PATH_FILE: // OK
  2016. break;
  2017. case PATH_NOTFOUND:
  2018. KMessageBox::error(this,QString("File \'%1\' not found").arg(fileName));
  2019. return isProject;
  2020. default:
  2021. KMessageBox::error(this,QString("\'%1\' is not a regular file").arg(fileName));
  2022. return isProject;
  2023. }
  2024. if (isProject) {
  2025. int ret=loadTPR(fileName, &TPRData);
  2026. if (ret == -1) {
  2027. KMessageBox::error(this,QString("Can't open \'%1\'").arg(fileName));
  2028. return TRUE;
  2029. }
  2030. if (ret > 0) {
  2031. KMessageBox::error(this,QString("Error at line %2 of \'%1\'").arg(fileName).arg(ret));
  2032. return TRUE;
  2033. }
  2034. if (TPRData.asm_files.path.count() && !asmFilesListItem) {
  2035. KMessageBox::error(this,"This project needs A68k, which is not installed.");
  2036. return TRUE;
  2037. }
  2038. if (TPRData.quill_files.path.count() && !qllFilesListItem) {
  2039. KMessageBox::error(this,"This project needs quill.drv, which is not installed.");
  2040. return TRUE;
  2041. }
  2042. if (TPRData.settings.fargo && !have_fargo) {
  2043. KMessageBox::error(this,"This project needs fargo.a, which is not installed.");
  2044. return TRUE;
  2045. }
  2046. if (TPRData.settings.flash_os && !have_flashos) {
  2047. KMessageBox::error(this,"This project needs flashos.a, which is not installed.");
  2048. return TRUE;
  2049. }
  2050. clearProject();
  2051. fileOpen_addList(hFilesListItem,&TPRData.h_files,&dir,TPRData.open_file);
  2052. fileOpen_addList(cFilesListItem,&TPRData.c_files,&dir,TPRData.open_file);
  2053. fileOpen_addList(qllFilesListItem,&TPRData.quill_files,&dir,TPRData.open_file);
  2054. fileOpen_addList(sFilesListItem,&TPRData.s_files,&dir,TPRData.open_file);
  2055. fileOpen_addList(asmFilesListItem,&TPRData.asm_files,&dir,TPRData.open_file);
  2056. fileOpen_addList(oFilesListItem,&TPRData.o_files,&dir,TPRData.open_file);
  2057. fileOpen_addList(aFilesListItem,&TPRData.a_files,&dir,TPRData.open_file);
  2058. fileOpen_addList(txtFilesListItem,&TPRData.txt_files,&dir,TPRData.open_file);
  2059. fileOpen_addList(othFilesListItem,&TPRData.oth_files,&dir,TPRData.open_file);
  2060. rootListItem->setText(0,TPRData.prj_name);
  2061. projectFileName=fileName;
  2062. settings=TPRData.settings;
  2063. libopts=TPRData.libopts;
  2064. bool runnable=!settings.archive&&!settings.flash_os&&preferences.linkTarget!=LT_NONE;
  2065. menuBar()->setItemVisible(5,runnable); //debugMenu
  2066. debugRunAction->setVisible(runnable);
  2067. debugPauseAction->setVisible(runnable);
  2068. updateLeftStatusLabel();
  2069. updateRightStatusLabel();
  2070. addRecent(fileName);
  2071. return TRUE;
  2072. } else {
  2073. Q3ListViewItem *category=othFilesListItem;
  2074. QString suffix,caption;
  2075. int p;
  2076. p=fileName.findRev('/');
  2077. if (p<0) p=-1;
  2078. caption=fileName.mid(p+1);
  2079. p=caption.findRev('.');
  2080. if (p>=0) {
  2081. suffix=caption.mid(p+1);
  2082. caption.truncate(p);
  2083. }
  2084. if (extractAllFileNames().contains(fileName)) {
  2085. KMessageBox::error(this,QString("The file \'%1\' is already included in the project.").arg(caption));
  2086. return FALSE;
  2087. }
  2088. foreach (SourceFileWindow *sourceFile, sourceFiles) {
  2089. if (!fileName.compare(sourceFile->fileName)) {
  2090. ACTIVATE_WINDOW(sourceFile->winId());
  2091. return FALSE;
  2092. }
  2093. }
  2094. if (!suffix.compare("h"))
  2095. category=hFilesListItem;
  2096. else if (!suffix.compare("c"))
  2097. category=cFilesListItem;
  2098. else if (!suffix.compare("s"))
  2099. category=sFilesListItem;
  2100. else if (!suffix.compare("asm") && asmFilesListItem)
  2101. category=asmFilesListItem;
  2102. else if (!suffix.compare("qll") && qllFilesListItem)
  2103. category=qllFilesListItem;
  2104. else if (!suffix.compare("txt"))
  2105. category=txtFilesListItem;
  2106. else {
  2107. KMessageBox::error(this,QString("\'%1\' is not a valid file for opening.").arg(fileName));
  2108. return FALSE;
  2109. }
  2110. int firstChar=peekFirstChar(fileName);
  2111. if (firstChar==-2) {
  2112. KMessageBox::error(this,QString("Can't open \'%1\'").arg(fileName));
  2113. return FALSE;
  2114. }
  2115. int type=((category==sFilesListItem||(category==hFilesListItem&&firstChar=='|'))?
  2116. 2:
  2117. (category==asmFilesListItem||(category==hFilesListItem&&firstChar==';'))?
  2118. 3:
  2119. (category==cFilesListItem||category==qllFilesListItem||category==hFilesListItem)?
  2120. 1:
  2121. 0);
  2122. new SourceFileWindow(this,fileName,
  2123. (category==qllFilesListItem)?QLL_ENABLED_HL_MODE:
  2124. (type==2)?S_ENABLED_HL_MODE:
  2125. (type==3)?ASM_ENABLED_HL_MODE:
  2126. (type==1)?C_ENABLED_HL_MODE:
  2127. "None",
  2128. (category==qllFilesListItem)?&(preferences.synQll.enabled):
  2129. (type==2)?&(preferences.synS.enabled):
  2130. (type==3)?&(preferences.synAsm.enabled):
  2131. (type==1)?&(preferences.synC.enabled):
  2132. NULL,category,(type==1),(type>1),category==txtFilesListItem);
  2133. return FALSE;
  2134. }
  2135. }
  2136. void MainForm::fileOpen()
  2137. {
  2138. if (compiling || savePrompt())
  2139. return;
  2140. QString fileName=SGetFileName(KFileDialog::Opening,findFilter(TIGCCOpenProjectFileFilter),"Open Project/File",this);
  2141. KUrl dir;
  2142. dir.setPath(fileName);
  2143. if (fileName.isEmpty())
  2144. return;
  2145. openProject(fileName);
  2146. }
  2147. void MainForm::fileRecent1()
  2148. {
  2149. QString recentFile=fileRecent1Action->statusTip();
  2150. if (compiling || savePrompt())
  2151. return;
  2152. openProject(recentFile);
  2153. }
  2154. void MainForm::fileRecent2()
  2155. {
  2156. QString recentFile=fileRecent2Action->statusTip();
  2157. if (compiling || savePrompt())
  2158. return;
  2159. openProject(recentFile);
  2160. }
  2161. void MainForm::fileRecent3()
  2162. {
  2163. QString recentFile=fileRecent3Action->statusTip();
  2164. if (compiling || savePrompt())
  2165. return;
  2166. openProject(recentFile);
  2167. }
  2168. void MainForm::fileRecent4()
  2169. {
  2170. QString recentFile=fileRecent4Action->statusTip();
  2171. if (compiling || savePrompt())
  2172. return;
  2173. openProject(recentFile);
  2174. }
  2175. int MainForm::fileSavePrompt(Q3ListViewItem *fileItem)
  2176. {
  2177. int result;
  2178. ListViewFile *theFile=static_cast<ListViewFile *>(fileItem);
  2179. if (!theFile->kateView) return 0;
  2180. while (theFile->kateView->document()->isModified()) { // "while" in case saving fails!
  2181. result=KMessageBox::questionYesNoCancel(this,QString("The file \'%1\' has been modified. Do you want to save the changes?").arg(theFile->text(0)),QString::null,KStandardGuiItem::save(),KStandardGuiItem::discard());
  2182. if (result==KMessageBox::Yes)
  2183. fileSave_save(fileItem);
  2184. else if (result==KMessageBox::No)
  2185. return 0;
  2186. else
  2187. return 1;
  2188. }
  2189. return 0;
  2190. }
  2191. //returns 1 if the current project data should not be cleared out, 0 if it can be cleared out.
  2192. int MainForm::savePrompt(void)
  2193. {
  2194. int result;
  2195. while (projectIsDirty) {
  2196. result=KMessageBox::questionYesNoCancel(this,"The current project has been modified. Do you want to save the changes?",QString::null,KStandardGuiItem::save(),KStandardGuiItem::discard());
  2197. if (result==KMessageBox::Yes)
  2198. fileSave();
  2199. else if (result==KMessageBox::No)
  2200. return 0;
  2201. else
  2202. return 1;
  2203. }
  2204. Q3ListViewItem *item=rootListItem->firstChild(),*next;
  2205. while (item)
  2206. {
  2207. if (IS_FOLDER(item))
  2208. {
  2209. next=item->firstChild();
  2210. if (next)
  2211. {
  2212. item=next;
  2213. continue;
  2214. }
  2215. }
  2216. if (IS_FILE(item))
  2217. {
  2218. if (fileSavePrompt(item))
  2219. return 1;
  2220. }
  2221. next=item->nextSibling();
  2222. while (!next)
  2223. {
  2224. next=item->parent();
  2225. if (next==rootListItem||!next)
  2226. {
  2227. return 0;
  2228. }
  2229. item=next;
  2230. next=item->nextSibling();
  2231. }
  2232. item=next;
  2233. }
  2234. return 0;
  2235. }
  2236. void MainForm::removeTrailingSpacesFromView(void *view)
  2237. {
  2238. if (!preferences.removeTrailingSpaces) return;
  2239. KTextEditor::View *kateView=reinterpret_cast<KTextEditor::View *>(view);
  2240. KTextEditor::Document *doc=kateView->document();
  2241. doc->startEditing();
  2242. int numLines=doc->lines();
  2243. for (int i=0; i<numLines; i++) {
  2244. QString line=doc->line(i);
  2245. int whitespace=line.find(QRegExp("\\s+$"));
  2246. if (whitespace>=0) doc->removeText(KTextEditor::Range(i,whitespace,i,line.length()));
  2247. }
  2248. doc->endEditing();
  2249. }
  2250. void MainForm::fileSave_save(Q3ListViewItem *theItem)
  2251. {
  2252. if (!IS_FILE(theItem))
  2253. return;
  2254. CATEGORY_OF(category,theItem);
  2255. if (!IS_EDITABLE_CATEGORY(category))
  2256. return;
  2257. ListViewFile *theFile=static_cast<ListViewFile *>(theItem);
  2258. if (!theFile->fileName.isEmpty() && theFile->fileName[0]!='/') {
  2259. fileSave_saveAs(theFile);
  2260. }
  2261. else {
  2262. KDirWatch::self()->removeFile(theFile->fileName);
  2263. if (!theFile->kateView->document()->save()) {
  2264. KMessageBox::error(this,QString("Can't save to \'%1\'").arg(theFile->text(0)));
  2265. KDirWatch::self()->addFile(theFile->fileName);
  2266. }
  2267. else {
  2268. KDirWatch::self()->addFile(theFile->fileName);
  2269. theFile->isNew=FALSE;
  2270. if (theFile->kateView) {
  2271. removeTrailingSpacesFromView(theFile->kateView);
  2272. theFile->kateView->document()->setModified(FALSE);
  2273. }
  2274. projectIsDirty=TRUE;
  2275. projectNeedsRelink=TRUE;
  2276. }
  2277. }
  2278. }
  2279. void MainForm::fileSave_saveAs(Q3ListViewItem *theItem)
  2280. {
  2281. if (!IS_FILE(theItem))
  2282. return;
  2283. CATEGORY_OF(category,theItem);
  2284. QString saveFileName=SGetFileName(KFileDialog::Saving,
  2285. category==hFilesListItem?TIGCC_H_Filter TIGCCAllFilter:
  2286. category==cFilesListItem?TIGCC_C_Filter TIGCCAllFilter:
  2287. category==sFilesListItem?TIGCC_S_Filter TIGCCAllFilter:
  2288. category==asmFilesListItem?TIGCC_ASM_Filter TIGCCAllFilter:
  2289. category==qllFilesListItem?TIGCC_QLL_Filter TIGCCAllFilter:
  2290. category==oFilesListItem?TIGCC_O_Filter TIGCCAllFilter:
  2291. category==aFilesListItem?TIGCC_A_Filter TIGCCAllFilter:
  2292. category==txtFilesListItem?TIGCC_TXT_Filter TIGCCAllFilter:
  2293. TIGCCAllFilter
  2294. ,"Save Source File",this);
  2295. ListViewFile *theFile=static_cast<ListViewFile *>(theItem);
  2296. if (saveFileName.isEmpty()
  2297. || (!IS_EDITABLE_CATEGORY(category)
  2298. && !saveFileName.compare(theFile->fileName)))
  2299. return;
  2300. if (saveFileName.compare(theFile->fileName)
  2301. && !checkFileName(saveFileName,extractAllFileNames())) {
  2302. KMessageBox::error(this,"The name you chose conflicts with that of another file.");
  2303. return;
  2304. }
  2305. if (!theFile->fileName.isEmpty() && theFile->fileName[0]=='/')
  2306. KDirWatch::self()->removeFile(theFile->fileName);
  2307. mkdir_multi(saveFileName);
  2308. if (IS_EDITABLE_CATEGORY(category)
  2309. ?!theFile->kateView->document()->saveAs(saveFileName)
  2310. :copyFile(theFile->fileName,saveFileName)) {
  2311. KMessageBox::error(this,QString("Can't save to \'%1\'").arg(saveFileName));
  2312. if (IS_EDITABLE_CATEGORY(category) && !theFile->fileName.isEmpty() && theFile->fileName[0]=='/')
  2313. KDirWatch::self()->addFile(theFile->fileName);
  2314. } else {
  2315. theFile->fileName=saveFileName;
  2316. if (IS_EDITABLE_CATEGORY(category)) {
  2317. KDirWatch::self()->addFile(saveFileName);
  2318. removeTrailingSpacesFromView(theFile->kateView);
  2319. theFile->kateView->document()->setModified(FALSE);
  2320. }
  2321. theFile->isNew=FALSE;
  2322. updateRightStatusLabel();
  2323. projectIsDirty=TRUE;
  2324. projectNeedsRelink=TRUE;
  2325. }
  2326. }
  2327. //loadList also saves the file contents
  2328. void MainForm::fileSave_loadList(Q3ListViewItem *category,void *fileListV,const QString &base_dir,void *dir_new,QString *open_file)
  2329. {
  2330. if (!category)
  2331. return;
  2332. TPRFileList *fileList=(TPRFileList*)fileListV;
  2333. KUrl *new_dir=(KUrl*)dir_new;
  2334. KUrl tmpPath;
  2335. Q3ListViewItem *item=category->firstChild();
  2336. Q3ListViewItem *next;
  2337. QString folderSpec=QString::null;
  2338. int o;
  2339. while (item)
  2340. {
  2341. if (IS_FILE(item))
  2342. {
  2343. ListViewFile *theFile=static_cast<ListViewFile *>(item);
  2344. QString absPath=theFile->fileName;
  2345. QString relPath=KUrl::relativePath(base_dir,absPath);
  2346. if (relPath.startsWith("./"))
  2347. {
  2348. relPath=relPath.mid(2);
  2349. }
  2350. else if (relPath.startsWith("../"))
  2351. {
  2352. relPath=absPath;
  2353. }
  2354. tmpPath=*new_dir;
  2355. kurlNewFileName(tmpPath,relPath);
  2356. if (!theFile->fileName.isEmpty() && theFile->fileName[0]=='/')
  2357. KDirWatch::self()->removeFile(theFile->fileName);
  2358. if (tmpPath.path().compare(theFile->fileName)
  2359. || (IS_EDITABLE_CATEGORY(category)
  2360. && (theFile->kateView->document()->isModified() || theFile->isNew))) {
  2361. mkdir_multi(tmpPath.path());
  2362. if (IS_EDITABLE_CATEGORY(category)
  2363. ?!theFile->kateView->document()->saveAs(tmpPath.path())
  2364. :copyFile(theFile->fileName,tmpPath.path())) {
  2365. KMessageBox::error(this,QString("Can't save to \'%1\'").arg(tmpPath.path()));
  2366. if (IS_EDITABLE_CATEGORY(category) && !theFile->fileName.isEmpty() && theFile->fileName[0]=='/')
  2367. KDirWatch::self()->addFile(theFile->fileName);
  2368. } else {
  2369. QString saveFileName=tmpPath.path();
  2370. theFile->fileName=saveFileName;
  2371. if (IS_EDITABLE_CATEGORY(category)) {
  2372. KDirWatch::self()->addFile(theFile->fileName);
  2373. removeTrailingSpacesFromView(theFile->kateView);
  2374. theFile->kateView->document()->setModified(FALSE);
  2375. }
  2376. theFile->isNew=FALSE;
  2377. projectIsDirty=TRUE; // in case saving the project fails
  2378. projectNeedsRelink=TRUE;
  2379. }
  2380. }
  2381. fileList->path << relPath;
  2382. fileList->folder << folderSpec;
  2383. if (item==currentListItem)
  2384. *open_file=theFile->fileName;
  2385. }
  2386. else if (IS_FOLDER(item))
  2387. {
  2388. next=item->firstChild();
  2389. if (next)
  2390. {
  2391. if (folderSpec.isEmpty())
  2392. folderSpec=item->text(0);
  2393. else
  2394. {
  2395. folderSpec+='\\';
  2396. folderSpec+=item->text(0);
  2397. }
  2398. item=next;
  2399. continue;
  2400. }
  2401. }
  2402. fsll_seeknext:
  2403. next=item->nextSibling();
  2404. if (!next)
  2405. {
  2406. next=item->parent();
  2407. if (next==category||!next)
  2408. break;
  2409. item=next;
  2410. o=folderSpec.findRev('\\');
  2411. if (o>=0)
  2412. folderSpec.truncate(o);
  2413. else
  2414. folderSpec.truncate(0);
  2415. goto fsll_seeknext;
  2416. }
  2417. item=next;
  2418. }
  2419. }
  2420. void MainForm::fileSave_fromto(const QString &lastProj,const QString &nextProj)
  2421. {
  2422. TPRDataStruct TPRData;
  2423. QString open_file;
  2424. KUrl base_dir_k(lastProj);
  2425. base_dir_k.setFileName("");
  2426. QString base_dir=base_dir_k.path();
  2427. KUrl new_dir(nextProj);
  2428. fileSave_loadList(hFilesListItem,&TPRData.h_files,base_dir,&new_dir,&open_file);
  2429. fileSave_loadList(cFilesListItem,&TPRData.c_files,base_dir,&new_dir,&open_file);
  2430. fileSave_loadList(qllFilesListItem,&TPRData.quill_files,base_dir,&new_dir,&open_file);
  2431. fileSave_loadList(sFilesListItem,&TPRData.s_files,base_dir,&new_dir,&open_file);
  2432. fileSave_loadList(asmFilesListItem,&TPRData.asm_files,base_dir,&new_dir,&open_file);
  2433. fileSave_loadList(oFilesListItem,&TPRData.o_files,base_dir,&new_dir,&open_file);
  2434. fileSave_loadList(aFilesListItem,&TPRData.a_files,base_dir,&new_dir,&open_file);
  2435. fileSave_loadList(txtFilesListItem,&TPRData.txt_files,base_dir,&new_dir,&open_file);
  2436. fileSave_loadList(othFilesListItem,&TPRData.oth_files,base_dir,&new_dir,&open_file);
  2437. if (projectFileName.isEmpty() && rootListItem->text(0)=="Project1")
  2438. fileTreeItemRenamed(rootListItem,QFileInfo(nextProj).baseName(),0);
  2439. TPRData.prj_name=rootListItem->text(0);
  2440. TPRData.open_file=open_file;
  2441. TPRData.settings=settings;
  2442. TPRData.libopts=libopts;
  2443. if (saveTPR(nextProj,&TPRData)) {
  2444. KMessageBox::error(this,QString("Can't save to \'%1\'").arg(nextProj));
  2445. updateRightStatusLabel();
  2446. return;
  2447. } else {
  2448. projectFileName=nextProj;
  2449. projectIsDirty=FALSE;
  2450. addRecent(nextProj);
  2451. }
  2452. updateRightStatusLabel();
  2453. foreach (SourceFileWindow *sourceFile, sourceFiles) {
  2454. if (sourceFile->kateView->document()->isModified())
  2455. sourceFile->fileSave();
  2456. }
  2457. }
  2458. bool MainForm::fileSave()
  2459. {
  2460. if (projectFileName.isEmpty())
  2461. return fileSaveAs();
  2462. else {
  2463. fileSave_fromto(projectFileName,projectFileName);
  2464. return TRUE;
  2465. }
  2466. }
  2467. bool MainForm::fileSaveAs()
  2468. {
  2469. QString fileName=SGetFileName(KFileDialog::Saving,TIGCC_TPR_Filter TIGCCAllFilter,"Save Project",this);
  2470. if (fileName.isEmpty())
  2471. return FALSE;
  2472. fileSave_fromto(projectFileName.isEmpty()?fileName:projectFileName,fileName);
  2473. return TRUE;
  2474. }
  2475. void MainForm::filePrint()
  2476. {
  2477. if (CURRENT_VIEW) CURRENT_VIEW->action(KStandardAction::name(KStandardAction::Print))->trigger();
  2478. }
  2479. void MainForm::filePrintQuickly()
  2480. {
  2481. // This still shows the print dialog, but then KDE 3.5 Kate did that too
  2482. // despite having 2 nominally different APIs (print and printDialog).
  2483. if (CURRENT_VIEW) CURRENT_VIEW->action(KStandardAction::name(KStandardAction::Print))->trigger();
  2484. }
  2485. void MainForm::filePreferences()
  2486. {
  2487. if (showPreferencesDialog(this,!!asmFilesListItem,!!qllFilesListItem)
  2488. ==QDialog::Accepted) {
  2489. // Apply the KatePart preferences and treeview icons.
  2490. Q3ListViewItemIterator it(fileTree);
  2491. Q3ListViewItem *item;
  2492. // Kate seems really insisting on making it a pain to update syntax highlighting settings.
  2493. for (item=it.current();item;item=(++it).current()) {
  2494. if (IS_FILE(item)) {
  2495. KTextEditor::View *kateView=static_cast<ListViewFile *>(item)->kateView;
  2496. if (kateView) {
  2497. kateView->document()->setHighlightingMode("None");
  2498. }
  2499. }
  2500. }
  2501. foreach (SourceFileWindow *sourceFile, sourceFiles) {
  2502. sourceFile->kateView->document()->setHighlightingMode("None");
  2503. }
  2504. KParts::Factory *factory=(KParts::Factory *)
  2505. KLibLoader::self()->factory("katepart");
  2506. if (!factory) qFatal("Failed to load KatePart");
  2507. KTextEditor::Document *doc=(KTextEditor::Document *)
  2508. factory->createPart(0,this,"KTextEditor::Document");
  2509. doc->setHighlightingMode("Asm6502"); // Don't ask...
  2510. doc->setHighlightingMode("None");
  2511. KTextEditor::Editor *editor=doc->editor();
  2512. int numConfigPages=editor->configPages();
  2513. for (int i=0; i<numConfigPages; i++) {
  2514. if (editor->configPageName(i)=="Fonts & Colors") {
  2515. KTextEditor::ConfigPage *configPage=editor->configPage(i,this);
  2516. configPage->apply();
  2517. delete configPage;
  2518. break;
  2519. }
  2520. }
  2521. delete doc;
  2522. it=Q3ListViewItemIterator(fileTree);
  2523. for (item=it.current();item;item=(++it).current()) {
  2524. if (item == rootListItem) {
  2525. item->setPixmap(0,SYSICON("exec","tpr.png"));
  2526. } else if (IS_FOLDER(item)) {
  2527. // Bluecurve's "folder-open" isn't actually more open than "folder".
  2528. item->setPixmap(0,(item==currentListItem)?SYSICON(KIconTheme::current()=="Bluecurve"?"folder-accept":"folder-open","folder2.png")
  2529. :SYSICON("folder","folder1.png"));
  2530. } else if (IS_FILE(item)) {
  2531. CATEGORY_OF(category,item);
  2532. KTextEditor::View *kateView=static_cast<ListViewFile *>(item)->kateView;
  2533. if (kateView) {
  2534. QString fileText=kateView->document()->text();
  2535. CATEGORY_OF(category,item);
  2536. if (preferences.removeTrailingSpaces) {
  2537. sendCommand(kateView,"set-remove-trailing-space 1");
  2538. sendCommand(kateView,"set-remove-trailing-space-save 1");
  2539. } else {
  2540. sendCommand(kateView,"set-remove-trailing-space 0");
  2541. sendCommand(kateView,"set-remove-trailing-space-save 0");
  2542. }
  2543. setTabWidth(kateView,
  2544. (category==sFilesListItem||category==asmFilesListItem||((category==hFilesListItem&&!fileText.isNull()&&!fileText.isEmpty()&&(fileText[0]=='|'||fileText[0]==';'))))?preferences.tabWidthAsm:
  2545. (category==cFilesListItem||category==qllFilesListItem||category==hFilesListItem)?preferences.tabWidthC:
  2546. 8
  2547. );
  2548. // Kate seems really insisting on making it a pain to update syntax highlighting settings.
  2549. kateView->document()->setHighlightingMode(
  2550. (category==qllFilesListItem?
  2551. QLL_HL_MODE:
  2552. (category==sFilesListItem||(category==hFilesListItem&&!fileText.isNull()&&!fileText.isEmpty()&&fileText[0]=='|'))?
  2553. S_HL_MODE:
  2554. (category==asmFilesListItem||(category==hFilesListItem&&!fileText.isNull()&&!fileText.isEmpty()&&fileText[0]==';'))?
  2555. ASM_HL_MODE:
  2556. (category==cFilesListItem||category==hFilesListItem)?
  2557. C_HL_MODE:
  2558. "None"));
  2559. }
  2560. item->setPixmap(0,
  2561. category==cFilesListItem||category==qllFilesListItem?SYSICON("source-c","filec.png"):
  2562. category==hFilesListItem?SYSICON("source-h","fileh.png"):
  2563. category==sFilesListItem||category==asmFilesListItem?SYSICON("source-s","files.png"):
  2564. category==txtFilesListItem?SYSICON("txt","filet.png"):
  2565. category==oFilesListItem||category==aFilesListItem?SYSICON("binary","fileo.png"):
  2566. SYSICON("unknown","filex.png"));
  2567. } else qWarning("Internal error: What's this item?");
  2568. }
  2569. KTextEditor::View *currView=CURRENT_VIEW;
  2570. if (currView) {
  2571. // Force redrawing to get the tab width right, repaint() is ignored for some reason.
  2572. currView->hide();
  2573. currView->show();
  2574. }
  2575. // Apply the icon preferences.
  2576. if (preferences.useSystemIcons) {
  2577. // Set the preferred icon size so system toolbar icons don't get annoying
  2578. // padding.
  2579. int toolbarIconSize=KIconLoader().currentSize(KIconLoader::MainToolbar);
  2580. setIconSize(QSize(toolbarIconSize,toolbarIconSize));
  2581. fileNewAction->setIcon(KIcon("document-new"));
  2582. fileNewMenu->menuAction()->setIcon(KIcon("document-new"));
  2583. fileOpenAction->setIcon(KIcon("document-open"));
  2584. fileSaveAllAction->setIcon(KIcon("document-save"));
  2585. filePrintAction->setIcon(KIcon("document-print"));
  2586. filePrintQuicklyAction->setIcon(KIcon("document-print"));
  2587. editClearAction->setIcon(KIcon("edit-delete"));
  2588. editCutAction->setIcon(KIcon("edit-cut"));
  2589. editCopyAction->setIcon(KIcon("edit-copy"));
  2590. editPasteAction->setIcon(KIcon("edit-paste"));
  2591. projectAddFilesAction->setIcon(KIcon("edit-add"));
  2592. projectCompileAction->setIcon(KIcon("compfile"));
  2593. projectMakeAction->setIcon(KIcon("make-kdevelop"));
  2594. projectBuildAction->setIcon(KIcon("rebuild"));
  2595. helpContentsAction->setIcon(KIcon("help-contents"));
  2596. helpDocumentationAction->setIcon(KIcon("help-contents"));
  2597. helpSearchAction->setIcon(KIcon("file-find"));
  2598. findFindAction->setIcon(KIcon("edit-find"));
  2599. if (KIconLoader::global()->iconPath("edit-find-replace",KIconLoader::Small,TRUE).isEmpty())
  2600. findReplaceAction->setIcon(KIcon("file-find"));
  2601. else
  2602. findReplaceAction->setIcon(KIcon("edit-find-replace"));
  2603. helpIndexAction->setIcon(KIcon("fileview-text"));
  2604. editUndoAction->setIcon(KIcon("edit-undo"));
  2605. editRedoAction->setIcon(KIcon("edit-redo"));
  2606. findFunctionsAction->setIcon(KIcon("view-tree"));
  2607. editIncreaseIndentAction->setIcon(KIcon("format-indent-more"));
  2608. editDecreaseIndentAction->setIcon(KIcon("format-indent-less"));
  2609. projectStopCompilationAction->setIcon(KIcon("process-stop"));
  2610. projectForceQuitAction->setIcon(KIcon("dialog-cancel"));
  2611. helpNewsAction->setIcon(KIcon("kontact-news"));
  2612. debugRunAction->setIcon(KIcon("media-playback-start"));
  2613. debugPauseAction->setIcon(KIcon("media-playback-pause"));
  2614. toolsConfigureAction->setIcon(KIcon("configure"));
  2615. debugResetAction->setIcon(KIcon("media-playback-stop"));
  2616. } else {
  2617. setIconSize(QSize(20,20));
  2618. fileNewAction->setIcon(QIcon(QPixmap(":/images/00.png")));
  2619. fileNewMenu->menuAction()->setIcon(QIcon(QPixmap(":/images/00.png")));
  2620. fileOpenAction->setIcon(QIcon(QPixmap(":/images/01.png")));
  2621. fileSaveAllAction->setIcon(QIcon(QPixmap(":/images/02.png")));
  2622. filePrintAction->setIcon(QIcon(QPixmap(":/images/03.png")));
  2623. filePrintQuicklyAction->setIcon(QIcon(QPixmap(":/images/03.png")));
  2624. editClearAction->setIcon(QIcon(QPixmap(":/images/04.png")));
  2625. editCutAction->setIcon(QIcon(QPixmap(":/images/05.png")));
  2626. editCopyAction->setIcon(QIcon(QPixmap(":/images/06.png")));
  2627. editPasteAction->setIcon(QIcon(QPixmap(":/images/07.png")));
  2628. projectAddFilesAction->setIcon(QIcon(QPixmap(":/images/08.png")));
  2629. projectCompileAction->setIcon(QIcon(QPixmap(":/images/09.png")));
  2630. projectMakeAction->setIcon(QIcon(QPixmap(":/images/10.png")));
  2631. projectBuildAction->setIcon(QIcon(QPixmap(":/images/11.png")));
  2632. helpContentsAction->setIcon(QIcon(QPixmap(":/images/12.png")));
  2633. helpDocumentationAction->setIcon(QIcon(QPixmap(":/images/12.png")));
  2634. helpSearchAction->setIcon(QIcon(QPixmap(":/images/13.png")));
  2635. findFindAction->setIcon(QIcon(QPixmap(":/images/13.png")));
  2636. findReplaceAction->setIcon(QIcon(QPixmap(":/images/14.png")));
  2637. helpIndexAction->setIcon(QIcon(QPixmap(":/images/15.png")));
  2638. editUndoAction->setIcon(QIcon(QPixmap(":/images/16.png")));
  2639. editRedoAction->setIcon(QIcon(QPixmap(":/images/17.png")));
  2640. findFunctionsAction->setIcon(QIcon(QPixmap(":/images/18.png")));
  2641. editIncreaseIndentAction->setIcon(QIcon(QPixmap(":/images/19.png")));
  2642. editDecreaseIndentAction->setIcon(QIcon(QPixmap(":/images/20.png")));
  2643. projectStopCompilationAction->setIcon(QIcon(QPixmap(":/images/21.png")));
  2644. projectForceQuitAction->setIcon(QIcon(QPixmap(":/images/22.png")));
  2645. helpNewsAction->setIcon(QIcon(QPixmap(":/images/23.png")));
  2646. debugRunAction->setIcon(QIcon(QPixmap(":/images/24.png")));
  2647. debugPauseAction->setIcon(QIcon(QPixmap(":/images/25.png")));
  2648. toolsConfigureAction->setIcon(QIcon(QPixmap(":/images/26.png")));
  2649. debugResetAction->setIcon(QIcon(QPixmap(":/images/27.png")));
  2650. }
  2651. it=Q3ListViewItemIterator(errorList->errorListView);
  2652. for (item=it.current();item;item=(++it).current()) {
  2653. switch(item->rtti()) {
  2654. case etError:
  2655. item->setPixmap(0,SYSICON("dialog-error","error.png"));
  2656. break;
  2657. case etWarning:
  2658. item->setPixmap(0,SYSICON("dialog-warning","warning.png"));
  2659. break;
  2660. default:
  2661. item->setPixmap(0,SYSICON("dialog-information","info.png"));
  2662. break;
  2663. }
  2664. }
  2665. // Apply the preferences to the source file windows.
  2666. foreach (SourceFileWindow *sourceFile, sourceFiles) sourceFile->applyPreferences();
  2667. // Apply the preferences to the debug menu.
  2668. debugPauseAction->setEnabled(!compiling&&preferences.linkTarget==LT_TIEMU);
  2669. debugResetAction->setEnabled(!compiling&&preferences.linkTarget==LT_TIEMU);
  2670. bool runnable=!settings.archive&&!settings.flash_os&&preferences.linkTarget!=LT_NONE;
  2671. menuBar()->setItemVisible(5,runnable); //debugMenu
  2672. debugRunAction->setVisible(runnable);
  2673. debugPauseAction->setVisible(runnable);
  2674. }
  2675. }
  2676. void MainForm::editUndo()
  2677. {
  2678. if (CURRENT_VIEW)
  2679. CURRENT_VIEW->action(KStandardAction::name(KStandardAction::Undo))->trigger();
  2680. }
  2681. void MainForm::editRedo()
  2682. {
  2683. if (CURRENT_VIEW)
  2684. CURRENT_VIEW->action(KStandardAction::name(KStandardAction::Redo))->trigger();
  2685. }
  2686. void MainForm::editClear()
  2687. {
  2688. if (CURRENT_VIEW)
  2689. CURRENT_VIEW->removeSelectionText();
  2690. }
  2691. void MainForm::editCut()
  2692. {
  2693. if (CURRENT_VIEW)
  2694. CURRENT_VIEW->action(KStandardAction::name(KStandardAction::Cut))->trigger();
  2695. }
  2696. void MainForm::editCopy()
  2697. {
  2698. if (CURRENT_VIEW)
  2699. CURRENT_VIEW->action(KStandardAction::name(KStandardAction::Copy))->trigger();
  2700. }
  2701. void MainForm::editPaste()
  2702. {
  2703. if (CURRENT_VIEW)
  2704. CURRENT_VIEW->action(KStandardAction::name(KStandardAction::PasteText))->trigger();
  2705. }
  2706. void MainForm::editSelectAll()
  2707. {
  2708. if (CURRENT_VIEW)
  2709. CURRENT_VIEW->action(KStandardAction::name(KStandardAction::SelectAll))->trigger();
  2710. }
  2711. void MainForm::editIncreaseIndent()
  2712. {
  2713. if (CURRENT_VIEW)
  2714. CURRENT_VIEW->action("tools_indent")->trigger();
  2715. }
  2716. void MainForm::editDecreaseIndent()
  2717. {
  2718. if (CURRENT_VIEW)
  2719. CURRENT_VIEW->action("tools_unindent")->trigger();
  2720. }
  2721. class NonModalFindDialog : public KFindDialog {
  2722. public:
  2723. explicit NonModalFindDialog(QWidget *parent=0, long options=0,
  2724. const QStringList &findStrings=QStringList(), bool hasSelection=false)
  2725. : KFindDialog(parent,options,findStrings,hasSelection)
  2726. {
  2727. setModal(false);
  2728. }
  2729. // Override accept() not to close the dialog.
  2730. virtual void accept(void)
  2731. {
  2732. setResult(QDialog::Accepted);
  2733. }
  2734. };
  2735. void MainForm::findFind()
  2736. {
  2737. if (kfinddialog)
  2738. ACTIVATE_WINDOW(kfinddialog->winId());
  2739. else {
  2740. // Never set hasSelection because finding in selection doesn't really make
  2741. // sense with my non-modal find dialog setup.
  2742. kfinddialog=new NonModalFindDialog(this,KFind::FromCursor,findHistory);
  2743. connect(kfinddialog, SIGNAL(okClicked()), this, SLOT(findFind_next()));
  2744. connect(kfinddialog, SIGNAL(cancelClicked()), this, SLOT(findFind_stop()));
  2745. kfinddialog->show();
  2746. }
  2747. }
  2748. void MainForm::findFind_next()
  2749. {
  2750. // Use a local KFind object. The search will need to be restarted next time
  2751. // this function is called because of the non-modality of the find dialog.
  2752. KFind *kfind=new KFind(kfinddialog->pattern(),kfinddialog->options(),this,kfinddialog);
  2753. // Initialize.
  2754. bool findBackwards=!!(kfinddialog->options()&KFind::FindBackwards);
  2755. int findCurrentCol;
  2756. kfind=new KFind(kfinddialog->pattern(),kfinddialog->options(),this,kfinddialog);
  2757. kfind->closeFindNextDialog(); // don't use this, a non-modal KFindDialog is used instead
  2758. connect(kfind,SIGNAL(highlight(const QString &,int,int)),
  2759. this,SLOT(findFind_highlight(const QString &,int,int)));
  2760. // Make sure we have a valid currentListItem.
  2761. if (!currentListItem) fileTreeClicked(rootListItem);
  2762. findCurrentDocument=currentListItem;
  2763. if (CURRENT_VIEW) {
  2764. if (kfinddialog->options()&KFind::FromCursor) {
  2765. if (CURRENT_VIEW->selection()) {
  2766. if (findBackwards) {
  2767. CURRENT_VIEW->selectionRange().start().position(findCurrentLine,findCurrentCol);
  2768. if ((--findCurrentCol)==-1) {
  2769. if (!findCurrentLine) goto skip_data;
  2770. findCurrentLine--;
  2771. }
  2772. } else {
  2773. CURRENT_VIEW->selectionRange().end().position(findCurrentLine,findCurrentCol);
  2774. }
  2775. } else {
  2776. CURRENT_VIEW->cursorPosition().position(findCurrentLine,findCurrentCol);
  2777. }
  2778. } else {
  2779. findCurrentLine=findBackwards?(CURRENT_VIEW->document()->lines()-1):0;
  2780. findCurrentCol=-1;
  2781. }
  2782. kfind->setData(CURRENT_VIEW->document()->line(findCurrentLine),findCurrentCol);
  2783. } else findCurrentLine=0;
  2784. skip_data:;
  2785. // Now find the next occurrence.
  2786. KFind::Result result;
  2787. KTextEditor::View *currView=CURRENT_VIEW;
  2788. // We never have a currBuffer here, the current list item is always either
  2789. // non-editable or instantiated.
  2790. QStringList currBuffer;
  2791. int currNumLines=0;
  2792. if (CURRENT_VIEW) currNumLines=CURRENT_VIEW->document()->lines();
  2793. do {
  2794. if (kfind->needData()) {
  2795. if (findBackwards?!findCurrentLine:(findCurrentLine>=currNumLines)) {
  2796. if (findBackwards) {
  2797. // Traverse the file tree in order backwards, restart from the end if
  2798. // the first file was reached. Stop at currentListItem.
  2799. if (findCurrentDocument) {
  2800. Q3ListViewItemIterator lvit(fileTree);
  2801. Q3PtrList<Q3ListViewItem> lst;
  2802. Q3ListViewItem *item;
  2803. for (item=lvit.current();item&&item!=findCurrentDocument;
  2804. item=(++lvit).current()) {
  2805. lst.prepend(item);
  2806. }
  2807. Q3PtrListIterator<Q3ListViewItem> it(lst);
  2808. for (findCurrentDocument=it.current();
  2809. findCurrentDocument&&findCurrentDocument!=currentListItem;
  2810. findCurrentDocument=++it) {
  2811. if (IS_FILE(findCurrentDocument)) {
  2812. CATEGORY_OF(category,findCurrentDocument);
  2813. if (IS_EDITABLE_CATEGORY(category)) goto file_found;
  2814. }
  2815. }
  2816. if (findCurrentDocument) goto not_found;
  2817. }
  2818. Q3ListViewItemIterator lvit(currentListItem);
  2819. Q3PtrList<Q3ListViewItem> lst;
  2820. Q3ListViewItem *item;
  2821. for (item=(++lvit).current();item;item=(++lvit).current()) {
  2822. lst.prepend(item);
  2823. }
  2824. Q3PtrListIterator<Q3ListViewItem> it(lst);
  2825. for (findCurrentDocument=it.current();findCurrentDocument;
  2826. findCurrentDocument=++it) {
  2827. if (IS_FILE(findCurrentDocument)) {
  2828. CATEGORY_OF(category,findCurrentDocument);
  2829. if (IS_EDITABLE_CATEGORY(category)) goto file_found;
  2830. }
  2831. }
  2832. goto not_found;
  2833. } else {
  2834. // Traverse the file tree in order, restart from the beginning if
  2835. // the last file was reached. Stop at currentListItem.
  2836. if (findCurrentDocument) {
  2837. Q3ListViewItemIterator it(findCurrentDocument);
  2838. for (findCurrentDocument=(++it).current();
  2839. findCurrentDocument&&findCurrentDocument!=currentListItem;
  2840. findCurrentDocument=(++it).current()) {
  2841. if (IS_FILE(findCurrentDocument)) {
  2842. CATEGORY_OF(category,findCurrentDocument);
  2843. if (IS_EDITABLE_CATEGORY(category)) goto file_found;
  2844. }
  2845. }
  2846. if (findCurrentDocument) goto not_found;
  2847. }
  2848. {
  2849. Q3ListViewItemIterator it(fileTree);
  2850. for (findCurrentDocument=it.current();
  2851. findCurrentDocument&&findCurrentDocument!=currentListItem;
  2852. findCurrentDocument=(++it).current()) {
  2853. if (IS_FILE(findCurrentDocument)) {
  2854. CATEGORY_OF(category,findCurrentDocument);
  2855. if (IS_EDITABLE_CATEGORY(category)) goto file_found;
  2856. }
  2857. }
  2858. }
  2859. not_found:
  2860. // No find in all files. Try currentListItem again because it hasn't
  2861. // been fully searched yet.
  2862. if (IS_FILE(currentListItem)) {
  2863. // currentListItem is always either instantiated or not editable
  2864. currView=static_cast<ListViewFile *>(currentListItem)->kateView;
  2865. if (currView) {
  2866. currNumLines=currView->document()->lines();
  2867. findCurrentLine=findBackwards?currNumLines-1:0;
  2868. do {
  2869. if (kfind->needData()) {
  2870. if (findBackwards?!findCurrentLine:(findCurrentLine>=currNumLines))
  2871. goto not_found_current;
  2872. if (findBackwards) findCurrentLine--; else findCurrentLine++;
  2873. kfind->setData(currView->document()->line(findCurrentLine));
  2874. }
  2875. result=kfind->find();
  2876. } while (result==KFind::NoMatch);
  2877. break;
  2878. }
  2879. }
  2880. not_found_current:
  2881. KMessageBox::error(this,QString("Text \'%1\' not found").arg(kfinddialog->pattern()));
  2882. delete kfind;
  2883. return;
  2884. file_found:
  2885. currView=static_cast<ListViewFile *>(findCurrentDocument)->kateView;
  2886. currNumLines=currView->document()->lines();
  2887. findCurrentLine=findBackwards?currNumLines-1:0;
  2888. }
  2889. } else if (findBackwards) findCurrentLine--; else findCurrentLine++;
  2890. if (currView)
  2891. kfind->setData(currView->document()->line(findCurrentLine));
  2892. else
  2893. kfind->setData(currBuffer[findCurrentLine]);
  2894. }
  2895. result=kfind->find();
  2896. } while (result==KFind::NoMatch);
  2897. delete kfind;
  2898. }
  2899. void MainForm::findFind_highlight(const QString &text __attribute__((unused)), int matchingindex, int matchedlength)
  2900. {
  2901. if (currentListItem!=findCurrentDocument) fileTreeClicked(findCurrentDocument);
  2902. if (!CURRENT_VIEW) qFatal("CURRENT_VIEW should be set here!");
  2903. CURRENT_VIEW->setCursorPosition(KTextEditor::Cursor(findCurrentLine,matchingindex+matchedlength));
  2904. CURRENT_VIEW->setSelection(KTextEditor::Range(findCurrentLine,matchingindex,
  2905. findCurrentLine,matchingindex+matchedlength));
  2906. }
  2907. void MainForm::findFind_stop()
  2908. {
  2909. if (kfinddialog) {
  2910. findHistory=kfinddialog->findHistory();
  2911. kfinddialog->deleteLater();
  2912. }
  2913. kfinddialog=static_cast<KFindDialog *>(NULL);
  2914. }
  2915. void MainForm::findReplace()
  2916. {
  2917. if (kreplace) {
  2918. KDialog *replaceNextDialog=kreplace->replaceNextDialog();
  2919. if (replaceNextDialog)
  2920. ACTIVATE_WINDOW(replaceNextDialog->winId());
  2921. return;
  2922. }
  2923. KReplaceDialog kreplacedialog(this,((CURRENT_VIEW&&CURRENT_VIEW->selection()
  2924. &&!CURRENT_VIEW->selectionRange().onSingleLine())?
  2925. KFind::SelectedText:0)|KFind::FromCursor,
  2926. findHistory,replacementHistory,
  2927. CURRENT_VIEW&&CURRENT_VIEW->selection());
  2928. if (kreplacedialog.exec()!=QDialog::Accepted)
  2929. return;
  2930. findHistory=kreplacedialog.findHistory();
  2931. replacementHistory=kreplacedialog.replacementHistory();
  2932. kreplace=new KReplaceWithSelection(kreplacedialog.pattern(),kreplacedialog.replacement(),
  2933. kreplacedialog.options(),this);
  2934. // Connect signals to code which handles highlighting of found text, and
  2935. // on-the-fly replacement.
  2936. connect(kreplace,SIGNAL(highlight(const QString &,int,int)),
  2937. this,SLOT(findReplace_highlight(const QString &,int,int)));
  2938. // Connect findNext signal - called when pressing the button in the dialog.
  2939. connect(kreplace,SIGNAL(findNext()),this,SLOT(findReplace_next()));
  2940. // Connect replace signal - called when doing a replacement.
  2941. connect(kreplace,SIGNAL(replace(const QString &,int,int,int)),
  2942. this,SLOT(findReplace_replace(const QString &,int,int,int)));
  2943. // Connect dialogClosed signal - called when closing the Replace Next dialog.
  2944. connect(kreplace,SIGNAL(dialogClosed()),this,SLOT(findReplace_stop()));
  2945. // Initialize.
  2946. bool findBackwards=!!(kreplace->options()&KFind::FindBackwards);
  2947. int replaceCurrentCol;
  2948. // Make sure we have a valid currentListItem.
  2949. if (!currentListItem) fileTreeClicked(rootListItem);
  2950. replaceCurrentDocument=currentListItem;
  2951. if (CURRENT_VIEW) {
  2952. if (kreplace->options()&KFind::SelectedText) {
  2953. kreplace->setSelection(CURRENT_VIEW->selectionRange());
  2954. if (findBackwards) {
  2955. replaceCurrentLine=kreplace->selEndLine();
  2956. replaceCurrentCol=kreplace->selEndCol();
  2957. } else {
  2958. replaceCurrentLine=kreplace->selStartLine();
  2959. replaceCurrentCol=kreplace->selStartCol();
  2960. }
  2961. kreplace->setOptions(kreplace->options()&~KFind::FromCursor);
  2962. } else if (kreplace->options()&KFind::FromCursor) {
  2963. if (CURRENT_VIEW->selection()) {
  2964. if (findBackwards) {
  2965. CURRENT_VIEW->selectionRange().start().position(replaceCurrentLine,
  2966. replaceCurrentCol);
  2967. if ((--replaceCurrentCol)==-1) {
  2968. if (!replaceCurrentLine) goto skip_data;
  2969. replaceCurrentLine--;
  2970. }
  2971. } else {
  2972. CURRENT_VIEW->selectionRange().end().position(replaceCurrentLine,
  2973. replaceCurrentCol);
  2974. }
  2975. } else {
  2976. CURRENT_VIEW->cursorPosition().position(replaceCurrentLine,replaceCurrentCol);
  2977. // Don't prompt for restarting if we actually searched the entire document.
  2978. if (findBackwards?(replaceCurrentLine==(CURRENT_VIEW->document()->lines()-1)
  2979. && replaceCurrentCol==(CURRENT_VIEW->document()->lineLength(replaceCurrentLine)))
  2980. :(!replaceCurrentLine&&!replaceCurrentCol))
  2981. kreplace->setOptions(kreplace->options()&~KFind::FromCursor);
  2982. }
  2983. } else {
  2984. replaceCurrentLine=findBackwards?(CURRENT_VIEW->document()->lines()-1):0;
  2985. replaceCurrentCol=-1;
  2986. }
  2987. kreplace->setData(CURRENT_VIEW->document()->line(replaceCurrentLine),replaceCurrentCol);
  2988. }
  2989. skip_data:
  2990. // Now find the next occurrence.
  2991. findReplace_next(TRUE);
  2992. }
  2993. void MainForm::findReplace_next()
  2994. {
  2995. findReplace_next(FALSE);
  2996. }
  2997. void MainForm::findReplace_next(bool firstTime)
  2998. {
  2999. // Replace All only works on the current file. Also, if we have a selection,
  3000. // we only want to work on the file containing the selection.
  3001. bool global=(kreplace->options()&KReplaceDialog::PromptOnReplace)&&!kreplace->haveSelection();
  3002. bool findBackwards=!!(kreplace->options()&KFind::FindBackwards);
  3003. // Reinitialize.
  3004. if (!firstTime) {
  3005. int replaceCurrentCol;
  3006. // Make sure we have a valid currentListItem.
  3007. if (!currentListItem) fileTreeClicked(rootListItem);
  3008. replaceCurrentDocument=currentListItem;
  3009. if (CURRENT_VIEW) {
  3010. // Non-first-time always continues from cursor.
  3011. if (CURRENT_VIEW->selection()) {
  3012. if (findBackwards) {
  3013. CURRENT_VIEW->selectionRange().start().position(replaceCurrentLine,
  3014. replaceCurrentCol);
  3015. if ((--replaceCurrentCol)==-1) {
  3016. if (!replaceCurrentLine) goto skip_data;
  3017. replaceCurrentLine--;
  3018. }
  3019. } else {
  3020. CURRENT_VIEW->selectionRange().end().position(replaceCurrentLine,
  3021. replaceCurrentCol);
  3022. }
  3023. } else {
  3024. CURRENT_VIEW->cursorPosition().position(replaceCurrentLine,replaceCurrentCol);
  3025. }
  3026. kreplace->setData(CURRENT_VIEW->document()->line(replaceCurrentLine),replaceCurrentCol);
  3027. } else replaceCurrentLine=0;
  3028. }
  3029. skip_data:;
  3030. // Now find the next occurrence.
  3031. KFind::Result result;
  3032. KTextEditor::View *currView=CURRENT_VIEW;
  3033. // We never have a currBuffer here, the current list item is always either
  3034. // non-editable or instantiated.
  3035. QStringList currBuffer;
  3036. int currNumLines=0;
  3037. if (CURRENT_VIEW) currNumLines=CURRENT_VIEW->document()->lines();
  3038. do {
  3039. if (kreplace->needData()) {
  3040. if (global) {
  3041. if (findBackwards?!replaceCurrentLine:(replaceCurrentLine>=currNumLines)) {
  3042. if (findBackwards) {
  3043. // Traverse the file tree in order backwards, restart from the end if
  3044. // the first file was reached. Stop at currentListItem.
  3045. if (replaceCurrentDocument) {
  3046. Q3ListViewItemIterator lvit(fileTree);
  3047. Q3PtrList<Q3ListViewItem> lst;
  3048. Q3ListViewItem *item;
  3049. for (item=lvit.current();item&&item!=replaceCurrentDocument;
  3050. item=(++lvit).current()) {
  3051. lst.prepend(item);
  3052. }
  3053. Q3PtrListIterator<Q3ListViewItem> it(lst);
  3054. for (replaceCurrentDocument=it.current();
  3055. replaceCurrentDocument&&replaceCurrentDocument!=currentListItem;
  3056. replaceCurrentDocument=++it) {
  3057. if (IS_FILE(replaceCurrentDocument)) {
  3058. CATEGORY_OF(category,replaceCurrentDocument);
  3059. if (IS_EDITABLE_CATEGORY(category)) goto file_found;
  3060. }
  3061. }
  3062. if (replaceCurrentDocument) goto not_found;
  3063. }
  3064. Q3ListViewItemIterator lvit(currentListItem);
  3065. Q3PtrList<Q3ListViewItem> lst;
  3066. Q3ListViewItem *item;
  3067. for (item=(++lvit).current();item;item=(++lvit).current()) {
  3068. lst.prepend(item);
  3069. }
  3070. Q3PtrListIterator<Q3ListViewItem> it(lst);
  3071. for (replaceCurrentDocument=it.current();replaceCurrentDocument;
  3072. replaceCurrentDocument=++it) {
  3073. if (IS_FILE(replaceCurrentDocument)) {
  3074. CATEGORY_OF(category,replaceCurrentDocument);
  3075. if (IS_EDITABLE_CATEGORY(category)) goto file_found;
  3076. }
  3077. }
  3078. goto not_found;
  3079. } else {
  3080. // Traverse the file tree in order, restart from the beginning if
  3081. // the last file was reached. Stop at currentListItem.
  3082. if (replaceCurrentDocument) {
  3083. Q3ListViewItemIterator it(replaceCurrentDocument);
  3084. for (replaceCurrentDocument=(++it).current();
  3085. replaceCurrentDocument&&replaceCurrentDocument!=currentListItem;
  3086. replaceCurrentDocument=(++it).current()) {
  3087. if (IS_FILE(replaceCurrentDocument)) {
  3088. CATEGORY_OF(category,replaceCurrentDocument);
  3089. if (IS_EDITABLE_CATEGORY(category)) goto file_found;
  3090. }
  3091. }
  3092. if (replaceCurrentDocument) goto not_found;
  3093. }
  3094. {
  3095. Q3ListViewItemIterator it(fileTree);
  3096. for (replaceCurrentDocument=it.current();
  3097. replaceCurrentDocument&&replaceCurrentDocument!=currentListItem;
  3098. replaceCurrentDocument=(++it).current()) {
  3099. if (IS_FILE(replaceCurrentDocument)) {
  3100. CATEGORY_OF(category,replaceCurrentDocument);
  3101. if (IS_EDITABLE_CATEGORY(category)) goto file_found;
  3102. }
  3103. }
  3104. }
  3105. not_found:
  3106. // No find in all files. Try currentListItem again because it hasn't
  3107. // been fully searched yet.
  3108. if (IS_FILE(currentListItem)) {
  3109. // currentListItem is always either instantiated or not editable
  3110. currView=static_cast<ListViewFile *>(currentListItem)->kateView;
  3111. if (currView) {
  3112. currNumLines=currView->document()->lines();
  3113. replaceCurrentLine=findBackwards?currNumLines-1:0;
  3114. do {
  3115. if (kreplace->needData()) {
  3116. if (findBackwards?!replaceCurrentLine:(replaceCurrentLine>=currNumLines))
  3117. goto not_found_current;
  3118. if (findBackwards) replaceCurrentLine--; else replaceCurrentLine++;
  3119. kreplace->setData(currView->document()->line(replaceCurrentLine));
  3120. }
  3121. result=kreplace->replace();
  3122. } while (result==KFind::NoMatch);
  3123. break;
  3124. }
  3125. }
  3126. not_found_current:
  3127. kreplace->displayFinalDialog();
  3128. findReplace_stop();
  3129. return;
  3130. file_found:
  3131. currView=static_cast<ListViewFile *>(replaceCurrentDocument)->kateView;
  3132. currNumLines=currView->document()->lines();
  3133. replaceCurrentLine=findBackwards?currNumLines-1:0;
  3134. }
  3135. } else if (findBackwards) replaceCurrentLine--; else replaceCurrentLine++;
  3136. if (currView)
  3137. kreplace->setData(currView->document()->line(replaceCurrentLine));
  3138. else
  3139. kreplace->setData(currBuffer[replaceCurrentLine]);
  3140. } else { // if not global
  3141. if (kreplace->haveSelection()
  3142. ?(findBackwards?(replaceCurrentLine<=kreplace->selStartLine())
  3143. :(replaceCurrentLine>=kreplace->selEndLine()))
  3144. :(findBackwards?!replaceCurrentLine:(replaceCurrentLine>=currNumLines))) {
  3145. // It makes no sense to prompt for restarting if we aren't actually
  3146. // searching anywhere.
  3147. if (CURRENT_VIEW) {
  3148. if (kreplace->shouldRestart()) {
  3149. // Drop "From cursor" and "Selected text" options.
  3150. kreplace->setOptions(kreplace->options()&~(KFind::FromCursor
  3151. |KFind::SelectedText));
  3152. kreplace->invalidateSelection();
  3153. // Reinitialize.
  3154. replaceCurrentLine=findBackwards?(CURRENT_VIEW->document()->lines()-1):0;
  3155. kreplace->setData(CURRENT_VIEW->document()->line(replaceCurrentLine));
  3156. // Start again as if it was the first time.
  3157. findReplace_next(TRUE);
  3158. return;
  3159. } else {
  3160. findReplace_stop();
  3161. return;
  3162. }
  3163. } else goto not_found_current;
  3164. } else if (findBackwards) replaceCurrentLine--; else replaceCurrentLine++;
  3165. if (currView)
  3166. kreplace->setData(currView->document()->line(replaceCurrentLine));
  3167. else
  3168. kreplace->setData(currBuffer[replaceCurrentLine]);
  3169. }
  3170. }
  3171. result=kreplace->replace();
  3172. } while (result==KFind::NoMatch);
  3173. }
  3174. void MainForm::findReplace_highlight(const QString &text __attribute__((unused)), int matchingindex, int matchedlength)
  3175. {
  3176. if (currentListItem!=replaceCurrentDocument) fileTreeClicked(replaceCurrentDocument);
  3177. if (!CURRENT_VIEW) qFatal("CURRENT_VIEW should be set here!");
  3178. CURRENT_VIEW->setCursorPosition(KTextEditor::Cursor(replaceCurrentLine,matchingindex+matchedlength));
  3179. CURRENT_VIEW->setSelection(KTextEditor::Range(replaceCurrentLine,matchingindex,
  3180. replaceCurrentLine,matchingindex+matchedlength));
  3181. }
  3182. void MainForm::findReplace_replace(const QString &text, int replacementIndex, int replacedLength, int matchedLength)
  3183. {
  3184. if (currentListItem!=replaceCurrentDocument) fileTreeClicked(replaceCurrentDocument);
  3185. if (!CURRENT_VIEW) qFatal("CURRENT_VIEW should be set here!");
  3186. bool update=!!(kreplace->options()&KReplaceDialog::PromptOnReplace);
  3187. bool haveSelection=kreplace->haveSelection();
  3188. // The initializations are redundant, but g++ doesn't understand this, and the
  3189. // self-initialization trick doesn't work either (-Wno-init-self is ignored).
  3190. int selStartLine=0, selStartCol=0, selEndLine=0, selEndCol=0;
  3191. if (haveSelection) {
  3192. selStartLine=kreplace->selStartLine();
  3193. selStartCol=kreplace->selStartCol();
  3194. selEndLine=kreplace->selEndLine();
  3195. selEndCol=kreplace->selEndCol();
  3196. }
  3197. CURRENT_VIEW->document()->startEditing();
  3198. CURRENT_VIEW->document()->insertText(KTextEditor::Cursor(replaceCurrentLine,replacementIndex),
  3199. text.mid(replacementIndex,replacedLength));
  3200. // We can't put the cursor back now because this breaks editBegin/editEnd.
  3201. int line,col;
  3202. CURRENT_VIEW->cursorPosition().position(line,col);
  3203. bool updateCursor=(line==replaceCurrentLine && col==replacementIndex+replacedLength);
  3204. CURRENT_VIEW->document()->removeText(KTextEditor::Range(replaceCurrentLine,replacementIndex+replacedLength,
  3205. replaceCurrentLine,replacementIndex+replacedLength+matchedLength));
  3206. CURRENT_VIEW->document()->endEditing();
  3207. if (updateCursor)
  3208. CURRENT_VIEW->setCursorPosition(KTextEditor::Cursor(replaceCurrentLine,replacementIndex));
  3209. if (update) {
  3210. CURRENT_VIEW->setCursorPosition(KTextEditor::Cursor(replaceCurrentLine,replacementIndex+replacedLength));
  3211. CURRENT_VIEW->setSelection(KTextEditor::Range(replaceCurrentLine,replacementIndex,
  3212. replaceCurrentLine,replacementIndex+replacedLength));
  3213. CURRENT_VIEW->repaint();
  3214. }
  3215. if (haveSelection) {
  3216. // Restore selection, updating coordinates if necessary.
  3217. kreplace->setSelection(selStartLine,selStartCol,selEndLine,
  3218. (replaceCurrentLine==selEndLine)
  3219. ?(selEndCol+replacedLength-matchedLength)
  3220. :selEndCol);
  3221. }
  3222. }
  3223. void MainForm::findReplace_stop()
  3224. {
  3225. if (kreplace) kreplace->deleteLater();
  3226. kreplace=static_cast<KReplaceWithSelection *>(NULL);
  3227. }
  3228. static SourceFileFunctions sourceFileFunctions;
  3229. static FunctionDialog *functionDialog;
  3230. void MainForm::findFunctions()
  3231. {
  3232. if (CURRENT_VIEW) {
  3233. functionDialog=new FunctionDialog(this);
  3234. connect(functionDialog->functionListBox,SIGNAL(highlighted(int)),
  3235. this,SLOT(findFunctions_functionListBox_highlighted(int)));
  3236. connect(functionDialog->functionListBox,SIGNAL(selected(int)),
  3237. this,SLOT(findFunctions_functionListBox_selected(int)));
  3238. connect(functionDialog->prototypeButton,SIGNAL(clicked()),
  3239. this,SLOT(findFunctions_prototypeButton_clicked()));
  3240. connect(functionDialog->implementationButton,SIGNAL(clicked()),
  3241. this,SLOT(findFunctions_implementationButton_clicked()));
  3242. functionDialog->functionListBox->clear();
  3243. CATEGORY_OF(category,currentListItem);
  3244. sourceFileFunctions=getFunctions(CURRENT_VIEW->document()->text(),
  3245. category==asmFilesListItem||category==sFilesListItem);
  3246. for (SourceFileFunctions::Iterator it=sourceFileFunctions.begin();
  3247. it!=sourceFileFunctions.end(); ++it)
  3248. functionDialog->functionListBox->insertItem((*it).name);
  3249. functionDialog->exec();
  3250. delete functionDialog;
  3251. }
  3252. }
  3253. void MainForm::findFunctions_functionListBox_highlighted(int index)
  3254. {
  3255. if (index>=0) {
  3256. functionDialog->prototypeButton->setEnabled(
  3257. sourceFileFunctions[index].prototypeLine>=0);
  3258. functionDialog->implementationButton->setEnabled(
  3259. sourceFileFunctions[index].implementationLine>=0);
  3260. } else {
  3261. functionDialog->prototypeButton->setEnabled(FALSE);
  3262. functionDialog->implementationButton->setEnabled(FALSE);
  3263. }
  3264. }
  3265. void MainForm::findFunctions_functionListBox_selected(int index)
  3266. {
  3267. if (index>=0) {
  3268. int line=sourceFileFunctions[index].implementationLine>=0
  3269. ?sourceFileFunctions[index].implementationLine
  3270. :sourceFileFunctions[index].prototypeLine;
  3271. CURRENT_VIEW->setCursorPosition(KTextEditor::Cursor(line,0));
  3272. functionDialog->accept();
  3273. }
  3274. }
  3275. void MainForm::findFunctions_prototypeButton_clicked()
  3276. {
  3277. int index=functionDialog->functionListBox->currentItem();
  3278. if (index>=0 && sourceFileFunctions[index].prototypeLine>=0) {
  3279. CURRENT_VIEW->setCursorPosition(KTextEditor::Cursor(
  3280. sourceFileFunctions[index].prototypeLine,0));
  3281. functionDialog->accept();
  3282. }
  3283. }
  3284. void MainForm::findFunctions_implementationButton_clicked()
  3285. {
  3286. int index=functionDialog->functionListBox->currentItem();
  3287. if (index>=0 && sourceFileFunctions[index].implementationLine>=0) {
  3288. CURRENT_VIEW->setCursorPosition(KTextEditor::Cursor(
  3289. sourceFileFunctions[index].implementationLine,0));
  3290. functionDialog->accept();
  3291. }
  3292. }
  3293. void MainForm::findFunctionsPopup_aboutToShow()
  3294. {
  3295. findFunctionsPopup->clear();
  3296. if (CURRENT_VIEW) {
  3297. CATEGORY_OF(category,currentListItem);
  3298. sourceFileFunctions=getFunctions(CURRENT_VIEW->document()->text(),
  3299. category==asmFilesListItem||category==sFilesListItem);
  3300. int idx=0;
  3301. for (SourceFileFunctions::Iterator it=sourceFileFunctions.begin();
  3302. it!=sourceFileFunctions.end(); ++it,++idx)
  3303. findFunctionsPopup->insertItem((*it).name,idx);
  3304. }
  3305. }
  3306. void MainForm::findFunctionsPopup_aboutToHide()
  3307. {
  3308. QTimer::singleShot(0,this,SLOT(findFunctionsPopup_aboutToHide_async()));
  3309. }
  3310. void MainForm::findFunctionsPopup_aboutToHide_async()
  3311. {
  3312. findFunctionsPopup->clear();
  3313. }
  3314. void MainForm::findFunctionsPopup_activated(int id)
  3315. {
  3316. if (CURRENT_VIEW) {
  3317. int line=sourceFileFunctions[id].implementationLine>=0
  3318. ?sourceFileFunctions[id].implementationLine
  3319. :sourceFileFunctions[id].prototypeLine;
  3320. CURRENT_VIEW->setCursorPosition(KTextEditor::Cursor(line,0));
  3321. }
  3322. }
  3323. void MainForm::findAndOpenFile(const QString &fileName, void *category)
  3324. {
  3325. // Look for the source file with the given name.
  3326. QString fileNameNoPath=QFileInfo(fileName).fileName();
  3327. bool inProject;
  3328. void *sourceFile;
  3329. if (findSourceFile(inProject,sourceFile,fileNameNoPath)) {
  3330. if (inProject)
  3331. fileTreeClicked(reinterpret_cast<ListViewFile *>(sourceFile));
  3332. else
  3333. ACTIVATE_WINDOW(reinterpret_cast<SourceFileWindow *>(sourceFile)->winId());
  3334. } else {
  3335. // Not found. Try to open it instead.
  3336. // Don't do this if the name ends with ".tpr" because that would cause
  3337. // openProject to close the current project and load the new one instead.
  3338. if (!fileName.endsWith(".tpr",FALSE)) {
  3339. QString fileNameFull=QFileInfo(projectFileName).dir().filePath(fileName);
  3340. if (getPathType(fileNameFull)==PATH_FILE) {
  3341. openProject(fileNameFull);
  3342. if (findSourceFile(inProject,sourceFile,fileNameFull) && !inProject)
  3343. ACTIVATE_WINDOW(reinterpret_cast<SourceFileWindow *>(sourceFile)->winId());
  3344. } else {
  3345. Q3ListViewItem *cat=reinterpret_cast<Q3ListViewItem *>(category);
  3346. QString includeDir=(cat==asmFilesListItem)?"asm":
  3347. (cat==sFilesListItem)?"s":"c";
  3348. fileNameFull=QDir(QString("%1/include/%2/").arg(tigcc_base)
  3349. .arg(includeDir)).filePath(fileName);
  3350. if (getPathType(fileNameFull)==PATH_FILE) {
  3351. openProject(fileNameFull);
  3352. if (findSourceFile(inProject,sourceFile,fileNameFull) && !inProject)
  3353. ACTIVATE_WINDOW(reinterpret_cast<SourceFileWindow *>(sourceFile)->winId());
  3354. } else {
  3355. KMessageBox::error(this,QString("File \'%1\' not found.").arg(fileName),
  3356. "Search Failed");
  3357. }
  3358. }
  3359. }
  3360. }
  3361. }
  3362. void MainForm::findOpenFileAtCursor()
  3363. {
  3364. if (CURRENT_VIEW && IS_FILE(currentListItem)) {
  3365. int line,col,i;
  3366. CURRENT_VIEW->cursorPosition().position(line,col);
  3367. QString textLine=CURRENT_VIEW->document()->line(line);
  3368. int l=textLine.length();
  3369. bool quotesInLine=textLine.contains("\"");
  3370. QString fileName;
  3371. for (i=col;i>=0;i--) {
  3372. QChar c=textLine[i];
  3373. if (!((quotesInLine && c==' ') || (c>='A' && c<='Z') || (c>='a' && c<='z')
  3374. || (c>='0' && c<='9') || QString("_-./\\:").contains(c)))
  3375. break;
  3376. fileName.prepend(c);
  3377. }
  3378. for (i=col+1;i<l;i++) {
  3379. QChar c=textLine[i];
  3380. if (!((quotesInLine && c==' ') || (c>='A' && c<='Z') || (c>='a' && c<='z')
  3381. || (c>='0' && c<='9') || QString("_-./\\:").contains(c)))
  3382. break;
  3383. fileName.append(c);
  3384. }
  3385. CATEGORY_OF(category,currentListItem);
  3386. findAndOpenFile(fileName,category);
  3387. }
  3388. }
  3389. void MainForm::openHeader(const QString &fileName, bool systemHeader,
  3390. int lineno)
  3391. {
  3392. if (systemHeader) {
  3393. // Don't do this if the name ends with ".tpr" because that would cause
  3394. // openProject to close the current project and load the new one instead.
  3395. if (!fileName.endsWith(".tpr",FALSE)) {
  3396. bool inProject;
  3397. void *sourceFile;
  3398. QString fileNameFull=QDir(QString("%1/include/c/").arg(tigcc_base))
  3399. .filePath(fileName);
  3400. if (findSourceFile(inProject,sourceFile,fileNameFull)) {
  3401. if (inProject) {
  3402. fileTreeClicked(reinterpret_cast<ListViewFile *>(sourceFile));
  3403. if (reinterpret_cast<ListViewFile *>(sourceFile)->kateView)
  3404. reinterpret_cast<ListViewFile *>(sourceFile)->kateView->setCursorPosition(KTextEditor::Cursor(lineno,0));
  3405. } else {
  3406. reinterpret_cast<SourceFileWindow *>(sourceFile)->kateView->setCursorPosition(KTextEditor::Cursor(lineno,0));
  3407. ACTIVATE_WINDOW(reinterpret_cast<SourceFileWindow *>(sourceFile)->winId());
  3408. }
  3409. } else {
  3410. if (getPathType(fileNameFull)==PATH_FILE) {
  3411. openProject(fileNameFull);
  3412. if (findSourceFile(inProject,sourceFile,fileNameFull) && !inProject) {
  3413. reinterpret_cast<SourceFileWindow *>(sourceFile)->kateView->setCursorPosition(KTextEditor::Cursor(lineno,0));
  3414. ACTIVATE_WINDOW(reinterpret_cast<SourceFileWindow *>(sourceFile)->winId());
  3415. }
  3416. } else {
  3417. KMessageBox::error(this,QString("File \'%1\' not found.").arg(fileName),
  3418. "Search Failed");
  3419. }
  3420. }
  3421. }
  3422. } else {
  3423. QString name=fileName;
  3424. int pos;
  3425. Q3ListViewItem *item=hFilesListItem;
  3426. while ((pos=name.find('/'))>=0) {
  3427. QString folder=name.left(pos);
  3428. name.remove(0,pos+1);
  3429. for (item=item->firstChild();item;item=item->nextSibling()) {
  3430. if (IS_FOLDER(item)) {
  3431. if (item->text(0)==folder) break;
  3432. }
  3433. }
  3434. if (!item) return;
  3435. }
  3436. for (item=item->firstChild();item;item=item->nextSibling()) {
  3437. if (IS_FILE(item)) {
  3438. ListViewFile *fileItem=static_cast<ListViewFile *>(item);
  3439. if (QFileInfo(fileItem->fileName).fileName()==name) {
  3440. fileTreeClicked(item);
  3441. if (fileItem->kateView)
  3442. fileItem->kateView->setCursorPosition(KTextEditor::Cursor(lineno,0));
  3443. return;
  3444. }
  3445. }
  3446. }
  3447. }
  3448. }
  3449. void MainForm::findFindSymbolDeclaration()
  3450. {
  3451. if (IS_FILE(currentListItem) && CURRENT_VIEW) {
  3452. QString fileText=CURRENT_VIEW->document()->text();
  3453. CATEGORY_OF(category,currentListItem);
  3454. // "Find symbol declaration" only operates on C files.
  3455. if (category==cFilesListItem || category==qllFilesListItem
  3456. || (category==hFilesListItem && !fileText.isEmpty()
  3457. && fileText[0]!='|' && fileText[0]!=';')) {
  3458. QString fileName=pathInProject(currentListItem);
  3459. QString symbolFile;
  3460. unsigned symbolLine;
  3461. bool systemHeader;
  3462. int line,col,i;
  3463. CURRENT_VIEW->cursorPosition().position(line,col);
  3464. QString textLine=CURRENT_VIEW->document()->line(line);
  3465. QString wordUnderCursor;
  3466. for (i=col-1;i>=0;i--) {
  3467. QChar c=textLine[i];
  3468. if ((c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9')
  3469. || c=='_' || c=='$' || c=='#')
  3470. wordUnderCursor.prepend(c);
  3471. }
  3472. int len=textLine.length();
  3473. for (i=col;i<len;i++) {
  3474. QChar c=textLine[i];
  3475. if ((c>='A' && c<='Z') || (c>='a' && c<='z') || (c>='0' && c<='9')
  3476. || c=='_' || c=='$' || c=='#')
  3477. wordUnderCursor.append(c);
  3478. }
  3479. if (findSymbolInFile(wordUnderCursor,fileText,fileName,this,symbolFile,
  3480. symbolLine,systemHeader)
  3481. && !symbolFile.isNull()) {
  3482. if (symbolFile==fileName)
  3483. CURRENT_VIEW->setCursorPosition(KTextEditor::Cursor(symbolLine,0));
  3484. else
  3485. openHeader(symbolFile,systemHeader,symbolLine);
  3486. }
  3487. }
  3488. }
  3489. }
  3490. //returns 1 on success
  3491. int MainForm::projectAddFiles_oneFile(const QString &fileName)
  3492. {
  3493. Q3ListViewItem *category=othFilesListItem;
  3494. QString suffix,caption;
  3495. int p;
  3496. p=fileName.findRev('/');
  3497. if (p<0) p=-1;
  3498. caption=fileName.mid(p+1);
  3499. p=caption.findRev('.');
  3500. if (p>=0) {
  3501. suffix=caption.mid(p+1);
  3502. caption.truncate(p);
  3503. }
  3504. if (!checkFileName(fileName,extractAllFileNames())) {
  3505. KMessageBox::error(this,QString("The file \'%1\' is already included in the project.").arg(caption));
  3506. return 0;
  3507. }
  3508. if (!suffix.compare("h"))
  3509. category=hFilesListItem;
  3510. else if (!suffix.compare("c"))
  3511. category=cFilesListItem;
  3512. else if (!suffix.compare("s"))
  3513. category=sFilesListItem;
  3514. else if (!suffix.compare("asm"))
  3515. category=asmFilesListItem;
  3516. else if (!suffix.compare("qll"))
  3517. category=qllFilesListItem;
  3518. else if (!suffix.compare("o"))
  3519. category=oFilesListItem;
  3520. else if (!suffix.compare("a"))
  3521. category=aFilesListItem;
  3522. else if (!suffix.compare("txt"))
  3523. category=txtFilesListItem;
  3524. if (category && category==qllFilesListItem && qllFileCount) {
  3525. KMessageBox::error(this,"There may be only one Quill source file in each project.","Quill Error");
  3526. return 0;
  3527. }
  3528. if (!category)
  3529. category=othFilesListItem;
  3530. if (openFile(category,category,caption,fileName))
  3531. return 1;
  3532. return 0;
  3533. }
  3534. void MainForm::projectAddFiles()
  3535. {
  3536. unsigned long i,e;
  3537. int projectChanged=0;
  3538. if (compiling) return;
  3539. QStringList result=SGetFileName_Multiple(findFilter(TIGCCAddFilesFilter),"Add Files",this);
  3540. e=result.count();
  3541. for (i=0;i<e;i++) {
  3542. if (projectAddFiles_oneFile(result[i]))
  3543. projectChanged=TRUE;
  3544. }
  3545. if (projectChanged) {
  3546. projectIsDirty=TRUE;
  3547. projectNeedsRelink=TRUE;
  3548. }
  3549. }
  3550. static bool stopCompilingFlag, errorsCompilingFlag;
  3551. static QString compileStats;
  3552. static QDateTime newestHeaderTimestamp;
  3553. static QStringList objectFiles;
  3554. static QStringList deletableObjectFiles;
  3555. static QStringList deletableAsmFiles;
  3556. static KProcess *process;
  3557. QString MainForm::writeTempSourceFile(void *srcFile, bool inProject)
  3558. {
  3559. const QString *origFileName;
  3560. Q3ListViewItem *category;
  3561. QString fileName;
  3562. QString fileText;
  3563. LineStartList *pLineStartList=0;
  3564. if (inProject) {
  3565. ListViewFile *sourceFile=reinterpret_cast<ListViewFile *>(srcFile);
  3566. origFileName=&(sourceFile->fileName);
  3567. CATEGORY_OF(cat,sourceFile);
  3568. category=cat;
  3569. QString folder;
  3570. Q3ListViewItem *item=sourceFile->parent();
  3571. while (!IS_CATEGORY(item)) {
  3572. folder.prepend('/');
  3573. folder.prepend(item->text(0));
  3574. item=item->parent();
  3575. }
  3576. QString ext;
  3577. // Some categories need fixed extensions.
  3578. if (category==cFilesListItem) {
  3579. ext=".c";
  3580. } else if (category==sFilesListItem) {
  3581. ext=".s";
  3582. } else if (category==asmFilesListItem) {
  3583. ext=".asm";
  3584. } else if (category==qllFilesListItem) {
  3585. ext=".qll";
  3586. } else if (category==oFilesListItem) {
  3587. ext=".o";
  3588. } else if (category==aFilesListItem) {
  3589. ext=".a";
  3590. } else {
  3591. // For others (header files in particular), we need to keep whatever
  3592. // extension the user supplied.
  3593. int dotPos=origFileName->findRev('.');
  3594. int slashPos=origFileName->findRev('/');
  3595. if (dotPos>slashPos) ext=origFileName->mid(dotPos);
  3596. }
  3597. fileName=QString("%1/%2%3%4").arg(tempdir).arg(folder)
  3598. .arg(sourceFile->text(0)).arg(ext);
  3599. if (IS_EDITABLE_CATEGORY(category)) {
  3600. fileText=sourceFile->kateView->document()->text();
  3601. pLineStartList=&(sourceFile->lineStartList);
  3602. } else {
  3603. if (copyFile(origFileName->ascii(),fileName.ascii())) {
  3604. KMessageBox::error(this,"Failed to copy file to temporary directory.");
  3605. stopCompilingFlag=TRUE;
  3606. }
  3607. return fileName;
  3608. }
  3609. } else {
  3610. SourceFileWindow *sourceFile=reinterpret_cast<SourceFileWindow *>(srcFile);
  3611. origFileName=&(sourceFile->fileName);
  3612. category=reinterpret_cast<Q3ListViewItem *>(sourceFile->category);
  3613. fileName=QString("%1%2").arg(tempdir)
  3614. .arg(origFileName->mid(origFileName->findRev('/')));
  3615. fileText=sourceFile->kateView->document()->text();
  3616. pLineStartList=&(sourceFile->lineStartList);
  3617. }
  3618. if (saveAndSplitFileText(fileName.ascii(),fileText,(category==cFilesListItem),
  3619. (category==cFilesListItem||category==qllFilesListItem),
  3620. (category==sFilesListItem),*origFileName,pLineStartList)) {
  3621. KMessageBox::error(this,"Failed to write source file to temporary directory.");
  3622. stopCompilingFlag=TRUE;
  3623. }
  3624. return fileName;
  3625. }
  3626. void MainForm::startCompiling()
  3627. {
  3628. if (preferences.autoSave) {
  3629. if (!fileSave()) {
  3630. stopCompilingFlag=TRUE;
  3631. return;
  3632. }
  3633. } else {
  3634. foreach (SourceFileWindow *sourceFile, sourceFiles) sourceFile->fileSave();
  3635. }
  3636. fileNewMenu->menuAction()->setEnabled(FALSE);
  3637. fileNewAction->setEnabled(FALSE);
  3638. fileOpenAction->setEnabled(FALSE);
  3639. fileRecent1Action->setEnabled(FALSE);
  3640. fileRecent2Action->setEnabled(FALSE);
  3641. fileRecent3Action->setEnabled(FALSE);
  3642. fileRecent4Action->setEnabled(FALSE);
  3643. fileExitAction->setEnabled(FALSE);
  3644. projectAddFilesAction->setEnabled(FALSE);
  3645. projectCompileAction->setVisible(FALSE);
  3646. projectMakeAction->setVisible(FALSE);
  3647. projectBuildAction->setVisible(FALSE);
  3648. projectCompileAction->setEnabled(FALSE);
  3649. shortcuts[15]->setEnabled(FALSE);
  3650. projectMakeAction->setEnabled(FALSE);
  3651. shortcuts[16]->setEnabled(FALSE);
  3652. projectBuildAction->setEnabled(FALSE);
  3653. projectStopCompilationAction->setEnabled(TRUE);
  3654. projectForceQuitAction->setEnabled(TRUE);
  3655. projectStopCompilationAction->setVisible(TRUE);
  3656. projectForceQuitAction->setVisible(TRUE);
  3657. debugRunAction->setEnabled(FALSE);
  3658. debugPauseAction->setEnabled(FALSE);
  3659. debugResetAction->setEnabled(FALSE);
  3660. foreach (SourceFileWindow *sourceFile, sourceFiles) {
  3661. sourceFile->fileAddToProjectAction->setEnabled(FALSE);
  3662. sourceFile->fileCompileAction->setEnabled(FALSE);
  3663. }
  3664. compiling=TRUE;
  3665. stopCompilingFlag=FALSE;
  3666. errorsCompilingFlag=FALSE;
  3667. newestHeaderTimestamp=QDateTime();
  3668. objectFiles.clear();
  3669. deletableObjectFiles.clear();
  3670. deletableAsmFiles.clear();
  3671. errorList->errorListView->clear();
  3672. programOutput=QString::null;
  3673. compileStats=QString::null;
  3674. projectProgramOutputAction->setEnabled(FALSE);
  3675. process=static_cast<KProcess *>(NULL);
  3676. // Write all the headers and incbin files to the temporary directory.
  3677. Q3ListViewItemIterator lvit(hFilesListItem);
  3678. Q3ListViewItem *item;
  3679. for (item=(++lvit).current();item&&!IS_CATEGORY(item);
  3680. item=(++lvit).current()) {
  3681. if (IS_FILE(item)) {
  3682. if (static_cast<ListViewFile *>(item)->modifiedSinceLastCompile)
  3683. headersModified=TRUE;
  3684. if (!headersModified) {
  3685. QDateTime headerTimestamp=QFileInfo(static_cast<ListViewFile *>(item)->fileName).lastModified();
  3686. if (!newestHeaderTimestamp.isValid()
  3687. || (headerTimestamp.isValid()
  3688. && headerTimestamp>newestHeaderTimestamp))
  3689. newestHeaderTimestamp=headerTimestamp;
  3690. }
  3691. writeTempSourceFile(static_cast<ListViewFile *>(item),TRUE);
  3692. if (stopCompilingFlag) return;
  3693. }
  3694. }
  3695. lvit=Q3ListViewItemIterator(othFilesListItem);
  3696. for (item=(++lvit).current();item&&!IS_CATEGORY(item);
  3697. item=(++lvit).current()) {
  3698. if (IS_FILE(item)) {
  3699. if (!headersModified) {
  3700. QDateTime headerTimestamp=QFileInfo(static_cast<ListViewFile *>(item)->fileName).lastModified();
  3701. if (!newestHeaderTimestamp.isValid()
  3702. || (headerTimestamp.isValid()
  3703. && headerTimestamp>newestHeaderTimestamp))
  3704. newestHeaderTimestamp=headerTimestamp;
  3705. }
  3706. writeTempSourceFile(static_cast<ListViewFile *>(item),TRUE);
  3707. if (stopCompilingFlag) return;
  3708. }
  3709. }
  3710. }
  3711. void MainForm::stopCompiling()
  3712. {
  3713. clear_temp_dir();
  3714. stopCompilingFlag=FALSE;
  3715. errorsCompilingFlag=FALSE;
  3716. compiling=FALSE;
  3717. foreach (SourceFileWindow *sourceFile, sourceFiles) {
  3718. sourceFile->fileAddToProjectAction->setEnabled(TRUE);
  3719. sourceFile->fileCompileAction->setEnabled(TRUE);
  3720. sourceFile->fileCloseAction->setEnabled(TRUE);
  3721. }
  3722. debugRunAction->setEnabled(TRUE);
  3723. debugPauseAction->setEnabled(preferences.linkTarget==LT_TIEMU);
  3724. debugResetAction->setEnabled(preferences.linkTarget==LT_TIEMU);
  3725. projectStopCompilationAction->setVisible(FALSE);
  3726. projectForceQuitAction->setVisible(FALSE);
  3727. projectStopCompilationAction->setEnabled(FALSE);
  3728. projectForceQuitAction->setEnabled(FALSE);
  3729. projectCompileAction->setEnabled(TRUE);
  3730. shortcuts[15]->setEnabled(TRUE);
  3731. projectMakeAction->setEnabled(TRUE);
  3732. shortcuts[16]->setEnabled(TRUE);
  3733. projectBuildAction->setEnabled(TRUE);
  3734. projectCompileAction->setVisible(TRUE);
  3735. projectMakeAction->setVisible(TRUE);
  3736. projectBuildAction->setVisible(TRUE);
  3737. projectAddFilesAction->setEnabled(TRUE);
  3738. fileExitAction->setEnabled(TRUE);
  3739. fileRecent1Action->setEnabled(TRUE);
  3740. fileRecent2Action->setEnabled(TRUE);
  3741. fileRecent3Action->setEnabled(TRUE);
  3742. fileRecent4Action->setEnabled(TRUE);
  3743. fileOpenAction->setEnabled(TRUE);
  3744. fileNewAction->setEnabled(TRUE);
  3745. fileNewMenu->menuAction()->setEnabled(TRUE);
  3746. statusBar()->clear();
  3747. }
  3748. static QString errorFunction;
  3749. static bool errorFlag;
  3750. static unsigned ldTigccStatPhase=0;
  3751. void MainForm::process_finished()
  3752. {
  3753. // If we're in a modal dialog, let it complete or exiting the event loop will
  3754. // crash.
  3755. if (QCoreApplication::loopLevel()>2) {
  3756. QTimer::singleShot(100,this,SLOT(process_finished()));
  3757. return;
  3758. }
  3759. errorFunction=QString::null;
  3760. ldTigccStatPhase=0;
  3761. QCoreApplication::exit_loop();
  3762. }
  3763. void MainForm::process_readyRead()
  3764. {
  3765. static int a68kErrorLine=0; // A68k errors are split onto several lines.
  3766. static int errorLine, errorColumn;
  3767. static QString errorFile;
  3768. while (process->canReadLine()) {
  3769. QString line=process->readLine();
  3770. line.chop(1); // zap newline
  3771. // ld-tigcc doesn't currently know the difference between host charset and
  3772. // calculator charset, so the variable name won't display properly if it
  3773. // contains non-ASCII characters. Fix that up.
  3774. if (ldTigccStatPhase==1
  3775. && line.trimmed().startsWith("Program Variable Name:",FALSE)) {
  3776. int pos=line.find(':');
  3777. while (line[++pos]==' ');
  3778. line.truncate(pos);
  3779. if (!rootListItem->text(0).contains('\\')) line.append("main\\");
  3780. line.append(rootListItem->text(0));
  3781. }
  3782. programOutput.append(line);
  3783. programOutput.append('\n');
  3784. projectProgramOutputAction->setEnabled(TRUE);
  3785. if (line.isEmpty()) continue;
  3786. // Parse the error message
  3787. switch (ldTigccStatPhase) {
  3788. default: // should not happen
  3789. ldTigccStatPhase=0;
  3790. case 0:
  3791. switch (a68kErrorLine) {
  3792. default: // should not happen
  3793. a68kErrorLine=0;
  3794. case 0:
  3795. errorLine=-1;
  3796. errorColumn=-1;
  3797. errorFile=QString::null;
  3798. case 1:
  3799. if (line.contains(QRegExp(" line [0-9]+$",FALSE))) {
  3800. if (line.contains("(user macro)",FALSE))
  3801. errorColumn=0;
  3802. else if (errorFile.isEmpty()) {
  3803. errorFile=QFileInfo(line.left(line.findRev(" line ",-1,FALSE)))
  3804. .fileName();
  3805. errorLine=line.mid(line.findRev(' ')+1).toInt()-1;
  3806. }
  3807. errorFunction=QString::null;
  3808. a68kErrorLine=1;
  3809. } else if (a68kErrorLine==1) {
  3810. // This line contains only a copy of the source line, skip it.
  3811. a68kErrorLine=2;
  3812. } else {
  3813. if (line.contains("Fatal errors - assembly aborted",FALSE)) break;
  3814. // Not an A68k error, so parse it as a standard *nix-style error.
  3815. // Normalize characters and strip whitespace
  3816. line=line.trimmed();
  3817. line.replace('`','\''); // backtick
  3818. line.replace(QChar(0xb4),'\''); // forward apostrophe
  3819. line.replace('\"','\''); // quote
  3820. if (line.contains("assembler messages:",FALSE)
  3821. || line.startsWith("from ",FALSE)
  3822. || (!preferences.allowImplicitDeclaration
  3823. && (line.contains("previous implicit declaration",FALSE)
  3824. || line.contains("previously implicitly declared",FALSE))))
  3825. break;
  3826. // ld-tigcc statistics start here, don't display them as errors.
  3827. if (line.toLower()=="target calculators:") {
  3828. ldTigccStatPhase=1;
  3829. break;
  3830. }
  3831. if (line.startsWith("in file",FALSE))
  3832. errorFunction=QString::null;
  3833. else {
  3834. // The regex also supports Windows file names, in case KTIGCC ever
  3835. // encounters them. Hopefully nobody will try giving it MacOS <=9
  3836. // file names.
  3837. int pos=line.find(QRegExp(":(?![/\\\\])"));
  3838. if (pos>=0) errorFile=line.left(pos);
  3839. if (errorFile.isEmpty()) {
  3840. if (!line.endsWith("."))
  3841. line.append('.');
  3842. errorFlag=TRUE;
  3843. new ErrorListItem(this,line.startsWith("please fill out ",FALSE)?
  3844. etInfo:etError,QString::null,QString::null,line,
  3845. errorLine,errorColumn);
  3846. } else {
  3847. QString errorMessage;
  3848. if (errorFile.toLower()=="error"||errorFile.toLower()=="warning") {
  3849. errorFile=QString::null;
  3850. errorMessage=line;
  3851. } else {
  3852. errorFile=QFileInfo(errorFile).fileName();
  3853. errorMessage=line.mid(pos+1);
  3854. }
  3855. if (!errorMessage.isEmpty() && errorMessage[0]>='0'
  3856. && errorMessage[0]<='9') {
  3857. pos=errorMessage.find(':');
  3858. if (pos>=0) {
  3859. bool ok;
  3860. errorLine=errorMessage.left(pos).toInt(&ok)-1;
  3861. if (ok) {
  3862. errorMessage.remove(0,pos+1);
  3863. if (!errorMessage.isEmpty() && errorMessage[0]>='0'
  3864. && errorMessage[0]<='9') {
  3865. pos=errorMessage.find(':');
  3866. if (pos>=0) {
  3867. errorColumn=errorMessage.left(pos).toInt(&ok)-1;
  3868. if (ok) errorMessage.remove(0,pos+1);
  3869. }
  3870. }
  3871. }
  3872. }
  3873. errorMessage=errorMessage.trimmed();
  3874. ErrorTypes errorType=etError;
  3875. if (errorMessage.startsWith("warning:",FALSE)) {
  3876. errorMessage.remove(0,8);
  3877. errorMessage=errorMessage.trimmed();
  3878. errorType=etWarning;
  3879. } else if (errorMessage.startsWith("error:",FALSE)) {
  3880. errorMessage.remove(0,6);
  3881. errorMessage=errorMessage.trimmed();
  3882. }
  3883. if (errorMessage.startsWith("#warning ",FALSE)) {
  3884. errorMessage.remove(0,9);
  3885. errorType=etWarning;
  3886. } else if (errorMessage.startsWith("#error ",FALSE))
  3887. errorMessage.remove(0,7);
  3888. if (errorMessage.startsWith("previous declaration of ",FALSE)
  3889. || errorMessage.startsWith("possible real start of ",FALSE)
  3890. || errorMessage.startsWith("unused variable ",FALSE)
  3891. || errorMessage.startsWith("unused parameter ",FALSE)
  3892. || errorMessage.contains("previously declared here",FALSE)
  3893. || errorMessage.contains("location of the previous definition",FALSE))
  3894. errorType=etInfo;
  3895. if (!preferences.allowImplicitDeclaration)
  3896. errorMessage.replace(QRegExp("^implicit declaration of ",FALSE),
  3897. "Undefined reference to ");
  3898. if (!errorMessage.endsWith("."))
  3899. errorMessage.append('.');
  3900. if (errorType==etError) errorFlag=TRUE;
  3901. new ErrorListItem(this,errorType,errorFile,errorFunction,
  3902. errorMessage,errorLine,errorColumn);
  3903. } else {
  3904. if (errorMessage.startsWith(" in function \'",FALSE)
  3905. && errorMessage.count('\'')>1) {
  3906. errorFunction=errorMessage.mid(14,errorMessage.find('\'',14)-14);
  3907. } else if (errorMessage.startsWith(" at top level",FALSE)) {
  3908. errorFunction=QString::null;
  3909. } else {
  3910. ErrorTypes errorType=etError;
  3911. if (errorMessage.startsWith("warning:",FALSE)) {
  3912. errorMessage.remove(0,8);
  3913. errorMessage=errorMessage.trimmed();
  3914. errorType=etWarning;
  3915. } else if (errorMessage.startsWith("error:",FALSE)) {
  3916. errorMessage.remove(0,6);
  3917. errorMessage=errorMessage.trimmed();
  3918. }
  3919. if (!errorMessage.endsWith("."))
  3920. errorMessage.append('.');
  3921. if (errorType==etError) errorFlag=TRUE;
  3922. new ErrorListItem(this,errorType,errorFile,QString::null,
  3923. errorMessage,errorLine,errorColumn);
  3924. }
  3925. }
  3926. }
  3927. }
  3928. }
  3929. break;
  3930. case 2:
  3931. if (line.contains(QRegExp("^\\s*\\^"))) {
  3932. int caretPos=line.find('^');
  3933. if (errorLine>=0 && errorColumn<0)
  3934. errorColumn=caretPos-1; // there's an extra tab at the beginning
  3935. QString errorMessage=line.mid(caretPos+2);
  3936. if (!errorMessage.endsWith("."))
  3937. errorMessage.append('.');
  3938. errorFlag=TRUE;
  3939. new ErrorListItem(this,etError,errorFile,QString::null,errorMessage,
  3940. errorLine,errorColumn);
  3941. }
  3942. a68kErrorLine=0;
  3943. break;
  3944. }
  3945. break;
  3946. case 1:
  3947. line=line.trimmed();
  3948. // The next line is the first one to display in the dialog. (TIGCC IDE
  3949. // does the same.)
  3950. if (line.startsWith("Program Variable Name:",FALSE))
  3951. ldTigccStatPhase=2;
  3952. break;
  3953. case 2:
  3954. compileStats.append(line.simplified());
  3955. compileStats.append('\n');
  3956. break;
  3957. }
  3958. }
  3959. if (errorFlag) {
  3960. errorsCompilingFlag=TRUE;
  3961. if (preferences.stopAtFirstError) stopCompilingFlag=TRUE;
  3962. }
  3963. }
  3964. void MainForm::process_readyRead_recordOnly()
  3965. {
  3966. QString line;
  3967. while (process->canReadLine()) {
  3968. programOutput.append(process->readLine());
  3969. projectProgramOutputAction->setEnabled(TRUE);
  3970. }
  3971. }
  3972. void MainForm::compileFile(void *srcFile, bool inProject, bool force)
  3973. {
  3974. Q3ListViewItem *category;
  3975. const QString *origFileName;
  3976. bool modified=FALSE;
  3977. QString shortFileName;
  3978. if (stopCompilingFlag) return;
  3979. errorFlag=FALSE;
  3980. if (inProject) {
  3981. ListViewFile *sourceFile=reinterpret_cast<ListViewFile *>(srcFile);
  3982. CATEGORY_OF(cat,sourceFile);
  3983. category=cat;
  3984. origFileName=&(sourceFile->fileName);
  3985. if (sourceFile->modifiedSinceLastCompile)
  3986. modified=TRUE;
  3987. shortFileName=sourceFile->text(0);
  3988. } else {
  3989. SourceFileWindow *sourceFile=reinterpret_cast<SourceFileWindow *>(srcFile);
  3990. category=reinterpret_cast<Q3ListViewItem *>(sourceFile->category);
  3991. origFileName=&(sourceFile->fileName);
  3992. if (sourceFile->kateView->document()->isModified())
  3993. modified=TRUE;
  3994. shortFileName=sourceFile->fileName;
  3995. }
  3996. if (category==cFilesListItem || category==sFilesListItem
  3997. || category==asmFilesListItem || category==qllFilesListItem) {
  3998. QString objectFile=*origFileName;
  3999. int dotPos=origFileName->findRev('.');
  4000. int slashPos=origFileName->findRev('/');
  4001. if (dotPos>slashPos) objectFile.truncate(dotPos);
  4002. // Compute correct file names for unsaved files.
  4003. if (!objectFile.isEmpty() && objectFile[0]!='/') {
  4004. if (inProject) {
  4005. ListViewFile *sourceFile=reinterpret_cast<ListViewFile *>(srcFile);
  4006. Q3ListViewItem *item=sourceFile->parent();
  4007. while (!IS_CATEGORY(item)) {
  4008. objectFile.prepend('/');
  4009. objectFile.prepend(item->text(0));
  4010. item=item->parent();
  4011. }
  4012. }
  4013. if (!projectFileName.isEmpty()) {
  4014. objectFile.prepend('/');
  4015. objectFile.prepend(QFileInfo(projectFileName).absolutePath());
  4016. }
  4017. }
  4018. QString asmFile=objectFile;
  4019. objectFile.append(".o");
  4020. deletableObjectFiles.append(objectFile);
  4021. objectFiles.append(objectFile);
  4022. asmFile.append(".s");
  4023. mkdir_multi(objectFile);
  4024. if (category==cFilesListItem || category==qllFilesListItem)
  4025. deletableAsmFiles.append(asmFile);
  4026. // Figure out whether to recompile the file.
  4027. if (!force && !modified && !headersModified) {
  4028. QFileInfo objectFileInfo(objectFile);
  4029. if (objectFileInfo.exists()) {
  4030. QDateTime timestamp=objectFileInfo.lastModified();
  4031. if (timestamp.isValid() && (!newestHeaderTimestamp.isValid()
  4032. || timestamp>=newestHeaderTimestamp)) {
  4033. QDateTime sourceTimestamp=QFileInfo(*origFileName).lastModified();
  4034. if (sourceTimestamp.isValid() && timestamp>=sourceTimestamp) {
  4035. return;
  4036. }
  4037. }
  4038. }
  4039. }
  4040. if (category==sFilesListItem||category==asmFilesListItem)
  4041. statusBar()->message(QString("Assembling File \'%1\'...").arg(shortFileName));
  4042. else
  4043. statusBar()->message(QString("Compiling File \'%1\'...").arg(shortFileName));
  4044. projectNeedsRelink=TRUE;
  4045. QString fileName=writeTempSourceFile(srcFile,inProject);
  4046. if (stopCompilingFlag) return;
  4047. QString tempObjectFile=fileName;
  4048. dotPos=fileName.findRev('.');
  4049. slashPos=fileName.findRev('/');
  4050. if (dotPos>slashPos) tempObjectFile.truncate(dotPos);
  4051. QString tempAsmFile=tempObjectFile;
  4052. tempObjectFile.append(".o");
  4053. tempAsmFile.append(".s");
  4054. QString fileDir=QFileInfo(fileName).absolutePath();
  4055. QDir qdir;
  4056. if (category==asmFilesListItem) {
  4057. // Assemble A68k file
  4058. KShell::Errors err;
  4059. QStringList args=KShell::splitArgs(settings.a68k_switches,
  4060. KShell::TildeExpand|KShell::AbortOnMeta,
  4061. &err);
  4062. if (err) {
  4063. new ErrorListItem(this,etError,QString::null,QString::null,
  4064. "Invalid A68k assembler command line options.",-1,-1);
  4065. stopCompilingFlag=TRUE;
  4066. }
  4067. if (!stopCompilingFlag) {
  4068. process=new KProcess();
  4069. process->setOutputChannelMode(KProcess::MergedChannels);
  4070. process->setWorkingDirectory(fileDir);
  4071. *process<<(QString("%1/bin/a68k").arg(tigcc_base))
  4072. <<fileName<<(QString("-o%1").arg(tempObjectFile))
  4073. <<(QString("-i%1/include/asm/").arg(tigcc_base))<<"-q"<<args;
  4074. if (settings.cut_ranges||settings.archive)
  4075. *process<<"-a"; // all relocs
  4076. if (settings.optimize_returns||settings.archive)
  4077. *process<<"-d"; // keep locals
  4078. connect(process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(process_finished()));
  4079. connect(process,SIGNAL(readyRead()),this,SLOT(process_readyRead()));
  4080. process->start();
  4081. // We need to block here, but events still need to be handled. The most
  4082. // effective way to do this is to enter the event loop recursively,
  4083. // even though it is not recommended by Qt.
  4084. QCoreApplication::enter_loop();
  4085. // This will be reached only after exitLoop() is called.
  4086. delete process;
  4087. process=static_cast<KProcess *>(NULL);
  4088. }
  4089. } else {
  4090. bool deleteTempAsmFile=FALSE;
  4091. QString fileNameToAssemble;
  4092. if (category==sFilesListItem) {
  4093. fileNameToAssemble=fileName;
  4094. } else /* C or Quill */ {
  4095. // Compile C/Quill file to assembly
  4096. KShell::Errors err;
  4097. QStringList args=KShell::splitArgs(settings.cc_switches,
  4098. KShell::TildeExpand|KShell::AbortOnMeta,
  4099. &err);
  4100. if (err) {
  4101. new ErrorListItem(this,etError,QString::null,QString::null,
  4102. "Invalid C compiler command line options.",-1,-1);
  4103. stopCompilingFlag=TRUE;
  4104. }
  4105. if (!stopCompilingFlag) {
  4106. process=new KProcess();
  4107. process->setOutputChannelMode(KProcess::MergedChannels);
  4108. process->setWorkingDirectory(fileDir);
  4109. *process<<(QString("%1/bin/gcc").arg(tigcc_base))
  4110. <<"-S"<<"-I"<<fileDir
  4111. <<"-B"<<(QString("%1/bin/").arg(tigcc_base))<<"-I-"
  4112. <<"-I"<<(QString("%1/include/c").arg(tigcc_base))<<args;
  4113. if (category==qllFilesListItem) { // Quill needs special switches.
  4114. *process<<"-I"<<(QString("%1/include/quill").arg(tigcc_base))
  4115. <<"-include"<<quill_drv;
  4116. }
  4117. if (settings.use_data_var)
  4118. *process<<"-mno-merge-sections";
  4119. if (!preferences.allowImplicitDeclaration)
  4120. *process<<"-Werror-implicit-function-declaration";
  4121. if (settings.debug_info)
  4122. *process<<"-gdwarf-2"<<"-g3"<<"-fasynchronous-unwind-tables";
  4123. if (settings.fargo)
  4124. *process<<"-DFARGO";
  4125. else if (settings.flash_os)
  4126. *process<<"-DFLASH_OS";
  4127. else if (!settings.archive) { // This leaves only regular programs.
  4128. *process<<process_libopts();
  4129. }
  4130. *process<<fileName<<"-o"<<tempAsmFile;
  4131. connect(process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(process_finished()));
  4132. connect(process,SIGNAL(readyRead()),this,SLOT(process_readyRead()));
  4133. process->start();
  4134. // We need to block here, but events still need to be handled. The most
  4135. // effective way to do this is to enter the event loop recursively,
  4136. // even though it is not recommended by Qt.
  4137. QCoreApplication::enter_loop();
  4138. // This will be reached only after exitLoop() is called.
  4139. delete process;
  4140. process=static_cast<KProcess *>(NULL);
  4141. }
  4142. if (!stopCompilingFlag && qdir.exists(tempAsmFile)) {
  4143. // Run patcher.
  4144. process=new KProcess();
  4145. process->setOutputChannelMode(KProcess::MergedChannels);
  4146. process->setWorkingDirectory(fileDir);
  4147. *process<<(QString("%1/bin/patcher").arg(tigcc_base))
  4148. <<tempAsmFile<<"-o"<<tempAsmFile;
  4149. connect(process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(process_finished()));
  4150. connect(process,SIGNAL(readyRead()),this,SLOT(process_readyRead()));
  4151. process->start();
  4152. // We need to block here, but events still need to be handled. The most
  4153. // effective way to do this is to enter the event loop recursively,
  4154. // even though it is not recommended by Qt.
  4155. QCoreApplication::enter_loop();
  4156. // This will be reached only after exitLoop() is called.
  4157. delete process;
  4158. process=static_cast<KProcess *>(NULL);
  4159. }
  4160. if (qdir.exists(tempAsmFile)) {
  4161. if (!stopCompilingFlag) {
  4162. fileNameToAssemble=tempAsmFile;
  4163. qdir.remove(asmFile);
  4164. if (copyFile(tempAsmFile.ascii(),asmFile.ascii())) {
  4165. new ErrorListItem(this,etError,QString::null,QString::null,
  4166. "Failed to copy assembly file from temporary directory.",
  4167. -1,-1);
  4168. stopCompilingFlag=TRUE;
  4169. }
  4170. }
  4171. deleteTempAsmFile=TRUE;
  4172. } else {
  4173. errorFlag=TRUE;
  4174. errorsCompilingFlag=TRUE;
  4175. if (preferences.stopAtFirstError) stopCompilingFlag=TRUE;
  4176. }
  4177. }
  4178. // Assemble GNU as file
  4179. if (!stopCompilingFlag && !fileNameToAssemble.isNull()) {
  4180. KShell::Errors err;
  4181. QStringList args=KShell::splitArgs(settings.as_switches,
  4182. KShell::TildeExpand|KShell::AbortOnMeta,
  4183. &err);
  4184. if (err) {
  4185. new ErrorListItem(this,etError,QString::null,QString::null,
  4186. "Invalid GNU assembler command line options.",-1,-1);
  4187. stopCompilingFlag=TRUE;
  4188. }
  4189. if (!stopCompilingFlag) {
  4190. process=new KProcess();
  4191. process->setOutputChannelMode(KProcess::MergedChannels);
  4192. process->setWorkingDirectory(fileDir);
  4193. *process<<(QString("%1/bin/as").arg(tigcc_base))
  4194. <<"-I"<<fileDir<<"-mc68000"
  4195. <<"-I"<<(QString("%1/include/s").arg(tigcc_base))<<args;
  4196. if (settings.cut_ranges||settings.archive)
  4197. *process<<"--all-relocs";
  4198. if (settings.optimize_returns||settings.archive)
  4199. *process<<"--keep-locals";
  4200. if (settings.debug_info)
  4201. *process<<"--gdwarf2";
  4202. *process<<fileNameToAssemble<<"-o"<<tempObjectFile;
  4203. connect(process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(process_finished()));
  4204. connect(process,SIGNAL(readyRead()),this,SLOT(process_readyRead()));
  4205. process->start();
  4206. // We need to block here, but events still need to be handled. The most
  4207. // effective way to do this is to enter the event loop recursively,
  4208. // even though it is not recommended by Qt.
  4209. QCoreApplication::enter_loop();
  4210. // This will be reached only after exitLoop() is called.
  4211. delete process;
  4212. process=static_cast<KProcess *>(NULL);
  4213. }
  4214. }
  4215. if (deleteTempAsmFile) qdir.remove(tempAsmFile);
  4216. }
  4217. qdir.remove(fileName);
  4218. if (qdir.exists(tempObjectFile)) {
  4219. qdir.remove(objectFile);
  4220. if (copyFile(tempObjectFile.ascii(),objectFile.ascii())) {
  4221. new ErrorListItem(this,etError,QString::null,QString::null,
  4222. "Failed to copy object file from temporary directory.",
  4223. -1,-1);
  4224. stopCompilingFlag=TRUE;
  4225. }
  4226. qdir.remove(tempObjectFile);
  4227. } else {
  4228. errorFlag=TRUE;
  4229. errorsCompilingFlag=TRUE;
  4230. if (preferences.stopAtFirstError) stopCompilingFlag=TRUE;
  4231. }
  4232. } else if (category==oFilesListItem || category==aFilesListItem) {
  4233. objectFiles.append(*origFileName);
  4234. } // else do nothing (ignore all other categories)
  4235. if (inProject && !errorFlag && !stopCompilingFlag)
  4236. reinterpret_cast<ListViewFile *>(srcFile)->modifiedSinceLastCompile=FALSE;
  4237. }
  4238. void MainForm::compileProject(bool forceAll)
  4239. {
  4240. Q3ListViewItemIterator lvit(fileTree);
  4241. Q3ListViewItem *item;
  4242. for (item=lvit.current(); item&&!stopCompilingFlag; item=(++lvit).current()) {
  4243. if (IS_FILE(item))
  4244. compileFile(static_cast<ListViewFile *>(item),TRUE,forceAll);
  4245. }
  4246. if (!errorsCompilingFlag && !stopCompilingFlag) headersModified=FALSE;
  4247. }
  4248. void MainForm::linkProject()
  4249. {
  4250. errorFlag=FALSE;
  4251. QString projectBaseName=projectFileName;
  4252. if (projectBaseName.endsWith(".tpr",FALSE))
  4253. projectBaseName.truncate(projectBaseName.length()-4);
  4254. QString projectDir=QFileInfo(projectFileName).absolutePath();
  4255. statusBar()->message(QString("Linking Project \'%1\'...")
  4256. .arg(QFileInfo(projectFileName).baseName()));
  4257. if (settings.archive) {
  4258. // Link static library using ar-tigcc.
  4259. process=new KProcess();
  4260. process->setOutputChannelMode(KProcess::MergedChannels);
  4261. process->setWorkingDirectory(projectDir);
  4262. *process<<(QString("%1/bin/ar-tigcc").arg(tigcc_base))
  4263. <<"-o"<<(projectBaseName+".a")<<"--no-names"<<objectFiles;
  4264. connect(process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(process_finished()));
  4265. connect(process,SIGNAL(readyRead()),this,SLOT(process_readyRead()));
  4266. process->start();
  4267. // We need to block here, but events still need to be handled. The most
  4268. // effective way to do this is to enter the event loop recursively,
  4269. // even though it is not recommended by Qt.
  4270. QCoreApplication::enter_loop();
  4271. // This will be reached only after exitLoop() is called.
  4272. delete process;
  4273. process=static_cast<KProcess *>(NULL);
  4274. if (errorsCompilingFlag || stopCompilingFlag) return;
  4275. QFileInfo fileInfo(projectBaseName+".a");
  4276. if (fileInfo.exists())
  4277. compileStats=QString("Archive Size: %1 Bytes\n").arg(fileInfo.size());
  4278. else
  4279. errorsCompilingFlag=TRUE;
  4280. } else {
  4281. // Link executable using ld-tigcc.
  4282. QByteArray packName;
  4283. QString pstarterName; // urlencoded
  4284. QStringList linkerOptions=process_settings(rootListItem->text(0),
  4285. projectBaseName,
  4286. pstarterName,packName);
  4287. process=new KProcess();
  4288. process->setOutputChannelMode(KProcess::MergedChannels);
  4289. process->setWorkingDirectory(projectDir);
  4290. *process<<(QString("%1/bin/ld-tigcc").arg(tigcc_base))
  4291. <<"-v"<<linkerOptions<<objectFiles;
  4292. if (settings.std_lib)
  4293. *process<<QString(settings.flash_os?"%1/lib/flashos.a"
  4294. :(settings.fargo?"%1/lib/fargo.a"
  4295. :"%1/lib/tigcc.a"))
  4296. .arg(tigcc_base);
  4297. connect(process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(process_finished()));
  4298. connect(process,SIGNAL(readyRead()),this,SLOT(process_readyRead()));
  4299. process->start();
  4300. // We need to block here, but events still need to be handled. The most
  4301. // effective way to do this is to enter the event loop recursively,
  4302. // even though it is not recommended by Qt.
  4303. QCoreApplication::enter_loop();
  4304. // This will be reached only after exitLoop() is called.
  4305. delete process;
  4306. process=static_cast<KProcess *>(NULL);
  4307. if (errorsCompilingFlag || stopCompilingFlag) return;
  4308. if (settings.pack) {
  4309. if (errorsCompilingFlag || stopCompilingFlag) return;
  4310. statusBar()->message("Creating launcher...");
  4311. const int numTargets=3;
  4312. static const char binexts[numTargets][5]={".z89",".z9x",".zv2"};
  4313. static const char exts[numTargets][5]={".89z",".9xz",".v2z"};
  4314. static const char cbinexts[numTargets][5]={".y89",".y9x",".yv2"};
  4315. static const char cexts[numTargets][5]={".89y",".9xy",".v2y"};
  4316. bool targeted[numTargets];
  4317. for (int target=0; target<numTargets; target++) {
  4318. targeted[target]=QFileInfo(projectBaseName
  4319. +(settings.outputbin?cbinexts[target]:cexts[target])).exists();
  4320. }
  4321. // Prepare the pstarter.
  4322. QString pstarterBaseName=QString("%1/pstarter").arg(tempdir);
  4323. if (insertName(QString("%1/lib/pstarter.o").arg(tigcc_base),
  4324. pstarterBaseName+".o",packName)) {
  4325. new ErrorListItem(this,etError,QString::null,QString::null,
  4326. "Failed to copy pstarter.o to temporary directory.",
  4327. -1,-1);
  4328. errorsCompilingFlag=TRUE;
  4329. }
  4330. if (errorsCompilingFlag || stopCompilingFlag) return;
  4331. // Link the pstarter with ld-tigcc.
  4332. process=new KProcess();
  4333. process->setOutputChannelMode(KProcess::MergedChannels);
  4334. process->setWorkingDirectory(projectDir);
  4335. *process<<(QString("%1/bin/ld-tigcc").arg(tigcc_base))
  4336. <<"-o"<<pstarterBaseName<<"-n"<<pstarterName
  4337. <<(pstarterBaseName+".o");
  4338. if (settings.outputbin) *process<<"--outputbin";
  4339. connect(process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(process_finished()));
  4340. connect(process,SIGNAL(readyRead()),this,SLOT(process_readyRead()));
  4341. process->start();
  4342. // We need to block here, but events still need to be handled. The most
  4343. // effective way to do this is to enter the event loop recursively,
  4344. // even though it is not recommended by Qt.
  4345. QCoreApplication::enter_loop();
  4346. // This will be reached only after exitLoop() is called.
  4347. delete process;
  4348. process=static_cast<KProcess *>(NULL);
  4349. if (errorsCompilingFlag || stopCompilingFlag) return;
  4350. // Now copy those pstarters actually requested.
  4351. for (int target=0; target<numTargets; target++) {
  4352. if (targeted[target]) {
  4353. if (copyFile(pstarterBaseName+(settings.outputbin?binexts[target]:exts[target]),
  4354. projectBaseName+(settings.outputbin?binexts[target]:exts[target]))) {
  4355. new ErrorListItem(this,etError,QString::null,QString::null,
  4356. "Failed to copy pstarter from temporary directory.",
  4357. -1,-1);
  4358. errorsCompilingFlag=TRUE;
  4359. }
  4360. if (errorsCompilingFlag || stopCompilingFlag) return;
  4361. }
  4362. }
  4363. // Remove any leftover "-titanium" launchers if the TI-89 is targeted.
  4364. if (*targeted) {
  4365. QDir qdir;
  4366. qdir.remove(projectBaseName+"-titanium.89z");
  4367. qdir.remove(projectBaseName+"-Titanium.89z");
  4368. }
  4369. }
  4370. }
  4371. if (errorsCompilingFlag || stopCompilingFlag) return;
  4372. if (!settings.post_build.isEmpty()) {
  4373. // Post-build processing.
  4374. statusBar()->message("Calling User-Defined Program...");
  4375. QString postBuild=settings.post_build;
  4376. // Remove double quotes for TIGCC IDE compatibility. Single quotes will be
  4377. // added instead.
  4378. postBuild.replace("\"($TI89FILE)\"","($TI89FILE)",FALSE);
  4379. postBuild.replace("\"($TI89TIFILE)\"","($TI89TIFILE)",FALSE);
  4380. postBuild.replace("\"($TI92PLUSFILE)\"","($TI92PLUSFILE)",FALSE);
  4381. postBuild.replace("\"($V200FILE)\"","($V200FILE)",FALSE);
  4382. postBuild.replace("\"($TI92FILE)\"","($TI92FILE)",FALSE);
  4383. postBuild.replace("($TI89FILE)",
  4384. KShell::quoteArg(libopts.use_ti89?projectBaseName+(
  4385. settings.archive?".a":settings.flash_os?"-89.tib":
  4386. settings.pack?(settings.outputbin?".y89":".89y"):
  4387. settings.outputbin?".z89":".89z"
  4388. ):""),FALSE);
  4389. postBuild.replace("($TI89TIFILE)",
  4390. KShell::quoteArg(libopts.use_ti89?projectBaseName+(
  4391. settings.archive?".a":settings.flash_os?"-89ti.tib":
  4392. settings.pack?(settings.outputbin?".y89":".89y"):
  4393. settings.outputbin?".z89":".89z"
  4394. ):""),FALSE);
  4395. postBuild.replace("($TI92PLUSFILE)",
  4396. KShell::quoteArg(libopts.use_ti92p?projectBaseName+(
  4397. settings.archive?".a":settings.flash_os?"-9x.tib":
  4398. settings.pack?(settings.outputbin?".y9x":".9xy"):
  4399. settings.outputbin?".z9x":".9xz"
  4400. ):""),FALSE);
  4401. postBuild.replace("($V200FILE)",
  4402. KShell::quoteArg(libopts.use_v200?projectBaseName+(
  4403. settings.archive?".a":settings.flash_os?"-v2.tib":
  4404. settings.pack?(settings.outputbin?".yv2":".v2y"):
  4405. settings.outputbin?".zv2":".v2z"
  4406. ):""),FALSE);
  4407. postBuild.replace("($TI92FILE)",
  4408. KShell::quoteArg(settings.fargo?projectBaseName+(
  4409. settings.outputbin?".p92":".92p"
  4410. ):""),FALSE);
  4411. KShell::Errors err;
  4412. QStringList args=KShell::splitArgs(postBuild,
  4413. KShell::TildeExpand|KShell::AbortOnMeta,
  4414. &err);
  4415. if (err) {
  4416. new ErrorListItem(this,etError,QString::null,QString::null,
  4417. "Invalid post-build command line.",-1,-1);
  4418. errorsCompilingFlag=TRUE;
  4419. }
  4420. if (errorsCompilingFlag || stopCompilingFlag) return;
  4421. process=new KProcess();
  4422. process->setOutputChannelMode(KProcess::MergedChannels);
  4423. process->setWorkingDirectory(projectDir);
  4424. *process<<args;
  4425. connect(process,SIGNAL(finished(int,QProcess::ExitStatus)),this,SLOT(process_finished()));
  4426. connect(process,SIGNAL(readyRead()),this,SLOT(process_readyRead_recordOnly()));
  4427. process->start();
  4428. // We need to block here, but events still need to be handled. The most
  4429. // effective way to do this is to enter the event loop recursively,
  4430. // even though it is not recommended by Qt.
  4431. QCoreApplication::enter_loop();
  4432. // This will be reached only after exitLoop() is called.
  4433. delete process;
  4434. process=static_cast<KProcess *>(NULL);
  4435. if (errorsCompilingFlag || stopCompilingFlag) return;
  4436. }
  4437. // Delete object and/or assembly files.
  4438. QDir qdir;
  4439. if (preferences.deleteObjFiles) {
  4440. for (QStringList::Iterator it=deletableObjectFiles.begin();
  4441. it!=deletableObjectFiles.end(); ++it) {
  4442. qdir.remove(*it);
  4443. }
  4444. }
  4445. if (preferences.deleteAsmFiles) {
  4446. for (QStringList::Iterator it=deletableAsmFiles.begin();
  4447. it!=deletableAsmFiles.end(); ++it) {
  4448. qdir.remove(*it);
  4449. }
  4450. }
  4451. projectNeedsRelink=FALSE;
  4452. }
  4453. void MainForm::showStats()
  4454. {
  4455. // KMessageBox also takes plain text, but it interprets \n as paragraph breaks
  4456. // and always renders them as \n\n, no matter whether there is actually just
  4457. // one, two or more than two \n characters. Thus the
  4458. // Qt::convertFromPlainText. Sadly, that replaces the spaces with character
  4459. // #160 (&nbsp;) which doesn't display properly in KMessageBox, so fix it up.
  4460. if (KMessageBox::questionYesNo(this,Qt::convertFromPlainText(
  4461. QString("The project has been compiled successfully.\n\n%1\n"
  4462. "Do you want to open the project folder?").arg(compileStats))
  4463. .replace(QChar(160)," "),
  4464. "Compilation Successful")==KMessageBox::Yes) {
  4465. KUrl projectDir(projectFileName);
  4466. projectDir.setFileName("");
  4467. KRun::runUrl(projectDir,"inode/directory",this);
  4468. }
  4469. }
  4470. void MainForm::projectCompile()
  4471. {
  4472. if (compiling) return;
  4473. startCompiling();
  4474. compileProject(FALSE);
  4475. stopCompiling();
  4476. }
  4477. void MainForm::projectMake()
  4478. {
  4479. if (compiling) return;
  4480. // Can't link a project without saving it first.
  4481. if (projectFileName.isEmpty()) {
  4482. if (!fileSave() || projectFileName.isEmpty()) return;
  4483. }
  4484. startCompiling();
  4485. compileProject(FALSE);
  4486. if (!errorsCompilingFlag && !stopCompilingFlag) linkProject();
  4487. bool success=(!errorsCompilingFlag && !stopCompilingFlag);
  4488. stopCompiling();
  4489. if (success && preferences.successMessage)
  4490. showStats();
  4491. }
  4492. void MainForm::projectBuild()
  4493. {
  4494. if (compiling) return;
  4495. // Can't link a project without saving it first.
  4496. if (projectFileName.isEmpty()) {
  4497. if (!fileSave() || projectFileName.isEmpty()) return;
  4498. }
  4499. startCompiling();
  4500. compileProject(TRUE);
  4501. if (!errorsCompilingFlag && !stopCompilingFlag) linkProject();
  4502. bool success=(!errorsCompilingFlag && !stopCompilingFlag);
  4503. stopCompiling();
  4504. if (success && preferences.successMessage)
  4505. showStats();
  4506. }
  4507. void MainForm::compileSourceFile(void *srcFile)
  4508. {
  4509. if (compiling) return;
  4510. SourceFileWindow *sourceFile=reinterpret_cast<SourceFileWindow *>(srcFile);
  4511. sourceFile->fileCloseAction->setEnabled(FALSE);
  4512. startCompiling();
  4513. compileFile(sourceFile,FALSE,TRUE);
  4514. stopCompiling();
  4515. }
  4516. void MainForm::projectStopCompilation()
  4517. {
  4518. if (!compiling) return;
  4519. stopCompilingFlag=TRUE;
  4520. projectStopCompilationAction->setEnabled(FALSE);
  4521. }
  4522. void MainForm::projectForceQuit()
  4523. {
  4524. if (!compiling) return;
  4525. stopCompilingFlag=TRUE;
  4526. if (process && process->state()!=QProcess::NotRunning) {
  4527. process->terminate();
  4528. QCoreApplication::processEvents(QEventLoop::ExcludeUserInput,100);
  4529. if (process && process->state()!=QProcess::NotRunning)
  4530. process->kill();
  4531. }
  4532. }
  4533. void MainForm::projectErrorsAndWarnings(bool on)
  4534. {
  4535. static bool lock=FALSE;
  4536. if (!lock) {
  4537. lock=TRUE;
  4538. if (!projectErrorsAndWarningsAction->isEnabled()) on=FALSE;
  4539. projectErrorsAndWarningsAction->setOn(on);
  4540. if (on)
  4541. errorListDock->show();
  4542. else
  4543. errorListDock->hide();
  4544. lock=FALSE;
  4545. }
  4546. }
  4547. void MainForm::projectProgramOutput()
  4548. {
  4549. ProgramOutput programOutputDialog;
  4550. programOutputDialog.textBrowser->setText(programOutput);
  4551. programOutputDialog.exec();
  4552. }
  4553. void MainForm::projectOptions()
  4554. {
  4555. ProjectOptions *projectoptions=new ProjectOptions(this);
  4556. projectoptions->exec();
  4557. if (projectoptions->result()==QDialog::Accepted) {
  4558. projectIsDirty=TRUE;
  4559. projectNeedsRelink=TRUE;
  4560. headersModified=TRUE; // force complete rebuild
  4561. }
  4562. delete(projectoptions);
  4563. bool runnable=!settings.archive&&!settings.flash_os&&preferences.linkTarget!=LT_NONE;
  4564. menuBar()->setItemVisible(5,runnable); //debugMenu
  4565. debugRunAction->setVisible(runnable);
  4566. debugPauseAction->setVisible(runnable);
  4567. }
  4568. bool MainForm::tiemuInstance(TiEmuDBus *&instance)
  4569. {
  4570. QDBusConnection connection=QDBusConnection::sessionBus();
  4571. if (!connection.isConnected()) {
  4572. KMessageBox::error(this,"Can\'t attach to D-Bus.");
  4573. instance=NULL;
  4574. return FALSE;
  4575. }
  4576. instance=new TiEmuDBus("org.ticalc.lpg.tiemu.TiEmuDBus",
  4577. "/org/ticalc/lpg/tiemu/TiEmuDBus",connection,this);
  4578. if (!instance->isValid()) {
  4579. delete instance;
  4580. instance=NULL;
  4581. }
  4582. return TRUE;
  4583. }
  4584. // Same values as TIGCC, except for CALCULATOR_INVALID.
  4585. enum CalculatorModels {CALCULATOR_TI89, CALCULATOR_TI92P, CALCULATOR_TI92,
  4586. CALCULATOR_V200, CALCULATOR_INVALID=-1};
  4587. QString MainForm::tilibsErrorMessage(int err)
  4588. {
  4589. if (!err) return "No error. (This is a bug, please report.)";
  4590. char *msg=0;
  4591. if ((err=ticables_error_get(err,&msg))
  4592. && (err=tifiles_error_get(err,&msg))
  4593. && (err=ticalcs_error_get(err,&msg)))
  4594. return "Invalid error code. (This is a bug, please report.)";
  4595. QString ret=msg;
  4596. g_free(msg);
  4597. return ret;
  4598. }
  4599. void MainForm::debugRun()
  4600. {
  4601. if (compiling) return;
  4602. // Can't link a project without saving it first.
  4603. if (projectFileName.isEmpty()) {
  4604. if (!fileSave() || projectFileName.isEmpty()) return;
  4605. }
  4606. startCompiling();
  4607. compileProject(FALSE);
  4608. if (!errorsCompilingFlag && !stopCompilingFlag && projectNeedsRelink)
  4609. linkProject();
  4610. bool success=(!errorsCompilingFlag && !stopCompilingFlag);
  4611. stopCompiling();
  4612. QString projectBaseName=projectFileName;
  4613. if (projectBaseName.endsWith(".tpr",FALSE))
  4614. projectBaseName.truncate(projectBaseName.length()-4);
  4615. if (success && (QFileInfo(projectBaseName+".89z").exists()
  4616. || QFileInfo(projectBaseName+".9xz").exists()
  4617. || QFileInfo(projectBaseName+".v2z").exists()
  4618. || QFileInfo(projectBaseName+".92p").exists())) {
  4619. QStringList files;
  4620. if (settings.fargo)
  4621. files.append(projectBaseName+".92p");
  4622. else {
  4623. files.append(projectBaseName+".89z");
  4624. if (settings.pack) files.append(projectBaseName+".89y");
  4625. if (settings.use_data_var) files.append(projectBaseName+"-data.89y");
  4626. }
  4627. if (files.isEmpty()) return;
  4628. // Detect model of linked calculator.
  4629. CalculatorModels model=CALCULATOR_INVALID;
  4630. TiEmuDBus *tiemuDBus=0;
  4631. CableHandle *cable=0;
  4632. CalcHandle *calc=0;
  4633. switch (preferences.linkTarget) {
  4634. case LT_TIEMU:
  4635. {
  4636. // Fire up TiEmu if it isn't running yet.
  4637. if (!tiemuInstance(tiemuDBus)) return;
  4638. if (!tiemuDBus) {
  4639. if (!KRun::runCommand("tiemu", this)) {
  4640. KMessageBox::error(this,"Can't run TiEmu.");
  4641. return;
  4642. }
  4643. do {
  4644. usleep(100000);
  4645. QCoreApplication::processEvents(QEventLoop::ExcludeUserInput,100);
  4646. if (!tiemuInstance(tiemuDBus)) return;
  4647. } while (!tiemuDBus);
  4648. }
  4649. // Wait for TiEmu to get ready.
  4650. bool ready=false;
  4651. do {
  4652. usleep(100000);
  4653. QCoreApplication::processEvents(QEventLoop::ExcludeUserInput,100);
  4654. QDBusReply<bool> reply=tiemuDBus->ready_for_transfers();
  4655. if (!reply.isValid()) {
  4656. KMessageBox::error(this,"D-Bus function call failed.");
  4657. delete tiemuDBus;
  4658. return;
  4659. }
  4660. ready=reply.value();
  4661. } while (!ready);
  4662. // Now obtain the model from TiEmu.
  4663. QDBusReply<int> reply=tiemuDBus->emulated_calc_type();
  4664. int tiemuCalcType;
  4665. if (!reply.isValid() || !(tiemuCalcType=reply.value())) {
  4666. KMessageBox::error(this,"D-Bus function call failed.");
  4667. delete tiemuDBus;
  4668. return;
  4669. }
  4670. switch (tiemuCalcType) {
  4671. case TIEMU_CALC_TI89:
  4672. case TIEMU_CALC_TI89t:
  4673. model=CALCULATOR_TI89;
  4674. break;
  4675. case TIEMU_CALC_TI92p:
  4676. model=CALCULATOR_TI92P;
  4677. break;
  4678. case TIEMU_CALC_V200:
  4679. model=CALCULATOR_V200;
  4680. break;
  4681. case TIEMU_CALC_TI92:
  4682. model=CALCULATOR_TI92;
  4683. break;
  4684. default:
  4685. KMessageBox::error(this,"Unsupported calculator model.");
  4686. return;
  4687. }
  4688. }
  4689. break;
  4690. case LT_REALCALC:
  4691. {
  4692. // Probe for the connected model.
  4693. CalcModel tilibsCalcModel=CALC_NONE;
  4694. int err;
  4695. if ((err=ticalcs_probe(preferences.linkCable,preferences.linkPort,
  4696. &tilibsCalcModel,TRUE))) {
  4697. KMessageBox::error(this,tilibsErrorMessage(err));
  4698. return;
  4699. }
  4700. switch (tilibsCalcModel) {
  4701. case CALC_TI89:
  4702. case CALC_TI89T:
  4703. case CALC_TI89T_USB:
  4704. model=CALCULATOR_TI89;
  4705. break;
  4706. case CALC_TI92P:
  4707. model=CALCULATOR_TI92P;
  4708. break;
  4709. case CALC_V200:
  4710. model=CALCULATOR_V200;
  4711. break;
  4712. case CALC_TI92:
  4713. model=CALCULATOR_TI92;
  4714. break;
  4715. default:
  4716. KMessageBox::error(this,"Unsupported calculator model.");
  4717. return;
  4718. }
  4719. // Allocate handle for the cable.
  4720. cable=ticables_handle_new(preferences.linkCable,preferences.linkPort);
  4721. if (!cable) {
  4722. KMessageBox::error(this,"Failed to allocate cable handle.");
  4723. return;
  4724. }
  4725. // Allocate handle for the calculator.
  4726. calc=ticalcs_handle_new(tilibsCalcModel);
  4727. if (!calc) {
  4728. KMessageBox::error(this,"Failed to allocate calculator handle.");
  4729. ticables_handle_del(cable);
  4730. return;
  4731. }
  4732. // Attach the calculator handle to the cable handle.
  4733. if ((err=ticalcs_cable_attach(calc,cable))) {
  4734. KMessageBox::error(this,tilibsErrorMessage(err));
  4735. ticalcs_handle_del(calc);
  4736. ticables_handle_del(cable);
  4737. return;
  4738. }
  4739. }
  4740. break;
  4741. default:
  4742. qWarning("Bug: debugRun called with no link target.");
  4743. return;
  4744. }
  4745. // Select the correct files for the model.
  4746. if (model!=CALCULATOR_TI92 && settings.fargo) {
  4747. KMessageBox::error(this,"Can't send Fargo program to a TI-89/89Ti/92+/V200.");
  4748. return;
  4749. }
  4750. if ((model==CALCULATOR_TI92 || model==CALCULATOR_INVALID) && !settings.fargo) {
  4751. KMessageBox::error(this,"Can't send AMS program to a TI-92.");
  4752. return;
  4753. }
  4754. for (QStringList::Iterator it=files.begin(); it!=files.end(); ++it) {
  4755. if (model==CALCULATOR_TI92P) (*it).replace(QRegExp("\\.89(?=.$)"),".9x");
  4756. else if (model==CALCULATOR_V200) (*it).replace(QRegExp("\\.89(?=.$)"),".v2");
  4757. if (!QFileInfo(*it).exists()) {
  4758. KMessageBox::error(this,"The program was not compiled for the linked calculator.");
  4759. return;
  4760. }
  4761. }
  4762. // Now send the files.
  4763. switch (preferences.linkTarget) {
  4764. case LT_TIEMU:
  4765. // Send the files.
  4766. if (settings.debug_info && !settings.pack
  4767. && QFileInfo(projectBaseName+".dbg").exists()) {
  4768. QString mainFile=files.first();
  4769. files.pop_front();
  4770. QDBusReply<bool> reply=tiemuDBus->debug_file(mainFile);
  4771. if (!reply.isValid() || !reply.value()) {
  4772. KMessageBox::error(this,"D-Bus function call failed.");
  4773. delete tiemuDBus;
  4774. return;
  4775. }
  4776. }
  4777. {
  4778. QDBusReply<bool> reply=tiemuDBus->send_files(files);
  4779. if (!reply.isValid() || !reply.value()) {
  4780. KMessageBox::error(this,"D-Bus function call failed.");
  4781. delete tiemuDBus;
  4782. return;
  4783. }
  4784. }
  4785. break;
  4786. case LT_REALCALC:
  4787. ticables_options_set_timeout(cable,DFLT_TIMEOUT<<2);
  4788. ticalcs_update_set(calc,&ticalcsUpdate);
  4789. for (QStringList::Iterator it=files.begin(); it!=files.end(); ++it) {
  4790. const char *file=*it;
  4791. int err;
  4792. // libticalcs2 does NO validation on the file, so better do it now.
  4793. if (!tifiles_file_is_single(file)
  4794. || !tifiles_calc_is_ti9x(tifiles_file_get_model(file))) {
  4795. KMessageBox::error(this,QString("File \'%1\' has an invalid format.").arg(file));
  4796. ticalcs_handle_del(calc);
  4797. ticables_handle_del(cable);
  4798. return;
  4799. }
  4800. // Send the file.
  4801. callbacksInit(this);
  4802. if ((err=ticalcs_calc_send_var2(calc,MODE_NORMAL,file))) {
  4803. bool cancelled=ticalcsUpdate.cancel;
  4804. callbacksCleanup();
  4805. if (!cancelled) KMessageBox::error(this,tilibsErrorMessage(err));
  4806. ticalcs_handle_del(calc);
  4807. ticables_handle_del(cable);
  4808. return;
  4809. }
  4810. callbacksCleanup();
  4811. }
  4812. break;
  4813. default:
  4814. qFatal("Bug: This code in debugRun should be unreachable!");
  4815. return;
  4816. }
  4817. // And finally run the program.
  4818. QString command=(QString("%1%2(%3)")
  4819. .arg(rootListItem->text(0).contains('\\')?"":"main\\")
  4820. .arg(rootListItem->text(0)).arg(settings.cmd_line));
  4821. switch (preferences.linkTarget) {
  4822. case LT_TIEMU:
  4823. {
  4824. // Execute the command.
  4825. QDBusReply<bool> reply=tiemuDBus->execute_command(command);
  4826. if (!reply.isValid() || !reply.value())
  4827. KMessageBox::error(this,"D-Bus function call failed.");
  4828. delete tiemuDBus;
  4829. }
  4830. break;
  4831. case LT_REALCALC:
  4832. {
  4833. int err;
  4834. // Convert the command to the calculator charset.
  4835. char *ti=ticonv_charset_utf16_to_ti(CALC_TI89,command.utf16());
  4836. // Send it character by character.
  4837. #define SEND_CHAR(c) \
  4838. if ((err=ticalcs_calc_send_key(calc,(c)))) { \
  4839. KMessageBox::error(this,tilibsErrorMessage(err)); \
  4840. g_free(ti); \
  4841. ticalcs_handle_del(calc); \
  4842. ticables_handle_del(cable); \
  4843. return; \
  4844. }
  4845. SEND_CHAR(264); // KEY_ESC
  4846. SEND_CHAR(264); // KEY_ESC
  4847. SEND_CHAR(model?8273:277); // KEY_HOME
  4848. SEND_CHAR(263); // KEY_CLEAR
  4849. SEND_CHAR(263); // KEY_CLEAR
  4850. for (unsigned char *p=reinterpret_cast<unsigned char *>(ti); *p; p++) {
  4851. SEND_CHAR(*p);
  4852. }
  4853. SEND_CHAR(13); // KEY_ENTER
  4854. #undef SEND_CHAR
  4855. g_free(ti);
  4856. }
  4857. ticalcs_handle_del(calc);
  4858. ticables_handle_del(cable);
  4859. break;
  4860. default:
  4861. qFatal("Bug: This code in debugRun should be unreachable!");
  4862. return;
  4863. }
  4864. }
  4865. }
  4866. void MainForm::debugPause()
  4867. {
  4868. // This is enabled only for LT_TIEMU. Run the TiEmu debugger.
  4869. TiEmuDBus *tiemuDBus;
  4870. if (!tiemuInstance(tiemuDBus) || !tiemuDBus) return;
  4871. if (!tiemuDBus->enter_debugger().isValid())
  4872. KMessageBox::error(this,"D-Bus function call failed.");
  4873. delete tiemuDBus;
  4874. }
  4875. void MainForm::debugReset()
  4876. {
  4877. // This is enabled only for LT_TIEMU. Reset TiEmu.
  4878. TiEmuDBus *tiemuDBus;
  4879. if (!tiemuInstance(tiemuDBus) || !tiemuDBus) return;
  4880. if (!tiemuDBus->reset_calc(FALSE).isValid())
  4881. KMessageBox::error(this,"D-Bus function call failed.");
  4882. delete tiemuDBus;
  4883. }
  4884. void MainForm::toolsConfigure()
  4885. {
  4886. ToolsDialog toolsDialog(this);
  4887. toolsDialog.exec();
  4888. if (toolsDialog.result()==QDialog::Accepted) {
  4889. KConfigGroup toolsConfig=pconfig->group("Tools");
  4890. unsigned toolCount=tools.count();
  4891. toolsConfig.writeEntry("Count",toolCount);
  4892. for (unsigned idx=0; idx<toolCount; idx++) {
  4893. pconfig->setGroup(QString("Tool %1").arg(idx));
  4894. Tool &tool=tools[idx];
  4895. toolsConfig.writeEntry("Title",tool.title);
  4896. toolsConfig.writeEntry("Command Line",tool.commandLine);
  4897. toolsConfig.writeEntry("Working Directory",tool.workingDirectory);
  4898. toolsConfig.writeEntry("Terminal",tool.runInTerminal);
  4899. }
  4900. pconfig->sync();
  4901. updateToolsMenu();
  4902. }
  4903. }
  4904. void MainForm::updateToolsMenu()
  4905. {
  4906. toolsMenu->clear();
  4907. toolsConfigureAction->addTo(toolsMenu);
  4908. unsigned toolCount=tools.count();
  4909. if (toolCount) toolsMenu->insertSeparator();
  4910. for (unsigned idx=0; idx<toolCount; idx++)
  4911. toolsMenu->insertItem(tools[idx].title,idx);
  4912. disconnect(toolsMenu,SIGNAL(highlighted(int)),0,0);
  4913. connect(toolsMenu,SIGNAL(highlighted(int)),
  4914. this,SLOT(toolsMenu_highlighted(int)));
  4915. disconnect(toolsMenu,SIGNAL(aboutToHide()),0,0);
  4916. connect(toolsMenu,SIGNAL(aboutToHide()),this,SLOT(toolsMenu_aboutToHide()));
  4917. }
  4918. void MainForm::toolsMenu_highlighted(int id)
  4919. {
  4920. if (id==toolsMenu->idAt(0))
  4921. statusBar()->message(toolsConfigureAction->statusTip());
  4922. else if (id!=toolsMenu->idAt(1))
  4923. statusBar()->message(tools[id].commandLine);
  4924. }
  4925. void MainForm::toolsMenu_activated(int id)
  4926. {
  4927. if (id!=toolsMenu->idAt(0) && id!=toolsMenu->idAt(1)) {
  4928. const Tool &tool=tools[id];
  4929. KProcess process(this);
  4930. KShell::Errors err;
  4931. QStringList args=KShell::splitArgs(tool.commandLine,
  4932. KShell::TildeExpand|KShell::AbortOnMeta,
  4933. &err);
  4934. if (err) {
  4935. KMessageBox::error(this,"Invalid command line.");
  4936. return;
  4937. }
  4938. if (tool.runInTerminal) {
  4939. KConfigGroup globalConfigGeneral(KGlobal::config(),"General");
  4940. QString terminal=globalConfigGeneral.readPathEntry("TerminalApplication",
  4941. "konsole");
  4942. if (terminal=="konsole")
  4943. terminal+=" -caption=%c";
  4944. QHash<QChar,QString> map;
  4945. map.insert('c',tool.title);
  4946. map.insert('i',"");
  4947. map.insert('m',"");
  4948. terminal=KMacroExpander::expandMacrosShellQuote(terminal,map);
  4949. if (terminal.isNull()) {
  4950. KMessageBox::error(this,"Invalid terminal specification.");
  4951. return;
  4952. }
  4953. QStringList termargs=KShell::splitArgs(terminal,
  4954. KShell::TildeExpand|KShell::AbortOnMeta,
  4955. &err);
  4956. if (err) {
  4957. KMessageBox::error(this,"Invalid terminal specification.");
  4958. return;
  4959. }
  4960. process << termargs << "-e" << "sh" << "-c"
  4961. << (tool.commandLine+" ; echo Press Return to close... ; read");
  4962. } else
  4963. process << args;
  4964. if (!tool.workingDirectory.isEmpty())
  4965. process.setWorkingDirectory(tool.workingDirectory);
  4966. if (!process.startDetached())
  4967. KMessageBox::error(this,QString("Can't run \'%1\'.").arg(tool.commandLine));
  4968. }
  4969. }
  4970. void MainForm::toolsMenu_aboutToHide()
  4971. {
  4972. statusBar()->clear();
  4973. }
  4974. void MainForm::helpDocumentation()
  4975. {
  4976. assistant->openAssistant();
  4977. }
  4978. void MainForm::helpContents()
  4979. {
  4980. force_qt_assistant_page(0);
  4981. assistant->openAssistant();
  4982. }
  4983. void MainForm::helpIndex()
  4984. {
  4985. force_qt_assistant_page(1);
  4986. assistant->openAssistant();
  4987. }
  4988. void MainForm::helpSearch()
  4989. {
  4990. force_qt_assistant_page(3);
  4991. assistant->openAssistant();
  4992. }
  4993. void MainForm::helpNews()
  4994. {
  4995. NewsDialog newsDialog(this);
  4996. newsDialog.loadNews();
  4997. newsDialog.exec();
  4998. }
  4999. void MainForm::helpAbout()
  5000. {
  5001. khelpmenu->aboutApplication();
  5002. }
  5003. void MainForm::updateSizes()
  5004. {
  5005. int leftSize=splitter->sizes().first();
  5006. int rightSize=splitter->sizes().last();
  5007. int totalSize=leftSize+rightSize;
  5008. int mySize=size().width();
  5009. leftStatusLabel->setMaximumWidth(leftSize*mySize/totalSize);
  5010. rightStatusLabel->setMaximumWidth(rightSize*mySize/totalSize-10>0?
  5011. rightSize*mySize/totalSize-10:0);
  5012. }
  5013. void MainForm::resizeEvent(QResizeEvent *event)
  5014. {
  5015. QMainWindow::resizeEvent(event);
  5016. if (event->size()==event->oldSize()) return;
  5017. updateSizes();
  5018. }
  5019. void MainForm::timerEvent(QTimerEvent *event)
  5020. {
  5021. static int lastSplitterPos=-1;
  5022. QMainWindow::timerEvent(event);
  5023. if (lastSplitterPos==splitter->sizes().first()) return;
  5024. lastSplitterPos=splitter->sizes().first();
  5025. updateSizes();
  5026. }
  5027. void MainForm::fileTreeClicked(Q3ListViewItem *item)
  5028. {
  5029. if (!item) return;
  5030. if (fileTree->selectedItem()!=item) {
  5031. fileTree->setSelected(item,TRUE);
  5032. fileTree->ensureItemVisible(item);
  5033. }
  5034. if (IS_FOLDER(currentListItem))
  5035. currentListItem->setPixmap(0,SYSICON("folder","folder1.png"));
  5036. if (IS_FILE(currentListItem)) {
  5037. CATEGORY_OF(category,currentListItem);
  5038. if (IS_EDITABLE_CATEGORY(category)) {
  5039. static_cast<ListViewFile *>(currentListItem)->kateView->hide();
  5040. widgetStack->removeWidget(static_cast<ListViewFile *>(currentListItem)->kateView);
  5041. widgetStack->raiseWidget(-1);
  5042. }
  5043. }
  5044. if (IS_FOLDER(item)) {
  5045. // Bluecurve's "folder-open" isn't actually more open than "folder".
  5046. item->setPixmap(0,SYSICON(KIconTheme::current()=="Bluecurve"?"folder-accept":"folder-open","folder2.png"));
  5047. fileNewFolderAction->setEnabled(TRUE);
  5048. filePrintAction->setEnabled(FALSE);
  5049. filePrintQuicklyAction->setEnabled(FALSE);
  5050. editUndoAction->setEnabled(FALSE);
  5051. editRedoAction->setEnabled(FALSE);
  5052. editClearAction->setEnabled(FALSE);
  5053. editCutAction->setEnabled(FALSE);
  5054. editCopyAction->setEnabled(FALSE);
  5055. editPasteAction->setEnabled(FALSE);
  5056. editSelectAllAction->setEnabled(FALSE);
  5057. editIncreaseIndentAction->setEnabled(FALSE);
  5058. editDecreaseIndentAction->setEnabled(FALSE);
  5059. findFunctionsAction->setEnabled(FALSE);
  5060. findOpenFileAtCursorAction->setEnabled(FALSE);
  5061. findFindSymbolDeclarationAction->setEnabled(FALSE);
  5062. shortcuts[0]->setEnabled(FALSE);
  5063. shortcuts[1]->setEnabled(FALSE);
  5064. shortcuts[2]->setEnabled(FALSE);
  5065. shortcuts[3]->setEnabled(FALSE);
  5066. shortcuts[4]->setEnabled(FALSE);
  5067. shortcuts[5]->setEnabled(FALSE);
  5068. shortcuts[6]->setEnabled(FALSE);
  5069. shortcuts[7]->setEnabled(FALSE);
  5070. shortcuts[8]->setEnabled(FALSE);
  5071. shortcuts[9]->setEnabled(FALSE);
  5072. shortcuts[10]->setEnabled(FALSE);
  5073. shortcuts[17]->setEnabled(FALSE);
  5074. } else if (IS_FILE(item)) {
  5075. fileNewFolderAction->setEnabled(TRUE);
  5076. CATEGORY_OF(category,item->parent());
  5077. if (IS_EDITABLE_CATEGORY(category)) {
  5078. KTextEditor::View *kateView=static_cast<ListViewFile *>(item)->kateView;
  5079. filePrintAction->setEnabled(TRUE);
  5080. filePrintQuicklyAction->setEnabled(TRUE);
  5081. widgetStack->addWidget(kateView);
  5082. kateView->show();
  5083. widgetStack->raiseWidget(kateView);
  5084. editUndoAction->setEnabled(kateView->action(KStandardAction::name(KStandardAction::Undo))->isEnabled());
  5085. editRedoAction->setEnabled(kateView->action(KStandardAction::name(KStandardAction::Redo))->isEnabled());
  5086. editClearAction->setEnabled(kateView->selection());
  5087. editCutAction->setEnabled(kateView->selection());
  5088. editCopyAction->setEnabled(kateView->selection());
  5089. editPasteAction->setEnabled(!clipboard->text().isNull());
  5090. editSelectAllAction->setEnabled(TRUE);
  5091. editIncreaseIndentAction->setEnabled(TRUE);
  5092. editDecreaseIndentAction->setEnabled(TRUE);
  5093. findFunctionsAction->setEnabled(category!=txtFilesListItem);
  5094. findOpenFileAtCursorAction->setEnabled(TRUE);
  5095. findFindSymbolDeclarationAction->setEnabled(TRUE);
  5096. shortcuts[0]->setEnabled(kateView->action(KStandardAction::name(KStandardAction::Undo))->isEnabled());
  5097. shortcuts[1]->setEnabled(kateView->action(KStandardAction::name(KStandardAction::Redo))->isEnabled());
  5098. shortcuts[2]->setEnabled(kateView->selection());
  5099. shortcuts[3]->setEnabled(kateView->selection());
  5100. shortcuts[4]->setEnabled(!clipboard->text().isNull());
  5101. shortcuts[5]->setEnabled(TRUE);
  5102. shortcuts[6]->setEnabled(TRUE);
  5103. shortcuts[7]->setEnabled(TRUE);
  5104. shortcuts[8]->setEnabled(TRUE);
  5105. shortcuts[9]->setEnabled(TRUE);
  5106. shortcuts[10]->setEnabled(TRUE);
  5107. shortcuts[17]->setEnabled(TRUE);
  5108. } else {
  5109. filePrintAction->setEnabled(FALSE);
  5110. filePrintQuicklyAction->setEnabled(FALSE);
  5111. editUndoAction->setEnabled(FALSE);
  5112. editRedoAction->setEnabled(FALSE);
  5113. editClearAction->setEnabled(FALSE);
  5114. editCutAction->setEnabled(FALSE);
  5115. editCopyAction->setEnabled(FALSE);
  5116. editPasteAction->setEnabled(FALSE);
  5117. editSelectAllAction->setEnabled(FALSE);
  5118. editIncreaseIndentAction->setEnabled(FALSE);
  5119. editDecreaseIndentAction->setEnabled(FALSE);
  5120. findFunctionsAction->setEnabled(FALSE);
  5121. findOpenFileAtCursorAction->setEnabled(FALSE);
  5122. findFindSymbolDeclarationAction->setEnabled(FALSE);
  5123. shortcuts[0]->setEnabled(FALSE);
  5124. shortcuts[1]->setEnabled(FALSE);
  5125. shortcuts[2]->setEnabled(FALSE);
  5126. shortcuts[3]->setEnabled(FALSE);
  5127. shortcuts[4]->setEnabled(FALSE);
  5128. shortcuts[5]->setEnabled(FALSE);
  5129. shortcuts[6]->setEnabled(FALSE);
  5130. shortcuts[7]->setEnabled(FALSE);
  5131. shortcuts[8]->setEnabled(FALSE);
  5132. shortcuts[9]->setEnabled(FALSE);
  5133. shortcuts[10]->setEnabled(FALSE);
  5134. shortcuts[17]->setEnabled(FALSE);
  5135. }
  5136. } else {
  5137. fileNewFolderAction->setEnabled(FALSE);
  5138. filePrintAction->setEnabled(FALSE);
  5139. filePrintQuicklyAction->setEnabled(FALSE);
  5140. editUndoAction->setEnabled(FALSE);
  5141. editRedoAction->setEnabled(FALSE);
  5142. editClearAction->setEnabled(FALSE);
  5143. editCutAction->setEnabled(FALSE);
  5144. editCopyAction->setEnabled(FALSE);
  5145. editPasteAction->setEnabled(FALSE);
  5146. editSelectAllAction->setEnabled(FALSE);
  5147. editIncreaseIndentAction->setEnabled(FALSE);
  5148. editDecreaseIndentAction->setEnabled(FALSE);
  5149. findFunctionsAction->setEnabled(FALSE);
  5150. findOpenFileAtCursorAction->setEnabled(FALSE);
  5151. findFindSymbolDeclarationAction->setEnabled(FALSE);
  5152. shortcuts[0]->setEnabled(FALSE);
  5153. shortcuts[1]->setEnabled(FALSE);
  5154. shortcuts[2]->setEnabled(FALSE);
  5155. shortcuts[3]->setEnabled(FALSE);
  5156. shortcuts[4]->setEnabled(FALSE);
  5157. shortcuts[5]->setEnabled(FALSE);
  5158. shortcuts[6]->setEnabled(FALSE);
  5159. shortcuts[7]->setEnabled(FALSE);
  5160. shortcuts[8]->setEnabled(FALSE);
  5161. shortcuts[9]->setEnabled(FALSE);
  5162. shortcuts[10]->setEnabled(FALSE);
  5163. shortcuts[17]->setEnabled(FALSE);
  5164. }
  5165. currentListItem=item;
  5166. updateLeftStatusLabel();
  5167. updateRightStatusLabel();
  5168. }
  5169. void MainForm::fileNewFolder()
  5170. {
  5171. if (compiling) return;
  5172. if (IS_FILE(currentListItem))
  5173. currentListItem=currentListItem->parent();
  5174. Q3ListViewItem *item=NULL, *next=currentListItem->firstChild();
  5175. for (; next; next=item->nextSibling())
  5176. {
  5177. item=next;
  5178. }
  5179. Q3ListViewItem *newFolder=item?new ListViewFolder(currentListItem,item)
  5180. :new ListViewFolder(currentListItem);
  5181. newFolder->setText(0,"NewFolder");
  5182. newFolder->setRenameEnabled(0,TRUE);
  5183. currentListItem->setOpen(TRUE);
  5184. fileTreeClicked(newFolder);
  5185. newFolder->startRename(0);
  5186. projectIsDirty=TRUE;
  5187. projectNeedsRelink=TRUE;
  5188. }
  5189. bool MainForm::removeItem(Q3ListViewItem *item)
  5190. {
  5191. if (IS_FOLDER(item) && !IS_CATEGORY(item)) {
  5192. Q3ListViewItem *child=item->firstChild();
  5193. while (child) {
  5194. Q3ListViewItem *nextChild=child->nextSibling();
  5195. if (!removeItem(child)) return FALSE;
  5196. child=nextChild;
  5197. }
  5198. delete item;
  5199. currentListItem=NULL;
  5200. fileTreeClicked(fileTree->currentItem());
  5201. projectIsDirty=TRUE;
  5202. projectNeedsRelink=TRUE;
  5203. return TRUE;
  5204. } else if (IS_FILE(item)) {
  5205. if (!fileSavePrompt(item)) {
  5206. delete item;
  5207. currentListItem=NULL;
  5208. fileTreeClicked(fileTree->currentItem());
  5209. projectIsDirty=TRUE;
  5210. projectNeedsRelink=TRUE;
  5211. return TRUE;
  5212. } else return FALSE;
  5213. } else return FALSE;
  5214. }
  5215. void MainForm::fileTreeContextMenuRequested(Q3ListViewItem *item,
  5216. const QPoint &pos,
  5217. int col __attribute__((unused)))
  5218. {
  5219. fileTreeClicked(item);
  5220. if (IS_FOLDER(item)) {
  5221. Q3PopupMenu menu;
  5222. menu.insertItem("New &Folder",0);
  5223. menu.insertItem("New F&ile",1);
  5224. if (compiling) {
  5225. menu.setItemEnabled(0,FALSE);
  5226. menu.setItemEnabled(1,FALSE);
  5227. }
  5228. CATEGORY_OF(category,item);
  5229. if (!IS_EDITABLE_CATEGORY(category))
  5230. menu.setItemEnabled(1,FALSE);
  5231. if (!IS_CATEGORY(item)) {
  5232. menu.insertSeparator();
  5233. menu.insertItem("&Remove",2);
  5234. if (compiling) menu.setItemEnabled(2,FALSE);
  5235. menu.insertItem("Re&name",3);
  5236. }
  5237. switch (menu.exec(pos)) {
  5238. case 0:
  5239. fileNewFolder();
  5240. break;
  5241. case 1:
  5242. newFile(item);
  5243. break;
  5244. case 2:
  5245. removeItem(item);
  5246. break;
  5247. case 3:
  5248. item->startRename(0);
  5249. }
  5250. } else if (IS_FILE(item)) {
  5251. Q3PopupMenu menu;
  5252. ListViewFile *theFile=static_cast<ListViewFile *>(item);
  5253. menu.insertItem("&Save",0);
  5254. CATEGORY_OF(category,item);
  5255. if (!IS_EDITABLE_CATEGORY(category))
  5256. menu.setItemEnabled(0,FALSE);
  5257. menu.insertItem("Save &As...",1);
  5258. menu.insertSeparator();
  5259. menu.insertItem("&Compile",2);
  5260. if (compiling || category==txtFilesListItem
  5261. || !IS_EDITABLE_CATEGORY(category))
  5262. menu.setItemEnabled(2,FALSE);
  5263. menu.insertSeparator();
  5264. menu.insertItem("&Remove",3);
  5265. menu.insertItem("&Delete",4);
  5266. if (compiling) {
  5267. menu.setItemEnabled(3,FALSE);
  5268. menu.setItemEnabled(4,FALSE);
  5269. }
  5270. if (theFile->isNew)
  5271. menu.setItemEnabled(4,FALSE);
  5272. menu.insertSeparator();
  5273. menu.insertItem("Re&name",5);
  5274. switch (menu.exec(pos)) {
  5275. case 0:
  5276. fileSave_save(item);
  5277. break;
  5278. case 1:
  5279. fileSave_saveAs(item);
  5280. break;
  5281. case 2:
  5282. if (compiling) return;
  5283. startCompiling();
  5284. compileFile(theFile,TRUE,TRUE);
  5285. stopCompiling();
  5286. break;
  5287. case 3:
  5288. removeItem(item);
  5289. break;
  5290. case 4:
  5291. if (KMessageBox::questionYesNo(this,
  5292. "Are you sure you want to delete this source file? "
  5293. "You cannot undo this operation.","Confirm Deletion")
  5294. ==KMessageBox::Yes) {
  5295. QString fileName=theFile->fileName;
  5296. KDirWatch::self()->removeFile(fileName);
  5297. if (QDir().remove(fileName)) {
  5298. delete item;
  5299. currentListItem=NULL;
  5300. fileTreeClicked(fileTree->currentItem());
  5301. projectIsDirty=TRUE;
  5302. projectNeedsRelink=TRUE;
  5303. } else {
  5304. KMessageBox::error(this,
  5305. QString("Error deleting file \'%1\'").arg(fileName));
  5306. if (IS_EDITABLE_CATEGORY(category) && !fileName.isEmpty() && fileName[0]=='/')
  5307. KDirWatch::self()->addFile(fileName);
  5308. }
  5309. }
  5310. break;
  5311. case 5:
  5312. item->startRename(0);
  5313. }
  5314. }
  5315. }
  5316. QStringList MainForm::extractAllFileNames(void)
  5317. {
  5318. Q3ListViewItem *item=rootListItem->firstChild(),*next;
  5319. QStringList allFiles;
  5320. while (item)
  5321. {
  5322. if (IS_FOLDER(item))
  5323. {
  5324. next=item->firstChild();
  5325. if (next)
  5326. {
  5327. item=next;
  5328. continue;
  5329. }
  5330. }
  5331. if (IS_FILE(item))
  5332. {
  5333. allFiles << (static_cast<ListViewFile *>(item)->fileName);
  5334. }
  5335. next=item->nextSibling();
  5336. while (!next)
  5337. {
  5338. next=item->parent();
  5339. if (next==rootListItem||!next)
  5340. {
  5341. return allFiles;
  5342. }
  5343. item=next;
  5344. next=item->nextSibling();
  5345. }
  5346. item=next;
  5347. }
  5348. return allFiles;
  5349. }
  5350. //you put in parent, and it gives you the rest, but you must have a place to put it all.
  5351. void MainForm::extractFileTreeInfo(Q3ListViewItem *parent,Q3ListViewItem **p_category,QString *p_folderPath)
  5352. {
  5353. Q3ListViewItem *item,*next;
  5354. QString tmp=QString::null;
  5355. int o;
  5356. CATEGORY_OF(category,parent);
  5357. *p_category=category;
  5358. item=category->firstChild();
  5359. while (item)
  5360. {
  5361. if (item==parent)
  5362. {
  5363. if (!tmp.isEmpty())
  5364. tmp+='/';
  5365. tmp+=item->text(0);
  5366. *p_folderPath=tmp;
  5367. }
  5368. if (IS_FOLDER(item))
  5369. {
  5370. next=item->firstChild();
  5371. if (next)
  5372. {
  5373. if (tmp.isEmpty())
  5374. tmp=item->text(0);
  5375. else
  5376. {
  5377. tmp+='/';
  5378. tmp+=item->text(0);
  5379. }
  5380. item=next;
  5381. continue;
  5382. }
  5383. }
  5384. mfnf_seeknext:
  5385. next=item->nextSibling();
  5386. if (!next)
  5387. {
  5388. next=item->parent();
  5389. if (next==category||!next)
  5390. break;
  5391. item=next;
  5392. o=tmp.findRev('/');
  5393. if (o>=0)
  5394. tmp.truncate(o);
  5395. else
  5396. tmp.truncate(0);
  5397. goto mfnf_seeknext;
  5398. }
  5399. item=next;
  5400. }
  5401. }
  5402. void MainForm::newFile(Q3ListViewItem *parent, QString text, const QPixmap &pixmap)
  5403. {
  5404. Q3ListViewItem *item=NULL, *next=parent->firstChild();
  5405. QString tmp,oldtmp,suffix,caption;
  5406. QStringList allFiles=extractAllFileNames();
  5407. Q3ListViewItem *category;
  5408. KUrl tmpK;
  5409. int tryNum;
  5410. for (; IS_FILE(next); next=item->nextSibling())
  5411. item=next;
  5412. extractFileTreeInfo(parent,&category,&tmp);
  5413. suffix="";
  5414. if (category==hFilesListItem)
  5415. suffix="h";
  5416. else if (category==cFilesListItem)
  5417. suffix="c";
  5418. else if (category==sFilesListItem)
  5419. suffix="s";
  5420. else if (category==asmFilesListItem)
  5421. suffix="asm";
  5422. else if (category==qllFilesListItem) {
  5423. if (qllFileCount) {
  5424. KMessageBox::error(this,"There may be only one Quill source file in each project.","Quill Error");
  5425. return;
  5426. }
  5427. suffix="qll";
  5428. } else if (category==oFilesListItem)
  5429. suffix="o";
  5430. else if (category==aFilesListItem)
  5431. suffix="a";
  5432. else if (category==txtFilesListItem)
  5433. suffix="txt";
  5434. suffix='.'+suffix;
  5435. if (!tmp.isEmpty())
  5436. tmp+='/';
  5437. tmp+="New File";
  5438. tmpK.setPath(projectFileName);
  5439. kurlNewFileName(tmpK,tmp);
  5440. tmp=tmpK.path();
  5441. if (projectFileName.isEmpty() && !tmp.isEmpty())
  5442. {
  5443. short o=0;
  5444. if (tmp[0]=='.')
  5445. o=1;
  5446. if (tmp[o]=='/')
  5447. tmp=tmp.mid(o+1);
  5448. }
  5449. caption="New File";
  5450. oldtmp=tmp+' ';
  5451. tmp+=suffix;
  5452. tryNum=1;
  5453. while (!checkFileName(tmp,allFiles))
  5454. {
  5455. tryNum++;
  5456. tmp=oldtmp+QString("%1").arg(tryNum)+suffix;
  5457. caption="New File "+QString("%1").arg(tryNum);
  5458. }
  5459. ListViewFile *newFile=item?new ListViewFile(parent,item)
  5460. :new ListViewFile(parent);
  5461. newFile->fileName=tmp;
  5462. if (IS_EDITABLE_CATEGORY(category) && !tmp.isEmpty() && tmp[0]=='/')
  5463. KDirWatch::self()->addFile(tmp);
  5464. newFile->setText(0,caption);
  5465. newFile->setPixmap(0,pixmap);
  5466. parent->setOpen(TRUE);
  5467. newFile->kateView=reinterpret_cast<KTextEditor::View *>(createView(QString::null,text,category));
  5468. fileTreeClicked(newFile);
  5469. projectIsDirty=TRUE;
  5470. projectNeedsRelink=TRUE;
  5471. newFile->startRename(0);
  5472. fileCount++;
  5473. COUNTER_FOR_CATEGORY(category)++;
  5474. updateLeftStatusLabel();
  5475. }
  5476. void MainForm::newFile( Q3ListViewItem *parent )
  5477. {
  5478. CATEGORY_OF(category,parent);
  5479. newFile(parent,category==txtFilesListItem?"":
  5480. ((category==hFilesListItem?"// Header File\n//":
  5481. category==cFilesListItem?"// C Source File\n//":
  5482. category==sFilesListItem?"| Assembly Source File\n|":
  5483. category==asmFilesListItem?"; Assembly Source File\n;":
  5484. category==qllFilesListItem?"// Quill Source File\n//":"???\n")
  5485. +QString(" Created ")
  5486. +QDateTime::currentDateTime ().toString(Qt::LocalDate)+"\n"+
  5487. QString(category==cFilesListItem?(cFileCount?
  5488. "\n#include <tigcclib.h>\n":
  5489. "\n// Delete or comment out the items you do not need.\n"
  5490. "#define COMMENT_STRING \"Place your comment here.\"\n"
  5491. "#define COMMENT_PROGRAM_NAME "
  5492. "\"Place your program name here.\"\n"
  5493. "#define COMMENT_VERSION_STRING "
  5494. "\"Place your version string here.\"\n"
  5495. "#define COMMENT_VERSION_NUMBER 0,0,0,0 "
  5496. "/* major, minor, revision, subrevision */\n"
  5497. "#define COMMENT_AUTHORS "
  5498. "\"Place your author name(s) here.\"\n"
  5499. "#define COMMENT_BW_ICON \\\n"
  5500. "\t{0b0000000000000000, \\\n"
  5501. "\t 0b0000000000000000, \\\n"
  5502. "\t 0b0000000000000000, \\\n"
  5503. "\t 0b0000000000000000, \\\n"
  5504. "\t 0b0000000000000000, \\\n"
  5505. "\t 0b0000000000000000, \\\n"
  5506. "\t 0b0000000000000000, \\\n"
  5507. "\t 0b0000000000000000, \\\n"
  5508. "\t 0b0000000000000000, \\\n"
  5509. "\t 0b0000000000000000, \\\n"
  5510. "\t 0b0000000000000000, \\\n"
  5511. "\t 0b0000000000000000, \\\n"
  5512. "\t 0b0000000000000000, \\\n"
  5513. "\t 0b0000000000000000, \\\n"
  5514. "\t 0b0000000000000000, \\\n"
  5515. "\t 0b0000000000000000}\n"
  5516. "#define COMMENT_GRAY_ICON \\\n"
  5517. "\t{0b0000000000000000, \\\n"
  5518. "\t 0b0000000000000000, \\\n"
  5519. "\t 0b0000000000000000, \\\n"
  5520. "\t 0b0000000000000000, \\\n"
  5521. "\t 0b0000000000000000, \\\n"
  5522. "\t 0b0000000000000000, \\\n"
  5523. "\t 0b0000000000000000, \\\n"
  5524. "\t 0b0000000000000000, \\\n"
  5525. "\t 0b0000000000000000, \\\n"
  5526. "\t 0b0000000000000000, \\\n"
  5527. "\t 0b0000000000000000, \\\n"
  5528. "\t 0b0000000000000000, \\\n"
  5529. "\t 0b0000000000000000, \\\n"
  5530. "\t 0b0000000000000000, \\\n"
  5531. "\t 0b0000000000000000, \\\n"
  5532. "\t 0b0000000000000000}, \\\n"
  5533. "\t{0b0000000000000000, \\\n"
  5534. "\t 0b0000000000000000, \\\n"
  5535. "\t 0b0000000000000000, \\\n"
  5536. "\t 0b0000000000000000, \\\n"
  5537. "\t 0b0000000000000000, \\\n"
  5538. "\t 0b0000000000000000, \\\n"
  5539. "\t 0b0000000000000000, \\\n"
  5540. "\t 0b0000000000000000, \\\n"
  5541. "\t 0b0000000000000000, \\\n"
  5542. "\t 0b0000000000000000, \\\n"
  5543. "\t 0b0000000000000000, \\\n"
  5544. "\t 0b0000000000000000, \\\n"
  5545. "\t 0b0000000000000000, \\\n"
  5546. "\t 0b0000000000000000, \\\n"
  5547. "\t 0b0000000000000000, \\\n"
  5548. "\t 0b0000000000000000}\n\n#include <tigcclib.h>\n\n"
  5549. "// Main Function\nvoid _main(void)\n{\n"
  5550. "\t// Place your code here.\n}\n"):"")),
  5551. category==cFilesListItem||category==qllFilesListItem
  5552. ?SYSICON("source-c","filec.png"):
  5553. category==hFilesListItem?SYSICON("source-h","fileh.png"):
  5554. category==sFilesListItem||category==asmFilesListItem
  5555. ?SYSICON("source-s","files.png"):
  5556. category==txtFilesListItem?SYSICON("txt","filet.png"):SYSICON("unknown","filex.png"));
  5557. }
  5558. Q3ListViewItem *MainForm::resolveParent(Q3ListViewItem *category)
  5559. {
  5560. Q3ListViewItem *ret=currentListItem;
  5561. if (!IS_FILE(ret)&&!IS_FOLDER(ret))
  5562. return category;
  5563. if (IS_FILE(ret))
  5564. ret=ret->parent();
  5565. Q3ListViewItem *actualCategory=ret;
  5566. while (IS_FOLDER(actualCategory->parent())) actualCategory=actualCategory->parent();
  5567. if (actualCategory!=category)
  5568. return category;
  5569. return ret;
  5570. }
  5571. void MainForm::fileNewCHeader()
  5572. {
  5573. if (compiling) return;
  5574. newFile(resolveParent(hFilesListItem),"// Header File\n// Created "+QDateTime::currentDateTime ().toString(Qt::LocalDate)+"\n",SYSICON("source-h","fileh.png"));
  5575. }
  5576. void MainForm::fileNewGNUAssemblyHeader()
  5577. {
  5578. if (compiling) return;
  5579. newFile(resolveParent(hFilesListItem),"| Header File\n| Created "+QDateTime::currentDateTime ().toString(Qt::LocalDate)+"\n",SYSICON("source-h","fileh.png"));
  5580. }
  5581. void MainForm::fileNewA68kAssemblyHeader()
  5582. {
  5583. if (compiling) return;
  5584. newFile(resolveParent(hFilesListItem),"; Header File\n; Created "+QDateTime::currentDateTime ().toString(Qt::LocalDate)+"\n",SYSICON("source-h","fileh.png"));
  5585. }
  5586. void MainForm::fileNewCSourceFile()
  5587. {
  5588. if (compiling) return;
  5589. newFile(resolveParent(cFilesListItem));
  5590. }
  5591. void MainForm::fileNewGNUAssemblySourceFile()
  5592. {
  5593. if (compiling) return;
  5594. newFile(resolveParent(sFilesListItem),"| Assembly Source File\n| Created "+QDateTime::currentDateTime ().toString(Qt::LocalDate)+"\n",SYSICON("source-s","files.png"));
  5595. }
  5596. void MainForm::fileNewA68kAssemblySourceFile()
  5597. {
  5598. if (compiling) return;
  5599. newFile(resolveParent(asmFilesListItem),"; Assembly Source File\n; Created "+QDateTime::currentDateTime ().toString(Qt::LocalDate)+"\n",SYSICON("source-s","files.png"));
  5600. }
  5601. void MainForm::fileNewQuillSourceFile()
  5602. {
  5603. if (compiling) return;
  5604. newFile(resolveParent(qllFilesListItem),"// Quill Source File\n// Created "+QDateTime::currentDateTime ().toString(Qt::LocalDate)+"\n",SYSICON("source-c","filec.png"));
  5605. }
  5606. void MainForm::fileNewTextFile()
  5607. {
  5608. if (compiling) return;
  5609. newFile(resolveParent(txtFilesListItem),"",SYSICON("txt","filet.png"));
  5610. }
  5611. void MainForm::updateLeftStatusLabel()
  5612. {
  5613. QString text=QString::number(fileCount)+QString(" File")
  5614. +QString(fileCount!=1?"s":"")+QString(" Total");
  5615. if (IS_FOLDER(currentListItem)||IS_FILE(currentListItem)) {
  5616. CATEGORY_OF(category,currentListItem);
  5617. text+=QString(", ")+QString::number(COUNTER_FOR_CATEGORY(category))
  5618. +QString(" in Category");
  5619. }
  5620. leftStatusLabel->setText(text);
  5621. }
  5622. void MainForm::statusBar_messageChanged(const QString & message)
  5623. {
  5624. if (message.isNull())
  5625. // Make sure no labels which should be hidden are shown.
  5626. updateRightStatusLabel();
  5627. }
  5628. void MainForm::updateRightStatusLabel()
  5629. {
  5630. int leftSize=splitter->sizes().first();
  5631. int rightSize=splitter->sizes().last();
  5632. int totalSize=leftSize+rightSize;
  5633. int mySize=size().width();
  5634. int rightStatusSize=rightSize*mySize/totalSize-10>0?
  5635. rightSize*mySize/totalSize-10:0;
  5636. if (currentListItem==rootListItem) {
  5637. rowStatusLabel->hide();
  5638. colStatusLabel->hide();
  5639. charsStatusLabel->hide();
  5640. rightStatusLabel->setMaximumWidth(rightStatusSize);
  5641. rightStatusLabel->setText(projectFileName);
  5642. } else if (IS_FOLDER(currentListItem)) {
  5643. rowStatusLabel->hide();
  5644. colStatusLabel->hide();
  5645. charsStatusLabel->hide();
  5646. rightStatusLabel->setMaximumWidth(rightStatusSize);
  5647. rightStatusLabel->setText("");
  5648. } else if (IS_FILE(currentListItem)) {
  5649. CATEGORY_OF(category,currentListItem);
  5650. if (IS_EDITABLE_CATEGORY(category) && CURRENT_VIEW) {
  5651. int line, col;
  5652. CURRENT_VIEW->cursorPosition().position(line,col);
  5653. rowStatusLabel->show();
  5654. rowStatusLabel->setMaximumWidth(30);
  5655. rowStatusLabel->setText(QString("%1").arg(line+1));
  5656. colStatusLabel->show();
  5657. colStatusLabel->setMaximumWidth(30);
  5658. colStatusLabel->setText(QString("%1").arg(col+1));
  5659. charsStatusLabel->show();
  5660. charsStatusLabel->setMaximumWidth(100);
  5661. charsStatusLabel->setText(QString("%1 Characters").arg(CURRENT_VIEW->document()->text().length()));
  5662. rightStatusLabel->setMaximumWidth(rightStatusSize-160>0?rightStatusSize-160:0);
  5663. } else {
  5664. rowStatusLabel->hide();
  5665. colStatusLabel->hide();
  5666. charsStatusLabel->hide();
  5667. rightStatusLabel->setMaximumWidth(rightStatusSize);
  5668. }
  5669. rightStatusLabel->setText(static_cast<ListViewFile *>(currentListItem)->fileName);
  5670. }
  5671. }
  5672. void MainForm::current_view_cursorPositionChanged(KTextEditor::View *view, const KTextEditor::Cursor &newPosition)
  5673. {
  5674. if (CURRENT_VIEW==view && !disableViewEvents) {
  5675. int line, col;
  5676. newPosition.position(line,col);
  5677. rowStatusLabel->setText(QString("%1").arg(line+1));
  5678. colStatusLabel->setText(QString("%1").arg(col+1));
  5679. }
  5680. }
  5681. void MainForm::current_view_textChanged(KTextEditor::Document *document)
  5682. {
  5683. if (disableViewEvents) return;
  5684. if (CURRENT_VIEW && CURRENT_VIEW->document()==document) {
  5685. charsStatusLabel->setText(QString("%1 Characters").arg(CURRENT_VIEW->document()->text().length()));
  5686. if (IS_FILE(currentListItem)) {
  5687. static_cast<ListViewFile *>(currentListItem)->modifiedSinceLastCompile=TRUE;
  5688. QString fileName=pathInProject(currentListItem);
  5689. if (projectCompletion.contains(fileName))
  5690. projectCompletion[fileName].dirty=TRUE;
  5691. }
  5692. if (preferences.deleteOverwrittenErrors && IS_FILE(currentListItem)
  5693. && CURRENT_VIEW==static_cast<ListViewFile *>(currentListItem)->kateView) {
  5694. ListViewFile *lvFile=static_cast<ListViewFile *>(currentListItem);
  5695. Q3ListViewItemIterator lvit(errorList->errorListView);
  5696. ErrorListItem *errorItem;
  5697. while ((errorItem=static_cast<ErrorListItem *>(lvit.current()))) {
  5698. ++lvit;
  5699. if (errorItem->lvFile==lvFile && errorItem->cursor) {
  5700. int line,col;
  5701. errorItem->cursor->position(line,col);
  5702. int curline,curcol;
  5703. lvFile->kateView->cursorPosition().position(curline,curcol);
  5704. if (curline==line && curcol==col)
  5705. delete errorItem;
  5706. }
  5707. }
  5708. }
  5709. }
  5710. if (kreplace) kreplace->invalidateSelection();
  5711. }
  5712. void MainForm::current_view_undoChanged()
  5713. {
  5714. if (CURRENT_VIEW && !disableViewEvents) {
  5715. editUndoAction->setEnabled(CURRENT_VIEW->action(KStandardAction::name(KStandardAction::Undo))->isEnabled());
  5716. editRedoAction->setEnabled(CURRENT_VIEW->action(KStandardAction::name(KStandardAction::Redo))->isEnabled());
  5717. shortcuts[0]->setEnabled(CURRENT_VIEW->action(KStandardAction::name(KStandardAction::Undo))->isEnabled());
  5718. shortcuts[1]->setEnabled(CURRENT_VIEW->action(KStandardAction::name(KStandardAction::Redo))->isEnabled());
  5719. }
  5720. }
  5721. void MainForm::current_view_selectionChanged(KTextEditor::View *view)
  5722. {
  5723. if (CURRENT_VIEW==view && !disableViewEvents) {
  5724. editClearAction->setEnabled(view->selection());
  5725. editCutAction->setEnabled(view->selection());
  5726. editCopyAction->setEnabled(view->selection());
  5727. shortcuts[2]->setEnabled(view->selection());
  5728. shortcuts[3]->setEnabled(view->selection());
  5729. }
  5730. }
  5731. void MainForm::current_view_textInserted(KTextEditor::View *view, const KTextEditor::Cursor &position, const QString &text)
  5732. {
  5733. int line,col;
  5734. position.position(line,col);
  5735. if (preferences.autoBlocks && text=="{"
  5736. && col==view->document()->lineLength(line)-1) {
  5737. KTextEditor::Document *doc=view->document();
  5738. CATEGORY_OF(category,currentListItem);
  5739. QString firstLine=doc->line(0);
  5740. // Only for C files.
  5741. if (category==cFilesListItem||category==qllFilesListItem
  5742. || (category==hFilesListItem && !firstLine.isEmpty()
  5743. && firstLine[0]!='|' && firstLine[0]!=';')) {
  5744. QString indent=doc->line(line);
  5745. // Only if the line was all whitespace, otherwise wait for Enter to be
  5746. // pressed (prevents annoying the user while typing a string or something).
  5747. if (indent.contains(QRegExp("^\\s*\\{$"))) {
  5748. indent=indent.remove('{');
  5749. QString cursorLine=indent+"\t";
  5750. doc->startEditing();
  5751. doc->insertLine(line+1,cursorLine);
  5752. doc->insertLine(line+2,indent+"}");
  5753. doc->endEditing();
  5754. view->setCursorPosition(KTextEditor::Cursor(line+1,cursorLine.length()));
  5755. }
  5756. }
  5757. }
  5758. if (IS_FILE(currentListItem)
  5759. && view==static_cast<ListViewFile *>(currentListItem)->kateView
  5760. && text=="(") {
  5761. QString firstLine=view->document()->line(0);
  5762. CATEGORY_OF(category,currentListItem);
  5763. // Completion only operates on C files.
  5764. if (category==cFilesListItem || category==qllFilesListItem
  5765. || (category==hFilesListItem && !firstLine.isEmpty()
  5766. && firstLine[0]!='|' && firstLine[0]!=';')) {
  5767. new ArgHintPopup(view,pathInProject(currentListItem),this);
  5768. }
  5769. }
  5770. }
  5771. void MainForm::current_view_newLineHook()
  5772. {
  5773. int line,col;
  5774. CURRENT_VIEW->cursorPosition().position(line,col);
  5775. KTextEditor::Document *doc=CURRENT_VIEW->document();
  5776. if (preferences.autoBlocks && line && doc->line(line-1).endsWith("{")) {
  5777. CATEGORY_OF(category,currentListItem);
  5778. QString firstLine=doc->line(0);
  5779. // Only for C files.
  5780. if (category==cFilesListItem || category==qllFilesListItem
  5781. || (category==hFilesListItem && !firstLine.isEmpty()
  5782. && firstLine[0]!='|' && firstLine[0]!=';')) {
  5783. QString indent=doc->line(line-1);
  5784. // Remove everything starting from the first non-whitespace character.
  5785. indent=indent.remove(QRegExp("(?!\\s).*$"));
  5786. QString cursorLine=indent+"\t";
  5787. doc->startEditing();
  5788. doc->removeText(KTextEditor::Range(line,0,line,col));
  5789. doc->insertLine(line,cursorLine);
  5790. doc->insertText(KTextEditor::Cursor(line+1,0),indent+"}");
  5791. doc->endEditing();
  5792. CURRENT_VIEW->setCursorPosition(KTextEditor::Cursor(line,cursorLine.length()));
  5793. }
  5794. }
  5795. }
  5796. void MainForm::clipboard_dataChanged()
  5797. {
  5798. if (CURRENT_VIEW) {
  5799. editPasteAction->setEnabled(!clipboard->text().isNull());
  5800. shortcuts[4]->setEnabled(!clipboard->text().isNull());
  5801. }
  5802. }
  5803. void MainForm::fileTreeItemRenamed( Q3ListViewItem *item, const QString &newName, int col)
  5804. {
  5805. if (col)
  5806. return;
  5807. if (item==rootListItem) {
  5808. // validate name, fix if invalid
  5809. QVector<QChar> validInVarname;
  5810. #define V(i) validInVarname.append(QChar(i))
  5811. #define VR(m,n) for(unsigned i=m;i<=n;i++)V(i)
  5812. VR(48,57); // 0..9
  5813. VR(65,90); // A..Z
  5814. V(95); // _
  5815. VR(97,122); // a..z
  5816. V(181); // mu
  5817. VR(192,214); // À..Ö
  5818. VR(216,246); // Ø..ö
  5819. VR(248,255); // ø..ÿ
  5820. VR(0x3b1,0x3b6);V(0x3b8);V(0x3bb);V(0x3be);V(0x3c1);V(0x3c3);V(0x3c4);
  5821. V(0x3c6);V(0x3c8);V(0x3c9); // small Greek letters
  5822. V(0x393);V(0x394);V(0x3a0);V(0x3a3);V(0x3a9); // capital Greek letters
  5823. #undef VR
  5824. #undef V
  5825. bool hasFolder=false;
  5826. int i;
  5827. QString prjName=newName;
  5828. for (i=prjName.length();i>=0;i--) {
  5829. if (prjName[i]=='\\') {
  5830. if (hasFolder)
  5831. prjName.remove(i,1);
  5832. else
  5833. hasFolder=true;
  5834. } else if (!validInVarname.contains(prjName[i]))
  5835. prjName.remove(i,1);
  5836. }
  5837. if (!prjName.isEmpty() && prjName[0]=='\\') prjName.remove(0,1);
  5838. if (prjName.isEmpty()) prjName="Project1";
  5839. if ((prjName[0]>='0'&&prjName[0]<='9')||prjName[0]=='_')
  5840. prjName.prepend('X');
  5841. i=prjName.find('\\');
  5842. if (i>=0) {
  5843. if (i>8) {
  5844. prjName.remove(8,i-8);
  5845. i=8;
  5846. }
  5847. if ((prjName[i+1]>='0'&&prjName[i+1]<='9')||prjName[i+1]=='_')
  5848. prjName.insert(i+1,'X');
  5849. prjName.truncate(i+9);
  5850. if (prjName.length()==i+1) prjName.append("Project1");
  5851. } else prjName.truncate(8);
  5852. item->setText(0,prjName);
  5853. projectIsDirty=true;
  5854. projectNeedsRelink=TRUE;
  5855. return;
  5856. }
  5857. if (!IS_FILE(item))
  5858. return;
  5859. ListViewFile *theFile=static_cast<ListViewFile *>(item);
  5860. QString suffix;
  5861. QString oldLabel;
  5862. QString &fileNameRef=theFile->fileName;
  5863. QString oldFileName=fileNameRef;
  5864. QString newFileName=fileNameRef;
  5865. int o,s;
  5866. o=oldFileName.findRev('.');
  5867. s=oldFileName.findRev('/');
  5868. if (o>=0&&(s<0||o>s)) {
  5869. suffix=oldFileName.mid(o+1);
  5870. newFileName.truncate(o);
  5871. } else {
  5872. suffix=QString::null;
  5873. }
  5874. if (s>=0) {
  5875. oldLabel=newFileName.mid(s+1);
  5876. newFileName.truncate(s+1);
  5877. } else {
  5878. oldLabel=newFileName;
  5879. newFileName.truncate(0);
  5880. }
  5881. if (!oldLabel.compare(newName))
  5882. return; //no changes are needed, and we don't want it to complain about the file conflicting with itself!
  5883. newFileName+=newName;
  5884. newFileName+='.';
  5885. newFileName+=suffix;
  5886. if (checkFileName(newFileName,extractAllFileNames())) {
  5887. CATEGORY_OF(category,item);
  5888. if (IS_EDITABLE_CATEGORY(category)) {
  5889. if (!oldFileName.isEmpty() && oldFileName[0]=='/')
  5890. KDirWatch::self()->removeFile(oldFileName);
  5891. if (newFileName.isEmpty() || newFileName[0]!='/')
  5892. newFileName.prepend(QFileInfo(projectFileName).absolutePath()+"/");
  5893. mkdir_multi(newFileName);
  5894. if (!theFile->kateView->document()->saveAs(newFileName)) {
  5895. KMessageBox::error(this,"Failed to rename the file.");
  5896. theFile->setText(0,oldLabel);
  5897. if (!oldFileName.isEmpty() && oldFileName[0]=='/')
  5898. KDirWatch::self()->addFile(oldFileName);
  5899. } else {
  5900. if (!theFile->isNew && !oldFileName.isEmpty() && oldFileName[0]=='/')
  5901. QDir().remove(oldFileName);
  5902. fileNameRef=newFileName;
  5903. KDirWatch::self()->addFile(newFileName);
  5904. removeTrailingSpacesFromView(theFile->kateView);
  5905. theFile->kateView->document()->setModified(FALSE);
  5906. theFile->isNew=FALSE;
  5907. projectIsDirty=TRUE;
  5908. projectNeedsRelink=TRUE;
  5909. }
  5910. } else {
  5911. mkdir_multi(newFileName);
  5912. if (!moveFile(oldFileName,newFileName)) {
  5913. KMessageBox::error(this,"Failed to rename the file.");
  5914. theFile->setText(0,oldLabel);
  5915. } else {
  5916. fileNameRef=newFileName;
  5917. projectIsDirty=TRUE;
  5918. projectNeedsRelink=TRUE;
  5919. }
  5920. }
  5921. } else {
  5922. KMessageBox::error(this,"The name you chose conflicts with that of another file.");
  5923. theFile->setText(0,oldLabel);
  5924. }
  5925. updateRightStatusLabel();
  5926. }
  5927. void MainForm::closeEvent(QCloseEvent *e)
  5928. {
  5929. if (compiling || savePrompt())
  5930. e->ignore();
  5931. else {
  5932. foreach (SourceFileWindow *sourceFile, sourceFiles) {
  5933. if (sourceFile->savePrompt()) {
  5934. e->ignore();
  5935. return;
  5936. }
  5937. }
  5938. clearProject();
  5939. e->accept();
  5940. }
  5941. }
  5942. void MainForm::KDirWatch_dirty(const QString &fileName)
  5943. {
  5944. Q3ListViewItem *item=rootListItem->firstChild(),*next;
  5945. QStringList allFiles;
  5946. while (item) {
  5947. if (IS_FOLDER(item)) {
  5948. next=item->firstChild();
  5949. if (next) {
  5950. item=next;
  5951. continue;
  5952. }
  5953. }
  5954. if (IS_FILE(item)) {
  5955. if (!fileName.compare(static_cast<ListViewFile *>(item)->fileName)) {
  5956. CATEGORY_OF(category,item);
  5957. if (!IS_EDITABLE_CATEGORY(category)) {
  5958. qWarning("KDirWatch_dirty called for non-editable file");
  5959. return;
  5960. }
  5961. if (KMessageBox::questionYesNo(this,
  5962. QString("The file \'%1\' has been changed by another program. "
  5963. "Do you want to reload it?").arg(fileName),"File Changed")
  5964. ==KMessageBox::Yes) {
  5965. static_cast<ListViewFile *>(item)->isNew=FALSE;
  5966. static_cast<ListViewFile *>(item)->kateView->document()->setModified(FALSE);
  5967. disableViewEvents=TRUE;
  5968. static_cast<ListViewFile *>(item)->kateView->document()->documentReload();
  5969. disableViewEvents=FALSE;
  5970. updateRightStatusLabel();
  5971. }
  5972. return;
  5973. }
  5974. }
  5975. next=item->nextSibling();
  5976. while (!next) {
  5977. next=item->parent();
  5978. if (next==rootListItem||!next) {
  5979. return;
  5980. }
  5981. item=next;
  5982. next=item->nextSibling();
  5983. }
  5984. item=next;
  5985. }
  5986. return;
  5987. }
  5988. QString MainForm::pathInProject(Q3ListViewItem *item)
  5989. {
  5990. QString path=QFileInfo(static_cast<ListViewFile *>(item)->fileName).fileName();
  5991. item=item->parent();
  5992. while (!IS_CATEGORY(item)) {
  5993. path.prepend('/');
  5994. path.prepend(item->text(0));
  5995. item=item->parent();
  5996. }
  5997. return path;
  5998. }
  5999. QString MainForm::textForHeader(const QString &fileName)
  6000. {
  6001. QString name=fileName;
  6002. int pos;
  6003. Q3ListViewItem *item=hFilesListItem;
  6004. while ((pos=name.find('/'))>=0) {
  6005. QString folder=name.left(pos);
  6006. name.remove(0,pos+1);
  6007. for (item=item->firstChild();item;item=item->nextSibling()) {
  6008. if (IS_FOLDER(item)) {
  6009. if (item->text(0)==folder) break;
  6010. }
  6011. }
  6012. if (!item) return QString::null;
  6013. }
  6014. for (item=item->firstChild();item;item=item->nextSibling()) {
  6015. if (IS_FILE(item)) {
  6016. ListViewFile *fileItem=static_cast<ListViewFile *>(item);
  6017. if (QFileInfo(fileItem->fileName).fileName()==name)
  6018. return fileItem->kateView->document()->text();
  6019. }
  6020. }
  6021. return QString::null;
  6022. }
  6023. void MainForm::languageChange()
  6024. {
  6025. retranslateUi(this);
  6026. }