FlatCAMApp.py 412 KB

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