FlatCAMApp.py 380 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588
  1. # ######################################################### ##
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ######################################################### ##
  8. import urllib.request, urllib.parse, urllib.error
  9. import getopt
  10. import random
  11. import simplejson as json
  12. import lzma
  13. import threading
  14. from stat import S_IREAD, S_IRGRP, S_IROTH
  15. import subprocess
  16. import tkinter as tk
  17. from PyQt5 import QtPrintSupport
  18. import urllib.request, urllib.parse, urllib.error
  19. from contextlib import contextmanager
  20. import gc
  21. from xml.dom.minidom import parseString as parse_xml_string
  22. # ##################################### ##
  23. # # Imports part of FlatCAM # ##
  24. # ##################################### ##
  25. from ObjectCollection import *
  26. from FlatCAMObj import *
  27. from flatcamGUI.PlotCanvas import *
  28. from flatcamGUI.FlatCAMGUI import *
  29. from FlatCAMCommon import LoudDict
  30. from FlatCAMPostProc import load_postprocessors
  31. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  32. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  33. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  34. from FlatCAMProcess import *
  35. from FlatCAMWorkerStack import WorkerStack
  36. from flatcamGUI.VisPyVisuals import Color
  37. from vispy.gloo.util import _screenshot
  38. from vispy.io import write_png
  39. from flatcamTools import *
  40. from multiprocessing import Pool
  41. import tclCommands
  42. import gettext
  43. import FlatCAMTranslation as fcTranslate
  44. import builtins
  45. fcTranslate.apply_language('strings')
  46. if '_' not in builtins.__dict__:
  47. _ = gettext.gettext
  48. # ##################################### ##
  49. # # App # ##
  50. # ##################################### ##
  51. class App(QtCore.QObject):
  52. """
  53. The main application class. The constructor starts the GUI.
  54. """
  55. # Get Cmd Line Options
  56. cmd_line_shellfile = ''
  57. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  58. try:
  59. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  60. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  61. except getopt.GetoptError:
  62. print(cmd_line_help)
  63. sys.exit(2)
  64. for opt, arg in cmd_line_options:
  65. if opt == '-h':
  66. print(cmd_line_help)
  67. sys.exit()
  68. elif opt == '--shellfile':
  69. cmd_line_shellfile = arg
  70. # Logging # ##
  71. log = logging.getLogger('base')
  72. log.setLevel(logging.DEBUG)
  73. # log.setLevel(logging.WARNING)
  74. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  75. handler = logging.StreamHandler()
  76. handler.setFormatter(formatter)
  77. log.addHandler(handler)
  78. # Version
  79. version = 8.918
  80. version_date = "2019/06/11"
  81. beta = True
  82. # current date now
  83. date = str(datetime.today()).rpartition('.')[0]
  84. date = ''.join(c for c in date if c not in ':-')
  85. date = date.replace(' ', '_')
  86. # URL for update checks and statistics
  87. version_url = "http://flatcam.org/version"
  88. # App URL
  89. app_url = "http://flatcam.org"
  90. # Manual URL
  91. manual_url = "http://flatcam.org/manual/index.html"
  92. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  93. # this variable will hold the project status
  94. # if True it will mean that the project was modified and not saved
  95. should_we_save = False
  96. # flag is True if saving action has been triggered
  97. save_in_progress = False
  98. # ############### ##
  99. # # Signals # ##
  100. # ############### ##
  101. # Inform the user
  102. # Handled by:
  103. # * App.info() --> Print on the status bar
  104. inform = QtCore.pyqtSignal(str)
  105. app_quit = QtCore.pyqtSignal()
  106. # General purpose background task
  107. worker_task = QtCore.pyqtSignal(dict)
  108. # File opened
  109. # Handled by:
  110. # * register_folder()
  111. # * register_recent()
  112. # Note: Setting the parameters to unicode does not seem
  113. # to have an effect. Then are received as Qstring
  114. # anyway.
  115. # File type and filename
  116. file_opened = QtCore.pyqtSignal(str, str)
  117. # File type and filename
  118. file_saved = QtCore.pyqtSignal(str, str)
  119. # Percentage of progress
  120. progress = QtCore.pyqtSignal(int)
  121. plots_updated = QtCore.pyqtSignal()
  122. # Emitted by new_object() and passes the new object as argument, plot flag.
  123. # on_object_created() adds the object to the collection, plots on appropriate flag
  124. # and emits new_object_available.
  125. object_created = QtCore.pyqtSignal(object, bool, bool)
  126. # Emitted when a object has been changed (like scaled, mirrored)
  127. object_changed = QtCore.pyqtSignal(object)
  128. # Emitted after object has been plotted.
  129. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  130. object_plotted = QtCore.pyqtSignal(object)
  131. # Emitted when a new object has been added or deleted from/to the collection
  132. object_status_changed = QtCore.pyqtSignal(object, str)
  133. message = QtCore.pyqtSignal(str, str, str)
  134. # Emmited when shell command is finished(one command only)
  135. shell_command_finished = QtCore.pyqtSignal(object)
  136. # Emitted when multiprocess pool has been recreated
  137. pool_recreated = QtCore.pyqtSignal(object)
  138. # Emitted when an unhandled exception happens
  139. # in the worker task.
  140. thread_exception = QtCore.pyqtSignal(object)
  141. def __init__(self, user_defaults=True, post_gui=None):
  142. """
  143. Starts the application.
  144. :return: app
  145. :rtype: App
  146. """
  147. App.log.info("FlatCAM Starting...")
  148. self.main_thread = QtWidgets.QApplication.instance().thread()
  149. # ################ ##
  150. # # ## OS-specific # ##
  151. # ################ ##
  152. # Folder for user settings.
  153. if sys.platform == 'win32':
  154. from win32com.shell import shell, shellcon
  155. if platform.architecture()[0] == '32bit':
  156. App.log.debug("Win32!")
  157. else:
  158. App.log.debug("Win64!")
  159. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\FlatCAM'
  160. self.os = 'windows'
  161. else: # Linux/Unix/MacOS
  162. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  163. self.os = 'unix'
  164. # ############################ ##
  165. # # ## Setup folders and files # ##
  166. # ############################ ##
  167. if not os.path.exists(self.data_path):
  168. os.makedirs(self.data_path)
  169. App.log.debug('Created data folder: ' + self.data_path)
  170. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  171. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  172. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  173. if not os.path.exists(self.postprocessorpaths):
  174. os.makedirs(self.postprocessorpaths)
  175. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  176. # create current_defaults.FlatConfig file if there is none
  177. try:
  178. f = open(self.data_path + '/current_defaults.FlatConfig')
  179. f.close()
  180. except IOError:
  181. App.log.debug('Creating empty current_defaults.FlatConfig')
  182. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  183. json.dump({}, f)
  184. f.close()
  185. # create factory_defaults.FlatConfig file if there is none
  186. try:
  187. f = open(self.data_path + '/factory_defaults.FlatConfig')
  188. f.close()
  189. except IOError:
  190. App.log.debug('Creating empty factory_defaults.FlatConfig')
  191. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  192. json.dump({}, f)
  193. f.close()
  194. try:
  195. f = open(self.data_path + '/recent.json')
  196. f.close()
  197. except IOError:
  198. App.log.debug('Creating empty recent.json')
  199. f = open(self.data_path + '/recent.json', 'w')
  200. json.dump([], f)
  201. f.close()
  202. # Application directory. CHDIR to it. Otherwise, trying to load
  203. # GUI icons will fail as their path is relative.
  204. # This will fail under cx_freeze ...
  205. self.app_home = os.path.dirname(os.path.realpath(__file__))
  206. App.log.debug("Application path is " + self.app_home)
  207. App.log.debug("Started in " + os.getcwd())
  208. # cx_freeze workaround
  209. if os.path.isfile(self.app_home):
  210. self.app_home = os.path.dirname(self.app_home)
  211. os.chdir(self.app_home)
  212. # Create multiprocessing pool
  213. self.pool = Pool()
  214. # variable to store mouse coordinates
  215. self.mouse = [0, 0]
  216. # ################# ##
  217. # # Initialize GUI # ##
  218. # ################# ##
  219. # FlatCAM colors used in plotting
  220. self.FC_light_green = '#BBF268BF'
  221. self.FC_dark_green = '#006E20BF'
  222. self.FC_light_blue = '#a5a5ffbf'
  223. self.FC_dark_blue = '#0000ffbf'
  224. QtCore.QObject.__init__(self)
  225. self.ui = FlatCAMGUI(self.version, self.beta, self)
  226. # self.connect(self.ui,
  227. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  228. # self.save_geometry) PyQt4
  229. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  230. self.ui.final_save.connect(self.final_save)
  231. # ########### ##
  232. # # ## Data ## ##
  233. # ########### ##
  234. self.recent = []
  235. self.clipboard = QtWidgets.QApplication.clipboard()
  236. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  237. self.project_filename = None
  238. self.toggle_units_ignore = False
  239. # self.defaults_form = PreferencesUI()
  240. # when adding entries here read the comments in the method found bellow named:
  241. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  242. self.defaults_form_fields = {
  243. # General App
  244. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  245. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  246. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  247. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  248. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  249. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  250. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  251. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  252. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  253. "global_project_autohide": self.ui.general_defaults_form.general_app_group.project_autohide_cb,
  254. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_group.toggle_tooltips_cb,
  255. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  256. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  257. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  258. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  259. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  260. # General GUI Preferences
  261. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  262. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  263. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  264. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  265. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  266. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  267. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  268. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  269. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  270. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  271. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  272. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  273. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  274. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  275. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  276. # General GUI Settings
  277. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  278. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  279. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  280. # Gerber General
  281. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  282. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  283. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  284. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  285. # Gerber Options
  286. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  287. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  288. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  289. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  290. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  291. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  292. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  293. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  294. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  295. # Gerber Advanced Options
  296. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  297. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  298. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  299. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  300. # Gerber Export
  301. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  302. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  303. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  304. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  305. # Gerber Editor
  306. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  307. # Excellon General
  308. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  309. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  310. "excellon_format_upper_in": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  311. "excellon_format_lower_in": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  312. "excellon_format_upper_mm": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  313. "excellon_format_lower_mm": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  314. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  315. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  316. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  317. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  318. # Excellon Options
  319. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  320. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  321. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  322. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  323. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_opt_group.spindledir_radio,
  324. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  325. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  326. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  327. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  328. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  329. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  330. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  331. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  332. # Excellon Advanced Options
  333. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  334. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  335. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  336. "excellon_endz": self.ui.excellon_defaults_form.excellon_adv_opt_group.eendz_entry,
  337. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  338. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  339. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  340. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  341. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  342. # Excellon Export
  343. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  344. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  345. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  346. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  347. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  348. # Geometry General
  349. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  350. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  351. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  352. # Geometry Options
  353. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  354. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  355. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  356. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  357. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  358. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_opt_group.spindledir_radio,
  359. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  360. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  361. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  362. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  363. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  364. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  365. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  366. # Geometry Advanced Options
  367. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  368. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  369. "geometry_endz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gendz_entry,
  370. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  371. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  372. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  373. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  374. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  375. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  376. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  377. # Geometry Editor
  378. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  379. # CNCJob General
  380. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  381. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  382. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  383. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontsize_sp,
  384. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry,
  385. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  386. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  387. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  388. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  389. # CNC Job Options
  390. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  391. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  392. # CNC Job Advanced Options
  393. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  394. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  395. # NCC Tool
  396. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  397. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  398. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  399. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  400. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  401. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  402. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  403. # CutOut Tool
  404. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  405. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  406. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  407. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  408. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  409. # Paint Area Tool
  410. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  411. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  412. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  413. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  414. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  415. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  416. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  417. # 2-sided Tool
  418. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  419. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  420. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  421. # Film Tool
  422. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  423. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  424. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  425. # Panelize Tool
  426. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  427. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  428. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  429. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  430. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  431. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  432. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  433. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  434. # Calculators Tool
  435. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  436. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  437. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  438. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  439. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  440. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  441. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  442. # Transformations Tool
  443. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  444. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  445. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  446. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  447. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  448. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  449. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  450. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  451. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  452. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  453. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  454. # SolderPaste Dispensing Tool
  455. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  456. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  457. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  458. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  459. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  460. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  461. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  462. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  463. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  464. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  465. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  466. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  467. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  468. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  469. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  470. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo
  471. }
  472. # ########################## ##
  473. # # ## LOAD POSTPROCESSORS ## ##
  474. # ########################## ##
  475. self.postprocessors = load_postprocessors(self)
  476. for name in list(self.postprocessors.keys()):
  477. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  478. if name.partition('_')[0] == 'Paste':
  479. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  480. continue
  481. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  482. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  483. if name == 'hpgl':
  484. continue
  485. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  486. # ########################## ##
  487. # # ## LOAD LANGUAGES ## ##
  488. # ########################## ##
  489. self.languages = fcTranslate.load_languages()
  490. for name in sorted(self.languages.values()):
  491. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  492. self.defaults = LoudDict()
  493. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  494. self.defaults.update({
  495. # Global APP Preferences
  496. "global_serial": 0,
  497. "global_stats": {},
  498. "units": "IN",
  499. "global_app_level": 'b',
  500. "global_language": 'English',
  501. "global_version_check": True,
  502. "global_send_stats": True,
  503. "global_pan_button": '2',
  504. "global_mselect_key": 'Control',
  505. "global_project_at_startup": False,
  506. "global_project_autohide": True,
  507. "global_toggle_tooltips": True,
  508. "global_worker_number": 2,
  509. "global_tolerance": 0.01,
  510. "global_open_style": True,
  511. "global_compression_level": 3,
  512. "global_save_compressed": True,
  513. # Global GUI Preferences
  514. "global_gridx": 0.0393701,
  515. "global_gridy": 0.0393701,
  516. "global_snap_max": 0.001968504,
  517. "global_workspace": False,
  518. "global_workspaceT": "A4P",
  519. "global_grid_context_menu": {
  520. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  521. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  522. },
  523. "global_plot_fill": '#BBF268BF',
  524. "global_plot_line": '#006E20BF',
  525. "global_sel_fill": '#a5a5ffbf',
  526. "global_sel_line": '#0000ffbf',
  527. "global_alt_sel_fill": '#BBF268BF',
  528. "global_alt_sel_line": '#006E20BF',
  529. "global_draw_color": '#FF0000',
  530. "global_sel_draw_color": '#0000FF',
  531. "global_proj_item_color": '#000000',
  532. "global_proj_item_dis_color": '#b7b7cb',
  533. "global_toolbar_view": 511,
  534. "global_background_timeout": 300000, # Default value is 5 minutes
  535. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  536. # (python trace only for unknown errors),
  537. # 1 = show trace(show trace always),
  538. # 2 = (For the future).
  539. # Persistence
  540. "global_last_folder": None,
  541. "global_last_save_folder": None,
  542. # Default window geometry
  543. "global_def_win_x": 100,
  544. "global_def_win_y": 100,
  545. "global_def_win_w": 1024,
  546. "global_def_win_h": 650,
  547. "global_def_notebook_width": 1,
  548. # Constants...
  549. "global_defaults_save_period_ms": 20000, # Time between default saves.
  550. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  551. "global_shell_at_startup": False, # Show the shell at startup.
  552. "global_recent_limit": 10, # Max. items in recent list.
  553. "fit_key": 'V',
  554. "zoom_out_key": '-',
  555. "zoom_in_key": '=',
  556. "grid_toggle_key": 'G',
  557. "zoom_ratio": 1.5,
  558. "global_point_clipboard_format": "(%.4f, %.4f)",
  559. "global_zdownrate": None,
  560. # General GUI Settings
  561. "global_hover": False,
  562. "global_selection_shape": True,
  563. "global_layout": "compact",
  564. # Gerber General
  565. "gerber_plot": True,
  566. "gerber_solid": True,
  567. "gerber_multicolored": False,
  568. "gerber_isotooldia": 0.016,
  569. "gerber_isopasses": 1,
  570. "gerber_isooverlap": 0.15,
  571. # Gerber Options
  572. "gerber_combine_passes": False,
  573. "gerber_milling_type": "cl",
  574. "gerber_noncoppermargin": 0.1,
  575. "gerber_noncopperrounded": False,
  576. "gerber_bboxmargin": 0.1,
  577. "gerber_bboxrounded": False,
  578. "gerber_circle_steps": 128,
  579. "gerber_use_buffer_for_union": True,
  580. # Gerber Advanced Options
  581. "gerber_aperture_display": False,
  582. "gerber_aperture_scale_factor": 1.0,
  583. "gerber_aperture_buffer_factor": 0.0,
  584. "gerber_follow": False,
  585. # Gerber Export
  586. "gerber_exp_units": 'IN',
  587. "gerber_exp_integer": 2,
  588. "gerber_exp_decimals": 4,
  589. "gerber_exp_zeros": 'L',
  590. # Gerber Editor
  591. "gerber_editor_sel_limit": 30,
  592. # Excellon General
  593. "excellon_plot": True,
  594. "excellon_solid": True,
  595. "excellon_format_upper_in": 2,
  596. "excellon_format_lower_in": 4,
  597. "excellon_format_upper_mm": 3,
  598. "excellon_format_lower_mm": 3,
  599. "excellon_zeros": "L",
  600. "excellon_units": "INCH",
  601. "excellon_optimization_type": 'B',
  602. "excellon_search_time": 3,
  603. # Excellon Options
  604. "excellon_drillz": -0.1,
  605. "excellon_travelz": 0.1,
  606. "excellon_feedrate": 3.0,
  607. "excellon_spindlespeed": None,
  608. "excellon_spindledir": 'CW',
  609. "excellon_dwell": False,
  610. "excellon_dwelltime": 1,
  611. "excellon_toolchange": False,
  612. "excellon_toolchangez": 0.5,
  613. "excellon_ppname_e": 'default',
  614. "excellon_tooldia": 0.016,
  615. "excellon_slot_tooldia": 0.016,
  616. "excellon_gcode_type": "drills",
  617. # Excellon Advanced Options
  618. "excellon_offset": 0.0,
  619. "excellon_toolchangexy": "0.0, 0.0",
  620. "excellon_startz": None,
  621. "excellon_endz": 0.5,
  622. "excellon_feedrate_rapid": 3.0,
  623. "excellon_z_pdepth": -0.02,
  624. "excellon_feedrate_probe": 3.0,
  625. "excellon_f_plunge": False,
  626. "excellon_f_retract": False,
  627. # Excellon Export
  628. "excellon_exp_units": 'INCH',
  629. "excellon_exp_format": 'ndec',
  630. "excellon_exp_integer": 2,
  631. "excellon_exp_decimals": 4,
  632. "excellon_exp_zeros": 'LZ',
  633. # Geometry General
  634. "geometry_plot": True,
  635. "geometry_circle_steps": 128,
  636. "geometry_cnctooldia": 0.016,
  637. # Geometry Options
  638. "geometry_cutz": -0.002,
  639. "geometry_multidepth": False,
  640. "geometry_depthperpass": 0.002,
  641. "geometry_travelz": 0.1,
  642. "geometry_toolchange": False,
  643. "geometry_toolchangez": 0.5,
  644. "geometry_feedrate": 3.0,
  645. "geometry_feedrate_z": 3.0,
  646. "geometry_spindlespeed": None,
  647. "geometry_spindledir": 'CW',
  648. "geometry_dwell": False,
  649. "geometry_dwelltime": 1,
  650. "geometry_ppname_g": 'default',
  651. # Geometry Advanced Options
  652. "geometry_toolchangexy": "0.0, 0.0",
  653. "geometry_startz": None,
  654. "geometry_endz": 0.5,
  655. "geometry_feedrate_rapid": 3.0,
  656. "geometry_extracut": False,
  657. "geometry_z_pdepth": -0.02,
  658. "geometry_f_plunge": False,
  659. "geometry_feedrate_probe": 3.0,
  660. "geometry_segx": 0.0,
  661. "geometry_segy": 0.0,
  662. # Geometry Editor
  663. "geometry_editor_sel_limit": 30,
  664. # CNC Job General
  665. "cncjob_plot": True,
  666. "cncjob_plot_kind": 'all',
  667. "cncjob_annotation": True,
  668. "cncjob_annotation_fontsize": 9,
  669. "cncjob_annotation_fontcolor": '#990000',
  670. "cncjob_tooldia": 0.0393701,
  671. "cncjob_coords_decimals": 4,
  672. "cncjob_fr_decimals": 2,
  673. "cncjob_steps_per_circle": 128,
  674. # CNC Job Options
  675. "cncjob_prepend": "",
  676. "cncjob_append": "",
  677. # CNC Job Advanced Options
  678. "cncjob_toolchange_macro": "",
  679. "cncjob_toolchange_macro_enable": False,
  680. "tools_ncctools": "0.0393701, 0.019685",
  681. "tools_nccoverlap": 0.015748,
  682. "tools_nccmargin": 0.00393701,
  683. "tools_nccmethod": "seed",
  684. "tools_nccconnect": True,
  685. "tools_ncccontour": True,
  686. "tools_nccrest": False,
  687. "tools_cutouttooldia": 0.00393701,
  688. "tools_cutoutmargin": 0.00393701,
  689. "tools_cutoutgapsize": 0.005905512,
  690. "tools_gaps_ff": "8",
  691. "tools_cutout_convexshape": False,
  692. "tools_painttooldia": 0.07,
  693. "tools_paintoverlap": 0.15,
  694. "tools_paintmargin": 0.0,
  695. "tools_paintmethod": "seed",
  696. "tools_selectmethod": "single",
  697. "tools_pathconnect": True,
  698. "tools_paintcontour": True,
  699. "tools_2sided_mirror_axis": "X",
  700. "tools_2sided_axis_loc": "point",
  701. "tools_2sided_drilldia": 0.0393701,
  702. "tools_film_type": 'neg',
  703. "tools_film_boundary": 0.0393701,
  704. "tools_film_scale": 0,
  705. "tools_panelize_spacing_columns": 0,
  706. "tools_panelize_spacing_rows": 0,
  707. "tools_panelize_columns": 1,
  708. "tools_panelize_rows": 1,
  709. "tools_panelize_constrain": False,
  710. "tools_panelize_constrainx": 0.0,
  711. "tools_panelize_constrainy": 0.0,
  712. "tools_panelize_panel_type": 'gerber',
  713. "tools_calc_vshape_tip_dia": 0.007874,
  714. "tools_calc_vshape_tip_angle": 30,
  715. "tools_calc_vshape_cut_z": 0.000787,
  716. "tools_calc_electro_length": 10.0,
  717. "tools_calc_electro_width": 10.0,
  718. "tools_calc_electro_cdensity":13.0,
  719. "tools_calc_electro_growth": 10.0,
  720. "tools_transform_rotate": 90,
  721. "tools_transform_skew_x": 0.0,
  722. "tools_transform_skew_y": 0.0,
  723. "tools_transform_scale_x": 1.0,
  724. "tools_transform_scale_y": 1.0,
  725. "tools_transform_scale_link": True,
  726. "tools_transform_scale_reference": True,
  727. "tools_transform_offset_x": 0.0,
  728. "tools_transform_offset_y": 0.0,
  729. "tools_transform_mirror_reference": False,
  730. "tools_transform_mirror_point": (0, 0),
  731. "tools_solderpaste_tools": "0.0393701, 0.011811",
  732. "tools_solderpaste_new": 0.011811,
  733. "tools_solderpaste_z_start": 0.00019685039,
  734. "tools_solderpaste_z_dispense": 0.00393701,
  735. "tools_solderpaste_z_stop": 0.00019685039,
  736. "tools_solderpaste_z_travel": 0.00393701,
  737. "tools_solderpaste_z_toolchange": 0.0393701,
  738. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  739. "tools_solderpaste_frxy": 3.0,
  740. "tools_solderpaste_frz": 3.0,
  741. "tools_solderpaste_frz_dispense": 0.0393701,
  742. "tools_solderpaste_speedfwd": 20,
  743. "tools_solderpaste_dwellfwd": 1,
  744. "tools_solderpaste_speedrev": 10,
  745. "tools_solderpaste_dwellrev": 1,
  746. "tools_solderpaste_pp": 'Paste_1'
  747. })
  748. # ############################ ##
  749. # # ## Load defaults from file # ##
  750. # ############################ ##
  751. if user_defaults:
  752. self.load_defaults(filename='current_defaults')
  753. # ######################### ##
  754. # #### APPLY APP LANGUAGE # ##
  755. # ######################### ##
  756. ret_val = fcTranslate.apply_language('strings')
  757. if ret_val == "no language":
  758. self.inform.emit(_("[ERROR] Could not find the Language files. The App strings are missing."))
  759. log.debug("Could not find the Language files. The App strings are missing.")
  760. else:
  761. # make the current language the current selection on the language combobox
  762. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  763. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  764. # ################################ ##
  765. # # ## CREATE UNIQUE SERIAL NUMBER # ##
  766. # ################################ ##
  767. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  768. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  769. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  770. self.save_defaults(silent=True)
  771. self.propagate_defaults(silent=True)
  772. self.restore_main_win_geom()
  773. def auto_save_defaults():
  774. try:
  775. self.save_defaults(silent=True)
  776. self.propagate_defaults(silent=True)
  777. finally:
  778. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  779. # the following lines activates automatic defaults save
  780. # if user_defaults:
  781. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  782. # self.options_form = PreferencesUI()
  783. self.options_form_fields = {
  784. "units": self.ui.general_options_form.general_app_group.units_radio,
  785. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  786. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  787. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  788. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  789. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  790. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  791. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  792. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  793. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  794. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  795. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  796. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  797. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  798. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  799. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  800. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  801. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  802. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  803. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  804. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  805. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  806. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  807. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  808. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  809. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  810. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  811. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  812. "excellon_spindledir": self.ui.excellon_options_form.excellon_opt_group.spindledir_radio,
  813. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  814. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  815. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  816. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  817. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  818. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  819. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  820. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  821. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  822. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  823. "excellon_endz": self.ui.excellon_options_form.excellon_adv_opt_group.eendz_entry,
  824. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  825. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  826. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  827. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  828. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  829. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  830. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  831. "geometry_spindledir": self.ui.geometry_options_form.geometry_opt_group.spindledir_radio,
  832. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  833. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  834. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  835. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  836. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  837. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  838. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  839. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  840. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  841. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  842. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  843. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  844. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  845. "geometry_endz": self.ui.geometry_options_form.geometry_adv_opt_group.gendz_entry,
  846. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  847. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  848. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  849. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  850. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  851. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  852. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  853. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  854. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  855. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  856. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  857. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  858. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  859. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  860. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  861. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  862. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  863. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  864. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  865. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  866. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  867. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  868. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  869. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  870. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  871. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  872. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  873. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  874. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  875. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  876. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  877. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  878. }
  879. for name in list(self.postprocessors.keys()):
  880. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  881. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  882. self.options = LoudDict()
  883. self.options.set_change_callback(self.on_options_dict_change)
  884. self.options.update({
  885. "units": "IN",
  886. "global_gridx": 1.0,
  887. "global_gridy": 1.0,
  888. "global_snap_max": 0.05,
  889. "global_background_timeout": 300000, # Default value is 5 minutes
  890. "global_verbose_error_level": 0, # Shell verbosity:
  891. # 0 = default(python trace only for unknown errors),
  892. # 1 = show trace(show trace allways), 2 = (For the future).
  893. "gerber_plot": True,
  894. "gerber_solid": True,
  895. "gerber_multicolored": False,
  896. "gerber_isotooldia": 0.016,
  897. "gerber_isopasses": 1,
  898. "gerber_isooverlap": 0.15,
  899. "gerber_combine_passes": True,
  900. "gerber_noncoppermargin": 0.0,
  901. "gerber_noncopperrounded": False,
  902. "gerber_bboxmargin": 0.0,
  903. "gerber_bboxrounded": False,
  904. "excellon_plot": True,
  905. "excellon_solid": False,
  906. "excellon_format_upper_in": 2,
  907. "excellon_format_lower_in": 4,
  908. "excellon_format_upper_mm": 3,
  909. "excellon_format_lower_mm": 3,
  910. "excellon_units": 'INCH',
  911. "excellon_optimization_type": 'B',
  912. "excellon_search_time": 3,
  913. "excellon_zeros": "L",
  914. "excellon_drillz": -0.1,
  915. "excellon_travelz": 0.1,
  916. "excellon_feedrate": 3.0,
  917. "excellon_feedrate_rapid": 3.0,
  918. "excellon_spindlespeed": None,
  919. "excellon_spindledir": 'CW',
  920. "excellon_dwell": True,
  921. "excellon_dwelltime": 1000,
  922. "excellon_toolchange": False,
  923. "excellon_toolchangez": 1.0,
  924. "excellon_toolchangexy": "0.0, 0.0",
  925. "excellon_tooldia": 0.016,
  926. "excellon_ppname_e": 'default',
  927. "excellon_f_plunge": False,
  928. "excellon_startz": None,
  929. "excellon_endz": 2.0,
  930. "geometry_plot": True,
  931. "geometry_segx": 0.0,
  932. "geometry_segy": 0.0,
  933. "geometry_cutz": -0.002,
  934. "geometry_travelz": 0.1,
  935. "geometry_feedrate": 3.0,
  936. "geometry_feedrate_z": 3.0,
  937. "geometry_feedrate_rapid": 3.0,
  938. "geometry_spindlespeed": None,
  939. "geometry_spindledir": 'CW',
  940. "geometry_dwell": True,
  941. "geometry_dwelltime": 1000,
  942. "geometry_cnctooldia": 0.016,
  943. "geometry_toolchange": False,
  944. "geometry_toolchangez": 2.0,
  945. "geometry_toolchangexy": "0.0, 0.0",
  946. "geometry_startz": None,
  947. "geometry_endz": 2.0,
  948. "geometry_ppname_g": "default",
  949. "geometry_f_plunge": False,
  950. "geometry_depthperpass": 0.002,
  951. "geometry_multidepth": False,
  952. "geometry_extracut": False,
  953. "cncjob_plot": True,
  954. "cncjob_tooldia": 0.016,
  955. "cncjob_prepend": "",
  956. "cncjob_append": "",
  957. "tools_ncctools": "1.0, 0.5",
  958. "tools_nccoverlap": 0.4,
  959. "tools_nccmargin": 1,
  960. "tools_cutouttooldia": 0.07,
  961. "tools_cutoutmargin": 0.1,
  962. "tools_cutoutgapsize": 0.15,
  963. "tools_gaps_ff": "8",
  964. "tools_painttooldia": 0.07,
  965. "tools_paintoverlap": 0.15,
  966. "tools_paintmargin": 0.0,
  967. "tools_paintmethod": "seed",
  968. "tools_selectmethod": "single",
  969. "tools_pathconnect": True,
  970. "tools_paintcontour": True,
  971. "tools_2sided_mirror_axis": "X",
  972. "tools_2sided_axis_loc": 'point',
  973. "tools_2sided_drilldia": 1,
  974. "tools_film_type": 'neg',
  975. "tools_film_boundary": 1,
  976. "tools_film_scale": 0,
  977. "tools_panelize_spacing_columns": 0,
  978. "tools_panelize_spacing_rows": 0,
  979. "tools_panelize_columns": 1,
  980. "tools_panelize_rows": 1,
  981. "tools_panelize_constrain": False,
  982. "tools_panelize_constrainx": 0.0,
  983. "tools_panelize_constrainy": 0.0
  984. })
  985. self.options.update(self.defaults) # Copy app defaults to project options
  986. self.gen_form = None
  987. self.ger_form = None
  988. self.exc_form = None
  989. self.geo_form = None
  990. self.cnc_form = None
  991. self.tools_form = None
  992. self.on_options_combo_change(0) # Will show the initial form
  993. # # ## Define OBJECT COLLECTION # ##
  994. self.collection = ObjectCollection(self)
  995. self.ui.project_tab_layout.addWidget(self.collection.view)
  996. # ###
  997. self.log.debug("Finished creating Object Collection.")
  998. # ### Initialize the color box's color in Preferences -> Global -> Color
  999. # Init Plot Colors
  1000. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1001. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1002. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1003. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1004. int(self.defaults['global_plot_fill'][7:9], 16))
  1005. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1006. int(self.defaults['global_plot_fill'][7:9], 16))
  1007. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1008. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1009. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1010. # Init Left-Right Selection colors
  1011. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1012. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1013. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1014. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1015. int(self.defaults['global_sel_fill'][7:9], 16))
  1016. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1017. int(self.defaults['global_sel_fill'][7:9], 16))
  1018. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1019. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1020. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1021. # Init Right-Left Selection colors
  1022. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1023. self.defaults['global_alt_sel_fill'])
  1024. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1025. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1026. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1027. int(self.defaults['global_sel_fill'][7:9], 16))
  1028. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1029. int(self.defaults['global_sel_fill'][7:9], 16))
  1030. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1031. self.defaults['global_alt_sel_line'])
  1032. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1033. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1034. # Init Draw color and Selection Draw Color
  1035. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1036. self.defaults['global_draw_color'])
  1037. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1038. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1039. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1040. self.defaults['global_sel_draw_color'])
  1041. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1042. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1043. # Init Project Items color
  1044. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1045. self.defaults['global_proj_item_color'])
  1046. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1047. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1048. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1049. self.defaults['global_proj_item_dis_color'])
  1050. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1051. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1052. # Init the Annotation CNC Job color
  1053. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(
  1054. self.defaults['cncjob_annotation_fontcolor'])
  1055. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  1056. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1057. # ### End of Data ## ##
  1058. # ### Plot Area ## ##
  1059. start_plot_time = time.time() # debug
  1060. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  1061. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  1062. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  1063. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  1064. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  1065. # Keys over plot enabled
  1066. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  1067. self.ui.splitter.setStretchFactor(1, 2)
  1068. # So it can receive key presses
  1069. self.plotcanvas.vispy_canvas.native.setFocus()
  1070. self.app_cursor = self.plotcanvas.new_cursor()
  1071. self.app_cursor.enabled = False
  1072. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1073. # depending on from where those tools are called different actions can be done
  1074. self.call_source = 'app'
  1075. end_plot_time = time.time()
  1076. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  1077. # # ## EDITOR section
  1078. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  1079. self.exc_editor = FlatCAMExcEditor(self)
  1080. self.grb_editor = FlatCAMGrbEditor(self)
  1081. # # ## Adjust tabs width ## ##
  1082. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1083. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1084. self.collection.view.setMinimumWidth(290)
  1085. self.log.debug("Finished adding FlatCAM Editor's.")
  1086. # # ## Worker ## ##
  1087. if self.defaults["global_worker_number"]:
  1088. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1089. else:
  1090. self.workers = WorkerStack(workers_number=2)
  1091. self.worker_task.connect(self.workers.add_task)
  1092. # # ## Signal handling # ##
  1093. # # ## Custom signals
  1094. self.inform.connect(self.info)
  1095. self.app_quit.connect(self.quit_application)
  1096. self.message.connect(self.message_dialog)
  1097. self.progress.connect(self.set_progress_bar)
  1098. self.object_created.connect(self.on_object_created)
  1099. self.object_changed.connect(self.on_object_changed)
  1100. self.object_plotted.connect(self.on_object_plotted)
  1101. self.plots_updated.connect(self.on_plots_updated)
  1102. self.file_opened.connect(self.register_recent)
  1103. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1104. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1105. # # ## Standard signals
  1106. # # ## Menu
  1107. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1108. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1109. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1110. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1111. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1112. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1113. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1114. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1115. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1116. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1117. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1118. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1119. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1120. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1121. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1122. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1123. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1124. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1125. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1126. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1127. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1128. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1129. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1130. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1131. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1132. self.ui.menufile_exit.triggered.connect(self.final_save)
  1133. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1134. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1135. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1136. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1137. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1138. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1139. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1140. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1141. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1142. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1143. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1144. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1145. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1146. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1147. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1148. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1149. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1150. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1151. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1152. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1153. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1154. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1155. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1156. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1157. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1158. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1159. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1160. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1161. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1162. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1163. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1164. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1165. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1166. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1167. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1168. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1169. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1170. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1171. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1172. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1173. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1174. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1175. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1176. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1177. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1178. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1179. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1180. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1181. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1182. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1183. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1184. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1185. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1186. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1187. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1188. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1189. # ToolBar signals
  1190. self.connect_toolbar_signals()
  1191. # Context Menu
  1192. self.ui.popmenu_disable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1193. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1194. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1195. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1196. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1197. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1198. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1199. self.ui.clearplot.triggered.connect(self.clear_plots)
  1200. self.ui.replot.triggered.connect(self.plot_all)
  1201. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1202. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1203. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1204. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1205. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1206. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1207. # Preferences Plot Area TAB
  1208. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1209. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1210. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1211. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1212. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1213. # ############################ ##
  1214. # # ## GUI PREFERENCES SIGNALS # ##
  1215. # ############################ ##
  1216. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1217. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1218. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1219. )
  1220. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1221. lambda: self.on_toggle_units(no_pref=False))
  1222. # ############################ ##
  1223. # # ## GUI PREFERENCES SIGNALS # ##
  1224. # ############################ ##
  1225. # Setting plot colors signals
  1226. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1227. self.on_pf_color_entry)
  1228. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1229. self.on_pf_color_button)
  1230. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1231. self.on_pf_color_spinner)
  1232. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1233. self.on_pf_color_slider)
  1234. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1235. self.on_pl_color_entry)
  1236. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1237. self.on_pl_color_button)
  1238. # Setting selection (left - right) colors signals
  1239. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1240. self.on_sf_color_entry)
  1241. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1242. self.on_sf_color_button)
  1243. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1244. self.on_sf_color_spinner)
  1245. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1246. self.on_sf_color_slider)
  1247. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1248. self.on_sl_color_entry)
  1249. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1250. self.on_sl_color_button)
  1251. # Setting selection (right - left) colors signals
  1252. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1253. self.on_alt_sf_color_entry)
  1254. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1255. self.on_alt_sf_color_button)
  1256. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1257. self.on_alt_sf_color_spinner)
  1258. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1259. self.on_alt_sf_color_slider)
  1260. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1261. self.on_alt_sl_color_entry)
  1262. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1263. self.on_alt_sl_color_button)
  1264. # Setting Editor Draw colors signals
  1265. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1266. self.on_draw_color_entry)
  1267. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1268. self.on_draw_color_button)
  1269. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1270. self.on_sel_draw_color_entry)
  1271. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1272. self.on_sel_draw_color_button)
  1273. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1274. self.on_proj_color_entry)
  1275. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1276. self.on_proj_color_button)
  1277. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1278. self.on_proj_color_dis_entry)
  1279. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1280. self.on_proj_color_dis_button)
  1281. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1282. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1283. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1284. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1285. self.on_cnc_custom_parameters)
  1286. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.editingFinished.connect(
  1287. self.on_annotation_fontcolor_entry)
  1288. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.clicked.connect(
  1289. self.on_annotation_fontcolor_button)
  1290. # Modify G-CODE Plot Area TAB
  1291. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1292. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1293. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1294. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1295. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1296. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1297. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1298. # Object list
  1299. self.collection.view.activated.connect(self.on_row_activated)
  1300. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1301. self.ui.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1302. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1303. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1304. self.on_excellon_defaults_button)
  1305. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1306. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1307. self.on_excellon_options_button)
  1308. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1309. self.tool_tab_locked = False
  1310. # decide if to show or hide the Notebook side of the screen at startup
  1311. if self.defaults["global_project_at_startup"] is True:
  1312. self.ui.splitter.setSizes([1, 1])
  1313. else:
  1314. self.ui.splitter.setSizes([0, 1])
  1315. # ################# ##
  1316. # # ## Other setups # ##
  1317. # ################# ##
  1318. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1319. self.setup_obj_classes()
  1320. self.setup_recent_items()
  1321. self.setup_component_editor()
  1322. # ########## ##
  1323. # # ## Shell # ##
  1324. # ########## ##
  1325. # # ##
  1326. # Auto-complete KEYWORDS
  1327. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1328. 'aligndrill', 'clear',
  1329. 'aligndrillgrid', 'cncjob', 'cutout', 'delete', 'drillcncjob',
  1330. 'export_gcode',
  1331. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1332. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1333. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1334. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1335. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1336. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1337. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1338. ]
  1339. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1340. 'holes', 'grid', 'minoffset', 'gridoffset', 'axisoffset', 'dia', 'dist',
  1341. 'gridoffsetx', 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate',
  1342. 'feedrate_rapid', 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g',
  1343. 'outname', 'margin', 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed',
  1344. 'toolchange', 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble',
  1345. 'filename', 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads',
  1346. 'x', 'y', 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value',
  1347. 'angle_x', 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1348. ]
  1349. self.tcl_keywords = [
  1350. "after", "append", "apply", "array", "auto_execok", "auto_import", "auto_load", "auto_mkindex",
  1351. "auto_qualify", "auto_reset", "bgerror", "binary", "break", "case", "catch", "cd", "chan", "clock", "close",
  1352. "concat", "continue", "coroutine", "dict", "encoding", "eof", "error", "eval", "exec", "exit", "expr",
  1353. "fblocked", "fconfigure", "fcopy", "file", "fileevent", "flush", "for", "foreach", "format", "gets", "glob",
  1354. "global", "history", "if", "incr", "info", "interp", "join", "lappend", "lassign", "lindex", "linsert",
  1355. "list", "llength", "load", "lrange", "lrepeat", "lreplace", "lreverse", "lsearch", "lset", "lsort",
  1356. "mathfunc", "mathop", "memory", "my", "namespace", "next", "nextto", "open", "package", "parray", "pid",
  1357. "pkg_mkIndex", "platform", "proc", "puts", "pwd", "read", "refchan", "regexp", "regsub", "rename", "return",
  1358. "scan", "seek", "self", "set", "socket", "source", "split", "string", "subst", "switch", "tailcall",
  1359. "tcl_endOfWord", "tcl_findLibrary", "tcl_startOfNextWord", "tcl_startOfPreviousWord", "tcl_wordBreakAfter",
  1360. "tcl_wordBreakBefore", "tell", "throw", "time", "tm", "trace", "transchan", "try", "unknown", "unload",
  1361. "unset", "update", "uplevel", "upvar", "variable", "vwait", "while", "yield", "yieldto", "zlib",
  1362. "attemptckalloc", "attemptckrealloc", "ckalloc", "ckfree", "ckrealloc", "Tcl_Access", "Tcl_AddErrorInfo",
  1363. "Tcl_AddObjErrorInfo", "Tcl_AlertNotifier", "Tcl_Alloc", "Tcl_AllocStatBuf", "Tcl_AllowExceptions",
  1364. "Tcl_AppendAllObjTypes", "Tcl_AppendElement", "Tcl_AppendExportList", "Tcl_AppendFormatToObj",
  1365. "Tcl_AppendLimitedToObj", "Tcl_AppendObjToErrorInfo", "Tcl_AppendObjToObj", "Tcl_AppendPrintfToObj",
  1366. "Tcl_AppendResult", "Tcl_AppendResultVA", "Tcl_AppendStringsToObj", "Tcl_AppendStringsToObjVA",
  1367. "Tcl_AppendToObj", "Tcl_AppendUnicodeToObj", "Tcl_AppInit", "Tcl_AsyncCreate", "Tcl_AsyncDelete",
  1368. "Tcl_AsyncInvoke", "Tcl_AsyncMark", "Tcl_AsyncReady", "Tcl_AttemptAlloc", "Tcl_AttemptRealloc",
  1369. "Tcl_AttemptSetObjLength", "Tcl_BackgroundError", "Tcl_BackgroundException", "Tcl_Backslash",
  1370. "Tcl_BadChannelOption", "Tcl_CallWhenDeleted", "Tcl_Canceled", "Tcl_CancelEval", "Tcl_CancelIdleCall",
  1371. "Tcl_ChannelBlockModeProc", "Tcl_ChannelBuffered", "Tcl_ChannelClose2Proc", "Tcl_ChannelCloseProc",
  1372. "Tcl_ChannelFlushProc", "Tcl_ChannelGetHandleProc", "Tcl_ChannelGetOptionProc", "Tcl_ChannelHandlerProc",
  1373. "Tcl_ChannelInputProc", "Tcl_ChannelName", "Tcl_ChannelOutputProc", "Tcl_ChannelSeekProc",
  1374. "Tcl_ChannelSetOptionProc", "Tcl_ChannelThreadActionProc", "Tcl_ChannelTruncateProc", "Tcl_ChannelVersion",
  1375. "Tcl_ChannelWatchProc", "Tcl_ChannelWideSeekProc", "Tcl_Chdir", "Tcl_ClassGetMetadata",
  1376. "Tcl_ClassSetConstructor", "Tcl_ClassSetDestructor", "Tcl_ClassSetMetadata", "Tcl_ClearChannelHandlers",
  1377. "Tcl_Close", "Tcl_CommandComplete", "Tcl_CommandTraceInfo", "Tcl_Concat", "Tcl_ConcatObj",
  1378. "Tcl_ConditionFinalize", "Tcl_ConditionNotify", "Tcl_ConditionWait", "Tcl_ConvertCountedElement",
  1379. "Tcl_ConvertElement", "Tcl_ConvertToType", "Tcl_CopyObjectInstance", "Tcl_CreateAlias",
  1380. "Tcl_CreateAliasObj", "Tcl_CreateChannel", "Tcl_CreateChannelHandler", "Tcl_CreateCloseHandler",
  1381. "Tcl_CreateCommand", "Tcl_CreateEncoding", "Tcl_CreateEnsemble", "Tcl_CreateEventSource",
  1382. "Tcl_CreateExitHandler", "Tcl_CreateFileHandler", "Tcl_CreateHashEntry", "Tcl_CreateInterp",
  1383. "Tcl_CreateMathFunc", "Tcl_CreateNamespace", "Tcl_CreateObjCommand", "Tcl_CreateObjTrace",
  1384. "Tcl_CreateSlave", "Tcl_CreateThread", "Tcl_CreateThreadExitHandler", "Tcl_CreateTimerHandler",
  1385. "Tcl_CreateTrace", "Tcl_CutChannel", "Tcl_DecrRefCount", "Tcl_DeleteAssocData", "Tcl_DeleteChannelHandler",
  1386. "Tcl_DeleteCloseHandler", "Tcl_DeleteCommand", "Tcl_DeleteCommandFromToken", "Tcl_DeleteEvents",
  1387. "Tcl_DeleteEventSource", "Tcl_DeleteExitHandler", "Tcl_DeleteFileHandler", "Tcl_DeleteHashEntry",
  1388. "Tcl_DeleteHashTable", "Tcl_DeleteInterp", "Tcl_DeleteNamespace", "Tcl_DeleteThreadExitHandler",
  1389. "Tcl_DeleteTimerHandler", "Tcl_DeleteTrace", "Tcl_DetachChannel", "Tcl_DetachPids", "Tcl_DictObjDone",
  1390. "Tcl_DictObjFirst", "Tcl_DictObjGet", "Tcl_DictObjNext", "Tcl_DictObjPut", "Tcl_DictObjPutKeyList",
  1391. "Tcl_DictObjRemove", "Tcl_DictObjRemoveKeyList", "Tcl_DictObjSize", "Tcl_DiscardInterpState",
  1392. "Tcl_DiscardResult", "Tcl_DontCallWhenDeleted", "Tcl_DoOneEvent", "Tcl_DoWhenIdle", "Tcl_DStringAppend",
  1393. "Tcl_DStringAppendElement", "Tcl_DStringEndSublist", "Tcl_DStringFree", "Tcl_DStringGetResult",
  1394. "Tcl_DStringInit", "Tcl_DStringLength", "Tcl_DStringResult", "Tcl_DStringSetLength",
  1395. "Tcl_DStringStartSublist", "Tcl_DStringTrunc", "Tcl_DStringValue", "Tcl_DumpActiveMemory",
  1396. "Tcl_DuplicateObj", "Tcl_Eof", "Tcl_ErrnoId", "Tcl_ErrnoMsg", "Tcl_Eval", "Tcl_EvalEx", "Tcl_EvalFile",
  1397. "Tcl_EvalObjEx", "Tcl_EvalObjv", "Tcl_EvalTokens", "Tcl_EvalTokensStandard", "Tcl_EventuallyFree",
  1398. "Tcl_Exit", "Tcl_ExitThread", "Tcl_Export", "Tcl_ExposeCommand", "Tcl_ExprBoolean", "Tcl_ExprBooleanObj",
  1399. "Tcl_ExprDouble", "Tcl_ExprDoubleObj", "Tcl_ExprLong", "Tcl_ExprLongObj", "Tcl_ExprObj", "Tcl_ExprString",
  1400. "Tcl_ExternalToUtf", "Tcl_ExternalToUtfDString", "Tcl_Finalize", "Tcl_FinalizeNotifier",
  1401. "Tcl_FinalizeThread", "Tcl_FindCommand", "Tcl_FindEnsemble", "Tcl_FindExecutable", "Tcl_FindHashEntry",
  1402. "Tcl_FindNamespace", "Tcl_FirstHashEntry", "Tcl_Flush", "Tcl_ForgetImport", "Tcl_Format",
  1403. "Tcl_Free· Tcl_FreeEncoding", "Tcl_FreeParse", "Tcl_FreeResult", "Tcl_FSAccess", "Tcl_FSChdir",
  1404. "Tcl_FSConvertToPathType", "Tcl_FSCopyDirectory", "Tcl_FSCopyFile", "Tcl_FSCreateDirectory", "Tcl_FSData",
  1405. "Tcl_FSDeleteFile", "Tcl_FSEqualPaths", "Tcl_FSEvalFile", "Tcl_FSEvalFileEx", "Tcl_FSFileAttrsGet",
  1406. "Tcl_FSFileAttrsSet", "Tcl_FSFileAttrStrings", "Tcl_FSFileSystemInfo", "Tcl_FSGetCwd",
  1407. "Tcl_FSGetFileSystemForPath", "Tcl_FSGetInternalRep", "Tcl_FSGetNativePath", "Tcl_FSGetNormalizedPath",
  1408. "Tcl_FSGetPathType", "Tcl_FSGetTranslatedPath", "Tcl_FSGetTranslatedStringPath", "Tcl_FSJoinPath",
  1409. "Tcl_FSJoinToPath", "Tcl_FSLink· Tcl_FSListVolumes", "Tcl_FSLoadFile", "Tcl_FSLstat",
  1410. "Tcl_FSMatchInDirectory", "Tcl_FSMountsChanged", "Tcl_FSNewNativePath", "Tcl_FSOpenFileChannel",
  1411. "Tcl_FSPathSeparator", "Tcl_FSRegister", "Tcl_FSRemoveDirectory", "Tcl_FSRenameFile", "Tcl_FSSplitPath",
  1412. "Tcl_FSStat", "Tcl_FSUnloadFile", "Tcl_FSUnregister", "Tcl_FSUtime", "Tcl_GetAccessTimeFromStat",
  1413. "Tcl_GetAlias", "Tcl_GetAliasObj", "Tcl_GetAssocData", "Tcl_GetBignumFromObj", "Tcl_GetBlocksFromStat",
  1414. "Tcl_GetBlockSizeFromStat", "Tcl_GetBoolean", "Tcl_GetBooleanFromObj", "Tcl_GetByteArrayFromObj",
  1415. "Tcl_GetChangeTimeFromStat", "Tcl_GetChannel", "Tcl_GetChannelBufferSize", "Tcl_GetChannelError",
  1416. "Tcl_GetChannelErrorInterp", "Tcl_GetChannelHandle", "Tcl_GetChannelInstanceData", "Tcl_GetChannelMode",
  1417. "Tcl_GetChannelName", "Tcl_GetChannelNames", "Tcl_GetChannelNamesEx", "Tcl_GetChannelOption",
  1418. "Tcl_GetChannelThread", "Tcl_GetChannelType", "Tcl_GetCharLength", "Tcl_GetClassAsObject",
  1419. "Tcl_GetCommandFromObj", "Tcl_GetCommandFullName", "Tcl_GetCommandInfo", "Tcl_GetCommandInfoFromToken",
  1420. "Tcl_GetCommandName", "Tcl_GetCurrentNamespace", "Tcl_GetCurrentThread", "Tcl_GetCwd",
  1421. "Tcl_GetDefaultEncodingDir", "Tcl_GetDeviceTypeFromStat", "Tcl_GetDouble", "Tcl_GetDoubleFromObj",
  1422. "Tcl_GetEncoding", "Tcl_GetEncodingFromObj", "Tcl_GetEncodingName", "Tcl_GetEncodingNameFromEnvironment",
  1423. "Tcl_GetEncodingNames", "Tcl_GetEncodingSearchPath", "Tcl_GetEnsembleFlags", "Tcl_GetEnsembleMappingDict",
  1424. "Tcl_GetEnsembleNamespace", "Tcl_GetEnsembleParameterList", "Tcl_GetEnsembleSubcommandList",
  1425. "Tcl_GetEnsembleUnknownHandler", "Tcl_GetErrno", "Tcl_GetErrorLine", "Tcl_GetFSDeviceFromStat",
  1426. "Tcl_GetFSInodeFromStat", "Tcl_GetGlobalNamespace", "Tcl_GetGroupIdFromStat", "Tcl_GetHashKey",
  1427. "Tcl_GetHashValue", "Tcl_GetHostName", "Tcl_GetIndexFromObj", "Tcl_GetIndexFromObjStruct", "Tcl_GetInt",
  1428. "Tcl_GetInterpPath", "Tcl_GetIntFromObj", "Tcl_GetLinkCountFromStat", "Tcl_GetLongFromObj", "Tcl_GetMaster",
  1429. "Tcl_GetMathFuncInfo", "Tcl_GetModeFromStat", "Tcl_GetModificationTimeFromStat", "Tcl_GetNameOfExecutable",
  1430. "Tcl_GetNamespaceUnknownHandler", "Tcl_GetObjectAsClass", "Tcl_GetObjectCommand", "Tcl_GetObjectFromObj",
  1431. "Tcl_GetObjectName", "Tcl_GetObjectNamespace", "Tcl_GetObjResult", "Tcl_GetObjType", "Tcl_GetOpenFile",
  1432. "Tcl_GetPathType", "Tcl_GetRange", "Tcl_GetRegExpFromObj", "Tcl_GetReturnOptions", "Tcl_Gets",
  1433. "Tcl_GetServiceMode", "Tcl_GetSizeFromStat", "Tcl_GetSlave", "Tcl_GetsObj", "Tcl_GetStackedChannel",
  1434. "Tcl_GetStartupScript", "Tcl_GetStdChannel", "Tcl_GetString", "Tcl_GetStringFromObj", "Tcl_GetStringResult",
  1435. "Tcl_GetThreadData", "Tcl_GetTime", "Tcl_GetTopChannel", "Tcl_GetUniChar", "Tcl_GetUnicode",
  1436. "Tcl_GetUnicodeFromObj", "Tcl_GetUserIdFromStat", "Tcl_GetVar", "Tcl_GetVar2", "Tcl_GetVar2Ex",
  1437. "Tcl_GetVersion", "Tcl_GetWideIntFromObj", "Tcl_GlobalEval", "Tcl_GlobalEvalObj", "Tcl_HashStats",
  1438. "Tcl_HideCommand", "Tcl_Import", "Tcl_IncrRefCount", "Tcl_Init", "Tcl_InitCustomHashTable",
  1439. "Tcl_InitHashTable", "Tcl_InitMemory", "Tcl_InitNotifier", "Tcl_InitObjHashTable", "Tcl_InitStubs",
  1440. "Tcl_InputBlocked", "Tcl_InputBuffered", "Tcl_InterpActive", "Tcl_InterpDeleted", "Tcl_InvalidateStringRep",
  1441. "Tcl_IsChannelExisting", "Tcl_IsChannelRegistered", "Tcl_IsChannelShared", "Tcl_IsEnsemble", "Tcl_IsSafe",
  1442. "Tcl_IsShared", "Tcl_IsStandardChannel", "Tcl_JoinPath", "Tcl_JoinThread", "Tcl_LimitAddHandler",
  1443. "Tcl_LimitCheck", "Tcl_LimitExceeded", "Tcl_LimitGetCommands", "Tcl_LimitGetGranularity",
  1444. "Tcl_LimitGetTime", "Tcl_LimitReady", "Tcl_LimitRemoveHandler", "Tcl_LimitSetCommands",
  1445. "Tcl_LimitSetGranularity", "Tcl_LimitSetTime", "Tcl_LimitTypeEnabled", "Tcl_LimitTypeExceeded",
  1446. "Tcl_LimitTypeReset", "Tcl_LimitTypeSet", "Tcl_LinkVar", "Tcl_ListMathFuncs", "Tcl_ListObjAppendElement",
  1447. "Tcl_ListObjAppendList", "Tcl_ListObjGetElements", "Tcl_ListObjIndex", "Tcl_ListObjLength",
  1448. "Tcl_ListObjReplace", "Tcl_LogCommandInfo", "Tcl_Main", "Tcl_MakeFileChannel", "Tcl_MakeSafe",
  1449. "Tcl_MakeTcpClientChannel", "Tcl_Merge", "Tcl_MethodDeclarerClass", "Tcl_MethodDeclarerObject",
  1450. "Tcl_MethodIsPublic", "Tcl_MethodIsType", "Tcl_MethodName", "Tcl_MutexFinalize", "Tcl_MutexLock",
  1451. "Tcl_MutexUnlock", "Tcl_NewBignumObj", "Tcl_NewBooleanObj", "Tcl_NewByteArrayObj", "Tcl_NewDictObj",
  1452. "Tcl_NewDoubleObj", "Tcl_NewInstanceMethod", "Tcl_NewIntObj", "Tcl_NewListObj", "Tcl_NewLongObj",
  1453. "Tcl_NewMethod", "Tcl_NewObj", "Tcl_NewObjectInstance", "Tcl_NewStringObj", "Tcl_NewUnicodeObj",
  1454. "Tcl_NewWideIntObj", "Tcl_NextHashEntry", "Tcl_NotifyChannel", "Tcl_NRAddCallback", "Tcl_NRCallObjProc",
  1455. "Tcl_NRCmdSwap", "Tcl_NRCreateCommand", "Tcl_NREvalObj", "Tcl_NREvalObjv", "Tcl_NumUtfChars",
  1456. "Tcl_ObjectContextInvokeNext", "Tcl_ObjectContextIsFiltering", "Tcl_ObjectContextMethod",
  1457. "Tcl_ObjectContextObject", "Tcl_ObjectContextSkippedArgs", "Tcl_ObjectDeleted", "Tcl_ObjectGetMetadata",
  1458. "Tcl_ObjectGetMethodNameMapper", "Tcl_ObjectSetMetadata", "Tcl_ObjectSetMethodNameMapper", "Tcl_ObjGetVar2",
  1459. "Tcl_ObjPrintf", "Tcl_ObjSetVar2", "Tcl_OpenCommandChannel", "Tcl_OpenFileChannel", "Tcl_OpenTcpClient",
  1460. "Tcl_OpenTcpServer", "Tcl_OutputBuffered", "Tcl_Panic", "Tcl_PanicVA", "Tcl_ParseArgsObjv",
  1461. "Tcl_ParseBraces", "Tcl_ParseCommand", "Tcl_ParseExpr", "Tcl_ParseQuotedString", "Tcl_ParseVar",
  1462. "Tcl_ParseVarName", "Tcl_PkgPresent", "Tcl_PkgPresentEx", "Tcl_PkgProvide", "Tcl_PkgProvideEx",
  1463. "Tcl_PkgRequire", "Tcl_PkgRequireEx", "Tcl_PkgRequireProc", "Tcl_PosixError", "Tcl_Preserve",
  1464. "Tcl_PrintDouble", "Tcl_PutEnv", "Tcl_QueryTimeProc", "Tcl_QueueEvent", "Tcl_Read", "Tcl_ReadChars",
  1465. "Tcl_ReadRaw", "Tcl_Realloc", "Tcl_ReapDetachedProcs", "Tcl_RecordAndEval", "Tcl_RecordAndEvalObj",
  1466. "Tcl_RegExpCompile", "Tcl_RegExpExec", "Tcl_RegExpExecObj", "Tcl_RegExpGetInfo", "Tcl_RegExpMatch",
  1467. "Tcl_RegExpMatchObj", "Tcl_RegExpRange", "Tcl_RegisterChannel", "Tcl_RegisterConfig", "Tcl_RegisterObjType",
  1468. "Tcl_Release", "Tcl_ResetResult", "Tcl_RestoreInterpState", "Tcl_RestoreResult", "Tcl_SaveInterpState",
  1469. "Tcl_SaveResult", "Tcl_ScanCountedElement", "Tcl_ScanElement", "Tcl_Seek", "Tcl_ServiceAll",
  1470. "Tcl_ServiceEvent", "Tcl_ServiceModeHook", "Tcl_SetAssocData", "Tcl_SetBignumObj", "Tcl_SetBooleanObj",
  1471. "Tcl_SetByteArrayLength", "Tcl_SetByteArrayObj", "Tcl_SetChannelBufferSize", "Tcl_SetChannelError",
  1472. "Tcl_SetChannelErrorInterp", "Tcl_SetChannelOption", "Tcl_SetCommandInfo", "Tcl_SetCommandInfoFromToken",
  1473. "Tcl_SetDefaultEncodingDir", "Tcl_SetDoubleObj", "Tcl_SetEncodingSearchPath", "Tcl_SetEnsembleFlags",
  1474. "Tcl_SetEnsembleMappingDict", "Tcl_SetEnsembleParameterList", "Tcl_SetEnsembleSubcommandList",
  1475. "Tcl_SetEnsembleUnknownHandler", "Tcl_SetErrno", "Tcl_SetErrorCode", "Tcl_SetErrorCodeVA",
  1476. "Tcl_SetErrorLine", "Tcl_SetExitProc", "Tcl_SetHashValue", "Tcl_SetIntObj", "Tcl_SetListObj",
  1477. "Tcl_SetLongObj", "Tcl_SetMainLoop", "Tcl_SetMaxBlockTime", "Tcl_SetNamespaceUnknownHandler",
  1478. "Tcl_SetNotifier", "Tcl_SetObjErrorCode", "Tcl_SetObjLength", "Tcl_SetObjResult", "Tcl_SetPanicProc",
  1479. "Tcl_SetRecursionLimit", "Tcl_SetResult", "Tcl_SetReturnOptions", "Tcl_SetServiceMode",
  1480. "Tcl_SetStartupScript", "Tcl_SetStdChannel", "Tcl_SetStringObj", "Tcl_SetSystemEncoding", "Tcl_SetTimeProc",
  1481. "Tcl_SetTimer", "Tcl_SetUnicodeObj", "Tcl_SetVar", "Tcl_SetVar2", "Tcl_SetVar2Ex", "Tcl_SetWideIntObj",
  1482. "Tcl_SignalId", "Tcl_SignalMsg", "Tcl_Sleep", "Tcl_SourceRCFile", "Tcl_SpliceChannel", "Tcl_SplitList",
  1483. "Tcl_SplitPath", "Tcl_StackChannel", "Tcl_StandardChannels", "Tcl_Stat", "Tcl_StaticPackage",
  1484. "Tcl_StringCaseMatch", "Tcl_StringMatch", "Tcl_SubstObj", "Tcl_TakeBignumFromObj", "Tcl_Tell",
  1485. "Tcl_ThreadAlert", "Tcl_ThreadQueueEvent", "Tcl_TraceCommand", "Tcl_TraceVar", "Tcl_TraceVar2",
  1486. "Tcl_TransferResult", "Tcl_TranslateFileName", "Tcl_TruncateChannel", "Tcl_Ungets", "Tcl_UniChar",
  1487. "Tcl_UniCharAtIndex", "Tcl_UniCharCaseMatch", "Tcl_UniCharIsAlnum", "Tcl_UniCharIsAlpha",
  1488. "Tcl_UniCharIsControl", "Tcl_UniCharIsDigit", "Tcl_UniCharIsGraph", "Tcl_UniCharIsLower",
  1489. "Tcl_UniCharIsPrint", "Tcl_UniCharIsPunct", "Tcl_UniCharIsSpace", "Tcl_UniCharIsUpper",
  1490. "Tcl_UniCharIsWordChar", "Tcl_UniCharLen", "Tcl_UniCharNcasecmp", "Tcl_UniCharNcmp", "Tcl_UniCharToLower",
  1491. "Tcl_UniCharToTitle", "Tcl_UniCharToUpper", "Tcl_UniCharToUtf", "Tcl_UniCharToUtfDString", "Tcl_UnlinkVar",
  1492. "Tcl_UnregisterChannel", "Tcl_UnsetVar", "Tcl_UnsetVar2", "Tcl_UnstackChannel", "Tcl_UntraceCommand",
  1493. "Tcl_UntraceVar", "Tcl_UntraceVar2", "Tcl_UpdateLinkedVar", "Tcl_UpVar", "Tcl_UpVar2", "Tcl_UtfAtIndex",
  1494. "Tcl_UtfBackslash", "Tcl_UtfCharComplete", "Tcl_UtfFindFirst", "Tcl_UtfFindLast", "Tcl_UtfNext",
  1495. "Tcl_UtfPrev", "Tcl_UtfToExternal", "Tcl_UtfToExternalDString", "Tcl_UtfToLower", "Tcl_UtfToTitle",
  1496. "Tcl_UtfToUniChar", "Tcl_UtfToUniCharDString", "Tcl_UtfToUpper", "Tcl_ValidateAllMemory", "Tcl_VarEval",
  1497. "Tcl_VarEvalVA", "Tcl_VarTraceInfo", "Tcl_VarTraceInfo2", "Tcl_WaitForEvent", "Tcl_WaitPid",
  1498. "Tcl_WinTCharToUtf", "Tcl_WinUtfToTChar", "Tcl_Write", "Tcl_WriteChars", "Tcl_WriteObj", "Tcl_WriteRaw",
  1499. "Tcl_WrongNumArgs", "Tcl_ZlibAdler32", "Tcl_ZlibCRC32", "Tcl_ZlibDeflate", "Tcl_ZlibInflate",
  1500. "Tcl_ZlibStreamChecksum", "Tcl_ZlibStreamClose", "Tcl_ZlibStreamEof", "Tcl_ZlibStreamGet",
  1501. "Tcl_ZlibStreamGetCommandName", "Tcl_ZlibStreamInit", "Tcl_ZlibStreamPut", "dde", "http", "msgcat",
  1502. "registry", "tcltest", "Tcl_AllocHashEntryProc", "Tcl_AppInitProc", "Tcl_ArgvInfo", "Tcl_AsyncProc",
  1503. "Tcl_ChannelProc", "Tcl_ChannelType", "Tcl_CloneProc", "Tcl_CloseProc", "Tcl_CmdDeleteProc", "Tcl_CmdInfo",
  1504. "Tcl_CmdObjTraceDeleteProc", "Tcl_CmdObjTraceProc", "Tcl_CmdProc", "Tcl_CmdTraceProc",
  1505. "Tcl_CommandTraceProc", "Tcl_CompareHashKeysProc", "Tcl_Config", "Tcl_DriverBlockModeProc",
  1506. "Tcl_DriverClose2Proc", "Tcl_DriverCloseProc", "Tcl_DriverFlushProc", "Tcl_DriverGetHandleProc",
  1507. "Tcl_DriverGetOptionProc", "Tcl_DriverHandlerProc", "Tcl_DriverInputProc", "Tcl_DriverOutputProc",
  1508. "Tcl_DriverSeekProc", "Tcl_DriverSetOptionProc", "Tcl_DriverThreadActionProc", "Tcl_DriverTruncateProc",
  1509. "Tcl_DriverWatchProc", "Tcl_DriverWideSeekProc", "Tcl_DupInternalRepProc", "Tcl_EncodingConvertProc",
  1510. "Tcl_EncodingFreeProc", "Tcl_EncodingType", "Tcl_Event", "Tcl_EventCheckProc", "Tcl_EventDeleteProc",
  1511. "Tcl_EventProc", "Tcl_EventSetupProc", "Tcl_ExitProc", "Tcl_FileProc", "Tcl_Filesystem",
  1512. "Tcl_FreeHashEntryProc", "Tcl_FreeInternalRepProc", "Tcl_FreeProc", "Tcl_FSAccessProc", "Tcl_FSChdirProc",
  1513. "Tcl_FSCopyDirectoryProc", "Tcl_FSCopyFileProc", "Tcl_FSCreateDirectoryProc", "Tcl_FSCreateInternalRepProc",
  1514. "Tcl_FSDeleteFileProc", "Tcl_FSDupInternalRepProc", "Tcl_FSFileAttrsGetProc", "Tcl_FSFileAttrsSetProc",
  1515. "Tcl_FSFilesystemPathTypeProc", "Tcl_FSFilesystemSeparatorProc", "Tcl_FSFreeInternalRepProc",
  1516. "Tcl_FSGetCwdProc", "Tcl_FSInternalToNormalizedProc", "Tcl_FSLinkProc", "Tcl_FSListVolumesProc",
  1517. "Tcl_FSLoadFileProc", "Tcl_FSLstatProc", "Tcl_FSMatchInDirectoryProc", "Tcl_FSNormalizePathProc",
  1518. "Tcl_FSOpenFileChannelProc", "Tcl_FSPathInFilesystemProc", "Tcl_FSRemoveDirectoryProc",
  1519. "Tcl_FSRenameFileProc", "Tcl_FSStatProc", "Tcl_FSUnloadFileProc", "Tcl_FSUtimeProc", "Tcl_GlobTypeData",
  1520. "Tcl_HashKeyType", "Tcl_IdleProc", "Tcl_Interp", "Tcl_InterpDeleteProc", "Tcl_LimitHandlerDeleteProc",
  1521. "Tcl_LimitHandlerProc", "Tcl_MainLoopProc", "Tcl_MathProc", "Tcl_MethodCallProc", "Tcl_MethodDeleteProc",
  1522. "Tcl_MethodType", "Tcl_NamespaceDeleteProc", "Tcl_NotifierProcs", "Tcl_Obj", "Tcl_ObjCmdProc",
  1523. "Tcl_ObjectMapMethodNameProc", "Tcl_ObjectMetadataDeleteProc", "Tcl_ObjType", "Tcl_PackageInitProc",
  1524. "Tcl_PackageUnloadProc", "Tcl_PanicProc", "Tcl_RegExpIndices", "Tcl_RegExpInfo", "Tcl_ScaleTimeProc",
  1525. "Tcl_SetFromAnyProc", "Tcl_TcpAcceptProc", "Tcl_Time", "Tcl_TimerProc", "Tcl_Token", "Tcl_UpdateStringProc",
  1526. "Tcl_Value", "Tcl_VarTraceProc", "argc", "argv", "argv0", "auto_path", "env", "errorCode", "errorInfo",
  1527. "filename", "re_syntax", "safe", "Tcl", "tcl_interactive", "tcl_library", "TCL_MEM_DEBUG",
  1528. "tcl_nonwordchars", "tcl_patchLevel", "tcl_pkgPath", "tcl_platform", "tcl_precision", "tcl_rcFileName",
  1529. "tcl_traceCompile", "tcl_traceEval", "tcl_version", "tcl_wordchars"
  1530. ]
  1531. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords + self.tcl_keywords
  1532. self.shell = FCShell(self, version=self.version)
  1533. self.shell._edit.set_model_data(self.myKeywords)
  1534. self.ui.code_editor.set_model_data(self.myKeywords)
  1535. self.shell.setWindowIcon(self.ui.app_icon)
  1536. self.shell.setWindowTitle("FlatCAM Shell")
  1537. self.shell.resize(*self.defaults["global_shell_shape"])
  1538. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1539. self.shell.append_output("(Type help to get started)\n\n")
  1540. self.init_tcl()
  1541. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1542. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1543. self.ui.shell_dock.setWidget(self.shell)
  1544. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1545. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1546. QtWidgets.QDockWidget.DockWidgetFloatable |
  1547. QtWidgets.QDockWidget.DockWidgetClosable)
  1548. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1549. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1550. if self.defaults["global_shell_at_startup"]:
  1551. self.ui.shell_dock.show()
  1552. else:
  1553. self.ui.shell_dock.hide()
  1554. # ###################### ##
  1555. # # ## Tools and Plugins # ##
  1556. # ###################### ##
  1557. self.dblsidedtool = None
  1558. self.measurement_tool = None
  1559. self.panelize_tool = None
  1560. self.film_tool = None
  1561. self.paste_tool = None
  1562. self.calculator_tool = None
  1563. self.sub_tool = None
  1564. self.move_tool = None
  1565. self.cutout_tool = None
  1566. self.ncclear_tool = None
  1567. self.paint_tool = None
  1568. self.transform_tool = None
  1569. self.properties_tool = None
  1570. self.pdf_tool = None
  1571. self.image_tool = None
  1572. self.pcb_wizard_tool = None
  1573. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1574. self.install_tools()
  1575. # # ## System Font Parsing # ##
  1576. # self.f_parse = ParseFont(self)
  1577. # self.parse_system_fonts()
  1578. # test if the program was started with a script as parameter
  1579. if self.cmd_line_shellfile:
  1580. try:
  1581. with open(self.cmd_line_shellfile, "r") as myfile:
  1582. cmd_line_shellfile_text = myfile.read()
  1583. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1584. except Exception as ext:
  1585. print("ERROR: ", ext)
  1586. sys.exit(2)
  1587. # ######################## ##
  1588. # # ## Check for updates ## ##
  1589. # ######################## ##
  1590. # Separate thread (Not worker)
  1591. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1592. if (self.beta is False or self.beta is None) and \
  1593. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1594. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1595. self.thr2 = QtCore.QThread()
  1596. self.worker_task.emit({'fcn': self.version_check,
  1597. 'params': []})
  1598. self.thr2.start(QtCore.QThread.LowPriority)
  1599. # ################################# ##
  1600. # # ## Variables for global usage ## ##
  1601. # ################################# ##
  1602. # coordinates for relative position display
  1603. self.rel_point1 = (0, 0)
  1604. self.rel_point2 = (0, 0)
  1605. # variable to store coordinates
  1606. self.pos = (0, 0)
  1607. self.pos_jump = (0, 0)
  1608. # decide if we have a double click or single click
  1609. self.doubleclick = False
  1610. # variable to store if a command is active (then the var is not None) and which one it is
  1611. self.command_active = None
  1612. # variable to store the status of moving selection action
  1613. # None value means that it's not an selection action
  1614. # True value = a selection from left to right
  1615. # False value = a selection from right to left
  1616. self.selection_type = None
  1617. # List to store the objects that are currently loaded in FlatCAM
  1618. # This list is updated on each object creation or object delete
  1619. self.all_objects_list = []
  1620. # List to store the objects that are selected
  1621. self.sel_objects_list = []
  1622. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1623. self.key_modifiers = None
  1624. # Variable to hold the status of the axis
  1625. self.toggle_axis = True
  1626. # Variable to store the status of the fullscreen event
  1627. self.toggle_fscreen = False
  1628. # Variable to store the status of the code editor
  1629. self.toggle_codeeditor = False
  1630. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1631. self.click_noproject = False
  1632. self.cursor = None
  1633. # Variable to store the GCODE that was edited
  1634. self.gcode_edited = ""
  1635. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3',
  1636. 'gko', 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15',
  1637. 'dim', 'mil', 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo',
  1638. 'art', 'gbd', 'gb0', 'gb1', 'gb2', 'gb3', 'g4', 'gb5', 'gb6', 'gb7', 'gb8', 'gb9'
  1639. ]
  1640. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc', 'ncd']
  1641. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1642. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1643. 'mpf'
  1644. ]
  1645. self.svg_list = ['svg']
  1646. self.dxf_list = ['dxf']
  1647. self.pdf_list = ['pdf']
  1648. self.prj_list = ['flatprj']
  1649. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1650. # flag for polygons not cleared
  1651. self.poly_not_cleared = False
  1652. # VisPy visuals
  1653. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.vispy_canvas.view.scene, layers=1)
  1654. self.isHovering = False
  1655. self.notHovering = True
  1656. # # ## Save defaults to factory_defaults.FlatConfig file # ##
  1657. # # ## It's done only once after install ########### ##
  1658. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1659. fac_def_from_file = factory_file.read()
  1660. factory_defaults = json.loads(fac_def_from_file)
  1661. # if the file contain an empty dictionary then save the factory defaults into the file
  1662. if not factory_defaults:
  1663. self.save_factory_defaults(silent=False)
  1664. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1665. initial_lay = 'compact'
  1666. self.on_layout(lay=initial_lay)
  1667. # Set the combobox in Preferences to the current layout
  1668. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  1669. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  1670. factory_file.close()
  1671. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1672. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1673. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1674. # Post-GUI initialization: Experimental attempt
  1675. # to perform unit tests on the GUI.
  1676. # if post_gui is not None:
  1677. # post_gui(self)
  1678. App.log.debug("END of constructor. Releasing control.")
  1679. # accept a project file as command line parameter
  1680. # the path/file_name must be enclosed in quotes if it contain spaces
  1681. for argument in App.args:
  1682. if '.FlatPrj' in argument:
  1683. try:
  1684. project_name = str(argument)
  1685. if project_name == "":
  1686. self.inform.emit(_("Open cancelled."))
  1687. else:
  1688. # self.open_project(project_name)
  1689. run_from_arg = True
  1690. self.worker_task.emit({'fcn': self.open_project,
  1691. 'params': [project_name, run_from_arg]})
  1692. except Exception as e:
  1693. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1694. if '.FlatConfig' in argument:
  1695. try:
  1696. file_name = str(argument)
  1697. if file_name == "":
  1698. self.inform.emit(_("Open Config file failed."))
  1699. else:
  1700. # run_from_arg = True
  1701. # self.worker_task.emit({'fcn': self.open_config_file,
  1702. # 'params': [file_name, run_from_arg]})
  1703. self.open_config_file(file_name, run_from_arg=True)
  1704. except Exception as e:
  1705. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1706. if '.FlatScript' in argument:
  1707. try:
  1708. file_name = str(argument)
  1709. if file_name == "":
  1710. self.inform.emit(_("Open Script file failed."))
  1711. else:
  1712. # run_from_arg = True
  1713. # self.worker_task.emit({'fcn': self.open_script_file,
  1714. # 'params': [file_name, run_from_arg]})
  1715. self.on_filerunscript(name=file_name)
  1716. except Exception as e:
  1717. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1718. def defaults_read_form(self):
  1719. for option in self.defaults_form_fields:
  1720. try:
  1721. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1722. except Exception as e:
  1723. log.debug("App.defaults_read_form() --> %s" % str(e))
  1724. def defaults_write_form(self, factor=None):
  1725. for option in self.defaults:
  1726. self.defaults_write_form_field(option, factor=factor)
  1727. # try:
  1728. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1729. # except KeyError:
  1730. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1731. # # TODO: Rethink this?
  1732. # pass
  1733. def defaults_write_form_field(self, field, factor=None):
  1734. try:
  1735. if factor is None:
  1736. self.defaults_form_fields[field].set_value(self.defaults[field])
  1737. else:
  1738. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  1739. except KeyError:
  1740. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  1741. # TODO: Rethink this?
  1742. pass
  1743. except AttributeError:
  1744. log.debug(field)
  1745. def clear_pool(self):
  1746. self.pool.close()
  1747. self.pool = Pool()
  1748. self.pool_recreated.emit(self.pool)
  1749. gc.collect()
  1750. # the order that the tools are installed is important as they can depend on each other install position
  1751. def install_tools(self):
  1752. self.dblsidedtool = DblSidedTool(self)
  1753. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1754. self.measurement_tool = Measurement(self)
  1755. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1756. self.panelize_tool = Panelize(self)
  1757. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1758. self.film_tool = Film(self)
  1759. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  1760. self.paste_tool = SolderPaste(self)
  1761. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  1762. self.calculator_tool = ToolCalculator(self)
  1763. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1764. self.sub_tool = ToolSub(self)
  1765. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menuedit_convert,
  1766. before=self.ui.menuedit_convert_sg2mg)
  1767. self.move_tool = ToolMove(self)
  1768. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1769. before=self.ui.menueditorigin)
  1770. self.cutout_tool = CutOut(self)
  1771. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  1772. before=self.measurement_tool.menuAction)
  1773. self.ncclear_tool = NonCopperClear(self)
  1774. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  1775. before=self.measurement_tool.menuAction, separator=True)
  1776. self.paint_tool = ToolPaint(self)
  1777. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1778. before=self.measurement_tool.menuAction, separator=True)
  1779. self.transform_tool = ToolTransform(self)
  1780. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1781. self.properties_tool = Properties(self)
  1782. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1783. self.pdf_tool = ToolPDF(self)
  1784. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  1785. separator=True)
  1786. self.image_tool = ToolImage(self)
  1787. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1788. separator=True)
  1789. self.pcb_wizard_tool = PcbWizard(self)
  1790. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  1791. self.log.debug("Tools are installed.")
  1792. def remove_tools(self):
  1793. for act in self.ui.menutool.actions():
  1794. self.ui.menutool.removeAction(act)
  1795. def init_tools(self):
  1796. log.debug("init_tools()")
  1797. # delete the data currently in the Tools Tab and the Tab itself
  1798. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1799. if widget is not None:
  1800. widget.deleteLater()
  1801. self.ui.notebook.removeTab(2)
  1802. # rebuild the Tools Tab
  1803. self.ui.tool_tab = QtWidgets.QWidget()
  1804. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1805. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1806. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1807. self.ui.tool_scroll_area = VerticalScrollArea()
  1808. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1809. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1810. # first remove all of them
  1811. self.remove_tools()
  1812. # second re add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1813. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  1814. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1815. # third install all of them
  1816. self.install_tools()
  1817. self.log.debug("Tools are initialized.")
  1818. # def parse_system_fonts(self):
  1819. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1820. # 'params': []})
  1821. def connect_toolbar_signals(self):
  1822. # Toolbar
  1823. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1824. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1825. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1826. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1827. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1828. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1829. self.ui.replot_btn.triggered.connect(self.plot_all)
  1830. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1831. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1832. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1833. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1834. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1835. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1836. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1837. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1838. self.ui.delete_btn.triggered.connect(self.on_delete)
  1839. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  1840. # Tools Toolbar Signals
  1841. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1842. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1843. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1844. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1845. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1846. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1847. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1848. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1849. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1850. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1851. def object2editor(self):
  1852. """
  1853. Send the current Geometry or Excellon object (if any) into the editor.
  1854. :return: None
  1855. """
  1856. self.report_usage("object2editor()")
  1857. edited_object = self.collection.get_active()
  1858. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  1859. isinstance(edited_object, FlatCAMExcellon):
  1860. pass
  1861. else:
  1862. self.inform.emit(_("[WARNING_NOTCL] Select a Geometry, Gerber or Excellon Object to edit."))
  1863. return
  1864. if isinstance(edited_object, FlatCAMGeometry):
  1865. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1866. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1867. if edited_object.multigeo is True:
  1868. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  1869. if len(edited_tools) > 1:
  1870. self.inform.emit(_("[WARNING_NOTCL] Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  1871. "is not possible.\n"
  1872. "Edit only one geometry at a time."))
  1873. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=edited_tools[0])
  1874. else:
  1875. self.geo_editor.edit_fcgeometry(edited_object)
  1876. # we set the notebook to hidden
  1877. self.ui.splitter.setSizes([0, 1])
  1878. # set call source to the Editor we go into
  1879. self.call_source = 'geo_editor'
  1880. elif isinstance(edited_object, FlatCAMExcellon):
  1881. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1882. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1883. self.exc_editor.edit_fcexcellon(edited_object)
  1884. # set call source to the Editor we go into
  1885. self.call_source = 'exc_editor'
  1886. if self.ui.splitter.sizes()[0] == 0:
  1887. self.ui.splitter.setSizes([1, 1])
  1888. elif isinstance(edited_object, FlatCAMGerber):
  1889. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1890. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1891. self.grb_editor.edit_fcgerber(edited_object)
  1892. # set call source to the Editor we go into
  1893. self.call_source = 'grb_editor'
  1894. if self.ui.splitter.sizes()[0] == 0:
  1895. self.ui.splitter.setSizes([1, 1])
  1896. # # make sure that we can't select another object while in Editor Mode:
  1897. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1898. self.ui.project_frame.setDisabled(True)
  1899. # delete any selection shape that might be active as they are not relevant in Editor
  1900. self.delete_selection_shape()
  1901. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1902. self.ui.plot_tab_area.protectTab(0)
  1903. self.inform.emit(_("[WARNING_NOTCL] Editor is activated ..."))
  1904. self.should_we_save = True
  1905. def editor2object(self, cleanup=None):
  1906. """
  1907. Transfers the Geometry or Excellon from the editor to the current object.
  1908. :return: None
  1909. """
  1910. self.report_usage("editor2object()")
  1911. # do not update a geometry or excellon object unless it comes out of an editor
  1912. if self.call_source != 'app':
  1913. edited_obj = self.collection.get_active()
  1914. if cleanup is None:
  1915. msgbox = QtWidgets.QMessageBox()
  1916. msgbox.setText(_("Do you want to save the edited object?"))
  1917. msgbox.setWindowTitle(_("Close Editor"))
  1918. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  1919. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1920. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1921. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1922. msgbox.setDefaultButton(bt_yes)
  1923. msgbox.exec_()
  1924. response = msgbox.clickedButton()
  1925. if response == bt_yes:
  1926. # clean the Tools Tab
  1927. self.ui.tool_scroll_area.takeWidget()
  1928. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1929. self.ui.notebook.setTabText(2, "Tool")
  1930. if isinstance(edited_obj, FlatCAMGeometry):
  1931. obj_type = "Geometry"
  1932. if cleanup is None:
  1933. self.geo_editor.update_fcgeometry(edited_obj)
  1934. self.geo_editor.update_options(edited_obj)
  1935. self.geo_editor.deactivate()
  1936. # update the geo object options so it is including the bounding box values
  1937. try:
  1938. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1939. edited_obj.options['xmin'] = xmin
  1940. edited_obj.options['ymin'] = ymin
  1941. edited_obj.options['xmax'] = xmax
  1942. edited_obj.options['ymax'] = ymax
  1943. except AttributeError as e:
  1944. self.inform.emit(_("[WARNING] Object empty after edit."))
  1945. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1946. elif isinstance(edited_obj, FlatCAMGerber):
  1947. obj_type = "Gerber"
  1948. if cleanup is None:
  1949. self.grb_editor.update_fcgerber()
  1950. self.grb_editor.update_options(edited_obj)
  1951. self.grb_editor.deactivate_grb_editor()
  1952. # delete the old object (the source object) if it was an empty one
  1953. if len(edited_obj.solid_geometry) == 0:
  1954. old_name = edited_obj.options['name']
  1955. self.collection.set_active(old_name)
  1956. self.collection.delete_active()
  1957. elif isinstance(edited_obj, FlatCAMExcellon):
  1958. obj_type = "Excellon"
  1959. if cleanup is None:
  1960. self.exc_editor.update_fcexcellon(edited_obj)
  1961. self.exc_editor.update_options(edited_obj)
  1962. self.exc_editor.deactivate()
  1963. else:
  1964. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  1965. return
  1966. self.inform.emit(_("[selected] %s is updated, returning to App...") % obj_type)
  1967. elif response == bt_no:
  1968. # clean the Tools Tab
  1969. self.ui.tool_scroll_area.takeWidget()
  1970. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1971. self.ui.notebook.setTabText(2, "Tool")
  1972. if isinstance(edited_obj, FlatCAMGeometry):
  1973. self.geo_editor.deactivate()
  1974. elif isinstance(edited_obj, FlatCAMGerber):
  1975. self.grb_editor.deactivate_grb_editor()
  1976. elif isinstance(edited_obj, FlatCAMExcellon):
  1977. self.exc_editor.deactivate()
  1978. # set focus on the project tab
  1979. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  1980. else:
  1981. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  1982. return
  1983. elif response == bt_cancel:
  1984. return
  1985. else:
  1986. if isinstance(edited_obj, FlatCAMGeometry):
  1987. self.geo_editor.deactivate()
  1988. elif isinstance(edited_obj, FlatCAMGerber):
  1989. self.grb_editor.deactivate_grb_editor()
  1990. elif isinstance(edited_obj, FlatCAMExcellon):
  1991. self.exc_editor.deactivate()
  1992. else:
  1993. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  1994. return
  1995. # if notebook is hidden we show it
  1996. if self.ui.splitter.sizes()[0] == 0:
  1997. self.ui.splitter.setSizes([1, 1])
  1998. # restore the call_source to app
  1999. self.call_source = 'app'
  2000. edited_obj.plot()
  2001. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2002. self.ui.plot_tab_area.protectTab(0)
  2003. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2004. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2005. self.ui.project_frame.setDisabled(False)
  2006. def get_last_folder(self):
  2007. return self.defaults["global_last_folder"]
  2008. def get_last_save_folder(self):
  2009. loc = self.defaults["global_last_save_folder"]
  2010. if loc is None:
  2011. loc = self.defaults["global_last_folder"]
  2012. if loc is None:
  2013. loc = os.path.dirname(__file__)
  2014. return loc
  2015. def report_usage(self, resource):
  2016. """
  2017. Increments usage counter for the given resource
  2018. in self.defaults['global_stats'].
  2019. :param resource: Name of the resource.
  2020. :return: None
  2021. """
  2022. if resource in self.defaults['global_stats']:
  2023. self.defaults['global_stats'][resource] += 1
  2024. else:
  2025. self.defaults['global_stats'][resource] = 1
  2026. def init_tcl(self):
  2027. if hasattr(self, 'tcl'):
  2028. # self.tcl = None
  2029. # TODO we need to clean non default variables and procedures here
  2030. # new object cannot be used here as it will not remember values created for next passes,
  2031. # because tcl was execudted in old instance of TCL
  2032. pass
  2033. else:
  2034. self.tcl = tk.Tcl()
  2035. self.setup_shell()
  2036. self.log.debug("TCL Shell has been initialized.")
  2037. # TODO: This shouldn't be here.
  2038. class TclErrorException(Exception):
  2039. """
  2040. this exception is defined here, to be able catch it if we ssuccessfully handle all errors from shell command
  2041. """
  2042. pass
  2043. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2044. """
  2045. Shows a message on the FlatCAM Shell
  2046. :param msg: Message to display.
  2047. :param show: Opens the shell.
  2048. :param error: Shows the message as an error.
  2049. :param warning: Shows the message as an warning.
  2050. :param warning: Shows the message as an success.
  2051. :param selected: Indicate that something was selected on canvas
  2052. :return: None
  2053. """
  2054. if show:
  2055. self.ui.shell_dock.show()
  2056. try:
  2057. if error:
  2058. self.shell.append_error(msg + "\n")
  2059. elif warning:
  2060. self.shell.append_warning(msg + "\n")
  2061. elif success:
  2062. self.shell.append_success(msg + "\n")
  2063. elif selected:
  2064. self.shell.append_selected(msg + "\n")
  2065. else:
  2066. self.shell.append_output(msg + "\n")
  2067. except AttributeError:
  2068. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2069. def raise_tcl_unknown_error(self, unknownException):
  2070. """
  2071. Raise exception if is different type than TclErrorException
  2072. this is here mainly to show unknown errors inside TCL shell console.
  2073. :param unknownException:
  2074. :return:
  2075. """
  2076. if not isinstance(unknownException, self.TclErrorException):
  2077. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2078. else:
  2079. raise unknownException
  2080. def display_tcl_error(self, error, error_info=None):
  2081. """
  2082. Escape bracket [ with '\' otherwise there is error
  2083. "ERROR: missing close-bracket" instead of real error
  2084. :param error: it may be text or exception
  2085. :param error_info: Some informations about the error
  2086. :return: None
  2087. """
  2088. if isinstance(error, Exception):
  2089. exc_type, exc_value, exc_traceback = error_info
  2090. if not isinstance(error, self.TclErrorException):
  2091. show_trace = 1
  2092. else:
  2093. show_trace = int(self.defaults['global_verbose_error_level'])
  2094. if show_trace > 0:
  2095. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2096. trc_formated = []
  2097. for a in reversed(trc):
  2098. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2099. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2100. else:
  2101. text = "%s" % error
  2102. else:
  2103. text = error
  2104. text = text.replace('[', '\\[').replace('"', '\\"')
  2105. self.tcl.eval('return -code error "%s"' % text)
  2106. def raise_tcl_error(self, text):
  2107. """
  2108. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2109. :param text: text of error
  2110. :return: raise exception
  2111. """
  2112. self.display_tcl_error(text)
  2113. raise self.TclErrorException(text)
  2114. def exec_command(self, text):
  2115. """
  2116. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2117. Also handles execution in separated threads
  2118. :param text:
  2119. :return: output if there was any
  2120. """
  2121. self.report_usage('exec_command')
  2122. result = self.exec_command_test(text, False)
  2123. # MS: added this method call so the geometry is updated once the TCL command is executed
  2124. self.plot_all()
  2125. return result
  2126. def exec_command_test(self, text, reraise=True):
  2127. """
  2128. Same as exec_command(...) with additional control over exceptions.
  2129. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2130. :param text: Input command
  2131. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2132. :return: Output from the command
  2133. """
  2134. text = str(text)
  2135. try:
  2136. self.shell.open_proccessing() # Disables input box.
  2137. result = self.tcl.eval(str(text))
  2138. if result != 'None':
  2139. self.shell.append_output(result + '\n')
  2140. except tk.TclError as e:
  2141. # This will display more precise answer if something in TCL shell fails
  2142. result = self.tcl.eval("set errorInfo")
  2143. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2144. self.shell.append_error('ERROR: ' + result + '\n')
  2145. # Show error in console and just return or in test raise exception
  2146. if reraise:
  2147. raise e
  2148. finally:
  2149. self.shell.close_proccessing()
  2150. pass
  2151. return result
  2152. # """
  2153. # Code below is unsused. Saved for later.
  2154. # """
  2155. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2156. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2157. # self.log.debug(parts)
  2158. # try:
  2159. # if parts[0] not in commands:
  2160. # self.shell.append_error("Unknown command\n")
  2161. # return
  2162. #
  2163. # #import inspect
  2164. # #inspect.getargspec(someMethod)
  2165. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2166. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2167. # self.shell.append_error(
  2168. # "Command %s takes %d arguments. %d given.\n" %
  2169. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2170. # )
  2171. # return
  2172. #
  2173. # cmdfcn = commands[parts[0]]["fcn"]
  2174. # cmdconv = commands[parts[0]]["converters"]
  2175. # if len(parts) - 1 > 0:
  2176. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2177. # else:
  2178. # retval = cmdfcn()
  2179. # retfcn = commands[parts[0]]["retfcn"]
  2180. # if retval and retfcn(retval):
  2181. # self.shell.append_output(retfcn(retval) + "\n")
  2182. #
  2183. # except Exception as e:
  2184. # #self.shell.append_error(''.join(traceback.format_exc()))
  2185. # #self.shell.append_error("?\n")
  2186. # self.shell.append_error(str(e) + "\n")
  2187. def info(self, msg):
  2188. """
  2189. Informs the user. Normally on the status bar, optionally
  2190. also on the shell.
  2191. :param msg: Text to write.
  2192. :return: None
  2193. """
  2194. # Type of message in brackets at the beginning of the message.
  2195. match = re.search("\[([^\]]+)\](.*)", msg)
  2196. if match:
  2197. level = match.group(1)
  2198. msg_ = match.group(2)
  2199. self.ui.fcinfo.set_status(str(msg_), level=level)
  2200. if level.lower() == "error":
  2201. self.shell_message(msg, error=True, show=True)
  2202. elif level.lower() == "warning":
  2203. self.shell_message(msg, warning=True, show=True)
  2204. elif level.lower() == "error_notcl":
  2205. self.shell_message(msg, error=True, show=False)
  2206. elif level.lower() == "warning_notcl":
  2207. self.shell_message(msg, warning=True, show=False)
  2208. elif level.lower() == "success":
  2209. self.shell_message(msg, success=True, show=False)
  2210. elif level.lower() == "selected":
  2211. self.shell_message(msg, selected=True, show=False)
  2212. else:
  2213. self.shell_message(msg, show=False)
  2214. else:
  2215. self.ui.fcinfo.set_status(str(msg), level="info")
  2216. # make sure that if the message is to clear the infobar with a space
  2217. # is not printed over and over on the shell
  2218. if msg != '':
  2219. self.shell_message(msg)
  2220. def restore_toolbar_view(self):
  2221. tb = self.defaults["global_toolbar_view"]
  2222. if tb & 1:
  2223. self.ui.toolbarfile.setVisible(True)
  2224. else:
  2225. self.ui.toolbarfile.setVisible(False)
  2226. if tb & 2:
  2227. self.ui.toolbargeo.setVisible(True)
  2228. else:
  2229. self.ui.toolbargeo.setVisible(False)
  2230. if tb & 4:
  2231. self.ui.toolbarview.setVisible(True)
  2232. else:
  2233. self.ui.toolbarview.setVisible(False)
  2234. if tb & 8:
  2235. self.ui.toolbartools.setVisible(True)
  2236. else:
  2237. self.ui.toolbartools.setVisible(False)
  2238. if tb & 16:
  2239. self.ui.exc_edit_toolbar.setVisible(True)
  2240. else:
  2241. self.ui.exc_edit_toolbar.setVisible(False)
  2242. if tb & 32:
  2243. self.ui.geo_edit_toolbar.setVisible(True)
  2244. else:
  2245. self.ui.geo_edit_toolbar.setVisible(False)
  2246. if tb & 64:
  2247. self.ui.grb_edit_toolbar.setVisible(True)
  2248. else:
  2249. self.ui.grb_edit_toolbar.setVisible(False)
  2250. if tb & 128:
  2251. self.ui.snap_toolbar.setVisible(True)
  2252. else:
  2253. self.ui.snap_toolbar.setVisible(False)
  2254. if tb & 256:
  2255. self.ui.toolbarshell.setVisible(True)
  2256. else:
  2257. self.ui.toolbarshell.setVisible(False)
  2258. def load_defaults(self, filename):
  2259. """
  2260. Loads the aplication's default settings from current_defaults.FlatConfig into
  2261. ``self.defaults``.
  2262. :return: None
  2263. """
  2264. try:
  2265. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2266. options = f.read()
  2267. f.close()
  2268. except IOError:
  2269. self.log.error("Could not load defaults file.")
  2270. self.inform.emit(_("[ERROR] Could not load defaults file."))
  2271. # in case the defaults file can't be loaded, show all toolbars
  2272. self.defaults["global_toolbar_view"] = 511
  2273. return
  2274. try:
  2275. defaults = json.loads(options)
  2276. except:
  2277. # in case the defaults file can't be loaded, show all toolbars
  2278. self.defaults["global_toolbar_view"] = 511
  2279. e = sys.exc_info()[0]
  2280. App.log.error(str(e))
  2281. self.inform.emit(_("[ERROR] Failed to parse defaults file."))
  2282. return
  2283. self.defaults.update(defaults)
  2284. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2285. # restore the toolbar view
  2286. self.restore_toolbar_view()
  2287. def on_import_preferences(self):
  2288. """
  2289. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2290. ``self.defaults``.
  2291. :return: None
  2292. """
  2293. self.report_usage("on_import_preferences")
  2294. App.log.debug("on_import_preferences()")
  2295. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2296. try:
  2297. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2298. directory=self.data_path,
  2299. filter=filter_)
  2300. except TypeError:
  2301. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2302. filter=filter_)
  2303. filename = str(filename)
  2304. if filename == "":
  2305. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences import cancelled."))
  2306. else:
  2307. try:
  2308. f = open(filename)
  2309. options = f.read()
  2310. f.close()
  2311. except IOError:
  2312. self.log.error("Could not load defaults file.")
  2313. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2314. return
  2315. try:
  2316. defaults_from_file = json.loads(options)
  2317. except Exception as e:
  2318. e = sys.exc_info()[0]
  2319. App.log.error(str(e))
  2320. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2321. return
  2322. self.defaults.update(defaults_from_file)
  2323. self.inform.emit(_("[success] Imported Defaults from %s") %filename)
  2324. def on_export_preferences(self):
  2325. self.report_usage("on_export_preferences")
  2326. App.log.debug("on_export_preferences()")
  2327. defaults_file_content = None
  2328. self.date = str(datetime.today()).rpartition('.')[0]
  2329. self.date = ''.join(c for c in self.date if c not in ':-')
  2330. self.date = self.date.replace(' ', '_')
  2331. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  2332. try:
  2333. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  2334. caption=_("Export FlatCAM Preferences"),
  2335. directory=self.data_path + '/preferences_' + self.date,
  2336. filter=filter
  2337. )
  2338. except TypeError:
  2339. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  2340. filter=filter)
  2341. filename = str(filename)
  2342. defaults_from_file = {}
  2343. if filename == "":
  2344. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences export cancelled."))
  2345. return
  2346. else:
  2347. try:
  2348. f = open(filename, 'w')
  2349. defaults_file_content = f.read()
  2350. f.close()
  2351. except IOError:
  2352. App.log.debug('Creating a new preferences file ...')
  2353. f = open(filename, 'w')
  2354. json.dump({}, f)
  2355. f.close()
  2356. except:
  2357. e = sys.exc_info()[0]
  2358. App.log.error("Could not load defaults file.")
  2359. App.log.error(str(e))
  2360. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2361. return
  2362. try:
  2363. defaults_from_file = json.loads(defaults_file_content)
  2364. except:
  2365. App.log.warning("Trying to read an empty Preferences file. Continue.")
  2366. # Update options
  2367. self.defaults_read_form()
  2368. defaults_from_file.update(self.defaults)
  2369. self.propagate_defaults(silent=True)
  2370. # Save update options
  2371. try:
  2372. f = open(filename, "w")
  2373. json.dump(defaults_from_file, f)
  2374. f.close()
  2375. except:
  2376. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2377. return
  2378. if self.defaults["global_open_style"] is False:
  2379. self.file_opened.emit("preferences", filename)
  2380. self.file_saved.emit("preferences", filename)
  2381. self.inform.emit("[success] Exported Defaults to %s" % filename)
  2382. def on_preferences_open_folder(self):
  2383. self.report_usage("on_preferences_open_folder()")
  2384. if sys.platform == 'win32':
  2385. subprocess.Popen('explorer %s' % self.data_path)
  2386. elif sys.platform == 'darwin':
  2387. os.system('open "%s"' % self.data_path)
  2388. else:
  2389. subprocess.Popen(['xdg-open', self.data_path])
  2390. self.inform.emit("[success] FlatCAM Preferences Folder opened.")
  2391. def save_geometry(self, x, y, width, height, notebook_width):
  2392. self.defaults["global_def_win_x"] = x
  2393. self.defaults["global_def_win_y"] = y
  2394. self.defaults["global_def_win_w"] = width
  2395. self.defaults["global_def_win_h"] = height
  2396. self.defaults["global_def_notebook_width"] = notebook_width
  2397. self.save_defaults()
  2398. def message_dialog(self, title, message, kind="info"):
  2399. icon = {"info": QtWidgets.QMessageBox.Information,
  2400. "warning": QtWidgets.QMessageBox.Warning,
  2401. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2402. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2403. dlg.setText(message)
  2404. dlg.exec_()
  2405. def register_recent(self, kind, filename):
  2406. self.log.debug("register_recent()")
  2407. self.log.debug(" %s" % kind)
  2408. self.log.debug(" %s" % filename)
  2409. record = {'kind': str(kind), 'filename': str(filename)}
  2410. if record in self.recent:
  2411. return
  2412. self.recent.insert(0, record)
  2413. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2414. self.recent.pop()
  2415. try:
  2416. f = open(self.data_path + '/recent.json', 'w')
  2417. except IOError:
  2418. App.log.error("Failed to open recent items file for writing.")
  2419. self.inform.emit(_('[ERROR_NOTCL] Failed to open recent files file for writing.'))
  2420. return
  2421. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2422. f.close()
  2423. # Re-build the recent items menu
  2424. self.setup_recent_items()
  2425. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2426. """
  2427. Creates a new specialized FlatCAMObj and attaches it to the application,
  2428. this is, updates the GUI accordingly, any other records and plots it.
  2429. This method is thread-safe.
  2430. Notes:
  2431. * If the name is in use, the self.collection will modify it
  2432. when appending it to the collection. There is no need to handle
  2433. name conflicts here.
  2434. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2435. :type kind: str
  2436. :param name: Name for the object.
  2437. :type name: str
  2438. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2439. The function is called with 2 parameters: the new object and the App instance.
  2440. :type initialize: function
  2441. :return: None
  2442. :rtype: None
  2443. """
  2444. App.log.debug("new_object()")
  2445. obj_plot = plot
  2446. obj_autoselected = autoselected
  2447. t0 = time.time() # Debug
  2448. # ## Create object
  2449. classdict = {
  2450. "gerber": FlatCAMGerber,
  2451. "excellon": FlatCAMExcellon,
  2452. "cncjob": FlatCAMCNCjob,
  2453. "geometry": FlatCAMGeometry
  2454. }
  2455. App.log.debug("Calling object constructor...")
  2456. obj = classdict[kind](name)
  2457. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  2458. # Set options from "Project options" form
  2459. self.options_read_form()
  2460. # IMPORTANT
  2461. # The key names in defaults and options dictionary's are not random:
  2462. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2463. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  2464. # the options from project options form into the self.options. After that, below, depending on the type of
  2465. # object that is created, it will strip the name of the object and the underline (if the original key was
  2466. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2467. # "toolchange"
  2468. for option in self.options:
  2469. if option.find(kind + "_") == 0:
  2470. oname = option[len(kind) + 1:]
  2471. obj.options[oname] = self.options[option]
  2472. obj.isHovering = False
  2473. obj.notHovering = True
  2474. # Initialize as per user request
  2475. # User must take care to implement initialize
  2476. # in a thread-safe way as is is likely that we
  2477. # have been invoked in a separate thread.
  2478. t1 = time.time()
  2479. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2480. try:
  2481. return_value = initialize(obj, self)
  2482. except Exception as e:
  2483. msg = _("[ERROR_NOTCL] An internal error has ocurred. See shell.\n")
  2484. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2485. msg += traceback.format_exc()
  2486. self.inform.emit(msg)
  2487. # if str(e) == "Empty Geometry":
  2488. # self.inform.emit("[ERROR_NOTCL] )
  2489. # else:
  2490. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  2491. return "fail"
  2492. t2 = time.time()
  2493. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2494. if return_value == 'fail':
  2495. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2496. return "fail"
  2497. # Check units and convert if necessary
  2498. # This condition CAN be true because initialize() can change obj.units
  2499. if self.options["units"].upper() != obj.units.upper():
  2500. self.inform.emit(_("Converting units to ") + self.options["units"] + ".")
  2501. obj.convert_units(self.options["units"])
  2502. t3 = time.time()
  2503. self.log.debug("%f seconds converting units." % (t3 - t2))
  2504. # Create the bounding box for the object and then add the results to the obj.options
  2505. try:
  2506. xmin, ymin, xmax, ymax = obj.bounds()
  2507. obj.options['xmin'] = xmin
  2508. obj.options['ymin'] = ymin
  2509. obj.options['xmax'] = xmax
  2510. obj.options['ymax'] = ymax
  2511. except:
  2512. log.warning("The object has no bounds properties.")
  2513. # don't plot objects with no bounds, there is nothing to plot
  2514. self.plot = False
  2515. pass
  2516. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  2517. # Move the object to the main thread and let the app know that it is available.
  2518. obj.moveToThread(self.main_thread)
  2519. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2520. return obj
  2521. def new_excellon_object(self):
  2522. self.report_usage("new_excellon_object()")
  2523. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2524. def new_geometry_object(self):
  2525. self.report_usage("new_geometry_object()")
  2526. def initialize(obj, self):
  2527. obj.multitool = False
  2528. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2529. def new_gerber_object(self):
  2530. self.report_usage("new_gerber_object()")
  2531. def initialize(grb_obj, self):
  2532. grb_obj.multitool = False
  2533. grb_obj.source_file = []
  2534. grb_obj.multigeo = False
  2535. grb_obj.follow = False
  2536. grb_obj.apertures = {}
  2537. grb_obj.solid_geometry = []
  2538. try:
  2539. grb_obj.options['xmin'] = 0
  2540. grb_obj.options['ymin'] = 0
  2541. grb_obj.options['xmax'] = 0
  2542. grb_obj.options['ymax'] = 0
  2543. except KeyError:
  2544. pass
  2545. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2546. def on_object_created(self, obj, plot, autoselect):
  2547. """
  2548. Event callback for object creation.
  2549. :param obj: The newly created FlatCAM object.
  2550. :return: None
  2551. """
  2552. t0 = time.time() # DEBUG
  2553. self.log.debug("on_object_created()")
  2554. # The Collection might change the name if there is a collision
  2555. self.collection.append(obj)
  2556. # after adding the object to the collection always update the list of objects that are in the collection
  2557. self.all_objects_list = self.collection.get_list()
  2558. # self.inform.emit('[selected] %s created & selected: %s' %
  2559. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2560. if obj.kind == 'gerber':
  2561. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2562. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  2563. elif obj.kind == 'excellon':
  2564. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2565. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  2566. elif obj.kind == 'cncjob':
  2567. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2568. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  2569. elif obj.kind == 'geometry':
  2570. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2571. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  2572. # update the SHELL auto-completer model with the name of the new object
  2573. self.myKeywords.append(obj.options['name'])
  2574. self.shell._edit.set_model_data(self.myKeywords)
  2575. self.ui.code_editor.set_model_data(self.myKeywords)
  2576. if autoselect:
  2577. # select the just opened object but deselect the previous ones
  2578. self.collection.set_all_inactive()
  2579. self.collection.set_active(obj.options["name"])
  2580. # here it is done the object plotting
  2581. def worker_task(t_obj):
  2582. with self.proc_container.new("Plotting"):
  2583. if isinstance(t_obj, FlatCAMCNCjob):
  2584. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2585. else:
  2586. t_obj.plot()
  2587. t1 = time.time() # DEBUG
  2588. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2589. self.object_plotted.emit(t_obj)
  2590. # Send to worker
  2591. # self.worker.add_task(worker_task, [self])
  2592. if plot is True:
  2593. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2594. def on_object_changed(self, obj):
  2595. # update the bounding box data from obj.options
  2596. xmin, ymin, xmax, ymax = obj.bounds()
  2597. obj.options['xmin'] = xmin
  2598. obj.options['ymin'] = ymin
  2599. obj.options['xmax'] = xmax
  2600. obj.options['ymax'] = ymax
  2601. log.debug("Object changed, updating the bounding box data on self.options")
  2602. # delete the old selection shape
  2603. self.delete_selection_shape()
  2604. self.should_we_save = True
  2605. def on_object_plotted(self, obj):
  2606. self.on_zoom_fit(None)
  2607. def options_read_form(self):
  2608. for option in self.options_form_fields:
  2609. self.options[option] = self.options_form_fields[option].get_value()
  2610. def options_write_form(self):
  2611. for option in self.options:
  2612. self.options_write_form_field(option)
  2613. def options_write_form_field(self, field):
  2614. try:
  2615. self.options_form_fields[field].set_value(self.options[field])
  2616. except KeyError:
  2617. # Changed from error to debug. This allows to have data stored
  2618. # which is not user-editable.
  2619. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  2620. pass
  2621. def on_about(self):
  2622. """
  2623. Displays the "about" dialog.
  2624. :return: None
  2625. """
  2626. self.report_usage("on_about")
  2627. version = self.version
  2628. version_date = self.version_date
  2629. beta = self.beta
  2630. class AboutDialog(QtWidgets.QDialog):
  2631. def __init__(self, parent=None):
  2632. QtWidgets.QDialog.__init__(self, parent)
  2633. # Icon and title
  2634. self.setWindowIcon(parent.app_icon)
  2635. self.setWindowTitle("FlatCAM")
  2636. layout1 = QtWidgets.QVBoxLayout()
  2637. self.setLayout(layout1)
  2638. layout2 = QtWidgets.QHBoxLayout()
  2639. layout1.addLayout(layout2)
  2640. logo = QtWidgets.QLabel()
  2641. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  2642. layout2.addWidget(logo, stretch=0)
  2643. title = QtWidgets.QLabel(
  2644. _(
  2645. "<font size=8><B>FlatCAM</B></font><BR>"
  2646. "Version {version} {beta} ({date}) - {arch} <BR>"
  2647. "<BR>"
  2648. "2D Computer-Aided Printed Circuit Board<BR>"
  2649. "Manufacturing.<BR>"
  2650. "<BR>"
  2651. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  2652. "<BR>"
  2653. "<B> Main Contributors:</B><BR>"
  2654. "Denis Hayrullin<BR>"
  2655. "Kamil Sopko<BR>"
  2656. "Marius Stanciu<BR>"
  2657. "Matthieu Berthomé<BR>"
  2658. "and many others found "
  2659. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  2660. "<BR>"
  2661. "Development is done "
  2662. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  2663. "DOWNLOAD area "
  2664. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  2665. ""
  2666. ).format(version=version,
  2667. beta=('BETA' if beta else ''),
  2668. date=version_date,
  2669. arch=platform.architecture()[0])
  2670. )
  2671. title.setOpenExternalLinks(True)
  2672. layout2.addWidget(title, stretch=1)
  2673. layout3 = QtWidgets.QHBoxLayout()
  2674. layout1.addLayout(layout3)
  2675. layout3.addStretch()
  2676. okbtn = QtWidgets.QPushButton("Close")
  2677. layout3.addWidget(okbtn)
  2678. okbtn.clicked.connect(self.accept)
  2679. AboutDialog(self.ui).exec_()
  2680. def on_file_savedefaults(self):
  2681. """
  2682. Callback for menu item File->Save Defaults. Saves application default options
  2683. ``self.defaults`` to current_defaults.FlatConfig.
  2684. :return: None
  2685. """
  2686. self.save_defaults()
  2687. # def on_app_exit(self):
  2688. # self.report_usage("on_app_exit()")
  2689. #
  2690. # if self.collection.get_list():
  2691. # msgbox = QtWidgets.QMessageBox()
  2692. # # msgbox.setText("<B>Save changes ...</B>")
  2693. # msgbox.setText("There are files/objects opened in FlatCAM. "
  2694. # "\n"
  2695. # "Do you want to Save the project?")
  2696. # msgbox.setWindowTitle("Save changes")
  2697. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2698. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2699. # QtWidgets.QMessageBox.Cancel)
  2700. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2701. #
  2702. # response = msgbox.exec_()
  2703. #
  2704. # if response == QtWidgets.QMessageBox.Yes:
  2705. # self.on_file_saveprojectas(thread=False)
  2706. # elif response == QtWidgets.QMessageBox.Cancel:
  2707. # return
  2708. # self.save_defaults()
  2709. # else:
  2710. # self.save_defaults()
  2711. # log.debug("Application defaults saved ... Exit event.")
  2712. # QtWidgets.qApp.quit()
  2713. def save_defaults(self, silent=False):
  2714. """
  2715. Saves application default options
  2716. ``self.defaults`` to current_defaults.FlatConfig.
  2717. :return: None
  2718. """
  2719. self.report_usage("save_defaults")
  2720. # Read options from file
  2721. try:
  2722. f = open(self.data_path + "/current_defaults.FlatConfig")
  2723. defaults_file_content = f.read()
  2724. f.close()
  2725. except:
  2726. e = sys.exc_info()[0]
  2727. App.log.error("Could not load defaults file.")
  2728. App.log.error(str(e))
  2729. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2730. return
  2731. try:
  2732. defaults = json.loads(defaults_file_content)
  2733. except:
  2734. e = sys.exc_info()[0]
  2735. App.log.error("Failed to parse defaults file.")
  2736. App.log.error(str(e))
  2737. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2738. return
  2739. # Update options
  2740. self.defaults_read_form()
  2741. defaults.update(self.defaults)
  2742. self.propagate_defaults(silent=True)
  2743. # Save the toolbar view
  2744. tb_status = 0
  2745. if self.ui.toolbarfile.isVisible():
  2746. tb_status += 1
  2747. if self.ui.toolbargeo.isVisible():
  2748. tb_status += 2
  2749. if self.ui.toolbarview.isVisible():
  2750. tb_status += 4
  2751. if self.ui.toolbartools.isVisible():
  2752. tb_status += 8
  2753. if self.ui.exc_edit_toolbar.isVisible():
  2754. tb_status += 16
  2755. if self.ui.geo_edit_toolbar.isVisible():
  2756. tb_status += 32
  2757. if self.ui.grb_edit_toolbar.isVisible():
  2758. tb_status += 64
  2759. if self.ui.snap_toolbar.isVisible():
  2760. tb_status += 128
  2761. if self.ui.toolbarshell.isVisible():
  2762. tb_status += 256
  2763. self.defaults["global_toolbar_view"] = tb_status
  2764. # Save update options
  2765. try:
  2766. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  2767. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  2768. f.close()
  2769. except:
  2770. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2771. return
  2772. if not silent:
  2773. self.inform.emit(_("[success] Defaults saved."))
  2774. def save_factory_defaults(self, silent=False):
  2775. """
  2776. Saves application factory default options
  2777. ``self.defaults`` to factory_defaults.FlatConfig.
  2778. It's a one time job done just after the first install.
  2779. :return: None
  2780. """
  2781. self.report_usage("save_factory_defaults")
  2782. # Read options from file
  2783. try:
  2784. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  2785. factory_defaults_file_content = f_f_def.read()
  2786. f_f_def.close()
  2787. except:
  2788. e = sys.exc_info()[0]
  2789. App.log.error("Could not load factory defaults file.")
  2790. App.log.error(str(e))
  2791. self.inform.emit(_("[ERROR_NOTCL] Could not load factory defaults file."))
  2792. return
  2793. try:
  2794. factory_defaults = json.loads(factory_defaults_file_content)
  2795. except:
  2796. e = sys.exc_info()[0]
  2797. App.log.error("Failed to parse factory defaults file.")
  2798. App.log.error(str(e))
  2799. self.inform.emit(_("[ERROR_NOTCL] Failed to parse factory defaults file."))
  2800. return
  2801. # Update options
  2802. self.defaults_read_form()
  2803. factory_defaults.update(self.defaults)
  2804. self.propagate_defaults(silent=True)
  2805. # Save update options
  2806. try:
  2807. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  2808. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  2809. f_f_def_s.close()
  2810. except:
  2811. self.inform.emit(_("[ERROR_NOTCL] Failed to write factory defaults to file."))
  2812. return
  2813. if silent is False:
  2814. self.inform.emit(_("Factory defaults saved."))
  2815. def final_save(self):
  2816. if self.save_in_progress:
  2817. self.inform.emit(_("[WARNING_NOTCL] Application is saving the project. Please wait ..."))
  2818. return
  2819. if self.should_we_save and self.collection.get_list():
  2820. msgbox = QtWidgets.QMessageBox()
  2821. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2822. "\n"
  2823. "Do you want to Save the project?"))
  2824. msgbox.setWindowTitle(_("Save changes"))
  2825. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2826. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2827. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2828. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2829. msgbox.setDefaultButton(bt_yes)
  2830. msgbox.exec_()
  2831. response = msgbox.clickedButton()
  2832. if response == bt_yes:
  2833. self.on_file_saveprojectas(thread=True, quit=True)
  2834. elif response == bt_no:
  2835. self.quit_application()
  2836. elif response == bt_cancel:
  2837. return
  2838. else:
  2839. self.quit_application()
  2840. def quit_application(self):
  2841. self.save_defaults()
  2842. log.debug("App.final_save() --> App Defaults saved.")
  2843. # save toolbar state to file
  2844. settings = QSettings("Open Source", "FlatCAM")
  2845. settings.setValue('saved_gui_state', self.ui.saveState())
  2846. settings.setValue('maximized_gui', self.ui.isMaximized())
  2847. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  2848. # This will write the setting to the platform specific storage.
  2849. del settings
  2850. log.debug("App.final_save() --> App UI state saved.")
  2851. QtWidgets.qApp.quit()
  2852. def on_toggle_shell(self):
  2853. """
  2854. toggle shell if is visible close it if closed open it
  2855. :return:
  2856. """
  2857. self.report_usage("on_toggle_shell()")
  2858. if self.ui.shell_dock.isVisible():
  2859. self.ui.shell_dock.hide()
  2860. else:
  2861. self.ui.shell_dock.show()
  2862. def on_edit_join(self, name=None):
  2863. """
  2864. Callback for Edit->Join. Joins the selected geometry objects into
  2865. a new one.
  2866. :return: None
  2867. """
  2868. self.report_usage("on_edit_join()")
  2869. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2870. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2871. tooldias = []
  2872. geo_type_list = []
  2873. objs = self.collection.get_selected()
  2874. for obj in objs:
  2875. geo_type_list.append(obj.multigeo)
  2876. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2877. if len(set(geo_type_list)) != 1:
  2878. self.inform.emit(_("[ERROR] Failed join. The Geometry objects are of different types.\n"
  2879. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2880. "convert from one to another and retry joining \n"
  2881. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2882. "the result may not be what was expected. \n"
  2883. "Check the generated GCODE."))
  2884. return
  2885. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2886. if True in geo_type_list:
  2887. def initialize(obj, app):
  2888. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2889. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2890. for v in obj.tools.values():
  2891. v['data']['name'] = obj_name_multi
  2892. self.new_object("geometry", obj_name_multi, initialize)
  2893. else:
  2894. def initialize(obj, app):
  2895. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2896. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2897. for v in obj.tools.values():
  2898. v['data']['name'] = obj_name_single
  2899. self.new_object("geometry", obj_name_single, initialize)
  2900. self.should_we_save = True
  2901. def on_edit_join_exc(self):
  2902. """
  2903. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2904. a new one.
  2905. :return: None
  2906. """
  2907. self.report_usage("on_edit_join_exc()")
  2908. objs = self.collection.get_selected()
  2909. for obj in objs:
  2910. if not isinstance(obj, FlatCAMExcellon):
  2911. self.inform.emit(_("[ERROR_NOTCL] Failed. Excellon joining works only on Excellon objects."))
  2912. return
  2913. def initialize(obj, app):
  2914. FlatCAMExcellon.merge(objs, obj)
  2915. self.new_object("excellon", 'Combo_Excellon', initialize)
  2916. self.should_we_save = True
  2917. def on_edit_join_grb(self):
  2918. """
  2919. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2920. a new one.
  2921. :return: None
  2922. """
  2923. self.report_usage("on_edit_join_grb()")
  2924. objs = self.collection.get_selected()
  2925. for obj in objs:
  2926. if not isinstance(obj, FlatCAMGerber):
  2927. self.inform.emit(_("[ERROR_NOTCL] Failed. Gerber joining works only on Gerber objects."))
  2928. return
  2929. def initialize(obj, app):
  2930. FlatCAMGerber.merge(objs, obj)
  2931. self.new_object("gerber", 'Combo_Gerber', initialize)
  2932. self.should_we_save = True
  2933. def on_convert_singlegeo_to_multigeo(self):
  2934. self.report_usage("on_convert_singlegeo_to_multigeo()")
  2935. obj = self.collection.get_active()
  2936. if obj is None:
  2937. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  2938. return
  2939. if not isinstance(obj, FlatCAMGeometry):
  2940. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  2941. return
  2942. obj.multigeo = True
  2943. for tooluid, dict_value in obj.tools.items():
  2944. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2945. if not isinstance(obj.solid_geometry, list):
  2946. obj.solid_geometry = [obj.solid_geometry]
  2947. obj.solid_geometry[:] = []
  2948. obj.plot()
  2949. self.should_we_save = True
  2950. self.inform.emit(_("[success] A Geometry object was converted to MultiGeo type."))
  2951. def on_convert_multigeo_to_singlegeo(self):
  2952. self.report_usage("on_convert_multigeo_to_singlegeo()")
  2953. obj = self.collection.get_active()
  2954. if obj is None:
  2955. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  2956. return
  2957. if not isinstance(obj, FlatCAMGeometry):
  2958. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  2959. return
  2960. obj.multigeo = False
  2961. total_solid_geometry = []
  2962. for tooluid, dict_value in obj.tools.items():
  2963. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2964. # clear the original geometry
  2965. dict_value['solid_geometry'][:] = []
  2966. obj.solid_geometry = deepcopy(total_solid_geometry)
  2967. obj.plot()
  2968. self.should_we_save = True
  2969. self.inform.emit(_("[success] A Geometry object was converted to SingleGeo type."))
  2970. def on_options_dict_change(self, field):
  2971. self.options_write_form_field(field)
  2972. if field == "units":
  2973. self.set_screen_units(self.options['units'])
  2974. def on_defaults_dict_change(self, field):
  2975. self.defaults_write_form_field(field)
  2976. if field == "units":
  2977. self.set_screen_units(self.defaults['units'])
  2978. def set_screen_units(self, units):
  2979. self.ui.units_label.setText("[" + units.lower() + "]")
  2980. def on_toggle_units(self, no_pref=False):
  2981. """
  2982. Callback for the Units radio-button change in the Options tab.
  2983. Changes the application's default units or the current project's units.
  2984. If changing the project's units, the change propagates to all of
  2985. the objects in the project.
  2986. :return: None
  2987. """
  2988. self.report_usage("on_toggle_units")
  2989. if self.toggle_units_ignore:
  2990. return
  2991. # If option is the same, then ignore
  2992. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == \
  2993. self.defaults["units"].upper():
  2994. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  2995. return
  2996. # Options to scale
  2997. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  2998. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  2999. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3000. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  3001. "excellon_z_pdepth",
  3002. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3003. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3004. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  3005. "geometry_feedrate_probe",
  3006. 'cncjob_tooldia',
  3007. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  3008. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin",
  3009. "tools_2sided_drilldia", "tools_film_boundary",
  3010. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  3011. "tools_panelize_constrainx", "tools_panelize_constrainy",
  3012. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3013. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  3014. "tools_transform_offset_y",
  3015. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3016. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3017. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3018. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3019. 'global_gridx', 'global_gridy', 'global_snap_max']
  3020. def scale_options(sfactor):
  3021. for dim in dimensions:
  3022. if dim == 'excellon_toolchangexy':
  3023. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  3024. coords_xy[0] *= sfactor
  3025. coords_xy[1] *= sfactor
  3026. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3027. elif dim == 'geometry_toolchangexy':
  3028. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  3029. coords_xy[0] *= sfactor
  3030. coords_xy[1] *= sfactor
  3031. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  3032. elif dim == 'tools_ncctools':
  3033. ncctols = [float(eval(a)) for a in self.defaults["tools_ncctools"].split(",")]
  3034. ncctols[0] *= sfactor
  3035. ncctols[1] *= sfactor
  3036. self.options['tools_ncctools'] = "%f, %f" % (ncctols[0], ncctols[1])
  3037. elif dim == 'tools_solderpaste_tools':
  3038. sp_tools = [float(eval(a)) for a in self.defaults["tools_solderpaste_tools"].split(",")]
  3039. sp_tools[0] *= sfactor
  3040. sp_tools[1] *= sfactor
  3041. self.options['tools_solderpaste_tools'] = "%f, %f" % (sp_tools[0], sp_tools[1])
  3042. elif dim == 'tools_solderpaste_xy_toolchange':
  3043. sp_coords = [float(eval(a)) for a in self.defaults["tools_solderpaste_xy_toolchange"].split(",")]
  3044. sp_coords[0] *= sfactor
  3045. sp_coords[1] *= sfactor
  3046. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  3047. else:
  3048. try:
  3049. self.options[dim] = float(self.options[dim]) * sfactor
  3050. except Exception as e:
  3051. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  3052. def scale_defaults(sfactor):
  3053. for dim in dimensions:
  3054. if dim == 'excellon_toolchangexy':
  3055. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  3056. coords_xy[0] *= sfactor
  3057. coords_xy[1] *= sfactor
  3058. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3059. elif dim == 'geometry_toolchangexy':
  3060. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  3061. coords_xy[0] *= sfactor
  3062. coords_xy[1] *= sfactor
  3063. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  3064. elif dim == 'tools_ncctools':
  3065. ncctols = [float(eval(a)) for a in self.defaults["tools_ncctools"].split(",")]
  3066. ncctols[0] *= sfactor
  3067. ncctols[1] *= sfactor
  3068. self.defaults['tools_ncctools'] = "%.4f, %.4f" % (ncctols[0], ncctols[1])
  3069. elif dim == 'tools_solderpaste_tools':
  3070. sp_tools = [float(eval(a)) for a in self.defaults["tools_solderpaste_tools"].split(",")]
  3071. sp_tools[0] *= sfactor
  3072. sp_tools[1] *= sfactor
  3073. self.defaults['tools_solderpaste_tools'] = "%.4f, %.4f" % (sp_tools[0], sp_tools[1])
  3074. elif dim == 'tools_solderpaste_xy_toolchange':
  3075. sp_coords = [float(eval(a)) for a in self.defaults["tools_solderpaste_xy_toolchange"].split(",")]
  3076. sp_coords[0] *= sfactor
  3077. sp_coords[1] *= sfactor
  3078. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  3079. else:
  3080. try:
  3081. self.defaults[dim] = float(self.defaults[dim]) * sfactor
  3082. except Exception as e:
  3083. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3084. # The scaling factor depending on choice of units.
  3085. factor = 1/25.4
  3086. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  3087. factor = 25.4
  3088. # Changing project units. Warn user.
  3089. msgbox = QtWidgets.QMessageBox()
  3090. msgbox.setWindowTitle("Toggle Units")
  3091. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  3092. msgbox.setText("<B>Change project units ...</B>")
  3093. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  3094. "properties of all objects to be scaled accordingly.\nContinue?")
  3095. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3096. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3097. msgbox.setDefaultButton(bt_ok)
  3098. msgbox.exec_()
  3099. response = msgbox.clickedButton()
  3100. if response == bt_ok:
  3101. if no_pref is False:
  3102. self.options_read_form()
  3103. scale_options(factor)
  3104. self.options_write_form()
  3105. self.defaults_read_form()
  3106. scale_defaults(factor)
  3107. self.defaults_write_form()
  3108. self.should_we_save = True
  3109. # change this only if the workspace is active
  3110. if self.defaults['global_workspace'] is True:
  3111. self.plotcanvas.draw_workspace()
  3112. # adjust the grid values on the main toolbar
  3113. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  3114. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  3115. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3116. for obj in self.collection.get_list():
  3117. obj.convert_units(units)
  3118. # make that the properties stored in the object are also updated
  3119. self.object_changed.emit(obj)
  3120. obj.build_ui()
  3121. current = self.collection.get_active()
  3122. if current is not None:
  3123. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3124. if not isinstance(current, FlatCAMGeometry):
  3125. current.to_form()
  3126. self.plot_all()
  3127. self.inform.emit(_("[success] Converted units to %s") % units)
  3128. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  3129. self.set_screen_units(units)
  3130. else:
  3131. # Undo toggling
  3132. self.toggle_units_ignore = True
  3133. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  3134. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3135. else:
  3136. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3137. self.toggle_units_ignore = False
  3138. self.inform.emit(_("[WARNING_NOTCL] Units conversion cancelled."))
  3139. self.options_read_form()
  3140. self.defaults_read_form()
  3141. def on_toggle_units_click(self):
  3142. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3143. if self.defaults["units"] == 'MM':
  3144. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3145. else:
  3146. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3147. self.on_toggle_units(no_pref=True)
  3148. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3149. lambda: self.on_toggle_units(no_pref=False))
  3150. def on_fullscreen(self):
  3151. self.report_usage("on_fullscreen()")
  3152. if self.toggle_fscreen is False:
  3153. if sys.platform == 'win32':
  3154. self.ui.showFullScreen()
  3155. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3156. tb.setVisible(False)
  3157. self.ui.splitter_left.setVisible(False)
  3158. self.toggle_fscreen = True
  3159. else:
  3160. if sys.platform == 'win32':
  3161. self.ui.showNormal()
  3162. self.restore_toolbar_view()
  3163. self.ui.splitter_left.setVisible(True)
  3164. self.toggle_fscreen = False
  3165. def on_toggle_plotarea(self):
  3166. self.report_usage("on_toggle_plotarea()")
  3167. try:
  3168. name = self.ui.plot_tab_area.widget(0).objectName()
  3169. except AttributeError:
  3170. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3171. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3172. self.ui.plot_tab_area.protectTab(0)
  3173. return
  3174. if name != 'plotarea':
  3175. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3176. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3177. self.ui.plot_tab_area.protectTab(0)
  3178. else:
  3179. self.ui.plot_tab_area.closeTab(0)
  3180. def on_toggle_notebook(self):
  3181. if self.ui.splitter.sizes()[0] == 0:
  3182. self.ui.splitter.setSizes([1, 1])
  3183. else:
  3184. self.ui.splitter.setSizes([0, 1])
  3185. def on_toggle_axis(self):
  3186. self.report_usage("on_toggle_axis()")
  3187. if self.toggle_axis is False:
  3188. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  3189. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  3190. self.plotcanvas.redraw()
  3191. self.toggle_axis = True
  3192. else:
  3193. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  3194. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  3195. self.plotcanvas.redraw()
  3196. self.toggle_axis = False
  3197. def on_toggle_grid(self):
  3198. self.report_usage("on_toggle_grid()")
  3199. self.ui.grid_snap_btn.trigger()
  3200. def on_options_combo_change(self, sel):
  3201. """
  3202. Called when the combo box to choose between application defaults and
  3203. project option changes value. The corresponding variables are
  3204. copied to the UI.
  3205. :param sel: The option index that was chosen.
  3206. :return: None
  3207. """
  3208. # combo_sel = self.ui.notebook.combo_options.get_active()
  3209. App.log.debug("Options --> %s" % sel)
  3210. # form = [self.defaults_form, self.options_form][sel]
  3211. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  3212. if sel == 0:
  3213. self.gen_form = self.ui.general_defaults_form
  3214. self.ger_form = self.ui.gerber_defaults_form
  3215. self.exc_form = self.ui.excellon_defaults_form
  3216. self.geo_form = self.ui.geometry_defaults_form
  3217. self.cnc_form = self.ui.cncjob_defaults_form
  3218. self.tools_form = self.ui.tools_defaults_form
  3219. elif sel == 1:
  3220. self.gen_form = self.ui.general_options_form
  3221. self.ger_form = self.ui.gerber_options_form
  3222. self.exc_form = self.ui.excellon_options_form
  3223. self.geo_form = self.ui.geometry_options_form
  3224. self.cnc_form = self.ui.cncjob_options_form
  3225. self.tools_form = self.ui.tools_options_form
  3226. else:
  3227. return
  3228. try:
  3229. self.ui.general_scroll_area.takeWidget()
  3230. except:
  3231. self.log.debug("Nothing to remove")
  3232. self.ui.general_scroll_area.setWidget(self.gen_form)
  3233. self.gen_form.show()
  3234. try:
  3235. self.ui.gerber_scroll_area.takeWidget()
  3236. except:
  3237. self.log.debug("Nothing to remove")
  3238. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  3239. self.ger_form.show()
  3240. try:
  3241. self.ui.excellon_scroll_area.takeWidget()
  3242. except:
  3243. self.log.debug("Nothing to remove")
  3244. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  3245. self.exc_form.show()
  3246. try:
  3247. self.ui.geometry_scroll_area.takeWidget()
  3248. except:
  3249. self.log.debug("Nothing to remove")
  3250. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  3251. self.geo_form.show()
  3252. try:
  3253. self.ui.cncjob_scroll_area.takeWidget()
  3254. except:
  3255. self.log.debug("Nothing to remove")
  3256. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  3257. self.cnc_form.show()
  3258. try:
  3259. self.ui.tools_scroll_area.takeWidget()
  3260. except:
  3261. self.log.debug("Nothing to remove")
  3262. self.ui.tools_scroll_area.setWidget(self.tools_form)
  3263. self.tools_form.show()
  3264. self.log.debug("Finished GUI form initialization.")
  3265. # self.options2form()
  3266. def on_excellon_defaults_button(self):
  3267. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  3268. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  3269. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  3270. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  3271. self.defaults_form_fields["excellon_zeros"].set_value('L')
  3272. self.defaults_form_fields["excellon_units"].set_value('INCH')
  3273. log.debug("Excellon app defaults loaded ...")
  3274. def on_excellon_options_button(self):
  3275. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  3276. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  3277. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  3278. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  3279. self.options_form_fields["excellon_zeros"].set_value('L')
  3280. self.options_form_fields["excellon_units"].set_value('INCH')
  3281. log.debug("Excellon options defaults loaded ...")
  3282. # Setting plot colors handlers
  3283. def on_pf_color_entry(self):
  3284. self.defaults['global_plot_fill'] = self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  3285. self.defaults['global_plot_fill'][7:9]
  3286. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  3287. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  3288. def on_pf_color_button(self):
  3289. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  3290. c_dialog = QtWidgets.QColorDialog()
  3291. plot_fill_color = c_dialog.getColor(initial=current_color)
  3292. if plot_fill_color.isValid() is False:
  3293. return
  3294. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  3295. "background-color:%s" % str(plot_fill_color.name()))
  3296. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  3297. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  3298. self.defaults['global_plot_fill'] = new_val
  3299. def on_pf_color_spinner(self):
  3300. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  3301. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  3302. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  3303. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3304. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  3305. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3306. def on_pf_color_slider(self):
  3307. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  3308. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  3309. def on_pl_color_entry(self):
  3310. self.defaults['global_plot_line'] = self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  3311. self.defaults['global_plot_line'][7:9]
  3312. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  3313. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  3314. def on_pl_color_button(self):
  3315. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  3316. # print(current_color)
  3317. c_dialog = QtWidgets.QColorDialog()
  3318. plot_line_color = c_dialog.getColor(initial=current_color)
  3319. if plot_line_color.isValid() is False:
  3320. return
  3321. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  3322. "background-color:%s" % str(plot_line_color.name()))
  3323. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  3324. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  3325. self.defaults['global_plot_line'] = new_val_line
  3326. # Setting selection colors (left - right) handlers
  3327. def on_sf_color_entry(self):
  3328. self.defaults['global_sel_fill'] = self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  3329. self.defaults['global_sel_fill'][7:9]
  3330. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  3331. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  3332. def on_sf_color_button(self):
  3333. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  3334. c_dialog = QtWidgets.QColorDialog()
  3335. plot_fill_color = c_dialog.getColor(initial=current_color)
  3336. if plot_fill_color.isValid() is False:
  3337. return
  3338. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  3339. "background-color:%s" % str(plot_fill_color.name()))
  3340. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  3341. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  3342. self.defaults['global_sel_fill'] = new_val
  3343. def on_sf_color_spinner(self):
  3344. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  3345. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  3346. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  3347. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3348. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  3349. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3350. def on_sf_color_slider(self):
  3351. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  3352. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  3353. def on_sl_color_entry(self):
  3354. self.defaults['global_sel_line'] = self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  3355. self.defaults['global_sel_line'][7:9]
  3356. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  3357. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  3358. def on_sl_color_button(self):
  3359. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  3360. c_dialog = QtWidgets.QColorDialog()
  3361. plot_line_color = c_dialog.getColor(initial=current_color)
  3362. if plot_line_color.isValid() is False:
  3363. return
  3364. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  3365. "background-color:%s" % str(plot_line_color.name()))
  3366. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  3367. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  3368. self.defaults['global_sel_line'] = new_val_line
  3369. # Setting selection colors (right - left) handlers
  3370. def on_alt_sf_color_entry(self):
  3371. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  3372. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  3373. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  3374. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  3375. def on_alt_sf_color_button(self):
  3376. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  3377. c_dialog = QtWidgets.QColorDialog()
  3378. plot_fill_color = c_dialog.getColor(initial=current_color)
  3379. if plot_fill_color.isValid() is False:
  3380. return
  3381. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  3382. "background-color:%s" % str(plot_fill_color.name()))
  3383. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  3384. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  3385. self.defaults['global_alt_sel_fill'] = new_val
  3386. def on_alt_sf_color_spinner(self):
  3387. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  3388. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  3389. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  3390. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3391. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  3392. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3393. def on_alt_sf_color_slider(self):
  3394. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  3395. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  3396. def on_alt_sl_color_entry(self):
  3397. self.defaults['global_alt_sel_line'] = \
  3398. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  3399. self.defaults['global_alt_sel_line'][7:9]
  3400. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  3401. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  3402. def on_alt_sl_color_button(self):
  3403. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  3404. c_dialog = QtWidgets.QColorDialog()
  3405. plot_line_color = c_dialog.getColor(initial=current_color)
  3406. if plot_line_color.isValid() is False:
  3407. return
  3408. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  3409. "background-color:%s" % str(plot_line_color.name()))
  3410. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  3411. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  3412. self.defaults['global_alt_sel_line'] = new_val_line
  3413. # Setting Editor colors
  3414. def on_draw_color_entry(self):
  3415. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3416. .draw_color_entry.get_value()
  3417. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  3418. "background-color:%s" % str(self.defaults['global_draw_color']))
  3419. def on_draw_color_button(self):
  3420. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  3421. c_dialog = QtWidgets.QColorDialog()
  3422. draw_color = c_dialog.getColor(initial=current_color)
  3423. if draw_color.isValid() is False:
  3424. return
  3425. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  3426. "background-color:%s" % str(draw_color.name()))
  3427. new_val = str(draw_color.name())
  3428. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  3429. self.defaults['global_draw_color'] = new_val
  3430. def on_sel_draw_color_entry(self):
  3431. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3432. .sel_draw_color_entry.get_value()
  3433. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3434. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  3435. def on_sel_draw_color_button(self):
  3436. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  3437. c_dialog = QtWidgets.QColorDialog()
  3438. sel_draw_color = c_dialog.getColor(initial=current_color)
  3439. if sel_draw_color.isValid() is False:
  3440. return
  3441. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3442. "background-color:%s" % str(sel_draw_color.name()))
  3443. new_val_sel = str(sel_draw_color.name())
  3444. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  3445. self.defaults['global_sel_draw_color'] = new_val_sel
  3446. def on_proj_color_entry(self):
  3447. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  3448. .proj_color_entry.get_value()
  3449. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  3450. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  3451. def on_proj_color_button(self):
  3452. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  3453. c_dialog = QtWidgets.QColorDialog()
  3454. proj_color = c_dialog.getColor(initial=current_color)
  3455. if proj_color.isValid() is False:
  3456. return
  3457. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  3458. "background-color:%s" % str(proj_color.name()))
  3459. new_val_sel = str(proj_color.name())
  3460. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  3461. self.defaults['global_proj_item_color'] = new_val_sel
  3462. def on_proj_color_dis_entry(self):
  3463. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  3464. .proj_color_dis_entry.get_value()
  3465. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  3466. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  3467. def on_proj_color_dis_button(self):
  3468. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  3469. c_dialog = QtWidgets.QColorDialog()
  3470. proj_color = c_dialog.getColor(initial=current_color)
  3471. if proj_color.isValid() is False:
  3472. return
  3473. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  3474. "background-color:%s" % str(proj_color.name()))
  3475. new_val_sel = str(proj_color.name())
  3476. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  3477. self.defaults['global_proj_item_dis_color'] = new_val_sel
  3478. def on_annotation_fontcolor_entry(self):
  3479. self.defaults['cncjob_annotation_fontcolor'] = \
  3480. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.get_value()
  3481. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  3482. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  3483. def on_annotation_fontcolor_button(self):
  3484. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  3485. c_dialog = QtWidgets.QColorDialog()
  3486. annotation_color = c_dialog.getColor(initial=current_color)
  3487. if annotation_color.isValid() is False:
  3488. return
  3489. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_button.setStyleSheet(
  3490. "background-color:%s" % str(annotation_color.name()))
  3491. new_val_sel = str(annotation_color.name())
  3492. self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_fontcolor_entry.set_value(new_val_sel)
  3493. self.defaults['global_proj_item_dis_color'] = new_val_sel
  3494. def on_deselect_all(self):
  3495. self.collection.set_all_inactive()
  3496. self.delete_selection_shape()
  3497. def on_workspace_modified(self):
  3498. self.save_defaults(silent=True)
  3499. self.plotcanvas.draw_workspace()
  3500. def on_workspace(self):
  3501. self.report_usage("on_workspace()")
  3502. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3503. self.plotcanvas.restore_workspace()
  3504. else:
  3505. self.plotcanvas.delete_workspace()
  3506. self.save_defaults(silent=True)
  3507. def on_workspace_menu(self):
  3508. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3509. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  3510. else:
  3511. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  3512. self.on_workspace()
  3513. def on_layout(self, index=None, lay=None):
  3514. self.report_usage("on_layout()")
  3515. if lay:
  3516. current_layout = lay
  3517. else:
  3518. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  3519. settings = QSettings("Open Source", "FlatCAM")
  3520. settings.setValue('layout', current_layout)
  3521. # This will write the setting to the platform specific storage.
  3522. del settings
  3523. # first remove the toolbars:
  3524. try:
  3525. self.ui.removeToolBar(self.ui.toolbarfile)
  3526. self.ui.removeToolBar(self.ui.toolbargeo)
  3527. self.ui.removeToolBar(self.ui.toolbarview)
  3528. self.ui.removeToolBar(self.ui.toolbarshell)
  3529. self.ui.removeToolBar(self.ui.toolbartools)
  3530. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  3531. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  3532. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  3533. self.ui.removeToolBar(self.ui.snap_toolbar)
  3534. self.ui.removeToolBar(self.ui.toolbarshell)
  3535. except:
  3536. pass
  3537. if current_layout == 'standard':
  3538. # ## TOOLBAR INSTALLATION # ##
  3539. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3540. self.ui.toolbarfile.setObjectName('File_TB')
  3541. self.ui.addToolBar(self.ui.toolbarfile)
  3542. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3543. self.ui.toolbargeo.setObjectName('Edit_TB')
  3544. self.ui.addToolBar(self.ui.toolbargeo)
  3545. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3546. self.ui.toolbarview.setObjectName('View_TB')
  3547. self.ui.addToolBar(self.ui.toolbarview)
  3548. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3549. self.ui.toolbarshell.setObjectName('Shell_TB')
  3550. self.ui.addToolBar(self.ui.toolbarshell)
  3551. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3552. self.ui.toolbartools.setObjectName('Tools_TB')
  3553. self.ui.addToolBar(self.ui.toolbartools)
  3554. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3555. self.ui.exc_edit_toolbar.setVisible(False)
  3556. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3557. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  3558. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3559. self.ui.geo_edit_toolbar.setVisible(False)
  3560. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3561. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  3562. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  3563. self.ui.grb_edit_toolbar.setVisible(False)
  3564. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  3565. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  3566. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3567. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3568. # self.ui.snap_toolbar.setMaximumHeight(30)
  3569. self.ui.addToolBar(self.ui.snap_toolbar)
  3570. self.ui.corner_snap_btn.setVisible(False)
  3571. self.ui.snap_magnet.setVisible(False)
  3572. elif current_layout == 'compact':
  3573. # ## TOOLBAR INSTALLATION # ##
  3574. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3575. self.ui.toolbarfile.setObjectName('File_TB')
  3576. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  3577. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3578. self.ui.toolbargeo.setObjectName('Edit_TB')
  3579. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  3580. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3581. self.ui.toolbarview.setObjectName('View_TB')
  3582. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  3583. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3584. self.ui.toolbarshell.setObjectName('Shell_TB')
  3585. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  3586. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3587. self.ui.toolbartools.setObjectName('Tools_TB')
  3588. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  3589. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3590. # self.ui.geo_edit_toolbar.setVisible(False)
  3591. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3592. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  3593. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  3594. # self.ui.grb_edit_toolbar.setVisible(False)
  3595. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  3596. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  3597. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3598. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3599. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  3600. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3601. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3602. self.ui.snap_toolbar.setMaximumHeight(30)
  3603. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  3604. self.ui.corner_snap_btn.setVisible(True)
  3605. self.ui.snap_magnet.setVisible(True)
  3606. # add all the actions to the toolbars
  3607. self.ui.populate_toolbars()
  3608. # reconnect all the signals to the toolbar actions
  3609. self.connect_toolbar_signals()
  3610. self.ui.grid_snap_btn.setChecked(True)
  3611. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  3612. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  3613. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  3614. self.ui.grid_gap_link_cb.setChecked(True)
  3615. def on_cnc_custom_parameters(self, signal_text):
  3616. if signal_text == 'Parameters':
  3617. return
  3618. else:
  3619. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  3620. def on_save_button(self):
  3621. self.save_defaults(silent=False)
  3622. # load the defaults so they are updated into the app
  3623. self.load_defaults(filename='current_defaults')
  3624. # Re-fresh project options
  3625. self.on_options_app2project()
  3626. def handlePrint(self):
  3627. self.report_usage("handlePrint()")
  3628. dialog = QtPrintSupport.QPrintDialog()
  3629. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  3630. self.ui.code_editor.document().print_(dialog.printer())
  3631. def handlePreview(self):
  3632. self.report_usage("handlePreview()")
  3633. dialog = QtPrintSupport.QPrintPreviewDialog()
  3634. dialog.paintRequested.connect(self.ui.code_editor.print_)
  3635. dialog.exec_()
  3636. def handleTextChanged(self):
  3637. # enable = not self.ui.code_editor.document().isEmpty()
  3638. # self.ui.buttonPrint.setEnabled(enable)
  3639. # self.ui.buttonPreview.setEnabled(enable)
  3640. pass
  3641. def handleOpen(self, filt=None):
  3642. self.report_usage("handleOpen()")
  3643. if filt:
  3644. _filter_ = filt
  3645. else:
  3646. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3647. "All Files (*.*)"
  3648. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  3649. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  3650. if path:
  3651. file = QtCore.QFile(path)
  3652. if file.open(QtCore.QIODevice.ReadOnly):
  3653. stream = QtCore.QTextStream(file)
  3654. self.gcode_edited = stream.readAll()
  3655. self.ui.code_editor.setPlainText(self.gcode_edited)
  3656. file.close()
  3657. def handleSaveGCode(self, name=None, filt=None):
  3658. self.report_usage("handleSaveGCode()")
  3659. if filt:
  3660. _filter_ = filt
  3661. else:
  3662. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3663. "All Files (*.*)"
  3664. if name:
  3665. obj_name = name
  3666. else:
  3667. try:
  3668. obj_name = self.collection.get_active().options['name']
  3669. except AttributeError:
  3670. obj_name = 'file'
  3671. if filt is None:
  3672. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  3673. try:
  3674. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  3675. caption=_("Export G-Code ..."),
  3676. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  3677. filter=_filter_
  3678. )[0])
  3679. except TypeError:
  3680. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  3681. if filename == "":
  3682. self.inform.emit(_("[WARNING_NOTCL] Export Code cancelled."))
  3683. return
  3684. else:
  3685. try:
  3686. my_gcode = self.ui.code_editor.toPlainText()
  3687. with open(filename, 'w') as f:
  3688. for line in my_gcode:
  3689. f.write(line)
  3690. except FileNotFoundError:
  3691. self.inform.emit(_("[WARNING] No such file or directory"))
  3692. return
  3693. # Just for adding it to the recent files list.
  3694. if self.defaults["global_open_style"] is False:
  3695. self.file_opened.emit("cncjob", filename)
  3696. self.file_saved.emit("cncjob", filename)
  3697. self.inform.emit(_("Saved to: %s") % filename)
  3698. def handleFindGCode(self):
  3699. self.report_usage("handleFindGCode()")
  3700. flags = QtGui.QTextDocument.FindCaseSensitively
  3701. text_to_be_found = self.ui.entryFind.get_value()
  3702. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  3703. if r is False:
  3704. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3705. def handleReplaceGCode(self):
  3706. self.report_usage("handleReplaceGCode()")
  3707. old = self.ui.entryFind.get_value()
  3708. new = self.ui.entryReplace.get_value()
  3709. if self.ui.sel_all_cb.isChecked():
  3710. while True:
  3711. cursor = self.ui.code_editor.textCursor()
  3712. cursor.beginEditBlock()
  3713. flags = QtGui.QTextDocument.FindCaseSensitively
  3714. # self.ui.editor is the QPlainTextEdit
  3715. r = self.ui.code_editor.find(str(old), flags)
  3716. if r:
  3717. qc = self.ui.code_editor.textCursor()
  3718. if qc.hasSelection():
  3719. qc.insertText(new)
  3720. else:
  3721. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3722. break
  3723. # Mark end of undo block
  3724. cursor.endEditBlock()
  3725. else:
  3726. cursor = self.ui.code_editor.textCursor()
  3727. cursor.beginEditBlock()
  3728. qc = self.ui.code_editor.textCursor()
  3729. if qc.hasSelection():
  3730. qc.insertText(new)
  3731. # Mark end of undo block
  3732. cursor.endEditBlock()
  3733. def on_tool_add_keypress(self):
  3734. # ## Current application units in Upper Case
  3735. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3736. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3737. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3738. if notebook_widget_name == 'selected_tab':
  3739. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3740. # Tool add works for Geometry only if Advanced is True in Preferences
  3741. if self.defaults["global_app_level"] == 'a':
  3742. tool_add_popup = FCInputDialog(title="New Tool ...",
  3743. text='Enter a Tool Diameter:',
  3744. min=0.0000, max=99.9999, decimals=4)
  3745. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3746. val, ok = tool_add_popup.get_value()
  3747. if ok:
  3748. if float(val) == 0:
  3749. self.inform.emit(
  3750. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3751. return
  3752. self.collection.get_active().on_tool_add(dia=float(val))
  3753. else:
  3754. self.inform.emit(
  3755. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3756. else:
  3757. msgbox = QtWidgets.QMessageBox()
  3758. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3759. "Go to Preferences -> General - Show Advanced Options."))
  3760. msgbox.setWindowTitle("Tool adding ...")
  3761. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  3762. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3763. msgbox.setDefaultButton(bt_ok)
  3764. msgbox.exec_()
  3765. # work only if the notebook tab on focus is the Tools_Tab
  3766. if notebook_widget_name == 'tool_tab':
  3767. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3768. tool_add_popup = FCInputDialog(title="New Tool ...",
  3769. text='Enter a Tool Diameter:',
  3770. min=0.0000, max=99.9999, decimals=4)
  3771. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3772. val, ok = tool_add_popup.get_value()
  3773. # and only if the tool is NCC Tool
  3774. if tool_widget == self.ncclear_tool.toolName:
  3775. if ok:
  3776. if float(val) == 0:
  3777. self.inform.emit(
  3778. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3779. return
  3780. self.ncclear_tool.on_tool_add(dia=float(val))
  3781. else:
  3782. self.inform.emit(
  3783. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3784. # and only if the tool is Paint Area Tool
  3785. elif tool_widget == self.paint_tool.toolName:
  3786. if ok:
  3787. if float(val) == 0:
  3788. self.inform.emit(
  3789. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3790. return
  3791. self.paint_tool.on_tool_add(dia=float(val))
  3792. else:
  3793. self.inform.emit(
  3794. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3795. # and only if the tool is Solder Paste Dispensing Tool
  3796. elif tool_widget == self.paste_tool.toolName:
  3797. if ok:
  3798. if float(val) == 0:
  3799. self.inform.emit(
  3800. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3801. return
  3802. self.paste_tool.on_tool_add(dia=float(val))
  3803. else:
  3804. self.inform.emit(
  3805. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3806. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3807. # See description bellow.
  3808. def on_delete_keypress(self):
  3809. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3810. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3811. if notebook_widget_name == 'selected_tab':
  3812. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3813. self.collection.get_active().on_tool_delete()
  3814. # work only if the notebook tab on focus is the Tools_Tab
  3815. elif notebook_widget_name == 'tool_tab':
  3816. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3817. # and only if the tool is NCC Tool
  3818. if tool_widget == self.ncclear_tool.toolName:
  3819. self.ncclear_tool.on_tool_delete()
  3820. # and only if the tool is Paint Tool
  3821. elif tool_widget == self.paint_tool.toolName:
  3822. self.paint_tool.on_tool_delete()
  3823. # and only if the tool is Solder Paste Dispensing Tool
  3824. elif tool_widget == self.paste_tool.toolName:
  3825. self.paste_tool.on_tool_delete()
  3826. else:
  3827. self.on_delete()
  3828. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3829. # some screens you have to be careful where you hover with your mouse.
  3830. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3831. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3832. # Complicated, I know :)
  3833. def on_delete(self):
  3834. """
  3835. Delete the currently selected FlatCAMObjs.
  3836. :return: None
  3837. """
  3838. self.report_usage("on_delete()")
  3839. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3840. # a geometry object before we update it.
  3841. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  3842. if self.collection.get_active():
  3843. self.log.debug("on_delete()")
  3844. self.report_usage("on_delete")
  3845. while (self.collection.get_active()):
  3846. obj_active = self.collection.get_active()
  3847. # if the deleted object is FlatCAMGerber then make sure to delete the possbile mark shapes
  3848. if isinstance(obj_active, FlatCAMGerber):
  3849. for el in obj_active.mark_shapes:
  3850. obj_active.mark_shapes[el].clear(update=True)
  3851. obj_active.mark_shapes[el].enabled = False
  3852. obj_active.mark_shapes[el] = None
  3853. self.delete_first_selected()
  3854. self.inform.emit(_("Object(s) deleted ..."))
  3855. # make sure that the selection shape is deleted, too
  3856. self.delete_selection_shape()
  3857. else:
  3858. self.inform.emit(_("Failed. No object(s) selected..."))
  3859. else:
  3860. self.inform.emit(_("Save the work in Editor and try again ..."))
  3861. def on_set_origin(self):
  3862. """
  3863. Set the origin to the left mouse click position
  3864. :return: None
  3865. """
  3866. # display the message for the user
  3867. # and ask him to click on the desired position
  3868. self.report_usage("on_set_origin()")
  3869. self.inform.emit(_('Click to set the origin ...'))
  3870. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  3871. def on_jump_to(self, custom_location=None, fit_center=True):
  3872. """
  3873. Jump to a location by setting the mouse cursor location
  3874. :return:
  3875. """
  3876. self.report_usage("on_jump_to()")
  3877. if not custom_location:
  3878. dia_box = Dialog_box(title=_("Jump to ..."),
  3879. label=_("Enter the coordinates in format X,Y:"),
  3880. icon=QtGui.QIcon('share/jump_to16.png'))
  3881. if dia_box.ok is True:
  3882. try:
  3883. location = eval(dia_box.location)
  3884. if not isinstance(location, tuple):
  3885. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3886. return
  3887. except:
  3888. return
  3889. else:
  3890. return
  3891. else:
  3892. location = custom_location
  3893. if fit_center:
  3894. self.plotcanvas.fit_center(loc=location)
  3895. cursor = QtGui.QCursor()
  3896. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3897. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  3898. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  3899. self.inform.emit(_("[success] Done."))
  3900. def on_copy_object(self):
  3901. self.report_usage("on_copy_object()")
  3902. def initialize(obj_init, app):
  3903. obj_init.solid_geometry = obj.solid_geometry
  3904. try:
  3905. obj_init.follow_geometry = obj.follow_geometry
  3906. except AttributeError:
  3907. pass
  3908. try:
  3909. obj_init.apertures = obj.apertures
  3910. except AttributeError:
  3911. pass
  3912. try:
  3913. if obj.tools:
  3914. obj_init.tools = obj.tools
  3915. except Exception as e:
  3916. log.debug("App.on_copy_object() --> %s" % str(e))
  3917. def initialize_excellon(obj_init, app):
  3918. obj_init.tools = obj.tools
  3919. # drills are offset, so they need to be deep copied
  3920. obj_init.drills = deepcopy(obj.drills)
  3921. # slots are offset, so they need to be deep copied
  3922. obj_init.slots = deepcopy(obj.slots)
  3923. obj_init.create_geometry()
  3924. for obj in self.collection.get_selected():
  3925. obj_name = obj.options["name"]
  3926. try:
  3927. if isinstance(obj, FlatCAMExcellon):
  3928. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3929. elif isinstance(obj,FlatCAMGerber):
  3930. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  3931. elif isinstance(obj,FlatCAMGeometry):
  3932. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  3933. except Exception as e:
  3934. return "Operation failed: %s" % str(e)
  3935. def on_copy_object2(self, custom_name):
  3936. def initialize_geometry(obj_init, app):
  3937. obj_init.solid_geometry = obj.solid_geometry
  3938. try:
  3939. obj_init.follow_geometry = obj.follow_geometry
  3940. except AttributeError:
  3941. pass
  3942. try:
  3943. obj_init.apertures = obj.apertures
  3944. except AttributeError:
  3945. pass
  3946. try:
  3947. if obj.tools:
  3948. obj_init.tools = obj.tools
  3949. except Exception as e:
  3950. log.debug("on_copy_object2() --> %s" % str(e))
  3951. def initialize_gerber(obj_init, app):
  3952. obj_init.solid_geometry = obj.solid_geometry
  3953. obj_init.apertures = deepcopy(obj.apertures)
  3954. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3955. def initialize_excellon(obj_init, app):
  3956. obj_init.tools = obj.tools
  3957. # drills are offset, so they need to be deep copied
  3958. obj_init.drills = deepcopy(obj.drills)
  3959. # slots are offset, so they need to be deep copied
  3960. obj_init.slots = deepcopy(obj.slots)
  3961. obj_init.create_geometry()
  3962. for obj in self.collection.get_selected():
  3963. obj_name = obj.options["name"]
  3964. try:
  3965. if isinstance(obj, FlatCAMExcellon):
  3966. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  3967. elif isinstance(obj,FlatCAMGerber):
  3968. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  3969. elif isinstance(obj,FlatCAMGeometry):
  3970. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  3971. except Exception as e:
  3972. return "Operation failed: %s" % str(e)
  3973. def on_rename_object(self, text):
  3974. self.report_usage("on_rename_object()")
  3975. named_obj = self.collection.get_active()
  3976. for obj in named_obj:
  3977. if obj is list:
  3978. self.on_rename_object(text)
  3979. else:
  3980. try:
  3981. obj.options['name'] = text
  3982. except Exception as e:
  3983. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  3984. def convert_any2geo(self):
  3985. self.report_usage("convert_any2geo()")
  3986. def initialize(obj_init, app):
  3987. obj_init.solid_geometry = obj.solid_geometry
  3988. try:
  3989. obj_init.follow_geometry = obj.follow_geometry
  3990. except AttributeError:
  3991. pass
  3992. try:
  3993. obj_init.apertures = obj.apertures
  3994. except AttributeError:
  3995. pass
  3996. try:
  3997. if obj.tools:
  3998. obj_init.tools = obj.tools
  3999. except AttributeError:
  4000. pass
  4001. def initialize_excellon(obj_init, app):
  4002. # objs = self.collection.get_selected()
  4003. # FlatCAMGeometry.merge(objs, obj)
  4004. solid_geo = []
  4005. for tool in obj.tools:
  4006. for geo in obj.tools[tool]['solid_geometry']:
  4007. solid_geo.append(geo)
  4008. obj_init.solid_geometry = deepcopy(solid_geo)
  4009. if not self.collection.get_selected():
  4010. log.warning("App.convert_any2geo --> No object selected")
  4011. self.inform.emit(_("[WARNING_NOTCL] No object is selected. Select an object and try again."))
  4012. return
  4013. for obj in self.collection.get_selected():
  4014. obj_name = obj.options["name"]
  4015. try:
  4016. if isinstance(obj, FlatCAMExcellon):
  4017. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4018. else:
  4019. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4020. except Exception as e:
  4021. return "Operation failed: %s" % str(e)
  4022. def convert_any2gerber(self):
  4023. self.report_usage("convert_any2gerber()")
  4024. def initialize_geometry(obj_init, app):
  4025. apertures = {}
  4026. apid = 0
  4027. apertures[str(apid)] = {}
  4028. apertures[str(apid)]['geometry'] = []
  4029. for obj_orig in obj.solid_geometry:
  4030. new_elem = dict()
  4031. new_elem['solid'] = obj_orig
  4032. new_elem['follow'] = obj_orig.exterior
  4033. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4034. apertures[str(apid)]['size'] = 0.0
  4035. apertures[str(apid)]['type'] = 'C'
  4036. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4037. obj_init.apertures = deepcopy(apertures)
  4038. def initialize_excellon(obj_init, app):
  4039. apertures = {}
  4040. apid = 10
  4041. for tool in obj.tools:
  4042. apertures[str(apid)] = {}
  4043. apertures[str(apid)]['geometry'] = []
  4044. for geo in obj.tools[tool]['solid_geometry']:
  4045. new_el = dict()
  4046. new_el['solid'] = geo
  4047. new_el['follow'] = geo.exterior
  4048. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4049. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4050. apertures[str(apid)]['type'] = 'C'
  4051. apid += 1
  4052. # create solid_geometry
  4053. solid_geometry = []
  4054. for apid in apertures:
  4055. for geo_el in apertures[apid]['geometry']:
  4056. solid_geometry.append(geo_el['solid'])
  4057. solid_geometry = MultiPolygon(solid_geometry)
  4058. solid_geometry = solid_geometry.buffer(0.0000001)
  4059. obj_init.solid_geometry = deepcopy(solid_geometry)
  4060. obj_init.apertures = deepcopy(apertures)
  4061. # clear the working objects (perhaps not necessary due of Python GC)
  4062. apertures.clear()
  4063. if not self.collection.get_selected():
  4064. log.warning("App.convert_any2gerber --> No object selected")
  4065. self.inform.emit(_("[WARNING_NOTCL] No object is selected. Select an object and try again."))
  4066. return
  4067. for obj in self.collection.get_selected():
  4068. obj_name = obj.options["name"]
  4069. try:
  4070. if isinstance(obj, FlatCAMExcellon):
  4071. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4072. elif isinstance(obj, FlatCAMGeometry):
  4073. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4074. else:
  4075. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4076. except Exception as e:
  4077. return "Operation failed: %s" % str(e)
  4078. def on_set_zero_click(self, event):
  4079. #this function will be available only for mouse left click
  4080. pos =[]
  4081. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4082. if event.button == 1:
  4083. if self.grid_status() == True:
  4084. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4085. else:
  4086. pos = pos_canvas
  4087. x = 0 - pos[0]
  4088. y = 0 - pos[1]
  4089. for obj in self.collection.get_list():
  4090. obj.offset((x,y))
  4091. self.object_changed.emit(obj)
  4092. obj.plot()
  4093. # Update the object bounding box options
  4094. a, b, c, d = obj.bounds()
  4095. obj.options['xmin'] = a
  4096. obj.options['ymin'] = b
  4097. obj.options['xmax'] = c
  4098. obj.options['ymax'] = d
  4099. # self.plot_all(zoom=False)
  4100. self.inform.emit(_('[success] Origin set ...'))
  4101. self.plotcanvas.fit_view()
  4102. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  4103. self.should_we_save = True
  4104. def on_selectall(self):
  4105. self.report_usage("on_selectall()")
  4106. # delete the possible selection box around a possible selected object
  4107. self.delete_selection_shape()
  4108. for name in self.collection.get_names():
  4109. self.collection.set_active(name)
  4110. curr_sel_obj = self.collection.get_by_name(name)
  4111. # create the selection box around the selected object
  4112. if self.defaults['global_selection_shape'] is True:
  4113. self.draw_selection_shape(curr_sel_obj)
  4114. def on_preferences(self):
  4115. # add the tab if it was closed
  4116. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4117. # delete the absolute and relative position and messages in the infobar
  4118. self.ui.position_label.setText("")
  4119. self.ui.rel_position_label.setText("")
  4120. # Switch plot_area to preferences page
  4121. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4122. self.ui.show()
  4123. def on_flipy(self):
  4124. self.report_usage("on_flipy()")
  4125. obj_list = self.collection.get_selected()
  4126. xminlist = []
  4127. yminlist = []
  4128. xmaxlist = []
  4129. ymaxlist = []
  4130. if not obj_list:
  4131. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on Y axis."))
  4132. else:
  4133. try:
  4134. # first get a bounding box to fit all
  4135. for obj in obj_list:
  4136. xmin, ymin, xmax, ymax = obj.bounds()
  4137. xminlist.append(xmin)
  4138. yminlist.append(ymin)
  4139. xmaxlist.append(xmax)
  4140. ymaxlist.append(ymax)
  4141. # get the minimum x,y and maximum x,y for all objects selected
  4142. xminimal = min(xminlist)
  4143. yminimal = min(yminlist)
  4144. xmaximal = max(xmaxlist)
  4145. ymaximal = max(ymaxlist)
  4146. px = 0.5 * (xminimal + xmaximal)
  4147. py = 0.5 * (yminimal + ymaximal)
  4148. # execute mirroring
  4149. for obj in obj_list:
  4150. obj.mirror('X', [px, py])
  4151. obj.plot()
  4152. self.object_changed.emit(obj)
  4153. self.inform.emit(_("[success] Flip on Y axis done."))
  4154. except Exception as e:
  4155. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  4156. return
  4157. def on_flipx(self):
  4158. self.report_usage("on_flipx()")
  4159. obj_list = self.collection.get_selected()
  4160. xminlist = []
  4161. yminlist = []
  4162. xmaxlist = []
  4163. ymaxlist = []
  4164. if not obj_list:
  4165. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on X axis."))
  4166. else:
  4167. try:
  4168. # first get a bounding box to fit all
  4169. for obj in obj_list:
  4170. xmin, ymin, xmax, ymax = obj.bounds()
  4171. xminlist.append(xmin)
  4172. yminlist.append(ymin)
  4173. xmaxlist.append(xmax)
  4174. ymaxlist.append(ymax)
  4175. # get the minimum x,y and maximum x,y for all objects selected
  4176. xminimal = min(xminlist)
  4177. yminimal = min(yminlist)
  4178. xmaximal = max(xmaxlist)
  4179. ymaximal = max(ymaxlist)
  4180. px = 0.5 * (xminimal + xmaximal)
  4181. py = 0.5 * (yminimal + ymaximal)
  4182. # execute mirroring
  4183. for obj in obj_list:
  4184. obj.mirror('Y', [px, py])
  4185. obj.plot()
  4186. self.object_changed.emit(obj)
  4187. self.inform.emit(_("[success] Flip on X axis done."))
  4188. except Exception as e:
  4189. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  4190. return
  4191. def on_rotate(self, silent=False, preset=None):
  4192. self.report_usage("on_rotate()")
  4193. obj_list = self.collection.get_selected()
  4194. xminlist = []
  4195. yminlist = []
  4196. xmaxlist = []
  4197. ymaxlist = []
  4198. if not obj_list:
  4199. self.inform.emit(_("[WARNING_NOTCL] No object selected to Rotate."))
  4200. else:
  4201. if silent is False:
  4202. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4203. min=-360, max=360, decimals=4,
  4204. init_val=float(self.defaults['tools_transform_rotate']))
  4205. num, ok = rotatebox.get_value()
  4206. else:
  4207. num = preset
  4208. ok = True
  4209. if ok:
  4210. try:
  4211. # first get a bounding box to fit all
  4212. for obj in obj_list:
  4213. xmin, ymin, xmax, ymax = obj.bounds()
  4214. xminlist.append(xmin)
  4215. yminlist.append(ymin)
  4216. xmaxlist.append(xmax)
  4217. ymaxlist.append(ymax)
  4218. # get the minimum x,y and maximum x,y for all objects selected
  4219. xminimal = min(xminlist)
  4220. yminimal = min(yminlist)
  4221. xmaximal = max(xmaxlist)
  4222. ymaximal = max(ymaxlist)
  4223. px = 0.5 * (xminimal + xmaximal)
  4224. py = 0.5 * (yminimal + ymaximal)
  4225. for sel_obj in obj_list:
  4226. sel_obj.rotate(-float(num), point=(px, py))
  4227. sel_obj.plot()
  4228. self.object_changed.emit(sel_obj)
  4229. self.inform.emit(_("[success] Rotation done."))
  4230. except Exception as e:
  4231. self.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  4232. return
  4233. def on_skewx(self):
  4234. self.report_usage("on_skewx()")
  4235. obj_list = self.collection.get_selected()
  4236. xminlist = []
  4237. yminlist = []
  4238. if not obj_list:
  4239. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on X axis."))
  4240. else:
  4241. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4242. min=-360, max=360, decimals=4,
  4243. init_val=float(self.defaults['tools_transform_skew_x']))
  4244. num, ok = skewxbox.get_value()
  4245. if ok:
  4246. # first get a bounding box to fit all
  4247. for obj in obj_list:
  4248. xmin, ymin, xmax, ymax = obj.bounds()
  4249. xminlist.append(xmin)
  4250. yminlist.append(ymin)
  4251. # get the minimum x,y and maximum x,y for all objects selected
  4252. xminimal = min(xminlist)
  4253. yminimal = min(yminlist)
  4254. for obj in obj_list:
  4255. obj.skew(num, 0, point=(xminimal, yminimal))
  4256. obj.plot()
  4257. self.object_changed.emit(obj)
  4258. self.inform.emit(_("[success] Skew on X axis done."))
  4259. def on_skewy(self):
  4260. self.report_usage("on_skewy()")
  4261. obj_list = self.collection.get_selected()
  4262. xminlist = []
  4263. yminlist = []
  4264. if not obj_list:
  4265. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on Y axis."))
  4266. else:
  4267. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4268. min=-360, max=360, decimals=4,
  4269. init_val=float(self.defaults['tools_transform_skew_y']))
  4270. num, ok = skewybox.get_value()
  4271. if ok:
  4272. # first get a bounding box to fit all
  4273. for obj in obj_list:
  4274. xmin, ymin, xmax, ymax = obj.bounds()
  4275. xminlist.append(xmin)
  4276. yminlist.append(ymin)
  4277. # get the minimum x,y and maximum x,y for all objects selected
  4278. xminimal = min(xminlist)
  4279. yminimal = min(yminlist)
  4280. for obj in obj_list:
  4281. obj.skew(0, num, point=(xminimal, yminimal))
  4282. obj.plot()
  4283. self.object_changed.emit(obj)
  4284. self.inform.emit(_("[success] Skew on Y axis done."))
  4285. def delete_first_selected(self):
  4286. # Keep this for later
  4287. try:
  4288. name = self.collection.get_active().options["name"]
  4289. except AttributeError:
  4290. self.log.debug("Nothing selected for deletion")
  4291. return
  4292. # Remove plot
  4293. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4294. # self.plotcanvas.auto_adjust_axes()
  4295. # Clear form
  4296. self.setup_component_editor()
  4297. # Remove from dictionary
  4298. self.collection.delete_active()
  4299. self.inform.emit("Object deleted: %s" % name)
  4300. def on_plots_updated(self):
  4301. """
  4302. Callback used to report when the plots have changed.
  4303. Adjust axes and zooms to fit.
  4304. :return: None
  4305. """
  4306. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  4307. self.on_zoom_fit(None)
  4308. self.collection.update_view()
  4309. # TODO: Rework toolbar 'clear', 'replot' functions
  4310. def on_toolbar_replot(self):
  4311. """
  4312. Callback for toolbar button. Re-plots all objects.
  4313. :return: None
  4314. """
  4315. self.report_usage("on_toolbar_replot")
  4316. self.log.debug("on_toolbar_replot()")
  4317. try:
  4318. self.collection.get_active().read_form()
  4319. except AttributeError:
  4320. self.log.debug("on_toolbar_replot(): AttributeError")
  4321. pass
  4322. self.plot_all()
  4323. def on_row_activated(self, index):
  4324. if index.isValid():
  4325. if index.internalPointer().parent_item != self.collection.root_item:
  4326. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4327. def grid_status(self):
  4328. if self.ui.grid_snap_btn.isChecked():
  4329. return 1
  4330. else:
  4331. return 0
  4332. def populate_cmenu_grids(self):
  4333. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4334. self.ui.cmenu_gridmenu.clear()
  4335. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4336. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  4337. grid_toggle.setCheckable(True)
  4338. if self.grid_status():
  4339. grid_toggle.setChecked(True)
  4340. else:
  4341. grid_toggle.setChecked(False)
  4342. self.ui.cmenu_gridmenu.addSeparator()
  4343. for grid in sorted_list:
  4344. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  4345. action.triggered.connect(self.set_grid)
  4346. self.ui.cmenu_gridmenu.addSeparator()
  4347. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  4348. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  4349. grid_add.triggered.connect(self.on_grid_add)
  4350. grid_delete.triggered.connect(self.on_grid_delete)
  4351. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4352. def set_grid(self):
  4353. self.ui.grid_gap_x_entry.setText(self.sender().text())
  4354. self.ui.grid_gap_y_entry.setText(self.sender().text())
  4355. def on_grid_add(self):
  4356. # ## Current application units in lower Case
  4357. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4358. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4359. text=_('Enter a Grid Value:'),
  4360. min=0.0000, max=99.9999, decimals=4)
  4361. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  4362. val, ok = grid_add_popup.get_value()
  4363. if ok:
  4364. if float(val) == 0:
  4365. self.inform.emit(
  4366. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  4367. return
  4368. else:
  4369. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4370. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4371. self.inform.emit(
  4372. _("[success] New Grid added ..."))
  4373. else:
  4374. self.inform.emit(
  4375. _("[WARNING_NOTCL] Grid already exists ..."))
  4376. else:
  4377. self.inform.emit(
  4378. _("[WARNING_NOTCL] Adding New Grid cancelled ..."))
  4379. def on_grid_delete(self):
  4380. # ## Current application units in lower Case
  4381. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4382. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4383. text='Enter a Grid Value:',
  4384. min=0.0000, max=99.9999, decimals=4)
  4385. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  4386. val, ok = grid_del_popup.get_value()
  4387. if ok:
  4388. if float(val) == 0:
  4389. self.inform.emit(
  4390. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  4391. return
  4392. else:
  4393. try:
  4394. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4395. except ValueError:
  4396. self.inform.emit(
  4397. _("[ERROR_NOTCL] Grid Value does not exist ..."))
  4398. return
  4399. self.inform.emit(
  4400. _("[success] Grid Value deleted ..."))
  4401. else:
  4402. self.inform.emit(
  4403. _("[WARNING_NOTCL] Delete Grid value cancelled ..."))
  4404. def on_shortcut_list(self):
  4405. self.report_usage("on_shortcut_list()")
  4406. # add the tab if it was closed
  4407. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, "Key Shortcut List")
  4408. # delete the absolute and relative position and messages in the infobar
  4409. self.ui.position_label.setText("")
  4410. self.ui.rel_position_label.setText("")
  4411. # Switch plot_area to preferences page
  4412. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4413. self.ui.show()
  4414. def on_select_tab(self, name):
  4415. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4416. if self.ui.splitter.sizes()[0] == 0:
  4417. self.ui.splitter.setSizes([1, 1])
  4418. else:
  4419. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4420. self.ui.splitter.setSizes([0, 1])
  4421. if name == 'project':
  4422. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4423. elif name == 'selected':
  4424. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4425. elif name == 'tool':
  4426. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4427. def on_copy_name(self):
  4428. self.report_usage("on_copy_name()")
  4429. obj = self.collection.get_active()
  4430. try:
  4431. name = obj.options["name"]
  4432. except AttributeError:
  4433. log.debug("on_copy_name() --> No object selected to copy it's name")
  4434. self.inform.emit(_("[WARNING_NOTCL] No object selected to copy it's name"))
  4435. return
  4436. self.clipboard.setText(name)
  4437. self.inform.emit(_("Name copied on clipboard ..."))
  4438. def on_mouse_click_over_plot(self, event):
  4439. """
  4440. Default actions are:
  4441. :param event: Contains information about the event, like which button
  4442. was clicked, the pixel coordinates and the axes coordinates.
  4443. :return: None
  4444. """
  4445. self.pos = []
  4446. # So it can receive key presses
  4447. self.plotcanvas.vispy_canvas.native.setFocus()
  4448. # Set the mouse button for panning
  4449. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  4450. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4451. if self.grid_status() == True:
  4452. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4453. self.app_cursor.enabled = True
  4454. else:
  4455. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4456. self.app_cursor.enabled = False
  4457. try:
  4458. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4459. if event.button == 1:
  4460. # Reset here the relative coordinates so there is a new reference on the click position
  4461. if self.rel_point1 is None:
  4462. self.rel_point1 = self.pos
  4463. else:
  4464. self.rel_point2 = copy(self.rel_point1)
  4465. self.rel_point1 = self.pos
  4466. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  4467. if modifiers == QtCore.Qt.ShiftModifier:
  4468. # do not auto open the Project Tab
  4469. self.click_noproject = True
  4470. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  4471. return
  4472. self.on_mouse_move_over_plot(event, origin_click=True)
  4473. except Exception as e:
  4474. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4475. def on_double_click_over_plot(self, event):
  4476. self.doubleclick = True
  4477. def on_mouse_move_over_plot(self, event, origin_click=None):
  4478. """
  4479. Callback for the mouse motion event over the plot.
  4480. :param event: Contains information about the event.
  4481. :param origin_click
  4482. :return: None
  4483. """
  4484. # So it can receive key presses
  4485. self.plotcanvas.vispy_canvas.native.setFocus()
  4486. self.pos_jump = event.pos
  4487. self.ui.popMenu.mouse_is_panning = False
  4488. if origin_click != True:
  4489. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4490. if event.button == 2 and event.is_dragging == 1:
  4491. self.ui.popMenu.mouse_is_panning = True
  4492. return
  4493. if self.rel_point1 is not None:
  4494. try: # May fail in case mouse not within axes
  4495. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4496. if self.grid_status():
  4497. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4498. self.app_cursor.enabled = True
  4499. # Update cursor
  4500. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  4501. else:
  4502. pos = (pos_canvas[0], pos_canvas[1])
  4503. self.app_cursor.enabled = False
  4504. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4505. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  4506. dx = pos[0] - self.rel_point1[0]
  4507. dy = pos[1] - self.rel_point1[1]
  4508. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4509. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4510. self.mouse = [pos[0], pos[1]]
  4511. # if the mouse is moved and the LMB is clicked then the action is a selection
  4512. if event.is_dragging == 1 and event.button == 1:
  4513. self.delete_selection_shape()
  4514. if dx < 0:
  4515. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4516. face_color=self.defaults['global_alt_sel_fill'])
  4517. self.selection_type = False
  4518. else:
  4519. self.draw_moving_selection_shape(self.pos, pos)
  4520. self.selection_type = True
  4521. # hover effect - enabled in Preferences -> General -> GUI Settings
  4522. if self.defaults['global_hover']:
  4523. for obj in self.collection.get_list():
  4524. try:
  4525. # select the object(s) only if it is enabled (plotted)
  4526. if obj.options['plot']:
  4527. if obj not in self.collection.get_selected():
  4528. poly_obj = Polygon(
  4529. [(obj.options['xmin'], obj.options['ymin']),
  4530. (obj.options['xmax'], obj.options['ymin']),
  4531. (obj.options['xmax'], obj.options['ymax']),
  4532. (obj.options['xmin'], obj.options['ymax'])]
  4533. )
  4534. if Point(pos).within(poly_obj):
  4535. if obj.isHovering is False:
  4536. obj.isHovering = True
  4537. obj.notHovering = True
  4538. # create the selection box around the selected object
  4539. self.draw_hover_shape(obj, color='#d1e0e0')
  4540. else:
  4541. if obj.notHovering is True:
  4542. obj.notHovering = False
  4543. obj.isHovering = False
  4544. self.delete_hover_shape()
  4545. except:
  4546. # the Exception here will happen if we try to select on screen and we have an
  4547. # newly (and empty) just created Geometry or Excellon object that do not have the
  4548. # xmin, xmax, ymin, ymax options.
  4549. # In this case poly_obj creation (see above) will fail
  4550. pass
  4551. except:
  4552. self.ui.position_label.setText("")
  4553. self.ui.rel_position_label.setText("")
  4554. self.mouse = None
  4555. def on_mouse_click_release_over_plot(self, event):
  4556. """
  4557. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  4558. and has been registered in ''self.__init__()''.
  4559. :param event: contains information about the event.
  4560. :return:
  4561. """
  4562. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4563. if self.grid_status():
  4564. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4565. else:
  4566. pos = (pos_canvas[0], pos_canvas[1])
  4567. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4568. # canvas menu
  4569. try:
  4570. if event.button == 2: # right click
  4571. if self.ui.popMenu.mouse_is_panning is False:
  4572. self.cursor = QtGui.QCursor()
  4573. self.populate_cmenu_grids()
  4574. self.ui.popMenu.popup(self.cursor.pos())
  4575. except Exception as e:
  4576. log.warning("Error: %s" % str(e))
  4577. return
  4578. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4579. # selection and then select a type of selection ("enclosing" or "touching")
  4580. try:
  4581. if event.button == 1: # left click
  4582. if self.doubleclick is True:
  4583. self.doubleclick = False
  4584. if self.collection.get_selected():
  4585. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4586. if self.ui.splitter.sizes()[0] == 0:
  4587. self.ui.splitter.setSizes([1, 1])
  4588. # delete the selection shape(S) as it may be in the way
  4589. self.delete_selection_shape()
  4590. self.delete_hover_shape()
  4591. else:
  4592. if self.selection_type is not None:
  4593. self.selection_area_handler(self.pos, pos, self.selection_type)
  4594. self.selection_type = None
  4595. else:
  4596. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4597. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  4598. # deselect, and if it's not selected then it will be selected
  4599. if modifiers == QtCore.Qt.ControlModifier:
  4600. # If there is no active command (self.command_active is None) then we check if we clicked
  4601. # on a object by checking the bounding limits against mouse click position
  4602. if self.command_active is None:
  4603. self.select_objects(key='CTRL')
  4604. self.delete_hover_shape()
  4605. else:
  4606. # If there is no active command (self.command_active is None) then we check if we clicked
  4607. # on a object by checking the bounding limits against mouse click position
  4608. if self.command_active is None:
  4609. self.select_objects()
  4610. self.delete_hover_shape()
  4611. except Exception as e:
  4612. log.warning("Error: %s" % str(e))
  4613. return
  4614. def selection_area_handler(self, start_pos, end_pos, sel_type):
  4615. """
  4616. :param start_pos: mouse position when the selection LMB click was done
  4617. :param end_pos: mouse position when the left mouse button is released
  4618. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4619. :return:
  4620. """
  4621. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4622. self.delete_selection_shape()
  4623. for obj in self.collection.get_list():
  4624. try:
  4625. # select the object(s) only if it is enabled (plotted)
  4626. if obj.options['plot']:
  4627. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  4628. (obj.options['xmax'], obj.options['ymin']),
  4629. (obj.options['xmax'], obj.options['ymax']),
  4630. (obj.options['xmin'], obj.options['ymax'])])
  4631. if sel_type is True:
  4632. if poly_obj.within(poly_selection):
  4633. # create the selection box around the selected object
  4634. if self.defaults['global_selection_shape'] is True:
  4635. self.draw_selection_shape(obj)
  4636. self.collection.set_active(obj.options['name'])
  4637. else:
  4638. if poly_selection.intersects(poly_obj):
  4639. # create the selection box around the selected object
  4640. if self.defaults['global_selection_shape'] is True:
  4641. self.draw_selection_shape(obj)
  4642. self.collection.set_active(obj.options['name'])
  4643. except Exception as e:
  4644. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  4645. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  4646. # In this case poly_obj creation (see above) will fail
  4647. log.debug("App.selection_area_handler() --> %s" % str(e))
  4648. def select_objects(self, key=None):
  4649. # list where we store the overlapped objects under our mouse left click position
  4650. objects_under_the_click_list = []
  4651. # Populate the list with the overlapped objects on the click position
  4652. curr_x, curr_y = self.pos
  4653. for obj in self.all_objects_list:
  4654. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  4655. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  4656. if obj.options['name'] not in objects_under_the_click_list:
  4657. if obj.options['plot']:
  4658. # add objects to the objects_under_the_click list only if the object is plotted
  4659. # (active and not disabled)
  4660. objects_under_the_click_list.append(obj.options['name'])
  4661. try:
  4662. # If there is no element in the overlapped objects list then make everyone inactive
  4663. # because we selected "nothing"
  4664. if not objects_under_the_click_list:
  4665. self.collection.set_all_inactive()
  4666. # delete the possible selection box around a possible selected object
  4667. self.delete_selection_shape()
  4668. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  4669. # only when working on App
  4670. if self.call_source == 'app':
  4671. if self.click_noproject is False:
  4672. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4673. else:
  4674. # restore auto open the Project Tab
  4675. self.click_noproject = False
  4676. # delete any text in the status bar, implicitly the last object name that was selected
  4677. self.inform.emit("")
  4678. else:
  4679. self.call_source = 'app'
  4680. else:
  4681. # case when there is only an object under the click and we toggle it
  4682. if len(objects_under_the_click_list) == 1:
  4683. if self.collection.get_active() is None :
  4684. self.collection.set_active(objects_under_the_click_list[0])
  4685. # create the selection box around the selected object
  4686. curr_sel_obj = self.collection.get_active()
  4687. if self.defaults['global_selection_shape'] is True:
  4688. self.draw_selection_shape(curr_sel_obj)
  4689. # self.inform.emit('[selected] %s: %s selected' %
  4690. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4691. if curr_sel_obj.kind == 'gerber':
  4692. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4693. color='green', name=str(curr_sel_obj.options['name'])))
  4694. elif curr_sel_obj.kind == 'excellon':
  4695. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4696. color='brown', name=str(curr_sel_obj.options['name'])))
  4697. elif curr_sel_obj.kind == 'cncjob':
  4698. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4699. color='blue', name=str(curr_sel_obj.options['name'])))
  4700. elif curr_sel_obj.kind == 'geometry':
  4701. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4702. color='red', name=str(curr_sel_obj.options['name'])))
  4703. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  4704. self.collection.set_all_inactive()
  4705. self.delete_selection_shape()
  4706. self.collection.set_active(objects_under_the_click_list[0])
  4707. # create the selection box around the selected object
  4708. curr_sel_obj = self.collection.get_active()
  4709. if self.defaults['global_selection_shape'] is True:
  4710. self.draw_selection_shape(curr_sel_obj)
  4711. # self.inform.emit('[selected] %s: %s selected' %
  4712. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4713. if curr_sel_obj.kind == 'gerber':
  4714. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4715. color='green', name=str(curr_sel_obj.options['name'])))
  4716. elif curr_sel_obj.kind == 'excellon':
  4717. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4718. color='brown', name=str(curr_sel_obj.options['name'])))
  4719. elif curr_sel_obj.kind == 'cncjob':
  4720. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4721. color='blue', name=str(curr_sel_obj.options['name'])))
  4722. elif curr_sel_obj.kind == 'geometry':
  4723. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4724. color='red', name=str(curr_sel_obj.options['name'])))
  4725. else:
  4726. self.collection.set_all_inactive()
  4727. self.delete_selection_shape()
  4728. if self.call_source == 'app':
  4729. # delete any text in the status bar, implicitly the last object name that was selected
  4730. self.inform.emit("")
  4731. else:
  4732. self.call_source = 'app'
  4733. else:
  4734. # If there is no selected object
  4735. # make active the first element of the overlapped objects list
  4736. if self.collection.get_active() is None:
  4737. self.collection.set_active(objects_under_the_click_list[0])
  4738. name_sel_obj = self.collection.get_active().options['name']
  4739. # In case that there is a selected object but it is not in the overlapped object list
  4740. # make that object inactive and activate the first element in the overlapped object list
  4741. if name_sel_obj not in objects_under_the_click_list:
  4742. self.collection.set_inactive(name_sel_obj)
  4743. name_sel_obj = objects_under_the_click_list[0]
  4744. self.collection.set_active(name_sel_obj)
  4745. else:
  4746. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  4747. self.collection.set_all_inactive()
  4748. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  4749. len(objects_under_the_click_list)])
  4750. curr_sel_obj = self.collection.get_active()
  4751. # delete the possible selection box around a possible selected object
  4752. self.delete_selection_shape()
  4753. # create the selection box around the selected object
  4754. if self.defaults['global_selection_shape'] is True:
  4755. self.draw_selection_shape(curr_sel_obj)
  4756. # self.inform.emit('[selected] %s: %s selected' %
  4757. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4758. if curr_sel_obj.kind == 'gerber':
  4759. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4760. color='green', name=str(curr_sel_obj.options['name'])))
  4761. elif curr_sel_obj.kind == 'excellon':
  4762. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4763. color='brown', name=str(curr_sel_obj.options['name'])))
  4764. elif curr_sel_obj.kind == 'cncjob':
  4765. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4766. color='blue', name=str(curr_sel_obj.options['name'])))
  4767. elif curr_sel_obj.kind == 'geometry':
  4768. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4769. color='red', name=str(curr_sel_obj.options['name'])))
  4770. # for obj in self.collection.get_list():
  4771. # obj.plot()
  4772. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  4773. # TODO: on selected objects change the object colors and do not draw the selection box
  4774. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  4775. except Exception as e:
  4776. log.error("[ERROR] Something went bad. %s" % str(e))
  4777. return
  4778. def delete_hover_shape(self):
  4779. self.hover_shapes.clear()
  4780. self.hover_shapes.redraw()
  4781. def draw_hover_shape(self, sel_obj, color=None):
  4782. """
  4783. :param sel_obj: the object for which the hover shape must be drawn
  4784. :return:
  4785. """
  4786. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  4787. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  4788. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  4789. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  4790. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  4791. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4792. hover_rect = hover_rect.buffer(-0.1)
  4793. hover_rect = hover_rect.buffer(0.2)
  4794. else:
  4795. hover_rect = hover_rect.buffer(-0.00393)
  4796. hover_rect = hover_rect.buffer(0.00787)
  4797. if color:
  4798. face = Color(color)
  4799. face.alpha = 0.2
  4800. outline = Color(color, alpha=0.8)
  4801. else:
  4802. face = Color(self.defaults['global_sel_fill'])
  4803. face.alpha = 0.2
  4804. outline = self.defaults['global_sel_line']
  4805. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  4806. def delete_selection_shape(self):
  4807. self.move_tool.sel_shapes.clear()
  4808. self.move_tool.sel_shapes.redraw()
  4809. def draw_selection_shape(self, sel_obj, color=None):
  4810. """
  4811. :param sel_obj: the object for which the selection shape must be drawn
  4812. :return:
  4813. """
  4814. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  4815. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  4816. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  4817. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  4818. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4819. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4820. sel_rect = sel_rect.buffer(-0.1)
  4821. sel_rect = sel_rect.buffer(0.2)
  4822. else:
  4823. sel_rect = sel_rect.buffer(-0.00393)
  4824. sel_rect = sel_rect.buffer(0.00787)
  4825. if color:
  4826. face = Color(color, alpha=0.2)
  4827. outline = Color(color, alpha=0.8)
  4828. else:
  4829. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  4830. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  4831. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=outline,
  4832. face_color=face, update=True, layer=0, tolerance=None))
  4833. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  4834. """
  4835. :param old_coords: old coordinates
  4836. :param coords: new coordinates
  4837. :return:
  4838. """
  4839. if 'color' in kwargs:
  4840. color = kwargs['color']
  4841. else:
  4842. color = self.defaults['global_sel_line']
  4843. if 'face_color' in kwargs:
  4844. face_color = kwargs['face_color']
  4845. else:
  4846. face_color = self.defaults['global_sel_fill']
  4847. x0, y0 = old_coords
  4848. x1, y1 = coords
  4849. pt1 = (x0, y0)
  4850. pt2 = (x1, y0)
  4851. pt3 = (x1, y1)
  4852. pt4 = (x0, y1)
  4853. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4854. color_t = Color(face_color)
  4855. color_t.alpha = 0.3
  4856. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  4857. layer=0, tolerance=None)
  4858. def on_file_new_click(self):
  4859. if self.collection.get_list() and self.should_we_save:
  4860. msgbox = QtWidgets.QMessageBox()
  4861. # msgbox.setText("<B>Save changes ...</B>")
  4862. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  4863. "Creating a New project will delete them.\n"
  4864. "Do you want to Save the project?"))
  4865. msgbox.setWindowTitle(_("Save changes"))
  4866. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4867. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4868. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4869. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4870. msgbox.setDefaultButton(bt_yes)
  4871. msgbox.exec_()
  4872. response = msgbox.clickedButton()
  4873. if response == bt_yes:
  4874. self.on_file_saveprojectas()
  4875. elif response == bt_cancel:
  4876. return
  4877. elif response == bt_no:
  4878. self.on_file_new()
  4879. else:
  4880. self.on_file_new()
  4881. self.inform.emit(_("[success] New Project created..."))
  4882. def on_file_new(self):
  4883. """
  4884. Callback for menu item File->New. Returns the application to its
  4885. startup state. This method is thread-safe.
  4886. :return: None
  4887. """
  4888. self.report_usage("on_file_new")
  4889. # Remove everything from memory
  4890. App.log.debug("on_file_new()")
  4891. if self.call_source != 'app':
  4892. self.editor2object(cleanup=True)
  4893. # ## EDITOR section
  4894. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  4895. self.exc_editor = FlatCAMExcEditor(self)
  4896. self.grb_editor = FlatCAMGrbEditor(self)
  4897. # Clear pool
  4898. self.clear_pool()
  4899. #delete shapes left drawn from mark shape_collections, if any
  4900. for obj in self.collection.get_list():
  4901. try:
  4902. obj.mark_shapes.enabled = False
  4903. obj.mark_shapes.clear(update=True)
  4904. except:
  4905. pass
  4906. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  4907. self.init_tcl()
  4908. self.delete_selection_shape()
  4909. self.collection.delete_all()
  4910. self.setup_component_editor()
  4911. # Clear project filename
  4912. self.project_filename = None
  4913. # Load the application defaults
  4914. self.load_defaults(filename='current_defaults')
  4915. # Re-fresh project options
  4916. self.on_options_app2project()
  4917. # Init Tools
  4918. self.init_tools()
  4919. # Close any Tabs opened in the Plot Tab Area section
  4920. for index in range(self.ui.plot_tab_area.count()):
  4921. self.ui.plot_tab_area.closeTab(index)
  4922. # for whatever reason previous command does not close the last tab so I do it manually
  4923. self.ui.plot_tab_area.closeTab(0)
  4924. # # And then add again the Plot Area
  4925. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4926. self.ui.plot_tab_area.protectTab(0)
  4927. # take the focus of the Notebook on Project Tab.
  4928. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4929. def obj_properties(self):
  4930. self.report_usage("obj_properties()")
  4931. self.properties_tool.run(toggle=False)
  4932. def on_project_context_save(self):
  4933. obj = self.collection.get_active()
  4934. if type(obj) == FlatCAMGeometry:
  4935. self.on_file_exportdxf()
  4936. elif type(obj) == FlatCAMExcellon:
  4937. self.on_file_saveexcellon()
  4938. elif type(obj) == FlatCAMCNCjob:
  4939. obj.on_exportgcode_button_click()
  4940. elif type(obj) == FlatCAMGerber:
  4941. self.on_file_savegerber()
  4942. def obj_move(self):
  4943. self.report_usage("obj_move()")
  4944. self.move_tool.run(toggle=False)
  4945. def on_fileopengerber(self):
  4946. """
  4947. File menu callback for opening a Gerber.
  4948. :return: None
  4949. """
  4950. self.report_usage("on_fileopengerber")
  4951. App.log.debug("on_fileopengerber()")
  4952. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  4953. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  4954. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  4955. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  4956. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  4957. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  4958. "Allegro Files (*.art);;" \
  4959. "Mentor Files (*.pho *.gdo);;" \
  4960. "All Files (*.*)"
  4961. try:
  4962. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  4963. directory=self.get_last_folder(), filter=_filter_)
  4964. except TypeError:
  4965. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  4966. filenames = [str(filename) for filename in filenames]
  4967. if len(filenames) == 0:
  4968. self.inform.emit(_("[WARNING_NOTCL] Open Gerber cancelled."))
  4969. else:
  4970. for filename in filenames:
  4971. if filename != '':
  4972. self.worker_task.emit({'fcn': self.open_gerber,
  4973. 'params': [filename]})
  4974. def on_fileopenexcellon(self):
  4975. """
  4976. File menu callback for opening an Excellon file.
  4977. :return: None
  4978. """
  4979. self.report_usage("on_fileopenexcellon")
  4980. App.log.debug("on_fileopenexcellon()")
  4981. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  4982. "All Files (*.*)"
  4983. try:
  4984. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  4985. directory=self.get_last_folder(), filter=_filter_)
  4986. except TypeError:
  4987. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  4988. filenames = [str(filename) for filename in filenames]
  4989. if len(filenames) == 0:
  4990. self.inform.emit(_("[WARNING_NOTCL] Open Excellon cancelled."))
  4991. else:
  4992. for filename in filenames:
  4993. if filename != '':
  4994. self.worker_task.emit({'fcn': self.open_excellon,
  4995. 'params': [filename]})
  4996. def on_fileopengcode(self):
  4997. """
  4998. File menu call back for opening gcode.
  4999. :return: None
  5000. """
  5001. self.report_usage("on_fileopengcode")
  5002. App.log.debug("on_fileopengcode()")
  5003. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5004. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5005. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  5006. "All Files (*.*)"
  5007. try:
  5008. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5009. directory=self.get_last_folder(), filter=_filter_)
  5010. except TypeError:
  5011. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5012. filenames = [str(filename) for filename in filenames]
  5013. if len(filenames) == 0:
  5014. self.inform.emit(_("[WARNING_NOTCL] Open G-Code cancelled."))
  5015. else:
  5016. for filename in filenames:
  5017. if filename != '':
  5018. self.worker_task.emit({'fcn': self.open_gcode,
  5019. 'params': [filename]})
  5020. def on_file_openproject(self):
  5021. """
  5022. File menu callback for opening a project.
  5023. :return: None
  5024. """
  5025. self.report_usage("on_file_openproject")
  5026. App.log.debug("on_file_openproject()")
  5027. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5028. try:
  5029. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5030. directory=self.get_last_folder(), filter=_filter_)
  5031. except TypeError:
  5032. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter = _filter_)
  5033. # The Qt methods above will return a QString which can cause problems later.
  5034. # So far json.dump() will fail to serialize it.
  5035. # TODO: Improve the serialization methods and remove this fix.
  5036. filename = str(filename)
  5037. if filename == "":
  5038. self.inform.emit(_("[WARNING_NOTCL] Open Project cancelled."))
  5039. else:
  5040. # self.worker_task.emit({'fcn': self.open_project,
  5041. # 'params': [filename]})
  5042. # The above was failing because open_project() is not
  5043. # thread safe. The new_project()
  5044. self.open_project(filename)
  5045. def on_file_openconfig(self):
  5046. """
  5047. File menu callback for opening a config file.
  5048. :return: None
  5049. """
  5050. self.report_usage("on_file_openconfig")
  5051. App.log.debug("on_file_openconfig()")
  5052. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5053. try:
  5054. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5055. directory=self.data_path, filter=_filter_)
  5056. except TypeError:
  5057. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5058. filter = _filter_)
  5059. if filename == "":
  5060. self.inform.emit(_("[WARNING_NOTCL Open Config cancelled."))
  5061. else:
  5062. self.open_config_file(filename)
  5063. def on_file_exportsvg(self):
  5064. """
  5065. Callback for menu item File->Export SVG.
  5066. :return: None
  5067. """
  5068. self.report_usage("on_file_exportsvg")
  5069. App.log.debug("on_file_exportsvg()")
  5070. obj = self.collection.get_active()
  5071. if obj is None:
  5072. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  5073. msg = _("Please Select a Geometry object to export")
  5074. msgbox = QtWidgets.QMessageBox()
  5075. msgbox.setInformativeText(msg)
  5076. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5077. msgbox.setDefaultButton(bt_ok)
  5078. msgbox.exec_()
  5079. return
  5080. # Check for more compatible types and add as required
  5081. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  5082. and not isinstance(obj, FlatCAMExcellon)):
  5083. msg = _("[ERROR_NOTCL] Only Geometry, Gerber and CNCJob objects can be used.")
  5084. msgbox = QtWidgets.QMessageBox()
  5085. msgbox.setInformativeText(msg)
  5086. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5087. msgbox.setDefaultButton(bt_ok)
  5088. msgbox.exec_()
  5089. return
  5090. name = self.collection.get_active().options["name"]
  5091. filter = "SVG File (*.svg);;All Files (*.*)"
  5092. try:
  5093. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5094. caption=_("Export SVG"),
  5095. directory=self.get_last_save_folder() + '/' + str(name),
  5096. filter=filter)
  5097. except TypeError:
  5098. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=filter)
  5099. filename = str(filename)
  5100. if filename == "":
  5101. self.inform.emit(_("[WARNING_NOTCL] Export SVG cancelled."))
  5102. return
  5103. else:
  5104. self.export_svg(name, filename)
  5105. if self.defaults["global_open_style"] is False:
  5106. self.file_opened.emit("SVG", filename)
  5107. self.file_saved.emit("SVG", filename)
  5108. def on_file_exportpng(self):
  5109. self.report_usage("on_file_exportpng")
  5110. App.log.debug("on_file_exportpng()")
  5111. self.date = str(datetime.today()).rpartition('.')[0]
  5112. self.date = ''.join(c for c in self.date if c not in ':-')
  5113. self.date = self.date.replace(' ', '_')
  5114. image = _screenshot()
  5115. data = np.asarray(image)
  5116. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5117. self.inform.emit(_('[[WARNING_NOTCL]] Data must be a 3D array with last dimension 3 or 4'))
  5118. return
  5119. filter_ = "PNG File (*.png);;All Files (*.*)"
  5120. try:
  5121. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5122. caption=_("Export PNG Image"),
  5123. directory=self.get_last_save_folder() + '/png_' + self.date,
  5124. filter=filter_)
  5125. except TypeError:
  5126. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  5127. filename = str(filename)
  5128. if filename == "":
  5129. self.inform.emit(_("Export PNG cancelled."))
  5130. return
  5131. else:
  5132. write_png(filename, data)
  5133. if self.defaults["global_open_style"] is False:
  5134. self.file_opened.emit("png", filename)
  5135. self.file_saved.emit("png", filename)
  5136. def on_file_savegerber(self):
  5137. """
  5138. Callback for menu item File->Export Gerber.
  5139. :return: None
  5140. """
  5141. self.report_usage("on_file_savegerber")
  5142. App.log.debug("on_file_savegerber()")
  5143. obj = self.collection.get_active()
  5144. if obj is None:
  5145. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Gerber object to export."))
  5146. return
  5147. # Check for more compatible types and add as required
  5148. if not isinstance(obj, FlatCAMGerber):
  5149. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  5150. return
  5151. name = self.collection.get_active().options["name"]
  5152. filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5153. try:
  5154. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5155. caption="Save Gerber source file",
  5156. directory=self.get_last_save_folder() + '/' + name,
  5157. filter=filter)
  5158. except TypeError:
  5159. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=filter)
  5160. filename = str(filename)
  5161. if filename == "":
  5162. self.inform.emit(_("[WARNING_NOTCL] Save Gerber source file cancelled."))
  5163. return
  5164. else:
  5165. self.save_source_file(name, filename)
  5166. if self.defaults["global_open_style"] is False:
  5167. self.file_opened.emit("Gerber", filename)
  5168. self.file_saved.emit("Gerber", filename)
  5169. def on_file_saveexcellon(self):
  5170. """
  5171. Callback for menu item File->Export Gerber.
  5172. :return: None
  5173. """
  5174. self.report_usage("on_file_saveexcellon")
  5175. App.log.debug("on_file_saveexcellon()")
  5176. obj = self.collection.get_active()
  5177. if obj is None:
  5178. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Excellon object to export."))
  5179. return
  5180. # Check for more compatible types and add as required
  5181. if not isinstance(obj, FlatCAMExcellon):
  5182. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  5183. return
  5184. name = self.collection.get_active().options["name"]
  5185. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5186. try:
  5187. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5188. caption=_("Save Excellon source file"),
  5189. directory=self.get_last_save_folder() + '/' + name,
  5190. filter=filter)
  5191. except TypeError:
  5192. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=filter)
  5193. filename = str(filename)
  5194. if filename == "":
  5195. self.inform.emit(_("[WARNING_NOTCL] Saving Excellon source file cancelled."))
  5196. return
  5197. else:
  5198. self.save_source_file(name, filename)
  5199. if self.defaults["global_open_style"] is False:
  5200. self.file_opened.emit("Excellon", filename)
  5201. self.file_saved.emit("Excellon", filename)
  5202. def on_file_exportexcellon(self):
  5203. """
  5204. Callback for menu item File->Export->Excellon.
  5205. :return: None
  5206. """
  5207. self.report_usage("on_file_exportexcellon")
  5208. App.log.debug("on_file_exportexcellon()")
  5209. obj = self.collection.get_active()
  5210. if obj is None:
  5211. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Excellon object to export."))
  5212. return
  5213. # Check for more compatible types and add as required
  5214. if not isinstance(obj, FlatCAMExcellon):
  5215. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  5216. return
  5217. name = self.collection.get_active().options["name"]
  5218. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5219. try:
  5220. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5221. caption=_("Export Excellon"),
  5222. directory=self.get_last_save_folder() + '/' + name,
  5223. filter=filter)
  5224. except TypeError:
  5225. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=filter)
  5226. filename = str(filename)
  5227. if filename == "":
  5228. self.inform.emit(_("[WARNING_NOTCL] Export Excellon cancelled."))
  5229. return
  5230. else:
  5231. self.export_excellon(name, filename)
  5232. if self.defaults["global_open_style"] is False:
  5233. self.file_opened.emit("Excellon", filename)
  5234. self.file_saved.emit("Excellon", filename)
  5235. def on_file_exportgerber(self):
  5236. """
  5237. Callback for menu item File->Export->Gerber.
  5238. :return: None
  5239. """
  5240. self.report_usage("on_file_exportgerber")
  5241. App.log.debug("on_file_exportgerber()")
  5242. obj = self.collection.get_active()
  5243. if obj is None:
  5244. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Gerber object to export."))
  5245. return
  5246. # Check for more compatible types and add as required
  5247. if not isinstance(obj, FlatCAMGerber):
  5248. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  5249. return
  5250. name = self.collection.get_active().options["name"]
  5251. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  5252. try:
  5253. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5254. caption=_("Export Gerber"),
  5255. directory=self.get_last_save_folder() + '/' + name,
  5256. filter=_filter_)
  5257. except TypeError:
  5258. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  5259. filename = str(filename)
  5260. if filename == "":
  5261. self.inform.emit(_("[WARNING_NOTCL] Export Gerber cancelled."))
  5262. return
  5263. else:
  5264. self.export_gerber(name, filename)
  5265. if self.defaults["global_open_style"] is False:
  5266. self.file_opened.emit("Gerber", filename)
  5267. self.file_saved.emit("Gerber", filename)
  5268. def on_file_exportdxf(self):
  5269. """
  5270. Callback for menu item File->Export DXF.
  5271. :return: None
  5272. """
  5273. self.report_usage("on_file_exportdxf")
  5274. App.log.debug("on_file_exportdxf()")
  5275. obj = self.collection.get_active()
  5276. if obj is None:
  5277. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  5278. msg = _("Please Select a Geometry object to export")
  5279. msgbox = QtWidgets.QMessageBox()
  5280. msgbox.setInformativeText(msg)
  5281. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5282. msgbox.setDefaultButton(bt_ok)
  5283. msgbox.exec_()
  5284. return
  5285. # Check for more compatible types and add as required
  5286. if not isinstance(obj, FlatCAMGeometry):
  5287. msg = _("[ERROR_NOTCL] Only Geometry objects can be used.")
  5288. msgbox = QtWidgets.QMessageBox()
  5289. msgbox.setInformativeText(msg)
  5290. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5291. msgbox.setDefaultButton(bt_ok)
  5292. msgbox.exec_()
  5293. return
  5294. name = self.collection.get_active().options["name"]
  5295. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  5296. try:
  5297. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5298. caption=_("Export DXF"),
  5299. directory=self.get_last_save_folder() + '/' + name,
  5300. filter=_filter_)
  5301. except TypeError:
  5302. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  5303. filter=_filter_)
  5304. filename = str(filename)
  5305. if filename == "":
  5306. self.inform.emit(_("[WARNING_NOTCL] Export DXF cancelled."))
  5307. return
  5308. else:
  5309. self.export_dxf(name, filename)
  5310. if self.defaults["global_open_style"] is False:
  5311. self.file_opened.emit("DXF", filename)
  5312. self.file_saved.emit("DXF", filename)
  5313. def on_file_importsvg(self, type_of_obj):
  5314. """
  5315. Callback for menu item File->Import SVG.
  5316. :param type_of_obj: to import the SVG as Geometry or as Gerber
  5317. :type type_of_obj: str
  5318. :return: None
  5319. """
  5320. self.report_usage("on_file_importsvg")
  5321. App.log.debug("on_file_importsvg()")
  5322. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  5323. try:
  5324. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5325. directory=self.get_last_folder(), filter=_filter_)
  5326. except TypeError:
  5327. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5328. filter=_filter_)
  5329. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  5330. type_of_obj = "geometry"
  5331. filenames = [str(filename) for filename in filenames]
  5332. if len(filenames) == 0:
  5333. self.inform.emit(_("[WARNING_NOTCL] Open SVG cancelled."))
  5334. else:
  5335. for filename in filenames:
  5336. if filename != '':
  5337. self.worker_task.emit({'fcn': self.import_svg,
  5338. 'params': [filename, type_of_obj]})
  5339. def on_file_importdxf(self, type_of_obj):
  5340. """
  5341. Callback for menu item File->Import DXF.
  5342. :param type_of_obj: to import the DXF as Geometry or as Gerber
  5343. :type type_of_obj: str
  5344. :return: None
  5345. """
  5346. self.report_usage("on_file_importdxf")
  5347. App.log.debug("on_file_importdxf()")
  5348. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  5349. try:
  5350. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5351. directory=self.get_last_folder(),
  5352. filter=_filter_)
  5353. except TypeError:
  5354. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5355. filter=_filter_)
  5356. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  5357. type_of_obj = "geometry"
  5358. filenames = [str(filename) for filename in filenames]
  5359. if len(filenames) == 0:
  5360. self.inform.emit(_("[WARNING_NOTCL] Open DXF cancelled."))
  5361. else:
  5362. for filename in filenames:
  5363. if filename != '':
  5364. self.worker_task.emit({'fcn': self.import_dxf,
  5365. 'params': [filename, type_of_obj]})
  5366. # ################################################################################################################ ##
  5367. # # ## The following section has the functions that are displayed and call the Editor tab CNCJob Tab ############### ##
  5368. # ################################################################################################################ ##
  5369. def init_code_editor(self, name):
  5370. # Signals section
  5371. # Disconnect the old signals
  5372. self.ui.buttonOpen.clicked.disconnect()
  5373. self.ui.buttonSave.clicked.disconnect()
  5374. # add the tab if it was closed
  5375. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _('%s') % name)
  5376. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  5377. # delete the absolute and relative position and messages in the infobar
  5378. self.ui.position_label.setText("")
  5379. self.ui.rel_position_label.setText("")
  5380. # first clear previous text in text editor (if any)
  5381. self.ui.code_editor.clear()
  5382. self.ui.code_editor.setReadOnly(False)
  5383. self.toggle_codeeditor = True
  5384. self.ui.code_editor.completer_enable = False
  5385. # Switch plot_area to CNCJob tab
  5386. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  5387. def on_view_source(self):
  5388. try:
  5389. obj = self.collection.get_active()
  5390. except:
  5391. self.inform.emit(_("[WARNING_NOTCL] Select an Gerber or Excellon file to view it's source file."))
  5392. return 'fail'
  5393. # then append the text from GCode to the text editor
  5394. try:
  5395. file = StringIO(obj.source_file)
  5396. except AttributeError:
  5397. self.inform.emit(_("[WARNING_NOTCL] There is no selected object for which to see it's source file code."))
  5398. return 'fail'
  5399. if obj.kind == 'gerber':
  5400. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  5401. elif obj.kind == 'excellon':
  5402. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  5403. self.init_code_editor(name=_("Source Editor"))
  5404. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  5405. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  5406. try:
  5407. for line in file:
  5408. proc_line = str(line).strip('\n')
  5409. self.ui.code_editor.append(proc_line)
  5410. except Exception as e:
  5411. log.debug('App.on_view_source() -->%s' % str(e))
  5412. self.inform.emit(_('[ERROR]App.on_view_source() -->%s') % str(e))
  5413. return
  5414. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5415. self.handleTextChanged()
  5416. self.ui.show()
  5417. def on_toggle_code_editor(self):
  5418. self.report_usage("on_toggle_code_editor()")
  5419. if self.toggle_codeeditor is False:
  5420. self.init_code_editor(name=_("Code Editor"))
  5421. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  5422. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  5423. else:
  5424. for idx in range(self.ui.plot_tab_area.count()):
  5425. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  5426. self.ui.plot_tab_area.closeTab(idx)
  5427. break
  5428. self.toggle_codeeditor = False
  5429. def on_filenewscript(self):
  5430. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5431. self.init_code_editor(name=_("Script Editor"))
  5432. self.ui.code_editor.completer_enable = True
  5433. self.ui.code_editor.append(_(
  5434. "#\n"
  5435. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  5436. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  5437. "#\n\n"
  5438. "# FlatCAM commands list:\n"
  5439. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, Cncjob,\n"
  5440. "# Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames, GetSys,\n"
  5441. "# ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillHoles, Mirror, New,\n"
  5442. "# NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject, Options, Paint, Panelize,\n"
  5443. "# Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,SubtractRectangle, Version,\n"
  5444. "# WriteGCode\n"
  5445. "#\n\n"
  5446. ))
  5447. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  5448. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  5449. self.handleTextChanged()
  5450. self.ui.code_editor.show()
  5451. def on_fileopenscript(self):
  5452. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  5453. try:
  5454. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  5455. directory=self.get_last_folder(), filter=_filter_)
  5456. except TypeError:
  5457. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  5458. # The Qt methods above will return a QString which can cause problems later.
  5459. # So far json.dump() will fail to serialize it.
  5460. # TODO: Improve the serialization methods and remove this fix.
  5461. filename = str(filename)
  5462. if filename == "":
  5463. self.inform.emit(_("[WARNING_NOTCL] Open TCL script cancelled."))
  5464. else:
  5465. self.on_filenewscript()
  5466. try:
  5467. with open(filename, "r") as opened_script:
  5468. try:
  5469. for line in opened_script:
  5470. proc_line = str(line).strip('\n')
  5471. self.ui.code_editor.append(proc_line)
  5472. except Exception as e:
  5473. log.debug('App.on_fileopenscript() -->%s' % str(e))
  5474. self.inform.emit(_('[ERROR]App.on_fileopenscript() -->%s') % str(e))
  5475. return
  5476. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5477. self.handleTextChanged()
  5478. self.ui.show()
  5479. except Exception as e:
  5480. log.debug("App.on_fileopenscript() -> %s" % str(e))
  5481. def on_filerunscript(self, name=None):
  5482. """
  5483. File menu callback for loading and running a TCL script.
  5484. :return: None
  5485. """
  5486. self.report_usage("on_filerunscript")
  5487. App.log.debug("on_file_runscript()")
  5488. if name:
  5489. filename = name
  5490. else:
  5491. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  5492. try:
  5493. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  5494. directory=self.get_last_folder(), filter=_filter_)
  5495. except TypeError:
  5496. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  5497. # The Qt methods above will return a QString which can cause problems later.
  5498. # So far json.dump() will fail to serialize it.
  5499. # TODO: Improve the serialization methods and remove this fix.
  5500. filename = str(filename)
  5501. if filename == "":
  5502. self.inform.emit(_("[WARNING_NOTCL] Run TCL script cancelled."))
  5503. else:
  5504. try:
  5505. with open(filename, "r") as tcl_script:
  5506. cmd_line_shellfile_content = tcl_script.read()
  5507. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  5508. except Exception as e:
  5509. log.debug("App.on_filerunscript() -> %s" % str(e))
  5510. sys.exit(2)
  5511. def on_file_saveproject(self):
  5512. """
  5513. Callback for menu item File->Save Project. Saves the project to
  5514. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  5515. if set to None. The project is saved by calling ``self.save_project()``.
  5516. :return: None
  5517. """
  5518. self.report_usage("on_file_saveproject")
  5519. if self.project_filename is None:
  5520. self.on_file_saveprojectas()
  5521. else:
  5522. self.worker_task.emit({'fcn': self.save_project,
  5523. 'params': [self.project_filename]})
  5524. if self.defaults["global_open_style"] is False:
  5525. self.file_opened.emit("project", self.project_filename)
  5526. self.file_saved.emit("project", self.project_filename)
  5527. self.should_we_save = False
  5528. def on_file_saveprojectas(self, make_copy=False, thread=True, quit=False):
  5529. """
  5530. Callback for menu item File->Save Project As... Opens a file
  5531. chooser and saves the project to the given file via
  5532. ``self.save_project()``.
  5533. :return: None
  5534. """
  5535. self.report_usage("on_file_saveprojectas")
  5536. self.date = str(datetime.today()).rpartition('.')[0]
  5537. self.date = ''.join(c for c in self.date if c not in ':-')
  5538. self.date = self.date.replace(' ', '_')
  5539. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  5540. try:
  5541. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5542. caption=_("Save Project As ..."),
  5543. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  5544. filter=filter_)
  5545. except TypeError:
  5546. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  5547. filename = str(filename)
  5548. if filename == '':
  5549. self.inform.emit(_("[WARNING_NOTCL] Save Project cancelled."))
  5550. return
  5551. try:
  5552. f = open(filename, 'r')
  5553. f.close()
  5554. except IOError:
  5555. pass
  5556. if thread is True:
  5557. self.worker_task.emit({'fcn': self.save_project,
  5558. 'params': [filename, quit]})
  5559. else:
  5560. self.save_project(filename, quit)
  5561. # self.save_project(filename)
  5562. if self.defaults["global_open_style"] is False:
  5563. self.file_opened.emit("project", filename)
  5564. self.file_saved.emit("project", filename)
  5565. if not make_copy:
  5566. self.project_filename = filename
  5567. self.should_we_save = False
  5568. def export_svg(self, obj_name, filename, scale_factor=0.00):
  5569. """
  5570. Exports a Geometry Object to an SVG file.
  5571. :param filename: Path to the SVG file to save to.
  5572. :return:
  5573. """
  5574. self.report_usage("export_svg()")
  5575. if filename is None:
  5576. filename = self.defaults["global_last_save_folder"]
  5577. self.log.debug("export_svg()")
  5578. try:
  5579. obj = self.collection.get_by_name(str(obj_name))
  5580. except:
  5581. # TODO: The return behavior has not been established... should raise exception?
  5582. return "Could not retrieve object: %s" % obj_name
  5583. with self.proc_container.new(_("Exporting SVG")) as proc:
  5584. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5585. # Determine bounding area for svg export
  5586. bounds = obj.bounds()
  5587. size = obj.size()
  5588. # Convert everything to strings for use in the xml doc
  5589. svgwidth = str(size[0])
  5590. svgheight = str(size[1])
  5591. minx = str(bounds[0])
  5592. miny = str(bounds[1] - size[1])
  5593. uom = obj.units.lower()
  5594. # Add a SVG Header and footer to the svg output from shapely
  5595. # The transform flips the Y Axis so that everything renders
  5596. # properly within svg apps such as inkscape
  5597. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5598. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5599. svg_header += 'width="' + svgwidth + uom + '" '
  5600. svg_header += 'height="' + svgheight + uom + '" '
  5601. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  5602. svg_header += '<g transform="scale(1,-1)">'
  5603. svg_footer = '</g> </svg>'
  5604. svg_elem = svg_header + exported_svg + svg_footer
  5605. # Parse the xml through a xml parser just to add line feeds
  5606. # and to make it look more pretty for the output
  5607. svgcode = parse_xml_string(svg_elem)
  5608. with open(filename, 'w') as fp:
  5609. fp.write(svgcode.toprettyxml())
  5610. if self.defaults["global_open_style"] is False:
  5611. self.file_opened.emit("SVG", filename)
  5612. self.file_saved.emit("SVG", filename)
  5613. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5614. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  5615. """
  5616. Exports a Geometry Object to an SVG file in negative.
  5617. :param filename: Path to the SVG file to save to.
  5618. :param: use_thread: If True use threads
  5619. :type: Bool
  5620. :return:
  5621. """
  5622. self.report_usage("export_negative()")
  5623. if filename is None:
  5624. filename = self.defaults["global_last_save_folder"]
  5625. self.log.debug("export_svg() negative")
  5626. try:
  5627. obj = self.collection.get_by_name(str(obj_name))
  5628. except:
  5629. # TODO: The return behavior has not been established... should raise exception?
  5630. return "Could not retrieve object: %s" % obj_name
  5631. try:
  5632. box = self.collection.get_by_name(str(box_name))
  5633. except:
  5634. # TODO: The return behavior has not been established... should raise exception?
  5635. return "Could not retrieve object: %s" % box_name
  5636. if box is None:
  5637. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  5638. box = obj
  5639. def make_negative_film():
  5640. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5641. self.progress.emit(40)
  5642. # Determine bounding area for svg export
  5643. bounds = box.bounds()
  5644. size = box.size()
  5645. uom = obj.units.lower()
  5646. # Convert everything to strings for use in the xml doc
  5647. svgwidth = str(size[0] + (2 * boundary))
  5648. svgheight = str(size[1] + (2 * boundary))
  5649. minx = str(bounds[0] - boundary)
  5650. miny = str(bounds[1] + boundary + size[1])
  5651. miny_rect = str(bounds[1] - boundary)
  5652. # Add a SVG Header and footer to the svg output from shapely
  5653. # The transform flips the Y Axis so that everything renders
  5654. # properly within svg apps such as inkscape
  5655. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5656. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5657. svg_header += 'width="' + svgwidth + uom + '" '
  5658. svg_header += 'height="' + svgheight + uom + '" '
  5659. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  5660. svg_header += '>'
  5661. svg_header += '<g transform="scale(1,-1)">'
  5662. svg_footer = '</g> </svg>'
  5663. self.progress.emit(60)
  5664. # Change the attributes of the exported SVG
  5665. # We don't need stroke-width - wrong, we do when we have lines with certain width
  5666. # We set opacity to maximum
  5667. # We set the color to WHITE
  5668. root = ET.fromstring(exported_svg)
  5669. for child in root:
  5670. child.set('fill', '#FFFFFF')
  5671. child.set('opacity', '1.0')
  5672. child.set('stroke', '#FFFFFF')
  5673. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  5674. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  5675. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  5676. first_svg_elem_tag = 'rect'
  5677. first_svg_elem_attribs = {
  5678. 'x': minx,
  5679. 'y': miny_rect,
  5680. 'width': svgwidth,
  5681. 'height': svgheight,
  5682. 'id': 'neg_rect',
  5683. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  5684. }
  5685. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  5686. exported_svg = ET.tostring(root)
  5687. svg_elem = svg_header + str(exported_svg) + svg_footer
  5688. self.progress.emit(80)
  5689. # Parse the xml through a xml parser just to add line feeds
  5690. # and to make it look more pretty for the output
  5691. doc = parse_xml_string(svg_elem)
  5692. with open(filename, 'w') as fp:
  5693. fp.write(doc.toprettyxml())
  5694. self.progress.emit(100)
  5695. if self.defaults["global_open_style"] is False:
  5696. self.file_opened.emit("SVG", filename)
  5697. self.file_saved.emit("SVG", filename)
  5698. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5699. if use_thread is True:
  5700. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  5701. def job_thread_film(app_obj):
  5702. try:
  5703. make_negative_film()
  5704. except Exception as e:
  5705. proc.done()
  5706. return
  5707. proc.done()
  5708. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  5709. else:
  5710. make_negative_film()
  5711. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  5712. """
  5713. Exports a Geometry Object to an SVG file in negative.
  5714. :param filename: Path to the SVG file to save to.
  5715. :param: use_thread: If True use threads
  5716. :type: Bool
  5717. :return:
  5718. """
  5719. self.report_usage("export_svg_black()")
  5720. if filename is None:
  5721. filename = self.defaults["global_last_save_folder"]
  5722. self.log.debug("export_svg() black")
  5723. try:
  5724. obj = self.collection.get_by_name(str(obj_name))
  5725. except:
  5726. # TODO: The return behavior has not been established... should raise exception?
  5727. return "Could not retrieve object: %s" % obj_name
  5728. try:
  5729. box = self.collection.get_by_name(str(box_name))
  5730. except:
  5731. # TODO: The return behavior has not been established... should raise exception?
  5732. return "Could not retrieve object: %s" % box_name
  5733. if box is None:
  5734. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  5735. box = obj
  5736. def make_black_film():
  5737. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5738. self.progress.emit(40)
  5739. # Change the attributes of the exported SVG
  5740. # We don't need stroke-width
  5741. # We set opacity to maximum
  5742. # We set the colour to WHITE
  5743. root = ET.fromstring(exported_svg)
  5744. for child in root:
  5745. child.set('fill', '#000000')
  5746. child.set('opacity', '1.0')
  5747. child.set('stroke', '#000000')
  5748. exported_svg = ET.tostring(root)
  5749. # Determine bounding area for svg export
  5750. bounds = box.bounds()
  5751. size = box.size()
  5752. # This contain the measure units
  5753. uom = obj.units.lower()
  5754. # Define a boundary around SVG of about 1.0mm (~39mils)
  5755. if uom in "mm":
  5756. boundary = 1.0
  5757. else:
  5758. boundary = 0.0393701
  5759. self.progress.emit(80)
  5760. # Convert everything to strings for use in the xml doc
  5761. svgwidth = str(size[0] + (2 * boundary))
  5762. svgheight = str(size[1] + (2 * boundary))
  5763. minx = str(bounds[0] - boundary)
  5764. miny = str(bounds[1] + boundary + size[1])
  5765. self.log.debug(minx)
  5766. self.log.debug(miny)
  5767. # Add a SVG Header and footer to the svg output from shapely
  5768. # The transform flips the Y Axis so that everything renders
  5769. # properly within svg apps such as inkscape
  5770. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5771. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5772. svg_header += 'width="' + svgwidth + uom + '" '
  5773. svg_header += 'height="' + svgheight + uom + '" '
  5774. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  5775. svg_header += '>'
  5776. svg_header += '<g transform="scale(1,-1)">'
  5777. svg_footer = '</g> </svg>'
  5778. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  5779. self.progress.emit(90)
  5780. # Parse the xml through a xml parser just to add line feeds
  5781. # and to make it look more pretty for the output
  5782. doc = parse_xml_string(svg_elem)
  5783. with open(filename, 'w') as fp:
  5784. fp.write(doc.toprettyxml())
  5785. self.progress.emit(100)
  5786. if self.defaults["global_open_style"] is False:
  5787. self.file_opened.emit("SVG", filename)
  5788. self.file_saved.emit("SVG", filename)
  5789. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5790. if use_thread is True:
  5791. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  5792. def job_thread_film(app_obj):
  5793. try:
  5794. make_black_film()
  5795. except Exception as e:
  5796. proc.done()
  5797. return
  5798. proc.done()
  5799. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  5800. else:
  5801. make_black_film()
  5802. def save_source_file(self, obj_name, filename, use_thread=True):
  5803. """
  5804. Exports a Gerber Object to an Gerber file.
  5805. :param filename: Path to the Gerber file to save to.
  5806. :return:
  5807. """
  5808. self.report_usage("save source file()")
  5809. if filename is None:
  5810. filename = self.defaults["global_last_save_folder"]
  5811. self.log.debug("save source file()")
  5812. obj = self.collection.get_by_name(obj_name)
  5813. file_string = StringIO(obj.source_file)
  5814. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5815. with open(filename, 'w') as file:
  5816. file.writelines('G04*\n')
  5817. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  5818. (obj.kind.upper(), str(self.version), str(self.version_date)))
  5819. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  5820. file.writelines('G04 Created on : %s*\n' % time_string)
  5821. for line in file_string:
  5822. file.writelines(line)
  5823. def export_excellon(self, obj_name, filename, use_thread=True):
  5824. """
  5825. Exports a Excellon Object to an Excellon file.
  5826. :param filename: Path to the Excellon file to save to.
  5827. :return:
  5828. """
  5829. self.report_usage("export_excellon()")
  5830. if filename is None:
  5831. filename = self.defaults["global_last_save_folder"]
  5832. self.log.debug("export_excellon()")
  5833. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  5834. self.defaults["excellon_exp_decimals"]
  5835. )
  5836. units = ''
  5837. try:
  5838. obj = self.collection.get_by_name(str(obj_name))
  5839. except:
  5840. # TODO: The return behavior has not been established... should raise exception?
  5841. return "Could not retrieve object: %s" % obj_name
  5842. # updated units
  5843. eunits = self.defaults["excellon_exp_units"]
  5844. ewhole = self.defaults["excellon_exp_integer"]
  5845. efract = self.defaults["excellon_exp_decimals"]
  5846. ezeros = self.defaults["excellon_exp_zeros"]
  5847. eformat = self.defaults[ "excellon_exp_format"]
  5848. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5849. if fc_units == 'MM':
  5850. factor = 1 if eunits == 'METRIC' else 0.03937
  5851. else:
  5852. factor = 25.4 if eunits == 'METRIC' else 1
  5853. def make_excellon():
  5854. try:
  5855. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5856. header = 'M48\n'
  5857. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  5858. (str(self.version), str(self.version_date))
  5859. header += ';Filename: %s' % str(obj_name) + '\n'
  5860. header += ';Created on : %s' % time_str + '\n'
  5861. if eformat == 'dec':
  5862. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor)
  5863. header += eunits + '\n'
  5864. for tool in obj.tools:
  5865. if eunits == 'METRIC':
  5866. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5867. tool=str(tool),
  5868. dec=2)
  5869. else:
  5870. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5871. tool=str(tool),
  5872. dec=4)
  5873. else:
  5874. if ezeros == 'LZ':
  5875. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  5876. form='ndec', e_zeros='LZ', factor=factor)
  5877. header += '%s,%s\n' % (eunits, 'LZ')
  5878. header += format_exc
  5879. for tool in obj.tools:
  5880. if eunits == 'METRIC':
  5881. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5882. tool=str(tool),
  5883. dec=2)
  5884. else:
  5885. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5886. tool=str(tool),
  5887. dec=4)
  5888. else:
  5889. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  5890. form='ndec', e_zeros='TZ', factor=factor)
  5891. header += '%s,%s\n' % (eunits, 'TZ')
  5892. header += format_exc
  5893. for tool in obj.tools:
  5894. if eunits == 'METRIC':
  5895. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5896. tool=str(tool),
  5897. dec=2)
  5898. else:
  5899. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5900. tool=str(tool),
  5901. dec=4)
  5902. header += '%\n'
  5903. footer = 'M30\n'
  5904. exported_excellon = header
  5905. exported_excellon += excellon_code
  5906. exported_excellon += footer
  5907. with open(filename, 'w') as fp:
  5908. fp.write(exported_excellon)
  5909. if self.defaults["global_open_style"] is False:
  5910. self.file_opened.emit("Excellon", filename)
  5911. self.file_saved.emit("Excellon", filename)
  5912. self.inform.emit(_("[success] Excellon file exported to %s") % filename)
  5913. except Exception as e:
  5914. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  5915. return 'fail'
  5916. if use_thread is True:
  5917. with self.proc_container.new(_("Exporting Excellon")) as proc:
  5918. def job_thread_exc(app_obj):
  5919. ret = make_excellon()
  5920. if ret == 'fail':
  5921. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  5922. return
  5923. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  5924. else:
  5925. ret = make_excellon()
  5926. if ret == 'fail':
  5927. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  5928. return
  5929. def export_gerber(self, obj_name, filename, use_thread=True):
  5930. """
  5931. Exports a Gerber Object to an Gerber file.
  5932. :param filename: Path to the Gerber file to save to.
  5933. :return:
  5934. """
  5935. self.report_usage("export_gerber()")
  5936. if filename is None:
  5937. filename = self.defaults["global_last_save_folder"]
  5938. self.log.debug("export_gerber()")
  5939. try:
  5940. obj = self.collection.get_by_name(str(obj_name))
  5941. except:
  5942. # TODO: The return behavior has not been established... should raise exception?
  5943. return "Could not retrieve object: %s" % obj_name
  5944. # updated units
  5945. gunits = self.defaults["gerber_exp_units"]
  5946. gwhole = self.defaults["gerber_exp_integer"]
  5947. gfract = self.defaults["gerber_exp_decimals"]
  5948. gzeros = self.defaults["gerber_exp_zeros"]
  5949. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5950. if fc_units == 'MM':
  5951. factor = 1 if gunits == 'MM' else 0.03937
  5952. else:
  5953. factor = 25.4 if gunits == 'MM' else 1
  5954. def make_gerber():
  5955. try:
  5956. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5957. header = 'G04*\n'
  5958. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  5959. (str(self.version), str(self.version_date))
  5960. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  5961. header += 'G04 Created on : %s*' % time_str + '\n'
  5962. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  5963. header += "%MO{units}*%\n".format(units=gunits)
  5964. for apid in obj.apertures:
  5965. if obj.apertures[apid]['type'] == 'C':
  5966. header += "%ADD{apid}{type},{size}*%\n".format(
  5967. apid=str(apid),
  5968. type='C',
  5969. size=(factor * obj.apertures[apid]['size'])
  5970. )
  5971. elif obj.apertures[apid]['type'] == 'R':
  5972. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  5973. apid=str(apid),
  5974. type='R',
  5975. width=(factor * obj.apertures[apid]['width']),
  5976. height=(factor * obj.apertures[apid]['height'])
  5977. )
  5978. elif obj.apertures[apid]['type'] == 'O':
  5979. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  5980. apid=str(apid),
  5981. type='O',
  5982. width=(factor * obj.apertures[apid]['width']),
  5983. height=(factor * obj.apertures[apid]['height'])
  5984. )
  5985. header += '\n'
  5986. # obsolete units but some software may need it
  5987. if gunits == 'IN':
  5988. header += 'G70*\n'
  5989. else:
  5990. header += 'G71*\n'
  5991. # Absolute Mode
  5992. header += 'G90*\n'
  5993. header += 'G01*\n'
  5994. # positive polarity
  5995. header += '%LPD*%\n'
  5996. footer = 'M02*\n'
  5997. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  5998. exported_gerber = header
  5999. exported_gerber += gerber_code
  6000. exported_gerber += footer
  6001. with open(filename, 'w') as fp:
  6002. fp.write(exported_gerber)
  6003. if self.defaults["global_open_style"] is False:
  6004. self.file_opened.emit("Gerber", filename)
  6005. self.file_saved.emit("Gerber", filename)
  6006. self.inform.emit(_("[success] Gerber file exported to %s") % filename)
  6007. except Exception as e:
  6008. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6009. return 'fail'
  6010. if use_thread is True:
  6011. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6012. def job_thread_exc(app_obj):
  6013. ret = make_gerber()
  6014. if ret == 'fail':
  6015. self.inform.emit(_('[ERROR_NOTCL] Could not export Gerber file.'))
  6016. return
  6017. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6018. else:
  6019. ret = make_gerber()
  6020. if ret == 'fail':
  6021. self.inform.emit(_('[ERROR_NOTCL] Could not export Gerber file.'))
  6022. return
  6023. def export_dxf(self, obj_name, filename, use_thread=True):
  6024. """
  6025. Exports a Geometry Object to an DXF file.
  6026. :param filename: Path to the DXF file to save to.
  6027. :return:
  6028. """
  6029. self.report_usage("export_dxf()")
  6030. if filename is None:
  6031. filename = self.defaults["global_last_save_folder"]
  6032. self.log.debug("export_dxf()")
  6033. format_exc = ''
  6034. units = ''
  6035. try:
  6036. obj = self.collection.get_by_name(str(obj_name))
  6037. except:
  6038. # TODO: The return behavior has not been established... should raise exception?
  6039. return "Could not retrieve object: %s" % obj_name
  6040. # updated units
  6041. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6042. if units == 'IN' or units == 'INCH':
  6043. units = 'INCH'
  6044. elif units == 'MM' or units == 'METIRC':
  6045. units ='METRIC'
  6046. def make_dxf():
  6047. try:
  6048. dxf_code = obj.export_dxf()
  6049. dxf_code.saveas(filename)
  6050. if self.defaults["global_open_style"] is False:
  6051. self.file_opened.emit("DXF", filename)
  6052. self.file_saved.emit("DXF", filename)
  6053. self.inform.emit(_("[success] DXF file exported to %s") % filename)
  6054. except:
  6055. return 'fail'
  6056. if use_thread is True:
  6057. with self.proc_container.new(_("Exporting DXF")) as proc:
  6058. def job_thread_exc(app_obj):
  6059. ret = make_dxf()
  6060. if ret == 'fail':
  6061. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  6062. return
  6063. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6064. else:
  6065. ret = make_dxf()
  6066. if ret == 'fail':
  6067. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  6068. return
  6069. def import_svg(self, filename, geo_type='geometry', outname=None):
  6070. """
  6071. Adds a new Geometry Object to the projects and populates
  6072. it with shapes extracted from the SVG file.
  6073. :param filename: Path to the SVG file.
  6074. :param outname:
  6075. :return:
  6076. """
  6077. self.report_usage("import_svg()")
  6078. obj_type = ""
  6079. if geo_type is None or geo_type == "geometry":
  6080. obj_type = "geometry"
  6081. elif geo_type == "gerber":
  6082. obj_type = geo_type
  6083. else:
  6084. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6085. "Only Geometry and Gerber are supported"))
  6086. return
  6087. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6088. def obj_init(geo_obj, app_obj):
  6089. geo_obj.import_svg(filename, obj_type, units=units)
  6090. geo_obj.multigeo = False
  6091. with self.proc_container.new(_("Importing SVG")) as proc:
  6092. # Object name
  6093. name = outname or filename.split('/')[-1].split('\\')[-1]
  6094. self.new_object(obj_type, name, obj_init, autoselected=False)
  6095. self.progress.emit(20)
  6096. # Register recent file
  6097. self.file_opened.emit("svg", filename)
  6098. # GUI feedback
  6099. self.inform.emit(_("[success] Opened: %s") % filename)
  6100. self.progress.emit(100)
  6101. def import_dxf(self, filename, geo_type='geometry', outname=None):
  6102. """
  6103. Adds a new Geometry Object to the projects and populates
  6104. it with shapes extracted from the DXF file.
  6105. :param filename: Path to the DXF file.
  6106. :param outname:
  6107. :type putname: str
  6108. :return:
  6109. """
  6110. self.report_usage("import_dxf()")
  6111. obj_type = ""
  6112. if geo_type is None or geo_type == "geometry":
  6113. obj_type = "geometry"
  6114. elif geo_type == "gerber":
  6115. obj_type = geo_type
  6116. else:
  6117. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6118. "Only Geometry and Gerber are supported"))
  6119. return
  6120. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  6121. def obj_init(geo_obj, app_obj):
  6122. geo_obj.import_dxf(filename, obj_type, units=units)
  6123. geo_obj.multigeo = False
  6124. with self.proc_container.new(_("Importing DXF")) as proc:
  6125. # Object name
  6126. name = outname or filename.split('/')[-1].split('\\')[-1]
  6127. self.new_object(obj_type, name, obj_init, autoselected=False)
  6128. self.progress.emit(20)
  6129. # Register recent file
  6130. self.file_opened.emit("dxf", filename)
  6131. # GUI feedback
  6132. self.inform.emit(_("[success] Opened: %s") % filename)
  6133. self.progress.emit(100)
  6134. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  6135. """
  6136. Adds a new Geometry Object to the projects and populates
  6137. it with shapes extracted from the SVG file.
  6138. :param filename: Path to the SVG file.
  6139. :param o_type: type of FlatCAM objeect
  6140. :param dpi: dot per inch
  6141. :param mode: black or color
  6142. :param mask: dictate the level of detail
  6143. :param outname: name for the resulting file
  6144. :return:
  6145. """
  6146. self.report_usage("import_image()")
  6147. if o_type is None or o_type == "geometry":
  6148. obj_type = "geometry"
  6149. elif o_type == "gerber":
  6150. obj_type = o_type
  6151. else:
  6152. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  6153. "Only Geometry and Gerber are supported"))
  6154. return
  6155. def obj_init(geo_obj, app_obj):
  6156. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  6157. geo_obj.multigeo = False
  6158. with self.proc_container.new(_("Importing Image")) as proc:
  6159. # Object name
  6160. name = outname or filename.split('/')[-1].split('\\')[-1]
  6161. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  6162. self.new_object(obj_type, name, obj_init)
  6163. self.progress.emit(20)
  6164. # Register recent file
  6165. self.file_opened.emit("image", filename)
  6166. # GUI feedback
  6167. self.inform.emit(_("[success] Opened: %s") % filename)
  6168. self.progress.emit(100)
  6169. def open_gerber(self, filename, outname=None):
  6170. """
  6171. Opens a Gerber file, parses it and creates a new object for
  6172. it in the program. Thread-safe.
  6173. :param outname: Name of the resulting object. None causes the
  6174. name to be that of the file.
  6175. :param filename: Gerber file filename
  6176. :type filename: str
  6177. :param follow: If true, the parser will not create polygons, just lines
  6178. following the gerber path.
  6179. :type follow: bool
  6180. :return: None
  6181. """
  6182. # How the object should be initialized
  6183. def obj_init(gerber_obj, app_obj):
  6184. assert isinstance(gerber_obj, FlatCAMGerber), \
  6185. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  6186. # Opening the file happens here
  6187. self.progress.emit(30)
  6188. try:
  6189. gerber_obj.parse_file(filename)
  6190. except IOError:
  6191. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to open file: %s") % filename)
  6192. app_obj.progress.emit(0)
  6193. self.inform.emit(_('[ERROR_NOTCL] Failed to open file: %s') % filename)
  6194. return "fail"
  6195. except ParseError as err:
  6196. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to parse file: {name}. {error}").format(name=filename,
  6197. error=str(err)))
  6198. app_obj.progress.emit(0)
  6199. self.log.error(str(err))
  6200. return "fail"
  6201. except:
  6202. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  6203. msg += traceback.format_exc()
  6204. app_obj.inform.emit(msg)
  6205. return "fail"
  6206. if gerber_obj.is_empty():
  6207. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  6208. # self.collection.set_active(gerber_obj.options["name"])
  6209. # self.collection.delete_active()
  6210. self.inform.emit(_("[ERROR_NOTCL] Object is not Gerber file or empty. Aborting object creation."))
  6211. return "fail"
  6212. # Further parsing
  6213. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  6214. App.log.debug("open_gerber()")
  6215. with self.proc_container.new(_("Opening Gerber")) as proc:
  6216. self.progress.emit(10)
  6217. # Object name
  6218. name = outname or filename.split('/')[-1].split('\\')[-1]
  6219. # # ## Object creation # ##
  6220. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  6221. if ret == 'fail':
  6222. self.inform.emit(_('[ERROR_NOTCL] Open Gerber failed. Probable not a Gerber file.'))
  6223. return
  6224. # Register recent file
  6225. self.file_opened.emit("gerber", filename)
  6226. self.progress.emit(100)
  6227. # GUI feedback
  6228. self.inform.emit(_("[success] Opened: %s") % filename)
  6229. def open_excellon(self, filename, outname=None):
  6230. """
  6231. Opens an Excellon file, parses it and creates a new object for
  6232. it in the program. Thread-safe.
  6233. :param outname: Name of the resulting object. None causes the
  6234. name to be that of the file.
  6235. :param filename: Excellon file filename
  6236. :type filename: str
  6237. :return: None
  6238. """
  6239. App.log.debug("open_excellon()")
  6240. # How the object should be initialized
  6241. def obj_init(excellon_obj, app_obj):
  6242. # self.progress.emit(20)
  6243. try:
  6244. ret = excellon_obj.parse_file(filename=filename)
  6245. if ret == "fail":
  6246. log.debug("Excellon parsing failed.")
  6247. self.inform.emit(_("[ERROR_NOTCL] This is not Excellon file."))
  6248. return "fail"
  6249. except IOError:
  6250. app_obj.inform.emit(_("[ERROR_NOTCL] Cannot open file: %s") % filename)
  6251. log.debug("Could not open Excellon object.")
  6252. self.progress.emit(0) # TODO: self and app_bjj mixed
  6253. return "fail"
  6254. except:
  6255. msg = _("[ERROR_NOTCL] An internal error has occurred. See shell.\n")
  6256. msg += traceback.format_exc()
  6257. app_obj.inform.emit(msg)
  6258. return "fail"
  6259. ret = excellon_obj.create_geometry()
  6260. if ret == 'fail':
  6261. log.debug("Could not create geometry for Excellon object.")
  6262. return "fail"
  6263. for tool in excellon_obj.tools:
  6264. if excellon_obj.tools[tool]['solid_geometry']:
  6265. return
  6266. app_obj.inform.emit(_("[ERROR_NOTCL] No geometry found in file: %s") % filename)
  6267. return "fail"
  6268. with self.proc_container.new(_("Opening Excellon.")):
  6269. # Object name
  6270. name = outname or filename.split('/')[-1].split('\\')[-1]
  6271. ret_val = self.new_object("excellon", name, obj_init, autoselected=False)
  6272. if ret_val == 'fail':
  6273. self.inform.emit(_('[ERROR_NOTCL] Open Excellon file failed. Probable not an Excellon file.'))
  6274. return
  6275. # Register recent file
  6276. self.file_opened.emit("excellon", filename)
  6277. # GUI feedback
  6278. self.inform.emit(_("[success] Opened: %s") % filename)
  6279. def open_gcode(self, filename, outname=None):
  6280. """
  6281. Opens a G-gcode file, parses it and creates a new object for
  6282. it in the program. Thread-safe.
  6283. :param outname: Name of the resulting object. None causes the name to be that of the file.
  6284. :param filename: G-code file filename
  6285. :type filename: str
  6286. :return: None
  6287. """
  6288. App.log.debug("open_gcode()")
  6289. # How the object should be initialized
  6290. def obj_init(job_obj, app_obj_):
  6291. """
  6292. :param job_obj: the resulting object
  6293. :type app_obj_: App
  6294. """
  6295. assert isinstance(app_obj_, App), \
  6296. "Initializer expected App, got %s" % type(app_obj_)
  6297. self.progress.emit(10)
  6298. try:
  6299. f = open(filename)
  6300. gcode = f.read()
  6301. f.close()
  6302. except IOError:
  6303. app_obj_.inform.emit(_("[ERROR_NOTCL] Failed to open %s") % filename)
  6304. self.progress.emit(0)
  6305. return "fail"
  6306. job_obj.gcode = gcode
  6307. self.progress.emit(20)
  6308. ret = job_obj.gcode_parse()
  6309. if ret == "fail":
  6310. self.inform.emit(_("[ERROR_NOTCL] This is not GCODE"))
  6311. return "fail"
  6312. self.progress.emit(60)
  6313. job_obj.create_geometry()
  6314. with self.proc_container.new(_("Opening G-Code.")):
  6315. # Object name
  6316. name = outname or filename.split('/')[-1].split('\\')[-1]
  6317. # New object creation and file processing
  6318. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  6319. if ret == 'fail':
  6320. self.inform.emit(_("[ERROR_NOTCL] Failed to create CNCJob Object. Probable not a GCode file.\n "
  6321. "Attempting to create a FlatCAM CNCJob Object from "
  6322. "G-Code file failed during processing"))
  6323. return "fail"
  6324. # Register recent file
  6325. self.file_opened.emit("cncjob", filename)
  6326. # GUI feedback
  6327. self.inform.emit(_("[success] Opened: %s") % filename)
  6328. self.progress.emit(100)
  6329. def open_config_file(self, filename, run_from_arg=None):
  6330. """
  6331. Loads a config file from the specified file.
  6332. :param filename: Name of the file from which to load.
  6333. :type filename: str
  6334. :return: None
  6335. """
  6336. App.log.debug("Opening config file: " + filename)
  6337. # add the tab if it was closed
  6338. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  6339. # first clear previous text in text editor (if any)
  6340. self.ui.code_editor.clear()
  6341. # Switch plot_area to CNCJob tab
  6342. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  6343. try:
  6344. if filename:
  6345. f = QtCore.QFile(filename)
  6346. if f.open(QtCore.QIODevice.ReadOnly):
  6347. stream = QtCore.QTextStream(f)
  6348. gcode_edited = stream.readAll()
  6349. self.ui.code_editor.setPlainText(gcode_edited)
  6350. f.close()
  6351. except IOError:
  6352. App.log.error("Failed to open config file: %s" % filename)
  6353. self.inform.emit(_("[ERROR_NOTCL] Failed to open config file: %s") % filename)
  6354. return
  6355. def open_project(self, filename, run_from_arg=None):
  6356. """
  6357. Loads a project from the specified file.
  6358. 1) Loads and parses file
  6359. 2) Registers the file as recently opened.
  6360. 3) Calls on_file_new()
  6361. 4) Updates options
  6362. 5) Calls new_object() with the object's from_dict() as init method.
  6363. 6) Calls plot_all()
  6364. :param filename: Name of the file from which to load.
  6365. :type filename: str
  6366. :param run_from_arg: True if run for arguments
  6367. :return: None
  6368. """
  6369. App.log.debug("Opening project: " + filename)
  6370. # Open and parse an uncompressed Project file
  6371. try:
  6372. f = open(filename, 'r')
  6373. except IOError:
  6374. App.log.error("Failed to open project file: %s" % filename)
  6375. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  6376. return
  6377. try:
  6378. d = json.load(f, object_hook=dict2obj)
  6379. except Exception as e:
  6380. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  6381. (filename, str(e)))
  6382. f.close()
  6383. # Open and parse a compressed Project file
  6384. try:
  6385. with lzma.open(filename) as f:
  6386. file_content = f.read().decode('utf-8')
  6387. d = json.loads(file_content, object_hook=dict2obj)
  6388. except IOError:
  6389. App.log.error("Failed to open project file: %s" % filename)
  6390. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  6391. return
  6392. # Clear the current project
  6393. # # NOT THREAD SAFE # ##
  6394. if run_from_arg is True:
  6395. pass
  6396. else:
  6397. self.on_file_new()
  6398. # Project options
  6399. self.options.update(d['options'])
  6400. self.project_filename = filename
  6401. self.set_screen_units(self.options["units"])
  6402. # Re create objects
  6403. App.log.debug("Re-creating objects...")
  6404. for obj in d['objs']:
  6405. def obj_init(obj_inst, app_inst):
  6406. obj_inst.from_dict(obj)
  6407. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  6408. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  6409. self.plot_all()
  6410. self.inform.emit(_("[success] Project loaded from: %s") % filename)
  6411. self.should_we_save = False
  6412. self.file_opened.emit("project", filename)
  6413. App.log.debug("Project loaded")
  6414. def propagate_defaults(self, silent=False):
  6415. """
  6416. This method is used to set default values in classes. It's
  6417. an alternative to project options but allows the use
  6418. of values invisible to the user.
  6419. :return: None
  6420. """
  6421. if silent is False:
  6422. self.log.debug("propagate_defaults()")
  6423. # Which objects to update the given parameters.
  6424. routes = {
  6425. "global_zdownrate": CNCjob,
  6426. "excellon_zeros": Excellon,
  6427. "excellon_format_upper_in": Excellon,
  6428. "excellon_format_lower_in": Excellon,
  6429. "excellon_format_upper_mm": Excellon,
  6430. "excellon_format_lower_mm": Excellon,
  6431. "excellon_units": Excellon,
  6432. "gerber_use_buffer_for_union": Gerber,
  6433. "geometry_multidepth": Geometry
  6434. }
  6435. for param in routes:
  6436. if param in routes[param].defaults:
  6437. try:
  6438. routes[param].defaults[param] = self.defaults[param]
  6439. if silent is False:
  6440. self.log.debug(" " + param + " OK")
  6441. except KeyError:
  6442. if silent is False:
  6443. self.log.debug(" ERROR: " + param + " not in defaults.")
  6444. else:
  6445. # Try extracting the name:
  6446. # classname_param here is param in the object
  6447. if param.find(routes[param].__name__.lower() + "_") == 0:
  6448. p = param[len(routes[param].__name__) + 1:]
  6449. if p in routes[param].defaults:
  6450. routes[param].defaults[p] = self.defaults[param]
  6451. if silent is False:
  6452. self.log.debug(" " + param + " OK!")
  6453. def restore_main_win_geom(self):
  6454. try:
  6455. self.ui.setGeometry(self.defaults["global_def_win_x"],
  6456. self.defaults["global_def_win_y"],
  6457. self.defaults["global_def_win_w"],
  6458. self.defaults["global_def_win_h"])
  6459. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  6460. settings = QSettings("Open Source", "FlatCAM")
  6461. if settings.contains("maximized_gui"):
  6462. maximized_ui = settings.value('maximized_gui', type=bool)
  6463. if maximized_ui is True:
  6464. self.ui.showMaximized()
  6465. except KeyError as e:
  6466. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  6467. def plot_all(self, zoom=True):
  6468. """
  6469. Re-generates all plots from all objects.
  6470. :return: None
  6471. """
  6472. self.log.debug("Plot_all()")
  6473. for obj in self.collection.get_list():
  6474. def worker_task(obj):
  6475. with self.proc_container.new("Plotting"):
  6476. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  6477. if zoom:
  6478. self.object_plotted.emit(obj)
  6479. # Send to worker
  6480. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  6481. def register_folder(self, filename):
  6482. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  6483. def register_save_folder(self, filename):
  6484. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  6485. def set_progress_bar(self, percentage, text=""):
  6486. self.ui.progress_bar.setValue(int(percentage))
  6487. def setup_shell(self):
  6488. """
  6489. Creates shell functions. Runs once at startup.
  6490. :return: None
  6491. """
  6492. self.log.debug("setup_shell()")
  6493. def shelp(p=None):
  6494. if not p:
  6495. return _("Available commands:\n") + \
  6496. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  6497. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  6498. if p not in commands:
  6499. return "Unknown command: %s" % p
  6500. return commands[p]["help"]
  6501. # --- Migrated to new architecture ---
  6502. # def options(name):
  6503. # ops = self.collection.get_by_name(str(name)).options
  6504. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  6505. def h(*args):
  6506. """
  6507. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  6508. and standalone parameters into list.
  6509. """
  6510. kwa = {}
  6511. a = []
  6512. n = len(args)
  6513. name = None
  6514. for i in range(n):
  6515. match = re.search(r'^-([a-zA-Z].*)', args[i])
  6516. if match:
  6517. assert name is None
  6518. name = match.group(1)
  6519. continue
  6520. if name is None:
  6521. a.append(args[i])
  6522. else:
  6523. kwa[name] = args[i]
  6524. name = None
  6525. return a, kwa
  6526. @contextmanager
  6527. def wait_signal(signal, timeout=10000):
  6528. """
  6529. Block loop until signal emitted, timeout (ms) elapses
  6530. or unhandled exception happens in a thread.
  6531. :param timeout: time after which the loop is exited
  6532. :param signal: Signal to wait for.
  6533. """
  6534. loop = QtCore.QEventLoop()
  6535. # Normal termination
  6536. signal.connect(loop.quit)
  6537. # Termination by exception in thread
  6538. self.thread_exception.connect(loop.quit)
  6539. status = {'timed_out': False}
  6540. def report_quit():
  6541. status['timed_out'] = True
  6542. loop.quit()
  6543. yield
  6544. # Temporarily change how exceptions are managed.
  6545. oeh = sys.excepthook
  6546. ex = []
  6547. def except_hook(type_, value, traceback_):
  6548. ex.append(value)
  6549. oeh(type_, value, traceback_)
  6550. sys.excepthook = except_hook
  6551. # Terminate on timeout
  6552. if timeout is not None:
  6553. QtCore.QTimer.singleShot(timeout, report_quit)
  6554. # # ## Block ## ##
  6555. loop.exec_()
  6556. # Restore exception management
  6557. sys.excepthook = oeh
  6558. if ex:
  6559. self.raiseTclError(str(ex[0]))
  6560. if status['timed_out']:
  6561. raise Exception('Timed out!')
  6562. def make_docs():
  6563. output = ''
  6564. import collections
  6565. od = collections.OrderedDict(sorted(commands.items()))
  6566. for cmd_, val in od.items():
  6567. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  6568. t = val['help']
  6569. usage_i = t.find('>')
  6570. if usage_i < 0:
  6571. expl = t
  6572. output += expl + '\n\n'
  6573. continue
  6574. expl = t[:usage_i - 1]
  6575. output += expl + '\n\n'
  6576. end_usage_i = t[usage_i:].find('\n')
  6577. if end_usage_i < 0:
  6578. end_usage_i = len(t[usage_i:])
  6579. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  6580. else:
  6581. extras = t[usage_i+end_usage_i+1:]
  6582. parts = [s.strip() for s in extras.split('\n')]
  6583. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  6584. for p in parts:
  6585. output += ' ' + p + '\n\n'
  6586. return output
  6587. '''
  6588. Howto implement TCL shell commands:
  6589. All parameters passed to command should be possible to set as None and test it afterwards.
  6590. This is because we need to see error caused in tcl,
  6591. if None value as default parameter is not allowed TCL will return empty error.
  6592. Use:
  6593. def mycommand(name=None,...):
  6594. Test it like this:
  6595. if name is None:
  6596. self.raise_tcl_error('Argument name is missing.')
  6597. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  6598. otherwise we will miss it and processing will silently continue.
  6599. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  6600. which is catched in exec_command and displayed in TCL shell console with red background.
  6601. Error in console is displayed with TCL trace.
  6602. This behavior works only within main thread,
  6603. errors with promissed tasks can be catched and detected only with log.
  6604. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  6605. TCL shell.
  6606. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  6607. '''
  6608. commands = {
  6609. 'help': {
  6610. 'fcn': shelp,
  6611. 'help': _("Shows list of commands.")
  6612. },
  6613. }
  6614. # Import/overwrite tcl commands as objects of TclCommand descendants
  6615. # This modifies the variable 'commands'.
  6616. tclCommands.register_all_commands(self, commands)
  6617. # Add commands to the tcl interpreter
  6618. for cmd in commands:
  6619. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  6620. # Make the tcl puts function return instead of print to stdout
  6621. self.tcl.eval('''
  6622. rename puts original_puts
  6623. proc puts {args} {
  6624. if {[llength $args] == 1} {
  6625. return "[lindex $args 0]"
  6626. } else {
  6627. eval original_puts $args
  6628. }
  6629. }
  6630. ''')
  6631. def setup_recent_items(self):
  6632. # TODO: Move this to constructor
  6633. icons = {
  6634. "gerber": "share/flatcam_icon16.png",
  6635. "excellon": "share/drill16.png",
  6636. 'geometry': "share/geometry16.png",
  6637. "cncjob": "share/cnc16.png",
  6638. "project": "share/project16.png",
  6639. "svg": "share/geometry16.png",
  6640. "dxf": "share/dxf16.png",
  6641. "pdf": "share/pdf32.png",
  6642. "image": "share/image16.png"
  6643. }
  6644. openers = {
  6645. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  6646. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  6647. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  6648. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  6649. 'project': self.open_project,
  6650. 'svg': self.import_svg,
  6651. 'dxf': self.import_dxf,
  6652. 'image': self.import_image,
  6653. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  6654. }
  6655. # Open file
  6656. try:
  6657. f = open(self.data_path + '/recent.json')
  6658. except IOError:
  6659. App.log.error("Failed to load recent item list.")
  6660. self.inform.emit(_("[ERROR_NOTCL] Failed to load recent item list."))
  6661. return
  6662. try:
  6663. self.recent = json.load(f)
  6664. except json.scanner.JSONDecodeError:
  6665. App.log.error("Failed to parse recent item list.")
  6666. self.inform.emit(_("[ERROR_NOTCL] Failed to parse recent item list."))
  6667. f.close()
  6668. return
  6669. f.close()
  6670. # Closure needed to create callbacks in a loop.
  6671. # Otherwise late binding occurs.
  6672. def make_callback(func, fname):
  6673. def opener():
  6674. func(fname)
  6675. return opener
  6676. def reset_recent():
  6677. # Reset menu
  6678. self.ui.recent.clear()
  6679. self.recent = []
  6680. try:
  6681. f = open(self.data_path + '/recent.json', 'w')
  6682. except IOError:
  6683. App.log.error("Failed to open recent items file for writing.")
  6684. return
  6685. json.dump(self.recent, f)
  6686. # Reset menu
  6687. self.ui.recent.clear()
  6688. # Create menu items
  6689. for recent in self.recent:
  6690. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  6691. try:
  6692. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  6693. # Attach callback
  6694. o = make_callback(openers[recent["kind"]], recent['filename'])
  6695. action.triggered.connect(o)
  6696. self.ui.recent.addAction(action)
  6697. except KeyError:
  6698. App.log.error("Unsupported file type: %s" % recent["kind"])
  6699. # Last action in Recent Files menu is one that Clear the content
  6700. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  6701. clear_action.triggered.connect(reset_recent)
  6702. self.ui.recent.addSeparator()
  6703. self.ui.recent.addAction(clear_action)
  6704. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  6705. # self.ui.menufilerecent.set_submenu(recent_menu)
  6706. # recent_menu.show_all()
  6707. # self.ui.recent.show()
  6708. self.log.debug("Recent items list has been populated.")
  6709. def setup_component_editor(self):
  6710. # label = QtWidgets.QLabel("Choose an item from Project")
  6711. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  6712. sel_title = QtWidgets.QTextEdit(
  6713. _('<b>Shortcut Key List</b>'))
  6714. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  6715. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  6716. # font = self.sel_title.font()
  6717. # font.setPointSize(12)
  6718. # self.sel_title.setFont(font)
  6719. selected_text = _('''
  6720. <p><span style="font-size:14px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  6721. <p><span style="font-size:10px"><strong>Details</strong>:<br />
  6722. The normal flow when working in FlatCAM is the following:</span></p>
  6723. <ol>
  6724. <li><span style="font-size:10px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the menu&#39;s, toolbars, key shortcuts or even dragging and dropping the files on the GUI.<br />
  6725. <br />
  6726. You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  6727. &nbsp;</li>
  6728. <li><span style="font-size:10px">Once an object is available in the Project Tab, by selecting it and then focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  6729. <br />
  6730. If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong> is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate it even if it was out of focus.<br />
  6731. <br />
  6732. You can change the parameters in this screen and the flow direction is like this:<br />
  6733. <br />
  6734. <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  6735. </ol>
  6736. <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: <strng>F3</strong>.</span></p>
  6737. ''')
  6738. sel_title.setText(selected_text)
  6739. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6740. self.ui.selected_scroll_area.setWidget(sel_title)
  6741. # tool_title = QtWidgets.QTextEdit(
  6742. # '<b>Shortcut Key List</b>')
  6743. # tool_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  6744. # tool_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  6745. # # font = self.sel_title.font()
  6746. # # font.setPointSize(12)
  6747. # # self.sel_title.setFont(font)
  6748. #
  6749. # tool_text = '''
  6750. # <p><span style="font-size:14px"><strong>Tool Tab - Choose an Item in Tools Menu</strong></span></p>
  6751. #
  6752. # <p><span style="font-size:10px"><strong>Details</strong>:<br />
  6753. # Some of the functionality of FlatCAM have been implemented as tools (a sort of plugins). </span></p>
  6754. #
  6755. # <p><span style="font-size:10px">Most of the tools are accessible through&nbsp;the Tools menu or by using the associated shortcut keys.<br />
  6756. # Each such a tool, if it needs an object to be used as a source it will provide the way to select this object(s) through a series of comboboxes. The result of using a tool is either a Geometry, an information that can be used in the app or it can be a file that can be saved.</span></p>
  6757. #
  6758. # <ol>
  6759. # </ol>
  6760. #
  6761. # <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: &#39;`&#39; (key left to 1).</span></p>
  6762. #
  6763. # '''
  6764. #
  6765. # tool_title.setText(tool_text)
  6766. # tool_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6767. #
  6768. # self.ui.tool_scroll_area.setWidget(tool_title)
  6769. def setup_obj_classes(self):
  6770. """
  6771. Sets up application specifics on the FlatCAMObj class.
  6772. :return: None
  6773. """
  6774. FlatCAMObj.app = self
  6775. ObjectCollection.app = self
  6776. FCProcess.app = self
  6777. FCProcessContainer.app = self
  6778. def version_check(self):
  6779. """
  6780. Checks for the latest version of the program. Alerts the
  6781. user if theirs is outdated. This method is meant to be run
  6782. in a separate thread.
  6783. :return: None
  6784. """
  6785. self.log.debug("version_check()")
  6786. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  6787. full_url = App.version_url + \
  6788. "?s=" + str(self.defaults['global_serial']) + \
  6789. "&v=" + str(self.version) + \
  6790. "&os=" + str(self.os) + \
  6791. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  6792. else:
  6793. # no_stats dict; just so it won't break things on website
  6794. no_ststs_dict = {}
  6795. no_ststs_dict["global_ststs"] = {}
  6796. full_url = App.version_url + \
  6797. "?s=" + str(self.defaults['global_serial']) + \
  6798. "&v=" + str(self.version) + \
  6799. "&os=" + str(self.os) + \
  6800. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  6801. App.log.debug("Checking for updates @ %s" % full_url)
  6802. # ## Get the data
  6803. try:
  6804. f = urllib.request.urlopen(full_url)
  6805. except:
  6806. # App.log.warning("Failed checking for latest version. Could not connect.")
  6807. self.log.warning("Failed checking for latest version. Could not connect.")
  6808. self.inform.emit(_("[WARNING_NOTCL] Failed checking for latest version. Could not connect."))
  6809. return
  6810. try:
  6811. data = json.load(f)
  6812. except Exception as e:
  6813. App.log.error("Could not parse information about latest version.")
  6814. self.inform.emit(_("[ERROR_NOTCL] Could not parse information about latest version."))
  6815. App.log.debug("json.load(): %s" % str(e))
  6816. f.close()
  6817. return
  6818. f.close()
  6819. # ## Latest version?
  6820. if self.version >= data["version"]:
  6821. App.log.debug("FlatCAM is up to date!")
  6822. self.inform.emit(_("[success] FlatCAM is up to date!"))
  6823. return
  6824. App.log.debug("Newer version available.")
  6825. self.message.emit(
  6826. _("Newer Version Available"),
  6827. _("There is a newer version of FlatCAM available for download:\n\n") +
  6828. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  6829. _("info")
  6830. )
  6831. def on_zoom_fit(self, event):
  6832. """
  6833. Callback for zoom-out request. This can be either from the corresponding
  6834. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  6835. with axes limits from the geometry bounds of all objects.
  6836. :param event: Ignored.
  6837. :return: None
  6838. """
  6839. self.plotcanvas.fit_view()
  6840. def disable_all_plots(self):
  6841. self.report_usage("disable_all_plots()")
  6842. self.disable_plots(self.collection.get_list())
  6843. self.inform.emit(_("[success] All plots disabled."))
  6844. def disable_other_plots(self):
  6845. self.report_usage("disable_other_plots()")
  6846. self.disable_plots(self.collection.get_non_selected())
  6847. self.inform.emit(_("[success] All non selected plots disabled."))
  6848. def enable_all_plots(self):
  6849. self.report_usage("enable_all_plots()")
  6850. self.enable_plots(self.collection.get_list())
  6851. self.inform.emit(_("[success] All plots enabled."))
  6852. def on_enable_sel_plots(self):
  6853. log.debug("App.on_enable_sel_plot()")
  6854. object_list = self.collection.get_selected()
  6855. self.enable_plots(objects=object_list)
  6856. self.inform.emit(_("[success] Selected plots enabled..."))
  6857. def on_disable_sel_plots(self):
  6858. log.debug("App.on_disable_sel_plot()")
  6859. # self.inform.emit(_("Disabling plots ..."))
  6860. object_list = self.collection.get_selected()
  6861. self.disable_plots(objects=object_list)
  6862. self.inform.emit(_("[success] Selected plots disabled..."))
  6863. def enable_plots(self, objects):
  6864. """
  6865. Disables plots
  6866. :param objects: list of Objects to be enabled
  6867. :return:
  6868. """
  6869. log.debug("Enabling plots ...")
  6870. self.inform.emit(_("Working ..."))
  6871. for obj in objects:
  6872. obj.options['plot'] = True
  6873. self.plots_updated.emit()
  6874. def disable_plots(self, objects):
  6875. """
  6876. Disables plots
  6877. :param objects: list of Objects to be disabled
  6878. :return:
  6879. """
  6880. log.debug("Disabling plots ...")
  6881. self.inform.emit(_("Working ..."))
  6882. for obj in objects:
  6883. obj.options['plot'] = False
  6884. self.plots_updated.emit()
  6885. def clear_plots(self):
  6886. objects = self.collection.get_list()
  6887. for obj in objects:
  6888. obj.clear(obj == objects[-1])
  6889. # Clear pool to free memory
  6890. self.clear_pool()
  6891. def generate_cnc_job(self, objects):
  6892. self.report_usage("generate_cnc_job()")
  6893. # for obj in objects:
  6894. # obj.generatecncjob()
  6895. for obj in objects:
  6896. obj.on_generatecnc_button_click()
  6897. def save_project(self, filename, quit=False):
  6898. """
  6899. Saves the current project to the specified file.
  6900. :param filename: Name of the file in which to save.
  6901. :type filename: str
  6902. :return: None
  6903. """
  6904. self.log.debug("save_project()")
  6905. self.save_in_progress = True
  6906. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  6907. # Capture the latest changes
  6908. # Current object
  6909. try:
  6910. self.collection.get_active().read_form()
  6911. except:
  6912. self.log.debug("There was no active object")
  6913. pass
  6914. # Project options
  6915. self.options_read_form()
  6916. # Serialize the whole project
  6917. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  6918. "options": self.options,
  6919. "version": self.version}
  6920. if self.defaults["global_save_compressed"] is True:
  6921. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  6922. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  6923. # # Write
  6924. f.write(g)
  6925. self.inform.emit(_("[success] Project saved to: %s") % filename)
  6926. else:
  6927. # Open file
  6928. try:
  6929. f = open(filename, 'w')
  6930. except IOError:
  6931. App.log.error("Failed to open file for saving: %s", filename)
  6932. return
  6933. # Write
  6934. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  6935. f.close()
  6936. # verification of the saved project
  6937. # Open and parse
  6938. try:
  6939. saved_f = open(filename, 'r')
  6940. except IOError:
  6941. self.inform.emit(_("[ERROR_NOTCL] Failed to verify project file: %s. Retry to save it.") % filename)
  6942. return
  6943. try:
  6944. saved_d = json.load(saved_f, object_hook=dict2obj)
  6945. except:
  6946. self.inform.emit(
  6947. _("[ERROR_NOTCL] Failed to parse saved project file: %s. Retry to save it.") % filename)
  6948. f.close()
  6949. return
  6950. saved_f.close()
  6951. if 'version' in saved_d:
  6952. self.inform.emit(_("[success] Project saved to: %s") % filename)
  6953. else:
  6954. self.inform.emit(_("[ERROR_NOTCL] Failed to save project file: %s. Retry to save it.") % filename)
  6955. # if quit:
  6956. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  6957. # t.start()
  6958. self.start_delayed_quit(delay=500, filename=filename, quit=quit)
  6959. def start_delayed_quit(self, delay, filename, quit=None):
  6960. """
  6961. :param delay: period of checking if project file size is more than zero; in seconds
  6962. :param filename: the name of the project file to be checked periodically for size more than zero
  6963. :return:
  6964. """
  6965. to_quit = quit
  6966. self.save_timer = QtCore.QTimer()
  6967. self.save_timer.setInterval(delay)
  6968. self.save_timer.timeout.connect(lambda : self.check_project_file_size(filename=filename, quit=to_quit))
  6969. self.save_timer.start()
  6970. def check_project_file_size(self, filename, quit=None):
  6971. """
  6972. :param filename: the name of the project file to be checked periodically for size more than zero
  6973. :return:
  6974. """
  6975. try:
  6976. if os.stat(filename).st_size > 0:
  6977. self.save_in_progress = False
  6978. self.save_timer.stop()
  6979. if quit:
  6980. self.app_quit.emit()
  6981. except Exception:
  6982. traceback.print_exc()
  6983. def on_options_app2project(self):
  6984. """
  6985. Callback for Options->Transfer Options->App=>Project. Copies options
  6986. from application defaults to project defaults.
  6987. :return: None
  6988. """
  6989. self.report_usage("on_options_app2project")
  6990. self.defaults_read_form()
  6991. self.options.update(self.defaults)
  6992. self.options_write_form()
  6993. def on_options_project2app(self):
  6994. """
  6995. Callback for Options->Transfer Options->Project=>App. Copies options
  6996. from project defaults to application defaults.
  6997. :return: None
  6998. """
  6999. self.report_usage("on_options_project2app")
  7000. self.options_read_form()
  7001. self.defaults.update(self.options)
  7002. self.defaults_write_form()
  7003. def on_options_project2object(self):
  7004. """
  7005. Callback for Options->Transfer Options->Project=>Object. Copies options
  7006. from project defaults to the currently selected object.
  7007. :return: None
  7008. """
  7009. self.report_usage("on_options_project2object")
  7010. self.options_read_form()
  7011. obj = self.collection.get_active()
  7012. if obj is None:
  7013. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7014. return
  7015. for option in self.options:
  7016. if option.find(obj.kind + "_") == 0:
  7017. oname = option[len(obj.kind) + 1:]
  7018. obj.options[oname] = self.options[option]
  7019. obj.to_form() # Update UI
  7020. def on_options_object2project(self):
  7021. """
  7022. Callback for Options->Transfer Options->Object=>Project. Copies options
  7023. from the currently selected object to project defaults.
  7024. :return: None
  7025. """
  7026. self.report_usage("on_options_object2project")
  7027. obj = self.collection.get_active()
  7028. if obj is None:
  7029. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7030. return
  7031. obj.read_form()
  7032. for option in obj.options:
  7033. if option in ['name']: # TODO: Handle this better...
  7034. continue
  7035. self.options[obj.kind + "_" + option] = obj.options[option]
  7036. self.options_write_form()
  7037. def on_options_object2app(self):
  7038. """
  7039. Callback for Options->Transfer Options->Object=>App. Copies options
  7040. from the currently selected object to application defaults.
  7041. :return: None
  7042. """
  7043. self.report_usage("on_options_object2app")
  7044. obj = self.collection.get_active()
  7045. if obj is None:
  7046. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7047. return
  7048. obj.read_form()
  7049. for option in obj.options:
  7050. if option in ['name']: # TODO: Handle this better...
  7051. continue
  7052. self.defaults[obj.kind + "_" + option] = obj.options[option]
  7053. self.defaults_write_form()
  7054. def on_options_app2object(self):
  7055. """
  7056. Callback for Options->Transfer Options->App=>Object. Copies options
  7057. from application defaults to the currently selected object.
  7058. :return: None
  7059. """
  7060. self.report_usage("on_options_app2object")
  7061. self.defaults_read_form()
  7062. obj = self.collection.get_active()
  7063. if obj is None:
  7064. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  7065. return
  7066. for option in self.defaults:
  7067. if option.find(obj.kind + "_") == 0:
  7068. oname = option[len(obj.kind) + 1:]
  7069. obj.options[oname] = self.defaults[option]
  7070. obj.to_form() # Update UI
  7071. # end of file