mainform.cpp 232 KB

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