mainform.cpp 238 KB

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