mainform.cpp 242 KB

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