mainform.cpp 232 KB

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